Subversion Repository Public Repository

Divide-Framework

This repository has no backups
This repository's network speed is throttled to 100KB/sec

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/*
   Copyright (c) 2014 DIVIDE-Studio
   Copyright (c) 2009 Ionut Cava

   This file is part of DIVIDE Framework.

   Permission is hereby granted, free of charge, to any person obtaining a copy of this software
   and associated documentation files (the "Software"), to deal in the Software without restriction,
   including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
   subject to the following conditions:

   The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
   INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
   OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 */

#ifndef _PLATFORM_DEFINES_H_
#define _PLATFORM_DEFINES_H_

#include "Utility/Headers/Vector.h"
#include "Utility/Headers/String.h"
#include "Utility/Headers/HashMap.h"
#include "Core/Headers/Singleton.h"
#include "Core/Headers/NonCopyable.h"
#include <limits.h>
#include <functional>
#include <atomic>

#if defined ( OS_WINDOWS )
#include <windows.h>
#ifdef DELETE
#undef DELETE
#endif
#endif

namespace Divide {

///Data Types
typedef uint8_t  U8;
typedef uint16_t U16; 
typedef uint32_t U32;
typedef uint64_t U64;
typedef int8_t   I8;
typedef int16_t  I16;
typedef int32_t  I32;
typedef int64_t  I64;
typedef __int64 _I64;
typedef float    F32;
typedef double   D32;

/// Converts an arbitrary positive integer value to a bitwise value used for masks
#define toBit(X) (1 << (X))
/// a la Boost
template<typename T>
inline void hash_combine(std::size_t& seed, const T& v) {
	std::hash<T> hasher;
	seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
/* See
 
http://randomascii.wordpress.com/2012/01/11/tricks-with-the-floating-point-format/
 
for the potential portability problems with the union and bit-fields below.
*/
union Float_t {
    Float_t(F32 num = 0.0f) : f(num) {}
    // Portable extraction of components.
    bool Negative()    const { return (i >> 31) != 0; }
    I32  RawMantissa() const { return i & ((1 << 23) - 1); }
    I32  RawExponent() const { return (i >> 23) & 0xFF; }
 
    I32 i;
    F32 f;
};

union Double_t {
    Double_t(D32 num = 0.0) : d(num) {}
    // Portable extraction of components.
    bool  Negative()    const { return (i >> 63) != 0; }
    I64   RawMantissa() const { return i & ((1LL << 52) - 1); }
    I64   RawExponent() const { return (i >> 52) & 0x7FF; }

   I64 i;
   D32 d;
};

inline bool AlmostEqualUlpsAndAbs(F32 A, F32 B, F32 maxDiff, I32 maxUlpsDiff)
{
    // Check if the numbers are really close -- needed
    // when comparing numbers near zero.
    F32 absDiff = std::fabs(A - B);
    if (absDiff <= maxDiff)
        return true;
 
    Float_t uA(A);
    Float_t uB(B);
 
    // Different signs means they do not match.
    if (uA.Negative() != uB.Negative())
        return false;
 
    // Find the difference in ULPs.
    return (std::abs(uA.i - uB.i) <= maxUlpsDiff);
}

inline bool AlmostEqualUlpsAndAbs(D32 A, D32 B, D32 maxDiff, I32 maxUlpsDiff)
{
    // Check if the numbers are really close -- needed
    // when comparing numbers near zero.
    D32 absDiff = std::fabs(A - B);
    if (absDiff <= maxDiff)
        return true;
 
    Double_t uA(A);
    Double_t uB(B);
 
    // Different signs means they do not match.
    if (uA.Negative() != uB.Negative())
        return false;
 
    // Find the difference in ULPs.
    return (std::abs(uA.i - uB.i) <= maxUlpsDiff);
}

inline bool AlmostEqualRelativeAndAbs(F32 A, F32 B, F32 maxDiff, F32 maxRelDiff)
{
    // Check if the numbers are really close -- needed
    // when comparing numbers near zero.
    F32 diff = std::fabs(A - B);
    if (diff <= maxDiff)
        return true;
 
    A = std::fabs(A);
    B = std::fabs(B);
    F32 largest = (B > A) ? B : A;
 
    return (diff <= largest * maxRelDiff);
}

inline bool AlmostEqualRelativeAndAbs(D32 A, D32 B, D32 maxDiff, D32 maxRelDiff)
{
    // Check if the numbers are really close -- needed
    // when comparing numbers near zero.
    D32 diff = std::fabs(A - B);
    if (diff <= maxDiff)
        return true;
 
    A = std::fabs(A);
    B = std::fabs(B);
    D32 largest = (B > A) ? B : A;
 
    return (diff <= largest * maxRelDiff);
}

static const F32 EPSILON_F32 = std::numeric_limits<F32>::epsilon();
static const D32 EPSILON_D32 = std::numeric_limits<D32>::epsilon();

template<typename T>
inline bool IS_ZERO( T X ) { return X == 0; }
template<>
inline bool IS_ZERO(F32 X) { return  (std::fabs(X) < EPSILON_F32); }
template<>
inline bool IS_ZERO(D32 X) { return  (std::fabs(X) < EPSILON_D32); }

template<typename T>
inline bool IS_TOLERANCE(T X, T TOLERANCE )      { return ( std::abs( X ) < TOLERANCE ); }
template<>
inline bool IS_TOLERANCE( F32 X, F32 TOLERANCE ) { return ( std::fabs( X ) < TOLERANCE ); }
template<>
inline bool IS_TOLERANCE( D32 X, D32 TOLERANCE ) { return ( std::fabs( X ) < TOLERANCE ); }

inline bool FLOAT_COMPARE_TOLERANCE(F32 X, F32 Y, F32 TOLERANCE)  {  return AlmostEqualUlpsAndAbs(X, Y, TOLERANCE, 4); }
inline bool DOUBLE_COMPARE_TOLERANCE(D32 X, D32 Y, D32 TOLERANCE) {  return AlmostEqualUlpsAndAbs(X, Y, TOLERANCE, 4); }

inline bool FLOAT_COMPARE(F32 X, F32 Y)  { return FLOAT_COMPARE_TOLERANCE(X, Y, EPSILON_F32); }
inline bool DOUBLE_COMPARE(D32 X, D32 Y) { return DOUBLE_COMPARE_TOLERANCE(X, Y, EPSILON_D32); }

/// Performes extra asserts steps (logging, message boxes, etc). Returns true if the assert should be processed.
bool preAssert( const bool expression, const char* failMessage );
/// It is safe to call evaluate expressions and call functions inside the assert check as it will compile for every build type
inline bool DIVIDE_ASSERT(const bool expression, const char* failMessage) {
	if ( preAssert( expression, failMessage ) ) {
		assert( expression && failMessage );
	}
	return expression;
}

typedef struct packed_int {
    U8 b0; U8 b1; U8 b2; U8 b3;
} packed_int;

typedef union {
    U32 i;
    packed_int b;
} P32;

template<typename... Args>
auto DELEGATE_BIND(Args&&... args) -> decltype(std::bind(std::forward<Args>(args)...)) {
	return std::bind(std::forward<Args>(args)...);
}

template<typename... Args>
auto DELEGATE_REF(Args&&... args) -> decltype(std::bind(std::forward<Args>(args)...)) {
	return std::bind(std::forward<Args>(args)...);
}

template<typename... Args>
auto DELEGATE_CREF(Args&&... args) -> decltype(std::cref(std::forward<Args>(args)...)) {
	return std::cref(std::forward<Args>(args)...);
}

template<typename T = void>
using DELEGATE_CBK = std::function<T()>;

}; //namespace Divide

void* operator new[](size_t size,
                     const char* pName,
                     Divide::I32 flags,
                     Divide::U32 debugFlags,
                     const char* file,
                     Divide::I32 line);

void  operator delete[](void* ptr,
                        const char* pName,
                        Divide::I32 flags,
                        Divide::U32 debugFlags,
                        const char* file,
                        Divide::I32 line);

void* operator new[](size_t size,
                     size_t alignment,
                     size_t alignmentOffset,
                     const char* pName,
                     Divide::I32 flags,
                     Divide::U32 debugFlags,
                     const char* file,
                     Divide::I32 line);

void  operator delete[](void* ptr,
                        size_t alignment,
                        size_t alignmentOffset,
                        const char* pName,
                        Divide::I32 flags,
                        Divide::U32 debugFlags,
                        const char* file,
                        Divide::I32 line);

// EASTL also wants us to define this (see string.h line 197)
Divide::I32 Vsnprintf8( char* pDestination, size_t n, const char* pFormat, va_list arguments );

#if defined(NDEBUG)
#   define MemoryManager_NEW new
#else
	void* operator new( size_t size );
	void  operator delete( void *p );
	void* operator new[]( size_t size );
	void  operator delete[]( void *p );

