add usd-21-05-win64_py37

This commit is contained in:
Sébastien Albert committed 2021-12-07 17:16:25 +01:00
1 parent 41d23e71ba
commit 66bc054336
15675 files changed
+3061008

No files matched your search

+95
View File
@@ -0,0 +1,95 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_FAR_ERROR_H
#define OPENSUBDIV3_FAR_ERROR_H
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far {
typedef enum {
FAR_NO_ERROR, ///< No error. Move along.
FAR_FATAL_ERROR, ///< Issue a fatal error and end the program.
FAR_INTERNAL_CODING_ERROR, ///< Issue an internal programming error, but continue execution.
FAR_CODING_ERROR, ///< Issue a generic programming error, but continue execution.
FAR_RUNTIME_ERROR ///< Issue a generic runtime error, but continue execution.
} ErrorType;
/// \brief The error callback function type (default is "printf")
typedef void (*ErrorCallbackFunc)(ErrorType err, const char *message);
/// \brief Sets the error callback function (default is "printf")
///
/// \note This function is not thread-safe !
///
/// @param func function pointer to the callback function
///
void SetErrorCallback(ErrorCallbackFunc func);
/// \brief The warning callback function type (default is "printf")
typedef void (*WarningCallbackFunc)(const char *message);
/// \brief Sets the warning callback function (default is "printf")
///
/// \note This function is not thread-safe !
///
/// @param func function pointer to the callback function
///
void SetWarningCallback(WarningCallbackFunc func);
//
// The following are intended for internal use only (and will eventually
// be moved within namespace internal)
//
/// \brief Sends an OSD error with a message (internal use only)
///
/// @param err the error type
///
/// @param format the format of the message (followed by arguments)
///
void Error(ErrorType err, const char *format, ...);
/// \brief Sends an OSD warning message (internal use only)
///
/// @param format the format of the message (followed by arguments)
///
void Warning(const char *format, ...);
} // end namespace
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_FAR_ERROR_H
+187
View File
@@ -0,0 +1,187 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_FAR_PATCH_DESCRIPTOR_H
#define OPENSUBDIV3_FAR_PATCH_DESCRIPTOR_H
#include "../version.h"
#include "../far/types.h"
#include "../sdc/types.h"
#include <vector>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far {
/// \brief Describes the type of a patch
///
/// Uniquely identifies all the different types of patches
///
class PatchDescriptor {
public:
enum Type {
NON_PATCH = 0, ///< undefined
POINTS, ///< points (useful for cage drawing)
LINES, ///< lines (useful for cage drawing)
QUADS, ///< 4-sided quadrilateral (bilinear)
TRIANGLES, ///< 3-sided triangle
LOOP, ///< regular triangular patch for the Loop scheme
REGULAR, ///< regular B-Spline patch for the Catmark scheme
GREGORY,
GREGORY_BOUNDARY,
GREGORY_BASIS,
GREGORY_TRIANGLE
};
public:
/// \brief Default constructor.
PatchDescriptor() :
_type(NON_PATCH) { }
/// \brief Constructor
PatchDescriptor(int type) :
_type(type) { }
/// \brief Copy Constructor
PatchDescriptor( PatchDescriptor const & d ) :
_type(d.GetType()) { }
/// \brief Returns the type of the patch
Type GetType() const {
return (Type)_type;
}
/// \brief Returns true if the type is an adaptive (non-linear) patch
static inline bool IsAdaptive(Type type) {
return type > TRIANGLES;
}
/// \brief Returns true if the type is an adaptive patch
bool IsAdaptive() const {
return IsAdaptive( this->GetType() );
}
/// \brief Returns the number of control vertices expected for a patch of the
/// type described
static inline short GetNumControlVertices( Type t );
/// \brief Deprecated @see PatchDescriptor#GetNumControlVertices
static inline short GetNumFVarControlVertices( Type t );
/// \brief Returns the number of control vertices expected for a patch of the
/// type described
short GetNumControlVertices() const {
return GetNumControlVertices( this->GetType() );
}
/// \brief Deprecated @see PatchDescriptor#GetNumControlVertices
short GetNumFVarControlVertices() const {
return GetNumFVarControlVertices( this->GetType() );
}
/// \brief Number of control vertices of Regular Patches in table.
static short GetRegularPatchSize() { return 16; }
/// \brief Number of control vertices of Gregory (and Gregory Boundary) Patches in table.
static short GetGregoryPatchSize() { return 4; }
/// \brief Number of control vertices of Gregory patch basis (20)
static short GetGregoryBasisPatchSize() { return 20; }
/// \brief Returns a vector of all the legal patch descriptors for the
/// given adaptive subdivision scheme
static Vtr::ConstArray<PatchDescriptor> GetAdaptivePatchDescriptors(Sdc::SchemeType type);
/// \brief Allows ordering of patches by type
inline bool operator < ( PatchDescriptor const other ) const;
/// \brief True if the descriptors are identical
inline bool operator == ( PatchDescriptor const other ) const;
// debug helper
void print() const;
private:
unsigned int _type;
};
typedef Vtr::ConstArray<PatchDescriptor> ConstPatchDescriptorArray;
// Returns the number of control vertices expected for a patch of this type
inline short
PatchDescriptor::GetNumControlVertices( Type type ) {
switch (type) {
case REGULAR : return GetRegularPatchSize();
case LOOP : return 12;
case QUADS : return 4;
case GREGORY :
case GREGORY_BOUNDARY : return GetGregoryPatchSize();
case GREGORY_BASIS : return GetGregoryBasisPatchSize();
case GREGORY_TRIANGLE : return 18;
case TRIANGLES : return 3;
case LINES : return 2;
case POINTS : return 1;
default : return -1;
}
}
// Returns the number of face-varying control vertices expected for a patch of this type
inline short
PatchDescriptor::GetNumFVarControlVertices( Type type ) {
return PatchDescriptor::GetNumControlVertices(type);
}
// Allows ordering of patches by type
inline bool
PatchDescriptor::operator < ( PatchDescriptor const other ) const {
return (_type < other._type);
}
// True if the descriptors are identical
inline bool
PatchDescriptor::operator == ( PatchDescriptor const other ) const {
return _type == other._type;
}
} // end namespace Far
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_FAR_PATCH_DESCRIPTOR_H */
+240
View File
@@ -0,0 +1,240 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_FAR_PATCH_MAP_H
#define OPENSUBDIV3_FAR_PATCH_MAP_H
#include "../version.h"
#include "../far/patchTable.h"
#include <cassert>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far {
/// \brief An quadtree-based map connecting coarse faces to their sub-patches
///
/// PatchTable::PatchArrays contain lists of patches that represent the limit
/// surface of a mesh, sorted by their topological type. These arrays break the
/// connection between coarse faces and their sub-patches.
///
/// The PatchMap provides a quad-tree based lookup structure that, given a singular
/// parametric location, can efficiently return a handle to the sub-patch that
/// contains this location.
///
class PatchMap {
public:
typedef PatchTable::PatchHandle Handle;
/// \brief Constructor
///
/// @param patchTable A valid PatchTable
///
PatchMap( PatchTable const & patchTable );
/// \brief Returns a handle to the sub-patch of the face at the given (u,v).
/// Note that the patch face ID corresponds to potentially quadrangulated
/// face indices and not the base face indices (see Far::PtexIndices for more
/// details).
///
/// @param patchFaceId The index of the patch (Ptex) face
///
/// @param u Local u parameter
///
/// @param v Local v parameter
///
/// @return A patch handle or 0 if the face is not supported (index
/// out of bounds) or is tagged as a hole
///
Handle const * FindPatch( int patchFaceId, double u, double v ) const;
private:
void initializeHandles(PatchTable const & patchTable);
void initializeQuadtree(PatchTable const & patchTable);
private:
// Quadtree node with 4 children, tree is just a vector of nodes
struct QuadNode {
QuadNode() { std::memset(this, 0, sizeof(QuadNode)); }
struct Child {
unsigned int isSet : 1; // true if the child has been set
unsigned int isLeaf : 1; // true if the child is a QuadNode
unsigned int index : 30; // child index (either QuadNode or Handle)
};
// sets all the children to point to the patch of given index
void SetChildren(int index);
// sets the child in "quadrant" to point to the node or patch of the given index
void SetChild(int quadrant, int index, bool isLeaf);
Child children[4];
};
typedef std::vector<QuadNode> QuadTree;
// Internal methods supporting quadtree construction and queries
void assignRootNode(QuadNode * node, int index);
QuadNode * assignLeafOrChildNode(QuadNode * node, bool isLeaf, int quad, int index);
template <class T>
static int transformUVToQuadQuadrant(T const & median, T & u, T & v);
template <class T>
static int transformUVToTriQuadrant(T const & median, T & u, T & v, bool & rotated);
private:
bool _patchesAreTriangular; // tri and quad assembly and search requirements differ
int _minPatchFace; // minimum patch face index supported by the map
int _maxPatchFace; // maximum patch face index supported by the map
int _maxDepth; // maximum depth of a patch in the tree
std::vector<Handle> _handles; // all the patches in the PatchTable
std::vector<QuadNode> _quadtree; // quadtree nodes
};
//
// Given a median value for both U and V, these methods transform a (u,v) pair
// into the quadrant that contains them and returns the quadrant index.
//
// Quadrant indexing for tri and quad patches -- consistent with PatchParam's
// usage of UV bits:
//
// (0,1) o-----o-----o (1,1) (0,1) o (1,0) o-----o-----o (0,0)
// | | | |\ \ 1 |\ 0 |
// | 2 | 3 | | \ \ | \ |
// | | | | 2 \ \| 3 \|
// o-----o-----o o-----o o-----o
// | | | |\ 3 |\ \ 2 |
// | 0 | 1 | | \ | \ \ |
// | | | | 0 \| 1 \ \|
// (0,0) o-----o-----o (1,0) (0,0) o-----o-----o (1,0) o (0,1)
//
// The triangular case also takes and returns/affects the rotation of the
// quadrant being searched and identified (quadrant 3 imparts a rotation).
//
template <class T>
inline int
PatchMap::transformUVToQuadQuadrant(T const & median, T & u, T & v) {
int uHalf = (u >= median);
if (uHalf) u -= median;
int vHalf = (v >= median);
if (vHalf) v -= median;
return (vHalf << 1) | uHalf;
}
template <class T>
int inline
PatchMap::transformUVToTriQuadrant(T const & median, T & u, T & v, bool & rotated) {
if (!rotated) {
if (u >= median) {
u -= median;
return 1;
}
if (v >= median) {
v -= median;
return 2;
}
if ((u + v) >= median) {
rotated = true;
return 3;
}
return 0;
} else {
if (u < median) {
v -= median;
return 1;
}
if (v < median) {
u -= median;
return 2;
}
u -= median;
v -= median;
if ((u + v) < median) {
rotated = false;
return 3;
}
return 0;
}
}
/// Returns a handle to the sub-patch of the face at the given (u,v).
inline PatchMap::Handle const *
PatchMap::FindPatch( int faceid, double u, double v ) const {
//
// Reject patch faces not supported by this map, or those corresponding
// to holes or otherwise unassigned (the root node for a patch will
// have all or no quadrants set):
//
if ((faceid < _minPatchFace) || (faceid > _maxPatchFace)) return 0;
QuadNode const * node = &_quadtree[faceid - _minPatchFace];
if (!node->children[0].isSet) return 0;
//
// Search the tree for the sub-patch containing the given (u,v)
//
assert( (u>=0.0) && (u<=1.0) && (v>=0.0) && (v<=1.0) );
double median = 0.5;
bool triRotated = false;
for (int depth = 0; depth <= _maxDepth; ++depth, median *= 0.5) {
int quadrant = _patchesAreTriangular
? transformUVToTriQuadrant(median, u, v, triRotated)
: transformUVToQuadQuadrant(median, u, v);
// holes should have been rejected at the root node of the face
assert(node->children[quadrant].isSet);
if (node->children[quadrant].isLeaf) {
return &_handles[node->children[quadrant].index];
} else {
node = &_quadtree[node->children[quadrant].index];
}
}
assert(0);
return 0;
}
} // end namespace Far
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_FAR_PATCH_PARAM */
+332
View File
@@ -0,0 +1,332 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_FAR_PATCH_PARAM_H
#define OPENSUBDIV3_FAR_PATCH_PARAM_H
#include "../version.h"
#include "../far/types.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far {
/// \brief Patch parameterization
///
/// Topological refinement splits coarse mesh faces into refined faces.
///
/// This patch parameterzation describes the relationship between one
/// of these refined faces and its corresponding coarse face. It is used
/// both for refined faces that are represented as full limit surface
/// parametric patches as well as for refined faces represented as simple
/// triangles or quads. This parameterization is needed to interpolate
/// primvar data across a refined face.
///
/// The U,V and refinement level parameters describe the scale and offset
/// needed to map a location on the patch between levels of refinement.
/// The encoding of these values exploits the quad-tree organization of
/// the faces produced by subdivision. We encode the U,V origin of the
/// patch using two 10-bit integer values and the refinement level as
/// a 4-bit integer. This is sufficient to represent up through 10 levels
/// of refinement.
///
/// Special consideration must be given to the refined faces resulting from
/// irregular coarse faces. We adopt a convention similar to Ptex texture
/// mapping and define the parameterization for these faces in terms of the
/// regular faces resulting from the first topological splitting of the
/// irregular coarse face.
///
/// When computing the basis functions needed to evaluate the limit surface
/// parametric patch representing a refined face, we also need to know which
/// edges of the patch are interpolated boundaries. These edges are encoded
/// as a boundary bitmask identifying the boundary edges of the patch in
/// sequential order starting from the first vertex of the refined face.
///
/// A sparse topological refinement (like feature adaptive refinement) can
/// produce refined faces that are adjacent to faces at the next level of
/// subdivision. We identify these transitional edges with a transition
/// bitmask using the same encoding as the boundary bitmask.
///
/// For triangular subdivision schemes we specify the parameterization using
/// a similar method. Alternate triangles at a given level of refinement
/// are parameterized from their opposite corners and encoded as occupying
/// the opposite diagonal of the quad-tree hierarchy. The third barycentric
/// coordinate is dependent on and can be derived from the other two
/// coordinates. This encoding also takes inspiration from the Ptex
/// texture mapping specification.
///
/// Bitfield layout :
///
/// Field0 | Bits | Content
/// -----------|:----:|------------------------------------------------------
/// faceId | 28 | the faceId of the patch
/// transition | 4 | transition edge mask encoding
///
/// Field1 | Bits | Content
/// -----------|:----:|------------------------------------------------------
/// level | 4 | the subdivision level of the patch
/// nonquad | 1 | whether patch is refined from a non-quad face
/// regular | 1 | whether patch is regular
/// unused | 1 | unused
/// boundary | 5 | boundary edge mask encoding
/// v | 10 | log2 value of u parameter at first patch corner
/// u | 10 | log2 value of v parameter at first patch corner
///
/// Note : the bitfield is not expanded in the struct due to differences in how
/// GPU & CPU compilers pack bit-fields and endian-ness.
///
/*!
\verbatim
Quad Patch Parameterization
(0,1) (1,1)
+-------+-------+---------------+
| | | |
| L2 | L2 | |
|0,3 |1,3 | |
+-------+-------+ L1 |
| | | |
| L2 | L2 | |
|0,2 |1,2 |1,1 |
+-------+-------+---------------+
| | |
| | |
| | |
| L1 | L1 |
| | |
| | |
|0,0 |1,0 |
+---------------+---------------+
(0,0) (1,0)
\endverbatim
*/
/*!
\verbatim
Triangle Patch Parameterization
(0,1) (1,1) (0,1,0)
+-------+-------+---------------+ +
| \ | \ | \ | | \
|L2 \ |L2 \ | \ | | \
|0,3 \ |1,3 \ | \ | | L2 \
+-------+-------+ \ | +-------+
| \ | \ | L1 \ | | \ L2 | \
|L2 \ |L2 \ | \ | | \ | \
|0,2 \ |1,2 \ |1,1 \ | | L2 \ | L2 \
+-------+-------+---------------+ +-------+-------+
| \ | \ | | \ | \
| \ | \ | | \ | \
| \ | \ | | \ L1 | \
| \ | \ | | \ | \
| L1 \ | L1 \ | | L1 \ | L1 \
| \ | \ | | \ | \
|0,0 \ |1,0 \ | | \ | \
+---------------+---------------+ +---------------+---------------+
(0,0) (1,0) (0,0,1) (1,0,0)
\endverbatim
*/
struct PatchParam {
/// \brief Sets the values of the bit fields
///
/// @param faceid face index
///
/// @param u value of the u parameter for the first corner of the face
/// @param v value of the v parameter for the first corner of the face
///
/// @param depth subdivision level of the patch
/// @param nonquad true if the root face is not a quad
///
/// @param boundary 5-bits identifying boundary edges (and verts for tris)
/// @param transition 4-bits identifying transition edges
///
/// @param regular whether the patch is regular
///
void Set(Index faceid, short u, short v,
unsigned short depth, bool nonquad,
unsigned short boundary, unsigned short transition,
bool regular = false);
/// \brief Resets everything to 0
void Clear() { field0 = field1 = 0; }
/// \brief Returns the faceid
Index GetFaceId() const { return Index(unpack(field0,28,0)); }
/// \brief Returns the log2 value of the u parameter at
/// the first corner of the patch
unsigned short GetU() const { return (unsigned short)unpack(field1,10,22); }
/// \brief Returns the log2 value of the v parameter at
/// the first corner of the patch
unsigned short GetV() const { return (unsigned short)unpack(field1,10,12); }
/// \brief Returns the transition edge encoding for the patch.
unsigned short GetTransition() const { return (unsigned short)unpack(field0,4,28); }
/// \brief Returns the boundary edge encoding for the patch.
unsigned short GetBoundary() const { return (unsigned short)unpack(field1,5,7); }
/// \brief True if the parent base face is a non-quad
bool NonQuadRoot() const { return (unpack(field1,1,4) != 0); }
/// \brief Returns the level of subdivision of the patch
unsigned short GetDepth() const { return (unsigned short)unpack(field1,4,0); }
/// \brief Returns the fraction of unit parametric space covered by this face.
float GetParamFraction() const;
/// \brief A (u,v) pair in the fraction of parametric space covered by this
/// face is mapped into a normalized parametric space.
///
/// @param u u parameter
/// @param v v parameter
///
template <typename REAL>
void Normalize( REAL & u, REAL & v ) const;
template <typename REAL>
void NormalizeTriangle( REAL & u, REAL & v ) const;
/// \brief A (u,v) pair in a normalized parametric space is mapped back into the
/// fraction of parametric space covered by this face.
///
/// @param u u parameter
/// @param v v parameter
///
template <typename REAL>
void Unnormalize( REAL & u, REAL & v ) const;
template <typename REAL>
void UnnormalizeTriangle( REAL & u, REAL & v ) const;
/// \brief Returns if a triangular patch is parametrically rotated 180 degrees
bool IsTriangleRotated() const;
/// \brief Returns whether the patch is regular
bool IsRegular() const { return (unpack(field1,1,5) != 0); }
unsigned int field0:32;
unsigned int field1:32;
private:
unsigned int pack(unsigned int value, int width, int offset) const {
return (unsigned int)((value & ((1<<width)-1)) << offset);
}
unsigned int unpack(unsigned int value, int width, int offset) const {
return (unsigned int)((value >> offset) & ((1<<width)-1));
}
};
typedef std::vector<PatchParam> PatchParamTable;
typedef Vtr::Array<PatchParam> PatchParamArray;
typedef Vtr::ConstArray<PatchParam> ConstPatchParamArray;
inline void
PatchParam::Set(Index faceid, short u, short v,
unsigned short depth, bool nonquad,
unsigned short boundary, unsigned short transition,
bool regular) {
field0 = pack(faceid, 28, 0) |
pack(transition, 4, 28);
field1 = pack(u, 10, 22) |
pack(v, 10, 12) |
pack(boundary, 5, 7) |
pack(regular, 1, 5) |
pack(nonquad, 1, 4) |
pack(depth, 4, 0);
}
inline float
PatchParam::GetParamFraction( ) const {
return 1.0f / (float)(1 << (GetDepth() - NonQuadRoot()));
}
template <typename REAL>
inline void
PatchParam::Normalize( REAL & u, REAL & v ) const {
REAL fracInv = (REAL)(1.0f / GetParamFraction());
u = u * fracInv - (REAL)GetU();
v = v * fracInv - (REAL)GetV();
}
template <typename REAL>
inline void
PatchParam::Unnormalize( REAL & u, REAL & v ) const {
REAL frac = (REAL)GetParamFraction();
u = (u + (REAL)GetU()) * frac;
v = (v + (REAL)GetV()) * frac;
}
inline bool
PatchParam::IsTriangleRotated() const {
return (GetU() + GetV()) >= (1 << GetDepth());
}
template <typename REAL>
inline void
PatchParam::NormalizeTriangle( REAL & u, REAL & v ) const {
if (IsTriangleRotated()) {
REAL fracInv = (REAL)(1.0f / GetParamFraction());
int depthFactor = 1 << GetDepth();
u = (REAL)(depthFactor - GetU()) - (u * fracInv);
v = (REAL)(depthFactor - GetV()) - (v * fracInv);
} else {
Normalize(u, v);
}
}
template <typename REAL>
inline void
PatchParam::UnnormalizeTriangle( REAL & u, REAL & v ) const {
if (IsTriangleRotated()) {
REAL frac = GetParamFraction();
int depthFactor = 1 << GetDepth();
u = ((REAL)(depthFactor - GetU()) - u) * frac;
v = ((REAL)(depthFactor - GetV()) - v) * frac;
} else {
Unnormalize(u, v);
}
}
} // end namespace Far
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_FAR_PATCH_PARAM */
+861
View File
@@ -0,0 +1,861 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_FAR_PATCH_TABLE_H
#define OPENSUBDIV3_FAR_PATCH_TABLE_H
#include "../version.h"
#include "../far/patchDescriptor.h"
#include "../far/patchParam.h"
#include "../far/stencilTable.h"
#include "../sdc/options.h"
#include <vector>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far {
/// \brief Container for arrays of parametric patches
///
/// PatchTable contains topology and parametric information about the patches
/// generated by the Refinement process. Patches in the table are sorted into
/// arrays based on their PatchDescriptor Type.
///
/// Note : PatchTable can be accessed either using a PatchHandle or a
/// combination of array and patch indices.
///
/// XXXX manuelk we should add a PatchIterator that can dereference into
/// a PatchHandle for fast linear traversal of the table
///
class PatchTable {
public:
/// \brief Handle that can be used as unique patch identifier within PatchTable
class PatchHandle {
// XXXX manuelk members will eventually be made private
public:
friend class PatchTable;
friend class PatchMap;
Index arrayIndex, // Array index of the patch
patchIndex, // Absolute Index of the patch
vertIndex; // Relative offset to the first CV of the patch in array
};
public:
/// \brief Copy constructor
PatchTable(PatchTable const & src);
/// \brief Destructor
~PatchTable();
/// \brief True if the patches are of feature adaptive types
bool IsFeatureAdaptive() const;
/// \brief Returns the total number of control vertex indices in the table
int GetNumControlVerticesTotal() const {
return (int)_patchVerts.size();
}
/// \brief Returns the total number of patches stored in the table
int GetNumPatchesTotal() const;
/// \brief Returns max vertex valence
int GetMaxValence() const { return _maxValence; }
/// \brief Returns the total number of ptex faces in the mesh
int GetNumPtexFaces() const { return _numPtexFaces; }
//@{
/// @name Individual patches
///
/// \anchor individual_patches
///
/// \brief Accessors for individual patches
///
/// \brief Returns the PatchDescriptor for the patch identified by \p handle
PatchDescriptor GetPatchDescriptor(PatchHandle const & handle) const;
/// \brief Returns the control vertex indices for the patch identified by \p handle
ConstIndexArray GetPatchVertices(PatchHandle const & handle) const;
/// \brief Returns a PatchParam for the patch identified by \p handle
PatchParam GetPatchParam(PatchHandle const & handle) const;
/// \brief Returns the control vertex indices for \p patch in \p array
ConstIndexArray GetPatchVertices(int array, int patch) const;
/// \brief Returns the PatchParam for \p patch in \p array
PatchParam GetPatchParam(int array, int patch) const;
//@}
//@{
/// @name Arrays of patches
///
/// \anchor arrays_of_patches
///
/// \brief Accessors for arrays of patches of the same type
///
/// \brief Returns the number of patch arrays in the table
int GetNumPatchArrays() const;
/// \brief Returns the number of patches in \p array
int GetNumPatches(int array) const;
/// \brief Returns the number of control vertices in \p array
int GetNumControlVertices(int array) const;
/// \brief Returns the PatchDescriptor for the patches in \p array
PatchDescriptor GetPatchArrayDescriptor(int array) const;
/// \brief Returns the control vertex indices for the patches in \p array
ConstIndexArray GetPatchArrayVertices(int array) const;
/// \brief Returns the PatchParams for the patches in \p array
ConstPatchParamArray const GetPatchParams(int array) const;
//@}
//@{
/// @name Change of basis patches
///
/// \anchor change_of_basis_patches
///
/// \brief Accessors for change of basis patches
///
///
/// \brief Returns the number of local vertex points.
int GetNumLocalPoints() const;
/// \brief Returns the stencil table to compute local point vertex values
StencilTable const *GetLocalPointStencilTable() const;
/// \brief Returns the stencil table to compute local point vertex values
template <typename REAL>
StencilTableReal<REAL> const *GetLocalPointStencilTable() const;
/// \brief Tests if the precision of the stencil table to compute local point
/// vertex values matches the given floating point type \<REAL\>.
template <typename REAL> bool LocalPointStencilPrecisionMatchesType() const;
/// \brief Updates local point vertex values.
///
/// @param src Buffer with primvar data for the base and refined
/// vertex values
///
/// @param dst Destination buffer for the computed local point
/// vertex values
///
/// For more flexibility computing local vertex points, retrieval of
/// the local point stencil table and use of its public methods is
/// recommended or often required.
///
template <class T> void
ComputeLocalPointValues(T const *src, T *dst) const;
/// \brief Returns the number of local varying points.
int GetNumLocalPointsVarying() const;
/// \brief Returns the stencil table to compute local point varying values
StencilTable const *GetLocalPointVaryingStencilTable() const;
/// \brief Returns the stencil table to compute local point varying values
template <typename REAL>
StencilTableReal<REAL> const *GetLocalPointVaryingStencilTable() const;
/// \brief Tests if the precision of the stencil table to compute local point
/// varying values matches the given floating point type \<REAL\>.
template <typename REAL> bool LocalPointVaryingStencilPrecisionMatchesType() const;
/// \brief Updates local point varying values.
///
/// @param src Buffer with primvar data for the base and refined
/// varying values
///
/// @param dst Destination buffer for the computed local point
/// varying values
///
/// For more flexibility computing local varying points, retrieval of
/// the local point varying stencil table and use of its public methods
/// is recommended or often required.
///
template <class T> void
ComputeLocalPointValuesVarying(T const *src, T *dst) const;
/// \brief Returns the number of local face-varying points for \p channel
int GetNumLocalPointsFaceVarying(int channel = 0) const;
/// \brief Returns the stencil table to compute local point face-varying values
StencilTable const *GetLocalPointFaceVaryingStencilTable(int channel = 0) const;
/// \brief Returns the stencil table to compute local point face-varying values
template <typename REAL>
StencilTableReal<REAL> const * GetLocalPointFaceVaryingStencilTable(int channel = 0) const;
/// \brief Tests if the precision of the stencil table to compute local point
/// face-varying values matches the given floating point type \<REAL\>.
template <typename REAL> bool LocalPointFaceVaryingStencilPrecisionMatchesType() const;
/// \brief Updates local point face-varying values.
///
/// @param src Buffer with primvar data for the base and refined
/// face-varying values
///
/// @param dst Destination buffer for the computed local point
/// face-varying values
///
/// @param channel face-varying channel
///
/// For more flexibility computing local face-varying points, retrieval
/// of the local point face-varying stencil table and use of its public
/// methods is recommended or often required.
///
template <class T> void
ComputeLocalPointValuesFaceVarying(T const *src, T *dst, int channel = 0) const;
//@}
//@{
/// @name Legacy gregory patch evaluation buffers
/// \brief Accessors for the gregory patch evaluation buffers.
/// These methods will be deprecated.
///
typedef Vtr::ConstArray<unsigned int> ConstQuadOffsetsArray;
/// \brief Returns the 'QuadOffsets' for the Gregory patch identified by \p handle
ConstQuadOffsetsArray GetPatchQuadOffsets(PatchHandle const & handle) const;
typedef std::vector<Index> VertexValenceTable;
/// \brief Returns the 'VertexValences' table (vertex neighborhoods table)
VertexValenceTable const & GetVertexValenceTable() const {
return _vertexValenceTable;
}
//@}
//@{
/// @name Single-crease patches
///
/// \anchor single_crease_patches
///
/// \brief Accessors for single-crease patch edge sharpness
///
/// \brief Returns the crease sharpness for the patch identified by \p handle
/// if it is a single-crease patch, or 0.0f
float GetSingleCreasePatchSharpnessValue(PatchHandle const & handle) const;
/// \brief Returns the crease sharpness for the \p patch in \p array
/// if it is a single-crease patch, or 0.0f
float GetSingleCreasePatchSharpnessValue(int array, int patch) const;
//@}
//@{
/// @name Varying data
///
/// \anchor varying_data
///
/// \brief Accessors for varying data
///
/// \brief Returns the varying patch descriptor
PatchDescriptor GetVaryingPatchDescriptor() const;
/// \brief Returns the varying vertex indices for a given patch
ConstIndexArray GetPatchVaryingVertices(PatchHandle const & handle) const;
/// \brief Returns the varying vertex indices for a given patch
ConstIndexArray GetPatchVaryingVertices(int array, int patch) const;
/// \brief Returns the varying vertex indices for the patches in \p array
ConstIndexArray GetPatchArrayVaryingVertices(int array) const;
/// \brief Returns an array of varying vertex indices for the patches.
ConstIndexArray GetVaryingVertices() const;
//@}
//@{
/// @name Face-varying channels
///
/// \anchor face_varying_channels
///
/// \brief Accessors for face-varying channels
///
/// \brief Returns the number of face-varying channels
int GetNumFVarChannels() const;
/// \brief Returns the regular patch descriptor for \p channel
PatchDescriptor GetFVarPatchDescriptorRegular(int channel = 0) const;
/// \brief Returns the irregular patch descriptor for \p channel
PatchDescriptor GetFVarPatchDescriptorIrregular(int channel = 0) const;
/// \brief Returns the default/irregular patch descriptor for \p channel
PatchDescriptor GetFVarPatchDescriptor(int channel = 0) const;
/// \brief Returns the value indices for a given patch in \p channel
ConstIndexArray GetPatchFVarValues(PatchHandle const & handle, int channel = 0) const;
/// \brief Returns the value indices for a given patch in \p channel
ConstIndexArray GetPatchFVarValues(int array, int patch, int channel = 0) const;
/// \brief Returns the value indices for the patches in \p array in \p channel
ConstIndexArray GetPatchArrayFVarValues(int array, int channel = 0) const;
/// \brief Returns an array of value indices for the patches in \p channel
ConstIndexArray GetFVarValues(int channel = 0) const;
/// \brief Returns the stride between patches in the value index array of \p channel
int GetFVarValueStride(int channel = 0) const;
/// \brief Returns the value indices for a given patch in \p channel
PatchParam GetPatchFVarPatchParam(PatchHandle const & handle, int channel = 0) const;
/// \brief Returns the face-varying params for a given patch \p channel
PatchParam GetPatchFVarPatchParam(int array, int patch, int channel = 0) const;
/// \brief Returns the face-varying for a given patch in \p array in \p channel
ConstPatchParamArray GetPatchArrayFVarPatchParams(int array, int channel = 0) const;
/// \brief Returns an array of face-varying patch param for \p channel
ConstPatchParamArray GetFVarPatchParams(int channel = 0) const;
/// \brief Deprecated @see PatchTable#GetFVarPatchDescriptor
Sdc::Options::FVarLinearInterpolation GetFVarChannelLinearInterpolation(int channel = 0) const;
//@}
//@{
/// @name Direct accessors
///
/// \warning These direct accessors are left for convenience, but they are
/// likely going to be deprecated in future releases
///
typedef std::vector<Index> PatchVertsTable;
/// \brief Get the table of patch control vertices
PatchVertsTable const & GetPatchControlVerticesTable() const { return _patchVerts; }
/// \brief Returns the PatchParamTable (PatchParams order matches patch array sorting)
PatchParamTable const & GetPatchParamTable() const { return _paramTable; }
/// \brief Returns a sharpness index table for each patch (if exists)
std::vector<Index> const &GetSharpnessIndexTable() const { return _sharpnessIndices; }
/// \brief Returns sharpness values table
std::vector<float> const &GetSharpnessValues() const { return _sharpnessValues; }
typedef std::vector<unsigned int> QuadOffsetsTable;
/// \brief Returns the quad-offsets table
QuadOffsetsTable const & GetQuadOffsetsTable() const {
return _quadOffsetsTable;
}
//@}
/// debug helper
void print() const;
public:
//@{
/// @name Evaluation methods
///
/// \brief Evaluate basis functions for position and derivatives at a
/// given (u,v) parametric location of a patch.
///
/// @param handle A patch handle identifying the sub-patch containing the
/// (u,v) location
///
/// @param u Patch coordinate (in base face normalized space)
///
/// @param v Patch coordinate (in base face normalized space)
///
/// @param wP Weights (evaluated basis functions) for the position
///
/// @param wDu Weights (evaluated basis functions) for derivative wrt u
///
/// @param wDv Weights (evaluated basis functions) for derivative wrt v
///
/// @param wDuu Weights (evaluated basis functions) for 2nd derivative wrt u
///
/// @param wDuv Weights (evaluated basis functions) for 2nd derivative wrt u and v
///
/// @param wDvv Weights (evaluated basis functions) for 2nd derivative wrt v
///
template <typename REAL>
void EvaluateBasis(PatchHandle const & handle, REAL u, REAL v,
REAL wP[], REAL wDu[] = 0, REAL wDv[] = 0,
REAL wDuu[] = 0, REAL wDuv[] = 0, REAL wDvv[] = 0) const;
/// \brief An overloaded version to assist template parameter resolution
/// when explicitly declaring unused array arguments as 0.
void EvaluateBasis(PatchHandle const & handle, float u, float v,
float wP[], float wDu[] = 0, float wDv[] = 0,
float wDuu[] = 0, float wDuv[] = 0, float wDvv[] = 0) const;
/// \brief An overloaded version to assist template parameter resolution
/// when explicitly declaring unused array arguments as 0.
void EvaluateBasis(PatchHandle const & handle, double u, double v,
double wP[], double wDu[] = 0, double wDv[] = 0,
double wDuu[] = 0, double wDuv[] = 0, double wDvv[] = 0) const;
/// \brief Evaluate basis functions for a varying value and
/// derivatives at a given (u,v) parametric location of a patch.
///
/// @param handle A patch handle identifying the sub-patch containing the
/// (u,v) location
///
/// @param u Patch coordinate (in base face normalized space)
///
/// @param v Patch coordinate (in base face normalized space)
///
/// @param wP Weights (evaluated basis functions) for the position
///
/// @param wDu Weights (evaluated basis functions) for derivative wrt u
///
/// @param wDv Weights (evaluated basis functions) for derivative wrt v
///
/// @param wDuu Weights (evaluated basis functions) for 2nd derivative wrt u
///
/// @param wDuv Weights (evaluated basis functions) for 2nd derivative wrt u and v
///
/// @param wDvv Weights (evaluated basis functions) for 2nd derivative wrt v
///
template <typename REAL>
void EvaluateBasisVarying(PatchHandle const & handle, REAL u, REAL v,
REAL wP[], REAL wDu[] = 0, REAL wDv[] = 0,
REAL wDuu[] = 0, REAL wDuv[] = 0, REAL wDvv[] = 0) const;
/// \brief An overloaded version to assist template parameter resolution
/// when explicitly declaring unused array arguments as 0.
void EvaluateBasisVarying(PatchHandle const & handle, float u, float v,
float wP[], float wDu[] = 0, float wDv[] = 0,
float wDuu[] = 0, float wDuv[] = 0, float wDvv[] = 0) const;
/// \brief An overloaded version to assist template parameter resolution
/// when explicitly declaring unused array arguments as 0.
void EvaluateBasisVarying(PatchHandle const & handle, double u, double v,
double wP[], double wDu[] = 0, double wDv[] = 0,
double wDuu[] = 0, double wDuv[] = 0, double wDvv[] = 0) const;
/// \brief Evaluate basis functions for a face-varying value and
/// derivatives at a given (u,v) parametric location of a patch.
///
/// @param handle A patch handle identifying the sub-patch containing the
/// (u,v) location
///
/// @param u Patch coordinate (in base face normalized space)
///
/// @param v Patch coordinate (in base face normalized space)
///
/// @param wP Weights (evaluated basis functions) for the position
///
/// @param wDu Weights (evaluated basis functions) for derivative wrt u
///
/// @param wDv Weights (evaluated basis functions) for derivative wrt v
///
/// @param wDuu Weights (evaluated basis functions) for 2nd derivative wrt u
///
/// @param wDuv Weights (evaluated basis functions) for 2nd derivative wrt u and v
///
/// @param wDvv Weights (evaluated basis functions) for 2nd derivative wrt v
///
/// @param channel face-varying channel
///
template <typename REAL>
void EvaluateBasisFaceVarying(PatchHandle const & handle, REAL u, REAL v,
REAL wP[], REAL wDu[] = 0, REAL wDv[] = 0,
REAL wDuu[] = 0, REAL wDuv[] = 0, REAL wDvv[] = 0,
int channel = 0) const;
/// \brief An overloaded version to assist template parameter resolution
/// when explicitly declaring unused array arguments as 0.
void EvaluateBasisFaceVarying(PatchHandle const & handle, float u, float v,
float wP[], float wDu[] = 0, float wDv[] = 0,
float wDuu[] = 0, float wDuv[] = 0, float wDvv[] = 0,
int channel = 0) const;
/// \brief An overloaded version to assist template parameter resolution
/// when explicitly declaring unused array arguments as 0.
void EvaluateBasisFaceVarying(PatchHandle const & handle, double u, double v,
double wP[], double wDu[] = 0, double wDv[] = 0,
double wDuu[] = 0, double wDuv[] = 0, double wDvv[] = 0,
int channel = 0) const;
//@}
protected:
friend class PatchTableBuilder;
// Factory constructor
PatchTable(int maxvalence);
Index getPatchIndex(int array, int patch) const;
PatchParamArray getPatchParams(int arrayIndex);
Index * getSharpnessIndices(Index arrayIndex);
float * getSharpnessValues(Index arrayIndex);
private:
//
// Patch arrays
//
struct PatchArray;
typedef std::vector<PatchArray> PatchArrayVector;
PatchArray & getPatchArray(Index arrayIndex);
PatchArray const & getPatchArray(Index arrayIndex) const;
void reservePatchArrays(int numPatchArrays);
void pushPatchArray(PatchDescriptor desc, int npatches,
Index * vidx, Index * pidx, Index * qoidx=0);
IndexArray getPatchArrayVertices(int arrayIndex);
Index findPatchArray(PatchDescriptor desc);
//
// Varying patch arrays
//
IndexArray getPatchArrayVaryingVertices(int arrayIndex);
void allocateVaryingVertices(
PatchDescriptor desc, int numPatches);
void populateVaryingVertices();
//
// Face-varying patch channels
//
struct FVarPatchChannel;
typedef std::vector<FVarPatchChannel> FVarPatchChannelVector;
FVarPatchChannel & getFVarPatchChannel(int channel);
FVarPatchChannel const & getFVarPatchChannel(int channel) const;
void allocateFVarPatchChannels(int numChannels);
void allocateFVarPatchChannelValues(
PatchDescriptor regDesc, PatchDescriptor irregDesc,
int numPatches, int channel);
// deprecated
void setFVarPatchChannelLinearInterpolation(
Sdc::Options::FVarLinearInterpolation interpolation, int channel);
IndexArray getFVarValues(int channel);
ConstIndexArray getPatchFVarValues(int patch, int channel) const;
PatchParamArray getFVarPatchParams(int channel);
PatchParam getPatchFVarPatchParam(int patch, int channel) const;
private:
//
// Simple private class to hold stencil table pointers of varying precision,
// where the discriminant of the precision is external.
//
// NOTE that this is a simple pointer container and NOT a smart pointer that
// manages the ownership of the object referred to by it.
//
class StencilTablePtr {
private:
typedef StencilTableReal<float> float_type;
typedef StencilTableReal<double> double_type;
union {
float_type * _fPtr;
double_type * _dPtr;
};
public:
StencilTablePtr() { _fPtr = 0; }
StencilTablePtr(float_type * ptr) { _fPtr = ptr; }
StencilTablePtr(double_type * ptr) { _dPtr = ptr; }
operator bool() const { return _fPtr != 0; }
void Set() { _fPtr = 0; }
void Set(float_type * ptr) { _fPtr = ptr; }
void Set(double_type * ptr) { _dPtr = ptr; }
template <typename REAL> StencilTableReal<REAL> * Get() const;
};
private:
//
// Topology
//
int _maxValence, // highest vertex valence found in the mesh
_numPtexFaces; // total number of ptex faces
PatchArrayVector _patchArrays; // Vector of descriptors for arrays of patches
std::vector<Index> _patchVerts; // Indices of the control vertices of the patches
PatchParamTable _paramTable; // PatchParam bitfields (one per patch)
//
// Extraordinary vertex closed-form evaluation / endcap basis conversion
//
// XXXtakahito: these data will probably be replaced with mask coefficient or something
// SchemeWorker populates.
//
QuadOffsetsTable _quadOffsetsTable; // Quad offsets (for Gregory patches)
VertexValenceTable _vertexValenceTable; // Vertex valence table (for Gregory patches)
StencilTablePtr _localPointStencils; // local point conversion stencils
StencilTablePtr _localPointVaryingStencils; // local point varying stencils
//
// Varying data
//
PatchDescriptor _varyingDesc;
std::vector<Index> _varyingVerts;
//
// Face-varying data
//
FVarPatchChannelVector _fvarChannels;
std::vector<StencilTablePtr> _localPointFaceVaryingStencils;
//
// 'single-crease' patch sharpness tables
//
std::vector<Index> _sharpnessIndices; // Indices of single-crease sharpness (one per patch)
std::vector<float> _sharpnessValues; // Sharpness values.
//
// Construction history -- relevant to at least one public query:
//
unsigned int _isUniformLinear : 1;
//
// Precision -- only applies to local-point stencil tables
//
unsigned int _vertexPrecisionIsDouble : 1;
unsigned int _varyingPrecisionIsDouble : 1;
unsigned int _faceVaryingPrecisionIsDouble : 1;
};
//
// Template specializations for float/double -- to be defined before used:
//
template <> inline StencilTableReal<float> *
PatchTable::StencilTablePtr::Get<float>() const { return _fPtr; }
template <> inline StencilTableReal<double> *
PatchTable::StencilTablePtr::Get<double>() const { return _dPtr; }
template <> inline bool
PatchTable::LocalPointStencilPrecisionMatchesType<float>() const {
return !_vertexPrecisionIsDouble;
}
template <> inline bool
PatchTable::LocalPointVaryingStencilPrecisionMatchesType<float>() const {
return !_varyingPrecisionIsDouble;
}
template <> inline bool
PatchTable::LocalPointFaceVaryingStencilPrecisionMatchesType<float>() const {
return !_faceVaryingPrecisionIsDouble;
}
template <> inline bool
PatchTable::LocalPointStencilPrecisionMatchesType<double>() const {
return _vertexPrecisionIsDouble;
}
template <> inline bool
PatchTable::LocalPointVaryingStencilPrecisionMatchesType<double>() const {
return _varyingPrecisionIsDouble;
}
template <> inline bool
PatchTable::LocalPointFaceVaryingStencilPrecisionMatchesType<double>() const {
return _faceVaryingPrecisionIsDouble;
}
//
// StencilTable access -- backward compatible and generic:
//
inline StencilTable const *
PatchTable::GetLocalPointStencilTable() const {
assert(LocalPointStencilPrecisionMatchesType<float>());
return static_cast<StencilTable const *>(_localPointStencils.Get<float>());
}
inline StencilTable const *
PatchTable::GetLocalPointVaryingStencilTable() const {
assert(LocalPointVaryingStencilPrecisionMatchesType<float>());
return static_cast<StencilTable const *>(
_localPointVaryingStencils.Get<float>());
}
inline StencilTable const *
PatchTable::GetLocalPointFaceVaryingStencilTable(int channel) const {
assert(LocalPointFaceVaryingStencilPrecisionMatchesType<float>());
if (channel >= 0 && channel < (int)_localPointFaceVaryingStencils.size()) {
return static_cast<StencilTable const *>(
_localPointFaceVaryingStencils[channel].Get<float>());
}
return NULL;
}
template <typename REAL>
inline StencilTableReal<REAL> const *
PatchTable::GetLocalPointStencilTable() const {
assert(LocalPointStencilPrecisionMatchesType<REAL>());
return _localPointStencils.Get<REAL>();
}
template <typename REAL>
inline StencilTableReal<REAL> const *
PatchTable::GetLocalPointVaryingStencilTable() const {
assert(LocalPointVaryingStencilPrecisionMatchesType<REAL>());
return _localPointVaryingStencils.Get<REAL>();
}
template <typename REAL>
inline StencilTableReal<REAL> const *
PatchTable::GetLocalPointFaceVaryingStencilTable(int channel) const {
assert(LocalPointFaceVaryingStencilPrecisionMatchesType<REAL>());
if (channel >= 0 && channel < (int)_localPointFaceVaryingStencils.size()) {
return _localPointFaceVaryingStencils[channel].Get<REAL>();
}
return NULL;
}
//
// Computation of local point values:
//
template <class T>
inline void
PatchTable::ComputeLocalPointValues(T const *src, T *dst) const {
assert(LocalPointStencilPrecisionMatchesType<float>());
if (_localPointStencils) {
_localPointStencils.Get<float>()->UpdateValues(src, dst);
}
}
template <class T>
inline void
PatchTable::ComputeLocalPointValuesVarying(T const *src, T *dst) const {
assert(LocalPointVaryingStencilPrecisionMatchesType<float>());
if (_localPointVaryingStencils) {
_localPointVaryingStencils.Get<float>()->UpdateValues(src, dst);
}
}
template <class T>
inline void
PatchTable::ComputeLocalPointValuesFaceVarying(T const *src, T *dst, int channel) const {
assert(LocalPointFaceVaryingStencilPrecisionMatchesType<float>());
if (channel >= 0 && channel < (int)_localPointFaceVaryingStencils.size()) {
if (_localPointFaceVaryingStencils[channel]) {
_localPointFaceVaryingStencils[channel].Get<float>()->UpdateValues(src, dst);
}
}
}
//
// Basis evaluation overloads
//
inline void
PatchTable::EvaluateBasis(PatchHandle const & handle, float u, float v,
float wP[], float wDu[], float wDv[],
float wDuu[], float wDuv[], float wDvv[]) const {
EvaluateBasis<float>(handle, u, v, wP, wDu, wDv, wDuu, wDuv, wDvv);
}
inline void
PatchTable::EvaluateBasis(PatchHandle const & handle, double u, double v,
double wP[], double wDu[], double wDv[],
double wDuu[], double wDuv[], double wDvv[]) const {
EvaluateBasis<double>(handle, u, v, wP, wDu, wDv, wDuu, wDuv, wDvv);
}
inline void
PatchTable::EvaluateBasisVarying(PatchHandle const & handle, float u, float v,
float wP[], float wDu[], float wDv[],
float wDuu[], float wDuv[], float wDvv[]) const {
EvaluateBasisVarying<float>(handle, u, v, wP, wDu, wDv, wDuu, wDuv, wDvv);
}
inline void
PatchTable::EvaluateBasisVarying(PatchHandle const & handle, double u, double v,
double wP[], double wDu[], double wDv[],
double wDuu[], double wDuv[], double wDvv[]) const {
EvaluateBasisVarying<double>(handle, u, v, wP, wDu, wDv, wDuu, wDuv, wDvv);
}
inline void
PatchTable::EvaluateBasisFaceVarying(PatchHandle const & handle, float u, float v,
float wP[], float wDu[], float wDv[],
float wDuu[], float wDuv[], float wDvv[], int channel) const {
EvaluateBasisFaceVarying<float>(handle, u, v, wP, wDu, wDv, wDuu, wDuv, wDvv, channel);
}
inline void
PatchTable::EvaluateBasisFaceVarying(PatchHandle const & handle, double u, double v,
double wP[], double wDu[], double wDv[],
double wDuu[], double wDuv[], double wDvv[], int channel) const {
EvaluateBasisFaceVarying<double>(handle, u, v, wP, wDu, wDv, wDuu, wDuv, wDvv, channel);
}
} // end namespace Far
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_FAR_PATCH_TABLE */
+232
View File
@@ -0,0 +1,232 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_FAR_PATCH_TABLE_FACTORY_H
#define OPENSUBDIV3_FAR_PATCH_TABLE_FACTORY_H
#include "../version.h"
#include "../far/topologyRefiner.h"
#include "../far/patchTable.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far {
/// \brief Factory for constructing a PatchTable from a TopologyRefiner
///
class PatchTableFactory {
public:
/// \brief Public options for the PatchTable factory
///
struct Options {
/// \brief Choice for approximating irregular patches (end-caps)
///
/// This enum specifies how irregular patches (end-caps) are approximated.
/// A basis is chosen, rather than a specific patch type, and has a
/// corresponding patch type for each subdivision scheme, i.e. a quad and
/// triangular patch type exists for each basis. These choices provide a
/// trade-off between surface quality and performance.
///
enum EndCapType {
ENDCAP_NONE = 0, ///< unspecified
ENDCAP_BILINEAR_BASIS, ///< use linear patches (simple quads or tris)
ENDCAP_BSPLINE_BASIS, ///< use BSpline-like patches (same patch type as regular)
ENDCAP_GREGORY_BASIS, ///< use Gregory patches (highest quality, recommended default)
ENDCAP_LEGACY_GREGORY ///< legacy option for 2.x style Gregory patches (Catmark only)
};
Options(unsigned int maxIsolation=10) :
generateAllLevels(false),
includeBaseLevelIndices(true),
includeFVarBaseLevelIndices(false),
triangulateQuads(false),
useSingleCreasePatch(false),
useInfSharpPatch(false),
maxIsolationLevel(maxIsolation),
endCapType(ENDCAP_GREGORY_BASIS),
shareEndCapPatchPoints(true),
generateVaryingTables(true),
generateVaryingLocalPoints(true),
generateFVarTables(false),
patchPrecisionDouble(false),
fvarPatchPrecisionDouble(false),
generateFVarLegacyLinearPatches(true),
generateLegacySharpCornerPatches(true),
numFVarChannels(-1),
fvarChannelIndices(0)
{ }
/// \brief Get endcap basis type
EndCapType GetEndCapType() const { return (EndCapType)endCapType; }
/// \brief Set endcap basis type
void SetEndCapType(EndCapType e) { endCapType = e; }
/// \brief Set precision of vertex patches
template <typename REAL> void SetPatchPrecision();
/// \brief Set precision of face-varying patches
template <typename REAL> void SetFVarPatchPrecision();
/// \brief Determine adaptive refinement options to match assigned patch options
TopologyRefiner::AdaptiveOptions GetRefineAdaptiveOptions() const {
TopologyRefiner::AdaptiveOptions adaptiveOptions(maxIsolationLevel);
adaptiveOptions.useInfSharpPatch = useInfSharpPatch;
adaptiveOptions.useSingleCreasePatch = useSingleCreasePatch;
adaptiveOptions.considerFVarChannels = generateFVarTables &&
!generateFVarLegacyLinearPatches;
return adaptiveOptions;
}
unsigned int generateAllLevels : 1, ///< Generate levels from 'firstLevel' to 'maxLevel' (Uniform mode only)
includeBaseLevelIndices : 1, ///< Include base level in patch point indices (Uniform mode only)
includeFVarBaseLevelIndices : 1, ///< Include base level in face-varying patch point indices (Uniform mode only)
triangulateQuads : 1, ///< Triangulate 'QUADS' primitives (Uniform mode only)
useSingleCreasePatch : 1, ///< Use single crease patch
useInfSharpPatch : 1, ///< Use infinitely-sharp patch
maxIsolationLevel : 4, ///< Cap adaptive feature isolation to the given level (max. 10)
// end-capping
endCapType : 3, ///< EndCapType
shareEndCapPatchPoints : 1, ///< Share endcap patch points among adjacent endcap patches.
///< currently only work with GregoryBasis.
// varying
generateVaryingTables : 1, ///< Generate varying patch tables
generateVaryingLocalPoints : 1, ///< Generate local points with varying patches
// face-varying
generateFVarTables : 1, ///< Generate face-varying patch tables
// precision
patchPrecisionDouble : 1, ///< Generate double-precision stencils for vertex patches
fvarPatchPrecisionDouble : 1, ///< Generate double-precision stencils for face-varying patches
// legacy behaviors (default to true)
generateFVarLegacyLinearPatches : 1, ///< Generate all linear face-varying patches (legacy)
generateLegacySharpCornerPatches : 1; ///< Generate sharp regular patches at smooth corners (legacy)
int numFVarChannels; ///< Number of channel indices and interpolation modes passed
int const * fvarChannelIndices; ///< List containing the indices of the channels selected for the factory
};
/// \brief Instantiates a PatchTable from a client-provided TopologyRefiner.
///
/// A PatchTable can be constructed from a TopologyRefiner that has been
/// either adaptively or uniformly refined. In both cases, the resulting
/// patches reference vertices in the various refined levels by index,
/// and those indices accumulate with the levels in different ways.
///
/// For adaptively refined patches, patches are defined at different levels,
/// including the base level, so the indices of patch vertices include
/// vertices from all levels. A sparse set of patches can be created by
/// restricting the patches generated to those descending from a given set
/// of faces at the base level. This sparse set of base faces is expected
/// to be a subset of the faces that were adaptively refined in the given
/// TopologyRefiner, otherwise results are undefined.
///
/// For uniformly refined patches, all patches are completely defined within
/// the last level. There is often no use for intermediate levels and they
/// can usually be ignored. Indices of patch vertices might therefore be
/// expected to be defined solely within the last level. While this is true
/// for face-varying patches, for historical reasons it is not the case for
/// vertex and varying patches. Indices for vertex and varying patches include
/// the base level in addition to the last level while indices for face-varying
/// patches include only the last level.
///
/// @param refiner TopologyRefiner from which to generate patches
///
/// @param options Options controlling the creation of the table
///
/// @param selectedFaces Only create patches for the given set of base faces.
///
/// @return A new instance of PatchTable
///
static PatchTable * Create(TopologyRefiner const & refiner,
Options options = Options(),
ConstIndexArray selectedFaces = ConstIndexArray());
public:
// PatchFaceTag
//
// This simple struct was previously used within the factory to take inventory of
// various kinds of patches to fully allocate buffers prior to populating them. It
// was not intended to be exposed as part of the public interface.
//
// It is no longer used internally and is being kept here to respect preservation
// of the public interface, but it will be deprecated at the earliest opportunity.
//
/// \brief Obsolete internal struct not intended for public use -- due to
/// be deprecated.
//
struct PatchFaceTag {
public:
unsigned int _hasPatch : 1;
unsigned int _isRegular : 1;
unsigned int _transitionMask : 4;
unsigned int _boundaryMask : 4;
unsigned int _boundaryIndex : 2;
unsigned int _boundaryCount : 3;
unsigned int _hasBoundaryEdge : 3;
unsigned int _isSingleCrease : 1;
void clear();
void assignBoundaryPropertiesFromEdgeMask(int boundaryEdgeMask);
void assignBoundaryPropertiesFromVertexMask(int boundaryVertexMask);
void assignTransitionPropertiesFromEdgeMask(int boundaryVertexMask);
};
typedef std::vector<PatchFaceTag> PatchTagVector;
};
template <> inline void PatchTableFactory::Options::SetPatchPrecision<float>() {
patchPrecisionDouble = false;
}
template <> inline void PatchTableFactory::Options::SetFVarPatchPrecision<float>() {
fvarPatchPrecisionDouble = false;
}
template <> inline void PatchTableFactory::Options::SetPatchPrecision<double>() {
patchPrecisionDouble = true;
}
template <> inline void PatchTableFactory::Options::SetFVarPatchPrecision<double>() {
fvarPatchPrecisionDouble = true;
}
} // end namespace Far
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_FAR_PATCH_TABLE_FACTORY_H */
File diff suppressed because it is too large. Load diff
+106
View File
@@ -0,0 +1,106 @@
//
// Copyright 2015 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_FAR_PTEX_INDICES_H
#define OPENSUBDIV3_FAR_PTEX_INDICES_H
#include "../version.h"
#include "../far/topologyRefiner.h"
#include "../far/types.h"
#include <vector>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far {
///
/// \brief Object used to compute and query ptex face indices.
///
/// Given a refiner, constructing a PtexIndices object builds the mapping
/// from coarse faces to ptex ids. Once built, the object can be used to
/// query the mapping.
///
class PtexIndices {
public:
/// \brief Constructor
PtexIndices(TopologyRefiner const &refiner);
/// \brief Destructor
~PtexIndices();
//@{
///
/// Ptex
///
/// \brief Returns the number of ptex faces in the mesh
///
int GetNumFaces() const;
/// \brief Returns the ptex face index given a coarse face 'f' or -1
///
int GetFaceId(Index f) const;
/// \brief Returns ptex face adjacency information for a given coarse face
///
/// @param refiner refiner used to build this PtexIndices object.
///
/// @param face coarse face index
///
/// @param quadrant quadrant index if 'face' is not a quad (the local ptex
/// sub-face index). Must be less than the number of face
/// vertices.
///
/// @param adjFaces ptex face indices of adjacent faces
///
/// @param adjEdges ptex edge indices of adjacent faces
///
void GetAdjacency(
TopologyRefiner const &refiner,
int face, int quadrant,
int adjFaces[4], int adjEdges[4]) const;
//@}
private:
void initializePtexIndices(TopologyRefiner const &refiner);
private:
std::vector<Index> _ptexIndices;
};
} // end namespace Far
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_FAR_PTEX_INDICES_H */
+793
View File
@@ -0,0 +1,793 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_FAR_STENCILTABLE_H
#define OPENSUBDIV3_FAR_STENCILTABLE_H
#include "../version.h"
#include "../far/types.h"
#include <cassert>
#include <cstring>
#include <vector>
#include <iostream>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far {
// Forward declarations for friends:
class PatchTableBuilder;
template <typename REAL> class StencilTableFactoryReal;
template <typename REAL> class LimitStencilTableFactoryReal;
/// \brief Vertex stencil descriptor
///
/// Allows access and manipulation of a single stencil in a StencilTable.
///
template <typename REAL>
class StencilReal {
public:
/// \brief Default constructor
StencilReal() {}
/// \brief Constructor
///
/// @param size Table pointer to the size of the stencil
///
/// @param indices Table pointer to the vertex indices of the stencil
///
/// @param weights Table pointer to the vertex weights of the stencil
///
StencilReal(int * size, Index * indices, REAL * weights)
: _size(size), _indices(indices), _weights(weights) { }
/// \brief Copy constructor
StencilReal(StencilReal const & other) {
_size = other._size;
_indices = other._indices;
_weights = other._weights;
}
/// \brief Returns the size of the stencil
int GetSize() const {
return *_size;
}
/// \brief Returns the size of the stencil as a pointer
int * GetSizePtr() const {
return _size;
}
/// \brief Returns the control vertices' indices
Index const * GetVertexIndices() const {
return _indices;
}
/// \brief Returns the interpolation weights
REAL const * GetWeights() const {
return _weights;
}
/// \brief Advance to the next stencil in the table
void Next() {
int stride = *_size;
++_size;
_indices += stride;
_weights += stride;
}
protected:
friend class StencilTableFactoryReal<REAL>;
friend class LimitStencilTableFactoryReal<REAL>;
int * _size;
Index * _indices;
REAL * _weights;
};
/// \brief Vertex stencil class wrapping the template for compatibility.
///
class Stencil : public StencilReal<float> {
protected:
typedef StencilReal<float> BaseStencil;
public:
Stencil() : BaseStencil() { }
Stencil(BaseStencil const & other) : BaseStencil(other) { }
Stencil(int * size, Index * indices, float * weights)
: BaseStencil(size, indices, weights) { }
};
/// \brief Table of subdivision stencils.
///
/// Stencils are the most direct method of evaluation of locations on the limit
/// of a surface. Every point of a limit surface can be computed by linearly
/// blending a collection of coarse control vertices.
///
/// A stencil assigns a series of control vertex indices with a blending weight
/// that corresponds to a unique parametric location of the limit surface. When
/// the control vertices move in space, the limit location can be very efficiently
/// recomputed simply by applying the blending weights to the series of coarse
/// control vertices.
///
template <typename REAL>
class StencilTableReal {
protected:
StencilTableReal(int numControlVerts,
std::vector<int> const& offsets,
std::vector<int> const& sizes,
std::vector<int> const& sources,
std::vector<REAL> const& weights,
bool includeCoarseVerts,
size_t firstOffset);
public:
virtual ~StencilTableReal() {};
/// \brief Returns the number of stencils in the table
int GetNumStencils() const {
return (int)_sizes.size();
}
/// \brief Returns the number of control vertices indexed in the table
int GetNumControlVertices() const {
return _numControlVertices;
}
/// \brief Returns a Stencil at index i in the table
StencilReal<REAL> GetStencil(Index i) const;
/// \brief Returns the number of control vertices of each stencil in the table
std::vector<int> const & GetSizes() const {
return _sizes;
}
/// \brief Returns the offset to a given stencil (factory may leave empty)
std::vector<Index> const & GetOffsets() const {
return _offsets;
}
/// \brief Returns the indices of the control vertices
std::vector<Index> const & GetControlIndices() const {
return _indices;
}
/// \brief Returns the stencil interpolation weights
std::vector<REAL> const & GetWeights() const {
return _weights;
}
/// \brief Returns the stencil at index i in the table
StencilReal<REAL> operator[] (Index index) const;
/// \brief Updates point values based on the control values
///
/// \note The destination buffers are assumed to have allocated at least
/// \c GetNumStencils() elements.
///
/// @param srcValues Buffer with primvar data for the control vertices
///
/// @param dstValues Destination buffer for the interpolated primvar data
///
/// @param start Index of first destination value to update
///
/// @param end Index of last destination value to update
///
template <class T, class U>
void UpdateValues(T const &srcValues, U &dstValues, Index start=-1, Index end=-1) const {
this->update(srcValues, dstValues, _weights, start, end);
}
template <class T1, class T2, class U>
void UpdateValues(T1 const &srcBase, int numBase, T2 const &srcRef,
U &dstValues, Index start=-1, Index end=-1) const {
this->update(srcBase, numBase, srcRef, dstValues, _weights, start, end);
}
// Pointer interface for backward compatibility
template <class T, class U>
void UpdateValues(T const *src, U *dst, Index start=-1, Index end=-1) const {
this->update(src, dst, _weights, start, end);
}
template <class T1, class T2, class U>
void UpdateValues(T1 const *srcBase, int numBase, T2 const *srcRef,
U *dst, Index start=-1, Index end=-1) const {
this->update(srcBase, numBase, srcRef, dst, _weights, start, end);
}
/// \brief Clears the stencils from the table
void Clear();
protected:
// Update values by applying cached stencil weights to new control values
template <class T, class U>
void update( T const &srcValues, U &dstValues,
std::vector<REAL> const & valueWeights, Index start, Index end) const;
template <class T1, class T2, class U>
void update( T1 const &srcBase, int numBase, T2 const &srcRef, U &dstValues,
std::vector<REAL> const & valueWeights, Index start, Index end) const;
// Populate the offsets table from the stencil sizes in _sizes (factory helper)
void generateOffsets();
// Resize the table arrays (factory helper)
void resize(int nstencils, int nelems);
// Reserves the table arrays (factory helper)
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:
StencilTableReal() : _numControlVertices(0) {}
StencilTableReal(int numControlVerts)
: _numControlVertices(numControlVerts)
{ }
friend class StencilTableFactoryReal<REAL>;
friend class Far::PatchTableBuilder;
int _numControlVertices; // number of control vertices
std::vector<int> _sizes; // number of coefficients for each stencil
std::vector<Index> _offsets, // offset to the start of each stencil
_indices; // indices of contributing coarse vertices
std::vector<REAL> _weights; // stencil weight coefficients
};
/// \brief Stencil table class wrapping the template for compatibility.
///
class StencilTable : public StencilTableReal<float> {
protected:
typedef StencilTableReal<float> BaseTable;
public:
Stencil GetStencil(Index index) const {
return Stencil(BaseTable::GetStencil(index));
}
Stencil operator[] (Index index) const {
return Stencil(BaseTable::GetStencil(index));
}
protected:
StencilTable() : BaseTable() { }
StencilTable(int numControlVerts) : BaseTable(numControlVerts) { }
StencilTable(int numControlVerts,
std::vector<int> const& offsets,
std::vector<int> const& sizes,
std::vector<int> const& sources,
std::vector<float> const& weights,
bool includeCoarseVerts,
size_t firstOffset)
: BaseTable(numControlVerts, offsets,
sizes, sources, weights, includeCoarseVerts, firstOffset) { }
};
/// \brief Limit point stencil descriptor
///
template <typename REAL>
class LimitStencilReal : public StencilReal<REAL> {
public:
/// \brief Constructor
///
/// @param size Table pointer to the size of the stencil
///
/// @param indices Table pointer to the vertex indices of the stencil
///
/// @param weights Table pointer to the vertex weights of the stencil
///
/// @param duWeights Table pointer to the 'u' derivative weights
///
/// @param dvWeights Table pointer to the 'v' derivative weights
///
/// @param duuWeights Table pointer to the 'uu' derivative weights
///
/// @param duvWeights Table pointer to the 'uv' derivative weights
///
/// @param dvvWeights Table pointer to the 'vv' derivative weights
///
LimitStencilReal( int* size,
Index * indices,
REAL * weights,
REAL * duWeights=0,
REAL * dvWeights=0,
REAL * duuWeights=0,
REAL * duvWeights=0,
REAL * dvvWeights=0)
: StencilReal<REAL>(size, indices, weights),
_duWeights(duWeights),
_dvWeights(dvWeights),
_duuWeights(duuWeights),
_duvWeights(duvWeights),
_dvvWeights(dvvWeights) {
}
/// \brief Returns the u derivative weights
REAL const * GetDuWeights() const {
return _duWeights;
}
/// \brief Returns the v derivative weights
REAL const * GetDvWeights() const {
return _dvWeights;
}
/// \brief Returns the uu derivative weights
REAL const * GetDuuWeights() const {
return _duuWeights;
}
/// \brief Returns the uv derivative weights
REAL const * GetDuvWeights() const {
return _duvWeights;
}
/// \brief Returns the vv derivative weights
REAL const * GetDvvWeights() const {
return _dvvWeights;
}
/// \brief Advance to the next stencil in the table
void Next() {
int stride = *this->_size;
++this->_size;
this->_indices += stride;
this->_weights += stride;
if (_duWeights) _duWeights += stride;
if (_dvWeights) _dvWeights += stride;
if (_duuWeights) _duuWeights += stride;
if (_duvWeights) _duvWeights += stride;
if (_dvvWeights) _dvvWeights += stride;
}
private:
friend class StencilTableFactoryReal<REAL>;
friend class LimitStencilTableFactoryReal<REAL>;
REAL * _duWeights, // pointer to stencil u derivative limit weights
* _dvWeights, // pointer to stencil v derivative limit weights
* _duuWeights, // pointer to stencil uu derivative limit weights
* _duvWeights, // pointer to stencil uv derivative limit weights
* _dvvWeights; // pointer to stencil vv derivative limit weights
};
/// \brief Limit point stencil class wrapping the template for compatibility.
///
class LimitStencil : public LimitStencilReal<float> {
protected:
typedef LimitStencilReal<float> BaseStencil;
public:
LimitStencil(BaseStencil const & other) : BaseStencil(other) { }
LimitStencil(int* size, Index * indices, float * weights,
float * duWeights=0, float * dvWeights=0,
float * duuWeights=0, float * duvWeights=0, float * dvvWeights=0)
: BaseStencil(size, indices, weights,
duWeights, dvWeights, duuWeights, duvWeights, dvvWeights) { }
};
/// \brief Table of limit subdivision stencils.
///
template <typename REAL>
class LimitStencilTableReal : public StencilTableReal<REAL> {
protected:
LimitStencilTableReal(
int numControlVerts,
std::vector<int> const& offsets,
std::vector<int> const& sizes,
std::vector<int> const& sources,
std::vector<REAL> const& weights,
std::vector<REAL> const& duWeights,
std::vector<REAL> const& dvWeights,
std::vector<REAL> const& duuWeights,
std::vector<REAL> const& duvWeights,
std::vector<REAL> const& dvvWeights,
bool includeCoarseVerts,
size_t firstOffset);
public:
/// \brief Returns a LimitStencil at index i in the table
LimitStencilReal<REAL> GetLimitStencil(Index i) const;
/// \brief Returns the limit stencil at index i in the table
LimitStencilReal<REAL> operator[] (Index index) const;
/// \brief Returns the 'u' derivative stencil interpolation weights
std::vector<REAL> const & GetDuWeights() const {
return _duWeights;
}
/// \brief Returns the 'v' derivative stencil interpolation weights
std::vector<REAL> const & GetDvWeights() const {
return _dvWeights;
}
/// \brief Returns the 'uu' derivative stencil interpolation weights
std::vector<REAL> const & GetDuuWeights() const {
return _duuWeights;
}
/// \brief Returns the 'uv' derivative stencil interpolation weights
std::vector<REAL> const & GetDuvWeights() const {
return _duvWeights;
}
/// \brief Returns the 'vv' derivative stencil interpolation weights
std::vector<REAL> const & GetDvvWeights() const {
return _dvvWeights;
}
/// \brief Updates derivative values based on the control values
///
/// \note The destination buffers ('uderivs' & 'vderivs') are assumed to
/// have allocated at least \c GetNumStencils() elements.
///
/// @param srcValues Buffer with primvar data for the control vertices
///
/// @param uderivs Destination buffer for the interpolated 'u'
/// derivative primvar data
///
/// @param vderivs Destination buffer for the interpolated 'v'
/// derivative primvar data
///
/// @param start Index of first destination derivative to update
///
/// @param end Index of last destination derivative to update
///
template <class T, class U>
void UpdateDerivs(T const & srcValues, U & uderivs, U & vderivs,
int start=-1, int end=-1) const {
this->update(srcValues, uderivs, _duWeights, start, end);
this->update(srcValues, vderivs, _dvWeights, start, end);
}
template <class T1, class T2, class U>
void UpdateDerivs(T1 const & srcBase, int numBase, T2 const & srcRef,
U & uderivs, U & vderivs, int start=-1, int end=-1) const {
this->update(srcBase, numBase, srcRef, uderivs, _duWeights, start, end);
this->update(srcBase, numBase, srcRef, vderivs, _dvWeights, start, end);
}
// Pointer interface for backward compatibility
template <class T, class U>
void UpdateDerivs(T const *src, U *uderivs, U *vderivs,
int start=-1, int end=-1) const {
this->update(src, uderivs, _duWeights, start, end);
this->update(src, vderivs, _dvWeights, start, end);
}
template <class T1, class T2, class U>
void UpdateDerivs(T1 const *srcBase, int numBase, T2 const *srcRef,
U *uderivs, U *vderivs, int start=-1, int end=-1) const {
this->update(srcBase, numBase, srcRef, uderivs, _duWeights, start, end);
this->update(srcBase, numBase, srcRef, vderivs, _dvWeights, start, end);
}
/// \brief Updates 2nd derivative values based on the control values
///
/// \note The destination buffers ('uuderivs', 'uvderivs', & 'vderivs') are
/// assumed to have allocated at least \c GetNumStencils() elements.
///
/// @param srcValues Buffer with primvar data for the control vertices
///
/// @param uuderivs Destination buffer for the interpolated 'uu'
/// derivative primvar data
///
/// @param uvderivs Destination buffer for the interpolated 'uv'
/// derivative primvar data
///
/// @param vvderivs Destination buffer for the interpolated 'vv'
/// derivative primvar data
///
/// @param start Index of first destination derivative to update
///
/// @param end Index of last destination derivative to update
///
template <class T, class U>
void Update2ndDerivs(T const & srcValues,
U & uuderivs, U & uvderivs, U & vvderivs,
int start=-1, int end=-1) const {
this->update(srcValues, uuderivs, _duuWeights, start, end);
this->update(srcValues, uvderivs, _duvWeights, start, end);
this->update(srcValues, vvderivs, _dvvWeights, start, end);
}
template <class T1, class T2, class U>
void Update2ndDerivs(T1 const & srcBase, int numBase, T2 const & srcRef,
U & uuderivs, U & uvderivs, U & vvderivs, int start=-1, int end=-1) const {
this->update(srcBase, numBase, srcRef, uuderivs, _duuWeights, start, end);
this->update(srcBase, numBase, srcRef, uvderivs, _duvWeights, start, end);
this->update(srcBase, numBase, srcRef, vvderivs, _dvvWeights, start, end);
}
// Pointer interface for backward compatibility
template <class T, class U>
void Update2ndDerivs(T const *src, T *uuderivs, U *uvderivs, U *vvderivs,
int start=-1, int end=-1) const {
this->update(src, uuderivs, _duuWeights, start, end);
this->update(src, uvderivs, _duvWeights, start, end);
this->update(src, vvderivs, _dvvWeights, start, end);
}
template <class T1, class T2, class U>
void Update2ndDerivs(T1 const *srcBase, int numBase, T2 const *srcRef,
U *uuderivs, U *uvderivs, U *vvderivs, int start=-1, int end=-1) const {
this->update(srcBase, numBase, srcRef, uuderivs, _duuWeights, start, end);
this->update(srcBase, numBase, srcRef, uvderivs, _duvWeights, start, end);
this->update(srcBase, numBase, srcRef, vvderivs, _dvvWeights, start, end);
}
/// \brief Clears the stencils from the table
void Clear();
private:
friend class LimitStencilTableFactoryReal<REAL>;
// Resize the table arrays (factory helper)
void resize(int nstencils, int nelems);
private:
std::vector<REAL> _duWeights, // u derivative limit stencil weights
_dvWeights, // v derivative limit stencil weights
_duuWeights, // uu derivative limit stencil weights
_duvWeights, // uv derivative limit stencil weights
_dvvWeights; // vv derivative limit stencil weights
};
/// \brief Limit stencil table class wrapping the template for compatibility.
///
class LimitStencilTable : public LimitStencilTableReal<float> {
protected:
typedef LimitStencilTableReal<float> BaseTable;
public:
LimitStencil GetLimitStencil(Index index) const {
return LimitStencil(BaseTable::GetLimitStencil(index));
}
LimitStencil operator[] (Index index) const {
return LimitStencil(BaseTable::GetLimitStencil(index));
}
protected:
LimitStencilTable(int numControlVerts,
std::vector<int> const& offsets,
std::vector<int> const& sizes,
std::vector<int> const& sources,
std::vector<float> const& weights,
std::vector<float> const& duWeights,
std::vector<float> const& dvWeights,
std::vector<float> const& duuWeights,
std::vector<float> const& duvWeights,
std::vector<float> const& dvvWeights,
bool includeCoarseVerts,
size_t firstOffset)
: BaseTable(numControlVerts,
offsets, sizes, sources, weights,
duWeights, dvWeights, duuWeights, duvWeights, dvvWeights,
includeCoarseVerts, firstOffset) { }
};
// Update values by applying cached stencil weights to new control values
template <typename REAL>
template <class T1, class T2, class U> void
StencilTableReal<REAL>::update(T1 const &srcBase, int numBase,
T2 const &srcRef, U &dstValues,
std::vector<REAL> const &valueWeights, Index start, Index end) const {
int const * sizes = &_sizes.at(0);
Index const * indices = &_indices.at(0);
REAL const * weights = &valueWeights.at(0);
if (start > 0) {
assert(start < (Index)_offsets.size());
sizes += start;
indices += _offsets[start];
weights += _offsets[start];
} else {
start = 0;
}
int nstencils = ((end < start) ? GetNumStencils() : end) - start;
for (int i = 0; i < nstencils; ++i, ++sizes) {
dstValues[start + i].Clear();
for (int j = 0; j < *sizes; ++j, ++indices, ++weights) {
if (*indices < numBase) {
dstValues[start + i].AddWithWeight(srcBase[*indices], *weights);
} else {
dstValues[start + i].AddWithWeight(srcRef[*indices - numBase], *weights);
}
}
}
}
template <typename REAL>
template <class T, class U> void
StencilTableReal<REAL>::update(T const &srcValues, U &dstValues,
std::vector<REAL> const &valueWeights, Index start, Index end) const {
int const * sizes = &_sizes.at(0);
Index const * indices = &_indices.at(0);
REAL const * weights = &valueWeights.at(0);
if (start > 0) {
assert(start < (Index)_offsets.size());
sizes += start;
indices += _offsets[start];
weights += _offsets[start];
} else {
start = 0;
}
int nstencils = ((end < start) ? GetNumStencils() : end) - start;
for (int i = 0; i < nstencils; ++i, ++sizes) {
dstValues[start + i].Clear();
for (int j = 0; j < *sizes; ++j, ++indices, ++weights) {
dstValues[start + i].AddWithWeight(srcValues[*indices], *weights);
}
}
}
template <typename REAL>
inline void
StencilTableReal<REAL>::generateOffsets() {
Index offset=0;
int noffsets = (int)_sizes.size();
_offsets.resize(noffsets);
for (int i=0; i<(int)_sizes.size(); ++i ) {
_offsets[i]=offset;
offset+=_sizes[i];
}
}
template <typename REAL>
inline void
StencilTableReal<REAL>::resize(int nstencils, int nelems) {
_sizes.resize(nstencils);
_indices.resize(nelems);
_weights.resize(nelems);
}
template <typename REAL>
inline void
StencilTableReal<REAL>::reserve(int nstencils, int nelems) {
_sizes.reserve(nstencils);
_indices.reserve(nelems);
_weights.reserve(nelems);
}
template <typename REAL>
inline void
StencilTableReal<REAL>::shrinkToFit() {
std::vector<int>(_sizes).swap(_sizes);
std::vector<Index>(_indices).swap(_indices);
std::vector<REAL>(_weights).swap(_weights);
}
template <typename REAL>
inline void
StencilTableReal<REAL>::finalize() {
shrinkToFit();
generateOffsets();
}
// Returns a Stencil at index i in the table
template <typename REAL>
inline StencilReal<REAL>
StencilTableReal<REAL>::GetStencil(Index i) const {
assert((! _offsets.empty()) && i<(int)_offsets.size());
Index ofs = _offsets[i];
return StencilReal<REAL>(const_cast<int*>(&_sizes[i]),
const_cast<Index*>(&_indices[ofs]),
const_cast<REAL*>(&_weights[ofs]));
}
template <typename REAL>
inline StencilReal<REAL>
StencilTableReal<REAL>::operator[] (Index index) const {
return GetStencil(index);
}
template <typename REAL>
inline void
LimitStencilTableReal<REAL>::resize(int nstencils, int nelems) {
StencilTableReal<REAL>::resize(nstencils, nelems);
_duWeights.resize(nelems);
_dvWeights.resize(nelems);
}
// Returns a LimitStencil at index i in the table
template <typename REAL>
inline LimitStencilReal<REAL>
LimitStencilTableReal<REAL>::GetLimitStencil(Index i) const {
assert((! this->GetOffsets().empty()) && i<(int)this->GetOffsets().size());
Index ofs = this->GetOffsets()[i];
if (!_duWeights.empty() && !_dvWeights.empty() &&
!_duuWeights.empty() && !_duvWeights.empty() && !_dvvWeights.empty()) {
return LimitStencilReal<REAL>(
const_cast<int *>(&this->GetSizes()[i]),
const_cast<Index *>(&this->GetControlIndices()[ofs]),
const_cast<REAL *>(&this->GetWeights()[ofs]),
const_cast<REAL *>(&GetDuWeights()[ofs]),
const_cast<REAL *>(&GetDvWeights()[ofs]),
const_cast<REAL *>(&GetDuuWeights()[ofs]),
const_cast<REAL *>(&GetDuvWeights()[ofs]),
const_cast<REAL *>(&GetDvvWeights()[ofs]) );
} else if (!_duWeights.empty() && !_dvWeights.empty()) {
return LimitStencilReal<REAL>(
const_cast<int *>(&this->GetSizes()[i]),
const_cast<Index *>(&this->GetControlIndices()[ofs]),
const_cast<REAL *>(&this->GetWeights()[ofs]),
const_cast<REAL *>(&GetDuWeights()[ofs]),
const_cast<REAL *>(&GetDvWeights()[ofs]) );
} else {
return LimitStencilReal<REAL>(
const_cast<int *>(&this->GetSizes()[i]),
const_cast<Index *>(&this->GetControlIndices()[ofs]),
const_cast<REAL *>(&this->GetWeights()[ofs]) );
}
}
template <typename REAL>
inline LimitStencilReal<REAL>
LimitStencilTableReal<REAL>::operator[] (Index index) const {
return GetLimitStencil(index);
}
} // end namespace Far
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_FAR_STENCILTABLE_H
@@ -0,0 +1,384 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_FAR_STENCILTABLE_FACTORY_H
#define OPENSUBDIV3_FAR_STENCILTABLE_FACTORY_H
#include "../version.h"
#include "../far/patchTable.h"
#include <vector>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far {
class TopologyRefiner;
template <typename REAL> class StencilReal;
template <typename REAL> class StencilTableReal;
template <typename REAL> class LimitStencilReal;
template <typename REAL> class LimitStencilTableReal;
/// \brief A specialized factory for StencilTable
///
template <typename REAL>
class StencilTableFactoryReal {
public:
enum Mode {
INTERPOLATE_VERTEX=0, ///< vertex primvar stencils
INTERPOLATE_VARYING, ///< varying primvar stencils
INTERPOLATE_FACE_VARYING ///< face-varying primvar stencils
};
struct Options {
Options() : interpolationMode(INTERPOLATE_VERTEX),
generateOffsets(false),
generateControlVerts(false),
generateIntermediateLevels(true),
factorizeIntermediateLevels(true),
maxLevel(10),
fvarChannel(0) { }
unsigned int interpolationMode : 2, ///< interpolation mode
generateOffsets : 1, ///< populate optional "_offsets" field
generateControlVerts : 1, ///< generate stencils for control-vertices
generateIntermediateLevels : 1, ///< vertices at all levels or highest only
factorizeIntermediateLevels : 1, ///< accumulate stencil weights from control
/// vertices or from the stencils of the
/// previous level
maxLevel : 4; ///< generate stencils up to 'maxLevel'
unsigned int fvarChannel; ///< face-varying channel to use
/// when generating face-varying stencils
};
/// \brief Instantiates StencilTable from TopologyRefiner that have been
/// refined uniformly or adaptively.
///
/// \note The factory only creates stencils for vertices that have already
/// been refined in the TopologyRefiner. Use RefineUniform() or
/// RefineAdaptive() before constructing the stencils.
///
/// @param refiner The TopologyRefiner containing the topology
///
/// @param options Options controlling the creation of the table
///
static StencilTableReal<REAL> const * Create(
TopologyRefiner const & refiner, Options options = Options());
/// \brief Instantiates StencilTable by concatenating an array of existing
/// stencil tables.
///
/// \note This factory checks that the stencil tables point to the same set
/// of supporting control vertices - no re-indexing is done.
/// GetNumControlVertices() *must* return the same value for all input
/// tables.
///
/// @param numTables Number of input StencilTables
///
/// @param tables Array of input StencilTables
///
static StencilTableReal<REAL> const * Create(
int numTables, StencilTableReal<REAL> const ** tables);
/// \brief Utility function for stencil splicing for local point stencils.
///
/// @param refiner The TopologyRefiner containing the topology
///
/// @param baseStencilTable Input StencilTable for refined vertices
///
/// @param localPointStencilTable
/// StencilTable for the change of basis patch points.
///
/// @param factorize If factorize is set to true, endcap stencils will be
/// factorized with supporting vertices from baseStencil
/// table so that the endcap points can be computed
/// directly from control vertices.
///
static StencilTableReal<REAL> const * AppendLocalPointStencilTable(
TopologyRefiner const &refiner,
StencilTableReal<REAL> const *baseStencilTable,
StencilTableReal<REAL> const *localPointStencilTable,
bool factorize = true);
/// \brief Utility function for stencil splicing for local point varying stencils.
///
/// @param refiner The TopologyRefiner containing the topology
///
/// @param baseStencilTable Input StencilTable for refined vertices
///
/// @param localPointStencilTable
/// StencilTable for the change of basis patch points.
///
/// @param factorize If factorize is set to true, endcap stencils will be
/// factorized with supporting vertices from baseStencil
/// table so that the endcap points can be computed
/// directly from control vertices.
///
static StencilTableReal<REAL> const * AppendLocalPointStencilTableVarying(
TopologyRefiner const &refiner,
StencilTableReal<REAL> const *baseStencilTable,
StencilTableReal<REAL> const *localPointStencilTable,
bool factorize = true) {
return AppendLocalPointStencilTable(
refiner, baseStencilTable, localPointStencilTable, factorize);
}
/// \brief Utility function for stencil splicing for local point
/// face-varying stencils.
///
/// @param refiner The TopologyRefiner containing the topology
///
/// @param baseStencilTable Input StencilTable for refined vertices
///
/// @param localPointStencilTable
/// StencilTable for the change of basis patch points.
///
/// @param channel face-varying channel
///
/// @param factorize If factorize is set to true, endcap stencils will be
/// factorized with supporting vertices from baseStencil
/// table so that the endcap points can be computed
/// directly from control vertices.
///
static StencilTableReal<REAL> const * AppendLocalPointStencilTableFaceVarying(
TopologyRefiner const &refiner,
StencilTableReal<REAL> const *baseStencilTable,
StencilTableReal<REAL> const *localPointStencilTable,
int channel = 0,
bool factorize = true);
private:
// Generate stencils for the coarse control-vertices (single weight = 1.0f)
static void generateControlVertStencils(
int numControlVerts,
StencilReal<REAL> & dst);
// Internal method to splice local point stencils
static StencilTableReal<REAL> const * appendLocalPointStencilTable(
TopologyRefiner const &refiner,
StencilTableReal<REAL> const * baseStencilTable,
StencilTableReal<REAL> const * localPointStencilTable,
int channel,
bool factorize);
};
/// \brief A specialized factory for LimitStencilTable
///
/// The LimitStencilTableFactory creates a table of limit stencils. Limit
/// stencils can interpolate any arbitrary location on the limit surface.
/// The stencils will be bilinear if the surface is refined uniformly, and
/// bicubic if feature adaptive isolation is used instead.
///
/// Surface locations are expressed as a combination of ptex face index and
/// normalized (s,t) patch coordinates. The factory exposes the LocationArray
/// struct as a container for these location descriptors.
///
template <typename REAL>
class LimitStencilTableFactoryReal {
public:
enum Mode {
INTERPOLATE_VERTEX=0, ///< vertex primvar stencils
INTERPOLATE_VARYING, ///< varying primvar stencils
INTERPOLATE_FACE_VARYING ///< face-varying primvar stencils
};
struct Options {
Options() : interpolationMode(INTERPOLATE_VERTEX),
generate1stDerivatives(true),
generate2ndDerivatives(false),
fvarChannel(0) { }
unsigned int interpolationMode : 2, ///< interpolation mode
generate1stDerivatives : 1, ///< Generate weights for 1st derivatives
generate2ndDerivatives : 1; ///< Generate weights for 2nd derivatives
unsigned int fvarChannel; ///< face-varying channel to use
};
/// \brief Descriptor for limit surface locations
struct LocationArray {
LocationArray() : ptexIdx(-1), numLocations(0), s(0), t(0) { }
int ptexIdx, ///< ptex face index
numLocations; ///< number of (u,v) coordinates in the array
REAL const * s, ///< array of u coordinates
* t; ///< array of v coordinates
};
typedef std::vector<LocationArray> LocationArrayVec;
/// \brief Instantiates LimitStencilTable from a TopologyRefiner that has
/// been refined either uniformly or adaptively.
///
/// @param refiner The TopologyRefiner containing the topology
///
/// @param locationArrays An array of surface location descriptors
/// (see LocationArray)
///
/// @param cvStencils A StencilTable generated from the TopologyRefiner
/// (Optional: prevents redundant instantiation of the
/// table if available. The given table must at least
/// contain stencils for all control points and all
/// refined points -- any stencils for local points of
/// a PatchTable must match the PatchTable provided or
/// internally generated)
///
/// @param patchTable A PatchTable generated from the TopologyRefiner
/// (Optional: prevents redundant instantiation of the
/// table if available. The given table must match
/// the optional StencilTable if also provided)
///
/// @param options Options controlling the creation of the table
///
static LimitStencilTableReal<REAL> const * Create(
TopologyRefiner const & refiner,
LocationArrayVec const & locationArrays,
StencilTableReal<REAL> const * cvStencils = 0,
PatchTable const * patchTable = 0,
Options options = Options());
};
//
// Public wrapper classes for the templates
//
class Stencil;
class StencilTable;
/// \brief Stencil table factory class wrapping the template for compatibility.
///
class StencilTableFactory : public StencilTableFactoryReal<float> {
private:
typedef StencilTableFactoryReal<float> BaseFactory;
typedef StencilTableReal<float> BaseTable;
public:
static StencilTable const * Create(
TopologyRefiner const & refiner, Options options = Options()) {
return static_cast<StencilTable const *>(
BaseFactory::Create(refiner, options));
}
static StencilTable const * Create(
int numTables, StencilTable const ** tables) {
return static_cast<StencilTable const *>(
BaseFactory::Create(numTables,
reinterpret_cast<BaseTable const **>(tables)));
}
static StencilTable const * AppendLocalPointStencilTable(
TopologyRefiner const &refiner,
StencilTable const *baseStencilTable,
StencilTable const *localPointStencilTable,
bool factorize = true) {
return static_cast<StencilTable const *>(
BaseFactory::AppendLocalPointStencilTable(refiner,
static_cast<BaseTable const *>(baseStencilTable),
static_cast<BaseTable const *>(localPointStencilTable),
factorize));
}
static StencilTable const * AppendLocalPointStencilTableVarying(
TopologyRefiner const &refiner,
StencilTable const *baseStencilTable,
StencilTable const *localPointStencilTable,
bool factorize = true) {
return static_cast<StencilTable const *>(
BaseFactory::AppendLocalPointStencilTableVarying(refiner,
static_cast<BaseTable const *>(baseStencilTable),
static_cast<BaseTable const *>(localPointStencilTable),
factorize));
}
static StencilTable const * AppendLocalPointStencilTableFaceVarying(
TopologyRefiner const &refiner,
StencilTable const *baseStencilTable,
StencilTable const *localPointStencilTable,
int channel = 0,
bool factorize = true) {
return static_cast<StencilTable const *>(
BaseFactory::AppendLocalPointStencilTableFaceVarying(refiner,
static_cast<BaseTable const *>(baseStencilTable),
static_cast<BaseTable const *>(localPointStencilTable),
channel, factorize));
}
};
class LimitStencil;
class LimitStencilTable;
/// \brief Stencil table factory class wrapping the template for compatibility.
///
class LimitStencilTableFactory : public LimitStencilTableFactoryReal<float> {
private:
typedef LimitStencilTableFactoryReal<float> BaseFactory;
typedef StencilTableReal<float> BaseTable;
public:
static LimitStencilTable const * Create(
TopologyRefiner const & refiner,
LocationArrayVec const & locationArrays,
StencilTable const * cvStencils = 0,
PatchTable const * patchTable = 0,
Options options = Options()) {
return static_cast<LimitStencilTable const *>(
BaseFactory::Create(
refiner,
locationArrays,
static_cast<BaseTable const *>(cvStencils),
patchTable,
options));
}
};
} // end namespace Far
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_FAR_STENCILTABLE_FACTORY_H
+127
View File
@@ -0,0 +1,127 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_FAR_TOPOLOGY_DESCRIPTOR_H
#define OPENSUBDIV3_FAR_TOPOLOGY_DESCRIPTOR_H
#include "../version.h"
#include "../far/topologyRefiner.h"
#include "../far/topologyRefinerFactory.h"
#include "../far/error.h"
#include <cassert>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far {
///
/// \brief A simple reference to raw topology data for use with TopologyRefinerFactory
///
/// TopologyDescriptor is a simple struct containing references to raw topology data used
/// to construct a TopologyRefiner. It is not a requirement but a convenience for use
/// with TopologyRefinerFactory when mesh topology is not available in an existing mesh
/// data structure. It should be functionally complete and simple to use, but for more
/// demanding situations, writing a custom Factory is usually warranted.
///
struct TopologyDescriptor {
int numVertices,
numFaces;
int const * numVertsPerFace;
Index const * vertIndicesPerFace;
int numCreases;
Index const * creaseVertexIndexPairs;
float const * creaseWeights;
int numCorners;
Index const * cornerVertexIndices;
float const * cornerWeights;
int numHoles;
Index const * holeIndices;
bool isLeftHanded;
// Face-varying data channel -- value indices correspond to vertex indices,
// i.e. one for every vertex of every face:
//
struct FVarChannel {
int numValues;
Index const * valueIndices;
FVarChannel() : numValues(0), valueIndices(0) { }
};
int numFVarChannels;
FVarChannel const * fvarChannels;
TopologyDescriptor();
};
//
// Forward declarations of required TopologyRefinerFactory<TopologyDescriptor>
// specializations (defined internally):
//
// @cond EXCLUDE_DOXYGEN
template <>
bool
TopologyRefinerFactory<TopologyDescriptor>::resizeComponentTopology(
TopologyRefiner & refiner, TopologyDescriptor const & desc);
template <>
bool
TopologyRefinerFactory<TopologyDescriptor>::assignComponentTopology(
TopologyRefiner & refiner, TopologyDescriptor const & desc);
template <>
bool
TopologyRefinerFactory<TopologyDescriptor>::assignComponentTags(
TopologyRefiner & refiner, TopologyDescriptor const & desc);
template <>
bool
TopologyRefinerFactory<TopologyDescriptor>::assignFaceVaryingTopology(
TopologyRefiner & refiner, TopologyDescriptor const & desc);
template <>
void
TopologyRefinerFactory<TopologyDescriptor>::reportInvalidTopology(
TopologyError errCode, char const * msg, TopologyDescriptor const & desc);
// @endcond
} // end namespace Far
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_FAR_TOPOLOGY_DESCRIPTOR_H */
+273
View File
@@ -0,0 +1,273 @@
//
// Copyright 2015 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_FAR_TOPOLOGY_LEVEL_H
#define OPENSUBDIV3_FAR_TOPOLOGY_LEVEL_H
#include "../version.h"
#include "../vtr/level.h"
#include "../vtr/refinement.h"
#include "../far/types.h"
#include <vector>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far {
///
/// \brief An interface for accessing data in a specific level of a refined topology hierarchy.
///
/// TopologyLevel provides an interface to data in a specific level of a topology hierarchy.
/// Instances of TopologyLevel are created and owned by a TopologyRefiner,
/// which will return const-references to them. Such references are only valid during the
/// lifetime of the TopologyRefiner that created and returned them, and only for a given refinement,
/// i.e. if the TopologyRefiner is re-refined, any references to TopoologyLevels are invalidated.
///
class TopologyLevel {
public:
//@{
/// @name Methods to inspect the overall inventory of components:
///
/// All three main component types are indexed locally within each level. For
/// some topological relationships -- notably face-vertices, which is often
/// the only relationship of interest -- the total number of entries is also
/// made available.
///
/// \brief Return the number of vertices in this level
int GetNumVertices() const { return _level->getNumVertices(); }
/// \brief Return the number of faces in this level
int GetNumFaces() const { return _level->getNumFaces(); }
/// \brief Return the number of edges in this level
int GetNumEdges() const { return _level->getNumEdges(); }
/// \brief Return the total number of face-vertices, i.e. the sum of all vertices for all faces
int GetNumFaceVertices() const { return _level->getNumFaceVerticesTotal(); }
//@}
//@{
/// @name Methods to inspect topological relationships for individual components:
///
/// With three main component types (vertices, faces and edges), for each of the
/// three components the TopologyLevel stores the incident/adjacent components of
/// the other two types. So there are six relationships available for immediate
/// inspection. All are accessed by methods that return an array of fixed size
/// containing the indices of the incident components.
///
/// For some of the relations, i.e. those for which the incident components are
/// of higher order or 'contain' the component itself (e.g. a vertex has incident
/// faces that contain it), an additional 'local index' is available that identifies
/// the component within each of its neighbors. For example, if vertex V is the k'th
/// vertex in some face F, then when F occurs in the set of incident vertices of V,
/// the local index corresponding to F will be k. The ordering of local indices
/// matches the ordering of the incident component to which it corresponds.
//
/// \brief Access the vertices incident a given face
ConstIndexArray GetFaceVertices(Index f) const { return _level->getFaceVertices(f); }
/// \brief Access the edges incident a given face
ConstIndexArray GetFaceEdges(Index f) const { return _level->getFaceEdges(f); }
/// \brief Access the vertices incident a given edge
ConstIndexArray GetEdgeVertices(Index e) const { return _level->getEdgeVertices(e); }
/// \brief Access the faces incident a given edge
ConstIndexArray GetEdgeFaces(Index e) const { return _level->getEdgeFaces(e); }
/// \brief Access the faces incident a given vertex
ConstIndexArray GetVertexFaces(Index v) const { return _level->getVertexFaces(v); }
/// \brief Access the edges incident a given vertex
ConstIndexArray GetVertexEdges(Index v) const { return _level->getVertexEdges(v); }
/// \brief Access the local indices of a vertex with respect to its incident faces
ConstLocalIndexArray GetVertexFaceLocalIndices(Index v) const { return _level->getVertexFaceLocalIndices(v); }
/// \brief Access the local indices of a vertex with respect to its incident edges
ConstLocalIndexArray GetVertexEdgeLocalIndices(Index v) const { return _level->getVertexEdgeLocalIndices(v); }
/// \brief Access the local indices of an edge with respect to its incident faces
ConstLocalIndexArray GetEdgeFaceLocalIndices(Index e) const { return _level->getEdgeFaceLocalIndices(e); }
/// \brief Identify the edge matching the given vertex pair
Index FindEdge(Index v0, Index v1) const { return _level->findEdge(v0, v1); }
//@}
//@{
/// @name Methods to inspect other topological properties of individual components:
///
/// \brief Return if the edge is non-manifold
bool IsEdgeNonManifold(Index e) const { return _level->isEdgeNonManifold(e); }
/// \brief Return if the vertex is non-manifold
bool IsVertexNonManifold(Index v) const { return _level->isVertexNonManifold(v); }
/// \brief Return if the edge is a boundary
bool IsEdgeBoundary(Index e) const { return _level->getEdgeTag(e)._boundary; }
/// \brief Return if the vertex is a boundary
bool IsVertexBoundary(Index v) const { return _level->getVertexTag(v)._boundary; }
//@}
//@{
/// @name Methods to inspect feature tags for individual components:
///
/// While only a subset of components may have been tagged with features such
/// as sharpness, all such features have a default value and so all components
/// can be inspected.
/// \brief Return the sharpness assigned a given edge
float GetEdgeSharpness(Index e) const { return _level->getEdgeSharpness(e); }
/// \brief Return the sharpness assigned a given vertex
float GetVertexSharpness(Index v) const { return _level->getVertexSharpness(v); }
/// \brief Return if a given face has been tagged as a hole
bool IsFaceHole(Index f) const { return _level->isFaceHole(f); }
/// \brief Return the subdivision rule assigned a given vertex specific to this level
Sdc::Crease::Rule GetVertexRule(Index v) const { return _level->getVertexRule(v); }
//@}
//@{
/// @name Methods to inspect face-varying data:
///
/// Face-varying data is organized into topologically independent channels,
/// each with an integer identifier. Access to face-varying data generally
/// requires the specification of a channel, though with a single channel
/// being a common situation the first/only channel will be assumed if
/// unspecified.
///
/// A face-varying channel is composed of a set of values that may be shared
/// by faces meeting at a common vertex. Just as there are sets of vertices
/// that are associated with faces by index (ranging from 0 to
/// num-vertices - 1), face-varying values are also referenced by index
/// (ranging from 0 to num-values -1).
///
/// The face-varying values associated with a face are accessed similarly to
/// the way in which vertices associated with the face are accessed -- an
/// array of fixed size containing the indices for each corner is provided
/// for inspection, iteration, etc.
///
/// When the face-varying topology around a vertex "matches", it has the
/// same limit properties and so results in the same limit surface when
/// collections of adjacent vertices match. Like other references to
/// "topology", this includes consideration of sharpness. So it may be
/// that face-varying values are assigned around a vertex on a boundary in
/// a way that appears to match, but the face-varying interpolation option
/// requires sharpening of that vertex in face-varying space -- the
/// difference in the topology of the resulting limit surfaces leading to
/// the query returning false for the match. The edge case is simpler in
/// that it only considers continuity across the edge, not the entire
/// neighborhood around each end vertex.
/// \brief Return the number of face-varying channels (should be same for all levels)
int GetNumFVarChannels() const { return _level->getNumFVarChannels(); }
/// \brief Return the total number of face-varying values in a particular channel
/// (the upper bound of a face-varying value index)
int GetNumFVarValues(int channel = 0) const { return _level->getNumFVarValues(channel); }
/// \brief Access the face-varying values associated with a particular face
ConstIndexArray GetFaceFVarValues(Index f, int channel = 0) const {
return _level->getFaceFVarValues(f, channel);
}
/// \brief Return if face-varying topology around a vertex matches
bool DoesVertexFVarTopologyMatch(Index v, int channel = 0) const {
return _level->doesVertexFVarTopologyMatch(v, channel);
}
/// \brief Return if face-varying topology across the edge only matches
bool DoesEdgeFVarTopologyMatch(Index e, int channel = 0) const {
return _level->doesEdgeFVarTopologyMatch(e, channel);
}
/// \brief Return if face-varying topology around a face matches
bool DoesFaceFVarTopologyMatch(Index f, int channel = 0) const {
return _level->doesFaceFVarTopologyMatch(f, channel);
}
//@}
//@{
/// @name Methods to identify parent or child components in adjoining levels of refinement:
/// \brief Access the child faces (in the next level) of a given face
ConstIndexArray GetFaceChildFaces(Index f) const { return _refToChild->getFaceChildFaces(f); }
/// \brief Access the child edges (in the next level) of a given face
ConstIndexArray GetFaceChildEdges(Index f) const { return _refToChild->getFaceChildEdges(f); }
/// \brief Access the child edges (in the next level) of a given edge
ConstIndexArray GetEdgeChildEdges(Index e) const { return _refToChild->getEdgeChildEdges(e); }
/// \brief Return the child vertex (in the next level) of a given face
Index GetFaceChildVertex( Index f) const { return _refToChild->getFaceChildVertex(f); }
/// \brief Return the child vertex (in the next level) of a given edge
Index GetEdgeChildVertex( Index e) const { return _refToChild->getEdgeChildVertex(e); }
/// \brief Return the child vertex (in the next level) of a given vertex
Index GetVertexChildVertex(Index v) const { return _refToChild->getVertexChildVertex(v); }
/// \brief Return the parent face (in the previous level) of a given face
Index GetFaceParentFace(Index f) const { return _refToParent->getChildFaceParentFace(f); }
//@}
//@{
/// @name Debugging aides:
bool ValidateTopology() const { return _level->validateTopology(); }
void PrintTopology(bool children = true) const { _level->print((children && _refToChild) ? _refToChild : 0); }
//@}
private:
friend class TopologyRefiner;
Vtr::internal::Level const * _level;
Vtr::internal::Refinement const * _refToParent;
Vtr::internal::Refinement const * _refToChild;
public:
// Not intended for public use, but required by std::vector, etc...
TopologyLevel() { }
~TopologyLevel() { }
};
} // end namespace Far
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_FAR_TOPOLOGY_LEVEL_H */
+298
View File
@@ -0,0 +1,298 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_FAR_TOPOLOGY_REFINER_H
#define OPENSUBDIV3_FAR_TOPOLOGY_REFINER_H
#include "../version.h"
#include "../sdc/types.h"
#include "../sdc/options.h"
#include "../far/types.h"
#include "../far/topologyLevel.h"
#include <vector>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Vtr { namespace internal { class SparseSelector; } }
namespace Far { namespace internal { class FeatureMask; } }
namespace Far {
template <typename REAL> class PrimvarRefinerReal;
template <class MESH> class TopologyRefinerFactory;
///
/// \brief Stores topology data for a specified set of refinement options.
///
class TopologyRefiner {
public:
/// \brief Constructor
TopologyRefiner(Sdc::SchemeType type, Sdc::Options options = Sdc::Options());
/// \brief Destructor
~TopologyRefiner();
/// \brief Returns the subdivision scheme
Sdc::SchemeType GetSchemeType() const { return _subdivType; }
/// \brief Returns the subdivision options
Sdc::Options GetSchemeOptions() const { return _subdivOptions; }
/// \brief Returns true if uniform refinement has been applied
bool IsUniform() const { return _isUniform; }
/// \brief Returns the number of refinement levels
int GetNumLevels() const { return (int)_farLevels.size(); }
/// \brief Returns the highest level of refinement
int GetMaxLevel() const { return _maxLevel; }
/// \brief Returns the maximum vertex valence in all levels
int GetMaxValence() const { return _maxValence; }
/// \brief Returns true if faces have been tagged as holes
bool HasHoles() const { return _hasHoles; }
/// \brief Returns the total number of vertices in all levels
int GetNumVerticesTotal() const { return _totalVertices; }
/// \brief Returns the total number of edges in all levels
int GetNumEdgesTotal() const { return _totalEdges; }
/// \brief Returns the total number of edges in all levels
int GetNumFacesTotal() const { return _totalFaces; }
/// \brief Returns the total number of face vertices in all levels
int GetNumFaceVerticesTotal() const { return _totalFaceVertices; }
/// \brief Returns a handle to access data specific to a particular level
TopologyLevel const & GetLevel(int level) const { return _farLevels[level]; }
//@{
/// @name High-level refinement and related methods
///
//
// Uniform refinement
//
/// \brief Uniform refinement options
///
/// Options for uniform refinement, including the number of levels, vertex
/// ordering and generation of topology information.
///
/// Note the impact of the option to generate fullTopologyInLastLevel. Given
/// subsequent levels of uniform refinement typically reguire 4x the data
/// of the previous level, only the minimum amount of data is generated in the
/// last level by default, i.e. a vertex and face-vertex list. If requiring
/// topology traversal of the last level, e.g. inspecting edges or incident
/// faces of vertices, the option to generate full topology in the last
/// level should be enabled.
///
struct UniformOptions {
UniformOptions(int level) :
refinementLevel(level),
orderVerticesFromFacesFirst(false),
fullTopologyInLastLevel(false) { }
unsigned int refinementLevel:4, ///< Number of refinement iterations
orderVerticesFromFacesFirst:1, ///< Order child vertices from faces first
///< instead of child vertices of vertices
fullTopologyInLastLevel:1; ///< Skip topological relationships in the last
///< level of refinement that are not needed for
///< interpolation (keep false if using limit).
};
/// \brief Refine the topology uniformly
///
/// This method applies uniform refinement to the level specified in the
/// given UniformOptions.
///
/// Note the impact of the UniformOption to generate fullTopologyInLastLevel
/// and be sure it is assigned to satisfy the needs of the resulting refinement.
///
/// @param options Options controlling uniform refinement
///
void RefineUniform(UniformOptions options);
/// \brief Returns the options specified on refinement
UniformOptions GetUniformOptions() const { return _uniformOptions; }
//
// Adaptive refinement
//
/// \brief Adaptive refinement options
struct AdaptiveOptions {
AdaptiveOptions(int level) :
isolationLevel(level),
secondaryLevel(15),
useSingleCreasePatch(false),
useInfSharpPatch(false),
considerFVarChannels(false),
orderVerticesFromFacesFirst(false) { }
unsigned int isolationLevel:4; ///< Number of iterations applied to isolate
///< extraordinary vertices and creases
unsigned int secondaryLevel:4; ///< Shallower level to stop isolation of
///< smooth irregular features
unsigned int useSingleCreasePatch:1; ///< Use 'single-crease' patch and stop
///< isolation where applicable
unsigned int useInfSharpPatch:1; ///< Use infinitely sharp patches and stop
///< isolation where applicable
unsigned int considerFVarChannels:1; ///< Inspect face-varying channels and
///< isolate when irregular features present
unsigned int orderVerticesFromFacesFirst:1; ///< Order child vertices from faces first
///< instead of child vertices of vertices
};
/// \brief Feature Adaptive topology refinement
///
/// @param options Options controlling adaptive refinement
///
/// @param selectedFaces Limit adaptive refinement to the specified faces
///
void RefineAdaptive(AdaptiveOptions options,
ConstIndexArray selectedFaces = ConstIndexArray());
/// \brief Returns the options specified on refinement
AdaptiveOptions GetAdaptiveOptions() const { return _adaptiveOptions; }
/// \brief Unrefine the topology, keeping only the base level.
void Unrefine();
//@{
/// @name Number and properties of face-varying channels:
///
/// \brief Returns the number of face-varying channels in the tables
int GetNumFVarChannels() const;
/// \brief Returns the face-varying interpolation rule set for a given channel
Sdc::Options::FVarLinearInterpolation GetFVarLinearInterpolation(int channel = 0) const;
/// \brief Returns the total number of face-varying values in all levels
int GetNumFVarValuesTotal(int channel = 0) const;
//@}
protected:
//
// Lower level protected methods intended strictly for internal use:
//
template <class MESH>
friend class TopologyRefinerFactory;
friend class TopologyRefinerFactoryBase;
friend class PatchTableBuilder;
friend class PatchBuilder;
friend class PtexIndices;
template <typename REAL>
friend class PrimvarRefinerReal;
// Copy constructor exposed via the factory class:
TopologyRefiner(TopologyRefiner const & source);
Vtr::internal::Level & getLevel(int l) { return *_levels[l]; }
Vtr::internal::Level const & getLevel(int l) const { return *_levels[l]; }
Vtr::internal::Refinement & getRefinement(int l) { return *_refinements[l]; }
Vtr::internal::Refinement const & getRefinement(int l) const { return *_refinements[l]; }
private:
// Not default constructible or copyable:
TopologyRefiner() : _uniformOptions(0), _adaptiveOptions(0) { }
TopologyRefiner & operator=(TopologyRefiner const &) { return *this; }
void selectFeatureAdaptiveComponents(Vtr::internal::SparseSelector& selector,
internal::FeatureMask const & mask,
ConstIndexArray selectedFaces);
void selectLinearIrregularFaces(Vtr::internal::SparseSelector& selector,
ConstIndexArray selectedFaces);
void initializeInventory();
void updateInventory(Vtr::internal::Level const & newLevel);
void appendLevel(Vtr::internal::Level & newLevel);
void appendRefinement(Vtr::internal::Refinement & newRefinement);
void assembleFarLevels();
private:
Sdc::SchemeType _subdivType;
Sdc::Options _subdivOptions;
unsigned int _isUniform : 1;
unsigned int _hasHoles : 1;
unsigned int _hasIrregFaces : 1;
unsigned int _regFaceSize : 3;
unsigned int _maxLevel : 4;
// Options assigned on refinement:
UniformOptions _uniformOptions;
AdaptiveOptions _adaptiveOptions;
// Cumulative properties of all levels:
int _totalVertices;
int _totalEdges;
int _totalFaces;
int _totalFaceVertices;
int _maxValence;
// Note the base level may be shared with another instance
bool _baseLevelOwned;
std::vector<Vtr::internal::Level *> _levels;
std::vector<Vtr::internal::Refinement *> _refinements;
std::vector<TopologyLevel> _farLevels;
};
inline int
TopologyRefiner::GetNumFVarChannels() const {
return _levels[0]->getNumFVarChannels();
}
inline Sdc::Options::FVarLinearInterpolation
TopologyRefiner::GetFVarLinearInterpolation(int channel) const {
return _levels[0]->getFVarOptions(channel).GetFVarLinearInterpolation();
}
} // end namespace Far
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_FAR_TOPOLOGY_REFINER_H */
@@ -0,0 +1,710 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_FAR_TOPOLOGY_REFINER_FACTORY_H
#define OPENSUBDIV3_FAR_TOPOLOGY_REFINER_FACTORY_H
#include "../version.h"
#include "../far/topologyRefiner.h"
#include "../far/error.h"
#include <cassert>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far {
///\brief Private base class of Factories for constructing TopologyRefiners
///
/// TopologyRefinerFactoryBase is the base class for subclasses that are intended to
/// construct TopologyRefiners directly from meshes in their native representations.
/// The subclasses are parameterized by the mesh type \<class MESH\> and are expected
/// to inherit the details related to assembly and validation provided here that are
/// independent of the subclass' mesh type.
//
class TopologyRefinerFactoryBase {
protected:
//
// Protected methods invoked by the subclass template to verify and process each
// stage of construction implemented by the subclass:
//
typedef Vtr::internal::Level::ValidationCallback TopologyCallback;
static bool prepareComponentTopologySizing(TopologyRefiner& refiner);
static bool prepareComponentTopologyAssignment(TopologyRefiner& refiner, bool fullValidation,
TopologyCallback callback, void const * callbackData);
static bool prepareComponentTagsAndSharpness(TopologyRefiner& refiner);
static bool prepareFaceVaryingChannels(TopologyRefiner& refiner);
};
///\brief Factory for constructing TopologyRefiners from specific mesh classes.
///
/// TopologyRefinerFactory<MESH> is the factory class template to convert an instance of
/// TopologyRefiner from an arbitrary mesh class. While a class template, the implementation
/// is not (cannot) be complete, so specialization of a few methods is required (it is a
/// stateless factory, so no instance and only static methods).
///
/// This template provides both the interface and high level assembly for the construction
/// of the TopologyRefiner instance. The high level construction executes a specific set
/// of operations to convert the client's MESH into TopologyRefiner. This set of operations
/// combines methods independent of MESH from the base class with those specialized here for
/// class MESH.
///
template <class MESH>
class TopologyRefinerFactory : public TopologyRefinerFactoryBase {
public:
/// \brief Options related to the construction of each TopologyRefiner.
///
struct Options {
Options(Sdc::SchemeType sdcType = Sdc::SCHEME_CATMARK, Sdc::Options sdcOptions = Sdc::Options()) :
schemeType(sdcType),
schemeOptions(sdcOptions),
validateFullTopology(false) { }
Sdc::SchemeType schemeType; ///< The subdivision scheme type identifier
Sdc::Options schemeOptions; ///< The full set of options for the scheme,
///< e.g. boundary interpolation rules...
unsigned int validateFullTopology : 1; ///< Apply more extensive validation of
///< the constructed topology -- intended
///< for debugging.
};
/// \brief Instantiates a TopologyRefiner from client-provided topological
/// representation.
///
/// If only the face-vertices topological relationships are specified
/// with this factory, edge relationships have to be inferred, which
/// requires additional processing. If the client topological rep can
/// provide this information, it is highly recommended to do so.
///
/// @param mesh Client's topological representation (or a converter)
//
/// @param options Options controlling the creation of the TopologyRefiner
///
/// @return A new instance of TopologyRefiner or 0 for failure
///
static TopologyRefiner* Create(MESH const& mesh, Options options = Options());
/// \brief Instantiates a TopologyRefiner from the base level of an
/// existing instance.
///
/// This allows lightweight copies of the same topology to be refined
/// differently for each new instance. As with other classes that refer
/// to an existing TopologyRefiner, it must generally exist for the entire
/// lifetime of the new instance. In this case, the base level of the
/// original instance must be preserved.
///
/// @param baseLevel An existing TopologyRefiner to share base level.
///
/// @return A new instance of TopologyRefiner or 0 for failure
///
static TopologyRefiner* Create(TopologyRefiner const & baseLevel);
protected:
typedef Vtr::internal::Level::TopologyError TopologyError;
//@{
/// @name Methods to be provided to complete assembly of the TopologyRefiner
///
///
/// These methods are to be specialized to implement all details specific to
/// class MESH required to convert MESH data to TopologyRefiner. Note that
/// some of these *must* be specialized in order to complete construction while
/// some are optional.
///
/// There are two minimal construction requirements (to specify the size and
/// content of all topology relations) and three optional (to specify feature
/// tags, face-varying data, and runtime validation and error reporting).
///
/// See comments in the generic stubs, the factory for Far::TopologyDescriptor
/// or the tutorials for more details on writing these.
///
/// \brief Specify the number of vertices, faces, face-vertices, etc.
static bool resizeComponentTopology(TopologyRefiner& newRefiner, MESH const& mesh);
/// \brief Specify the relationships between vertices, faces, etc. ie the
/// face-vertices, vertex-faces, edge-vertices, etc.
static bool assignComponentTopology(TopologyRefiner& newRefiner, MESH const& mesh);
/// \brief (Optional) Specify edge or vertex sharpness or face holes
static bool assignComponentTags(TopologyRefiner& newRefiner, MESH const& mesh);
/// \brief (Optional) Specify face-varying data per face
static bool assignFaceVaryingTopology(TopologyRefiner& newRefiner, MESH const& mesh);
/// \brief (Optional) Control run-time topology validation and error reporting
static void reportInvalidTopology(TopologyError errCode, char const * msg, MESH const& mesh);
//@}
protected:
//@{
/// @name Base level assembly methods to be used within resizeComponentTopology()
///
/// \brief These methods specify sizes of various quantities, e.g. the number of
/// vertices, faces, face-vertices, etc. The number of the primary components
/// (vertices, faces and edges) should be specified prior to anything else that
/// references them (e.g. we need to know the number of faces before specifying
/// the vertices for that face.
///
/// If a full boundary representation with all neighborhood information is not
/// available, e.g. faces and vertices are available but not edges, only the
/// face-vertices should be specified. The remaining topological relationships
/// will be constructed later in the assembly (though at greater cost than if
/// specified directly).
///
/// The sizes for topological relationships between individual components should be
/// specified in order, i.e. the number of face-vertices for each successive face.
///
/// \brief Specify the number of vertices to be accommodated
static void setNumBaseVertices(TopologyRefiner & newRefiner, int count);
/// \brief Specify the number of faces to be accommodated
static void setNumBaseFaces(TopologyRefiner & newRefiner, int count);
/// \brief Specify the number of edges to be accommodated
static void setNumBaseEdges(TopologyRefiner & newRefiner, int count);
/// \brief Specify the number of vertices incident each face
static void setNumBaseFaceVertices(TopologyRefiner & newRefiner, Index f, int count);
/// \brief Specify the number of faces incident each edge
static void setNumBaseEdgeFaces(TopologyRefiner & newRefiner, Index e, int count);
/// \brief Specify the number of faces incident each vertex
static void setNumBaseVertexFaces(TopologyRefiner & newRefiner, Index v, int count);
/// \brief Specify the number of edges incident each vertex
static void setNumBaseVertexEdges(TopologyRefiner & newRefiner, Index v, int count);
static int getNumBaseVertices(TopologyRefiner const & newRefiner);
static int getNumBaseFaces(TopologyRefiner const & newRefiner);
static int getNumBaseEdges(TopologyRefiner const & newRefiner);
//@}
//@{
/// @name Base level assembly methods to be used within assignComponentTopology()
///
/// \brief These methods populate relationships between components -- in much the
/// same manner as they are inspected once the TopologyRefiner is completed.
///
/// An array of fixed size is returned from these methods and its entries are to be
/// populated with the appropriate indices for its neighbors. At minimum, the
/// vertices for each face must be specified. As noted previously, the remaining
/// relationships will be constructed as needed.
///
/// The ordering of entries in these arrays is important -- they are expected to
/// be ordered counter-clockwise for a right-hand orientation.
///
/// Non-manifold components must be explicitly tagged as such and they do not
/// require the ordering expected of manifold components. Special consideration
/// must also be given to certain non-manifold situations, e.g. the same edge
/// cannot appear twice in a face, and a degenerate edge (same vertex at both
/// ends) can only have one incident face. Such considerations are typically
/// achievable by creating multiple instances of an edge. So while there will
/// always be a one-to-one correspondence between vertices and faces, the same
/// is not guaranteed of edges in certain non-manifold circumstances.
///
/// \brief Assign the vertices incident each face
static IndexArray getBaseFaceVertices(TopologyRefiner & newRefiner, Index f);
/// \brief Assign the edges incident each face
static IndexArray getBaseFaceEdges(TopologyRefiner & newRefiner, Index f);
/// \brief Assign the vertices incident each edge
static IndexArray getBaseEdgeVertices(TopologyRefiner & newRefiner, Index e);
/// \brief Assign the faces incident each edge
static IndexArray getBaseEdgeFaces(TopologyRefiner & newRefiner, Index e);
/// \brief Assign the faces incident each vertex
static IndexArray getBaseVertexFaces(TopologyRefiner & newRefiner, Index v);
/// \brief Assign the edges incident each vertex
static IndexArray getBaseVertexEdges(TopologyRefiner & newRefiner, Index v);
/// \brief Assign the local indices of a vertex within each of its incident faces
static LocalIndexArray getBaseVertexFaceLocalIndices(TopologyRefiner & newRefiner, Index v);
/// \brief Assign the local indices of a vertex within each of its incident edges
static LocalIndexArray getBaseVertexEdgeLocalIndices(TopologyRefiner & newRefiner, Index v);
/// \brief Assign the local indices of an edge within each of its incident faces
static LocalIndexArray getBaseEdgeFaceLocalIndices(TopologyRefiner & newRefiner, Index e);
/// \brief Determine all local indices by inspection (only for pure manifold meshes)
static void populateBaseLocalIndices(TopologyRefiner & newRefiner);
/// \brief Tag an edge as non-manifold
static void setBaseEdgeNonManifold(TopologyRefiner & newRefiner, Index e, bool b);
/// \brief Tag a vertex as non-manifold
static void setBaseVertexNonManifold(TopologyRefiner & newRefiner, Index v, bool b);
//@}
//@{
/// @name Base level assembly methods to be used within assignComponentTags()
///
/// These methods are used to assign edge or vertex sharpness, for tagging faces
/// as holes, etc. Unlike topological assignment, only those components that
/// possess a feature of interest need be explicitly assigned.
///
/// Since topological construction is largely complete by this point, a method is
/// available to identify an edge for sharpness assignment given a pair of vertices.
///
/// \brief Identify an edge to be assigned a sharpness value given a vertex pair
static Index findBaseEdge(TopologyRefiner const & newRefiner, Index v0, Index v1);
/// \brief Assign a sharpness value to a given edge
static void setBaseEdgeSharpness(TopologyRefiner & newRefiner, Index e, float sharpness);
/// \brief Assign a sharpness value to a given vertex
static void setBaseVertexSharpness(TopologyRefiner & newRefiner, Index v, float sharpness);
/// \brief Tag a face as a hole
static void setBaseFaceHole(TopologyRefiner & newRefiner, Index f, bool isHole);
//@}
//@{
/// @name Base level assembly methods to be used within assignFaceVaryingTopology()
///
/// Face-varying data is assigned to faces in much the same way as face-vertex
/// topology is assigned -- indices for face-varying values are assigned to the
/// corners of each face just as indices for vertices were assigned.
///
/// Independent sets of face-varying data are stored in channels. The identifier
/// of each channel (an integer) is expected whenever referring to face-varying
/// data in any form.
///
/// \brief Create a new face-varying channel with the given number of values
static int createBaseFVarChannel(TopologyRefiner & newRefiner, int numValues);
/// \brief Create a new face-varying channel with the given number of values and independent interpolation options
static int createBaseFVarChannel(TopologyRefiner & newRefiner, int numValues, Sdc::Options const& fvarOptions);
/// \brief Assign the face-varying values for the corners of each face
static IndexArray getBaseFaceFVarValues(TopologyRefiner & newRefiner, Index face, int channel = 0);
//@}
protected:
//
// Not to be specialized:
//
static bool populateBaseLevel(TopologyRefiner& refiner, MESH const& mesh, Options options);
};
//
// Generic implementations:
//
template <class MESH>
TopologyRefiner*
TopologyRefinerFactory<MESH>::Create(MESH const& mesh, Options options) {
TopologyRefiner * refiner = new TopologyRefiner(options.schemeType, options.schemeOptions);
if (! populateBaseLevel(*refiner, mesh, options)) {
delete refiner;
return 0;
}
// Eventually want to move the Refiner's inventory initialization here. Currently it
// is handled after topology assignment, but if the inventory is to include additional
// features (e.g. holes, etc.) it is better off deferred to here.
return refiner;
}
template <class MESH>
TopologyRefiner*
TopologyRefinerFactory<MESH>::Create(TopologyRefiner const & source) {
return new TopologyRefiner(source);
}
template <class MESH>
bool
TopologyRefinerFactory<MESH>::populateBaseLevel(TopologyRefiner& refiner, MESH const& mesh, Options options) {
//
// Construction of a specialized topology refiner involves four steps, each of which
// involves a method specialized for MESH followed by one that takes an action in
// response to it or in preparation for the next step.
//
// Both the specialized methods and those that follow them may find fault in the
// construction and trigger failure at any time:
//
//
// Sizing of the topology -- this is a required specialization for MESH. This defines
// an inventory of all components and their relations that is used to allocate buffers
// to be efficiently populated in the subsequent topology assignment step.
//
if (! resizeComponentTopology(refiner, mesh)) return false;
if (! prepareComponentTopologySizing(refiner)) return false;
//
// Assignment of the topology -- this is a required specialization for MESH. If edges
// are specified, all other topological relations are expected to be defined for them.
// Otherwise edges and remaining topology will be completed from the face-vertices:
//
bool validate = options.validateFullTopology;
TopologyCallback callback = reinterpret_cast<TopologyCallback>(reportInvalidTopology);
void const * userData = &mesh;
if (! assignComponentTopology(refiner, mesh)) return false;
if (! prepareComponentTopologyAssignment(refiner, validate, callback, userData)) return false;
//
// User assigned and internal tagging of components -- an optional specialization for
// MESH. Allows the specification of sharpness values, holes, etc.
//
if (! assignComponentTags(refiner, mesh)) return false;
if (! prepareComponentTagsAndSharpness(refiner)) return false;
//
// Defining channels of face-varying primvar data -- an optional specialization for MESH.
//
if (! assignFaceVaryingTopology(refiner, mesh)) return false;
if (! prepareFaceVaryingChannels(refiner)) return false;
return true;
}
template <class MESH>
inline void
TopologyRefinerFactory<MESH>::setNumBaseFaces(TopologyRefiner & newRefiner, int count) {
newRefiner._levels[0]->resizeFaces(count);
}
template <class MESH>
inline void
TopologyRefinerFactory<MESH>::setNumBaseEdges(TopologyRefiner & newRefiner, int count) {
newRefiner._levels[0]->resizeEdges(count);
}
template <class MESH>
inline void
TopologyRefinerFactory<MESH>::setNumBaseVertices(TopologyRefiner & newRefiner, int count) {
newRefiner._levels[0]->resizeVertices(count);
}
template <class MESH>
inline int
TopologyRefinerFactory<MESH>::getNumBaseFaces(TopologyRefiner const & newRefiner) {
return newRefiner._levels[0]->getNumFaces();
}
template <class MESH>
inline int
TopologyRefinerFactory<MESH>::getNumBaseEdges(TopologyRefiner const & newRefiner) {
return newRefiner._levels[0]->getNumEdges();
}
template <class MESH>
inline int
TopologyRefinerFactory<MESH>::getNumBaseVertices(TopologyRefiner const & newRefiner) {
return newRefiner._levels[0]->getNumVertices();
}
template <class MESH>
inline void
TopologyRefinerFactory<MESH>::setNumBaseFaceVertices(TopologyRefiner & newRefiner, Index f, int count) {
newRefiner._levels[0]->resizeFaceVertices(f, count);
newRefiner._hasIrregFaces |= (count != newRefiner._regFaceSize);
}
template <class MESH>
inline void
TopologyRefinerFactory<MESH>::setNumBaseEdgeFaces(TopologyRefiner & newRefiner, Index e, int count) {
newRefiner._levels[0]->resizeEdgeFaces(e, count);
}
template <class MESH>
inline void
TopologyRefinerFactory<MESH>::setNumBaseVertexFaces(TopologyRefiner & newRefiner, Index v, int count) {
newRefiner._levels[0]->resizeVertexFaces(v, count);
}
template <class MESH>
inline void
TopologyRefinerFactory<MESH>::setNumBaseVertexEdges(TopologyRefiner & newRefiner, Index v, int count) {
newRefiner._levels[0]->resizeVertexEdges(v, count);
}
template <class MESH>
inline IndexArray
TopologyRefinerFactory<MESH>::getBaseFaceVertices(TopologyRefiner & newRefiner, Index f) {
return newRefiner._levels[0]->getFaceVertices(f);
}
template <class MESH>
inline IndexArray
TopologyRefinerFactory<MESH>::getBaseFaceEdges(TopologyRefiner & newRefiner, Index f) {
return newRefiner._levels[0]->getFaceEdges(f);
}
template <class MESH>
inline IndexArray
TopologyRefinerFactory<MESH>::getBaseEdgeVertices(TopologyRefiner & newRefiner, Index e) {
return newRefiner._levels[0]->getEdgeVertices(e);
}
template <class MESH>
inline IndexArray
TopologyRefinerFactory<MESH>::getBaseEdgeFaces(TopologyRefiner & newRefiner, Index e) {
return newRefiner._levels[0]->getEdgeFaces(e);
}
template <class MESH>
inline IndexArray
TopologyRefinerFactory<MESH>::getBaseVertexFaces(TopologyRefiner & newRefiner, Index v) {
return newRefiner._levels[0]->getVertexFaces(v);
}
template <class MESH>
inline IndexArray
TopologyRefinerFactory<MESH>::getBaseVertexEdges(TopologyRefiner & newRefiner, Index v) {
return newRefiner._levels[0]->getVertexEdges(v);
}
template <class MESH>
inline LocalIndexArray
TopologyRefinerFactory<MESH>::getBaseEdgeFaceLocalIndices(TopologyRefiner & newRefiner, Index e) {
return newRefiner._levels[0]->getEdgeFaceLocalIndices(e);
}
template <class MESH>
inline LocalIndexArray
TopologyRefinerFactory<MESH>::getBaseVertexFaceLocalIndices(TopologyRefiner & newRefiner, Index v) {
return newRefiner._levels[0]->getVertexFaceLocalIndices(v);
}
template <class MESH>
inline LocalIndexArray
TopologyRefinerFactory<MESH>::getBaseVertexEdgeLocalIndices(TopologyRefiner & newRefiner, Index v) {
return newRefiner._levels[0]->getVertexEdgeLocalIndices(v);
}
template <class MESH>
inline Index
TopologyRefinerFactory<MESH>::findBaseEdge(TopologyRefiner const & newRefiner, Index v0, Index v1) {
return newRefiner._levels[0]->findEdge(v0, v1);
}
template <class MESH>
inline void
TopologyRefinerFactory<MESH>::populateBaseLocalIndices(TopologyRefiner & newRefiner) {
newRefiner._levels[0]->populateLocalIndices();
}
template <class MESH>
inline void
TopologyRefinerFactory<MESH>::setBaseEdgeNonManifold(TopologyRefiner & newRefiner, Index e, bool b) {
newRefiner._levels[0]->setEdgeNonManifold(e, b);
}
template <class MESH>
inline void
TopologyRefinerFactory<MESH>::setBaseVertexNonManifold(TopologyRefiner & newRefiner, Index v, bool b) {
newRefiner._levels[0]->setVertexNonManifold(v, b);
}
template <class MESH>
inline void
TopologyRefinerFactory<MESH>::setBaseEdgeSharpness(TopologyRefiner & newRefiner, Index e, float s) {
newRefiner._levels[0]->getEdgeSharpness(e) = s;
}
template <class MESH>
inline void
TopologyRefinerFactory<MESH>::setBaseVertexSharpness(TopologyRefiner & newRefiner, Index v, float s) {
newRefiner._levels[0]->getVertexSharpness(v) = s;
}
template <class MESH>
inline void
TopologyRefinerFactory<MESH>::setBaseFaceHole(TopologyRefiner & newRefiner, Index f, bool b) {
newRefiner._levels[0]->setFaceHole(f, b);
newRefiner._hasHoles |= b;
}
template <class MESH>
inline int
TopologyRefinerFactory<MESH>::createBaseFVarChannel(TopologyRefiner & newRefiner, int numValues) {
return newRefiner._levels[0]->createFVarChannel(numValues, newRefiner._subdivOptions);
}
template <class MESH>
inline int
TopologyRefinerFactory<MESH>::createBaseFVarChannel(TopologyRefiner & newRefiner, int numValues, Sdc::Options const& fvarOptions) {
Sdc::Options newOptions = newRefiner._subdivOptions;
newOptions.SetFVarLinearInterpolation(fvarOptions.GetFVarLinearInterpolation());
return newRefiner._levels[0]->createFVarChannel(numValues, newOptions);
}
template <class MESH>
inline IndexArray
TopologyRefinerFactory<MESH>::getBaseFaceFVarValues(TopologyRefiner & newRefiner, Index face, int channel) {
return newRefiner._levels[0]->getFaceFVarValues(face, channel);
}
template <class MESH>
bool
TopologyRefinerFactory<MESH>::resizeComponentTopology(TopologyRefiner& /* refiner */, MESH const& /* mesh */) {
Error(FAR_RUNTIME_ERROR,
"Failure in TopologyRefinerFactory<>::resizeComponentTopology() -- no specialization provided.");
//
// Sizing the topology tables:
// This method is for determining the sizes of the various topology tables (and other
// data) associated with the mesh. Once completed, appropriate memory will be allocated
// and an additional method invoked to populate it accordingly.
//
// The following methods should be called -- first those to specify the number of faces,
// edges and vertices in the mesh:
//
// void setBaseFaceCount( TopologyRefiner& newRefiner, int count)
// void setBaseEdgeCount( TopologyRefiner& newRefiner, int count)
// void setBaseVertexCount(TopologyRefiner& newRefiner, int count)
//
// and then for each face, edge and vertex, the number of its incident components:
//
// void setBaseFaceVertexCount(TopologyRefiner& newRefiner, Index face, int count)
// void setBaseEdgeFaceCount( TopologyRefiner& newRefiner, Index edge, int count)
// void setBaseVertexFaceCount(TopologyRefiner& newRefiner, Index vertex, int count)
// void setBaseVertexEdgeCount(TopologyRefiner& newRefiner, Index vertex, int count)
//
// The count/size for a component type must be set before indices associated with that
// component type can be used.
//
// Note that it is only necessary to size 4 of the 6 supported topological relations --
// the number of edge-vertices is fixed at two per edge, and the number of face-edges is
// the same as the number of face-vertices.
//
// So a single pass through your mesh to gather up all of this sizing information will
// allow the Tables to be allocated appropriately once and avoid any dynamic resizing as
// it grows.
//
return false;
}
template <class MESH>
bool
TopologyRefinerFactory<MESH>::assignComponentTopology(TopologyRefiner& /* refiner */, MESH const& /* mesh */) {
Error(FAR_RUNTIME_ERROR,
"Failure in TopologyRefinerFactory<>::assignComponentTopology() -- no specialization provided.");
//
// Assigning the topology tables:
// Once the topology tables have been allocated, the six required topological
// relations can be directly populated using the following methods:
//
// IndexArray setBaseFaceVertices(TopologyRefiner& newRefiner, Index face)
// IndexArray setBaseFaceEdges(TopologyRefiner& newRefiner, Index face)
//
// IndexArray setBaseEdgeVertices(TopologyRefiner& newRefiner, Index edge)
// IndexArray setBaseEdgeFaces(TopologyRefiner& newRefiner, Index edge)
//
// IndexArray setBaseVertexEdges(TopologyRefiner& newRefiner, Index vertex)
// IndexArray setBaseVertexFaces(TopologyRefiner& newRefiner, Index vertex)
//
// For the last two relations -- the faces and edges incident a vertex -- there are
// also "local indices" that must be specified (considering doing this internally),
// where the "local index" of each incident face or edge is the index of the vertex
// within that face or edge, and so ranging from 0-3 for incident quads and 0-1 for
// incident edges. These are assigned through similarly retrieved arrays:
//
// LocalIndexArray setBaseVertexFaceLocalIndices(TopologyRefiner& newRefiner, Index vertex)
// LocalIndexArray setBaseVertexEdgeLocalIndices(TopologyRefiner& newRefiner, Index vertex)
// LocalIndexArray setBaseEdgeFaceLocalIndices( TopologyRefiner& newRefiner, Index edge)
//
// or, if the mesh is manifold, explicit assignment of these can be deferred and
// all can be determined by calling:
//
// void populateBaseLocalIndices(TopologyRefiner& newRefiner)
//
// All components are assumed to be locally manifold and ordering of components in
// the above relations is expected to be counter-clockwise.
//
// For non-manifold components, no ordering/orientation of incident components is
// assumed or required, but be sure to explicitly tag such components (vertices and
// edges) as non-manifold:
//
// void setBaseEdgeNonManifold(TopologyRefiner& newRefiner, Index edge, bool b);
//
// void setBaseVertexNonManifold(TopologyRefiner& newRefiner, Index vertex, bool b);
//
// Also consider using TopologyLevel::ValidateTopology() when debugging to ensure
// that topology has been completely and correctly specified.
//
return false;
}
template <class MESH>
bool
TopologyRefinerFactory<MESH>::assignFaceVaryingTopology(TopologyRefiner& /* refiner */, MESH const& /* mesh */) {
//
// Optional assigning face-varying topology tables:
//
// Create independent face-varying primitive variable channels:
// int createBaseFVarChannel(TopologyRefiner& newRefiner, int numValues)
//
// For each channel, populate the face-vertex values:
// IndexArray setBaseFaceFVarValues(TopologyRefiner& newRefiner, Index face, int channel = 0)
//
return true;
}
template <class MESH>
bool
TopologyRefinerFactory<MESH>::assignComponentTags(TopologyRefiner& /* refiner */, MESH const& /* mesh */) {
//
// Optional tagging:
// This is where any additional feature tags -- sharpness, holes, etc. -- can be
// specified using:
//
// void setBaseEdgeSharpness(TopologyRefiner& newRefiner, Index edge, float sharpness)
// void setBaseVertexSharpness(TopologyRefiner& newRefiner, Index vertex, float sharpness)
//
// void setBaseFaceHole(TopologyRefiner& newRefiner, Index face, bool hole)
//
return true;
}
template <class MESH>
void
TopologyRefinerFactory<MESH>::reportInvalidTopology(
TopologyError /* errCode */, char const * /* msg */, MESH const& /* mesh */) {
//
// Optional topology validation error reporting:
// This method is called whenever the factory encounters topology validation
// errors. By default, nothing is reported
//
}
} // end namespace Far
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_FAR_TOPOLOGY_REFINER_FACTORY_H */
+61
View File
@@ -0,0 +1,61 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_FAR_TYPES_H
#define OPENSUBDIV3_FAR_TYPES_H
#include "../version.h"
#include "../vtr/types.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far {
//
// Typedefs for indices that are inherited from the Vtr level -- eventually
// these primitive Vtr types may be declared at a lower, more public level.
//
typedef Vtr::Index Index;
typedef Vtr::LocalIndex LocalIndex;
typedef Vtr::IndexArray IndexArray;
typedef Vtr::LocalIndexArray LocalIndexArray;
typedef Vtr::ConstIndexArray ConstIndexArray;
typedef Vtr::ConstLocalIndexArray ConstLocalIndexArray;
inline bool IndexIsValid(Index index) { return Vtr::IndexIsValid(index); }
static const Index INDEX_INVALID = Vtr::INDEX_INVALID;
static const int VALENCE_LIMIT = Vtr::VALENCE_LIMIT;
} // end namespace Far
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_FAR_TYPES_H */
+172
View File
@@ -0,0 +1,172 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_HBRALLOCATOR_H
#define OPENSUBDIV3_HBRALLOCATOR_H
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
typedef void (*HbrMemStatFunction)(size_t bytes);
/**
* HbrAllocator - derived from UtBlockAllocator.h, but embedded in
* libhbrep.
*/
template <typename T> class HbrAllocator {
public:
/// Constructor
HbrAllocator(size_t *memorystat, int blocksize, void (*increment)(size_t bytes), void (*decrement)(size_t bytes), size_t elemsize = sizeof(T));
/// Destructor
~HbrAllocator();
/// Create an allocated object
T * Allocate();
/// Return an allocated object to the block allocator
void Deallocate(T *);
/// Clear the allocator, deleting all allocated objects.
void Clear();
void SetMemStatsIncrement(void (*increment)(size_t bytes)) { m_increment = increment; }
void SetMemStatsDecrement(void (*decrement)(size_t bytes)) { m_decrement = decrement; }
private:
size_t *m_memorystat;
const int m_blocksize;
int m_elemsize;
T** m_blocks;
// Number of actually allocated blocks
int m_nblocks;
// Size of the m_blocks array (which is NOT the number of actually
// allocated blocks)
int m_blockCapacity;
int m_freecount;
T * m_freelist;
// Memory statistics tracking routines
HbrMemStatFunction m_increment;
HbrMemStatFunction m_decrement;
};
template <typename T>
HbrAllocator<T>::HbrAllocator(size_t *memorystat, int blocksize, void (*increment)(size_t bytes), void (*decrement)(size_t bytes), size_t elemsize)
: m_memorystat(memorystat), m_blocksize(blocksize), m_elemsize((int)elemsize), m_blocks(0), m_nblocks(0), m_blockCapacity(0), m_freecount(0), m_increment(increment), m_decrement(decrement) {
}
template <typename T>
HbrAllocator<T>::~HbrAllocator() {
Clear();
}
template <typename T>
void HbrAllocator<T>::Clear() {
for (int i = 0; i < m_nblocks; ++i) {
// Run the destructors (placement)
T* blockptr = m_blocks[i];
T* startblock = blockptr;
for (int j = 0; j < m_blocksize; ++j) {
blockptr->~T();
blockptr = (T*) ((char*) blockptr + m_elemsize);
}
free(startblock);
if (m_decrement) m_decrement(m_blocksize * m_elemsize);
*m_memorystat -= m_blocksize * m_elemsize;
}
free(m_blocks);
m_blocks = 0;
m_nblocks = 0;
m_blockCapacity = 0;
m_freecount = 0;
m_freelist = NULL;
}
template <typename T>
T*
HbrAllocator<T>::Allocate() {
if (!m_freecount) {
// Allocate a new block
T* block = (T*) malloc(m_blocksize * m_elemsize);
T* blockptr = block;
// Run the constructors on each element using placement new
for (int i = 0; i < m_blocksize; ++i) {
new (blockptr) T();
blockptr = (T*) ((char*) blockptr + m_elemsize);
}
if (m_increment) m_increment(m_blocksize * m_elemsize);
*m_memorystat += m_blocksize * m_elemsize;
// Put the block's entries on the free list
blockptr = block;
for (int i = 0; i < m_blocksize - 1; ++i) {
T* next = (T*) ((char*) blockptr + m_elemsize);
blockptr->GetNext() = next;
blockptr = next;
}
blockptr->GetNext() = 0;
m_freelist = block;
// Keep track of the newly allocated block
if (m_nblocks + 1 >= m_blockCapacity) {
m_blockCapacity = m_blockCapacity * 2;
if (m_blockCapacity < 1) m_blockCapacity = 1;
m_blocks = (T**) realloc(m_blocks, m_blockCapacity * sizeof(T*));
}
m_blocks[m_nblocks] = block;
m_nblocks++;
m_freecount += m_blocksize;
}
T* obj = m_freelist;
m_freelist = obj->GetNext();
obj->GetNext() = 0;
m_freecount--;
return obj;
}
template <typename T>
void
HbrAllocator<T>::Deallocate(T * obj) {
assert(!obj->GetNext());
obj->GetNext() = m_freelist;
m_freelist = obj;
m_freecount++;
}
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_HBRALLOCATOR_H */
+909
View File
@@ -0,0 +1,909 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_HBRBILINEAR_H
#define OPENSUBDIV3_HBRBILINEAR_H
/*#define HBR_DEBUG */
#include "../hbr/subdivision.h"
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
template <class T>
class HbrBilinearSubdivision : public HbrSubdivision<T> {
public:
HbrBilinearSubdivision<T>()
: HbrSubdivision<T>() {}
virtual HbrSubdivision<T>* Clone() const {
return new HbrBilinearSubdivision<T>();
}
virtual void Refine(HbrMesh<T>* mesh, HbrFace<T>* face);
virtual HbrFace<T>* RefineFaceAtVertex(HbrMesh<T>* mesh, HbrFace<T>* face, HbrVertex<T>* vertex);
virtual void GuaranteeNeighbor(HbrMesh<T>* mesh, HbrHalfedge<T>* edge);
virtual void GuaranteeNeighbors(HbrMesh<T>* mesh, HbrVertex<T>* vertex);
virtual bool HasLimit(HbrMesh<T>* mesh, HbrFace<T>* face);
virtual bool HasLimit(HbrMesh<T>* mesh, HbrHalfedge<T>* edge);
virtual bool HasLimit(HbrMesh<T>* mesh, HbrVertex<T>* vertex);
virtual HbrVertex<T>* Subdivide(HbrMesh<T>* mesh, HbrFace<T>* face);
virtual HbrVertex<T>* Subdivide(HbrMesh<T>* mesh, HbrHalfedge<T>* edge);
virtual HbrVertex<T>* Subdivide(HbrMesh<T>* mesh, HbrVertex<T>* vertex);
virtual bool VertexIsExtraordinary(HbrMesh<T> const * /* mesh */, HbrVertex<T>* vertex) { return vertex->GetValence() != 4; }
virtual bool FaceIsExtraordinary(HbrMesh<T> const * /* mesh */, HbrFace<T>* face) { return face->GetNumVertices() != 4; }
virtual int GetFaceChildrenCount(int nvertices) const { return nvertices; }
private:
// Transfers facevarying data from a parent face to a child face
void transferFVarToChild(HbrMesh<T>* mesh, HbrFace<T>* face, HbrFace<T>* child, int index);
// Transfers vertex and edge edits from a parent face to a child face
void transferEditsToChild(HbrFace<T>* face, HbrFace<T>* child, int index);
};
template <class T>
void
HbrBilinearSubdivision<T>::transferFVarToChild(HbrMesh<T>* mesh, HbrFace<T>* face, HbrFace<T>* child, int index) {
typename HbrMesh<T>::InterpolateBoundaryMethod fvarinterp = mesh->GetFVarInterpolateBoundaryMethod();
const int fvarcount = mesh->GetFVarCount();
int fvarindex = 0;
const int nv = face->GetNumVertices();
bool extraordinary = (nv != 4);
HbrVertex<T> *v = face->GetVertex(index), *childVertex;
HbrHalfedge<T>* edge;
// We do the face subdivision rule first, because we may reuse the
// result (stored in fv2) for the other subdivisions.
float weight = 1.0f / nv;
// For the face center vertex, the facevarying data can be cleared
// and averaged en masse, since the subdivision rules don't change
// for any of the data - we use the smooth rule for all of it.
// And since we know that the fvardata for this particular vertex
// is smooth and therefore shareable amongst all incident faces,
// we don't have to allocate extra storage for it. We also don't
// have to compute it if some other face got to it first (as
// indicated by the IsInitialized() flag).
HbrFVarData<T>& fv2 = child->GetFVarData(extraordinary ? 2 : (index+2)%4);
if (!fv2.IsInitialized()) {
const int totalfvarwidth = mesh->GetTotalFVarWidth();
fv2.ClearAll(totalfvarwidth);
for (int j = 0; j < nv; ++j) {
fv2.AddWithWeightAll(face->GetFVarData(j), totalfvarwidth, weight);
}
}
assert(fv2.IsInitialized());
v->GuaranteeNeighbors();
// Make sure that that each of the vertices of the child face have
// the appropriate facevarying storage as needed. If there are
// discontinuities in any facevarying datum, the vertex must
// allocate a new block of facevarying storage specific to the
// child face.
bool fv0IsSmooth, fv1IsSmooth, fv3IsSmooth;
childVertex = child->GetVertex(extraordinary ? 0 : (index+0)%4);
fv0IsSmooth = v->IsFVarAllSmooth();
if (!fv0IsSmooth) {
childVertex->NewFVarData(child);
}
HbrFVarData<T>& fv0 = childVertex->GetFVarData(child);
edge = face->GetEdge(index);
GuaranteeNeighbor(mesh, edge);
assert(edge->GetOrgVertex() == v);
childVertex = child->GetVertex(extraordinary ? 1 : (index+1)%4);
fv1IsSmooth = !edge->IsFVarInfiniteSharpAnywhere();
if (!fv1IsSmooth) {
childVertex->NewFVarData(child);
}
HbrFVarData<T>& fv1 = childVertex->GetFVarData(child);
edge = edge->GetPrev();
GuaranteeNeighbor(mesh, edge);
assert(edge == face->GetEdge((index + nv - 1) % nv));
assert(edge->GetDestVertex() == v);
childVertex = child->GetVertex(extraordinary ? 3 : (index+3)%4);
fv3IsSmooth = !edge->IsFVarInfiniteSharpAnywhere();
if (!fv3IsSmooth) {
childVertex->NewFVarData(child);
}
HbrFVarData<T>& fv3 = childVertex->GetFVarData(child);
fvarindex = 0;
for (int fvaritem = 0; fvaritem < fvarcount; ++fvaritem) {
// Vertex subdivision rule. Analyze whether the vertex is on the
// boundary and whether it's an infinitely sharp corner. We
// determine the last by checking the propagate corners flag on
// the mesh; if it's off, we check the two edges of this face
// incident to that vertex and determining whether they are
// facevarying boundary edges - this is analogous to what goes on
// for the interpolateboundary tag (which when set to
// EDGEANDCORNER marks vertices with a valence of two as being
// sharp corners). If propagate corners is on, we check *all*
// faces to see if two edges side by side are facevarying boundary
// edges. The facevarying boundary check ignores geometric
// sharpness, otherwise we may swim at geometric creases which
// aren't actually discontinuous.
bool infcorner = false;
const int fvarwidth = mesh->GetFVarWidths()[fvaritem];
const unsigned char fvarmask = v->GetFVarMask(fvaritem);
if (fvarinterp == HbrMesh<T>::k_InterpolateBoundaryEdgeAndCorner) {
if (fvarmask >= HbrVertex<T>::k_Corner) {
infcorner = true;
} else if (mesh->GetFVarPropagateCorners()) {
if (v->IsFVarCorner(fvaritem)) {
infcorner = true;
}
} else {
if (face->GetEdge(index)->GetFVarSharpness(fvaritem, true) && face->GetEdge(index)->GetPrev()->GetFVarSharpness(fvaritem, true)) {
infcorner = true;
}
}
}
// Infinitely sharp vertex rule. Applied if the vertex is:
// - undergoing no facevarying boundary interpolation;
// - at a geometric crease, in either boundary interpolation case; or
// - is an infinitely sharp facevarying vertex, in the EDGEANDCORNER case; or
// - has a mask equal or greater than one, in the "always
// sharp" interpolate boundary case
if (fvarinterp == HbrMesh<T>::k_InterpolateBoundaryNone ||
(fvarinterp == HbrMesh<T>::k_InterpolateBoundaryAlwaysSharp &&
fvarmask >= 1) ||
v->GetSharpness() > HbrVertex<T>::k_Smooth ||
infcorner) {
fv0.SetWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 1.0f);
}
// Dart rule: unlike geometric creases, because there's two
// discontinuous values for the one incident edge, we use the
// boundary rule and not the smooth rule
else if (fvarmask == 1) {
assert(!v->OnBoundary());
// Use 0.75 of the current vert
fv0.SetWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 0.75f);
// 0.125 of "two adjacent edge vertices", which in actuality
// are the facevarying values of the same vertex but on each
// side of the single incident facevarying sharp edge
HbrHalfedge<T>* start = v->GetIncidentEdge(), *nextedge;
edge = start;
while (edge) {
if (edge->GetFVarSharpness(fvaritem)) {
break;
}
nextedge = v->GetNextEdge(edge);
if (nextedge == start) {
assert(0); // we should have found it by now
break;
} else if (!nextedge) {
// should never get into this case - if the vertex is
// on a boundary, it can never be a facevarying dart
// vertex
assert(0);
edge = edge->GetPrev();
break;
} else {
edge = nextedge;
}
}
HbrVertex<T>* w = edge->GetDestVertex();
HbrFace<T>* bestface = edge->GetLeftFace();
int j;
for (j = 0; j < bestface->GetNumVertices(); ++j) {
if (bestface->GetVertex(j) == w) break;
}
assert(j != bestface->GetNumVertices());
fv0.AddWithWeight(bestface->GetFVarData(j), fvarindex, fvarwidth, 0.125f);
bestface = edge->GetRightFace();
for (j = 0; j < bestface->GetNumVertices(); ++j) {
if (bestface->GetVertex(j) == w) break;
}
assert(j != bestface->GetNumVertices());
fv0.AddWithWeight(bestface->GetFVarData(j), fvarindex, fvarwidth, 0.125f);
}
// Boundary vertex rule
else if (fvarmask != 0) {
// Use 0.75 of the current vert
fv0.SetWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 0.75f);
// Compute 0.125 of two adjacent edge vertices. However the
// two adjacent edge vertices we use must be part of the
// facevarying "boundary". To find the first edge we cycle
// counterclockwise around the current vertex v and look for
// the first boundary edge
HbrFace<T>* bestface = face;
HbrHalfedge<T>* bestedge = face->GetEdge(index)->GetPrev();
HbrHalfedge<T>* starte = bestedge->GetOpposite();
HbrVertex<T>* w = 0;
if (!starte) {
w = face->GetEdge(index)->GetPrev()->GetOrgVertex();
} else {
HbrHalfedge<T>* e = starte, *next;
assert(starte->GetOrgVertex() == v);
do {
if (e->GetFVarSharpness(fvaritem) || !e->GetLeftFace()) {
bestface = e->GetRightFace();
bestedge = e;
break;
}
next = v->GetNextEdge(e);
if (!next) {
bestface = e->GetLeftFace();
w = e->GetPrev()->GetOrgVertex();
break;
}
e = next;
} while (e && e != starte);
}
if (!w) w = bestedge->GetDestVertex();
int j;
for (j = 0; j < bestface->GetNumVertices(); ++j) {
if (bestface->GetVertex(j) == w) break;
}
assert(j != bestface->GetNumVertices());
fv0.AddWithWeight(bestface->GetFVarData(j), fvarindex, fvarwidth, 0.125f);
// Look for the other edge by cycling clockwise around v
bestface = face;
bestedge = face->GetEdge(index);
starte = bestedge;
w = 0;
if (HbrHalfedge<T>* e = starte) {
assert(starte->GetOrgVertex() == v);
do {
if (e->GetFVarSharpness(fvaritem) || !e->GetRightFace()) {
bestface = e->GetLeftFace();
bestedge = e;
break;
}
assert(e->GetOpposite());
e = v->GetPreviousEdge(e);
} while (e && e != starte);
}
if (!w) w = bestedge->GetDestVertex();
for (j = 0; j < bestface->GetNumVertices(); ++j) {
if (bestface->GetVertex(j) == w) break;
}
assert(j != bestface->GetNumVertices());
fv0.AddWithWeight(bestface->GetFVarData(j), fvarindex, fvarwidth, 0.125f);
}
// Smooth rule. Here, we can take a shortcut if we know that
// the vertex is smooth and some other vertex has completely
// computed the facevarying values
else if (!fv0IsSmooth || !fv0.IsInitialized()) {
int valence = v->GetValence();
float invvalencesquared = 1.0f / (valence * valence);
// Use n-2/n of the current vertex value
fv0.SetWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, invvalencesquared * valence * (valence - 2));
// Add 1/n^2 of surrounding edge vertices and surrounding face
// averages. We loop over all surrounding faces..
HbrHalfedge<T>* start = v->GetIncidentEdge(), *edge;
edge = start;
while (edge) {
HbrFace<T>* g = edge->GetLeftFace();
weight = invvalencesquared / g->GetNumVertices();
// .. and compute the average of each face. At the same
// time, we look for the edge on that face whose origin is
// the same as v, and add a contribution from its
// destination vertex value; this takes care of the
// surrounding edge vertex addition.
for (int j = 0; j < g->GetNumVertices(); ++j) {
fv0.AddWithWeight(g->GetFVarData(j), fvarindex, fvarwidth, weight);
if (g->GetEdge(j)->GetOrgVertex() == v) {
fv0.AddWithWeight(g->GetFVarData((j + 1) % g->GetNumVertices()), fvarindex, fvarwidth, invvalencesquared);
}
}
edge = v->GetNextEdge(edge);
if (edge == start) break;
}
}
// Edge subdivision rule
edge = face->GetEdge(index);
if (fvarinterp == HbrMesh<T>::k_InterpolateBoundaryNone ||
edge->GetFVarSharpness(fvaritem) || edge->IsBoundary()) {
// Sharp edge rule
fv1.SetWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 0.5f);
fv1.AddWithWeight(face->GetFVarData((index + 1) % nv), fvarindex, fvarwidth, 0.5f);
} else if (!fv1IsSmooth || !fv1.IsInitialized()) {
// Smooth edge subdivision. Add 0.25 of adjacent vertices
fv1.SetWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 0.25f);
fv1.AddWithWeight(face->GetFVarData((index + 1) % nv), fvarindex, fvarwidth, 0.25f);
// Local subdivided face vertex
fv1.AddWithWeight(fv2, fvarindex, fvarwidth, 0.25f);
// Add 0.25 * average of neighboring face vertices
HbrFace<T>* oppFace = edge->GetRightFace();
weight = 0.25f / oppFace->GetNumVertices();
for (int j = 0; j < oppFace->GetNumVertices(); ++j) {
fv1.AddWithWeight(oppFace->GetFVarData(j), fvarindex, fvarwidth, weight);
}
}
// Edge subdivision rule
edge = edge->GetPrev();
if (fvarinterp == HbrMesh<T>::k_InterpolateBoundaryNone ||
edge->GetFVarSharpness(fvaritem) || edge->IsBoundary()) {
// Sharp edge rule
fv3.SetWithWeight(face->GetFVarData((index + nv - 1) % nv), fvarindex, fvarwidth, 0.5f);
fv3.AddWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 0.5f);
} else if (!fv3IsSmooth || !fv3.IsInitialized()) {
// Smooth edge subdivision. Add 0.25 of adjacent vertices
fv3.SetWithWeight(face->GetFVarData((index + nv - 1) % nv), fvarindex, fvarwidth, 0.25f);
fv3.AddWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 0.25f);
// Local subdivided face vertex
fv3.AddWithWeight(fv2, fvarindex, fvarwidth, 0.25f);
// Add 0.25 * average of neighboring face vertices
HbrFace<T>* oppFace = edge->GetRightFace();
weight = 0.25f / oppFace->GetNumVertices();
for (int j = 0; j < oppFace->GetNumVertices(); ++j) {
fv3.AddWithWeight(oppFace->GetFVarData(j), fvarindex, fvarwidth, weight);
}
}
fvarindex += fvarwidth;
}
fv0.SetInitialized();
fv1.SetInitialized();
fv3.SetInitialized();
}
template <class T>
void
HbrBilinearSubdivision<T>::transferEditsToChild(HbrFace<T>* face, HbrFace<T>* child, int index) {
// Hand down hole tag
child->SetHole(face->IsHole());
// Hand down pointers to hierarchical edits
if (HbrHierarchicalEdit<T>** edits = face->GetHierarchicalEdits()) {
while (HbrHierarchicalEdit<T>* edit = *edits) {
if (!edit->IsRelevantToFace(face)) break;
if (edit->GetNSubfaces() > face->GetDepth() &&
(edit->GetSubface(face->GetDepth()) == index)) {
child->SetHierarchicalEdits(edits);
break;
}
edits++;
}
}
}
template <class T>
void
HbrBilinearSubdivision<T>::Refine(HbrMesh<T>* mesh, HbrFace<T>* face) {
// Create new quadrilateral children faces from this face
HbrFace<T>* child;
HbrVertex<T>* vertices[4];
HbrHalfedge<T>* edge = face->GetFirstEdge();
HbrHalfedge<T>* prevedge = edge->GetPrev();
HbrHalfedge<T>* childedge;
int nv = face->GetNumVertices();
float sharpness;
bool extraordinary = (nv != 4);
// The funny indexing on vertices is done only for
// non-extraordinary faces in order to correctly preserve
// parametric space through the refinement. If we split an
// extraordinary face then it doesn't matter.
for (int i = 0; i < nv; ++i) {
if (!face->GetChild(i)) {
#ifdef HBR_DEBUG
std::cerr << "Kid " << i << "\n";
#endif
HbrVertex<T>* vertex = edge->GetOrgVertex();
if (extraordinary) {
vertices[0] = vertex->Subdivide();
vertices[1] = edge->Subdivide();
vertices[2] = face->Subdivide();
vertices[3] = prevedge->Subdivide();
} else {
vertices[i] = vertex->Subdivide();
vertices[(i+1)%4] = edge->Subdivide();
vertices[(i+2)%4] = face->Subdivide();
vertices[(i+3)%4] = prevedge->Subdivide();
}
child = mesh->NewFace(4, vertices, face, i);
#ifdef HBR_DEBUG
std::cerr << "Creating face " << *child << " during refine\n";
#endif
// Hand down edge sharpnesses
childedge = vertex->Subdivide()->GetEdge(edge->Subdivide());
assert(childedge);
if ((sharpness = edge->GetSharpness()) > HbrHalfedge<T>::k_Smooth) {
HbrSubdivision<T>::SubdivideCreaseWeight(edge, edge->GetOrgVertex(), childedge);
}
childedge->CopyFVarInfiniteSharpness(edge);
childedge = prevedge->Subdivide()->GetEdge(vertex->Subdivide());
assert(childedge);
if ((sharpness = prevedge->GetSharpness()) > HbrHalfedge<T>::k_Smooth) {
HbrSubdivision<T>::SubdivideCreaseWeight(prevedge, prevedge->GetDestVertex(), childedge);
}
childedge->CopyFVarInfiniteSharpness(prevedge);
if (mesh->GetTotalFVarWidth()) {
transferFVarToChild(mesh, face, child, i);
}
// Special handling of ptex index for extraordinary faces: make
// sure the children get their indices reassigned to be
// consecutive within the block reserved for the parent.
if (face->GetNumVertices() != 4 && face->GetPtexIndex() != -1) {
child->SetPtexIndex(face->GetPtexIndex() + i);
}
transferEditsToChild(face, child, i);
}
prevedge = edge;
edge = edge->GetNext();
}
}
template <class T>
HbrFace<T>*
HbrBilinearSubdivision<T>::RefineFaceAtVertex(HbrMesh<T>* mesh, HbrFace<T>* face, HbrVertex<T>* vertex) {
#ifdef HBR_DEBUG
std::cerr << " forcing refine on " << *face << " at " << *vertex << '\n';
#endif
// Create new quadrilateral children faces from this face
HbrHalfedge<T>* edge = face->GetFirstEdge();
HbrHalfedge<T>* prevedge = edge->GetPrev();
HbrHalfedge<T>* childedge;
int nv = face->GetNumVertices();
float sharpness;
bool extraordinary = (nv != 4);
// The funny indexing on vertices is done only for
// non-extraordinary faces in order to correctly preserve
// parametric space through the refinement. If we split an
// extraordinary face then it doesn't matter.
for (int i = 0; i < nv; ++i) {
if (edge->GetOrgVertex() == vertex) {
if (!face->GetChild(i)) {
HbrFace<T>* child;
HbrVertex<T>* vertices[4];
if (extraordinary) {
vertices[0] = vertex->Subdivide();
vertices[1] = edge->Subdivide();
vertices[2] = face->Subdivide();
vertices[3] = prevedge->Subdivide();
} else {
vertices[i] = vertex->Subdivide();
vertices[(i+1)%4] = edge->Subdivide();
vertices[(i+2)%4] = face->Subdivide();
vertices[(i+3)%4] = prevedge->Subdivide();
}
#ifdef HBR_DEBUG
std::cerr << "Kid " << i << "\n";
std::cerr << " subdivision created " << *vertices[0] << '\n';
std::cerr << " subdivision created " << *vertices[1] << '\n';
std::cerr << " subdivision created " << *vertices[2] << '\n';
std::cerr << " subdivision created " << *vertices[3] << '\n';
#endif
child = mesh->NewFace(4, vertices, face, i);
#ifdef HBR_DEBUG
std::cerr << "Creating face " << *child << " during refine\n";
#endif
// Hand down edge sharpness
childedge = vertex->Subdivide()->GetEdge(edge->Subdivide());
assert(childedge);
if ((sharpness = edge->GetSharpness()) > HbrHalfedge<T>::k_Smooth) {
HbrSubdivision<T>::SubdivideCreaseWeight(edge, edge->GetOrgVertex(), childedge);
}
childedge->CopyFVarInfiniteSharpness(edge);
childedge = prevedge->Subdivide()->GetEdge(vertex->Subdivide());
assert(childedge);
if ((sharpness = prevedge->GetSharpness()) > HbrHalfedge<T>::k_Smooth) {
HbrSubdivision<T>::SubdivideCreaseWeight(prevedge, prevedge->GetDestVertex(), childedge);
}
childedge->CopyFVarInfiniteSharpness(prevedge);
if (mesh->GetTotalFVarWidth()) {
transferFVarToChild(mesh, face, child, i);
}
// Special handling of ptex index for extraordinary faces: make
// sure the children get their indices reassigned to be
// consecutive within the block reserved for the parent.
if (face->GetNumVertices() != 4 && face->GetPtexIndex() != -1) {
child->SetPtexIndex(face->GetPtexIndex() + i);
}
transferEditsToChild(face, child, i);
return child;
} else {
return face->GetChild(i);
}
}
prevedge = edge;
edge = edge->GetNext();
}
return 0;
}
template <class T>
void
HbrBilinearSubdivision<T>::GuaranteeNeighbor(HbrMesh<T>* mesh, HbrHalfedge<T>* edge) {
if (edge->GetOpposite()) {
return;
}
// For the given edge: if the parent of either of its incident
// vertices is itself a _face_, then ensuring that this parent
// face has refined at a particular vertex is sufficient to
// ensure that both of the faces on each side of the edge have
// been created.
bool destParentWasEdge = true;
HbrFace<T>* parentFace = edge->GetOrgVertex()->GetParentFace();
HbrHalfedge<T>* parentEdge = edge->GetDestVertex()->GetParentEdge();
if (!parentFace) {
destParentWasEdge = false;
parentFace = edge->GetDestVertex()->GetParentFace();
parentEdge = edge->GetOrgVertex()->GetParentEdge();
}
if (parentFace) {
// Make sure we deal with a parent halfedge which is
// associated with the parent face
if (parentEdge->GetFace() != parentFace) {
parentEdge = parentEdge->GetOpposite();
}
// If one of the vertices had a parent face, the other one MUST
// have been a child of an edge
assert(parentEdge && parentEdge->GetFace() == parentFace);
#ifdef HBR_DEBUG
std::cerr << "\nparent edge is " << *parentEdge << "\n";
#endif
// The vertex to refine at depends on whether the
// destination or origin vertex of this edge had a parent
// edge
if (destParentWasEdge) {
RefineFaceAtVertex(mesh, parentFace, parentEdge->GetOrgVertex());
} else {
RefineFaceAtVertex(mesh, parentFace, parentEdge->GetDestVertex());
}
// It should always be the case that the opposite now exists -
// we can't have a boundary case here
assert(edge->GetOpposite());
} else {
HbrVertex<T>* parentVertex = edge->GetOrgVertex()->GetParentVertex();
parentEdge = edge->GetDestVertex()->GetParentEdge();
if (!parentVertex) {
parentVertex = edge->GetDestVertex()->GetParentVertex();
parentEdge = edge->GetOrgVertex()->GetParentEdge();
}
if (parentVertex) {
assert(parentEdge);
#ifdef HBR_DEBUG
std::cerr << "\nparent edge is " << *parentEdge << "\n";
#endif
// 1. Go up to the parent of my face
parentFace = edge->GetFace()->GetParent();
#ifdef HBR_DEBUG
std::cerr << "\nparent face is " << *parentFace << "\n";
#endif
// 2. Ask the opposite face (if it exists) to refine
if (parentFace) {
// A vertex can be associated with either of two
// parent halfedges. If the parent edge that we're
// interested in doesn't match then we should look at
// its opposite
if (parentEdge->GetFace() != parentFace)
parentEdge = parentEdge->GetOpposite();
assert(parentEdge->GetFace() == parentFace);
// Make sure the parent edge has its neighbor as well
GuaranteeNeighbor(mesh, parentEdge);
// Now access that neighbor and refine it
if (parentEdge->GetRightFace()) {
RefineFaceAtVertex(mesh, parentEdge->GetRightFace(), parentVertex);
// FIXME: assertion?
assert(edge->GetOpposite());
}
}
}
}
}
template <class T>
void
HbrBilinearSubdivision<T>::GuaranteeNeighbors(HbrMesh<T>* mesh, HbrVertex<T>* vertex) {
#ifdef HBR_DEBUG
std::cerr << "\n\nneighbor guarantee at " << *vertex << " invoked\n";
#endif
// If the vertex is a child of a face, guaranteeing the neighbors
// of the vertex is simply a matter of ensuring the parent face
// has refined.
HbrFace<T>* parentFace = vertex->GetParentFace();
if (parentFace) {
#ifdef HBR_DEBUG
std::cerr << " forcing full refine on parent face\n";
#endif
Refine(mesh, parentFace);
return;
}
// Otherwise if the vertex is a child of an edge, we need to
// ensure that the parent faces on either side of the parent edge
// 1) exist, and 2) have refined at both vertices of the parent
// edge
HbrHalfedge<T>* parentEdge = vertex->GetParentEdge();
if (parentEdge) {
#ifdef HBR_DEBUG
std::cerr << " forcing full refine on adjacent faces of parent edge\n";
#endif
HbrVertex<T>* dest = parentEdge->GetDestVertex();
HbrVertex<T>* org = parentEdge->GetOrgVertex();
GuaranteeNeighbor(mesh, parentEdge);
parentFace = parentEdge->GetLeftFace();
RefineFaceAtVertex(mesh, parentFace, dest);
RefineFaceAtVertex(mesh, parentFace, org);
#ifdef HBR_DEBUG
std::cerr << " on the right face?\n";
#endif
parentFace = parentEdge->GetRightFace();
// The right face may not necessarily exist even after
// GuaranteeNeighbor
if (parentFace) {
RefineFaceAtVertex(mesh, parentFace, dest);
RefineFaceAtVertex(mesh, parentFace, org);
}
#ifdef HBR_DEBUG
std::cerr << " end force\n";
#endif
return;
}
// The last case: the vertex is a child of a vertex. In this case
// we have to first recursively guarantee that the parent's
// adjacent faces also exist.
HbrVertex<T>* parentVertex = vertex->GetParentVertex();
if (parentVertex) {
#ifdef HBR_DEBUG
std::cerr << " recursive parent vertex guarantee call\n";
#endif
parentVertex->GuaranteeNeighbors();
// And then we refine all the face neighbors of the
// parentVertex
HbrHalfedge<T>* start = parentVertex->GetIncidentEdge(), *edge;
edge = start;
while (edge) {
HbrFace<T>* f = edge->GetLeftFace();
RefineFaceAtVertex(mesh, f, parentVertex);
edge = parentVertex->GetNextEdge(edge);
if (edge == start) break;
}
}
}
template <class T>
bool
HbrBilinearSubdivision<T>::HasLimit(HbrMesh<T>* mesh, HbrFace<T>* face) {
if (face->IsHole()) return false;
// A limit face exists if all the bounding edges have limit curves
for (int i = 0; i < face->GetNumVertices(); ++i) {
if (!HasLimit(mesh, face->GetEdge(i))) {
return false;
}
}
return true;
}
template <class T>
bool
HbrBilinearSubdivision<T>::HasLimit(HbrMesh<T>* /* mesh */, HbrHalfedge<T>* /* edge */) {
return true;
}
template <class T>
bool
HbrBilinearSubdivision<T>::HasLimit(HbrMesh<T>* /* mesh */, HbrVertex<T>* vertex) {
vertex->GuaranteeNeighbors();
switch (vertex->GetMask(false)) {
case HbrVertex<T>::k_Smooth:
case HbrVertex<T>::k_Dart:
return !vertex->OnBoundary();
break;
case HbrVertex<T>::k_Crease:
case HbrVertex<T>::k_Corner:
default:
return true;
}
}
template <class T>
HbrVertex<T>*
HbrBilinearSubdivision<T>::Subdivide(HbrMesh<T>* mesh, HbrFace<T>* face) {
// Face rule: simply average all vertices on the face
HbrVertex<T>* v = mesh->NewVertex();
T& data = v->GetData();
int nv = face->GetNumVertices();
float weight = 1.0f / nv;
HbrHalfedge<T>* edge = face->GetFirstEdge();
for (int i = 0; i < face->GetNumVertices(); ++i) {
HbrVertex<T>* w = edge->GetOrgVertex();
// If there are vertex edits we have to make sure the edit
// has been applied
if (mesh->HasVertexEdits()) {
w->GuaranteeNeighbors();
}
data.AddWithWeight(w->GetData(), weight);
data.AddVaryingWithWeight(w->GetData(), weight);
edge = edge->GetNext();
}
#ifdef HBR_DEBUG
std::cerr << "Subdividing at " << *face << "\n";
#endif
// Set the extraordinary flag if the face had anything other than
// 4 vertices
if (nv != 4) v->SetExtraordinary();
#ifdef HBR_DEBUG
std::cerr << " created " << *v << "\n";
#endif
return v;
}
template <class T>
HbrVertex<T>*
HbrBilinearSubdivision<T>::Subdivide(HbrMesh<T>* mesh, HbrHalfedge<T>* edge) {
#ifdef HBR_DEBUG
float esharp = edge->GetSharpness();
std::cerr << "Subdividing at " << *edge << " (sharpness = " << esharp << ")";
#endif
HbrVertex<T>* v = mesh->NewVertex();
T& data = v->GetData();
// If there's the possibility of a crease edits, make sure the
// edit has been applied
if (mesh->HasCreaseEdits()) {
edge->GuaranteeNeighbor();
}
// If there's the possibility of vertex edits on either vertex, we
// have to make sure the edit has been applied
if (mesh->HasVertexEdits()) {
edge->GetOrgVertex()->GuaranteeNeighbors();
edge->GetDestVertex()->GuaranteeNeighbors();
}
// Average the two end points
data.AddWithWeight(edge->GetOrgVertex()->GetData(), 0.5f);
data.AddWithWeight(edge->GetDestVertex()->GetData(), 0.5f);
// Varying data is always the average of two end points
data.AddVaryingWithWeight(edge->GetOrgVertex()->GetData(), 0.5f);
data.AddVaryingWithWeight(edge->GetDestVertex()->GetData(), 0.5f);
#ifdef HBR_DEBUG
std::cerr << " created " << *v << "\n";
#endif
return v;
}
template <class T>
HbrVertex<T>*
HbrBilinearSubdivision<T>::Subdivide(HbrMesh<T>* mesh, HbrVertex<T>* vertex) {
HbrVertex<T>* v;
// If there are vertex edits we have to make sure the edit has
// been applied by guaranteeing the neighbors of the
// vertex. Unfortunately in this case, we can't share the data
// with the parent
if (mesh->HasVertexEdits()) {
vertex->GuaranteeNeighbors();
v = mesh->NewVertex();
T& data = v->GetData();
// Just copy the old value
data.AddWithWeight(vertex->GetData(), 1.0f);
// Varying data is always just propagated down
data.AddVaryingWithWeight(vertex->GetData(), 1.0f);
} else {
// Create a new vertex that just shares the same data
v = mesh->NewVertex(vertex->GetData());
}
#ifdef HBR_DEBUG
std::cerr << "Subdividing at " << *vertex << "\n";
std::cerr << " created " << *v << "\n";
#endif
// Inherit extraordinary flag and sharpness
if (vertex->IsExtraordinary()) v->SetExtraordinary();
float sharp = vertex->GetSharpness();
if (sharp >= HbrVertex<T>::k_InfinitelySharp) {
v->SetSharpness(HbrVertex<T>::k_InfinitelySharp);
} else if (sharp > HbrVertex<T>::k_Smooth) {
sharp -= 1.0f;
if (sharp < (float) HbrVertex<T>::k_Smooth) {
sharp = (float) HbrVertex<T>::k_Smooth;
}
v->SetSharpness(sharp);
} else {
v->SetSharpness(HbrVertex<T>::k_Smooth);
}
return v;
}
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_HBRBILINEAR_H */
File diff suppressed because it is too large. Load diff
+98
View File
@@ -0,0 +1,98 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_HBRCORNEREDIT_H
#define OPENSUBDIV3_HBRCORNEREDIT_H
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
template <class T> class HbrCornerEdit;
template <class T>
std::ostream& operator<<(std::ostream& out, const HbrCornerEdit<T>& path) {
out << "vertex path = (" << path.faceid << ' ';
for (int i = 0; i < path.nsubfaces; ++i) {
out << static_cast<int>(path.subfaces[i]) << ' ';
}
return out << static_cast<int>(path.vertexid) << "), sharpness = " << path.sharpness;
}
template <class T>
class HbrCornerEdit : public HbrHierarchicalEdit<T> {
public:
HbrCornerEdit(int _faceid, int _nsubfaces, unsigned char *_subfaces, unsigned char _vertexid, typename HbrHierarchicalEdit<T>::Operation _op, float _sharpness)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces), vertexid(_vertexid), op(_op), sharpness(_sharpness) {
}
HbrCornerEdit(int _faceid, int _nsubfaces, int *_subfaces, int _vertexid, typename HbrHierarchicalEdit<T>::Operation _op, float _sharpness)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces), vertexid(static_cast<unsigned char>(_vertexid)), op(_op), sharpness(_sharpness) {
}
virtual ~HbrCornerEdit() {}
friend std::ostream& operator<< <T> (std::ostream& out, const HbrCornerEdit<T>& path);
virtual void ApplyEditToFace(HbrFace<T>* face) {
if (HbrHierarchicalEdit<T>::GetNSubfaces() == face->GetDepth()) {
// Modify vertex sharpness. Note that we could actually do
// this in ApplyEditToVertex as well!
float sharp = 0.0f;
if (op == HbrHierarchicalEdit<T>::Set) {
sharp = sharpness;
} else if (op == HbrHierarchicalEdit<T>::Add) {
sharp = face->GetVertex(vertexid)->GetSharpness() + sharpness;
} else if (op == HbrHierarchicalEdit<T>::Subtract) {
sharp = face->GetVertex(vertexid)->GetSharpness() - sharpness;
}
if (sharp < HbrVertex<T>::k_Smooth) {
sharp = HbrVertex<T>::k_Smooth;
}
if (sharp > HbrVertex<T>::k_InfinitelySharp) {
sharp = HbrVertex<T>::k_InfinitelySharp;
}
face->GetVertex(vertexid)->SetSharpness(sharp);
}
}
private:
// ID of the edge (you can think of this also as the id of the
// origin vertex of the two-vertex length edge)
const unsigned char vertexid;
typename HbrHierarchicalEdit<T>::Operation op;
// sharpness of the vertex edit
const float sharpness;
};
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_HBRCORNEREDIT_H */
+100
View File
@@ -0,0 +1,100 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_HBRCREASEEDIT_H
#define OPENSUBDIV3_HBRCREASEEDIT_H
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
template <class T> class HbrCreaseEdit;
template <class T>
std::ostream& operator<<(std::ostream& out, const HbrCreaseEdit<T>& path) {
out << "edge path = (" << path.faceid << ' ';
for (int i = 0; i < path.nsubfaces; ++i) {
out << static_cast<int>(path.subfaces[i]) << ' ';
}
return out << static_cast<int>(path.edgeid) << "), sharpness = " << path.sharpness;
}
template <class T>
class HbrCreaseEdit : public HbrHierarchicalEdit<T> {
public:
HbrCreaseEdit(int _faceid, int _nsubfaces, unsigned char *_subfaces, unsigned char _edgeid, typename HbrHierarchicalEdit<T>::Operation _op, float _sharpness)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces), edgeid(_edgeid), op(_op), sharpness(_sharpness) {
}
HbrCreaseEdit(int _faceid, int _nsubfaces, int *_subfaces, int _edgeid, typename HbrHierarchicalEdit<T>::Operation _op, float _sharpness)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces), edgeid(static_cast<unsigned char>(_edgeid)), op(_op), sharpness(_sharpness) {
}
virtual ~HbrCreaseEdit() {}
friend std::ostream& operator<< <T> (std::ostream& out, const HbrCreaseEdit<T>& path);
virtual void ApplyEditToFace(HbrFace<T>* face) {
if (HbrHierarchicalEdit<T>::GetNSubfaces() == face->GetDepth()) {
// Modify edge sharpness
float sharp=0.0f;
if (op == HbrHierarchicalEdit<T>::Set) {
sharp = sharpness;
} else if (op == HbrHierarchicalEdit<T>::Add) {
sharp = face->GetEdge(edgeid)->GetSharpness() + sharpness;
} else if (op == HbrHierarchicalEdit<T>::Subtract) {
sharp = face->GetEdge(edgeid)->GetSharpness() - sharpness;
}
if (sharp < HbrHalfedge<T>::k_Smooth)
sharp = HbrHalfedge<T>::k_Smooth;
if (sharp > HbrHalfedge<T>::k_InfinitelySharp)
sharp = HbrHalfedge<T>::k_InfinitelySharp;
// We have to make sure the neighbor of the edge exists at
// this point. Otherwise, if it comes into being late, it
// will clobber the overriden sharpness and we will lose
// the edit.
face->GetEdge(edgeid)->GuaranteeNeighbor();
face->GetEdge(edgeid)->SetSharpness(sharp);
}
}
private:
// ID of the edge (you can think of this also as the id of the
// origin vertex of the two-vertex length edge)
const unsigned char edgeid;
typename HbrHierarchicalEdit<T>::Operation op;
// sharpness of the edge edit
const float sharpness;
};
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_HBRCREASEEDIT_H */
File diff suppressed because it is too large. Load diff
+125
View File
@@ -0,0 +1,125 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_HBRFACEEDIT_H
#define OPENSUBDIV3_HBRFACEEDIT_H
#include "../hbr/hierarchicalEdit.h"
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
template <class T> class HbrFaceEdit;
template <class T>
std::ostream& operator<<(std::ostream& out, const HbrFaceEdit<T>& path) {
out << "face path = (" << path.faceid << ' ';
for (int i = 0; i < path.nsubfaces; ++i) {
out << static_cast<int>(path.subfaces[i]) << ' ';
}
return out << ")";
}
template <class T>
class HbrFaceEdit : public HbrHierarchicalEdit<T> {
public:
HbrFaceEdit(int _faceid, int _nsubfaces, unsigned char *_subfaces, int _index, int _width, typename HbrHierarchicalEdit<T>::Operation _op, float *_edit)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces), index(_index), width(_width), op(_op) {
edit = new float[width];
memcpy(edit, _edit, width * sizeof(float));
}
HbrFaceEdit(int _faceid, int _nsubfaces, int *_subfaces, int _index, int _width, typename HbrHierarchicalEdit<T>::Operation _op, float *_edit)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces), index(_index), width(_width), op(_op) {
edit = new float[width];
memcpy(edit, _edit, width * sizeof(float));
}
#ifdef PRMAN
HbrFaceEdit(int _faceid, int _nsubfaces, unsigned char *_subfaces, int _index, int _width, typename HbrHierarchicalEdit<T>::Operation _op, RtToken _edit)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces), index(_index), width(_width), op(_op) {
edit = new float[width];
RtString* sedit = (RtString*) edit;
*sedit = _edit;
}
HbrFaceEdit(int _faceid, int _nsubfaces, int *_subfaces, int _index, int _width, typename HbrHierarchicalEdit<T>::Operation _op, RtToken _edit)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces), index(_index), width(_width), op(_op) {
edit = new float[width];
RtString* sedit = (RtString*) edit;
*sedit = _edit;
}
#endif
virtual ~HbrFaceEdit() {
delete[] edit;
}
friend std::ostream& operator<< <T> (std::ostream& out, const HbrFaceEdit<T>& path);
// Return index of variable this edit applies to
int GetIndex() const { return index; }
// Return width of the variable
int GetWidth() const { return width; }
// Get the numerical value of the edit
const float* GetEdit() const { return edit; }
// Get the type of operation
typename HbrHierarchicalEdit<T>::Operation GetOperation() const { return op; }
virtual void ApplyEditToFace(HbrFace<T>* face) {
if (HbrHierarchicalEdit<T>::GetNSubfaces() == face->GetDepth()) {
int oldUniformIndex = face->GetUniformIndex();
// Any face below level 0 needs a new uniform index
if (face->GetDepth() > 0) {
face->SetUniformIndex(face->GetMesh()->NewUniformIndex());
}
// Apply edit
face->GetVertex(0)->GetData().ApplyFaceEdit(oldUniformIndex, face->GetUniformIndex(), *const_cast<const HbrFaceEdit<T>*>(this));
}
}
private:
int index;
int width;
typename HbrHierarchicalEdit<T>::Operation op;
float* edit;
};
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_HBRFACEEDIT_H */
+200
View File
@@ -0,0 +1,200 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_HBRFVARDATA_H
#define OPENSUBDIV3_HBRFVARDATA_H
#include <cstring>
#include <cmath>
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
template <class T> class HbrFVarEdit;
template <class T> class HbrFace;
template <class T> class HbrVertex;
// This class implements a "face varying vector item". Really it's
// just a smart wrapper around face varying data (itself just a bunch
// of floats) stored on each vertex.
template <class T> class HbrFVarData {
private:
HbrFVarData()
: faceid(0), initialized(0) {
}
~HbrFVarData() {
Uninitialize();
}
HbrFVarData(const HbrFVarData &/* data */) {}
public:
// Sets the face id
void SetFaceID(int id) {
faceid = id;
}
// Returns the id of the face to which this data is bound
int GetFaceID() const {
return faceid;
}
// Clears the initialized flag
void Uninitialize() {
initialized = 0;
faceid = 0;
}
// Returns initialized flag
bool IsInitialized() const {
return initialized;
}
// Sets initialized flag
void SetInitialized() {
initialized = 1;
}
// Return the data from the NgpFVVector
float* GetData(int item) { return data + item; }
// Clears the indicates value of this item
void Clear(int startindex, int width) {
memset(data + startindex, 0, width * sizeof(float));
}
// Clears all values of this item
void ClearAll(int width) {
initialized = 1;
memset(data, 0, width * sizeof(float));
}
// Set values of the indicated item (with the indicated weighing)
// on this item
void SetWithWeight(const HbrFVarData& fvvi, int startindex, int width, float weight) {
float *dst = data + startindex;
const float *src = fvvi.data + startindex;
for (int i = 0; i < width; ++i) {
*dst++ = weight * *src++;
}
}
// Add values of the indicated item (with the indicated weighing)
// to this item
void AddWithWeight(const HbrFVarData& fvvi, int startindex, int width, float weight) {
float *dst = data + startindex;
const float *src = fvvi.data + startindex;
for (int i = 0; i < width; ++i) {
*dst++ += weight * *src++;
}
}
// Add all values of the indicated item (with the indicated
// weighing) to this item
void AddWithWeightAll(const HbrFVarData& fvvi, int width, float weight) {
float *dst = data;
const float *src = fvvi.data;
for (int i = 0; i < width; ++i) {
*dst++ += weight * *src++;
}
}
// Compare all values item against a float buffer. Returns true
// if all values match
bool CompareAll(int width, const float *values, float tolerance=0.0f) const {
if (!initialized) return false;
for (int i = 0; i < width; ++i) {
if (fabsf(values[i] - data[i]) > tolerance) return false;
}
return true;
}
// Initializes data
void SetAllData(int width, const float *values) {
initialized = 1;
memcpy(data, values, width * sizeof(float));
}
// Compare this item against another item with tolerance. Returns
// true if it compares identical
bool Compare(const HbrFVarData& fvvi, int startindex, int width, float tolerance=0.0f) const {
for (int i = 0; i < width; ++i) {
if (fabsf(data[startindex + i] - fvvi.data[startindex + i]) > tolerance) return false;
}
return true;
}
// Modify the data of the item with an edit
void ApplyFVarEdit(const HbrFVarEdit<T>& edit);
friend class HbrVertex<T>;
private:
unsigned int faceid:31;
unsigned int initialized:1;
float data[1];
};
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#include "../hbr/fvarEdit.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
template <class T>
void
HbrFVarData<T>::ApplyFVarEdit(const HbrFVarEdit<T>& edit) {
float *dst = data + edit.GetIndex() + edit.GetOffset();
const float *src = edit.GetEdit();
for (int i = 0; i < edit.GetWidth(); ++i) {
switch(edit.GetOperation()) {
case HbrVertexEdit<T>::Set:
*dst++ = *src++;
break;
case HbrVertexEdit<T>::Add:
*dst++ += *src++;
break;
case HbrVertexEdit<T>::Subtract:
*dst++ -= *src++;
}
}
initialized = 1;
}
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_HBRFVARDATA_H */
+121
View File
@@ -0,0 +1,121 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_HBRFVAREDIT_H
#define OPENSUBDIV3_HBRFVAREDIT_H
#include "../hbr/hierarchicalEdit.h"
#include "../hbr/vertexEdit.h"
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
template <class T> class HbrFVarEdit;
template <class T>
std::ostream& operator<<(std::ostream& out, const HbrFVarEdit<T>& path) {
out << "vertex path = (" << path.faceid << ' ';
for (int i = 0; i < path.nsubfaces; ++i) {
out << static_cast<int>(path.subfaces[i]) << ' ';
}
return out << static_cast<int>(path.vertexid) << "), edit = (" << path.edit[0] << ',' << path.edit[1] << ',' << path.edit[2] << ')';
}
template <class T>
class HbrFVarEdit : public HbrHierarchicalEdit<T> {
public:
HbrFVarEdit(int _faceid, int _nsubfaces, unsigned char *_subfaces, unsigned char _vertexid, int _index, int _width, int _offset, typename HbrHierarchicalEdit<T>::Operation _op, float *_edit)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces), vertexid(_vertexid), index(_index), width(_width), offset(_offset), op(_op) {
edit = new float[width];
memcpy(edit, _edit, width * sizeof(float));
}
HbrFVarEdit(int _faceid, int _nsubfaces, int *_subfaces, int _vertexid, int _index, int _width, int _offset, typename HbrHierarchicalEdit<T>::Operation _op, float *_edit)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces), vertexid(_vertexid), index(_index), width(_width), offset(_offset), op(_op) {
edit = new float[width];
memcpy(edit, _edit, width * sizeof(float));
}
virtual ~HbrFVarEdit() {
delete[] edit;
}
// Return the vertex id (the last element in the path)
unsigned char GetVertexID() const { return vertexid; }
friend std::ostream& operator<< <T> (std::ostream& out, const HbrFVarEdit<T>& path);
// Return index into the facevarying data
int GetIndex() const { return index; }
// Return width of the data
int GetWidth() const { return width; }
// Return offset of the data
int GetOffset() const { return offset; }
// Get the numerical value of the edit
const float* GetEdit() const { return edit; }
// Get the type of operation
typename HbrHierarchicalEdit<T>::Operation GetOperation() const { return op; }
virtual void ApplyEditToFace(HbrFace<T>* face) {
if (HbrHierarchicalEdit<T>::GetNSubfaces() == face->GetDepth()) {
// The edit will modify the data and almost certainly
// create a discontinuity, so allocate storage for a new
// copy of the existing data specific to the face (or use
// one that already exists) and modify that
HbrFVarData<T> &fvt = face->GetVertex(vertexid)->GetFVarData(face);
if (fvt.GetFaceID() != face->GetID()) {
// This is the generic fvt, allocate a new copy and edit it
HbrFVarData<T> &newfvt = face->GetVertex(vertexid)->NewFVarData(face);
newfvt.SetAllData(face->GetMesh()->GetTotalFVarWidth(), fvt.GetData(0));
newfvt.ApplyFVarEdit(*const_cast<const HbrFVarEdit<T>*>(this));
} else {
fvt.ApplyFVarEdit(*const_cast<const HbrFVarEdit<T>*>(this));
}
}
}
private:
const unsigned char vertexid;
const int index;
const int width;
const int offset;
float* edit;
typename HbrHierarchicalEdit<T>::Operation op;
};
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_HBRFVAREDIT_H */
+740
View File
@@ -0,0 +1,740 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_HBRHALFEDGE_H
#define OPENSUBDIV3_HBRHALFEDGE_H
#include <assert.h>
#include <stddef.h>
#include <cstring>
#include <iostream>
#ifdef HBRSTITCH
#include "libgprims/stitch.h"
#include "libgprims/stitchInternal.h"
#endif
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
template <class T> class HbrFace;
template <class T> class HbrHalfedge;
template <class T> class HbrVertex;
template <class T> class HbrMesh;
template <class T> std::ostream& operator<<(std::ostream& out, const HbrHalfedge<T>& edge);
template <class T> class HbrHalfedge {
private:
HbrHalfedge(): opposite(0), incidentVertex(-1), vchild(-1), sharpness(0.0f)
#ifdef HBRSTITCH
, stitchccw(1), raystitchccw(1)
#endif
, coarse(1)
{
}
HbrHalfedge(const HbrHalfedge &/* edge */) {}
~HbrHalfedge();
void Clear();
// Finish the initialization of the halfedge. Should only be
// called by HbrFace
void Initialize(HbrHalfedge<T>* opposite, int index, HbrVertex<T>* origin, unsigned int *fvarbits, HbrFace<T>* face);
public:
// Returns the opposite half edge
HbrHalfedge<T>* GetOpposite() const { return opposite; }
// Sets the opposite half edge
void SetOpposite(HbrHalfedge<T>* opposite) { this->opposite = opposite; sharpness = opposite->sharpness; }
// Returns the next clockwise halfedge around the incident face
HbrHalfedge<T>* GetNext() const {
if (m_index == 4) {
const size_t edgesize = sizeof(HbrHalfedge<T>) + sizeof(HbrFace<T>*);
if (lastedge) {
return (HbrHalfedge<T>*) ((char*) this - (GetFace()->GetNumVertices() - 1) * edgesize);
} else {
return (HbrHalfedge<T>*) ((char*) this + edgesize);
}
} else {
if (lastedge) {
return (HbrHalfedge<T>*) ((char*) this - (m_index) * sizeof(HbrHalfedge<T>));
} else {
return (HbrHalfedge<T>*) ((char*) this + sizeof(HbrHalfedge<T>));
}
}
}
// Returns the previous counterclockwise halfedge around the incident face
HbrHalfedge<T>* GetPrev() const {
const size_t edgesize = (m_index == 4) ?
(sizeof(HbrHalfedge<T>) + sizeof(HbrFace<T>*)) :
sizeof(HbrHalfedge<T>);
if (firstedge) {
return (HbrHalfedge<T>*) ((char*) this + (GetFace()->GetNumVertices() - 1) * edgesize);
} else {
return (HbrHalfedge<T>*) ((char*) this - edgesize);
}
}
// Returns the incident vertex
HbrVertex<T>* GetVertex() const {
return GetMesh()->GetVertex(incidentVertex);
}
// Returns the incident vertex
HbrVertex<T>* GetVertex(HbrMesh<T> *mesh) const {
return mesh->GetVertex(incidentVertex);
}
// Returns the incident vertex
int GetVertexID() const {
return incidentVertex;
}
// Returns the source vertex
HbrVertex<T>* GetOrgVertex() const {
return GetVertex();
}
// Returns the source vertex
HbrVertex<T>* GetOrgVertex(HbrMesh<T> *mesh) const {
return GetVertex(mesh);
}
// Returns the source vertex id
int GetOrgVertexID() const {
return incidentVertex;
}
// Changes the origin vertex. Generally not a good idea to do
void SetOrgVertex(HbrVertex<T>* v) { incidentVertex = v->GetID(); }
// Returns the destination vertex
HbrVertex<T>* GetDestVertex() const { return GetNext()->GetOrgVertex(); }
// Returns the destination vertex
HbrVertex<T>* GetDestVertex(HbrMesh<T> *mesh) const { return GetNext()->GetOrgVertex(mesh); }
// Returns the destination vertex ID
int GetDestVertexID() const { return GetNext()->GetOrgVertexID(); }
// Returns the incident facet
HbrFace<T>* GetFace() const {
if (m_index == 4) {
// Pointer to face is stored after the data for the edge
return *(HbrFace<T>**)((char *) this + sizeof(HbrHalfedge<T>));
} else {
return (HbrFace<T>*) ((char*) this - (m_index) * sizeof(HbrHalfedge<T>) -
offsetof(HbrFace<T>, edges));
}
}
// Returns the mesh to which this edge belongs
HbrMesh<T>* GetMesh() const { return GetFace()->GetMesh(); }
// Returns the face on the right
HbrFace<T>* GetRightFace() const { return opposite ? opposite->GetLeftFace() : NULL; }
// Return the face on the left of the halfedge
HbrFace<T>* GetLeftFace() const { return GetFace(); }
// Returns whether this is a boundary edge
bool IsBoundary() const { return opposite == 0; }
// Tag the edge as being an infinitely sharp facevarying edge
void SetFVarInfiniteSharp(int datum, bool infsharp) {
int intindex = datum >> 4;
unsigned int bits = infsharp << ((datum & 15) * 2);
getFVarInfSharp()[intindex] |= bits;
if (opposite) {
opposite->getFVarInfSharp()[intindex] |= bits;
}
}
// Copy fvar infinite sharpness flags from another edge
void CopyFVarInfiniteSharpness(HbrHalfedge<T>* edge) {
unsigned int *fvarinfsharp = getFVarInfSharp();
if (fvarinfsharp) {
const int fvarcount = GetMesh()->GetFVarCount();
int fvarbitsSizePerEdge = ((fvarcount + 15) / 16);
if (edge->IsSharp(true)) {
memset(fvarinfsharp, 0x55555555, fvarbitsSizePerEdge * sizeof(unsigned int));
} else {
memcpy(fvarinfsharp, edge->getFVarInfSharp(), fvarbitsSizePerEdge * sizeof(unsigned int));
}
}
}
// Returns whether the edge is infinitely sharp in facevarying for
// a particular facevarying datum
bool GetFVarInfiniteSharp(int datum);
// Returns whether the edge is infinitely sharp in any facevarying
// datum
bool IsFVarInfiniteSharpAnywhere();
// Get the sharpness relative to facevarying data
float GetFVarSharpness(int datum, bool ignoreGeometry=false);
// Returns the (raw) sharpness of the edge
float GetSharpness() const { return sharpness; }
// Sets the sharpness of the edge
void SetSharpness(float sharp) { sharpness = sharp; if (opposite) opposite->sharpness = sharp; ClearMask(); }
// Returns whether the edge is sharp at the current level of
// subdivision (next = false) or at the next level of subdivision
// (next = true).
bool IsSharp(bool next) const { return (next ? (sharpness > 0.0f) : (sharpness >= 1.0f)); }
// Clears the masks of the adjacent edge vertices. Usually called
// when a change in edge sharpness occurs.
void ClearMask() { GetOrgVertex()->ClearMask(); GetDestVertex()->ClearMask(); }
// Subdivide the edge into a vertex if needed and return
HbrVertex<T>* Subdivide();
// Make sure the edge has its opposite face
void GuaranteeNeighbor();
// True if the edge has a subdivided child vertex
bool HasChild() const { return vchild!=-1; }
// Remove the reference to subdivided vertex
void RemoveChild() { vchild = -1; }
// Sharpness constants
enum Mask {
k_Smooth = 0,
k_Sharp = 1,
k_InfinitelySharp = 10
};
#ifdef HBRSTITCH
StitchEdge* GetStitchEdge(int i) {
StitchEdge **stitchEdge = getStitchEdges();
// If the stitch edge exists, the ownership is transferred to
// the caller. Make sure the opposite edge loses ownership as
// well.
if (stitchEdge[i]) {
if (opposite) {
opposite->getStitchEdges()[i] = 0;
}
return StitchGetEdge(&stitchEdge[i]);
}
// If the stitch edge does not exist then we create one now.
// Make sure the opposite edge gets a copy of it too
else {
StitchGetEdge(&stitchEdge[i]);
if (opposite) {
opposite->getStitchEdges()[i] = stitchEdge[i];
}
return stitchEdge[i];
}
}
// If stitch edge exists, and this edge has no opposite, destroy
// it
void DestroyStitchEdges(int stitchcount) {
if (!opposite) {
StitchEdge **stitchEdge = getStitchEdges();
for (int i = 0; i < stitchcount; ++i) {
if (stitchEdge[i]) {
StitchFreeEdge(stitchEdge[i]);
stitchEdge[i] = 0;
}
}
}
}
StitchEdge* GetRayStitchEdge(int i) {
return GetStitchEdge(i + 2);
}
// Splits our split edge between our children. We'd better have
// subdivided this edge by this point
void SplitStitchEdge(int i) {
StitchEdge* se = GetStitchEdge(i);
HbrHalfedge<T>* ea = GetOrgVertex()->Subdivide()->GetEdge(Subdivide());
HbrHalfedge<T>* eb = Subdivide()->GetEdge(GetDestVertex()->Subdivide());
StitchEdge **ease = ea->getStitchEdges();
StitchEdge **ebse = eb->getStitchEdges();
if (i >= 2) { // ray tracing stitches
if (!raystitchccw) {
StitchSplitEdge(se, &ease[i], &ebse[i], false, 0, 0, 0);
} else {
StitchSplitEdge(se, &ebse[i], &ease[i], true, 0, 0, 0);
}
ea->raystitchccw = eb->raystitchccw = raystitchccw;
if (eb->opposite) {
eb->opposite->getStitchEdges()[i] = ebse[i];
eb->opposite->raystitchccw = raystitchccw;
}
if (ea->opposite) {
ea->opposite->getStitchEdges()[i] = ease[i];
ea->opposite->raystitchccw = raystitchccw;
}
} else {
if (!stitchccw) {
StitchSplitEdge(se, &ease[i], &ebse[i], false, 0, 0, 0);
} else {
StitchSplitEdge(se, &ebse[i], &ease[i], true, 0, 0, 0);
}
ea->stitchccw = eb->stitchccw = stitchccw;
if (eb->opposite) {
eb->opposite->getStitchEdges()[i] = ebse[i];
eb->opposite->stitchccw = stitchccw;
}
if (ea->opposite) {
ea->opposite->getStitchEdges()[i] = ease[i];
ea->opposite->stitchccw = stitchccw;
}
}
}
void SplitRayStitchEdge(int i) {
SplitStitchEdge(i + 2);
}
void SetStitchEdge(int i, StitchEdge* edge) {
StitchEdge **stitchEdges = getStitchEdges();
stitchEdges[i] = edge;
if (opposite) {
opposite->getStitchEdges()[i] = edge;
}
}
void SetRayStitchEdge(int i, StitchEdge* edge) {
StitchEdge **stitchEdges = getStitchEdges();
stitchEdges[i+2] = edge;
if (opposite) {
opposite->getStitchEdges()[i+2] = edge;
}
}
void* GetStitchData() const {
if (stitchdatavalid) return GetMesh()->GetStitchData(this);
else return 0;
}
void SetStitchData(void* data) {
GetMesh()->SetStitchData(this, data);
stitchdatavalid = data ? 1 : 0;
if (opposite) {
opposite->GetMesh()->SetStitchData(opposite, data);
opposite->stitchdatavalid = stitchdatavalid;
}
}
bool GetStitchCCW(bool raytraced) const { return raytraced ? raystitchccw : stitchccw; }
void ClearStitchCCW(bool raytraced) {
if (raytraced) {
raystitchccw = 0;
if (opposite) opposite->raystitchccw = 0;
} else {
stitchccw = 0;
if (opposite) opposite->stitchccw = 0;
}
}
void ToggleStitchCCW(bool raytraced) {
if (raytraced) {
raystitchccw = 1 - raystitchccw;
if (opposite) opposite->raystitchccw = raystitchccw;
} else {
stitchccw = 1 - stitchccw;
if (opposite) opposite->stitchccw = stitchccw;
}
}
#endif
// Marks the edge as being "coarse" (belonging to the control
// mesh). Generally this distinction only needs to be made if
// we're worried about interpolateboundary behaviour
void SetCoarse(bool c) { coarse = c; }
bool IsCoarse() const { return coarse; }
friend class HbrFace<T>;
private:
HbrHalfedge<T>* opposite;
// Index of incident vertex
int incidentVertex;
// Index of subdivided vertex child
int vchild;
float sharpness;
#ifdef HBRSTITCH
unsigned short stitchccw:1;
unsigned short raystitchccw:1;
unsigned short stitchdatavalid:1;
#endif
unsigned short coarse:1;
unsigned short lastedge:1;
unsigned short firstedge:1;
// If m_index = 0, 1, 2 or 3: we are the m_index edge of an
// incident face with 3 or 4 vertices.
// If m_index = 4: our incident face has more than 4 vertices, and
// we must do some extra math to determine what our actual index
// is. See getIndex()
unsigned short m_index:3;
// Returns the index of the edge relative to its incident face.
// This relies on knowledge of the face's edge allocation pattern
int getIndex() const {
if (m_index < 4) {
return m_index;
} else {
// We allocate room for up to 4 values (to handle tri or
// quad) in the edges array. If there are more than that,
// they _all_ go in the faces' extraedges array.
HbrFace<T>* incidentFace = *(HbrFace<T>**)((char *) this + sizeof(HbrHalfedge<T>));
return int(((char *) this - incidentFace->extraedges) /
(sizeof(HbrHalfedge<T>) + sizeof(HbrFace<T>*)));
}
}
// Returns bitmask indicating whether a given facevarying datum
// for the edge is infinitely sharp. Each datum has two bits, and
// if those two bits are set to 3, it means the status has not
// been computed yet.
unsigned int *getFVarInfSharp() {
unsigned int *fvarbits = GetFace()->fvarbits;
if (fvarbits) {
int fvarbitsSizePerEdge = ((GetMesh()->GetFVarCount() + 15) / 16);
return fvarbits + getIndex() * fvarbitsSizePerEdge;
} else {
return 0;
}
}
#ifdef HBRSTITCH
StitchEdge **getStitchEdges() {
return GetFace()->stitchEdges + GetMesh()->GetStitchCount() * getIndex();
}
#endif
#ifdef HBR_ADAPTIVE
public:
struct adaptiveFlags {
unsigned isTransition:1;
unsigned isTriangleHead:1;
unsigned isWatertightCritical:1;
adaptiveFlags() : isTransition(0),isTriangleHead(0),isWatertightCritical(0) { }
};
adaptiveFlags _adaptiveFlags;
bool IsInsideHole() const {
HbrFace<T> * left = GetLeftFace();
if (left and (not left->IsHole()))
return false;
HbrFace<T> * right = GetRightFace();
if (right and (not right->IsHole()))
return false;
return true;
}
bool IsTransition() const { return _adaptiveFlags.isTransition; }
bool IsTriangleHead() const { return _adaptiveFlags.isTriangleHead; }
bool IsWatertightCritical() const { return _adaptiveFlags.isWatertightCritical; }
#endif
};
template <class T>
void
HbrHalfedge<T>::Initialize(HbrHalfedge<T>* opposite, int index, HbrVertex<T>* origin,
unsigned int *fvarbits, HbrFace<T>* face) {
HbrMesh<T> *mesh = face->GetMesh();
if (face->GetNumVertices() <= 4) {
m_index = index;
} else {
m_index = 4;
// Assumes upstream allocation ensured we have extra storage
// for pointer to face after the halfedge data structure
// itself
*(HbrFace<T>**)((char *) this + sizeof(HbrHalfedge<T>)) = face;
}
this->opposite = opposite;
incidentVertex = origin->GetID();
lastedge = (index == face->GetNumVertices() - 1);
firstedge = (index == 0);
if (opposite) {
sharpness = opposite->sharpness;
#ifdef HBRSTITCH
StitchEdge **stitchEdges = face->stitchEdges +
mesh->GetStitchCount() * index;
for (int i = 0; i < mesh->GetStitchCount(); ++i) {
stitchEdges[i] = opposite->getStitchEdges()[i];
}
stitchccw = opposite->stitchccw;
raystitchccw = opposite->raystitchccw;
stitchdatavalid = 0;
if (stitchEdges && opposite->GetStitchData()) {
mesh->SetStitchData(this, opposite->GetStitchData());
stitchdatavalid = 1;
}
#endif
if (fvarbits) {
const int fvarcount = mesh->GetFVarCount();
int fvarbitsSizePerEdge = ((fvarcount + 15) / 16);
memcpy(fvarbits, opposite->getFVarInfSharp(), fvarbitsSizePerEdge * sizeof(unsigned int));
}
} else {
sharpness = 0.0f;
#ifdef HBRSTITCH
StitchEdge **stitchEdges = getStitchEdges();
for (int i = 0; i < mesh->GetStitchCount(); ++i) {
stitchEdges[i] = 0;
}
stitchccw = 1;
raystitchccw = 1;
stitchdatavalid = 0;
#endif
if (fvarbits) {
const int fvarcount = mesh->GetFVarCount();
int fvarbitsSizePerEdge = ((fvarcount + 15) / 16);
memset(fvarbits, 0xff, fvarbitsSizePerEdge * sizeof(unsigned int));
}
}
}
template <class T>
HbrHalfedge<T>::~HbrHalfedge() {
Clear();
}
template <class T>
void
HbrHalfedge<T>::Clear() {
if (opposite) {
opposite->opposite = 0;
if (vchild != -1) {
// Transfer ownership of the vchild to the opposite ptr
opposite->vchild = vchild;
HbrVertex<T> *vchildVert = GetMesh()->GetVertex(vchild);
// Done this way just for assertion sanity
vchildVert->SetParent(static_cast<HbrHalfedge*>(0));
vchildVert->SetParent(opposite);
vchild = -1;
}
opposite = 0;
}
// Orphan the child vertex
else if (vchild != -1) {
HbrVertex<T> *vchildVert = GetMesh()->GetVertex(vchild);
vchildVert->SetParent(static_cast<HbrHalfedge*>(0));
vchild = -1;
}
}
template <class T>
HbrVertex<T>*
HbrHalfedge<T>::Subdivide() {
HbrMesh<T>* mesh = GetMesh();
if (vchild != -1) return mesh->GetVertex(vchild);
// Make sure that our opposite doesn't "own" a subdivided vertex
// already. If it does, use that
if (opposite && opposite->vchild != -1) return mesh->GetVertex(opposite->vchild);
HbrVertex<T>* vchildVert = mesh->GetSubdivision()->Subdivide(mesh, this);
vchild = vchildVert->GetID();
vchildVert->SetParent(this);
return vchildVert;
}
template <class T>
void
HbrHalfedge<T>::GuaranteeNeighbor() {
HbrMesh<T>* mesh = GetMesh();
mesh->GetSubdivision()->GuaranteeNeighbor(mesh, this);
}
// Determines whether an edge is infinitely sharp as far as its
// facevarying data is concerned. Happens if the faces on both sides
// disagree on the facevarying data at either of the shared vertices
// on the edge.
template <class T>
bool
HbrHalfedge<T>::GetFVarInfiniteSharp(int datum) {
// Check to see if already initialized
int intindex = datum >> 4;
int shift = (datum & 15) << 1;
unsigned int *fvarinfsharp = getFVarInfSharp();
unsigned int bits = (fvarinfsharp[intindex] >> shift) & 0x3;
if (bits != 3) {
assert (bits != 2);
return bits ? true : false;
}
// If there is no face varying data it can't be infinitely sharp!
const int fvarwidth = GetMesh()->GetTotalFVarWidth();
if (!fvarwidth) {
bits = ~(0x3 << shift);
fvarinfsharp[intindex] &= bits;
if (opposite) opposite->getFVarInfSharp()[intindex] &= bits;
return false;
}
// If either incident face is missing, it's a geometric boundary
// edge, and also a facevarying boundary edge
HbrFace<T>* left = GetLeftFace(), *right = GetRightFace();
if (!left || !right) {
bits = ~(0x2 << shift);
fvarinfsharp[intindex] &= bits;
if (opposite) opposite->getFVarInfSharp()[intindex] &= bits;
return true;
}
// Look for the indices on each face which correspond to the
// origin and destination vertices of the edge
int lorg = -1, ldst = -1, rorg = -1, rdst = -1, i, nv;
HbrHalfedge<T>* e;
e = left->GetFirstEdge();
nv = left->GetNumVertices();
for (i = 0; i < nv; ++i) {
if (e->GetOrgVertex() == GetOrgVertex()) lorg = i;
if (e->GetOrgVertex() == GetDestVertex()) ldst = i;
e = e->GetNext();
}
e = right->GetFirstEdge();
nv = right->GetNumVertices();
for (i = 0; i < nv; ++i) {
if (e->GetOrgVertex() == GetOrgVertex()) rorg = i;
if (e->GetOrgVertex() == GetDestVertex()) rdst = i;
e = e->GetNext();
}
assert(lorg >= 0 && ldst >= 0 && rorg >= 0 && rdst >= 0);
// Compare the facevarying data to some tolerance
const int startindex = GetMesh()->GetFVarIndices()[datum];
const int width = GetMesh()->GetFVarWidths()[datum];
if (!right->GetFVarData(rorg).Compare(left->GetFVarData(lorg), startindex, width, 0.001f) ||
!right->GetFVarData(rdst).Compare(left->GetFVarData(ldst), startindex, width, 0.001f)) {
bits = ~(0x2 << shift);
fvarinfsharp[intindex] &= bits;
if (opposite) opposite->getFVarInfSharp()[intindex] &= bits;
return true;
}
bits = ~(0x3 << shift);
fvarinfsharp[intindex] &= bits;
if (opposite) opposite->getFVarInfSharp()[intindex] &= bits;
return false;
}
template <class T>
bool
HbrHalfedge<T>::IsFVarInfiniteSharpAnywhere() {
if (sharpness > k_Smooth) {
return true;
}
for (int i = 0; i < GetMesh()->GetFVarCount(); ++i) {
if (GetFVarInfiniteSharp(i)) return true;
}
return false;
}
template <class T>
float
HbrHalfedge<T>::GetFVarSharpness(int datum, bool ignoreGeometry) {
if (GetFVarInfiniteSharp(datum)) return k_InfinitelySharp;
if (!ignoreGeometry) {
// If it's a geometrically sharp edge it's going to be a
// facevarying sharp edge too
if (sharpness > k_Smooth) {
SetFVarInfiniteSharp(datum, true);
return k_InfinitelySharp;
}
}
return k_Smooth;
}
template <class T>
std::ostream&
operator<<(std::ostream& out, const HbrHalfedge<T>& edge) {
if (edge.IsBoundary()) out << "boundary ";
out << "edge connecting ";
if (edge.GetOrgVertex())
out << *edge.GetOrgVertex();
else
out << "(none)";
out << " to ";
if (edge.GetDestVertex()) {
out << *edge.GetDestVertex();
} else {
out << "(none)";
}
return out;
}
// Sorts half edges by the relative ordering of the incident faces'
// paths.
template <class T>
class HbrHalfedgeCompare {
public:
bool operator() (const HbrHalfedge<T>* a, HbrHalfedge<T>* b) const {
return (a->GetFace()->GetPath() < b->GetFace()->GetPath());
}
};
template <class T>
class HbrHalfedgeOperator {
public:
virtual void operator() (HbrHalfedge<T> &edge) = 0;
virtual ~HbrHalfedgeOperator() {}
};
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_HBRHALFEDGE_H */
+171
View File
@@ -0,0 +1,171 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_HBRHIERARCHICALEDIT_H
#define OPENSUBDIV3_HBRHIERARCHICALEDIT_H
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
template <class T> class HbrHierarchicalEdit;
template <class T> class HbrFace;
template <class T> class HbrVertex;
template <class T>
class HbrHierarchicalEdit {
public:
typedef enum Operation {
Set,
Add,
Subtract
} Operation;
protected:
HbrHierarchicalEdit(int _faceid, int _nsubfaces, unsigned char *_subfaces)
: faceid(_faceid), nsubfaces(_nsubfaces) {
subfaces = new unsigned char[_nsubfaces];
for (int i = 0; i < nsubfaces; ++i) {
subfaces[i] = _subfaces[i];
}
}
HbrHierarchicalEdit(int _faceid, int _nsubfaces, int *_subfaces)
: faceid(_faceid), nsubfaces(_nsubfaces) {
subfaces = new unsigned char[_nsubfaces];
for (int i = 0; i < nsubfaces; ++i) {
subfaces[i] = static_cast<unsigned char>(_subfaces[i]);
}
}
public:
virtual ~HbrHierarchicalEdit() {
delete[] subfaces;
}
bool operator<(const HbrHierarchicalEdit& p) const {
if (faceid < p.faceid) return true;
if (faceid > p.faceid) return false;
int minlength = nsubfaces;
if (minlength > p.nsubfaces) minlength = p.nsubfaces;
for (int i = 0; i < minlength; ++i) {
if (subfaces[i] < p.subfaces[i]) return true;
if (subfaces[i] > p.subfaces[i]) return false;
}
return (nsubfaces < p.nsubfaces);
}
// Return the face id (the first element in the path)
int GetFaceID() const { return faceid; }
// Return the number of subfaces in the path
int GetNSubfaces() const { return nsubfaces; }
// Return a subface element in the path
unsigned char GetSubface(int index) const { return subfaces[index]; }
// Determines whether this hierarchical edit is relevant to the
// face in question
bool IsRelevantToFace(HbrFace<T>* face) const;
// Applys edit to face. All subclasses may override this method
virtual void ApplyEditToFace(HbrFace<T>* /* face */) {}
// Applys edit to vertex. Subclasses may override this method.
virtual void ApplyEditToVertex(HbrFace<T>* /* face */, HbrVertex<T>* /* vertex */) {}
#ifdef PRMAN
// Gets the effect of this hierarchical edit on the bounding box.
// Subclasses may override this method
virtual void ApplyToBound(struct bbox& /* box */, RtMatrix * /* mx */) const {}
#endif
protected:
// ID of the top most face in the mesh which begins the path
const int faceid;
// Number of subfaces
const int nsubfaces;
// IDs of the subfaces
unsigned char *subfaces;
};
template <class T>
class HbrHierarchicalEditComparator {
public:
bool operator() (const HbrHierarchicalEdit<T>* path1, const HbrHierarchicalEdit<T>* path2) const {
return (*path1 < *path2);
}
};
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#include "../hbr/face.h"
#include <cstring>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
template <class T>
bool
HbrHierarchicalEdit<T>::IsRelevantToFace(HbrFace<T>* face) const {
// Key assumption: the face's first vertex edit is relevant to
// that face. We will then compare ourselves to that edit and if
// the first part of our subpath is identical to the entirety of
// that subpath, this edit is relevant.
// Calling code is responsible for making sure we don't
// dereference a null pointer here
HbrHierarchicalEdit<T>* p = *face->GetHierarchicalEdits();
if (!p) return false;
if (this == p) return true;
if (faceid != p->faceid) return false;
// If our path length is less than the face depth, it should mean
// that we're dealing with another face somewhere up the path, so
// we're not relevant
if (nsubfaces < face->GetDepth()) return false;
if (memcmp(subfaces, p->subfaces, face->GetDepth() * sizeof(unsigned char)) != 0) {
return false;
}
return true;
}
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_HBRHIERARCHICALEDIT_H */
+74
View File
@@ -0,0 +1,74 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_HBRHOLEEDIT_H
#define OPENSUBDIV3_HBRHOLEEDIT_H
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
template <class T> class HbrHoleEdit;
template <class T>
std::ostream& operator<<(std::ostream& out, const HbrHoleEdit<T>& path) {
out << "edge path = (" << path.faceid << ' ';
for (int i = 0; i < path.nsubfaces; ++i) {
out << static_cast<int>(path.subfaces[i]) << ' ';
}
return out << ")";
}
template <class T>
class HbrHoleEdit : public HbrHierarchicalEdit<T> {
public:
HbrHoleEdit(int _faceid, int _nsubfaces, unsigned char *_subfaces)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces) {
}
HbrHoleEdit(int _faceid, int _nsubfaces, int *_subfaces)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces) {
}
virtual ~HbrHoleEdit() {}
friend std::ostream& operator<< <T> (std::ostream& out, const HbrHoleEdit<T>& path);
virtual void ApplyEditToFace(HbrFace<T>* face) {
if (HbrHierarchicalEdit<T>::GetNSubfaces() == face->GetDepth()) {
face->SetHole();
}
}
};
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_HBRHOLEEDIT_H */
+979
View File
@@ -0,0 +1,979 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_HBRLOOP_H
#define OPENSUBDIV3_HBRLOOP_H
#include <cmath>
#include <assert.h>
#include <algorithm>
#include "../hbr/subdivision.h"
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
/* #define HBR_DEBUG */
template <class T>
class HbrLoopSubdivision : public HbrSubdivision<T>{
public:
HbrLoopSubdivision<T>()
: HbrSubdivision<T>() {}
virtual HbrSubdivision<T>* Clone() const {
return new HbrLoopSubdivision<T>();
}
virtual void Refine(HbrMesh<T>* mesh, HbrFace<T>* face);
virtual HbrFace<T>* RefineFaceAtVertex(HbrMesh<T>* mesh, HbrFace<T>* face, HbrVertex<T>* vertex);
virtual void GuaranteeNeighbor(HbrMesh<T>* mesh, HbrHalfedge<T>* edge);
virtual void GuaranteeNeighbors(HbrMesh<T>* mesh, HbrVertex<T>* vertex);
virtual bool HasLimit(HbrMesh<T>* mesh, HbrFace<T>* face);
virtual bool HasLimit(HbrMesh<T>* mesh, HbrHalfedge<T>* edge);
virtual bool HasLimit(HbrMesh<T>* mesh, HbrVertex<T>* vertex);
virtual HbrVertex<T>* Subdivide(HbrMesh<T>* mesh, HbrFace<T>* face);
virtual HbrVertex<T>* Subdivide(HbrMesh<T>* mesh, HbrHalfedge<T>* edge);
virtual HbrVertex<T>* Subdivide(HbrMesh<T>* mesh, HbrVertex<T>* vertex);
virtual bool VertexIsExtraordinary(HbrMesh<T> const * /* mesh */, HbrVertex<T>* vertex) { return vertex->GetValence() != 6; }
virtual bool FaceIsExtraordinary(HbrMesh<T> const * /* mesh */, HbrFace<T>* face) { return face->GetNumVertices() != 3; }
virtual int GetFaceChildrenCount(int /* nvertices */) const { return 4; }
private:
// Transfers facevarying data from a parent face to a child face
void transferFVarToChild(HbrMesh<T>* mesh, HbrFace<T>* face, HbrFace<T>* child, int index);
// Transfers vertex and edge edits from a parent face to a child face
void transferEditsToChild(HbrFace<T>* face, HbrFace<T>* child, int index);
// Generates the fourth child of a triangle: the triangle in the
// middle whose vertices have parents which are all edges
void refineFaceAtMiddle(HbrMesh<T>* mesh, HbrFace<T>* face);
};
template <class T>
void
HbrLoopSubdivision<T>::transferFVarToChild(HbrMesh<T>* mesh, HbrFace<T>* face, HbrFace<T>* child, int index) {
typename HbrMesh<T>::InterpolateBoundaryMethod fvarinterp = mesh->GetFVarInterpolateBoundaryMethod();
HbrVertex<T>* childVertex;
// In the case of index == 3, this is the middle face, and so
// we need to do three edge subdivision rules
if (index == 3) {
const int fvarcount = mesh->GetFVarCount();
for (int i = 0; i < 3; ++i) {
HbrHalfedge<T> *edge = face->GetEdge(i);
GuaranteeNeighbor(mesh, edge);
childVertex = child->GetVertex((i + 2) % 3);
bool fvIsSmooth = !edge->IsFVarInfiniteSharpAnywhere();
if (!fvIsSmooth) {
childVertex->NewFVarData(child);
}
HbrFVarData<T>& fv = childVertex->GetFVarData(child);
int fvarindex = 0;
for (int fvaritem = 0; fvaritem < fvarcount; ++fvaritem) {
const int fvarwidth = mesh->GetFVarWidths()[fvaritem];
if (fvarinterp == HbrMesh<T>::k_InterpolateBoundaryNone ||
face->GetEdge(i)->GetFVarSharpness(fvaritem) || face->GetEdge(i)->IsBoundary()) {
// Sharp edge rule
fv.SetWithWeight(face->GetFVarData(i), fvarindex, fvarwidth, 0.5f);
fv.AddWithWeight(face->GetFVarData((i + 1) % 3), fvarindex, fvarwidth, 0.5f);
} else if (!fvIsSmooth || !fv.IsInitialized()) {
// Smooth edge subdivision. Add 0.375 of adjacent vertices
fv.SetWithWeight(face->GetFVarData(i), fvarindex, fvarwidth, 0.375f);
fv.AddWithWeight(face->GetFVarData((i + 1) % 3), fvarindex, fvarwidth, 0.375f);
// Add 0.125 of opposite vertices
fv.AddWithWeight(face->GetFVarData((i + 2) % 3), fvarindex, fvarwidth, 0.125f);
HbrFace<T>* oppFace = face->GetEdge(i)->GetRightFace();
for (int j = 0; j < oppFace->GetNumVertices(); ++j) {
if (oppFace->GetVertex(j) == face->GetVertex(i)) {
fv.AddWithWeight(oppFace->GetFVarData((j+1)%oppFace->GetNumVertices()), fvarindex, fvarwidth, 0.125f);
break;
}
}
}
fvarindex += fvarwidth;
}
fv.SetInitialized();
}
return;
}
HbrHalfedge<T>* edge;
HbrVertex<T>* v = face->GetVertex(index);
// Otherwise we proceed with one vertex and two edge subdivision
// applications. First the vertex subdivision rule. Analyze
// whether the vertex is on the boundary and whether it's an
// infinitely sharp corner. We determine the last by checking the
// propagate corners flag on the mesh; if it's off, we check the
// two edges of this face incident to that vertex and determining
// whether they are facevarying boundary edges - this is analogous
// to what goes on for the interpolateboundary tag (which when set
// to EDGEANDCORNER marks vertices with a valence of two as being
// sharp corners). If propagate corners is on, we check *all*
// faces to see if two edges side by side are facevarying boundary
// edges. The facevarying boundary check ignores geometric
// sharpness, otherwise we may swim at geometric creases which
// aren't actually discontinuous.
//
// We need to make sure that that each of the vertices of the
// child face have the appropriate facevarying storage as
// needed. If there are discontinuities in any facevarying datum,
// the vertex must allocate a new block of facevarying storage
// specific to the child face.
v->GuaranteeNeighbors();
bool fv0IsSmooth, fv1IsSmooth, fv2IsSmooth;
childVertex = child->GetVertex(index);
fv0IsSmooth = v->IsFVarAllSmooth();
if (!fv0IsSmooth) {
childVertex->NewFVarData(child);
}
HbrFVarData<T>& fv0 = childVertex->GetFVarData(child);
edge = face->GetEdge(index);
GuaranteeNeighbor(mesh, edge);
assert(edge->GetOrgVertex() == v);
childVertex = child->GetVertex((index + 1) % 3);
fv1IsSmooth = !edge->IsFVarInfiniteSharpAnywhere();
if (!fv1IsSmooth) {
childVertex->NewFVarData(child);
}
HbrFVarData<T>& fv1 = childVertex->GetFVarData(child);
edge = edge->GetPrev();
GuaranteeNeighbor(mesh, edge);
assert(edge == face->GetEdge((index + 2) % 3));
assert(edge->GetDestVertex() == v);
childVertex = child->GetVertex((index + 2) % 3);
fv2IsSmooth = !edge->IsFVarInfiniteSharpAnywhere();
if (!fv2IsSmooth) {
childVertex->NewFVarData(child);
}
HbrFVarData<T>& fv2 = childVertex->GetFVarData(child);
const int fvarcount = mesh->GetFVarCount();
int fvarindex = 0;
for (int fvaritem = 0; fvaritem < fvarcount; ++fvaritem) {
bool infcorner = false;
const int fvarwidth = mesh->GetFVarWidths()[fvaritem];
const char fvarmask = v->GetFVarMask(fvaritem);
if (fvarinterp == HbrMesh<T>::k_InterpolateBoundaryEdgeAndCorner) {
if (fvarmask >= HbrVertex<T>::k_Corner) {
infcorner = true;
} else if (mesh->GetFVarPropagateCorners()) {
if (v->IsFVarCorner(fvaritem)) {
infcorner = true;
}
} else {
if (face->GetEdge(index)->GetFVarSharpness(fvaritem, true) && face->GetEdge(index)->GetPrev()->GetFVarSharpness(fvaritem, true)) {
infcorner = true;
}
}
}
// Infinitely sharp vertex rule. Applied if the vertex is:
// - undergoing no facevarying boundary interpolation;
// - at a geometric crease, in either boundary interpolation case; or
// - is an infinitely sharp facevarying vertex, in the EDGEANDCORNER case; or
// - has a mask equal or greater than one, in the "always
// sharp" interpolate boundary case
if (fvarinterp == HbrMesh<T>::k_InterpolateBoundaryNone ||
(fvarinterp == HbrMesh<T>::k_InterpolateBoundaryAlwaysSharp &&
fvarmask >= 1) ||
v->GetSharpness() > HbrVertex<T>::k_Smooth ||
infcorner) {
fv0.SetWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 1.0f);
}
// Dart rule: unlike geometric creases, because there's two
// discontinuous values for the one incident edge, we use the
// boundary rule and not the smooth rule
else if (fvarmask == 1) {
// Use 0.75 of the current vert
fv0.SetWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 0.75f);
// 0.125 of "two adjacent edge vertices", which in actuality
// are the facevarying values of the same vertex but on each
// side of the single incident facevarying sharp edge
HbrHalfedge<T>* start = v->GetIncidentEdge(), *edge, *nextedge;
edge = start;
while (edge) {
if (edge->GetFVarSharpness(fvaritem)) {
break;
}
nextedge = v->GetNextEdge(edge);
if (nextedge == start) {
assert(0); // we should have found it by now
break;
} else if (!nextedge) {
// should never get into this case - if the vertex is
// on a boundary, it can never be a facevarying dart
// vertex
assert(0);
edge = edge->GetPrev();
break;
} else {
edge = nextedge;
}
}
HbrVertex<T>* w = edge->GetDestVertex();
HbrFace<T>* bestface = edge->GetLeftFace();
int j;
for (j = 0; j < bestface->GetNumVertices(); ++j) {
if (bestface->GetVertex(j) == w) break;
}
assert(j != bestface->GetNumVertices());
fv0.AddWithWeight(bestface->GetFVarData(j), fvarindex, fvarwidth, 0.125f);
bestface = edge->GetRightFace();
for (j = 0; j < bestface->GetNumVertices(); ++j) {
if (bestface->GetVertex(j) == w) break;
}
assert(j != bestface->GetNumVertices());
fv0.AddWithWeight(bestface->GetFVarData(j), fvarindex, fvarwidth, 0.125f);
}
// Boundary vertex rule (can use FVarSmooth, which is equivalent
// to checking that it's sharper than a dart)
else if (fvarmask != 0) {
// Use 0.75 of the current vert
fv0.SetWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 0.75f);
// Compute 0.125 of two adjacent edge vertices. However the
// two adjacent edge vertices we use must be part of the
// facevarying "boundary". To find the first edge we cycle
// counterclockwise around the current vertex v and look for
// the first boundary edge
HbrFace<T>* bestface = face;
HbrHalfedge<T>* bestedge = face->GetEdge(index)->GetPrev();
HbrHalfedge<T>* starte = bestedge->GetOpposite();
HbrVertex<T>* w = 0;
if (!starte) {
w = face->GetEdge(index)->GetPrev()->GetOrgVertex();
} else {
HbrHalfedge<T>* e = starte, *next;
assert(starte->GetOrgVertex() == v);
do {
if (e->GetFVarSharpness(fvaritem) || !e->GetLeftFace()) {
bestface = e->GetRightFace();
bestedge = e;
break;
}
next = v->GetNextEdge(e);
if (!next) {
bestface = e->GetLeftFace();
w = e->GetPrev()->GetOrgVertex();
break;
}
e = next;
} while (e && e != starte);
}
if (!w) w = bestedge->GetDestVertex();
int j;
for (j = 0; j < bestface->GetNumVertices(); ++j) {
if (bestface->GetVertex(j) == w) break;
}
assert(j != bestface->GetNumVertices());
fv0.AddWithWeight(bestface->GetFVarData(j), fvarindex, fvarwidth, 0.125f);
// Look for the other edge by cycling clockwise around v
bestface = face;
bestedge = face->GetEdge(index);
starte = bestedge;
w = 0;
if (HbrHalfedge<T>* e = starte) {
assert(starte->GetOrgVertex() == v);
do {
if (e->GetFVarSharpness(fvaritem) || !e->GetRightFace()) {
bestface = e->GetLeftFace();
bestedge = e;
break;
}
assert(e->GetOpposite());
e = v->GetPreviousEdge(e);
} while (e && e != starte);
}
if (!w) w = bestedge->GetDestVertex();
for (j = 0; j < bestface->GetNumVertices(); ++j) {
if (bestface->GetVertex(j) == w) break;
}
assert(j != bestface->GetNumVertices());
fv0.AddWithWeight(bestface->GetFVarData(j), fvarindex, fvarwidth, 0.125f);
}
// Smooth rule
else if (!fv0IsSmooth || !fv0.IsInitialized()) {
int valence = v->GetValence();
float invvalence = 1.0f / valence;
float beta = 0.25f * cosf((float)M_PI * 2.0f * invvalence) + 0.375f;
beta = beta * beta;
beta = (0.625f - beta) * invvalence;
// Use 1 - beta * valence of the current vertex value
fv0.SetWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 1 - (beta * valence));
// Add beta of surrounding vertices averages. We loop over all
// surrounding faces..
HbrHalfedge<T>* start = v->GetIncidentEdge(), *edge;
edge = start;
while (edge) {
HbrFace<T>* g = edge->GetLeftFace();
// .. and look for the edge on that face whose origin is
// the same as v, and add a contribution from its
// destination vertex value; this takes care of the
// surrounding edge vertex addition.
for (int j = 0; j < g->GetNumVertices(); ++j) {
if (g->GetEdge(j)->GetOrgVertex() == v) {
fv0.AddWithWeight(g->GetFVarData((j + 1) % g->GetNumVertices()), fvarindex, fvarwidth, beta);
break;
}
}
edge = v->GetNextEdge(edge);
if (edge == start) break;
}
}
// Edge subdivision rule
HbrHalfedge<T>* edge = face->GetEdge(index);
if (fvarinterp == HbrMesh<T>::k_InterpolateBoundaryNone ||
edge->GetFVarSharpness(fvaritem) || edge->IsBoundary()) {
// Sharp edge rule
fv1.SetWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 0.5f);
fv1.AddWithWeight(face->GetFVarData((index + 1) % 3), fvarindex, fvarwidth, 0.5f);
} else if (!fv1IsSmooth || !fv1.IsInitialized()) {
// Smooth edge subdivision. Add 0.375 of adjacent vertices
fv1.SetWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 0.375f);
fv1.AddWithWeight(face->GetFVarData((index + 1) % 3), fvarindex, fvarwidth, 0.375f);
// Add 0.125 of opposite vertices
fv1.AddWithWeight(face->GetFVarData((index + 2) % 3), fvarindex, fvarwidth, 0.125f);
HbrFace<T>* oppFace = edge->GetRightFace();
for (int j = 0; j < oppFace->GetNumVertices(); ++j) {
if (oppFace->GetVertex(j) == v) {
fv1.AddWithWeight(oppFace->GetFVarData((j+1)%oppFace->GetNumVertices()), fvarindex, fvarwidth, 0.125f);
break;
}
}
}
// Edge subdivision rule
edge = edge->GetPrev();
if (fvarinterp == HbrMesh<T>::k_InterpolateBoundaryNone ||
edge->GetFVarSharpness(fvaritem) || edge->IsBoundary()) {
// Sharp edge rule
fv2.SetWithWeight(face->GetFVarData((index + 2) % 3), fvarindex, fvarwidth, 0.5f);
fv2.AddWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 0.5f);
} else if (!fv2IsSmooth || !fv2.IsInitialized()) {
// Smooth edge subdivision. Add 0.375 of adjacent vertices
fv2.SetWithWeight(face->GetFVarData((index + 2) % 3), fvarindex, fvarwidth, 0.375f);
fv2.AddWithWeight(face->GetFVarData(index), fvarindex, fvarwidth, 0.375f);
// Add 0.125 of opposite vertices
fv2.AddWithWeight(face->GetFVarData((index + 1) % 3), fvarindex, fvarwidth, 0.125f);
HbrFace<T>* oppFace = edge->GetRightFace();
for (int j = 0; j < oppFace->GetNumVertices(); ++j) {
if (oppFace->GetVertex(j) == v) {
fv2.AddWithWeight(oppFace->GetFVarData((j+2)%oppFace->GetNumVertices()), fvarindex, fvarwidth, 0.125f);
break;
}
}
}
fvarindex += fvarwidth;
}
fv0.SetInitialized();
fv1.SetInitialized();
fv2.SetInitialized();
}
template <class T>
void
HbrLoopSubdivision<T>::transferEditsToChild(HbrFace<T>* face, HbrFace<T>* child, int index) {
// Hand down hole tag
child->SetHole(face->IsHole());
// Hand down pointers to hierarchical edits
if (HbrHierarchicalEdit<T>** edits = face->GetHierarchicalEdits()) {
while (HbrHierarchicalEdit<T>* edit = *edits) {
if (!edit->IsRelevantToFace(face)) break;
if (edit->GetNSubfaces() > face->GetDepth() &&
(edit->GetSubface(face->GetDepth()) == index)) {
child->SetHierarchicalEdits(edits);
break;
}
edits++;
}
}
}
template <class T>
void
HbrLoopSubdivision<T>::Refine(HbrMesh<T>* mesh, HbrFace<T>* face) {
#ifdef HBR_DEBUG
std::cerr << "\n\nRefining face " << *face << "\n";
#endif
assert(face->GetNumVertices() == 3); // or triangulate it?
HbrHalfedge<T>* edge = face->GetFirstEdge();
HbrHalfedge<T>* prevedge = edge->GetPrev();
for (int i = 0; i < 3; ++i) {
HbrVertex<T>* vertex = edge->GetOrgVertex();
if (!face->GetChild(i)) {
#ifdef HBR_DEBUG
std::cerr << "Kid " << i << "\n";
#endif
HbrFace<T>* child;
HbrVertex<T>* vertices[3];
vertices[i] = vertex->Subdivide();
vertices[(i + 1) % 3] = edge->Subdivide();
vertices[(i + 2) % 3] = prevedge->Subdivide();
child = mesh->NewFace(3, vertices, face, i);
#ifdef HBR_DEBUG
std::cerr << "Creating face " << *child << " during refine\n";
#endif
// Hand down edge sharpness
float sharpness;
HbrHalfedge<T>* childedge;
childedge = child->GetEdge(i);
if ((sharpness = edge->GetSharpness()) > HbrHalfedge<T>::k_Smooth) {
HbrSubdivision<T>::SubdivideCreaseWeight(
edge, edge->GetOrgVertex(), childedge);
}
childedge->CopyFVarInfiniteSharpness(edge);
childedge = child->GetEdge((i+2)%3);
if ((sharpness = prevedge->GetSharpness()) > HbrHalfedge<T>::k_Smooth) {
HbrSubdivision<T>::SubdivideCreaseWeight(
prevedge, prevedge->GetDestVertex(), childedge);
}
childedge->CopyFVarInfiniteSharpness(prevedge);
if (mesh->GetTotalFVarWidth()) {
transferFVarToChild(mesh, face, child, i);
}
transferEditsToChild(face, child, i);
}
prevedge = edge;
edge = edge->GetNext();
}
refineFaceAtMiddle(mesh, face);
}
template <class T>
HbrFace<T>*
HbrLoopSubdivision<T>::RefineFaceAtVertex(HbrMesh<T>* mesh, HbrFace<T>* face, HbrVertex<T>* vertex) {
#ifdef HBR_DEBUG
std::cerr << " forcing refine on " << *face << " at " << *vertex << '\n';
#endif
HbrHalfedge<T>* edge = face->GetFirstEdge();
HbrHalfedge<T>* prevedge = edge->GetPrev();
for (int i = 0; i < 3; ++i) {
if (edge->GetOrgVertex() == vertex) {
if (!face->GetChild(i)) {
#ifdef HBR_DEBUG
std::cerr << "Kid " << i << "\n";
#endif
HbrFace<T>* child;
HbrVertex<T>* vertices[3];
vertices[i] = vertex->Subdivide();
vertices[(i + 1) % 3] = edge->Subdivide();
vertices[(i + 2) % 3] = prevedge->Subdivide();
child = mesh->NewFace(3, vertices, face, i);
#ifdef HBR_DEBUG
std::cerr << "Creating face " << *child << " during refine\n";
#endif
// Hand down edge sharpness
float sharpness;
HbrHalfedge<T>* childedge;
childedge = child->GetEdge(i);
if ((sharpness = edge->GetSharpness()) > HbrHalfedge<T>::k_Smooth) {
HbrSubdivision<T>::SubdivideCreaseWeight(
edge, edge->GetOrgVertex(), childedge);
}
childedge->CopyFVarInfiniteSharpness(edge);
childedge = child->GetEdge((i+2)%3);
if ((sharpness = prevedge->GetSharpness()) > HbrHalfedge<T>::k_Smooth) {
HbrSubdivision<T>::SubdivideCreaseWeight(
prevedge, prevedge->GetDestVertex(), childedge);
}
childedge->CopyFVarInfiniteSharpness(prevedge);
if (mesh->GetTotalFVarWidth()) {
transferFVarToChild(mesh, face, child, i);
}
transferEditsToChild(face, child, i);
return child;
} else {
return face->GetChild(i);
}
}
prevedge = edge;
edge = edge->GetNext();
}
return 0;
}
template <class T>
void
HbrLoopSubdivision<T>::GuaranteeNeighbor(HbrMesh<T>* mesh, HbrHalfedge<T>* edge) {
if (edge->GetOpposite()) {
return;
}
#ifdef HBR_DEBUG
std::cerr << "\n\nneighbor guarantee at " << *edge << " invoked\n";
#endif
/*
Imagine the following:
X
/ \
/ \
/ \
X \
/\ \
2/ \3 \
/ \ \
X------X--------X
1
If the parent of _both_ incident vertices are themselves edges,
(like the edge marked 3 above), then this edge is in the center
of the parent face. Refining the parent face in the middle or
refining the parent face at one vertex (where the two parent
edges meet) should suffice
*/
HbrHalfedge<T>* parentEdge1 = edge->GetOrgVertex()->GetParentEdge();
HbrHalfedge<T>* parentEdge2 = edge->GetDestVertex()->GetParentEdge();
if (parentEdge1 && parentEdge2) {
#ifdef HBR_DEBUG
std::cerr << "two parent edge situation\n";
#endif
HbrFace<T>* parentFace = parentEdge1->GetFace();
assert(parentFace == parentEdge2->GetFace());
if(parentEdge1->GetOrgVertex() == parentEdge2->GetDestVertex()) {
refineFaceAtMiddle(mesh, parentFace);
} else {
RefineFaceAtVertex(mesh, parentFace, parentEdge1->GetOrgVertex());
}
assert(edge->GetOpposite());
return;
}
// Otherwise we're in the situation of edge 1 or edge 2 in the
// diagram above.
if (parentEdge1) {
#ifdef HBR_DEBUG
std::cerr << "parent edge 1 " << *parentEdge1 << "\n";
#endif
HbrVertex<T>* parentVertex2 = edge->GetDestVertex()->GetParentVertex();
assert(parentVertex2);
RefineFaceAtVertex(mesh, parentEdge1->GetLeftFace(), parentVertex2);
if (parentEdge1->GetRightFace()) {
RefineFaceAtVertex(mesh, parentEdge1->GetRightFace(), parentVertex2);
}
} else if (parentEdge2) {
#ifdef HBR_DEBUG
std::cerr << "parent edge 2 " << *parentEdge2 << "\n";
#endif
HbrVertex<T>* parentVertex1 = edge->GetOrgVertex()->GetParentVertex();
assert(parentVertex1);
RefineFaceAtVertex(mesh, parentEdge2->GetLeftFace(), parentVertex1);
if (parentEdge2->GetRightFace()) {
RefineFaceAtVertex(mesh, parentEdge2->GetRightFace(), parentVertex1);
}
}
}
template <class T>
void
HbrLoopSubdivision<T>::GuaranteeNeighbors(HbrMesh<T>* mesh, HbrVertex<T>* vertex) {
#ifdef HBR_DEBUG
std::cerr << "\n\nneighbor guarantee at " << *vertex << " invoked\n";
#endif
assert(vertex->GetParentFace() == 0);
// The first case: the vertex is a child of an edge. Make sure
// that the parent faces on either side of the parent edge exist,
// and have 1) refined at both vertices of the parent edge, and 2)
// have refined their "middle" face (which doesn't live at either
// vertex).
HbrHalfedge<T>* parentEdge = vertex->GetParentEdge();
if (parentEdge) {
#ifdef HBR_DEBUG
std::cerr << "parent edge situation " << *parentEdge << "\n";
#endif
HbrVertex<T>* dest = parentEdge->GetDestVertex();
HbrVertex<T>* org = parentEdge->GetOrgVertex();
GuaranteeNeighbor(mesh, parentEdge);
HbrFace<T>* parentFace = parentEdge->GetLeftFace();
RefineFaceAtVertex(mesh, parentFace, dest);
RefineFaceAtVertex(mesh, parentFace, org);
refineFaceAtMiddle(mesh, parentFace);
parentFace = parentEdge->GetRightFace();
// The right face may not necessarily exist even after
// GuaranteeNeighbor
if (parentFace) {
RefineFaceAtVertex(mesh, parentFace, dest);
RefineFaceAtVertex(mesh, parentFace, org);
refineFaceAtMiddle(mesh, parentFace);
}
return;
}
// The second case: the vertex is a child of a vertex. In this case
// we have to recursively guarantee that the parent's adjacent
// faces also exist.
HbrVertex<T>* parentVertex = vertex->GetParentVertex();
if (parentVertex) {
#ifdef HBR_DEBUG
std::cerr << "parent vertex situation " << *parentVertex << "\n";
#endif
parentVertex->GuaranteeNeighbors();
// And then we refine all the face neighbors of the parent
// vertex
HbrHalfedge<T>* start = parentVertex->GetIncidentEdge(), *edge;
edge = start;
while (edge) {
HbrFace<T>* f = edge->GetLeftFace();
RefineFaceAtVertex(mesh, f, parentVertex);
edge = parentVertex->GetNextEdge(edge);
if (edge == start) break;
}
}
}
template <class T>
bool
HbrLoopSubdivision<T>::HasLimit(HbrMesh<T>* mesh, HbrFace<T>* face) {
if (face->IsHole()) return false;
// A limit face exists if all the bounding edges have limit curves
for (int i = 0; i < face->GetNumVertices(); ++i) {
if (!HasLimit(mesh, face->GetEdge(i))) {
return false;
}
}
return true;
}
template <class T>
bool
HbrLoopSubdivision<T>::HasLimit(HbrMesh<T>* mesh, HbrHalfedge<T>* edge) {
// A sharp edge has a limit curve if both endpoints have limits.
// A smooth edge has a limit if both endpoints have limits and
// the edge isn't on the boundary.
if (edge->GetSharpness() >= HbrHalfedge<T>::k_InfinitelySharp) return true;
if (!HasLimit(mesh, edge->GetOrgVertex()) || !HasLimit(mesh, edge->GetDestVertex())) return false;
return !edge->IsBoundary();
}
template <class T>
bool
HbrLoopSubdivision<T>::HasLimit(HbrMesh<T>* /* mesh */, HbrVertex<T>* vertex) {
vertex->GuaranteeNeighbors();
switch (vertex->GetMask(false)) {
case HbrVertex<T>::k_Smooth:
case HbrVertex<T>::k_Dart:
return !vertex->OnBoundary();
break;
case HbrVertex<T>::k_Crease:
case HbrVertex<T>::k_Corner:
default:
if (vertex->IsVolatile()) {
// Search for any incident semisharp boundary edge
HbrHalfedge<T>* start = vertex->GetIncidentEdge(), *edge, *next;
edge = start;
while (edge) {
if (edge->IsBoundary() && edge->GetSharpness() < HbrHalfedge<T>::k_InfinitelySharp) {
return false;
}
next = vertex->GetNextEdge(edge);
if (next == start) {
break;
} else if (!next) {
edge = edge->GetPrev();
if (edge->IsBoundary() && edge->GetSharpness() < HbrHalfedge<T>::k_InfinitelySharp) {
return false;
}
break;
} else {
edge = next;
}
}
}
return true;
}
}
template <class T>
HbrVertex<T>*
HbrLoopSubdivision<T>::Subdivide(HbrMesh<T>* /* mesh */, HbrFace<T>* /* face */) {
// In loop subdivision, faces never subdivide
assert(0);
return 0;
}
template <class T>
HbrVertex<T>*
HbrLoopSubdivision<T>::Subdivide(HbrMesh<T>* mesh, HbrHalfedge<T>* edge) {
#ifdef HBR_DEBUG
std::cerr << "Subdividing at " << *edge << "\n";
#endif
// Ensure the opposite face exists.
GuaranteeNeighbor(mesh, edge);
float esharp = edge->GetSharpness();
HbrVertex<T>* v = mesh->NewVertex();
T& data = v->GetData();
// If there's the possibility of vertex edits on either vertex, we
// have to make sure the edit has been applied
if (mesh->HasVertexEdits()) {
edge->GetOrgVertex()->GuaranteeNeighbors();
edge->GetDestVertex()->GuaranteeNeighbors();
}
if (!edge->IsBoundary() && esharp <= 1.0f) {
// Of the two half-edges, pick one of them consistently such
// that the org and dest vertices are also consistent through
// multi-threading. It doesn't matter as far as the
// theoretical calculation is concerned, but it is desirable
// to be consistent about it in the face of the limitations of
// floating point commutativity. So we always pick the
// half-edge such that its incident face is the smallest of
// the two faces, as far as the face paths are concerned.
if (edge->GetOpposite() && edge->GetOpposite()->GetFace()->GetPath() < edge->GetFace()->GetPath()) {
edge = edge->GetOpposite();
}
// Handle both the smooth and fractional sharpness cases. We
// lerp between the sharp case (average of the two end points)
// and the unsharp case (3/8 of each of the two end points
// plus 1/8 of the two opposite face averages).
// Lerp end point weight between non sharp contribution of
// 3/8 and the sharp contribution of 0.5.
float endPtWeight = 0.375f + esharp * (0.5f - 0.375f);
data.AddWithWeight(edge->GetOrgVertex()->GetData(), endPtWeight);
data.AddWithWeight(edge->GetDestVertex()->GetData(), endPtWeight);
// Lerp the opposite pt weights between non sharp contribution
// of 1/8 and the sharp contribution of 0.
float oppPtWeight = 0.125f * (1 - esharp);
HbrHalfedge<T>* ee = edge->GetNext();
data.AddWithWeight(ee->GetDestVertex()->GetData(), oppPtWeight);
ee = edge->GetOpposite()->GetNext();
data.AddWithWeight(ee->GetDestVertex()->GetData(), oppPtWeight);
} else {
// Fully sharp edge, just average the two end points
data.AddWithWeight(edge->GetOrgVertex()->GetData(), 0.5f);
data.AddWithWeight(edge->GetDestVertex()->GetData(), 0.5f);
}
// Varying data is always the average of two end points
data.AddVaryingWithWeight(edge->GetOrgVertex()->GetData(), 0.5f);
data.AddVaryingWithWeight(edge->GetDestVertex()->GetData(), 0.5f);
#ifdef HBR_DEBUG
std::cerr << " created " << *v << "\n";
#endif
// Only boundary edges will create extraordinary vertices
if (edge->IsBoundary()) {
v->SetExtraordinary();
}
return v;
}
template <class T>
HbrVertex<T>*
HbrLoopSubdivision<T>::Subdivide(HbrMesh<T>* mesh, HbrVertex<T>* vertex) {
// Ensure the ring of faces around this vertex exists before
// we compute the valence
vertex->GuaranteeNeighbors();
float valence = static_cast<float>(vertex->GetValence());
float invvalence = 1.0f / valence;
HbrVertex<T>* v = mesh->NewVertex();
T& data = v->GetData();
// Due to fractional weights we may need to do two subdivision
// passes
int masks[2];
float weights[2];
int passes;
masks[0] = vertex->GetMask(false);
masks[1] = vertex->GetMask(true);
// If the masks are different, we subdivide twice: once using the
// current mask, once using the mask at the next level of
// subdivision, then use fractional mask weights to weigh
// each weighing
if (masks[0] != masks[1]) {
weights[1] = vertex->GetFractionalMask();
weights[0] = 1.0f - weights[1];
passes = 2;
} else {
weights[0] = 1.0f;
weights[1] = 0.0f;
passes = 1;
}
for (int i = 0; i < passes; ++i) {
switch (masks[i]) {
case HbrVertex<T>::k_Smooth:
case HbrVertex<T>::k_Dart: {
float beta = 0.25f * cosf((float)M_PI * 2.0f * invvalence) + 0.375f;
beta = beta * beta;
beta = (0.625f - beta) * invvalence;
data.AddWithWeight(vertex->GetData(), weights[i] * (1 - (beta * valence)));
HbrSubdivision<T>::AddSurroundingVerticesWithWeight(
mesh, vertex, weights[i] * beta, &data);
break;
}
case HbrVertex<T>::k_Crease: {
// Compute 3/4 of old vertex value
data.AddWithWeight(vertex->GetData(), weights[i] * 0.75f);
// Add 0.125f of the (hopefully only two!) neighbouring
// sharp edges
HbrSubdivision<T>::AddCreaseEdgesWithWeight(
mesh, vertex, i == 1, weights[i] * 0.125f, &data);
break;
}
case HbrVertex<T>::k_Corner:
default: {
// Just copy the old value
data.AddWithWeight(vertex->GetData(), weights[i]);
break;
}
}
}
// Varying data is always just propagated down
data.AddVaryingWithWeight(vertex->GetData(), 1.0f);
#ifdef HBR_DEBUG
std::cerr << "Subdividing at " << *vertex << "\n";
std::cerr << " created " << *v << "\n";
#endif
// Inherit extraordinary flag and sharpness
if (vertex->IsExtraordinary()) v->SetExtraordinary();
float sharp = vertex->GetSharpness();
if (sharp >= HbrVertex<T>::k_InfinitelySharp) {
v->SetSharpness(HbrVertex<T>::k_InfinitelySharp);
} else if (sharp > HbrVertex<T>::k_Smooth) {
v->SetSharpness(std::max((float) HbrVertex<T>::k_Smooth, sharp - 1.0f));
} else {
v->SetSharpness(HbrVertex<T>::k_Smooth);
}
return v;
}
template <class T>
void
HbrLoopSubdivision<T>::refineFaceAtMiddle(HbrMesh<T>* mesh, HbrFace<T>* face) {
#ifdef HBR_DEBUG
std::cerr << "Refining middle face of " << *face << "\n";
#endif
if (!face->GetChild(3)) {
HbrFace<T>* child;
HbrVertex<T>* vertices[3];
// The fourth face is not an obvious child of any vertex. We
// assign it index 3 despite there being no fourth vertex in
// the triangle. The ordering of vertices here is done to
// preserve parametric space as best we can
vertices[0] = face->GetEdge(1)->Subdivide();
vertices[1] = face->GetEdge(2)->Subdivide();
vertices[2] = face->GetEdge(0)->Subdivide();
child = mesh->NewFace(3, vertices, face, 3);
#ifdef HBR_DEBUG
std::cerr << "Creating face " << *child << "\n";
#endif
if (mesh->GetTotalFVarWidth()) {
transferFVarToChild(mesh, face, child, 3);
}
transferEditsToChild(face, child, 3);
}
}
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_HBRLOOP_H */
File diff suppressed because it is too large. Load diff
+293
View File
@@ -0,0 +1,293 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_HBRSUBDIVISION_H
#define OPENSUBDIV3_HBRSUBDIVISION_H
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
template <class T> class HbrFace;
template <class T> class HbrVertex;
template <class T> class HbrHalfedge;
template <class T> class HbrMesh;
template <class T> class HbrSubdivision {
public:
HbrSubdivision<T>()
: creaseSubdivision(k_CreaseNormal) {}
virtual ~HbrSubdivision<T>() {}
virtual HbrSubdivision<T>* Clone() const = 0;
// How to subdivide a face
virtual void Refine(HbrMesh<T>* mesh, HbrFace<T>* face) = 0;
// Subdivide a face only at a particular vertex (creating one child)
virtual HbrFace<T>* RefineFaceAtVertex(HbrMesh<T>* mesh, HbrFace<T>* face, HbrVertex<T>* vertex) = 0;
// Refine all faces around a particular vertex
virtual void RefineAtVertex(HbrMesh<T>* mesh, HbrVertex<T>* vertex);
// Given an edge, try to ensure the edge's opposite exists by
// forcing refinement up the hierarchy
virtual void GuaranteeNeighbor(HbrMesh<T>* mesh, HbrHalfedge<T>* edge) = 0;
// Given an vertex, ensure all faces in the ring around it exist
// by forcing refinement up the hierarchy
virtual void GuaranteeNeighbors(HbrMesh<T>* mesh, HbrVertex<T>* vertex) = 0;
// Returns true if the vertex, edge, or face has a limit point,
// curve, or surface associated with it
virtual bool HasLimit(HbrMesh<T>* /* mesh */, HbrFace<T>* /* face */) { return true; }
virtual bool HasLimit(HbrMesh<T>* /* mesh */, HbrHalfedge<T>* /* edge */) { return true; }
virtual bool HasLimit(HbrMesh<T>* /* mesh */, HbrVertex<T>* /* vertex */) { return true; }
// How to turn faces, edges, and vertices into vertices
virtual HbrVertex<T>* Subdivide(HbrMesh<T>* mesh, HbrFace<T>* face) = 0;
virtual HbrVertex<T>* Subdivide(HbrMesh<T>* mesh, HbrHalfedge<T>* edge) = 0;
virtual HbrVertex<T>* Subdivide(HbrMesh<T>* mesh, HbrVertex<T>* vertex) = 0;
// Returns true if the vertex is extraordinary in the subdivision scheme
virtual bool VertexIsExtraordinary(HbrMesh<T> const * /* mesh */, HbrVertex<T>* /* vertex */) { return false; }
// Returns true if the face is extraordinary in the subdivision scheme
virtual bool FaceIsExtraordinary(HbrMesh<T> const * /* mesh */, HbrFace<T>* /* face */) { return false; }
// Crease subdivision rules. When subdividing a edge with a crease
// strength, we get two child subedges, and we need to determine
// what weights to assign these subedges. The "normal" rule
// is to simply assign the current edge's crease strength - 1
// to both of the child subedges. The "Chaikin" rule looks at the
// current edge and incident edges to the current edge's end
// vertices, and weighs them; for more information consult
// the Geri's Game paper.
enum CreaseSubdivision {
k_CreaseNormal,
k_CreaseChaikin
};
CreaseSubdivision GetCreaseSubdivisionMethod() const { return creaseSubdivision; }
void SetCreaseSubdivisionMethod(CreaseSubdivision method) { creaseSubdivision = method; }
// Figures out how to assign a crease weight on an edge to its
// subedge. The subedge must be a child of the parent edge
// (either subedge->GetOrgVertex() or subedge->GetDestVertex()
// == edge->Subdivide()). The vertex supplied must NOT be
// a parent of the subedge; it is either the origin or
// destination vertex of edge.
void SubdivideCreaseWeight(HbrHalfedge<T>* edge, HbrVertex<T>* vertex, HbrHalfedge<T>* subedge);
// Returns the expected number of children faces after subdivision
// for a face with the given number of vertices.
virtual int GetFaceChildrenCount(int nvertices) const = 0;
protected:
CreaseSubdivision creaseSubdivision;
// Helper routine for subclasses: for a given vertex, sums
// contributions from surrounding vertices
void AddSurroundingVerticesWithWeight(HbrMesh<T>* mesh, HbrVertex<T>* vertex, float weight, T* data);
// Helper routine for subclasses: for a given vertex with a crease
// mask, adds contributions from the two crease edges
void AddCreaseEdgesWithWeight(HbrMesh<T>* mesh, HbrVertex<T>* vertex, bool next, float weight, T* data);
private:
// Helper class used by AddSurroundingVerticesWithWeight
class SmoothSubdivisionVertexOperator : public HbrVertexOperator<T> {
public:
SmoothSubdivisionVertexOperator(T* data, bool meshHasEdits, float weight)
: m_data(data),
m_meshHasEdits(meshHasEdits),
m_weight(weight)
{
}
virtual void operator() (HbrVertex<T> &vertex) {
// Must ensure vertex edits have been applied
if (m_meshHasEdits) {
vertex.GuaranteeNeighbors();
}
m_data->AddWithWeight(vertex.GetData(), m_weight);
}
private:
T* m_data;
const bool m_meshHasEdits;
const float m_weight;
};
// Helper class used by AddCreaseEdgesWithWeight
class CreaseSubdivisionHalfedgeOperator : public HbrHalfedgeOperator<T> {
public:
CreaseSubdivisionHalfedgeOperator(HbrVertex<T> *vertex, T* data, bool meshHasEdits, bool next, float weight)
: m_vertex(vertex),
m_data(data),
m_meshHasEdits(meshHasEdits),
m_next(next),
m_weight(weight),
m_count(0)
{
}
virtual void operator() (HbrHalfedge<T> &edge) {
if (m_count < 2 && edge.IsSharp(m_next)) {
HbrVertex<T>* a = edge.GetDestVertex();
if (a == m_vertex) a = edge.GetOrgVertex();
// Must ensure vertex edits have been applied
if (m_meshHasEdits) {
a->GuaranteeNeighbors();
}
m_data->AddWithWeight(a->GetData(), m_weight);
m_count++;
}
}
private:
HbrVertex<T>* m_vertex;
T* m_data;
const bool m_meshHasEdits;
const bool m_next;
const float m_weight;
int m_count;
};
private:
// Helper class used by RefineAtVertex.
class RefineFaceAtVertexOperator : public HbrFaceOperator<T> {
public:
RefineFaceAtVertexOperator(HbrSubdivision<T>* subdivision, HbrMesh<T>* mesh, HbrVertex<T> *vertex)
: m_subdivision(subdivision),
m_mesh(mesh),
m_vertex(vertex)
{
}
virtual void operator() (HbrFace<T> &face) {
m_subdivision->RefineFaceAtVertex(m_mesh, &face, m_vertex);
}
private:
HbrSubdivision<T>* const m_subdivision;
HbrMesh<T>* const m_mesh;
HbrVertex<T>* const m_vertex;
};
};
template <class T>
void
HbrSubdivision<T>::RefineAtVertex(HbrMesh<T>* mesh, HbrVertex<T>* vertex) {
GuaranteeNeighbors(mesh, vertex);
RefineFaceAtVertexOperator op(this, mesh, vertex);
vertex->ApplyOperatorSurroundingFaces(op);
}
template <class T>
void
HbrSubdivision<T>::SubdivideCreaseWeight(HbrHalfedge<T>* edge, HbrVertex<T>* vertex, HbrHalfedge<T>* subedge) {
float sharpness = edge->GetSharpness();
// In all methods, if the parent edge is infinitely sharp, the
// child edge is also infinitely sharp
if (sharpness >= HbrHalfedge<T>::k_InfinitelySharp) {
subedge->SetSharpness(HbrHalfedge<T>::k_InfinitelySharp);
}
// Chaikin's curve subdivision: use 3/4 of the parent sharpness,
// plus 1/4 of crease sharpnesses incident to vertex
else if (creaseSubdivision == HbrSubdivision<T>::k_CreaseChaikin) {
float childsharp = 0.0f;
int n = 0;
// Add 1/4 of the sharpness of all crease edges incident to
// the vertex (other than this crease edge)
class ChaikinEdgeCreaseOperator : public HbrHalfedgeOperator<T> {
public:
ChaikinEdgeCreaseOperator(
HbrHalfedge<T> const * edge, float & childsharp, int & count) :
m_edge(edge), m_childsharp(childsharp), m_count(count) { }
virtual void operator() (HbrHalfedge<T> &edge) {
// Skip original edge or it's opposite
if ((&edge==m_edge) || (&edge==m_edge->GetOpposite()))
return;
if (edge.GetSharpness() > HbrHalfedge<T>::k_Smooth) {
m_childsharp += edge.GetSharpness();
++m_count;
}
}
private:
HbrHalfedge<T> const * m_edge;
float & m_childsharp;
int & m_count;
};
ChaikinEdgeCreaseOperator op(edge, childsharp, n);
vertex->GuaranteeNeighbors();
vertex->ApplyOperatorSurroundingEdges(op);
if (n) {
childsharp = childsharp * 0.25f / float(n);
}
// Add 3/4 of the sharpness of this crease edge
childsharp += sharpness * 0.75f;
childsharp -= 1.0f;
if (childsharp < (float) HbrHalfedge<T>::k_Smooth) {
childsharp = (float) HbrHalfedge<T>::k_Smooth;
}
subedge->SetSharpness(childsharp);
} else {
sharpness -= 1.0f;
if (sharpness < (float) HbrHalfedge<T>::k_Smooth) {
sharpness = (float) HbrHalfedge<T>::k_Smooth;
}
subedge->SetSharpness(sharpness);
}
}
template <class T>
void
HbrSubdivision<T>::AddSurroundingVerticesWithWeight(HbrMesh<T>* mesh, HbrVertex<T>* vertex, float weight, T* data) {
SmoothSubdivisionVertexOperator op(data, mesh->HasVertexEdits(), weight);
vertex->ApplyOperatorSurroundingVertices(op);
}
template <class T>
void
HbrSubdivision<T>::AddCreaseEdgesWithWeight(HbrMesh<T>* mesh, HbrVertex<T>* vertex, bool next, float weight, T* data) {
CreaseSubdivisionHalfedgeOperator op(vertex, data, mesh->HasVertexEdits(), next, weight);
vertex->ApplyOperatorSurroundingEdges(op);
}
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_HBRSUBDIVISION_H */
File diff suppressed because it is too large. Load diff
+241
View File
@@ -0,0 +1,241 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_HBRVERTEXEDIT_H
#define OPENSUBDIV3_HBRVERTEXEDIT_H
#include <algorithm>
#include "../hbr/hierarchicalEdit.h"
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
template <class T> class HbrVertexEdit;
template <class T>
std::ostream& operator<<(std::ostream& out, const HbrVertexEdit<T>& path) {
out << "vertex path = (" << path.faceid << ' ';
for (int i = 0; i < path.nsubfaces; ++i) {
out << static_cast<int>(path.subfaces[i]) << ' ';
}
return out << static_cast<int>(path.vertexid) << "), edit = (" << path.edit[0] << ',' << path.edit[1] << ',' << path.edit[2] << ')';
}
template <class T>
class HbrVertexEdit : public HbrHierarchicalEdit<T> {
public:
HbrVertexEdit(int _faceid, int _nsubfaces, unsigned char *_subfaces, unsigned char _vertexid, int _index, int _width, bool _isP, typename HbrHierarchicalEdit<T>::Operation _op, float *_edit)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces), vertexid(_vertexid), index(_index), width(_width), isP(_isP), op(_op) {
edit = new float[width];
memcpy(edit, _edit, width * sizeof(float));
}
HbrVertexEdit(int _faceid, int _nsubfaces, int *_subfaces, int _vertexid, int _index, int _width, bool _isP, typename HbrHierarchicalEdit<T>::Operation _op, float *_edit)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces), vertexid(static_cast<unsigned char>(_vertexid)), index(_index), width(_width), isP(_isP), op(_op) {
edit = new float[width];
memcpy(edit, _edit, width * sizeof(float));
}
virtual ~HbrVertexEdit() {
delete[] edit;
}
// Return the vertex id (the last element in the path)
unsigned char GetVertexID() const { return vertexid; }
friend std::ostream& operator<< <T> (std::ostream& out, const HbrVertexEdit<T>& path);
// Return index of variable this edit applies to
int GetIndex() const { return index; }
// Return width of the variable
int GetWidth() const { return width; }
// Get the numerical value of the edit
const float* GetEdit() const { return edit; }
// Get the type of operation
typename HbrHierarchicalEdit<T>::Operation GetOperation() const { return op; }
virtual void ApplyEditToFace(HbrFace<T>* face) {
if (HbrHierarchicalEdit<T>::GetNSubfaces() == face->GetDepth()) {
// Tags the vertex as being edited; it'll figure out what to
// when GuaranteeNeighbor is called
face->GetVertex(vertexid)->SetVertexEdit();
}
// In any event, mark the face as having a vertex edit (which
// may only be applied on subfaces)
face->MarkVertexEdits();
}
virtual void ApplyEditToVertex(HbrFace<T>* face, HbrVertex<T>* vertex) {
if (HbrHierarchicalEdit<T>::GetNSubfaces() == face->GetDepth() &&
face->GetVertex(vertexid) == vertex) {
vertex->GetData().ApplyVertexEdit(*const_cast<const HbrVertexEdit<T>*>(this));
}
}
#ifdef PRMAN
virtual void ApplyToBound(struct bbox& bbox, RtMatrix *mx) const {
if (isP) {
struct xyz p = *(struct xyz*)edit;
if (mx)
MxTransformByMatrix(&p, &p, *mx, 1);
if (op == HbrHierarchicalEdit<T>::Set) {
bbox.min.x = std::min(bbox.min.x, p.x);
bbox.min.y = std::min(bbox.min.y, p.y);
bbox.min.z = std::min(bbox.min.z, p.z);
bbox.max.x = std::max(bbox.max.x, p.x);
bbox.max.y = std::max(bbox.max.y, p.y);
bbox.max.z = std::max(bbox.max.z, p.z);
} else if (op == HbrHierarchicalEdit<T>::Add ||
op == HbrHierarchicalEdit<T>::Subtract) {
bbox.min.x -= fabsf(p.x);
bbox.min.y -= fabsf(p.y);
bbox.min.z -= fabsf(p.z);
bbox.max.x += fabsf(p.x);
bbox.max.y += fabsf(p.y);
bbox.max.z += fabsf(p.z);
}
}
}
#endif
private:
const unsigned char vertexid;
int index;
int width;
unsigned isP:1;
typename HbrHierarchicalEdit<T>::Operation op;
float* edit;
};
template <class T>
class HbrMovingVertexEdit : public HbrHierarchicalEdit<T> {
public:
HbrMovingVertexEdit(int _faceid, int _nsubfaces, unsigned char *_subfaces, unsigned char _vertexid, int _index, int _width, bool _isP, typename HbrHierarchicalEdit<T>::Operation _op, float *_edit)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces), vertexid(_vertexid), index(_index), width(_width), isP(_isP), op(_op) {
edit = new float[width * 2];
memcpy(edit, _edit, 2 * width * sizeof(float));
}
HbrMovingVertexEdit(int _faceid, int _nsubfaces, int *_subfaces, int _vertexid, int _index, int _width, bool _isP, typename HbrHierarchicalEdit<T>::Operation _op, float *_edit)
: HbrHierarchicalEdit<T>(_faceid, _nsubfaces, _subfaces), vertexid(_vertexid), index(_index), width(_width), isP(_isP), op(_op) {
edit = new float[width * 2];
memcpy(edit, _edit, 2 * width * sizeof(float));
}
virtual ~HbrMovingVertexEdit() {
delete[] edit;
}
// Return the vertex id (the last element in the path)
unsigned char GetVertexID() const { return vertexid; }
friend std::ostream& operator<< <T> (std::ostream& out, const HbrVertexEdit<T>& path);
// Return index of variable this edit applies to
int GetIndex() const { return index; }
// Return width of the variable
int GetWidth() const { return width; }
// Get the numerical value of the edit
const float* GetEdit() const { return edit; }
// Get the type of operation
typename HbrHierarchicalEdit<T>::Operation GetOperation() const { return op; }
virtual void ApplyEditToFace(HbrFace<T>* face) {
if (HbrHierarchicalEdit<T>::GetNSubfaces() == face->GetDepth()) {
// Tags the vertex as being edited; it'll figure out what to
// when GuaranteeNeighbor is called
face->GetVertex(vertexid)->SetVertexEdit();
}
// In any event, mark the face as having a vertex edit (which
// may only be applied on subfaces)
face->MarkVertexEdits();
}
virtual void ApplyEditToVertex(HbrFace<T>* face, HbrVertex<T>* vertex) {
if (HbrHierarchicalEdit<T>::GetNSubfaces() == face->GetDepth() &&
face->GetVertex(vertexid) == vertex) {
vertex->GetData().ApplyMovingVertexEdit(*const_cast<const HbrMovingVertexEdit<T>*>(this));
}
}
#ifdef PRMAN
virtual void ApplyToBound(struct bbox& bbox, RtMatrix *mx) const {
if (isP) {
struct xyz p1 = *(struct xyz*)edit;
struct xyz p2 = *(struct xyz*)&edit[3];
if (mx) {
MxTransformByMatrix(&p1, &p1, *mx, 1);
MxTransformByMatrix(&p2, &p2, *mx, 1);
}
if (op == HbrVertexEdit<T>::Set) {
bbox.min.x = std::min(std::min(bbox.min.x, p1.x), p2.x);
bbox.min.y = std::min(std::min(bbox.min.y, p1.y), p2.y);
bbox.min.z = std::min(std::min(bbox.min.z, p1.z), p2.z);
bbox.max.x = std::max(std::max(bbox.max.x, p1.x), p2.x);
bbox.max.y = std::max(std::max(bbox.max.y, p1.y), p2.y);
bbox.max.z = std::max(std::max(bbox.max.z, p1.z), p2.z);
} else if (op == HbrVertexEdit<T>::Add ||
op == HbrVertexEdit<T>::Subtract) {
float maxx = std::max(fabsf(p1.x), fabsf(p2.x));
float maxy = std::max(fabsf(p1.y), fabsf(p2.y));
float maxz = std::max(fabsf(p1.z), fabsf(p2.z));
bbox.min.x -= maxx;
bbox.min.y -= maxy;
bbox.min.z -= maxz;
bbox.max.x += maxx;
bbox.max.y += maxy;
bbox.max.z += maxz;
}
}
}
#endif
private:
const unsigned char vertexid;
int index;
int width;
unsigned isP:1;
typename HbrHierarchicalEdit<T>::Operation op;
float* edit;
};
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_HBRVERTEXEDIT_H */
+112
View File
@@ -0,0 +1,112 @@
//
// Copyright 2015 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_OSD_BUFFER_DESCRIPTOR_H
#define OPENSUBDIV3_OSD_BUFFER_DESCRIPTOR_H
#include "../version.h"
#include <string.h>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Osd {
/// \brief BufferDescriptor is a struct which describes buffer elements in
/// interleaved data buffers. Almost all Osd Evaluator APIs take
/// BufferDescriptors along with device-specific buffer objects.
///
/// The offset of BufferDescriptor can also be used to express a
/// batching offset if the data buffer is combined across multiple
/// objects together.
///
/// * Note that each element has the same data type (float)
///
// example:
// n
// -----+----------------------------------------+-------------------------
// | vertex 0 |
// -----+----------------------------------------+-------------------------
// | X Y Z R G B A Xu Yu Zu Xv Yv Zv |
// -----+----------------------------------------+-------------------------
// <------------- stride = 13 -------------->
//
// - XYZ (offset = n+0, length = 3, stride = 13)
// - RGBA (offset = n+3, length = 4, stride = 13)
// - uTangent (offset = n+7, length = 3, stride = 13)
// - vTangent (offset = n+10, length = 3, stride = 13)
//
struct BufferDescriptor {
/// Default Constructor
BufferDescriptor() : offset(0), length(0), stride(0) { }
/// Constructor
BufferDescriptor(int o, int l, int s) : offset(o), length(l), stride(s) { }
/// Returns the relative offset within a stride
int GetLocalOffset() const {
return stride > 0 ? offset % stride : 0;
}
/// True if the descriptor values are internally consistent
bool IsValid() const {
return ((length > 0) &&
(length <= stride - GetLocalOffset()));
}
/// Resets the descriptor to default
void Reset() {
offset = length = stride = 0;
}
/// True if the descriptors are identical
bool operator == (BufferDescriptor const &other) const {
return (offset == other.offset &&
length == other.length &&
stride == other.stride);
}
/// True if the descriptors are not identical
bool operator != (BufferDescriptor const &other) const {
return !(this->operator==(other));
}
/// offset to desired element data
int offset;
/// number or length of the data
int length;
/// stride to the next element
int stride;
};
} // end namespace Osd
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_OSD_BUFFER_DESCRIPTOR_H
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,97 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_OSD_CPU_GL_VERTEX_BUFFER_H
#define OPENSUBDIV3_OSD_CPU_GL_VERTEX_BUFFER_H
#include "../version.h"
#include <cstddef>
#include "../osd/opengl.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Osd {
///
/// \brief Concrete vertex buffer class for cpu subdivision and OpenGL drawing.
///
/// CpuGLVertexBuffer implements CpuVertexBufferInterface and
/// GLVertexBufferInterface.
///
/// The buffer interop between Cpu and GL is handled automatically when a
/// client calls BindCpuBuffer and BindVBO methods.
///
class CpuGLVertexBuffer {
public:
/// Creator. Returns NULL if error.
static CpuGLVertexBuffer * Create(int numElements, int numVertices,
void *deviceContext = NULL);
/// Destructor.
~CpuGLVertexBuffer();
/// This method is meant to be used in client code in order to provide
/// coarse vertices data to Osd.
void UpdateData(const float *src, int startVertex, int numVertices,
void *deviceContext = NULL);
/// Returns how many elements defined in this vertex buffer.
int GetNumElements() const;
/// Returns how many vertices allocated in this vertex buffer.
int GetNumVertices() const;
/// Returns cpu memory. GL buffer will be mapped to cpu address
/// if necessary.
float * BindCpuBuffer();
/// Returns the name of GL buffer object. If the buffer is mapped
/// to cpu address, it will be unmapped back to GL.
GLuint BindVBO(void *deviceContext = NULL);
protected:
/// Constructor.
CpuGLVertexBuffer(int numElements, int numVertices);
/// Allocates VBO for this buffer. Returns true if success.
bool allocate();
private:
int _numElements;
int _numVertices;
GLuint _vbo;
float *_cpuBuffer;
bool _dataDirty;
};
} // end namespace Osd
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_OSD_CPU_GL_VERTEX_BUFFER_H
+145
View File
@@ -0,0 +1,145 @@
//
// Copyright 2015 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_OSD_CPU_PATCH_TABLE_H
#define OPENSUBDIV3_OSD_CPU_PATCH_TABLE_H
#include "../version.h"
#include <vector>
#include "../far/patchDescriptor.h"
#include "../osd/nonCopyable.h"
#include "../osd/types.h"
#include <vector>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far{
class PatchTable;
};
namespace Osd {
/// \brief Cpu patch table
///
/// XXX: We can use just Far::PatchTable for typical CpuEval use cases.
///
/// Currently this class exists because of the template resolution
/// for the CpuEvaluator's generic interface functions
/// (glEvalLimit example uses), and
/// device-specific patch tables such as GLPatchTables internally use
/// as a staging buffer to splice patcharray and interleave sharpnesses.
///
/// Ideally Far::PatchTables should have the same data representation
/// and accessors so that we don't have to copy data unnecessarily.
///
class CpuPatchTable {
public:
static CpuPatchTable *Create(const Far::PatchTable *patchTable,
void *deviceContext = NULL) {
(void)deviceContext; // unused
return new CpuPatchTable(patchTable);
}
explicit CpuPatchTable(const Far::PatchTable *patchTable);
~CpuPatchTable() {}
const PatchArray *GetPatchArrayBuffer() const {
return &_patchArrays[0];
}
const int *GetPatchIndexBuffer() const {
return &_indexBuffer[0];
}
const PatchParam *GetPatchParamBuffer() const {
return &_patchParamBuffer[0];
}
size_t GetNumPatchArrays() const {
return _patchArrays.size();
}
size_t GetPatchIndexSize() const {
return _indexBuffer.size();
}
size_t GetPatchParamSize() const {
return _patchParamBuffer.size();
}
const PatchArray *GetVaryingPatchArrayBuffer() const {
if (_varyingPatchArrays.empty()) {
return NULL;
}
return &_varyingPatchArrays[0];
}
const int *GetVaryingPatchIndexBuffer() const {
if (_varyingIndexBuffer.empty()) {
return NULL;
}
return &_varyingIndexBuffer[0];
}
size_t GetVaryingPatchIndexSize() const {
return _varyingIndexBuffer.size();
}
int GetNumFVarChannels() const {
return (int)_fvarPatchArrays.size();
}
const PatchArray *GetFVarPatchArrayBuffer(int fvarChannel = 0) const {
return &_fvarPatchArrays[fvarChannel][0];
}
const int *GetFVarPatchIndexBuffer(int fvarChannel = 0) const {
return &_fvarIndexBuffers[fvarChannel][0];
}
size_t GetFVarPatchIndexSize(int fvarChannel = 0) const {
return _fvarIndexBuffers[fvarChannel].size();
}
const PatchParam *GetFVarPatchParamBuffer(int fvarChannel= 0) const {
return &_fvarParamBuffers[fvarChannel][0];
}
size_t GetFVarPatchParamSize(int fvarChannel = 0) const {
return _fvarParamBuffers[fvarChannel].size();
}
protected:
PatchArrayVector _patchArrays;
std::vector<int> _indexBuffer;
PatchParamVector _patchParamBuffer;
PatchArrayVector _varyingPatchArrays;
std::vector<int> _varyingIndexBuffer;
std::vector< PatchArrayVector > _fvarPatchArrays;
std::vector< std::vector<int> > _fvarIndexBuffers;
std::vector< PatchParamVector > _fvarParamBuffers;
};
} // end namespace Osd
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_OSD_CPU_PATCH_TABLE_H
+83
View File
@@ -0,0 +1,83 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_OSD_CPU_VERTEX_BUFFER_H
#define OPENSUBDIV3_OSD_CPU_VERTEX_BUFFER_H
#include "../version.h"
#include <cstddef>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Osd {
/// \brief Concrete vertex buffer class for CPU subdivision.
///
/// CpuVertexBuffer implements the VertexBufferInterface. An instance
/// of this buffer class can be passed to CpuEvaluator
///
class CpuVertexBuffer {
public:
/// Creator. Returns NULL if error.
static CpuVertexBuffer * Create(int numElements, int numVertices,
void *deviceContext = NULL);
/// Destructor.
~CpuVertexBuffer();
/// This method is meant to be used in client code in order to provide
/// coarse vertices data to Osd.
void UpdateData(const float *src, int startVertex, int numVertices,
void *deviceContext = NULL);
/// Returns how many elements defined in this vertex buffer.
int GetNumElements() const;
/// Returns how many vertices allocated in this vertex buffer.
int GetNumVertices() const;
/// Returns the address of CPU buffer
float * BindCpuBuffer();
protected:
/// Constructor.
CpuVertexBuffer(int numElements, int numVertices);
private:
int _numElements;
int _numVertices;
float *_cpuBuffer;
};
} // end namespace Osd
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_OSD_CPU_VERTEX_BUFFER_H
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,86 @@
//
// Copyright 2015 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_OSD_GL_LEGACY_GREGORY_PATCH_TABLE_H
#define OPENSUBDIV3_OSD_GL_LEGACY_GREGORY_PATCH_TABLE_H
#include "../version.h"
#include "../far/patchTable.h"
#include "../osd/nonCopyable.h"
#include "../osd/opengl.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Osd {
class GLLegacyGregoryPatchTable
: private NonCopyable<GLLegacyGregoryPatchTable> {
public:
~GLLegacyGregoryPatchTable();
static GLLegacyGregoryPatchTable *Create(Far::PatchTable const *patchTable);
void UpdateVertexBuffer(GLuint vbo);
GLuint GetVertexTextureBuffer() const {
return _vertexTextureBuffer;
}
GLuint GetVertexValenceTextureBuffer() const {
return _vertexValenceTextureBuffer;
}
GLuint GetQuadOffsetsTextureBuffer() const {
return _quadOffsetsTextureBuffer;
}
GLuint GetQuadOffsetsBase(Far::PatchDescriptor::Type type) {
if (type == Far::PatchDescriptor::GREGORY_BOUNDARY) {
return _quadOffsetsBase[1];
}
return _quadOffsetsBase[0];
}
protected:
GLLegacyGregoryPatchTable();
private:
GLuint _vertexTextureBuffer;
GLuint _vertexValenceTextureBuffer;
GLuint _quadOffsetsTextureBuffer;
GLuint _quadOffsetsBase[2]; // gregory, boundaryGregory
};
} // end namespace Osd
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_OSD_GL_LEGACY_GREGORY_PATCH_TABLE_H
+48
View File
@@ -0,0 +1,48 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_OSD_GL_MESH_H
#define OPENSUBDIV3_OSD_GL_MESH_H
#include "../version.h"
#include "../osd/mesh.h"
#include "../osd/glPatchTable.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Osd {
typedef MeshInterface<GLPatchTable> GLMeshInterface;
} // end namespace Osd
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_OSD_GL_MESH_H
+156
View File
@@ -0,0 +1,156 @@
//
// Copyright 2015 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_OSD_GL_PATCH_TABLE_H
#define OPENSUBDIV3_OSD_GL_PATCH_TABLE_H
#include "../version.h"
#include "../osd/nonCopyable.h"
#include "../osd/opengl.h"
#include "../osd/types.h"
#include <vector>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Far{
class PatchTable;
};
namespace Osd {
class GLPatchTable : private NonCopyable<GLPatchTable> {
public:
typedef GLuint VertexBufferBinding;
~GLPatchTable();
static GLPatchTable *Create(Far::PatchTable const *farPatchTable,
void *deviceContext = NULL);
/// Returns the patch arrays for vertex index buffer data
PatchArrayVector const &GetPatchArrays() const {
return _patchArrays;
}
/// Returns the GL index buffer containing the patch control vertices
GLuint GetPatchIndexBuffer() const {
return _patchIndexBuffer;
}
/// Returns the GL index buffer containing the patch parameter
GLuint GetPatchParamBuffer() const {
return _patchParamBuffer;
}
/// Returns the GL texture buffer containing the patch control vertices
GLuint GetPatchIndexTextureBuffer() const {
return _patchIndexTexture;
}
/// Returns the GL texture buffer containing the patch parameter
GLuint GetPatchParamTextureBuffer() const {
return _patchParamTexture;
}
/// Returns the patch arrays for varying index buffer data
PatchArrayVector const &GetVaryingPatchArrays() const {
return _varyingPatchArrays;
}
/// Returns the GL index buffer containing the varying control vertices
GLuint GetVaryingPatchIndexBuffer() const {
return _varyingIndexBuffer;
}
/// Returns the GL texture buffer containing the varying control vertices
GLuint GetVaryingPatchIndexTextureBuffer() const {
return _varyingIndexTexture;
}
/// Returns the number of face-varying channel buffers
int GetNumFVarChannels() const { return (int)_fvarPatchArrays.size(); }
/// Returns the patch arrays for face-varying index buffer data
PatchArrayVector const &GetFVarPatchArrays(int fvarChannel = 0) const {
return _fvarPatchArrays[fvarChannel];
}
/// Returns the GL index buffer containing face-varying control vertices
GLuint GetFVarPatchIndexBuffer(int fvarChannel = 0) const {
return _fvarIndexBuffers[fvarChannel];
}
/// Returns the GL texture buffer containing face-varying control vertices
GLuint GetFVarPatchIndexTextureBuffer(int fvarChannel = 0) const {
return _fvarIndexTextures[fvarChannel];
}
/// Returns the GL index buffer containing face-varying patch params
GLuint GetFVarPatchParamBuffer(int fvarChannel = 0) const {
return _fvarParamBuffers[fvarChannel];
}
/// Returns the GL texture buffer containing face-varying patch params
GLuint GetFVarPatchParamTextureBuffer(int fvarChannel = 0) const {
return _fvarParamTextures[fvarChannel];
}
protected:
GLPatchTable();
// allocate buffers from patchTable
bool allocate(Far::PatchTable const *farPatchTable);
PatchArrayVector _patchArrays;
GLuint _patchIndexBuffer;
GLuint _patchParamBuffer;
GLuint _patchIndexTexture;
GLuint _patchParamTexture;
PatchArrayVector _varyingPatchArrays;
GLuint _varyingIndexBuffer;
GLuint _varyingIndexTexture;
std::vector<PatchArrayVector> _fvarPatchArrays;
std::vector<GLuint> _fvarIndexBuffers;
std::vector<GLuint> _fvarIndexTextures;
std::vector<GLuint> _fvarParamBuffers;
std::vector<GLuint> _fvarParamTextures;
};
} // end namespace Osd
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_OSD_GL_PATCH_TABLE_H
+88
View File
@@ -0,0 +1,88 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_OSD_GL_VERTEX_BUFFER_H
#define OPENSUBDIV3_OSD_GL_VERTEX_BUFFER_H
#include "../version.h"
#include "../osd/opengl.h"
#include <cstddef>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Osd {
///
/// \brief Concrete vertex buffer class for GLSL subdivision and OpenGL drawing.
///
/// GLVertexBuffer implements GLVertexBufferInterface. An instance
/// of this buffer class can be passed to OsdGLComputeEvaluator.
///
class GLVertexBuffer {
public:
/// Creator. Returns NULL if error.
static GLVertexBuffer * Create(int numElements, int numVertices,
void *deviceContext = NULL);
/// Destructor.
~GLVertexBuffer();
/// This method is meant to be used in client code in order to provide coarse
/// vertices data to Osd.
void UpdateData(const float *src, int startVertex, int numVertices,
void *deviceContext = NULL);
/// Returns how many elements defined in this vertex buffer.
int GetNumElements() const;
/// Returns how many vertices allocated in this vertex buffer.
int GetNumVertices() const;
/// Returns the GL buffer object.
GLuint BindVBO(void *deviceContext = NULL);
protected:
/// Constructor.
GLVertexBuffer(int numElements, int numVertices);
/// Allocates VBO for this buffer.
/// Returns true if success.
bool allocate();
private:
int _numElements;
int _numVertices;
GLuint _vbo;
};
} // end namespace Osd
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_OSD_GL_VERTEX_BUFFER_H
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,60 @@
//
// Copyright 2015 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_OSD_GLSL_PATCH_SHADER_SOURCE_H
#define OPENSUBDIV3_OSD_GLSL_PATCH_SHADER_SOURCE_H
#include "../version.h"
#include <string>
#include "../far/patchDescriptor.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Osd {
class GLSLPatchShaderSource {
public:
static std::string GetCommonShaderSource();
static std::string GetPatchBasisShaderSource();
static std::string GetVertexShaderSource(
Far::PatchDescriptor::Type type);
static std::string GetTessControlShaderSource(
Far::PatchDescriptor::Type type);
static std::string GetTessEvalShaderSource(
Far::PatchDescriptor::Type type);
};
} // end namespace Osd
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_OSD_GLSL_PATCH_SHADER_SOURCE
+723
View File
@@ -0,0 +1,723 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_OSD_MESH_H
#define OPENSUBDIV3_OSD_MESH_H
#include "../version.h"
#include <bitset>
#include <cassert>
#include <cstring>
#include <vector>
#include "../far/topologyRefiner.h"
#include "../far/patchTableFactory.h"
#include "../far/stencilTable.h"
#include "../far/stencilTableFactory.h"
#include "../osd/bufferDescriptor.h"
struct ID3D11DeviceContext;
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Osd {
enum MeshBits {
MeshAdaptive = 0,
MeshInterleaveVarying = 1,
MeshFVarData = 2,
MeshFVarAdaptive = 3,
MeshUseSmoothCornerPatch = 4,
MeshUseSingleCreasePatch = 5,
MeshUseInfSharpPatch = 6,
MeshEndCapBilinearBasis = 7, // exclusive
MeshEndCapBSplineBasis = 8, // exclusive
MeshEndCapGregoryBasis = 9, // exclusive
MeshEndCapLegacyGregory = 10, // exclusive
NUM_MESH_BITS = 11,
};
typedef std::bitset<NUM_MESH_BITS> MeshBitset;
// ---------------------------------------------------------------------------
template <class PATCH_TABLE>
class MeshInterface {
public:
typedef PATCH_TABLE PatchTable;
typedef typename PatchTable::VertexBufferBinding VertexBufferBinding;
public:
MeshInterface() { }
virtual ~MeshInterface() { }
virtual int GetNumVertices() const = 0;
virtual int GetMaxValence() const = 0;
virtual void UpdateVertexBuffer(float const *vertexData,
int startVertex, int numVerts) = 0;
virtual void UpdateVaryingBuffer(float const *varyingData,
int startVertex, int numVerts) = 0;
virtual void Refine() = 0;
virtual void Synchronize() = 0;
virtual PatchTable * GetPatchTable() const = 0;
virtual Far::PatchTable const *GetFarPatchTable() const = 0;
virtual VertexBufferBinding BindVertexBuffer() = 0;
virtual VertexBufferBinding BindVaryingBuffer() = 0;
protected:
static inline void refineMesh(Far::TopologyRefiner & refiner,
int level, bool adaptive,
bool singleCreasePatch) {
if (adaptive) {
Far::TopologyRefiner::AdaptiveOptions options(level);
options.useSingleCreasePatch = singleCreasePatch;
refiner.RefineAdaptive(options);
} else {
// This dependency on FVar channels should not be necessary
bool fullTopologyInLastLevel = refiner.GetNumFVarChannels()>0;
Far::TopologyRefiner::UniformOptions options(level);
options.fullTopologyInLastLevel = fullTopologyInLastLevel;
refiner.RefineUniform(options);
}
}
static inline void refineMesh(Far::TopologyRefiner & refiner,
int level, MeshBitset bits) {
if (bits.test(MeshAdaptive)) {
Far::TopologyRefiner::AdaptiveOptions options(level);
options.useSingleCreasePatch = bits.test(MeshUseSingleCreasePatch);
options.useInfSharpPatch = bits.test(MeshUseInfSharpPatch);
options.considerFVarChannels = bits.test(MeshFVarAdaptive);
refiner.RefineAdaptive(options);
} else {
// This dependency on FVar channels should not be necessary
bool fullTopologyInLastLevel = refiner.GetNumFVarChannels()>0;
Far::TopologyRefiner::UniformOptions options(level);
options.fullTopologyInLastLevel = fullTopologyInLastLevel;
refiner.RefineUniform(options);
}
}
};
// ---------------------------------------------------------------------------
template <typename STENCIL_TABLE, typename SRC_STENCIL_TABLE,
typename DEVICE_CONTEXT>
STENCIL_TABLE const *
convertToCompatibleStencilTable(
SRC_STENCIL_TABLE const *table, DEVICE_CONTEXT *context) {
if (! table) return NULL;
return STENCIL_TABLE::Create(table, context);
}
template <>
inline Far::StencilTable const *
convertToCompatibleStencilTable<Far::StencilTable, Far::StencilTable, void>(
Far::StencilTable const *table, void * /*context*/) {
// no need for conversion
// XXX: We don't want to even copy.
if (! table) return NULL;
return new Far::StencilTable(*table);
}
template <>
inline Far::LimitStencilTable const *
convertToCompatibleStencilTable<Far::LimitStencilTable, Far::LimitStencilTable, void>(
Far::LimitStencilTable const *table, void * /*context*/) {
// no need for conversion
// XXX: We don't want to even copy.
if (! table) return NULL;
return new Far::LimitStencilTable(*table);
}
template <>
inline Far::StencilTable const *
convertToCompatibleStencilTable<Far::StencilTable, Far::StencilTable, ID3D11DeviceContext>(
Far::StencilTable const *table, ID3D11DeviceContext * /*context*/) {
// no need for conversion
// XXX: We don't want to even copy.
if (! table) return NULL;
return new Far::StencilTable(*table);
}
// ---------------------------------------------------------------------------
// Osd evaluator cache: for the GPU backends require compiled instance
// (GLXFB, GLCompute, CL)
//
// note: this is just an example usage and client applications are supposed
// to implement their own structure for Evaluator instance.
//
template <typename EVALUATOR>
class EvaluatorCacheT {
public:
~EvaluatorCacheT() {
for(typename Evaluators::iterator it = _evaluators.begin();
it != _evaluators.end(); ++it) {
delete it->evaluator;
}
}
// XXX: FIXME, linear search
struct Entry {
Entry(BufferDescriptor const &srcDescArg,
BufferDescriptor const &dstDescArg,
BufferDescriptor const &duDescArg,
BufferDescriptor const &dvDescArg,
EVALUATOR *evalArg) : srcDesc(srcDescArg), dstDesc(dstDescArg),
duDesc(duDescArg), dvDesc(dvDescArg),
duuDesc(BufferDescriptor()),
duvDesc(BufferDescriptor()),
dvvDesc(BufferDescriptor()),
evaluator(evalArg) {}
Entry(BufferDescriptor const &srcDescArg,
BufferDescriptor const &dstDescArg,
BufferDescriptor const &duDescArg,
BufferDescriptor const &dvDescArg,
BufferDescriptor const &duuDescArg,
BufferDescriptor const &duvDescArg,
BufferDescriptor const &dvvDescArg,
EVALUATOR *evalArg) : srcDesc(srcDescArg), dstDesc(dstDescArg),
duDesc(duDescArg), dvDesc(dvDescArg),
duuDesc(duuDescArg),
duvDesc(duvDescArg),
dvvDesc(dvvDescArg),
evaluator(evalArg) {}
BufferDescriptor srcDesc, dstDesc;
BufferDescriptor duDesc, dvDesc;
BufferDescriptor duuDesc, duvDesc, dvvDesc;
EVALUATOR *evaluator;
};
typedef std::vector<Entry> Evaluators;
template <typename DEVICE_CONTEXT>
EVALUATOR *GetEvaluator(BufferDescriptor const &srcDesc,
BufferDescriptor const &dstDesc,
DEVICE_CONTEXT *deviceContext) {
return GetEvaluator(srcDesc, dstDesc,
BufferDescriptor(),
BufferDescriptor(),
BufferDescriptor(),
BufferDescriptor(),
BufferDescriptor(),
deviceContext);
}
template <typename DEVICE_CONTEXT>
EVALUATOR *GetEvaluator(BufferDescriptor const &srcDesc,
BufferDescriptor const &dstDesc,
BufferDescriptor const &duDesc,
BufferDescriptor const &dvDesc,
DEVICE_CONTEXT *deviceContext) {
return GetEvaluator(srcDesc, dstDesc,
duDesc, dvDesc,
BufferDescriptor(),
BufferDescriptor(),
BufferDescriptor(),
deviceContext);
}
template <typename DEVICE_CONTEXT>
EVALUATOR *GetEvaluator(BufferDescriptor const &srcDesc,
BufferDescriptor const &dstDesc,
BufferDescriptor const &duDesc,
BufferDescriptor const &dvDesc,
BufferDescriptor const &duuDesc,
BufferDescriptor const &duvDesc,
BufferDescriptor const &dvvDesc,
DEVICE_CONTEXT *deviceContext) {
for(typename Evaluators::iterator it = _evaluators.begin();
it != _evaluators.end(); ++it) {
if (isEqual(srcDesc, it->srcDesc) &&
isEqual(dstDesc, it->dstDesc) &&
isEqual(duDesc, it->duDesc) &&
isEqual(dvDesc, it->dvDesc) &&
isEqual(duuDesc, it->duuDesc) &&
isEqual(duvDesc, it->duvDesc) &&
isEqual(dvvDesc, it->dvvDesc)) {
return it->evaluator;
}
}
EVALUATOR *e = EVALUATOR::Create(srcDesc, dstDesc,
duDesc, dvDesc,
duuDesc, duvDesc, dvvDesc,
deviceContext);
_evaluators.push_back(Entry(srcDesc, dstDesc,
duDesc, dvDesc,
duuDesc, duvDesc, dvvDesc, e));
return e;
}
private:
static bool isEqual(BufferDescriptor const &a,
BufferDescriptor const &b) {
int offsetA = a.stride ? (a.offset % a.stride) : 0;
int offsetB = b.stride ? (b.offset % b.stride) : 0;
// Note: XFB kernel needs to be configured with the local offset
// of the dstDesc to skip preceding primvars.
return (offsetA == offsetB &&
a.length == b.length &&
a.stride == b.stride);
}
Evaluators _evaluators;
};
/// @cond INTERNAL
// template helpers to see if the evaluator is instantiatable or not.
template <typename EVALUATOR>
struct instantiatable
{
typedef char yes[1];
typedef char no[2];
template <typename C> static yes &chk(typename C::Instantiatable *t=0);
template <typename C> static no &chk(...);
static bool const value = sizeof(chk<EVALUATOR>(0)) == sizeof(yes);
};
template <bool C, typename T=void>
struct enable_if { typedef T type; };
template <typename T>
struct enable_if<false, T> { };
/// @endcond
// extract a kernel from cache if available
template <typename EVALUATOR, typename DEVICE_CONTEXT>
static EVALUATOR *GetEvaluator(
EvaluatorCacheT<EVALUATOR> *cache,
BufferDescriptor const &srcDesc,
BufferDescriptor const &dstDesc,
BufferDescriptor const &duDesc,
BufferDescriptor const &dvDesc,
BufferDescriptor const &duuDesc,
BufferDescriptor const &duvDesc,
BufferDescriptor const &dvvDesc,
DEVICE_CONTEXT deviceContext,
typename enable_if<instantiatable<EVALUATOR>::value, void>::type*t=0) {
(void)t;
if (cache == NULL) return NULL;
return cache->GetEvaluator(srcDesc, dstDesc,
duDesc, dvDesc, duuDesc, duvDesc, dvvDesc,
deviceContext);
}
template <typename EVALUATOR, typename DEVICE_CONTEXT>
static EVALUATOR *GetEvaluator(
EvaluatorCacheT<EVALUATOR> *cache,
BufferDescriptor const &srcDesc,
BufferDescriptor const &dstDesc,
BufferDescriptor const &duDesc,
BufferDescriptor const &dvDesc,
DEVICE_CONTEXT deviceContext,
typename enable_if<instantiatable<EVALUATOR>::value, void>::type*t=0) {
(void)t;
if (cache == NULL) return NULL;
return cache->GetEvaluator(srcDesc, dstDesc, duDesc, dvDesc, deviceContext);
}
template <typename EVALUATOR, typename DEVICE_CONTEXT>
static EVALUATOR *GetEvaluator(
EvaluatorCacheT<EVALUATOR> *cache,
BufferDescriptor const &srcDesc,
BufferDescriptor const &dstDesc,
DEVICE_CONTEXT deviceContext,
typename enable_if<instantiatable<EVALUATOR>::value, void>::type*t=0) {
(void)t;
if (cache == NULL) return NULL;
return cache->GetEvaluator(srcDesc, dstDesc,
BufferDescriptor(),
BufferDescriptor(),
deviceContext);
}
// fallback
template <typename EVALUATOR, typename DEVICE_CONTEXT>
static EVALUATOR *GetEvaluator(
EvaluatorCacheT<EVALUATOR> *,
BufferDescriptor const &,
BufferDescriptor const &,
BufferDescriptor const &,
BufferDescriptor const &,
BufferDescriptor const &,
BufferDescriptor const &,
BufferDescriptor const &,
DEVICE_CONTEXT,
typename enable_if<!instantiatable<EVALUATOR>::value, void>::type*t=0) {
(void)t;
return NULL;
}
template <typename EVALUATOR, typename DEVICE_CONTEXT>
static EVALUATOR *GetEvaluator(
EvaluatorCacheT<EVALUATOR> *,
BufferDescriptor const &,
BufferDescriptor const &,
BufferDescriptor const &,
BufferDescriptor const &,
DEVICE_CONTEXT,
typename enable_if<!instantiatable<EVALUATOR>::value, void>::type*t=0) {
(void)t;
return NULL;
}
template <typename EVALUATOR, typename DEVICE_CONTEXT>
static EVALUATOR *GetEvaluator(
EvaluatorCacheT<EVALUATOR> *,
BufferDescriptor const &,
BufferDescriptor const &,
DEVICE_CONTEXT,
typename enable_if<!instantiatable<EVALUATOR>::value, void>::type*t=0) {
(void)t;
return NULL;
}
// ---------------------------------------------------------------------------
template <typename VERTEX_BUFFER,
typename STENCIL_TABLE,
typename EVALUATOR,
typename PATCH_TABLE,
typename DEVICE_CONTEXT = void>
class Mesh : public MeshInterface<PATCH_TABLE> {
public:
typedef VERTEX_BUFFER VertexBuffer;
typedef EVALUATOR Evaluator;
typedef STENCIL_TABLE StencilTable;
typedef PATCH_TABLE PatchTable;
typedef DEVICE_CONTEXT DeviceContext;
typedef EvaluatorCacheT<Evaluator> EvaluatorCache;
typedef typename PatchTable::VertexBufferBinding VertexBufferBinding;
Mesh(Far::TopologyRefiner * refiner,
int numVertexElements,
int numVaryingElements,
int level,
MeshBitset bits = MeshBitset(),
EvaluatorCache * evaluatorCache = NULL,
DeviceContext * deviceContext = NULL) :
_refiner(refiner),
_farPatchTable(NULL),
_numVertices(0),
_maxValence(0),
_vertexBuffer(NULL),
_varyingBuffer(NULL),
_vertexStencilTable(NULL),
_varyingStencilTable(NULL),
_evaluatorCache(evaluatorCache),
_patchTable(NULL),
_deviceContext(deviceContext) {
assert(_refiner);
MeshInterface<PATCH_TABLE>::refineMesh(
*_refiner, level, bits);
int vertexBufferStride = numVertexElements +
(bits.test(MeshInterleaveVarying) ? numVaryingElements : 0);
int varyingBufferStride =
(bits.test(MeshInterleaveVarying) ? 0 : numVaryingElements);
initializeContext(numVertexElements,
numVaryingElements,
level, bits);
initializeVertexBuffers(_numVertices,
vertexBufferStride,
varyingBufferStride);
// configure vertex buffer descriptor
_vertexDesc =
BufferDescriptor(0, numVertexElements, vertexBufferStride);
if (bits.test(MeshInterleaveVarying)) {
_varyingDesc = BufferDescriptor(
numVertexElements, numVaryingElements, vertexBufferStride);
} else {
_varyingDesc = BufferDescriptor(
0, numVaryingElements, varyingBufferStride);
}
}
virtual ~Mesh() {
delete _refiner;
delete _farPatchTable;
delete _vertexBuffer;
delete _varyingBuffer;
delete _vertexStencilTable;
delete _varyingStencilTable;
delete _patchTable;
// deviceContext and evaluatorCache are not owned by this class.
}
virtual void UpdateVertexBuffer(float const *vertexData,
int startVertex, int numVerts) {
_vertexBuffer->UpdateData(vertexData, startVertex, numVerts,
_deviceContext);
}
virtual void UpdateVaryingBuffer(float const *varyingData,
int startVertex, int numVerts) {
_varyingBuffer->UpdateData(varyingData, startVertex, numVerts,
_deviceContext);
}
virtual void Refine() {
int numControlVertices = _refiner->GetLevel(0).GetNumVertices();
BufferDescriptor srcDesc = _vertexDesc;
BufferDescriptor dstDesc(srcDesc);
dstDesc.offset += numControlVertices * dstDesc.stride;
// note that the _evaluatorCache can be NULL and thus
// the evaluatorInstance can be NULL
// (for uninstantiatable kernels CPU,TBB etc)
Evaluator const *instance = GetEvaluator<Evaluator>(
_evaluatorCache, srcDesc, dstDesc,
_deviceContext);
Evaluator::EvalStencils(_vertexBuffer, srcDesc,
_vertexBuffer, dstDesc,
_vertexStencilTable,
instance, _deviceContext);
if (_varyingDesc.length > 0) {
BufferDescriptor vSrcDesc = _varyingDesc;
BufferDescriptor vDstDesc(vSrcDesc);
vDstDesc.offset += numControlVertices * vDstDesc.stride;
instance = GetEvaluator<Evaluator>(
_evaluatorCache, vSrcDesc, vDstDesc,
_deviceContext);
if (_varyingBuffer) {
// non-interleaved
Evaluator::EvalStencils(_varyingBuffer, vSrcDesc,
_varyingBuffer, vDstDesc,
_varyingStencilTable,
instance, _deviceContext);
} else {
// interleaved
Evaluator::EvalStencils(_vertexBuffer, vSrcDesc,
_vertexBuffer, vDstDesc,
_varyingStencilTable,
instance, _deviceContext);
}
}
}
virtual void Synchronize() {
Evaluator::Synchronize(_deviceContext);
}
virtual PatchTable * GetPatchTable() const {
return _patchTable;
}
virtual Far::PatchTable const *GetFarPatchTable() const {
return _farPatchTable;
}
virtual int GetNumVertices() const { return _numVertices; }
virtual int GetMaxValence() const { return _maxValence; }
virtual VertexBufferBinding BindVertexBuffer() {
return _vertexBuffer->BindVBO(_deviceContext);
}
virtual VertexBufferBinding BindVaryingBuffer() {
return _varyingBuffer->BindVBO(_deviceContext);
}
virtual VertexBuffer * GetVertexBuffer() {
return _vertexBuffer;
}
virtual VertexBuffer * GetVaryingBuffer() {
return _varyingBuffer;
}
virtual Far::TopologyRefiner const * GetTopologyRefiner() const {
return _refiner;
}
private:
void initializeContext(int numVertexElements,
int numVaryingElements,
int level, MeshBitset bits) {
assert(_refiner);
Far::StencilTableFactory::Options options;
options.generateOffsets = true;
options.generateIntermediateLevels =
_refiner->IsUniform() ? false : true;
Far::StencilTable const * vertexStencils = NULL;
Far::StencilTable const * varyingStencils = NULL;
if (numVertexElements>0) {
vertexStencils = Far::StencilTableFactory::Create(*_refiner,
options);
}
if (numVaryingElements>0) {
options.interpolationMode =
Far::StencilTableFactory::INTERPOLATE_VARYING;
varyingStencils = Far::StencilTableFactory::Create(*_refiner,
options);
}
Far::PatchTableFactory::Options poptions(level);
poptions.generateFVarTables = bits.test(MeshFVarData);
poptions.generateFVarLegacyLinearPatches = !bits.test(MeshFVarAdaptive);
poptions.generateLegacySharpCornerPatches = !bits.test(MeshUseSmoothCornerPatch);
poptions.useSingleCreasePatch = bits.test(MeshUseSingleCreasePatch);
poptions.useInfSharpPatch = bits.test(MeshUseInfSharpPatch);
// points on bilinear and gregory basis endcap boundaries can be
// shared among adjacent patches to save some stencils.
if (bits.test(MeshEndCapBilinearBasis)) {
poptions.SetEndCapType(
Far::PatchTableFactory::Options::ENDCAP_BILINEAR_BASIS);
poptions.shareEndCapPatchPoints = true;
} else if (bits.test(MeshEndCapBSplineBasis)) {
poptions.SetEndCapType(
Far::PatchTableFactory::Options::ENDCAP_BSPLINE_BASIS);
} else if (bits.test(MeshEndCapGregoryBasis)) {
poptions.SetEndCapType(
Far::PatchTableFactory::Options::ENDCAP_GREGORY_BASIS);
poptions.shareEndCapPatchPoints = true;
} else if (bits.test(MeshEndCapLegacyGregory)) {
poptions.SetEndCapType(
Far::PatchTableFactory::Options::ENDCAP_LEGACY_GREGORY);
}
_farPatchTable = Far::PatchTableFactory::Create(*_refiner, poptions);
// if there's endcap stencils, merge it into regular stencils.
if (_farPatchTable->GetLocalPointStencilTable()) {
// append stencils
if (Far::StencilTable const *vertexStencilsWithLocalPoints =
Far::StencilTableFactory::AppendLocalPointStencilTable(
*_refiner,
vertexStencils,
_farPatchTable->GetLocalPointStencilTable())) {
delete vertexStencils;
vertexStencils = vertexStencilsWithLocalPoints;
}
if (varyingStencils) {
if (Far::StencilTable const *varyingStencilsWithLocalPoints =
Far::StencilTableFactory::AppendLocalPointStencilTable(
*_refiner,
varyingStencils,
_farPatchTable->GetLocalPointVaryingStencilTable())) {
delete varyingStencils;
varyingStencils = varyingStencilsWithLocalPoints;
}
}
}
_maxValence = _farPatchTable->GetMaxValence();
_patchTable = PatchTable::Create(_farPatchTable, _deviceContext);
// numvertices = coarse verts + refined verts + gregory basis verts
_numVertices = vertexStencils->GetNumControlVertices()
+ vertexStencils->GetNumStencils();
// convert to device stenciltable if necessary.
_vertexStencilTable =
convertToCompatibleStencilTable<StencilTable>(
vertexStencils, _deviceContext);
_varyingStencilTable =
convertToCompatibleStencilTable<StencilTable>(
varyingStencils, _deviceContext);
// FIXME: we do extra copyings for Far::Stencils.
delete vertexStencils;
delete varyingStencils;
}
void initializeVertexBuffers(int numVertices,
int numVertexElements,
int numVaryingElements) {
if (numVertexElements) {
_vertexBuffer = VertexBuffer::Create(numVertexElements,
numVertices, _deviceContext);
}
if (numVaryingElements) {
_varyingBuffer = VertexBuffer::Create(numVaryingElements,
numVertices, _deviceContext);
}
}
Far::TopologyRefiner * _refiner;
Far::PatchTable * _farPatchTable;
int _numVertices;
int _maxValence;
VertexBuffer * _vertexBuffer;
VertexBuffer * _varyingBuffer;
BufferDescriptor _vertexDesc;
BufferDescriptor _varyingDesc;
StencilTable const * _vertexStencilTable;
StencilTable const * _varyingStencilTable;
EvaluatorCache * _evaluatorCache;
PatchTable *_patchTable;
DeviceContext *_deviceContext;
};
} // end namespace Osd
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_OSD_MESH_H
+52
View File
@@ -0,0 +1,52 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_OSD_NON_COPYABLE_H
#define OPENSUBDIV3_OSD_NON_COPYABLE_H
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Osd {
template <class T>
class NonCopyable {
protected:
NonCopyable() {}
~NonCopyable() {}
private:
NonCopyable(const NonCopyable &);
T & operator = (const T &);
};
} // end namespace Osd
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_OSD_NON_COPYABLE_H
+53
View File
@@ -0,0 +1,53 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_OSD_OPENGL_H
#define OPENSUBDIV3_OSD_OPENGL_H
#if defined(__APPLE__)
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
#include <OpenGLES/ES2/gl.h>
#else
#if defined(OSD_USES_GLEW)
#include <GL/glew.h>
#else
#include <OpenGL/gl3.h>
#endif
#endif
#elif defined(ANDROID)
#include <GLES2/gl2.h>
#else
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#if defined(OSD_USES_GLEW)
#include <GL/glew.h>
#else
#include <GL/gl.h>
#endif
#endif
#endif // OPENSUBDIV3_OSD_OPENGL_H
+143
View File
@@ -0,0 +1,143 @@
//
// Copyright 2015 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_OSD_TYPES_H
#define OPENSUBDIV3_OSD_TYPES_H
#include "../version.h"
#include "../far/patchTable.h"
#include <algorithm>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Osd {
/// \brief Coordinates set on a patch table
///
/// XXX: this class may be moved into Far
///
struct PatchCoord {
// 5-ints struct.
/// \brief Constructor
///
/// @param handleArg patch handle
///
/// @param sArg parametric location on the patch
///
/// @param tArg parametric location on the patch
///
PatchCoord(Far::PatchTable::PatchHandle handleArg, float sArg, float tArg) :
handle(handleArg), s(sArg), t(tArg) { }
PatchCoord() : s(0), t(0) {
handle.arrayIndex = 0;
handle.patchIndex = 0;
handle.vertIndex = 0;
}
Far::PatchTable::PatchHandle handle; ///< patch handle
float s, t; ///< parametric location on patch
};
struct PatchArray {
// 4-ints struct.
PatchArray(Far::PatchDescriptor desc_in,
int numPatches_in, int indexBase_in, int primitiveIdBase_in) :
regDesc(desc_in), desc(desc_in),
numPatches(numPatches_in), indexBase(indexBase_in),
stride(desc_in.GetNumControlVertices()),
primitiveIdBase(primitiveIdBase_in) {}
PatchArray(Far::PatchDescriptor regDesc_in, Far::PatchDescriptor irregDesc_in,
int numPatches_in, int indexBase_in, int primitiveIdBase_in) :
regDesc(regDesc_in), desc(irregDesc_in),
numPatches(numPatches_in), indexBase(indexBase_in),
stride(std::max(regDesc_in.GetNumControlVertices(),
irregDesc_in.GetNumControlVertices())),
primitiveIdBase(primitiveIdBase_in) {}
Far::PatchDescriptor const &GetDescriptor() const {
return desc;
}
Far::PatchDescriptor const &GetDescriptorRegular() const {
return regDesc;
}
Far::PatchDescriptor const &GetDescriptorIrregular() const {
return desc;
}
int GetPatchType() const {
return desc.GetType();
}
int GetPatchTypeRegular() const {
return regDesc.GetType();
}
int GetPatchTypeIrregular() const {
return desc.GetType();
}
int GetNumPatches() const {
return numPatches;
}
int GetIndexBase() const {
return indexBase;
}
int GetStride() const {
return stride;
}
int GetPrimitiveIdBase() const {
return primitiveIdBase;
}
// Separate regular and irregular patch descriptors for cases where the
// array is mixed -- both will be equal if only a single type specified
Far::PatchDescriptor regDesc;
Far::PatchDescriptor desc;
int numPatches;
int indexBase; // an offset within the index buffer
int stride; // stride in buffer between patches
int primitiveIdBase; // an offset within the patch param buffer
};
struct PatchParam : public Far::PatchParam {
// int3 struct.
float sharpness;
};
typedef std::vector<PatchArray> PatchArrayVector;
typedef std::vector<PatchParam> PatchParamVector;
} // end namespace Osd
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_OSD_TYPES_H
+164
View File
@@ -0,0 +1,164 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_SDC_BILINEAR_SCHEME_H
#define OPENSUBDIV3_SDC_BILINEAR_SCHEME_H
#include "../version.h"
#include "../sdc/scheme.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Sdc {
//
// Specializations for Scheme<SCHEME_BILINEAR>:
//
//
// Bilinear traits:
//
template <>
inline Split Scheme<SCHEME_BILINEAR>::GetTopologicalSplitType() { return SPLIT_TO_QUADS; }
template <>
inline int Scheme<SCHEME_BILINEAR>::GetRegularFaceSize() { return 4; }
template <>
inline int Scheme<SCHEME_BILINEAR>::GetRegularVertexValence() { return 4; }
template <>
inline int Scheme<SCHEME_BILINEAR>::GetLocalNeighborhoodSize() { return 0; }
//
// Refinement masks:
//
template <>
template <typename EDGE, typename MASK>
void
Scheme<SCHEME_BILINEAR>::ComputeEdgeVertexMask(EDGE const& edge, MASK& mask,
Crease::Rule, Crease::Rule) const {
// This should be inline, otherwise trivially replicate it:
assignCreaseMaskForEdge(edge, mask);
}
template <>
template <typename VERTEX, typename MASK>
void
Scheme<SCHEME_BILINEAR>::ComputeVertexVertexMask(VERTEX const& vertex, MASK& mask,
Crease::Rule, Crease::Rule) const {
// This should be inline, otherwise trivially replicate it:
assignCornerMaskForVertex(vertex, mask);
}
//
// Limit masks for position -- the limit position of all vertices is the refined vertex.
//
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_BILINEAR>::assignCornerLimitMask(VERTEX const& /* vertex */, MASK& posMask) const {
posMask.SetNumVertexWeights(1);
posMask.SetNumEdgeWeights(0);
posMask.SetNumFaceWeights(0);
posMask.SetFaceWeightsForFaceCenters(false);
posMask.VertexWeight(0) = 1.0f;
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_BILINEAR>::assignCreaseLimitMask(VERTEX const& vertex, MASK& posMask,
int const /* creaseEnds */[2]) const {
assignCornerLimitMask(vertex, posMask);
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_BILINEAR>::assignSmoothLimitMask(VERTEX const& vertex, MASK& posMask) const {
assignCornerLimitMask(vertex, posMask);
}
//
// Limit masks for tangents -- these are ambiguous around all vertices. Provide
// the tangents based on the incident edges of the first face.
//
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_BILINEAR>::assignCornerLimitTangentMasks(VERTEX const& /* vertex */,
MASK& tan1Mask, MASK& tan2Mask) const {
tan1Mask.SetNumVertexWeights(1);
tan1Mask.SetNumEdgeWeights(2);
tan1Mask.SetNumFaceWeights(0);
tan1Mask.SetFaceWeightsForFaceCenters(false);
tan2Mask.SetNumVertexWeights(1);
tan2Mask.SetNumEdgeWeights(2);
tan2Mask.SetNumFaceWeights(0);
tan2Mask.SetFaceWeightsForFaceCenters(false);
tan1Mask.VertexWeight(0) = -1.0f;
tan1Mask.EdgeWeight(0) = 1.0f;
tan1Mask.EdgeWeight(1) = 0.0f;
tan2Mask.VertexWeight(0) = -1.0f;
tan2Mask.EdgeWeight(0) = 0.0f;
tan2Mask.EdgeWeight(1) = 1.0f;
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_BILINEAR>::assignCreaseLimitTangentMasks(VERTEX const& vertex,
MASK& tan1Mask, MASK& tan2Mask, int const /* creaseEnds */[2]) const {
assignCornerLimitTangentMasks(vertex, tan1Mask, tan2Mask);
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_BILINEAR>::assignSmoothLimitTangentMasks(VERTEX const& vertex,
MASK& tan1Mask, MASK& tan2Mask) const {
assignCornerLimitTangentMasks(vertex, tan1Mask, tan2Mask);
}
} // end namespace sdc
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_SDC_BILINEAR_SCHEME_H */
+534
View File
@@ -0,0 +1,534 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_SDC_CATMARK_SCHEME_H
#define OPENSUBDIV3_SDC_CATMARK_SCHEME_H
#include "../version.h"
#include "../sdc/scheme.h"
#include <cassert>
#include <cmath>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Sdc {
//
// Specializations for Scheme<SCHEME_CATMARK>:
//
//
// Catmark traits:
//
template <>
inline Split Scheme<SCHEME_CATMARK>::GetTopologicalSplitType() { return SPLIT_TO_QUADS; }
template <>
inline int Scheme<SCHEME_CATMARK>::GetRegularFaceSize() { return 4; }
template <>
inline int Scheme<SCHEME_CATMARK>::GetRegularVertexValence() { return 4; }
template <>
inline int Scheme<SCHEME_CATMARK>::GetLocalNeighborhoodSize() { return 1; }
//
// Masks for edge-vertices: the hard Crease mask does not need to be specialized
// (simply the midpoint), so all that is left is the Smooth case:
//
// The Smooth mask is complicated by the need to support the "triangle subdivision"
// option, which applies different weighting in the presence of triangles. It is
// up for debate as to whether this is useful or not -- we may be able to deprecate
// this option.
//
template <>
template <typename EDGE, typename MASK>
inline void
Scheme<SCHEME_CATMARK>::assignSmoothMaskForEdge(EDGE const& edge, MASK& mask) const {
typedef typename MASK::Weight Weight;
int faceCount = edge.GetNumFaces();
mask.SetNumVertexWeights(2);
mask.SetNumEdgeWeights(0);
mask.SetNumFaceWeights(faceCount);
mask.SetFaceWeightsForFaceCenters(true);
//
// Determine if we need to inspect incident faces and apply alternate weighting for
// triangles -- and if so, determine which of the two are triangles.
//
bool face0IsTri = false;
bool face1IsTri = false;
bool useTriangleOption = (_options.GetTriangleSubdivision() == Options::TRI_SUB_SMOOTH);
if (useTriangleOption) {
if (faceCount == 2) {
//
// Ideally we want to avoid this inspection when we have already subdivided at
// least once -- need something in the Edge interface to help avoid this, e.g.
// an IsRegular() query, the subdivision level...
//
int vertsPerFace[2];
edge.GetNumVerticesPerFace(vertsPerFace);
face0IsTri = (vertsPerFace[0] == 3);
face1IsTri = (vertsPerFace[1] == 3);
useTriangleOption = face0IsTri || face1IsTri;
} else {
useTriangleOption = false;
}
}
if (! useTriangleOption) {
mask.VertexWeight(0) = 0.25f;
mask.VertexWeight(1) = 0.25f;
if (faceCount == 2) {
mask.FaceWeight(0) = 0.25f;
mask.FaceWeight(1) = 0.25f;
} else {
Weight fWeight = 0.5f / (Weight)faceCount;
for (int i = 0; i < faceCount; ++i) {
mask.FaceWeight(i) = fWeight;
}
}
} else {
//
// This mimics the implementation in Hbr in terms of order of operations.
//
const Weight CATMARK_SMOOTH_TRI_EDGE_WEIGHT = (Weight) 0.470;
Weight f0Weight = face0IsTri ? CATMARK_SMOOTH_TRI_EDGE_WEIGHT : 0.25f;
Weight f1Weight = face1IsTri ? CATMARK_SMOOTH_TRI_EDGE_WEIGHT : 0.25f;
Weight fWeight = 0.5f * (f0Weight + f1Weight);
Weight vWeight = 0.5f * (1.0f - 2.0f * fWeight);
mask.VertexWeight(0) = vWeight;
mask.VertexWeight(1) = vWeight;
mask.FaceWeight(0) = fWeight;
mask.FaceWeight(1) = fWeight;
}
}
//
// Masks for vertex-vertices: the hard Corner mask does not need to be specialized
// (simply the vertex itself), leaving the Crease and Smooth cases (Dart is smooth):
//
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_CATMARK>::assignCreaseMaskForVertex(VERTEX const& vertex, MASK& mask,
int const creaseEnds[2]) const {
typedef typename MASK::Weight Weight;
int valence = vertex.GetNumEdges();
mask.SetNumVertexWeights(1);
mask.SetNumEdgeWeights(valence);
mask.SetNumFaceWeights(0);
mask.SetFaceWeightsForFaceCenters(false);
Weight vWeight = 0.75f;
Weight eWeight = 0.125f;
mask.VertexWeight(0) = vWeight;
for (int i = 0; i < valence; ++i) {
mask.EdgeWeight(i) = 0.0f;
}
mask.EdgeWeight(creaseEnds[0]) = eWeight;
mask.EdgeWeight(creaseEnds[1]) = eWeight;
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_CATMARK>::assignSmoothMaskForVertex(VERTEX const& vertex, MASK& mask) const {
typedef typename MASK::Weight Weight;
//
// A Smooth vertex must be manifold and interior -- manifold boundary vertices will be
// Creases and non-manifold vertices of any kind will be Corners or Creases. If smooth
// rules for non-manifold vertices are ever defined, this will need adjusting:
//
assert(vertex.GetNumFaces() == vertex.GetNumEdges());
int valence = vertex.GetNumFaces();
mask.SetNumVertexWeights(1);
mask.SetNumEdgeWeights(valence);
mask.SetNumFaceWeights(valence);
mask.SetFaceWeightsForFaceCenters(true);
Weight vWeight = (Weight)(valence - 2) / (Weight)valence;
Weight fWeight = 1.0f / (Weight)(valence * valence);
Weight eWeight = fWeight;
mask.VertexWeight(0) = vWeight;
for (int i = 0; i < valence; ++i) {
mask.EdgeWeight(i) = eWeight;
mask.FaceWeight(i) = fWeight;
}
}
//
// Limit masks for position:
//
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_CATMARK>::assignCornerLimitMask(VERTEX const& /* vertex */, MASK& posMask) const {
posMask.SetNumVertexWeights(1);
posMask.SetNumEdgeWeights(0);
posMask.SetNumFaceWeights(0);
posMask.SetFaceWeightsForFaceCenters(false);
posMask.VertexWeight(0) = 1.0f;
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_CATMARK>::assignCreaseLimitMask(VERTEX const& vertex, MASK& posMask,
int const creaseEnds[2]) const {
typedef typename MASK::Weight Weight;
int valence = vertex.GetNumEdges();
posMask.SetNumVertexWeights(1);
posMask.SetNumEdgeWeights(valence);
posMask.SetNumFaceWeights(0);
posMask.SetFaceWeightsForFaceCenters(false);
Weight vWeight = (Weight)(2.0 / 3.0);
Weight eWeight = (Weight)(1.0 / 6.0);
posMask.VertexWeight(0) = vWeight;
for (int i = 0; i < valence; ++i) {
posMask.EdgeWeight(i) = 0.0f;
}
posMask.EdgeWeight(creaseEnds[0]) = eWeight;
posMask.EdgeWeight(creaseEnds[1]) = eWeight;
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_CATMARK>::assignSmoothLimitMask(VERTEX const& vertex, MASK& posMask) const {
typedef typename MASK::Weight Weight;
int valence = vertex.GetNumFaces();
if (valence == 2) {
assignCornerLimitMask(vertex, posMask);
return;
}
posMask.SetNumVertexWeights(1);
posMask.SetNumEdgeWeights(valence);
posMask.SetNumFaceWeights(valence);
posMask.SetFaceWeightsForFaceCenters(false);
// Specialize for the regular case:
if (valence == 4) {
Weight fWeight = (Weight)(1.0 / 36.0);
Weight eWeight = (Weight)(1.0 / 9.0);
Weight vWeight = (Weight)(4.0 / 9.0);
posMask.VertexWeight(0) = vWeight;
posMask.EdgeWeight(0) = eWeight;
posMask.EdgeWeight(1) = eWeight;
posMask.EdgeWeight(2) = eWeight;
posMask.EdgeWeight(3) = eWeight;
posMask.FaceWeight(0) = fWeight;
posMask.FaceWeight(1) = fWeight;
posMask.FaceWeight(2) = fWeight;
posMask.FaceWeight(3) = fWeight;
} else {
Weight fWeight = 1.0f / (Weight)(valence * (valence + 5.0f));
Weight eWeight = 4.0f * fWeight;
Weight vWeight = (Weight)(1.0f - valence * (eWeight + fWeight));
posMask.VertexWeight(0) = vWeight;
for (int i = 0; i < valence; ++i) {
posMask.EdgeWeight(i) = eWeight;
posMask.FaceWeight(i) = fWeight;
}
}
}
//
// Limit masks for tangents -- these are stubs for now, or have a temporary
// implementation
//
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_CATMARK>::assignCornerLimitTangentMasks(VERTEX const& vertex,
MASK& tan1Mask, MASK& tan2Mask) const {
int valence = vertex.GetNumEdges();
tan1Mask.SetNumVertexWeights(1);
tan1Mask.SetNumEdgeWeights(valence);
tan1Mask.SetNumFaceWeights(0);
tan1Mask.SetFaceWeightsForFaceCenters(false);
tan2Mask.SetNumVertexWeights(1);
tan2Mask.SetNumEdgeWeights(valence);
tan2Mask.SetNumFaceWeights(0);
tan2Mask.SetFaceWeightsForFaceCenters(false);
// Should be at least 2 edges -- be sure to clear weights for any more:
tan1Mask.VertexWeight(0) = -1.0f;
tan1Mask.EdgeWeight(0) = 1.0f;
tan1Mask.EdgeWeight(1) = 0.0f;
tan2Mask.VertexWeight(0) = -1.0f;
tan2Mask.EdgeWeight(0) = 0.0f;
tan2Mask.EdgeWeight(1) = 1.0f;
for (int i = 2; i < valence; ++i) {
tan1Mask.EdgeWeight(i) = 0.0f;
tan2Mask.EdgeWeight(i) = 0.0f;
}
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_CATMARK>::assignCreaseLimitTangentMasks(VERTEX const& vertex,
MASK& tan1Mask, MASK& tan2Mask, int const creaseEnds[2]) const {
typedef typename MASK::Weight Weight;
//
// First, the tangent along the crease:
// The first crease edge is considered the "leading" edge of the span
// of surface for which we are evaluating tangents and the second edge the
// "trailing edge". By convention, the tangent along the crease is oriented
// in the direction of the leading edge.
//
int numEdges = vertex.GetNumEdges();
int numFaces = vertex.GetNumFaces();
tan1Mask.SetNumVertexWeights(1);
tan1Mask.SetNumEdgeWeights(numEdges);
tan1Mask.SetNumFaceWeights(numFaces);
tan1Mask.SetFaceWeightsForFaceCenters(false);
tan1Mask.VertexWeight(0) = 0.0f;
for (int i = 0; i < numEdges; ++i) {
tan1Mask.EdgeWeight(i) = 0.0f;
}
for (int i = 0; i < numFaces; ++i) {
tan1Mask.FaceWeight(i) = 0.0f;
}
tan1Mask.EdgeWeight(creaseEnds[0]) = 0.5f;
tan1Mask.EdgeWeight(creaseEnds[1]) = -0.5f;
//
// Second, the tangent across the interior faces:
// Note this is ambiguous for an interior vertex. We currently return
// the tangent for the surface in the counter-clockwise span between the
// leading and trailing edges that form the crease. Given the expected
// computation of a surface normal as Tan1 X Tan2, this tangent should be
// oriented "inward" from the crease/boundary -- across the surface rather
// than outward and away from it.
//
tan2Mask.SetNumVertexWeights(1);
tan2Mask.SetNumEdgeWeights(numEdges);
tan2Mask.SetNumFaceWeights(numFaces);
tan2Mask.SetFaceWeightsForFaceCenters(false);
// Prepend weights of 0 preceding the crease:
for (int i = 0; i < creaseEnds[0]; ++i) {
tan2Mask.EdgeWeight(i) = 0.0f;
tan2Mask.FaceWeight(i) = 0.0f;
}
// Assign weights to crease edge and interior points:
int interiorEdgeCount = creaseEnds[1] - creaseEnds[0] - 1;
if (interiorEdgeCount == 1) {
// The regular case -- uniform B-spline cross-tangent:
tan2Mask.VertexWeight(0) = (Weight)(-4.0 / 6.0);
tan2Mask.EdgeWeight(creaseEnds[0]) = (Weight)(-1.0 / 6.0);
tan2Mask.EdgeWeight(creaseEnds[0] + 1) = (Weight)( 4.0 / 6.0);
tan2Mask.EdgeWeight(creaseEnds[1]) = (Weight)(-1.0 / 6.0);
tan2Mask.FaceWeight(creaseEnds[0]) = (Weight)(1.0 / 6.0);
tan2Mask.FaceWeight(creaseEnds[0] + 1) = (Weight)(1.0 / 6.0);
} else if (interiorEdgeCount > 1) {
// The irregular case -- formulae from Biermann et al:
double k = (double) (interiorEdgeCount + 1);
double theta = M_PI / k;
double cosTheta = std::cos(theta);
double sinTheta = std::sin(theta);
// Loop/Schaefer use a different divisor here (3*k + cos(theta)):
double commonDenom = 1.0f / (k * (3.0f + cosTheta));
double R = (cosTheta + 1.0f) / sinTheta;
double vertexWeight = 4.0f * R * (cosTheta - 1.0f);
double creaseWeight = -R * (1.0f + 2.0f * cosTheta);
tan2Mask.VertexWeight(0) = (Weight) (vertexWeight * commonDenom);
tan2Mask.EdgeWeight(creaseEnds[0]) = (Weight) (creaseWeight * commonDenom);
tan2Mask.EdgeWeight(creaseEnds[1]) = (Weight) (creaseWeight * commonDenom);
tan2Mask.FaceWeight(creaseEnds[0]) = (Weight) (sinTheta * commonDenom);
double sinThetaI = 0.0f;
double sinThetaIplus1 = sinTheta;
for (int i = 1; i < k; ++i) {
sinThetaI = sinThetaIplus1;
sinThetaIplus1 = std::sin((i+1)*theta);
tan2Mask.EdgeWeight(creaseEnds[0] + i) = (Weight) ((4.0f * sinThetaI) * commonDenom);
tan2Mask.FaceWeight(creaseEnds[0] + i) = (Weight) ((sinThetaI + sinThetaIplus1) * commonDenom);
}
} else {
// Special case for a single face -- simple average of boundary edges:
tan2Mask.VertexWeight(0) = -6.0f;
tan2Mask.EdgeWeight(creaseEnds[0]) = 3.0f;
tan2Mask.EdgeWeight(creaseEnds[1]) = 3.0f;
tan2Mask.FaceWeight(creaseEnds[0]) = 0.0f;
}
// Append weights of 0 following the crease:
for (int i = creaseEnds[1]; i < numFaces; ++i) {
tan2Mask.FaceWeight(i) = 0.0f;
}
for (int i = creaseEnds[1] + 1; i < numEdges; ++i) {
tan2Mask.EdgeWeight(i) = 0.0f;
}
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_CATMARK>::assignSmoothLimitTangentMasks(VERTEX const& vertex,
MASK& tan1Mask, MASK& tan2Mask) const {
typedef typename MASK::Weight Weight;
int valence = vertex.GetNumFaces();
if (valence == 2) {
assignCornerLimitTangentMasks(vertex, tan1Mask, tan2Mask);
return;
}
// Compute tan1 initially -- tan2 is simply a rotation:
tan1Mask.SetNumVertexWeights(1);
tan1Mask.SetNumEdgeWeights(valence);
tan1Mask.SetNumFaceWeights(valence);
tan1Mask.SetFaceWeightsForFaceCenters(false);
tan1Mask.VertexWeight(0) = 0.0f;
if (valence == 4) {
tan1Mask.EdgeWeight(0) = 4.0f;
tan1Mask.EdgeWeight(1) = 0.0f;
tan1Mask.EdgeWeight(2) = -4.0f;
tan1Mask.EdgeWeight(3) = 0.0f;
tan1Mask.FaceWeight(0) = 1.0f;
tan1Mask.FaceWeight(1) = -1.0f;
tan1Mask.FaceWeight(2) = -1.0f;
tan1Mask.FaceWeight(3) = 1.0f;
} else {
double theta = 2.0f * M_PI / (double)valence;
double cosTheta = std::cos(theta);
double cosHalfTheta = std::cos(theta * 0.5f);
double lambda = (5.0 / 16.0) + (1.0 / 16.0) *
(cosTheta + cosHalfTheta * std::sqrt(2.0f * (9.0f + cosTheta)));
double edgeWeightScale = 4.0f;
double faceWeightScale = 1.0f / (4.0f * lambda - 1.0f);
for (int i = 0; i < valence; ++i) {
double cosThetaI = std::cos( i * theta);
double cosThetaIplus1 = std::cos((i+1)* theta);
tan1Mask.EdgeWeight(i) = (Weight) (edgeWeightScale * cosThetaI);
tan1Mask.FaceWeight(i) = (Weight) (faceWeightScale * (cosThetaI + cosThetaIplus1));
}
}
// Now rotate/copy tan1 weights to tan2:
tan2Mask.SetNumVertexWeights(1);
tan2Mask.SetNumEdgeWeights(valence);
tan2Mask.SetNumFaceWeights(valence);
tan2Mask.SetFaceWeightsForFaceCenters(false);
tan2Mask.VertexWeight(0) = 0.0f;
if (valence == 4) {
tan2Mask.EdgeWeight(0) = 0.0f;
tan2Mask.EdgeWeight(1) = 4.0f;
tan2Mask.EdgeWeight(2) = 0.0f;
tan2Mask.EdgeWeight(3) = -4.0f;
tan2Mask.FaceWeight(0) = 1.0f;
tan2Mask.FaceWeight(1) = 1.0f;
tan2Mask.FaceWeight(2) = -1.0f;
tan2Mask.FaceWeight(3) = -1.0f;
} else {
tan2Mask.EdgeWeight(0) = tan1Mask.EdgeWeight(valence-1);
tan2Mask.FaceWeight(0) = tan1Mask.FaceWeight(valence-1);
for (int i = 1; i < valence; ++i) {
tan2Mask.EdgeWeight(i) = tan1Mask.EdgeWeight(i-1);
tan2Mask.FaceWeight(i) = tan1Mask.FaceWeight(i-1);
}
}
}
} // end namespace sdc
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_SDC_CATMARK_SCHEME_H */
+247
View File
@@ -0,0 +1,247 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_SDC_CREASE_H
#define OPENSUBDIV3_SDC_CREASE_H
#include "../version.h"
#include "../sdc/options.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Sdc {
///
/// \brief Types, constants and utilities related to semi-sharp creasing -- whose implementation
/// is independent of the subdivision scheme.
///
/// Crease is intended to be a light-weight, trivially constructed class that computes
/// crease-related properties -- typically sharpness values and associated interpolation
/// weights. An instance of Crease is defined with a set of options that include current
/// and future variations that will impact computations involving sharpness values.
///
/// The Crease methods do not use topological neighborhoods as input. The methods here
/// rely more on the sharpness values and less on the topology, so we choose to work directly
/// with the sharpness values. We also follow the trend of using primitive arrays in the
/// interface to encourage local gathering for re-use.
///
/// Note on the need for and use of sharpness values:
/// In general, mask queries rely on the sharpness values. The common case of a smooth
/// vertex, when known, avoids the need to inspect them, but unless the rules are well understood,
/// users will be expected to provided them -- particularly when they expect the mask queries
/// to do all of the work (just determining if a vertex is smooth will require inspection of
/// incident edge sharpness).
/// Mask queries will occasionally require the subdivided sharpness values around the
/// child vertex. So users will be expected to either provide them up front when known, or to be
/// gathered on demand. Any implementation of subdivision with creasing cannot avoid subdividing
/// the sharpness values first, so keeping them available for re-use is a worthwhile consideration.
///
class Crease {
public:
//@{
/// Constants and related queries of sharpness values:
///
static float const SHARPNESS_SMOOTH; // = 0.0f, do we really need this?
static float const SHARPNESS_INFINITE; // = 10.0f;
static bool IsSmooth(float sharpness) { return sharpness <= SHARPNESS_SMOOTH; }
static bool IsSharp(float sharpness) { return sharpness > SHARPNESS_SMOOTH; }
static bool IsInfinite(float sharpness) { return sharpness >= SHARPNESS_INFINITE; }
static bool IsSemiSharp(float sharpness) { return (SHARPNESS_SMOOTH < sharpness) && (sharpness < SHARPNESS_INFINITE); }
//@}
///
/// Enum for the types of subdivision rules applied based on sharpness values (note these
/// correspond to Hbr's vertex "mask"). The values are assigned to bit positions as it is
/// useful to use bitwise operations to inspect collections of vertices (i.e. all of the
/// vertices incident a particular face).
///
enum Rule {
RULE_UNKNOWN = 0,
RULE_SMOOTH = (1 << 0),
RULE_DART = (1 << 1),
RULE_CREASE = (1 << 2),
RULE_CORNER = (1 << 3)
};
public:
Crease() : _options() { }
Crease(Options const& options) : _options(options) { }
~Crease() { }
bool IsUniform() const { return _options.GetCreasingMethod() == Options::CREASE_UNIFORM; }
//@{
/// Optional sharp features:
/// Since options treat certain topological features as infinitely sharp -- boundaries
/// or (in future) non-manifold features -- sharpness values should be adjusted before use.
/// The following methods will adjust (by return) specific values according to the options
/// applied.
///
float SharpenBoundaryEdge(float edgeSharpness) const;
float SharpenBoundaryVertex(float edgeSharpness) const;
// For future consideration
//float SharpenNonManifoldEdge(float edgeSharpness) const;
//float SharpenNonManifoldVertex(float edgeSharpness) const;
//@}
//@{
/// Sharpness subdivision:
/// The computation of a Uniform subdivided sharpness value is as follows:
/// - Smooth edges or verts stay Smooth
/// - Sharp edges or verts stay Sharp
/// - semi-sharp edges or verts are decremented by 1.0
/// but for Chaikin (and potentially future non-uniform schemes that improve upon it) the
/// computation is more involved. In the case of edges in particular, the sharpness of a
/// child edge is determined by the sharpness in the neighborhood of the end vertex
/// corresponding to the child. For this reason, an alternative to subdividing sharpness
/// that computes all child edges around a vertex is given.
///
float SubdivideUniformSharpness(float vertexOrEdgeSharpness) const;
float SubdivideVertexSharpness(float vertexSharpness) const;
float SubdivideEdgeSharpnessAtVertex(float edgeSharpness,
int incidentEdgeCountAtEndVertex,
float const* edgeSharpnessAroundEndVertex) const;
void SubdivideEdgeSharpnessesAroundVertex(int incidentEdgeCountAtVertex,
float const* incidentEdgeSharpnessAroundVertex,
float* childEdgesSharpnessAroundVertex) const;
//@}
//@{
/// Rule determination:
/// Mask queries do not require the Rule to be known, it can be determined from
/// the information provided, but it is generally more efficient when the Rule is known
/// and provided. In particular, the Smooth case dominates and is known to be applicable
/// based on the origin of the vertex without inspection of sharpness.
///
Rule DetermineVertexVertexRule(float vertexSharpness,
int incidentEdgeCount,
float const* incidentEdgeSharpness) const;
Rule DetermineVertexVertexRule(float vertexSharpness,
int sharpEdgeCount) const;
//@}
/// \brief Transitional weighting:
/// When the rules applicable to a parent vertex and its child differ, one or more
/// sharpness values has "decayed" to zero. Both rules are then applicable and blended
/// by a weight between 0 and 1 that reflects the transition. Most often this will be
/// a single sharpness value that decays from within the interval [0,1] to zero -- and
/// the weight to apply is exactly that sharpness value -- but more than one may decay,
/// and values > 1 may also decay to 0 in a single step while others within [0,1] may
/// remain > 0.
/// So to properly determine a transitional weight, sharpness values for both the
/// parent and child must be inspected, combined and clamped accordingly.
///
float ComputeFractionalWeightAtVertex(float vertexSharpness,
float childVertexSharpness,
int incidentEdgeCount,
float const* incidentEdgeSharpness,
float const* childEdgesSharpness) const;
void GetSharpEdgePairOfCrease(float const * incidentEdgeSharpness,
int incidentEdgeCount,
int sharpEdgePair[2]) const;
// Would these really help? Maybe only need Rules for the vertex-vertex case...
//
// Rule DetermineEdgeVertexRule(float parentEdgeSharpness) const;
// Rule DetermineEdgeVertexRule(float childEdge1Sharpness, float childEdge2Sharpness) const;
protected:
float decrementSharpness(float sharpness) const;
private:
Options _options;
};
//
// Inline declarations:
//
inline float
Crease::SharpenBoundaryEdge(float /* edgeSharpness */) const {
//
// Despite the presence of the BOUNDARY_NONE option, boundary edges are always sharpened.
// Much of the code relies on sharpness to indicate boundaries to avoid the more complex
// topological inspection
//
return SHARPNESS_INFINITE;
}
inline float
Crease::SharpenBoundaryVertex(float vertexSharpness) const {
return (_options.GetVtxBoundaryInterpolation() == Options::VTX_BOUNDARY_EDGE_AND_CORNER) ?
SHARPNESS_INFINITE : vertexSharpness;
}
inline float
Crease::decrementSharpness(float sharpness) const {
if (IsSmooth(sharpness)) return Crease::SHARPNESS_SMOOTH; // redundant but most common
if (IsInfinite(sharpness)) return Crease::SHARPNESS_INFINITE;
if (sharpness > 1.0f) return (sharpness - 1.0f);
return Crease::SHARPNESS_SMOOTH;
}
inline float
Crease::SubdivideUniformSharpness(float vertexOrEdgeSharpness) const {
return decrementSharpness(vertexOrEdgeSharpness);
}
inline float
Crease::SubdivideVertexSharpness(float vertexSharpness) const {
return decrementSharpness(vertexSharpness);
}
inline void
Crease::GetSharpEdgePairOfCrease(float const * incidentEdgeSharpness, int incidentEdgeCount,
int sharpEdgePair[2]) const {
// Only to be called when a crease is present at a vertex -- exactly two sharp
// edges are expected here:
//
sharpEdgePair[0] = 0;
while (IsSmooth(incidentEdgeSharpness[sharpEdgePair[0]])) ++ sharpEdgePair[0];
sharpEdgePair[1] = incidentEdgeCount - 1;
while (IsSmooth(incidentEdgeSharpness[sharpEdgePair[1]])) -- sharpEdgePair[1];
}
} // end namespace sdc
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_SDC_CREASE_H */
+583
View File
@@ -0,0 +1,583 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_SDC_LOOP_SCHEME_H
#define OPENSUBDIV3_SDC_LOOP_SCHEME_H
#include "../version.h"
#include "../sdc/scheme.h"
#include <cassert>
#include <cmath>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Sdc {
//
// Specializations for Sdc::Scheme<SCHEME_LOOP>:
//
//
//
// Loop traits:
//
template <>
inline Split Scheme<SCHEME_LOOP>::GetTopologicalSplitType() { return SPLIT_TO_TRIS; }
template <>
inline int Scheme<SCHEME_LOOP>::GetRegularFaceSize() { return 3; }
template <>
inline int Scheme<SCHEME_LOOP>::GetRegularVertexValence() { return 6; }
template <>
inline int Scheme<SCHEME_LOOP>::GetLocalNeighborhoodSize() { return 1; }
//
// Protected methods to assign the two types of masks for an edge-vertex --
// Crease and Smooth.
//
// The Crease case does not really need to be specialized, though it may be
// preferable to define all explicitly here.
//
template <>
template <typename EDGE, typename MASK>
inline void
Scheme<SCHEME_LOOP>::assignCreaseMaskForEdge(EDGE const&, MASK& mask) const
{
mask.SetNumVertexWeights(2);
mask.SetNumEdgeWeights(0);
mask.SetNumFaceWeights(0);
mask.SetFaceWeightsForFaceCenters(false);
mask.VertexWeight(0) = 0.5f;
mask.VertexWeight(1) = 0.5f;
}
template <>
template <typename EDGE, typename MASK>
inline void
Scheme<SCHEME_LOOP>::assignSmoothMaskForEdge(EDGE const& edge, MASK& mask) const
{
int faceCount = edge.GetNumFaces();
mask.SetNumVertexWeights(2);
mask.SetNumEdgeWeights(0);
mask.SetNumFaceWeights(faceCount);
mask.SetFaceWeightsForFaceCenters(false);
//
// This is where we run into the issue of "face weights" -- we want to weight the
// face-centers for Catmark, but face-centers are not generated for Loop. So do
// we make assumptions on how the mask is used, assign some property to the mask
// to indicate how they were assigned, or take input from the mask itself?
//
// Regardless, we have two choices:
// - face-weights are for the vertices opposite the edge (as in Hbr):
// vertex weights = 0.375f;
// face weights = 0.125f;
//
// - face-weights are for the face centers:
// vertex weights = 0.125f;
// face weights = 0.375f;
//
// Coincidentally the coefficients are the same but reversed.
//
typedef typename MASK::Weight Weight;
Weight vWeight = mask.AreFaceWeightsForFaceCenters() ? 0.125f : 0.375f;
Weight fWeight = mask.AreFaceWeightsForFaceCenters() ? 0.375f : 0.125f;
mask.VertexWeight(0) = vWeight;
mask.VertexWeight(1) = vWeight;
if (faceCount == 2) {
mask.FaceWeight(0) = fWeight;
mask.FaceWeight(1) = fWeight;
} else {
// The non-manifold case is not clearly defined -- we adjust the above
// face-weight to preserve the ratio of edge-center and face-centers:
fWeight *= 2.0f / (Weight) faceCount;
for (int i = 0; i < faceCount; ++i) {
mask.FaceWeight(i) = fWeight;
}
}
}
//
// Protected methods to assign the three types of masks for a vertex-vertex --
// Corner, Crease and Smooth (Dart is the same as Smooth).
//
// Corner and Crease do not really need to be specialized, though it may be
// preferable to define all explicitly here.
//
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_LOOP>::assignCornerMaskForVertex(VERTEX const&, MASK& mask) const
{
mask.SetNumVertexWeights(1);
mask.SetNumEdgeWeights(0);
mask.SetNumFaceWeights(0);
mask.SetFaceWeightsForFaceCenters(false);
mask.VertexWeight(0) = 1.0f;
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_LOOP>::assignCreaseMaskForVertex(VERTEX const& vertex, MASK& mask,
int const creaseEnds[2]) const {
typedef typename MASK::Weight Weight;
int valence = vertex.GetNumEdges();
mask.SetNumVertexWeights(1);
mask.SetNumEdgeWeights(valence);
mask.SetNumFaceWeights(0);
mask.SetFaceWeightsForFaceCenters(false);
Weight vWeight = 0.75f;
Weight eWeight = 0.125f;
mask.VertexWeight(0) = vWeight;
for (int i = 0; i < valence; ++i) {
mask.EdgeWeight(i) = 0.0f;
}
mask.EdgeWeight(creaseEnds[0]) = eWeight;
mask.EdgeWeight(creaseEnds[1]) = eWeight;
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_LOOP>::assignSmoothMaskForVertex(VERTEX const& vertex, MASK& mask) const
{
typedef typename MASK::Weight Weight;
int valence = vertex.GetNumFaces();
mask.SetNumVertexWeights(1);
mask.SetNumEdgeWeights(valence);
mask.SetNumFaceWeights(0);
mask.SetFaceWeightsForFaceCenters(false);
// Specialize for the regular case: 1/16 per edge-vert, 5/8 for the vert itself:
Weight eWeight = (Weight) 0.0625f;
Weight vWeight = (Weight) 0.625f;
if (valence != 6) {
// From HbrLoopSubdivision<T>::Subdivide(mesh, vertex):
// - could use some lookup tables here for common irregular valence (5, 7, 8)
// or all of these cosine calls will be adding up...
double dValence = (double) valence;
double invValence = 1.0f / dValence;
double cosTheta = std::cos(M_PI * 2.0f * invValence);
double beta = 0.25f * cosTheta + 0.375f;
eWeight = (Weight) ((0.625f - (beta * beta)) * invValence);
vWeight = (Weight) (1.0f - (eWeight * dValence));
}
mask.VertexWeight(0) = vWeight;
for (int i = 0; i < valence; ++i) {
mask.EdgeWeight(i) = eWeight;
}
}
//
// Limit masks for position:
//
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_LOOP>::assignCornerLimitMask(VERTEX const& /* vertex */, MASK& posMask) const {
posMask.SetNumVertexWeights(1);
posMask.SetNumEdgeWeights(0);
posMask.SetNumFaceWeights(0);
posMask.SetFaceWeightsForFaceCenters(false);
posMask.VertexWeight(0) = 1.0f;
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_LOOP>::assignCreaseLimitMask(VERTEX const& vertex, MASK& posMask,
int const creaseEnds[2]) const {
typedef typename MASK::Weight Weight;
int valence = vertex.GetNumEdges();
posMask.SetNumVertexWeights(1);
posMask.SetNumEdgeWeights(valence);
posMask.SetNumFaceWeights(0);
posMask.SetFaceWeightsForFaceCenters(false);
//
// The refinement mask for a crease vertex is (1/8, 3/4, 1/8) and for a crease
// edge is (1/2, 1/2) -- producing a uniform B-spline curve along the crease
// (boundary) whether the vertex or its crease is regular or not. The limit
// mask is therefore (1/6, 2/3, 1/6) for ALL cases.
//
// An alternative limit mask (1/5, 3/5, 1/5) is often published for use either
// for irregular crease vertices or for all crease/boundary vertices, but this
// is based on an alternate refinement mask for the edge -- (3/8, 5/8) versus
// the usual (1/2, 1/2) -- and will not produce the B-spline curve desired.
//
Weight vWeight = (Weight) (4.0 / 6.0);
Weight eWeight = (Weight) (1.0 / 6.0);
posMask.VertexWeight(0) = vWeight;
for (int i = 0; i < valence; ++i) {
posMask.EdgeWeight(i) = 0.0f;
}
posMask.EdgeWeight(creaseEnds[0]) = eWeight;
posMask.EdgeWeight(creaseEnds[1]) = eWeight;
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_LOOP>::assignSmoothLimitMask(VERTEX const& vertex, MASK& posMask) const {
typedef typename MASK::Weight Weight;
int valence = vertex.GetNumFaces();
posMask.SetNumVertexWeights(1);
posMask.SetNumEdgeWeights(valence);
posMask.SetNumFaceWeights(0);
posMask.SetFaceWeightsForFaceCenters(false);
// Specialize for the regular case: 1/12 per edge-vert, 1/2 for the vert itself:
if (valence == 6) {
Weight eWeight = (Weight) (1.0 / 12.0);
Weight vWeight = 0.5f;
posMask.VertexWeight(0) = vWeight;
posMask.EdgeWeight(0) = eWeight;
posMask.EdgeWeight(1) = eWeight;
posMask.EdgeWeight(2) = eWeight;
posMask.EdgeWeight(3) = eWeight;
posMask.EdgeWeight(4) = eWeight;
posMask.EdgeWeight(5) = eWeight;
} else {
double dValence = (double) valence;
double invValence = 1.0f / dValence;
double cosTheta = std::cos(M_PI * 2.0f * invValence);
double beta = 0.25f * cosTheta + 0.375f;
double gamma = (0.625f - (beta * beta)) * invValence;
Weight eWeight = (Weight) (1.0f / (dValence + 3.0f / (8.0f * gamma)));
Weight vWeight = (Weight) (1.0f - (eWeight * dValence));
posMask.VertexWeight(0) = vWeight;
for (int i = 0; i < valence; ++i) {
posMask.EdgeWeight(i) = eWeight;
}
}
}
/*
// Limit masks for tangents:
//
// A note on tangent magnitudes:
//
// Several formulae exist for limit tangents at a vertex to accommodate the
// different topological configurations around the vertex. While these produce
// the desired direction, there is inconsistency in the resulting magnitudes.
// Ideally a regular mesh of uniformly shaped triangles with similar edge lengths
// should produce tangents of similar magnitudes throughout -- including corners
// and boundaries. So some of the common formulae for these are adjusted with
// scale factors.
//
// For uses where magnitude does not matter, this scaling should be irrelevant.
// But just as with patches, where the magnitudes of partial derivatives are
// consistent between similar patches, the magnitudes of limit tangents should
// also be similar.
//
// The reference tangents, in terms of magnitudes, are those produced by the
// limit tangent mask for smooth interior vertices, for which well established
// sin/cos formulae apply -- these remain unscaled. Formulae for the other
// crease/boundary, corner tangents and irregular cases are scaled to be more
// consistent with these.
//
// The crease/boundary tangents for the regular case can be viewed as derived
// from the smooth interior masks with two "phantom" points extrapolated across
// the regular boundary:
//
// v3 v2
// X - - - - - X
// / \ / \
// / \ / \
// v4 X - - - - - X - - - - - X v1
// . . 0 . .
// . . . .
// . . . .
// (v5) (v6)
//
// where v5 = v0 + (v4 - v3) and v6 = v0 + v1 - v2.
//
// When the standard limit tangent mask is applied, the cosines of increments
// of pi/3 give us coefficients that are multiples of 1/2, leading to the first
// tangent T1 = 3/2 * (v1 - v4), rather than the widely used T1 = v1 - v4. So
// this scale factor of 3/2 is applied to ensure tangents along the boundaries
// are of similar magnitude as tangents in the immediate interior (which may be
// parallel).
//
// Tangents at corners are essentially a form of boundary tangent, and so its
// simple difference formula is scaled to be consistent with adjoining boundary
// tangents -- not just with the 3/2 factor from above, but with an additional
// 2.0 to compensate for the fact that the difference of only side of the vertex
// is considered here. The resulting scale factor of 3.0 for the regular corner
// is what similarly arises by extrapolating an interior region around the
// vertex and using the interior mask for the first tangent.
//
// The cross-tangent formula for the regular crease/boundary is similarly found
// from the above construction of the boundary, but the commonly used weights of
// +/- 1 and 2 result from omitting the common factor of sqrt(3)/2 (arising from
// the sines of increments of pi/3). With that scale factor close to one, it has
// less impact than the irregular cases, which are analogous to corner tangents
// in that differences on only one side of the vertex are considered. While a
// scaling of 3.0 is similarly understandable for the valence 2 and 3 cases, it is
// less obvious in the irregular formula for valence > 4, but similarly effective.
//
// The end result of these adjustments should be a set of limit tangents that are
// of similar magnitude over a regular mesh including boundaries and corners.
*/
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_LOOP>::assignCornerLimitTangentMasks(VERTEX const& vertex,
MASK& tan1Mask, MASK& tan2Mask) const {
int valence = vertex.GetNumEdges();
tan1Mask.SetNumVertexWeights(1);
tan1Mask.SetNumEdgeWeights(valence);
tan1Mask.SetNumFaceWeights(0);
tan1Mask.SetFaceWeightsForFaceCenters(false);
tan2Mask.SetNumVertexWeights(1);
tan2Mask.SetNumEdgeWeights(valence);
tan2Mask.SetNumFaceWeights(0);
tan2Mask.SetFaceWeightsForFaceCenters(false);
// See note above regarding scale factor of 3.0:
tan1Mask.VertexWeight(0) = -3.0f;
tan1Mask.EdgeWeight(0) = 3.0f;
tan1Mask.EdgeWeight(1) = 0.0f;
tan2Mask.VertexWeight(0) = -3.0f;
tan2Mask.EdgeWeight(0) = 0.0f;
tan2Mask.EdgeWeight(1) = 3.0f;
// Should be at least 2 edges -- be sure to clear weights for any more:
for (int i = 2; i < valence; ++i) {
tan1Mask.EdgeWeight(i) = 0.0f;
tan2Mask.EdgeWeight(i) = 0.0f;
}
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_LOOP>::assignCreaseLimitTangentMasks(VERTEX const& vertex,
MASK& tan1Mask, MASK& tan2Mask, int const creaseEnds[2]) const {
typedef typename MASK::Weight Weight;
//
// First, the tangent along the crease:
// The first crease edge is considered the "leading" edge of the span
// of surface for which we are evaluating tangents and the second edge the
// "trailing edge". By convention, the tangent along the crease is oriented
// in the direction of the leading edge.
//
int valence = vertex.GetNumEdges();
tan1Mask.SetNumVertexWeights(1);
tan1Mask.SetNumEdgeWeights(valence);
tan1Mask.SetNumFaceWeights(0);
tan1Mask.SetFaceWeightsForFaceCenters(false);
tan1Mask.VertexWeight(0) = 0.0f;
for (int i = 0; i < valence; ++i) {
tan1Mask.EdgeWeight(i) = 0.0f;
}
// See the note above regarding scale factor of 1.5:
tan1Mask.EdgeWeight(creaseEnds[0]) = 1.5f;
tan1Mask.EdgeWeight(creaseEnds[1]) = -1.5f;
//
// Second, the tangent across the interior faces:
// Note this is ambiguous for an interior vertex. We currently return
// the tangent for the surface in the counter-clockwise span between the
// leading and trailing edges that form the crease. Given the expected
// computation of a surface normal as Tan1 X Tan2, this tangent should be
// oriented "inward" from the crease/boundary -- across the surface rather
// than outward and away from it.
//
// There is inconsistency in the orientation of this tangent in commonly
// published results: the general formula provided for arbitrary valence
// has the tangent pointing across the crease and "outward" from the surface,
// while the special cases for regular valence and lower have the tangent
// pointing across the surface and "inward" from the crease. So if we are
// to consistently orient the first tangent along the crease, regardless of
// the interior topology, we have to correct this. With the first tangent
// following the direction of the leading crease edge, we want the second
// tangent pointing inward/across the surface -- so we flip the result of
// the general formula.
//
tan2Mask.SetNumVertexWeights(1);
tan2Mask.SetNumEdgeWeights(valence);
tan2Mask.SetNumFaceWeights(0);
tan2Mask.SetFaceWeightsForFaceCenters(false);
for (int i = 0; i < creaseEnds[0]; ++i) {
tan2Mask.EdgeWeight(i) = 0.0f;
}
int interiorEdgeCount = creaseEnds[1] - creaseEnds[0] - 1;
if (interiorEdgeCount == 2) {
// See note above regarding scale factor of (sin(60 degs) == sqrt(3)/2:
static Weight const Root3 = (Weight) 1.73205080756887729352;
static Weight const Root3by2 = (Weight) (Root3 * 0.5);
tan2Mask.VertexWeight(0) = -Root3;
tan2Mask.EdgeWeight(creaseEnds[0]) = -Root3by2;
tan2Mask.EdgeWeight(creaseEnds[1]) = -Root3by2;
tan2Mask.EdgeWeight(creaseEnds[0] + 1) = Root3;
tan2Mask.EdgeWeight(creaseEnds[0] + 2) = Root3;
} else if (interiorEdgeCount > 2) {
// See notes above regarding scale factor of -3.0 (-1 for orientation,
// 2.0 for considering the region as a half-disk, and 1.5 in keeping
// with the crease tangent):
double theta = M_PI / (interiorEdgeCount + 1);
tan2Mask.VertexWeight(0) = 0.0f;
Weight cWeight = (Weight) (-3.0f * std::sin(theta));
tan2Mask.EdgeWeight(creaseEnds[0]) = cWeight;
tan2Mask.EdgeWeight(creaseEnds[1]) = cWeight;
double eCoeff = -3.0f * 2.0f * (std::cos(theta) - 1.0f);
for (int i = 1; i <= interiorEdgeCount; ++i) {
tan2Mask.EdgeWeight(creaseEnds[0] + i) = (Weight) (eCoeff * std::sin(i * theta));
}
} else if (interiorEdgeCount == 1) {
// See notes above regarding scale factor of 3.0:
tan2Mask.VertexWeight(0) = -3.0f;
tan2Mask.EdgeWeight(creaseEnds[0]) = 0.0f;
tan2Mask.EdgeWeight(creaseEnds[1]) = 0.0f;
tan2Mask.EdgeWeight(creaseEnds[0] + 1) = 3.0f;
} else {
// See notes above regarding scale factor of 3.0:
tan2Mask.VertexWeight(0) = -6.0f;
tan2Mask.EdgeWeight(creaseEnds[0]) = 3.0f;
tan2Mask.EdgeWeight(creaseEnds[1]) = 3.0f;
}
for (int i = creaseEnds[1] + 1; i < valence; ++i) {
tan2Mask.EdgeWeight(i) = 0.0f;
}
}
template <>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME_LOOP>::assignSmoothLimitTangentMasks(VERTEX const& vertex,
MASK& tan1Mask, MASK& tan2Mask) const {
typedef typename MASK::Weight Weight;
int valence = vertex.GetNumFaces();
tan1Mask.SetNumVertexWeights(1);
tan1Mask.SetNumEdgeWeights(valence);
tan1Mask.SetNumFaceWeights(0);
tan1Mask.SetFaceWeightsForFaceCenters(false);
tan2Mask.SetNumVertexWeights(1);
tan2Mask.SetNumEdgeWeights(valence);
tan2Mask.SetNumFaceWeights(0);
tan2Mask.SetFaceWeightsForFaceCenters(false);
tan1Mask.VertexWeight(0) = 0.0f;
tan2Mask.VertexWeight(0) = 0.0f;
if (valence == 6) {
static Weight const Root3by2 = (Weight)(0.5 * 1.73205080756887729352);
tan1Mask.EdgeWeight(0) = 1.0f;
tan1Mask.EdgeWeight(1) = 0.5f;
tan1Mask.EdgeWeight(2) = -0.5f;
tan1Mask.EdgeWeight(3) = -1.0f;
tan1Mask.EdgeWeight(4) = -0.5f;
tan1Mask.EdgeWeight(5) = 0.5f;
tan2Mask.EdgeWeight(0) = 0.0f;
tan2Mask.EdgeWeight(1) = Root3by2;
tan2Mask.EdgeWeight(2) = Root3by2;
tan2Mask.EdgeWeight(3) = 0.0f;
tan2Mask.EdgeWeight(4) = -Root3by2;
tan2Mask.EdgeWeight(5) = -Root3by2;
} else {
double alpha = 2.0f * M_PI / valence;
for (int i = 0; i < valence; ++i) {
double alphaI = alpha * i;
tan1Mask.EdgeWeight(i) = (Weight) std::cos(alphaI);
tan2Mask.EdgeWeight(i) = (Weight) std::sin(alphaI);
}
}
}
} // end namespace Sdc
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_SDC_LOOP_SCHEME_H */
+127
View File
@@ -0,0 +1,127 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_SDC_OPTIONS_H
#define OPENSUBDIV3_SDC_OPTIONS_H
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Sdc {
///
/// \brief All supported options applying to subdivision scheme.
///
/// The Options class contains all supported options that can be applied to a
/// subdivision scheme to affect the shape of the limit surface. These differ from
/// approximations that may be applied at a higher level, i.e. options to limit the
/// level of feature adaptive subdivision, options to ignore fractional creasing,
/// or creasing entirely, etc. These options define the shape of a particular
/// limit surface, including the "shape" of primitive variable data associated with
/// it.
///
/// The intent is that these sets of options be defined at a high level and
/// propagated into the lowest-level computation in support of each subdivision
/// scheme. Ideally it remains a set of bit-fields (essentially an int) and so
/// remains light weight and easily passed around by value.
///
class Options {
public:
enum VtxBoundaryInterpolation {
VTX_BOUNDARY_NONE = 0, ///< no boundary interpolation, except where
///< boundary edges were explicitly sharpened
VTX_BOUNDARY_EDGE_ONLY, ///< all boundary edges sharpened and interpolated
VTX_BOUNDARY_EDGE_AND_CORNER ///< all boundary edges and corner vertices
///< sharpened and interpolated
};
enum FVarLinearInterpolation {
FVAR_LINEAR_NONE = 0, ///< smooth everywhere ("edge only")
FVAR_LINEAR_CORNERS_ONLY, ///< sharpen corners only
FVAR_LINEAR_CORNERS_PLUS1, ///< ("edge corner")
FVAR_LINEAR_CORNERS_PLUS2, ///< ("edge and corner + propagate corner")
FVAR_LINEAR_BOUNDARIES, ///< sharpen all boundaries ("always sharp")
FVAR_LINEAR_ALL ///< bilinear interpolation ("bilinear")
};
enum CreasingMethod {
CREASE_UNIFORM = 0, ///< Catmark rule
CREASE_CHAIKIN ///< Chaikin rule
};
enum TriangleSubdivision {
TRI_SUB_CATMARK = 0, ///< Catmark weights (Catmark scheme only)
TRI_SUB_SMOOTH ///< "smooth triangle" weights (Catmark scheme only)
};
public:
Options() : _vtxBoundInterp(VTX_BOUNDARY_NONE),
_fvarLinInterp(FVAR_LINEAR_ALL),
_creasingMethod(CREASE_UNIFORM),
_triangleSub(TRI_SUB_CATMARK) { }
//
// Trivial get/set methods:
//
/// \brief Get vertex boundary interpolation rule
VtxBoundaryInterpolation GetVtxBoundaryInterpolation() const { return (VtxBoundaryInterpolation) _vtxBoundInterp; }
/// \brief Set vertex boundary interpolation rule
void SetVtxBoundaryInterpolation(VtxBoundaryInterpolation b) { _vtxBoundInterp = b; }
/// \brief Get face-varying interpolation rule
FVarLinearInterpolation GetFVarLinearInterpolation() const { return (FVarLinearInterpolation) _fvarLinInterp; }
/// \brief Set face-varying interpolation rule
void SetFVarLinearInterpolation(FVarLinearInterpolation b) { _fvarLinInterp = b; }
/// \brief Get edge crease rule
CreasingMethod GetCreasingMethod() const { return (CreasingMethod) _creasingMethod; }
/// \brief Set edge crease rule
void SetCreasingMethod(CreasingMethod c) { _creasingMethod = c; }
/// \brief Get triangle subdivision weights rule (Catmark scheme only !)
TriangleSubdivision GetTriangleSubdivision() const { return (TriangleSubdivision) _triangleSub; }
/// \brief Set triangle subdivision weights rule (Catmark scheme only !)
void SetTriangleSubdivision(TriangleSubdivision t) { _triangleSub = t; }
private:
// Bitfield members:
unsigned int _vtxBoundInterp : 2,
_fvarLinInterp : 3,
_creasingMethod : 2,
_triangleSub : 2;
};
} // end namespace sdc
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_SDC_OPTIONS_H */
+660
View File
@@ -0,0 +1,660 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_SDC_SCHEME_H
#define OPENSUBDIV3_SDC_SCHEME_H
#include "../version.h"
#include "../sdc/types.h"
#include "../sdc/options.h"
#include "../sdc/crease.h"
#include <cassert>
#include <cstdlib>
#include <vector>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Sdc {
///
/// \brief Scheme is a class template which provides all implementation for the
/// subdivision schemes supported by OpenSubdiv through specializations of the
/// methods of each. An instance of Scheme<SCHEME_TYPE> includes a set of Options
/// that will dictate the variable aspects of its behavior.
///
/// The primary purpose of Scheme is to provide the mask weights for vertices
/// generated by subdivision. Methods to determine the masks are given topological
/// neighborhoods from which to compute the appropriate weights for neighboring
/// components. While these neighborhoods may require sharpness values for
/// creasing, the computation of subdivided crease values is independent of the
/// scheme type and is also made available through the Crease class.
///
/// Mask queries are assisted by two utility classes -- a Neighborhood class
/// defining the set of relevant data in the topological neighborhood of the vertex
/// being subdivided, and a Mask class into which the associated mask weights will
/// be stored. Depending on where and how these queries are used, more or less
/// information may be available. See the details of the Neighborhood classes as
/// appropriate initialization of them is critical. It is generally best to
/// initialize them with what data is known and accessible for immediate and
/// efficient retrieval, but subclasses can be created to gather it lazily if
/// desired.
///
template <SchemeType SCHEME_TYPE>
class Scheme {
public:
Scheme() : _options() { }
Scheme(Options const& options) : _options(options) { }
Options GetOptions() const { return _options; }
void SetOptions(const Options& newOptions) { _options = newOptions; }
///
/// \brief Face-vertex masks - trivial for all current schemes
///
template <typename FACE, typename MASK>
void ComputeFaceVertexMask(FACE const& faceNeighborhood, MASK& faceVertexMask) const;
///
/// \brief Edge-vertex masks
/// If known, the Rule for the edge and/or the derived vertex can be specified to
/// accelerate the computation (though the Rule for the parent is trivially determined).
/// In particular, knowing the child rule can avoid the need to subdivide the sharpness
/// of the edge to see if it is a transitional crease that warrants fractional blending.
///
/// Whether to use the "Rules" in this interface is really debatable -- the parent Rule
/// is really based on the edge and its sharpness, while the child Rule is technically
/// based on the neighborhood of the child vertex, but it can be deduced from the two
/// child edges' sharpness. So the Crease methods used to compute these rules differ
/// from those for the vertex-vertex mask. Perhaps a simple pair of new methods for
/// Crease should be added specific to the edge-vertex case, i.e. one that takes a
/// single sharpness (for the parent rule) and one that takes a pair (for the child).
///
template <typename EDGE, typename MASK>
void ComputeEdgeVertexMask(EDGE const& edgeNeighborhood, MASK& edgeVertexMask,
Crease::Rule parentRule = Crease::RULE_UNKNOWN,
Crease::Rule childRule = Crease::RULE_UNKNOWN) const;
///
/// \brief Vertex-vertex masks
/// If known, a single Rule or pair of Rules can be specified (indicating a crease
/// transition) to accelerate the computation. Either no Rules, the first, or both should
/// be specified. Specification of only the first Rule implies it to be true for both
/// (wish the compiler would allow such default value specification), i.e. no transition.
/// The case of knowing the parent Rule but deferring determination of the child Rule to
/// this method is not supported.
///
template <typename VERTEX, typename MASK>
void ComputeVertexVertexMask(VERTEX const& vertexNeighborhood, MASK& vertexVertexMask,
Crease::Rule parentRule = Crease::RULE_UNKNOWN,
Crease::Rule childRule = Crease::RULE_UNKNOWN) const;
///
/// \brief Limit masks for vertices -- position and tangents
/// These presume that a vertex is suitably isolated for its limit to be well-defined
/// and, unlike the refinement masks, the subdivision Rule for the vertex (presumably at
/// its last level of refinement) is required rather than being optional. In the
/// presence of semi-sharp creasing that has not decayed to zero, the limit is neither
/// sharp nor smooth -- in such cases the Rule specified by the caller determines the
/// result.
///
/// For tangent masks, the direction of the first tangent (T1) is oriented towards the
/// leading edge of the vertex, i.e. the first incident edge of the vertex (beginning
/// the set of incident edges in counter-clockwise order). The second tangent (T2) lies
/// within the tangent plane such that its normal can be computed as T1 x T2. So for a
/// boundary vertex, T1 will point along the boundary in the direction of the leading
/// edge while T2 points inward across the limit surface.
///
/// As for magnitude, no assumptions should be made of the magnitudes of the resulting
/// tangent vectors. Common formulae often factor out scale factors that contribute to
/// magnitude. While some attempt has been made to make magnitudes more consistent
/// between regular corners, boundaries and the interior, the same has not been done at
/// irregular vertices -- at least not yet. This may be addressed in future, as having
/// consistent magnitudes returned here can aid in the construction of patches from
/// limit positions and tangents.
///
template <typename VERTEX, typename MASK>
void ComputeVertexLimitMask(VERTEX const& vertexNeighborhood, MASK& positionMask,
Crease::Rule vertexRule) const;
template <typename VERTEX, typename MASK>
void ComputeVertexLimitMask(VERTEX const& vertexNeighborhood, MASK& positionMask,
MASK& tangent1Mask, MASK& tangent2Mask,
Crease::Rule vertexRule) const;
//
// Static methods defining traits/properties of the scheme:
//
static Split GetTopologicalSplitType();
static int GetRegularFaceSize();
static int GetRegularVertexValence();
static int GetLocalNeighborhoodSize();
protected:
//
// Supporting internal methods -- optionally implemented, depending on specialization:
//
// Subdivision/refinement masks -- two for edge-vertices and three for vertex-vertices:
//
template <typename EDGE, typename MASK>
void assignCreaseMaskForEdge(EDGE const& edge, MASK& mask) const;
template <typename EDGE, typename MASK>
void assignSmoothMaskForEdge(EDGE const& edge, MASK& mask) const;
template <typename VERTEX, typename MASK>
void assignCornerMaskForVertex(VERTEX const& edge, MASK& mask) const;
template <typename VERTEX, typename MASK>
void assignCreaseMaskForVertex(VERTEX const& edge, MASK& mask, int const creaseEnds[2]) const;
template <typename VERTEX, typename MASK>
void assignSmoothMaskForVertex(VERTEX const& edge, MASK& mask) const;
//
// Limit masks for position and tangents at vertices -- three cases for each:
//
template <typename VERTEX, typename MASK>
void assignCornerLimitMask(VERTEX const& vertex, MASK& pos) const;
template <typename VERTEX, typename MASK>
void assignCreaseLimitMask(VERTEX const& vertex, MASK& pos, int const creaseEnds[2]) const;
template <typename VERTEX, typename MASK>
void assignSmoothLimitMask(VERTEX const& vertex, MASK& pos) const;
template <typename VERTEX, typename MASK>
void assignCornerLimitTangentMasks(VERTEX const& vertex, MASK& tan1, MASK& tan2) const;
template <typename VERTEX, typename MASK>
void assignCreaseLimitTangentMasks(VERTEX const& vertex, MASK& tan1, MASK& tan2, int const creaseEnds[2]) const;
template <typename VERTEX, typename MASK>
void assignSmoothLimitTangentMasks(VERTEX const& vertex, MASK& tan1, MASK& tan2) const;
private:
Options _options;
protected:
//
// Internal implementation support:
//
// We need a local "mask" class to be declared locally within the vertex-vertex mask query
// to hold one of the two possible masks required and to combine the local mask with the mask
// the caller provides. It has been parameterized by <WEIGHT> so that a version compatible
// with the caller's mask class is created.
//
template <typename WEIGHT>
class LocalMask {
public:
typedef WEIGHT Weight;
public:
LocalMask(Weight* v, Weight* e, Weight* f) : _vWeights(v), _eWeights(e), _fWeights(f) { }
~LocalMask() { }
public:
//
// Methods required for general mask assignments and queries:
//
int GetNumVertexWeights() const { return _vCount; }
int GetNumEdgeWeights() const { return _eCount; }
int GetNumFaceWeights() const { return _fCount; }
void SetNumVertexWeights(int count) { _vCount = count; }
void SetNumEdgeWeights( int count) { _eCount = count; }
void SetNumFaceWeights( int count) { _fCount = count; }
Weight const& VertexWeight(int index) const { return _vWeights[index]; }
Weight const& EdgeWeight( int index) const { return _eWeights[index]; }
Weight const& FaceWeight( int index) const { return _fWeights[index]; }
Weight& VertexWeight(int index) { return _vWeights[index]; }
Weight& EdgeWeight( int index) { return _eWeights[index]; }
Weight& FaceWeight( int index) { return _fWeights[index]; }
bool AreFaceWeightsForFaceCenters() const { return _fWeightsForCenters; }
void SetFaceWeightsForFaceCenters(bool on) { _fWeightsForCenters = on; }
public:
//
// Additional methods -- mainly the blending method for vertex-vertex masks:
//
template <typename USER_MASK>
inline void
CombineVertexVertexMasks(Weight thisCoeff, Weight dstCoeff, USER_MASK& dst) const {
//
// This implementation is convoluted by the potential sparsity of each mask. Since
// it is specific to a vertex-vertex mask, we are guaranteed to have exactly one
// vertex-weight for both masks, but the edge- and face-weights are optional. The
// child mask (the "source") should have a superset of the weights of the parent
// (the "destination") given its reduced sharpness, so we fortunately don't need to
// test all permutations.
//
dst.VertexWeight(0) = dstCoeff * dst.VertexWeight(0) + thisCoeff * this->VertexWeight(0);
int edgeWeightCount = this->GetNumEdgeWeights();
if (edgeWeightCount) {
if (dst.GetNumEdgeWeights() == 0) {
dst.SetNumEdgeWeights(edgeWeightCount);
for (int i = 0; i < edgeWeightCount; ++i) {
dst.EdgeWeight(i) = thisCoeff * this->EdgeWeight(i);
}
} else {
for (int i = 0; i < edgeWeightCount; ++i) {
dst.EdgeWeight(i) = dstCoeff * dst.EdgeWeight(i) + thisCoeff * this->EdgeWeight(i);
}
}
}
int faceWeightCount = this->GetNumFaceWeights();
if (faceWeightCount) {
//
// If combining face weights, be sure their interpretation (i.e. face-centers
// or opposite vertices) is properly set in the destination mask:
//
if (dst.GetNumFaceWeights() == 0) {
dst.SetNumFaceWeights(faceWeightCount);
dst.SetFaceWeightsForFaceCenters(this->AreFaceWeightsForFaceCenters());
for (int i = 0; i < faceWeightCount; ++i) {
dst.FaceWeight(i) = thisCoeff * this->FaceWeight(i);
}
} else {
assert(this->AreFaceWeightsForFaceCenters() == dst.AreFaceWeightsForFaceCenters());
for (int i = 0; i < faceWeightCount; ++i) {
dst.FaceWeight(i) = dstCoeff * dst.FaceWeight(i) + thisCoeff * this->FaceWeight(i);
}
}
}
}
private:
Weight* _vWeights;
Weight* _eWeights;
Weight* _fWeights;
int _vCount;
int _eCount;
int _fCount;
bool _fWeightsForCenters;
};
};
//
// Crease and corner masks are common to most schemes -- the rest need to be provided
// for each Scheme specialization.
//
template <SchemeType SCHEME>
template <typename EDGE, typename MASK>
inline void
Scheme<SCHEME>::assignCreaseMaskForEdge(EDGE const&, MASK& mask) const {
mask.SetNumVertexWeights(2);
mask.SetNumEdgeWeights(0);
mask.SetNumFaceWeights(0);
mask.SetFaceWeightsForFaceCenters(false);
mask.VertexWeight(0) = 0.5f;
mask.VertexWeight(1) = 0.5f;
}
template <SchemeType SCHEME>
template <typename VERTEX, typename MASK>
inline void
Scheme<SCHEME>::assignCornerMaskForVertex(VERTEX const&, MASK& mask) const {
mask.SetNumVertexWeights(1);
mask.SetNumEdgeWeights(0);
mask.SetNumFaceWeights(0);
mask.SetFaceWeightsForFaceCenters(false);
mask.VertexWeight(0) = 1.0f;
}
//
// The computation of a face-vertex mask is trivial and consistent for all schemes:
//
template <SchemeType SCHEME>
template <typename FACE, typename MASK>
void
Scheme<SCHEME>::ComputeFaceVertexMask(FACE const& face, MASK& mask) const {
int vertCount = face.GetNumVertices();
mask.SetNumVertexWeights(vertCount);
mask.SetNumEdgeWeights(0);
mask.SetNumFaceWeights(0);
mask.SetFaceWeightsForFaceCenters(false);
typename MASK::Weight vWeight = 1.0f / (typename MASK::Weight) vertCount;
for (int i = 0; i < vertCount; ++i) {
mask.VertexWeight(i) = vWeight;
}
}
//
// The computation of an edge-vertex mask requires inspection of sharpness values to
// determine if smooth or a crease, and also to detect and apply a transition from a
// crease to smooth. Using the protected methods to assign the specific masks (only
// two -- smooth or crease) this implementation should serve all non-linear schemes
// (currently Catmark and Loop) and only needs to be specialized for Bilinear to
// trivialize it to the crease case.
//
// The implementation here is slightly complicated by combining two scenarios into a
// single implementation -- either the caller knows the parent and child rules and
// provides them, or they don't and the Rules have to be determined from sharpness
// values. Both cases include quick return once the parent is determined to be
// smooth or the child a crease, leaving the transitional case remaining.
//
// The overall process is as follows:
//
// - quickly detect the most common specified or detected Smooth case and return
// - quickly detect a full Crease by child Rule assignment and return
// - determine from sharpness if unspecified child is a crease -- return if so
// - compute smooth mask for child and combine with crease from parent
//
// Usage of the parent Rule here allows some misuse in that only three of five possible
// assignments are legitimate for the parent and four for the child (Dart being only
// valid for the child and Corner for neither). Results are undefined in these cases.
//
template <SchemeType SCHEME>
template <typename EDGE, typename MASK>
void
Scheme<SCHEME>::ComputeEdgeVertexMask(EDGE const& edge,
MASK& mask,
Crease::Rule parentRule,
Crease::Rule childRule) const {
//
// If the parent was specified or determined to be Smooth, we can quickly return
// with a Smooth mask. Otherwise the parent is a crease -- if the child was
// also specified to be a crease, we can quickly return with a Crease mask.
//
if ((parentRule == Crease::RULE_SMOOTH) ||
((parentRule == Crease::RULE_UNKNOWN) && (edge.GetSharpness() <= 0.0f))) {
assignSmoothMaskForEdge(edge, mask);
return;
}
if (childRule == Crease::RULE_CREASE) {
assignCreaseMaskForEdge(edge, mask);
return;
}
//
// We have a Crease on the parent and the child was either specified as Smooth
// or was not specified at all -- deal with the unspecified case first (again
// returning a Crease mask if the child is also determined to be a Crease) and
// continue if we have a transition to Smooth.
//
// Note when qualifying the child that if the parent sharpness > 1.0, regardless
// of the creasing method, whether the child sharpness values decay to zero is
// irrelevant -- the fractional weight for such a case (the value of the parent
// sharpness) is > 1.0, and when clamped to 1 effectively yields a full crease.
//
if (childRule == Crease::RULE_UNKNOWN) {
Crease crease(_options);
bool childIsCrease = false;
if (parentRule == Crease::RULE_CREASE) {
// Child unknown as default value but parent Rule specified as Crease
childIsCrease = true;
} else if (edge.GetSharpness() >= 1.0f) {
// Sharpness >= 1.0 always a crease -- see note above
childIsCrease = true;
} else if (crease.IsUniform()) {
// Sharpness < 1.0 is guaranteed to decay to 0.0 for Uniform child edges
childIsCrease = false;
} else {
// Sharpness <= 1.0 does not necessarily decay to 0.0 for both child edges...
float cEdgeSharpness[2];
edge.GetChildSharpnesses(crease, cEdgeSharpness);
childIsCrease = (cEdgeSharpness[0] > 0.0f) && (cEdgeSharpness[1] > 0.0f);
}
if (childIsCrease) {
assignCreaseMaskForEdge(edge, mask);
return;
}
}
//
// We are now left with the Crease-to-Smooth case -- compute the Smooth mask
// for the child and augment it with the transitional Crease of the parent.
//
// A general combination of separately assigned masks here (as done in the vertex-
// vertex case) is overkill -- trivially combine the 0.5f vertex coefficient for
// the Crease of the parent with the vertex weights and attenuate the face weights
// accordingly.
//
assignSmoothMaskForEdge(edge, mask);
typedef typename MASK::Weight Weight;
Weight pWeight = edge.GetSharpness();
Weight cWeight = 1.0f - pWeight;
mask.VertexWeight(0) = pWeight * 0.5f + cWeight * mask.VertexWeight(0);
mask.VertexWeight(1) = pWeight * 0.5f + cWeight * mask.VertexWeight(1);
int faceCount = mask.GetNumFaceWeights();
for (int i = 0; i < faceCount; ++i) {
mask.FaceWeight(i) *= cWeight;
}
}
//
// The computation of a vertex-vertex mask requires inspection of creasing sharpness values
// to determine what subdivision Rules apply to the parent and its child vertex, and also to
// detect and apply a transition between two differing Rules. Using the protected methods to
// assign specific masks, this implementation should serve all non-linear schemes (currently
// Catmark and Loop) and only needs to be specialized for Bilinear to remove all unnecessary
// complexity relating to creasing, Rules, etc.
//
// The implementation here is slightly complicated by combining two scenarios into one --
// either the caller knows the parent and child rules and provides them, or they don't and
// the Rules have to be determined from sharpness values. Even when the Rules are known and
// provided though, there are cases where the parent and child sharpness values need to be
// identified, so accounting for the unknown Rules too is not much of an added complication.
//
// The benefit of supporting specified Rules is that they can often be trivially
// determined from context (e.g. a vertex derived from a face at a previous level will always
// be smooth) rather than more generally, and at greater cost, inspecting neighboring and
// they are often the same for parent and child.
//
// The overall process is as follows:
//
// - quickly detect the most common Smooth case when specified and return
// - determine if sharpness for parent is required and gather if so
// - if unspecified, determine the parent rule
// - assign mask for the parent rule -- returning if Smooth/Dart
// - return if child rule matches parent
// - gather sharpness for child to determine or combine child rule
// - if unspecified, determine the child rule, returning if it matches parent
// - assign local mask for child rule
// - combine local child mask with the parent mask
//
// Remember -- if the parent rule is specified but the child is not, this implies only one
// of the two optional rules was specified and is meant to indicate there is no transition,
// so the child rule should be assigned to be the same (wish the compiler would allow this
// in default value assignment).
//
template <SchemeType SCHEME>
template <typename VERTEX, typename MASK>
void
Scheme<SCHEME>::ComputeVertexVertexMask(VERTEX const& vertex,
MASK& mask,
Crease::Rule pRule,
Crease::Rule cRule) const {
// Quick assignment and return for the most common case:
if ((pRule == Crease::RULE_SMOOTH) || (pRule == Crease::RULE_DART)) {
assignSmoothMaskForVertex(vertex, mask);
return;
}
// If unspecified, assign the child rule to match the parent rule if specified:
if ((cRule == Crease::RULE_UNKNOWN) && (pRule != Crease::RULE_UNKNOWN)) {
cRule = pRule;
}
int valence = vertex.GetNumEdges();
//
// Determine if we need the parent edge sharpness values -- identify/gather if so
// and use it to compute the parent rule if unspecified:
//
float * pEdgeSharpnessBuffer = (float *)alloca(valence*sizeof(float)),
* pEdgeSharpness = 0,
pVertexSharpness = 0.0f;
bool requireParentSharpness = (pRule == Crease::RULE_UNKNOWN) ||
(pRule == Crease::RULE_CREASE) ||
(pRule != cRule);
if (requireParentSharpness) {
pVertexSharpness = vertex.GetSharpness();
pEdgeSharpness = vertex.GetSharpnessPerEdge(pEdgeSharpnessBuffer);
if (pRule == Crease::RULE_UNKNOWN) {
pRule = Crease(_options).DetermineVertexVertexRule(pVertexSharpness, valence, pEdgeSharpness);
}
}
if ((pRule == Crease::RULE_SMOOTH) || (pRule == Crease::RULE_DART)) {
assignSmoothMaskForVertex(vertex, mask);
return; // As done on entry, we can return immediately if parent is Smooth/Dart
} else if (pRule == Crease::RULE_CREASE) {
int creaseEnds[2];
Crease(_options).GetSharpEdgePairOfCrease(pEdgeSharpness, valence, creaseEnds);
assignCreaseMaskForVertex(vertex, mask, creaseEnds);
} else {
assignCornerMaskForVertex(vertex, mask);
}
if (cRule == pRule) return;
//
// Identify/gather child sharpness to combine masks for the two differing Rules:
//
Crease crease(_options);
float * cEdgeSharpnessBuffer = (float *)alloca(valence*sizeof(float)),
* cEdgeSharpness = vertex.GetChildSharpnessPerEdge(crease, cEdgeSharpnessBuffer),
cVertexSharpness = vertex.GetChildSharpness(crease);
if (cRule == Crease::RULE_UNKNOWN) {
cRule = crease.DetermineVertexVertexRule(cVertexSharpness, valence, cEdgeSharpness);
if (cRule == pRule) return;
}
//
// Initialize a local child mask, compute the fractional weight from parent and child
// sharpness values and combine the two masks:
//
typedef typename MASK::Weight Weight;
Weight * cMaskWeights = (Weight *)alloca((1 + 2 * valence)*sizeof(Weight));
LocalMask<Weight> cMask(cMaskWeights, cMaskWeights + 1, cMaskWeights + 1 + valence);
if ((cRule == Crease::RULE_SMOOTH) || (cRule == Crease::RULE_DART)) {
assignSmoothMaskForVertex(vertex, cMask);
} else if (cRule == Crease::RULE_CREASE) {
int creaseEnds[2];
Crease(_options).GetSharpEdgePairOfCrease(cEdgeSharpness, valence, creaseEnds);
assignCreaseMaskForVertex(vertex, cMask, creaseEnds);
} else {
assignCornerMaskForVertex(vertex, cMask);
}
Weight pWeight = crease.ComputeFractionalWeightAtVertex(pVertexSharpness, cVertexSharpness,
valence, pEdgeSharpness, cEdgeSharpness);
Weight cWeight = 1.0f - pWeight;
cMask.CombineVertexVertexMasks(cWeight, pWeight, mask);
}
//
// The computation of limit masks for vertices:
//
template <SchemeType SCHEME>
template <typename VERTEX, typename MASK>
void
Scheme<SCHEME>::ComputeVertexLimitMask(VERTEX const& vertex,
MASK& mask,
Crease::Rule rule) const {
if ((rule == Crease::RULE_SMOOTH) || (rule == Crease::RULE_DART)) {
assignSmoothLimitMask(vertex, mask);
} else if (rule == Crease::RULE_CREASE) {
float * edgeSharpness = (float *)alloca(vertex.GetNumEdges() * sizeof(float));
vertex.GetSharpnessPerEdge(edgeSharpness);
int creaseEnds[2];
Crease(_options).GetSharpEdgePairOfCrease(edgeSharpness, vertex.GetNumEdges(), creaseEnds);
assignCreaseLimitMask(vertex, mask, creaseEnds);
} else {
assignCornerLimitMask(vertex, mask);
}
}
template <SchemeType SCHEME>
template <typename VERTEX, typename MASK>
void
Scheme<SCHEME>::ComputeVertexLimitMask(VERTEX const& vertex,
MASK& posMask,
MASK& tan1Mask,
MASK& tan2Mask,
Crease::Rule rule) const {
if ((rule == Crease::RULE_SMOOTH) || (rule == Crease::RULE_DART)) {
assignSmoothLimitMask(vertex, posMask);
assignSmoothLimitTangentMasks(vertex, tan1Mask, tan2Mask);
} else if (rule == Crease::RULE_CREASE) {
float * edgeSharpness = (float *)alloca(vertex.GetNumEdges() * sizeof(float));
vertex.GetSharpnessPerEdge(edgeSharpness);
int creaseEnds[2];
Crease(_options).GetSharpEdgePairOfCrease(edgeSharpness, vertex.GetNumEdges(), creaseEnds);
assignCreaseLimitMask(vertex, posMask, creaseEnds);
assignCreaseLimitTangentMasks(vertex, tan1Mask, tan2Mask, creaseEnds);
} else {
assignCornerLimitMask(vertex, posMask);
assignCornerLimitTangentMasks(vertex, tan1Mask, tan2Mask);
}
}
} // end namespace sdc
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_SDC_SCHEME_H */
+76
View File
@@ -0,0 +1,76 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_SDC_TYPES_H
#define OPENSUBDIV3_SDC_TYPES_H
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Sdc {
///
/// \brief Enumerated type for all subdivision schemes supported by OpenSubdiv
///
enum SchemeType {
SCHEME_BILINEAR,
SCHEME_CATMARK,
SCHEME_LOOP
};
///
/// \brief Enumerated type for all face splitting schemes
///
enum Split {
SPLIT_TO_QUADS, ///< Used by Catmark and Bilinear
SPLIT_TO_TRIS, ///< Used by Loop
SPLIT_HYBRID ///< Not currently used (potential future extension)
};
///
/// \brief Traits associated with the types of all subdivision schemes -- parameterized by
/// the scheme type. All traits are also defined in the scheme itself.
///
struct SchemeTypeTraits {
static SchemeType GetType(SchemeType schemeType) { return schemeType; }
static Split GetTopologicalSplitType(SchemeType schemeType);
static int GetRegularFaceSize(SchemeType schemeType);
static int GetRegularVertexValence(SchemeType schemeType);
static int GetLocalNeighborhoodSize(SchemeType schemeType);
static char const* GetName(SchemeType schemeType);
};
} // end namespace sdc
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_SDC_TYPES_H */
+45
View File
@@ -0,0 +1,45 @@
//
// Copyright 2013 Pixar
//
// 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.
//
#ifndef OPENSUBDIV3_VERSION_H
#define OPENSUBDIV3_VERSION_H
#define OPENSUBDIV_VERSION v3_4_3
#define OPENSUBDIV_VERSION_NUMBER 30403
#define OPENSUBDIV_VERSION_MAJOR 3
#define OPENSUBDIV_VERSION_MINOR 4
#define OPENSUBDIV_VERSION_PATCH 3
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_VERSION_H */
+148
View File
@@ -0,0 +1,148 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_VTR_ARRAY_INTERFACE_H
#define OPENSUBDIV3_VTR_ARRAY_INTERFACE_H
#include "../version.h"
#include <cassert>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Vtr {
//
// This class provides a simple array-like interface -- a subset std::vector's interface -- for
// a sequence of elements stored in contiguous memory. It provides a unified representation for
// referencing data on the stack, all or a subset of std::vector<>, or anywhere else in memory.
//
// Note that its members are head/size rather than begin/end as in std::vector -- we frequently
// need only the size for many queries, and that is most often what is stored elsewhere in other
// classes, so we hope to reduce unnecessary address arithmetic constructing the interface and
// accessing the size. The size type is also specifically 32-bit (rather than size_t) to match
// internal usage and avoid unnecessary conversion to/from 64-bit.
//
// Question:
// Naming is at issue here... formerly called ArrayInterface until that was shot down it has
// been simplified to Array but needs to be distanced from std::array as it DOES NOT store its
// own memory and is simply an interface to memory stored elsewhere.
//
template <typename TYPE>
class ConstArray {
public:
typedef TYPE value_type;
typedef int size_type;
typedef TYPE const& const_reference;
typedef TYPE const* const_iterator;
typedef TYPE& reference;
typedef TYPE* iterator;
public:
ConstArray() : _begin(0), _size(0) { }
ConstArray(value_type const * ptr, size_type sizeArg) :
_begin(ptr), _size(sizeArg) { }
size_type size() const { return _size; }
bool empty() const { return _size==0; }
const_reference operator[](int index) const { return _begin[index]; }
const_iterator begin() const { return _begin; }
const_iterator end() const { return _begin + _size; }
size_type FindIndexIn4Tuple(value_type value) const {
assert(_size>=4);
if (value == _begin[0]) return 0;
if (value == _begin[1]) return 1;
if (value == _begin[2]) return 2;
if (value == _begin[3]) return 3;
assert("FindIndexIn4Tuple() did not find expected value!" == 0);
return -1;
}
size_type FindIndex(value_type value) const {
for (size_type i=0; i<size(); ++i) {
if (value==_begin[i]) {
return i;
}
}
return -1;
}
protected:
value_type const * _begin;
size_type _size;
};
template <typename TYPE>
class Array : public ConstArray<TYPE> {
public:
typedef TYPE value_type;
typedef int size_type;
typedef TYPE const& const_reference;
typedef TYPE& reference;
typedef TYPE* iterator;
public:
Array() : ConstArray<TYPE>() { }
Array(value_type * ptr, size_type sizeArg) : ConstArray<TYPE>(ptr, sizeArg) { }
public:
const_reference operator[](int index) const {
return ConstArray<TYPE>::_begin[index];
}
reference operator[](int index) {
return const_cast<reference>(ConstArray<TYPE>::_begin[index]);
}
iterator begin() {
return const_cast<iterator>(ConstArray<TYPE>::_begin);
}
iterator end() {
return const_cast<iterator>(ConstArray<TYPE>::_begin +
ConstArray<TYPE>::_size);
}
};
} // end namespace Vtr
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_VTR_ARRAY_INTERFACE_H */
@@ -0,0 +1,158 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_VTR_COMPONENT_INTERFACES_H
#define OPENSUBDIV3_VTR_COMPONENT_INTERFACES_H
#include "../version.h"
#include "../sdc/types.h"
#include "../sdc/crease.h"
#include "../vtr/types.h"
#include "../vtr/stackBuffer.h"
#include <vector>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Vtr {
namespace internal {
//
// Simple classes supporting the interfaces required of generic topological
// types in the Scheme mask queries, e.g. <typename FACE, VERTEX, etc.>
//
// These are not used with Vtr but arguably belong with it as the details to
// write these efficiently depends very much on intimate details of Vtr's
// implementation, e.g. the use of tag bits, subdivision Rules, etc.
//
//
// For <typename FACE>, which provides information in the neighborhood of a face:
//
class FaceInterface {
public:
FaceInterface() { }
FaceInterface(int vertCount) : _vertCount(vertCount) { }
~FaceInterface() { }
public: // Generic interface expected of <typename FACE>:
int GetNumVertices() const { return _vertCount; }
private:
int _vertCount;
};
//
// For <typename EDGE>, which provides information in the neighborhood of an edge:
//
class EdgeInterface {
public:
EdgeInterface() { }
EdgeInterface(Level const& level) : _level(&level) { }
~EdgeInterface() { }
void SetIndex(int edgeIndex) { _eIndex = edgeIndex; }
public: // Generic interface expected of <typename EDGE>:
int GetNumFaces() const { return _level->getEdgeFaces(_eIndex).size(); }
float GetSharpness() const { return _level->getEdgeSharpness(_eIndex); }
void GetChildSharpnesses(Sdc::Crease const&, float s[2]) const {
// Need to use the Refinement here to identify the two child edges:
s[0] = s[1] = GetSharpness() - 1.0f;
}
void GetNumVerticesPerFace(int vertsPerFace[]) const {
ConstIndexArray eFaces = _level->getEdgeFaces(_eIndex);
for (int i = 0; i < eFaces.size(); ++i) {
vertsPerFace[i] = _level->getFaceVertices(eFaces[i]).size();
}
}
private:
const Level* _level;
int _eIndex;
};
//
// For <typename VERTEX>, which provides information in the neighborhood of a vertex:
//
class VertexInterface {
public:
VertexInterface() { }
VertexInterface(Level const& parent, Level const& child) : _parent(&parent), _child(&child) { }
~VertexInterface() { }
void SetIndex(int parentIndex, int childIndex) {
_pIndex = parentIndex;
_cIndex = childIndex;
_eCount = _parent->getVertexEdges(_pIndex).size();
_fCount = _parent->getVertexFaces(_pIndex).size();
}
public: // Generic interface expected of <typename VERT>:
int GetNumEdges() const { return _eCount; }
int GetNumFaces() const { return _fCount; }
float GetSharpness() const { return _parent->getVertexSharpness(_pIndex); }
float* GetSharpnessPerEdge(float pSharpness[]) const {
ConstIndexArray pEdges = _parent->getVertexEdges(_pIndex);
for (int i = 0; i < _eCount; ++i) {
pSharpness[i] = _parent->getEdgeSharpness(pEdges[i]);
}
return pSharpness;
}
float GetChildSharpness(Sdc::Crease const&) const { return _child->getVertexSharpness(_cIndex); }
float* GetChildSharpnessPerEdge(Sdc::Crease const& crease, float cSharpness[]) const {
internal::StackBuffer<float,16> pSharpness(_eCount);
GetSharpnessPerEdge(pSharpness);
crease.SubdivideEdgeSharpnessesAroundVertex(_eCount, pSharpness, cSharpness);
return cSharpness;
}
private:
const Level* _parent;
const Level* _child;
int _pIndex;
int _cIndex;
int _eCount;
int _fCount;
};
} // end namespace internal
} // end namespace Vtr
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_VTR_COMPONENT_INTERFACES_H */
+439
View File
@@ -0,0 +1,439 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_VTR_FVAR_LEVEL_H
#define OPENSUBDIV3_VTR_FVAR_LEVEL_H
#include "../version.h"
#include "../sdc/types.h"
#include "../sdc/crease.h"
#include "../sdc/options.h"
#include "../vtr/types.h"
#include "../vtr/level.h"
#include <vector>
#include <cassert>
#include <cstring>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Vtr {
namespace internal {
//
// FVarLevel:
// A "face-varying channel" includes the topology for a set of face-varying
// data, relative to the topology of the Level with which it is associated.
//
// Analogous to a set of vertices and face-vertices that define the topology for
// the geometry, a channel requires a set of "values" and "face-values". The
// "values" are indices of entries in a set of face-varying data, just as vertices
// are indices into a set of vertex data. The face-values identify a value for
// each vertex of the face, and so define topology for the values that may be
// unique to each channel.
//
// In addition to the value size and the vector of face-values (which matches the
// size of the geometry's face-vertices), tags are associated with each component
// to identify deviations of the face-varying topology from the vertex topology.
// And since there may be a one-to-many mapping between vertices and face-varying
// values, that mapping is also allocated.
//
// It turns out that the mapping used is able to completely encode the set of
// face-values and is more amenable to refinement. Currently the face-values
// take up almost half the memory of this representation, so if memory does
// become a concern, we do not need to store them. The only reason we do so now
// is that the face-value interface for specifying base topology and inspecting
// subsequent levels is very familiar to that of face-vertices for clients. So
// having them available for such access is convenient.
//
// Regarding scope and access...
// Unclear at this early state, but leaning towards nesting this class within
// Level, given the intimate dependency between the two.
// Everything is being declared public for now to facilitate access until it's
// clearer how this functionality will be provided.
//
class FVarLevel {
public:
//
// Component tags -- trying to minimize the types needed here:
//
// Tag per Edge:
// - facilitates topological analysis around each vertex
// - required during refinement to spawn one or more edge-values
//
struct ETag {
ETag() { }
void clear() { std::memset(this, 0, sizeof(ETag)); }
typedef unsigned char ETagSize;
ETagSize _mismatch : 1; // local FVar topology does not match
ETagSize _disctsV0 : 1; // discontinuous at vertex 0
ETagSize _disctsV1 : 1; // discontinuous at vertex 1
ETagSize _linear : 1; // linear boundary constraints
Level::ETag combineWithLevelETag(Level::ETag) const;
};
//
// Tag per Value:
// - informs both refinement and interpolation
// - every value spawns a child value in refinement
// - includes a subset of Level::VTag to be later combined with a VTag
//
struct ValueTag {
ValueTag() { }
void clear() { std::memset(this, 0, sizeof(ValueTag)); }
bool isMismatch() const { return _mismatch; }
bool isCrease() const { return _crease; }
bool isCorner() const { return !_crease; }
bool isSemiSharp() const { return _semiSharp; }
bool isInfSharp() const { return !_semiSharp && !_crease; }
bool isDepSharp() const { return _depSharp; }
bool hasCreaseEnds() const { return _crease || _semiSharp; }
bool hasInfSharpEdges() const { return _infSharpEdges; }
bool hasInfIrregularity() const { return _infIrregular; }
typedef unsigned char ValueTagSize;
// If there is no mismatch, no other members should be inspected
ValueTagSize _mismatch : 1; // local FVar topology does not match
ValueTagSize _xordinary : 1; // local FVar topology is extra-ordinary
ValueTagSize _nonManifold : 1; // local FVar topology is non-manifold
ValueTagSize _crease : 1; // value is a crease, otherwise a corner
ValueTagSize _semiSharp : 1; // value is a corner decaying to crease
ValueTagSize _depSharp : 1; // value is a corner by dependency on another
ValueTagSize _infSharpEdges : 1; // value is a corner by inf-sharp features
ValueTagSize _infIrregular : 1; // value span includes inf-sharp irregularity
Level::VTag combineWithLevelVTag(Level::VTag) const;
// Alternate constructor and accessor for dealing with integer bits directly:
explicit ValueTag(ValueTagSize bits) {
std::memcpy(this, &bits, sizeof(bits));
}
ValueTagSize getBits() const {
ValueTagSize bits;
std::memcpy(&bits, this, sizeof(bits));
return bits;
}
};
typedef Vtr::ConstArray<ValueTag> ConstValueTagArray;
typedef Vtr::Array<ValueTag> ValueTagArray;
//
// Simple struct containing the "end faces" of a crease, i.e. the faces which
// contain the FVar values to be used when interpolating the crease. (Prefer
// the struct over std::pair for its member names)
//
struct CreaseEndPair {
LocalIndex _startFace;
LocalIndex _endFace;
};
typedef Vtr::ConstArray<CreaseEndPair> ConstCreaseEndPairArray;
typedef Vtr::Array<CreaseEndPair> CreaseEndPairArray;
typedef LocalIndex Sibling;
typedef ConstLocalIndexArray ConstSiblingArray;
typedef LocalIndexArray SiblingArray;
public:
FVarLevel(Level const& level);
~FVarLevel();
// Queries for the entire channel:
Level const& getLevel() const { return _level; }
int getNumValues() const { return _valueCount; }
int getNumFaceValuesTotal() const { return (int) _faceVertValues.size(); }
bool isLinear() const { return _isLinear; }
bool hasLinearBoundaries() const { return _hasLinearBoundaries; }
bool hasSmoothBoundaries() const { return ! _hasLinearBoundaries; }
bool hasCreaseEnds() const { return hasSmoothBoundaries(); }
Sdc::Options getOptions() const { return _options; }
// Queries per face:
ConstIndexArray getFaceValues(Index fIndex) const;
IndexArray getFaceValues(Index fIndex);
// Queries per edge:
ETag getEdgeTag(Index eIndex) const { return _edgeTags[eIndex]; }
bool edgeTopologyMatches(Index eIndex) const { return !getEdgeTag(eIndex)._mismatch; }
// Queries per vertex (and its potential sibling values):
int getNumVertexValues(Index v) const { return _vertSiblingCounts[v]; }
Index getVertexValueOffset(Index v, Sibling i = 0) const { return _vertSiblingOffsets[v] + i; }
Index getVertexValue(Index v, Sibling i = 0) const { return _vertValueIndices[getVertexValueOffset(v,i)]; }
Index findVertexValueIndex(Index vertexIndex, Index valueIndex) const;
// Methods to access/modify array properties per vertex:
ConstIndexArray getVertexValues(Index vIndex) const;
IndexArray getVertexValues(Index vIndex);
ConstValueTagArray getVertexValueTags(Index vIndex) const;
ValueTagArray getVertexValueTags(Index vIndex);
ConstCreaseEndPairArray getVertexValueCreaseEnds(Index vIndex) const;
CreaseEndPairArray getVertexValueCreaseEnds(Index vIndex);
ConstSiblingArray getVertexFaceSiblings(Index vIndex) const;
SiblingArray getVertexFaceSiblings(Index vIndex);
// Queries per value:
ValueTag getValueTag(Index valueIndex) const { return _vertValueTags[valueIndex]; }
bool valueTopologyMatches(Index valueIndex) const { return !getValueTag(valueIndex)._mismatch; }
CreaseEndPair getValueCreaseEndPair(Index valueIndex) const { return _vertValueCreaseEnds[valueIndex]; }
// Tag queries related to faces (use Level methods for those returning Level::VTag/ETag)
void getFaceValueTags(Index faceIndex, ValueTag valueTags[]) const;
ValueTag getFaceCompositeValueTag(Index faceIndex) const;
// Higher-level topological queries, i.e. values in a neighborhood:
void getEdgeFaceValues(Index eIndex, int fIncToEdge, Index valuesPerVert[2]) const;
void getVertexEdgeValues(Index vIndex, Index valuesPerEdge[]) const;
void getVertexCreaseEndValues(Index vIndex, Sibling sibling, Index endValues[2]) const;
// Initialization and allocation helpers:
void setOptions(Sdc::Options const& options);
void resizeVertexValues(int numVertexValues);
void resizeValues(int numValues);
void resizeComponents();
// Topological analysis methods -- tagging and face-value population:
void completeTopologyFromFaceValues(int regBoundaryValence);
void initializeFaceValuesFromFaceVertices();
void initializeFaceValuesFromVertexFaceSiblings();
struct ValueSpan;
void gatherValueSpans(Index vIndex, ValueSpan * vValueSpans) const;
// Debugging methods:
bool validate() const;
void print() const;
void buildFaceVertexSiblingsFromVertexFaceSiblings(std::vector<Sibling>& fvSiblings) const;
private:
// Just as Refinements build Levels, FVarRefinements build FVarLevels...
friend class FVarRefinement;
Level const & _level;
// Linear interpolation options vary between channels:
Sdc::Options _options;
bool _isLinear;
bool _hasLinearBoundaries;
bool _hasDependentSharpness;
int _valueCount;
//
// Vectors recording face-varying topology including tags that help propagate
// data through the refinement hierarchy. Vectors are not sparse but most use
// 8-bit values relative to the local topology.
//
// The vector of face-values is actually redundant here, but is constructed as
// it is most convenient for clients. It represents almost half the memory of
// the topology (4 32-bit integers per face) and not surprisingly, populating
// it takes a considerable amount of the refinement time (1/3). We can reduce
// both if we are willing to compute these on demand for clients.
//
// Per-face (matches face-verts of corresponding level):
std::vector<Index> _faceVertValues;
// Per-edge:
std::vector<ETag> _edgeTags;
// Per-vertex:
std::vector<Sibling> _vertSiblingCounts;
std::vector<int> _vertSiblingOffsets;
std::vector<Sibling> _vertFaceSiblings;
// Per-value:
std::vector<Index> _vertValueIndices;
std::vector<ValueTag> _vertValueTags;
std::vector<CreaseEndPair> _vertValueCreaseEnds;
};
//
// Access/modify the values associated with each face:
//
inline ConstIndexArray
FVarLevel::getFaceValues(Index fIndex) const {
int vCount = _level.getNumFaceVertices(fIndex);
int vOffset = _level.getOffsetOfFaceVertices(fIndex);
return ConstIndexArray(&_faceVertValues[vOffset], vCount);
}
inline IndexArray
FVarLevel::getFaceValues(Index fIndex) {
int vCount = _level.getNumFaceVertices(fIndex);
int vOffset = _level.getOffsetOfFaceVertices(fIndex);
return IndexArray(&_faceVertValues[vOffset], vCount);
}
inline FVarLevel::ConstSiblingArray
FVarLevel::getVertexFaceSiblings(Index vIndex) const {
int vCount = _level.getNumVertexFaces(vIndex);
int vOffset = _level.getOffsetOfVertexFaces(vIndex);
return ConstSiblingArray(&_vertFaceSiblings[vOffset], vCount);
}
inline FVarLevel::SiblingArray
FVarLevel::getVertexFaceSiblings(Index vIndex) {
int vCount = _level.getNumVertexFaces(vIndex);
int vOffset = _level.getOffsetOfVertexFaces(vIndex);
return SiblingArray(&_vertFaceSiblings[vOffset], vCount);
}
inline ConstIndexArray
FVarLevel::getVertexValues(Index vIndex) const
{
int vCount = getNumVertexValues(vIndex);
int vOffset = getVertexValueOffset(vIndex);
return ConstIndexArray(&_vertValueIndices[vOffset], vCount);
}
inline IndexArray
FVarLevel::getVertexValues(Index vIndex)
{
int vCount = getNumVertexValues(vIndex);
int vOffset = getVertexValueOffset(vIndex);
return IndexArray(&_vertValueIndices[vOffset], vCount);
}
inline FVarLevel::ConstValueTagArray
FVarLevel::getVertexValueTags(Index vIndex) const
{
int vCount = getNumVertexValues(vIndex);
int vOffset = getVertexValueOffset(vIndex);
return ConstValueTagArray(&_vertValueTags[vOffset], vCount);
}
inline FVarLevel::ValueTagArray
FVarLevel::getVertexValueTags(Index vIndex)
{
int vCount = getNumVertexValues(vIndex);
int vOffset = getVertexValueOffset(vIndex);
return ValueTagArray(&_vertValueTags[vOffset], vCount);
}
inline FVarLevel::ConstCreaseEndPairArray
FVarLevel::getVertexValueCreaseEnds(Index vIndex) const
{
int vCount = getNumVertexValues(vIndex);
int vOffset = getVertexValueOffset(vIndex);
return ConstCreaseEndPairArray(&_vertValueCreaseEnds[vOffset], vCount);
}
inline FVarLevel::CreaseEndPairArray
FVarLevel::getVertexValueCreaseEnds(Index vIndex)
{
int vCount = getNumVertexValues(vIndex);
int vOffset = getVertexValueOffset(vIndex);
return CreaseEndPairArray(&_vertValueCreaseEnds[vOffset], vCount);
}
inline Index
FVarLevel::findVertexValueIndex(Index vertexIndex, Index valueIndex) const {
if (_level.getDepth() > 0) return valueIndex;
Index vvIndex = getVertexValueOffset(vertexIndex);
while (_vertValueIndices[vvIndex] != valueIndex) {
++ vvIndex;
}
return vvIndex;
}
//
// Methods related to tagging:
//
inline Level::ETag
FVarLevel::ETag::combineWithLevelETag(Level::ETag levelTag) const
{
if (this->_mismatch) {
levelTag._boundary = true;
levelTag._infSharp = true;
}
return levelTag;
}
inline Level::VTag
FVarLevel::ValueTag::combineWithLevelVTag(Level::VTag levelTag) const
{
if (this->_mismatch) {
//
// Semi-sharp FVar values are always tagged and treated as corners
// (at least three sharp edges (two boundary edges and one interior
// semi-sharp) and/or vertex is semi-sharp) until the sharpness has
// decayed, but they ultimately lie on the inf-sharp crease of the
// FVar boundary. Consider this when tagging inf-sharp features.
//
if (this->isCorner()) {
levelTag._rule = (Level::VTag::VTagSize) Sdc::Crease::RULE_CORNER;
} else {
levelTag._rule = (Level::VTag::VTagSize) Sdc::Crease::RULE_CREASE;
}
if (this->isCrease() || this->isSemiSharp()) {
levelTag._infSharp = false;
levelTag._infSharpCrease = true;
levelTag._corner = false;
} else {
levelTag._infSharp = true;
levelTag._infSharpCrease = false;
levelTag._corner = !this->_infIrregular && !this->_infSharpEdges;
}
levelTag._infSharpEdges = true;
levelTag._infIrregular = this->_infIrregular;
levelTag._boundary = true;
levelTag._xordinary = this->_xordinary;
levelTag._nonManifold |= this->_nonManifold;
}
return levelTag;
}
} // end namespace internal
} // end namespace Vtr
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_VTR_FVAR_LEVEL_H */
+117
View File
@@ -0,0 +1,117 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_VTR_FVAR_REFINEMENT_H
#define OPENSUBDIV3_VTR_FVAR_REFINEMENT_H
#include "../version.h"
#include "../sdc/types.h"
#include "../sdc/crease.h"
#include "../vtr/types.h"
#include "../vtr/refinement.h"
#include "../vtr/fvarLevel.h"
#include <vector>
#include <cassert>
#include <cstring>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Vtr {
namespace internal {
//
// FVarRefinement:
// A face-varying refinement contains data to support the refinement of a
// particular face-varying "channel". Just as Refinement maintains a mapping
// between the components of a parent Level and its child, the face-varying
// analog maintains a mapping between the face-varying values of a parent
// FVarLevel and its child.
//
// It turns out there is little data necessary here, so the class consists
// mainly of methods that populate the child FVarLevel. The mapping data in
// the refinement between Levels serves most purposes and all that is required
// in addition is a mapping from values in the child FVarLevel to the parent.
//
class FVarRefinement {
public:
FVarRefinement(Refinement const& refinement, FVarLevel& parent, FVarLevel& child);
~FVarRefinement();
int getChildValueParentSource(Index vIndex, int sibling) const {
return _childValueParentSource[_childFVar.getVertexValueOffset(vIndex, (LocalIndex)sibling)];
}
float getFractionalWeight(Index pVert, LocalIndex pSibling,
Index cVert, LocalIndex cSibling) const;
// Modifiers supporting application of the refinement:
void applyRefinement();
void estimateAndAllocateChildValues();
void populateChildValues();
void populateChildValuesFromFaceVertices();
void populateChildValuesFromEdgeVertices();
int populateChildValuesForEdgeVertex(Index cVert, Index pEdge);
void populateChildValuesFromVertexVertices();
int populateChildValuesForVertexVertex(Index cVert, Index pVert);
void trimAndFinalizeChildValues();
void propagateEdgeTags();
void propagateValueTags();
void propagateValueCreases();
void reclassifySemisharpValues();
private:
//
// Identify the Refinement, its Levels and assigned FVarLevels for more
// immediate access -- child FVarLevel is non-const as it is to be assigned:
//
Refinement const & _refinement;
Level const & _parentLevel;
FVarLevel const & _parentFVar;
Level const & _childLevel;
FVarLevel & _childFVar;
// When refinement is sparse, we need a mapping between siblings of a vertex
// value in the parent and child -- and for some child values, there will not
// be a parent value, in which case the source of the parent component will
// be stored. So we refer to the parent "source" rather than "sibling":
//
std::vector<LocalIndex> _childValueParentSource;
};
} // end namespace internal
} // end namespace Vtr
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_VTR_FVAR_REFINEMENT_H */
+879
View File
@@ -0,0 +1,879 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_VTR_LEVEL_H
#define OPENSUBDIV3_VTR_LEVEL_H
#include "../version.h"
#include "../sdc/types.h"
#include "../sdc/crease.h"
#include "../sdc/options.h"
#include "../vtr/types.h"
#include <algorithm>
#include <vector>
#include <cassert>
#include <cstring>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Vtr {
namespace internal {
class Refinement;
class TriRefinement;
class QuadRefinement;
class FVarRefinement;
class FVarLevel;
//
// Level:
// A refinement level includes a vectorized representation of the topology
// for a particular subdivision level. The topology is "complete" in that any
// level can be used as the base level of another subdivision hierarchy and can
// be considered a complete mesh independent of its ancestors. It currently
// does contain a "depth" member -- as some inferences can then be made about
// the topology (i.e. all quads or all tris if not level 0).
//
// This class is intended for private use within the library. There are still
// opportunities to specialize levels -- e.g. those supporting N-sided faces vs
// those that are purely quads or tris -- so we prefer to insulate it from public
// access.
//
// The representation of topology here is to store six topological relationships
// in tables of integers. Each is stored in its own array(s) so the result is
// a SOA representation of the topology. The six relations are:
//
// - face-verts: vertices incident/comprising a face
// - face-edges: edges incident a face
// - edge-verts: vertices incident/comprising an edge
// - edge-faces: faces incident an edge
// - vert-faces: faces incident a vertex
// - vert-edges: edges incident a vertex
//
// There is some redundancy here but the intent is not that this be a minimal
// representation, the intent is that it be amenable to refinement. Classes in
// the Far layer essentially store 5 of these 6 in a permuted form -- we add
// the face-edges here to simplify refinement.
//
class Level {
public:
//
// Simple nested types to hold the tags for each component type -- some of
// which are user-specified features (e.g. whether a face is a hole or not)
// while others indicate the topological nature of the component, how it
// is affected by creasing in its neighborhood, etc.
//
// Most of these properties are passed down to child components during
// refinement, but some -- notably the designation of a component as semi-
// sharp -- require re-determination as sharpness values are reduced at each
// level.
//
struct VTag {
VTag() { }
// When cleared, the VTag ALMOST represents a smooth, regular, interior
// vertex -- the Type enum requires a bit be explicitly set for Smooth,
// so that must be done explicitly if desired on initialization.
void clear() { std::memset(this, 0, sizeof(VTag)); }
typedef unsigned short VTagSize;
VTagSize _nonManifold : 1; // fixed
VTagSize _xordinary : 1; // fixed
VTagSize _boundary : 1; // fixed
VTagSize _corner : 1; // fixed
VTagSize _infSharp : 1; // fixed
VTagSize _semiSharp : 1; // variable
VTagSize _semiSharpEdges : 1; // variable
VTagSize _rule : 4; // variable when _semiSharp
// These next to tags are complementary -- the "incomplete" tag is only
// relevant for refined levels while the "incident an irregular face" tag
// is only relevant for the base level. They could be combined as both
// indicate "no full regular ring" around a vertex
VTagSize _incomplete : 1; // variable only set in refined levels
VTagSize _incidIrregFace : 1; // variable only set in base level
// Tags indicating incident infinitely-sharp (permanent) features
VTagSize _infSharpEdges : 1; // fixed
VTagSize _infSharpCrease : 1; // fixed
VTagSize _infIrregular : 1; // fixed
// Alternate constructor and accessor for dealing with integer bits directly:
explicit VTag(VTagSize bits) {
std::memcpy(this, &bits, sizeof(bits));
}
VTagSize getBits() const {
VTagSize bits;
std::memcpy(&bits, this, sizeof(bits));
return bits;
}
static VTag BitwiseOr(VTag const vTags[], int size = 4);
};
struct ETag {
ETag() { }
// When cleared, the ETag represents a smooth, manifold, interior edge
void clear() { std::memset(this, 0, sizeof(ETag)); }
typedef unsigned char ETagSize;
ETagSize _nonManifold : 1; // fixed
ETagSize _boundary : 1; // fixed
ETagSize _infSharp : 1; // fixed
ETagSize _semiSharp : 1; // variable
// Alternate constructor and accessor for dealing with integer bits directly:
explicit ETag(ETagSize bits) {
std::memcpy(this, &bits, sizeof(bits));
}
ETagSize getBits() const {
ETagSize bits;
std::memcpy(&bits, this, sizeof(bits));
return bits;
}
static ETag BitwiseOr(ETag const eTags[], int size = 4);
};
struct FTag {
FTag() { }
void clear() { std::memset(this, 0, sizeof(FTag)); }
typedef unsigned char FTagSize;
FTagSize _hole : 1; // fixed
// On deck -- coming soon...
//FTagSize _hasEdits : 1; // variable
};
// Additional simple struct to identify a "span" around a vertex, i.e. a
// subset of the faces around a vertex delimited by some property (e.g. a
// face-varying discontinuity, an inf-sharp edge, etc.)
//
// The span requires an "origin" and a "size" to fully define its extent.
// Use of the size is required over a leading/trailing pair as the valence
// around a non-manifold vertex cannot be trivially determined from two
// extremeties. Similarly a start face is chosen over an edge as starting
// with a manifold edge is ambiguous. Additional tags also support
// non-manifold cases, e.g. periodic spans at the apex of a double cone.
//
// Currently setting the size to 0 or leaving the span "unassigned" is an
// indication to use the full neighborhood rather than a subset -- prefer
// use of the const method here to direct inspection of the member.
//
struct VSpan {
VSpan() { std::memset(this, 0, sizeof(VSpan)); }
void clear() { std::memset(this, 0, sizeof(VSpan)); }
bool isAssigned() const { return _numFaces > 0; }
LocalIndex _numFaces;
LocalIndex _startFace;
LocalIndex _cornerInSpan;
unsigned short _periodic : 1;
unsigned short _sharp : 1;
};
public:
Level();
~Level();
// Simple accessors:
int getDepth() const { return _depth; }
int getNumVertices() const { return _vertCount; }
int getNumFaces() const { return _faceCount; }
int getNumEdges() const { return _edgeCount; }
// More global sizes may prove useful...
int getNumFaceVerticesTotal() const { return (int) _faceVertIndices.size(); }
int getNumFaceEdgesTotal() const { return (int) _faceEdgeIndices.size(); }
int getNumEdgeVerticesTotal() const { return (int) _edgeVertIndices.size(); }
int getNumEdgeFacesTotal() const { return (int) _edgeFaceIndices.size(); }
int getNumVertexFacesTotal() const { return (int) _vertFaceIndices.size(); }
int getNumVertexEdgesTotal() const { return (int) _vertEdgeIndices.size(); }
int getMaxValence() const { return _maxValence; }
int getMaxEdgeFaces() const { return _maxEdgeFaces; }
// Methods to access the relation tables/indices -- note that for some relations
// (i.e. those where a component is "contained by" a neighbor, or more generally
// when the neighbor is a simplex of higher dimension) we store an additional
// "local index", e.g. for the case of vert-faces if one of the faces F[i] is
// incident a vertex V, then L[i] is the "local index" in F[i] of vertex V.
// Once have only quads (or tris), this local index need only occupy two bits
// and could conceivably be packed into the same integer as the face index, but
// for now, given the need to support faces of potentially high valence we'll
// use an 8- or 16-bit integer.
//
// Methods to access the six topological relations:
ConstIndexArray getFaceVertices(Index faceIndex) const;
ConstIndexArray getFaceEdges(Index faceIndex) const;
ConstIndexArray getEdgeVertices(Index edgeIndex) const;
ConstIndexArray getEdgeFaces(Index edgeIndex) const;
ConstIndexArray getVertexFaces(Index vertIndex) const;
ConstIndexArray getVertexEdges(Index vertIndex) const;
ConstLocalIndexArray getEdgeFaceLocalIndices(Index edgeIndex) const;
ConstLocalIndexArray getVertexFaceLocalIndices(Index vertIndex) const;
ConstLocalIndexArray getVertexEdgeLocalIndices(Index vertIndex) const;
// Replace these with access to sharpness buffers/arrays rather than elements:
float getEdgeSharpness(Index edgeIndex) const;
float getVertexSharpness(Index vertIndex) const;
Sdc::Crease::Rule getVertexRule(Index vertIndex) const;
Index findEdge(Index v0Index, Index v1Index) const;
// Holes
void setFaceHole(Index faceIndex, bool b);
bool isFaceHole(Index faceIndex) const;
// Face-varying
Sdc::Options getFVarOptions(int channel) const;
int getNumFVarChannels() const { return (int) _fvarChannels.size(); }
int getNumFVarValues(int channel) const;
ConstIndexArray getFaceFVarValues(Index faceIndex, int channel) const;
FVarLevel & getFVarLevel(int channel) { return *_fvarChannels[channel]; }
FVarLevel const & getFVarLevel(int channel) const { return *_fvarChannels[channel]; }
// Manifold/non-manifold tags:
void setEdgeNonManifold(Index edgeIndex, bool b);
bool isEdgeNonManifold(Index edgeIndex) const;
void setVertexNonManifold(Index vertIndex, bool b);
bool isVertexNonManifold(Index vertIndex) const;
// General access to all component tags:
VTag const & getVertexTag(Index vertIndex) const { return _vertTags[vertIndex]; }
ETag const & getEdgeTag(Index edgeIndex) const { return _edgeTags[edgeIndex]; }
FTag const & getFaceTag(Index faceIndex) const { return _faceTags[faceIndex]; }
VTag & getVertexTag(Index vertIndex) { return _vertTags[vertIndex]; }
ETag & getEdgeTag(Index edgeIndex) { return _edgeTags[edgeIndex]; }
FTag & getFaceTag(Index faceIndex) { return _faceTags[faceIndex]; }
public:
// Debugging aides:
enum TopologyError {
TOPOLOGY_MISSING_EDGE_FACES=0,
TOPOLOGY_MISSING_EDGE_VERTS,
TOPOLOGY_MISSING_FACE_EDGES,
TOPOLOGY_MISSING_FACE_VERTS,
TOPOLOGY_MISSING_VERT_FACES,
TOPOLOGY_MISSING_VERT_EDGES,
TOPOLOGY_FAILED_CORRELATION_EDGE_FACE,
TOPOLOGY_FAILED_CORRELATION_FACE_VERT,
TOPOLOGY_FAILED_CORRELATION_FACE_EDGE,
TOPOLOGY_FAILED_ORIENTATION_INCIDENT_EDGE,
TOPOLOGY_FAILED_ORIENTATION_INCIDENT_FACE,
TOPOLOGY_FAILED_ORIENTATION_INCIDENT_FACES_EDGES,
TOPOLOGY_DEGENERATE_EDGE,
TOPOLOGY_NON_MANIFOLD_EDGE,
TOPOLOGY_INVALID_CREASE_EDGE,
TOPOLOGY_INVALID_CREASE_VERT
};
static char const * getTopologyErrorString(TopologyError errCode);
typedef void (* ValidationCallback)(TopologyError errCode, char const * msg, void const * clientData);
bool validateTopology(ValidationCallback callback=0, void const * clientData=0) const;
void print(const Refinement* parentRefinement = 0) const;
public:
// High-level topology queries -- these may be moved elsewhere:
bool isSingleCreasePatch(Index face, float* sharpnessOut=NULL, int* rotationOut=NULL) const;
//
// When inspecting topology, the component tags -- particularly VTag and ETag -- are most
// often inspected in groups for the face to which they belong. They are designed to be
// bitwise OR'd (the result then referred to as a "composite" tag) to make quick decisions
// about the face as a whole to avoid tedious topological inspection.
//
// The same logic can be applied to topology in a FVar channel when tags specific to that
// channel are used. Note that the VTags apply to the FVar values assigned to the corners
// of the face and not the vertex as a whole. The "composite" face-varying VTag for a
// vertex is the union of VTags of all distinct FVar values for that vertex.
//
bool doesVertexFVarTopologyMatch(Index vIndex, int fvarChannel) const;
bool doesFaceFVarTopologyMatch( Index fIndex, int fvarChannel) const;
bool doesEdgeFVarTopologyMatch( Index eIndex, int fvarChannel) const;
void getFaceVTags(Index fIndex, VTag vTags[], int fvarChannel = -1) const;
void getFaceETags(Index fIndex, ETag eTags[], int fvarChannel = -1) const;
VTag getFaceCompositeVTag(Index fIndex, int fvarChannel = -1) const;
VTag getFaceCompositeVTag(ConstIndexArray & fVerts) const;
VTag getVertexCompositeFVarVTag(Index vIndex, int fvarChannel) const;
//
// When gathering "patch points" we may want the indices of the vertices or the corresponding
// FVar values for a particular channel. Both are represented and equally accessible within
// the faces, so we allow all to be returned through these methods. Setting the optional FVar
// channel to -1 will retrieve indices of vertices instead of FVar values:
//
int gatherQuadLinearPatchPoints(Index fIndex, Index patchPoints[], int rotation = 0,
int fvarChannel = -1) const;
int gatherQuadRegularInteriorPatchPoints(Index fIndex, Index patchPoints[], int rotation = 0,
int fvarChannel = -1) const;
int gatherQuadRegularBoundaryPatchPoints(Index fIndex, Index patchPoints[], int boundaryEdgeInFace,
int fvarChannel = -1) const;
int gatherQuadRegularCornerPatchPoints( Index fIndex, Index patchPoints[], int cornerVertInFace,
int fvarChannel = -1) const;
int gatherQuadRegularRingAroundVertex(Index vIndex, Index ringPoints[],
int fvarChannel = -1) const;
int gatherQuadRegularPartialRingAroundVertex(Index vIndex, VSpan const & span, Index ringPoints[],
int fvarChannel = -1) const;
// WIP -- for future use, need to extend for face-varying...
int gatherTriRegularInteriorPatchPoints( Index fIndex, Index patchVerts[], int rotation = 0) const;
int gatherTriRegularBoundaryVertexPatchPoints(Index fIndex, Index patchVerts[], int boundaryVertInFace) const;
int gatherTriRegularBoundaryEdgePatchPoints( Index fIndex, Index patchVerts[], int boundaryEdgeInFace) const;
int gatherTriRegularCornerVertexPatchPoints( Index fIndex, Index patchVerts[], int cornerVertInFace) const;
int gatherTriRegularCornerEdgePatchPoints( Index fIndex, Index patchVerts[], int cornerEdgeInFace) const;
public:
// Sizing methods used to construct a level to populate:
void resizeFaces( int numFaces);
void resizeFaceVertices(int numFaceVertsTotal);
void resizeFaceEdges( int numFaceEdgesTotal);
void resizeEdges( int numEdges);
void resizeEdgeVertices(); // always 2*edgeCount
void resizeEdgeFaces(int numEdgeFacesTotal);
void resizeVertices( int numVertices);
void resizeVertexFaces(int numVertexFacesTotal);
void resizeVertexEdges(int numVertexEdgesTotal);
void setMaxValence(int maxValence);
// Modifiers to populate the relations for each component:
IndexArray getFaceVertices(Index faceIndex);
IndexArray getFaceEdges(Index faceIndex);
IndexArray getEdgeVertices(Index edgeIndex);
IndexArray getEdgeFaces(Index edgeIndex);
IndexArray getVertexFaces(Index vertIndex);
IndexArray getVertexEdges(Index vertIndex);
LocalIndexArray getEdgeFaceLocalIndices(Index edgeIndex);
LocalIndexArray getVertexFaceLocalIndices(Index vertIndex);
LocalIndexArray getVertexEdgeLocalIndices(Index vertIndex);
// Replace these with access to sharpness buffers/arrays rather than elements:
float& getEdgeSharpness(Index edgeIndex);
float& getVertexSharpness(Index vertIndex);
// Create, destroy and populate face-varying channels:
int createFVarChannel(int fvarValueCount, Sdc::Options const& options);
void destroyFVarChannel(int channel);
IndexArray getFaceFVarValues(Index faceIndex, int channel);
void completeFVarChannelTopology(int channel, int regBoundaryValence);
// Counts and offsets for all relation types:
// - these may be unwarranted if we let Refinement access members directly...
int getNumFaceVertices( Index faceIndex) const { return _faceVertCountsAndOffsets[2*faceIndex]; }
int getOffsetOfFaceVertices(Index faceIndex) const { return _faceVertCountsAndOffsets[2*faceIndex + 1]; }
int getNumFaceEdges( Index faceIndex) const { return getNumFaceVertices(faceIndex); }
int getOffsetOfFaceEdges(Index faceIndex) const { return getOffsetOfFaceVertices(faceIndex); }
int getNumEdgeVertices( Index ) const { return 2; }
int getOffsetOfEdgeVertices(Index edgeIndex) const { return 2 * edgeIndex; }
int getNumEdgeFaces( Index edgeIndex) const { return _edgeFaceCountsAndOffsets[2*edgeIndex]; }
int getOffsetOfEdgeFaces(Index edgeIndex) const { return _edgeFaceCountsAndOffsets[2*edgeIndex + 1]; }
int getNumVertexFaces( Index vertIndex) const { return _vertFaceCountsAndOffsets[2*vertIndex]; }
int getOffsetOfVertexFaces(Index vertIndex) const { return _vertFaceCountsAndOffsets[2*vertIndex + 1]; }
int getNumVertexEdges( Index vertIndex) const { return _vertEdgeCountsAndOffsets[2*vertIndex]; }
int getOffsetOfVertexEdges(Index vertIndex) const { return _vertEdgeCountsAndOffsets[2*vertIndex + 1]; }
ConstIndexArray getFaceVertices() const;
//
// Note that for some relations, the size of the relations for a child component
// can vary radically from its parent due to the sparsity of the refinement. So
// in these cases a few additional utilities are provided to help define the set
// of incident components. Assuming adequate memory has been allocated, the
// "resize" methods here initialize the set of incident components by setting
// both the size and the appropriate offset, while "trim" is use to quickly lower
// the size from an upper bound and nothing else.
//
void resizeFaceVertices(Index FaceIndex, int count);
void resizeEdgeFaces(Index edgeIndex, int count);
void trimEdgeFaces( Index edgeIndex, int count);
void resizeVertexFaces(Index vertIndex, int count);
void trimVertexFaces( Index vertIndex, int count);
void resizeVertexEdges(Index vertIndex, int count);
void trimVertexEdges( Index vertIndex, int count);
public:
//
// Initial plans were to have a few specific classes properly construct the
// topology from scratch, e.g. the Refinement class and a Factory class for
// the base level, by populating all topological relations. The need to have
// a class construct full topology given only a simple face-vertex list, made
// it necessary to write code to define and orient all relations -- and most
// of that seemed best placed here.
//
bool completeTopologyFromFaceVertices();
Index findEdge(Index v0, Index v1, ConstIndexArray v0Edges) const;
// Methods supporting the above:
void orientIncidentComponents();
bool orderVertexFacesAndEdges(Index vIndex, Index* vFaces, Index* vEdges) const;
bool orderVertexFacesAndEdges(Index vIndex);
void populateLocalIndices();
IndexArray shareFaceVertCountsAndOffsets() const;
private:
// Refinement classes (including all subclasses) build a Level:
friend class Refinement;
friend class TriRefinement;
friend class QuadRefinement;
//
// A Level is independent of subdivision scheme or options. While it may have been
// affected by them in its construction, they are not associated with it -- a Level
// is pure topology and any subdivision parameters are external.
//
// Simple members for inventory, etc.
int _faceCount;
int _edgeCount;
int _vertCount;
// The "depth" member is clearly useful in both the topological splitting and the
// stencil queries, but arguably it ties the Level to a hierarchy which counters
// the idea of it being independent.
int _depth;
// Maxima to help clients manage sizing of data buffers. Given "max valence",
// the "max edge faces" is strictly redundant as it will always be less, but
// since it will typically be so much less (i.e. 2) it is kept for now.
int _maxEdgeFaces;
int _maxValence;
//
// Topology vectors:
// Note that of all of these, only data for the face-edge relation is not
// stored in the osd::FarTables in any form. The FarTable vectors combine
// the edge-vert and edge-face relations. The eventual goal is that this
// data be part of the osd::Far classes and be a superset of the FarTable
// vectors, i.e. no data duplication or conversion. The fact that FarTable
// already stores 5 of the 6 possible relations should make the topology
// storage as a whole a non-issue.
//
// The vert-face-child and vert-edge-child indices are also arguably not
// a topology relation but more one for parent/child relations. But it is
// a topological relationship, and if named differently would not likely
// raise this. It has been named with "child" in the name as it does play
// a more significant role during subdivision in mapping between parent
// and child components, and so has been named to reflect that more clearly.
//
// Per-face:
std::vector<Index> _faceVertCountsAndOffsets; // 2 per face, redundant after level 0
std::vector<Index> _faceVertIndices; // 3 or 4 per face, variable at level 0
std::vector<Index> _faceEdgeIndices; // matches face-vert indices
std::vector<FTag> _faceTags; // 1 per face: includes "hole" tag
// Per-edge:
std::vector<Index> _edgeVertIndices; // 2 per edge
std::vector<Index> _edgeFaceCountsAndOffsets; // 2 per edge
std::vector<Index> _edgeFaceIndices; // varies with faces per edge
std::vector<LocalIndex> _edgeFaceLocalIndices; // varies with faces per edge
std::vector<float> _edgeSharpness; // 1 per edge
std::vector<ETag> _edgeTags; // 1 per edge: manifold, boundary, etc.
// Per-vertex:
std::vector<Index> _vertFaceCountsAndOffsets; // 2 per vertex
std::vector<Index> _vertFaceIndices; // varies with valence
std::vector<LocalIndex> _vertFaceLocalIndices; // varies with valence, 8-bit for now
std::vector<Index> _vertEdgeCountsAndOffsets; // 2 per vertex
std::vector<Index> _vertEdgeIndices; // varies with valence
std::vector<LocalIndex> _vertEdgeLocalIndices; // varies with valence, 8-bit for now
std::vector<float> _vertSharpness; // 1 per vertex
std::vector<VTag> _vertTags; // 1 per vertex: manifold, Sdc::Rule, etc.
// Face-varying channels:
std::vector<FVarLevel*> _fvarChannels;
};
//
// Access/modify the vertices incident a given face:
//
inline ConstIndexArray
Level::getFaceVertices(Index faceIndex) const {
return ConstIndexArray(&_faceVertIndices[_faceVertCountsAndOffsets[faceIndex*2+1]],
_faceVertCountsAndOffsets[faceIndex*2]);
}
inline IndexArray
Level::getFaceVertices(Index faceIndex) {
return IndexArray(&_faceVertIndices[_faceVertCountsAndOffsets[faceIndex*2+1]],
_faceVertCountsAndOffsets[faceIndex*2]);
}
inline void
Level::resizeFaceVertices(Index faceIndex, int count) {
int* countOffsetPair = &_faceVertCountsAndOffsets[faceIndex*2];
countOffsetPair[0] = count;
countOffsetPair[1] = (faceIndex == 0) ? 0 : (countOffsetPair[-2] + countOffsetPair[-1]);
_maxValence = std::max(_maxValence, count);
}
inline ConstIndexArray
Level::getFaceVertices() const {
return ConstIndexArray(&_faceVertIndices[0], (int)_faceVertIndices.size());
}
//
// Access/modify the edges incident a given face:
//
inline ConstIndexArray
Level::getFaceEdges(Index faceIndex) const {
return ConstIndexArray(&_faceEdgeIndices[_faceVertCountsAndOffsets[faceIndex*2+1]],
_faceVertCountsAndOffsets[faceIndex*2]);
}
inline IndexArray
Level::getFaceEdges(Index faceIndex) {
return IndexArray(&_faceEdgeIndices[_faceVertCountsAndOffsets[faceIndex*2+1]],
_faceVertCountsAndOffsets[faceIndex*2]);
}
//
// Access/modify the faces incident a given vertex:
//
inline ConstIndexArray
Level::getVertexFaces(Index vertIndex) const {
return ConstIndexArray( (&_vertFaceIndices[0]) + _vertFaceCountsAndOffsets[vertIndex*2+1],
_vertFaceCountsAndOffsets[vertIndex*2]);
}
inline IndexArray
Level::getVertexFaces(Index vertIndex) {
return IndexArray( (&_vertFaceIndices[0]) + _vertFaceCountsAndOffsets[vertIndex*2+1],
_vertFaceCountsAndOffsets[vertIndex*2]);
}
inline ConstLocalIndexArray
Level::getVertexFaceLocalIndices(Index vertIndex) const {
return ConstLocalIndexArray( (&_vertFaceLocalIndices[0]) + _vertFaceCountsAndOffsets[vertIndex*2+1],
_vertFaceCountsAndOffsets[vertIndex*2]);
}
inline LocalIndexArray
Level::getVertexFaceLocalIndices(Index vertIndex) {
return LocalIndexArray( (&_vertFaceLocalIndices[0]) + _vertFaceCountsAndOffsets[vertIndex*2+1],
_vertFaceCountsAndOffsets[vertIndex*2]);
}
inline void
Level::resizeVertexFaces(Index vertIndex, int count) {
int* countOffsetPair = &_vertFaceCountsAndOffsets[vertIndex*2];
countOffsetPair[0] = count;
countOffsetPair[1] = (vertIndex == 0) ? 0 : (countOffsetPair[-2] + countOffsetPair[-1]);
}
inline void
Level::trimVertexFaces(Index vertIndex, int count) {
_vertFaceCountsAndOffsets[vertIndex*2] = count;
}
//
// Access/modify the edges incident a given vertex:
//
inline ConstIndexArray
Level::getVertexEdges(Index vertIndex) const {
return ConstIndexArray( (&_vertEdgeIndices[0]) +_vertEdgeCountsAndOffsets[vertIndex*2+1],
_vertEdgeCountsAndOffsets[vertIndex*2]);
}
inline IndexArray
Level::getVertexEdges(Index vertIndex) {
return IndexArray( (&_vertEdgeIndices[0]) +_vertEdgeCountsAndOffsets[vertIndex*2+1],
_vertEdgeCountsAndOffsets[vertIndex*2]);
}
inline ConstLocalIndexArray
Level::getVertexEdgeLocalIndices(Index vertIndex) const {
return ConstLocalIndexArray( (&_vertEdgeLocalIndices[0]) + _vertEdgeCountsAndOffsets[vertIndex*2+1],
_vertEdgeCountsAndOffsets[vertIndex*2]);
}
inline LocalIndexArray
Level::getVertexEdgeLocalIndices(Index vertIndex) {
return LocalIndexArray( (&_vertEdgeLocalIndices[0]) + _vertEdgeCountsAndOffsets[vertIndex*2+1],
_vertEdgeCountsAndOffsets[vertIndex*2]);
}
inline void
Level::resizeVertexEdges(Index vertIndex, int count) {
int* countOffsetPair = &_vertEdgeCountsAndOffsets[vertIndex*2];
countOffsetPair[0] = count;
countOffsetPair[1] = (vertIndex == 0) ? 0 : (countOffsetPair[-2] + countOffsetPair[-1]);
_maxValence = std::max(_maxValence, count);
}
inline void
Level::trimVertexEdges(Index vertIndex, int count) {
_vertEdgeCountsAndOffsets[vertIndex*2] = count;
}
inline void
Level::setMaxValence(int valence) {
_maxValence = valence;
}
//
// Access/modify the vertices incident a given edge:
//
inline ConstIndexArray
Level::getEdgeVertices(Index edgeIndex) const {
return ConstIndexArray(&_edgeVertIndices[edgeIndex*2], 2);
}
inline IndexArray
Level::getEdgeVertices(Index edgeIndex) {
return IndexArray(&_edgeVertIndices[edgeIndex*2], 2);
}
//
// Access/modify the faces incident a given edge:
//
inline ConstIndexArray
Level::getEdgeFaces(Index edgeIndex) const {
return ConstIndexArray(&_edgeFaceIndices[0] +
_edgeFaceCountsAndOffsets[edgeIndex*2+1],
_edgeFaceCountsAndOffsets[edgeIndex*2]);
}
inline IndexArray
Level::getEdgeFaces(Index edgeIndex) {
return IndexArray(&_edgeFaceIndices[0] +
_edgeFaceCountsAndOffsets[edgeIndex*2+1],
_edgeFaceCountsAndOffsets[edgeIndex*2]);
}
inline ConstLocalIndexArray
Level::getEdgeFaceLocalIndices(Index edgeIndex) const {
return ConstLocalIndexArray(&_edgeFaceLocalIndices[0] +
_edgeFaceCountsAndOffsets[edgeIndex*2+1],
_edgeFaceCountsAndOffsets[edgeIndex*2]);
}
inline LocalIndexArray
Level::getEdgeFaceLocalIndices(Index edgeIndex) {
return LocalIndexArray(&_edgeFaceLocalIndices[0] +
_edgeFaceCountsAndOffsets[edgeIndex*2+1],
_edgeFaceCountsAndOffsets[edgeIndex*2]);
}
inline void
Level::resizeEdgeFaces(Index edgeIndex, int count) {
int* countOffsetPair = &_edgeFaceCountsAndOffsets[edgeIndex*2];
countOffsetPair[0] = count;
countOffsetPair[1] = (edgeIndex == 0) ? 0 : (countOffsetPair[-2] + countOffsetPair[-1]);
_maxEdgeFaces = std::max(_maxEdgeFaces, count);
}
inline void
Level::trimEdgeFaces(Index edgeIndex, int count) {
_edgeFaceCountsAndOffsets[edgeIndex*2] = count;
}
//
// Access/modify sharpness values:
//
inline float
Level::getEdgeSharpness(Index edgeIndex) const {
return _edgeSharpness[edgeIndex];
}
inline float&
Level::getEdgeSharpness(Index edgeIndex) {
return _edgeSharpness[edgeIndex];
}
inline float
Level::getVertexSharpness(Index vertIndex) const {
return _vertSharpness[vertIndex];
}
inline float&
Level::getVertexSharpness(Index vertIndex) {
return _vertSharpness[vertIndex];
}
inline Sdc::Crease::Rule
Level::getVertexRule(Index vertIndex) const {
return (Sdc::Crease::Rule) _vertTags[vertIndex]._rule;
}
//
// Access/modify hole tag:
//
inline void
Level::setFaceHole(Index faceIndex, bool b) {
_faceTags[faceIndex]._hole = b;
}
inline bool
Level::isFaceHole(Index faceIndex) const {
return _faceTags[faceIndex]._hole;
}
//
// Access/modify non-manifold tags:
//
inline void
Level::setEdgeNonManifold(Index edgeIndex, bool b) {
_edgeTags[edgeIndex]._nonManifold = b;
}
inline bool
Level::isEdgeNonManifold(Index edgeIndex) const {
return _edgeTags[edgeIndex]._nonManifold;
}
inline void
Level::setVertexNonManifold(Index vertIndex, bool b) {
_vertTags[vertIndex]._nonManifold = b;
}
inline bool
Level::isVertexNonManifold(Index vertIndex) const {
return _vertTags[vertIndex]._nonManifold;
}
//
// Sizing methods to allocate space:
//
inline void
Level::resizeFaces(int faceCount) {
_faceCount = faceCount;
_faceVertCountsAndOffsets.resize(2 * faceCount);
_faceTags.resize(faceCount);
std::memset(&_faceTags[0], 0, _faceCount * sizeof(FTag));
}
inline void
Level::resizeFaceVertices(int totalFaceVertCount) {
_faceVertIndices.resize(totalFaceVertCount);
}
inline void
Level::resizeFaceEdges(int totalFaceEdgeCount) {
_faceEdgeIndices.resize(totalFaceEdgeCount);
}
inline void
Level::resizeEdges(int edgeCount) {
_edgeCount = edgeCount;
_edgeFaceCountsAndOffsets.resize(2 * edgeCount);
_edgeSharpness.resize(edgeCount);
_edgeTags.resize(edgeCount);
if (edgeCount>0) {
std::memset(&_edgeTags[0], 0, _edgeCount * sizeof(ETag));
}
}
inline void
Level::resizeEdgeVertices() {
_edgeVertIndices.resize(2 * _edgeCount);
}
inline void
Level::resizeEdgeFaces(int totalEdgeFaceCount) {
_edgeFaceIndices.resize(totalEdgeFaceCount);
_edgeFaceLocalIndices.resize(totalEdgeFaceCount);
}
inline void
Level::resizeVertices(int vertCount) {
_vertCount = vertCount;
_vertFaceCountsAndOffsets.resize(2 * vertCount);
_vertEdgeCountsAndOffsets.resize(2 * vertCount);
_vertSharpness.resize(vertCount);
_vertTags.resize(vertCount);
std::memset(&_vertTags[0], 0, _vertCount * sizeof(VTag));
}
inline void
Level::resizeVertexFaces(int totalVertFaceCount) {
_vertFaceIndices.resize(totalVertFaceCount);
_vertFaceLocalIndices.resize(totalVertFaceCount);
}
inline void
Level::resizeVertexEdges(int totalVertEdgeCount) {
_vertEdgeIndices.resize(totalVertEdgeCount);
_vertEdgeLocalIndices.resize(totalVertEdgeCount);
}
inline IndexArray
Level::shareFaceVertCountsAndOffsets() const {
// XXXX manuelk we have to force const casting here (classes don't 'share'
// members usually...)
return IndexArray(const_cast<Index *>(&_faceVertCountsAndOffsets[0]),
(int)_faceVertCountsAndOffsets.size());
}
} // end namespace internal
} // end namespace Vtr
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_VTR_LEVEL_H */
+456
View File
@@ -0,0 +1,456 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_VTR_REFINEMENT_H
#define OPENSUBDIV3_VTR_REFINEMENT_H
#include "../version.h"
#include "../sdc/types.h"
#include "../sdc/options.h"
#include "../vtr/types.h"
#include "../vtr/level.h"
#include <vector>
//
// Declaration for the main refinement class (Refinement) and its pre-requisites:
//
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Vtr {
namespace internal {
class FVarRefinement;
//
// Refinement:
// A refinement is a mapping between two levels -- relating the components in the original
// (parent) level to the one refined (child). The refinement may be complete (uniform) or sparse
// (adaptive or otherwise selective), so not all components in the parent level will spawn
// components in the child level.
//
// Refinement is an abstract class and expects subclasses corresponding to the different types
// of topological splits that the supported subdivision schemes collectively require, i.e. those
// listed in Sdc::SplitType. Note the virtual requirements expected of the subclasses in the list
// of protected methods -- they differ mainly in the topology that is created in the child Level
// and not the propagation of tags through refinement, subdivision of sharpness values or the
// treatment of face-varying data. The primary subclasses are QuadRefinement and TriRefinement.
//
// At a high level, all that is necessary in terms of interface is to construct, initialize
// (linking the two levels), optionally select components for sparse refinement (via use of the
// SparseSelector) and call the refine() method. This usage is expected of Far::TopologyRefiner.
//
// Since we really want this class to be restricted from public access eventually, all methods
// begin with lower case (as is the convention for protected methods) and the list of friends
// will be maintained more strictly.
//
class Refinement {
public:
Refinement(Level const & parent, Level & child, Sdc::Options const& schemeOptions);
virtual ~Refinement();
Level const& parent() const { return *_parent; }
Level const& child() const { return *_child; }
Level& child() { return *_child; }
Sdc::Split getSplitType() const { return _splitType; }
int getRegularFaceSize() const { return _regFaceSize; }
Sdc::Options getOptions() const { return _options; }
// Face-varying:
int getNumFVarChannels() const { return (int) _fvarChannels.size(); }
FVarRefinement const & getFVarRefinement(int c) const { return *_fvarChannels[c]; }
//
// Options associated with the actual refinement operation, which may end up
// quite involved if we want to allow for the refinement of data that is not
// of interest to be suppressed. For now we have:
//
// "sparse": the alternative to uniform refinement, which requires that
// components be previously selected/marked to be included.
//
// "minimal topology": this is one that may get broken down into a finer
// set of options. It suppresses "full topology" in the child level
// and only generates what is minimally necessary for interpolation --
// which requires at least the face-vertices for faces, but also the
// vertex-faces for any face-varying channels present. So it will
// generate one or two of the six possible topological relations.
//
// These are strictly controlled right now, e.g. for sparse refinement, we
// currently enforce full topology at the finest level to allow for subsequent
// patch construction.
//
struct Options {
Options() : _sparse(false),
_faceVertsFirst(false),
_minimalTopology(false)
{ }
unsigned int _sparse : 1;
unsigned int _faceVertsFirst : 1;
unsigned int _minimalTopology : 1;
// Still under consideration:
//unsigned int _childToParentMap : 1;
};
void refine(Options options = Options());
bool hasFaceVerticesFirst() const { return _faceVertsFirst; }
public:
//
// Access to members -- some testing classes (involving vertex interpolation)
// currently make use of these:
//
int getNumChildFacesFromFaces() const { return _childFaceFromFaceCount; }
int getNumChildEdgesFromFaces() const { return _childEdgeFromFaceCount; }
int getNumChildEdgesFromEdges() const { return _childEdgeFromEdgeCount; }
int getNumChildVerticesFromFaces() const { return _childVertFromFaceCount; }
int getNumChildVerticesFromEdges() const { return _childVertFromEdgeCount; }
int getNumChildVerticesFromVertices() const { return _childVertFromVertCount; }
Index getFirstChildFaceFromFaces() const { return _firstChildFaceFromFace; }
Index getFirstChildEdgeFromFaces() const { return _firstChildEdgeFromFace; }
Index getFirstChildEdgeFromEdges() const { return _firstChildEdgeFromEdge; }
Index getFirstChildVertexFromFaces() const { return _firstChildVertFromFace; }
Index getFirstChildVertexFromEdges() const { return _firstChildVertFromEdge; }
Index getFirstChildVertexFromVertices() const { return _firstChildVertFromVert; }
Index getFaceChildVertex(Index f) const { return _faceChildVertIndex[f]; }
Index getEdgeChildVertex(Index e) const { return _edgeChildVertIndex[e]; }
Index getVertexChildVertex(Index v) const { return _vertChildVertIndex[v]; }
ConstIndexArray getFaceChildFaces(Index parentFace) const;
ConstIndexArray getFaceChildEdges(Index parentFace) const;
ConstIndexArray getEdgeChildEdges(Index parentEdge) const;
// Child-to-parent relationships
bool isChildVertexComplete(Index v) const { return ! _childVertexTag[v]._incomplete; }
Index getChildFaceParentFace(Index f) const { return _childFaceParentIndex[f]; }
int getChildFaceInParentFace(Index f) const { return _childFaceTag[f]._indexInParent; }
Index getChildEdgeParentIndex(Index e) const { return _childEdgeParentIndex[e]; }
Index getChildVertexParentIndex(Index v) const { return _childVertexParentIndex[v]; }
//
// Modifiers intended for internal/protected use:
//
public:
IndexArray getFaceChildFaces(Index parentFace);
IndexArray getFaceChildEdges(Index parentFace);
IndexArray getEdgeChildEdges(Index parentEdge);
public:
//
// Tags have now been added per-component in Level, but there is additional need to tag
// components within Refinement -- we can't tag the parent level components for any
// refinement (in order to keep it const) and tags associated with children that are
// specific to the child-to-parent mapping may not be warranted in the child level.
//
// Parent tags are only required for sparse refinement. The main property to tag is
// whether a component was selected, and so a single SparseTag is used for all three
// component types. Tagging if a component is "transitional" is also useful. This may
// only be necessary for edges but is currently packed into a mask per-edge for faces,
// which could be deferred, in which case "transitional" could be a single bit.
//
// Child tags are part of the child-to-parent mapping, which consists of the parent
// component index for each child component, plus a tag for the child indicating more
// about its relationship to its parent, e.g. is it completely defined, what the parent
// component type is, what is the index of the child within its parent, etc.
//
struct SparseTag {
SparseTag() : _selected(0), _transitional(0) { }
unsigned char _selected : 1; // component specifically selected for refinement
unsigned char _transitional : 4; // adjacent to a refined component (4-bits for face)
};
struct ChildTag {
ChildTag() { }
unsigned char _incomplete : 1; // incomplete neighborhood to represent limit of parent
unsigned char _parentType : 2; // type of parent component: vertex, edge or face
unsigned char _indexInParent : 2; // index of child wrt parent: 0-3, or iterative if N > 4
};
// Methods to access and modify tags:
SparseTag const & getParentFaceSparseTag( Index f) const { return _parentFaceTag[f]; }
SparseTag const & getParentEdgeSparseTag( Index e) const { return _parentEdgeTag[e]; }
SparseTag const & getParentVertexSparseTag(Index v) const { return _parentVertexTag[v]; }
SparseTag & getParentFaceSparseTag( Index f) { return _parentFaceTag[f]; }
SparseTag & getParentEdgeSparseTag( Index e) { return _parentEdgeTag[e]; }
SparseTag & getParentVertexSparseTag(Index v) { return _parentVertexTag[v]; }
ChildTag const & getChildFaceTag( Index f) const { return _childFaceTag[f]; }
ChildTag const & getChildEdgeTag( Index e) const { return _childEdgeTag[e]; }
ChildTag const & getChildVertexTag(Index v) const { return _childVertexTag[v]; }
ChildTag & getChildFaceTag( Index f) { return _childFaceTag[f]; }
ChildTag & getChildEdgeTag( Index e) { return _childEdgeTag[e]; }
ChildTag & getChildVertexTag(Index v) { return _childVertexTag[v]; }
// Remaining methods should really be protected -- for use by subclasses...
public:
//
// Methods involved in constructing the parent-to-child mapping -- when the
// refinement is sparse, additional methods are needed to identify the selection:
//
void populateParentToChildMapping();
void populateParentChildIndices();
void printParentToChildMapping() const;
virtual void allocateParentChildIndices() = 0;
// Supporting method for sparse refinement:
void initializeSparseSelectionTags();
void markSparseChildComponentIndices();
void markSparseVertexChildren();
void markSparseEdgeChildren();
virtual void markSparseFaceChildren() = 0;
void initializeChildComponentCounts();
//
// Methods involved in constructing the child-to-parent mapping:
//
void populateChildToParentMapping();
void populateFaceParentVectors(ChildTag const initialChildTags[2][4]);
void populateFaceParentFromParentFaces(ChildTag const initialChildTags[2][4]);
void populateEdgeParentVectors(ChildTag const initialChildTags[2][4]);
void populateEdgeParentFromParentFaces(ChildTag const initialChildTags[2][4]);
void populateEdgeParentFromParentEdges(ChildTag const initialChildTags[2][4]);
void populateVertexParentVectors(ChildTag const initialChildTags[2][4]);
void populateVertexParentFromParentFaces(ChildTag const initialChildTags[2][4]);
void populateVertexParentFromParentEdges(ChildTag const initialChildTags[2][4]);
void populateVertexParentFromParentVertices(ChildTag const initialChildTags[2][4]);
//
// Methods involved in propagating component tags from parent to child:
//
void propagateComponentTags();
void populateFaceTagVectors();
void populateFaceTagsFromParentFaces();
void populateEdgeTagVectors();
void populateEdgeTagsFromParentFaces();
void populateEdgeTagsFromParentEdges();
void populateVertexTagVectors();
void populateVertexTagsFromParentFaces();
void populateVertexTagsFromParentEdges();
void populateVertexTagsFromParentVertices();
//
// Methods (and types) involved in subdividing the topology -- though not
// fully exploited, any subset of the 6 relations can be generated:
//
struct Relations {
unsigned int _faceVertices : 1;
unsigned int _faceEdges : 1;
unsigned int _edgeVertices : 1;
unsigned int _edgeFaces : 1;
unsigned int _vertexFaces : 1;
unsigned int _vertexEdges : 1;
void setAll(bool enable) {
_faceVertices = enable;
_faceEdges = enable;
_edgeVertices = enable;
_edgeFaces = enable;
_vertexFaces = enable;
_vertexEdges = enable;
}
};
void subdivideTopology(Relations const& relationsToSubdivide);
virtual void populateFaceVertexRelation() = 0;
virtual void populateFaceEdgeRelation() = 0;
virtual void populateEdgeVertexRelation() = 0;
virtual void populateEdgeFaceRelation() = 0;
virtual void populateVertexFaceRelation() = 0;
virtual void populateVertexEdgeRelation() = 0;
//
// Methods involved in subdividing and inspecting sharpness values:
//
void subdivideSharpnessValues();
void subdivideVertexSharpness();
void subdivideEdgeSharpness();
void reclassifySemisharpVertices();
//
// Methods involved in subdividing face-varying topology:
//
void subdivideFVarChannels();
protected:
// A debug method of Level prints a Refinement (should really change this)
friend void Level::print(const Refinement *) const;
//
// Data members -- the logical grouping of some of these (and methods that make use
// of them) may lead to grouping them into a few utility classes or structs...
//
// Defined on construction:
Level const * _parent;
Level * _child;
Sdc::Options _options;
// Defined by the subclass:
Sdc::Split _splitType;
int _regFaceSize;
// Determined by the refinement options:
bool _uniform;
bool _faceVertsFirst;
//
// Inventory and ordering of the types of child components:
//
int _childFaceFromFaceCount; // arguably redundant (all faces originate from faces)
int _childEdgeFromFaceCount;
int _childEdgeFromEdgeCount;
int _childVertFromFaceCount;
int _childVertFromEdgeCount;
int _childVertFromVertCount;
int _firstChildFaceFromFace; // arguably redundant (all faces originate from faces)
int _firstChildEdgeFromFace;
int _firstChildEdgeFromEdge;
int _firstChildVertFromFace;
int _firstChildVertFromEdge;
int _firstChildVertFromVert;
//
// The parent-to-child mapping:
// These are vectors sized according to the number of parent components (and
// their topology) that contain references/indices to the child components that
// result from them by refinement. When refinement is sparse, parent components
// that have not spawned all child components will have their missing children
// marked as invalid.
//
// NOTE the "Array" members here. Often vectors within the Level can be shared
// with the Refinement, and an Array instance is used to do so. If not shared
// the subclass just initializes the Array members after allocating its own local
// vector members.
//
IndexArray _faceChildFaceCountsAndOffsets;
IndexArray _faceChildEdgeCountsAndOffsets;
IndexVector _faceChildFaceIndices; // *cannot* always use face-vert counts/offsets
IndexVector _faceChildEdgeIndices; // can use face-vert counts/offsets
IndexVector _faceChildVertIndex;
IndexVector _edgeChildEdgeIndices; // trivial/corresponding pair for each
IndexVector _edgeChildVertIndex;
IndexVector _vertChildVertIndex;
//
// The child-to-parent mapping:
//
IndexVector _childFaceParentIndex;
IndexVector _childEdgeParentIndex;
IndexVector _childVertexParentIndex;
std::vector<ChildTag> _childFaceTag;
std::vector<ChildTag> _childEdgeTag;
std::vector<ChildTag> _childVertexTag;
//
// Tags for sparse selection of components:
//
std::vector<SparseTag> _parentFaceTag;
std::vector<SparseTag> _parentEdgeTag;
std::vector<SparseTag> _parentVertexTag;
//
// Refinement data for face-varying channels present in the Levels being refined:
//
std::vector<FVarRefinement*> _fvarChannels;
};
inline ConstIndexArray
Refinement::getFaceChildFaces(Index parentFace) const {
return ConstIndexArray(&_faceChildFaceIndices[_faceChildFaceCountsAndOffsets[2*parentFace+1]],
_faceChildFaceCountsAndOffsets[2*parentFace]);
}
inline IndexArray
Refinement::getFaceChildFaces(Index parentFace) {
return IndexArray(&_faceChildFaceIndices[_faceChildFaceCountsAndOffsets[2*parentFace+1]],
_faceChildFaceCountsAndOffsets[2*parentFace]);
}
inline ConstIndexArray
Refinement::getFaceChildEdges(Index parentFace) const {
return ConstIndexArray(&_faceChildEdgeIndices[_faceChildEdgeCountsAndOffsets[2*parentFace+1]],
_faceChildEdgeCountsAndOffsets[2*parentFace]);
}
inline IndexArray
Refinement::getFaceChildEdges(Index parentFace) {
return IndexArray(&_faceChildEdgeIndices[_faceChildEdgeCountsAndOffsets[2*parentFace+1]],
_faceChildEdgeCountsAndOffsets[2*parentFace]);
}
inline ConstIndexArray
Refinement::getEdgeChildEdges(Index parentEdge) const {
return ConstIndexArray(&_edgeChildEdgeIndices[parentEdge*2], 2);
}
inline IndexArray
Refinement::getEdgeChildEdges(Index parentEdge) {
return IndexArray(&_edgeChildEdgeIndices[parentEdge*2], 2);
}
} // end namespace internal
} // end namespace Vtr
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_VTR_REFINEMENT_H */
+101
View File
@@ -0,0 +1,101 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_VTR_SPARSE_SELECTOR_H
#define OPENSUBDIV3_VTR_SPARSE_SELECTOR_H
#include "../version.h"
#include "../vtr/types.h"
#include "../vtr/refinement.h"
#include <vector>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Vtr {
namespace internal {
//
// SparseSelector:
// Class supporting "selection" of components in a Level for sparse Refinement.
// The term "selection" here implies interest in the limit for that component, i.e.
// the limit point for a selected vertex, the limit patch for a face, etc. So this
// class is responsible for ensuring that all neighboring components required to
// support the limit of those selected are included in the refinement.
//
// This class is associated with (and constructed given) a Refinement and its role
// is to initialize that Refinement instance for eventual sparse refinement. So it
// is a friend of and expected to modify the Refinement as part of the selection.
// Given its simplicity and scope it may be worth nesting it in Vtr::Refinement.
//
// While all three component types -- vertices, edges and faces -- can be selected,
// only selection of faces is currently used and actively supported as part of the
// feature-adaptive refinement.
//
class SparseSelector {
public:
SparseSelector(Refinement& refine) : _refine(&refine), _selected(false) { }
~SparseSelector() { }
void setRefinement(Refinement& refine) { _refine = &refine; }
Refinement& getRefinement() const { return *_refine; }
bool isSelectionEmpty() const { return !_selected; }
//
// Methods for selecting (and marking) components for refinement. All component indices
// refer to components in the parent:
//
void selectVertex(Index pVertex);
void selectEdge( Index pEdge);
void selectFace( Index pFace);
private:
SparseSelector() : _refine(0), _selected(false) { }
bool wasVertexSelected(Index pVertex) const { return _refine->getParentVertexSparseTag(pVertex)._selected; }
bool wasEdgeSelected( Index pEdge) const { return _refine->getParentEdgeSparseTag(pEdge)._selected; }
bool wasFaceSelected( Index pFace) const { return _refine->getParentFaceSparseTag(pFace)._selected; }
void markVertexSelected(Index pVertex) const { _refine->getParentVertexSparseTag(pVertex)._selected = true; }
void markEdgeSelected( Index pEdge) const { _refine->getParentEdgeSparseTag(pEdge)._selected = true; }
void markFaceSelected( Index pFace) const { _refine->getParentFaceSparseTag(pFace)._selected = true; }
void initializeSelection();
private:
Refinement* _refine;
bool _selected;
};
} // end namespace internal
} // end namespace Vtr
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_VTR_SPARSE_SELECTOR_H */
+227
View File
@@ -0,0 +1,227 @@
//
// Copyright 2015 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_VTR_STACK_BUFFER_H
#define OPENSUBDIV3_VTR_STACK_BUFFER_H
#include "../version.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Vtr {
namespace internal {
//
// The StackBuffer class is intended solely to take the place of VLAs (Variable
// Length Arrays) which most compilers support, but are not strictly standard C++.
// Portability concerns forces us to make use of either alloca() or some other
// mechanism to create small arrays on the stack that are typically based on the
// valence of a vertex -- small in general, but occasionally large.
//
// Note also that since the intent of this is to replace VLAs -- not general
// std::vectors -- support for std::vector functionality is intentionally limited
// and STL-like naming is avoided. Like a VLA there is no incremental growth.
// Support for resizing is available to reuse an instance at the beginning of a
// loop with a new size, but resizing in this case reinitializes all elements.
//
template <typename TYPE, unsigned int SIZE, bool POD_TYPE = false>
class StackBuffer
{
public:
typedef unsigned int size_type;
public:
// Constructors and destructor -- declared inline below:
StackBuffer();
StackBuffer(size_type size);
~StackBuffer();
public:
// Note the reliance on implicit casting so that it can be used similar to
// a VLA. This removes the need for operator[] as the resulting TYPE* will
// natively support []. (The presence of both TYPE* and operator[] also
// causes an ambiguous overloading error with 32-bit MSVC builds.)
operator TYPE const * () const { return _data; }
operator TYPE * () { return _data; }
size_type GetSize() const { return _size; }
void SetSize(size_type size);
void Reserve(size_type capacity);
private:
// Non-copyable:
StackBuffer(const StackBuffer<TYPE,SIZE,POD_TYPE> &) { }
StackBuffer& operator=(const StackBuffer<TYPE,SIZE,POD_TYPE> &) { return *this; }
void allocate(size_type capacity);
void deallocate();
void construct();
void destruct();
private:
TYPE * _data;
size_type _size;
size_type _capacity;
// Is alignment an issue here? The staticData arena will at least be double-word
// aligned within this struct, which meets current and most anticipated needs.
char _staticData[SIZE * sizeof(TYPE)];
char * _dynamicData;
};
//
// Core allocation/deallocation methods:
//
template <typename TYPE, unsigned int SIZE, bool POD_TYPE>
inline void
StackBuffer<TYPE,SIZE,POD_TYPE>::allocate(size_type capacity) {
// Again, is alignment an issue here? C++ spec says new will return pointer
// "suitably aligned" for conversion to pointers of other types, which implies
// at least an alignment of 16.
_dynamicData = static_cast<char*>(::operator new(capacity * sizeof(TYPE)));
_data = reinterpret_cast<TYPE*>(_dynamicData);
_capacity = capacity;
}
template <typename TYPE, unsigned int SIZE, bool POD_TYPE>
inline void
StackBuffer<TYPE,SIZE,POD_TYPE>::deallocate() {
::operator delete(_dynamicData);
_data = reinterpret_cast<TYPE*>(_staticData);
_capacity = SIZE;
}
//
// Explicit element-wise construction and destruction within allocated memory.
// Compilers do not always optimize out the iteration here even when there is
// no construction or destruction, so the POD_TYPE arguement can be used to
// force this when/if it becomes an issue (and it has been in some cases).
//
template <typename TYPE, unsigned int SIZE, bool POD_TYPE>
inline void
StackBuffer<TYPE,SIZE,POD_TYPE>::construct() {
for (size_type i = 0; i < _size; ++i) {
(void) new (&_data[i]) TYPE;
}
}
template <typename TYPE, unsigned int SIZE, bool POD_TYPE>
inline void
StackBuffer<TYPE,SIZE,POD_TYPE>::destruct() {
for (size_type i = 0; i < _size; ++i) {
_data[i].~TYPE();
}
}
//
// Inline constructors and destructor:
//
template <typename TYPE, unsigned int SIZE, bool POD_TYPE>
inline
StackBuffer<TYPE,SIZE,POD_TYPE>::StackBuffer() :
_data(reinterpret_cast<TYPE*>(_staticData)),
_size(0),
_capacity(SIZE),
_dynamicData(0) {
}
template <typename TYPE, unsigned int SIZE, bool POD_TYPE>
inline
StackBuffer<TYPE,SIZE,POD_TYPE>::StackBuffer(size_type size) :
_data(reinterpret_cast<TYPE*>(_staticData)),
_size(size),
_capacity(SIZE),
_dynamicData(0) {
if (size > SIZE) {
allocate(size);
}
if (!POD_TYPE) {
construct();
}
}
template <typename TYPE, unsigned int SIZE, bool POD_TYPE>
inline
StackBuffer<TYPE,SIZE,POD_TYPE>::~StackBuffer() {
if (!POD_TYPE) {
destruct();
}
deallocate();
}
//
// Inline sizing methods:
//
template <typename TYPE, unsigned int SIZE, bool POD_TYPE>
inline void
StackBuffer<TYPE,SIZE,POD_TYPE>::Reserve(size_type capacity) {
if (capacity > _capacity) {
if (!POD_TYPE) {
destruct();
}
deallocate();
allocate(capacity);
}
}
template <typename TYPE, unsigned int SIZE, bool POD_TYPE>
inline void
StackBuffer<TYPE,SIZE,POD_TYPE>::SetSize(size_type size)
{
if (!POD_TYPE) {
destruct();
}
if (size == 0) {
deallocate();
} else if (size > _capacity) {
deallocate();
allocate(size);
}
_size = size;
if (!POD_TYPE) {
construct();
}
}
} // end namespace internal
} // end namespace Vtr
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_VTR_STACK_BUFFER_H */
+92
View File
@@ -0,0 +1,92 @@
//
// Copyright 2014 DreamWorks Animation LLC.
//
// 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.
//
#ifndef OPENSUBDIV3_VTR_TYPES_H
#define OPENSUBDIV3_VTR_TYPES_H
#include "../version.h"
#include "../vtr/array.h"
#include <vector>
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Vtr {
//
// A few types (and constants) for use within Vtr and potentially by its
// clients (appropriately exported and retyped)
//
//
// Integer type and constants to index the vectors of components. Note that we
// can't use specific width integer types like uint32_t, etc. as use of stdint
// is not portable.
//
// The convention throughout the OpenSubdiv code is to use "int" in most places,
// with "unsigned int" being limited to a few cases (why?). So we continue that
// trend here and use "int" for topological indices (with -1 indicating "invalid")
// despite the fact that we lose half the range compared to using "uint" (with ~0
// as invalid).
//
typedef int Index;
static const Index INDEX_INVALID = -1;
inline bool IndexIsValid(Index index) { return (index != INDEX_INVALID); }
//
// Integer type and constants used to index one component within another. Ideally
// this is just 2 bits once refinement reduces faces to tris or quads -- and so
// could potentially be combined with an Index -- but we need something larger for
// the N-sided face.
//
typedef unsigned short LocalIndex;
// Declared as "int" since it's intended for more general use
static const int VALENCE_LIMIT = ((1 << 16) - 1); // std::numeric_limits<LocalIndex>::max()
//
// Collections of integer types in variable or fixed sized arrays. Note that the use
// of "vector" in the name indicates a class that wraps an std::vector (typically a
// member variable) which is fully resizable and owns its own storage, whereas "array"
// wraps a vtr::Array which uses a fixed block of pre-allocated memory.
//
typedef std::vector<Index> IndexVector;
typedef Array<Index> IndexArray;
typedef ConstArray<Index> ConstIndexArray;
typedef Array<LocalIndex> LocalIndexArray;
typedef ConstArray<LocalIndex> ConstLocalIndexArray;
} // end namespace Vtr
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif /* OPENSUBDIV3_VTR_TYPES_H */