Drop unused thekla_atlas dependency

Since f12cb82 @reduz dropped the use of the thirdparty thekla_atlas
library, which is replaced by xatlas.

Fixes #28180.
Fixes #28182.
This commit is contained in:
Rémi Verschelde 2019-04-19 11:42:58 +02:00
parent 1b3ea697c5
commit 6640f397f1
131 changed files with 0 additions and 32167 deletions

View file

@ -374,11 +374,6 @@ Comment: libSquish
Copyright: 2006, Simon Brown
License: Expat
Files: ./thirdparty/thekla_atlas/
Comment: Thekla Atlas
Copyright: 2013, Thekla, Inc
License: Expat
Files: ./thirdparty/tinyexr/
Comment: TinyEXR
Copyright: 2014-2018, Syoyo Fujita

View file

@ -180,7 +180,6 @@ opts.Add(BoolVariable('builtin_opus', "Use the built-in Opus library", True))
opts.Add(BoolVariable('builtin_pcre2', "Use the built-in PCRE2 library)", True))
opts.Add(BoolVariable('builtin_recast', "Use the built-in Recast library", True))
opts.Add(BoolVariable('builtin_squish', "Use the built-in squish library", True))
opts.Add(BoolVariable('builtin_thekla_atlas', "Use the built-in thekla_altas library", True))
opts.Add(BoolVariable('builtin_xatlas', "Use the built-in xatlas library", True))
opts.Add(BoolVariable('builtin_zlib', "Use the built-in zlib library", True))
opts.Add(BoolVariable('builtin_zstd', "Use the built-in Zstd library", True))

View file

@ -1,85 +0,0 @@
#!/usr/bin/env python
import platform
Import('env')
Import('env_modules')
env_thekla_unwrap = env_modules.Clone()
# Thirdparty source files
if env['builtin_thekla_atlas']:
thirdparty_dir = "#thirdparty/thekla_atlas/"
thirdparty_sources = [
"nvcore/Memory.cpp",
"nvcore/Debug.cpp",
"nvcore/StrLib.cpp",
"nvcore/FileSystem.cpp",
"nvcore/RadixSort.cpp",
"nvmath/Basis.cpp",
"nvmath/ConvexHull.cpp",
"nvmath/Fitting.cpp",
"nvmath/Plane.cpp",
"nvmath/ProximityGrid.cpp",
"nvmath/Random.cpp",
"nvmath/Solver.cpp",
"nvmath/Sparse.cpp",
"nvmath/TypeSerialization.cpp",
"poshlib/posh.c",
"nvimage/BitMap.cpp",
"nvimage/Image.cpp",
"nvmesh/BaseMesh.cpp",
"nvmesh/MeshBuilder.cpp",
"nvmesh/TriMesh.cpp",
"nvmesh/QuadTriMesh.cpp",
"nvmesh/MeshTopology.cpp",
"nvmesh/halfedge/Edge.cpp",
"nvmesh/halfedge/Mesh.cpp",
"nvmesh/halfedge/Face.cpp",
"nvmesh/halfedge/Vertex.cpp",
"nvmesh/geometry/Bounds.cpp",
"nvmesh/geometry/Measurements.cpp",
"nvmesh/raster/Raster.cpp",
"nvmesh/param/Atlas.cpp",
"nvmesh/param/AtlasBuilder.cpp",
"nvmesh/param/AtlasPacker.cpp",
"nvmesh/param/LeastSquaresConformalMap.cpp",
"nvmesh/param/OrthogonalProjectionMap.cpp",
"nvmesh/param/ParameterizationQuality.cpp",
"nvmesh/param/SingleFaceMap.cpp",
"nvmesh/param/Util.cpp",
"nvmesh/weld/VertexWeld.cpp",
"nvmesh/weld/Snap.cpp",
"thekla/thekla_atlas.cpp"
]
thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
env_thekla_unwrap.Append(CPPPATH=[thirdparty_dir, thirdparty_dir + "poshlib", thirdparty_dir + "nvcore", thirdparty_dir + "nvmesh"])
# upstream uses c++11
if (not env.msvc):
env_thekla_unwrap.Append(CXXFLAGS="-std=c++11")
if env["platform"] == 'x11':
# if not specifically one of the *BSD, then use LINUX as default
if platform.system() == "FreeBSD":
env_thekla_unwrap.Append(CCFLAGS=["-DNV_OS_FREEBSD", "-DPOSH_COMPILER_GCC"])
elif platform.system() == "OpenBSD":
env_thekla_unwrap.Append(CCFLAGS=["-DNV_OS_OPENBSD", "-DPOSH_COMPILER_GCC"])
else:
env_thekla_unwrap.Append(CCFLAGS=["-DNV_OS_LINUX", "-DPOSH_COMPILER_GCC"])
elif env["platform"] == 'osx':
env_thekla_unwrap.Append(CCFLAGS=["-DNV_OS_DARWIN", "-DPOSH_COMPILER_GCC"])
elif env["platform"] == 'windows':
if env.msvc:
env_thekla_unwrap.Append(CCFLAGS=["-DNV_OS_WIN32", "-DNV_CC_MSVC", "-DPOSH_COMPILER_MSVC" ])
else:
env_thekla_unwrap.Append(CCFLAGS=["-DNV_OS_MINGW", "-DNV_CC_GNUC", "-DPOSH_COMPILER_GCC", "-U__STRICT_ANSI__"])
env.Append(LIBS=["dbghelp"])
env_thirdparty = env_thekla_unwrap.Clone()
env_thirdparty.disable_warnings()
env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
# Godot source files
env_thekla_unwrap.add_source_files(env.modules_sources, "*.cpp")

View file

@ -1,6 +0,0 @@
def can_build(env, platform):
#return (env['tools'] and platform not in ["android", "ios"])
return False
def configure(env):
pass

View file

@ -1,124 +0,0 @@
/*************************************************************************/
/* register_types.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "register_types.h"
#include "core/error_macros.h"
#include "thirdparty/thekla_atlas/thekla/thekla_atlas.h"
#include <stdio.h>
#include <stdlib.h>
extern bool (*array_mesh_lightmap_unwrap_callback)(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, const int *p_face_materials, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y);
bool thekla_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, const int *p_face_materials, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y) {
//set up input mesh
Thekla::Atlas_Input_Mesh input_mesh;
input_mesh.face_array = new Thekla::Atlas_Input_Face[p_index_count / 3];
for (int i = 0; i < p_index_count / 3; i++) {
input_mesh.face_array[i].vertex_index[0] = p_indices[i * 3 + 0];
input_mesh.face_array[i].vertex_index[1] = p_indices[i * 3 + 1];
input_mesh.face_array[i].vertex_index[2] = p_indices[i * 3 + 2];
//printf("face %i - %i, %i, %i - mat %i\n", i, input_mesh.face_array[i].vertex_index[0], input_mesh.face_array[i].vertex_index[1], input_mesh.face_array[i].vertex_index[2], p_face_materials[i]);
input_mesh.face_array[i].material_index = p_face_materials[i];
}
input_mesh.vertex_array = new Thekla::Atlas_Input_Vertex[p_vertex_count];
for (int i = 0; i < p_vertex_count; i++) {
input_mesh.vertex_array[i].first_colocal = i; //wtf
for (int j = 0; j < 3; j++) {
input_mesh.vertex_array[i].position[j] = p_vertices[i * 3 + j];
input_mesh.vertex_array[i].normal[j] = p_normals[i * 3 + j];
}
input_mesh.vertex_array[i].uv[0] = 0;
input_mesh.vertex_array[i].uv[1] = 0;
//printf("vertex %i - %f, %f, %f\n", i, input_mesh.vertex_array[i].position[0], input_mesh.vertex_array[i].position[1], input_mesh.vertex_array[i].position[2]);
//printf("normal %i - %f, %f, %f\n", i, input_mesh.vertex_array[i].normal[0], input_mesh.vertex_array[i].normal[1], input_mesh.vertex_array[i].normal[2]);
}
input_mesh.face_count = p_index_count / 3;
input_mesh.vertex_count = p_vertex_count;
//set up options
Thekla::Atlas_Options options;
Thekla::atlas_set_default_options(&options);
options.packer_options.witness.packing_quality = 1;
options.packer_options.witness.texel_area = 1.0 / p_texel_size;
options.packer_options.witness.conservative = false;
//generate
Thekla::Atlas_Error err;
Thekla::Atlas_Output_Mesh *output = atlas_generate(&input_mesh, &options, &err);
delete[] input_mesh.face_array;
delete[] input_mesh.vertex_array;
if (output == NULL) {
ERR_PRINT("could not generate atlas output mesh");
return false;
}
if (err != Thekla::Atlas_Error_Success) {
printf("error with atlas\n");
} else {
*r_vertex = (int *)malloc(sizeof(int) * output->vertex_count);
*r_uv = (float *)malloc(sizeof(float) * output->vertex_count * 3);
*r_index = (int *)malloc(sizeof(int) * output->index_count);
// printf("w: %i, h: %i\n", output->atlas_width, output->atlas_height);
for (int i = 0; i < output->vertex_count; i++) {
(*r_vertex)[i] = output->vertex_array[i].xref;
(*r_uv)[i * 2 + 0] = output->vertex_array[i].uv[0] / output->atlas_width;
(*r_uv)[i * 2 + 1] = output->vertex_array[i].uv[1] / output->atlas_height;
// printf("uv: %f,%f\n", (*r_uv)[i * 2 + 0], (*r_uv)[i * 2 + 1]);
}
*r_vertex_count = output->vertex_count;
for (int i = 0; i < output->index_count; i++) {
(*r_index)[i] = output->index_array[i];
}
*r_index_count = output->index_count;
*r_size_hint_x = output->atlas_height;
*r_size_hint_y = output->atlas_width;
}
if (output) {
atlas_free(output);
}
return err == Thekla::Atlas_Error_Success;
}
void register_thekla_unwrap_types() {
array_mesh_lightmap_unwrap_callback = thekla_mesh_lightmap_unwrap_callback;
}
void unregister_thekla_unwrap_types() {
}

View file

@ -1,32 +0,0 @@
/*************************************************************************/
/* register_types.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
void register_thekla_unwrap_types();
void unregister_thekla_unwrap_types();

15
thirdparty/README.md vendored
View file

@ -502,21 +502,6 @@ They are marked with `// -- GODOT start --` and `// -- GODOT end --`
comments and a patch is provided in the squish/ folder.
## thekla_atlas
- Upstream: https://github.com/Thekla/thekla_atlas
- Version: git (80a1430, 2017)
- License: MIT
Files extracted from the upstream source:
- Relevant sources from src/
- License.txt
Important: Some files have Godot-made changes, those
changes are marked with `// -- GODOT --` comments.
## tinyexr
- Upstream: https://github.com/syoyo/tinyexr

View file

@ -1,8 +0,0 @@
Copyright (c) 2013 Thekla, Inc
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,154 +0,0 @@
diff --git a/thirdparty/thekla_atlas/nvmesh/param/AtlasPacker.cpp b/thirdparty/thekla_atlas/nvmesh/param/AtlasPacker.cpp
index 5ce452c..11e635d 100644
--- a/thirdparty/thekla_atlas/nvmesh/param/AtlasPacker.cpp
+++ b/thirdparty/thekla_atlas/nvmesh/param/AtlasPacker.cpp
@@ -142,9 +142,11 @@ AtlasPacker::AtlasPacker(Atlas * atlas) : m_atlas(atlas), m_bitmap(256, 256)
{
m_width = 0;
m_height = 0;
-
- m_debug_bitmap.allocate(256, 256);
- m_debug_bitmap.fill(Color32(0,0,0,0));
+
+ // -- GODOT start --
+ //m_debug_bitmap.allocate(256, 256);
+ //m_debug_bitmap.fill(Color32(0,0,0,0));
+ // -- GODOT end --
}
AtlasPacker::~AtlasPacker()
@@ -465,7 +467,11 @@ void AtlasPacker::packCharts(int quality, float texelsPerUnit, bool blockAligned
nvDebug("origin: %f %f\n", origin.x, origin.y);
nvDebug("majorAxis: %f %f\n", majorAxis.x, majorAxis.y);
nvDebug("minorAxis: %f %f\n", minorAxis.x, minorAxis.y);
- nvDebugBreak();
+ // -- GODOT start --
+ //nvDebugBreak();
+ m_atlas->setFailed();
+ return;
+ // -- GODOT end --
}
//nvCheck(tmp.x >= 0 && tmp.y >= 0);
@@ -597,8 +603,10 @@ void AtlasPacker::packCharts(int quality, float texelsPerUnit, bool blockAligned
m_bitmap.clearAll();
if (approximateExtent > m_bitmap.width()) {
m_bitmap.resize(approximateExtent, approximateExtent, false);
- m_debug_bitmap.resize(approximateExtent, approximateExtent);
- m_debug_bitmap.fill(Color32(0,0,0,0));
+ // -- GODOT start --
+ //m_debug_bitmap.resize(approximateExtent, approximateExtent);
+ //m_debug_bitmap.fill(Color32(0,0,0,0));
+ // -- GODOT end --
}
@@ -680,20 +688,24 @@ void AtlasPacker::packCharts(int quality, float texelsPerUnit, bool blockAligned
{
//nvDebug("Resize bitmap (%d, %d).\n", nextPowerOfTwo(w), nextPowerOfTwo(h));
m_bitmap.resize(nextPowerOfTwo(U32(w)), nextPowerOfTwo(U32(h)), false);
- m_debug_bitmap.resize(nextPowerOfTwo(U32(w)), nextPowerOfTwo(U32(h)));
+ // -- GODOT start --
+ //m_debug_bitmap.resize(nextPowerOfTwo(U32(w)), nextPowerOfTwo(U32(h)));
+ // -- GODOT end --
}
//nvDebug("Add chart at (%d, %d).\n", best_x, best_y);
addChart(&chart_bitmap, w, h, best_x, best_y, best_r, /*debugOutput=*/NULL);
+ // -- GODOT start --
// IC: Output chart again to debug bitmap.
- if (chart->isVertexMapped()) {
+ /*if (chart->isVertexMapped()) {
addChart(&chart_bitmap, w, h, best_x, best_y, best_r, &m_debug_bitmap);
}
else {
addChart(chart, w, h, best_x, best_y, best_r, &m_debug_bitmap);
- }
+ }*/
+ // -- GODOT end --
//float best_angle = 2 * PI * best_r;
@@ -842,8 +854,10 @@ void AtlasPacker::packCharts(int quality, float texelsPerUnit, bool blockAligned
nvCheck(isAligned(m_width, 4));
nvCheck(isAligned(m_height, 4));
- m_debug_bitmap.resize(m_width, m_height);
- m_debug_bitmap.setFormat(Image::Format_ARGB);
+ // -- GODOT start --
+ //m_debug_bitmap.resize(m_width, m_height);
+ //m_debug_bitmap.setFormat(Image::Format_ARGB);
+ // -- GODOT end --
#if DEBUG_OUTPUT
//outputDebugBitmap("debug_packer_final.tga", m_bitmap, w, h);
diff --git a/thirdparty/thekla_atlas/nvmesh/param/AtlasPacker.h b/thirdparty/thekla_atlas/nvmesh/param/AtlasPacker.h
index 2d305f3..845dbfb 100644
--- a/thirdparty/thekla_atlas/nvmesh/param/AtlasPacker.h
+++ b/thirdparty/thekla_atlas/nvmesh/param/AtlasPacker.h
@@ -48,7 +48,9 @@ namespace nv
Atlas * m_atlas;
BitMap m_bitmap;
- Image m_debug_bitmap;
+ // -- GODOT start --
+ //Image m_debug_bitmap;
+ // -- GODOT end --
RadixSort m_radix;
uint m_width;
diff --git a/thirdparty/thekla_atlas/thekla/thekla_atlas.cpp b/thirdparty/thekla_atlas/thekla/thekla_atlas.cpp
index d6f0acc..de1953d 100644
--- a/thirdparty/thekla_atlas/thekla/thekla_atlas.cpp
+++ b/thirdparty/thekla_atlas/thekla/thekla_atlas.cpp
@@ -2,6 +2,9 @@
#include "thekla_atlas.h"
#include <cfloat>
+// -- GODOT start --
+#include <stdio.h>
+// -- GODOT end --
#include "nvmesh/halfedge/Edge.h"
#include "nvmesh/halfedge/Mesh.h"
@@ -112,6 +115,8 @@ static Atlas_Output_Mesh * mesh_atlas_to_output(const HalfEdge::Mesh * mesh, con
output->index_count = face_count * 3;
output->index_array = new int[face_count * 3];
+ // -- GODOT start --
+ int face_ofs = 0;
// Set face indices.
for (int f = 0; f < face_count; f++) {
uint c = charts->faceChartAt(f);
@@ -121,14 +126,26 @@ static Atlas_Output_Mesh * mesh_atlas_to_output(const HalfEdge::Mesh * mesh, con
const Chart * chart = charts->chartAt(c);
nvDebugCheck(chart->faceAt(i) == f);
+ if (i >= chart->chartMesh()->faceCount()) {
+ printf("WARNING: Faces may be missing in the final vertex, which could not be packed\n");
+ continue;
+ }
+
const HalfEdge::Face * face = chart->chartMesh()->faceAt(i);
const HalfEdge::Edge * edge = face->edge;
- output->index_array[3*f+0] = vertexOffset + edge->vertex->id;
- output->index_array[3*f+1] = vertexOffset + edge->next->vertex->id;
- output->index_array[3*f+2] = vertexOffset + edge->next->next->vertex->id;
+ //output->index_array[3*f+0] = vertexOffset + edge->vertex->id;
+ //output->index_array[3*f+1] = vertexOffset + edge->next->vertex->id;
+ //output->index_array[3*f+2] = vertexOffset + edge->next->next->vertex->id;
+ output->index_array[3 * face_ofs + 0] = vertexOffset + edge->vertex->id;
+ output->index_array[3 * face_ofs + 1] = vertexOffset + edge->next->vertex->id;
+ output->index_array[3 * face_ofs + 2] = vertexOffset + edge->next->next->vertex->id;
+ face_ofs++;
}
+ output->index_count = face_ofs * 3;
+ // -- GODOT end --
+
*error = Atlas_Error_Success;
output->atlas_width = w;
output->atlas_height = h;

View file

@ -1,37 +0,0 @@
#ifndef NV_CONFIG
#define NV_CONFIG
#if NV_OS_DARWIN
// Hardcoded.
#define NV_HAVE_UNISTD_H
#define NV_HAVE_STDARG_H
#define NV_HAVE_SIGNAL_H
#define NV_HAVE_EXECINFO_H
//#define NV_HAVE_MALLOC_H
#else
//#define HAVE_UNISTD_H
#define NV_HAVE_STDARG_H
//#define HAVE_SIGNAL_H
//#define HAVE_EXECINFO_H
//#define HAVE_MALLOC_H
#endif
//#define HAVE_OPENMP // Only in MSVC pro edition.
//#cmakedefine HAVE_PNG
//#cmakedefine HAVE_JPEG
//#cmakedefine HAVE_TIFF
//#cmakedefine HAVE_OPENEXR
//#cmakedefine HAVE_FREEIMAGE
#if !NV_OS_IOS
#define NV_HAVE_STBIMAGE
#endif
//#cmakedefine HAVE_MAYA
#endif // NV_CONFIG

View file

@ -1,182 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_CORE_ARRAY_H
#define NV_CORE_ARRAY_H
/*
This array class requires the elements to be relocable; it uses memmove and realloc. Ideally I should be
using swap, but I honestly don't care. The only thing that you should be aware of is that internal pointers
are not supported.
Note also that push_back and resize does not support inserting arguments elements that are in the same
container. This is forbidden to prevent an extra copy.
*/
#include "Memory.h"
#include "Debug.h"
#include "ForEach.h" // PseudoIndex
namespace nv
{
class Stream;
/**
* Replacement for std::vector that is easier to debug and provides
* some nice foreach enumerators.
*/
template<typename T>
class NVCORE_CLASS Array {
public:
typedef uint size_type;
// Default constructor.
NV_FORCEINLINE Array() : m_buffer(NULL), m_capacity(0), m_size(0) {}
// Copy constructor.
NV_FORCEINLINE Array(const Array & a) : m_buffer(NULL), m_capacity(0), m_size(0) {
copy(a.m_buffer, a.m_size);
}
// Constructor that initializes the vector with the given elements.
NV_FORCEINLINE Array(const T * ptr, uint num) : m_buffer(NULL), m_capacity(0), m_size(0) {
copy(ptr, num);
}
// Allocate array.
NV_FORCEINLINE explicit Array(uint capacity) : m_buffer(NULL), m_capacity(0), m_size(0) {
setArrayCapacity(capacity);
}
// Destructor.
NV_FORCEINLINE ~Array() {
clear();
free<T>(m_buffer);
}
/// Const element access.
NV_FORCEINLINE const T & operator[]( uint index ) const
{
nvDebugCheck(index < m_size);
return m_buffer[index];
}
NV_FORCEINLINE const T & at( uint index ) const
{
nvDebugCheck(index < m_size);
return m_buffer[index];
}
/// Element access.
NV_FORCEINLINE T & operator[] ( uint index )
{
nvDebugCheck(index < m_size);
return m_buffer[index];
}
NV_FORCEINLINE T & at( uint index )
{
nvDebugCheck(index < m_size);
return m_buffer[index];
}
/// Get vector size.
NV_FORCEINLINE uint size() const { return m_size; }
/// Get vector size.
NV_FORCEINLINE uint count() const { return m_size; }
/// Get vector capacity.
NV_FORCEINLINE uint capacity() const { return m_capacity; }
/// Get const vector pointer.
NV_FORCEINLINE const T * buffer() const { return m_buffer; }
/// Get vector pointer.
NV_FORCEINLINE T * buffer() { return m_buffer; }
/// Provide begin/end pointers for C++11 range-based for loops.
NV_FORCEINLINE T * begin() { return m_buffer; }
NV_FORCEINLINE T * end() { return m_buffer + m_size; }
NV_FORCEINLINE const T * begin() const { return m_buffer; }
NV_FORCEINLINE const T * end() const { return m_buffer + m_size; }
/// Is vector empty.
NV_FORCEINLINE bool isEmpty() const { return m_size == 0; }
/// Is a null vector.
NV_FORCEINLINE bool isNull() const { return m_buffer == NULL; }
T & append();
void push_back( const T & val );
void pushBack( const T & val );
Array<T> & append( const T & val );
Array<T> & operator<< ( T & t );
void pop_back();
void popBack(uint count = 1);
void popFront(uint count = 1);
const T & back() const;
T & back();
const T & front() const;
T & front();
bool contains(const T & e) const;
bool find(const T & element, uint * indexPtr) const;
bool find(const T & element, uint begin, uint end, uint * indexPtr) const;
void removeAt(uint index);
bool remove(const T & element);
void insertAt(uint index, const T & val = T());
void append(const Array<T> & other);
void append(const T other[], uint count);
void replaceWithLast(uint index);
void resize(uint new_size);
void resize(uint new_size, const T & elem);
void fill(const T & elem);
void clear();
void shrink();
void reserve(uint desired_size);
void copy(const T * data, uint count);
Array<T> & operator=( const Array<T> & a );
T * release();
// Array enumerator.
typedef uint PseudoIndex;
NV_FORCEINLINE PseudoIndex start() const { return 0; }
NV_FORCEINLINE bool isDone(const PseudoIndex & i) const { nvDebugCheck(i <= this->m_size); return i == this->m_size; }
NV_FORCEINLINE void advance(PseudoIndex & i) const { nvDebugCheck(i <= this->m_size); i++; }
#if NV_NEED_PSEUDOINDEX_WRAPPER
NV_FORCEINLINE T & operator[]( const PseudoIndexWrapper & i ) {
return m_buffer[i(this)];
}
NV_FORCEINLINE const T & operator[]( const PseudoIndexWrapper & i ) const {
return m_buffer[i(this)];
}
#endif
// Friends.
template <typename Typ>
friend Stream & operator<< ( Stream & s, Array<Typ> & p );
template <typename Typ>
friend void swap(Array<Typ> & a, Array<Typ> & b);
protected:
void setArraySize(uint new_size);
void setArrayCapacity(uint new_capacity);
T * m_buffer;
uint m_capacity;
uint m_size;
};
} // nv namespace
#endif // NV_CORE_ARRAY_H

View file

@ -1,452 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_CORE_ARRAY_INL
#define NV_CORE_ARRAY_INL
#include "Array.h"
#include "Stream.h"
#include "Utils.h" // swap
#include <string.h> // memmove
#include <new> // for placement new
namespace nv
{
template <typename T>
NV_FORCEINLINE T & Array<T>::append()
{
uint old_size = m_size;
uint new_size = m_size + 1;
setArraySize(new_size);
construct_range(m_buffer, new_size, old_size);
return m_buffer[old_size]; // Return reference to last element.
}
// Push an element at the end of the vector.
template <typename T>
NV_FORCEINLINE void Array<T>::push_back( const T & val )
{
#if 1
nvDebugCheck(&val < m_buffer || &val >= m_buffer+m_size);
uint old_size = m_size;
uint new_size = m_size + 1;
setArraySize(new_size);
construct_range(m_buffer, new_size, old_size, val);
#else
uint new_size = m_size + 1;
if (new_size > m_capacity)
{
// @@ Is there any way to avoid this copy?
// @@ Can we create a copy without side effects? Ie. without calls to constructor/destructor. Use alloca + memcpy?
// @@ Assert instead of copy?
const T copy(val); // create a copy in case value is inside of this array.
setArraySize(new_size);
new (m_buffer+new_size-1) T(copy);
}
else
{
m_size = new_size;
new(m_buffer+new_size-1) T(val);
}
#endif // 0/1
}
template <typename T>
NV_FORCEINLINE void Array<T>::pushBack( const T & val )
{
push_back(val);
}
template <typename T>
NV_FORCEINLINE Array<T> & Array<T>::append( const T & val )
{
push_back(val);
return *this;
}
// Qt like push operator.
template <typename T>
NV_FORCEINLINE Array<T> & Array<T>::operator<< ( T & t )
{
push_back(t);
return *this;
}
// Pop the element at the end of the vector.
template <typename T>
NV_FORCEINLINE void Array<T>::pop_back()
{
nvDebugCheck( m_size > 0 );
resize( m_size - 1 );
}
template <typename T>
NV_FORCEINLINE void Array<T>::popBack(uint count)
{
nvDebugCheck(m_size >= count);
resize(m_size - count);
}
template <typename T>
NV_FORCEINLINE void Array<T>::popFront(uint count)
{
nvDebugCheck(m_size >= count);
//resize(m_size - count);
if (m_size == count) {
clear();
}
else {
destroy_range(m_buffer, 0, count);
memmove(m_buffer, m_buffer + count, sizeof(T) * (m_size - count));
m_size -= count;
}
}
// Get back element.
template <typename T>
NV_FORCEINLINE const T & Array<T>::back() const
{
nvDebugCheck( m_size > 0 );
return m_buffer[m_size-1];
}
// Get back element.
template <typename T>
NV_FORCEINLINE T & Array<T>::back()
{
nvDebugCheck( m_size > 0 );
return m_buffer[m_size-1];
}
// Get front element.
template <typename T>
NV_FORCEINLINE const T & Array<T>::front() const
{
nvDebugCheck( m_size > 0 );
return m_buffer[0];
}
// Get front element.
template <typename T>
NV_FORCEINLINE T & Array<T>::front()
{
nvDebugCheck( m_size > 0 );
return m_buffer[0];
}
// Check if the given element is contained in the array.
template <typename T>
NV_FORCEINLINE bool Array<T>::contains(const T & e) const
{
return find(e, NULL);
}
// Return true if element found.
template <typename T>
NV_FORCEINLINE bool Array<T>::find(const T & element, uint * indexPtr) const
{
return find(element, 0, m_size, indexPtr);
}
// Return true if element found within the given range.
template <typename T>
NV_FORCEINLINE bool Array<T>::find(const T & element, uint begin, uint end, uint * indexPtr) const
{
return ::nv::find(element, m_buffer, begin, end, indexPtr);
}
// Remove the element at the given index. This is an expensive operation!
template <typename T>
void Array<T>::removeAt(uint index)
{
nvDebugCheck(index >= 0 && index < m_size);
if (m_size == 1) {
clear();
}
else {
m_buffer[index].~T();
memmove(m_buffer+index, m_buffer+index+1, sizeof(T) * (m_size - 1 - index));
m_size--;
}
}
// Remove the first instance of the given element.
template <typename T>
bool Array<T>::remove(const T & element)
{
uint index;
if (find(element, &index)) {
removeAt(index);
return true;
}
return false;
}
// Insert the given element at the given index shifting all the elements up.
template <typename T>
void Array<T>::insertAt(uint index, const T & val/*=T()*/)
{
nvDebugCheck( index >= 0 && index <= m_size );
setArraySize(m_size + 1);
if (index < m_size - 1) {
memmove(m_buffer+index+1, m_buffer+index, sizeof(T) * (m_size - 1 - index));
}
// Copy-construct into the newly opened slot.
new(m_buffer+index) T(val);
}
// Append the given data to our vector.
template <typename T>
NV_FORCEINLINE void Array<T>::append(const Array<T> & other)
{
append(other.m_buffer, other.m_size);
}
// Append the given data to our vector.
template <typename T>
void Array<T>::append(const T other[], uint count)
{
if (count > 0) {
const uint old_size = m_size;
setArraySize(m_size + count);
for (uint i = 0; i < count; i++ ) {
new(m_buffer + old_size + i) T(other[i]);
}
}
}
// Remove the given element by replacing it with the last one.
template <typename T>
void Array<T>::replaceWithLast(uint index)
{
nvDebugCheck( index < m_size );
nv::swap(m_buffer[index], back()); // @@ Is this OK when index == size-1?
(m_buffer+m_size-1)->~T();
m_size--;
}
// Resize the vector preserving existing elements.
template <typename T>
void Array<T>::resize(uint new_size)
{
uint old_size = m_size;
// Destruct old elements (if we're shrinking).
destroy_range(m_buffer, new_size, old_size);
setArraySize(new_size);
// Call default constructors
construct_range(m_buffer, new_size, old_size);
}
// Resize the vector preserving existing elements and initializing the
// new ones with the given value.
template <typename T>
void Array<T>::resize(uint new_size, const T & elem)
{
nvDebugCheck(&elem < m_buffer || &elem > m_buffer+m_size);
uint old_size = m_size;
// Destruct old elements (if we're shrinking).
destroy_range(m_buffer, new_size, old_size);
setArraySize(new_size);
// Call copy constructors
construct_range(m_buffer, new_size, old_size, elem);
}
// Fill array with the given value.
template <typename T>
void Array<T>::fill(const T & elem)
{
fill(m_buffer, m_size, elem);
}
// Clear the buffer.
template <typename T>
NV_FORCEINLINE void Array<T>::clear()
{
nvDebugCheck(isValidPtr(m_buffer));
// Destruct old elements
destroy_range(m_buffer, 0, m_size);
m_size = 0;
}
// Shrink the allocated vector.
template <typename T>
NV_FORCEINLINE void Array<T>::shrink()
{
if (m_size < m_capacity) {
setArrayCapacity(m_size);
}
}
// Preallocate space.
template <typename T>
NV_FORCEINLINE void Array<T>::reserve(uint desired_size)
{
if (desired_size > m_capacity) {
setArrayCapacity(desired_size);
}
}
// Copy elements to this array. Resizes it if needed.
template <typename T>
NV_FORCEINLINE void Array<T>::copy(const T * data, uint count)
{
#if 1 // More simple, but maybe not be as efficient?
destroy_range(m_buffer, 0, m_size);
setArraySize(count);
construct_range(m_buffer, count, 0, data);
#else
const uint old_size = m_size;
destroy_range(m_buffer, count, old_size);
setArraySize(count);
copy_range(m_buffer, data, old_size);
construct_range(m_buffer, count, old_size, data);
#endif
}
// Assignment operator.
template <typename T>
NV_FORCEINLINE Array<T> & Array<T>::operator=( const Array<T> & a )
{
copy(a.m_buffer, a.m_size);
return *this;
}
// Release ownership of allocated memory and returns pointer to it.
template <typename T>
T * Array<T>::release() {
T * tmp = m_buffer;
m_buffer = NULL;
m_capacity = 0;
m_size = 0;
return tmp;
}
// Change array size.
template <typename T>
inline void Array<T>::setArraySize(uint new_size) {
m_size = new_size;
if (new_size > m_capacity) {
uint new_buffer_size;
if (m_capacity == 0) {
// first allocation is exact
new_buffer_size = new_size;
}
else {
// following allocations grow array by 25%
new_buffer_size = new_size + (new_size >> 2);
}
setArrayCapacity( new_buffer_size );
}
}
// Change array capacity.
template <typename T>
inline void Array<T>::setArrayCapacity(uint new_capacity) {
nvDebugCheck(new_capacity >= m_size);
if (new_capacity == 0) {
// free the buffer.
if (m_buffer != NULL) {
free<T>(m_buffer);
m_buffer = NULL;
}
}
else {
// realloc the buffer
m_buffer = realloc<T>(m_buffer, new_capacity);
}
m_capacity = new_capacity;
}
// Array serialization.
template <typename Typ>
inline Stream & operator<< ( Stream & s, Array<Typ> & p )
{
if (s.isLoading()) {
uint size;
s << size;
p.resize( size );
}
else {
s << p.m_size;
}
for (uint i = 0; i < p.m_size; i++) {
s << p.m_buffer[i];
}
return s;
}
// Swap the members of the two given vectors.
template <typename Typ>
inline void swap(Array<Typ> & a, Array<Typ> & b)
{
nv::swap(a.m_buffer, b.m_buffer);
nv::swap(a.m_capacity, b.m_capacity);
nv::swap(a.m_size, b.m_size);
}
} // nv namespace
// IC: These functions are for compatibility with the Foreach macro in The Witness.
template <typename T> inline int item_count(const nv::Array<T> & array) { return array.count(); }
template <typename T> inline const T & item_at(const nv::Array<T> & array, int i) { return array.at(i); }
template <typename T> inline T & item_at(nv::Array<T> & array, int i) { return array.at(i); }
template <typename T> inline int item_advance(const nv::Array<T> & array, int i) { return ++i; }
template <typename T> inline int item_remove(nv::Array<T> & array, int i) { array.replaceWithLast(i); return i - 1; }
template <typename T> inline int item_count(const nv::Array<T> * array) { return array->count(); }
template <typename T> inline const T & item_at(const nv::Array<T> * array, int i) { return array->at(i); }
template <typename T> inline T & item_at(nv::Array<T> * array, int i) { return array->at(i); }
template <typename T> inline int item_advance(const nv::Array<T> * array, int i) { return ++i; }
template <typename T> inline int item_remove(nv::Array<T> * array, int i) { array->replaceWithLast(i); return i - 1; }
#endif // NV_CORE_ARRAY_INL

View file

@ -1,250 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_CORE_BITARRAY_H
#define NV_CORE_BITARRAY_H
#include "nvcore.h"
#include "Array.inl"
namespace nv
{
// @@ Uh, this could be much faster.
inline uint countSetBits(uint32 x) {
uint count = 0;
for(; x != 0; x >>= 1) {
count += (x & 1);
}
return count;
}
// @@ This is even more lame. What was I thinking?
inline uint countSetBits(uint32 x, int bits) {
uint count = 0;
for(; x != 0 && bits != 0; x >>= 1, bits--) {
count += (x & 1);
}
return count;
}
// See "Conditionally set or clear bits without branching" at http://graphics.stanford.edu/~seander/bithacks.html
inline uint setBits(uint w, uint m, bool b) {
return (w & ~m) | (-int(b) & m);
}
// Simple bit array.
class BitArray
{
public:
BitArray() {}
BitArray(uint sz) {
resize(sz);
}
uint size() const { return m_size; }
void clear() { resize(0); }
void resize(uint new_size)
{
m_size = new_size;
m_wordArray.resize( (m_size + 31) >> 5 );
}
void resize(uint new_size, bool init)
{
//if (new_size == m_size) return;
uint old_size = m_size;
uint size_mod_32 = old_size & 31;
uint last_word_index = ((old_size + 31) >> 5) - 1;
uint mask = (1 << size_mod_32) - 1;
uint init_dword;
if (init) {
if (size_mod_32) m_wordArray[last_word_index] |= ~mask;
init_dword = ~0;
}
else {
if (size_mod_32) m_wordArray[last_word_index] &= mask;
init_dword = 0;
}
m_size = new_size;
m_wordArray.resize((new_size + 31) >> 5, init_dword);
// Make sure new bits are initialized correctly.
/*for (uint i = old_size; i < new_size; i++) {
nvCheck(bitAt(i) == init);
}*/
}
/// Get bit.
bool bitAt(uint b) const
{
nvDebugCheck( b < m_size );
return (m_wordArray[b >> 5] & (1 << (b & 31))) != 0;
}
// It may be useful to pack mulitple bit arrays together interleaving their bits.
uint bitsAt(uint idx, uint count) const
{
//nvDebugCheck(count == 2 || count == 4 || count == 8 || count == 16 || count == 32);
nvDebugCheck(count == 2); // @@ Hardcoded for two.
uint b = idx * count;
nvDebugCheck(b < m_size);
return (m_wordArray[b >> 5] & (0x3 << (b & 31))) >> (b & 31);
}
// It would be useful to have a function to set two bits simultaneously.
/*void setBitsAt(uint idx, uint count, uint bits) const
{
//nvDebugCheck(count == 2 || count == 4 || count == 8 || count == 16 || count == 32);
nvDebugCheck(count == 2); // @@ Hardcoded for two.
uint b = idx * count;
nvDebugCheck(b < m_size);
return (m_wordArray[b >> 5] & (0x3 << (b & 31))) >> (b & 31);
}*/
// Set a bit.
void setBitAt(uint idx)
{
nvDebugCheck(idx < m_size);
m_wordArray[idx >> 5] |= (1 << (idx & 31));
}
// Clear a bit.
void clearBitAt(uint idx)
{
nvDebugCheck(idx < m_size);
m_wordArray[idx >> 5] &= ~(1 << (idx & 31));
}
// Toggle a bit.
void toggleBitAt(uint idx)
{
nvDebugCheck(idx < m_size);
m_wordArray[idx >> 5] ^= (1 << (idx & 31));
}
// Set a bit to the given value. @@ Rename modifyBitAt?
void setBitAt(uint idx, bool b)
{
nvDebugCheck(idx < m_size);
m_wordArray[idx >> 5] = setBits(m_wordArray[idx >> 5], 1 << (idx & 31), b);
nvDebugCheck(bitAt(idx) == b);
}
void append(bool value)
{
resize(m_size + 1);
setBitAt(m_size - 1, value);
}
// Clear all the bits.
void clearAll()
{
memset(m_wordArray.buffer(), 0, m_wordArray.size() * sizeof(uint));
}
// Set all the bits.
void setAll()
{
memset(m_wordArray.buffer(), 0xFF, m_wordArray.size() * sizeof(uint));
}
// Toggle all the bits.
void toggleAll()
{
const uint wordCount = m_wordArray.count();
for(uint b = 0; b < wordCount; b++) {
m_wordArray[b] ^= 0xFFFFFFFF;
}
}
// Count the number of bits set.
uint countSetBits() const
{
const uint num = m_wordArray.size();
if( num == 0 ) {
return 0;
}
uint count = 0;
for(uint i = 0; i < num - 1; i++) {
count += nv::countSetBits(m_wordArray[i]);
}
count += nv::countSetBits(m_wordArray[num - 1], m_size & 31);
//piDebugCheck(count + countClearBits() == m_size);
return count;
}
// Count the number of bits clear.
uint countClearBits() const {
const uint num = m_wordArray.size();
if( num == 0 ) {
return 0;
}
uint count = 0;
for(uint i = 0; i < num - 1; i++) {
count += nv::countSetBits(~m_wordArray[i]);
}
count += nv::countSetBits(~m_wordArray[num - 1], m_size & 31);
//piDebugCheck(count + countSetBits() == m_size);
return count;
}
friend void swap(BitArray & a, BitArray & b)
{
swap(a.m_size, b.m_size);
swap(a.m_wordArray, b.m_wordArray);
}
void operator &= (const BitArray & other) {
if (other.m_size != m_size) {
resize(other.m_size);
}
const uint wordCount = m_wordArray.count();
for (uint i = 0; i < wordCount; i++) {
m_wordArray[i] &= other.m_wordArray[i];
}
}
void operator |= (const BitArray & other) {
if (other.m_size != m_size) {
resize(other.m_size);
}
const uint wordCount = m_wordArray.count();
for (uint i = 0; i < wordCount; i++) {
m_wordArray[i] |= other.m_wordArray[i];
}
}
private:
// Number of bits stored.
uint m_size;
// Array of bits.
Array<uint> m_wordArray;
};
} // nv namespace
#endif // NV_CORE_BITARRAY_H

File diff suppressed because it is too large Load diff

View file

@ -1,246 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_CORE_DEBUG_H
#define NV_CORE_DEBUG_H
#include "nvcore.h"
#include <stdarg.h> // va_list
#if NV_OS_IOS //ACS: maybe we want this for OSX too?
# ifdef __APPLE__
# include <TargetConditionals.h>
# include <signal.h>
# endif
#endif
// Make sure we are using our assert.
#undef assert
#define NV_ABORT_DEBUG 1
#define NV_ABORT_IGNORE 2
#define NV_ABORT_EXIT 3
#define nvNoAssert(exp) \
NV_MULTI_LINE_MACRO_BEGIN \
(void)sizeof(exp); \
NV_MULTI_LINE_MACRO_END
#if NV_NO_ASSERT
# define nvAssert(exp) nvNoAssert(exp)
# define nvCheck(exp) nvNoAssert(exp)
# define nvDebugAssert(exp) nvNoAssert(exp)
# define nvDebugCheck(exp) nvNoAssert(exp)
# define nvDebugBreak() nvNoAssert(0)
#else // NV_NO_ASSERT
# if NV_CC_MSVC
// @@ Does this work in msvc-6 and earlier?
# define nvDebugBreak() __debugbreak()
//# define nvDebugBreak() __asm { int 3 }
# elif NV_OS_ORBIS
# define nvDebugBreak() __debugbreak()
# elif NV_OS_IOS && TARGET_OS_IPHONE
# define nvDebugBreak() raise(SIGINT)
# elif NV_CC_CLANG
# define nvDebugBreak() __builtin_debugtrap()
# elif NV_CC_GNUC
//# define nvDebugBreak() __builtin_debugtrap() // Does GCC have debugtrap?
# define nvDebugBreak() __builtin_trap()
/*
# elif NV_CC_GNUC && NV_CPU_PPC && NV_OS_DARWIN
// @@ Use __builtin_trap() on GCC
# define nvDebugBreak() __asm__ volatile ("trap")
# elif NV_CC_GNUC && NV_CPU_X86 && NV_OS_DARWIN
# define nvDebugBreak() __asm__ volatile ("int3")
# elif NV_CC_GNUC && NV_CPU_X86
# define nvDebugBreak() __asm__ ( "int %0" : :"I"(3) )
# elif NV_OS_ORBIS
# define nvDebugBreak() __asm volatile ("int $0x41")
# else
# include <signal.h>
# define nvDebugBreak() raise(SIGTRAP);
// define nvDebugBreak() *((int *)(0)) = 0
*/
# endif
# if NV_CC_MSVC
# define nvExpect(expr) (expr)
#else
# define nvExpect(expr) __builtin_expect((expr) != 0, true)
#endif
#if NV_CC_CLANG
# if __has_feature(attribute_analyzer_noreturn)
# define NV_ANALYZER_NORETURN __attribute__((analyzer_noreturn))
# else
# define NV_ANALYZER_NORETURN
# endif
#else
# define NV_ANALYZER_NORETURN
#endif
#define nvDebugBreakOnce() \
NV_MULTI_LINE_MACRO_BEGIN \
static bool firstTime = true; \
if (firstTime) { firstTime = false; nvDebugBreak(); } \
NV_MULTI_LINE_MACRO_END
#define nvAssertMacro(exp) \
NV_MULTI_LINE_MACRO_BEGIN \
if (!nvExpect(exp)) { \
if (nvAbort(#exp, __FILE__, __LINE__, __FUNC__) == NV_ABORT_DEBUG) { \
nvDebugBreak(); \
} \
} \
NV_MULTI_LINE_MACRO_END
// GCC, LLVM need "##" before the __VA_ARGS__, MSVC doesn't care
#define nvAssertMacroWithIgnoreAll(exp,...) \
NV_MULTI_LINE_MACRO_BEGIN \
static bool ignoreAll = false; \
if (!ignoreAll && !nvExpect(exp)) { \
int _result = nvAbort(#exp, __FILE__, __LINE__, __FUNC__, ##__VA_ARGS__); \
if (_result == NV_ABORT_DEBUG) { \
nvDebugBreak(); \
} else if (_result == NV_ABORT_IGNORE) { \
ignoreAll = true; \
} \
} \
NV_MULTI_LINE_MACRO_END
// Interesting assert macro from Insomniac:
// http://www.gdcvault.com/play/1015319/Developing-Imperfect-Software-How-to
// Used as follows:
// if (nvCheck(i < count)) {
// normal path
// } else {
// fixup code.
// }
// This style of macro could be combined with __builtin_expect to let the compiler know failure is unlikely.
#define nvCheckMacro(exp) \
(\
(exp) ? true : ( \
(nvAbort(#exp, __FILE__, __LINE__, __FUNC__) == NV_ABORT_DEBUG) ? (nvDebugBreak(), true) : ( false ) \
) \
)
#define nvAssert(exp) nvAssertMacro(exp)
#define nvCheck(exp) nvAssertMacro(exp)
#if defined(_DEBUG)
# define nvDebugAssert(exp) nvAssertMacro(exp)
# define nvDebugCheck(exp) nvAssertMacro(exp)
#else // _DEBUG
# define nvDebugAssert(exp) nvNoAssert(exp)
# define nvDebugCheck(exp) nvNoAssert(exp)
#endif // _DEBUG
#endif // NV_NO_ASSERT
// Use nvAssume for very simple expresions only: nvAssume(0), nvAssume(value == true), etc.
/*#if !defined(_DEBUG)
# if NV_CC_MSVC
# define nvAssume(exp) __assume(exp)
# else
# define nvAssume(exp) nvCheck(exp)
# endif
#else
# define nvAssume(exp) nvCheck(exp)
#endif*/
#if defined(_DEBUG)
# if NV_CC_MSVC
# define nvUnreachable() nvAssert(0 && "unreachable"); __assume(0)
# else
# define nvUnreachable() nvAssert(0 && "unreachable"); __builtin_unreachable()
# endif
#else
# if NV_CC_MSVC
# define nvUnreachable() __assume(0)
# else
# define nvUnreachable() __builtin_unreachable()
# endif
#endif
#define nvError(x) nvAbort(x, __FILE__, __LINE__, __FUNC__)
#define nvWarning(x) nvDebugPrint("*** Warning %s/%d: %s\n", __FILE__, __LINE__, (x))
#ifndef NV_DEBUG_PRINT
#define NV_DEBUG_PRINT 1 //defined(_DEBUG)
#endif
#if NV_DEBUG_PRINT
#define nvDebug(...) nvDebugPrint(__VA_ARGS__)
#else
#if NV_CC_MSVC
#define nvDebug(...) __noop(__VA_ARGS__)
#else
#define nvDebug(...) ((void)0) // Non-msvc platforms do not evaluate arguments?
#endif
#endif
NVCORE_API int nvAbort(const char *exp, const char *file, int line, const char * func = NULL, const char * msg = NULL, ...) __attribute__((format (printf, 5, 6))) NV_ANALYZER_NORETURN;
NVCORE_API void NV_CDECL nvDebugPrint( const char *msg, ... ) __attribute__((format (printf, 1, 2)));
namespace nv
{
inline bool isValidPtr(const void * ptr) {
#if NV_OS_DARWIN
return true; // IC: Not sure what ranges are OK on OSX.
#endif
#if NV_CPU_X86_64
if (ptr == NULL) return true;
if (reinterpret_cast<uint64>(ptr) < 0x10000ULL) return false;
if (reinterpret_cast<uint64>(ptr) >= 0x000007FFFFFEFFFFULL) return false;
#else
if (reinterpret_cast<uintptr_t>(ptr) == 0xcccccccc) return false;
if (reinterpret_cast<uintptr_t>(ptr) == 0xcdcdcdcd) return false;
if (reinterpret_cast<uintptr_t>(ptr) == 0xdddddddd) return false;
if (reinterpret_cast<uintptr_t>(ptr) == 0xffffffff) return false;
#endif
return true;
}
// Message handler interface.
struct MessageHandler {
virtual void log(const char * str, va_list arg) = 0;
virtual ~MessageHandler() {}
};
// Assert handler interface.
struct AssertHandler {
virtual int assertion(const char *exp, const char *file, int line, const char *func, const char *msg, va_list arg) = 0;
virtual ~AssertHandler() {}
};
namespace debug
{
NVCORE_API void dumpInfo();
NVCORE_API void dumpCallstack( MessageHandler *messageHandler, int callstackLevelsToSkip = 0 );
NVCORE_API void setMessageHandler( MessageHandler * messageHandler );
NVCORE_API void resetMessageHandler();
NVCORE_API void setAssertHandler( AssertHandler * assertHanlder );
NVCORE_API void resetAssertHandler();
NVCORE_API void enableSigHandler(bool interactive);
NVCORE_API void disableSigHandler();
NVCORE_API bool isDebuggerPresent();
NVCORE_API bool attachToDebugger();
NVCORE_API void terminate(int code);
}
} // nv namespace
#endif // NV_CORE_DEBUG_H

View file

@ -1,57 +0,0 @@
#ifndef NV_CORE_H
#error "Do not include this file directly."
#endif
#include <stdint.h> // uint8_t, int8_t, ... uintptr_t
#include <stddef.h> // operator new, size_t, NULL
// Function linkage
#define DLL_IMPORT
#if __GNUC__ >= 4
# define DLL_EXPORT __attribute__((visibility("default")))
# define DLL_EXPORT_CLASS DLL_EXPORT
#else
# define DLL_EXPORT
# define DLL_EXPORT_CLASS
#endif
// Function calling modes
#if NV_CPU_X86
# define NV_CDECL __attribute__((cdecl))
# define NV_STDCALL __attribute__((stdcall))
#else
# define NV_CDECL
# define NV_STDCALL
#endif
#define NV_FASTCALL __attribute__((fastcall))
#define NV_FORCEINLINE __attribute__((always_inline)) inline
#define NV_DEPRECATED __attribute__((deprecated))
#if NV_OS_IOS
#define NV_THREAD_LOCAL // @@ IC: Looks like iOS does not have support for TLS declarations.
#else
#define NV_THREAD_LOCAL __thread
#endif
#if __GNUC__ > 2
#define NV_PURE __attribute__((pure))
#define NV_CONST __attribute__((const))
#else
#define NV_PURE
#define NV_CONST
#endif
#define NV_NOINLINE __attribute__((noinline))
// Define __FUNC__ properly.
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2
# define __FUNC__ __PRETTY_FUNCTION__ // __FUNCTION__
# else
# define __FUNC__ "<unknown>"
# endif
#else
# define __FUNC__ __PRETTY_FUNCTION__
#endif
#define restrict __restrict__

View file

@ -1,59 +0,0 @@
#ifndef NV_CORE_H
#error "Do not include this file directly."
#endif
#include <stdint.h> // uint8_t, int8_t, ... uintptr_t
#include <stddef.h> // operator new, size_t, NULL
// Function linkage
#define DLL_IMPORT
#if __GNUC__ >= 4
# define DLL_EXPORT __attribute__((visibility("default")))
# define DLL_EXPORT_CLASS DLL_EXPORT
#else
# define DLL_EXPORT
# define DLL_EXPORT_CLASS
#endif
// Function calling modes
#if NV_CPU_X86
# define NV_CDECL __attribute__((cdecl))
# define NV_STDCALL __attribute__((stdcall))
#else
# define NV_CDECL
# define NV_STDCALL
#endif
#define NV_FASTCALL __attribute__((fastcall))
//#if __GNUC__ > 3
// It seems that GCC does not assume always_inline implies inline. I think this depends on the GCC version :(
#define NV_FORCEINLINE inline __attribute__((always_inline))
//#else
// Some compilers complain that inline and always_inline are redundant.
//#define NV_FORCEINLINE __attribute__((always_inline))
//#endif
#define NV_DEPRECATED __attribute__((deprecated))
#define NV_THREAD_LOCAL __thread
#if __GNUC__ > 2
#define NV_PURE __attribute__((pure))
#define NV_CONST __attribute__((const))
#else
#define NV_PURE
#define NV_CONST
#endif
#define NV_NOINLINE __attribute__((noinline))
// Define __FUNC__ properly.
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2
# define __FUNC__ __PRETTY_FUNCTION__ // __FUNCTION__
# else
# define __FUNC__ "<unknown>"
# endif
#else
# define __FUNC__ __PRETTY_FUNCTION__
#endif
#define restrict __restrict__

View file

@ -1,67 +0,0 @@
#ifndef NV_CORE_H
#error "Do not include this file directly."
#endif
//#include <cstddef> // size_t, NULL
// Function linkage
#define DLL_IMPORT __declspec(dllimport)
#define DLL_EXPORT __declspec(dllexport)
#define DLL_EXPORT_CLASS DLL_EXPORT
// Function calling modes
#if NV_CPU_X86
# define NV_CDECL __attribute__((cdecl))
# define NV_STDCALL __attribute__((stdcall))
#else
# define NV_CDECL
# define NV_STDCALL
#endif
#define NV_FASTCALL __attribute__((fastcall))
// -- GODOT start -
#define NV_FORCEINLINE __attribute__((always_inline)) inline
// -- GODOT end -
#define NV_DEPRECATED __attribute__((deprecated))
#if __GNUC__ > 2
#define NV_PURE __attribute__((pure))
#define NV_CONST __attribute__((const))
#else
#define NV_PURE
#define NV_CONST
#endif
#define NV_NOINLINE __attribute__((noinline))
// Define __FUNC__ properly.
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2
# define __FUNC__ __PRETTY_FUNCTION__ // __FUNCTION__
# else
# define __FUNC__ "<unknown>"
# endif
#else
# define __FUNC__ __PRETTY_FUNCTION__
#endif
#define restrict __restrict__
/*
// Type definitions
typedef unsigned char uint8;
typedef signed char int8;
typedef unsigned short uint16;
typedef signed short int16;
typedef unsigned int uint32;
typedef signed int int32;
typedef unsigned long long uint64;
typedef signed long long int64;
// Aliases
typedef uint32 uint;
*/

View file

@ -1,94 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#ifndef NV_CORE_H
#error "Do not include this file directly."
#endif
// Function linkage
#define DLL_IMPORT __declspec(dllimport)
#define DLL_EXPORT __declspec(dllexport)
#define DLL_EXPORT_CLASS DLL_EXPORT
// Function calling modes
#define NV_CDECL __cdecl
#define NV_STDCALL __stdcall
#define NV_FASTCALL __fastcall
#define NV_DEPRECATED
#define NV_PURE
#define NV_CONST
// Set standard function names.
#if _MSC_VER < 1900
# define snprintf _snprintf
#endif
#if _MSC_VER < 1500
# define vsnprintf _vsnprintf
#endif
#if _MSC_VER < 1700
# define strtoll _strtoi64
# define strtoull _strtoui64
#endif
//#define chdir _chdir
#define getcwd _getcwd
#if _MSC_VER <= 1600
#define va_copy(a, b) (a) = (b)
#endif
#if !defined restrict
#define restrict
#endif
// Ignore gcc attributes.
#define __attribute__(X)
#if !defined __FUNC__
#define __FUNC__ __FUNCTION__
#endif
#define NV_NOINLINE __declspec(noinline)
#define NV_FORCEINLINE __forceinline
#define NV_THREAD_LOCAL __declspec(thread)
/*
// Type definitions
typedef unsigned char uint8;
typedef signed char int8;
typedef unsigned short uint16;
typedef signed short int16;
typedef unsigned int uint32;
typedef signed int int32;
typedef unsigned __int64 uint64;
typedef signed __int64 int64;
// Aliases
typedef uint32 uint;
*/
// Unwanted VC++ warnings to disable.
/*
#pragma warning(disable : 4244) // conversion to float, possible loss of data
#pragma warning(disable : 4245) // conversion from 'enum ' to 'unsigned long', signed/unsigned mismatch
#pragma warning(disable : 4100) // unreferenced formal parameter
#pragma warning(disable : 4514) // unreferenced inline function has been removed
#pragma warning(disable : 4710) // inline function not expanded
#pragma warning(disable : 4127) // Conditional expression is constant
#pragma warning(disable : 4305) // truncation from 'const double' to 'float'
#pragma warning(disable : 4505) // unreferenced local function has been removed
#pragma warning(disable : 4702) // unreachable code in inline expanded function
#pragma warning(disable : 4711) // function selected for automatic inlining
#pragma warning(disable : 4725) // Pentium fdiv bug
#pragma warning(disable : 4786) // Identifier was truncated and cannot be debugged.
#pragma warning(disable : 4675) // resolved overload was found by argument-dependent lookup
*/
#pragma warning(1 : 4705) // Report unused local variables.
#pragma warning(1 : 4555) // Expression has no effect.

View file

@ -1,75 +0,0 @@
// This code is in the public domain -- castano@gmail.com
#include "FileSystem.h"
#if NV_OS_WIN32
#define _CRT_NONSTDC_NO_WARNINGS // _chdir is defined deprecated, but that's a bug, chdir is deprecated, _chdir is *not*.
//#include <shlwapi.h> // PathFileExists
#include <windows.h> // GetFileAttributes
#include <direct.h> // _mkdir
#elif NV_OS_XBOX
#include <Xtl.h>
#elif NV_OS_DURANGO
#include <Windows.h>
#else
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include <stdio.h> // remove, unlink
using namespace nv;
bool FileSystem::exists(const char * path)
{
#if NV_OS_UNIX
return access(path, F_OK|R_OK) == 0;
//struct stat buf;
//return stat(path, &buf) == 0;
#elif NV_OS_WIN32 || NV_OS_XBOX || NV_OS_DURANGO
// PathFileExists requires linking to shlwapi.lib
//return PathFileExists(path) != 0;
return GetFileAttributesA(path) != INVALID_FILE_ATTRIBUTES;
#else
if (FILE * fp = fopen(path, "r"))
{
fclose(fp);
return true;
}
return false;
#endif
}
bool FileSystem::createDirectory(const char * path)
{
#if NV_OS_WIN32 || NV_OS_XBOX || NV_OS_DURANGO
return CreateDirectoryA(path, NULL) != 0;
#elif NV_OS_ORBIS
// not implemented
return false;
#else
return mkdir(path, 0777) != -1;
#endif
}
bool FileSystem::changeDirectory(const char * path)
{
#if NV_OS_WIN32
return _chdir(path) != -1;
#elif NV_OS_XBOX || NV_OS_DURANGO
// Xbox doesn't support Current Working Directory!
return false;
#elif NV_OS_ORBIS
// Orbis doesn't support Current Working Directory!
return false;
#else
return chdir(path) != -1;
#endif
}
bool FileSystem::removeFile(const char * path)
{
// @@ Use unlink or remove?
return remove(path) == 0;
}

View file

@ -1,24 +0,0 @@
// This code is in the public domain -- castano@gmail.com
#pragma once
#ifndef NV_CORE_FILESYSTEM_H
#define NV_CORE_FILESYSTEM_H
#include "nvcore.h"
namespace nv
{
namespace FileSystem
{
NVCORE_API bool exists(const char * path);
NVCORE_API bool createDirectory(const char * path);
NVCORE_API bool changeDirectory(const char * path);
NVCORE_API bool removeFile(const char * path);
} // FileSystem namespace
} // nv namespace
#endif // NV_CORE_FILESYSTEM_H

View file

@ -1,71 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_CORE_FOREACH_H
#define NV_CORE_FOREACH_H
/*
These foreach macros are very non-standard and somewhat confusing, but I like them.
*/
#include "nvcore.h"
#if NV_CC_CPP11
#define NV_FOREACH(i, container) \
for (auto i = (container).start(); !(container).isDone(i); (container).advance(i))
#elif NV_CC_GNUC // If typeof is available:
/*
Ideally we would like to write this:
#define NV_FOREACH(i, container) \
for(decltype(container)::PseudoIndex i((container).start()); !(container).isDone(i); (container).advance(i))
But gcc versions prior to 4.7 required an intermediate type. See:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=6709
*/
#define NV_FOREACH(i, container) \
typedef typeof(container) NV_STRING_JOIN2(cont,__LINE__); \
for(NV_STRING_JOIN2(cont,__LINE__)::PseudoIndex i((container).start()); !(container).isDone(i); (container).advance(i))
#else // If typeof not available:
#define NV_NEED_PSEUDOINDEX_WRAPPER 1
#include <new> // placement new
struct PseudoIndexWrapper {
template <typename T>
PseudoIndexWrapper(const T & container) {
nvStaticCheck(sizeof(typename T::PseudoIndex) <= sizeof(memory));
new (memory) typename T::PseudoIndex(container.start());
}
// PseudoIndex cannot have a dtor!
template <typename T> typename T::PseudoIndex & operator()(const T * /*container*/) {
return *reinterpret_cast<typename T::PseudoIndex *>(memory);
}
template <typename T> const typename T::PseudoIndex & operator()(const T * /*container*/) const {
return *reinterpret_cast<const typename T::PseudoIndex *>(memory);
}
uint8 memory[4]; // Increase the size if we have bigger enumerators.
};
#define NV_FOREACH(i, container) \
for(PseudoIndexWrapper i(container); !(container).isDone(i(&(container))); (container).advance(i(&(container))))
#endif
// Declare foreach keyword.
#if !defined NV_NO_USE_KEYWORDS
# define foreach NV_FOREACH
# define foreach_index NV_FOREACH
#endif
#endif // NV_CORE_FOREACH_H

View file

@ -1,83 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_CORE_HASH_H
#define NV_CORE_HASH_H
#include "nvcore.h"
namespace nv
{
inline uint sdbmHash(const void * data_in, uint size, uint h = 5381)
{
const uint8 * data = (const uint8 *) data_in;
uint i = 0;
while (i < size) {
h = (h << 16) + (h << 6) - h + (uint) data[i++];
}
return h;
}
// Note that this hash does not handle NaN properly.
inline uint sdbmFloatHash(const float * f, uint count, uint h = 5381)
{
for (uint i = 0; i < count; i++) {
//nvDebugCheck(nv::isFinite(*f));
union { float f; uint32 i; } x = { f[i] };
if (x.i == 0x80000000) x.i = 0;
h = sdbmHash(&x, 4, h);
}
return h;
}
template <typename T>
inline uint hash(const T & t, uint h = 5381)
{
return sdbmHash(&t, sizeof(T), h);
}
template <>
inline uint hash(const float & f, uint h)
{
return sdbmFloatHash(&f, 1, h);
}
// Functors for hash table:
template <typename Key> struct Hash
{
uint operator()(const Key & k) const {
return hash(k);
}
};
template <typename Key> struct Equal
{
bool operator()(const Key & k0, const Key & k1) const {
return k0 == k1;
}
};
// @@ Move to Utils.h?
template <typename T1, typename T2>
struct Pair {
T1 first;
T2 second;
};
template <typename T1, typename T2>
bool operator==(const Pair<T1,T2> & p0, const Pair<T1,T2> & p1) {
return p0.first == p1.first && p0.second == p1.second;
}
template <typename T1, typename T2>
uint hash(const Pair<T1,T2> & p, uint h = 5381) {
return hash(p.second, hash(p.first));
}
} // nv namespace
#endif // NV_CORE_HASH_H

View file

@ -1,174 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_CORE_HASHMAP_H
#define NV_CORE_HASHMAP_H
/*
HashMap based on Thatcher Ulrich <tu@tulrich.com> container, donated to the Public Domain.
I'd like to do something to reduce the amount of code generated with this template. The type of
U is largely irrelevant to the generated code, except for calls to constructors and destructors,
but the combination of all T and U pairs, generate a large amounts of code.
HashMap is not used in NVTT, so it could be removed from the repository.
*/
#include "Memory.h"
#include "Debug.h"
#include "ForEach.h"
#include "Hash.h"
namespace nv
{
class Stream;
/** Thatcher Ulrich's hash table.
*
* Hash table, linear probing, internal chaining. One
* interesting/nice thing about this implementation is that the table
* itself is a flat chunk of memory containing no pointers, only
* relative indices. If the key and value types of the hash contain
* no pointers, then the hash can be serialized using raw IO. Could
* come in handy.
*
* Never shrinks, unless you explicitly clear() it. Expands on
* demand, though. For best results, if you know roughly how big your
* table will be, default it to that size when you create it.
*/
template<typename T, typename U, typename H = Hash<T>, typename E = Equal<T> >
class NVCORE_CLASS HashMap
{
NV_FORBID_COPY(HashMap);
public:
/// Default ctor.
HashMap() : entry_count(0), size_mask(-1), table(NULL) { }
/// Ctor with size hint.
explicit HashMap(int size_hint) : entry_count(0), size_mask(-1), table(NULL) { setCapacity(size_hint); }
/// Dtor.
~HashMap() { clear(); }
void set(const T& key, const U& value);
void add(const T& key, const U& value);
bool remove(const T& key);
void clear();
bool isEmpty() const;
bool get(const T& key, U* value = NULL, T* other_key = NULL) const;
bool contains(const T & key) const;
int size() const;
int count() const;
int capacity() const;
void checkExpand();
void resize(int n);
void setCapacity(int new_size);
// Behaves much like std::pair.
struct Entry
{
int next_in_chain; // internal chaining for collisions
uint hash_value; // avoids recomputing. Worthwhile?
T key;
U value;
Entry() : next_in_chain(-2) {}
Entry(const Entry& e) : next_in_chain(e.next_in_chain), hash_value(e.hash_value), key(e.key), value(e.value) {}
Entry(const T& k, const U& v, int next, int hash) : next_in_chain(next), hash_value(hash), key(k), value(v) {}
bool isEmpty() const { return next_in_chain == -2; }
bool isEndOfChain() const { return next_in_chain == -1; }
bool isTombstone() const { return hash_value == TOMBSTONE_HASH; }
void clear() {
key.~T(); // placement delete
value.~U(); // placement delete
next_in_chain = -2;
hash_value = ~TOMBSTONE_HASH;
}
void makeTombstone() {
key.~T();
value.~U();
hash_value = TOMBSTONE_HASH;
}
};
// HashMap enumerator.
typedef int PseudoIndex;
PseudoIndex start() const { PseudoIndex i = 0; findNext(i); return i; }
bool isDone(const PseudoIndex & i) const { nvDebugCheck(i <= size_mask+1); return i == size_mask+1; };
void advance(PseudoIndex & i) const { nvDebugCheck(i <= size_mask+1); i++; findNext(i); }
#if NV_NEED_PSEUDOINDEX_WRAPPER
Entry & operator[]( const PseudoIndexWrapper & i ) {
Entry & e = entry(i(this));
nvDebugCheck(e.isTombstone() == false);
return e;
}
const Entry & operator[]( const PseudoIndexWrapper & i ) const {
const Entry & e = entry(i(this));
nvDebugCheck(e.isTombstone() == false);
return e;
}
#else
Entry & operator[](const PseudoIndex & i) {
Entry & e = entry(i);
nvDebugCheck(e.isTombstone() == false);
return e;
}
const Entry & operator[](const PseudoIndex & i) const {
const Entry & e = entry(i);
nvDebugCheck(e.isTombstone() == false);
return e;
}
#endif
// By default we serialize the key-value pairs compactl y.
template<typename _T, typename _U, typename _H, typename _E>
friend Stream & operator<< (Stream & s, HashMap<_T, _U, _H, _E> & map);
// This requires more storage, but saves us from rehashing the elements.
template<typename _T, typename _U, typename _H, typename _E>
friend Stream & rawSerialize(Stream & s, HashMap<_T, _U, _H, _E> & map);
/// Swap the members of this vector and the given vector.
template<typename _T, typename _U, typename _H, typename _E>
friend void swap(HashMap<_T, _U, _H, _E> & a, HashMap<_T, _U, _H, _E> & b);
private:
static const uint TOMBSTONE_HASH = (uint) -1;
uint compute_hash(const T& key) const;
// Find the index of the matching entry. If no match, then return -1.
int findIndex(const T& key) const;
// Return the index of the newly cleared element.
int removeTombstone(int index);
// Helpers.
Entry & entry(int index);
const Entry & entry(int index) const;
void setRawCapacity(int new_size);
// Move the enumerator to the next valid element.
void findNext(PseudoIndex & i) const;
int entry_count;
int size_mask;
Entry * table;
};
} // nv namespace
#endif // NV_CORE_HASHMAP_H

View file

@ -1,550 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_CORE_HASHMAP_INL
#define NV_CORE_HASHMAP_INL
#include "HashMap.h"
#include "Stream.h"
#include "Utils.h" // swap
#include <new> // for placement new
namespace nv
{
// Set a new or existing value under the key, to the value.
template<typename T, typename U, typename H, typename E>
void HashMap<T, U, H, E>::set(const T& key, const U& value)
{
int index = findIndex(key);
if (index >= 0)
{
entry(index).value = value;
return;
}
// Entry under key doesn't exist.
add(key, value);
}
// Add a new value to the hash table, under the specified key.
template<typename T, typename U, typename H, typename E>
void HashMap<T, U, H, E>::add(const T& key, const U& value)
{
nvCheck(findIndex(key) == -1);
checkExpand();
nvCheck(table != NULL);
entry_count++;
const uint hash_value = compute_hash(key);
const int index = hash_value & size_mask;
Entry * natural_entry = &(entry(index));
if (natural_entry->isEmpty())
{
// Put the new entry in.
new (natural_entry) Entry(key, value, -1, hash_value);
}
else if (natural_entry->isTombstone()) {
// Put the new entry in, without disturbing the rest of the chain.
int next_in_chain = natural_entry->next_in_chain;
new (natural_entry) Entry(key, value, next_in_chain, hash_value);
}
else
{
// Find a blank spot.
int blank_index = index;
for (int search_count = 0; ; search_count++)
{
blank_index = (blank_index + 1) & size_mask;
if (entry(blank_index).isEmpty()) break; // found it
if (entry(blank_index).isTombstone()) {
blank_index = removeTombstone(blank_index);
break;
}
nvCheck(search_count < this->size_mask);
}
Entry * blank_entry = &entry(blank_index);
if (int(natural_entry->hash_value & size_mask) == index)
{
// Collision. Link into this chain.
// Move existing list head.
new (blank_entry) Entry(*natural_entry); // placement new, copy ctor
// Put the new info in the natural entry.
natural_entry->key = key;
natural_entry->value = value;
natural_entry->next_in_chain = blank_index;
natural_entry->hash_value = hash_value;
}
else
{
// Existing entry does not naturally
// belong in this slot. Existing
// entry must be moved.
// Find natural location of collided element (i.e. root of chain)
int collided_index = natural_entry->hash_value & size_mask;
for (int search_count = 0; ; search_count++)
{
Entry * e = &entry(collided_index);
if (e->next_in_chain == index)
{
// Here's where we need to splice.
new (blank_entry) Entry(*natural_entry);
e->next_in_chain = blank_index;
break;
}
collided_index = e->next_in_chain;
nvCheck(collided_index >= 0 && collided_index <= size_mask);
nvCheck(search_count <= size_mask);
}
// Put the new data in the natural entry.
natural_entry->key = key;
natural_entry->value = value;
natural_entry->hash_value = hash_value;
natural_entry->next_in_chain = -1;
}
}
}
// Remove the first value under the specified key.
template<typename T, typename U, typename H, typename E>
bool HashMap<T, U, H, E>::remove(const T& key)
{
if (table == NULL)
{
return false;
}
int index = findIndex(key);
if (index < 0)
{
return false;
}
Entry * pos = &entry(index);
int natural_index = (int) (pos->hash_value & size_mask);
if (index != natural_index) {
// We're not the head of our chain, so we can
// be spliced out of it.
// Iterate up the chain, and splice out when
// we get to m_index.
Entry* e = &entry(natural_index);
while (e->next_in_chain != index) {
nvDebugCheck(e->isEndOfChain() == false);
e = &entry(e->next_in_chain);
}
if (e->isTombstone() && pos->isEndOfChain()) {
// Tombstone has nothing else to point
// to, so mark it empty.
e->next_in_chain = -2;
} else {
e->next_in_chain = pos->next_in_chain;
}
pos->clear();
}
else if (pos->isEndOfChain() == false) {
// We're the head of our chain, and there are
// additional elements.
//
// We need to put a tombstone here.
//
// We can't clear the element, because the
// rest of the elements in the chain must be
// linked to this position.
//
// We can't move any of the succeeding
// elements in the chain (i.e. to fill this
// entry), because we don't want to invalidate
// any other existing iterators.
pos->makeTombstone();
} else {
// We're the head of the chain, but we're the
// only member of the chain.
pos->clear();
}
entry_count--;
return true;
}
// Remove all entries from the hash table.
template<typename T, typename U, typename H, typename E>
void HashMap<T, U, H, E>::clear()
{
if (table != NULL)
{
// Delete the entries.
for (int i = 0, n = size_mask; i <= n; i++)
{
Entry * e = &entry(i);
if (e->isEmpty() == false && e->isTombstone() == false)
{
e->clear();
}
}
free(table);
table = NULL;
entry_count = 0;
size_mask = -1;
}
}
// Returns true if the hash is empty.
template<typename T, typename U, typename H, typename E>
bool HashMap<T, U, H, E>::isEmpty() const
{
return table == NULL || entry_count == 0;
}
// Retrieve the value under the given key.
// - If there's no value under the key, then return false and leave *value alone.
// - If there is a value, return true, and set *value to the entry's value.
// - If value == NULL, return true or false according to the presence of the key, but don't touch *value.
template<typename T, typename U, typename H, typename E>
bool HashMap<T, U, H, E>::get(const T& key, U* value/*= NULL*/, T* other_key/*= NULL*/) const
{
int index = findIndex(key);
if (index >= 0)
{
if (value != NULL) {
*value = entry(index).value; // take care with side-effects!
}
if (other_key != NULL) {
*other_key = entry(index).key;
}
return true;
}
return false;
}
// Determine if the given key is contained in the hash.
template<typename T, typename U, typename H, typename E>
bool HashMap<T, U, H, E>::contains(const T & key) const
{
return get(key);
}
// Number of entries in the hash.
template<typename T, typename U, typename H, typename E>
int HashMap<T, U, H, E>::size() const
{
return entry_count;
}
// Number of entries in the hash.
template<typename T, typename U, typename H, typename E>
int HashMap<T, U, H, E>::count() const
{
return size();
}
template<typename T, typename U, typename H, typename E>
int HashMap<T, U, H, E>::capacity() const
{
return size_mask+1;
}
// Resize the hash table to fit one more entry. Often this doesn't involve any action.
template<typename T, typename U, typename H, typename E>
void HashMap<T, U, H, E>::checkExpand()
{
if (table == NULL) {
// Initial creation of table. Make a minimum-sized table.
setRawCapacity(16);
}
else if (entry_count * 3 > (size_mask + 1) * 2) {
// Table is more than 2/3rds full. Expand.
setRawCapacity(entry_count * 2);
}
}
// Hint the bucket count to >= n.
template<typename T, typename U, typename H, typename E>
void HashMap<T, U, H, E>::resize(int n)
{
// Not really sure what this means in relation to
// STLport's hash_map... they say they "increase the
// bucket count to at least n" -- but does that mean
// their real capacity after resize(n) is more like
// n*2 (since they do linked-list chaining within
// buckets?).
setCapacity(n);
}
// Size the hash so that it can comfortably contain the given number of elements. If the hash already contains more
// elements than new_size, then this may be a no-op.
template<typename T, typename U, typename H, typename E>
void HashMap<T, U, H, E>::setCapacity(int new_size)
{
int new_raw_size = (new_size * 3) / 2;
if (new_raw_size < size()) { return; }
setRawCapacity(new_raw_size);
}
// By default we serialize the key-value pairs compactly.
template<typename _T, typename _U, typename _H, typename _E>
Stream & operator<< (Stream & s, HashMap<_T, _U, _H, _E> & map)
{
typedef typename HashMap<_T, _U, _H, _E>::Entry HashMapEntry;
int entry_count = map.entry_count;
s << entry_count;
if (s.isLoading()) {
map.clear();
if(entry_count == 0) {
return s;
}
map.entry_count = entry_count;
map.size_mask = nextPowerOfTwo(U32(entry_count)) - 1;
map.table = malloc<HashMapEntry>(map.size_mask + 1);
for (int i = 0; i <= map.size_mask; i++) {
map.table[i].next_in_chain = -2; // mark empty
}
_T key;
_U value;
for (int i = 0; i < entry_count; i++) {
s << key << value;
map.add(key, value);
}
}
else {
int i = 0;
map.findNext(i);
while (i != map.size_mask+1) {
HashMapEntry & e = map.entry(i);
s << e.key << e.value;
i++;
map.findNext(i);
}
//for(HashMap<_T, _U, _H, _E>::PseudoIndex i((map).start()); !(map).isDone(i); (map).advance(i)) {
//foreach(i, map) {
// s << map[i].key << map[i].value;
//}
}
return s;
}
// This requires more storage, but saves us from rehashing the elements.
template<typename _T, typename _U, typename _H, typename _E>
Stream & rawSerialize(Stream & s, HashMap<_T, _U, _H, _E> & map)
{
typedef typename HashMap<_T, _U, _H, _E>::Entry HashMapEntry;
if (s.isLoading()) {
map.clear();
}
s << map.size_mask;
if (map.size_mask != -1) {
s << map.entry_count;
if (s.isLoading()) {
map.table = new HashMapEntry[map.size_mask+1];
}
for (int i = 0; i <= map.size_mask; i++) {
HashMapEntry & e = map.table[i];
s << e.next_in_chain << e.hash_value;
s << e.key;
s << e.value;
}
}
return s;
}
// Swap the members of this vector and the given vector.
template<typename _T, typename _U, typename _H, typename _E>
void swap(HashMap<_T, _U, _H, _E> & a, HashMap<_T, _U, _H, _E> & b)
{
swap(a.entry_count, b.entry_count);
swap(a.size_mask, b.size_mask);
swap(a.table, b.table);
}
template<typename T, typename U, typename H, typename E>
uint HashMap<T, U, H, E>::compute_hash(const T& key) const
{
H hash;
uint hash_value = hash(key);
if (hash_value == TOMBSTONE_HASH) {
hash_value ^= 0x8000;
}
return hash_value;
}
// Find the index of the matching entry. If no match, then return -1.
template<typename T, typename U, typename H, typename E>
int HashMap<T, U, H, E>::findIndex(const T& key) const
{
if (table == NULL) return -1;
E equal;
uint hash_value = compute_hash(key);
int index = hash_value & size_mask;
const Entry * e = &entry(index);
if (e->isEmpty()) return -1;
if (e->isTombstone() == false && int(e->hash_value & size_mask) != index) {
// occupied by a collider
return -1;
}
for (;;)
{
nvCheck(e->isTombstone() || (e->hash_value & size_mask) == (hash_value & size_mask));
if (e->hash_value == hash_value && equal(e->key, key))
{
// Found it.
return index;
}
nvDebugCheck(e->isTombstone() || !equal(e->key, key)); // keys are equal, but hash differs!
// Keep looking through the chain.
index = e->next_in_chain;
if (index == -1) break; // end of chain
nvCheck(index >= 0 && index <= size_mask);
e = &entry(index);
nvCheck(e->isEmpty() == false || e->isTombstone());
}
return -1;
}
// Return the index of the newly cleared element.
template<typename T, typename U, typename H, typename E>
int HashMap<T, U, H, E>::removeTombstone(int index) {
Entry* e = &entry(index);
nvCheck(e->isTombstone());
nvCheck(!e->isEndOfChain());
// Move the next element of the chain into the
// tombstone slot, and return the vacated element.
int new_blank_index = e->next_in_chain;
Entry* new_blank = &entry(new_blank_index);
new (e) Entry(*new_blank);
new_blank->clear();
return new_blank_index;
}
// Helpers.
template<typename T, typename U, typename H, typename E>
typename HashMap<T, U, H, E>::Entry & HashMap<T, U, H, E>::entry(int index)
{
nvDebugCheck(table != NULL);
nvDebugCheck(index >= 0 && index <= size_mask);
return table[index];
}
template<typename T, typename U, typename H, typename E>
const typename HashMap<T, U, H, E>::Entry & HashMap<T, U, H, E>::entry(int index) const
{
nvDebugCheck(table != NULL);
nvDebugCheck(index >= 0 && index <= size_mask);
return table[index];
}
// Resize the hash table to the given size (Rehash the contents of the current table). The arg is the number of
// hash table entries, not the number of elements we should actually contain (which will be less than this).
template<typename T, typename U, typename H, typename E>
void HashMap<T, U, H, E>::setRawCapacity(int new_size)
{
if (new_size <= 0) {
// Special case.
clear();
return;
}
// Force new_size to be a power of two.
new_size = nextPowerOfTwo(U32(new_size));
HashMap<T, U, H, E> new_hash;
new_hash.table = malloc<Entry>(new_size);
nvDebugCheck(new_hash.table != NULL);
new_hash.entry_count = 0;
new_hash.size_mask = new_size - 1;
for (int i = 0; i < new_size; i++)
{
new_hash.entry(i).next_in_chain = -2; // mark empty
}
// Copy stuff to new_hash
if (table != NULL)
{
for (int i = 0, n = size_mask; i <= n; i++)
{
Entry * e = &entry(i);
if (e->isEmpty() == false && e->isTombstone() == false)
{
// Insert old entry into new hash.
new_hash.add(e->key, e->value);
e->clear(); // placement delete of old element
}
}
// Delete our old data buffer.
free(table);
}
// Steal new_hash's data.
entry_count = new_hash.entry_count;
size_mask = new_hash.size_mask;
table = new_hash.table;
new_hash.entry_count = 0;
new_hash.size_mask = -1;
new_hash.table = NULL;
}
// Move the enumerator to the next valid element.
template<typename T, typename U, typename H, typename E>
void HashMap<T, U, H, E>::findNext(PseudoIndex & i) const {
while (i <= size_mask) {
const Entry & e = entry(i);
if (e.isEmpty() == false && e.isTombstone() == false) {
break;
}
i++;
}
}
} // nv namespace
#endif // NV_CORE_HASHMAP_INL

View file

@ -1,153 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#include "Memory.h"
#include "Debug.h"
#include "Utils.h"
#include <stdlib.h>
#ifdef NV_OS_LINUX
#include <malloc.h>
#endif
#define USE_EFENCE 0
#if USE_EFENCE
extern "C" void *EF_malloc(size_t size);
extern "C" void *EF_realloc(void * oldBuffer, size_t newSize);
extern "C" void EF_free(void * address);
#endif
using namespace nv;
#if NV_OVERRIDE_ALLOC
void * malloc(size_t size)
{
#if USE_EFENCE
return EF_malloc(size);
#else
return ::malloc(size);
#endif
}
void * debug_malloc(size_t size, const char * file, int line)
{
NV_UNUSED(file);
NV_UNUSED(line);
#if USE_EFENCE
return EF_malloc(size);
#else
return ::malloc(size);
#endif
}
void free(void * ptr)
{
#if USE_EFENCE
return EF_free(const_cast<void *>(ptr));
#else
::free(const_cast<void *>(ptr));
#endif
}
void * realloc(void * ptr, size_t size)
{
nvDebugCheck(ptr != NULL || size != 0); // undefined realloc behavior.
#if USE_EFENCE
return EF_realloc(ptr, size);
#else
return ::realloc(ptr, size);
#endif
}
/* No need to override this unless we want line info.
void * operator new (size_t size) throw()
{
return malloc(size);
}
void operator delete (void *p) throw()
{
free(p);
}
void * operator new [] (size_t size) throw()
{
return malloc(size);
}
void operator delete [] (void * p) throw()
{
free(p);
}
*/
#if 0 // Code from Apple:
void* operator new(std::size_t sz) throw (std::bad_alloc)
{
void *result = std::malloc (sz == 0 ? 1 : sz);
if (result == NULL)
throw std::bad_alloc();
gNewCounter++;
return result;
}
void operator delete(void* p) throw()
{
if (p == NULL)
return;
std::free (p);
gDeleteCounter++;
}
/* These are the 'nothrow' versions of the above operators.
The system version will try to call a std::new_handler if they
fail, but your overriding versions are not required to do this. */
void* operator new(std::size_t sz, const std::nothrow_t&) throw()
{
try {
void * result = ::operator new (sz); // calls our overridden operator new
return result;
} catch (std::bad_alloc &) {
return NULL;
}
}
void operator delete(void* p, const std::nothrow_t&) throw()
{
::operator delete (p);
}
#endif // 0
#endif // NV_OVERRIDE_ALLOC
void * nv::aligned_malloc(size_t size, size_t alignment)
{
// alignment must be a power of two, multiple of sizeof(void*)
nvDebugCheck(isPowerOfTwo(alignment));
nvDebugCheck((alignment & (sizeof(void*) - 1)) == 0);
#if NV_OS_WIN32 || NV_OS_DURANGO
return _aligned_malloc(size, alignment);
#elif NV_OS_DARWIN && !NV_OS_IOS
void * ptr = NULL;
posix_memalign(&ptr, alignment, size);
return ptr;
#elif NV_OS_LINUX
return memalign(alignment, size);
#else // NV_OS_ORBIS || NV_OS_IOS
// @@ IC: iOS appears to be 16 byte aligned, should we check alignment and assert if we request a higher alignment factor?
return ::malloc(size);
#endif
}
void nv::aligned_free(void * ptr)
{
#if NV_OS_WIN32 || NV_OS_DURANGO
_aligned_free(ptr);
#else
::free(ptr);
#endif
}

View file

@ -1,72 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_CORE_MEMORY_H
#define NV_CORE_MEMORY_H
#include "nvcore.h"
#include <stdlib.h> // malloc(), realloc() and free()
#include <string.h> // memset
//#include <stddef.h> // size_t
//#include <new> // new and delete
#define TRACK_MEMORY_LEAKS 0
#if TRACK_MEMORY_LEAKS
#include <vld.h>
#endif
#if NV_CC_GNUC
# define NV_ALIGN_16 __attribute__ ((__aligned__ (16)))
#else
# define NV_ALIGN_16 __declspec(align(16))
#endif
#define NV_OVERRIDE_ALLOC 0
#if NV_OVERRIDE_ALLOC
// Custom memory allocator
extern "C" {
NVCORE_API void * malloc(size_t size);
NVCORE_API void * debug_malloc(size_t size, const char * file, int line);
NVCORE_API void free(void * ptr);
NVCORE_API void * realloc(void * ptr, size_t size);
}
/*
#ifdef _DEBUG
#define new new(__FILE__, __LINE__)
#define malloc(i) debug_malloc(i, __FILE__, __LINE__)
#endif
*/
#endif
namespace nv {
NVCORE_API void * aligned_malloc(size_t size, size_t alignment);
NVCORE_API void aligned_free(void * );
// C++ helpers.
template <typename T> NV_FORCEINLINE T * malloc(size_t count) {
return (T *)::malloc(sizeof(T) * count);
}
template <typename T> NV_FORCEINLINE T * realloc(T * ptr, size_t count) {
return (T *)::realloc(ptr, sizeof(T) * count);
}
template <typename T> NV_FORCEINLINE void free(const T * ptr) {
::free((void *)ptr);
}
template <typename T> NV_FORCEINLINE void zero(T & data) {
memset(&data, 0, sizeof(T));
}
} // nv namespace
#endif // NV_CORE_MEMORY_H

View file

@ -1,322 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#ifndef NV_CORE_PTR_H
#define NV_CORE_PTR_H
#include "nvcore.h"
#include "Debug.h"
#include "RefCounted.h"
namespace nv
{
class WeakProxy;
/** Simple auto pointer template class.
*
* This is very similar to the standard auto_ptr class, but with some
* additional limitations to make its use less error prone:
* - Copy constructor and assignment operator are disabled.
* - reset method is removed.
*
* The semantics of the standard auto_ptr are not clear and change depending
* on the std implementation. For a discussion of the problems of auto_ptr read:
* http://www.awprofessional.com/content/images/020163371X/autoptrupdate\auto_ptr_update.html
*/
template <class T>
class AutoPtr
{
NV_FORBID_COPY(AutoPtr);
NV_FORBID_HEAPALLOC();
public:
/// Ctor.
AutoPtr(T * p = NULL) : m_ptr(p) { }
template <class Q>
AutoPtr(Q * p) : m_ptr(static_cast<T *>(p)) { }
/// Dtor. Deletes owned pointer.
~AutoPtr() {
delete m_ptr;
m_ptr = NULL;
}
/// Delete owned pointer and assign new one.
void operator=( T * p ) {
if (p != m_ptr)
{
delete m_ptr;
m_ptr = p;
}
}
template <class Q>
void operator=( Q * p ) {
if (p != m_ptr)
{
delete m_ptr;
m_ptr = static_cast<T *>(p);
}
}
/// Member access.
T * operator -> () const {
nvDebugCheck(m_ptr != NULL);
return m_ptr;
}
/// Get reference.
T & operator*() const {
nvDebugCheck(m_ptr != NULL);
return *m_ptr;
}
/// Get pointer.
T * ptr() const { return m_ptr; }
/// Relinquish ownership of the underlying pointer and returns that pointer.
T * release() {
T * tmp = m_ptr;
m_ptr = NULL;
return tmp;
}
/// Const pointer equal comparation.
friend bool operator == (const AutoPtr<T> & ap, const T * const p) {
return (ap.ptr() == p);
}
/// Const pointer nequal comparation.
friend bool operator != (const AutoPtr<T> & ap, const T * const p) {
return (ap.ptr() != p);
}
/// Const pointer equal comparation.
friend bool operator == (const T * const p, const AutoPtr<T> & ap) {
return (ap.ptr() == p);
}
/// Const pointer nequal comparation.
friend bool operator != (const T * const p, const AutoPtr<T> & ap) {
return (ap.ptr() != p);
}
private:
T * m_ptr;
};
/// Smart pointer template class.
template <class BaseClass>
class SmartPtr {
public:
// BaseClass must implement addRef() and release().
typedef SmartPtr<BaseClass> ThisType;
/// Default ctor.
SmartPtr() : m_ptr(NULL)
{
}
/// Other type assignment.
template <class OtherBase>
SmartPtr( const SmartPtr<OtherBase> & tc )
{
m_ptr = static_cast<BaseClass *>( tc.ptr() );
if (m_ptr) {
m_ptr->addRef();
}
}
/// Copy ctor.
SmartPtr( const ThisType & bc )
{
m_ptr = bc.ptr();
if (m_ptr) {
m_ptr->addRef();
}
}
/// Copy cast ctor. SmartPtr(NULL) is valid.
explicit SmartPtr( BaseClass * bc )
{
m_ptr = bc;
if (m_ptr) {
m_ptr->addRef();
}
}
/// Dtor.
~SmartPtr()
{
set(NULL);
}
/// -> operator.
BaseClass * operator -> () const
{
nvCheck( m_ptr != NULL );
return m_ptr;
}
/// * operator.
BaseClass & operator*() const
{
nvCheck( m_ptr != NULL );
return *m_ptr;
}
/// Get pointer.
BaseClass * ptr() const
{
return m_ptr;
}
/// Other type assignment.
template <class OtherBase>
void operator = ( const SmartPtr<OtherBase> & tc )
{
set( static_cast<BaseClass *>(tc.ptr()) );
}
/// This type assignment.
void operator = ( const ThisType & bc )
{
set( bc.ptr() );
}
/// Pointer assignment.
void operator = ( BaseClass * bc )
{
set( bc );
}
/// Other type equal comparation.
template <class OtherBase>
bool operator == ( const SmartPtr<OtherBase> & other ) const
{
return m_ptr == other.ptr();
}
/// This type equal comparation.
bool operator == ( const ThisType & bc ) const
{
return m_ptr == bc.ptr();
}
/// Const pointer equal comparation.
bool operator == ( const BaseClass * const bc ) const
{
return m_ptr == bc;
}
/// Other type not equal comparation.
template <class OtherBase>
bool operator != ( const SmartPtr<OtherBase> & other ) const
{
return m_ptr != other.ptr();
}
/// Other type not equal comparation.
bool operator != ( const ThisType & bc ) const
{
return m_ptr != bc.ptr();
}
/// Const pointer not equal comparation.
bool operator != (const BaseClass * const bc) const
{
return m_ptr != bc;
}
/// This type lower than comparation.
bool operator < (const ThisType & p) const
{
return m_ptr < p.ptr();
}
bool isValid() const {
return isValidPtr(m_ptr);
}
private:
// Set this pointer.
void set( BaseClass * p )
{
if (p) p->addRef();
if (m_ptr) m_ptr->release();
m_ptr = p;
}
private:
BaseClass * m_ptr;
};
/// Smart pointer template class.
template <class T>
class WeakPtr {
public:
WeakPtr() {}
WeakPtr(T * p) { operator=(p); }
WeakPtr(const SmartPtr<T> & p) { operator=(p.ptr()); }
// Default constructor and assignment from weak_ptr<T> are OK.
void operator=(T * p)
{
if (p) {
m_proxy = p->getWeakProxy();
nvDebugCheck(m_proxy != NULL);
nvDebugCheck(m_proxy->ptr() == p);
}
else {
m_proxy = NULL;
}
}
void operator=(const SmartPtr<T> & ptr) { operator=(ptr.ptr()); }
bool operator==(const SmartPtr<T> & p) const { return ptr() == p.ptr(); }
bool operator!=(const SmartPtr<T> & p) const { return ptr() != p.ptr(); }
bool operator==(const WeakPtr<T> & p) const { return ptr() == p.ptr(); }
bool operator!=(const WeakPtr<T> & p) const { return ptr() != p.ptr(); }
bool operator==(T * p) const { return ptr() == p; }
bool operator!=(T * p) const { return ptr() != p; }
T * operator->() const
{
T * p = ptr();
nvDebugCheck(p != NULL);
return p;
}
T * ptr() const
{
if (m_proxy != NULL) {
return static_cast<T *>(m_proxy->ptr());
}
return NULL;
}
private:
mutable SmartPtr<WeakProxy> m_proxy;
};
} // nv namespace
#endif // NV_CORE_PTR_H

View file

@ -1,285 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#include "RadixSort.h"
#include "Utils.h"
#include <string.h> // memset
using namespace nv;
static inline void FloatFlip(uint32 & f) {
//uint32 mask = -int32(f >> 31) | 0x80000000; // Michael Herf.
int32 mask = (int32(f) >> 31) | 0x80000000; // Warren Hunt, Manchor Ko.
f ^= mask;
}
static inline void IFloatFlip(uint32 & f) {
uint32 mask = ((f >> 31) - 1) | 0x80000000; // Michael Herf.
//uint32 mask = (int32(f ^ 0x80000000) >> 31) | 0x80000000; // Warren Hunt, Manchor Ko. @@ Correct, but fails in release on gcc-4.2.1
f ^= mask;
}
template<typename T>
void createHistograms(const T * buffer, uint count, uint * histogram)
{
const uint bucketCount = sizeof(T); // (8 * sizeof(T)) / log2(radix)
// Init bucket pointers.
uint * h[bucketCount];
for (uint i = 0; i < bucketCount; i++) {
#if NV_BIG_ENDIAN
h[sizeof(T)-1-i] = histogram + 256 * i;
#else
h[i] = histogram + 256 * i;
#endif
}
// Clear histograms.
memset(histogram, 0, 256 * bucketCount * sizeof(uint));
// @@ Add support for signed integers.
// Build histograms.
const uint8 * p = (const uint8 *)buffer; // @@ Does this break aliasing rules?
const uint8 * pe = p + count * sizeof(T);
while (p != pe) {
h[0][*p++]++, h[1][*p++]++, h[2][*p++]++, h[3][*p++]++;
if (bucketCount == 8) h[4][*p++]++, h[5][*p++]++, h[6][*p++]++, h[7][*p++]++;
}
}
/*
template <>
void createHistograms<float>(const float * buffer, uint count, uint * histogram)
{
// Init bucket pointers.
uint32 * h[4];
for (uint i = 0; i < 4; i++) {
#if NV_BIG_ENDIAN
h[3-i] = histogram + 256 * i;
#else
h[i] = histogram + 256 * i;
#endif
}
// Clear histograms.
memset(histogram, 0, 256 * 4 * sizeof(uint32));
// Build histograms.
for (uint i = 0; i < count; i++) {
uint32 fi = FloatFlip(buffer[i]);
h[0][fi & 0xFF]++;
h[1][(fi >> 8) & 0xFF]++;
h[2][(fi >> 16) & 0xFF]++;
h[3][fi >> 24]++;
}
}
*/
RadixSort::RadixSort() : m_size(0), m_ranks(NULL), m_ranks2(NULL), m_validRanks(false)
{
}
RadixSort::RadixSort(uint reserve_count) : m_size(0), m_ranks(NULL), m_ranks2(NULL), m_validRanks(false)
{
checkResize(reserve_count);
}
RadixSort::~RadixSort()
{
// Release everything
free(m_ranks2);
free(m_ranks);
}
void RadixSort::resize(uint count)
{
m_ranks2 = realloc<uint>(m_ranks2, count);
m_ranks = realloc<uint>(m_ranks, count);
}
inline void RadixSort::checkResize(uint count)
{
if (count != m_size)
{
if (count > m_size) resize(count);
m_size = count;
m_validRanks = false;
}
}
template <typename T> inline void RadixSort::insertionSort(const T * input, uint count)
{
if (!m_validRanks) {
/*for (uint i = 0; i < count; i++) {
m_ranks[i] = i;
}*/
m_ranks[0] = 0;
for (uint i = 1; i != count; ++i)
{
int rank = m_ranks[i] = i;
uint j = i;
while (j != 0 && input[rank] < input[m_ranks[j-1]])
{
m_ranks[j] = m_ranks[j-1];
--j;
}
if (i != j)
{
m_ranks[j] = rank;
}
}
m_validRanks = true;
}
else {
for (uint i = 1; i != count; ++i)
{
int rank = m_ranks[i];
uint j = i;
while (j != 0 && input[rank] < input[m_ranks[j-1]])
{
m_ranks[j] = m_ranks[j-1];
--j;
}
if (i != j)
{
m_ranks[j] = rank;
}
}
}
}
template <typename T> inline void RadixSort::radixSort(const T * input, uint count)
{
const uint P = sizeof(T); // pass count
// Allocate histograms & offsets on the stack
uint histogram[256 * P];
uint * link[256];
createHistograms(input, count, histogram);
// Radix sort, j is the pass number (0=LSB, P=MSB)
for (uint j = 0; j < P; j++)
{
// Pointer to this bucket.
const uint * h = &histogram[j * 256];
const uint8 * inputBytes = (const uint8*)input; // @@ Is this aliasing legal?
#if NV_BIG_ENDIAN
inputBytes += P - 1 - j;
#else
inputBytes += j;
#endif
if (h[inputBytes[0]] == count) {
// Skip this pass, all values are the same.
continue;
}
// Create offsets
link[0] = m_ranks2;
for (uint i = 1; i < 256; i++) link[i] = link[i-1] + h[i-1];
// Perform Radix Sort
if (!m_validRanks)
{
for (uint i = 0; i < count; i++)
{
*link[inputBytes[i*P]]++ = i;
}
m_validRanks = true;
}
else
{
for (uint i = 0; i < count; i++)
{
const uint idx = m_ranks[i];
*link[inputBytes[idx*P]]++ = idx;
}
}
// Swap pointers for next pass. Valid indices - the most recent ones - are in m_ranks after the swap.
swap(m_ranks, m_ranks2);
}
// All values were equal, generate linear ranks.
if (!m_validRanks)
{
for (uint i = 0; i < count; i++)
{
m_ranks[i] = i;
}
m_validRanks = true;
}
}
RadixSort & RadixSort::sort(const uint32 * input, uint count)
{
if (input == NULL || count == 0) return *this;
// Resize lists if needed
checkResize(count);
if (count < 32) {
insertionSort(input, count);
}
else {
radixSort<uint32>(input, count);
}
return *this;
}
RadixSort & RadixSort::sort(const uint64 * input, uint count)
{
if (input == NULL || count == 0) return *this;
// Resize lists if needed
checkResize(count);
if (count < 64) {
insertionSort(input, count);
}
else {
radixSort(input, count);
}
return *this;
}
RadixSort& RadixSort::sort(const float * input, uint count)
{
if (input == NULL || count == 0) return *this;
// Resize lists if needed
checkResize(count);
if (count < 32) {
insertionSort(input, count);
}
else {
// @@ Avoid touching the input multiple times.
for (uint i = 0; i < count; i++) {
FloatFlip((uint32 &)input[i]);
}
radixSort<uint32>((const uint32 *)input, count);
for (uint i = 0; i < count; i++) {
IFloatFlip((uint32 &)input[i]);
}
}
return *this;
}

View file

@ -1,75 +0,0 @@
#pragma once
#ifndef NV_CORE_RADIXSORT_H
#define NV_CORE_RADIXSORT_H
// Based on Pierre Terdiman's and Michael Herf's source code.
// http://www.codercorner.com/RadixSortRevisited.htm
// http://www.stereopsis.com/radix.html
#include "nvcore.h"
#include "Array.h"
namespace nv
{
class NVCORE_CLASS RadixSort
{
NV_FORBID_COPY(RadixSort);
public:
// Constructor/Destructor
RadixSort();
RadixSort(uint reserve_count);
~RadixSort();
// Invalidate ranks.
RadixSort & reset() { m_validRanks = false; return *this; }
// Sorting methods.
RadixSort & sort(const uint32 * input, uint count);
RadixSort & sort(const uint64 * input, uint count);
RadixSort & sort(const float * input, uint count);
// Helpers.
RadixSort & sort(const Array<uint32> & input);
RadixSort & sort(const Array<uint64> & input);
RadixSort & sort(const Array<float> & input);
// Access to results. m_ranks is a list of indices in sorted order, i.e. in the order you may further process your data
inline const uint * ranks() const { nvDebugCheck(m_validRanks); return m_ranks; }
inline uint * ranks() { nvDebugCheck(m_validRanks); return m_ranks; }
inline uint rank(uint i) const { nvDebugCheck(m_validRanks); return m_ranks[i]; }
// query whether the sort has been performed
inline bool valid() const { return m_validRanks; }
private:
uint m_size;
uint * m_ranks;
uint * m_ranks2;
bool m_validRanks;
// Internal methods
template <typename T> void insertionSort(const T * input, uint count);
template <typename T> void radixSort(const T * input, uint count);
void checkResize(uint nb);
void resize(uint nb);
};
inline RadixSort & RadixSort::sort(const Array<uint32> & input) {
return sort(input.buffer(), input.count());
}
inline RadixSort & RadixSort::sort(const Array<uint64> & input) {
return sort(input.buffer(), input.count());
}
inline RadixSort & RadixSort::sort(const Array<float> & input) {
return sort(input.buffer(), input.count());
}
} // nv namespace
#endif // NV_CORE_RADIXSORT_H

View file

@ -1,149 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#ifndef NV_CORE_REFCOUNTED_H
#define NV_CORE_REFCOUNTED_H
#include "nvcore.h"
#include "Debug.h"
#define NV_DECLARE_PTR(Class) \
template <class T> class SmartPtr; \
typedef SmartPtr<class Class> Class ## Ptr; \
typedef SmartPtr<const class Class> Class ## ConstPtr
namespace nv
{
/// Weak proxy.
class WeakProxy
{
NV_FORBID_COPY(WeakProxy);
public:
/// Ctor.
WeakProxy(void * ptr) : m_count(0), m_ptr(ptr) { }
/// Dtor.
~WeakProxy()
{
nvCheck( m_count == 0 );
}
/// Increase reference count.
uint addRef() const
{
m_count++;
return m_count;
}
/// Decrease reference count and remove when 0.
uint release() const
{
nvCheck( m_count > 0 );
m_count--;
if( m_count == 0 ) {
delete this;
return 0;
}
return m_count;
}
/// WeakPtr's call this to determine if their pointer is valid or not.
bool isAlive() const {
return m_ptr != NULL;
}
/// Only the actual object should call this.
void notifyObjectDied() {
m_ptr = NULL;
}
/// Return proxy pointer.
void * ptr() const {
return m_ptr;
}
private:
mutable int m_count;
void * m_ptr;
};
/// Reference counted base class to be used with SmartPtr and WeakPtr.
class RefCounted
{
NV_FORBID_COPY(RefCounted);
public:
/// Ctor.
RefCounted() : m_count(0), m_weak_proxy(NULL)
{
}
/// Virtual dtor.
virtual ~RefCounted()
{
nvCheck( m_count == 0 );
releaseWeakProxy();
}
/// Increase reference count.
uint addRef() const
{
m_count++;
return m_count;
}
/// Decrease reference count and remove when 0.
uint release() const
{
nvCheck( m_count > 0 );
m_count--;
if( m_count == 0 ) {
delete this;
return 0;
}
return m_count;
}
/// Get weak proxy.
WeakProxy * getWeakProxy() const
{
if (m_weak_proxy == NULL) {
m_weak_proxy = new WeakProxy((void *)this);
m_weak_proxy->addRef();
}
return m_weak_proxy;
}
/// Release the weak proxy.
void releaseWeakProxy() const
{
if (m_weak_proxy != NULL) {
m_weak_proxy->notifyObjectDied();
m_weak_proxy->release();
m_weak_proxy = NULL;
}
}
/// Get reference count.
int refCount() const
{
return m_count;
}
private:
mutable int m_count;
mutable WeakProxy * m_weak_proxy;
};
} // nv namespace
#endif // NV_CORE_REFCOUNTED_H

View file

@ -1,474 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
//#pragma once
//#ifndef NV_CORE_STDSTREAM_H
//#define NV_CORE_STDSTREAM_H
#include "nvcore.h"
#include "Stream.h"
#include "Array.h"
#include <stdio.h> // fopen
#include <string.h> // memcpy
namespace nv
{
// Portable version of fopen.
inline FILE * fileOpen(const char * fileName, const char * mode)
{
nvCheck(fileName != NULL);
#if NV_CC_MSVC && _MSC_VER >= 1400
FILE * fp;
if (fopen_s(&fp, fileName, mode) == 0) {
return fp;
}
return NULL;
#else
return fopen(fileName, mode);
#endif
}
/// Base stdio stream.
class NVCORE_CLASS StdStream : public Stream
{
NV_FORBID_COPY(StdStream);
public:
/// Ctor.
StdStream( FILE * fp, bool autoclose ) : m_fp(fp), m_autoclose(autoclose) { }
/// Dtor.
virtual ~StdStream()
{
if( m_fp != NULL && m_autoclose ) {
#if NV_OS_WIN32
_fclose_nolock( m_fp );
#else
fclose( m_fp );
#endif
}
}
/** @name Stream implementation. */
//@{
virtual void seek( uint pos )
{
nvDebugCheck(m_fp != NULL);
nvDebugCheck(pos <= size());
#if NV_OS_WIN32
_fseek_nolock(m_fp, pos, SEEK_SET);
#else
fseek(m_fp, pos, SEEK_SET);
#endif
}
virtual uint tell() const
{
nvDebugCheck(m_fp != NULL);
#if NV_OS_WIN32
return _ftell_nolock(m_fp);
#else
return (uint)ftell(m_fp);
#endif
}
virtual uint size() const
{
nvDebugCheck(m_fp != NULL);
#if NV_OS_WIN32
uint pos = _ftell_nolock(m_fp);
_fseek_nolock(m_fp, 0, SEEK_END);
uint end = _ftell_nolock(m_fp);
_fseek_nolock(m_fp, pos, SEEK_SET);
#else
uint pos = (uint)ftell(m_fp);
fseek(m_fp, 0, SEEK_END);
uint end = (uint)ftell(m_fp);
fseek(m_fp, pos, SEEK_SET);
#endif
return end;
}
virtual bool isError() const
{
return m_fp == NULL || ferror( m_fp ) != 0;
}
virtual void clearError()
{
nvDebugCheck(m_fp != NULL);
clearerr(m_fp);
}
// @@ The original implementation uses feof, which only returns true when we attempt to read *past* the end of the stream.
// That is, if we read the last byte of a file, then isAtEnd would still return false, even though the stream pointer is at the file end. This is not the intent and was inconsistent with the implementation of the MemoryStream, a better
// implementation uses use ftell and fseek to determine our location within the file.
virtual bool isAtEnd() const
{
if (m_fp == NULL) return true;
//nvDebugCheck(m_fp != NULL);
//return feof( m_fp ) != 0;
#if NV_OS_WIN32
uint pos = _ftell_nolock(m_fp);
_fseek_nolock(m_fp, 0, SEEK_END);
uint end = _ftell_nolock(m_fp);
_fseek_nolock(m_fp, pos, SEEK_SET);
#else
uint pos = (uint)ftell(m_fp);
fseek(m_fp, 0, SEEK_END);
uint end = (uint)ftell(m_fp);
fseek(m_fp, pos, SEEK_SET);
#endif
return pos == end;
}
/// Always true.
virtual bool isSeekable() const { return true; }
//@}
protected:
FILE * m_fp;
bool m_autoclose;
};
/// Standard output stream.
class NVCORE_CLASS StdOutputStream : public StdStream
{
NV_FORBID_COPY(StdOutputStream);
public:
/// Construct stream by file name.
StdOutputStream( const char * name ) : StdStream(fileOpen(name, "wb"), /*autoclose=*/true) { }
/// Construct stream by file handle.
StdOutputStream( FILE * fp, bool autoclose ) : StdStream(fp, autoclose)
{
}
/** @name Stream implementation. */
//@{
/// Write data.
virtual uint serialize( void * data, uint len )
{
nvDebugCheck(data != NULL);
nvDebugCheck(m_fp != NULL);
#if NV_OS_WIN32
return (uint)_fwrite_nolock(data, 1, len, m_fp);
#elif NV_OS_LINUX
return (uint)fwrite_unlocked(data, 1, len, m_fp);
#elif NV_OS_DARWIN
// @@ No error checking, always returns len.
for (uint i = 0; i < len; i++) {
putc_unlocked(((char *)data)[i], m_fp);
}
return len;
#else
return (uint)fwrite(data, 1, len, m_fp);
#endif
}
virtual bool isLoading() const
{
return false;
}
virtual bool isSaving() const
{
return true;
}
//@}
};
/// Standard input stream.
class NVCORE_CLASS StdInputStream : public StdStream
{
NV_FORBID_COPY(StdInputStream);
public:
/// Construct stream by file name.
StdInputStream( const char * name ) : StdStream(fileOpen(name, "rb"), /*autoclose=*/true) { }
/// Construct stream by file handle.
StdInputStream( FILE * fp, bool autoclose=true ) : StdStream(fp, autoclose)
{
}
/** @name Stream implementation. */
//@{
/// Read data.
virtual uint serialize( void * data, uint len )
{
nvDebugCheck(data != NULL);
nvDebugCheck(m_fp != NULL);
#if NV_OS_WIN32
return (uint)_fread_nolock(data, 1, len, m_fp);
#elif NV_OS_LINUX
return (uint)fread_unlocked(data, 1, len, m_fp);
#elif NV_OS_DARWIN
// This is rather lame. Not sure if it's faster than the locked version.
for (uint i = 0; i < len; i++) {
((char *)data)[i] = getc_unlocked(m_fp);
if (feof_unlocked(m_fp) != 0) {
return i;
}
}
return len;
#else
return (uint)fread(data, 1, len, m_fp);
#endif
}
virtual bool isLoading() const
{
return true;
}
virtual bool isSaving() const
{
return false;
}
//@}
};
/// Memory input stream.
class NVCORE_CLASS MemoryInputStream : public Stream
{
NV_FORBID_COPY(MemoryInputStream);
public:
/// Ctor.
MemoryInputStream( const uint8 * mem, uint size ) : m_mem(mem), m_ptr(mem), m_size(size) { }
/** @name Stream implementation. */
//@{
/// Read data.
virtual uint serialize( void * data, uint len )
{
nvDebugCheck(data != NULL);
nvDebugCheck(!isError());
uint left = m_size - tell();
if (len > left) len = left;
memcpy( data, m_ptr, len );
m_ptr += len;
return len;
}
virtual void seek( uint pos )
{
nvDebugCheck(!isError());
m_ptr = m_mem + pos;
nvDebugCheck(!isError());
}
virtual uint tell() const
{
nvDebugCheck(m_ptr >= m_mem);
return uint(m_ptr - m_mem);
}
virtual uint size() const
{
return m_size;
}
virtual bool isError() const
{
return m_mem == NULL || m_ptr > m_mem + m_size || m_ptr < m_mem;
}
virtual void clearError()
{
// Nothing to do.
}
virtual bool isAtEnd() const
{
return m_ptr == m_mem + m_size;
}
/// Always true.
virtual bool isSeekable() const
{
return true;
}
virtual bool isLoading() const
{
return true;
}
virtual bool isSaving() const
{
return false;
}
//@}
const uint8 * ptr() const { return m_ptr; }
private:
const uint8 * m_mem;
const uint8 * m_ptr;
uint m_size;
};
/// Buffer output stream.
class NVCORE_CLASS BufferOutputStream : public Stream
{
NV_FORBID_COPY(BufferOutputStream);
public:
BufferOutputStream(Array<uint8> & buffer) : m_buffer(buffer) { }
virtual uint serialize( void * data, uint len )
{
nvDebugCheck(data != NULL);
m_buffer.append((uint8 *)data, len);
return len;
}
virtual void seek( uint /*pos*/ ) { /*Not implemented*/ }
virtual uint tell() const { return m_buffer.size(); }
virtual uint size() const { return m_buffer.size(); }
virtual bool isError() const { return false; }
virtual void clearError() {}
virtual bool isAtEnd() const { return true; }
virtual bool isSeekable() const { return false; }
virtual bool isLoading() const { return false; }
virtual bool isSaving() const { return true; }
private:
Array<uint8> & m_buffer;
};
/// Protected input stream.
class NVCORE_CLASS ProtectedStream : public Stream
{
NV_FORBID_COPY(ProtectedStream);
public:
/// Ctor.
ProtectedStream( Stream & s ) : m_s(&s), m_autodelete(false)
{
}
/// Ctor.
ProtectedStream( Stream * s, bool autodelete = true ) :
m_s(s), m_autodelete(autodelete)
{
nvDebugCheck(m_s != NULL);
}
/// Dtor.
virtual ~ProtectedStream()
{
if( m_autodelete ) {
delete m_s;
}
}
/** @name Stream implementation. */
//@{
/// Read data.
virtual uint serialize( void * data, uint len )
{
nvDebugCheck(data != NULL);
len = m_s->serialize( data, len );
if( m_s->isError() ) {
#if NV_OS_ORBIS
//SBtodoORBIS disabled (no exceptions)
#else
throw;
#endif
}
return len;
}
virtual void seek( uint pos )
{
m_s->seek( pos );
if( m_s->isError() ) {
#if NV_OS_ORBIS
//SBtodoORBIS disabled (no exceptions)
#else
throw;
#endif
}
}
virtual uint tell() const
{
return m_s->tell();
}
virtual uint size() const
{
return m_s->size();
}
virtual bool isError() const
{
return m_s->isError();
}
virtual void clearError()
{
m_s->clearError();
}
virtual bool isAtEnd() const
{
return m_s->isAtEnd();
}
virtual bool isSeekable() const
{
return m_s->isSeekable();
}
virtual bool isLoading() const
{
return m_s->isLoading();
}
virtual bool isSaving() const
{
return m_s->isSaving();
}
//@}
private:
Stream * const m_s;
bool const m_autodelete;
};
} // nv namespace
//#endif // NV_CORE_STDSTREAM_H

View file

@ -1,796 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#include "StrLib.h"
#include "Memory.h"
#include "Utils.h" // swap
#include <math.h> // log
#include <stdio.h> // vsnprintf
#include <string.h> // strlen, strcmp, etc.
#if NV_CC_MSVC
#include <stdarg.h> // vsnprintf
#endif
using namespace nv;
namespace
{
static char * strAlloc(uint size)
{
return malloc<char>(size);
}
static char * strReAlloc(char * str, uint size)
{
return realloc<char>(str, size);
}
static void strFree(const char * str)
{
return free<char>(str);
}
/*static char * strDup( const char * str )
{
nvDebugCheck( str != NULL );
uint len = uint(strlen( str ) + 1);
char * dup = strAlloc( len );
memcpy( dup, str, len );
return dup;
}*/
// helper function for integer to string conversion.
static char * i2a( uint i, char *a, uint r )
{
if( i / r > 0 ) {
a = i2a( i / r, a, r );
}
*a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i % r];
return a + 1;
}
// Locale independent functions.
static inline char toUpper( char c ) {
return (c<'a' || c>'z') ? (c) : (c+'A'-'a');
}
static inline char toLower( char c ) {
return (c<'A' || c>'Z') ? (c) : (c+'a'-'A');
}
static inline bool isAlpha( char c ) {
return (c>='a' && c<='z') || (c>='A' && c<='Z');
}
static inline bool isDigit( char c ) {
return c>='0' && c<='9';
}
static inline bool isAlnum( char c ) {
return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9');
}
}
uint nv::strLen(const char * str)
{
nvDebugCheck(str != NULL);
return U32(strlen(str));
}
int nv::strDiff(const char * s1, const char * s2)
{
nvDebugCheck(s1 != NULL);
nvDebugCheck(s2 != NULL);
return strcmp(s1, s2);
}
int nv::strCaseDiff(const char * s1, const char * s2)
{
nvDebugCheck(s1 != NULL);
nvDebugCheck(s1 != NULL);
#if NV_CC_MSVC
return _stricmp(s1, s2);
#else
return strcasecmp(s1, s2);
#endif
}
bool nv::strEqual(const char * s1, const char * s2)
{
if (s1 == s2) return true;
if (s1 == NULL || s2 == NULL) return false;
return strcmp(s1, s2) == 0;
}
bool nv::strCaseEqual(const char * s1, const char * s2)
{
if (s1 == s2) return true;
if (s1 == NULL || s2 == NULL) return false;
return strCaseDiff(s1, s2) == 0;
}
bool nv::strBeginsWith(const char * str, const char * prefix)
{
//return strstr(str, prefix) == dst;
return strncmp(str, prefix, strlen(prefix)) == 0;
}
bool nv::strEndsWith(const char * str, const char * suffix)
{
uint ml = strLen(str);
uint sl = strLen(suffix);
if (ml < sl) return false;
return strncmp(str + ml - sl, suffix, sl) == 0;
}
// @@ Add asserts to detect overlap between dst and src?
void nv::strCpy(char * dst, uint size, const char * src)
{
nvDebugCheck(dst != NULL);
nvDebugCheck(src != NULL);
#if NV_CC_MSVC && _MSC_VER >= 1400
strcpy_s(dst, size, src);
#else
NV_UNUSED(size);
strcpy(dst, src);
#endif
}
void nv::strCpy(char * dst, uint size, const char * src, uint len)
{
nvDebugCheck(dst != NULL);
nvDebugCheck(src != NULL);
#if NV_CC_MSVC && _MSC_VER >= 1400
strncpy_s(dst, size, src, len);
#else
int n = min(len+1, size);
strncpy(dst, src, n);
dst[n-1] = '\0';
#endif
}
void nv::strCat(char * dst, uint size, const char * src)
{
nvDebugCheck(dst != NULL);
nvDebugCheck(src != NULL);
#if NV_CC_MSVC && _MSC_VER >= 1400
strcat_s(dst, size, src);
#else
NV_UNUSED(size);
strcat(dst, src);
#endif
}
NVCORE_API const char * nv::strSkipWhiteSpace(const char * str)
{
nvDebugCheck(str != NULL);
while (*str == ' ') str++;
return str;
}
NVCORE_API char * nv::strSkipWhiteSpace(char * str)
{
nvDebugCheck(str != NULL);
while (*str == ' ') str++;
return str;
}
/** Pattern matching routine. I don't remember where did I get this. */
bool nv::strMatch(const char * str, const char * pat)
{
nvDebugCheck(str != NULL);
nvDebugCheck(pat != NULL);
char c2;
while (true) {
if (*pat==0) {
if (*str==0) return true;
else return false;
}
if ((*str==0) && (*pat!='*')) return false;
if (*pat=='*') {
pat++;
if (*pat==0) return true;
while (true) {
if (strMatch(str, pat)) return true;
if (*str==0) return false;
str++;
}
}
if (*pat=='?') goto match;
if (*pat=='[') {
pat++;
while (true) {
if ((*pat==']') || (*pat==0)) return false;
if (*pat==*str) break;
if (pat[1] == '-') {
c2 = pat[2];
if (c2==0) return false;
if ((*pat<=*str) && (c2>=*str)) break;
if ((*pat>=*str) && (c2<=*str)) break;
pat+=2;
}
pat++;
}
while (*pat!=']') {
if (*pat==0) {
pat--;
break;
}
pat++;
}
goto match;
}
if (*pat == NV_PATH_SEPARATOR) {
pat++;
if (*pat==0) return false;
}
if (*pat!=*str) return false;
match:
pat++;
str++;
}
}
bool nv::isNumber(const char * str) {
while(*str != '\0') {
if (!isDigit(*str)) return false;
str++;
}
return true;
}
/** Empty string. */
StringBuilder::StringBuilder() : m_size(0), m_str(NULL)
{
}
/** Preallocate space. */
StringBuilder::StringBuilder( uint size_hint ) : m_size(size_hint)
{
nvDebugCheck(m_size > 0);
m_str = strAlloc(m_size);
*m_str = '\0';
}
/** Copy ctor. */
StringBuilder::StringBuilder( const StringBuilder & s ) : m_size(0), m_str(NULL)
{
copy(s);
}
/** Copy string. */
StringBuilder::StringBuilder(const char * s) : m_size(0), m_str(NULL)
{
if (s != NULL) {
copy(s);
}
}
/** Copy string. */
StringBuilder::StringBuilder(const char * s, uint len) : m_size(0), m_str(NULL)
{
copy(s, len);
}
/** Delete the string. */
StringBuilder::~StringBuilder()
{
strFree(m_str);
}
/** Format a string safely. */
StringBuilder & StringBuilder::format( const char * fmt, ... )
{
nvDebugCheck(fmt != NULL);
va_list arg;
va_start( arg, fmt );
formatList( fmt, arg );
va_end( arg );
return *this;
}
/** Format a string safely. */
StringBuilder & StringBuilder::formatList( const char * fmt, va_list arg )
{
nvDebugCheck(fmt != NULL);
if (m_size == 0) {
m_size = 64;
m_str = strAlloc( m_size );
}
va_list tmp;
va_copy(tmp, arg);
#if NV_CC_MSVC && _MSC_VER >= 1400
int n = vsnprintf_s(m_str, m_size, _TRUNCATE, fmt, tmp);
#else
int n = vsnprintf(m_str, m_size, fmt, tmp);
#endif
va_end(tmp);
while( n < 0 || n >= int(m_size) ) {
if( n > -1 ) {
m_size = n + 1;
}
else {
m_size *= 2;
}
m_str = strReAlloc(m_str, m_size);
va_copy(tmp, arg);
#if NV_CC_MSVC && _MSC_VER >= 1400
n = vsnprintf_s(m_str, m_size, _TRUNCATE, fmt, tmp);
#else
n = vsnprintf(m_str, m_size, fmt, tmp);
#endif
va_end(tmp);
}
nvDebugCheck(n < int(m_size));
// Make sure it's null terminated.
nvDebugCheck(m_str[n] == '\0');
//str[n] = '\0';
return *this;
}
// Append a character.
StringBuilder & StringBuilder::append( char c )
{
return append(&c, 1);
}
// Append a string.
StringBuilder & StringBuilder::append( const char * s )
{
return append(s, U32(strlen( s )));
}
// Append a string.
StringBuilder & StringBuilder::append(const char * s, uint len)
{
nvDebugCheck(s != NULL);
uint offset = length();
const uint size = offset + len + 1;
reserve(size);
strCpy(m_str + offset, len + 1, s, len);
return *this;
}
StringBuilder & StringBuilder::append(const StringBuilder & str)
{
return append(str.m_str, str.length());
}
/** Append a formatted string. */
StringBuilder & StringBuilder::appendFormat( const char * fmt, ... )
{
nvDebugCheck( fmt != NULL );
va_list arg;
va_start( arg, fmt );
appendFormatList( fmt, arg );
va_end( arg );
return *this;
}
/** Append a formatted string. */
StringBuilder & StringBuilder::appendFormatList( const char * fmt, va_list arg )
{
nvDebugCheck( fmt != NULL );
va_list tmp;
va_copy(tmp, arg);
if (m_size == 0) {
formatList(fmt, arg);
}
else {
StringBuilder tmp_str;
tmp_str.formatList( fmt, tmp );
append( tmp_str.str() );
}
va_end(tmp);
return *this;
}
// Append n spaces.
StringBuilder & StringBuilder::appendSpace(uint n)
{
if (m_str == NULL) {
m_size = n + 1;
m_str = strAlloc(m_size);
memset(m_str, ' ', m_size);
m_str[n] = '\0';
}
else {
const uint len = strLen(m_str);
if (m_size < len + n + 1) {
m_size = len + n + 1;
m_str = strReAlloc(m_str, m_size);
}
memset(m_str + len, ' ', n);
m_str[len+n] = '\0';
}
return *this;
}
/** Convert number to string in the given base. */
StringBuilder & StringBuilder::number( int i, int base )
{
nvCheck( base >= 2 );
nvCheck( base <= 36 );
// @@ This needs to be done correctly.
// length = floor(log(i, base));
uint len = uint(log(float(i)) / log(float(base)) + 2); // one more if negative
reserve(len);
if( i < 0 ) {
*m_str = '-';
*i2a(uint(-i), m_str+1, base) = 0;
}
else {
*i2a(i, m_str, base) = 0;
}
return *this;
}
/** Convert number to string in the given base. */
StringBuilder & StringBuilder::number( uint i, int base )
{
nvCheck( base >= 2 );
nvCheck( base <= 36 );
// @@ This needs to be done correctly.
// length = floor(log(i, base));
uint len = uint(log(float(i)) / log(float(base)) - 0.5f + 1);
reserve(len);
*i2a(i, m_str, base) = 0;
return *this;
}
/** Resize the string preserving the contents. */
StringBuilder & StringBuilder::reserve( uint size_hint )
{
nvCheck(size_hint != 0);
if (size_hint > m_size) {
m_str = strReAlloc(m_str, size_hint);
m_size = size_hint;
}
return *this;
}
/** Copy a string safely. */
StringBuilder & StringBuilder::copy(const char * s)
{
nvCheck( s != NULL );
const uint str_size = uint(strlen( s )) + 1;
reserve(str_size);
memcpy(m_str, s, str_size);
return *this;
}
/** Copy a string safely. */
StringBuilder & StringBuilder::copy(const char * s, uint len)
{
nvCheck( s != NULL );
const uint str_size = len + 1;
reserve(str_size);
strCpy(m_str, str_size, s, len);
return *this;
}
/** Copy an StringBuilder. */
StringBuilder & StringBuilder::copy( const StringBuilder & s )
{
if (s.m_str == NULL) {
nvCheck( s.m_size == 0 );
reset();
}
else {
reserve( s.m_size );
strCpy( m_str, s.m_size, s.m_str );
}
return *this;
}
bool StringBuilder::endsWith(const char * str) const
{
uint l = uint(strlen(str));
uint ml = uint(strlen(m_str));
if (ml < l) return false;
return strncmp(m_str + ml - l, str, l) == 0;
}
bool StringBuilder::beginsWith(const char * str) const
{
size_t l = strlen(str);
return strncmp(m_str, str, l) == 0;
}
// Find given char starting from the end.
char * StringBuilder::reverseFind(char c)
{
int length = (int)strlen(m_str) - 1;
while (length >= 0 && m_str[length] != c) {
length--;
}
if (length >= 0) {
return m_str + length;
}
else {
return NULL;
}
}
/** Reset the string. */
void StringBuilder::reset()
{
m_size = 0;
strFree( m_str );
m_str = NULL;
}
/** Release the allocated string. */
char * StringBuilder::release()
{
char * str = m_str;
m_size = 0;
m_str = NULL;
return str;
}
// Take ownership of string.
void StringBuilder::acquire(char * str)
{
if (str) {
m_size = strLen(str) + 1;
m_str = str;
}
else {
m_size = 0;
m_str = NULL;
}
}
// Swap strings.
void nv::swap(StringBuilder & a, StringBuilder & b) {
swap(a.m_size, b.m_size);
swap(a.m_str, b.m_str);
}
/// Get the file name from a path.
const char * Path::fileName() const
{
return fileName(m_str);
}
/// Get the extension from a file path.
const char * Path::extension() const
{
return extension(m_str);
}
/*static */void Path::translatePath(char * path, char pathSeparator/*= NV_PATH_SEPARATOR*/) {
if (path != NULL) {
for (int i = 0;; i++) {
if (path[i] == '\0') break;
if (path[i] == '\\' || path[i] == '/') path[i] = pathSeparator;
}
}
}
/// Toggles path separators (ie. \\ into /).
void Path::translatePath(char pathSeparator/*=NV_PATH_SEPARATOR*/)
{
if (!isNull()) {
translatePath(m_str, pathSeparator);
}
}
void Path::appendSeparator(char pathSeparator/*=NV_PATH_SEPARATOR*/)
{
nvCheck(!isNull());
const uint l = length();
if (m_str[l] != '\\' && m_str[l] != '/') {
char separatorString[] = { pathSeparator, '\0' };
append(separatorString);
}
}
/**
* Strip the file name from a path.
* @warning path cannot end with '/' o '\\', can't it?
*/
void Path::stripFileName()
{
nvCheck( m_str != NULL );
int length = (int)strlen(m_str) - 1;
while (length > 0 && m_str[length] != '/' && m_str[length] != '\\'){
length--;
}
if( length ) {
m_str[length+1] = 0;
}
else {
m_str[0] = 0;
}
}
/// Strip the extension from a path name.
void Path::stripExtension()
{
nvCheck( m_str != NULL );
int length = (int)strlen(m_str) - 1;
while (length > 0 && m_str[length] != '.') {
length--;
if( m_str[length] == NV_PATH_SEPARATOR ) {
return; // no extension
}
}
if (length > 0) {
m_str[length] = 0;
}
}
/// Get the path separator.
// static
char Path::separator()
{
return NV_PATH_SEPARATOR;
}
// static
const char * Path::fileName(const char * str)
{
nvCheck( str != NULL );
int length = (int)strlen(str) - 1;
while (length >= 0 && str[length] != '\\' && str[length] != '/') {
length--;
}
return &str[length+1];
}
// static
const char * Path::extension(const char * str)
{
nvCheck( str != NULL );
int length, l;
l = length = (int)strlen( str );
while (length > 0 && str[length] != '.') {
length--;
if (str[length] == '\\' || str[length] == '/') {
return &str[l]; // no extension
}
}
if (length == 0) {
return &str[l];
}
return &str[length];
}
/// Clone this string
String String::clone() const
{
String str(data);
return str;
}
void String::setString(const char * str)
{
if (str == NULL) {
data = NULL;
}
else {
allocString( str );
addRef();
}
}
void String::setString(const char * str, uint length)
{
nvDebugCheck(str != NULL);
allocString(str, length);
addRef();
}
void String::setString(const StringBuilder & str)
{
if (str.str() == NULL) {
data = NULL;
}
else {
allocString(str.str());
addRef();
}
}
// Add reference count.
void String::addRef()
{
if (data != NULL)
{
setRefCount(getRefCount() + 1);
}
}
// Decrease reference count.
void String::release()
{
if (data != NULL)
{
const uint16 count = getRefCount();
setRefCount(count - 1);
if (count - 1 == 0) {
free(data - 2);
data = NULL;
}
}
}
void String::allocString(const char * str, uint len)
{
const char * ptr = malloc<char>(2 + len + 1);
setData( ptr );
setRefCount( 0 );
// Copy string.
strCpy(const_cast<char *>(data), len+1, str, len);
// Add terminating character.
const_cast<char *>(data)[len] = '\0';
}
void nv::swap(String & a, String & b) {
swap(a.data, b.data);
}

View file

@ -1,433 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_CORE_STRING_H
#define NV_CORE_STRING_H
#include "Debug.h"
#include "Hash.h" // hash
//#include <string.h> // strlen, etc.
#if NV_OS_WIN32
#define NV_PATH_SEPARATOR '\\'
#else
#define NV_PATH_SEPARATOR '/'
#endif
namespace nv
{
NVCORE_API uint strHash(const char * str, uint h) NV_PURE;
/// String hash based on Bernstein's hash.
inline uint strHash(const char * data, uint h = 5381)
{
uint i = 0;
while(data[i] != 0) {
h = (33 * h) ^ uint(data[i]);
i++;
}
return h;
}
template <> struct Hash<const char *> {
uint operator()(const char * str) const { return strHash(str); }
};
NVCORE_API uint strLen(const char * str) NV_PURE; // Asserts on NULL strings.
NVCORE_API int strDiff(const char * s1, const char * s2) NV_PURE; // Asserts on NULL strings.
NVCORE_API int strCaseDiff(const char * s1, const char * s2) NV_PURE; // Asserts on NULL strings.
NVCORE_API bool strEqual(const char * s1, const char * s2) NV_PURE; // Accepts NULL strings.
NVCORE_API bool strCaseEqual(const char * s1, const char * s2) NV_PURE; // Accepts NULL strings.
template <> struct Equal<const char *> {
bool operator()(const char * a, const char * b) const { return strEqual(a, b); }
};
NVCORE_API bool strBeginsWith(const char * dst, const char * prefix) NV_PURE;
NVCORE_API bool strEndsWith(const char * dst, const char * suffix) NV_PURE;
NVCORE_API void strCpy(char * dst, uint size, const char * src);
NVCORE_API void strCpy(char * dst, uint size, const char * src, uint len);
NVCORE_API void strCat(char * dst, uint size, const char * src);
NVCORE_API const char * strSkipWhiteSpace(const char * str);
NVCORE_API char * strSkipWhiteSpace(char * str);
NVCORE_API bool strMatch(const char * str, const char * pat) NV_PURE;
NVCORE_API bool isNumber(const char * str) NV_PURE;
/* @@ Implement these two functions and modify StringBuilder to use them?
NVCORE_API void strFormat(const char * dst, const char * fmt, ...);
NVCORE_API void strFormatList(const char * dst, const char * fmt, va_list arg);
template <size_t count> void strFormatSafe(char (&buffer)[count], const char *fmt, ...) __attribute__((format (printf, 2, 3)));
template <size_t count> void strFormatSafe(char (&buffer)[count], const char *fmt, ...) {
va_list args;
va_start(args, fmt);
strFormatList(buffer, count, fmt, args);
va_end(args);
}
template <size_t count> void strFormatListSafe(char (&buffer)[count], const char *fmt, va_list arg) {
va_list tmp;
va_copy(tmp, args);
strFormatList(buffer, count, fmt, tmp);
va_end(tmp);
}*/
template <int count> void strCpySafe(char (&buffer)[count], const char *src) {
strCpy(buffer, count, src);
}
template <int count> void strCatSafe(char (&buffer)[count], const char * src) {
strCat(buffer, count, src);
}
/// String builder.
class NVCORE_CLASS StringBuilder
{
public:
StringBuilder();
explicit StringBuilder( uint size_hint );
StringBuilder(const char * str);
StringBuilder(const char * str, uint len);
StringBuilder(const StringBuilder & other);
~StringBuilder();
StringBuilder & format( const char * format, ... ) __attribute__((format (printf, 2, 3)));
StringBuilder & formatList( const char * format, va_list arg );
StringBuilder & append(char c);
StringBuilder & append(const char * str);
StringBuilder & append(const char * str, uint len);
StringBuilder & append(const StringBuilder & str);
StringBuilder & appendFormat(const char * format, ...) __attribute__((format (printf, 2, 3)));
StringBuilder & appendFormatList(const char * format, va_list arg);
StringBuilder & appendSpace(uint n);
StringBuilder & number( int i, int base = 10 );
StringBuilder & number( uint i, int base = 10 );
StringBuilder & reserve(uint size_hint);
StringBuilder & copy(const char * str);
StringBuilder & copy(const char * str, uint len);
StringBuilder & copy(const StringBuilder & str);
StringBuilder & toLower();
StringBuilder & toUpper();
bool endsWith(const char * str) const;
bool beginsWith(const char * str) const;
char * reverseFind(char c);
void reset();
bool isNull() const { return m_size == 0; }
// const char * accessors
//operator const char * () const { return m_str; }
//operator char * () { return m_str; }
const char * str() const { return m_str; }
char * str() { return m_str; }
char * release(); // Release ownership of string.
void acquire(char *); // Take ownership of string.
/// Implement value semantics.
StringBuilder & operator=( const StringBuilder & s ) {
return copy(s);
}
/// Implement value semantics.
StringBuilder & operator=( const char * s ) {
return copy(s);
}
/// Equal operator.
bool operator==( const StringBuilder & s ) const {
return strMatch(s.m_str, m_str);
}
/// Return the exact length.
uint length() const { return isNull() ? 0 : strLen(m_str); }
/// Return the size of the string container.
uint capacity() const { return m_size; }
/// Return the hash of the string.
uint hash() const { return isNull() ? 0 : strHash(m_str); }
// Swap strings.
friend void swap(StringBuilder & a, StringBuilder & b);
protected:
/// Size of the string container.
uint m_size;
/// String.
char * m_str;
};
/// Path string. @@ This should be called PathBuilder.
class NVCORE_CLASS Path : public StringBuilder
{
public:
Path() : StringBuilder() {}
explicit Path(int size_hint) : StringBuilder(size_hint) {}
Path(const char * str) : StringBuilder(str) {}
Path(const Path & path) : StringBuilder(path) {}
const char * fileName() const;
const char * extension() const;
void translatePath(char pathSeparator = NV_PATH_SEPARATOR);
void appendSeparator(char pathSeparator = NV_PATH_SEPARATOR);
void stripFileName();
void stripExtension();
// statics
NVCORE_API static char separator();
NVCORE_API static const char * fileName(const char *);
NVCORE_API static const char * extension(const char *);
NVCORE_API static void translatePath(char * path, char pathSeparator = NV_PATH_SEPARATOR);
};
/// String class.
class NVCORE_CLASS String
{
public:
/// Constructs a null string. @sa isNull()
String()
{
data = NULL;
}
/// Constructs a shared copy of str.
String(const String & str)
{
data = str.data;
if (data != NULL) addRef();
}
/// Constructs a shared string from a standard string.
String(const char * str)
{
setString(str);
}
/// Constructs a shared string from a standard string.
String(const char * str, int length)
{
setString(str, length);
}
/// Constructs a shared string from a StringBuilder.
String(const StringBuilder & str)
{
setString(str);
}
/// Dtor.
~String()
{
release();
}
String clone() const;
/// Release the current string and allocate a new one.
const String & operator=( const char * str )
{
release();
setString( str );
return *this;
}
/// Release the current string and allocate a new one.
const String & operator=( const StringBuilder & str )
{
release();
setString( str );
return *this;
}
/// Implement value semantics.
String & operator=( const String & str )
{
if (str.data != data)
{
release();
data = str.data;
addRef();
}
return *this;
}
/// Equal operator.
bool operator==( const String & str ) const
{
return strMatch(str.data, data);
}
/// Equal operator.
bool operator==( const char * str ) const
{
return strMatch(str, data);
}
/// Not equal operator.
bool operator!=( const String & str ) const
{
return !strMatch(str.data, data);
}
/// Not equal operator.
bool operator!=( const char * str ) const
{
return !strMatch(str, data);
}
/// Returns true if this string is the null string.
bool isNull() const { return data == NULL; }
/// Return the exact length.
uint length() const { nvDebugCheck(data != NULL); return strLen(data); }
/// Return the hash of the string.
uint hash() const { nvDebugCheck(data != NULL); return strHash(data); }
/// const char * cast operator.
operator const char * () const { return data; }
/// Get string pointer.
const char * str() const { return data; }
private:
// Add reference count.
void addRef();
// Decrease reference count.
void release();
uint16 getRefCount() const
{
nvDebugCheck(data != NULL);
return *reinterpret_cast<const uint16 *>(data - 2);
}
void setRefCount(uint16 count) {
nvDebugCheck(data != NULL);
nvCheck(count < 0xFFFF);
*reinterpret_cast<uint16 *>(const_cast<char *>(data - 2)) = uint16(count);
}
void setData(const char * str) {
data = str + 2;
}
void allocString(const char * str)
{
allocString(str, strLen(str));
}
void allocString(const char * str, uint length);
void setString(const char * str);
void setString(const char * str, uint length);
void setString(const StringBuilder & str);
// Swap strings.
friend void swap(String & a, String & b);
private:
const char * data;
};
template <> struct Hash<String> {
uint operator()(const String & str) const { return str.hash(); }
};
// Like AutoPtr, but for const char strings.
class AutoString
{
NV_FORBID_COPY(AutoString);
NV_FORBID_HEAPALLOC();
public:
// Ctor.
AutoString(const char * p = NULL) : m_ptr(p) { }
#if NV_CC_CPP11
// Move ctor.
AutoString(AutoString && ap) : m_ptr(ap.m_ptr) { ap.m_ptr = NULL; }
#endif
// Dtor. Deletes owned pointer.
~AutoString() {
delete [] m_ptr;
m_ptr = NULL;
}
// Delete owned pointer and assign new one.
void operator=(const char * p) {
if (p != m_ptr)
{
delete [] m_ptr;
m_ptr = p;
}
}
// Get pointer.
const char * ptr() const { return m_ptr; }
operator const char *() const { return m_ptr; }
// Relinquish ownership of the underlying pointer and returns that pointer.
const char * release() {
const char * tmp = m_ptr;
m_ptr = NULL;
return tmp;
}
// comparison operators.
friend bool operator == (const AutoString & ap, const char * const p) {
return (ap.ptr() == p);
}
friend bool operator != (const AutoString & ap, const char * const p) {
return (ap.ptr() != p);
}
friend bool operator == (const char * const p, const AutoString & ap) {
return (ap.ptr() == p);
}
friend bool operator != (const char * const p, const AutoString & ap) {
return (ap.ptr() != p);
}
private:
const char * m_ptr;
};
} // nv namespace
#endif // NV_CORE_STRING_H

View file

@ -1,164 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_CORE_STREAM_H
#define NV_CORE_STREAM_H
#include "nvcore.h"
#include "Debug.h"
namespace nv
{
/// Base stream class.
class NVCORE_CLASS Stream {
public:
enum ByteOrder {
LittleEndian = false,
BigEndian = true,
};
/// Get the byte order of the system.
static ByteOrder getSystemByteOrder() {
#if NV_LITTLE_ENDIAN
return LittleEndian;
#else
return BigEndian;
#endif
}
/// Ctor.
Stream() : m_byteOrder(LittleEndian) { }
/// Virtual destructor.
virtual ~Stream() {}
/// Set byte order.
void setByteOrder(ByteOrder bo) { m_byteOrder = bo; }
/// Get byte order.
ByteOrder byteOrder() const { return m_byteOrder; }
/// Serialize the given data.
virtual uint serialize( void * data, uint len ) = 0;
/// Move to the given position in the archive.
virtual void seek( uint pos ) = 0;
/// Return the current position in the archive.
virtual uint tell() const = 0;
/// Return the current size of the archive.
virtual uint size() const = 0;
/// Determine if there has been any error.
virtual bool isError() const = 0;
/// Clear errors.
virtual void clearError() = 0;
/// Return true if the stream is at the end.
virtual bool isAtEnd() const = 0;
/// Return true if the stream is seekable.
virtual bool isSeekable() const = 0;
/// Return true if this is an input stream.
virtual bool isLoading() const = 0;
/// Return true if this is an output stream.
virtual bool isSaving() const = 0;
void advance(uint offset) { seek(tell() + offset); }
// friends
friend Stream & operator<<( Stream & s, bool & c ) {
#if NV_OS_DARWIN && !NV_CC_CPP11
nvStaticCheck(sizeof(bool) == 4);
uint8 b = c ? 1 : 0;
s.serialize( &b, 1 );
c = (b != 0);
#else
nvStaticCheck(sizeof(bool) == 1);
s.serialize( &c, 1 );
#endif
return s;
}
friend Stream & operator<<( Stream & s, char & c ) {
nvStaticCheck(sizeof(char) == 1);
s.serialize( &c, 1 );
return s;
}
friend Stream & operator<<( Stream & s, uint8 & c ) {
nvStaticCheck(sizeof(uint8) == 1);
s.serialize( &c, 1 );
return s;
}
friend Stream & operator<<( Stream & s, int8 & c ) {
nvStaticCheck(sizeof(int8) == 1);
s.serialize( &c, 1 );
return s;
}
friend Stream & operator<<( Stream & s, uint16 & c ) {
nvStaticCheck(sizeof(uint16) == 2);
return s.byteOrderSerialize( &c, 2 );
}
friend Stream & operator<<( Stream & s, int16 & c ) {
nvStaticCheck(sizeof(int16) == 2);
return s.byteOrderSerialize( &c, 2 );
}
friend Stream & operator<<( Stream & s, uint32 & c ) {
nvStaticCheck(sizeof(uint32) == 4);
return s.byteOrderSerialize( &c, 4 );
}
friend Stream & operator<<( Stream & s, int32 & c ) {
nvStaticCheck(sizeof(int32) == 4);
return s.byteOrderSerialize( &c, 4 );
}
friend Stream & operator<<( Stream & s, uint64 & c ) {
nvStaticCheck(sizeof(uint64) == 8);
return s.byteOrderSerialize( &c, 8 );
}
friend Stream & operator<<( Stream & s, int64 & c ) {
nvStaticCheck(sizeof(int64) == 8);
return s.byteOrderSerialize( &c, 8 );
}
friend Stream & operator<<( Stream & s, float & c ) {
nvStaticCheck(sizeof(float) == 4);
return s.byteOrderSerialize( &c, 4 );
}
friend Stream & operator<<( Stream & s, double & c ) {
nvStaticCheck(sizeof(double) == 8);
return s.byteOrderSerialize( &c, 8 );
}
protected:
/// Serialize in the stream byte order.
Stream & byteOrderSerialize( void * v, uint len ) {
if( m_byteOrder == getSystemByteOrder() ) {
serialize( v, len );
}
else {
for( uint i = len; i > 0; i-- ) {
serialize( (uint8 *)v + i - 1, 1 );
}
}
return *this;
}
private:
ByteOrder m_byteOrder;
};
} // nv namespace
#endif // NV_CORE_STREAM_H

View file

@ -1,315 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_CORE_UTILS_H
#define NV_CORE_UTILS_H
#include "Debug.h" // nvDebugCheck
#include <new> // for placement new
// Just in case. Grrr.
#undef min
#undef max
#define NV_INT8_MIN (-128)
#define NV_INT8_MAX 127
#define NV_UINT8_MAX 255
#define NV_INT16_MIN (-32767-1)
#define NV_INT16_MAX 32767
#define NV_UINT16_MAX 0xffff
#define NV_INT32_MIN (-2147483647-1)
#define NV_INT32_MAX 2147483647
#define NV_UINT32_MAX 0xffffffff
#define NV_INT64_MAX POSH_I64(9223372036854775807)
#define NV_INT64_MIN (-POSH_I64(9223372036854775807)-1)
#define NV_UINT64_MAX POSH_U64(0xffffffffffffffff)
#define NV_HALF_MAX 65504.0F
#define NV_FLOAT_MAX 3.402823466e+38F
#define NV_INTEGER_TO_FLOAT_MAX 16777217 // Largest integer such that it and all smaller integers can be stored in a 32bit float.
namespace nv
{
// Less error prone than casting. From CB:
// http://cbloomrants.blogspot.com/2011/06/06-17-11-c-casting-is-devil.html
// These intentionally look like casts.
// uint64 casts:
template <typename T> inline uint64 U64(T x) { return x; }
//template <> inline uint64 U64<uint64>(uint64 x) { return x; }
template <> inline uint64 U64<int64>(int64 x) { nvDebugCheck(x >= 0); return (uint64)x; }
//template <> inline uint64 U32<uint32>(uint32 x) { return x; }
template <> inline uint64 U64<int32>(int32 x) { nvDebugCheck(x >= 0); return (uint64)x; }
//template <> inline uint64 U64<uint16>(uint16 x) { return x; }
template <> inline uint64 U64<int16>(int16 x) { nvDebugCheck(x >= 0); return (uint64)x; }
//template <> inline uint64 U64<uint8>(uint8 x) { return x; }
template <> inline uint64 U64<int8>(int8 x) { nvDebugCheck(x >= 0); return (uint64)x; }
// int64 casts:
template <typename T> inline int64 I64(T x) { return x; }
template <> inline int64 I64<uint64>(uint64 x) { nvDebugCheck(x <= NV_INT64_MAX); return (int64)x; }
//template <> inline uint64 U64<int64>(int64 x) { return x; }
//template <> inline uint64 U32<uint32>(uint32 x) { return x; }
//template <> inline uint64 U64<int32>(int32 x) { return x; }
//template <> inline uint64 U64<uint16>(uint16 x) { return x; }
//template <> inline uint64 U64<int16>(int16 x) { return x; }
//template <> inline uint64 U64<uint8>(uint8 x) { return x; }
//template <> inline uint64 U64<int8>(int8 x) { return x; }
// uint32 casts:
template <typename T> inline uint32 U32(T x) { return x; }
template <> inline uint32 U32<uint64>(uint64 x) { nvDebugCheck(x <= NV_UINT32_MAX); return (uint32)x; }
template <> inline uint32 U32<int64>(int64 x) { nvDebugCheck(x >= 0 && x <= NV_UINT32_MAX); return (uint32)x; }
//template <> inline uint32 U32<uint32>(uint32 x) { return x; }
template <> inline uint32 U32<int32>(int32 x) { nvDebugCheck(x >= 0); return (uint32)x; }
//template <> inline uint32 U32<uint16>(uint16 x) { return x; }
template <> inline uint32 U32<int16>(int16 x) { nvDebugCheck(x >= 0); return (uint32)x; }
//template <> inline uint32 U32<uint8>(uint8 x) { return x; }
template <> inline uint32 U32<int8>(int8 x) { nvDebugCheck(x >= 0); return (uint32)x; }
// int32 casts:
template <typename T> inline int32 I32(T x) { return x; }
template <> inline int32 I32<uint64>(uint64 x) { nvDebugCheck(x <= NV_INT32_MAX); return (int32)x; }
template <> inline int32 I32<int64>(int64 x) { nvDebugCheck(x >= NV_INT32_MIN && x <= NV_UINT32_MAX); return (int32)x; }
template <> inline int32 I32<uint32>(uint32 x) { nvDebugCheck(x <= NV_INT32_MAX); return (int32)x; }
//template <> inline int32 I32<int32>(int32 x) { return x; }
//template <> inline int32 I32<uint16>(uint16 x) { return x; }
//template <> inline int32 I32<int16>(int16 x) { return x; }
//template <> inline int32 I32<uint8>(uint8 x) { return x; }
//template <> inline int32 I32<int8>(int8 x) { return x; }
// uint16 casts:
template <typename T> inline uint16 U16(T x) { return x; }
template <> inline uint16 U16<uint64>(uint64 x) { nvDebugCheck(x <= NV_UINT16_MAX); return (uint16)x; }
template <> inline uint16 U16<int64>(int64 x) { nvDebugCheck(x >= 0 && x <= NV_UINT16_MAX); return (uint16)x; }
template <> inline uint16 U16<uint32>(uint32 x) { nvDebugCheck(x <= NV_UINT16_MAX); return (uint16)x; }
template <> inline uint16 U16<int32>(int32 x) { nvDebugCheck(x >= 0 && x <= NV_UINT16_MAX); return (uint16)x; }
//template <> inline uint16 U16<uint16>(uint16 x) { return x; }
template <> inline uint16 U16<int16>(int16 x) { nvDebugCheck(x >= 0); return (uint16)x; }
//template <> inline uint16 U16<uint8>(uint8 x) { return x; }
template <> inline uint16 U16<int8>(int8 x) { nvDebugCheck(x >= 0); return (uint16)x; }
// int16 casts:
template <typename T> inline int16 I16(T x) { return x; }
template <> inline int16 I16<uint64>(uint64 x) { nvDebugCheck(x <= NV_INT16_MAX); return (int16)x; }
template <> inline int16 I16<int64>(int64 x) { nvDebugCheck(x >= NV_INT16_MIN && x <= NV_UINT16_MAX); return (int16)x; }
template <> inline int16 I16<uint32>(uint32 x) { nvDebugCheck(x <= NV_INT16_MAX); return (int16)x; }
template <> inline int16 I16<int32>(int32 x) { nvDebugCheck(x >= NV_INT16_MIN && x <= NV_UINT16_MAX); return (int16)x; }
template <> inline int16 I16<uint16>(uint16 x) { nvDebugCheck(x <= NV_INT16_MAX); return (int16)x; }
//template <> inline int16 I16<int16>(int16 x) { return x; }
//template <> inline int16 I16<uint8>(uint8 x) { return x; }
//template <> inline int16 I16<int8>(int8 x) { return x; }
// uint8 casts:
template <typename T> inline uint8 U8(T x) { return x; }
template <> inline uint8 U8<uint64>(uint64 x) { nvDebugCheck(x <= NV_UINT8_MAX); return (uint8)x; }
template <> inline uint8 U8<int64>(int64 x) { nvDebugCheck(x >= 0 && x <= NV_UINT8_MAX); return (uint8)x; }
template <> inline uint8 U8<uint32>(uint32 x) { nvDebugCheck(x <= NV_UINT8_MAX); return (uint8)x; }
template <> inline uint8 U8<int32>(int32 x) { nvDebugCheck(x >= 0 && x <= NV_UINT8_MAX); return (uint8)x; }
template <> inline uint8 U8<uint16>(uint16 x) { nvDebugCheck(x <= NV_UINT8_MAX); return (uint8)x; }
template <> inline uint8 U8<int16>(int16 x) { nvDebugCheck(x >= 0 && x <= NV_UINT8_MAX); return (uint8)x; }
//template <> inline uint8 U8<uint8>(uint8 x) { return x; }
template <> inline uint8 U8<int8>(int8 x) { nvDebugCheck(x >= 0); return (uint8)x; }
//template <> inline uint8 U8<float>(int8 x) { nvDebugCheck(x >= 0.0f && x <= 255.0f); return (uint8)x; }
// int8 casts:
template <typename T> inline int8 I8(T x) { return x; }
template <> inline int8 I8<uint64>(uint64 x) { nvDebugCheck(x <= NV_INT8_MAX); return (int8)x; }
template <> inline int8 I8<int64>(int64 x) { nvDebugCheck(x >= NV_INT8_MIN && x <= NV_UINT8_MAX); return (int8)x; }
template <> inline int8 I8<uint32>(uint32 x) { nvDebugCheck(x <= NV_INT8_MAX); return (int8)x; }
template <> inline int8 I8<int32>(int32 x) { nvDebugCheck(x >= NV_INT8_MIN && x <= NV_UINT8_MAX); return (int8)x; }
template <> inline int8 I8<uint16>(uint16 x) { nvDebugCheck(x <= NV_INT8_MAX); return (int8)x; }
template <> inline int8 I8<int16>(int16 x) { nvDebugCheck(x >= NV_INT8_MIN && x <= NV_UINT8_MAX); return (int8)x; }
template <> inline int8 I8<uint8>(uint8 x) { nvDebugCheck(x <= NV_INT8_MAX); return (int8)x; }
//template <> inline int8 I8<int8>(int8 x) { return x; }
// float casts:
template <typename T> inline float F32(T x) { return x; }
template <> inline float F32<uint64>(uint64 x) { nvDebugCheck(x <= NV_INTEGER_TO_FLOAT_MAX); return (float)x; }
template <> inline float F32<int64>(int64 x) { nvDebugCheck(x >= -NV_INTEGER_TO_FLOAT_MAX && x <= NV_INTEGER_TO_FLOAT_MAX); return (float)x; }
template <> inline float F32<uint32>(uint32 x) { nvDebugCheck(x <= NV_INTEGER_TO_FLOAT_MAX); return (float)x; }
template <> inline float F32<int32>(int32 x) { nvDebugCheck(x >= -NV_INTEGER_TO_FLOAT_MAX && x <= NV_INTEGER_TO_FLOAT_MAX); return (float)x; }
// The compiler should not complain about these conversions:
//template <> inline float F32<uint16>(uint16 x) { nvDebugCheck(return (float)x; }
//template <> inline float F32<int16>(int16 x) { nvDebugCheck(return (float)x; }
//template <> inline float F32<uint8>(uint8 x) { nvDebugCheck(return (float)x; }
//template <> inline float F32<int8>(int8 x) { nvDebugCheck(return (float)x; }
/// Swap two values.
template <typename T>
inline void swap(T & a, T & b)
{
T temp(a);
a = b;
b = temp;
}
/// Return the maximum of the two arguments. For floating point values, it returns the second value if the first is NaN.
template <typename T>
//inline const T & max(const T & a, const T & b)
inline T max(const T & a, const T & b)
{
return (b < a) ? a : b;
}
/// Return the maximum of the four arguments.
template <typename T>
//inline const T & max4(const T & a, const T & b, const T & c)
inline T max4(const T & a, const T & b, const T & c, const T & d)
{
return max(max(a, b), max(c, d));
}
/// Return the maximum of the three arguments.
template <typename T>
//inline const T & max3(const T & a, const T & b, const T & c)
inline T max3(const T & a, const T & b, const T & c)
{
return max(a, max(b, c));
}
/// Return the minimum of two values.
template <typename T>
//inline const T & min(const T & a, const T & b)
inline T min(const T & a, const T & b)
{
return (a < b) ? a : b;
}
/// Return the maximum of the three arguments.
template <typename T>
//inline const T & min3(const T & a, const T & b, const T & c)
inline T min3(const T & a, const T & b, const T & c)
{
return min(a, min(b, c));
}
/// Clamp between two values.
template <typename T>
//inline const T & clamp(const T & x, const T & a, const T & b)
inline T clamp(const T & x, const T & a, const T & b)
{
return min(max(x, a), b);
}
/** Return the next power of two.
* @see http://graphics.stanford.edu/~seander/bithacks.html
* @warning Behaviour for 0 is undefined.
* @note isPowerOfTwo(x) == true -> nextPowerOfTwo(x) == x
* @note nextPowerOfTwo(x) = 2 << log2(x-1)
*/
inline uint32 nextPowerOfTwo(uint32 x)
{
nvDebugCheck( x != 0 );
#if 1 // On modern CPUs this is supposed to be as fast as using the bsr instruction.
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x+1;
#else
uint p = 1;
while( x > p ) {
p += p;
}
return p;
#endif
}
inline uint64 nextPowerOfTwo(uint64 x)
{
nvDebugCheck(x != 0);
uint p = 1;
while (x > p) {
p += p;
}
return p;
}
// @@ Should I just use a macro instead?
template <typename T>
inline bool isPowerOfTwo(T n)
{
return (n & (n-1)) == 0;
}
// @@ Move this to utils?
/// Delete all the elements of a container.
template <typename T>
void deleteAll(T & container)
{
for (typename T::PseudoIndex i = container.start(); !container.isDone(i); container.advance(i))
{
delete container[i];
}
}
// @@ Specialize these methods for numeric, pointer, and pod types.
template <typename T>
void construct_range(T * restrict ptr, uint new_size, uint old_size) {
for (uint i = old_size; i < new_size; i++) {
new(ptr+i) T; // placement new
}
}
template <typename T>
void construct_range(T * restrict ptr, uint new_size, uint old_size, const T & elem) {
for (uint i = old_size; i < new_size; i++) {
new(ptr+i) T(elem); // placement new
}
}
template <typename T>
void construct_range(T * restrict ptr, uint new_size, uint old_size, const T * src) {
for (uint i = old_size; i < new_size; i++) {
new(ptr+i) T(src[i]); // placement new
}
}
template <typename T>
void destroy_range(T * restrict ptr, uint new_size, uint old_size) {
for (uint i = new_size; i < old_size; i++) {
(ptr+i)->~T(); // Explicit call to the destructor
}
}
template <typename T>
void fill(T * restrict dst, uint count, const T & value) {
for (uint i = 0; i < count; i++) {
dst[i] = value;
}
}
template <typename T>
void copy_range(T * restrict dst, const T * restrict src, uint count) {
for (uint i = 0; i < count; i++) {
dst[i] = src[i];
}
}
template <typename T>
bool find(const T & element, const T * restrict ptr, uint begin, uint end, uint * index) {
for (uint i = begin; i < end; i++) {
if (ptr[i] == element) {
if (index != NULL) *index = i;
return true;
}
}
return false;
}
} // nv namespace
#endif // NV_CORE_UTILS_H

View file

@ -1,360 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_CORE_H
#define NV_CORE_H
// Function linkage
#if NVCORE_SHARED
#ifdef NVCORE_EXPORTS
#define NVCORE_API DLL_EXPORT
#define NVCORE_CLASS DLL_EXPORT_CLASS
#else
#define NVCORE_API DLL_IMPORT
#define NVCORE_CLASS DLL_IMPORT
#endif
#else // NVCORE_SHARED
#define NVCORE_API
#define NVCORE_CLASS
#endif // NVCORE_SHARED
// Platform definitions
#include <posh.h>
// OS:
// NV_OS_WIN32
// NV_OS_WIN64
// NV_OS_MINGW
// NV_OS_CYGWIN
// NV_OS_LINUX
// NV_OS_UNIX
// NV_OS_DARWIN
// NV_OS_XBOX
// NV_OS_ORBIS
// NV_OS_IOS
#define NV_OS_STRING POSH_OS_STRING
#if defined POSH_OS_LINUX
# define NV_OS_LINUX 1
# define NV_OS_UNIX 1
#elif defined POSH_OS_ORBIS
# define NV_OS_ORBIS 1
#elif defined POSH_OS_FREEBSD
# define NV_OS_FREEBSD 1
# define NV_OS_UNIX 1
#elif defined POSH_OS_HAIKU
# define NV_OS_HAIKU 1
# define NV_OS_UNIX 1
#elif defined POSH_OS_OPENBSD
# define NV_OS_OPENBSD 1
# define NV_OS_UNIX 1
#elif defined POSH_OS_CYGWIN32
# define NV_OS_CYGWIN 1
#elif defined POSH_OS_MINGW
# define NV_OS_MINGW 1
# define NV_OS_WIN32 1
#elif defined POSH_OS_OSX
# define NV_OS_OSX 1 // IC: Adding this, because iOS defines NV_OS_DARWIN too.
# define NV_OS_DARWIN 1
# define NV_OS_UNIX 1
#elif defined POSH_OS_IOS
# define NV_OS_DARWIN 1 //ACS should we keep this on IOS?
# define NV_OS_UNIX 1
# define NV_OS_IOS 1
#elif defined POSH_OS_UNIX
# define NV_OS_UNIX 1
#elif defined POSH_OS_WIN64
# define NV_OS_WIN32 1
# define NV_OS_WIN64 1
#elif defined POSH_OS_WIN32
# define NV_OS_WIN32 1
#elif defined POSH_OS_XBOX
# define NV_OS_XBOX 1
#elif defined POSH_OS_DURANGO
# define NV_OS_DURANGO 1
#else
# error "Unsupported OS"
#endif
// Is this a console OS? (i.e. connected to a TV)
#if NV_OS_ORBIS || NV_OS_XBOX || NV_OS_DURANGO
# define NV_OS_CONSOLE 1
#endif
// Threading:
// some platforms don't implement __thread or similar for thread-local-storage
#if NV_OS_UNIX || NV_OS_ORBIS || NV_OS_IOS //ACStodoIOS darwin instead of ios?
# define NV_OS_USE_PTHREAD 1
# if NV_OS_IOS
# define NV_OS_HAS_TLS_QUALIFIER 0
# else
# define NV_OS_HAS_TLS_QUALIFIER 1
# endif
#else
# define NV_OS_USE_PTHREAD 0
# define NV_OS_HAS_TLS_QUALIFIER 1
#endif
// CPUs:
// NV_CPU_X86
// NV_CPU_X86_64
// NV_CPU_PPC
// NV_CPU_ARM
#define NV_CPU_STRING POSH_CPU_STRING
#if defined POSH_CPU_X86_64
//# define NV_CPU_X86 1
# define NV_CPU_X86_64 1
#elif defined POSH_CPU_X86
# define NV_CPU_X86 1
#elif defined POSH_CPU_PPC
# define NV_CPU_PPC 1
#elif defined POSH_CPU_STRONGARM
# define NV_CPU_ARM 1
#else
# error "Unsupported CPU"
#endif
// Compiler:
// NV_CC_GNUC
// NV_CC_MSVC
// NV_CC_CLANG
#if defined POSH_COMPILER_CLANG
# define NV_CC_CLANG 1
# define NV_CC_GNUC 1 // Clang is compatible with GCC.
# define NV_CC_STRING "clang"
#elif defined POSH_COMPILER_GCC
# define NV_CC_GNUC 1
# define NV_CC_STRING "gcc"
#elif defined POSH_COMPILER_MSVC
# define NV_CC_MSVC 1
# define NV_CC_STRING "msvc"
#else
# error "Unsupported compiler"
#endif
#if NV_CC_MSVC
#define NV_CC_CPP11 (__cplusplus > 199711L || _MSC_VER >= 1800) // Visual Studio 2013 has all the features we use, but doesn't advertise full C++11 support yet.
#else
// @@ IC: This works in CLANG, about GCC?
// @@ ES: Doesn't work in gcc. These 3 features are available in GCC >= 4.4.
#ifdef __clang__
#define NV_CC_CPP11 (__has_feature(cxx_deleted_functions) && __has_feature(cxx_rvalue_references) && __has_feature(cxx_static_assert))
#elif defined __GNUC__
#define NV_CC_CPP11 ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
#endif
#endif
// Endiannes:
#define NV_LITTLE_ENDIAN POSH_LITTLE_ENDIAN
#define NV_BIG_ENDIAN POSH_BIG_ENDIAN
#define NV_ENDIAN_STRING POSH_ENDIAN_STRING
// Define the right printf prefix for size_t arguments:
#if POSH_64BIT_POINTER
# define NV_SIZET_PRINTF_PREFIX POSH_I64_PRINTF_PREFIX
#else
# define NV_SIZET_PRINTF_PREFIX
#endif
// cmake config
#include "nvconfig.h"
#if NV_OS_DARWIN
#include <stdint.h>
//#include <inttypes.h>
// Type definitions:
typedef uint8_t uint8;
typedef int8_t int8;
typedef uint16_t uint16;
typedef int16_t int16;
typedef uint32_t uint32;
typedef int32_t int32;
typedef uint64_t uint64;
typedef int64_t int64;
// POSH gets this wrong due to __LP64__
#undef POSH_I64_PRINTF_PREFIX
#define POSH_I64_PRINTF_PREFIX "ll"
#else
// Type definitions:
typedef posh_u8_t uint8;
typedef posh_i8_t int8;
typedef posh_u16_t uint16;
typedef posh_i16_t int16;
typedef posh_u32_t uint32;
typedef posh_i32_t int32;
//#if NV_OS_DARWIN
// OSX-64 is supposed to be LP64 (longs and pointers are 64 bits), thus uint64 is defined as
// unsigned long. However, some OSX headers define it as unsigned long long, producing errors,
// even though both types are 64 bit. Ideally posh should handle that, but it has not been
// updated in ages, so here I'm just falling back to the standard C99 types defined in inttypes.h
//#include <inttypes.h>
//typedef posh_u64_t uint64_t;
//typedef posh_i64_t int64_t;
//#else
typedef posh_u64_t uint64;
typedef posh_i64_t int64;
//#endif
#if NV_OS_DARWIN
// To avoid duplicate definitions.
#define _UINT64
#endif
#endif
// Aliases
typedef uint32 uint;
// Version string:
#define NV_VERSION_STRING \
NV_OS_STRING "/" NV_CC_STRING "/" NV_CPU_STRING"/" \
NV_ENDIAN_STRING"-endian - " __DATE__ "-" __TIME__
// Disable copy constructor and assignment operator.
#if NV_CC_CPP11
#define NV_FORBID_COPY(C) \
C( const C & ) = delete; \
C &operator=( const C & ) = delete
#else
#define NV_FORBID_COPY(C) \
private: \
C( const C & ); \
C &operator=( const C & )
#endif
// Disable dynamic allocation on the heap.
// See Prohibiting Heap-Based Objects in More Effective C++.
#define NV_FORBID_HEAPALLOC() \
private: \
void *operator new(size_t size); \
void *operator new[](size_t size)
//static void *operator new(size_t size); \
//static void *operator new[](size_t size);
// String concatenation macros.
#define NV_STRING_JOIN2(arg1, arg2) NV_DO_STRING_JOIN2(arg1, arg2)
#define NV_DO_STRING_JOIN2(arg1, arg2) arg1 ## arg2
#define NV_STRING_JOIN3(arg1, arg2, arg3) NV_DO_STRING_JOIN3(arg1, arg2, arg3)
#define NV_DO_STRING_JOIN3(arg1, arg2, arg3) arg1 ## arg2 ## arg3
#define NV_STRING2(x) #x
#define NV_STRING(x) NV_STRING2(x)
#if NV_CC_MSVC
#define NV_MULTI_LINE_MACRO_BEGIN do {
#define NV_MULTI_LINE_MACRO_END \
__pragma(warning(push)) \
__pragma(warning(disable:4127)) \
} while(false) \
__pragma(warning(pop))
#else
#define NV_MULTI_LINE_MACRO_BEGIN do {
#define NV_MULTI_LINE_MACRO_END } while(false)
#endif
#if NV_CC_CPP11
#define nvStaticCheck(x) static_assert((x), "Static assert "#x" failed")
#else
#define nvStaticCheck(x) typedef char NV_STRING_JOIN2(__static_assert_,__LINE__)[(x)]
#endif
#define NV_COMPILER_CHECK(x) nvStaticCheck(x) // I like this name best.
// Make sure type definitions are fine.
NV_COMPILER_CHECK(sizeof(int8) == 1);
NV_COMPILER_CHECK(sizeof(uint8) == 1);
NV_COMPILER_CHECK(sizeof(int16) == 2);
NV_COMPILER_CHECK(sizeof(uint16) == 2);
NV_COMPILER_CHECK(sizeof(int32) == 4);
NV_COMPILER_CHECK(sizeof(uint32) == 4);
NV_COMPILER_CHECK(sizeof(int32) == 4);
NV_COMPILER_CHECK(sizeof(uint32) == 4);
#include <stddef.h> // for size_t
template <typename T, size_t N> char (&ArraySizeHelper(T (&array)[N]))[N];
#define NV_ARRAY_SIZE(x) sizeof(ArraySizeHelper(x))
//#define NV_ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))
#if 0 // Disabled in The Witness.
#if NV_CC_MSVC
#define NV_MESSAGE(x) message(__FILE__ "(" NV_STRING(__LINE__) ") : " x)
#else
#define NV_MESSAGE(x) message(x)
#endif
#else
#define NV_MESSAGE(x)
#endif
// Startup initialization macro.
#define NV_AT_STARTUP(some_code) \
namespace { \
static struct NV_STRING_JOIN2(AtStartup_, __LINE__) { \
NV_STRING_JOIN2(AtStartup_, __LINE__)() { some_code; } \
} \
NV_STRING_JOIN3(AtStartup_, __LINE__, Instance); \
}
// Indicate the compiler that the parameter is not used to suppress compier warnings.
#if NV_CC_MSVC
#define NV_UNUSED(a) ((a)=(a))
#else
#define NV_UNUSED(a) _Pragma(NV_STRING(unused(a)))
#endif
// Null index. @@ Move this somewhere else... it's only used by nvmesh.
//const unsigned int NIL = unsigned int(~0);
#define NIL uint(~0)
// Null pointer.
#ifndef NULL
#define NULL 0
#endif
// Platform includes
#if NV_CC_MSVC
# if NV_OS_WIN32
# include "DefsVcWin32.h"
# elif NV_OS_XBOX
# include "DefsVcXBox.h"
# elif NV_OS_DURANGO
# include "DefsVcDurango.h"
# else
# error "MSVC: Platform not supported"
# endif
#elif NV_CC_GNUC
# if NV_OS_LINUX
# include "DefsGnucLinux.h"
# elif NV_OS_DARWIN || NV_OS_FREEBSD || NV_OS_OPENBSD || NV_OS_HAIKU
# include "DefsGnucDarwin.h"
# elif NV_OS_ORBIS
# include "DefsOrbis.h"
# elif NV_OS_MINGW
# include "DefsGnucWin32.h"
# elif NV_OS_CYGWIN
# error "GCC: Cygwin not supported"
# else
# error "GCC: Platform not supported"
# endif
#endif
#endif // NV_CORE_H

View file

@ -1,641 +0,0 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Chris Torek.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* From: Id: vfscanf.c,v 1.13 1998/09/25 12:20:27 obrien Exp
* From: static char sccsid[] = "@(#)strtol.c 8.1 (Berkeley) 6/4/93";
* From: static char sccsid[] = "@(#)strtoul.c 8.1 (Berkeley) 6/4/93";
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
#pragma warning(disable : 4244) // conversion from '*' to '*', possible loss of data
#pragma warning(disable : 4018) // signed/unsigned mismatch
#pragma warning(disable : 4267) // '=' : conversion from 'size_t' to 'int', possible loss of data
#define strtoq _strtoi64
#define strtouq _strtoui64
#define bcopy(b1,b2,len) (memmove((b2), (b1), (len)), (void) 0)
typedef int long long quad_t;
typedef unsigned long long u_quad_t;
typedef unsigned char u_char;
#define BUF 32 /* Maximum length of numeric string. */
/*
* Flags used during conversion.
*/
#define LONG 0x01 /* l: long or double */
#define SHORT 0x04 /* h: short */
#define SUPPRESS 0x08 /* suppress assignment */
#define POINTER 0x10 /* weird %p pointer (`fake hex') */
#define NOSKIP 0x20 /* do not skip blanks */
#define QUAD 0x400
/*
* The following are used in numeric conversions only:
* SIGNOK, NDIGITS, DPTOK, and EXPOK are for floating point;
* SIGNOK, NDIGITS, PFXOK, and NZDIGITS are for integral.
*/
#define SIGNOK 0x40 /* +/- is (still) legal */
#define NDIGITS 0x80 /* no digits detected */
#define DPTOK 0x100 /* (float) decimal point is still legal */
#define EXPOK 0x200 /* (float) exponent (e+3, etc) still legal */
#define PFXOK 0x100 /* 0x prefix is (still) legal */
#define NZDIGITS 0x200 /* no zero digits detected */
/*
* Conversion types.
*/
#define CT_CHAR 0 /* %c conversion */
#define CT_CCL 1 /* %[...] conversion */
#define CT_STRING 2 /* %s conversion */
#define CT_INT 3 /* integer, i.e., strtoq or strtouq */
typedef u_quad_t (*ccfntype)(const char *, char **, int);
static const u_char *__sccl(char *, const u_char *);
int
vsscanf(const char *inp, char const *fmt0, va_list ap)
{
int inr;
const u_char *fmt = (const u_char *)fmt0;
int c; /* character from format, or conversion */
size_t width; /* field width, or 0 */
char *p; /* points into all kinds of strings */
int n; /* handy integer */
int flags; /* flags as defined above */
char *p0; /* saves original value of p when necessary */
int nassigned; /* number of fields assigned */
int nconversions; /* number of conversions */
int nread; /* number of characters consumed from fp */
int base; /* base argument to strtoq/strtouq */
ccfntype ccfn; /* conversion function (strtoq/strtouq) */
char ccltab[256]; /* character class table for %[...] */
char buf[BUF]; /* buffer for numeric conversions */
/* `basefix' is used to avoid `if' tests in the integer scanner */
static short basefix[17] =
{ 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
inr = strlen(inp);
nassigned = 0;
nconversions = 0;
nread = 0;
base = 0; /* XXX just to keep gcc happy */
ccfn = NULL; /* XXX just to keep gcc happy */
for (;;) {
c = *fmt++;
if (c == 0)
return (nassigned);
if (isspace(c)) {
while (inr > 0 && isspace(*inp))
nread++, inr--, inp++;
continue;
}
if (c != '%')
goto literal;
width = 0;
flags = 0;
/*
* switch on the format. continue if done;
* break once format type is derived.
*/
again: c = *fmt++;
switch (c) {
case '%':
literal:
if (inr <= 0)
goto input_failure;
if (*inp != c)
goto match_failure;
inr--, inp++;
nread++;
continue;
case '*':
flags |= SUPPRESS;
goto again;
case 'l':
flags |= LONG;
goto again;
case 'q':
flags |= QUAD;
goto again;
case 'h':
flags |= SHORT;
goto again;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
width = width * 10 + c - '0';
goto again;
/*
* Conversions.
*
*/
case 'd':
c = CT_INT;
ccfn = (ccfntype)strtoq;
base = 10;
break;
case 'i':
c = CT_INT;
ccfn = (ccfntype)strtoq;
base = 0;
break;
case 'o':
c = CT_INT;
ccfn = strtouq;
base = 8;
break;
case 'u':
c = CT_INT;
ccfn = strtouq;
base = 10;
break;
case 'x':
flags |= PFXOK; /* enable 0x prefixing */
c = CT_INT;
ccfn = strtouq;
base = 16;
break;
case 's':
c = CT_STRING;
break;
case '[':
fmt = __sccl(ccltab, fmt);
flags |= NOSKIP;
c = CT_CCL;
break;
case 'c':
flags |= NOSKIP;
c = CT_CHAR;
break;
case 'p': /* pointer format is like hex */
flags |= POINTER | PFXOK;
c = CT_INT;
ccfn = strtouq;
base = 16;
break;
case 'n':
nconversions++;
if (flags & SUPPRESS) /* ??? */
continue;
if (flags & SHORT)
*va_arg(ap, short *) = nread;
else if (flags & LONG)
*va_arg(ap, long *) = nread;
else if (flags & QUAD)
*va_arg(ap, quad_t *) = nread;
else
*va_arg(ap, int *) = nread;
continue;
}
/*
* We have a conversion that requires input.
*/
if (inr <= 0)
goto input_failure;
/*
* Consume leading white space, except for formats
* that suppress this.
*/
if ((flags & NOSKIP) == 0) {
while (isspace(*inp)) {
nread++;
if (--inr > 0)
inp++;
else
goto input_failure;
}
/*
* Note that there is at least one character in
* the buffer, so conversions that do not set NOSKIP
* can no longer result in an input failure.
*/
}
/*
* Do the conversion.
*/
switch (c) {
case CT_CHAR:
/* scan arbitrary characters (sets NOSKIP) */
if (width == 0)
width = 1;
if (flags & SUPPRESS) {
size_t sum = 0;
for (;;) {
if ((n = inr) < width) {
sum += n;
width -= n;
inp += n;
if (sum == 0)
goto input_failure;
break;
} else {
sum += width;
inr -= width;
inp += width;
break;
}
}
nread += sum;
} else {
bcopy(inp, va_arg(ap, char *), width);
inr -= width;
inp += width;
nread += width;
nassigned++;
}
nconversions++;
break;
case CT_CCL:
/* scan a (nonempty) character class (sets NOSKIP) */
if (width == 0)
width = (size_t)~0; /* `infinity' */
/* take only those things in the class */
if (flags & SUPPRESS) {
n = 0;
while (ccltab[(unsigned char)*inp]) {
n++, inr--, inp++;
if (--width == 0)
break;
if (inr <= 0) {
if (n == 0)
goto input_failure;
break;
}
}
if (n == 0)
goto match_failure;
} else {
p0 = p = va_arg(ap, char *);
while (ccltab[(unsigned char)*inp]) {
inr--;
*p++ = *inp++;
if (--width == 0)
break;
if (inr <= 0) {
if (p == p0)
goto input_failure;
break;
}
}
n = p - p0;
if (n == 0)
goto match_failure;
*p = 0;
nassigned++;
}
nread += n;
nconversions++;
break;
case CT_STRING:
/* like CCL, but zero-length string OK, & no NOSKIP */
if (width == 0)
width = (size_t)~0;
if (flags & SUPPRESS) {
n = 0;
while (!isspace(*inp)) {
n++, inr--, inp++;
if (--width == 0)
break;
if (inr <= 0)
break;
}
nread += n;
} else {
p0 = p = va_arg(ap, char *);
while (!isspace(*inp)) {
inr--;
*p++ = *inp++;
if (--width == 0)
break;
if (inr <= 0)
break;
}
*p = 0;
nread += p - p0;
nassigned++;
}
nconversions++;
continue;
case CT_INT:
/* scan an integer as if by strtoq/strtouq */
#ifdef hardway
if (width == 0 || width > sizeof(buf) - 1)
width = sizeof(buf) - 1;
#else
/* size_t is unsigned, hence this optimisation */
if (--width > sizeof(buf) - 2)
width = sizeof(buf) - 2;
width++;
#endif
flags |= SIGNOK | NDIGITS | NZDIGITS;
for (p = buf; width; width--) {
c = *inp;
/*
* Switch on the character; `goto ok'
* if we accept it as a part of number.
*/
switch (c) {
/*
* The digit 0 is always legal, but is
* special. For %i conversions, if no
* digits (zero or nonzero) have been
* scanned (only signs), we will have
* base==0. In that case, we should set
* it to 8 and enable 0x prefixing.
* Also, if we have not scanned zero digits
* before this, do not turn off prefixing
* (someone else will turn it off if we
* have scanned any nonzero digits).
*/
case '0':
if (base == 0) {
base = 8;
flags |= PFXOK;
}
if (flags & NZDIGITS)
flags &= ~(SIGNOK|NZDIGITS|NDIGITS);
else
flags &= ~(SIGNOK|PFXOK|NDIGITS);
goto ok;
/* 1 through 7 always legal */
case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
base = basefix[base];
flags &= ~(SIGNOK | PFXOK | NDIGITS);
goto ok;
/* digits 8 and 9 ok iff decimal or hex */
case '8': case '9':
base = basefix[base];
if (base <= 8)
break; /* not legal here */
flags &= ~(SIGNOK | PFXOK | NDIGITS);
goto ok;
/* letters ok iff hex */
case 'A': case 'B': case 'C':
case 'D': case 'E': case 'F':
case 'a': case 'b': case 'c':
case 'd': case 'e': case 'f':
/* no need to fix base here */
if (base <= 10)
break; /* not legal here */
flags &= ~(SIGNOK | PFXOK | NDIGITS);
goto ok;
/* sign ok only as first character */
case '+': case '-':
if (flags & SIGNOK) {
flags &= ~SIGNOK;
goto ok;
}
break;
/* x ok iff flag still set & 2nd char */
case 'x': case 'X':
if (flags & PFXOK && p == buf + 1) {
base = 16; /* if %i */
flags &= ~PFXOK;
goto ok;
}
break;
}
/*
* If we got here, c is not a legal character
* for a number. Stop accumulating digits.
*/
break;
ok:
/*
* c is legal: store it and look at the next.
*/
*p++ = c;
if (--inr > 0)
inp++;
else
break; /* end of input */
}
/*
* If we had only a sign, it is no good; push
* back the sign. If the number ends in `x',
* it was [sign] '0' 'x', so push back the x
* and treat it as [sign] '0'.
*/
if (flags & NDIGITS) {
if (p > buf) {
inp--;
inr++;
}
goto match_failure;
}
c = ((u_char *)p)[-1];
if (c == 'x' || c == 'X') {
--p;
inp--;
inr++;
}
if ((flags & SUPPRESS) == 0) {
u_quad_t res;
*p = 0;
res = (*ccfn)(buf, (char **)NULL, base);
if (flags & POINTER)
*va_arg(ap, void **) =
(void *)(uintptr_t)res;
else if (flags & SHORT)
*va_arg(ap, short *) = res;
else if (flags & LONG)
*va_arg(ap, long *) = res;
else if (flags & QUAD)
*va_arg(ap, quad_t *) = res;
else
*va_arg(ap, int *) = res;
nassigned++;
}
nread += p - buf;
nconversions++;
break;
}
}
input_failure:
return (nconversions != 0 ? nassigned : -1);
match_failure:
return (nassigned);
}
/*
* Fill in the given table from the scanset at the given format
* (just after `['). Return a pointer to the character past the
* closing `]'. The table has a 1 wherever characters should be
* considered part of the scanset.
*/
static const u_char *
__sccl(char *tab, const u_char *fmt)
{
int c, n, v;
/* first `clear' the whole table */
c = *fmt++; /* first char hat => negated scanset */
if (c == '^') {
v = 1; /* default => accept */
c = *fmt++; /* get new first char */
} else
v = 0; /* default => reject */
/* XXX: Will not work if sizeof(tab*) > sizeof(char) */
for (n = 0; n < 256; n++)
tab[n] = v; /* memset(tab, v, 256) */
if (c == 0)
return (fmt - 1);/* format ended before closing ] */
/*
* Now set the entries corresponding to the actual scanset
* to the opposite of the above.
*
* The first character may be ']' (or '-') without being special;
* the last character may be '-'.
*/
v = 1 - v;
for (;;) {
tab[c] = v; /* take character c */
doswitch:
n = *fmt++; /* and examine the next */
switch (n) {
case 0: /* format ended too soon */
return (fmt - 1);
case '-':
/*
* A scanset of the form
* [01+-]
* is defined as `the digit 0, the digit 1,
* the character +, the character -', but
* the effect of a scanset such as
* [a-zA-Z0-9]
* is implementation defined. The V7 Unix
* scanf treats `a-z' as `the letters a through
* z', but treats `a-a' as `the letter a, the
* character -, and the letter a'.
*
* For compatibility, the `-' is not considerd
* to define a range if the character following
* it is either a close bracket (required by ANSI)
* or is not numerically greater than the character
* we just stored in the table (c).
*/
n = *fmt;
if (n == ']' || n < c) {
c = '-';
break; /* resume the for(;;) */
}
fmt++;
/* fill in the range */
do {
tab[++c] = v;
} while (c < n);
c = n;
/*
* Alas, the V7 Unix scanf also treats formats
* such as [a-c-e] as `the letters a through e'.
* This too is permitted by the standard....
*/
goto doswitch;
break;
case ']': /* end of scanset */
return (fmt);
default: /* just another character */
c = n;
break;
}
}
/* NOTREACHED */
}
/*
int
sscanf(const char *ibuf, const char *fmt, ...)
{
va_list ap;
int ret;
va_start(ap, fmt);
ret = vsscanf(ibuf, fmt, ap);
va_end(ap);
return(ret);
}
*/
#ifdef __cplusplus
}
#endif

View file

@ -1,27 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#include "BitMap.h"
using namespace nv;
void BitMap::resize(uint w, uint h, bool initValue)
{
BitArray tmp(w*h);
if (initValue) tmp.setAll();
else tmp.clearAll();
// @@ Copying one bit at a time. This could be much faster.
for (uint y = 0; y < m_height; y++)
{
for (uint x = 0; x < m_width; x++)
{
//tmp.setBitAt(y*w + x, bitAt(x, y));
if (bitAt(x, y) != initValue) tmp.toggleBitAt(y*w + x);
}
}
swap(m_bitArray, tmp);
m_width = w;
m_height = h;
}

View file

@ -1,87 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_IMAGE_BITMAP_H
#define NV_IMAGE_BITMAP_H
#include "nvimage.h"
#include "nvcore/BitArray.h"
namespace nv
{
/// Bit map. This should probably be called BitImage.
class NVIMAGE_CLASS BitMap
{
public:
BitMap() : m_width(0), m_height(0) {}
BitMap(uint w, uint h) : m_width(w), m_height(h), m_bitArray(w*h) {}
uint width() const { return m_width; }
uint height() const { return m_height; }
void resize(uint w, uint h, bool initValue);
bool bitAt(uint x, uint y) const
{
nvDebugCheck(x < m_width && y < m_height);
return m_bitArray.bitAt(y * m_width + x);
}
bool bitAt(uint idx) const
{
return m_bitArray.bitAt(idx);
}
void setBitAt(uint x, uint y)
{
nvDebugCheck(x < m_width && y < m_height);
m_bitArray.setBitAt(y * m_width + x);
}
void setBitAt(uint idx)
{
m_bitArray.setBitAt(idx);
}
void clearBitAt(uint x, uint y)
{
nvDebugCheck(x < m_width && y < m_height);
m_bitArray.clearBitAt(y * m_width + x);
}
void clearBitAt(uint idx)
{
m_bitArray.clearBitAt(idx);
}
void clearAll()
{
m_bitArray.clearAll();
}
void setAll()
{
m_bitArray.setAll();
}
void toggleAll()
{
m_bitArray.toggleAll();
}
friend void swap(BitMap & a, BitMap & b)
{
nvCheck(a.m_width == b.m_width);
nvCheck(a.m_height == b.m_height);
swap(a.m_bitArray, b.m_bitArray);
}
private:
uint m_width;
uint m_height;
BitArray m_bitArray;
};
} // nv namespace
#endif // NV_IMAGE_BITMAP_H

View file

@ -1,210 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#include "Image.h"
//#include "ImageIO.h"
#include "nvmath/Color.h"
#include "nvcore/Debug.h"
#include "nvcore/Ptr.h"
#include "nvcore/Utils.h" // swap
#include "nvcore/Memory.h" // realloc, free
#include <string.h> // memcpy
using namespace nv;
Image::Image() : m_width(0), m_height(0), m_format(Format_RGB), m_data(NULL)
{
}
Image::Image(const Image & img) : m_data(NULL)
{
allocate(img.m_width, img.m_height, img.m_depth);
m_format = img.m_format;
memcpy(m_data, img.m_data, sizeof(Color32) * m_width * m_height * m_depth);
}
Image::~Image()
{
free();
}
const Image & Image::operator=(const Image & img)
{
allocate(img.m_width, img.m_height, m_depth);
m_format = img.m_format;
memcpy(m_data, img.m_data, sizeof(Color32) * m_width * m_height * m_depth);
return *this;
}
void Image::allocate(uint w, uint h, uint d/*= 1*/)
{
m_width = w;
m_height = h;
m_depth = d;
m_data = realloc<Color32>(m_data, w * h * d);
}
void Image::acquire(Color32 * data, uint w, uint h, uint d/*= 1*/)
{
free();
m_width = w;
m_height = h;
m_depth = d;
m_data = data;
}
void Image::resize(uint w, uint h, uint d/*= 1*/) {
Image img;
img.allocate(w, h, d);
Color32 background(0,0,0,0);
// Copy image.
uint x, y, z;
for(z = 0; z < min(d, m_depth); z++) {
for(y = 0; y < min(h, m_height); y++) {
for(x = 0; x < min(w, m_width); x++) {
img.pixel(x, y, z) = pixel(x, y, z);
}
for(; x < w; x++) {
img.pixel(x, y, z) = background;
}
}
for(; y < h; y++) {
for(x = 0; x < w; x++) {
img.pixel(x, y, z) = background;
}
}
}
for(; z < d; z++) {
for(y = 0; y < h; y++) {
for(x = 0; x < w; x++) {
img.pixel(x, y, z) = background;
}
}
}
swap(m_width, img.m_width);
swap(m_height, img.m_height);
swap(m_depth, img.m_depth);
swap(m_format, img.m_format);
swap(m_data, img.m_data);
}
/*bool Image::load(const char * name)
{
free();
AutoPtr<Image> img(ImageIO::load(name));
if (img == NULL) {
return false;
}
swap(m_width, img->m_width);
swap(m_height, img->m_height);
swap(m_depth, img->m_depth);
swap(m_format, img->m_format);
swap(m_data, img->m_data);
return true;
}*/
void Image::wrap(void * data, uint w, uint h, uint d)
{
free();
m_data = (Color32 *)data;
m_width = w;
m_height = h;
m_depth = d;
}
void Image::unwrap()
{
m_data = NULL;
m_width = 0;
m_height = 0;
m_depth = 0;
}
void Image::free()
{
::free(m_data);
m_data = NULL;
}
uint Image::width() const
{
return m_width;
}
uint Image::height() const
{
return m_height;
}
uint Image::depth() const
{
return m_depth;
}
const Color32 * Image::scanline(uint h) const
{
nvDebugCheck(h < m_height);
return m_data + h * m_width;
}
Color32 * Image::scanline(uint h)
{
nvDebugCheck(h < m_height);
return m_data + h * m_width;
}
const Color32 * Image::pixels() const
{
return m_data;
}
Color32 * Image::pixels()
{
return m_data;
}
const Color32 & Image::pixel(uint idx) const
{
nvDebugCheck(idx < m_width * m_height * m_depth);
return m_data[idx];
}
Color32 & Image::pixel(uint idx)
{
nvDebugCheck(idx < m_width * m_height * m_depth);
return m_data[idx];
}
Image::Format Image::format() const
{
return m_format;
}
void Image::setFormat(Image::Format f)
{
m_format = f;
}
void Image::fill(Color32 c)
{
const uint size = m_width * m_height * m_depth;
for (uint i = 0; i < size; ++i)
{
m_data[i] = c;
}
}

View file

@ -1,89 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_IMAGE_IMAGE_H
#define NV_IMAGE_IMAGE_H
#include "nvimage.h"
#include "nvcore/Debug.h"
namespace nv
{
class Color32;
/// 32 bit RGBA image.
class NVIMAGE_CLASS Image
{
public:
enum Format
{
Format_RGB,
Format_ARGB,
};
Image();
Image(const Image & img);
~Image();
const Image & operator=(const Image & img);
void allocate(uint w, uint h, uint d = 1);
void acquire(Color32 * data, uint w, uint h, uint d = 1);
//bool load(const char * name);
void resize(uint w, uint h, uint d = 1);
void wrap(void * data, uint w, uint h, uint d = 1);
void unwrap();
uint width() const;
uint height() const;
uint depth() const;
const Color32 * scanline(uint h) const;
Color32 * scanline(uint h);
const Color32 * pixels() const;
Color32 * pixels();
const Color32 & pixel(uint idx) const;
Color32 & pixel(uint idx);
const Color32 & pixel(uint x, uint y, uint z = 0) const;
Color32 & pixel(uint x, uint y, uint z = 0);
Format format() const;
void setFormat(Format f);
void fill(Color32 c);
private:
void free();
private:
uint m_width;
uint m_height;
uint m_depth;
Format m_format;
Color32 * m_data;
};
inline const Color32 & Image::pixel(uint x, uint y, uint z) const
{
nvDebugCheck(x < m_width && y < m_height && z < m_depth);
return pixel((z * m_height + y) * m_width + x);
}
inline Color32 & Image::pixel(uint x, uint y, uint z)
{
nvDebugCheck(x < m_width && y < m_height && z < m_depth);
return pixel((z * m_height + y) * m_width + x);
}
} // nv namespace
#endif // NV_IMAGE_IMAGE_H

View file

@ -1,48 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_IMAGE_H
#define NV_IMAGE_H
#include "nvcore/nvcore.h"
#include "nvcore/Debug.h" // nvDebugCheck
#include "nvcore/Utils.h" // isPowerOfTwo
// Function linkage
#if NVIMAGE_SHARED
#ifdef NVIMAGE_EXPORTS
#define NVIMAGE_API DLL_EXPORT
#define NVIMAGE_CLASS DLL_EXPORT_CLASS
#else
#define NVIMAGE_API DLL_IMPORT
#define NVIMAGE_CLASS DLL_IMPORT
#endif
#else
#define NVIMAGE_API
#define NVIMAGE_CLASS
#endif
namespace nv {
// Some utility functions:
inline uint computeBitPitch(uint w, uint bitsize, uint alignmentInBits)
{
nvDebugCheck(isPowerOfTwo(alignmentInBits));
return ((w * bitsize + alignmentInBits - 1) / alignmentInBits) * alignmentInBits;
}
inline uint computeBytePitch(uint w, uint bitsize, uint alignmentInBytes)
{
uint pitch = computeBitPitch(w, bitsize, 8*alignmentInBytes);
nvDebugCheck((pitch & 7) == 0);
return (pitch + 7) / 8;
}
} // nv namespace
#endif // NV_IMAGE_H

View file

@ -1,270 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#include "Basis.h"
using namespace nv;
/// Normalize basis vectors.
void Basis::normalize(float epsilon /*= NV_EPSILON*/)
{
normal = ::normalizeSafe(normal, Vector3(0.0f), epsilon);
tangent = ::normalizeSafe(tangent, Vector3(0.0f), epsilon);
bitangent = ::normalizeSafe(bitangent, Vector3(0.0f), epsilon);
}
/// Gram-Schmidt orthogonalization.
/// @note Works only if the vectors are close to orthogonal.
void Basis::orthonormalize(float epsilon /*= NV_EPSILON*/)
{
// N' = |N|
// T' = |T - (N' dot T) N'|
// B' = |B - (N' dot B) N' - (T' dot B) T'|
normal = ::normalize(normal, epsilon);
tangent -= normal * dot(normal, tangent);
tangent = ::normalize(tangent, epsilon);
bitangent -= normal * dot(normal, bitangent);
bitangent -= tangent * dot(tangent, bitangent);
bitangent = ::normalize(bitangent, epsilon);
}
/// Robust orthonormalization.
/// Returns an orthonormal basis even when the original is degenerate.
void Basis::robustOrthonormalize(float epsilon /*= NV_EPSILON*/)
{
// Normalize all vectors.
normalize(epsilon);
if (lengthSquared(normal) < epsilon*epsilon)
{
// Build normal from tangent and bitangent.
normal = cross(tangent, bitangent);
if (lengthSquared(normal) < epsilon*epsilon)
{
// Arbitrary basis.
tangent = Vector3(1, 0, 0);
bitangent = Vector3(0, 1, 0);
normal = Vector3(0, 0, 1);
return;
}
normal = nv::normalize(normal, epsilon);
}
// Project tangents to normal plane.
tangent -= normal * dot(normal, tangent);
bitangent -= normal * dot(normal, bitangent);
if (lengthSquared(tangent) < epsilon*epsilon)
{
if (lengthSquared(bitangent) < epsilon*epsilon)
{
// Arbitrary basis.
buildFrameForDirection(normal);
}
else
{
// Build tangent from bitangent.
bitangent = nv::normalize(bitangent, epsilon);
tangent = cross(bitangent, normal);
nvDebugCheck(isNormalized(tangent, epsilon));
}
}
else
{
tangent = nv::normalize(tangent, epsilon);
#if 0
bitangent -= tangent * dot(tangent, bitangent);
if (lengthSquared(bitangent) < epsilon*epsilon)
{
bitangent = cross(tangent, normal);
nvDebugCheck(isNormalized(bitangent, epsilon));
}
else
{
bitangent = nv::normalize(bitangent, epsilon);
}
#else
if (lengthSquared(bitangent) < epsilon*epsilon)
{
// Build bitangent from tangent.
bitangent = cross(tangent, normal);
nvDebugCheck(isNormalized(bitangent, epsilon));
}
else
{
bitangent = nv::normalize(bitangent, epsilon);
// At this point tangent and bitangent are orthogonal to normal, but we don't know whether their orientation.
Vector3 bisector;
if (lengthSquared(tangent + bitangent) < epsilon*epsilon)
{
bisector = tangent;
}
else
{
bisector = nv::normalize(tangent + bitangent);
}
Vector3 axis = nv::normalize(cross(bisector, normal));
//nvDebugCheck(isNormalized(axis, epsilon));
nvDebugCheck(equal(dot(axis, tangent), -dot(axis, bitangent), epsilon));
if (dot(axis, tangent) > 0)
{
tangent = bisector + axis;
bitangent = bisector - axis;
}
else
{
tangent = bisector - axis;
bitangent = bisector + axis;
}
// Make sure the resulting tangents are still perpendicular to the normal.
tangent -= normal * dot(normal, tangent);
bitangent -= normal * dot(normal, bitangent);
// Double check.
nvDebugCheck(equal(dot(normal, tangent), 0.0f, epsilon));
nvDebugCheck(equal(dot(normal, bitangent), 0.0f, epsilon));
// Normalize.
tangent = nv::normalize(tangent);
bitangent = nv::normalize(bitangent);
// If tangent and bitangent are not orthogonal, then derive bitangent from tangent, just in case...
if (!equal(dot(tangent, bitangent), 0.0f, epsilon)) {
bitangent = cross(tangent, normal);
bitangent = nv::normalize(bitangent);
}
}
#endif
}
/*// Check vector lengths.
if (!isNormalized(normal, epsilon))
{
nvDebug("%f %f %f\n", normal.x, normal.y, normal.z);
nvDebug("%f %f %f\n", tangent.x, tangent.y, tangent.z);
nvDebug("%f %f %f\n", bitangent.x, bitangent.y, bitangent.z);
}*/
nvDebugCheck(isNormalized(normal, epsilon));
nvDebugCheck(isNormalized(tangent, epsilon));
nvDebugCheck(isNormalized(bitangent, epsilon));
// Check vector angles.
nvDebugCheck(equal(dot(normal, tangent), 0.0f, epsilon));
nvDebugCheck(equal(dot(normal, bitangent), 0.0f, epsilon));
nvDebugCheck(equal(dot(tangent, bitangent), 0.0f, epsilon));
// Check vector orientation.
const float det = dot(cross(normal, tangent), bitangent);
nvDebugCheck(equal(det, 1.0f, epsilon) || equal(det, -1.0f, epsilon));
}
/// Build an arbitrary frame for the given direction.
void Basis::buildFrameForDirection(Vector3::Arg d, float angle/*= 0*/)
{
nvCheck(isNormalized(d));
normal = d;
// Choose minimum axis.
if (fabsf(normal.x) < fabsf(normal.y) && fabsf(normal.x) < fabsf(normal.z))
{
tangent = Vector3(1, 0, 0);
}
else if (fabsf(normal.y) < fabsf(normal.z))
{
tangent = Vector3(0, 1, 0);
}
else
{
tangent = Vector3(0, 0, 1);
}
// Ortogonalize
tangent -= normal * dot(normal, tangent);
tangent = ::normalize(tangent);
bitangent = cross(normal, tangent);
// Rotate frame around normal according to angle.
if (angle != 0.0f) {
float c = cosf(angle);
float s = sinf(angle);
Vector3 tmp = c * tangent - s * bitangent;
bitangent = s * tangent + c * bitangent;
tangent = tmp;
}
}
bool Basis::isValid() const
{
if (equal(normal, Vector3(0.0f))) return false;
if (equal(tangent, Vector3(0.0f))) return false;
if (equal(bitangent, Vector3(0.0f))) return false;
if (equal(determinant(), 0.0f)) return false;
return true;
}
/// Transform by this basis. (From this basis to object space).
Vector3 Basis::transform(Vector3::Arg v) const
{
Vector3 o = tangent * v.x;
o += bitangent * v.y;
o += normal * v.z;
return o;
}
/// Transform by the transpose. (From object space to this basis).
Vector3 Basis::transformT(Vector3::Arg v)
{
return Vector3(dot(tangent, v), dot(bitangent, v), dot(normal, v));
}
/// Transform by the inverse. (From object space to this basis).
/// @note Uses Cramer's rule so the inverse is not accurate if the basis is ill-conditioned.
Vector3 Basis::transformI(Vector3::Arg v) const
{
const float det = determinant();
nvDebugCheck(!equal(det, 0.0f, 0.0f));
const float idet = 1.0f / det;
// Rows of the inverse matrix.
Vector3 r0(
(bitangent.y * normal.z - bitangent.z * normal.y),
-(bitangent.x * normal.z - bitangent.z * normal.x),
(bitangent.x * normal.y - bitangent.y * normal.x));
Vector3 r1(
-(tangent.y * normal.z - tangent.z * normal.y),
(tangent.x * normal.z - tangent.z * normal.x),
-(tangent.x * normal.y - tangent.y * normal.x));
Vector3 r2(
(tangent.y * bitangent.z - tangent.z * bitangent.y),
-(tangent.x * bitangent.z - tangent.z * bitangent.x),
(tangent.x * bitangent.y - tangent.y * bitangent.x));
return Vector3(dot(v, r0), dot(v, r1), dot(v, r2)) * idet;
}

View file

@ -1,82 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_MATH_BASIS_H
#define NV_MATH_BASIS_H
#include "nvmath.h"
#include "Vector.inl"
#include "Matrix.h"
namespace nv
{
/// Basis class to compute tangent space basis, ortogonalizations and to
/// transform vectors from one space to another.
class Basis
{
public:
/// Create a null basis.
Basis() : tangent(0, 0, 0), bitangent(0, 0, 0), normal(0, 0, 0) {}
/// Create a basis given three vectors.
Basis(Vector3::Arg n, Vector3::Arg t, Vector3::Arg b) : tangent(t), bitangent(b), normal(n) {}
/// Create a basis with the given tangent vectors and the handness.
Basis(Vector3::Arg n, Vector3::Arg t, float sign)
{
build(n, t, sign);
}
NVMATH_API void normalize(float epsilon = NV_EPSILON);
NVMATH_API void orthonormalize(float epsilon = NV_EPSILON);
NVMATH_API void robustOrthonormalize(float epsilon = NV_EPSILON);
NVMATH_API void buildFrameForDirection(Vector3::Arg d, float angle = 0);
/// Calculate the determinant [ F G N ] to obtain the handness of the basis.
float handness() const
{
return determinant() > 0.0f ? 1.0f : -1.0f;
}
/// Build a basis from 2 vectors and a handness flag.
void build(Vector3::Arg n, Vector3::Arg t, float sign)
{
normal = n;
tangent = t;
bitangent = sign * cross(t, n);
}
/// Compute the determinant of this basis.
float determinant() const
{
return
tangent.x * bitangent.y * normal.z - tangent.z * bitangent.y * normal.x +
tangent.y * bitangent.z * normal.x - tangent.y * bitangent.x * normal.z +
tangent.z * bitangent.x * normal.y - tangent.x * bitangent.z * normal.y;
}
bool isValid() const;
// Get transform matrix for this basis.
NVMATH_API Matrix matrix() const;
// Transform by this basis. (From this basis to object space).
NVMATH_API Vector3 transform(Vector3::Arg v) const;
// Transform by the transpose. (From object space to this basis).
NVMATH_API Vector3 transformT(Vector3::Arg v);
// Transform by the inverse. (From object space to this basis).
NVMATH_API Vector3 transformI(Vector3::Arg v) const;
Vector3 tangent;
Vector3 bitangent;
Vector3 normal;
};
} // nv namespace
#endif // NV_MATH_BASIS_H

View file

@ -1,119 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#include "Box.h"
#include "Box.inl"
#include "Sphere.h"
using namespace nv;
// Clip the given segment against this box.
bool Box::clipSegment(const Vector3 & origin, const Vector3 & dir, float * t_near, float * t_far) const {
// Avoid aliasing.
float tnear = *t_near;
float tfar = *t_far;
// clip ray segment to box
for (int i = 0; i < 3; i++)
{
const float pos = origin.component[i] + tfar * dir.component[i];
const float dt = tfar - tnear;
if (dir.component[i] < 0) {
// clip end point
if (pos < minCorner.component[i]) {
tfar = tnear + dt * (origin.component[i] - minCorner.component[i]) / (origin.component[i] - pos);
}
// clip start point
if (origin.component[i] > maxCorner.component[i]) {
tnear = tnear + dt * (origin.component[i] - maxCorner.component[i]) / (tfar * dir.component[i]);
}
}
else {
// clip end point
if (pos > maxCorner.component[i]) {
tfar = tnear + dt * (maxCorner.component[i] - origin.component[i]) / (pos - origin.component[i]);
}
// clip start point
if (origin.component[i] < minCorner.component[i]) {
tnear = tnear + dt * (minCorner.component[i] - origin.component[i]) / (tfar * dir.component[i]);
}
}
if (tnear > tfar) {
// Clipped away.
return false;
}
}
// Return result.
*t_near = tnear;
*t_far = tfar;
return true;
}
float nv::distanceSquared(const Box &box, const Vector3 &point) {
Vector3 closest;
if (point.x < box.minCorner.x) closest.x = box.minCorner.x;
else if (point.x > box.maxCorner.x) closest.x = box.maxCorner.x;
else closest.x = point.x;
if (point.y < box.minCorner.y) closest.y = box.minCorner.y;
else if (point.y > box.maxCorner.y) closest.y = box.maxCorner.y;
else closest.y = point.y;
if (point.z < box.minCorner.z) closest.z = box.minCorner.z;
else if (point.z > box.maxCorner.z) closest.z = box.maxCorner.z;
else closest.z = point.z;
return lengthSquared(point - closest);
}
bool nv::overlap(const Box &box, const Sphere &sphere) {
return distanceSquared(box, sphere.center) < sphere.radius * sphere.radius;
}
bool nv::intersect(const Box & box, const Vector3 & p, const Vector3 & id, float * t /*= NULL*/) {
// Precompute these in ray structure?
int sdx = (id.x < 0);
int sdy = (id.y < 0);
int sdz = (id.z < 0);
float tmin = (box.corner( sdx).x - p.x) * id.x;
float tmax = (box.corner(1-sdx).x - p.x) * id.x;
float tymin = (box.corner( sdy).y - p.y) * id.y;
float tymax = (box.corner(1-sdy).y - p.y) * id.y;
if ((tmin > tymax) || (tymin > tmax))
return false;
if (tymin > tmin) tmin = tymin;
if (tymax < tmax) tmax = tymax;
float tzmin = (box.corner( sdz).z - p.z) * id.z;
float tzmax = (box.corner(1-sdz).z - p.z) * id.z;
if ((tmin > tzmax) || (tzmin > tmax))
return false;
if (tzmin > tmin) tmin = tzmin;
if (tzmax < tmax) tmax = tzmax;
if (tmax < 0)
return false;
if (t != NULL) *t = tmin;
return true;
}

View file

@ -1,103 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MATH_BOX_H
#define NV_MATH_BOX_H
#include "Vector.h"
#include <float.h> // FLT_MAX
namespace nv
{
class Vector;
class Stream;
class Sphere;
// Axis Aligned Bounding Box.
class Box
{
public:
inline Box() {}
inline Box(const Box & b) : minCorner(b.minCorner), maxCorner(b.maxCorner) {}
inline Box(const Vector3 & mins, const Vector3 & maxs) : minCorner(mins), maxCorner(maxs) {}
Box & operator=(const Box & b);
operator const float * () const { return reinterpret_cast<const float *>(this); }
// Clear the bounds.
void clearBounds();
// min < max
bool isValid() const;
// Build a cube centered on center and with edge = 2*dist
void cube(const Vector3 & center, float dist);
// Build a box, given center and extents.
void setCenterExtents(const Vector3 & center, const Vector3 & extents);
// Get box center.
Vector3 center() const;
// Return extents of the box.
Vector3 extents() const;
// Return extents of the box.
float extents(uint axis) const;
// Add a point to this box.
void addPointToBounds(const Vector3 & p);
// Add a box to this box.
void addBoxToBounds(const Box & b);
// Add sphere to this box.
void addSphereToBounds(const Vector3 & p, float r);
// Translate box.
void translate(const Vector3 & v);
// Scale the box.
void scale(float s);
// Expand the box by a fixed amount.
void expand(float r);
// Get the area of the box.
float area() const;
// Get the volume of the box.
float volume() const;
// Return true if the box contains the given point.
bool contains(const Vector3 & p) const;
// Split the given box in 8 octants and assign the ith one to this box.
void setOctant(const Box & box, const Vector3 & center, int i);
// Clip the given segment against this box.
bool clipSegment(const Vector3 & origin, const Vector3 & dir, float * t_near, float * t_far) const;
friend Stream & operator<< (Stream & s, Box & box);
const Vector3 & corner(int i) const { return (&minCorner)[i]; }
Vector3 minCorner;
Vector3 maxCorner;
};
float distanceSquared(const Box &box, const Vector3 &point);
bool overlap(const Box &box, const Sphere &sphere);
// p is ray origin, id is inverse ray direction.
bool intersect(const Box & box, const Vector3 & p, const Vector3 & id, float * t);
} // nv namespace
#endif // NV_MATH_BOX_H

View file

@ -1,154 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MATH_BOX_INL
#define NV_MATH_BOX_INL
#include "Box.h"
#include "Vector.inl"
#include <float.h> // FLT_MAX
namespace nv
{
// Default ctor.
//inline Box::Box() { };
// Copy ctor.
//inline Box::Box(const Box & b) : minCorner(b.minCorner), maxCorner(b.maxCorner) { }
// Init ctor.
//inline Box::Box(const Vector3 & mins, const Vector3 & maxs) : minCorner(mins), maxCorner(maxs) { }
// Assignment operator.
inline Box & Box::operator=(const Box & b) { minCorner = b.minCorner; maxCorner = b.maxCorner; return *this; }
// Clear the bounds.
inline void Box::clearBounds()
{
minCorner.set(FLT_MAX, FLT_MAX, FLT_MAX);
maxCorner.set(-FLT_MAX, -FLT_MAX, -FLT_MAX);
}
// min < max
inline bool Box::isValid() const
{
return minCorner.x <= maxCorner.x && minCorner.y <= maxCorner.y && minCorner.z <= maxCorner.z;
}
// Build a cube centered on center and with edge = 2*dist
inline void Box::cube(const Vector3 & center, float dist)
{
setCenterExtents(center, Vector3(dist));
}
// Build a box, given center and extents.
inline void Box::setCenterExtents(const Vector3 & center, const Vector3 & extents)
{
minCorner = center - extents;
maxCorner = center + extents;
}
// Get box center.
inline Vector3 Box::center() const
{
return (minCorner + maxCorner) * 0.5f;
}
// Return extents of the box.
inline Vector3 Box::extents() const
{
return (maxCorner - minCorner) * 0.5f;
}
// Return extents of the box.
inline float Box::extents(uint axis) const
{
nvDebugCheck(axis < 3);
if (axis == 0) return (maxCorner.x - minCorner.x) * 0.5f;
if (axis == 1) return (maxCorner.y - minCorner.y) * 0.5f;
if (axis == 2) return (maxCorner.z - minCorner.z) * 0.5f;
nvUnreachable();
return 0.0f;
}
// Add a point to this box.
inline void Box::addPointToBounds(const Vector3 & p)
{
minCorner = min(minCorner, p);
maxCorner = max(maxCorner, p);
}
// Add a box to this box.
inline void Box::addBoxToBounds(const Box & b)
{
minCorner = min(minCorner, b.minCorner);
maxCorner = max(maxCorner, b.maxCorner);
}
// Add sphere to this box.
inline void Box::addSphereToBounds(const Vector3 & p, float r) {
minCorner = min(minCorner, p - Vector3(r));
maxCorner = min(maxCorner, p + Vector3(r));
}
// Translate box.
inline void Box::translate(const Vector3 & v)
{
minCorner += v;
maxCorner += v;
}
// Scale the box.
inline void Box::scale(float s)
{
minCorner *= s;
maxCorner *= s;
}
// Expand the box by a fixed amount.
inline void Box::expand(float r) {
minCorner -= Vector3(r,r,r);
maxCorner += Vector3(r,r,r);
}
// Get the area of the box.
inline float Box::area() const
{
const Vector3 d = extents();
return 8.0f * (d.x*d.y + d.x*d.z + d.y*d.z);
}
// Get the volume of the box.
inline float Box::volume() const
{
Vector3 d = extents();
return 8.0f * (d.x * d.y * d.z);
}
// Return true if the box contains the given point.
inline bool Box::contains(const Vector3 & p) const
{
return
minCorner.x < p.x && minCorner.y < p.y && minCorner.z < p.z &&
maxCorner.x > p.x && maxCorner.y > p.y && maxCorner.z > p.z;
}
// Split the given box in 8 octants and assign the ith one to this box.
inline void Box::setOctant(const Box & box, const Vector3 & center, int i)
{
minCorner = box.minCorner;
maxCorner = box.maxCorner;
if (i & 4) minCorner.x = center.x;
else maxCorner.x = center.x;
if (i & 2) minCorner.y = center.y;
else maxCorner.y = center.y;
if (i & 1) minCorner.z = center.z;
else maxCorner.z = center.z;
}
} // nv namespace
#endif // NV_MATH_BOX_INL

View file

@ -1,150 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MATH_COLOR_H
#define NV_MATH_COLOR_H
#include "nvmath.h"
namespace nv
{
/// 64 bit color stored as BGRA.
class NVMATH_CLASS Color64
{
public:
Color64() { }
Color64(const Color64 & c) : u(c.u) { }
Color64(uint16 R, uint16 G, uint16 B, uint16 A) { setRGBA(R, G, B, A); }
explicit Color64(uint64 U) : u(U) { }
void setRGBA(uint16 R, uint16 G, uint16 B, uint16 A)
{
r = R;
g = G;
b = B;
a = A;
}
operator uint64 () const {
return u;
}
union {
struct {
#if NV_LITTLE_ENDIAN
uint16 r, a, b, g;
#else
uint16 a: 16;
uint16 r: 16;
uint16 g: 16;
uint16 b: 16;
#endif
};
uint64 u;
};
};
/// 32 bit color stored as BGRA.
class NVMATH_CLASS Color32
{
public:
Color32() { }
Color32(const Color32 & c) : u(c.u) { }
Color32(uint8 R, uint8 G, uint8 B) { setRGBA(R, G, B, 0xFF); }
Color32(uint8 R, uint8 G, uint8 B, uint8 A) { setRGBA( R, G, B, A); }
//Color32(uint8 c[4]) { setRGBA(c[0], c[1], c[2], c[3]); }
//Color32(float R, float G, float B) { setRGBA(uint(R*255), uint(G*255), uint(B*255), 0xFF); }
//Color32(float R, float G, float B, float A) { setRGBA(uint(R*255), uint(G*255), uint(B*255), uint(A*255)); }
explicit Color32(uint32 U) : u(U) { }
void setRGBA(uint8 R, uint8 G, uint8 B, uint8 A)
{
r = R;
g = G;
b = B;
a = A;
}
void setBGRA(uint8 B, uint8 G, uint8 R, uint8 A = 0xFF)
{
r = R;
g = G;
b = B;
a = A;
}
operator uint32 () const {
return u;
}
union {
struct {
#if NV_LITTLE_ENDIAN
uint8 b, g, r, a;
#else
uint8 a: 8;
uint8 r: 8;
uint8 g: 8;
uint8 b: 8;
#endif
};
uint8 component[4];
uint32 u;
};
};
/// 16 bit 565 BGR color.
class NVMATH_CLASS Color16
{
public:
Color16() { }
Color16(const Color16 & c) : u(c.u) { }
explicit Color16(uint16 U) : u(U) { }
union {
struct {
#if NV_LITTLE_ENDIAN
uint16 b : 5;
uint16 g : 6;
uint16 r : 5;
#else
uint16 r : 5;
uint16 g : 6;
uint16 b : 5;
#endif
};
uint16 u;
};
};
/// 16 bit 4444 BGRA color.
class NVMATH_CLASS Color16_4444
{
public:
Color16_4444() { }
Color16_4444(const Color16_4444 & c) : u(c.u) { }
explicit Color16_4444(uint16 U) : u(U) { }
union {
struct {
#if NV_LITTLE_ENDIAN
uint16 b : 4;
uint16 g : 4;
uint16 r : 4;
uint16 a : 4;
#else
uint16 a : 4;
uint16 r : 4;
uint16 g : 4;
uint16 b : 4;
#endif
};
uint16 u;
};
};
} // nv namespace
#endif // NV_MATH_COLOR_H

View file

@ -1,120 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#include "ConvexHull.h"
#include "Vector.inl"
#include "nvcore/RadixSort.h"
#include "nvcore/Array.inl"
using namespace nv;
inline static float triangleArea(Vector2::Arg v1, Vector2::Arg v2, Vector2::Arg v3)
{
return 0.5f * (v3.x * v1.y + v1.x * v2.y + v2.x * v3.y - v2.x * v1.y - v3.x * v2.y - v1.x * v3.y);
}
// Compute the convex hull using Graham Scan.
void nv::convexHull(const Array<Vector2> & input, Array<Vector2> & output, float epsilon/*=0*/)
{
const uint inputCount = input.count();
Array<float> coords;
coords.resize(inputCount);
for (uint i = 0; i < inputCount; i++) {
coords[i] = input[i].x;
}
RadixSort radix;
radix.sort(coords);
const uint * ranks = radix.ranks();
Array<Vector2> top(inputCount);
Array<Vector2> bottom(inputCount);
Vector2 P = input[ranks[0]];
Vector2 Q = input[ranks[inputCount-1]];
float topy = max(P.y, Q.y);
float boty = min(P.y, Q.y);
for (uint i = 0; i < inputCount; i++) {
Vector2 p = input[ranks[i]];
if (p.y >= boty) top.append(p);
}
for (uint i = 0; i < inputCount; i++) {
Vector2 p = input[ranks[inputCount-1-i]];
if (p.y <= topy) bottom.append(p);
}
// Filter top list.
output.clear();
output.append(top[0]);
output.append(top[1]);
for (uint i = 2; i < top.count(); ) {
Vector2 a = output[output.count()-2];
Vector2 b = output[output.count()-1];
Vector2 c = top[i];
float area = triangleArea(a, b, c);
if (area >= -epsilon) {
output.popBack();
}
if (area < -epsilon || output.count() == 1) {
output.append(c);
i++;
}
}
uint top_count = output.count();
output.append(bottom[1]);
// Filter bottom list.
for (uint i = 2; i < bottom.count(); ) {
Vector2 a = output[output.count()-2];
Vector2 b = output[output.count()-1];
Vector2 c = bottom[i];
float area = triangleArea(a, b, c);
if (area >= -epsilon) {
output.popBack();
}
if (area < -epsilon || output.count() == top_count) {
output.append(c);
i++;
}
}
// Remove duplicate element.
nvDebugCheck(output.front() == output.back());
output.popBack();
}
/*
void testConvexHull() {
Array<Vector2> points;
points.append(Vector2(1.00, 1.00));
points.append(Vector2(0.00, 0.00));
points.append(Vector2(1.00, 1.00));
points.append(Vector2(1.00, -1.00));
points.append(Vector2(2.00, 5.00));
points.append(Vector2(-5.00, 3.00));
points.append(Vector2(-4.00, -3.00));
points.append(Vector2(7.00, -4.00));
Array<Vector2> hull;
convexHull(points, hull);
}
*/

View file

@ -1,17 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_MATH_CONVEXHULL_H
#define NV_MATH_CONVEXHULL_H
#include "nvmath.h"
#include "nvcore/Array.h"
namespace nv {
class Vector2;
void convexHull(const Array<Vector2> & input, Array<Vector2> & output, float epsilon = 0);
} // namespace nv
#endif // NV_MATH_CONVEXHULL_H

File diff suppressed because it is too large Load diff

View file

@ -1,50 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_MATH_FITTING_H
#define NV_MATH_FITTING_H
#include "Vector.h"
#include "Plane.h"
namespace nv
{
namespace Fit
{
Vector3 computeCentroid(int n, const Vector3 * points);
Vector3 computeCentroid(int n, const Vector3 * points, const float * weights, const Vector3 & metric);
Vector4 computeCentroid(int n, const Vector4 * points);
Vector4 computeCentroid(int n, const Vector4 * points, const float * weights, const Vector4 & metric);
Vector3 computeCovariance(int n, const Vector3 * points, float * covariance);
Vector3 computeCovariance(int n, const Vector3 * points, const float * weights, const Vector3 & metric, float * covariance);
Vector4 computeCovariance(int n, const Vector4 * points, float * covariance);
Vector4 computeCovariance(int n, const Vector4 * points, const float * weights, const Vector4 & metric, float * covariance);
Vector3 computePrincipalComponent_PowerMethod(int n, const Vector3 * points);
Vector3 computePrincipalComponent_PowerMethod(int n, const Vector3 * points, const float * weights, const Vector3 & metric);
Vector3 computePrincipalComponent_EigenSolver(int n, const Vector3 * points);
Vector3 computePrincipalComponent_EigenSolver(int n, const Vector3 * points, const float * weights, const Vector3 & metric);
Vector4 computePrincipalComponent_EigenSolver(int n, const Vector4 * points);
Vector4 computePrincipalComponent_EigenSolver(int n, const Vector4 * points, const float * weights, const Vector4 & metric);
Vector3 computePrincipalComponent_SVD(int n, const Vector3 * points);
Vector4 computePrincipalComponent_SVD(int n, const Vector4 * points);
Plane bestPlane(int n, const Vector3 * points);
bool isPlanar(int n, const Vector3 * points, float epsilon = NV_EPSILON);
bool eigenSolveSymmetric3(const float matrix[6], float eigenValues[3], Vector3 eigenVectors[3]);
bool eigenSolveSymmetric4(const float matrix[10], float eigenValues[4], Vector4 eigenVectors[4]);
// Returns number of clusters [1-4].
int compute4Means(int n, const Vector3 * points, const float * weights, const Vector3 & metric, Vector3 * cluster);
}
} // nv namespace
#endif // NV_MATH_FITTING_H

View file

@ -1,39 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_MATH_KAHANSUM_H
#define NV_MATH_KAHANSUM_H
#include "nvmath.h"
namespace nv
{
class KahanSum
{
public:
KahanSum() : accum(0.0f), err(0) {};
void add(float f)
{
float compensated = f + err;
float tmp = accum + compensated;
err = accum - tmp;
err += compensated;
accum = tmp;
}
float sum() const
{
return accum;
}
private:
float accum;
float err;
};
} // nv namespace
#endif // NV_MATH_KAHANSUM_H

View file

@ -1,441 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#include "Matrix.inl"
#include "Vector.inl"
#include "nvcore/Array.inl"
#include <float.h>
#if !NV_CC_MSVC && !NV_OS_ORBIS
#include <alloca.h>
#endif
using namespace nv;
// Given a matrix a[1..n][1..n], this routine replaces it by the LU decomposition of a rowwise
// permutation of itself. a and n are input. a is output, arranged as in equation (2.3.14) above;
// indx[1..n] is an output vector that records the row permutation effected by the partial
// pivoting; d is output as -1 depending on whether the number of row interchanges was even
// or odd, respectively. This routine is used in combination with lubksb to solve linear equations
// or invert a matrix.
static bool ludcmp(float **a, int n, int *indx, float *d)
{
const float TINY = 1.0e-20f;
float * vv = (float*)alloca(sizeof(float) * n); // vv stores the implicit scaling of each row.
*d = 1.0; // No row interchanges yet.
for (int i = 0; i < n; i++) { // Loop over rows to get the implicit scaling information.
float big = 0.0;
for (int j = 0; j < n; j++) {
big = max(big, fabsf(a[i][j]));
}
if (big == 0) {
return false; // Singular matrix
}
// No nonzero largest element.
vv[i] = 1.0f / big; // Save the scaling.
}
for (int j = 0; j < n; j++) { // This is the loop over columns of Crout's method.
for (int i = 0; i < j; i++) { // This is equation (2.3.12) except for i = j.
float sum = a[i][j];
for (int k = 0; k < i; k++) sum -= a[i][k]*a[k][j];
a[i][j] = sum;
}
int imax = -1;
float big = 0.0; // Initialize for the search for largest pivot element.
for (int i = j; i < n; i++) { // This is i = j of equation (2.3.12) and i = j+ 1 : : : N
float sum = a[i][j]; // of equation (2.3.13).
for (int k = 0; k < j; k++) {
sum -= a[i][k]*a[k][j];
}
a[i][j]=sum;
float dum = vv[i]*fabs(sum);
if (dum >= big) {
// Is the figure of merit for the pivot better than the best so far?
big = dum;
imax = i;
}
}
nvDebugCheck(imax != -1);
if (j != imax) { // Do we need to interchange rows?
for (int k = 0; k < n; k++) { // Yes, do so...
swap(a[imax][k], a[j][k]);
}
*d = -(*d); // ...and change the parity of d.
vv[imax]=vv[j]; // Also interchange the scale factor.
}
indx[j]=imax;
if (a[j][j] == 0.0) a[j][j] = TINY;
// If the pivot element is zero the matrix is singular (at least to the precision of the
// algorithm). For some applications on singular matrices, it is desirable to substitute
// TINY for zero.
if (j != n-1) { // Now, finally, divide by the pivot element.
float dum = 1.0f / a[j][j];
for (int i = j+1; i < n; i++) a[i][j] *= dum;
}
} // Go back for the next column in the reduction.
return true;
}
// Solves the set of n linear equations Ax = b. Here a[1..n][1..n] is input, not as the matrix
// A but rather as its LU decomposition, determined by the routine ludcmp. indx[1..n] is input
// as the permutation vector returned by ludcmp. b[1..n] is input as the right-hand side vector
// B, and returns with the solution vector X. a, n, and indx are not modified by this routine
// and can be left in place for successive calls with different right-hand sides b. This routine takes
// into account the possibility that b will begin with many zero elements, so it is efficient for use
// in matrix inversion.
static void lubksb(float **a, int n, int *indx, float b[])
{
int ii = 0;
for (int i=0; i<n; i++) { // When ii is set to a positive value, it will become
int ip = indx[i]; // the index of the first nonvanishing element of b. We now
float sum = b[ip]; // do the forward substitution, equation (2.3.6). The
b[ip] = b[i]; // only new wrinkle is to unscramble the permutation as we go.
if (ii != 0) {
for (int j = ii-1; j < i; j++) sum -= a[i][j]*b[j];
}
else if (sum != 0.0f) {
ii = i+1; // A nonzero element was encountered, so from now on we
}
b[i] = sum; // will have to do the sums in the loop above.
}
for (int i=n-1; i>=0; i--) { // Now we do the backsubstitution, equation (2.3.7).
float sum = b[i];
for (int j = i+1; j < n; j++) {
sum -= a[i][j]*b[j];
}
b[i] = sum/a[i][i]; // Store a component of the solution vector X.
} // All done!
}
bool nv::solveLU(const Matrix & A, const Vector4 & b, Vector4 * x)
{
nvDebugCheck(x != NULL);
float m[4][4];
float *a[4] = {m[0], m[1], m[2], m[3]};
int idx[4];
float d;
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
a[x][y] = A(x, y);
}
}
// Create LU decomposition.
if (!ludcmp(a, 4, idx, &d)) {
// Singular matrix.
return false;
}
// Init solution.
*x = b;
// Do back substitution.
lubksb(a, 4, idx, x->component);
return true;
}
// @@ Not tested.
Matrix nv::inverseLU(const Matrix & A)
{
Vector4 Ai[4];
solveLU(A, Vector4(1, 0, 0, 0), &Ai[0]);
solveLU(A, Vector4(0, 1, 0, 0), &Ai[1]);
solveLU(A, Vector4(0, 0, 1, 0), &Ai[2]);
solveLU(A, Vector4(0, 0, 0, 1), &Ai[3]);
return Matrix(Ai[0], Ai[1], Ai[2], Ai[3]);
}
bool nv::solveLU(const Matrix3 & A, const Vector3 & b, Vector3 * x)
{
nvDebugCheck(x != NULL);
float m[3][3];
float *a[3] = {m[0], m[1], m[2]};
int idx[3];
float d;
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
a[x][y] = A(x, y);
}
}
// Create LU decomposition.
if (!ludcmp(a, 3, idx, &d)) {
// Singular matrix.
return false;
}
// Init solution.
*x = b;
// Do back substitution.
lubksb(a, 3, idx, x->component);
return true;
}
bool nv::solveCramer(const Matrix & A, const Vector4 & b, Vector4 * x)
{
nvDebugCheck(x != NULL);
*x = transform(inverseCramer(A), b);
return true; // @@ Return false if determinant(A) == 0 !
}
bool nv::solveCramer(const Matrix3 & A, const Vector3 & b, Vector3 * x)
{
nvDebugCheck(x != NULL);
const float det = A.determinant();
if (equal(det, 0.0f)) { // @@ Use input epsilon.
return false;
}
Matrix3 Ai = inverseCramer(A);
*x = transform(Ai, b);
return true;
}
// Inverse using gaussian elimination. From Jon's code.
Matrix nv::inverse(const Matrix & m) {
Matrix A = m;
Matrix B(identity);
int i, j, k;
float max, t, det, pivot;
det = 1.0;
for (i=0; i<4; i++) { /* eliminate in column i, below diag */
max = -1.;
for (k=i; k<4; k++) /* find pivot for column i */
if (fabs(A(k, i)) > max) {
max = fabs(A(k, i));
j = k;
}
if (max<=0.) return B; /* if no nonzero pivot, PUNT */
if (j!=i) { /* swap rows i and j */
for (k=i; k<4; k++)
swap(A(i, k), A(j, k));
for (k=0; k<4; k++)
swap(B(i, k), B(j, k));
det = -det;
}
pivot = A(i, i);
det *= pivot;
for (k=i+1; k<4; k++) /* only do elems to right of pivot */
A(i, k) /= pivot;
for (k=0; k<4; k++)
B(i, k) /= pivot;
/* we know that A(i, i) will be set to 1, so don't bother to do it */
for (j=i+1; j<4; j++) { /* eliminate in rows below i */
t = A(j, i); /* we're gonna zero this guy */
for (k=i+1; k<4; k++) /* subtract scaled row i from row j */
A(j, k) -= A(i, k)*t; /* (ignore k<=i, we know they're 0) */
for (k=0; k<4; k++)
B(j, k) -= B(i, k)*t;
}
}
/*---------- backward elimination ----------*/
for (i=4-1; i>0; i--) { /* eliminate in column i, above diag */
for (j=0; j<i; j++) { /* eliminate in rows above i */
t = A(j, i); /* we're gonna zero this guy */
for (k=0; k<4; k++) /* subtract scaled row i from row j */
B(j, k) -= B(i, k)*t;
}
}
return B;
}
Matrix3 nv::inverse(const Matrix3 & m) {
Matrix3 A = m;
Matrix3 B(identity);
int i, j, k;
float max, t, det, pivot;
det = 1.0;
for (i=0; i<3; i++) { /* eliminate in column i, below diag */
max = -1.;
for (k=i; k<3; k++) /* find pivot for column i */
if (fabs(A(k, i)) > max) {
max = fabs(A(k, i));
j = k;
}
if (max<=0.) return B; /* if no nonzero pivot, PUNT */
if (j!=i) { /* swap rows i and j */
for (k=i; k<3; k++)
swap(A(i, k), A(j, k));
for (k=0; k<3; k++)
swap(B(i, k), B(j, k));
det = -det;
}
pivot = A(i, i);
det *= pivot;
for (k=i+1; k<3; k++) /* only do elems to right of pivot */
A(i, k) /= pivot;
for (k=0; k<3; k++)
B(i, k) /= pivot;
/* we know that A(i, i) will be set to 1, so don't bother to do it */
for (j=i+1; j<3; j++) { /* eliminate in rows below i */
t = A(j, i); /* we're gonna zero this guy */
for (k=i+1; k<3; k++) /* subtract scaled row i from row j */
A(j, k) -= A(i, k)*t; /* (ignore k<=i, we know they're 0) */
for (k=0; k<3; k++)
B(j, k) -= B(i, k)*t;
}
}
/*---------- backward elimination ----------*/
for (i=3-1; i>0; i--) { /* eliminate in column i, above diag */
for (j=0; j<i; j++) { /* eliminate in rows above i */
t = A(j, i); /* we're gonna zero this guy */
for (k=0; k<3; k++) /* subtract scaled row i from row j */
B(j, k) -= B(i, k)*t;
}
}
return B;
}
#if 0
// Copyright (C) 1999-2004 Michael Garland.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, provided that the above
// copyright notice(s) and this permission notice appear in all copies of
// the Software and that both the above copyright notice(s) and this
// permission notice appear in supporting documentation.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
// OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
// INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
// FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
// NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
// WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
// Except as contained in this notice, the name of a copyright holder
// shall not be used in advertising or otherwise to promote the sale, use
// or other dealings in this Software without prior written authorization
// of the copyright holder.
// Matrix inversion code for 4x4 matrices using Gaussian elimination
// with partial pivoting. This is a specialized version of a
// procedure originally due to Paul Heckbert <ph@cs.cmu.edu>.
//
// Returns determinant of A, and B=inverse(A)
// If matrix A is singular, returns 0 and leaves trash in B.
//
#define SWAP(a, b, t) {t = a; a = b; b = t;}
double invert(Mat4& B, const Mat4& m)
{
Mat4 A = m;
int i, j, k;
double max, t, det, pivot;
/*---------- forward elimination ----------*/
for (i=0; i<4; i++) /* put identity matrix in B */
for (j=0; j<4; j++)
B(i, j) = (double)(i==j);
det = 1.0;
for (i=0; i<4; i++) { /* eliminate in column i, below diag */
max = -1.;
for (k=i; k<4; k++) /* find pivot for column i */
if (fabs(A(k, i)) > max) {
max = fabs(A(k, i));
j = k;
}
if (max<=0.) return 0.; /* if no nonzero pivot, PUNT */
if (j!=i) { /* swap rows i and j */
for (k=i; k<4; k++)
SWAP(A(i, k), A(j, k), t);
for (k=0; k<4; k++)
SWAP(B(i, k), B(j, k), t);
det = -det;
}
pivot = A(i, i);
det *= pivot;
for (k=i+1; k<4; k++) /* only do elems to right of pivot */
A(i, k) /= pivot;
for (k=0; k<4; k++)
B(i, k) /= pivot;
/* we know that A(i, i) will be set to 1, so don't bother to do it */
for (j=i+1; j<4; j++) { /* eliminate in rows below i */
t = A(j, i); /* we're gonna zero this guy */
for (k=i+1; k<4; k++) /* subtract scaled row i from row j */
A(j, k) -= A(i, k)*t; /* (ignore k<=i, we know they're 0) */
for (k=0; k<4; k++)
B(j, k) -= B(i, k)*t;
}
}
/*---------- backward elimination ----------*/
for (i=4-1; i>0; i--) { /* eliminate in column i, above diag */
for (j=0; j<i; j++) { /* eliminate in rows above i */
t = A(j, i); /* we're gonna zero this guy */
for (k=0; k<4; k++) /* subtract scaled row i from row j */
B(j, k) -= B(i, k)*t;
}
}
return det;
}
#endif // 0

View file

@ -1,113 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MATH_MATRIX_H
#define NV_MATH_MATRIX_H
#include "Vector.h"
// - Matrices are stored in memory in *column major* order.
// - Points are to be though of as column vectors.
// - Transformation of a point p by a matrix M is: p' = M * p
namespace nv
{
enum identity_t { identity };
// 3x3 matrix.
class NVMATH_CLASS Matrix3
{
public:
Matrix3();
explicit Matrix3(float f);
explicit Matrix3(identity_t);
Matrix3(const Matrix3 & m);
Matrix3(Vector3::Arg v0, Vector3::Arg v1, Vector3::Arg v2);
float data(uint idx) const;
float & data(uint idx);
float get(uint row, uint col) const;
float operator()(uint row, uint col) const;
float & operator()(uint row, uint col);
Vector3 row(uint i) const;
Vector3 column(uint i) const;
void operator*=(float s);
void operator/=(float s);
void operator+=(const Matrix3 & m);
void operator-=(const Matrix3 & m);
void scale(float s);
void scale(Vector3::Arg s);
float determinant() const;
private:
float m_data[9];
};
// Solve equation system using LU decomposition and back-substitution.
extern bool solveLU(const Matrix3 & m, const Vector3 & b, Vector3 * x);
// Solve equation system using Cramer's inverse.
extern bool solveCramer(const Matrix3 & A, const Vector3 & b, Vector3 * x);
// 4x4 matrix.
class NVMATH_CLASS Matrix
{
public:
typedef Matrix const & Arg;
Matrix();
explicit Matrix(float f);
explicit Matrix(identity_t);
Matrix(const Matrix3 & m);
Matrix(const Matrix & m);
Matrix(Vector4::Arg v0, Vector4::Arg v1, Vector4::Arg v2, Vector4::Arg v3);
//explicit Matrix(const float m[]); // m is assumed to contain 16 elements
float data(uint idx) const;
float & data(uint idx);
float get(uint row, uint col) const;
float operator()(uint row, uint col) const;
float & operator()(uint row, uint col);
const float * ptr() const;
Vector4 row(uint i) const;
Vector4 column(uint i) const;
void zero();
void identity();
void scale(float s);
void scale(Vector3::Arg s);
void translate(Vector3::Arg t);
void rotate(float theta, float v0, float v1, float v2);
float determinant() const;
void operator+=(const Matrix & m);
void operator-=(const Matrix & m);
void apply(Matrix::Arg m);
private:
float m_data[16];
};
// Solve equation system using LU decomposition and back-substitution.
extern bool solveLU(const Matrix & A, const Vector4 & b, Vector4 * x);
// Solve equation system using Cramer's inverse.
extern bool solveCramer(const Matrix & A, const Vector4 & b, Vector4 * x);
// Compute inverse using LU decomposition.
extern Matrix inverseLU(const Matrix & m);
// Compute inverse using Gaussian elimination and partial pivoting.
extern Matrix inverse(const Matrix & m);
extern Matrix3 inverse(const Matrix3 & m);
} // nv namespace
#endif // NV_MATH_MATRIX_H

File diff suppressed because it is too large Load diff

View file

@ -1,83 +0,0 @@
// Code from ryg:
// http://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/
// "Insert" a 0 bit after each of the 16 low bits of x
inline uint32 part1By1(uint32 x)
{
x &= 0x0000ffff; // x = ---- ---- ---- ---- fedc ba98 7654 3210
x = (x ^ (x << 8)) & 0x00ff00ff; // x = ---- ---- fedc ba98 ---- ---- 7654 3210
x = (x ^ (x << 4)) & 0x0f0f0f0f; // x = ---- fedc ---- ba98 ---- 7654 ---- 3210
x = (x ^ (x << 2)) & 0x33333333; // x = --fe --dc --ba --98 --76 --54 --32 --10
x = (x ^ (x << 1)) & 0x55555555; // x = -f-e -d-c -b-a -9-8 -7-6 -5-4 -3-2 -1-0
return x;
}
// "Insert" two 0 bits after each of the 10 low bits of x
inline uint32 part1By2(uint32 x)
{
x &= 0x000003ff; // x = ---- ---- ---- ---- ---- --98 7654 3210
x = (x ^ (x << 16)) & 0xff0000ff; // x = ---- --98 ---- ---- ---- ---- 7654 3210
x = (x ^ (x << 8)) & 0x0300f00f; // x = ---- --98 ---- ---- 7654 ---- ---- 3210
x = (x ^ (x << 4)) & 0x030c30c3; // x = ---- --98 ---- 76-- --54 ---- 32-- --10
x = (x ^ (x << 2)) & 0x09249249; // x = ---- 9--8 --7- -6-- 5--4 --3- -2-- 1--0
return x;
}
inline uint32 encodeMorton2(uint32 x, uint32 y)
{
return (part1By1(y) << 1) + part1By1(x);
}
inline uint32 encodeMorton3(uint32 x, uint32 y, uint32 z)
{
return (part1By2(z) << 2) + (part1By2(y) << 1) + part1By2(x);
}
// Inverse of part1By1 - "delete" all odd-indexed bits
inline uint32 compact1By1(uint32 x)
{
x &= 0x55555555; // x = -f-e -d-c -b-a -9-8 -7-6 -5-4 -3-2 -1-0
x = (x ^ (x >> 1)) & 0x33333333; // x = --fe --dc --ba --98 --76 --54 --32 --10
x = (x ^ (x >> 2)) & 0x0f0f0f0f; // x = ---- fedc ---- ba98 ---- 7654 ---- 3210
x = (x ^ (x >> 4)) & 0x00ff00ff; // x = ---- ---- fedc ba98 ---- ---- 7654 3210
x = (x ^ (x >> 8)) & 0x0000ffff; // x = ---- ---- ---- ---- fedc ba98 7654 3210
return x;
}
// Inverse of part1By2 - "delete" all bits not at positions divisible by 3
inline uint32 compact1By2(uint32 x)
{
x &= 0x09249249; // x = ---- 9--8 --7- -6-- 5--4 --3- -2-- 1--0
x = (x ^ (x >> 2)) & 0x030c30c3; // x = ---- --98 ---- 76-- --54 ---- 32-- --10
x = (x ^ (x >> 4)) & 0x0300f00f; // x = ---- --98 ---- ---- 7654 ---- ---- 3210
x = (x ^ (x >> 8)) & 0xff0000ff; // x = ---- --98 ---- ---- ---- ---- 7654 3210
x = (x ^ (x >> 16)) & 0x000003ff; // x = ---- ---- ---- ---- ---- --98 7654 3210
return x;
}
inline uint32 decodeMorton2X(uint32 code)
{
return compact1By1(code >> 0);
}
inline uint32 decodeMorton2Y(uint32 code)
{
return compact1By1(code >> 1);
}
inline uint32 decodeMorton3X(uint32 code)
{
return compact1By2(code >> 0);
}
inline uint32 decodeMorton3Y(uint32 code)
{
return compact1By2(code >> 1);
}
inline uint32 decodeMorton3Z(uint32 code)
{
return compact1By2(code >> 2);
}

View file

@ -1,27 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#include "Plane.h"
#include "Plane.inl"
#include "Matrix.inl"
namespace nv
{
Plane transformPlane(const Matrix & m, const Plane & p)
{
Vector3 newVec = transformVector(m, p.vector());
Vector3 ptInPlane = p.offset() * p.vector();
ptInPlane = transformPoint(m, ptInPlane);
return Plane(newVec, ptInPlane);
}
Vector3 planeIntersection(const Plane & a, const Plane & b, const Plane & c)
{
return dot(a.vector(), cross(b.vector(), c.vector())) * (
a.offset() * cross(b.vector(), c.vector()) +
c.offset() * cross(a.vector(), b.vector()) +
b.offset() * cross(c.vector(), a.vector()));
}
} // nv namespace

View file

@ -1,42 +0,0 @@
// This code is in the public domain -- Ignacio Castańo <castano@gmail.com>
#pragma once
#ifndef NV_MATH_PLANE_H
#define NV_MATH_PLANE_H
#include "nvmath.h"
#include "Vector.h"
namespace nv
{
class Matrix;
class NVMATH_CLASS Plane
{
public:
Plane();
Plane(float x, float y, float z, float w);
Plane(const Vector4 & v);
Plane(const Vector3 & v, float d);
Plane(const Vector3 & normal, const Vector3 & point);
Plane(const Vector3 & v0, const Vector3 & v1, const Vector3 & v2);
const Plane & operator=(const Plane & v);
Vector3 vector() const;
float offset() const;
Vector3 normal() const;
void operator*=(float s);
Vector4 v;
};
Plane transformPlane(const Matrix &, const Plane &);
Vector3 planeIntersection(const Plane & a, const Plane & b, const Plane & c);
} // nv namespace
#endif // NV_MATH_PLANE_H

View file

@ -1,50 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_MATH_PLANE_INL
#define NV_MATH_PLANE_INL
#include "Plane.h"
#include "Vector.inl"
namespace nv
{
inline Plane::Plane() {}
inline Plane::Plane(float x, float y, float z, float w) : v(x, y, z, w) {}
inline Plane::Plane(const Vector4 & v) : v(v) {}
inline Plane::Plane(const Vector3 & v, float d) : v(v, d) {}
inline Plane::Plane(const Vector3 & normal, const Vector3 & point) : v(normal, -dot(normal, point)) {}
inline Plane::Plane(const Vector3 & v0, const Vector3 & v1, const Vector3 & v2) {
Vector3 n = cross(v1-v0, v2-v0);
float d = -dot(n, v0);
v = Vector4(n, d);
}
inline const Plane & Plane::operator=(const Plane & p) { v = p.v; return *this; }
inline Vector3 Plane::vector() const { return v.xyz(); }
inline float Plane::offset() const { return v.w; }
inline Vector3 Plane::normal() const { return normalize(vector(), 0.0f); }
// Normalize plane.
inline Plane normalize(const Plane & plane, float epsilon = NV_EPSILON)
{
const float len = length(plane.vector());
const float inv = isZero(len, epsilon) ? 0 : 1.0f / len;
return Plane(plane.v * inv);
}
// Get the signed distance from the given point to this plane.
inline float distance(const Plane & plane, const Vector3 & point)
{
return dot(plane.vector(), point) + plane.offset();
}
inline void Plane::operator*=(float s)
{
v *= s;
}
} // nv namespace
#endif // NV_MATH_PLANE_H

View file

@ -1,158 +0,0 @@
#include "ProximityGrid.h"
#include "Box.inl"
#include "Morton.h"
using namespace nv;
ProximityGrid::ProximityGrid() {
}
void ProximityGrid::reset() {
cellArray.clear();
}
void ProximityGrid::init(const Array<Vector3> & pointArray) {
// Compute bounding box.
Box box;
box.clearBounds();
const uint count = pointArray.count();
for (uint i = 0; i < count; i++) {
box.addPointToBounds(pointArray[i]);
}
init(box, count);
// Insert all points.
for (uint i = 0; i < count; i++) {
add(pointArray[i], i);
}
}
void ProximityGrid::init(const Box & box, uint count) {
reset();
// Determine grid size.
float cellWidth;
Vector3 diagonal = box.extents() * 2.f;
float volume = box.volume();
if (equal(volume, 0)) {
// Degenerate box, treat like a quad.
Vector2 quad;
if (diagonal.x < diagonal.y && diagonal.x < diagonal.z) {
quad.x = diagonal.y;
quad.y = diagonal.z;
}
else if (diagonal.y < diagonal.x && diagonal.y < diagonal.z) {
quad.x = diagonal.x;
quad.y = diagonal.z;
}
else {
quad.x = diagonal.x;
quad.y = diagonal.y;
}
float cellArea = quad.x * quad.y / count;
cellWidth = sqrtf(cellArea); // pow(cellArea, 1.0f / 2.0f);
}
else {
// Ideally we want one cell per point.
float cellVolume = volume / count;
cellWidth = pow(cellVolume, 1.0f / 3.0f);
}
nvDebugCheck(cellWidth != 0);
sx = max(1, ftoi_ceil(diagonal.x / cellWidth));
sy = max(1, ftoi_ceil(diagonal.y / cellWidth));
sz = max(1, ftoi_ceil(diagonal.z / cellWidth));
invCellSize.x = float(sx) / diagonal.x;
invCellSize.y = float(sy) / diagonal.y;
invCellSize.z = float(sz) / diagonal.z;
cellArray.resize(sx * sy * sz);
corner = box.minCorner; // @@ Align grid better?
}
// Gather all points inside the given sphere.
// Radius is assumed to be small, so we don't bother culling the cells.
void ProximityGrid::gather(const Vector3 & position, float radius, Array<uint> & indexArray) {
int x0 = index_x(position.x - radius);
int x1 = index_x(position.x + radius);
int y0 = index_y(position.y - radius);
int y1 = index_y(position.y + radius);
int z0 = index_z(position.z - radius);
int z1 = index_z(position.z + radius);
for (int z = z0; z <= z1; z++) {
for (int y = y0; y <= y1; y++) {
for (int x = x0; x <= x1; x++) {
int idx = index(x, y, z);
indexArray.append(cellArray[idx].indexArray);
}
}
}
}
uint32 ProximityGrid::mortonCount() const {
uint64 s = U64(max3(sx, sy, sz));
s = nextPowerOfTwo(s);
if (s > 1024) {
return U32(s * s * min3(sx, sy, sz));
}
return U32(s * s * s);
}
int ProximityGrid::mortonIndex(uint32 code) const {
uint32 x, y, z;
uint s = U32(max3(sx, sy, sz));
if (s > 1024) {
// Use layered two-dimensional morton order.
s = nextPowerOfTwo(s);
uint layer = code / (s * s);
code = code % (s * s);
uint layer_count = U32(min3(sx, sy, sz));
if (sx == layer_count) {
x = layer;
y = decodeMorton2X(code);
z = decodeMorton2Y(code);
}
else if (sy == layer_count) {
x = decodeMorton2Y(code);
y = layer;
z = decodeMorton2X(code);
}
else /*if (sz == layer_count)*/ {
x = decodeMorton2X(code);
y = decodeMorton2Y(code);
z = layer;
}
}
else {
x = decodeMorton3X(code);
y = decodeMorton3Y(code);
z = decodeMorton3Z(code);
}
if (x >= U32(sx) || y >= U32(sy) || z >= U32(sz)) {
return -1;
}
return index(x, y, z);
}

View file

@ -1,99 +0,0 @@
#pragma once
#ifndef NV_MATH_PROXIMITYGRID_H
#define NV_MATH_PROXIMITYGRID_H
#include "Vector.h"
#include "ftoi.h"
#include "nvcore/Array.inl"
// A simple, dynamic proximity grid based on Jon's code.
// Instead of storing pointers here I store indices.
namespace nv {
class Box;
struct Cell {
Array<uint> indexArray;
};
struct ProximityGrid {
ProximityGrid();
void reset();
void init(const Array<Vector3> & pointArray);
void init(const Box & box, uint count);
int index_x(float x) const;
int index_y(float y) const;
int index_z(float z) const;
int index(int x, int y, int z) const;
int index(const Vector3 & pos) const;
uint32 mortonCount() const;
int mortonIndex(uint32 code) const;
void add(const Vector3 & pos, uint key);
bool remove(const Vector3 & pos, uint key);
void gather(const Vector3 & pos, float radius, Array<uint> & indices);
Array<Cell> cellArray;
Vector3 corner;
Vector3 invCellSize;
int sx, sy, sz;
};
// For morton traversal, do:
// for (int code = 0; code < mortonCount(); code++) {
// int idx = mortonIndex(code);
// if (idx < 0) continue;
// }
inline int ProximityGrid::index_x(float x) const {
return clamp(ftoi_floor((x - corner.x) * invCellSize.x), 0, sx-1);
}
inline int ProximityGrid::index_y(float y) const {
return clamp(ftoi_floor((y - corner.y) * invCellSize.y), 0, sy-1);
}
inline int ProximityGrid::index_z(float z) const {
return clamp(ftoi_floor((z - corner.z) * invCellSize.z), 0, sz-1);
}
inline int ProximityGrid::index(int x, int y, int z) const {
nvDebugCheck(x >= 0 && x < sx);
nvDebugCheck(y >= 0 && y < sy);
nvDebugCheck(z >= 0 && z < sz);
int idx = (z * sy + y) * sx + x;
nvDebugCheck(idx >= 0 && uint(idx) < cellArray.count());
return idx;
}
inline int ProximityGrid::index(const Vector3 & pos) const {
int x = index_x(pos.x);
int y = index_y(pos.y);
int z = index_z(pos.z);
return index(x, y, z);
}
inline void ProximityGrid::add(const Vector3 & pos, uint key) {
uint idx = index(pos);
cellArray[idx].indexArray.append(key);
}
inline bool ProximityGrid::remove(const Vector3 & pos, uint key) {
uint idx = index(pos);
return cellArray[idx].indexArray.remove(key);
}
} // nv namespace
#endif // NV_MATH_PROXIMITYGRID_H

View file

@ -1,213 +0,0 @@
// This code is in the public domain -- castano@gmail.com
#pragma once
#ifndef NV_MATH_QUATERNION_H
#define NV_MATH_QUATERNION_H
#include "nvmath/nvmath.h"
#include "nvmath/Vector.inl" // @@ Do not include inl files from header files.
#include "nvmath/Matrix.h"
namespace nv
{
class NVMATH_CLASS Quaternion
{
public:
typedef Quaternion const & Arg;
Quaternion();
explicit Quaternion(float f);
Quaternion(float x, float y, float z, float w);
Quaternion(Vector4::Arg v);
const Quaternion & operator=(Quaternion::Arg v);
Vector4 asVector() const;
union {
struct {
float x, y, z, w;
};
float component[4];
};
};
inline Quaternion::Quaternion() {}
inline Quaternion::Quaternion(float f) : x(f), y(f), z(f), w(f) {}
inline Quaternion::Quaternion(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {}
inline Quaternion::Quaternion(Vector4::Arg v) : x(v.x), y(v.y), z(v.z), w(v.w) {}
// @@ Move all these to Quaternion.inl!
inline const Quaternion & Quaternion::operator=(Quaternion::Arg v) {
x = v.x;
y = v.y;
z = v.z;
w = v.w;
return *this;
}
inline Vector4 Quaternion::asVector() const { return Vector4(x, y, z, w); }
inline Quaternion mul(Quaternion::Arg a, Quaternion::Arg b)
{
return Quaternion(
+ a.x*b.w + a.y*b.z - a.z*b.y + a.w*b.x,
- a.x*b.z + a.y*b.w + a.z*b.x + a.w*b.y,
+ a.x*b.y - a.y*b.x + a.z*b.w + a.w*b.z,
- a.x*b.x - a.y*b.y - a.z*b.z + a.w*b.w);
}
inline Quaternion mul(Quaternion::Arg a, Vector3::Arg b)
{
return Quaternion(
+ a.y*b.z - a.z*b.y + a.w*b.x,
- a.x*b.z + a.z*b.x + a.w*b.y,
+ a.x*b.y - a.y*b.x + a.w*b.z,
- a.x*b.x - a.y*b.y - a.z*b.z );
}
inline Quaternion mul(Vector3::Arg a, Quaternion::Arg b)
{
return Quaternion(
+ a.x*b.w + a.y*b.z - a.z*b.y,
- a.x*b.z + a.y*b.w + a.z*b.x,
+ a.x*b.y - a.y*b.x + a.z*b.w,
- a.x*b.x - a.y*b.y - a.z*b.z);
}
inline Quaternion operator *(Quaternion::Arg a, Quaternion::Arg b)
{
return mul(a, b);
}
inline Quaternion operator *(Quaternion::Arg a, Vector3::Arg b)
{
return mul(a, b);
}
inline Quaternion operator *(Vector3::Arg a, Quaternion::Arg b)
{
return mul(a, b);
}
inline Quaternion scale(Quaternion::Arg q, float s)
{
return scale(q.asVector(), s);
}
inline Quaternion operator *(Quaternion::Arg q, float s)
{
return scale(q, s);
}
inline Quaternion operator *(float s, Quaternion::Arg q)
{
return scale(q, s);
}
inline Quaternion scale(Quaternion::Arg q, Vector4::Arg s)
{
return scale(q.asVector(), s);
}
/*inline Quaternion operator *(Quaternion::Arg q, Vector4::Arg s)
{
return scale(q, s);
}
inline Quaternion operator *(Vector4::Arg s, Quaternion::Arg q)
{
return scale(q, s);
}*/
inline Quaternion conjugate(Quaternion::Arg q)
{
return scale(q, Vector4(-1, -1, -1, 1));
}
inline float length(Quaternion::Arg q)
{
return length(q.asVector());
}
inline bool isNormalized(Quaternion::Arg q, float epsilon = NV_NORMAL_EPSILON)
{
return equal(length(q), 1, epsilon);
}
inline Quaternion normalize(Quaternion::Arg q, float epsilon = NV_EPSILON)
{
float l = length(q);
nvDebugCheck(!isZero(l, epsilon));
Quaternion n = scale(q, 1.0f / l);
nvDebugCheck(isNormalized(n));
return n;
}
inline Quaternion inverse(Quaternion::Arg q)
{
return conjugate(normalize(q));
}
/// Create a rotation quaternion for @a angle alpha around normal vector @a v.
inline Quaternion axisAngle(Vector3::Arg v, float alpha)
{
float s = sinf(alpha * 0.5f);
float c = cosf(alpha * 0.5f);
return Quaternion(Vector4(v * s, c));
}
inline Vector3 imag(Quaternion::Arg q)
{
return q.asVector().xyz();
}
inline float real(Quaternion::Arg q)
{
return q.w;
}
/// Transform vector.
inline Vector3 transform(Quaternion::Arg q, Vector3::Arg v)
{
//Quaternion t = q * v * conjugate(q);
//return imag(t);
// Faster method by Fabian Giesen and others:
// http://molecularmusings.wordpress.com/2013/05/24/a-faster-quaternion-vector-multiplication/
// http://mollyrocket.com/forums/viewtopic.php?t=833&sid=3a84e00a70ccb046cfc87ac39881a3d0
Vector3 t = 2 * cross(imag(q), v);
return v + q.w * t + cross(imag(q), t);
}
// @@ Not tested.
// From Insomniac's Mike Day:
// http://www.insomniacgames.com/converting-a-rotation-matrix-to-a-quaternion/
inline Quaternion fromMatrix(const Matrix & m) {
if (m(2, 2) < 0) {
if (m(0, 0) < m(1,1)) {
float t = 1 - m(0, 0) - m(1, 1) - m(2, 2);
return Quaternion(t, m(0,1)+m(1,0), m(2,0)+m(0,2), m(1,2)-m(2,1));
}
else {
float t = 1 - m(0, 0) + m(1, 1) - m(2, 2);
return Quaternion(t, m(0,1) + m(1,0), m(1,2) + m(2,1), m(2,0) - m(0,2));
}
}
else {
if (m(0, 0) < -m(1, 1)) {
float t = 1 - m(0, 0) - m(1, 1) + m(2, 2);
return Quaternion(t, m(2,0) + m(0,2), m(1,2) + m(2,1), m(0,1) - m(1,0));
}
else {
float t = 1 + m(0, 0) + m(1, 1) + m(2, 2);
return Quaternion(t, m(1,2) - m(2,1), m(2,0) - m(0,2), m(0,1) - m(1,0));
}
}
}
} // nv namespace
#endif // NV_MATH_QUATERNION_H

View file

@ -1,54 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#include <nvmath/Random.h>
#include <time.h>
using namespace nv;
// Statics
const uint16 Rand48::a0 = 0xE66D;
const uint16 Rand48::a1 = 0xDEEC;
const uint16 Rand48::a2 = 0x0005;
const uint16 Rand48::c0 = 0x000B;
/// Get a random seed based on the current time.
uint Rand::randomSeed()
{
return (uint)time(NULL);
}
void MTRand::initialize( uint32 seed )
{
// Initialize generator state with seed
// See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
// In previous versions, most significant bits (MSBs) of the seed affect
// only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto.
uint32 *s = state;
uint32 *r = state;
int i = 1;
*s++ = seed & 0xffffffffUL;
for( ; i < N; ++i )
{
*s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL;
r++;
}
}
void MTRand::reload()
{
// Generate N new values in state
// Made clearer and faster by Matthew Bellew (matthew.bellew@home.com)
uint32 *p = state;
int i;
for( i = N - M; i--; ++p )
*p = twist( p[M], p[0], p[1] );
for( i = M; --i; ++p )
*p = twist( p[M-N], p[0], p[1] );
*p = twist( p[M-N], p[0], state[0] );
left = N, next = state;
}

View file

@ -1,376 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MATH_RANDOM_H
#define NV_MATH_RANDOM_H
#include "nvmath.h"
#include "nvcore/Utils.h" // nextPowerOfTwo
namespace nv
{
/// Interface of the random number generators.
class Rand
{
public:
virtual ~Rand() {}
enum time_e { Time };
/// Provide a new seed.
virtual void seed( uint s ) { /* empty */ };
/// Get an integer random number.
virtual uint get() = 0;
/// Get a random number on [0, max] interval.
uint getRange( uint max )
{
if (max == 0) return 0;
if (max == NV_UINT32_MAX) return get();
const uint np2 = nextPowerOfTwo( max+1 ); // @@ This fails if max == NV_UINT32_MAX
const uint mask = np2 - 1;
uint n;
do { n = get() & mask; } while( n > max );
return n;
}
/// Random number on [0.0, 1.0] interval.
float getFloat()
{
union
{
uint32 i;
float f;
} pun;
pun.i = 0x3f800000UL | (get() & 0x007fffffUL);
return pun.f - 1.0f;
}
float getFloatRange(float min, float max) {
return getFloat() * (max - min) + min;
}
/*
/// Random number on [0.0, 1.0] interval.
double getReal()
{
return double(get()) * (1.0/4294967295.0); // 2^32-1
}
/// Random number on [0.0, 1.0) interval.
double getRealExclusive()
{
return double(get()) * (1.0/4294967296.0); // 2^32
}
*/
/// Get the max value of the random number.
uint max() const { return NV_UINT32_MAX; }
// Get a random seed.
static uint randomSeed();
};
/// Very simple random number generator with low storage requirements.
class SimpleRand : public Rand
{
public:
/// Constructor that uses the current time as the seed.
SimpleRand( time_e )
{
seed(randomSeed());
}
/// Constructor that uses the given seed.
SimpleRand( uint s = 0 )
{
seed(s);
}
/// Set the given seed.
virtual void seed( uint s )
{
current = s;
}
/// Get a random number.
virtual uint get()
{
return current = current * 1103515245 + 12345;
}
private:
uint current;
};
/// Mersenne twister random number generator.
class MTRand : public Rand
{
public:
enum { N = 624 }; // length of state vector
enum { M = 397 };
/// Constructor that uses the current time as the seed.
MTRand( time_e )
{
seed(randomSeed());
}
/// Constructor that uses the given seed.
MTRand( uint s = 0 )
{
seed(s);
}
/// Constructor that uses the given seeds.
NVMATH_API MTRand( const uint * seed_array, uint length );
/// Provide a new seed.
virtual void seed( uint s )
{
initialize(s);
reload();
}
/// Get a random number between 0 - 65536.
virtual uint get()
{
// Pull a 32-bit integer from the generator state
// Every other access function simply transforms the numbers extracted here
if( left == 0 ) {
reload();
}
left--;
uint s1;
s1 = *next++;
s1 ^= (s1 >> 11);
s1 ^= (s1 << 7) & 0x9d2c5680U;
s1 ^= (s1 << 15) & 0xefc60000U;
return ( s1 ^ (s1 >> 18) );
};
private:
NVMATH_API void initialize( uint32 seed );
NVMATH_API void reload();
uint hiBit( uint u ) const { return u & 0x80000000U; }
uint loBit( uint u ) const { return u & 0x00000001U; }
uint loBits( uint u ) const { return u & 0x7fffffffU; }
uint mixBits( uint u, uint v ) const { return hiBit(u) | loBits(v); }
uint twist( uint m, uint s0, uint s1 ) const { return m ^ (mixBits(s0,s1)>>1) ^ ((~loBit(s1)+1) & 0x9908b0dfU); }
private:
uint state[N]; // internal state
uint * next; // next value to get from state
int left; // number of values left before reload needed
};
/** George Marsaglia's random number generator.
* Code based on Thatcher Ulrich public domain source code:
* http://cvs.sourceforge.net/viewcvs.py/tu-testbed/tu-testbed/base/tu_random.cpp?rev=1.7&view=auto
*
* PRNG code adapted from the complimentary-multiply-with-carry
* code in the article: George Marsaglia, "Seeds for Random Number
* Generators", Communications of the ACM, May 2003, Vol 46 No 5,
* pp90-93.
*
* The article says:
*
* "Any one of the choices for seed table size and multiplier will
* provide a RNG that has passed extensive tests of randomness,
* particularly those in [3], yet is simple and fast --
* approximately 30 million random 32-bit integers per second on a
* 850MHz PC. The period is a*b^n, where a is the multiplier, n
* the size of the seed table and b=2^32-1. (a is chosen so that
* b is a primitive root of the prime a*b^n + 1.)"
*
* [3] Marsaglia, G., Zaman, A., and Tsang, W. Toward a universal
* random number generator. _Statistics and Probability Letters
* 8_ (1990), 35-39.
*/
class GMRand : public Rand
{
public:
enum { SEED_COUNT = 8 };
// const uint64 a = 123471786; // for SEED_COUNT=1024
// const uint64 a = 123554632; // for SEED_COUNT=512
// const uint64 a = 8001634; // for SEED_COUNT=255
// const uint64 a = 8007626; // for SEED_COUNT=128
// const uint64 a = 647535442; // for SEED_COUNT=64
// const uint64 a = 547416522; // for SEED_COUNT=32
// const uint64 a = 487198574; // for SEED_COUNT=16
// const uint64 a = 716514398U; // for SEED_COUNT=8
enum { a = 716514398U };
GMRand( time_e )
{
seed(randomSeed());
}
GMRand(uint s = 987654321)
{
seed(s);
}
/// Provide a new seed.
virtual void seed( uint s )
{
c = 362436;
i = SEED_COUNT - 1;
for(int i = 0; i < SEED_COUNT; i++) {
s = s ^ (s << 13);
s = s ^ (s >> 17);
s = s ^ (s << 5);
Q[i] = s;
}
}
/// Get a random number between 0 - 65536.
virtual uint get()
{
const uint32 r = 0xFFFFFFFE;
uint64 t;
uint32 x;
i = (i + 1) & (SEED_COUNT - 1);
t = a * Q[i] + c;
c = uint32(t >> 32);
x = uint32(t + c);
if( x < c ) {
x++;
c++;
}
uint32 val = r - x;
Q[i] = val;
return val;
};
private:
uint32 c;
uint32 i;
uint32 Q[8];
};
/** Random number implementation from the GNU Sci. Lib. (GSL).
* Adapted from Nicholas Chapman version:
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
* This is the Unix rand48() generator. The generator returns the
* upper 32 bits from each term of the sequence,
*
* x_{n+1} = (a x_n + c) mod m
*
* using 48-bit unsigned arithmetic, with a = 0x5DEECE66D , c = 0xB
* and m = 2^48. The seed specifies the upper 32 bits of the initial
* value, x_1, with the lower 16 bits set to 0x330E.
*
* The theoretical value of x_{10001} is 244131582646046.
*
* The period of this generator is ? FIXME (probably around 2^48).
*/
class Rand48 : public Rand
{
public:
Rand48( time_e )
{
seed(randomSeed());
}
Rand48( uint s = 0x1234ABCD )
{
seed(s);
}
/** Set the given seed. */
virtual void seed( uint s ) {
vstate.x0 = 0x330E;
vstate.x1 = uint16(s & 0xFFFF);
vstate.x2 = uint16((s >> 16) & 0xFFFF);
}
/** Get a random number. */
virtual uint get() {
advance();
uint x1 = vstate.x1;
uint x2 = vstate.x2;
return (x2 << 16) + x1;
}
private:
void advance()
{
/* work with unsigned long ints throughout to get correct integer
promotions of any unsigned short ints */
const uint32 x0 = vstate.x0;
const uint32 x1 = vstate.x1;
const uint32 x2 = vstate.x2;
uint32 a;
a = a0 * x0 + c0;
vstate.x0 = uint16(a & 0xFFFF);
a >>= 16;
/* although the next line may overflow we only need the top 16 bits
in the following stage, so it does not matter */
a += a0 * x1 + a1 * x0;
vstate.x1 = uint16(a & 0xFFFF);
a >>= 16;
a += a0 * x2 + a1 * x1 + a2 * x0;
vstate.x2 = uint16(a & 0xFFFF);
}
private:
NVMATH_API static const uint16 a0, a1, a2, c0;
struct rand48_state_t {
uint16 x0, x1, x2;
} vstate;
};
} // nv namespace
#endif // NV_MATH_RANDOM_H

View file

@ -1,744 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#include "Solver.h"
#include "Sparse.h"
#include "nvcore/Array.inl"
using namespace nv;
namespace
{
class Preconditioner
{
public:
// Virtual dtor.
virtual ~Preconditioner() { }
// Apply preconditioning step.
virtual void apply(const FullVector & x, FullVector & y) const = 0;
};
// Jacobi preconditioner.
class JacobiPreconditioner : public Preconditioner
{
public:
JacobiPreconditioner(const SparseMatrix & M, bool symmetric) : m_inverseDiagonal(M.width())
{
nvCheck(M.isSquare());
for(uint x = 0; x < M.width(); x++)
{
float elem = M.getCoefficient(x, x);
//nvDebugCheck( elem != 0.0f ); // This can be zero in the presence of zero area triangles.
if (symmetric)
{
m_inverseDiagonal[x] = (elem != 0) ? 1.0f / sqrtf(fabsf(elem)) : 1.0f;
}
else
{
m_inverseDiagonal[x] = (elem != 0) ? 1.0f / elem : 1.0f;
}
}
}
void apply(const FullVector & x, FullVector & y) const
{
nvDebugCheck(x.dimension() == m_inverseDiagonal.dimension());
nvDebugCheck(y.dimension() == m_inverseDiagonal.dimension());
// @@ Wrap vector component-wise product into a separate function.
const uint D = x.dimension();
for (uint i = 0; i < D; i++)
{
y[i] = m_inverseDiagonal[i] * x[i];
}
}
private:
FullVector m_inverseDiagonal;
};
} // namespace
static bool ConjugateGradientSolver(const SparseMatrix & A, const FullVector & b, FullVector & x, float epsilon);
static bool ConjugateGradientSolver(const Preconditioner & preconditioner, const SparseMatrix & A, const FullVector & b, FullVector & x, float epsilon);
// Solve the symmetric system: At·A·x = At·b
bool nv::LeastSquaresSolver(const SparseMatrix & A, const FullVector & b, FullVector & x, float epsilon/*1e-5f*/)
{
nvDebugCheck(A.width() == x.dimension());
nvDebugCheck(A.height() == b.dimension());
nvDebugCheck(A.height() >= A.width()); // @@ If height == width we could solve it directly...
const uint D = A.width();
SparseMatrix At(A.height(), A.width());
transpose(A, At);
FullVector Atb(D);
//mult(Transposed, A, b, Atb);
mult(At, b, Atb);
SparseMatrix AtA(D);
//mult(Transposed, A, NoTransposed, A, AtA);
mult(At, A, AtA);
return SymmetricSolver(AtA, Atb, x, epsilon);
}
// See section 10.4.3 in: Mesh Parameterization: Theory and Practice, Siggraph Course Notes, August 2007
bool nv::LeastSquaresSolver(const SparseMatrix & A, const FullVector & b, FullVector & x, const uint * lockedParameters, uint lockedCount, float epsilon/*= 1e-5f*/)
{
nvDebugCheck(A.width() == x.dimension());
nvDebugCheck(A.height() == b.dimension());
nvDebugCheck(A.height() >= A.width() - lockedCount);
// @@ This is not the most efficient way of building a system with reduced degrees of freedom. It would be faster to do it on the fly.
const uint D = A.width() - lockedCount;
nvDebugCheck(D > 0);
// Compute: b - Al * xl
FullVector b_Alxl(b);
for (uint y = 0; y < A.height(); y++)
{
const uint count = A.getRow(y).count();
for (uint e = 0; e < count; e++)
{
uint column = A.getRow(y)[e].x;
bool isFree = true;
for (uint i = 0; i < lockedCount; i++)
{
isFree &= (lockedParameters[i] != column);
}
if (!isFree)
{
b_Alxl[y] -= x[column] * A.getRow(y)[e].v;
}
}
}
// Remove locked columns from A.
SparseMatrix Af(D, A.height());
for (uint y = 0; y < A.height(); y++)
{
const uint count = A.getRow(y).count();
for (uint e = 0; e < count; e++)
{
uint column = A.getRow(y)[e].x;
uint ix = column;
bool isFree = true;
for (uint i = 0; i < lockedCount; i++)
{
isFree &= (lockedParameters[i] != column);
if (column > lockedParameters[i]) ix--; // shift columns
}
if (isFree)
{
Af.setCoefficient(ix, y, A.getRow(y)[e].v);
}
}
}
// Remove elements from x
FullVector xf(D);
for (uint i = 0, j = 0; i < A.width(); i++)
{
bool isFree = true;
for (uint l = 0; l < lockedCount; l++)
{
isFree &= (lockedParameters[l] != i);
}
if (isFree)
{
xf[j++] = x[i];
}
}
// Solve reduced system.
bool result = LeastSquaresSolver(Af, b_Alxl, xf, epsilon);
// Copy results back to x.
for (uint i = 0, j = 0; i < A.width(); i++)
{
bool isFree = true;
for (uint l = 0; l < lockedCount; l++)
{
isFree &= (lockedParameters[l] != i);
}
if (isFree)
{
x[i] = xf[j++];
}
}
return result;
}
bool nv::SymmetricSolver(const SparseMatrix & A, const FullVector & b, FullVector & x, float epsilon/*1e-5f*/)
{
nvDebugCheck(A.height() == A.width());
nvDebugCheck(A.height() == b.dimension());
nvDebugCheck(b.dimension() == x.dimension());
JacobiPreconditioner jacobi(A, true);
return ConjugateGradientSolver(jacobi, A, b, x, epsilon);
//return ConjugateGradientSolver(A, b, x, epsilon);
}
/**
* Compute the solution of the sparse linear system Ab=x using the Conjugate
* Gradient method.
*
* Solving sparse linear systems:
* (1) A·x = b
*
* The conjugate gradient algorithm solves (1) only in the case that A is
* symmetric and positive definite. It is based on the idea of minimizing the
* function
*
* (2) f(x) = 1/2·x·A·x - b·x
*
* This function is minimized when its gradient
*
* (3) df = A·x - b
*
* is zero, which is equivalent to (1). The minimization is carried out by
* generating a succession of search directions p.k and improved minimizers x.k.
* At each stage a quantity alfa.k is found that minimizes f(x.k + alfa.k·p.k),
* and x.k+1 is set equal to the new point x.k + alfa.k·p.k. The p.k and x.k are
* built up in such a way that x.k+1 is also the minimizer of f over the whole
* vector space of directions already taken, {p.1, p.2, . . . , p.k}. After N
* iterations you arrive at the minimizer over the entire vector space, i.e., the
* solution to (1).
*
* For a really good explanation of the method see:
*
* "An Introduction to the Conjugate Gradient Method Without the Agonizing Pain",
* Jonhathan Richard Shewchuk.
*
**/
/*static*/ bool ConjugateGradientSolver(const SparseMatrix & A, const FullVector & b, FullVector & x, float epsilon)
{
nvDebugCheck( A.isSquare() );
nvDebugCheck( A.width() == b.dimension() );
nvDebugCheck( A.width() == x.dimension() );
int i = 0;
const int D = A.width();
const int i_max = 4 * D; // Convergence should be linear, but in some cases, it's not.
FullVector r(D); // residual
FullVector p(D); // search direction
FullVector q(D); //
float delta_0;
float delta_old;
float delta_new;
float alpha;
float beta;
// r = b - A·x;
copy(b, r);
sgemv(-1, A, x, 1, r);
// p = r;
copy(r, p);
delta_new = dot( r, r );
delta_0 = delta_new;
while (i < i_max && delta_new > epsilon*epsilon*delta_0)
{
i++;
// q = A·p
mult(A, p, q);
// alpha = delta_new / p·q
alpha = delta_new / dot( p, q );
// x = alfa·p + x
saxpy(alpha, p, x);
if ((i & 31) == 0) // recompute r after 32 steps
{
// r = b - A·x
copy(b, r);
sgemv(-1, A, x, 1, r);
}
else
{
// r = r - alpha·q
saxpy(-alpha, q, r);
}
delta_old = delta_new;
delta_new = dot( r, r );
beta = delta_new / delta_old;
// p = beta·p + r
scal(beta, p);
saxpy(1, r, p);
}
return delta_new <= epsilon*epsilon*delta_0;
}
// Conjugate gradient with preconditioner.
/*static*/ bool ConjugateGradientSolver(const Preconditioner & preconditioner, const SparseMatrix & A, const FullVector & b, FullVector & x, float epsilon)
{
nvDebugCheck( A.isSquare() );
nvDebugCheck( A.width() == b.dimension() );
nvDebugCheck( A.width() == x.dimension() );
int i = 0;
const int D = A.width();
const int i_max = 4 * D; // Convergence should be linear, but in some cases, it's not.
FullVector r(D); // residual
FullVector p(D); // search direction
FullVector q(D); //
FullVector s(D); // preconditioned
float delta_0;
float delta_old;
float delta_new;
float alpha;
float beta;
// r = b - A·x
copy(b, r);
sgemv(-1, A, x, 1, r);
// p = M^-1 · r
preconditioner.apply(r, p);
//copy(r, p);
delta_new = dot(r, p);
delta_0 = delta_new;
while (i < i_max && delta_new > epsilon*epsilon*delta_0)
{
i++;
// q = A·p
mult(A, p, q);
// alpha = delta_new / p·q
alpha = delta_new / dot(p, q);
// x = alfa·p + x
saxpy(alpha, p, x);
if ((i & 31) == 0) // recompute r after 32 steps
{
// r = b - A·x
copy(b, r);
sgemv(-1, A, x, 1, r);
}
else
{
// r = r - alfa·q
saxpy(-alpha, q, r);
}
// s = M^-1 · r
preconditioner.apply(r, s);
//copy(r, s);
delta_old = delta_new;
delta_new = dot( r, s );
beta = delta_new / delta_old;
// p = s + beta·p
scal(beta, p);
saxpy(1, s, p);
}
return delta_new <= epsilon*epsilon*delta_0;
}
#if 0 // Nonsymmetric solvers
/** Bi-conjugate gradient method. */
MATHLIB_API int BiConjugateGradientSolve( const SparseMatrix &A, const DenseVector &b, DenseVector &x, float epsilon ) {
piDebugCheck( A.IsSquare() );
piDebugCheck( A.Width() == b.Dim() );
piDebugCheck( A.Width() == x.Dim() );
int i = 0;
const int D = A.Width();
const int i_max = 4 * D;
float resid;
float rho_1 = 0;
float rho_2 = 0;
float alpha;
float beta;
DenseVector r(D);
DenseVector rtilde(D);
DenseVector p(D);
DenseVector ptilde(D);
DenseVector q(D);
DenseVector qtilde(D);
DenseVector tmp(D); // temporal vector.
// r = b - A·x;
A.Product( x, tmp );
r.Sub( b, tmp );
// rtilde = r
rtilde.Set( r );
// p = r;
p.Set( r );
// ptilde = rtilde
ptilde.Set( rtilde );
float normb = b.Norm();
if( normb == 0.0 ) normb = 1;
// test convergence
resid = r.Norm() / normb;
if( resid < epsilon ) {
// method converges?
return 0;
}
while( i < i_max ) {
i++;
rho_1 = DenseVectorDotProduct( r, rtilde );
if( rho_1 == 0 ) {
// method fails.
return -i;
}
if (i == 1) {
p.Set( r );
ptilde.Set( rtilde );
}
else {
beta = rho_1 / rho_2;
// p = r + beta * p;
p.Mad( r, p, beta );
// ptilde = ztilde + beta * ptilde;
ptilde.Mad( rtilde, ptilde, beta );
}
// q = A * p;
A.Product( p, q );
// qtilde = A^t * ptilde;
A.TransProduct( ptilde, qtilde );
alpha = rho_1 / DenseVectorDotProduct( ptilde, q );
// x += alpha * p;
x.Mad( x, p, alpha );
// r -= alpha * q;
r.Mad( r, q, -alpha );
// rtilde -= alpha * qtilde;
rtilde.Mad( rtilde, qtilde, -alpha );
rho_2 = rho_1;
// test convergence
resid = r.Norm() / normb;
if( resid < epsilon ) {
// method converges
return i;
}
}
return i;
}
/** Bi-conjugate gradient stabilized method. */
int BiCGSTABSolve( const SparseMatrix &A, const DenseVector &b, DenseVector &x, float epsilon ) {
piDebugCheck( A.IsSquare() );
piDebugCheck( A.Width() == b.Dim() );
piDebugCheck( A.Width() == x.Dim() );
int i = 0;
const int D = A.Width();
const int i_max = 2 * D;
float resid;
float rho_1 = 0;
float rho_2 = 0;
float alpha = 0;
float beta = 0;
float omega = 0;
DenseVector p(D);
DenseVector phat(D);
DenseVector s(D);
DenseVector shat(D);
DenseVector t(D);
DenseVector v(D);
DenseVector r(D);
DenseVector rtilde(D);
DenseVector tmp(D);
// r = b - A·x;
A.Product( x, tmp );
r.Sub( b, tmp );
// rtilde = r
rtilde.Set( r );
float normb = b.Norm();
if( normb == 0.0 ) normb = 1;
// test convergence
resid = r.Norm() / normb;
if( resid < epsilon ) {
// method converges?
return 0;
}
while( i<i_max ) {
i++;
rho_1 = DenseVectorDotProduct( rtilde, r );
if( rho_1 == 0 ) {
// method fails
return -i;
}
if( i == 1 ) {
p.Set( r );
}
else {
beta = (rho_1 / rho_2) * (alpha / omega);
// p = r + beta * (p - omega * v);
p.Mad( p, v, -omega );
p.Mad( r, p, beta );
}
//phat = M.solve(p);
phat.Set( p );
//Precond( &phat, p );
//v = A * phat;
A.Product( phat, v );
alpha = rho_1 / DenseVectorDotProduct( rtilde, v );
// s = r - alpha * v;
s.Mad( r, v, -alpha );
resid = s.Norm() / normb;
if( resid < epsilon ) {
// x += alpha * phat;
x.Mad( x, phat, alpha );
return i;
}
//shat = M.solve(s);
shat.Set( s );
//Precond( &shat, s );
//t = A * shat;
A.Product( shat, t );
omega = DenseVectorDotProduct( t, s ) / DenseVectorDotProduct( t, t );
// x += alpha * phat + omega * shat;
x.Mad( x, shat, omega );
x.Mad( x, phat, alpha );
//r = s - omega * t;
r.Mad( s, t, -omega );
rho_2 = rho_1;
resid = r.Norm() / normb;
if( resid < epsilon ) {
return i;
}
if( omega == 0 ) {
return -i; // ???
}
}
return i;
}
/** Bi-conjugate gradient stabilized method. */
int BiCGSTABPrecondSolve( const SparseMatrix &A, const DenseVector &b, DenseVector &x, const IPreconditioner &M, float epsilon ) {
piDebugCheck( A.IsSquare() );
piDebugCheck( A.Width() == b.Dim() );
piDebugCheck( A.Width() == x.Dim() );
int i = 0;
const int D = A.Width();
const int i_max = D;
// const int i_max = 1000;
float resid;
float rho_1 = 0;
float rho_2 = 0;
float alpha = 0;
float beta = 0;
float omega = 0;
DenseVector p(D);
DenseVector phat(D);
DenseVector s(D);
DenseVector shat(D);
DenseVector t(D);
DenseVector v(D);
DenseVector r(D);
DenseVector rtilde(D);
DenseVector tmp(D);
// r = b - A·x;
A.Product( x, tmp );
r.Sub( b, tmp );
// rtilde = r
rtilde.Set( r );
float normb = b.Norm();
if( normb == 0.0 ) normb = 1;
// test convergence
resid = r.Norm() / normb;
if( resid < epsilon ) {
// method converges?
return 0;
}
while( i<i_max ) {
i++;
rho_1 = DenseVectorDotProduct( rtilde, r );
if( rho_1 == 0 ) {
// method fails
return -i;
}
if( i == 1 ) {
p.Set( r );
}
else {
beta = (rho_1 / rho_2) * (alpha / omega);
// p = r + beta * (p - omega * v);
p.Mad( p, v, -omega );
p.Mad( r, p, beta );
}
//phat = M.solve(p);
//phat.Set( p );
M.Precond( &phat, p );
//v = A * phat;
A.Product( phat, v );
alpha = rho_1 / DenseVectorDotProduct( rtilde, v );
// s = r - alpha * v;
s.Mad( r, v, -alpha );
resid = s.Norm() / normb;
//printf( "--- Iteration %d: residual = %f\n", i, resid );
if( resid < epsilon ) {
// x += alpha * phat;
x.Mad( x, phat, alpha );
return i;
}
//shat = M.solve(s);
//shat.Set( s );
M.Precond( &shat, s );
//t = A * shat;
A.Product( shat, t );
omega = DenseVectorDotProduct( t, s ) / DenseVectorDotProduct( t, t );
// x += alpha * phat + omega * shat;
x.Mad( x, shat, omega );
x.Mad( x, phat, alpha );
//r = s - omega * t;
r.Mad( s, t, -omega );
rho_2 = rho_1;
resid = r.Norm() / normb;
if( resid < epsilon ) {
return i;
}
if( omega == 0 ) {
return -i; // ???
}
}
return i;
}
#endif

View file

@ -1,24 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MATH_SOLVER_H
#define NV_MATH_SOLVER_H
#include "nvmath.h"
namespace nv
{
class SparseMatrix;
class FullVector;
// Linear solvers.
NVMATH_API bool LeastSquaresSolver(const SparseMatrix & A, const FullVector & b, FullVector & x, float epsilon = 1e-5f);
NVMATH_API bool LeastSquaresSolver(const SparseMatrix & A, const FullVector & b, FullVector & x, const uint * lockedParameters, uint lockedCount, float epsilon = 1e-5f);
NVMATH_API bool SymmetricSolver(const SparseMatrix & A, const FullVector & b, FullVector & x, float epsilon = 1e-5f);
//NVMATH_API void NonSymmetricSolver(const SparseMatrix & A, const FullVector & b, FullVector & x, float epsilon = 1e-5f);
} // nv namespace
#endif // NV_MATH_SOLVER_H

View file

@ -1,889 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castanyo@yahoo.es>
#include "Sparse.h"
#include "KahanSum.h"
#include "nvcore/Array.inl"
#define USE_KAHAN_SUM 0
using namespace nv;
FullVector::FullVector(uint dim)
{
m_array.resize(dim);
}
FullVector::FullVector(const FullVector & v) : m_array(v.m_array)
{
}
const FullVector & FullVector::operator=(const FullVector & v)
{
nvCheck(dimension() == v.dimension());
m_array = v.m_array;
return *this;
}
void FullVector::fill(float f)
{
const uint dim = dimension();
for (uint i = 0; i < dim; i++)
{
m_array[i] = f;
}
}
void FullVector::operator+= (const FullVector & v)
{
nvDebugCheck(dimension() == v.dimension());
const uint dim = dimension();
for (uint i = 0; i < dim; i++)
{
m_array[i] += v.m_array[i];
}
}
void FullVector::operator-= (const FullVector & v)
{
nvDebugCheck(dimension() == v.dimension());
const uint dim = dimension();
for (uint i = 0; i < dim; i++)
{
m_array[i] -= v.m_array[i];
}
}
void FullVector::operator*= (const FullVector & v)
{
nvDebugCheck(dimension() == v.dimension());
const uint dim = dimension();
for (uint i = 0; i < dim; i++)
{
m_array[i] *= v.m_array[i];
}
}
void FullVector::operator+= (float f)
{
const uint dim = dimension();
for (uint i = 0; i < dim; i++)
{
m_array[i] += f;
}
}
void FullVector::operator-= (float f)
{
const uint dim = dimension();
for (uint i = 0; i < dim; i++)
{
m_array[i] -= f;
}
}
void FullVector::operator*= (float f)
{
const uint dim = dimension();
for (uint i = 0; i < dim; i++)
{
m_array[i] *= f;
}
}
void nv::saxpy(float a, const FullVector & x, FullVector & y)
{
nvDebugCheck(x.dimension() == y.dimension());
const uint dim = x.dimension();
for (uint i = 0; i < dim; i++)
{
y[i] += a * x[i];
}
}
void nv::copy(const FullVector & x, FullVector & y)
{
nvDebugCheck(x.dimension() == y.dimension());
const uint dim = x.dimension();
for (uint i = 0; i < dim; i++)
{
y[i] = x[i];
}
}
void nv::scal(float a, FullVector & x)
{
const uint dim = x.dimension();
for (uint i = 0; i < dim; i++)
{
x[i] *= a;
}
}
float nv::dot(const FullVector & x, const FullVector & y)
{
nvDebugCheck(x.dimension() == y.dimension());
const uint dim = x.dimension();
#if USE_KAHAN_SUM
KahanSum kahan;
for (uint i = 0; i < dim; i++)
{
kahan.add(x[i] * y[i]);
}
return kahan.sum();
#else
float sum = 0;
for (uint i = 0; i < dim; i++)
{
sum += x[i] * y[i];
}
return sum;
#endif
}
FullMatrix::FullMatrix(uint d) : m_width(d), m_height(d)
{
m_array.resize(d*d, 0.0f);
}
FullMatrix::FullMatrix(uint w, uint h) : m_width(w), m_height(h)
{
m_array.resize(w*h, 0.0f);
}
FullMatrix::FullMatrix(const FullMatrix & m) : m_width(m.m_width), m_height(m.m_height)
{
m_array = m.m_array;
}
const FullMatrix & FullMatrix::operator=(const FullMatrix & m)
{
nvCheck(width() == m.width());
nvCheck(height() == m.height());
m_array = m.m_array;
return *this;
}
float FullMatrix::getCoefficient(uint x, uint y) const
{
nvDebugCheck( x < width() );
nvDebugCheck( y < height() );
return m_array[y * width() + x];
}
void FullMatrix::setCoefficient(uint x, uint y, float f)
{
nvDebugCheck( x < width() );
nvDebugCheck( y < height() );
m_array[y * width() + x] = f;
}
void FullMatrix::addCoefficient(uint x, uint y, float f)
{
nvDebugCheck( x < width() );
nvDebugCheck( y < height() );
m_array[y * width() + x] += f;
}
void FullMatrix::mulCoefficient(uint x, uint y, float f)
{
nvDebugCheck( x < width() );
nvDebugCheck( y < height() );
m_array[y * width() + x] *= f;
}
float FullMatrix::dotRow(uint y, const FullVector & v) const
{
nvDebugCheck( v.dimension() == width() );
nvDebugCheck( y < height() );
float sum = 0;
const uint count = v.dimension();
for (uint i = 0; i < count; i++)
{
sum += m_array[y * count + i] * v[i];
}
return sum;
}
void FullMatrix::madRow(uint y, float alpha, FullVector & v) const
{
nvDebugCheck( v.dimension() == width() );
nvDebugCheck( y < height() );
const uint count = v.dimension();
for (uint i = 0; i < count; i++)
{
v[i] += m_array[y * count + i];
}
}
// y = M * x
void nv::mult(const FullMatrix & M, const FullVector & x, FullVector & y)
{
mult(NoTransposed, M, x, y);
}
void nv::mult(Transpose TM, const FullMatrix & M, const FullVector & x, FullVector & y)
{
const uint w = M.width();
const uint h = M.height();
if (TM == Transposed)
{
nvDebugCheck( h == x.dimension() );
nvDebugCheck( w == y.dimension() );
y.fill(0.0f);
for (uint i = 0; i < h; i++)
{
M.madRow(i, x[i], y);
}
}
else
{
nvDebugCheck( w == x.dimension() );
nvDebugCheck( h == y.dimension() );
for (uint i = 0; i < h; i++)
{
y[i] = M.dotRow(i, x);
}
}
}
// y = alpha*A*x + beta*y
void nv::sgemv(float alpha, const FullMatrix & A, const FullVector & x, float beta, FullVector & y)
{
sgemv(alpha, NoTransposed, A, x, beta, y);
}
void nv::sgemv(float alpha, Transpose TA, const FullMatrix & A, const FullVector & x, float beta, FullVector & y)
{
const uint w = A.width();
const uint h = A.height();
if (TA == Transposed)
{
nvDebugCheck( h == x.dimension() );
nvDebugCheck( w == y.dimension() );
for (uint i = 0; i < h; i++)
{
A.madRow(i, alpha * x[i], y);
}
}
else
{
nvDebugCheck( w == x.dimension() );
nvDebugCheck( h == y.dimension() );
for (uint i = 0; i < h; i++)
{
y[i] = alpha * A.dotRow(i, x) + beta * y[i];
}
}
}
// Multiply a row of A by a column of B.
static float dot(uint j, Transpose TA, const FullMatrix & A, uint i, Transpose TB, const FullMatrix & B)
{
const uint w = (TA == NoTransposed) ? A.width() : A.height();
nvDebugCheck(w == ((TB == NoTransposed) ? B.height() : A.width()));
float sum = 0.0f;
for (uint k = 0; k < w; k++)
{
const float a = (TA == NoTransposed) ? A.getCoefficient(k, j) : A.getCoefficient(j, k); // @@ Move branches out of the loop?
const float b = (TB == NoTransposed) ? B.getCoefficient(i, k) : A.getCoefficient(k, i);
sum += a * b;
}
return sum;
}
// C = A * B
void nv::mult(const FullMatrix & A, const FullMatrix & B, FullMatrix & C)
{
mult(NoTransposed, A, NoTransposed, B, C);
}
void nv::mult(Transpose TA, const FullMatrix & A, Transpose TB, const FullMatrix & B, FullMatrix & C)
{
sgemm(1.0f, TA, A, TB, B, 0.0f, C);
}
// C = alpha*A*B + beta*C
void nv::sgemm(float alpha, const FullMatrix & A, const FullMatrix & B, float beta, FullMatrix & C)
{
sgemm(alpha, NoTransposed, A, NoTransposed, B, beta, C);
}
void nv::sgemm(float alpha, Transpose TA, const FullMatrix & A, Transpose TB, const FullMatrix & B, float beta, FullMatrix & C)
{
const uint w = C.width();
const uint h = C.height();
uint aw = (TA == NoTransposed) ? A.width() : A.height();
uint ah = (TA == NoTransposed) ? A.height() : A.width();
uint bw = (TB == NoTransposed) ? B.width() : B.height();
uint bh = (TB == NoTransposed) ? B.height() : B.width();
nvDebugCheck(aw == bh);
nvDebugCheck(bw == ah);
nvDebugCheck(w == bw);
nvDebugCheck(h == ah);
for (uint y = 0; y < h; y++)
{
for (uint x = 0; x < w; x++)
{
float c = alpha * ::dot(x, TA, A, y, TB, B) + beta * C.getCoefficient(x, y);
C.setCoefficient(x, y, c);
}
}
}
/// Ctor. Init the size of the sparse matrix.
SparseMatrix::SparseMatrix(uint d) : m_width(d)
{
m_array.resize(d);
}
/// Ctor. Init the size of the sparse matrix.
SparseMatrix::SparseMatrix(uint w, uint h) : m_width(w)
{
m_array.resize(h);
}
SparseMatrix::SparseMatrix(const SparseMatrix & m) : m_width(m.m_width)
{
m_array = m.m_array;
}
const SparseMatrix & SparseMatrix::operator=(const SparseMatrix & m)
{
nvCheck(width() == m.width());
nvCheck(height() == m.height());
m_array = m.m_array;
return *this;
}
// x is column, y is row
float SparseMatrix::getCoefficient(uint x, uint y) const
{
nvDebugCheck( x < width() );
nvDebugCheck( y < height() );
const uint count = m_array[y].count();
for (uint i = 0; i < count; i++)
{
if (m_array[y][i].x == x) return m_array[y][i].v;
}
return 0.0f;
}
void SparseMatrix::setCoefficient(uint x, uint y, float f)
{
nvDebugCheck( x < width() );
nvDebugCheck( y < height() );
const uint count = m_array[y].count();
for (uint i = 0; i < count; i++)
{
if (m_array[y][i].x == x)
{
m_array[y][i].v = f;
return;
}
}
if (f != 0.0f)
{
Coefficient c = { x, f };
m_array[y].append( c );
}
}
void SparseMatrix::addCoefficient(uint x, uint y, float f)
{
nvDebugCheck( x < width() );
nvDebugCheck( y < height() );
if (f != 0.0f)
{
const uint count = m_array[y].count();
for (uint i = 0; i < count; i++)
{
if (m_array[y][i].x == x)
{
m_array[y][i].v += f;
return;
}
}
Coefficient c = { x, f };
m_array[y].append( c );
}
}
void SparseMatrix::mulCoefficient(uint x, uint y, float f)
{
nvDebugCheck( x < width() );
nvDebugCheck( y < height() );
const uint count = m_array[y].count();
for (uint i = 0; i < count; i++)
{
if (m_array[y][i].x == x)
{
m_array[y][i].v *= f;
return;
}
}
if (f != 0.0f)
{
Coefficient c = { x, f };
m_array[y].append( c );
}
}
float SparseMatrix::sumRow(uint y) const
{
nvDebugCheck( y < height() );
const uint count = m_array[y].count();
#if USE_KAHAN_SUM
KahanSum kahan;
for (uint i = 0; i < count; i++)
{
kahan.add(m_array[y][i].v);
}
return kahan.sum();
#else
float sum = 0;
for (uint i = 0; i < count; i++)
{
sum += m_array[y][i].v;
}
return sum;
#endif
}
float SparseMatrix::dotRow(uint y, const FullVector & v) const
{
nvDebugCheck( y < height() );
const uint count = m_array[y].count();
#if USE_KAHAN_SUM
KahanSum kahan;
for (uint i = 0; i < count; i++)
{
kahan.add(m_array[y][i].v * v[m_array[y][i].x]);
}
return kahan.sum();
#else
float sum = 0;
for (uint i = 0; i < count; i++)
{
sum += m_array[y][i].v * v[m_array[y][i].x];
}
return sum;
#endif
}
void SparseMatrix::madRow(uint y, float alpha, FullVector & v) const
{
nvDebugCheck(y < height());
const uint count = m_array[y].count();
for (uint i = 0; i < count; i++)
{
v[m_array[y][i].x] += alpha * m_array[y][i].v;
}
}
void SparseMatrix::clearRow(uint y)
{
nvDebugCheck( y < height() );
m_array[y].clear();
}
void SparseMatrix::scaleRow(uint y, float f)
{
nvDebugCheck( y < height() );
const uint count = m_array[y].count();
for (uint i = 0; i < count; i++)
{
m_array[y][i].v *= f;
}
}
void SparseMatrix::normalizeRow(uint y)
{
nvDebugCheck( y < height() );
float norm = 0.0f;
const uint count = m_array[y].count();
for (uint i = 0; i < count; i++)
{
float f = m_array[y][i].v;
norm += f * f;
}
scaleRow(y, 1.0f / sqrtf(norm));
}
void SparseMatrix::clearColumn(uint x)
{
nvDebugCheck(x < width());
for (uint y = 0; y < height(); y++)
{
const uint count = m_array[y].count();
for (uint e = 0; e < count; e++)
{
if (m_array[y][e].x == x)
{
m_array[y][e].v = 0.0f;
break;
}
}
}
}
void SparseMatrix::scaleColumn(uint x, float f)
{
nvDebugCheck(x < width());
for (uint y = 0; y < height(); y++)
{
const uint count = m_array[y].count();
for (uint e = 0; e < count; e++)
{
if (m_array[y][e].x == x)
{
m_array[y][e].v *= f;
break;
}
}
}
}
const Array<SparseMatrix::Coefficient> & SparseMatrix::getRow(uint y) const
{
return m_array[y];
}
bool SparseMatrix::isSymmetric() const
{
for (uint y = 0; y < height(); y++)
{
const uint count = m_array[y].count();
for (uint e = 0; e < count; e++)
{
const uint x = m_array[y][e].x;
if (x > y) {
float v = m_array[y][e].v;
if (!equal(getCoefficient(y, x), v)) { // @@ epsilon
return false;
}
}
}
}
return true;
}
// y = M * x
void nv::mult(const SparseMatrix & M, const FullVector & x, FullVector & y)
{
mult(NoTransposed, M, x, y);
}
void nv::mult(Transpose TM, const SparseMatrix & M, const FullVector & x, FullVector & y)
{
const uint w = M.width();
const uint h = M.height();
if (TM == Transposed)
{
nvDebugCheck( h == x.dimension() );
nvDebugCheck( w == y.dimension() );
y.fill(0.0f);
for (uint i = 0; i < h; i++)
{
M.madRow(i, x[i], y);
}
}
else
{
nvDebugCheck( w == x.dimension() );
nvDebugCheck( h == y.dimension() );
for (uint i = 0; i < h; i++)
{
y[i] = M.dotRow(i, x);
}
}
}
// y = alpha*A*x + beta*y
void nv::sgemv(float alpha, const SparseMatrix & A, const FullVector & x, float beta, FullVector & y)
{
sgemv(alpha, NoTransposed, A, x, beta, y);
}
void nv::sgemv(float alpha, Transpose TA, const SparseMatrix & A, const FullVector & x, float beta, FullVector & y)
{
const uint w = A.width();
const uint h = A.height();
if (TA == Transposed)
{
nvDebugCheck( h == x.dimension() );
nvDebugCheck( w == y.dimension() );
for (uint i = 0; i < h; i++)
{
A.madRow(i, alpha * x[i], y);
}
}
else
{
nvDebugCheck( w == x.dimension() );
nvDebugCheck( h == y.dimension() );
for (uint i = 0; i < h; i++)
{
y[i] = alpha * A.dotRow(i, x) + beta * y[i];
}
}
}
// dot y-row of A by x-column of B
static float dotRowColumn(int y, const SparseMatrix & A, int x, const SparseMatrix & B)
{
const Array<SparseMatrix::Coefficient> & row = A.getRow(y);
const uint count = row.count();
#if USE_KAHAN_SUM
KahanSum kahan;
for (uint i = 0; i < count; i++)
{
const SparseMatrix::Coefficient & c = row[i];
kahan.add(c.v * B.getCoefficient(x, c.x));
}
return kahan.sum();
#else
float sum = 0.0f;
for (uint i = 0; i < count; i++)
{
const SparseMatrix::Coefficient & c = row[i];
sum += c.v * B.getCoefficient(x, c.x);
}
return sum;
#endif
}
// dot y-row of A by x-row of B
static float dotRowRow(int y, const SparseMatrix & A, int x, const SparseMatrix & B)
{
const Array<SparseMatrix::Coefficient> & row = A.getRow(y);
const uint count = row.count();
#if USE_KAHAN_SUM
KahanSum kahan;
for (uint i = 0; i < count; i++)
{
const SparseMatrix::Coefficient & c = row[i];
kahan.add(c.v * B.getCoefficient(c.x, x));
}
return kahan.sum();
#else
float sum = 0.0f;
for (uint i = 0; i < count; i++)
{
const SparseMatrix::Coefficient & c = row[i];
sum += c.v * B.getCoefficient(c.x, x);
}
return sum;
#endif
}
// dot y-column of A by x-column of B
static float dotColumnColumn(int y, const SparseMatrix & A, int x, const SparseMatrix & B)
{
nvDebugCheck(A.height() == B.height());
const uint h = A.height();
#if USE_KAHAN_SUM
KahanSum kahan;
for (uint i = 0; i < h; i++)
{
kahan.add(A.getCoefficient(y, i) * B.getCoefficient(x, i));
}
return kahan.sum();
#else
float sum = 0.0f;
for (uint i = 0; i < h; i++)
{
sum += A.getCoefficient(y, i) * B.getCoefficient(x, i);
}
return sum;
#endif
}
void nv::transpose(const SparseMatrix & A, SparseMatrix & B)
{
nvDebugCheck(A.width() == B.height());
nvDebugCheck(B.width() == A.height());
const uint w = A.width();
for (uint x = 0; x < w; x++)
{
B.clearRow(x);
}
const uint h = A.height();
for (uint y = 0; y < h; y++)
{
const Array<SparseMatrix::Coefficient> & row = A.getRow(y);
const uint count = row.count();
for (uint i = 0; i < count; i++)
{
const SparseMatrix::Coefficient & c = row[i];
nvDebugCheck(c.x < w);
B.setCoefficient(y, c.x, c.v);
}
}
}
// C = A * B
void nv::mult(const SparseMatrix & A, const SparseMatrix & B, SparseMatrix & C)
{
mult(NoTransposed, A, NoTransposed, B, C);
}
void nv::mult(Transpose TA, const SparseMatrix & A, Transpose TB, const SparseMatrix & B, SparseMatrix & C)
{
sgemm(1.0f, TA, A, TB, B, 0.0f, C);
}
// C = alpha*A*B + beta*C
void nv::sgemm(float alpha, const SparseMatrix & A, const SparseMatrix & B, float beta, SparseMatrix & C)
{
sgemm(alpha, NoTransposed, A, NoTransposed, B, beta, C);
}
void nv::sgemm(float alpha, Transpose TA, const SparseMatrix & A, Transpose TB, const SparseMatrix & B, float beta, SparseMatrix & C)
{
const uint w = C.width();
const uint h = C.height();
uint aw = (TA == NoTransposed) ? A.width() : A.height();
uint ah = (TA == NoTransposed) ? A.height() : A.width();
uint bw = (TB == NoTransposed) ? B.width() : B.height();
uint bh = (TB == NoTransposed) ? B.height() : B.width();
nvDebugCheck(aw == bh);
nvDebugCheck(bw == ah);
nvDebugCheck(w == bw);
nvDebugCheck(h == ah);
for (uint y = 0; y < h; y++)
{
for (uint x = 0; x < w; x++)
{
float c = beta * C.getCoefficient(x, y);
if (TA == NoTransposed && TB == NoTransposed)
{
// dot y-row of A by x-column of B.
c += alpha * dotRowColumn(y, A, x, B);
}
else if (TA == Transposed && TB == Transposed)
{
// dot y-column of A by x-row of B.
c += alpha * dotRowColumn(x, B, y, A);
}
else if (TA == Transposed && TB == NoTransposed)
{
// dot y-column of A by x-column of B.
c += alpha * dotColumnColumn(y, A, x, B);
}
else if (TA == NoTransposed && TB == Transposed)
{
// dot y-row of A by x-row of B.
c += alpha * dotRowRow(y, A, x, B);
}
C.setCoefficient(x, y, c);
}
}
}
// C = At * A
void nv::sqm(const SparseMatrix & A, SparseMatrix & C)
{
// This is quite expensive...
mult(Transposed, A, NoTransposed, A, C);
}

View file

@ -1,204 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MATH_SPARSE_H
#define NV_MATH_SPARSE_H
#include "nvmath.h"
#include "nvcore/Array.h"
// Full and sparse vector and matrix classes. BLAS subset.
namespace nv
{
class FullVector;
class FullMatrix;
class SparseMatrix;
/// Fixed size vector class.
class FullVector
{
public:
FullVector(uint dim);
FullVector(const FullVector & v);
const FullVector & operator=(const FullVector & v);
uint dimension() const { return m_array.count(); }
const float & operator[]( uint index ) const { return m_array[index]; }
float & operator[] ( uint index ) { return m_array[index]; }
void fill(float f);
void operator+= (const FullVector & v);
void operator-= (const FullVector & v);
void operator*= (const FullVector & v);
void operator+= (float f);
void operator-= (float f);
void operator*= (float f);
private:
Array<float> m_array;
};
// Pseudo-BLAS interface.
NVMATH_API void saxpy(float a, const FullVector & x, FullVector & y); // y = a * x + y
NVMATH_API void copy(const FullVector & x, FullVector & y);
NVMATH_API void scal(float a, FullVector & x);
NVMATH_API float dot(const FullVector & x, const FullVector & y);
enum Transpose
{
NoTransposed = 0,
Transposed = 1
};
/// Full matrix class.
class FullMatrix
{
public:
FullMatrix(uint d);
FullMatrix(uint w, uint h);
FullMatrix(const FullMatrix & m);
const FullMatrix & operator=(const FullMatrix & m);
uint width() const { return m_width; }
uint height() const { return m_height; }
bool isSquare() const { return m_width == m_height; }
float getCoefficient(uint x, uint y) const;
void setCoefficient(uint x, uint y, float f);
void addCoefficient(uint x, uint y, float f);
void mulCoefficient(uint x, uint y, float f);
float dotRow(uint y, const FullVector & v) const;
void madRow(uint y, float alpha, FullVector & v) const;
protected:
bool isValid() const {
return m_array.size() == (m_width * m_height);
}
private:
const uint m_width;
const uint m_height;
Array<float> m_array;
};
NVMATH_API void mult(const FullMatrix & M, const FullVector & x, FullVector & y);
NVMATH_API void mult(Transpose TM, const FullMatrix & M, const FullVector & x, FullVector & y);
// y = alpha*A*x + beta*y
NVMATH_API void sgemv(float alpha, const FullMatrix & A, const FullVector & x, float beta, FullVector & y);
NVMATH_API void sgemv(float alpha, Transpose TA, const FullMatrix & A, const FullVector & x, float beta, FullVector & y);
NVMATH_API void mult(const FullMatrix & A, const FullMatrix & B, FullMatrix & C);
NVMATH_API void mult(Transpose TA, const FullMatrix & A, Transpose TB, const FullMatrix & B, FullMatrix & C);
// C = alpha*A*B + beta*C
NVMATH_API void sgemm(float alpha, const FullMatrix & A, const FullMatrix & B, float beta, FullMatrix & C);
NVMATH_API void sgemm(float alpha, Transpose TA, const FullMatrix & A, Transpose TB, const FullMatrix & B, float beta, FullMatrix & C);
/**
* Sparse matrix class. The matrix is assumed to be sparse and to have
* very few non-zero elements, for this reason it's stored in indexed
* format. To multiply column vectors efficiently, the matrix stores
* the elements in indexed-column order, there is a list of indexed
* elements for each row of the matrix. As with the FullVector the
* dimension of the matrix is constant.
**/
class SparseMatrix
{
friend class FullMatrix;
public:
// An element of the sparse array.
struct Coefficient {
uint x; // column
float v; // value
};
public:
SparseMatrix(uint d);
SparseMatrix(uint w, uint h);
SparseMatrix(const SparseMatrix & m);
const SparseMatrix & operator=(const SparseMatrix & m);
uint width() const { return m_width; }
uint height() const { return m_array.count(); }
bool isSquare() const { return width() == height(); }
float getCoefficient(uint x, uint y) const; // x is column, y is row
void setCoefficient(uint x, uint y, float f);
void addCoefficient(uint x, uint y, float f);
void mulCoefficient(uint x, uint y, float f);
float sumRow(uint y) const;
float dotRow(uint y, const FullVector & v) const;
void madRow(uint y, float alpha, FullVector & v) const;
void clearRow(uint y);
void scaleRow(uint y, float f);
void normalizeRow(uint y);
void clearColumn(uint x);
void scaleColumn(uint x, float f);
const Array<Coefficient> & getRow(uint y) const;
bool isSymmetric() const;
private:
/// Number of columns.
const uint m_width;
/// Array of matrix elements.
Array< Array<Coefficient> > m_array;
};
NVMATH_API void transpose(const SparseMatrix & A, SparseMatrix & B);
NVMATH_API void mult(const SparseMatrix & M, const FullVector & x, FullVector & y);
NVMATH_API void mult(Transpose TM, const SparseMatrix & M, const FullVector & x, FullVector & y);
// y = alpha*A*x + beta*y
NVMATH_API void sgemv(float alpha, const SparseMatrix & A, const FullVector & x, float beta, FullVector & y);
NVMATH_API void sgemv(float alpha, Transpose TA, const SparseMatrix & A, const FullVector & x, float beta, FullVector & y);
NVMATH_API void mult(const SparseMatrix & A, const SparseMatrix & B, SparseMatrix & C);
NVMATH_API void mult(Transpose TA, const SparseMatrix & A, Transpose TB, const SparseMatrix & B, SparseMatrix & C);
// C = alpha*A*B + beta*C
NVMATH_API void sgemm(float alpha, const SparseMatrix & A, const SparseMatrix & B, float beta, SparseMatrix & C);
NVMATH_API void sgemm(float alpha, Transpose TA, const SparseMatrix & A, Transpose TB, const SparseMatrix & B, float beta, SparseMatrix & C);
// C = At * A
NVMATH_API void sqm(const SparseMatrix & A, SparseMatrix & C);
} // nv namespace
#endif // NV_MATH_SPARSE_H

View file

@ -1,431 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#include "Sphere.h"
#include "Vector.inl"
#include "Box.inl"
#include <float.h> // FLT_MAX
using namespace nv;
const float radiusEpsilon = 1e-4f;
Sphere::Sphere(Vector3::Arg p0, Vector3::Arg p1)
{
if (p0 == p1) *this = Sphere(p0);
else {
center = (p0 + p1) * 0.5f;
radius = length(p0 - center) + radiusEpsilon;
float d0 = length(p0 - center);
float d1 = length(p1 - center);
nvDebugCheck(equal(d0, radius - radiusEpsilon));
nvDebugCheck(equal(d1, radius - radiusEpsilon));
}
}
Sphere::Sphere(Vector3::Arg p0, Vector3::Arg p1, Vector3::Arg p2)
{
if (p0 == p1 || p0 == p2) *this = Sphere(p1, p2);
else if (p1 == p2) *this = Sphere(p0, p2);
else {
Vector3 a = p1 - p0;
Vector3 b = p2 - p0;
Vector3 c = cross(a, b);
float denominator = 2.0f * lengthSquared(c);
if (!isZero(denominator)) {
Vector3 d = (lengthSquared(b) * cross(c, a) + lengthSquared(a) * cross(b, c)) / denominator;
center = p0 + d;
radius = length(d) + radiusEpsilon;
float d0 = length(p0 - center);
float d1 = length(p1 - center);
float d2 = length(p2 - center);
nvDebugCheck(equal(d0, radius - radiusEpsilon));
nvDebugCheck(equal(d1, radius - radiusEpsilon));
nvDebugCheck(equal(d2, radius - radiusEpsilon));
}
else {
// @@ This is a specialization of the code below, but really, the only thing we need to do here is to find the two most distant points.
// Compute all possible spheres, invalidate those that do not contain the four points, keep the smallest.
Sphere s0(p1, p2);
float d0 = distanceSquared(s0, p0);
if (d0 > 0) s0.radius = NV_FLOAT_MAX;
Sphere s1(p0, p2);
float d1 = distanceSquared(s1, p1);
if (d1 > 0) s1.radius = NV_FLOAT_MAX;
Sphere s2(p0, p1);
float d2 = distanceSquared(s2, p2);
if (d2 > 0) s1.radius = NV_FLOAT_MAX;
if (s0.radius < s1.radius && s0.radius < s2.radius) {
center = s0.center;
radius = s0.radius;
}
else if (s1.radius < s2.radius) {
center = s1.center;
radius = s1.radius;
}
else {
center = s2.center;
radius = s2.radius;
}
}
}
}
Sphere::Sphere(Vector3::Arg p0, Vector3::Arg p1, Vector3::Arg p2, Vector3::Arg p3)
{
if (p0 == p1 || p0 == p2 || p0 == p3) *this = Sphere(p1, p2, p3);
else if (p1 == p2 || p1 == p3) *this = Sphere(p0, p2, p3);
else if (p2 == p3) *this = Sphere(p0, p1, p2);
else {
// @@ This only works if the points are not coplanar!
Vector3 a = p1 - p0;
Vector3 b = p2 - p0;
Vector3 c = p3 - p0;
float denominator = 2.0f * dot(c, cross(a, b)); // triple product.
if (!isZero(denominator)) {
Vector3 d = (lengthSquared(c) * cross(a, b) + lengthSquared(b) * cross(c, a) + lengthSquared(a) * cross(b, c)) / denominator;
center = p0 + d;
radius = length(d) + radiusEpsilon;
float d0 = length(p0 - center);
float d1 = length(p1 - center);
float d2 = length(p2 - center);
float d3 = length(p3 - center);
nvDebugCheck(equal(d0, radius - radiusEpsilon));
nvDebugCheck(equal(d1, radius - radiusEpsilon));
nvDebugCheck(equal(d2, radius - radiusEpsilon));
nvDebugCheck(equal(d3, radius - radiusEpsilon));
}
else {
// Compute all possible spheres, invalidate those that do not contain the four points, keep the smallest.
Sphere s0(p1, p2, p3);
float d0 = distanceSquared(s0, p0);
if (d0 > 0) s0.radius = NV_FLOAT_MAX;
Sphere s1(p0, p2, p3);
float d1 = distanceSquared(s1, p1);
if (d1 > 0) s1.radius = NV_FLOAT_MAX;
Sphere s2(p0, p1, p3);
float d2 = distanceSquared(s2, p2);
if (d2 > 0) s2.radius = NV_FLOAT_MAX;
Sphere s3(p0, p1, p2);
float d3 = distanceSquared(s3, p3);
if (d3 > 0) s2.radius = NV_FLOAT_MAX;
if (s0.radius < s1.radius && s0.radius < s2.radius && s0.radius < s3.radius) {
center = s0.center;
radius = s0.radius;
}
else if (s1.radius < s2.radius && s1.radius < s3.radius) {
center = s1.center;
radius = s1.radius;
}
else if (s1.radius < s3.radius) {
center = s2.center;
radius = s2.radius;
}
else {
center = s3.center;
radius = s3.radius;
}
}
}
}
float nv::distanceSquared(const Sphere & sphere, const Vector3 & point)
{
return lengthSquared(sphere.center - point) - square(sphere.radius);
}
// Implementation of "MiniBall" based on:
// http://www.flipcode.com/archives/Smallest_Enclosing_Spheres.shtml
static Sphere recurseMini(const Vector3 *P[], uint p, uint b = 0)
{
Sphere MB;
switch(b)
{
case 0:
MB = Sphere(*P[0]);
break;
case 1:
MB = Sphere(*P[-1]);
break;
case 2:
MB = Sphere(*P[-1], *P[-2]);
break;
case 3:
MB = Sphere(*P[-1], *P[-2], *P[-3]);
break;
case 4:
MB = Sphere(*P[-1], *P[-2], *P[-3], *P[-4]);
return MB;
}
for (uint i = 0; i < p; i++)
{
if (distanceSquared(MB, *P[i]) > 0) // Signed square distance to sphere
{
for (uint j = i; j > 0; j--)
{
swap(P[j], P[j-1]);
}
MB = recurseMini(P + 1, i, b + 1);
}
}
return MB;
}
static bool allInside(const Sphere & sphere, const Vector3 * pointArray, const uint pointCount) {
for (uint i = 0; i < pointCount; i++) {
if (distanceSquared(sphere, pointArray[i]) >= NV_EPSILON) {
return false;
}
}
return true;
}
Sphere nv::miniBall(const Vector3 * pointArray, const uint pointCount)
{
nvDebugCheck(pointArray != NULL);
nvDebugCheck(pointCount > 0);
const Vector3 **L = new const Vector3*[pointCount];
for (uint i = 0; i < pointCount; i++) {
L[i] = &pointArray[i];
}
Sphere sphere = recurseMini(L, pointCount);
delete [] L;
nvDebugCheck(allInside(sphere, pointArray, pointCount));
return sphere;
}
// Approximate bounding sphere, based on "An Efficient Bounding Sphere" by Jack Ritter, from "Graphics Gems"
Sphere nv::approximateSphere_Ritter(const Vector3 * pointArray, const uint pointCount)
{
nvDebugCheck(pointArray != NULL);
nvDebugCheck(pointCount > 0);
Vector3 xmin, xmax, ymin, ymax, zmin, zmax;
xmin = xmax = ymin = ymax = zmin = zmax = pointArray[0];
// FIRST PASS: find 6 minima/maxima points
xmin.x = ymin.y = zmin.z = FLT_MAX;
xmax.x = ymax.y = zmax.z = -FLT_MAX;
for (uint i = 0; i < pointCount; i++)
{
const Vector3 & p = pointArray[i];
if (p.x < xmin.x) xmin = p;
if (p.x > xmax.x) xmax = p;
if (p.y < ymin.y) ymin = p;
if (p.y > ymax.y) ymax = p;
if (p.z < zmin.z) zmin = p;
if (p.z > zmax.z) zmax = p;
}
float xspan = lengthSquared(xmax - xmin);
float yspan = lengthSquared(ymax - ymin);
float zspan = lengthSquared(zmax - zmin);
// Set points dia1 & dia2 to the maximally separated pair.
Vector3 dia1 = xmin;
Vector3 dia2 = xmax;
float maxspan = xspan;
if (yspan > maxspan) {
maxspan = yspan;
dia1 = ymin;
dia2 = ymax;
}
if (zspan > maxspan) {
dia1 = zmin;
dia2 = zmax;
}
// |dia1-dia2| is a diameter of initial sphere
// calc initial center
Sphere sphere;
sphere.center = (dia1 + dia2) / 2.0f;
// calculate initial radius**2 and radius
float rad_sq = lengthSquared(dia2 - sphere.center);
sphere.radius = sqrtf(rad_sq);
// SECOND PASS: increment current sphere
for (uint i = 0; i < pointCount; i++)
{
const Vector3 & p = pointArray[i];
float old_to_p_sq = lengthSquared(p - sphere.center);
if (old_to_p_sq > rad_sq) // do r**2 test first
{
// this point is outside of current sphere
float old_to_p = sqrtf(old_to_p_sq);
// calc radius of new sphere
sphere.radius = (sphere.radius + old_to_p) / 2.0f;
rad_sq = sphere.radius * sphere.radius; // for next r**2 compare
float old_to_new = old_to_p - sphere.radius;
// calc center of new sphere
sphere.center = (sphere.radius * sphere.center + old_to_new * p) / old_to_p;
}
}
nvDebugCheck(allInside(sphere, pointArray, pointCount));
return sphere;
}
static float computeSphereRadius(const Vector3 & center, const Vector3 * pointArray, const uint pointCount) {
float maxRadius2 = 0;
for (uint i = 0; i < pointCount; i++)
{
const Vector3 & p = pointArray[i];
float r2 = lengthSquared(center - p);
if (r2 > maxRadius2) {
maxRadius2 = r2;
}
}
return sqrtf(maxRadius2) + radiusEpsilon;
}
Sphere nv::approximateSphere_AABB(const Vector3 * pointArray, const uint pointCount)
{
nvDebugCheck(pointArray != NULL);
nvDebugCheck(pointCount > 0);
Box box;
box.clearBounds();
for (uint i = 0; i < pointCount; i++) {
box.addPointToBounds(pointArray[i]);
}
Sphere sphere;
sphere.center = box.center();
sphere.radius = computeSphereRadius(sphere.center, pointArray, pointCount);
nvDebugCheck(allInside(sphere, pointArray, pointCount));
return sphere;
}
static void computeExtremalPoints(const Vector3 & dir, const Vector3 * pointArray, uint pointCount, Vector3 * minPoint, Vector3 * maxPoint) {
nvDebugCheck(pointCount > 0);
uint mini = 0;
uint maxi = 0;
float minDist = FLT_MAX;
float maxDist = -FLT_MAX;
for (uint i = 0; i < pointCount; i++) {
float d = dot(dir, pointArray[i]);
if (d < minDist) {
minDist = d;
mini = i;
}
if (d > maxDist) {
maxDist = d;
maxi = i;
}
}
nvDebugCheck(minDist != FLT_MAX);
nvDebugCheck(maxDist != -FLT_MAX);
*minPoint = pointArray[mini];
*maxPoint = pointArray[maxi];
}
// EPOS algorithm based on:
// http://www.ep.liu.se/ecp/034/009/ecp083409.pdf
Sphere nv::approximateSphere_EPOS6(const Vector3 * pointArray, uint pointCount)
{
nvDebugCheck(pointArray != NULL);
nvDebugCheck(pointCount > 0);
Vector3 extremalPoints[6];
// Compute 6 extremal points.
computeExtremalPoints(Vector3(1, 0, 0), pointArray, pointCount, extremalPoints+0, extremalPoints+1);
computeExtremalPoints(Vector3(0, 1, 0), pointArray, pointCount, extremalPoints+2, extremalPoints+3);
computeExtremalPoints(Vector3(0, 0, 1), pointArray, pointCount, extremalPoints+4, extremalPoints+5);
Sphere sphere = miniBall(extremalPoints, 6);
sphere.radius = computeSphereRadius(sphere.center, pointArray, pointCount);
nvDebugCheck(allInside(sphere, pointArray, pointCount));
return sphere;
}
Sphere nv::approximateSphere_EPOS14(const Vector3 * pointArray, uint pointCount)
{
nvDebugCheck(pointArray != NULL);
nvDebugCheck(pointCount > 0);
Vector3 extremalPoints[14];
// Compute 14 extremal points.
computeExtremalPoints(Vector3(1, 0, 0), pointArray, pointCount, extremalPoints+0, extremalPoints+1);
computeExtremalPoints(Vector3(0, 1, 0), pointArray, pointCount, extremalPoints+2, extremalPoints+3);
computeExtremalPoints(Vector3(0, 0, 1), pointArray, pointCount, extremalPoints+4, extremalPoints+5);
float d = sqrtf(1.0f/3.0f);
computeExtremalPoints(Vector3(d, d, d), pointArray, pointCount, extremalPoints+6, extremalPoints+7);
computeExtremalPoints(Vector3(-d, d, d), pointArray, pointCount, extremalPoints+8, extremalPoints+9);
computeExtremalPoints(Vector3(-d, -d, d), pointArray, pointCount, extremalPoints+10, extremalPoints+11);
computeExtremalPoints(Vector3(d, -d, d), pointArray, pointCount, extremalPoints+12, extremalPoints+13);
Sphere sphere = miniBall(extremalPoints, 14);
sphere.radius = computeSphereRadius(sphere.center, pointArray, pointCount);
nvDebugCheck(allInside(sphere, pointArray, pointCount));
return sphere;
}

View file

@ -1,43 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_MATH_SPHERE_H
#define NV_MATH_SPHERE_H
#include "Vector.h"
namespace nv
{
class Sphere
{
public:
Sphere() {}
Sphere(Vector3::Arg center, float radius) : center(center), radius(radius) {}
Sphere(Vector3::Arg center) : center(center), radius(0.0f) {}
Sphere(Vector3::Arg p0, Vector3::Arg p1);
Sphere(Vector3::Arg p0, Vector3::Arg p1, Vector3::Arg p2);
Sphere(Vector3::Arg p0, Vector3::Arg p1, Vector3::Arg p2, Vector3::Arg p3);
Vector3 center;
float radius;
};
// Returns negative values if point is inside.
float distanceSquared(const Sphere & sphere, const Vector3 &point);
// Welz's algorithm. Fairly slow, recursive implementation uses large stack.
Sphere miniBall(const Vector3 * pointArray, uint pointCount);
Sphere approximateSphere_Ritter(const Vector3 * pointArray, uint pointCount);
Sphere approximateSphere_AABB(const Vector3 * pointArray, uint pointCount);
Sphere approximateSphere_EPOS6(const Vector3 * pointArray, uint pointCount);
Sphere approximateSphere_EPOS14(const Vector3 * pointArray, uint pointCount);
} // nv namespace
#endif // NV_MATH_SPHERE_H

View file

@ -1,54 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#include "TypeSerialization.h"
#include "nvcore/Stream.h"
#include "nvmath/Vector.h"
#include "nvmath/Matrix.h"
#include "nvmath/Quaternion.h"
#include "nvmath/Basis.h"
#include "nvmath/Box.h"
#include "nvmath/Plane.inl"
using namespace nv;
Stream & nv::operator<< (Stream & s, Vector2 & v)
{
return s << v.x << v.y;
}
Stream & nv::operator<< (Stream & s, Vector3 & v)
{
return s << v.x << v.y << v.z;
}
Stream & nv::operator<< (Stream & s, Vector4 & v)
{
return s << v.x << v.y << v.z << v.w;
}
Stream & nv::operator<< (Stream & s, Matrix & m)
{
return s;
}
Stream & nv::operator<< (Stream & s, Quaternion & q)
{
return s << q.x << q.y << q.z << q.w;
}
Stream & nv::operator<< (Stream & s, Basis & basis)
{
return s << basis.tangent << basis.bitangent << basis.normal;
}
Stream & nv::operator<< (Stream & s, Box & box)
{
return s << box.minCorner << box.maxCorner;
}
Stream & nv::operator<< (Stream & s, Plane & plane)
{
return s << plane.v;
}

View file

@ -1,35 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_MATH_TYPESERIALIZATION_H
#define NV_MATH_TYPESERIALIZATION_H
#include "nvmath.h"
namespace nv
{
class Stream;
class Vector2;
class Vector3;
class Vector4;
class Matrix;
class Quaternion;
class Basis;
class Box;
class Plane;
NVMATH_API Stream & operator<< (Stream & s, Vector2 & obj);
NVMATH_API Stream & operator<< (Stream & s, Vector3 & obj);
NVMATH_API Stream & operator<< (Stream & s, Vector4 & obj);
NVMATH_API Stream & operator<< (Stream & s, Matrix & obj);
NVMATH_API Stream & operator<< (Stream & s, Quaternion & obj);
NVMATH_API Stream & operator<< (Stream & s, Basis & obj);
NVMATH_API Stream & operator<< (Stream & s, Box & obj);
NVMATH_API Stream & operator<< (Stream & s, Plane & obj);
} // nv namespace
#endif // NV_MATH_TYPESERIALIZATION_H

View file

@ -1,4 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#include "Vector.h"
#include "Vector.inl"

View file

@ -1,149 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MATH_VECTOR_H
#define NV_MATH_VECTOR_H
#include "nvmath.h"
namespace nv
{
class NVMATH_CLASS Vector2
{
public:
typedef Vector2 const & Arg;
Vector2();
explicit Vector2(float f);
Vector2(float x, float y);
Vector2(Vector2::Arg v);
//template <typename T> explicit Vector2(const T & v) : x(v.x), y(v.y) {}
//template <typename T> operator T() const { return T(x, y); }
const Vector2 & operator=(Vector2::Arg v);
const float * ptr() const;
void set(float x, float y);
Vector2 operator-() const;
void operator+=(Vector2::Arg v);
void operator-=(Vector2::Arg v);
void operator*=(float s);
void operator*=(Vector2::Arg v);
friend bool operator==(Vector2::Arg a, Vector2::Arg b);
friend bool operator!=(Vector2::Arg a, Vector2::Arg b);
union {
struct {
float x, y;
};
float component[2];
};
};
class NVMATH_CLASS Vector3
{
public:
typedef Vector3 const & Arg;
Vector3();
explicit Vector3(float x);
//explicit Vector3(int x) : x(float(x)), y(float(x)), z(float(x)) {}
Vector3(float x, float y, float z);
Vector3(Vector2::Arg v, float z);
Vector3(Vector3::Arg v);
//template <typename T> explicit Vector3(const T & v) : x(v.x), y(v.y), z(v.z) {}
//template <typename T> operator T() const { return T(x, y, z); }
const Vector3 & operator=(Vector3::Arg v);
Vector2 xy() const;
const float * ptr() const;
void set(float x, float y, float z);
Vector3 operator-() const;
void operator+=(Vector3::Arg v);
void operator-=(Vector3::Arg v);
void operator*=(float s);
void operator/=(float s);
void operator*=(Vector3::Arg v);
void operator/=(Vector3::Arg v);
friend bool operator==(Vector3::Arg a, Vector3::Arg b);
friend bool operator!=(Vector3::Arg a, Vector3::Arg b);
union {
struct {
float x, y, z;
};
float component[3];
};
};
class NVMATH_CLASS Vector4
{
public:
typedef Vector4 const & Arg;
Vector4();
explicit Vector4(float x);
Vector4(float x, float y, float z, float w);
Vector4(Vector2::Arg v, float z, float w);
Vector4(Vector2::Arg v, Vector2::Arg u);
Vector4(Vector3::Arg v, float w);
Vector4(Vector4::Arg v);
// Vector4(const Quaternion & v);
//template <typename T> explicit Vector4(const T & v) : x(v.x), y(v.y), z(v.z), w(v.w) {}
//template <typename T> operator T() const { return T(x, y, z, w); }
const Vector4 & operator=(Vector4::Arg v);
Vector2 xy() const;
Vector2 zw() const;
Vector3 xyz() const;
const float * ptr() const;
void set(float x, float y, float z, float w);
Vector4 operator-() const;
void operator+=(Vector4::Arg v);
void operator-=(Vector4::Arg v);
void operator*=(float s);
void operator/=(float s);
void operator*=(Vector4::Arg v);
void operator/=(Vector4::Arg v);
friend bool operator==(Vector4::Arg a, Vector4::Arg b);
friend bool operator!=(Vector4::Arg a, Vector4::Arg b);
union {
struct {
float x, y, z, w;
};
float component[4];
};
};
} // nv namespace
// If we had these functions, they would be ambiguous, the compiler would not know which one to pick:
//template <typename T> Vector2 to(const T & v) { return Vector2(v.x, v.y); }
//template <typename T> Vector3 to(const T & v) { return Vector3(v.x, v.y, v.z); }
//template <typename T> Vector4 to(const T & v) { return Vector4(v.x, v.y, v.z, v.z); }
// We could use a cast operator so that we could infer the expected type, but that doesn't work the same way in all compilers and produces horrible error messages.
// Instead we simply have explicit casts:
template <typename T> T to(const nv::Vector2 & v) { NV_COMPILER_CHECK(sizeof(T) == sizeof(nv::Vector2)); return T(v.x, v.y); }
template <typename T> T to(const nv::Vector3 & v) { NV_COMPILER_CHECK(sizeof(T) == sizeof(nv::Vector3)); return T(v.x, v.y, v.z); }
template <typename T> T to(const nv::Vector4 & v) { NV_COMPILER_CHECK(sizeof(T) == sizeof(nv::Vector4)); return T(v.x, v.y, v.z, v.w); }
#endif // NV_MATH_VECTOR_H

View file

@ -1,919 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MATH_VECTOR_INL
#define NV_MATH_VECTOR_INL
#include "Vector.h"
#include "nvcore/Utils.h" // min, max
#include "nvcore/Hash.h" // hash
namespace nv
{
// Helpers to convert vector types. Assume T has x,y members and 2 argument constructor.
//template <typename T> T to(Vector2::Arg v) { return T(v.x, v.y); }
// Helpers to convert vector types. Assume T has x,y,z members and 3 argument constructor.
//template <typename T> T to(Vector3::Arg v) { return T(v.x, v.y, v.z); }
// Helpers to convert vector types. Assume T has x,y,z members and 3 argument constructor.
//template <typename T> T to(Vector4::Arg v) { return T(v.x, v.y, v.z, v.w); }
// Vector2
inline Vector2::Vector2() {}
inline Vector2::Vector2(float f) : x(f), y(f) {}
inline Vector2::Vector2(float x, float y) : x(x), y(y) {}
inline Vector2::Vector2(Vector2::Arg v) : x(v.x), y(v.y) {}
inline const Vector2 & Vector2::operator=(Vector2::Arg v)
{
x = v.x;
y = v.y;
return *this;
}
inline const float * Vector2::ptr() const
{
return &x;
}
inline void Vector2::set(float x, float y)
{
this->x = x;
this->y = y;
}
inline Vector2 Vector2::operator-() const
{
return Vector2(-x, -y);
}
inline void Vector2::operator+=(Vector2::Arg v)
{
x += v.x;
y += v.y;
}
inline void Vector2::operator-=(Vector2::Arg v)
{
x -= v.x;
y -= v.y;
}
inline void Vector2::operator*=(float s)
{
x *= s;
y *= s;
}
inline void Vector2::operator*=(Vector2::Arg v)
{
x *= v.x;
y *= v.y;
}
inline bool operator==(Vector2::Arg a, Vector2::Arg b)
{
return a.x == b.x && a.y == b.y;
}
inline bool operator!=(Vector2::Arg a, Vector2::Arg b)
{
return a.x != b.x || a.y != b.y;
}
// Vector3
inline Vector3::Vector3() {}
inline Vector3::Vector3(float f) : x(f), y(f), z(f) {}
inline Vector3::Vector3(float x, float y, float z) : x(x), y(y), z(z) {}
inline Vector3::Vector3(Vector2::Arg v, float z) : x(v.x), y(v.y), z(z) {}
inline Vector3::Vector3(Vector3::Arg v) : x(v.x), y(v.y), z(v.z) {}
inline const Vector3 & Vector3::operator=(Vector3::Arg v)
{
x = v.x;
y = v.y;
z = v.z;
return *this;
}
inline Vector2 Vector3::xy() const
{
return Vector2(x, y);
}
inline const float * Vector3::ptr() const
{
return &x;
}
inline void Vector3::set(float x, float y, float z)
{
this->x = x;
this->y = y;
this->z = z;
}
inline Vector3 Vector3::operator-() const
{
return Vector3(-x, -y, -z);
}
inline void Vector3::operator+=(Vector3::Arg v)
{
x += v.x;
y += v.y;
z += v.z;
}
inline void Vector3::operator-=(Vector3::Arg v)
{
x -= v.x;
y -= v.y;
z -= v.z;
}
inline void Vector3::operator*=(float s)
{
x *= s;
y *= s;
z *= s;
}
inline void Vector3::operator/=(float s)
{
float is = 1.0f / s;
x *= is;
y *= is;
z *= is;
}
inline void Vector3::operator*=(Vector3::Arg v)
{
x *= v.x;
y *= v.y;
z *= v.z;
}
inline void Vector3::operator/=(Vector3::Arg v)
{
x /= v.x;
y /= v.y;
z /= v.z;
}
inline bool operator==(Vector3::Arg a, Vector3::Arg b)
{
return a.x == b.x && a.y == b.y && a.z == b.z;
}
inline bool operator!=(Vector3::Arg a, Vector3::Arg b)
{
return a.x != b.x || a.y != b.y || a.z != b.z;
}
// Vector4
inline Vector4::Vector4() {}
inline Vector4::Vector4(float f) : x(f), y(f), z(f), w(f) {}
inline Vector4::Vector4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {}
inline Vector4::Vector4(Vector2::Arg v, float z, float w) : x(v.x), y(v.y), z(z), w(w) {}
inline Vector4::Vector4(Vector2::Arg v, Vector2::Arg u) : x(v.x), y(v.y), z(u.x), w(u.y) {}
inline Vector4::Vector4(Vector3::Arg v, float w) : x(v.x), y(v.y), z(v.z), w(w) {}
inline Vector4::Vector4(Vector4::Arg v) : x(v.x), y(v.y), z(v.z), w(v.w) {}
inline const Vector4 & Vector4::operator=(const Vector4 & v)
{
x = v.x;
y = v.y;
z = v.z;
w = v.w;
return *this;
}
inline Vector2 Vector4::xy() const
{
return Vector2(x, y);
}
inline Vector2 Vector4::zw() const
{
return Vector2(z, w);
}
inline Vector3 Vector4::xyz() const
{
return Vector3(x, y, z);
}
inline const float * Vector4::ptr() const
{
return &x;
}
inline void Vector4::set(float x, float y, float z, float w)
{
this->x = x;
this->y = y;
this->z = z;
this->w = w;
}
inline Vector4 Vector4::operator-() const
{
return Vector4(-x, -y, -z, -w);
}
inline void Vector4::operator+=(Vector4::Arg v)
{
x += v.x;
y += v.y;
z += v.z;
w += v.w;
}
inline void Vector4::operator-=(Vector4::Arg v)
{
x -= v.x;
y -= v.y;
z -= v.z;
w -= v.w;
}
inline void Vector4::operator*=(float s)
{
x *= s;
y *= s;
z *= s;
w *= s;
}
inline void Vector4::operator/=(float s)
{
x /= s;
y /= s;
z /= s;
w /= s;
}
inline void Vector4::operator*=(Vector4::Arg v)
{
x *= v.x;
y *= v.y;
z *= v.z;
w *= v.w;
}
inline void Vector4::operator/=(Vector4::Arg v)
{
x /= v.x;
y /= v.y;
z /= v.z;
w /= v.w;
}
inline bool operator==(Vector4::Arg a, Vector4::Arg b)
{
return a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w;
}
inline bool operator!=(Vector4::Arg a, Vector4::Arg b)
{
return a.x != b.x || a.y != b.y || a.z != b.z || a.w != b.w;
}
// Functions
// Vector2
inline Vector2 add(Vector2::Arg a, Vector2::Arg b)
{
return Vector2(a.x + b.x, a.y + b.y);
}
inline Vector2 operator+(Vector2::Arg a, Vector2::Arg b)
{
return add(a, b);
}
inline Vector2 sub(Vector2::Arg a, Vector2::Arg b)
{
return Vector2(a.x - b.x, a.y - b.y);
}
inline Vector2 operator-(Vector2::Arg a, Vector2::Arg b)
{
return sub(a, b);
}
inline Vector2 scale(Vector2::Arg v, float s)
{
return Vector2(v.x * s, v.y * s);
}
inline Vector2 scale(Vector2::Arg v, Vector2::Arg s)
{
return Vector2(v.x * s.x, v.y * s.y);
}
inline Vector2 operator*(Vector2::Arg v, float s)
{
return scale(v, s);
}
inline Vector2 operator*(Vector2::Arg v1, Vector2::Arg v2)
{
return Vector2(v1.x*v2.x, v1.y*v2.y);
}
inline Vector2 operator*(float s, Vector2::Arg v)
{
return scale(v, s);
}
inline Vector2 operator/(Vector2::Arg v, float s)
{
return scale(v, 1.0f/s);
}
inline Vector2 lerp(Vector2::Arg v1, Vector2::Arg v2, float t)
{
const float s = 1.0f - t;
return Vector2(v1.x * s + t * v2.x, v1.y * s + t * v2.y);
}
inline float dot(Vector2::Arg a, Vector2::Arg b)
{
return a.x * b.x + a.y * b.y;
}
inline float lengthSquared(Vector2::Arg v)
{
return v.x * v.x + v.y * v.y;
}
inline float length(Vector2::Arg v)
{
return sqrtf(lengthSquared(v));
}
inline float distance(Vector2::Arg a, Vector2::Arg b)
{
return length(a - b);
}
inline float inverseLength(Vector2::Arg v)
{
return 1.0f / sqrtf(lengthSquared(v));
}
inline bool isNormalized(Vector2::Arg v, float epsilon = NV_NORMAL_EPSILON)
{
return equal(length(v), 1, epsilon);
}
inline Vector2 normalize(Vector2::Arg v, float epsilon = NV_EPSILON)
{
float l = length(v);
nvDebugCheck(!isZero(l, epsilon));
Vector2 n = scale(v, 1.0f / l);
nvDebugCheck(isNormalized(n));
return n;
}
inline Vector2 normalizeSafe(Vector2::Arg v, Vector2::Arg fallback, float epsilon = NV_EPSILON)
{
float l = length(v);
if (isZero(l, epsilon)) {
return fallback;
}
return scale(v, 1.0f / l);
}
// Safe, branchless normalization from Andy Firth. All error checking ommitted.
// http://altdevblogaday.com/2011/08/21/practical-flt-point-tricks/
inline Vector2 normalizeFast(Vector2::Arg v)
{
const float very_small_float = 1.0e-037f;
float l = very_small_float + length(v);
return scale(v, 1.0f / l);
}
inline bool equal(Vector2::Arg v1, Vector2::Arg v2, float epsilon = NV_EPSILON)
{
return equal(v1.x, v2.x, epsilon) && equal(v1.y, v2.y, epsilon);
}
inline Vector2 min(Vector2::Arg a, Vector2::Arg b)
{
return Vector2(min(a.x, b.x), min(a.y, b.y));
}
inline Vector2 max(Vector2::Arg a, Vector2::Arg b)
{
return Vector2(max(a.x, b.x), max(a.y, b.y));
}
inline Vector2 clamp(Vector2::Arg v, float min, float max)
{
return Vector2(clamp(v.x, min, max), clamp(v.y, min, max));
}
inline Vector2 saturate(Vector2::Arg v)
{
return Vector2(saturate(v.x), saturate(v.y));
}
inline bool isFinite(Vector2::Arg v)
{
return isFinite(v.x) && isFinite(v.y);
}
inline Vector2 validate(Vector2::Arg v, Vector2::Arg fallback = Vector2(0.0f))
{
if (!isFinite(v)) return fallback;
Vector2 vf = v;
nv::floatCleanup(vf.component, 2);
return vf;
}
// Note, this is the area scaled by 2!
inline float triangleArea(Vector2::Arg v0, Vector2::Arg v1)
{
return (v0.x * v1.y - v0.y * v1.x); // * 0.5f;
}
inline float triangleArea(Vector2::Arg a, Vector2::Arg b, Vector2::Arg c)
{
// IC: While it may be appealing to use the following expression:
//return (c.x * a.y + a.x * b.y + b.x * c.y - b.x * a.y - c.x * b.y - a.x * c.y); // * 0.5f;
// That's actually a terrible idea. Small triangles far from the origin can end up producing fairly large floating point
// numbers and the results becomes very unstable and dependent on the order of the factors.
// Instead, it's preferable to subtract the vertices first, and multiply the resulting small values together. The result
// in this case is always much more accurate (as long as the triangle is small) and less dependent of the location of
// the triangle.
//return ((a.x - c.x) * (b.y - c.y) - (a.y - c.y) * (b.x - c.x)); // * 0.5f;
return triangleArea(a-c, b-c);
}
template <>
inline uint hash(const Vector2 & v, uint h)
{
return sdbmFloatHash(v.component, 2, h);
}
// Vector3
inline Vector3 add(Vector3::Arg a, Vector3::Arg b)
{
return Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
}
inline Vector3 add(Vector3::Arg a, float b)
{
return Vector3(a.x + b, a.y + b, a.z + b);
}
inline Vector3 operator+(Vector3::Arg a, Vector3::Arg b)
{
return add(a, b);
}
inline Vector3 operator+(Vector3::Arg a, float b)
{
return add(a, b);
}
inline Vector3 sub(Vector3::Arg a, Vector3::Arg b)
{
return Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
}
inline Vector3 sub(Vector3::Arg a, float b)
{
return Vector3(a.x - b, a.y - b, a.z - b);
}
inline Vector3 operator-(Vector3::Arg a, Vector3::Arg b)
{
return sub(a, b);
}
inline Vector3 operator-(Vector3::Arg a, float b)
{
return sub(a, b);
}
inline Vector3 cross(Vector3::Arg a, Vector3::Arg b)
{
return Vector3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
}
inline Vector3 scale(Vector3::Arg v, float s)
{
return Vector3(v.x * s, v.y * s, v.z * s);
}
inline Vector3 scale(Vector3::Arg v, Vector3::Arg s)
{
return Vector3(v.x * s.x, v.y * s.y, v.z * s.z);
}
inline Vector3 operator*(Vector3::Arg v, float s)
{
return scale(v, s);
}
inline Vector3 operator*(float s, Vector3::Arg v)
{
return scale(v, s);
}
inline Vector3 operator*(Vector3::Arg v, Vector3::Arg s)
{
return scale(v, s);
}
inline Vector3 operator/(Vector3::Arg v, float s)
{
return scale(v, 1.0f/s);
}
/*inline Vector3 add_scaled(Vector3::Arg a, Vector3::Arg b, float s)
{
return Vector3(a.x + b.x * s, a.y + b.y * s, a.z + b.z * s);
}*/
inline Vector3 lerp(Vector3::Arg v1, Vector3::Arg v2, float t)
{
const float s = 1.0f - t;
return Vector3(v1.x * s + t * v2.x, v1.y * s + t * v2.y, v1.z * s + t * v2.z);
}
inline float dot(Vector3::Arg a, Vector3::Arg b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
inline float lengthSquared(Vector3::Arg v)
{
return v.x * v.x + v.y * v.y + v.z * v.z;
}
inline float length(Vector3::Arg v)
{
return sqrtf(lengthSquared(v));
}
inline float distance(Vector3::Arg a, Vector3::Arg b)
{
return length(a - b);
}
inline float distanceSquared(Vector3::Arg a, Vector3::Arg b)
{
return lengthSquared(a - b);
}
inline float inverseLength(Vector3::Arg v)
{
return 1.0f / sqrtf(lengthSquared(v));
}
inline bool isNormalized(Vector3::Arg v, float epsilon = NV_NORMAL_EPSILON)
{
return equal(length(v), 1, epsilon);
}
inline Vector3 normalize(Vector3::Arg v, float epsilon = NV_EPSILON)
{
float l = length(v);
nvDebugCheck(!isZero(l, epsilon));
Vector3 n = scale(v, 1.0f / l);
nvDebugCheck(isNormalized(n));
return n;
}
inline Vector3 normalizeSafe(Vector3::Arg v, Vector3::Arg fallback, float epsilon = NV_EPSILON)
{
float l = length(v);
if (isZero(l, epsilon)) {
return fallback;
}
return scale(v, 1.0f / l);
}
// Safe, branchless normalization from Andy Firth. All error checking ommitted.
// http://altdevblogaday.com/2011/08/21/practical-flt-point-tricks/
inline Vector3 normalizeFast(Vector3::Arg v)
{
const float very_small_float = 1.0e-037f;
float l = very_small_float + length(v);
return scale(v, 1.0f / l);
}
inline bool equal(Vector3::Arg v1, Vector3::Arg v2, float epsilon = NV_EPSILON)
{
return equal(v1.x, v2.x, epsilon) && equal(v1.y, v2.y, epsilon) && equal(v1.z, v2.z, epsilon);
}
inline Vector3 min(Vector3::Arg a, Vector3::Arg b)
{
return Vector3(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z));
}
inline Vector3 max(Vector3::Arg a, Vector3::Arg b)
{
return Vector3(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z));
}
inline Vector3 clamp(Vector3::Arg v, float min, float max)
{
return Vector3(clamp(v.x, min, max), clamp(v.y, min, max), clamp(v.z, min, max));
}
inline Vector3 saturate(Vector3::Arg v)
{
return Vector3(saturate(v.x), saturate(v.y), saturate(v.z));
}
inline Vector3 floor(Vector3::Arg v)
{
return Vector3(floorf(v.x), floorf(v.y), floorf(v.z));
}
inline Vector3 ceil(Vector3::Arg v)
{
return Vector3(ceilf(v.x), ceilf(v.y), ceilf(v.z));
}
inline bool isFinite(Vector3::Arg v)
{
return isFinite(v.x) && isFinite(v.y) && isFinite(v.z);
}
inline Vector3 validate(Vector3::Arg v, Vector3::Arg fallback = Vector3(0.0f))
{
if (!isFinite(v)) return fallback;
Vector3 vf = v;
nv::floatCleanup(vf.component, 3);
return vf;
}
inline Vector3 reflect(Vector3::Arg v, Vector3::Arg n)
{
return v - (2 * dot(v, n)) * n;
}
template <>
inline uint hash(const Vector3 & v, uint h)
{
return sdbmFloatHash(v.component, 3, h);
}
// Vector4
inline Vector4 add(Vector4::Arg a, Vector4::Arg b)
{
return Vector4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
}
inline Vector4 operator+(Vector4::Arg a, Vector4::Arg b)
{
return add(a, b);
}
inline Vector4 sub(Vector4::Arg a, Vector4::Arg b)
{
return Vector4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w);
}
inline Vector4 operator-(Vector4::Arg a, Vector4::Arg b)
{
return sub(a, b);
}
inline Vector4 scale(Vector4::Arg v, float s)
{
return Vector4(v.x * s, v.y * s, v.z * s, v.w * s);
}
inline Vector4 scale(Vector4::Arg v, Vector4::Arg s)
{
return Vector4(v.x * s.x, v.y * s.y, v.z * s.z, v.w * s.w);
}
inline Vector4 operator*(Vector4::Arg v, float s)
{
return scale(v, s);
}
inline Vector4 operator*(float s, Vector4::Arg v)
{
return scale(v, s);
}
inline Vector4 operator*(Vector4::Arg v, Vector4::Arg s)
{
return scale(v, s);
}
inline Vector4 operator/(Vector4::Arg v, float s)
{
return scale(v, 1.0f/s);
}
/*inline Vector4 add_scaled(Vector4::Arg a, Vector4::Arg b, float s)
{
return Vector4(a.x + b.x * s, a.y + b.y * s, a.z + b.z * s, a.w + b.w * s);
}*/
inline Vector4 lerp(Vector4::Arg v1, Vector4::Arg v2, float t)
{
const float s = 1.0f - t;
return Vector4(v1.x * s + t * v2.x, v1.y * s + t * v2.y, v1.z * s + t * v2.z, v1.w * s + t * v2.w);
}
inline float dot(Vector4::Arg a, Vector4::Arg b)
{
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
inline float lengthSquared(Vector4::Arg v)
{
return v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w;
}
inline float length(Vector4::Arg v)
{
return sqrtf(lengthSquared(v));
}
inline float inverseLength(Vector4::Arg v)
{
return 1.0f / sqrtf(lengthSquared(v));
}
inline bool isNormalized(Vector4::Arg v, float epsilon = NV_NORMAL_EPSILON)
{
return equal(length(v), 1, epsilon);
}
inline Vector4 normalize(Vector4::Arg v, float epsilon = NV_EPSILON)
{
float l = length(v);
nvDebugCheck(!isZero(l, epsilon));
Vector4 n = scale(v, 1.0f / l);
nvDebugCheck(isNormalized(n));
return n;
}
inline Vector4 normalizeSafe(Vector4::Arg v, Vector4::Arg fallback, float epsilon = NV_EPSILON)
{
float l = length(v);
if (isZero(l, epsilon)) {
return fallback;
}
return scale(v, 1.0f / l);
}
// Safe, branchless normalization from Andy Firth. All error checking ommitted.
// http://altdevblogaday.com/2011/08/21/practical-flt-point-tricks/
inline Vector4 normalizeFast(Vector4::Arg v)
{
const float very_small_float = 1.0e-037f;
float l = very_small_float + length(v);
return scale(v, 1.0f / l);
}
inline bool equal(Vector4::Arg v1, Vector4::Arg v2, float epsilon = NV_EPSILON)
{
return equal(v1.x, v2.x, epsilon) && equal(v1.y, v2.y, epsilon) && equal(v1.z, v2.z, epsilon) && equal(v1.w, v2.w, epsilon);
}
inline Vector4 min(Vector4::Arg a, Vector4::Arg b)
{
return Vector4(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z), min(a.w, b.w));
}
inline Vector4 max(Vector4::Arg a, Vector4::Arg b)
{
return Vector4(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z), max(a.w, b.w));
}
inline Vector4 clamp(Vector4::Arg v, float min, float max)
{
return Vector4(clamp(v.x, min, max), clamp(v.y, min, max), clamp(v.z, min, max), clamp(v.w, min, max));
}
inline Vector4 saturate(Vector4::Arg v)
{
return Vector4(saturate(v.x), saturate(v.y), saturate(v.z), saturate(v.w));
}
inline bool isFinite(Vector4::Arg v)
{
return isFinite(v.x) && isFinite(v.y) && isFinite(v.z) && isFinite(v.w);
}
inline Vector4 validate(Vector4::Arg v, Vector4::Arg fallback = Vector4(0.0f))
{
if (!isFinite(v)) return fallback;
Vector4 vf = v;
nv::floatCleanup(vf.component, 4);
return vf;
}
template <>
inline uint hash(const Vector4 & v, uint h)
{
return sdbmFloatHash(v.component, 4, h);
}
#if NV_OS_IOS // LLVM is not happy with implicit conversion of immediate constants to float
//int:
inline Vector2 scale(Vector2::Arg v, int s)
{
return Vector2(v.x * s, v.y * s);
}
inline Vector2 operator*(Vector2::Arg v, int s)
{
return scale(v, s);
}
inline Vector2 operator*(int s, Vector2::Arg v)
{
return scale(v, s);
}
inline Vector2 operator/(Vector2::Arg v, int s)
{
return scale(v, 1.0f/s);
}
inline Vector3 scale(Vector3::Arg v, int s)
{
return Vector3(v.x * s, v.y * s, v.z * s);
}
inline Vector3 operator*(Vector3::Arg v, int s)
{
return scale(v, s);
}
inline Vector3 operator*(int s, Vector3::Arg v)
{
return scale(v, s);
}
inline Vector3 operator/(Vector3::Arg v, int s)
{
return scale(v, 1.0f/s);
}
inline Vector4 scale(Vector4::Arg v, int s)
{
return Vector4(v.x * s, v.y * s, v.z * s, v.w * s);
}
inline Vector4 operator*(Vector4::Arg v, int s)
{
return scale(v, s);
}
inline Vector4 operator*(int s, Vector4::Arg v)
{
return scale(v, s);
}
inline Vector4 operator/(Vector4::Arg v, int s)
{
return scale(v, 1.0f/s);
}
//double:
inline Vector3 operator*(Vector3::Arg v, double s)
{
return scale(v, (float)s);
}
inline Vector3 operator*(double s, Vector3::Arg v)
{
return scale(v, (float)s);
}
inline Vector3 operator/(Vector3::Arg v, double s)
{
return scale(v, 1.f/((float)s));
}
#endif //NV_OS_IOS
} // nv namespace
#endif // NV_MATH_VECTOR_INL

View file

@ -1,261 +0,0 @@
// This code is in the public domain -- castano@gmail.com
#pragma once
#ifndef NV_MATH_FTOI_H
#define NV_MATH_FTOI_H
#include "nvmath/nvmath.h"
#include <math.h>
namespace nv
{
// Optimized float to int conversions. See:
// http://cbloomrants.blogspot.com/2009/01/01-17-09-float-to-int.html
// http://www.stereopsis.com/sree/fpu2006.html
// http://assemblyrequired.crashworks.org/2009/01/12/why-you-should-never-cast-floats-to-ints/
// http://chrishecker.com/Miscellaneous_Technical_Articles#Floating_Point
union DoubleAnd64 {
uint64 i;
double d;
};
static const double floatutil_xs_doublemagic = (6755399441055744.0); // 2^52 * 1.5
static const double floatutil_xs_doublemagicdelta = (1.5e-8); // almost .5f = .5f + 1e^(number of exp bit)
static const double floatutil_xs_doublemagicroundeps = (0.5f - floatutil_xs_doublemagicdelta); // almost .5f = .5f - 1e^(number of exp bit)
NV_FORCEINLINE int ftoi_round_xs(double val, double magic) {
#if 1
DoubleAnd64 dunion;
dunion.d = val + magic;
return (int32) dunion.i; // just cast to grab the bottom bits
#else
val += magic;
return ((int*)&val)[0]; // @@ Assumes little endian.
#endif
}
NV_FORCEINLINE int ftoi_round_xs(float val) {
return ftoi_round_xs(val, floatutil_xs_doublemagic);
}
NV_FORCEINLINE int ftoi_floor_xs(float val) {
return ftoi_round_xs(val - floatutil_xs_doublemagicroundeps, floatutil_xs_doublemagic);
}
NV_FORCEINLINE int ftoi_ceil_xs(float val) {
return ftoi_round_xs(val + floatutil_xs_doublemagicroundeps, floatutil_xs_doublemagic);
}
NV_FORCEINLINE int ftoi_trunc_xs(float val) {
return (val<0) ? ftoi_ceil_xs(val) : ftoi_floor_xs(val);
}
// -- GODOT start --
//#if NV_CPU_X86 || NV_CPU_X86_64
#if NV_USE_SSE
// -- GODOT end --
NV_FORCEINLINE int ftoi_round_sse(float f) {
return _mm_cvt_ss2si(_mm_set_ss(f));
}
NV_FORCEINLINE int ftoi_trunc_sse(float f) {
return _mm_cvtt_ss2si(_mm_set_ss(f));
}
#endif
#if NV_USE_SSE
NV_FORCEINLINE int ftoi_round(float val) {
return ftoi_round_sse(val);
}
NV_FORCEINLINE int ftoi_trunc(float f) {
return ftoi_trunc_sse(f);
}
// We can probably do better than this. See for example:
// http://dss.stephanierct.com/DevBlog/?p=8
NV_FORCEINLINE int ftoi_floor(float val) {
return ftoi_round(floorf(val));
}
NV_FORCEINLINE int ftoi_ceil(float val) {
return ftoi_round(ceilf(val));
}
#else
// In theory this should work with any double floating point math implementation, but it appears that MSVC produces incorrect code
// when SSE2 is targeted and fast math is enabled (/arch:SSE2 & /fp:fast). These problems go away with /fp:precise, which is the default mode.
NV_FORCEINLINE int ftoi_round(float val) {
return ftoi_round_xs(val);
}
NV_FORCEINLINE int ftoi_floor(float val) {
return ftoi_floor_xs(val);
}
NV_FORCEINLINE int ftoi_ceil(float val) {
return ftoi_ceil_xs(val);
}
NV_FORCEINLINE int ftoi_trunc(float f) {
return ftoi_trunc_xs(f);
}
#endif
inline void test_ftoi() {
// Round to nearest integer.
nvCheck(ftoi_round(0.1f) == 0);
nvCheck(ftoi_round(0.6f) == 1);
nvCheck(ftoi_round(-0.2f) == 0);
nvCheck(ftoi_round(-0.7f) == -1);
nvCheck(ftoi_round(10.1f) == 10);
nvCheck(ftoi_round(10.6f) == 11);
nvCheck(ftoi_round(-90.1f) == -90);
nvCheck(ftoi_round(-90.6f) == -91);
nvCheck(ftoi_round(0) == 0);
nvCheck(ftoi_round(1) == 1);
nvCheck(ftoi_round(-1) == -1);
nvCheck(ftoi_round(0.5f) == 0); // How are midpoints rounded? Bankers rounding.
nvCheck(ftoi_round(1.5f) == 2);
nvCheck(ftoi_round(2.5f) == 2);
nvCheck(ftoi_round(3.5f) == 4);
nvCheck(ftoi_round(4.5f) == 4);
nvCheck(ftoi_round(-0.5f) == 0);
nvCheck(ftoi_round(-1.5f) == -2);
// Truncation (round down if > 0, round up if < 0).
nvCheck(ftoi_trunc(0.1f) == 0);
nvCheck(ftoi_trunc(0.6f) == 0);
nvCheck(ftoi_trunc(-0.2f) == 0);
nvCheck(ftoi_trunc(-0.7f) == 0); // @@ When using /arch:SSE2 in Win32, msvc produce wrong code for this one. It is skipping the addition.
nvCheck(ftoi_trunc(1.99f) == 1);
nvCheck(ftoi_trunc(-1.2f) == -1);
// Floor (round down).
nvCheck(ftoi_floor(0.1f) == 0);
nvCheck(ftoi_floor(0.6f) == 0);
nvCheck(ftoi_floor(-0.2f) == -1);
nvCheck(ftoi_floor(-0.7f) == -1);
nvCheck(ftoi_floor(1.99f) == 1);
nvCheck(ftoi_floor(-1.2f) == -2);
nvCheck(ftoi_floor(0) == 0);
nvCheck(ftoi_floor(1) == 1);
nvCheck(ftoi_floor(-1) == -1);
nvCheck(ftoi_floor(2) == 2);
nvCheck(ftoi_floor(-2) == -2);
// Ceil (round up).
nvCheck(ftoi_ceil(0.1f) == 1);
nvCheck(ftoi_ceil(0.6f) == 1);
nvCheck(ftoi_ceil(-0.2f) == 0);
nvCheck(ftoi_ceil(-0.7f) == 0);
nvCheck(ftoi_ceil(1.99f) == 2);
nvCheck(ftoi_ceil(-1.2f) == -1);
nvCheck(ftoi_ceil(0) == 0);
nvCheck(ftoi_ceil(1) == 1);
nvCheck(ftoi_ceil(-1) == -1);
nvCheck(ftoi_ceil(2) == 2);
nvCheck(ftoi_ceil(-2) == -2);
}
// Safe versions using standard casts.
inline int iround(float f)
{
return ftoi_round(f);
//return int(floorf(f + 0.5f));
}
inline int iround(double f)
{
return int(::floor(f + 0.5));
}
inline int ifloor(float f)
{
return ftoi_floor(f);
//return int(floorf(f));
}
inline int iceil(float f)
{
return int(ceilf(f));
}
// I'm always confused about which quantizer to use. I think we should choose a quantizer based on how the values are expanded later and this is generally using the 'exact endpoints' rule.
// Some notes from cbloom: http://cbloomrants.blogspot.com/2011/07/07-26-11-pixel-int-to-float-options.html
// Quantize a float in the [0,1] range, using exact end points or uniform bins.
inline float quantizeFloat(float x, uint bits, bool exactEndPoints = true) {
nvDebugCheck(bits <= 16);
float range = float(1 << bits);
if (exactEndPoints) {
return floorf(x * (range-1) + 0.5f) / (range-1);
}
else {
return (floorf(x * range) + 0.5f) / range;
}
}
// This is the most common rounding mode:
//
// 0 1 2 3
// |___|_______|_______|___|
// 0 1
//
// You get that if you take the unit floating point number multiply by 'N-1' and round to nearest. That is, `i = round(f * (N-1))`.
// You reconstruct the original float dividing by 'N-1': `f = i / (N-1)`
// 0 1 2 3
// |_____|_____|_____|_____|
// 0 1
/*enum BinningMode {
RoundMode_ExactEndPoints,
RoundMode_UniformBins,
};*/
template <int N>
inline uint unitFloatToFixed(float f) {
return ftoi_round(f * ((1<<N)-1));
}
inline uint8 unitFloatToFixed8(float f) {
return (uint8)unitFloatToFixed<8>(f);
}
inline uint16 unitFloatToFixed16(float f) {
return (uint16)unitFloatToFixed<16>(f);
}
} // nv
#endif // NV_MATH_FTOI_H

View file

@ -1,342 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MATH_H
#define NV_MATH_H
#include "nvcore/nvcore.h"
#include "nvcore/Debug.h" // nvDebugCheck
#include "nvcore/Utils.h" // max, clamp
#include <math.h>
#if NV_OS_WIN32 || NV_OS_XBOX || NV_OS_DURANGO
#include <float.h> // finite, isnan
#endif
// -- GODOT start --
//#if NV_CPU_X86 || NV_CPU_X86_64
// //#include <intrin.h>
// #include <xmmintrin.h>
//#endif
// -- GODOT end --
// Function linkage
#if NVMATH_SHARED
#ifdef NVMATH_EXPORTS
#define NVMATH_API DLL_EXPORT
#define NVMATH_CLASS DLL_EXPORT_CLASS
#else
#define NVMATH_API DLL_IMPORT
#define NVMATH_CLASS DLL_IMPORT
#endif
#else // NVMATH_SHARED
#define NVMATH_API
#define NVMATH_CLASS
#endif // NVMATH_SHARED
// Set some reasonable defaults.
#ifndef NV_USE_ALTIVEC
# define NV_USE_ALTIVEC NV_CPU_PPC
//# define NV_USE_ALTIVEC defined(__VEC__)
#endif
#ifndef NV_USE_SSE
# if NV_CPU_X86_64
// x64 always supports at least SSE2
# define NV_USE_SSE 2
# elif NV_CC_MSVC && defined(_M_IX86_FP)
// Also on x86 with the /arch:SSE flag in MSVC.
# define NV_USE_SSE _M_IX86_FP // 1=SSE, 2=SS2
# elif defined(__SSE__)
# define NV_USE_SSE 1
# elif defined(__SSE2__)
# define NV_USE_SSE 2
# else
// Otherwise we assume no SSE.
# define NV_USE_SSE 0
# endif
#endif
// Internally set NV_USE_SIMD when either altivec or sse is available.
#if NV_USE_ALTIVEC && NV_USE_SSE
# error "Cannot enable both altivec and sse!"
#endif
// -- GODOT start --
#if NV_USE_SSE
//#include <intrin.h>
#include <xmmintrin.h>
#endif
// -- GODOT end --
#ifndef PI
#define PI float(3.1415926535897932384626433833)
#endif
#define NV_EPSILON (0.0001f)
#define NV_NORMAL_EPSILON (0.001f)
/*
#define SQ(r) ((r)*(r))
#define SIGN_BITMASK 0x80000000
/// Integer representation of a floating-point value.
#define IR(x) ((uint32 &)(x))
/// Absolute integer representation of a floating-point value
#define AIR(x) (IR(x) & 0x7fffffff)
/// Floating-point representation of an integer value.
#define FR(x) ((float&)(x))
/// Integer-based comparison of a floating point value.
/// Don't use it blindly, it can be faster or slower than the FPU comparison, depends on the context.
#define IS_NEGATIVE_FLOAT(x) (IR(x)&SIGN_BITMASK)
*/
extern "C" inline double sqrt_assert(const double f)
{
nvDebugCheck(f >= 0.0f);
return sqrt(f);
}
inline float sqrtf_assert(const float f)
{
nvDebugCheck(f >= 0.0f);
return sqrtf(f);
}
extern "C" inline double acos_assert(const double f)
{
nvDebugCheck(f >= -1.0f && f <= 1.0f);
return acos(f);
}
inline float acosf_assert(const float f)
{
nvDebugCheck(f >= -1.0f && f <= 1.0f);
return acosf(f);
}
extern "C" inline double asin_assert(const double f)
{
nvDebugCheck(f >= -1.0f && f <= 1.0f);
return asin(f);
}
inline float asinf_assert(const float f)
{
nvDebugCheck(f >= -1.0f && f <= 1.0f);
return asinf(f);
}
// Replace default functions with asserting ones.
#if !NV_CC_MSVC || (NV_CC_MSVC && (_MSC_VER < 1700)) // IC: Apparently this was causing problems in Visual Studio 2012. See Issue 194: https://code.google.com/p/nvidia-texture-tools/issues/detail?id=194
#define sqrt sqrt_assert
#define sqrtf sqrtf_assert
#define acos acos_assert
#define acosf acosf_assert
#define asin asin_assert
#define asinf asinf_assert
#endif
#if NV_CC_MSVC
NV_FORCEINLINE float log2f(float x)
{
nvCheck(x >= 0);
return logf(x) / logf(2.0f);
}
NV_FORCEINLINE float exp2f(float x)
{
return powf(2.0f, x);
}
#endif
namespace nv
{
inline float toRadian(float degree) { return degree * (PI / 180.0f); }
inline float toDegree(float radian) { return radian * (180.0f / PI); }
// Robust floating point comparisons:
// http://realtimecollisiondetection.net/blog/?p=89
inline bool equal(const float f0, const float f1, const float epsilon = NV_EPSILON)
{
//return fabs(f0-f1) <= epsilon;
return fabs(f0-f1) <= epsilon * max3(1.0f, fabsf(f0), fabsf(f1));
}
inline bool isZero(const float f, const float epsilon = NV_EPSILON)
{
return fabs(f) <= epsilon;
}
inline bool isFinite(const float f)
{
#if NV_OS_WIN32 || NV_OS_XBOX || NV_OS_DURANGO
return _finite(f) != 0;
#elif NV_OS_DARWIN || NV_OS_FREEBSD || NV_OS_OPENBSD || NV_OS_ORBIS || NV_OS_LINUX
return isfinite(f);
#else
# error "isFinite not supported"
#endif
//return std::isfinite (f);
//return finite (f);
}
inline bool isNan(const float f)
{
#if NV_OS_WIN32 || NV_OS_XBOX || NV_OS_DURANGO
return _isnan(f) != 0;
#elif NV_OS_DARWIN || NV_OS_FREEBSD || NV_OS_OPENBSD || NV_OS_ORBIS || NV_OS_LINUX
return isnan(f);
#else
# error "isNan not supported"
#endif
}
inline uint log2(uint32 i)
{
uint32 value = 0;
while( i >>= 1 ) value++;
return value;
}
inline uint log2(uint64 i)
{
uint64 value = 0;
while (i >>= 1) value++;
return U32(value);
}
inline float lerp(float f0, float f1, float t)
{
const float s = 1.0f - t;
return f0 * s + f1 * t;
}
inline float square(float f) { return f * f; }
inline int square(int i) { return i * i; }
inline float cube(float f) { return f * f * f; }
inline int cube(int i) { return i * i * i; }
inline float frac(float f)
{
return f - floor(f);
}
inline float floatRound(float f)
{
return floorf(f + 0.5f);
}
// Eliminates negative zeros from a float array.
inline void floatCleanup(float * fp, int n)
{
for (int i = 0; i < n; i++) {
//nvDebugCheck(isFinite(fp[i]));
union { float f; uint32 i; } x = { fp[i] };
if (x.i == 0x80000000) fp[i] = 0.0f;
}
}
inline float saturate(float f) {
return clamp(f, 0.0f, 1.0f);
}
inline float linearstep(float edge0, float edge1, float x) {
// Scale, bias and saturate x to 0..1 range
return saturate((x - edge0) / (edge1 - edge0));
}
inline float smoothstep(float edge0, float edge1, float x) {
x = linearstep(edge0, edge1, x);
// Evaluate polynomial
return x*x*(3 - 2*x);
}
inline int sign(float a)
{
return (a > 0) - (a < 0);
//if (a > 0.0f) return 1;
//if (a < 0.0f) return -1;
//return 0;
}
union Float754 {
unsigned int raw;
float value;
struct {
#if NV_BIG_ENDIAN
unsigned int negative:1;
unsigned int biasedexponent:8;
unsigned int mantissa:23;
#else
unsigned int mantissa:23;
unsigned int biasedexponent:8;
unsigned int negative:1;
#endif
} field;
};
// Return the exponent of x ~ Floor(Log2(x))
inline int floatExponent(float x)
{
Float754 f;
f.value = x;
return (f.field.biasedexponent - 127);
}
// FloatRGB9E5
union Float3SE {
uint32 v;
struct {
#if NV_BIG_ENDIAN
uint32 e : 5;
uint32 zm : 9;
uint32 ym : 9;
uint32 xm : 9;
#else
uint32 xm : 9;
uint32 ym : 9;
uint32 zm : 9;
uint32 e : 5;
#endif
};
};
// FloatR11G11B10
union Float3PK {
uint32 v;
struct {
#if NV_BIG_ENDIAN
uint32 ze : 5;
uint32 zm : 5;
uint32 ye : 5;
uint32 ym : 6;
uint32 xe : 5;
uint32 xm : 6;
#else
uint32 xm : 6;
uint32 xe : 5;
uint32 ym : 6;
uint32 ye : 5;
uint32 zm : 5;
uint32 ze : 5;
#endif
};
};
} // nv
#endif // NV_MATH_H

View file

@ -1,19 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#include "BaseMesh.h"
#include "Stream.h"
#include "nvmath/TypeSerialization.h"
namespace nv
{
static Stream & operator<< (Stream & s, BaseMesh::Vertex & vertex)
{
return s << vertex.id << vertex.pos << vertex.nor << vertex.tex;
}
Stream & operator<< (Stream & s, BaseMesh & mesh)
{
return s << mesh.m_vertexArray;
}
}

View file

@ -1,72 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_MESH_BASEMESH_H
#define NV_MESH_BASEMESH_H
#include "nvmesh.h"
#include "nvmath/Vector.h"
#include "nvcore/Array.h"
#include "nvcore/Hash.h"
namespace nv
{
/// Base mesh without connectivity.
class BaseMesh
{
public:
struct Vertex;
BaseMesh() {}
BaseMesh(uint vertexNum) :
m_vertexArray(vertexNum) {}
// Vertex methods.
uint vertexCount() const { return m_vertexArray.count(); }
const Vertex & vertexAt(uint i) const { return m_vertexArray[i]; }
Vertex & vertexAt(uint i) { return m_vertexArray[i]; }
const Array<Vertex> & vertices() const { return m_vertexArray; }
Array<Vertex> & vertices() { return m_vertexArray; }
friend Stream & operator<< (Stream & s, BaseMesh & obj);
protected:
Array<Vertex> m_vertexArray;
};
/// BaseMesh vertex.
struct BaseMesh::Vertex
{
Vertex() : id(NIL), pos(0.0f), nor(0.0f), tex(0.0f) {}
uint id; // @@ Vertex should be an index into the vertex data.
Vector3 pos;
Vector3 nor;
Vector2 tex;
};
inline bool operator==(const BaseMesh::Vertex & a, const BaseMesh::Vertex & b)
{
return a.pos == b.pos && a.nor == b.nor && a.tex == b.tex;
}
inline bool operator!=(const BaseMesh::Vertex & a, const BaseMesh::Vertex & b)
{
return a.pos != b.pos && a.nor != b.nor && a.tex != b.tex;
}
template <> struct Hash<BaseMesh::Vertex>
{
uint operator()(const BaseMesh::Vertex & v) const
{
return Hash<Vector3>()(v.pos);
}
};
} // nv namespace
#endif // NV_MESH_BASEMESH_H

File diff suppressed because it is too large Load diff

View file

@ -1,119 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MESH_MESHBUILDER_H
#define NV_MESH_MESHBUILDER_H
#include "nvmesh.h"
#include "nvcore/Array.h"
#include "nvmath/Vector.h"
namespace nv
{
class String;
class TriMesh;
class QuadTriMesh;
namespace HalfEdge { class Mesh; }
/// Mesh builder is a helper class for importers.
/// Ideally it should handle any vertex data, but for now it only accepts positions,
/// normals and texcoords.
class MeshBuilder
{
NV_FORBID_COPY(MeshBuilder);
NV_FORBID_HEAPALLOC();
public:
MeshBuilder();
~MeshBuilder();
// Builder methods.
uint addPosition(const Vector3 & v);
uint addNormal(const Vector3 & v);
uint addTexCoord(const Vector2 & v, uint set = 0);
uint addColor(const Vector4 & v, uint set = 0);
void beginGroup(uint id);
void endGroup();
uint addMaterial(const char * name);
void beginMaterial(uint id);
void endMaterial();
void beginPolygon(uint id = 0);
uint addVertex(uint p, uint n = NIL, uint t0 = NIL, uint t1 = NIL, uint c0 = NIL, uint c1 = NIL, uint c2 = NIL);
uint addVertex(const Vector3 & p);
//uint addVertex(const Vector3 & p, const Vector3 & n, const Vector2 & t0 = Vector2(0), const Vector2 & t1 = Vector2(0), const Vector4 & c0 = Vector4(0), const Vector4 & c1 = Vector4(0));
bool endPolygon();
uint weldPositions();
uint weldNormals();
uint weldTexCoords(uint set = 0);
uint weldColors(uint set = 0);
void weldVertices();
void optimize(); // eliminate duplicate components and duplicate vertices.
void removeUnusedMaterials(Array<uint> & newMaterialId);
void sortFacesByGroup();
void sortFacesByMaterial();
void done();
void reset();
// Hints.
void hintTriangleCount(uint count);
void hintVertexCount(uint count);
void hintPositionCount(uint count);
void hintNormalCount(uint count);
void hintTexCoordCount(uint count, uint set = 0);
void hintColorCount(uint count, uint set = 0);
// Helpers.
void addTriangle(uint v0, uint v1, uint v2);
void addQuad(uint v0, uint v1, uint v2, uint v3);
// Get result.
TriMesh * buildTriMesh() const;
QuadTriMesh * buildQuadTriMesh() const;
enum Error {
Error_None,
Error_NonManifoldEdge,
Error_NonManifoldVertex,
};
HalfEdge::Mesh * buildHalfEdgeMesh(bool weldPositions, Error * error = NULL, Array<uint> * badFaces = NULL) const;
bool buildPositions(Array<Vector3> & positionArray);
bool buildNormals(Array<Vector3> & normalArray);
bool buildTexCoords(Array<Vector2> & texCoordArray, uint set = 0);
bool buildColors(Array<Vector4> & colorArray, uint set = 0);
void buildVertexToPositionMap(Array<int> & map);
// Expose attribute indices of the unified vertex array.
uint vertexCount() const;
uint positionCount() const;
uint normalCount() const;
uint texCoordCount(uint set = 0) const;
uint colorCount(uint set = 0) const;
uint materialCount() const;
const char * material(uint i) const;
uint positionIndex(uint vertex) const;
uint normalIndex(uint vertex) const;
uint texCoordIndex(uint vertex, uint set = 0) const;
uint colorIndex(uint vertex, uint set = 0) const;
private:
struct PrivateData;
PrivateData * d;
};
} // nv namespace
#endif // NV_MESH_MESHBUILDER_H

View file

@ -1,122 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#include "nvmesh.h" // pch
#include "nvcore/Array.h"
#include "nvcore/BitArray.h"
#include "nvmesh/MeshTopology.h"
#include "nvmesh/halfedge/Mesh.h"
#include "nvmesh/halfedge/Edge.h"
#include "nvmesh/halfedge/Face.h"
using namespace nv;
void MeshTopology::buildTopologyInfo(const HalfEdge::Mesh * mesh)
{
const uint vertexCount = mesh->colocalVertexCount();
const uint faceCount = mesh->faceCount();
const uint edgeCount = mesh->edgeCount();
nvDebug( "--- Building mesh topology:\n" );
Array<uint> stack(faceCount);
BitArray bitFlags(faceCount);
bitFlags.clearAll();
// Compute connectivity.
nvDebug( "--- Computing connectivity.\n" );
m_connectedCount = 0;
for(uint f = 0; f < faceCount; f++ ) {
if( bitFlags.bitAt(f) == false ) {
m_connectedCount++;
stack.pushBack( f );
while( !stack.isEmpty() ) {
const uint top = stack.back();
nvCheck(top != NIL);
stack.popBack();
if( bitFlags.bitAt(top) == false ) {
bitFlags.setBitAt(top);
const HalfEdge::Face * face = mesh->faceAt(top);
const HalfEdge::Edge * firstEdge = face->edge;
const HalfEdge::Edge * edge = firstEdge;
do {
const HalfEdge::Face * neighborFace = edge->pair->face;
if (neighborFace != NULL) {
stack.pushBack(neighborFace->id);
}
edge = edge->next;
} while(edge != firstEdge);
}
}
}
}
nvCheck(stack.isEmpty());
nvDebug( "--- %d connected components.\n", m_connectedCount );
// Count boundary loops.
nvDebug( "--- Counting boundary loops.\n" );
m_boundaryCount = 0;
bitFlags.resize(edgeCount);
bitFlags.clearAll();
// Don't forget to link the boundary otherwise this won't work.
for (uint e = 0; e < edgeCount; e++)
{
const HalfEdge::Edge * startEdge = mesh->edgeAt(e);
if (startEdge != NULL && startEdge->isBoundary() && bitFlags.bitAt(e) == false)
{
nvDebugCheck(startEdge->face != NULL);
nvDebugCheck(startEdge->pair->face == NULL);
startEdge = startEdge->pair;
m_boundaryCount++;
const HalfEdge::Edge * edge = startEdge;
do {
bitFlags.setBitAt(edge->id / 2);
edge = edge->next;
} while(startEdge != edge);
}
}
nvDebug("--- %d boundary loops found.\n", m_boundaryCount );
// Compute euler number.
m_eulerNumber = vertexCount - edgeCount + faceCount;
nvDebug("--- Euler number: %d.\n", m_eulerNumber);
// Compute genus. (only valid on closed connected surfaces)
m_genus = -1;
if( isClosed() && isConnected() ) {
m_genus = (2 - m_eulerNumber) / 2;
nvDebug("--- Genus: %d.\n", m_genus);
}
}
/*static*/ bool MeshTopology::isQuadOnly(const HalfEdge::Mesh * mesh)
{
const uint faceCount = mesh->faceCount();
for(uint f = 0; f < faceCount; f++)
{
const HalfEdge::Face * face = mesh->faceAt(f);
if (face->edgeCount() != 4) {
return false;
}
}
return true;
}

View file

@ -1,66 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MESH_MESHTOPOLOGY_H
#define NV_MESH_MESHTOPOLOGY_H
#include <nvmesh/nvmesh.h>
namespace nv
{
namespace HalfEdge { class Mesh; }
class MeshAdjacency;
/// Mesh topology information.
class MeshTopology
{
public:
MeshTopology(const HalfEdge::Mesh * mesh) { buildTopologyInfo(mesh); }
/// Determine if the mesh is connected.
bool isConnected() const { return m_connectedCount == 1; }
/// Determine if the mesh is closed. (Each edge is shared by two faces)
bool isClosed() const { return m_boundaryCount == 0; }
/// Return true if the mesh has the topology of a disk.
bool isDisk() const { return isConnected() && m_boundaryCount == 1/* && m_eulerNumber == 1*/; }
/// Return the number of connected components.
int connectedCount() const { return m_connectedCount; }
/// Return the number of open holes.
int holeCount() const { return m_boundaryCount; }
/// Return the genus of the mesh.
int genus() const { return m_genus; }
/// Return the euler number of the mesh.
int euler() const { return m_eulerNumber; }
static bool isQuadOnly(const HalfEdge::Mesh * mesh);
private:
NVMESH_API void buildTopologyInfo(const HalfEdge::Mesh * mesh);
private:
///< Number of boundary loops.
int m_boundaryCount;
///< Number of connected components.
int m_connectedCount;
///< Euler number.
int m_eulerNumber;
/// Mesh genus.
int m_genus;
};
} // nv namespace
#endif // NV_MESH_MESHTOPOLOGY_H

View file

@ -1,36 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#include "QuadTriMesh.h"
#include "Stream.h"
using namespace nv;
bool QuadTriMesh::isQuadFace(uint i) const
{
return m_faceArray[i].isQuadFace();
}
const QuadTriMesh::Vertex & QuadTriMesh::faceVertex(uint f, uint v) const
{
if (isQuadFace(f)) nvDebugCheck(v < 4);
else nvDebugCheck(v < 3);
const Face & face = this->faceAt(f);
return this->vertexAt(face.v[v]);
}
namespace nv
{
static Stream & operator<< (Stream & s, QuadTriMesh::Face & face)
{
return s << face.id << face.v[0] << face.v[1] << face.v[2] << face.v[3];
}
Stream & operator<< (Stream & s, QuadTriMesh & mesh)
{
return s << mesh.m_faceArray << (BaseMesh &) mesh;
}
}

View file

@ -1,60 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_MESH_QUADTRIMESH_H
#define NV_MESH_QUADTRIMESH_H
#include "nvcore/Array.h"
#include "nvmath/Vector.h"
#include "nvmesh/nvmesh.h"
#include "nvmesh/BaseMesh.h"
namespace nv
{
class Stream;
/// Mixed quad/triangle mesh.
class QuadTriMesh : public BaseMesh
{
public:
struct Face;
typedef BaseMesh::Vertex Vertex;
QuadTriMesh() {};
QuadTriMesh(uint faceCount, uint vertexCount) : BaseMesh(vertexCount), m_faceArray(faceCount) {}
// Face methods.
uint faceCount() const { return m_faceArray.count(); }
const Face & faceAt(uint i) const { return m_faceArray[i]; }
Face & faceAt(uint i) { return m_faceArray[i]; }
const Array<Face> & faces() const { return m_faceArray; }
Array<Face> & faces() { return m_faceArray; }
bool isQuadFace(uint i) const;
const Vertex & faceVertex(uint f, uint v) const;
friend Stream & operator<< (Stream & s, QuadTriMesh & obj);
private:
Array<Face> m_faceArray;
};
/// QuadTriMesh face.
struct QuadTriMesh::Face
{
uint id;
uint v[4];
bool isQuadFace() const { return v[3] != NIL; }
};
} // nv namespace
#endif // NV_MESH_QUADTRIMESH_H

View file

@ -1,25 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#include "TriMesh.h"
using namespace nv;
/// Triangle mesh.
Vector3 TriMesh::faceNormal(uint f) const
{
const Face & face = this->faceAt(f);
const Vector3 & p0 = this->vertexAt(face.v[0]).pos;
const Vector3 & p1 = this->vertexAt(face.v[1]).pos;
const Vector3 & p2 = this->vertexAt(face.v[2]).pos;
return normalizeSafe(cross(p1 - p0, p2 - p0), Vector3(0.0f), 0.0f);
}
/// Get face vertex.
const TriMesh::Vertex & TriMesh::faceVertex(uint f, uint v) const
{
nvDebugCheck(v < 3);
const Face & face = this->faceAt(f);
return this->vertexAt(face.v[v]);
}

View file

@ -1,51 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_MESH_TRIMESH_H
#define NV_MESH_TRIMESH_H
#include "nvcore/Array.h"
#include "nvmath/Vector.inl"
#include "nvmesh/nvmesh.h"
#include "nvmesh/BaseMesh.h"
namespace nv
{
/// Triangle mesh.
class TriMesh : public BaseMesh
{
public:
struct Face;
typedef BaseMesh::Vertex Vertex;
TriMesh(uint faceCount, uint vertexCount) : BaseMesh(vertexCount), m_faceArray(faceCount) {}
// Face methods.
uint faceCount() const { return m_faceArray.count(); }
const Face & faceAt(uint i) const { return m_faceArray[i]; }
Face & faceAt(uint i) { return m_faceArray[i]; }
const Array<Face> & faces() const { return m_faceArray; }
Array<Face> & faces() { return m_faceArray; }
NVMESH_API Vector3 faceNormal(uint f) const;
NVMESH_API const Vertex & faceVertex(uint f, uint v) const;
friend Stream & operator<< (Stream & s, BaseMesh & obj);
private:
Array<Face> m_faceArray;
};
/// TriMesh face.
struct TriMesh::Face
{
uint id;
uint v[3];
};
} // nv namespace
#endif // NV_MESH_TRIMESH_H

View file

@ -1,54 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#include "nvmesh.h" // pch
#include "Bounds.h"
#include "nvmesh/BaseMesh.h"
#include "nvmesh/halfedge/Mesh.h"
#include "nvmesh/halfedge/Vertex.h"
#include "nvmath/Box.inl"
using namespace nv;
Box MeshBounds::box(const BaseMesh * mesh)
{
nvCheck(mesh != NULL);
Box bounds;
bounds.clearBounds();
const uint vertexCount = mesh->vertexCount();
for (uint v = 0; v < vertexCount; v++)
{
const BaseMesh::Vertex & vertex = mesh->vertexAt(v);
bounds.addPointToBounds( vertex.pos );
}
return bounds;
}
Box MeshBounds::box(const HalfEdge::Mesh * mesh)
{
nvCheck(mesh != NULL);
Box bounds;
bounds.clearBounds();
const uint vertexCount = mesh->vertexCount();
for (uint v = 0; v < vertexCount; v++)
{
const HalfEdge::Vertex * vertex = mesh->vertexAt(v);
nvDebugCheck(vertex != NULL);
bounds.addPointToBounds( vertex->pos );
}
return bounds;
}
/*Sphere MeshBounds::sphere(const HalfEdge::Mesh * mesh)
{
// @@ TODO
return Sphere();
}*/

View file

@ -1,28 +0,0 @@
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#pragma once
#ifndef NV_MESH_MESHBOUNDS_H
#define NV_MESH_MESHBOUNDS_H
#include <nvmath/Sphere.h>
#include <nvmath/Box.h>
#include <nvmesh/nvmesh.h>
namespace nv
{
class BaseMesh;
namespace HalfEdge { class Mesh; }
// Bounding volumes computation.
namespace MeshBounds
{
Box box(const BaseMesh * mesh);
Box box(const HalfEdge::Mesh * mesh);
Sphere sphere(const HalfEdge::Mesh * mesh);
}
} // nv namespace
#endif // NV_MESH_MESHBOUNDS_H

View file

@ -1,36 +0,0 @@
// This code is in the public domain -- castano@gmail.com
#include "nvmesh.h" // pch
#include "Measurements.h"
#include "nvmesh/halfedge/Mesh.h"
#include "nvmesh/halfedge/Face.h"
using namespace nv;
float nv::computeSurfaceArea(const HalfEdge::Mesh * mesh)
{
float area = 0;
for (HalfEdge::Mesh::ConstFaceIterator it(mesh->faces()); !it.isDone(); it.advance())
{
const HalfEdge::Face * face = it.current();
area += face->area();
}
nvDebugCheck(area >= 0);
return area;
}
float nv::computeParametricArea(const HalfEdge::Mesh * mesh)
{
float area = 0;
for (HalfEdge::Mesh::ConstFaceIterator it(mesh->faces()); !it.isDone(); it.advance())
{
const HalfEdge::Face * face = it.current();
area += face->parametricArea();
}
return area;
}

View file

@ -1,18 +0,0 @@
// This code is in the public domain -- castano@gmail.com
#pragma once
#ifndef NV_MESH_MESHMEASUREMENTS_H
#define NV_MESH_MESHMEASUREMENTS_H
#include "nvmesh/nvmesh.h"
namespace nv
{
namespace HalfEdge { class Mesh; }
float computeSurfaceArea(const HalfEdge::Mesh * mesh);
float computeParametricArea(const HalfEdge::Mesh * mesh);
} // nv namespace
#endif // NV_MESH_MESHMEASUREMENTS_H

View file

@ -1,57 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#include "nvmesh.h" // pch
#include "Edge.h"
#include "Vertex.h"
#include "nvmath/Vector.inl"
using namespace nv;
using namespace HalfEdge;
Vector3 Edge::midPoint() const
{
return (to()->pos + from()->pos) * 0.5f;
}
float Edge::length() const
{
return ::length(to()->pos - from()->pos);
}
// Return angle between this edge and the previous one.
float Edge::angle() const {
Vector3 p = vertex->pos;
Vector3 a = prev->vertex->pos;
Vector3 b = next->vertex->pos;
Vector3 v0 = a - p;
Vector3 v1 = b - p;
return acosf(dot(v0, v1) / (nv::length(v0) * nv::length(v1)));
}
bool Edge::isValid() const
{
// null face is OK.
if (next == NULL || prev == NULL || pair == NULL || vertex == NULL) return false;
if (next->prev != this) return false;
if (prev->next != this) return false;
if (pair->pair != this) return false;
return true;
}
/*
Edge * Edge::nextBoundary() {
nvDebugCheck(this->m_pair == NULL);
}
Edge * Edge::prevBoundary() {
nvDebugCheck(this->m_pair == NULL);
}
*/

View file

@ -1,70 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MESH_HALFEDGE_EDGE_H
#define NV_MESH_HALFEDGE_EDGE_H
#include "nvmath/Vector.h"
namespace nv
{
namespace HalfEdge { class Vertex; class Face; class Edge; }
/// Half edge edge.
class HalfEdge::Edge
{
NV_FORBID_COPY(Edge);
public:
uint id;
Edge * next;
Edge * prev; // This is not strictly half-edge, but makes algorithms easier and faster.
Edge * pair;
Vertex * vertex;
Face * face;
// Default constructor.
Edge(uint id) : id(id), next(NULL), prev(NULL), pair(NULL), vertex(NULL), face(NULL)
{
}
// Vertex queries.
const Vertex * from() const { return vertex; }
Vertex * from() { return vertex; }
const Vertex * to() const { return pair->vertex; } // This used to be 'next->vertex', but that changed often when the connectivity of the mesh changes.
Vertex * to() { return pair->vertex; }
// Edge queries.
void setNext(Edge * e) { next = e; if (e != NULL) e->prev = this; }
void setPrev(Edge * e) { prev = e; if (e != NULL) e->next = this; }
// @@ Add these helpers:
//Edge * nextBoundary();
//Edge * prevBoundary();
// @@ It would be more simple to only check m_pair == NULL
// Face queries.
bool isBoundary() const { return !(face && pair->face); }
// @@ This is not exactly accurate, we should compare the texture coordinates...
bool isSeam() const { return vertex != pair->next->vertex || next->vertex != pair->vertex; }
bool isValid() const;
// Geometric queries.
Vector3 midPoint() const;
float length() const;
float angle() const;
};
} // nv namespace
#endif // NV_MESH_HALFEDGE_EDGE_H

View file

@ -1,268 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#include "nvmesh.h" // pch
#include "Face.h"
#include "Vertex.h"
#include "nvmath/Fitting.h"
#include "nvmath/Plane.h"
#include "nvmath/Vector.inl"
#include "nvcore/Array.h"
using namespace nv;
using namespace HalfEdge;
/// Get face area.
float Face::area() const
{
float area = 0;
const Vector3 & v0 = edge->from()->pos;
for (ConstEdgeIterator it(edges(edge->next)); it.current() != edge->prev; it.advance())
{
const Edge * e = it.current();
const Vector3 & v1 = e->vertex->pos;
const Vector3 & v2 = e->next->vertex->pos;
area += length(cross(v1-v0, v2-v0));
}
return area * 0.5f;
}
float Face::parametricArea() const
{
float area = 0;
const Vector2 & v0 = edge->from()->tex;
for (ConstEdgeIterator it(edges(edge->next)); it.current() != edge->prev; it.advance())
{
const Edge * e = it.current();
const Vector2 & v1 = e->vertex->tex;
const Vector2 & v2 = e->next->vertex->tex;
area += triangleArea(v0, v1, v2);
}
return area * 0.5f;
}
/// Get boundary length.
float Face::boundaryLength() const
{
float bl = 0;
for (ConstEdgeIterator it(edges()); !it.isDone(); it.advance())
{
const Edge * edge = it.current();
bl += edge->length();
}
return bl;
}
/// Get face normal.
Vector3 Face::normal() const
{
Vector3 n(0);
const Vertex * vertex0 = NULL;
for (ConstEdgeIterator it(edges()); !it.isDone(); it.advance())
{
const Edge * edge = it.current();
nvCheck(edge != NULL);
if (vertex0 == NULL)
{
vertex0 = edge->vertex;
}
else if (edge->next->vertex != vertex0)
{
const HalfEdge::Vertex * vertex1 = edge->from();
const HalfEdge::Vertex * vertex2 = edge->to();
const Vector3 & p0 = vertex0->pos;
const Vector3 & p1 = vertex1->pos;
const Vector3 & p2 = vertex2->pos;
Vector3 v10 = p1 - p0;
Vector3 v20 = p2 - p0;
n += cross(v10, v20);
}
}
return normalizeSafe(n, Vector3(0, 0, 1), 0.0f);
// Get face points eliminating duplicates.
/*Array<Vector3> points(4);
points.append(m_edge->prev()->from()->pos);
for (ConstEdgeIterator it(edges()); !it.isDone(); it.advance())
{
const Edge * edge = it.current();
nvDebugCheck(edge != NULL);
const Vector3 & p = edge->from()->pos;
if (points.back() != p)
{
points.append(edge->from()->pos);
}
}
points.popBack();
if (points.count() < 3)
{
// Invalid normal.
return Vector3(0.0f);
}
else
{
// Compute regular normal.
Vector3 normal = normalizeSafe(cross(points[1] - points[0], points[2] - points[0]), Vector3(0.0f), 0.0f);
#pragma NV_MESSAGE("TODO: make sure these three points are not colinear")
if (points.count() > 3)
{
// Compute best fitting plane to the points.
Plane plane = Fit::bestPlane(points.count(), points.buffer());
// Adjust normal orientation.
if (dot(normal, plane.vector()) > 0) {
normal = plane.vector();
}
else {
normal = -plane.vector();
}
}
nvDebugCheck(isNormalized(normal));
return normal;
}*/
}
Vector3 Face::centroid() const
{
Vector3 sum(0.0f);
uint count = 0;
for (ConstEdgeIterator it(edges()); !it.isDone(); it.advance())
{
const Edge * edge = it.current();
sum += edge->from()->pos;
count++;
}
return sum / float(count);
}
bool Face::isValid() const
{
uint count = 0;
for (ConstEdgeIterator it(edges()); !it.isDone(); it.advance())
{
const Edge * edge = it.current();
if (edge->face != this) return false;
if (!edge->isValid()) return false;
if (!edge->pair->isValid()) return false;
count++;
}
if (count < 3) return false;
return true;
}
// Determine if this face contains the given edge.
bool Face::contains(const Edge * e) const
{
for (ConstEdgeIterator it(edges()); !it.isDone(); it.advance())
{
if(it.current() == e) return true;
}
return false;
}
// Returns index in this face of the given edge.
uint Face::edgeIndex(const Edge * e) const
{
int i = 0;
for (ConstEdgeIterator it(edges()); !it.isDone(); it.advance(), i++)
{
if(it.current() == e) return i;
}
return NIL;
}
Edge * Face::edgeAt(uint idx)
{
int i = 0;
for(EdgeIterator it(edges()); !it.isDone(); it.advance(), i++) {
if (i == idx) return it.current();
}
return NULL;
}
const Edge * Face::edgeAt(uint idx) const
{
int i = 0;
for(ConstEdgeIterator it(edges()); !it.isDone(); it.advance(), i++) {
if (i == idx) return it.current();
}
return NULL;
}
// Count the number of edges in this face.
uint Face::edgeCount() const
{
uint count = 0;
for (ConstEdgeIterator it(edges()); !it.isDone(); it.advance()) { ++count; }
return count;
}
// Determine if this is a boundary face.
bool Face::isBoundary() const
{
for (ConstEdgeIterator it(edges()); !it.isDone(); it.advance())
{
const Edge * edge = it.current();
nvDebugCheck(edge->pair != NULL);
if (edge->pair->face == NULL) {
return true;
}
}
return false;
}
// Count the number of boundary edges in the face.
uint Face::boundaryCount() const
{
uint count = 0;
for (ConstEdgeIterator it(edges()); !it.isDone(); it.advance())
{
const Edge * edge = it.current();
nvDebugCheck(edge->pair != NULL);
if (edge->pair->face == NULL) {
count++;
}
}
return count;
}

View file

@ -1,106 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MESH_HALFEDGE_FACE_H
#define NV_MESH_HALFEDGE_FACE_H
#include <nvmesh/halfedge/Edge.h>
namespace nv
{
namespace HalfEdge { class Vertex; class Face; class Edge; }
/// Face of a half-edge mesh.
class HalfEdge::Face
{
NV_FORBID_COPY(Face);
public:
uint id;
uint16 group;
uint16 material;
Edge * edge;
Face(uint id) : id(id), group(~0), material(~0), edge(NULL) {}
float area() const;
float parametricArea() const;
float boundaryLength() const;
Vector3 normal() const;
Vector3 centroid() const;
bool isValid() const;
bool contains(const Edge * e) const;
uint edgeIndex(const Edge * e) const;
Edge * edgeAt(uint idx);
const Edge * edgeAt(uint idx) const;
uint edgeCount() const;
bool isBoundary() const;
uint boundaryCount() const;
// The iterator that visits the edges of this face in clockwise order.
class EdgeIterator //: public Iterator<Edge *>
{
public:
EdgeIterator(Edge * e) : m_end(NULL), m_current(e) { }
virtual void advance()
{
if (m_end == NULL) m_end = m_current;
m_current = m_current->next;
}
virtual bool isDone() const { return m_end == m_current; }
virtual Edge * current() const { return m_current; }
Vertex * vertex() const { return m_current->vertex; }
private:
Edge * m_end;
Edge * m_current;
};
EdgeIterator edges() { return EdgeIterator(edge); }
EdgeIterator edges(Edge * e)
{
nvDebugCheck(contains(e));
return EdgeIterator(e);
}
// The iterator that visits the edges of this face in clockwise order.
class ConstEdgeIterator //: public Iterator<const Edge *>
{
public:
ConstEdgeIterator(const Edge * e) : m_end(NULL), m_current(e) { }
ConstEdgeIterator(const EdgeIterator & it) : m_end(NULL), m_current(it.current()) { }
virtual void advance()
{
if (m_end == NULL) m_end = m_current;
m_current = m_current->next;
}
virtual bool isDone() const { return m_end == m_current; }
virtual const Edge * current() const { return m_current; }
const Vertex * vertex() const { return m_current->vertex; }
private:
const Edge * m_end;
const Edge * m_current;
};
ConstEdgeIterator edges() const { return ConstEdgeIterator(edge); }
ConstEdgeIterator edges(const Edge * e) const
{
nvDebugCheck(contains(e));
return ConstEdgeIterator(e);
}
};
} // nv namespace
#endif // NV_MESH_HALFEDGE_FACE_H

File diff suppressed because it is too large Load diff

View file

@ -1,274 +0,0 @@
// This code is in the public domain -- castanyo@yahoo.es
#pragma once
#ifndef NV_MESH_HALFEDGE_MESH_H
#define NV_MESH_HALFEDGE_MESH_H
#include "nvmesh/nvmesh.h"
#include "nvcore/Array.h"
#include "nvcore/HashMap.h"
/*
If I were to redo this again, there are a number of things that I would do differently.
- Edge map is only useful when importing a mesh to guarantee the result is two-manifold. However, when manipulating the mesh
it's a pain to maintain the map up to date.
- Edge array only points to the even vertices. There's no good reason for that. The map becomes required to traverse all edges
or you have to make sure edges are properly paired.
- Linked boundaries. It's cleaner to assume a NULL pair means a boundary edge. Makes easier to seal boundaries. The only reason
why we link boundaries is to simplify traversal, but that could be done with two helper functions (nextBoundary, prevBoundary).
- Minimize the amount of state that needs to be set in a certain way:
- boundary vertices point to boundary edge.
- Remove parenthesis! Make some members public.
- Remove member functions with side effects:
- e->setNext(n) modifies e->next and n->prev, instead use "link(e, n)", or "e->next = n, n->prev = e"
*/
namespace nv
{
class Vector3;
class TriMesh;
class QuadTriMesh;
//template <typename T> struct Hash<Mesh::Key>;
namespace HalfEdge
{
class Edge;
class Face;
class Vertex;
/// Simple half edge mesh designed for dynamic mesh manipulation.
class Mesh
{
public:
Mesh();
Mesh(const Mesh * mesh);
~Mesh();
void clear();
Vertex * addVertex(const Vector3 & pos);
//Vertex * addVertex(uint id, const Vector3 & pos);
//void addVertices(const Mesh * mesh);
void linkColocals();
void linkColocalsWithCanonicalMap(const Array<uint> & canonicalMap);
void resetColocalLinks();
Face * addFace();
Face * addFace(uint v0, uint v1, uint v2);
Face * addFace(uint v0, uint v1, uint v2, uint v3);
Face * addFace(const Array<uint> & indexArray);
Face * addFace(const Array<uint> & indexArray, uint first, uint num);
//void addFaces(const Mesh * mesh);
// These functions disconnect the given element from the mesh and delete it.
void disconnect(Edge * edge);
void disconnectPair(Edge * edge);
void disconnect(Vertex * vertex);
void disconnect(Face * face);
void remove(Edge * edge);
void remove(Vertex * vertex);
void remove(Face * face);
// Remove holes from arrays and reassign indices.
void compactEdges();
void compactVertices();
void compactFaces();
void triangulate();
void linkBoundary();
bool splitBoundaryEdges(); // Returns true if any split was made.
// Sew the boundary that starts at the given edge, returns one edge that still belongs to boundary, or NULL if boundary closed.
HalfEdge::Edge * sewBoundary(Edge * startEdge);
// Vertices
uint vertexCount() const { return m_vertexArray.count(); }
const Vertex * vertexAt(int i) const { return m_vertexArray[i]; }
Vertex * vertexAt(int i) { return m_vertexArray[i]; }
uint colocalVertexCount() const { return m_colocalVertexCount; }
// Faces
uint faceCount() const { return m_faceArray.count(); }
const Face * faceAt(int i) const { return m_faceArray[i]; }
Face * faceAt(int i) { return m_faceArray[i]; }
// Edges
uint edgeCount() const { return m_edgeArray.count(); }
const Edge * edgeAt(int i) const { return m_edgeArray[i]; }
Edge * edgeAt(int i) { return m_edgeArray[i]; }
class ConstVertexIterator;
class VertexIterator
{
friend class ConstVertexIterator;
public:
VertexIterator(Mesh * mesh) : m_mesh(mesh), m_current(0) { }
virtual void advance() { m_current++; }
virtual bool isDone() const { return m_current == m_mesh->vertexCount(); }
virtual Vertex * current() const { return m_mesh->vertexAt(m_current); }
private:
HalfEdge::Mesh * m_mesh;
uint m_current;
};
VertexIterator vertices() { return VertexIterator(this); }
class ConstVertexIterator
{
public:
ConstVertexIterator(const Mesh * mesh) : m_mesh(mesh), m_current(0) { }
ConstVertexIterator(class VertexIterator & it) : m_mesh(it.m_mesh), m_current(it.m_current) { }
virtual void advance() { m_current++; }
virtual bool isDone() const { return m_current == m_mesh->vertexCount(); }
virtual const Vertex * current() const { return m_mesh->vertexAt(m_current); }
private:
const HalfEdge::Mesh * m_mesh;
uint m_current;
};
ConstVertexIterator vertices() const { return ConstVertexIterator(this); }
class ConstFaceIterator;
class FaceIterator
{
friend class ConstFaceIterator;
public:
FaceIterator(Mesh * mesh) : m_mesh(mesh), m_current(0) { }
virtual void advance() { m_current++; }
virtual bool isDone() const { return m_current == m_mesh->faceCount(); }
virtual Face * current() const { return m_mesh->faceAt(m_current); }
private:
HalfEdge::Mesh * m_mesh;
uint m_current;
};
FaceIterator faces() { return FaceIterator(this); }
class ConstFaceIterator
{
public:
ConstFaceIterator(const Mesh * mesh) : m_mesh(mesh), m_current(0) { }
ConstFaceIterator(const FaceIterator & it) : m_mesh(it.m_mesh), m_current(it.m_current) { }
virtual void advance() { m_current++; }
virtual bool isDone() const { return m_current == m_mesh->faceCount(); }
virtual const Face * current() const { return m_mesh->faceAt(m_current); }
private:
const HalfEdge::Mesh * m_mesh;
uint m_current;
};
ConstFaceIterator faces() const { return ConstFaceIterator(this); }
class ConstEdgeIterator;
class EdgeIterator
{
friend class ConstEdgeIterator;
public:
EdgeIterator(Mesh * mesh) : m_mesh(mesh), m_current(0) { }
virtual void advance() { m_current++; }
virtual bool isDone() const { return m_current == m_mesh->edgeCount(); }
virtual Edge * current() const { return m_mesh->edgeAt(m_current); }
private:
HalfEdge::Mesh * m_mesh;
uint m_current;
};
EdgeIterator edges() { return EdgeIterator(this); }
class ConstEdgeIterator
{
public:
ConstEdgeIterator(const Mesh * mesh) : m_mesh(mesh), m_current(0) { }
ConstEdgeIterator(const EdgeIterator & it) : m_mesh(it.m_mesh), m_current(it.m_current) { }
virtual void advance() { m_current++; }
virtual bool isDone() const { return m_current == m_mesh->edgeCount(); }
virtual const Edge * current() const { return m_mesh->edgeAt(m_current); }
private:
const HalfEdge::Mesh * m_mesh;
uint m_current;
};
ConstEdgeIterator edges() const { return ConstEdgeIterator(this); }
// @@ Add half-edge iterator.
// Convert to tri mesh.
TriMesh * toTriMesh() const;
QuadTriMesh * toQuadTriMesh() const;
bool isValid() const;
public:
// Error status:
mutable uint errorCount;
mutable uint errorIndex0;
mutable uint errorIndex1;
private:
bool canAddFace(const Array<uint> & indexArray, uint first, uint num) const;
bool canAddEdge(uint i, uint j) const;
Edge * addEdge(uint i, uint j);
Edge * findEdge(uint i, uint j) const;
void linkBoundaryEdge(Edge * edge);
Vertex * splitBoundaryEdge(Edge * edge, float t, const Vector3 & pos);
void splitBoundaryEdge(Edge * edge, Vertex * vertex);
private:
Array<Vertex *> m_vertexArray;
Array<Edge *> m_edgeArray;
Array<Face *> m_faceArray;
struct Key {
Key() {}
Key(const Key & k) : p0(k.p0), p1(k.p1) {}
Key(uint v0, uint v1) : p0(v0), p1(v1) {}
void operator=(const Key & k) { p0 = k.p0; p1 = k.p1; }
bool operator==(const Key & k) const { return p0 == k.p0 && p1 == k.p1; }
uint p0;
uint p1;
};
friend struct Hash<Mesh::Key>;
HashMap<Key, Edge *> m_edgeMap;
uint m_colocalVertexCount;
};
/*
// This is a much better hash than the default and greatly improves performance!
template <> struct hash<Mesh::Key>
{
uint operator()(const Mesh::Key & k) const { return k.p0 + k.p1; }
};
*/
} // HalfEdge namespace
} // nv namespace
#endif // NV_MESH_HALFEDGE_MESH_H

View file

@ -1,94 +0,0 @@
// This code is in the public domain -- castano@gmail.com
#include "nvmesh.h" // pch
#include "Vertex.h"
#include "nvmath/Vector.inl"
using namespace nv;
using namespace HalfEdge;
// Set first edge of all colocals.
void Vertex::setEdge(Edge * e)
{
for (VertexIterator it(colocals()); !it.isDone(); it.advance()) {
it.current()->edge = e;
}
}
// Update position of all colocals.
void Vertex::setPos(const Vector3 & p)
{
for (VertexIterator it(colocals()); !it.isDone(); it.advance()) {
it.current()->pos = p;
}
}
uint HalfEdge::Vertex::colocalCount() const
{
uint count = 0;
for (ConstVertexIterator it(colocals()); !it.isDone(); it.advance()) { ++count; }
return count;
}
uint HalfEdge::Vertex::valence() const
{
uint count = 0;
for (ConstEdgeIterator it(edges()); !it.isDone(); it.advance()) { ++count; }
return count;
}
const HalfEdge::Vertex * HalfEdge::Vertex::firstColocal() const
{
uint firstId = id;
const Vertex * vertex = this;
for (ConstVertexIterator it(colocals()); !it.isDone(); it.advance())
{
if (it.current()->id < firstId) {
firstId = vertex->id;
vertex = it.current();
}
}
return vertex;
}
HalfEdge::Vertex * HalfEdge::Vertex::firstColocal()
{
Vertex * vertex = this;
uint firstId = id;
for (VertexIterator it(colocals()); !it.isDone(); it.advance())
{
if (it.current()->id < firstId) {
firstId = vertex->id;
vertex = it.current();
}
}
return vertex;
}
bool HalfEdge::Vertex::isFirstColocal() const
{
return firstColocal() == this;
}
bool HalfEdge::Vertex::isColocal(const Vertex * v) const {
if (this == v) return true;
if (pos != v->pos) return false;
for (ConstVertexIterator it(colocals()); !it.isDone(); it.advance())
{
if (v == it.current()) {
return true;
}
}
return false;
}

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