	void* operator new( size_t size, char* zFile, Divide::I32 nLine );
	void  operator delete( void *ptr, char* zFile, Divide::I32 nLine );
	void* operator new[]( size_t size, char* zFile, Divide::I32 nLine );
	void  operator delete[]( void *ptr, char* zFile, Divide::I32 nLine );

#   define MemoryManager_NEW new(__FILE__, __LINE__)
#endif

namespace Divide {
    namespace MemoryManager {

    template<typename T>
	inline void SAFE_FREE(T*& ptr){
		if (ptr) {
			free(ptr);
			ptr = nullptr;
		}
	}
    
    /// Deletes and nullifies the specified pointer
    template<typename T>
    inline void DELETE( T*& ptr ) {
        delete ptr;
        ptr = nullptr;
    }
#   define SET_DELETE_FRIEND template<typename T> \
                             friend void MemoryManager::DELETE( T*& ptr );

    /// Deletes and nullifies the specified pointer
    template<typename T>
    inline void SAFE_DELETE(T*& ptr) {
        DIVIDE_ASSERT(ptr != nullptr, "SAFE_DELETE: null pointer received");

        delete ptr;
        ptr = nullptr;
    }
#   define SET_SAFE_DELETE_FRIEND template<typename T> \
                                  friend void MemoryManager::DELETE( T*& ptr );

    /// Deletes and nullifies the specified array pointer
    template<typename T>
    inline void DELETE_ARRAY( T*& ptr ) {
        delete[] ptr;
        ptr = nullptr;
    }
#   define SET_DELETE_ARRAY_FRIEND template<typename T> \
                                   friend void MemoryManager::DELETE_ARRAY( T*& ptr );

    /// Deletes and nullifies the specified array pointer
    template<typename T>
    inline void SAFE_DELETE_ARRAY(T*& ptr) {
        DIVIDE_ASSERT(ptr != nullptr, "SAFE_DELETE_ARRAY: null pointer received");

        delete[] ptr;
        ptr = nullptr;
    }
#   define SET_SAFE_DELETE_ARRAY_FRIEND template<typename T> \
                                        friend void MemoryManager::DELETE_ARRAY( T*& ptr );

    /// Deletes and nullifies the specified pointer. Returns "false" if the pointer was already null
    template<typename T>
    inline bool DELETE_CHECK( T*& ptr ) {
        if ( ptr == nullptr) {
            return false;
        }

        delete ptr;
        ptr = nullptr;

        return true;
    }
#   define SET_DELETE_CHECK_FRIEND template<typename T> \
                                   friend void MemoryManager::DELETE_CHECK( T*& ptr );

    /// Deletes and nullifies the specified array pointer. Returns "false" if the pointer was already null
    template<typename T>
    inline bool DELETE_ARRAY_CHECK( T*& ptr ) {
        if (ptr == nullptr) {
            return false;
        }
         
        delete[] ptr;
        ptr = nullptr;

        return true;
    }

#   define SET_DELETE_ARRAY_CHECK_FRIEND template<typename T> \
                                         friend void MemoryManager::DELETE_ARRAY_CHECK( T*& ptr );
    /// Deletes every element from the vector and clears it at the end
    template<typename T>
    inline void DELETE_VECTOR( vectorImpl<T*>& vec ) {
        if ( !vec.empty() ) {
            for ( T* iter : vec ) {
                delete iter;
            }
            vec.clear();
        }
    }
#   define SET_DELETE_VECTOR_FRIEND template<typename T> \
                                    friend void MemoryManager::DELETE_VECTOR( vectorImpl<T*>& vec );

    /// Deletes every element from the map and clears it at the end
    template<typename K, typename V, typename HashFun = hashAlg::hash<K> >
    inline void DELETE_HASHMAP(hashMapImpl<K, V, HashFun>& map) {
        if (!map.empty()) {
            for (hashMapImpl<K, V, HashFun>::value_type& iter : map) {
                delete iter.second;
            }
            hashAlg::fastClear(map);
        }
    }
#   define SET_DELETE_HASHMAP_FRIEND template<typename K, typename V, typename HashFun = hashAlg::hash<K> > \
                                     friend void MemoryManager::DELETE_HASHMAP( hashMapImpl<K, V, HashFun>& map );

    /// Deletes the object pointed to by "OLD" and redirects that pointer to the object pointed by "NEW"
    /// "NEW" must be a derived (or same) class of OLD
    template<typename Base, typename Derived>
    inline void SAFE_UPDATE(Base*& OLD, Derived* const NEW) {
        static_assert(std::is_base_of<Base, Derived>::value, "SAFE_UPDATE error: New must be a descendant of Old");

        delete OLD;
        OLD = NEW;
    }
#   define SET_SAFE_UPDATE_FRIEND template<typename Base, typename Derived> \
                                  friend void MemoryManager::SAFE_UPDATE( Base*& OLD, Derived* const NEW );

    }; //namespace MemoryManager
}; //namespace Divide
#if defined(_MSC_VER)

#	pragma warning(disable:4103) //< Boost alignment shouts
#	pragma warning(disable:4244)
#	pragma warning(disable:4996) //< strcpy
#	pragma warning(disable:4201) //< nameless struct
#	pragma warning(disable:4100) //< unreferenced formal param
#	pragma warning(disable:4505) //< unreferenced local function removal
#	pragma warning(disable:4127) //< Constant conditional expressions
#elif defined(__GNUC__)
//#	pragma GCC diagnostic ignored "-Wall"
#endif

#ifdef max
#undef max
#endif

#ifdef min
#undef min
#endif

#endif

Commits for Divide-Framework/trunk/Source Code/Hardware/Platform/Headers/PlatformDefines.h

Diff revisions: vs.
Revision Author Commited Message
331 Diff Diff IonutCava picture IonutCava Sat 06 Dec, 2014 20:53:45 +0000

[Ionut]
- Limited line length to 132 characters to improve readability and diff-comparisons
- Refactored memory allocation/deallocation functions
- Fixed a few compatibility issues with HashMap.h
- Fixed a bug in GPU Skinning shaders (cast a float to int)

326 Diff Diff IonutCava picture IonutCava Tue 30 Sep, 2014 21:11:32 +0000

[Ionut]
- Fixed more memory leaks
- Simplified Task interface and timing System
- Improved compatibility between Boost, STL and EASTL with random combinations of vectors, strings and maps
- Simplified Light class by removing the “slot” member
- Random optimizations

325 Diff Diff IonutCava picture IonutCava Wed 17 Sep, 2014 20:06:13 +0000

[Ionut]
- Reworked transform system:
— Parent transform chain system moved from Transform class to the PhysicsComponent
— PhysicsComponent now returns all transform values needed both global and local (still needs heavy optimization and caching)

- Reworked SceneGraph node management:
— Proper ref counting of SceneNodes and proper removing of resource (ResourceCache is now empty on destruction, as it should be)
— Removed parent transform tracking as that’s the PhysicsComponent’s responsibility
— Only nodes loaded via the ResourceCache are allowed to be added to the SceneGraph (added proper loaders for Impostors, Sky, etc)

- Optimized some of the math classes (mat4, mat3)

324 Diff Diff IonutCava picture IonutCava Sun 14 Sep, 2014 14:01:39 +0000

[Ionut]
- New memory management system (no custom allocators in this commit)
— Memory tracer to detect memory leaks on shutdown (from: https://www.relisoft.com/book/tech/9new.html)
— SAFE_DELETE_XYZ are now inline template functions not macros
— ASSERTION system now supports logging and message boxes and continue on error configurable for each build type
— Fixed a lot of memory leaks detected by the new system (some still remain)

- Added SRGB support (part 1)
— Albedo textures are loaded as SRGB (make sure resources are SRGB)
— Shaders output gamma corrected colors
— Moved terrain textures back to 2 array system (albedo and normal maps, albedo maps using a SRGB sampler)

- Sky is now loaded via the ResourceCache system
- Added include safeguards in shader atoms

322 Diff Diff IonutCava picture IonutCava Sat 06 Sep, 2014 20:33:47 +0000

[Ionut]
- Refactored most of Boost related code to be C++11 based
— Boost is only used for ThreadPool, Mutex handling, XML parsing and networking (ASIO)
— Function binds, threads, regex, NonCopyable base, Hashing algorithms and more are now using C++11 libraries
- Replaced all FOR_EACH calls with standard, range, “for” calls

321 Diff Diff IonutCava picture IonutCava Wed 03 Sep, 2014 22:05:15 +0000

[Ionut]
- Added support (and enabled by default) for the EASTL library (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html / https://github.com/paulhodge/EASTL)
— Strings, vectors and hash_maps can be combined from EASTL, STL and Boost (not all combinations work. e.g. EASTL strings with STL/Boost containers due to the lack of a proper hash function)

318 Diff Diff IonutCava picture IonutCava Sat 30 Aug, 2014 17:35:53 +0000

[Ionut]
- Wrapped the entire code in a “Divide” namespace
- VertexBuffers now call “shrink_to_fit” on all internal data storage
- Improved some vector performance by preferring “emplace_back” instead of “push_back” + proepr usage of reserve / resize
- Wrapped OIS specific types and classes in Divide::Input namespace
- Added the messageBox.layout file (forgot it in the previous few commits)

292 Diff Diff k1ngp1n picture k1ngp1n Mon 28 Jul, 2014 20:23:56 +0000

[Ionut]
- More nVidia compatibility issues (including the ability to disable persistent mapped buffer altogether. Thanks nsight ....)
- Cross-platform compatibility fixes for types (custom types now mirror types in stdint.h and are now typdefed instead of defined)
- Removed redundant files

275 Diff Diff IonutCava picture IonutCava Fri 13 Jun, 2014 15:11:02 +0000

[Ionut [[BR]]
- Removed all GLM dependencies (great library, but my math class can handle all of my requirements now) [[BR]]
- Moved view/projection/texture matrix management to GFXDevice class (from API specific classes) [[BR]]

273 IonutCava picture IonutCava Wed 11 Jun, 2014 20:34:00 +0000

[Ionut] [[BR]]
- Improved batching part2: [[BR]]
— Moved all bone transformation matrices upload from uniform functions in SceneNode to Shader Storage Buffers in AnimationController class with updates controlled by SceneGraphNode’s AnimationComponent [[BR]]
-— No double-buffering or efficient mapping of data yet. Just raw buffer updates [[BR]]
— Replaced all RenderStateBlock* pointers with I64 hash values [[BR]]
-— Will be used later in draw commands as per-shader state hash [[BR]]
— Moved getShaderProgram from Material to Material::ShaderInfo [[BR]]
-— Improved redundant uniform checks [[BR]]
— Improved texture unit changing in case of redundant texture bind case (i.e. skip changing the texture unit) [[BR]]
[[BR]]
- Improved float and double comparison functions using algorithms described in http://randomascii.wordpress.com/2012/02/13/dont-store-that-in-a-float/ [[BR]]
- Added a new utility function, DIVIDE_ASSERT, to more easily bind an assert check with a specific message [[BR]]
- Added missing files from Forward+ renderer’s initial code [[BR]]