Kaynağa Gözat

Reformat Urho3D source files to get rid of the indents on empty lines.
Reorganize includes.
Misc. fixes to perform explicit C-style cast on type mismatch.
Misc. fixes on bugs identified by CLion's static analyzer.

Yao Wei Tjong 姚伟忠 10 yıl önce
ebeveyn
işleme
fa77a456f8
100 değiştirilmiş dosya ile 3390 ekleme ve 2260 silme
  1. 3 0
      Source/Tools/RampGenerator/CMakeLists.txt
  2. 33 32
      Source/Urho3D/Audio/Audio.cpp
  3. 12 3
      Source/Urho3D/Audio/Audio.h
  4. 14 14
      Source/Urho3D/Audio/BufferedSoundStream.cpp
  5. 6 6
      Source/Urho3D/Audio/BufferedSoundStream.h
  6. 12 9
      Source/Urho3D/Audio/OggVorbisSoundStream.cpp
  7. 3 3
      Source/Urho3D/Audio/OggVorbisSoundStream.h
  8. 41 40
      Source/Urho3D/Audio/Sound.cpp
  9. 19 6
      Source/Urho3D/Audio/Sound.h
  10. 3 3
      Source/Urho3D/Audio/SoundListener.cpp
  11. 1 1
      Source/Urho3D/Audio/SoundListener.h
  12. 11 11
      Source/Urho3D/Audio/SoundSource.cpp
  13. 19 10
      Source/Urho3D/Audio/SoundSource.h
  14. 21 20
      Source/Urho3D/Audio/SoundSource3D.cpp
  15. 9 5
      Source/Urho3D/Audio/SoundSource3D.h
  16. 2 2
      Source/Urho3D/Audio/SoundStream.cpp
  17. 8 3
      Source/Urho3D/Audio/SoundStream.h
  18. 6 1
      Source/Urho3D/CMakeLists.txt
  19. 12 14
      Source/Urho3D/Container/Allocator.cpp
  20. 21 13
      Source/Urho3D/Container/Allocator.h
  21. 104 71
      Source/Urho3D/Container/ArrayPtr.h
  22. 17 17
      Source/Urho3D/Container/Hash.h
  23. 5 5
      Source/Urho3D/Container/HashBase.cpp
  24. 24 12
      Source/Urho3D/Container/HashBase.h
  25. 202 129
      Source/Urho3D/Container/HashMap.h
  26. 166 106
      Source/Urho3D/Container/HashSet.h
  27. 20 14
      Source/Urho3D/Container/LinkedList.h
  28. 140 74
      Source/Urho3D/Container/List.h
  29. 17 10
      Source/Urho3D/Container/ListBase.h
  30. 11 10
      Source/Urho3D/Container/Pair.h
  31. 106 75
      Source/Urho3D/Container/Ptr.h
  32. 4 4
      Source/Urho3D/Container/RefCounted.cpp
  33. 13 6
      Source/Urho3D/Container/RefCounted.h
  34. 4 4
      Source/Urho3D/Container/Sort.h
  35. 167 163
      Source/Urho3D/Container/Str.cpp
  36. 156 92
      Source/Urho3D/Container/Str.h
  37. 6 7
      Source/Urho3D/Container/Swap.cpp
  38. 5 5
      Source/Urho3D/Container/Swap.h
  39. 249 158
      Source/Urho3D/Container/Vector.h
  40. 2 0
      Source/Urho3D/Container/VectorBase.cpp
  41. 140 45
      Source/Urho3D/Container/VectorBase.h
  42. 7 6
      Source/Urho3D/Core/Attribute.h
  43. 8 2
      Source/Urho3D/Core/Condition.cpp
  44. 12 6
      Source/Urho3D/Core/Condition.h
  45. 8 6
      Source/Urho3D/Core/Context.cpp
  46. 25 2
      Source/Urho3D/Core/Context.h
  47. 3 1
      Source/Urho3D/Core/MiniDump.cpp
  48. 6 0
      Source/Urho3D/Core/Mutex.cpp
  49. 11 5
      Source/Urho3D/Core/Mutex.h
  50. 40 38
      Source/Urho3D/Core/Object.cpp
  51. 33 24
      Source/Urho3D/Core/Object.h
  52. 56 52
      Source/Urho3D/Core/ProcessUtils.cpp
  53. 23 21
      Source/Urho3D/Core/Profiler.cpp
  54. 13 8
      Source/Urho3D/Core/Spline.cpp
  55. 15 4
      Source/Urho3D/Core/Spline.h
  56. 19 13
      Source/Urho3D/Core/StringUtils.cpp
  57. 27 23
      Source/Urho3D/Core/Thread.cpp
  58. 11 5
      Source/Urho3D/Core/Thread.h
  59. 25 24
      Source/Urho3D/Core/Timer.cpp
  60. 17 13
      Source/Urho3D/Core/Timer.h
  61. 91 88
      Source/Urho3D/Core/Variant.cpp
  62. 309 131
      Source/Urho3D/Core/Variant.h
  63. 29 29
      Source/Urho3D/Core/WorkQueue.cpp
  64. 13 8
      Source/Urho3D/Core/WorkQueue.h
  65. 10 11
      Source/Urho3D/Engine/Application.cpp
  66. 8 6
      Source/Urho3D/Engine/Application.h
  67. 24 20
      Source/Urho3D/Engine/Console.cpp
  68. 16 0
      Source/Urho3D/Engine/Console.h
  69. 6 4
      Source/Urho3D/Engine/DebugHud.cpp
  70. 7 0
      Source/Urho3D/Engine/DebugHud.h
  71. 67 55
      Source/Urho3D/Engine/Engine.cpp
  72. 18 8
      Source/Urho3D/Engine/Engine.h
  73. 22 14
      Source/Urho3D/Graphics/AnimatedModel.cpp
  74. 14 1
      Source/Urho3D/Graphics/AnimatedModel.h
  75. 28 26
      Source/Urho3D/Graphics/Animation.cpp
  76. 17 10
      Source/Urho3D/Graphics/Animation.h
  77. 12 7
      Source/Urho3D/Graphics/AnimationController.cpp
  78. 1 1
      Source/Urho3D/Graphics/AnimationController.h
  79. 43 43
      Source/Urho3D/Graphics/AnimationState.cpp
  80. 12 5
      Source/Urho3D/Graphics/AnimationState.h
  81. 174 174
      Source/Urho3D/Graphics/Batch.cpp
  82. 29 19
      Source/Urho3D/Graphics/Batch.h
  83. 43 23
      Source/Urho3D/Graphics/BillboardSet.cpp
  84. 10 2
      Source/Urho3D/Graphics/BillboardSet.h
  85. 11 7
      Source/Urho3D/Graphics/Camera.cpp
  86. 22 2
      Source/Urho3D/Graphics/Camera.h
  87. 59 48
      Source/Urho3D/Graphics/CustomGeometry.cpp
  88. 8 1
      Source/Urho3D/Graphics/CustomGeometry.h
  89. 44 23
      Source/Urho3D/Graphics/DebugRenderer.cpp
  90. 14 9
      Source/Urho3D/Graphics/DebugRenderer.h
  91. 21 19
      Source/Urho3D/Graphics/DecalSet.cpp
  92. 21 7
      Source/Urho3D/Graphics/DecalSet.h
  93. 2 0
      Source/Urho3D/Graphics/Direct3D11/D3D11ConstantBuffer.cpp
  94. 0 3
      Source/Urho3D/Graphics/Direct3D11/D3D11ConstantBuffer.h
  95. 2 0
      Source/Urho3D/Graphics/Direct3D11/D3D11GPUObject.cpp
  96. 2 0
      Source/Urho3D/Graphics/Direct3D11/D3D11Graphics.cpp
  97. 2 0
      Source/Urho3D/Graphics/Direct3D11/D3D11GraphicsImpl.cpp
  98. 2 0
      Source/Urho3D/Graphics/Direct3D11/D3D11IndexBuffer.cpp
  99. 2 0
      Source/Urho3D/Graphics/Direct3D11/D3D11RenderSurface.cpp
  100. 2 0
      Source/Urho3D/Graphics/Direct3D11/D3D11ShaderVariation.cpp

+ 3 - 0
Source/Tools/RampGenerator/CMakeLists.txt

@@ -30,4 +30,7 @@ define_source_files ()
 set (LIBS STB)
 set (LIBS STB)
 
 
 # Setup target
 # Setup target
+if (APPLE)
+    setup_macosx_linker_flags (CMAKE_EXE_LINKER_FLAGS)
+endif ()
 setup_executable ()
 setup_executable ()

+ 33 - 32
Source/Urho3D/Audio/Audio.cpp

@@ -20,16 +20,17 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Audio/Audio.h"
 #include "../Audio/Audio.h"
+#include "../Audio/Sound.h"
+#include "../Audio/SoundListener.h"
+#include "../Audio/SoundSource3D.h"
 #include "../Core/Context.h"
 #include "../Core/Context.h"
 #include "../Core/CoreEvents.h"
 #include "../Core/CoreEvents.h"
-#include "../IO/Log.h"
-#include "../Core/Mutex.h"
 #include "../Core/ProcessUtils.h"
 #include "../Core/ProcessUtils.h"
 #include "../Core/Profiler.h"
 #include "../Core/Profiler.h"
-#include "../Audio/Sound.h"
-#include "../Audio/SoundListener.h"
-#include "../Audio/SoundSource3D.h"
+#include "../IO/Log.h"
 
 
 #include <SDL/SDL.h>
 #include <SDL/SDL.h>
 
 
@@ -45,7 +46,7 @@ static const int MIN_MIXRATE = 11025;
 static const int MAX_MIXRATE = 48000;
 static const int MAX_MIXRATE = 48000;
 static const StringHash SOUND_MASTER_HASH("MASTER");
 static const StringHash SOUND_MASTER_HASH("MASTER");
 
 
-static void SDLAudioCallback(void *userdata, Uint8 *stream, int len);
+static void SDLAudioCallback(void* userdata, Uint8* stream, int len);
 
 
 Audio::Audio(Context* context) :
 Audio::Audio(Context* context) :
     Object(context),
     Object(context),
@@ -78,20 +79,20 @@ bool Audio::SetMode(int bufferLengthMSec, int mixRate, bool stereo, bool interpo
     SDL_AudioSpec obtained;
     SDL_AudioSpec obtained;
 
 
     desired.freq = mixRate;
     desired.freq = mixRate;
-
-// The concept behind the emspcripten audio port is to treat it as 16 bit until the final acumulation form the clip buffer
-#ifdef EMSCRIPTEN
+
+// The concept behind the emscripten audio port is to treat it as 16 bit until the final accumulation form the clip buffer
+#ifdef EMSCRIPTEN
     desired.format = AUDIO_F32LSB;
     desired.format = AUDIO_F32LSB;
-#else
+#else
     desired.format = AUDIO_S16;
     desired.format = AUDIO_S16;
-#endif
-    desired.channels = stereo ? 2 : 1;
+#endif
+    desired.channels = (Uint8)(stereo ? 2 : 1);
     desired.callback = SDLAudioCallback;
     desired.callback = SDLAudioCallback;
     desired.userdata = this;
     desired.userdata = this;
 
 
     // SDL uses power of two audio fragments. Determine the closest match
     // SDL uses power of two audio fragments. Determine the closest match
     int bufferSamples = mixRate * bufferLengthMSec / 1000;
     int bufferSamples = mixRate * bufferLengthMSec / 1000;
-    desired.samples = NextPowerOfTwo(bufferSamples);
+    desired.samples = (Uint16)NextPowerOfTwo((unsigned)bufferSamples);
     if (Abs((int)desired.samples / 2 - bufferSamples) < Abs((int)desired.samples - bufferSamples))
     if (Abs((int)desired.samples / 2 - bufferSamples) < Abs((int)desired.samples - bufferSamples))
         desired.samples /= 2;
         desired.samples /= 2;
 
 
@@ -100,17 +101,17 @@ bool Audio::SetMode(int bufferLengthMSec, int mixRate, bool stereo, bool interpo
     {
     {
         LOGERROR("Could not initialize audio output");
         LOGERROR("Could not initialize audio output");
         return false;
         return false;
-    }
-
-#ifdef EMSCRIPTEN
+    }
+
+#ifdef EMSCRIPTEN
     if (obtained.format != AUDIO_F32LSB && obtained.format != AUDIO_F32MSB && obtained.format != AUDIO_F32SYS)
     if (obtained.format != AUDIO_F32LSB && obtained.format != AUDIO_F32MSB && obtained.format != AUDIO_F32SYS)
-    {
+    {
         LOGERROR("Could not initialize audio output, 32-bit float buffer format not supported");
         LOGERROR("Could not initialize audio output, 32-bit float buffer format not supported");
         SDL_CloseAudioDevice(deviceID_);
         SDL_CloseAudioDevice(deviceID_);
         deviceID_ = 0;
         deviceID_ = 0;
         return false;
         return false;
-    }
-#else
+    }
+#else
     if (obtained.format != AUDIO_S16SYS && obtained.format != AUDIO_S16LSB && obtained.format != AUDIO_S16MSB)
     if (obtained.format != AUDIO_S16SYS && obtained.format != AUDIO_S16LSB && obtained.format != AUDIO_S16MSB)
     {
     {
         LOGERROR("Could not initialize audio output, 16-bit buffer format not supported");
         LOGERROR("Could not initialize audio output, 16-bit buffer format not supported");
@@ -118,18 +119,18 @@ bool Audio::SetMode(int bufferLengthMSec, int mixRate, bool stereo, bool interpo
         deviceID_ = 0;
         deviceID_ = 0;
         return false;
         return false;
     }
     }
-#endif
+#endif
 
 
     stereo_ = obtained.channels == 2;
     stereo_ = obtained.channels == 2;
-    sampleSize_ = stereo_ ? sizeof(int) : sizeof(short);
+    sampleSize_ = (unsigned)(stereo_ ? sizeof(int) : sizeof(short));
     // Guarantee a fragment size that is low enough so that Vorbis decoding buffers do not wrap
     // Guarantee a fragment size that is low enough so that Vorbis decoding buffers do not wrap
-    fragmentSize_ = Min((int)NextPowerOfTwo(mixRate >> 6), (int)obtained.samples);
+    fragmentSize_ = (unsigned)Min((int)NextPowerOfTwo((unsigned)(mixRate >> 6)), (int)obtained.samples);
     mixRate_ = obtained.freq;
     mixRate_ = obtained.freq;
     interpolation_ = interpolation;
     interpolation_ = interpolation;
     clipBuffer_ = new int[stereo ? fragmentSize_ << 1 : fragmentSize_];
     clipBuffer_ = new int[stereo ? fragmentSize_ << 1 : fragmentSize_];
 
 
     LOGINFO("Set audio mode " + String(mixRate_) + " Hz " + (stereo_ ? "stereo" : "mono") + " " +
     LOGINFO("Set audio mode " + String(mixRate_) + " Hz " + (stereo_ ? "stereo" : "mono") + " " +
-        (interpolation_ ? "interpolated" : ""));
+            (interpolation_ ? "interpolated" : ""));
 
 
     return Play();
     return Play();
 }
 }
@@ -233,7 +234,7 @@ float Audio::GetSoundSourceMasterGain(StringHash typeHash) const
     return masterIt->second_.GetFloat() * typeIt->second_.GetFloat();
     return masterIt->second_.GetFloat() * typeIt->second_.GetFloat();
 }
 }
 
 
-void SDLAudioCallback(void *userdata, Uint8* stream, int len)
+void SDLAudioCallback(void* userdata, Uint8* stream, int len)
 {
 {
     Audio* audio = static_cast<Audio*>(userdata);
     Audio* audio = static_cast<Audio*>(userdata);
     {
     {
@@ -242,7 +243,7 @@ void SDLAudioCallback(void *userdata, Uint8* stream, int len)
     }
     }
 }
 }
 
 
-void Audio::MixOutput(void *dest, unsigned samples)
+void Audio::MixOutput(void* dest, unsigned samples)
 {
 {
     if (!playing_ || !clipBuffer_)
     if (!playing_ || !clipBuffer_)
     {
     {
@@ -253,7 +254,7 @@ void Audio::MixOutput(void *dest, unsigned samples)
     while (samples)
     while (samples)
     {
     {
         // If sample count exceeds the fragment (clip buffer) size, split the work
         // If sample count exceeds the fragment (clip buffer) size, split the work
-        unsigned workSamples = Min((int)samples, (int)fragmentSize_);
+        unsigned workSamples = (unsigned)Min((int)samples, (int)fragmentSize_);
         unsigned clipSamples = workSamples;
         unsigned clipSamples = workSamples;
         if (stereo_)
         if (stereo_)
             clipSamples <<= 1;
             clipSamples <<= 1;
@@ -266,15 +267,15 @@ void Audio::MixOutput(void *dest, unsigned samples)
         for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
         for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
             (*i)->Mix(clipPtr, workSamples, mixRate_, stereo_, interpolation_);
             (*i)->Mix(clipPtr, workSamples, mixRate_, stereo_, interpolation_);
 
 
-        // Copy output from clip buffer to destination
-#ifdef EMSCRIPTEN
+        // Copy output from clip buffer to destination
+#ifdef EMSCRIPTEN
         float* destPtr = (float*)dest;
         float* destPtr = (float*)dest;
         while (clipSamples--)
         while (clipSamples--)
             *destPtr++ = (float)Clamp(*clipPtr++, -32768, 32767) / 32768.0f;
             *destPtr++ = (float)Clamp(*clipPtr++, -32768, 32767) / 32768.0f;
-#else
-        short* destPtr = (short*)dest;
-        while (clipSamples--)
-            *destPtr++ = Clamp(*clipPtr++, -32768, 32767);
+#else
+        short* destPtr = (short*)dest;
+        while (clipSamples--)
+            *destPtr++ = (short)Clamp(*clipPtr++, -32768, 32767);
 #endif
 #endif
         samples -= workSamples;
         samples -= workSamples;
         ((unsigned char*&)dest) += sampleSize_ * SAMPLE_SIZE_MUL * workSamples;
         ((unsigned char*&)dest) += sampleSize_ * SAMPLE_SIZE_MUL * workSamples;

+ 12 - 3
Source/Urho3D/Audio/Audio.h

@@ -22,8 +22,8 @@
 
 
 #pragma once
 #pragma once
 
 
-#include "../Container/ArrayPtr.h"
 #include "../Audio/AudioDefs.h"
 #include "../Audio/AudioDefs.h"
+#include "../Container/ArrayPtr.h"
 #include "../Core/Mutex.h"
 #include "../Core/Mutex.h"
 #include "../Core/Object.h"
 #include "../Core/Object.h"
 
 
@@ -63,20 +63,27 @@ public:
 
 
     /// Return byte size of one sample.
     /// Return byte size of one sample.
     unsigned GetSampleSize() const { return sampleSize_; }
     unsigned GetSampleSize() const { return sampleSize_; }
+
     /// Return mixing rate.
     /// Return mixing rate.
     int GetMixRate() const { return mixRate_; }
     int GetMixRate() const { return mixRate_; }
+
     /// Return whether output is interpolated.
     /// Return whether output is interpolated.
     bool GetInterpolation() const { return interpolation_; }
     bool GetInterpolation() const { return interpolation_; }
+
     /// Return whether output is stereo.
     /// Return whether output is stereo.
     bool IsStereo() const { return stereo_; }
     bool IsStereo() const { return stereo_; }
+
     /// Return whether audio is being output.
     /// Return whether audio is being output.
     bool IsPlaying() const { return playing_; }
     bool IsPlaying() const { return playing_; }
+
     /// Return whether an audio stream has been reserved.
     /// Return whether an audio stream has been reserved.
     bool IsInitialized() const { return deviceID_ != 0; }
     bool IsInitialized() const { return deviceID_ != 0; }
+
     /// Return master gain for a specific sound source type. Unknown sound types will return full gain (1).
     /// Return master gain for a specific sound source type. Unknown sound types will return full gain (1).
     float GetMasterGain(const String& type) const;
     float GetMasterGain(const String& type) const;
     /// Return active sound listener.
     /// Return active sound listener.
     SoundListener* GetListener() const;
     SoundListener* GetListener() const;
+
     /// Return all sound sources.
     /// Return all sound sources.
     const PODVector<SoundSource*>& GetSoundSources() const { return soundSources_; }
     const PODVector<SoundSource*>& GetSoundSources() const { return soundSources_; }
 
 
@@ -87,14 +94,16 @@ public:
     void AddSoundSource(SoundSource* soundSource);
     void AddSoundSource(SoundSource* soundSource);
     /// Remove a sound source. Called by SoundSource.
     /// Remove a sound source. Called by SoundSource.
     void RemoveSoundSource(SoundSource* soundSource);
     void RemoveSoundSource(SoundSource* soundSource);
+
     /// Return audio thread mutex.
     /// Return audio thread mutex.
     Mutex& GetMutex() { return audioMutex_; }
     Mutex& GetMutex() { return audioMutex_; }
+
     /// Return sound type specific gain multiplied by master gain.
     /// Return sound type specific gain multiplied by master gain.
     float GetSoundSourceMasterGain(StringHash typeHash) const;
     float GetSoundSourceMasterGain(StringHash typeHash) const;
 
 
     /// Mix sound sources into the buffer.
     /// Mix sound sources into the buffer.
-    void MixOutput(void *dest, unsigned samples);
-
+    void MixOutput(void* dest, unsigned samples);
+
     /// Final multiplier for for audio byte conversion
     /// Final multiplier for for audio byte conversion
 #ifdef EMSCRIPTEN
 #ifdef EMSCRIPTEN
     static const int SAMPLE_SIZE_MUL = 2;
     static const int SAMPLE_SIZE_MUL = 2;

+ 14 - 14
Source/Urho3D/Audio/BufferedSoundStream.cpp

@@ -20,9 +20,9 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
-#include "../Audio/BufferedSoundStream.h"
+#include "../Precompiled.h"
 
 
-#include <cstring>
+#include "../Audio/BufferedSoundStream.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -41,18 +41,18 @@ BufferedSoundStream::~BufferedSoundStream()
 unsigned BufferedSoundStream::GetData(signed char* dest, unsigned numBytes)
 unsigned BufferedSoundStream::GetData(signed char* dest, unsigned numBytes)
 {
 {
     MutexLock lock(bufferMutex_);
     MutexLock lock(bufferMutex_);
-    
+
     unsigned outBytes = 0;
     unsigned outBytes = 0;
-    
+
     while (numBytes && buffers_.Size())
     while (numBytes && buffers_.Size())
     {
     {
         // Copy as much from the front buffer as possible, then discard it and move to the next
         // Copy as much from the front buffer as possible, then discard it and move to the next
         List<Pair<SharedArrayPtr<signed char>, unsigned> >::Iterator front = buffers_.Begin();
         List<Pair<SharedArrayPtr<signed char>, unsigned> >::Iterator front = buffers_.Begin();
-        
+
         unsigned copySize = front->second_ - position_;
         unsigned copySize = front->second_ - position_;
         if (copySize > numBytes)
         if (copySize > numBytes)
             copySize = numBytes;
             copySize = numBytes;
-        
+
         memcpy(dest, front->first_.Get() + position_, copySize);
         memcpy(dest, front->first_.Get() + position_, copySize);
         position_ += copySize;
         position_ += copySize;
         if (position_ >= front->second_)
         if (position_ >= front->second_)
@@ -60,12 +60,12 @@ unsigned BufferedSoundStream::GetData(signed char* dest, unsigned numBytes)
             buffers_.PopFront();
             buffers_.PopFront();
             position_ = 0;
             position_ = 0;
         }
         }
-        
+
         dest += copySize;
         dest += copySize;
         outBytes += copySize;
         outBytes += copySize;
         numBytes -= copySize;
         numBytes -= copySize;
     }
     }
-    
+
     return outBytes;
     return outBytes;
 }
 }
 
 
@@ -74,7 +74,7 @@ void BufferedSoundStream::AddData(void* data, unsigned numBytes)
     if (data && numBytes)
     if (data && numBytes)
     {
     {
         MutexLock lock(bufferMutex_);
         MutexLock lock(bufferMutex_);
-        
+
         SharedArrayPtr<signed char> newBuffer(new signed char[numBytes]);
         SharedArrayPtr<signed char> newBuffer(new signed char[numBytes]);
         memcpy(newBuffer.Get(), data, numBytes);
         memcpy(newBuffer.Get(), data, numBytes);
         buffers_.Push(MakePair(newBuffer, numBytes));
         buffers_.Push(MakePair(newBuffer, numBytes));
@@ -86,7 +86,7 @@ void BufferedSoundStream::AddData(SharedArrayPtr<signed char> data, unsigned num
     if (data && numBytes)
     if (data && numBytes)
     {
     {
         MutexLock lock(bufferMutex_);
         MutexLock lock(bufferMutex_);
-        
+
         buffers_.Push(MakePair(data, numBytes));
         buffers_.Push(MakePair(data, numBytes));
     }
     }
 }
 }
@@ -96,7 +96,7 @@ void BufferedSoundStream::AddData(SharedArrayPtr<signed short> data, unsigned nu
     if (data && numBytes)
     if (data && numBytes)
     {
     {
         MutexLock lock(bufferMutex_);
         MutexLock lock(bufferMutex_);
-        
+
         buffers_.Push(MakePair(ReinterpretCast<signed char>(data), numBytes));
         buffers_.Push(MakePair(ReinterpretCast<signed char>(data), numBytes));
     }
     }
 }
 }
@@ -104,7 +104,7 @@ void BufferedSoundStream::AddData(SharedArrayPtr<signed short> data, unsigned nu
 void BufferedSoundStream::Clear()
 void BufferedSoundStream::Clear()
 {
 {
     MutexLock lock(bufferMutex_);
     MutexLock lock(bufferMutex_);
-    
+
     buffers_.Clear();
     buffers_.Clear();
     position_ = 0;
     position_ = 0;
 }
 }
@@ -112,13 +112,13 @@ void BufferedSoundStream::Clear()
 unsigned BufferedSoundStream::GetBufferNumBytes() const
 unsigned BufferedSoundStream::GetBufferNumBytes() const
 {
 {
     MutexLock lock(bufferMutex_);
     MutexLock lock(bufferMutex_);
-    
+
     unsigned ret = 0;
     unsigned ret = 0;
     for (List<Pair<SharedArrayPtr<signed char>, unsigned> >::ConstIterator i = buffers_.Begin(); i != buffers_.End(); ++i)
     for (List<Pair<SharedArrayPtr<signed char>, unsigned> >::ConstIterator i = buffers_.Begin(); i != buffers_.End(); ++i)
         ret += i->second_;
         ret += i->second_;
     // Subtract amount of sound data played from the front buffer
     // Subtract amount of sound data played from the front buffer
     ret -= position_;
     ret -= position_;
-    
+
     return ret;
     return ret;
 }
 }
 
 

+ 6 - 6
Source/Urho3D/Audio/BufferedSoundStream.h

@@ -22,11 +22,11 @@
 
 
 #pragma once
 #pragma once
 
 
+#include "../Audio/SoundStream.h"
 #include "../Container/ArrayPtr.h"
 #include "../Container/ArrayPtr.h"
 #include "../Container/List.h"
 #include "../Container/List.h"
 #include "../Core/Mutex.h"
 #include "../Core/Mutex.h"
 #include "../Container/Pair.h"
 #include "../Container/Pair.h"
-#include "../Audio/SoundStream.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {
@@ -39,10 +39,10 @@ public:
     BufferedSoundStream();
     BufferedSoundStream();
     /// Destruct.
     /// Destruct.
     ~BufferedSoundStream();
     ~BufferedSoundStream();
-    
+
     /// Produce sound data into destination. Return number of bytes produced. Called by SoundSource from the mixing thread.
     /// Produce sound data into destination. Return number of bytes produced. Called by SoundSource from the mixing thread.
     virtual unsigned GetData(signed char* dest, unsigned numBytes);
     virtual unsigned GetData(signed char* dest, unsigned numBytes);
-    
+
     /// Buffer sound data. Makes a copy of it.
     /// Buffer sound data. Makes a copy of it.
     void AddData(void* data, unsigned numBytes);
     void AddData(void* data, unsigned numBytes);
     /// Buffer sound data by taking ownership of it.
     /// Buffer sound data by taking ownership of it.
@@ -51,16 +51,16 @@ public:
     void AddData(SharedArrayPtr<signed short> data, unsigned numBytes);
     void AddData(SharedArrayPtr<signed short> data, unsigned numBytes);
     /// Remove all buffered audio data.
     /// Remove all buffered audio data.
     void Clear();
     void Clear();
-    
+
     /// Return amount of buffered (unplayed) sound data in bytes.
     /// Return amount of buffered (unplayed) sound data in bytes.
     unsigned GetBufferNumBytes() const;
     unsigned GetBufferNumBytes() const;
     /// Return length of buffered (unplayed) sound data in seconds.
     /// Return length of buffered (unplayed) sound data in seconds.
     float GetBufferLength() const;
     float GetBufferLength() const;
-    
+
 private:
 private:
     /// Buffers and their sizes.
     /// Buffers and their sizes.
     List<Pair<SharedArrayPtr<signed char>, unsigned> > buffers_;
     List<Pair<SharedArrayPtr<signed char>, unsigned> > buffers_;
-    /// Byte position in the frontmost buffer.
+    /// Byte position in the front most buffer.
     unsigned position_;
     unsigned position_;
     /// Mutex for buffer data.
     /// Mutex for buffer data.
     mutable Mutex bufferMutex_;
     mutable Mutex bufferMutex_;

+ 12 - 9
Source/Urho3D/Audio/OggVorbisSoundStream.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Audio/OggVorbisSoundStream.h"
 #include "../Audio/OggVorbisSoundStream.h"
 #include "../Audio/Sound.h"
 #include "../Audio/Sound.h"
 
 
@@ -33,11 +35,11 @@ namespace Urho3D
 OggVorbisSoundStream::OggVorbisSoundStream(const Sound* sound)
 OggVorbisSoundStream::OggVorbisSoundStream(const Sound* sound)
 {
 {
     assert(sound && sound->IsCompressed());
     assert(sound && sound->IsCompressed());
-    
+
     SetFormat(sound->GetIntFrequency(), sound->IsSixteenBit(), sound->IsStereo());
     SetFormat(sound->GetIntFrequency(), sound->IsSixteenBit(), sound->IsStereo());
     // If the sound is looped, the stream will automatically rewind at end
     // If the sound is looped, the stream will automatically rewind at end
     SetStopAtEnd(!sound->IsLooped());
     SetStopAtEnd(!sound->IsLooped());
-    
+
     // Initialize decoder
     // Initialize decoder
     data_ = sound->GetData();
     data_ = sound->GetData();
     dataSize_ = sound->GetDataSize();
     dataSize_ = sound->GetDataSize();
@@ -51,7 +53,7 @@ OggVorbisSoundStream::~OggVorbisSoundStream()
     if (decoder_)
     if (decoder_)
     {
     {
         stb_vorbis* vorbis = static_cast<stb_vorbis*>(decoder_);
         stb_vorbis* vorbis = static_cast<stb_vorbis*>(decoder_);
-        
+
         stb_vorbis_close(vorbis);
         stb_vorbis_close(vorbis);
         decoder_ = 0;
         decoder_ = 0;
     }
     }
@@ -61,22 +63,23 @@ unsigned OggVorbisSoundStream::GetData(signed char* dest, unsigned numBytes)
 {
 {
     if (!decoder_)
     if (!decoder_)
         return 0;
         return 0;
-    
+
     stb_vorbis* vorbis = static_cast<stb_vorbis*>(decoder_);
     stb_vorbis* vorbis = static_cast<stb_vorbis*>(decoder_);
-    
+
     unsigned channels = stereo_ ? 2 : 1;
     unsigned channels = stereo_ ? 2 : 1;
-    unsigned outSamples = stb_vorbis_get_samples_short_interleaved(vorbis, channels, (short*)dest, numBytes >> 1);
+    unsigned outSamples = (unsigned)stb_vorbis_get_samples_short_interleaved(vorbis, channels, (short*)dest, numBytes >> 1);
     unsigned outBytes = (outSamples * channels) << 1;
     unsigned outBytes = (outSamples * channels) << 1;
-    
+
     // Rewind and retry if is looping and produced less output than should have
     // Rewind and retry if is looping and produced less output than should have
     if (outBytes < numBytes && !stopAtEnd_)
     if (outBytes < numBytes && !stopAtEnd_)
     {
     {
         numBytes -= outBytes;
         numBytes -= outBytes;
         stb_vorbis_seek_start(vorbis);
         stb_vorbis_seek_start(vorbis);
-        outSamples = stb_vorbis_get_samples_short_interleaved(vorbis, channels, (short*)(dest + outBytes), numBytes >> 1);
+        outSamples =
+            (unsigned)stb_vorbis_get_samples_short_interleaved(vorbis, channels, (short*)(dest + outBytes), numBytes >> 1);
         outBytes += (outSamples * channels) << 1;
         outBytes += (outSamples * channels) << 1;
     }
     }
-    
+
     return outBytes;
     return outBytes;
 }
 }
 
 

+ 3 - 3
Source/Urho3D/Audio/OggVorbisSoundStream.h

@@ -22,8 +22,8 @@
 
 
 #pragma once
 #pragma once
 
 
-#include "../Container/ArrayPtr.h"
 #include "../Audio/SoundStream.h"
 #include "../Audio/SoundStream.h"
+#include "../Container/ArrayPtr.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {
@@ -38,10 +38,10 @@ public:
     OggVorbisSoundStream(const Sound* sound);
     OggVorbisSoundStream(const Sound* sound);
     /// Destruct.
     /// Destruct.
     ~OggVorbisSoundStream();
     ~OggVorbisSoundStream();
-    
+
     /// Produce sound data into destination. Return number of bytes produced. Called by SoundSource from the mixing thread.
     /// Produce sound data into destination. Return number of bytes produced. Called by SoundSource from the mixing thread.
     virtual unsigned GetData(signed char* dest, unsigned numBytes);
     virtual unsigned GetData(signed char* dest, unsigned numBytes);
-    
+
 protected:
 protected:
     /// Decoder state.
     /// Decoder state.
     void* decoder_;
     void* decoder_;

+ 41 - 40
Source/Urho3D/Audio/Sound.cpp

@@ -20,16 +20,17 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
+#include "../Audio/OggVorbisSoundStream.h"
+#include "../Audio/Sound.h"
 #include "../Core/Context.h"
 #include "../Core/Context.h"
+#include "../Core/Profiler.h"
 #include "../IO/FileSystem.h"
 #include "../IO/FileSystem.h"
 #include "../IO/Log.h"
 #include "../IO/Log.h"
-#include "../Audio/OggVorbisSoundStream.h"
-#include "../Core/Profiler.h"
 #include "../Resource/ResourceCache.h"
 #include "../Resource/ResourceCache.h"
-#include "../Audio/Sound.h"
 #include "../Resource/XMLFile.h"
 #include "../Resource/XMLFile.h"
 
 
-#include <cstring>
 #include <STB/stb_vorbis.h>
 #include <STB/stb_vorbis.h>
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
@@ -83,19 +84,19 @@ void Sound::RegisterObject(Context* context)
 bool Sound::BeginLoad(Deserializer& source)
 bool Sound::BeginLoad(Deserializer& source)
 {
 {
     PROFILE(LoadSound);
     PROFILE(LoadSound);
-    
-    bool success = false;
+
+    bool success;
     if (GetExtension(source.GetName()) == ".ogg")
     if (GetExtension(source.GetName()) == ".ogg")
         success = LoadOggVorbis(source);
         success = LoadOggVorbis(source);
     else if (GetExtension(source.GetName()) == ".wav")
     else if (GetExtension(source.GetName()) == ".wav")
         success = LoadWav(source);
         success = LoadWav(source);
     else
     else
         success = LoadRaw(source);
         success = LoadRaw(source);
-    
+
     // Load optional parameters
     // Load optional parameters
     if (success)
     if (success)
         LoadParameters();
         LoadParameters();
-    
+
     return success;
     return success;
 }
 }
 
 
@@ -104,7 +105,7 @@ bool Sound::LoadOggVorbis(Deserializer& source)
     unsigned dataSize = source.GetSize();
     unsigned dataSize = source.GetSize();
     SharedArrayPtr<signed char> data(new signed char[dataSize]);
     SharedArrayPtr<signed char> data(new signed char[dataSize]);
     source.Read(data.Get(), dataSize);
     source.Read(data.Get(), dataSize);
-    
+
     // Check for validity of data
     // Check for validity of data
     int error;
     int error;
     stb_vorbis* vorbis = stb_vorbis_open_memory((unsigned char*)data.Get(), dataSize, &error, 0);
     stb_vorbis* vorbis = stb_vorbis_open_memory((unsigned char*)data.Get(), dataSize, &error, 0);
@@ -113,19 +114,19 @@ bool Sound::LoadOggVorbis(Deserializer& source)
         LOGERROR("Could not read Ogg Vorbis data from " + source.GetName());
         LOGERROR("Could not read Ogg Vorbis data from " + source.GetName());
         return false;
         return false;
     }
     }
-    
+
     // Store length, frequency and stereo flag
     // Store length, frequency and stereo flag
     stb_vorbis_info info = stb_vorbis_get_info(vorbis);
     stb_vorbis_info info = stb_vorbis_get_info(vorbis);
     compressedLength_ = stb_vorbis_stream_length_in_seconds(vorbis);
     compressedLength_ = stb_vorbis_stream_length_in_seconds(vorbis);
     frequency_ = info.sample_rate;
     frequency_ = info.sample_rate;
     stereo_ = info.channels > 1;
     stereo_ = info.channels > 1;
     stb_vorbis_close(vorbis);
     stb_vorbis_close(vorbis);
-    
+
     data_ = data;
     data_ = data;
     dataSize_ = dataSize;
     dataSize_ = dataSize;
     sixteenBit_ = true;
     sixteenBit_ = true;
     compressed_ = true;
     compressed_ = true;
-    
+
     SetMemoryUse(dataSize);
     SetMemoryUse(dataSize);
     return true;
     return true;
 }
 }
@@ -133,19 +134,19 @@ bool Sound::LoadOggVorbis(Deserializer& source)
 bool Sound::LoadWav(Deserializer& source)
 bool Sound::LoadWav(Deserializer& source)
 {
 {
     WavHeader header;
     WavHeader header;
-    
+
     // Try to open
     // Try to open
     memset(&header, 0, sizeof header);
     memset(&header, 0, sizeof header);
     source.Read(&header.riffText_, 4);
     source.Read(&header.riffText_, 4);
     header.totalLength_ = source.ReadUInt();
     header.totalLength_ = source.ReadUInt();
     source.Read(&header.waveText_, 4);
     source.Read(&header.waveText_, 4);
-    
+
     if (memcmp("RIFF", header.riffText_, 4) || memcmp("WAVE", header.waveText_, 4))
     if (memcmp("RIFF", header.riffText_, 4) || memcmp("WAVE", header.waveText_, 4))
     {
     {
         LOGERROR("Could not read WAV data from " + source.GetName());
         LOGERROR("Could not read WAV data from " + source.GetName());
         return false;
         return false;
     }
     }
-    
+
     // Search for the FORMAT chunk
     // Search for the FORMAT chunk
     for (;;)
     for (;;)
     {
     {
@@ -153,7 +154,7 @@ bool Sound::LoadWav(Deserializer& source)
         header.formatLength_ = source.ReadUInt();
         header.formatLength_ = source.ReadUInt();
         if (!memcmp("fmt ", &header.formatText_, 4))
         if (!memcmp("fmt ", &header.formatText_, 4))
             break;
             break;
-        
+
         source.Seek(source.GetPosition() + header.formatLength_);
         source.Seek(source.GetPosition() + header.formatLength_);
         if (!header.formatLength_ || source.GetPosition() >= source.GetSize())
         if (!header.formatLength_ || source.GetPosition() >= source.GetSize())
         {
         {
@@ -161,7 +162,7 @@ bool Sound::LoadWav(Deserializer& source)
             return false;
             return false;
         }
         }
     }
     }
-    
+
     // Read the FORMAT chunk
     // Read the FORMAT chunk
     header.format_ = source.ReadUShort();
     header.format_ = source.ReadUShort();
     header.channels_ = source.ReadUShort();
     header.channels_ = source.ReadUShort();
@@ -169,17 +170,17 @@ bool Sound::LoadWav(Deserializer& source)
     header.avgBytes_ = source.ReadUInt();
     header.avgBytes_ = source.ReadUInt();
     header.blockAlign_ = source.ReadUShort();
     header.blockAlign_ = source.ReadUShort();
     header.bits_ = source.ReadUShort();
     header.bits_ = source.ReadUShort();
-    
+
     // Skip data if the format chunk was bigger than what we use
     // Skip data if the format chunk was bigger than what we use
     source.Seek(source.GetPosition() + header.formatLength_ - 16);
     source.Seek(source.GetPosition() + header.formatLength_ - 16);
-    
+
     // Check for correct format
     // Check for correct format
     if (header.format_ != 1)
     if (header.format_ != 1)
     {
     {
         LOGERROR("Could not read WAV data from " + source.GetName());
         LOGERROR("Could not read WAV data from " + source.GetName());
         return false;
         return false;
     }
     }
-    
+
     // Search for the DATA chunk
     // Search for the DATA chunk
     for (;;)
     for (;;)
     {
     {
@@ -187,7 +188,7 @@ bool Sound::LoadWav(Deserializer& source)
         header.dataLength_ = source.ReadUInt();
         header.dataLength_ = source.ReadUInt();
         if (!memcmp("data", &header.dataText_, 4))
         if (!memcmp("data", &header.dataText_, 4))
             break;
             break;
-        
+
         source.Seek(source.GetPosition() + header.dataLength_);
         source.Seek(source.GetPosition() + header.dataLength_);
         if (!header.dataLength_ || source.GetPosition() >= source.GetSize())
         if (!header.dataLength_ || source.GetPosition() >= source.GetSize())
         {
         {
@@ -195,20 +196,20 @@ bool Sound::LoadWav(Deserializer& source)
             return false;
             return false;
         }
         }
     }
     }
-    
+
     // Allocate sound and load audio data
     // Allocate sound and load audio data
     unsigned length = header.dataLength_;
     unsigned length = header.dataLength_;
     SetSize(length);
     SetSize(length);
     SetFormat(header.frequency_, header.bits_ == 16, header.channels_ == 2);
     SetFormat(header.frequency_, header.bits_ == 16, header.channels_ == 2);
     source.Read(data_.Get(), length);
     source.Read(data_.Get(), length);
-    
+
     // Convert 8-bit audio to signed
     // Convert 8-bit audio to signed
     if (!sixteenBit_)
     if (!sixteenBit_)
     {
     {
         for (unsigned i = 0; i < length; ++i)
         for (unsigned i = 0; i < length; ++i)
             data_[i] -= 128;
             data_[i] -= 128;
     }
     }
-    
+
     return true;
     return true;
 }
 }
 
 
@@ -223,12 +224,12 @@ void Sound::SetSize(unsigned dataSize)
 {
 {
     if (!dataSize)
     if (!dataSize)
         return;
         return;
-    
+
     data_ = new signed char[dataSize + IP_SAFETY];
     data_ = new signed char[dataSize + IP_SAFETY];
     dataSize_ = dataSize;
     dataSize_ = dataSize;
     compressed_ = false;
     compressed_ = false;
     SetLooped(false);
     SetLooped(false);
-    
+
     SetMemoryUse(dataSize + IP_SAFETY);
     SetMemoryUse(dataSize + IP_SAFETY);
 }
 }
 
 
@@ -236,7 +237,7 @@ void Sound::SetData(const void* data, unsigned dataSize)
 {
 {
     if (!dataSize)
     if (!dataSize)
         return;
         return;
-    
+
     SetSize(dataSize);
     SetSize(dataSize);
     memcpy(data_.Get(), data, dataSize);
     memcpy(data_.Get(), data, dataSize);
 }
 }
@@ -259,7 +260,7 @@ void Sound::SetLooped(bool enable)
         {
         {
             end_ = data_.Get() + dataSize_;
             end_ = data_.Get() + dataSize_;
             looped_ = false;
             looped_ = false;
-            
+
             FixInterpolation();
             FixInterpolation();
         }
         }
         else
         else
@@ -275,16 +276,16 @@ void Sound::SetLoop(unsigned repeatOffset, unsigned endOffset)
             repeatOffset = dataSize_;
             repeatOffset = dataSize_;
         if (endOffset > dataSize_)
         if (endOffset > dataSize_)
             endOffset = dataSize_;
             endOffset = dataSize_;
-        
+
         // Align repeat and end on sample boundaries
         // Align repeat and end on sample boundaries
         int sampleSize = GetSampleSize();
         int sampleSize = GetSampleSize();
         repeatOffset &= -sampleSize;
         repeatOffset &= -sampleSize;
         endOffset &= -sampleSize;
         endOffset &= -sampleSize;
-        
+
         repeat_ = data_.Get() + repeatOffset;
         repeat_ = data_.Get() + repeatOffset;
         end_ = data_.Get() + endOffset;
         end_ = data_.Get() + endOffset;
         looped_ = true;
         looped_ = true;
-        
+
         FixInterpolation();
         FixInterpolation();
     }
     }
     else
     else
@@ -295,7 +296,7 @@ void Sound::FixInterpolation()
 {
 {
     if (!data_ || compressed_)
     if (!data_ || compressed_)
         return;
         return;
-    
+
     // If looped, copy loop start to loop end. If oneshot, insert silence to end
     // If looped, copy loop start to loop end. If oneshot, insert silence to end
     if (looped_)
     if (looped_)
     {
     {
@@ -341,22 +342,22 @@ void Sound::LoadParameters()
 {
 {
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     String xmlName = ReplaceExtension(GetName(), ".xml");
     String xmlName = ReplaceExtension(GetName(), ".xml");
-    
+
     SharedPtr<XMLFile> file(cache->GetTempResource<XMLFile>(xmlName, false));
     SharedPtr<XMLFile> file(cache->GetTempResource<XMLFile>(xmlName, false));
     if (!file)
     if (!file)
         return;
         return;
-    
+
     XMLElement rootElem = file->GetRoot();
     XMLElement rootElem = file->GetRoot();
     XMLElement paramElem = rootElem.GetChild();
     XMLElement paramElem = rootElem.GetChild();
-    
+
     while (paramElem)
     while (paramElem)
     {
     {
         String name = paramElem.GetName();
         String name = paramElem.GetName();
-        
+
         if (name == "format" && !compressed_)
         if (name == "format" && !compressed_)
         {
         {
             if (paramElem.HasAttribute("frequency"))
             if (paramElem.HasAttribute("frequency"))
-                frequency_ = paramElem.GetInt("frequency");
+                frequency_ = (unsigned)paramElem.GetInt("frequency");
             if (paramElem.HasAttribute("sixteenbit"))
             if (paramElem.HasAttribute("sixteenbit"))
                 sixteenBit_ = paramElem.GetBool("sixteenbit");
                 sixteenBit_ = paramElem.GetBool("sixteenbit");
             if (paramElem.HasAttribute("16bit"))
             if (paramElem.HasAttribute("16bit"))
@@ -364,15 +365,15 @@ void Sound::LoadParameters()
             if (paramElem.HasAttribute("stereo"))
             if (paramElem.HasAttribute("stereo"))
                 stereo_ = paramElem.GetBool("stereo");
                 stereo_ = paramElem.GetBool("stereo");
         }
         }
-        
+
         if (name == "loop")
         if (name == "loop")
         {
         {
             if (paramElem.HasAttribute("enable"))
             if (paramElem.HasAttribute("enable"))
                 SetLooped(paramElem.GetBool("enable"));
                 SetLooped(paramElem.GetBool("enable"));
             if (paramElem.HasAttribute("start") && paramElem.HasAttribute("end"))
             if (paramElem.HasAttribute("start") && paramElem.HasAttribute("end"))
-                SetLoop(paramElem.GetInt("start"), paramElem.GetInt("end"));
+                SetLoop((unsigned)paramElem.GetInt("start"), (unsigned)paramElem.GetInt("end"));
         }
         }
-        
+
         paramElem = paramElem.GetNext();
         paramElem = paramElem.GetNext();
     }
     }
 }
 }

+ 19 - 6
Source/Urho3D/Audio/Sound.h

@@ -34,7 +34,7 @@ class SoundStream;
 class URHO3D_API Sound : public Resource
 class URHO3D_API Sound : public Resource
 {
 {
     OBJECT(Sound);
     OBJECT(Sound);
-    
+
 public:
 public:
     /// Construct.
     /// Construct.
     Sound(Context* context);
     Sound(Context* context);
@@ -42,10 +42,10 @@ public:
     virtual ~Sound();
     virtual ~Sound();
     /// Register object factory.
     /// Register object factory.
     static void RegisterObject(Context* context);
     static void RegisterObject(Context* context);
-    
+
     /// Load resource from stream. May be called from a worker thread. Return true if successful.
     /// Load resource from stream. May be called from a worker thread. Return true if successful.
     virtual bool BeginLoad(Deserializer& source);
     virtual bool BeginLoad(Deserializer& source);
-    
+
     /// Load raw sound data.
     /// Load raw sound data.
     bool LoadRaw(Deserializer& source);
     bool LoadRaw(Deserializer& source);
     /// Load WAV format sound data.
     /// Load WAV format sound data.
@@ -62,43 +62,56 @@ public:
     void SetLooped(bool enable);
     void SetLooped(bool enable);
     /// Define loop.
     /// Define loop.
     void SetLoop(unsigned repeatOffset, unsigned endOffset);
     void SetLoop(unsigned repeatOffset, unsigned endOffset);
-    
+
     /// Return a new instance of a decoder sound stream. Used by compressed sounds.
     /// Return a new instance of a decoder sound stream. Used by compressed sounds.
     SharedPtr<SoundStream> GetDecoderStream() const;
     SharedPtr<SoundStream> GetDecoderStream() const;
+
     /// Return shared sound data.
     /// Return shared sound data.
     SharedArrayPtr<signed char> GetData() const { return data_; }
     SharedArrayPtr<signed char> GetData() const { return data_; }
+
     /// Return sound data start.
     /// Return sound data start.
     signed char* GetStart() const { return data_.Get(); }
     signed char* GetStart() const { return data_.Get(); }
+
     /// Return loop start.
     /// Return loop start.
     signed char* GetRepeat() const { return repeat_; }
     signed char* GetRepeat() const { return repeat_; }
+
     /// Return sound data end.
     /// Return sound data end.
     signed char* GetEnd() const { return end_; }
     signed char* GetEnd() const { return end_; }
+
     /// Return length in seconds.
     /// Return length in seconds.
     float GetLength() const;
     float GetLength() const;
+
     /// Return total sound data size.
     /// Return total sound data size.
     unsigned GetDataSize() const { return dataSize_; }
     unsigned GetDataSize() const { return dataSize_; }
+
     /// Return sample size.
     /// Return sample size.
     unsigned GetSampleSize() const;
     unsigned GetSampleSize() const;
+
     /// Return default frequency as a float.
     /// Return default frequency as a float.
     float GetFrequency() const { return (float)frequency_; }
     float GetFrequency() const { return (float)frequency_; }
+
     /// Return default frequency as an integer.
     /// Return default frequency as an integer.
     unsigned GetIntFrequency() const { return frequency_; }
     unsigned GetIntFrequency() const { return frequency_; }
+
     /// Return whether is looped.
     /// Return whether is looped.
     bool IsLooped() const { return looped_; }
     bool IsLooped() const { return looped_; }
+
     /// Return whether data is sixteen bit.
     /// Return whether data is sixteen bit.
     bool IsSixteenBit() const { return sixteenBit_; }
     bool IsSixteenBit() const { return sixteenBit_; }
+
     /// Return whether data is stereo.
     /// Return whether data is stereo.
     bool IsStereo() const { return stereo_; }
     bool IsStereo() const { return stereo_; }
+
     /// Return whether is compressed.
     /// Return whether is compressed.
     bool IsCompressed() const { return compressed_; }
     bool IsCompressed() const { return compressed_; }
-    
+
     /// Fix interpolation by copying data from loop start to loop end (looped), or adding silence (oneshot.) Called internally, does not normally need to be called, unless the sound data is modified manually on the fly.
     /// Fix interpolation by copying data from loop start to loop end (looped), or adding silence (oneshot.) Called internally, does not normally need to be called, unless the sound data is modified manually on the fly.
     void FixInterpolation();
     void FixInterpolation();
 
 
 private:
 private:
     /// Load optional parameters from an XML file.
     /// Load optional parameters from an XML file.
     void LoadParameters();
     void LoadParameters();
-    
+
     /// Sound data.
     /// Sound data.
     SharedArrayPtr<signed char> data_;
     SharedArrayPtr<signed char> data_;
     /// Loop start.
     /// Loop start.

+ 3 - 3
Source/Urho3D/Audio/SoundListener.cpp

@@ -20,10 +20,10 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
-#include "../Core/Context.h"
-#include "../Audio/SoundListener.h"
+#include "../Precompiled.h"
 
 
-#include "../DebugNew.h"
+#include "../Audio/SoundListener.h"
+#include "../Core/Context.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {

+ 1 - 1
Source/Urho3D/Audio/SoundListener.h

@@ -31,7 +31,7 @@ namespace Urho3D
 class URHO3D_API SoundListener : public Component
 class URHO3D_API SoundListener : public Component
 {
 {
     OBJECT(SoundListener);
     OBJECT(SoundListener);
-    
+
 public:
 public:
     /// Construct.
     /// Construct.
     SoundListener(Context* context);
     SoundListener(Context* context);

+ 11 - 11
Source/Urho3D/Audio/SoundSource.cpp

@@ -20,14 +20,14 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Audio/Audio.h"
 #include "../Audio/Audio.h"
-#include "../Core/Context.h"
-#include "../Resource/ResourceCache.h"
 #include "../Audio/Sound.h"
 #include "../Audio/Sound.h"
 #include "../Audio/SoundSource.h"
 #include "../Audio/SoundSource.h"
 #include "../Audio/SoundStream.h"
 #include "../Audio/SoundStream.h"
-
-#include <cstring>
+#include "../Core/Context.h"
+#include "../Resource/ResourceCache.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -115,7 +115,7 @@ SoundSource::SoundSource(Context* context) :
 
 
     if (audio_)
     if (audio_)
         audio_->AddSoundSource(this);
         audio_->AddSoundSource(this);
-    
+
     UpdateMasterGain();
     UpdateMasterGain();
 }
 }
 
 
@@ -236,7 +236,7 @@ void SoundSource::SetSoundType(const String& type)
     soundType_ = type;
     soundType_ = type;
     soundTypeHash_ = StringHash(type);
     soundTypeHash_ = StringHash(type);
     UpdateMasterGain();
     UpdateMasterGain();
-    
+
     MarkNetworkUpdate();
     MarkNetworkUpdate();
 }
 }
 
 
@@ -337,12 +337,12 @@ void SoundSource::Mix(int* dest, unsigned samples, int mixRate, bool stereo, boo
         position_ = streamBuffer_->GetStart();
         position_ = streamBuffer_->GetStart();
 
 
         // Request new data from the stream
         // Request new data from the stream
-        signed char* dest = streamBuffer_->GetStart() + unusedStreamSize_;
-        outBytes = neededSize ? soundStream_->GetData(dest, neededSize) : 0;
-        dest += outBytes;
+        signed char* destination = streamBuffer_->GetStart() + unusedStreamSize_;
+        outBytes = neededSize ? soundStream_->GetData(destination, (unsigned)neededSize) : 0;
+        destination += outBytes;
         // Zero-fill rest if stream did not produce enough data
         // Zero-fill rest if stream did not produce enough data
         if (outBytes < neededSize)
         if (outBytes < neededSize)
-            memset(dest, 0, neededSize - outBytes);
+            memset(destination, 0, (size_t)(neededSize - outBytes));
 
 
         // Calculate amount of total bytes of data in stream buffer now, to know how much went unused after mixing
         // Calculate amount of total bytes of data in stream buffer now, to know how much went unused after mixing
         streamFilledSize = neededSize + unusedStreamSize_;
         streamFilledSize = neededSize + unusedStreamSize_;
@@ -396,7 +396,7 @@ void SoundSource::Mix(int* dest, unsigned samples, int mixRate, bool stereo, boo
 
 
         unusedStreamSize_ = Max(streamFilledSize - (int)(size_t)(position_ - streamBuffer_->GetStart()), 0);
         unusedStreamSize_ = Max(streamFilledSize - (int)(size_t)(position_ - streamBuffer_->GetStart()), 0);
         if (unusedStreamSize_)
         if (unusedStreamSize_)
-            memcpy(streamBuffer_->GetStart(), (const void*)position_, unusedStreamSize_);
+            memcpy(streamBuffer_->GetStart(), (const void*)position_, (size_t)unusedStreamSize_);
 
 
         // If stream did not produce any data, stop if applicable
         // If stream did not produce any data, stop if applicable
         if (!outBytes && soundStream_->GetStopAtEnd())
         if (!outBytes && soundStream_->GetStopAtEnd())

+ 19 - 10
Source/Urho3D/Audio/SoundSource.h

@@ -39,7 +39,7 @@ static const int STREAM_BUFFER_LENGTH = 100;
 class URHO3D_API SoundSource : public Component
 class URHO3D_API SoundSource : public Component
 {
 {
     OBJECT(SoundSource);
     OBJECT(SoundSource);
-    
+
 public:
 public:
     /// Construct.
     /// Construct.
     SoundSource(Context* context);
     SoundSource(Context* context);
@@ -47,7 +47,7 @@ public:
     virtual ~SoundSource();
     virtual ~SoundSource();
     /// Register object factory.
     /// Register object factory.
     static void RegisterObject(Context* context);
     static void RegisterObject(Context* context);
-    
+
     /// Play a sound.
     /// Play a sound.
     void Play(Sound* sound);
     void Play(Sound* sound);
     /// Play a sound with specified frequency.
     /// Play a sound with specified frequency.
@@ -70,39 +70,48 @@ public:
     void SetAttenuation(float attenuation);
     void SetAttenuation(float attenuation);
     /// Set stereo panning. -1.0 is full left and 1.0 is full right.
     /// Set stereo panning. -1.0 is full left and 1.0 is full right.
     void SetPanning(float panning);
     void SetPanning(float panning);
-   /// Set whether sound source will be automatically removed from the scene node when playback stops.
+    /// Set whether sound source will be automatically removed from the scene node when playback stops.
     void SetAutoRemove(bool enable);
     void SetAutoRemove(bool enable);
     /// Set new playback position.
     /// Set new playback position.
     void SetPlayPosition(signed char* pos);
     void SetPlayPosition(signed char* pos);
-    
+
     /// Return sound.
     /// Return sound.
     Sound* GetSound() const { return sound_; }
     Sound* GetSound() const { return sound_; }
+
     /// Return playback position.
     /// Return playback position.
     volatile signed char* GetPlayPosition() const { return position_; }
     volatile signed char* GetPlayPosition() const { return position_; }
+
     /// Return sound type, determines the master gain group.
     /// Return sound type, determines the master gain group.
     String GetSoundType() const { return soundType_; }
     String GetSoundType() const { return soundType_; }
+
     /// Return playback time position.
     /// Return playback time position.
     float GetTimePosition() const { return timePosition_; }
     float GetTimePosition() const { return timePosition_; }
+
     /// Return frequency.
     /// Return frequency.
     float GetFrequency() const { return frequency_; }
     float GetFrequency() const { return frequency_; }
+
     /// Return gain.
     /// Return gain.
     float GetGain() const { return gain_; }
     float GetGain() const { return gain_; }
+
     /// Return attenuation.
     /// Return attenuation.
     float GetAttenuation() const { return attenuation_; }
     float GetAttenuation() const { return attenuation_; }
+
     /// Return stereo panning.
     /// Return stereo panning.
     float GetPanning() const { return panning_; }
     float GetPanning() const { return panning_; }
+
     /// Return autoremove mode.
     /// Return autoremove mode.
     bool GetAutoRemove() const { return autoRemove_; }
     bool GetAutoRemove() const { return autoRemove_; }
+
     /// Return whether is playing.
     /// Return whether is playing.
     bool IsPlaying() const;
     bool IsPlaying() const;
-    
+
     /// Update the sound source. Perform subclass specific operations. Called by Audio.
     /// Update the sound source. Perform subclass specific operations. Called by Audio.
     virtual void Update(float timeStep);
     virtual void Update(float timeStep);
     /// Mix sound source output to a 32-bit clipping buffer. Called by Audio.
     /// Mix sound source output to a 32-bit clipping buffer. Called by Audio.
     void Mix(int* dest, unsigned samples, int mixRate, bool stereo, bool interpolation);
     void Mix(int* dest, unsigned samples, int mixRate, bool stereo, bool interpolation);
     /// Update the effective master gain. Called internally and by Audio when the master gain changes.
     /// Update the effective master gain. Called internally and by Audio when the master gain changes.
     void UpdateMasterGain();
     void UpdateMasterGain();
-    
+
     /// Set sound attribute.
     /// Set sound attribute.
     void SetSoundAttr(const ResourceRef& value);
     void SetSoundAttr(const ResourceRef& value);
     /// Set sound position attribute.
     /// Set sound position attribute.
@@ -113,7 +122,7 @@ public:
     void SetPlayingAttr(bool value);
     void SetPlayingAttr(bool value);
     /// Return sound position attribute.
     /// Return sound position attribute.
     int GetPositionAttr() const;
     int GetPositionAttr() const;
-    
+
 protected:
 protected:
     /// Audio subsystem.
     /// Audio subsystem.
     WeakPtr<Audio> audio_;
     WeakPtr<Audio> audio_;
@@ -135,7 +144,7 @@ protected:
     float masterGain_;
     float masterGain_;
     /// Autoremove flag.
     /// Autoremove flag.
     bool autoRemove_;
     bool autoRemove_;
-    
+
 private:
 private:
     /// Play a sound without locking the audio mutex. Called internally.
     /// Play a sound without locking the audio mutex. Called internally.
     void PlayLockless(Sound* sound);
     void PlayLockless(Sound* sound);
@@ -165,13 +174,13 @@ private:
     void MixZeroVolume(Sound* sound, unsigned samples, int mixRate);
     void MixZeroVolume(Sound* sound, unsigned samples, int mixRate);
     /// Advance playback pointer to simulate audio playback in headless mode.
     /// Advance playback pointer to simulate audio playback in headless mode.
     void MixNull(float timeStep);
     void MixNull(float timeStep);
-    
+
     /// Sound that is being played.
     /// Sound that is being played.
     SharedPtr<Sound> sound_;
     SharedPtr<Sound> sound_;
     /// Sound stream that is being played.
     /// Sound stream that is being played.
     SharedPtr<SoundStream> soundStream_;
     SharedPtr<SoundStream> soundStream_;
     /// Playback position.
     /// Playback position.
-    volatile signed char *position_;
+    volatile signed char* position_;
     /// Playback fractional position.
     /// Playback fractional position.
     volatile int fractPosition_;
     volatile int fractPosition_;
     /// Playback time position.
     /// Playback time position.

+ 21 - 20
Source/Urho3D/Audio/SoundSource3D.cpp

@@ -20,15 +20,15 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Audio/Audio.h"
 #include "../Audio/Audio.h"
-#include "../Core/Context.h"
-#include "../Graphics/DebugRenderer.h"
-#include "../Scene/Node.h"
 #include "../Audio/Sound.h"
 #include "../Audio/Sound.h"
 #include "../Audio/SoundListener.h"
 #include "../Audio/SoundListener.h"
 #include "../Audio/SoundSource3D.h"
 #include "../Audio/SoundSource3D.h"
-
-#include "../DebugNew.h"
+#include "../Core/Context.h"
+#include "../Graphics/DebugRenderer.h"
+#include "../Scene/Node.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {
@@ -47,7 +47,7 @@ static Vector3 PointOnSphere(float radius, float theta, float phi)
 {
 {
     // Zero angles point toward positive Z axis
     // Zero angles point toward positive Z axis
     phi += 90.0f;
     phi += 90.0f;
-    
+
     return Vector3(
     return Vector3(
         radius * Sin(theta) * Sin(phi),
         radius * Sin(theta) * Sin(phi),
         radius * Cos(phi),
         radius * Cos(phi),
@@ -65,10 +65,10 @@ static void DrawDebugArc(const Vector3& worldPosition, const Quaternion& worldRo
         debug->AddSphere(Sphere(worldPosition, distance), color, depthTest);
         debug->AddSphere(Sphere(worldPosition, distance), color, depthTest);
         return;
         return;
     }
     }
-    
+
     unsigned uintColor = color.ToUInt();
     unsigned uintColor = color.ToUInt();
     float halfAngle = 0.5f * angle;
     float halfAngle = 0.5f * angle;
-    
+
     if (drawLines)
     if (drawLines)
     {
     {
         debug->AddLine(worldPosition, worldPosition + worldRotation * PointOnSphere(distance, halfAngle, halfAngle),
         debug->AddLine(worldPosition, worldPosition + worldRotation * PointOnSphere(distance, halfAngle, halfAngle),
@@ -80,9 +80,9 @@ static void DrawDebugArc(const Vector3& worldPosition, const Quaternion& worldRo
         debug->AddLine(worldPosition, worldPosition + worldRotation * PointOnSphere(distance, -halfAngle, -halfAngle),
         debug->AddLine(worldPosition, worldPosition + worldRotation * PointOnSphere(distance, -halfAngle, -halfAngle),
             uintColor);
             uintColor);
     }
     }
-    
+
     const float step = 0.5f;
     const float step = 0.5f;
-    
+
     for (float x = -1.0f; x < 1.0f; x += step)
     for (float x = -1.0f; x < 1.0f; x += step)
     {
     {
         debug->AddLine(worldPosition + worldRotation * PointOnSphere(distance, x * halfAngle, halfAngle),
         debug->AddLine(worldPosition + worldRotation * PointOnSphere(distance, x * halfAngle, halfAngle),
@@ -131,11 +131,11 @@ void SoundSource3D::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
 {
 {
     if (!debug || !node_ || !IsEnabledEffective())
     if (!debug || !node_ || !IsEnabledEffective())
         return;
         return;
-    
+
     const Matrix3x4& worldTransform = node_->GetWorldTransform();
     const Matrix3x4& worldTransform = node_->GetWorldTransform();
     Vector3 worldPosition = worldTransform.Translation();
     Vector3 worldPosition = worldTransform.Translation();
     Quaternion worldRotation = worldTransform.Rotation();
     Quaternion worldRotation = worldTransform.Rotation();
-    
+
     // Draw cones for directional sounds, or spheres for non-directional
     // Draw cones for directional sounds, or spheres for non-directional
     if (innerAngle_ < DEFAULT_ANGLE && outerAngle_ > 0.0f)
     if (innerAngle_ < DEFAULT_ANGLE && outerAngle_ > 0.0f)
     {
     {
@@ -216,28 +216,29 @@ void SoundSource3D::CalculateAttenuation()
         if (listener && listener->IsEnabledEffective() && (!listener->GetScene() || listener->GetScene() == GetScene()))
         if (listener && listener->IsEnabledEffective() && (!listener->GetScene() || listener->GetScene() == GetScene()))
         {
         {
             Node* listenerNode = listener->GetNode();
             Node* listenerNode = listener->GetNode();
-            Vector3 relativePos(listenerNode->GetWorldRotation().Inverse() * (node_->GetWorldPosition() - listenerNode->GetWorldPosition()));
+            Vector3 relativePos
+                (listenerNode->GetWorldRotation().Inverse() * (node_->GetWorldPosition() - listenerNode->GetWorldPosition()));
             float distance = relativePos.Length();
             float distance = relativePos.Length();
-            
+
             // Distance attenuation
             // Distance attenuation
             if (interval > 0.0f)
             if (interval > 0.0f)
                 attenuation_ = powf(1.0f - Clamp(distance - nearDistance_, 0.0f, interval) / interval, rolloffFactor_);
                 attenuation_ = powf(1.0f - Clamp(distance - nearDistance_, 0.0f, interval) / interval, rolloffFactor_);
             else
             else
                 attenuation_ = distance <= nearDistance_ ? 1.0f : 0.0f;
                 attenuation_ = distance <= nearDistance_ ? 1.0f : 0.0f;
-            
+
             // Panning
             // Panning
             panning_ = relativePos.Normalized().x_;
             panning_ = relativePos.Normalized().x_;
-            
+
             // Angle attenuation
             // Angle attenuation
             if (innerAngle_ < DEFAULT_ANGLE && outerAngle_ > 0.0f)
             if (innerAngle_ < DEFAULT_ANGLE && outerAngle_ > 0.0f)
             {
             {
-                Vector3 listenerRelativePos(node_->GetWorldRotation().Inverse() * (listenerNode->GetWorldPosition() -
-                    node_->GetWorldPosition()));
+                Vector3 listenerRelativePos
+                    (node_->GetWorldRotation().Inverse() * (listenerNode->GetWorldPosition() - node_->GetWorldPosition()));
                 float listenerDot = Vector3::FORWARD.DotProduct(listenerRelativePos.Normalized());
                 float listenerDot = Vector3::FORWARD.DotProduct(listenerRelativePos.Normalized());
                 float listenerAngle = acosf(listenerDot) * M_RADTODEG * 2.0f;
                 float listenerAngle = acosf(listenerDot) * M_RADTODEG * 2.0f;
                 float angleInterval = Max(outerAngle_ - innerAngle_, 0.0f);
                 float angleInterval = Max(outerAngle_ - innerAngle_, 0.0f);
                 float angleAttenuation = 1.0f;
                 float angleAttenuation = 1.0f;
-                
+
                 if (angleInterval > 0.0f)
                 if (angleInterval > 0.0f)
                 {
                 {
                     if (listenerAngle > innerAngle_)
                     if (listenerAngle > innerAngle_)
@@ -248,7 +249,7 @@ void SoundSource3D::CalculateAttenuation()
                 }
                 }
                 else
                 else
                     angleAttenuation = listenerAngle <= innerAngle_ ? 1.0f : 0.0f;
                     angleAttenuation = listenerAngle <= innerAngle_ ? 1.0f : 0.0f;
-                
+
                 attenuation_ *= angleAttenuation;
                 attenuation_ *= angleAttenuation;
             }
             }
         }
         }

+ 9 - 5
Source/Urho3D/Audio/SoundSource3D.h

@@ -33,18 +33,18 @@ class Audio;
 class URHO3D_API SoundSource3D : public SoundSource
 class URHO3D_API SoundSource3D : public SoundSource
 {
 {
     OBJECT(SoundSource3D);
     OBJECT(SoundSource3D);
-    
+
 public:
 public:
     /// Construct.
     /// Construct.
     SoundSource3D(Context* context);
     SoundSource3D(Context* context);
     /// Register object factory.
     /// Register object factory.
     static void RegisterObject(Context* context);
     static void RegisterObject(Context* context);
-    
+
     /// Visualize the component as debug geometry.
     /// Visualize the component as debug geometry.
     virtual void DrawDebugGeometry(DebugRenderer* debug, bool depthTest);
     virtual void DrawDebugGeometry(DebugRenderer* debug, bool depthTest);
     /// Update sound source.
     /// Update sound source.
     virtual void Update(float timeStep);
     virtual void Update(float timeStep);
-    
+
     /// Set attenuation parameters.
     /// Set attenuation parameters.
     void SetDistanceAttenuation(float nearDistance, float farDistance, float rolloffFactor);
     void SetDistanceAttenuation(float nearDistance, float farDistance, float rolloffFactor);
     /// Set angle attenuation parameters.
     /// Set angle attenuation parameters.
@@ -61,18 +61,22 @@ public:
     void SetRolloffFactor(float factor);
     void SetRolloffFactor(float factor);
     /// Calculate attenuation and panning based on current position and listener position.
     /// Calculate attenuation and panning based on current position and listener position.
     void CalculateAttenuation();
     void CalculateAttenuation();
-    
+
     /// Return near distance.
     /// Return near distance.
     float GetNearDistance() const { return nearDistance_; }
     float GetNearDistance() const { return nearDistance_; }
+
     /// Return far distance.
     /// Return far distance.
     float GetFarDistance() const { return farDistance_; }
     float GetFarDistance() const { return farDistance_; }
+
     /// Return inner angle in degrees.
     /// Return inner angle in degrees.
     float GetInnerAngle() const { return innerAngle_; }
     float GetInnerAngle() const { return innerAngle_; }
+
     /// Return outer angle in degrees.
     /// Return outer angle in degrees.
     float GetOuterAngle() const { return outerAngle_; }
     float GetOuterAngle() const { return outerAngle_; }
+
     /// Return rolloff power factor.
     /// Return rolloff power factor.
     float RollAngleoffFactor() const { return rolloffFactor_; }
     float RollAngleoffFactor() const { return rolloffFactor_; }
-    
+
 protected:
 protected:
     /// Near distance.
     /// Near distance.
     float nearDistance_;
     float nearDistance_;

+ 2 - 2
Source/Urho3D/Audio/SoundStream.cpp

@@ -20,9 +20,9 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
-#include "../Audio/SoundStream.h"
+#include "../Precompiled.h"
 
 
-#include "../DebugNew.h"
+#include "../Audio/SoundStream.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {

+ 8 - 3
Source/Urho3D/Audio/SoundStream.h

@@ -35,25 +35,30 @@ public:
     SoundStream();
     SoundStream();
     /// Destruct.
     /// Destruct.
     ~SoundStream();
     ~SoundStream();
-    
+
     /// Produce sound data into destination. Return number of bytes produced. Called by SoundSource from the mixing thread.
     /// Produce sound data into destination. Return number of bytes produced. Called by SoundSource from the mixing thread.
     virtual unsigned GetData(signed char* dest, unsigned numBytes) = 0;
     virtual unsigned GetData(signed char* dest, unsigned numBytes) = 0;
-    
+
     /// Set sound data format.
     /// Set sound data format.
     void SetFormat(unsigned frequency, bool sixteenBit, bool stereo);
     void SetFormat(unsigned frequency, bool sixteenBit, bool stereo);
     /// Set whether playback should stop when no more data. Default false.
     /// Set whether playback should stop when no more data. Default false.
     void SetStopAtEnd(bool enable);
     void SetStopAtEnd(bool enable);
-    
+
     /// Return sample size.
     /// Return sample size.
     unsigned GetSampleSize() const;
     unsigned GetSampleSize() const;
+
     /// Return default frequency as a float.
     /// Return default frequency as a float.
     float GetFrequency() const { return (float)frequency_; }
     float GetFrequency() const { return (float)frequency_; }
+
     /// Return default frequency as an integer.
     /// Return default frequency as an integer.
     unsigned GetIntFrequency() const { return frequency_; }
     unsigned GetIntFrequency() const { return frequency_; }
+
     /// Return whether playback should stop when no more data.
     /// Return whether playback should stop when no more data.
     bool GetStopAtEnd() const { return stopAtEnd_; }
     bool GetStopAtEnd() const { return stopAtEnd_; }
+
     /// Return whether data is sixteen bit.
     /// Return whether data is sixteen bit.
     bool IsSixteenBit() const { return sixteenBit_; }
     bool IsSixteenBit() const { return sixteenBit_; }
+
     /// Return whether data is stereo.
     /// Return whether data is stereo.
     bool IsStereo() const { return stereo_; }
     bool IsStereo() const { return stereo_; }
 
 

+ 6 - 1
Source/Urho3D/CMakeLists.txt

@@ -23,6 +23,8 @@
 # Define target name
 # Define target name
 set (TARGET_NAME Urho3D)
 set (TARGET_NAME Urho3D)
 
 
+add_definitions (-DURHO3D_IS_BUILDING)
+
 if (WIN32)
 if (WIN32)
     set (CMAKE_DEBUG_POSTFIX _d)
     set (CMAKE_DEBUG_POSTFIX _d)
 endif ()
 endif ()
@@ -140,7 +142,10 @@ if (APPLE AND NOT IOS)
     set (GLOB_OBJC_PATTERN *.m)     # Should only pick up MacFileWatcher.m for MacOSX platform at the moment
     set (GLOB_OBJC_PATTERN *.m)     # Should only pick up MacFileWatcher.m for MacOSX platform at the moment
 endif ()
 endif ()
 string (REPLACE ";" "/[^;]+;" EXCLUDE_PATTERNS "${EXCLUDED_SOURCE_DIRS};")
 string (REPLACE ";" "/[^;]+;" EXCLUDE_PATTERNS "${EXCLUDED_SOURCE_DIRS};")
-define_source_files (EXCLUDE_PATTERNS ${EXCLUDE_PATTERNS} GLOB_CPP_PATTERNS *.cpp ${GLOB_OBJC_PATTERN} EXTRA_H_FILES librevision.h Urho3D.h RECURSE GROUP PCH Precompiled.h)
+if (URHO3D_PCH)
+    set (PCH PCH Precompiled.h)
+endif ()
+define_source_files (EXCLUDE_PATTERNS ${EXCLUDE_PATTERNS} GLOB_CPP_PATTERNS *.cpp ${GLOB_OBJC_PATTERN} EXTRA_H_FILES librevision.h Urho3D.h RECURSE GROUP ${PCH})
 list (APPEND SOURCE_FILES ${GEN_CPP_FILES} ${ALL_OBJ_FILES})
 list (APPEND SOURCE_FILES ${GEN_CPP_FILES} ${ALL_OBJ_FILES})
 
 
 # Define dependency libs
 # Define dependency libs

+ 12 - 14
Source/Urho3D/Container/Allocator.cpp

@@ -20,9 +20,7 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
-#include "../Container/Allocator.h"
-
-#include "stdio.h"
+#include "../Precompiled.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -33,14 +31,14 @@ AllocatorBlock* AllocatorReserveBlock(AllocatorBlock* allocator, unsigned nodeSi
 {
 {
     if (!capacity)
     if (!capacity)
         capacity = 1;
         capacity = 1;
-    
+
     unsigned char* blockPtr = new unsigned char[sizeof(AllocatorBlock) + capacity * (sizeof(AllocatorNode) + nodeSize)];
     unsigned char* blockPtr = new unsigned char[sizeof(AllocatorBlock) + capacity * (sizeof(AllocatorNode) + nodeSize)];
     AllocatorBlock* newBlock = reinterpret_cast<AllocatorBlock*>(blockPtr);
     AllocatorBlock* newBlock = reinterpret_cast<AllocatorBlock*>(blockPtr);
     newBlock->nodeSize_ = nodeSize;
     newBlock->nodeSize_ = nodeSize;
     newBlock->capacity_ = capacity;
     newBlock->capacity_ = capacity;
     newBlock->free_ = 0;
     newBlock->free_ = 0;
     newBlock->next_ = 0;
     newBlock->next_ = 0;
-    
+
     if (!allocator)
     if (!allocator)
         allocator = newBlock;
         allocator = newBlock;
     else
     else
@@ -48,11 +46,11 @@ AllocatorBlock* AllocatorReserveBlock(AllocatorBlock* allocator, unsigned nodeSi
         newBlock->next_ = allocator->next_;
         newBlock->next_ = allocator->next_;
         allocator->next_ = newBlock;
         allocator->next_ = newBlock;
     }
     }
-    
+
     // Initialize the nodes. Free nodes are always chained to the first (parent) allocator
     // Initialize the nodes. Free nodes are always chained to the first (parent) allocator
     unsigned char* nodePtr = blockPtr + sizeof(AllocatorBlock);
     unsigned char* nodePtr = blockPtr + sizeof(AllocatorBlock);
     AllocatorNode* firstNewNode = reinterpret_cast<AllocatorNode*>(nodePtr);
     AllocatorNode* firstNewNode = reinterpret_cast<AllocatorNode*>(nodePtr);
-    
+
     for (unsigned i = 0; i < capacity - 1; ++i)
     for (unsigned i = 0; i < capacity - 1; ++i)
     {
     {
         AllocatorNode* newNode = reinterpret_cast<AllocatorNode*>(nodePtr);
         AllocatorNode* newNode = reinterpret_cast<AllocatorNode*>(nodePtr);
@@ -64,9 +62,9 @@ AllocatorBlock* AllocatorReserveBlock(AllocatorBlock* allocator, unsigned nodeSi
         AllocatorNode* newNode = reinterpret_cast<AllocatorNode*>(nodePtr);
         AllocatorNode* newNode = reinterpret_cast<AllocatorNode*>(nodePtr);
         newNode->next_ = 0;
         newNode->next_ = 0;
     }
     }
-    
+
     allocator->free_ = firstNewNode;
     allocator->free_ = firstNewNode;
-    
+
     return newBlock;
     return newBlock;
 }
 }
 
 
@@ -90,7 +88,7 @@ void* AllocatorReserve(AllocatorBlock* allocator)
 {
 {
     if (!allocator)
     if (!allocator)
         return 0;
         return 0;
-    
+
     if (!allocator->free_)
     if (!allocator->free_)
     {
     {
         // Free nodes have been exhausted. Allocate a new larger block
         // Free nodes have been exhausted. Allocate a new larger block
@@ -98,13 +96,13 @@ void* AllocatorReserve(AllocatorBlock* allocator)
         AllocatorReserveBlock(allocator, allocator->nodeSize_, newCapacity);
         AllocatorReserveBlock(allocator, allocator->nodeSize_, newCapacity);
         allocator->capacity_ += newCapacity;
         allocator->capacity_ += newCapacity;
     }
     }
-    
+
     // We should have new free node(s) chained
     // We should have new free node(s) chained
     AllocatorNode* freeNode = allocator->free_;
     AllocatorNode* freeNode = allocator->free_;
     void* ptr = (reinterpret_cast<unsigned char*>(freeNode)) + sizeof(AllocatorNode);
     void* ptr = (reinterpret_cast<unsigned char*>(freeNode)) + sizeof(AllocatorNode);
     allocator->free_ = freeNode->next_;
     allocator->free_ = freeNode->next_;
     freeNode->next_ = 0;
     freeNode->next_ = 0;
-    
+
     return ptr;
     return ptr;
 }
 }
 
 
@@ -112,10 +110,10 @@ void AllocatorFree(AllocatorBlock* allocator, void* ptr)
 {
 {
     if (!allocator || !ptr)
     if (!allocator || !ptr)
         return;
         return;
-    
+
     unsigned char* dataPtr = static_cast<unsigned char*>(ptr);
     unsigned char* dataPtr = static_cast<unsigned char*>(ptr);
     AllocatorNode* node = reinterpret_cast<AllocatorNode*>(dataPtr - sizeof(AllocatorNode));
     AllocatorNode* node = reinterpret_cast<AllocatorNode*>(dataPtr - sizeof(AllocatorNode));
-    
+
     // Chain the node back to free nodes
     // Chain the node back to free nodes
     node->next_ = allocator->free_;
     node->next_ = allocator->free_;
     allocator->free_ = node;
     allocator->free_ = node;

+ 21 - 13
Source/Urho3D/Container/Allocator.h

@@ -22,7 +22,15 @@
 
 
 #pragma once
 #pragma once
 
 
-#include <new>
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
+#include <stddef.h>
+
+#include "../DebugNew.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {
@@ -70,50 +78,50 @@ public:
         allocator_(0)
         allocator_(0)
     {
     {
         if (initialCapacity)
         if (initialCapacity)
-            allocator_ = AllocatorInitialize(sizeof(T), initialCapacity);
+            allocator_ = AllocatorInitialize((unsigned)sizeof(T), initialCapacity);
     }
     }
-    
+
     /// Destruct.
     /// Destruct.
     ~Allocator()
     ~Allocator()
     {
     {
         AllocatorUninitialize(allocator_);
         AllocatorUninitialize(allocator_);
     }
     }
-    
+
     /// Reserve and default-construct an object.
     /// Reserve and default-construct an object.
     T* Reserve()
     T* Reserve()
     {
     {
         if (!allocator_)
         if (!allocator_)
-            allocator_ = AllocatorInitialize(sizeof(T));
+            allocator_ = AllocatorInitialize((unsigned)sizeof(T));
         T* newObject = static_cast<T*>(AllocatorReserve(allocator_));
         T* newObject = static_cast<T*>(AllocatorReserve(allocator_));
         new(newObject) T();
         new(newObject) T();
-        
+
         return newObject;
         return newObject;
     }
     }
-    
+
     /// Reserve and copy-construct an object.
     /// Reserve and copy-construct an object.
     T* Reserve(const T& object)
     T* Reserve(const T& object)
     {
     {
         if (!allocator_)
         if (!allocator_)
-            allocator_ = AllocatorInitialize(sizeof(T));
+            allocator_ = AllocatorInitialize((unsigned)sizeof(T));
         T* newObject = static_cast<T*>(AllocatorReserve(allocator_));
         T* newObject = static_cast<T*>(AllocatorReserve(allocator_));
         new(newObject) T(object);
         new(newObject) T(object);
-        
+
         return newObject;
         return newObject;
     }
     }
-    
+
     /// Destruct and free an object.
     /// Destruct and free an object.
     void Free(T* object)
     void Free(T* object)
     {
     {
         (object)->~T();
         (object)->~T();
         AllocatorFree(allocator_, object);
         AllocatorFree(allocator_, object);
     }
     }
-    
+
 private:
 private:
     /// Prevent copy construction.
     /// Prevent copy construction.
     Allocator(const Allocator<T>& rhs);
     Allocator(const Allocator<T>& rhs);
     /// Prevent assignment.
     /// Prevent assignment.
-    Allocator<T>& operator = (const Allocator<T>& rhs);
-    
+    Allocator<T>& operator =(const Allocator<T>& rhs);
+
     /// Allocator block.
     /// Allocator block.
     AllocatorBlock* allocator_;
     AllocatorBlock* allocator_;
 };
 };

+ 104 - 71
Source/Urho3D/Container/ArrayPtr.h

@@ -40,7 +40,7 @@ public:
         refCount_(0)
         refCount_(0)
     {
     {
     }
     }
-    
+
     /// Copy-construct from another shared array pointer.
     /// Copy-construct from another shared array pointer.
     SharedArrayPtr(const SharedArrayPtr<T>& rhs) :
     SharedArrayPtr(const SharedArrayPtr<T>& rhs) :
         ptr_(rhs.ptr_),
         ptr_(rhs.ptr_),
@@ -48,7 +48,7 @@ public:
     {
     {
         AddRef();
         AddRef();
     }
     }
-    
+
     /// Construct from a raw pointer.
     /// Construct from a raw pointer.
     explicit SharedArrayPtr(T* ptr) :
     explicit SharedArrayPtr(T* ptr) :
         ptr_(ptr),
         ptr_(ptr),
@@ -56,63 +56,81 @@ public:
     {
     {
         AddRef();
         AddRef();
     }
     }
-    
+
     /// Destruct. Release the array reference.
     /// Destruct. Release the array reference.
     ~SharedArrayPtr()
     ~SharedArrayPtr()
     {
     {
         ReleaseRef();
         ReleaseRef();
     }
     }
-    
+
     /// Assign from another shared array pointer.
     /// Assign from another shared array pointer.
-    SharedArrayPtr<T>& operator = (const SharedArrayPtr<T>& rhs)
+    SharedArrayPtr<T>& operator =(const SharedArrayPtr<T>& rhs)
     {
     {
         if (ptr_ == rhs.ptr_)
         if (ptr_ == rhs.ptr_)
             return *this;
             return *this;
-        
+
         ReleaseRef();
         ReleaseRef();
         ptr_ = rhs.ptr_;
         ptr_ = rhs.ptr_;
         refCount_ = rhs.refCount_;
         refCount_ = rhs.refCount_;
         AddRef();
         AddRef();
-        
+
         return *this;
         return *this;
     }
     }
-    
+
     /// Assign from a raw pointer.
     /// Assign from a raw pointer.
-    SharedArrayPtr<T>& operator = (T* ptr)
+    SharedArrayPtr<T>& operator =(T* ptr)
     {
     {
         if (ptr_ == ptr)
         if (ptr_ == ptr)
             return *this;
             return *this;
-        
+
         ReleaseRef();
         ReleaseRef();
-        
+
         if (ptr)
         if (ptr)
         {
         {
             ptr_ = ptr;
             ptr_ = ptr;
             refCount_ = new RefCount();
             refCount_ = new RefCount();
             AddRef();
             AddRef();
         }
         }
-        
+
         return *this;
         return *this;
     }
     }
-    
+
     /// Point to the array.
     /// Point to the array.
-    T* operator -> () const { assert(ptr_); return ptr_; }
+    T* operator ->() const
+    {
+        assert(ptr_);
+        return ptr_;
+    }
+
     /// Dereference the array.
     /// Dereference the array.
-    T& operator * () const { assert(ptr_); return *ptr_; }
+    T& operator *() const
+    {
+        assert(ptr_);
+        return *ptr_;
+    }
+
     /// Subscript the array.
     /// Subscript the array.
-    T& operator [] (const int index) { assert(ptr_); return ptr_[index]; }
+    T& operator [](const int index)
+    {
+        assert(ptr_);
+        return ptr_[index];
+    }
+
     /// Test for equality with another shared array pointer.
     /// Test for equality with another shared array pointer.
-    bool operator == (const SharedArrayPtr<T>& rhs) const { return ptr_ == rhs.ptr_; }
+    bool operator ==(const SharedArrayPtr<T>& rhs) const { return ptr_ == rhs.ptr_; }
+
     /// Test for inequality with another shared array pointer.
     /// Test for inequality with another shared array pointer.
-    bool operator != (const SharedArrayPtr<T>& rhs) const { return ptr_ != rhs.ptr_; }
+    bool operator !=(const SharedArrayPtr<T>& rhs) const { return ptr_ != rhs.ptr_; }
+
     /// Test for less than with another array pointer.
     /// Test for less than with another array pointer.
-    bool operator < (const SharedArrayPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+    bool operator <(const SharedArrayPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+
     /// Convert to a raw pointer.
     /// Convert to a raw pointer.
-    operator T* () const { return ptr_; }
-    
+    operator T*() const { return ptr_; }
+
     /// Reset to null and release the array reference.
     /// Reset to null and release the array reference.
     void Reset() { ReleaseRef(); }
     void Reset() { ReleaseRef(); }
-    
+
     /// Perform a static cast from a shared array pointer of another type.
     /// Perform a static cast from a shared array pointer of another type.
     template <class U> void StaticCast(const SharedArrayPtr<U>& rhs)
     template <class U> void StaticCast(const SharedArrayPtr<U>& rhs)
     {
     {
@@ -121,8 +139,8 @@ public:
         refCount_ = rhs.RefCountPtr();
         refCount_ = rhs.RefCountPtr();
         AddRef();
         AddRef();
     }
     }
-    
-   /// Perform a reinterpret cast from a shared array pointer of another type.
+
+    /// Perform a reinterpret cast from a shared array pointer of another type.
     template <class U> void ReinterpretCast(const SharedArrayPtr<U>& rhs)
     template <class U> void ReinterpretCast(const SharedArrayPtr<U>& rhs)
     {
     {
         ReleaseRef();
         ReleaseRef();
@@ -130,26 +148,32 @@ public:
         refCount_ = rhs.RefCountPtr();
         refCount_ = rhs.RefCountPtr();
         AddRef();
         AddRef();
     }
     }
-    
+
     /// Check if the pointer is null.
     /// Check if the pointer is null.
     bool Null() const { return ptr_ == 0; }
     bool Null() const { return ptr_ == 0; }
+
     /// Check if the pointer is not null.
     /// Check if the pointer is not null.
     bool NotNull() const { return ptr_ != 0; }
     bool NotNull() const { return ptr_ != 0; }
+
     /// Return the raw pointer.
     /// Return the raw pointer.
     T* Get() const { return ptr_; }
     T* Get() const { return ptr_; }
+
     /// Return the array's reference count, or 0 if the pointer is null.
     /// Return the array's reference count, or 0 if the pointer is null.
     int Refs() const { return refCount_ ? refCount_->refs_ : 0; }
     int Refs() const { return refCount_ ? refCount_->refs_ : 0; }
+
     /// Return the array's weak reference count, or 0 if the pointer is null.
     /// Return the array's weak reference count, or 0 if the pointer is null.
     int WeakRefs() const { return refCount_ ? refCount_->weakRefs_ : 0; }
     int WeakRefs() const { return refCount_ ? refCount_->weakRefs_ : 0; }
+
     /// Return pointer to the RefCount structure.
     /// Return pointer to the RefCount structure.
     RefCount* RefCountPtr() const { return refCount_; }
     RefCount* RefCountPtr() const { return refCount_; }
+
     /// Return hash value for HashSet & HashMap.
     /// Return hash value for HashSet & HashMap.
-    unsigned ToHash() const { return ((unsigned)(size_t)ptr_) / sizeof(T); }
-    
+    unsigned ToHash() const { return (unsigned)((size_t)ptr_ / sizeof(T)); }
+
 private:
 private:
     /// Prevent direct assignment from a shared array pointer of different type.
     /// Prevent direct assignment from a shared array pointer of different type.
-    template <class U> SharedArrayPtr<T>& operator = (const SharedArrayPtr<U>& rhs);
-    
+    template <class U> SharedArrayPtr<T>& operator =(const SharedArrayPtr<U>& rhs);
+
     /// Add a reference to the array pointed to.
     /// Add a reference to the array pointed to.
     void AddRef()
     void AddRef()
     {
     {
@@ -159,7 +183,7 @@ private:
             ++(refCount_->refs_);
             ++(refCount_->refs_);
         }
         }
     }
     }
-    
+
     /// Release the array reference and delete it and the RefCount structure if necessary.
     /// Release the array reference and delete it and the RefCount structure if necessary.
     void ReleaseRef()
     void ReleaseRef()
     {
     {
@@ -172,15 +196,15 @@ private:
                 refCount_->refs_ = -1;
                 refCount_->refs_ = -1;
                 delete[] ptr_;
                 delete[] ptr_;
             }
             }
-            
+
             if (refCount_->refs_ < 0 && !refCount_->weakRefs_)
             if (refCount_->refs_ < 0 && !refCount_->weakRefs_)
                 delete refCount_;
                 delete refCount_;
         }
         }
-        
+
         ptr_ = 0;
         ptr_ = 0;
         refCount_ = 0;
         refCount_ = 0;
     }
     }
-    
+
     /// Pointer to the array.
     /// Pointer to the array.
     T* ptr_;
     T* ptr_;
     /// Pointer to the RefCount structure.
     /// Pointer to the RefCount structure.
@@ -213,7 +237,7 @@ public:
         refCount_(0)
         refCount_(0)
     {
     {
     }
     }
-    
+
     /// Copy-construct from another weak array pointer.
     /// Copy-construct from another weak array pointer.
     WeakArrayPtr(const WeakArrayPtr<T>& rhs) :
     WeakArrayPtr(const WeakArrayPtr<T>& rhs) :
         ptr_(rhs.ptr_),
         ptr_(rhs.ptr_),
@@ -221,7 +245,7 @@ public:
     {
     {
         AddRef();
         AddRef();
     }
     }
-    
+
     /// Construct from a shared array pointer.
     /// Construct from a shared array pointer.
     WeakArrayPtr(const SharedArrayPtr<T>& rhs) :
     WeakArrayPtr(const SharedArrayPtr<T>& rhs) :
         ptr_(rhs.Get()),
         ptr_(rhs.Get()),
@@ -229,41 +253,41 @@ public:
     {
     {
         AddRef();
         AddRef();
     }
     }
-    
+
     /// Destruct. Release the weak reference to the array.
     /// Destruct. Release the weak reference to the array.
     ~WeakArrayPtr()
     ~WeakArrayPtr()
     {
     {
         ReleaseRef();
         ReleaseRef();
     }
     }
-    
+
     /// Assign from a shared array pointer.
     /// Assign from a shared array pointer.
-    WeakArrayPtr<T>& operator = (const SharedArrayPtr<T>& rhs)
+    WeakArrayPtr<T>& operator =(const SharedArrayPtr<T>& rhs)
     {
     {
         if (ptr_ == rhs.Get() && refCount_ == rhs.RefCountPtr())
         if (ptr_ == rhs.Get() && refCount_ == rhs.RefCountPtr())
             return *this;
             return *this;
-        
+
         ReleaseRef();
         ReleaseRef();
         ptr_ = rhs.Get();
         ptr_ = rhs.Get();
         refCount_ = rhs.RefCountPtr();
         refCount_ = rhs.RefCountPtr();
         AddRef();
         AddRef();
-        
+
         return *this;
         return *this;
     }
     }
-    
+
     /// Assign from another weak array pointer.
     /// Assign from another weak array pointer.
-    WeakArrayPtr<T>& operator = (const WeakArrayPtr<T>& rhs)
+    WeakArrayPtr<T>& operator =(const WeakArrayPtr<T>& rhs)
     {
     {
         if (ptr_ == rhs.ptr_ && refCount_ == rhs.refCount_)
         if (ptr_ == rhs.ptr_ && refCount_ == rhs.refCount_)
             return *this;
             return *this;
-        
+
         ReleaseRef();
         ReleaseRef();
         ptr_ = rhs.ptr_;
         ptr_ = rhs.ptr_;
         refCount_ = rhs.refCount_;
         refCount_ = rhs.refCount_;
         AddRef();
         AddRef();
-        
+
         return *this;
         return *this;
     }
     }
-    
+
     /// Convert to shared array pointer. If expired, return a null shared array pointer.
     /// Convert to shared array pointer. If expired, return a null shared array pointer.
     SharedArrayPtr<T> Lock() const
     SharedArrayPtr<T> Lock() const
     {
     {
@@ -272,7 +296,7 @@ public:
         else
         else
             return SharedArrayPtr<T>(ptr_, refCount_);
             return SharedArrayPtr<T>(ptr_, refCount_);
     }
     }
-    
+
     /// Return raw pointer. If expired, return null.
     /// Return raw pointer. If expired, return null.
     T* Get() const
     T* Get() const
     {
     {
@@ -281,43 +305,46 @@ public:
         else
         else
             return ptr_;
             return ptr_;
     }
     }
-    
+
     /// Point to the array.
     /// Point to the array.
-    T* operator -> () const
+    T* operator ->() const
     {
     {
         T* rawPtr = Get();
         T* rawPtr = Get();
         assert(rawPtr);
         assert(rawPtr);
         return rawPtr;
         return rawPtr;
     }
     }
-    
+
     /// Dereference the array.
     /// Dereference the array.
-    T& operator * () const
+    T& operator *() const
     {
     {
         T* rawPtr = Get();
         T* rawPtr = Get();
         assert(rawPtr);
         assert(rawPtr);
         return *rawPtr;
         return *rawPtr;
     }
     }
-    
+
     /// Subscript the array.
     /// Subscript the array.
-    T& operator [] (const int index)
+    T& operator [](const int index)
     {
     {
         T* rawPtr = Get();
         T* rawPtr = Get();
         assert(rawPtr);
         assert(rawPtr);
         return (*rawPtr)[index];
         return (*rawPtr)[index];
     }
     }
-    
+
     /// Test for equality with another weak array pointer.
     /// Test for equality with another weak array pointer.
-    bool operator == (const WeakArrayPtr<T>& rhs) const { return ptr_ == rhs.ptr_ && refCount_ == rhs.refCount_; }
+    bool operator ==(const WeakArrayPtr<T>& rhs) const { return ptr_ == rhs.ptr_ && refCount_ == rhs.refCount_; }
+
     /// Test for inequality with another weak array pointer.
     /// Test for inequality with another weak array pointer.
-    bool operator != (const WeakArrayPtr<T>& rhs) const { return ptr_ != rhs.ptr_ || refCount_ != rhs.refCount_; }
+    bool operator !=(const WeakArrayPtr<T>& rhs) const { return ptr_ != rhs.ptr_ || refCount_ != rhs.refCount_; }
+
     /// Test for less than with another weak array pointer.
     /// Test for less than with another weak array pointer.
-    bool operator < (const WeakArrayPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+    bool operator <(const WeakArrayPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+
     /// Convert to a raw pointer, null if array is expired.
     /// Convert to a raw pointer, null if array is expired.
-    operator T* () const { return Get(); }
-    
+    operator T*() const { return Get(); }
+
     /// Reset to null and release the weak reference.
     /// Reset to null and release the weak reference.
     void Reset() { ReleaseRef(); }
     void Reset() { ReleaseRef(); }
-    
+
     /// Perform a static cast from a weak array pointer of another type.
     /// Perform a static cast from a weak array pointer of another type.
     template <class U> void StaticCast(const WeakArrayPtr<U>& rhs)
     template <class U> void StaticCast(const WeakArrayPtr<U>& rhs)
     {
     {
@@ -326,13 +353,13 @@ public:
         refCount_ = rhs.refCount_;
         refCount_ = rhs.refCount_;
         AddRef();
         AddRef();
     }
     }
-    
+
     /// Perform a dynamic cast from a weak array pointer of another type.
     /// Perform a dynamic cast from a weak array pointer of another type.
     template <class U> void DynamicCast(const WeakArrayPtr<U>& rhs)
     template <class U> void DynamicCast(const WeakArrayPtr<U>& rhs)
     {
     {
         ReleaseRef();
         ReleaseRef();
         ptr_ = dynamic_cast<T*>(rhs.Get());
         ptr_ = dynamic_cast<T*>(rhs.Get());
-        
+
         if (ptr_)
         if (ptr_)
         {
         {
             refCount_ = rhs.refCount_;
             refCount_ = rhs.refCount_;
@@ -341,26 +368,32 @@ public:
         else
         else
             refCount_ = 0;
             refCount_ = 0;
     }
     }
-    
+
     /// Check if the pointer is null.
     /// Check if the pointer is null.
     bool Null() const { return refCount_ == 0; }
     bool Null() const { return refCount_ == 0; }
+
     /// Check if the pointer is not null.
     /// Check if the pointer is not null.
     bool NotNull() const { return refCount_ != 0; }
     bool NotNull() const { return refCount_ != 0; }
+
     /// Return the array's reference count, or 0 if null pointer or if array has expired.
     /// Return the array's reference count, or 0 if null pointer or if array has expired.
     int Refs() const { return (refCount_ && refCount_->refs_ >= 0) ? refCount_->refs_ : 0; }
     int Refs() const { return (refCount_ && refCount_->refs_ >= 0) ? refCount_->refs_ : 0; }
+
     /// Return the array's weak reference count.
     /// Return the array's weak reference count.
     int WeakRefs() const { return refCount_ ? refCount_->weakRefs_ : 0; }
     int WeakRefs() const { return refCount_ ? refCount_->weakRefs_ : 0; }
+
     /// Return whether the array has expired. If null pointer, always return true.
     /// Return whether the array has expired. If null pointer, always return true.
     bool Expired() const { return refCount_ ? refCount_->refs_ < 0 : true; }
     bool Expired() const { return refCount_ ? refCount_->refs_ < 0 : true; }
+
     /// Return pointer to RefCount structure.
     /// Return pointer to RefCount structure.
     RefCount* RefCountPtr() const { return refCount_; }
     RefCount* RefCountPtr() const { return refCount_; }
+
     /// Return hash value for HashSet & HashMap.
     /// Return hash value for HashSet & HashMap.
-    unsigned ToHash() const { return ((unsigned)(size_t)ptr_) / sizeof(T); }
-    
+    unsigned ToHash() const { return (unsigned)((size_t)ptr_ / sizeof(T)); }
+
 private:
 private:
     /// Prevent direct assignment from a weak array pointer of different type.
     /// Prevent direct assignment from a weak array pointer of different type.
-    template <class U> WeakArrayPtr<T>& operator = (const WeakArrayPtr<U>& rhs);
-    
+    template <class U> WeakArrayPtr<T>& operator =(const WeakArrayPtr<U>& rhs);
+
     /// Add a weak reference to the array pointed to.
     /// Add a weak reference to the array pointed to.
     void AddRef()
     void AddRef()
     {
     {
@@ -370,25 +403,25 @@ private:
             ++(refCount_->weakRefs_);
             ++(refCount_->weakRefs_);
         }
         }
     }
     }
-    
+
     /// Release the weak reference. Delete the Refcount structure if necessary.
     /// Release the weak reference. Delete the Refcount structure if necessary.
     void ReleaseRef()
     void ReleaseRef()
     {
     {
         if (refCount_)
         if (refCount_)
         {
         {
             assert(refCount_->weakRefs_ >= 0);
             assert(refCount_->weakRefs_ >= 0);
-            
+
             if (refCount_->weakRefs_ > 0)
             if (refCount_->weakRefs_ > 0)
                 --(refCount_->weakRefs_);
                 --(refCount_->weakRefs_);
-            
+
             if (Expired() && !refCount_->weakRefs_)
             if (Expired() && !refCount_->weakRefs_)
                 delete refCount_;
                 delete refCount_;
         }
         }
-        
+
         ptr_ = 0;
         ptr_ = 0;
         refCount_ = 0;
         refCount_ = 0;
     }
     }
-    
+
     /// Pointer to the array.
     /// Pointer to the array.
     T* ptr_;
     T* ptr_;
     /// Pointer to the RefCount structure.
     /// Pointer to the RefCount structure.

+ 17 - 17
Source/Urho3D/Container/Hash.h

@@ -30,13 +30,13 @@ namespace Urho3D
 /// Pointer hash function.
 /// Pointer hash function.
 template <class T> unsigned MakeHash(T* value)
 template <class T> unsigned MakeHash(T* value)
 {
 {
-    return ((unsigned)(size_t)value) / sizeof(T);
+    return (unsigned)((size_t)value / sizeof(T));
 }
 }
 
 
 /// Const pointer hash function.
 /// Const pointer hash function.
 template <class T> unsigned MakeHash(const T* value)
 template <class T> unsigned MakeHash(const T* value)
 {
 {
-    return ((unsigned)(size_t)value) / sizeof(T);
+    return (unsigned)((size_t)value / sizeof(T));
 }
 }
 
 
 /// Generic hash function.
 /// Generic hash function.
@@ -46,61 +46,61 @@ template <class T> unsigned MakeHash(const T& value)
 }
 }
 
 
 /// Void pointer hash function.
 /// Void pointer hash function.
-template<> inline unsigned MakeHash(void* value)
+template <> inline unsigned MakeHash(void* value)
 {
 {
     return (unsigned)(size_t)value;
     return (unsigned)(size_t)value;
 }
 }
 
 
 /// Const void pointer hash function.
 /// Const void pointer hash function.
-template<> inline unsigned MakeHash(const void* value)
+template <> inline unsigned MakeHash(const void* value)
 {
 {
     return (unsigned)(size_t)value;
     return (unsigned)(size_t)value;
 }
 }
 
 
 /// Long long hash function.
 /// Long long hash function.
-template<> inline unsigned MakeHash(const long long& value)
+template <> inline unsigned MakeHash(const long long& value)
 {
 {
-    return (value >> 32) | (value & 0xffffffff);
+    return (unsigned)((value >> 32) | (value & 0xffffffff));
 }
 }
 
 
 /// Unsigned long long hash function.
 /// Unsigned long long hash function.
-template<> inline unsigned MakeHash(const unsigned long long& value)
+template <> inline unsigned MakeHash(const unsigned long long& value)
 {
 {
-    return (value >> 32) | (value & 0xffffffff);
+    return (unsigned)((value >> 32) | (value & 0xffffffff));
 }
 }
 
 
 /// Int hash function.
 /// Int hash function.
-template<> inline unsigned MakeHash(const int& value)
+template <> inline unsigned MakeHash(const int& value)
 {
 {
-    return value;
+    return (unsigned)value;
 }
 }
 
 
 /// Unsigned hash function.
 /// Unsigned hash function.
-template<> inline unsigned MakeHash(const unsigned& value)
+template <> inline unsigned MakeHash(const unsigned& value)
 {
 {
     return value;
     return value;
 }
 }
 
 
 /// Short hash function.
 /// Short hash function.
-template<> inline unsigned MakeHash(const short& value)
+template <> inline unsigned MakeHash(const short& value)
 {
 {
-    return value;
+    return (unsigned)value;
 }
 }
 
 
 /// Unsigned short hash function.
 /// Unsigned short hash function.
-template<> inline unsigned MakeHash(const unsigned short& value)
+template <> inline unsigned MakeHash(const unsigned short& value)
 {
 {
     return value;
     return value;
 }
 }
 
 
 /// Char hash function.
 /// Char hash function.
-template<> inline unsigned MakeHash(const char& value)
+template <> inline unsigned MakeHash(const char& value)
 {
 {
-    return value;
+    return (unsigned)value;
 }
 }
 
 
 /// Unsigned char hash function.
 /// Unsigned char hash function.
-template<> inline unsigned MakeHash(const unsigned char& value)
+template <> inline unsigned MakeHash(const unsigned char& value)
 {
 {
     return value;
     return value;
 }
 }

+ 5 - 5
Source/Urho3D/Container/HashBase.cpp

@@ -20,7 +20,7 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
-#include "../Container/HashBase.h"
+#include "../Precompiled.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -31,13 +31,13 @@ void HashBase::AllocateBuckets(unsigned size, unsigned numBuckets)
 {
 {
     if (ptrs_)
     if (ptrs_)
         delete[] ptrs_;
         delete[] ptrs_;
-    
-    HashNodeBase** ptrs = new HashNodeBase*[numBuckets + 2];
+
+    HashNodeBase** ptrs = new HashNodeBase* [numBuckets + 2];
     unsigned* data = reinterpret_cast<unsigned*>(ptrs);
     unsigned* data = reinterpret_cast<unsigned*>(ptrs);
     data[0] = size;
     data[0] = size;
     data[1] = numBuckets;
     data[1] = numBuckets;
     ptrs_ = ptrs;
     ptrs_ = ptrs;
-    
+
     ResetPtrs();
     ResetPtrs();
 }
 }
 
 
@@ -46,7 +46,7 @@ void HashBase::ResetPtrs()
     // Reset bucket pointers
     // Reset bucket pointers
     if (!ptrs_)
     if (!ptrs_)
         return;
         return;
-    
+
     unsigned numBuckets = NumBuckets();
     unsigned numBuckets = NumBuckets();
     HashNodeBase** ptrs = Ptrs();
     HashNodeBase** ptrs = Ptrs();
     for (unsigned i = 0; i < numBuckets; ++i)
     for (unsigned i = 0; i < numBuckets; ++i)

+ 24 - 12
Source/Urho3D/Container/HashBase.h

@@ -22,6 +22,12 @@
 
 
 #pragma once
 #pragma once
 
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 #include "../Container/Allocator.h"
 #include "../Container/Allocator.h"
 #include "../Container/Hash.h"
 #include "../Container/Hash.h"
 #include "../Container/Swap.h"
 #include "../Container/Swap.h"
@@ -39,7 +45,7 @@ struct HashNodeBase
         next_(0)
         next_(0)
     {
     {
     }
     }
-    
+
     /// Next node in the bucket.
     /// Next node in the bucket.
     HashNodeBase* down_;
     HashNodeBase* down_;
     /// Previous node.
     /// Previous node.
@@ -56,32 +62,33 @@ struct HashIteratorBase
         ptr_(0)
         ptr_(0)
     {
     {
     }
     }
-    
+
     /// Construct with a node pointer.
     /// Construct with a node pointer.
     explicit HashIteratorBase(HashNodeBase* ptr) :
     explicit HashIteratorBase(HashNodeBase* ptr) :
         ptr_(ptr)
         ptr_(ptr)
     {
     {
     }
     }
-    
+
     /// Test for equality with another iterator.
     /// Test for equality with another iterator.
-    bool operator == (const HashIteratorBase& rhs) const { return ptr_ == rhs.ptr_; }
+    bool operator ==(const HashIteratorBase& rhs) const { return ptr_ == rhs.ptr_; }
+
     /// Test for inequality with another iterator.
     /// Test for inequality with another iterator.
-    bool operator != (const HashIteratorBase& rhs) const { return ptr_ != rhs.ptr_; }
-    
+    bool operator !=(const HashIteratorBase& rhs) const { return ptr_ != rhs.ptr_; }
+
     /// Go to the next node.
     /// Go to the next node.
     void GotoNext()
     void GotoNext()
     {
     {
         if (ptr_)
         if (ptr_)
             ptr_ = ptr_->next_;
             ptr_ = ptr_->next_;
     }
     }
-    
+
     /// Go to the previous node.
     /// Go to the previous node.
     void GotoPrev()
     void GotoPrev()
     {
     {
         if (ptr_)
         if (ptr_)
             ptr_ = ptr_->prev_;
             ptr_ = ptr_->prev_;
     }
     }
-    
+
     /// Node pointer.
     /// Node pointer.
     HashNodeBase* ptr_;
     HashNodeBase* ptr_;
 };
 };
@@ -97,7 +104,7 @@ public:
     static const unsigned MIN_BUCKETS = 8;
     static const unsigned MIN_BUCKETS = 8;
     /// Maximum load factor.
     /// Maximum load factor.
     static const unsigned MAX_LOAD_FACTOR = 4;
     static const unsigned MAX_LOAD_FACTOR = 4;
-    
+
     /// Construct.
     /// Construct.
     HashBase() :
     HashBase() :
         ptrs_(0),
         ptrs_(0),
@@ -113,24 +120,29 @@ public:
         Urho3D::Swap(ptrs_, rhs.ptrs_);
         Urho3D::Swap(ptrs_, rhs.ptrs_);
         Urho3D::Swap(allocator_, rhs.allocator_);
         Urho3D::Swap(allocator_, rhs.allocator_);
     }
     }
-    
+
     /// Return number of elements.
     /// Return number of elements.
     unsigned Size() const { return ptrs_ ? (reinterpret_cast<unsigned*>(ptrs_))[0] : 0; }
     unsigned Size() const { return ptrs_ ? (reinterpret_cast<unsigned*>(ptrs_))[0] : 0; }
+
     /// Return number of buckets.
     /// Return number of buckets.
     unsigned NumBuckets() const { return ptrs_ ? (reinterpret_cast<unsigned*>(ptrs_))[1] : 0; }
     unsigned NumBuckets() const { return ptrs_ ? (reinterpret_cast<unsigned*>(ptrs_))[1] : 0; }
+
     /// Return whether has no elements.
     /// Return whether has no elements.
     bool Empty() const { return Size() == 0; }
     bool Empty() const { return Size() == 0; }
-    
+
 protected:
 protected:
     /// Allocate bucket head pointers + room for size and bucket count variables.
     /// Allocate bucket head pointers + room for size and bucket count variables.
     void AllocateBuckets(unsigned size, unsigned numBuckets);
     void AllocateBuckets(unsigned size, unsigned numBuckets);
+
     /// Reset bucket head pointers.
     /// Reset bucket head pointers.
     void ResetPtrs();
     void ResetPtrs();
+
     /// Set new size.
     /// Set new size.
     void SetSize(unsigned size) { if (ptrs_) (reinterpret_cast<unsigned*>(ptrs_))[0] = size; }
     void SetSize(unsigned size) { if (ptrs_) (reinterpret_cast<unsigned*>(ptrs_))[0] = size; }
+
     /// Return bucket head pointers.
     /// Return bucket head pointers.
     HashNodeBase** Ptrs() const { return ptrs_ ? ptrs_ + 2 : 0; }
     HashNodeBase** Ptrs() const { return ptrs_ ? ptrs_ + 2 : 0; }
-    
+
     /// List head node pointer.
     /// List head node pointer.
     HashNodeBase* head_;
     HashNodeBase* head_;
     /// List tail node pointer.
     /// List tail node pointer.

+ 202 - 129
Source/Urho3D/Container/HashMap.h

@@ -38,7 +38,7 @@ template <class T, class U> class HashMap : public HashBase
 public:
 public:
     typedef T KeyType;
     typedef T KeyType;
     typedef U ValueType;
     typedef U ValueType;
-    
+
     /// Hash map key-value pair with const key.
     /// Hash map key-value pair with const key.
     class KeyValue
     class KeyValue
     {
     {
@@ -48,36 +48,37 @@ public:
             first_(T())
             first_(T())
         {
         {
         }
         }
-        
+
         /// Construct with key and value.
         /// Construct with key and value.
         KeyValue(const T& first, const U& second) :
         KeyValue(const T& first, const U& second) :
             first_(first),
             first_(first),
             second_(second)
             second_(second)
         {
         {
         }
         }
-        
+
         /// Copy-construct.
         /// Copy-construct.
         KeyValue(const KeyValue& value) :
         KeyValue(const KeyValue& value) :
             first_(value.first_),
             first_(value.first_),
             second_(value.second_)
             second_(value.second_)
         {
         {
         }
         }
-        
+
         /// Test for equality with another pair.
         /// Test for equality with another pair.
-        bool operator == (const KeyValue& rhs) const { return first_ == rhs.first_ && second_ == rhs.second_; }
+        bool operator ==(const KeyValue& rhs) const { return first_ == rhs.first_ && second_ == rhs.second_; }
+
         /// Test for inequality with another pair.
         /// Test for inequality with another pair.
-        bool operator != (const KeyValue& rhs) const { return first_ != rhs.first_ || second_ != rhs.second_; }
-        
+        bool operator !=(const KeyValue& rhs) const { return first_ != rhs.first_ || second_ != rhs.second_; }
+
         /// Key.
         /// Key.
         const T first_;
         const T first_;
         /// Value.
         /// Value.
         U second_;
         U second_;
-        
+
     private:
     private:
         /// Prevent assignment.
         /// Prevent assignment.
-        KeyValue& operator = (const KeyValue& rhs);
+        KeyValue& operator =(const KeyValue& rhs);
     };
     };
-    
+
     /// Hash map node.
     /// Hash map node.
     struct Node : public HashNodeBase
     struct Node : public HashNodeBase
     {
     {
@@ -85,24 +86,26 @@ public:
         Node()
         Node()
         {
         {
         }
         }
-        
+
         /// Construct with key and value.
         /// Construct with key and value.
         Node(const T& key, const U& value) :
         Node(const T& key, const U& value) :
             pair_(key, value)
             pair_(key, value)
         {
         {
         }
         }
-        
+
         /// Key-value pair.
         /// Key-value pair.
         KeyValue pair_;
         KeyValue pair_;
-        
+
         /// Return next node.
         /// Return next node.
         Node* Next() const { return static_cast<Node*>(next_); }
         Node* Next() const { return static_cast<Node*>(next_); }
+
         /// Return previous node.
         /// Return previous node.
         Node* Prev() const { return static_cast<Node*>(prev_); }
         Node* Prev() const { return static_cast<Node*>(prev_); }
+
         /// Return next node in the bucket.
         /// Return next node in the bucket.
         Node* Down() const { return static_cast<Node*>(down_); }
         Node* Down() const { return static_cast<Node*>(down_); }
     };
     };
-    
+
     /// Hash map node iterator.
     /// Hash map node iterator.
     struct Iterator : public HashIteratorBase
     struct Iterator : public HashIteratorBase
     {
     {
@@ -110,28 +113,50 @@ public:
         Iterator()
         Iterator()
         {
         {
         }
         }
-        
+
         /// Construct with a node pointer.
         /// Construct with a node pointer.
         Iterator(Node* ptr) :
         Iterator(Node* ptr) :
             HashIteratorBase(ptr)
             HashIteratorBase(ptr)
         {
         {
         }
         }
-        
+
         /// Preincrement the pointer.
         /// Preincrement the pointer.
-        Iterator& operator ++ () { GotoNext(); return *this; }
+        Iterator& operator ++()
+        {
+            GotoNext();
+            return *this;
+        }
+
         /// Postincrement the pointer.
         /// Postincrement the pointer.
-        Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
+        Iterator operator ++(int)
+        {
+            Iterator it = *this;
+            GotoNext();
+            return it;
+        }
+
         /// Predecrement the pointer.
         /// Predecrement the pointer.
-        Iterator& operator -- () { GotoPrev(); return *this; }
+        Iterator& operator --()
+        {
+            GotoPrev();
+            return *this;
+        }
+
         /// Postdecrement the pointer.
         /// Postdecrement the pointer.
-        Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
-        
+        Iterator operator --(int)
+        {
+            Iterator it = *this;
+            GotoPrev();
+            return it;
+        }
+
         /// Point to the pair.
         /// Point to the pair.
-        KeyValue* operator -> () const { return &(static_cast<Node*>(ptr_))->pair_; }
+        KeyValue* operator ->() const { return &(static_cast<Node*>(ptr_))->pair_; }
+
         /// Dereference the pair.
         /// Dereference the pair.
-        KeyValue& operator * () const { return (static_cast<Node*>(ptr_))->pair_; }
+        KeyValue& operator *() const { return (static_cast<Node*>(ptr_))->pair_; }
     };
     };
-    
+
     /// Hash map node const iterator.
     /// Hash map node const iterator.
     struct ConstIterator : public HashIteratorBase
     struct ConstIterator : public HashIteratorBase
     {
     {
@@ -139,53 +164,80 @@ public:
         ConstIterator()
         ConstIterator()
         {
         {
         }
         }
-        
+
         /// Construct with a node pointer.
         /// Construct with a node pointer.
         ConstIterator(Node* ptr) :
         ConstIterator(Node* ptr) :
             HashIteratorBase(ptr)
             HashIteratorBase(ptr)
         {
         {
         }
         }
-        
+
         /// Construct from a non-const iterator.
         /// Construct from a non-const iterator.
         ConstIterator(const Iterator& rhs) :
         ConstIterator(const Iterator& rhs) :
             HashIteratorBase(rhs.ptr_)
             HashIteratorBase(rhs.ptr_)
         {
         {
         }
         }
-        
+
         /// Assign from a non-const iterator.
         /// Assign from a non-const iterator.
-        ConstIterator& operator = (const Iterator& rhs) { ptr_ = rhs.ptr_; return *this; }
+        ConstIterator& operator =(const Iterator& rhs)
+        {
+            ptr_ = rhs.ptr_;
+            return *this;
+        }
+
         /// Preincrement the pointer.
         /// Preincrement the pointer.
-        ConstIterator& operator ++ () { GotoNext(); return *this; }
+        ConstIterator& operator ++()
+        {
+            GotoNext();
+            return *this;
+        }
+
         /// Postincrement the pointer.
         /// Postincrement the pointer.
-        ConstIterator operator ++ (int) { ConstIterator it = *this; GotoNext(); return it; }
+        ConstIterator operator ++(int)
+        {
+            ConstIterator it = *this;
+            GotoNext();
+            return it;
+        }
+
         /// Predecrement the pointer.
         /// Predecrement the pointer.
-        ConstIterator& operator -- () { GotoPrev(); return *this; }
+        ConstIterator& operator --()
+        {
+            GotoPrev();
+            return *this;
+        }
+
         /// Postdecrement the pointer.
         /// Postdecrement the pointer.
-        ConstIterator operator -- (int) { ConstIterator it = *this; GotoPrev(); return it; }
-        
+        ConstIterator operator --(int)
+        {
+            ConstIterator it = *this;
+            GotoPrev();
+            return it;
+        }
+
         /// Point to the pair.
         /// Point to the pair.
-        const KeyValue* operator -> () const { return &(static_cast<Node*>(ptr_))->pair_; }
+        const KeyValue* operator ->() const { return &(static_cast<Node*>(ptr_))->pair_; }
+
         /// Dereference the pair.
         /// Dereference the pair.
-        const KeyValue& operator * () const { return (static_cast<Node*>(ptr_))->pair_; }
+        const KeyValue& operator *() const { return (static_cast<Node*>(ptr_))->pair_; }
     };
     };
-    
+
     /// Construct empty.
     /// Construct empty.
     HashMap()
     HashMap()
     {
     {
         // Reserve the tail node
         // Reserve the tail node
-        allocator_ = AllocatorInitialize(sizeof(Node));
+        allocator_ = AllocatorInitialize((unsigned)sizeof(Node));
         head_ = tail_ = ReserveNode();
         head_ = tail_ = ReserveNode();
     }
     }
-    
+
     /// Construct from another hash map.
     /// Construct from another hash map.
     HashMap(const HashMap<T, U>& map)
     HashMap(const HashMap<T, U>& map)
     {
     {
         // Reserve the tail node + initial capacity according to the map's size
         // Reserve the tail node + initial capacity according to the map's size
-        allocator_ = AllocatorInitialize(sizeof(Node), map.Size() + 1);
+        allocator_ = AllocatorInitialize((unsigned)sizeof(Node), map.Size() + 1);
         head_ = tail_ = ReserveNode();
         head_ = tail_ = ReserveNode();
         *this = map;
         *this = map;
     }
     }
-    
+
     /// Destruct.
     /// Destruct.
     ~HashMap()
     ~HashMap()
     {
     {
@@ -194,35 +246,35 @@ public:
         AllocatorUninitialize(allocator_);
         AllocatorUninitialize(allocator_);
         delete[] ptrs_;
         delete[] ptrs_;
     }
     }
-    
+
     /// Assign a hash map.
     /// Assign a hash map.
-    HashMap& operator = (const HashMap<T, U>& rhs)
+    HashMap& operator =(const HashMap<T, U>& rhs)
     {
     {
         Clear();
         Clear();
         Insert(rhs);
         Insert(rhs);
         return *this;
         return *this;
     }
     }
-    
+
     /// Add-assign a pair.
     /// Add-assign a pair.
-    HashMap& operator += (const Pair<T, U>& rhs)
+    HashMap& operator +=(const Pair<T, U>& rhs)
     {
     {
         Insert(rhs);
         Insert(rhs);
         return *this;
         return *this;
     }
     }
-    
+
     /// Add-assign a hash map.
     /// Add-assign a hash map.
-    HashMap& operator += (const HashMap<T, U>& rhs)
+    HashMap& operator +=(const HashMap<T, U>& rhs)
     {
     {
         Insert(rhs);
         Insert(rhs);
         return *this;
         return *this;
     }
     }
-    
+
     /// Test for equality with another hash map.
     /// Test for equality with another hash map.
-    bool operator == (const HashMap<T, U>& rhs) const
+    bool operator ==(const HashMap<T, U>& rhs) const
     {
     {
         if (rhs.Size() != Size())
         if (rhs.Size() != Size())
             return false;
             return false;
-        
+
         ConstIterator i = Begin();
         ConstIterator i = Begin();
         while (i != End())
         while (i != End())
         {
         {
@@ -231,16 +283,16 @@ public:
                 return false;
                 return false;
             ++i;
             ++i;
         }
         }
-        
+
         return true;
         return true;
     }
     }
-    
+
     /// Test for inequality with another hash map.
     /// Test for inequality with another hash map.
-    bool operator != (const HashMap<T, U>& rhs) const
+    bool operator !=(const HashMap<T, U>& rhs) const
     {
     {
         if (rhs.Size() != Size())
         if (rhs.Size() != Size())
             return true;
             return true;
-        
+
         ConstIterator i = Begin();
         ConstIterator i = Begin();
         while (i != End())
         while (i != End())
         {
         {
@@ -249,31 +301,40 @@ public:
                 return true;
                 return true;
             ++i;
             ++i;
         }
         }
-        
+
         return false;
         return false;
     }
     }
-    
+
     /// Index the map. Create a new pair if key not found.
     /// Index the map. Create a new pair if key not found.
-    U& operator [] (const T& key)
+    U& operator [](const T& key)
     {
     {
         if (!ptrs_)
         if (!ptrs_)
             return InsertNode(key, U(), false)->pair_.second_;
             return InsertNode(key, U(), false)->pair_.second_;
-        
+
         unsigned hashKey = Hash(key);
         unsigned hashKey = Hash(key);
-        
+
         Node* node = FindNode(key, hashKey);
         Node* node = FindNode(key, hashKey);
-        if (node)
-            return node->pair_.second_;
-        else
-            return InsertNode(key, U(), false)->pair_.second_;
+        return node ? node->pair_.second_ : InsertNode(key, U(), false)->pair_.second_;
+    }
+
+    /// Index the map. Return null if key is not found, does not create a new pair.
+    U* operator [](const T& key) const
+    {
+        if (!ptrs_)
+            return 0;
+
+        unsigned hashKey = Hash(key);
+
+        Node* node = FindNode(key, hashKey);
+        return node ? &node->pair_.second_ : 0;
     }
     }
-    
+
     /// Insert a pair. Return an iterator to it.
     /// Insert a pair. Return an iterator to it.
     Iterator Insert(const Pair<T, U>& pair)
     Iterator Insert(const Pair<T, U>& pair)
     {
     {
         return Iterator(InsertNode(pair.first_, pair.second_));
         return Iterator(InsertNode(pair.first_, pair.second_));
     }
     }
-    
+
     /// Insert a map.
     /// Insert a map.
     void Insert(const HashMap<T, U>& map)
     void Insert(const HashMap<T, U>& map)
     {
     {
@@ -285,10 +346,10 @@ public:
             ++it;
             ++it;
         }
         }
     }
     }
-    
+
     /// Insert a pair by iterator. Return iterator to the value.
     /// Insert a pair by iterator. Return iterator to the value.
     Iterator Insert(const ConstIterator& it) { return Iterator(InsertNode(it->first_, it->second_)); }
     Iterator Insert(const ConstIterator& it) { return Iterator(InsertNode(it->first_, it->second_)); }
-    
+
     /// Insert a range by iterators.
     /// Insert a range by iterators.
     void Insert(const ConstIterator& start, const ConstIterator& end)
     void Insert(const ConstIterator& start, const ConstIterator& end)
     {
     {
@@ -296,40 +357,40 @@ public:
         while (it != end)
         while (it != end)
             InsertNode(*it++);
             InsertNode(*it++);
     }
     }
-    
+
     /// Erase a pair by key. Return true if was found.
     /// Erase a pair by key. Return true if was found.
     bool Erase(const T& key)
     bool Erase(const T& key)
     {
     {
         if (!ptrs_)
         if (!ptrs_)
             return false;
             return false;
-        
+
         unsigned hashKey = Hash(key);
         unsigned hashKey = Hash(key);
-        
+
         Node* previous;
         Node* previous;
         Node* node = FindNode(key, hashKey, previous);
         Node* node = FindNode(key, hashKey, previous);
         if (!node)
         if (!node)
             return false;
             return false;
-        
+
         if (previous)
         if (previous)
             previous->down_ = node->down_;
             previous->down_ = node->down_;
         else
         else
             Ptrs()[hashKey] = node->down_;
             Ptrs()[hashKey] = node->down_;
-        
+
         EraseNode(node);
         EraseNode(node);
         return true;
         return true;
     }
     }
-    
+
     /// Erase a pair by iterator. Return iterator to the next pair.
     /// Erase a pair by iterator. Return iterator to the next pair.
     Iterator Erase(const Iterator& it)
     Iterator Erase(const Iterator& it)
     {
     {
         if (!ptrs_ || !it.ptr_)
         if (!ptrs_ || !it.ptr_)
             return End();
             return End();
-        
+
         Node* node = static_cast<Node*>(it.ptr_);
         Node* node = static_cast<Node*>(it.ptr_);
         Node* next = node->Next();
         Node* next = node->Next();
-        
+
         unsigned hashKey = Hash(node->pair_.first_);
         unsigned hashKey = Hash(node->pair_.first_);
-        
+
         Node* previous = 0;
         Node* previous = 0;
         Node* current = static_cast<Node*>(Ptrs()[hashKey]);
         Node* current = static_cast<Node*>(Ptrs()[hashKey]);
         while (current && current != node)
         while (current && current != node)
@@ -337,54 +398,54 @@ public:
             previous = current;
             previous = current;
             current = current->Down();
             current = current->Down();
         }
         }
-        
+
         assert(current == node);
         assert(current == node);
-        
+
         if (previous)
         if (previous)
             previous->down_ = node->down_;
             previous->down_ = node->down_;
         else
         else
             Ptrs()[hashKey] = node->down_;
             Ptrs()[hashKey] = node->down_;
-        
+
         EraseNode(node);
         EraseNode(node);
         return Iterator(next);
         return Iterator(next);
     }
     }
-    
+
     /// Clear the map.
     /// Clear the map.
     void Clear()
     void Clear()
     {
     {
         if (Size())
         if (Size())
         {
         {
-            for (Iterator i = Begin(); i != End(); )
+            for (Iterator i = Begin(); i != End();)
             {
             {
                 FreeNode(static_cast<Node*>(i++.ptr_));
                 FreeNode(static_cast<Node*>(i++.ptr_));
                 i.ptr_->prev_ = 0;
                 i.ptr_->prev_ = 0;
             }
             }
-            
+
             head_ = tail_;
             head_ = tail_;
             SetSize(0);
             SetSize(0);
         }
         }
-        
+
         ResetPtrs();
         ResetPtrs();
     }
     }
-    
+
     /// Sort pairs. After sorting the map can be iterated in order until new elements are inserted.
     /// Sort pairs. After sorting the map can be iterated in order until new elements are inserted.
     void Sort()
     void Sort()
     {
     {
         unsigned numKeys = Size();
         unsigned numKeys = Size();
         if (!numKeys)
         if (!numKeys)
             return;
             return;
-        
-        Node** ptrs = new Node*[numKeys];
+
+        Node** ptrs = new Node* [numKeys];
         Node* ptr = Head();
         Node* ptr = Head();
-        
+
         for (unsigned i = 0; i < numKeys; ++i)
         for (unsigned i = 0; i < numKeys; ++i)
         {
         {
             ptrs[i] = ptr;
             ptrs[i] = ptr;
             ptr = ptr->Next();
             ptr = ptr->Next();
         }
         }
-        
+
         Urho3D::Sort(RandomAccessIterator<Node*>(ptrs), RandomAccessIterator<Node*>(ptrs + numKeys), CompareNodes);
         Urho3D::Sort(RandomAccessIterator<Node*>(ptrs), RandomAccessIterator<Node*>(ptrs + numKeys), CompareNodes);
-        
+
         head_ = ptrs[0];
         head_ = ptrs[0];
         ptrs[0]->prev_ = 0;
         ptrs[0]->prev_ = 0;
         for (unsigned i = 1; i < numKeys; ++i)
         for (unsigned i = 1; i < numKeys; ++i)
@@ -394,10 +455,10 @@ public:
         }
         }
         ptrs[numKeys - 1]->next_ = tail_;
         ptrs[numKeys - 1]->next_ = tail_;
         tail_->prev_ = ptrs[numKeys - 1];
         tail_->prev_ = ptrs[numKeys - 1];
-        
+
         delete[] ptrs;
         delete[] ptrs;
     }
     }
-    
+
     /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
     /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
     bool Rehash(unsigned numBuckets)
     bool Rehash(unsigned numBuckets)
     {
     {
@@ -405,25 +466,25 @@ public:
             return true;
             return true;
         if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
         if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
             return false;
             return false;
-        
+
         // Check for being power of two
         // Check for being power of two
         unsigned check = numBuckets;
         unsigned check = numBuckets;
         while (!(check & 1))
         while (!(check & 1))
             check >>= 1;
             check >>= 1;
         if (check != 1)
         if (check != 1)
             return false;
             return false;
-        
+
         AllocateBuckets(Size(), numBuckets);
         AllocateBuckets(Size(), numBuckets);
         Rehash();
         Rehash();
         return true;
         return true;
     }
     }
-    
+
     /// Return iterator to the pair with key, or end iterator if not found.
     /// Return iterator to the pair with key, or end iterator if not found.
     Iterator Find(const T& key)
     Iterator Find(const T& key)
     {
     {
         if (!ptrs_)
         if (!ptrs_)
             return End();
             return End();
-        
+
         unsigned hashKey = Hash(key);
         unsigned hashKey = Hash(key);
         Node* node = FindNode(key, hashKey);
         Node* node = FindNode(key, hashKey);
         if (node)
         if (node)
@@ -431,13 +492,13 @@ public:
         else
         else
             return End();
             return End();
     }
     }
-    
+
     /// Return const iterator to the pair with key, or end iterator if not found.
     /// Return const iterator to the pair with key, or end iterator if not found.
     ConstIterator Find(const T& key) const
     ConstIterator Find(const T& key) const
     {
     {
         if (!ptrs_)
         if (!ptrs_)
             return End();
             return End();
-        
+
         unsigned hashKey = Hash(key);
         unsigned hashKey = Hash(key);
         Node* node = FindNode(key, hashKey);
         Node* node = FindNode(key, hashKey);
         if (node)
         if (node)
@@ -445,17 +506,17 @@ public:
         else
         else
             return End();
             return End();
     }
     }
-    
+
     /// Return whether contains a pair with key.
     /// Return whether contains a pair with key.
     bool Contains(const T& key) const
     bool Contains(const T& key) const
     {
     {
         if (!ptrs_)
         if (!ptrs_)
             return false;
             return false;
-        
+
         unsigned hashKey = Hash(key);
         unsigned hashKey = Hash(key);
         return FindNode(key, hashKey) != 0;
         return FindNode(key, hashKey) != 0;
     }
     }
-    
+
     /// Return all the keys.
     /// Return all the keys.
     Vector<T> Keys() const
     Vector<T> Keys() const
     {
     {
@@ -475,26 +536,32 @@ public:
             result.Push(i->second_);
             result.Push(i->second_);
         return result;
         return result;
     }
     }
-    
+
     /// Return iterator to the beginning.
     /// Return iterator to the beginning.
     Iterator Begin() { return Iterator(Head()); }
     Iterator Begin() { return Iterator(Head()); }
+
     /// Return iterator to the beginning.
     /// Return iterator to the beginning.
     ConstIterator Begin() const { return ConstIterator(Head()); }
     ConstIterator Begin() const { return ConstIterator(Head()); }
+
     /// Return iterator to the end.
     /// Return iterator to the end.
     Iterator End() { return Iterator(Tail()); }
     Iterator End() { return Iterator(Tail()); }
+
     /// Return iterator to the end.
     /// Return iterator to the end.
     ConstIterator End() const { return ConstIterator(Tail()); }
     ConstIterator End() const { return ConstIterator(Tail()); }
+
     /// Return first key.
     /// Return first key.
     const T& Front() const { return *Begin(); }
     const T& Front() const { return *Begin(); }
+
     /// Return last key.
     /// Return last key.
     const T& Back() const { return *(--End()); }
     const T& Back() const { return *(--End()); }
-    
+
 private:
 private:
     /// Return the head node.
     /// Return the head node.
     Node* Head() const { return static_cast<Node*>(head_); }
     Node* Head() const { return static_cast<Node*>(head_); }
+
     /// Return the tail node.
     /// Return the tail node.
     Node* Tail() const { return static_cast<Node*>(tail_); }
     Node* Tail() const { return static_cast<Node*>(tail_); }
-    
+
     /// Find a node from the buckets. Do not call if the buckets have not been allocated.
     /// Find a node from the buckets. Do not call if the buckets have not been allocated.
     Node* FindNode(const T& key, unsigned hashKey) const
     Node* FindNode(const T& key, unsigned hashKey) const
     {
     {
@@ -505,15 +572,15 @@ private:
                 return node;
                 return node;
             node = node->Down();
             node = node->Down();
         }
         }
-        
+
         return 0;
         return 0;
     }
     }
-    
+
     /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
     /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
     Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
     Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
     {
     {
         previous = 0;
         previous = 0;
-        
+
         Node* node = static_cast<Node*>(Ptrs()[hashKey]);
         Node* node = static_cast<Node*>(Ptrs()[hashKey]);
         while (node)
         while (node)
         {
         {
@@ -522,10 +589,10 @@ private:
             previous = node;
             previous = node;
             node = node->Down();
             node = node->Down();
         }
         }
-        
+
         return 0;
         return 0;
     }
     }
-    
+
     /// Insert a key and value and return either the new or existing node.
     /// Insert a key and value and return either the new or existing node.
     Node* InsertNode(const T& key, const U& value, bool findExisting = true)
     Node* InsertNode(const T& key, const U& value, bool findExisting = true)
     {
     {
@@ -535,9 +602,9 @@ private:
             AllocateBuckets(Size(), MIN_BUCKETS);
             AllocateBuckets(Size(), MIN_BUCKETS);
             Rehash();
             Rehash();
         }
         }
-        
+
         unsigned hashKey = Hash(key);
         unsigned hashKey = Hash(key);
-        
+
         if (findExisting)
         if (findExisting)
         {
         {
             // If exists, just change the value
             // If exists, just change the value
@@ -548,27 +615,27 @@ private:
                 return existing;
                 return existing;
             }
             }
         }
         }
-        
+
         Node* newNode = InsertNode(Tail(), key, value);
         Node* newNode = InsertNode(Tail(), key, value);
         newNode->down_ = Ptrs()[hashKey];
         newNode->down_ = Ptrs()[hashKey];
         Ptrs()[hashKey] = newNode;
         Ptrs()[hashKey] = newNode;
-        
+
         // Rehash if the maximum load factor has been exceeded
         // Rehash if the maximum load factor has been exceeded
         if (Size() > NumBuckets() * MAX_LOAD_FACTOR)
         if (Size() > NumBuckets() * MAX_LOAD_FACTOR)
         {
         {
             AllocateBuckets(Size(), NumBuckets() << 1);
             AllocateBuckets(Size(), NumBuckets() << 1);
             Rehash();
             Rehash();
         }
         }
-        
+
         return newNode;
         return newNode;
     }
     }
-    
+
     /// Insert a node into the list. Return the new node.
     /// Insert a node into the list. Return the new node.
     Node* InsertNode(Node* dest, const T& key, const U& value)
     Node* InsertNode(Node* dest, const T& key, const U& value)
     {
     {
         if (!dest)
         if (!dest)
             return 0;
             return 0;
-        
+
         Node* newNode = ReserveNode(key, value);
         Node* newNode = ReserveNode(key, value);
         Node* prev = dest->Prev();
         Node* prev = dest->Prev();
         newNode->next_ = dest;
         newNode->next_ = dest;
@@ -576,39 +643,39 @@ private:
         if (prev)
         if (prev)
             prev->next_ = newNode;
             prev->next_ = newNode;
         dest->prev_ = newNode;
         dest->prev_ = newNode;
-        
+
         // Reassign the head node if necessary
         // Reassign the head node if necessary
         if (dest == Head())
         if (dest == Head())
             head_ = newNode;
             head_ = newNode;
-        
+
         SetSize(Size() + 1);
         SetSize(Size() + 1);
-        
+
         return newNode;
         return newNode;
     }
     }
-    
+
     /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
     /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
     Node* EraseNode(Node* node)
     Node* EraseNode(Node* node)
     {
     {
         // The tail node can not be removed
         // The tail node can not be removed
         if (!node || node == tail_)
         if (!node || node == tail_)
             return Tail();
             return Tail();
-        
+
         Node* prev = node->Prev();
         Node* prev = node->Prev();
         Node* next = node->Next();
         Node* next = node->Next();
         if (prev)
         if (prev)
             prev->next_ = next;
             prev->next_ = next;
         next->prev_ = prev;
         next->prev_ = prev;
-        
+
         // Reassign the head node if necessary
         // Reassign the head node if necessary
         if (node == Head())
         if (node == Head())
             head_ = next;
             head_ = next;
-        
+
         FreeNode(node);
         FreeNode(node);
         SetSize(Size() - 1);
         SetSize(Size() - 1);
-        
+
         return next;
         return next;
     }
     }
-    
+
     /// Reserve a node.
     /// Reserve a node.
     Node* ReserveNode()
     Node* ReserveNode()
     {
     {
@@ -616,7 +683,7 @@ private:
         new(newNode) Node();
         new(newNode) Node();
         return newNode;
         return newNode;
     }
     }
-    
+
     /// Reserve a node with specified key and value.
     /// Reserve a node with specified key and value.
     Node* ReserveNode(const T& key, const U& value)
     Node* ReserveNode(const T& key, const U& value)
     {
     {
@@ -624,14 +691,14 @@ private:
         new(newNode) Node(key, value);
         new(newNode) Node(key, value);
         return newNode;
         return newNode;
     }
     }
-    
+
     /// Free a node.
     /// Free a node.
     void FreeNode(Node* node)
     void FreeNode(Node* node)
     {
     {
         (node)->~Node();
         (node)->~Node();
         AllocatorFree(allocator_, node);
         AllocatorFree(allocator_, node);
     }
     }
-    
+
     /// Rehash the buckets.
     /// Rehash the buckets.
     void Rehash()
     void Rehash()
     {
     {
@@ -643,10 +710,10 @@ private:
             Ptrs()[hashKey] = node;
             Ptrs()[hashKey] = node;
         }
         }
     }
     }
-    
+
     /// Compare two nodes.
     /// Compare two nodes.
     static bool CompareNodes(Node*& lhs, Node*& rhs) { return lhs->pair_.first_ < rhs->pair_.first_; }
     static bool CompareNodes(Node*& lhs, Node*& rhs) { return lhs->pair_.first_ < rhs->pair_.first_; }
-    
+
     /// Compute a hash based on the key and the bucket size
     /// Compute a hash based on the key and the bucket size
     unsigned Hash(const T& key) const { return MakeHash(key) & (NumBuckets() - 1); }
     unsigned Hash(const T& key) const { return MakeHash(key) & (NumBuckets() - 1); }
 };
 };
@@ -656,9 +723,15 @@ private:
 namespace std
 namespace std
 {
 {
 
 
-template <class T, class U> typename Urho3D::HashMap<T, U>::ConstIterator begin(const Urho3D::HashMap<T, U>& v) { return v.Begin(); }
+template <class T, class U> typename Urho3D::HashMap<T, U>::ConstIterator begin(const Urho3D::HashMap<T, U>& v)
+{
+    return v.Begin();
+}
+
 template <class T, class U> typename Urho3D::HashMap<T, U>::ConstIterator end(const Urho3D::HashMap<T, U>& v) { return v.End(); }
 template <class T, class U> typename Urho3D::HashMap<T, U>::ConstIterator end(const Urho3D::HashMap<T, U>& v) { return v.End(); }
+
 template <class T, class U> typename Urho3D::HashMap<T, U>::Iterator begin(Urho3D::HashMap<T, U>& v) { return v.Begin(); }
 template <class T, class U> typename Urho3D::HashMap<T, U>::Iterator begin(Urho3D::HashMap<T, U>& v) { return v.Begin(); }
+
 template <class T, class U> typename Urho3D::HashMap<T, U>::Iterator end(Urho3D::HashMap<T, U>& v) { return v.End(); }
 template <class T, class U> typename Urho3D::HashMap<T, U>::Iterator end(Urho3D::HashMap<T, U>& v) { return v.End(); }
 
 
 }
 }

+ 166 - 106
Source/Urho3D/Container/HashSet.h

@@ -41,24 +41,26 @@ public:
         Node()
         Node()
         {
         {
         }
         }
-        
+
         /// Construct with key.
         /// Construct with key.
         Node(const T& key) :
         Node(const T& key) :
             key_(key)
             key_(key)
         {
         {
         }
         }
-        
+
         /// Key.
         /// Key.
         T key_;
         T key_;
-        
+
         /// Return next node.
         /// Return next node.
         Node* Next() const { return static_cast<Node*>(next_); }
         Node* Next() const { return static_cast<Node*>(next_); }
+
         /// Return previous node.
         /// Return previous node.
         Node* Prev() const { return static_cast<Node*>(prev_); }
         Node* Prev() const { return static_cast<Node*>(prev_); }
+
         /// Return next node in the bucket.
         /// Return next node in the bucket.
         Node* Down() const { return static_cast<Node*>(down_); }
         Node* Down() const { return static_cast<Node*>(down_); }
     };
     };
-    
+
     /// Hash set node iterator.
     /// Hash set node iterator.
     struct Iterator : public HashIteratorBase
     struct Iterator : public HashIteratorBase
     {
     {
@@ -66,28 +68,50 @@ public:
         Iterator()
         Iterator()
         {
         {
         }
         }
-        
+
         /// Construct with a node pointer.
         /// Construct with a node pointer.
         Iterator(Node* ptr) :
         Iterator(Node* ptr) :
             HashIteratorBase(ptr)
             HashIteratorBase(ptr)
         {
         {
         }
         }
-        
+
         /// Preincrement the pointer.
         /// Preincrement the pointer.
-        Iterator& operator ++ () { GotoNext(); return *this; }
+        Iterator& operator ++()
+        {
+            GotoNext();
+            return *this;
+        }
+
         /// Postincrement the pointer.
         /// Postincrement the pointer.
-        Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
+        Iterator operator ++(int)
+        {
+            Iterator it = *this;
+            GotoNext();
+            return it;
+        }
+
         /// Predecrement the pointer.
         /// Predecrement the pointer.
-        Iterator& operator -- () { GotoPrev(); return *this; }
+        Iterator& operator --()
+        {
+            GotoPrev();
+            return *this;
+        }
+
         /// Postdecrement the pointer.
         /// Postdecrement the pointer.
-        Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
-        
+        Iterator operator --(int)
+        {
+            Iterator it = *this;
+            GotoPrev();
+            return it;
+        }
+
         /// Point to the key.
         /// Point to the key.
-        const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
+        const T* operator ->() const { return &(static_cast<Node*>(ptr_))->key_; }
+
         /// Dereference the key.
         /// Dereference the key.
-        const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
+        const T& operator *() const { return (static_cast<Node*>(ptr_))->key_; }
     };
     };
-    
+
     /// Hash set node const iterator.
     /// Hash set node const iterator.
     struct ConstIterator : public HashIteratorBase
     struct ConstIterator : public HashIteratorBase
     {
     {
@@ -95,53 +119,80 @@ public:
         ConstIterator()
         ConstIterator()
         {
         {
         }
         }
-        
+
         /// Construct with a node pointer.
         /// Construct with a node pointer.
         ConstIterator(Node* ptr) :
         ConstIterator(Node* ptr) :
             HashIteratorBase(ptr)
             HashIteratorBase(ptr)
         {
         {
         }
         }
-        
+
         /// Construct from a non-const iterator.
         /// Construct from a non-const iterator.
         ConstIterator(const Iterator& rhs) :
         ConstIterator(const Iterator& rhs) :
             HashIteratorBase(rhs.ptr_)
             HashIteratorBase(rhs.ptr_)
         {
         {
         }
         }
-        
+
         /// Assign from a non-const iterator.
         /// Assign from a non-const iterator.
-        ConstIterator& operator = (const Iterator& rhs) { ptr_ = rhs.ptr_; return *this; }
+        ConstIterator& operator =(const Iterator& rhs)
+        {
+            ptr_ = rhs.ptr_;
+            return *this;
+        }
+
         /// Preincrement the pointer.
         /// Preincrement the pointer.
-        ConstIterator& operator ++ () { GotoNext(); return *this; }
+        ConstIterator& operator ++()
+        {
+            GotoNext();
+            return *this;
+        }
+
         /// Postincrement the pointer.
         /// Postincrement the pointer.
-        ConstIterator operator ++ (int) { ConstIterator it = *this; GotoNext(); return it; }
+        ConstIterator operator ++(int)
+        {
+            ConstIterator it = *this;
+            GotoNext();
+            return it;
+        }
+
         /// Predecrement the pointer.
         /// Predecrement the pointer.
-        ConstIterator& operator -- () { GotoPrev(); return *this; }
+        ConstIterator& operator --()
+        {
+            GotoPrev();
+            return *this;
+        }
+
         /// Postdecrement the pointer.
         /// Postdecrement the pointer.
-        ConstIterator operator -- (int) { ConstIterator it = *this; GotoPrev(); return it; }
-        
+        ConstIterator operator --(int)
+        {
+            ConstIterator it = *this;
+            GotoPrev();
+            return it;
+        }
+
         /// Point to the key.
         /// Point to the key.
-        const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
+        const T* operator ->() const { return &(static_cast<Node*>(ptr_))->key_; }
+
         /// Dereference the key.
         /// Dereference the key.
-        const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
+        const T& operator *() const { return (static_cast<Node*>(ptr_))->key_; }
     };
     };
-    
+
     /// Construct empty.
     /// Construct empty.
     HashSet()
     HashSet()
     {
     {
         // Reserve the tail node
         // Reserve the tail node
-        allocator_ = AllocatorInitialize(sizeof(Node));
+        allocator_ = AllocatorInitialize((unsigned)sizeof(Node));
         head_ = tail_ = ReserveNode();
         head_ = tail_ = ReserveNode();
     }
     }
-    
+
     /// Construct from another hash set.
     /// Construct from another hash set.
     HashSet(const HashSet<T>& set)
     HashSet(const HashSet<T>& set)
     {
     {
         // Reserve the tail node + initial capacity according to the set's size
         // Reserve the tail node + initial capacity according to the set's size
-        allocator_ = AllocatorInitialize(sizeof(Node), set.Size() + 1);
+        allocator_ = AllocatorInitialize((unsigned)sizeof(Node), set.Size() + 1);
         head_ = tail_ = ReserveNode();
         head_ = tail_ = ReserveNode();
         *this = set;
         *this = set;
     }
     }
-    
+
     /// Destruct.
     /// Destruct.
     ~HashSet()
     ~HashSet()
     {
     {
@@ -150,35 +201,35 @@ public:
         AllocatorUninitialize(allocator_);
         AllocatorUninitialize(allocator_);
         delete[] ptrs_;
         delete[] ptrs_;
     }
     }
-    
+
     /// Assign a hash set.
     /// Assign a hash set.
-    HashSet& operator = (const HashSet<T>& rhs)
+    HashSet& operator =(const HashSet<T>& rhs)
     {
     {
         Clear();
         Clear();
         Insert(rhs);
         Insert(rhs);
         return *this;
         return *this;
     }
     }
-    
+
     /// Add-assign a value.
     /// Add-assign a value.
-    HashSet& operator += (const T& rhs)
+    HashSet& operator +=(const T& rhs)
     {
     {
         Insert(rhs);
         Insert(rhs);
         return *this;
         return *this;
     }
     }
-    
+
     /// Add-assign a hash set.
     /// Add-assign a hash set.
-    HashSet& operator += (const HashSet<T>& rhs)
+    HashSet& operator +=(const HashSet<T>& rhs)
     {
     {
         Insert(rhs);
         Insert(rhs);
         return *this;
         return *this;
     }
     }
-    
+
     /// Test for equality with another hash set.
     /// Test for equality with another hash set.
-    bool operator == (const HashSet<T>& rhs) const
+    bool operator ==(const HashSet<T>& rhs) const
     {
     {
         if (rhs.Size() != Size())
         if (rhs.Size() != Size())
             return false;
             return false;
-        
+
         ConstIterator it = Begin();
         ConstIterator it = Begin();
         while (it != End())
         while (it != End())
         {
         {
@@ -186,16 +237,16 @@ public:
                 return false;
                 return false;
             ++it;
             ++it;
         }
         }
-        
+
         return true;
         return true;
     }
     }
-    
+
     /// Test for inequality with another hash set.
     /// Test for inequality with another hash set.
-    bool operator != (const HashSet<T>& rhs) const
+    bool operator !=(const HashSet<T>& rhs) const
     {
     {
         if (rhs.Size() != Size())
         if (rhs.Size() != Size())
             return true;
             return true;
-        
+
         ConstIterator it = Begin();
         ConstIterator it = Begin();
         while (it != End())
         while (it != End())
         {
         {
@@ -203,10 +254,10 @@ public:
                 return true;
                 return true;
             ++it;
             ++it;
         }
         }
-        
+
         return false;
         return false;
     }
     }
-    
+
     /// Insert a key. Return an iterator to it.
     /// Insert a key. Return an iterator to it.
     Iterator Insert(const T& key)
     Iterator Insert(const T& key)
     {
     {
@@ -216,27 +267,27 @@ public:
             AllocateBuckets(Size(), MIN_BUCKETS);
             AllocateBuckets(Size(), MIN_BUCKETS);
             Rehash();
             Rehash();
         }
         }
-        
+
         unsigned hashKey = Hash(key);
         unsigned hashKey = Hash(key);
-        
+
         Node* existing = FindNode(key, hashKey);
         Node* existing = FindNode(key, hashKey);
         if (existing)
         if (existing)
             return Iterator(existing);
             return Iterator(existing);
-        
+
         Node* newNode = InsertNode(Tail(), key);
         Node* newNode = InsertNode(Tail(), key);
         newNode->down_ = Ptrs()[hashKey];
         newNode->down_ = Ptrs()[hashKey];
         Ptrs()[hashKey] = newNode;
         Ptrs()[hashKey] = newNode;
-        
+
         // Rehash if the maximum load factor has been exceeded
         // Rehash if the maximum load factor has been exceeded
         if (Size() > NumBuckets() * MAX_LOAD_FACTOR)
         if (Size() > NumBuckets() * MAX_LOAD_FACTOR)
         {
         {
             AllocateBuckets(Size(), NumBuckets() << 1);
             AllocateBuckets(Size(), NumBuckets() << 1);
             Rehash();
             Rehash();
         }
         }
-        
+
         return Iterator(newNode);
         return Iterator(newNode);
     }
     }
-    
+
     /// Insert a set.
     /// Insert a set.
     void Insert(const HashSet<T>& set)
     void Insert(const HashSet<T>& set)
     {
     {
@@ -245,46 +296,46 @@ public:
         while (it != end)
         while (it != end)
             Insert(*it++);
             Insert(*it++);
     }
     }
-    
+
     /// Insert a key by iterator. Return iterator to the value.
     /// Insert a key by iterator. Return iterator to the value.
     Iterator Insert(const ConstIterator& it)
     Iterator Insert(const ConstIterator& it)
     {
     {
         return Iterator(InsertNode(*it));
         return Iterator(InsertNode(*it));
     }
     }
-    
+
     /// Erase a key. Return true if was found.
     /// Erase a key. Return true if was found.
     bool Erase(const T& key)
     bool Erase(const T& key)
     {
     {
         if (!ptrs_)
         if (!ptrs_)
             return false;
             return false;
-        
+
         unsigned hashKey = Hash(key);
         unsigned hashKey = Hash(key);
-        
+
         Node* previous;
         Node* previous;
         Node* node = FindNode(key, hashKey, previous);
         Node* node = FindNode(key, hashKey, previous);
         if (!node)
         if (!node)
             return false;
             return false;
-        
+
         if (previous)
         if (previous)
             previous->down_ = node->down_;
             previous->down_ = node->down_;
         else
         else
             Ptrs()[hashKey] = node->down_;
             Ptrs()[hashKey] = node->down_;
-        
+
         EraseNode(node);
         EraseNode(node);
         return true;
         return true;
     }
     }
-    
+
     /// Erase a key by iterator. Return iterator to the next key.
     /// Erase a key by iterator. Return iterator to the next key.
     Iterator Erase(const Iterator& it)
     Iterator Erase(const Iterator& it)
     {
     {
         if (!ptrs_ || !it.ptr_)
         if (!ptrs_ || !it.ptr_)
             return End();
             return End();
-        
+
         Node* node = static_cast<Node*>(it.ptr_);
         Node* node = static_cast<Node*>(it.ptr_);
         Node* next = node->Next();
         Node* next = node->Next();
-        
+
         unsigned hashKey = Hash(node->key_);
         unsigned hashKey = Hash(node->key_);
-        
+
         Node* previous = 0;
         Node* previous = 0;
         Node* current = static_cast<Node*>(Ptrs()[hashKey]);
         Node* current = static_cast<Node*>(Ptrs()[hashKey]);
         while (current && current != node)
         while (current && current != node)
@@ -292,54 +343,54 @@ public:
             previous = current;
             previous = current;
             current = current->Down();
             current = current->Down();
         }
         }
-        
+
         assert(current == node);
         assert(current == node);
-        
+
         if (previous)
         if (previous)
             previous->down_ = node->down_;
             previous->down_ = node->down_;
         else
         else
             Ptrs()[hashKey] = node->down_;
             Ptrs()[hashKey] = node->down_;
-        
+
         EraseNode(node);
         EraseNode(node);
         return Iterator(next);
         return Iterator(next);
     }
     }
-    
+
     /// Clear the set.
     /// Clear the set.
     void Clear()
     void Clear()
     {
     {
         if (Size())
         if (Size())
         {
         {
-            for (Iterator i = Begin(); i != End(); )
+            for (Iterator i = Begin(); i != End();)
             {
             {
                 FreeNode(static_cast<Node*>(i++.ptr_));
                 FreeNode(static_cast<Node*>(i++.ptr_));
                 i.ptr_->prev_ = 0;
                 i.ptr_->prev_ = 0;
             }
             }
-            
+
             head_ = tail_;
             head_ = tail_;
             SetSize(0);
             SetSize(0);
         }
         }
-        
+
         ResetPtrs();
         ResetPtrs();
     }
     }
-    
+
     /// Sort keys. After sorting the set can be iterated in order until new elements are inserted.
     /// Sort keys. After sorting the set can be iterated in order until new elements are inserted.
     void Sort()
     void Sort()
     {
     {
         unsigned numKeys = Size();
         unsigned numKeys = Size();
         if (!numKeys)
         if (!numKeys)
             return;
             return;
-        
-        Node** ptrs = new Node*[numKeys];
+
+        Node** ptrs = new Node* [numKeys];
         Node* ptr = Head();
         Node* ptr = Head();
-        
+
         for (unsigned i = 0; i < numKeys; ++i)
         for (unsigned i = 0; i < numKeys; ++i)
         {
         {
             ptrs[i] = ptr;
             ptrs[i] = ptr;
             ptr = ptr->Next();
             ptr = ptr->Next();
         }
         }
-        
+
         Urho3D::Sort(RandomAccessIterator<Node*>(ptrs), RandomAccessIterator<Node*>(ptrs + numKeys), CompareNodes);
         Urho3D::Sort(RandomAccessIterator<Node*>(ptrs), RandomAccessIterator<Node*>(ptrs + numKeys), CompareNodes);
-        
+
         head_ = ptrs[0];
         head_ = ptrs[0];
         ptrs[0]->prev_ = 0;
         ptrs[0]->prev_ = 0;
         for (unsigned i = 1; i < numKeys; ++i)
         for (unsigned i = 1; i < numKeys; ++i)
@@ -349,10 +400,10 @@ public:
         }
         }
         ptrs[numKeys - 1]->next_ = tail_;
         ptrs[numKeys - 1]->next_ = tail_;
         tail_->prev_ = ptrs[numKeys - 1];
         tail_->prev_ = ptrs[numKeys - 1];
-        
+
         delete[] ptrs;
         delete[] ptrs;
     }
     }
-    
+
     /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
     /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
     bool Rehash(unsigned numBuckets)
     bool Rehash(unsigned numBuckets)
     {
     {
@@ -360,25 +411,25 @@ public:
             return true;
             return true;
         if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
         if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
             return false;
             return false;
-        
+
         // Check for being power of two
         // Check for being power of two
         unsigned check = numBuckets;
         unsigned check = numBuckets;
         while (!(check & 1))
         while (!(check & 1))
             check >>= 1;
             check >>= 1;
         if (check != 1)
         if (check != 1)
             return false;
             return false;
-        
+
         AllocateBuckets(Size(), numBuckets);
         AllocateBuckets(Size(), numBuckets);
         Rehash();
         Rehash();
         return true;
         return true;
     }
     }
-    
+
     /// Return iterator to the key, or end iterator if not found.
     /// Return iterator to the key, or end iterator if not found.
     Iterator Find(const T& key)
     Iterator Find(const T& key)
     {
     {
         if (!ptrs_)
         if (!ptrs_)
             return End();
             return End();
-        
+
         unsigned hashKey = Hash(key);
         unsigned hashKey = Hash(key);
         Node* node = FindNode(key, hashKey);
         Node* node = FindNode(key, hashKey);
         if (node)
         if (node)
@@ -386,13 +437,13 @@ public:
         else
         else
             return End();
             return End();
     }
     }
-    
+
     /// Return const iterator to the key, or end iterator if not found.
     /// Return const iterator to the key, or end iterator if not found.
     ConstIterator Find(const T& key) const
     ConstIterator Find(const T& key) const
     {
     {
         if (!ptrs_)
         if (!ptrs_)
             return End();
             return End();
-        
+
         unsigned hashKey = Hash(key);
         unsigned hashKey = Hash(key);
         Node* node = FindNode(key, hashKey);
         Node* node = FindNode(key, hashKey);
         if (node)
         if (node)
@@ -400,36 +451,42 @@ public:
         else
         else
             return End();
             return End();
     }
     }
-    
+
     /// Return whether contains a key.
     /// Return whether contains a key.
     bool Contains(const T& key) const
     bool Contains(const T& key) const
     {
     {
         if (!ptrs_)
         if (!ptrs_)
             return false;
             return false;
-        
+
         unsigned hashKey = Hash(key);
         unsigned hashKey = Hash(key);
         return FindNode(key, hashKey) != 0;
         return FindNode(key, hashKey) != 0;
     }
     }
-    
+
     /// Return iterator to the beginning.
     /// Return iterator to the beginning.
     Iterator Begin() { return Iterator(Head()); }
     Iterator Begin() { return Iterator(Head()); }
+
     /// Return iterator to the beginning.
     /// Return iterator to the beginning.
     ConstIterator Begin() const { return ConstIterator(Head()); }
     ConstIterator Begin() const { return ConstIterator(Head()); }
+
     /// Return iterator to the end.
     /// Return iterator to the end.
     Iterator End() { return Iterator(Tail()); }
     Iterator End() { return Iterator(Tail()); }
+
     /// Return iterator to the end.
     /// Return iterator to the end.
     ConstIterator End() const { return ConstIterator(Tail()); }
     ConstIterator End() const { return ConstIterator(Tail()); }
+
     /// Return first key.
     /// Return first key.
     const T& Front() const { return *Begin(); }
     const T& Front() const { return *Begin(); }
+
     /// Return last key.
     /// Return last key.
     const T& Back() const { return *(--End()); }
     const T& Back() const { return *(--End()); }
-    
+
 private:
 private:
     /// Return the head node.
     /// Return the head node.
     Node* Head() const { return static_cast<Node*>(head_); }
     Node* Head() const { return static_cast<Node*>(head_); }
+
     /// Return the tail node.
     /// Return the tail node.
     Node* Tail() const { return static_cast<Node*>(tail_); }
     Node* Tail() const { return static_cast<Node*>(tail_); }
-    
+
     /// Find a node from the buckets. Do not call if the buckets have not been allocated.
     /// Find a node from the buckets. Do not call if the buckets have not been allocated.
     Node* FindNode(const T& key, unsigned hashKey) const
     Node* FindNode(const T& key, unsigned hashKey) const
     {
     {
@@ -440,15 +497,15 @@ private:
                 return node;
                 return node;
             node = node->Down();
             node = node->Down();
         }
         }
-        
+
         return 0;
         return 0;
     }
     }
-    
+
     /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
     /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
     Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
     Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
     {
     {
         previous = 0;
         previous = 0;
-        
+
         Node* node = static_cast<Node*>(Ptrs()[hashKey]);
         Node* node = static_cast<Node*>(Ptrs()[hashKey]);
         while (node)
         while (node)
         {
         {
@@ -457,16 +514,16 @@ private:
             previous = node;
             previous = node;
             node = node->Down();
             node = node->Down();
         }
         }
-        
+
         return 0;
         return 0;
     }
     }
-    
+
     /// Insert a node into the list. Return the new node.
     /// Insert a node into the list. Return the new node.
     Node* InsertNode(Node* dest, const T& key)
     Node* InsertNode(Node* dest, const T& key)
     {
     {
         if (!dest)
         if (!dest)
             return 0;
             return 0;
-        
+
         Node* newNode = ReserveNode(key);
         Node* newNode = ReserveNode(key);
         Node* prev = dest->Prev();
         Node* prev = dest->Prev();
         newNode->next_ = dest;
         newNode->next_ = dest;
@@ -474,39 +531,39 @@ private:
         if (prev)
         if (prev)
             prev->next_ = newNode;
             prev->next_ = newNode;
         dest->prev_ = newNode;
         dest->prev_ = newNode;
-        
+
         // Reassign the head node if necessary
         // Reassign the head node if necessary
         if (dest == Head())
         if (dest == Head())
             head_ = newNode;
             head_ = newNode;
-        
+
         SetSize(Size() + 1);
         SetSize(Size() + 1);
-        
+
         return newNode;
         return newNode;
     }
     }
-    
+
     /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
     /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
     Node* EraseNode(Node* node)
     Node* EraseNode(Node* node)
     {
     {
         // The tail node can not be removed
         // The tail node can not be removed
         if (!node || node == tail_)
         if (!node || node == tail_)
             return Tail();
             return Tail();
-        
+
         Node* prev = node->Prev();
         Node* prev = node->Prev();
         Node* next = node->Next();
         Node* next = node->Next();
         if (prev)
         if (prev)
             prev->next_ = next;
             prev->next_ = next;
         next->prev_ = prev;
         next->prev_ = prev;
-        
+
         // Reassign the head node if necessary
         // Reassign the head node if necessary
         if (node == Head())
         if (node == Head())
             head_ = next;
             head_ = next;
-        
+
         FreeNode(node);
         FreeNode(node);
         SetSize(Size() - 1);
         SetSize(Size() - 1);
-        
+
         return next;
         return next;
     }
     }
-    
+
     /// Reserve a node.
     /// Reserve a node.
     Node* ReserveNode()
     Node* ReserveNode()
     {
     {
@@ -514,7 +571,7 @@ private:
         new(newNode) Node();
         new(newNode) Node();
         return newNode;
         return newNode;
     }
     }
-    
+
     /// Reserve a node with specified key.
     /// Reserve a node with specified key.
     Node* ReserveNode(const T& key)
     Node* ReserveNode(const T& key)
     {
     {
@@ -522,14 +579,14 @@ private:
         new(newNode) Node(key);
         new(newNode) Node(key);
         return newNode;
         return newNode;
     }
     }
-    
+
     /// Free a node.
     /// Free a node.
     void FreeNode(Node* node)
     void FreeNode(Node* node)
     {
     {
         (node)->~Node();
         (node)->~Node();
         AllocatorFree(allocator_, node);
         AllocatorFree(allocator_, node);
     }
     }
-    
+
     /// Rehash the buckets.
     /// Rehash the buckets.
     void Rehash()
     void Rehash()
     {
     {
@@ -541,7 +598,7 @@ private:
             Ptrs()[hashKey] = node;
             Ptrs()[hashKey] = node;
         }
         }
     }
     }
-    
+
     /// Compare two nodes.
     /// Compare two nodes.
     static bool CompareNodes(Node*& lhs, Node*& rhs) { return lhs->key_ < rhs->key_; }
     static bool CompareNodes(Node*& lhs, Node*& rhs) { return lhs->key_ < rhs->key_; }
 
 
@@ -555,8 +612,11 @@ namespace std
 {
 {
 
 
 template <class T> typename Urho3D::HashSet<T>::ConstIterator begin(const Urho3D::HashSet<T>& v) { return v.Begin(); }
 template <class T> typename Urho3D::HashSet<T>::ConstIterator begin(const Urho3D::HashSet<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::HashSet<T>::ConstIterator end(const Urho3D::HashSet<T>& v) { return v.End(); }
 template <class T> typename Urho3D::HashSet<T>::ConstIterator end(const Urho3D::HashSet<T>& v) { return v.End(); }
+
 template <class T> typename Urho3D::HashSet<T>::Iterator begin(Urho3D::HashSet<T>& v) { return v.Begin(); }
 template <class T> typename Urho3D::HashSet<T>::Iterator begin(Urho3D::HashSet<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::HashSet<T>::Iterator end(Urho3D::HashSet<T>& v) { return v.End(); }
 template <class T> typename Urho3D::HashSet<T>::Iterator end(Urho3D::HashSet<T>& v) { return v.End(); }
 
 
 }
 }

+ 20 - 14
Source/Urho3D/Container/LinkedList.h

@@ -22,6 +22,12 @@
 
 
 #pragma once
 #pragma once
 
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 namespace Urho3D
 namespace Urho3D
 {
 {
 
 
@@ -33,7 +39,7 @@ struct URHO3D_API LinkedListNode
         next_(0)
         next_(0)
     {
     {
     }
     }
-    
+
     /// Pointer to next node.
     /// Pointer to next node.
     LinkedListNode* next_;
     LinkedListNode* next_;
 };
 };
@@ -47,13 +53,13 @@ public:
         head_(0)
         head_(0)
     {
     {
     }
     }
-    
+
     /// Destruct.
     /// Destruct.
     ~LinkedList()
     ~LinkedList()
     {
     {
         Clear();
         Clear();
     }
     }
-    
+
     /// Remove all elements.
     /// Remove all elements.
     void Clear()
     void Clear()
     {
     {
@@ -65,7 +71,7 @@ public:
             element = next;
             element = next;
         }
         }
     }
     }
-    
+
     /// Insert an element at the beginning.
     /// Insert an element at the beginning.
     void InsertFront(T* element)
     void InsertFront(T* element)
     {
     {
@@ -75,7 +81,7 @@ public:
             head_ = element;
             head_ = element;
         }
         }
     }
     }
-    
+
     /// Insert an element at the end.
     /// Insert an element at the end.
     void Insert(T* element)
     void Insert(T* element)
     {
     {
@@ -91,7 +97,7 @@ public:
             head_ = element;
             head_ = element;
         }
         }
     }
     }
-    
+
     /// Erase an element. Return true if successful.
     /// Erase an element. Return true if successful.
     bool Erase(T* element)
     bool Erase(T* element)
     {
     {
@@ -116,10 +122,10 @@ public:
                 }
                 }
             }
             }
         }
         }
-        
+
         return false;
         return false;
     }
     }
-    
+
     /// Erase an element when the previous element is known (optimization.) Return true if successful.
     /// Erase an element when the previous element is known (optimization.) Return true if successful.
     bool Erase(T* element, T* previous)
     bool Erase(T* element, T* previous)
     {
     {
@@ -138,13 +144,13 @@ public:
                 return true;
                 return true;
             }
             }
         }
         }
-        
+
         return false;
         return false;
     }
     }
-    
+
     /// Return first element, or null if empty.
     /// Return first element, or null if empty.
     T* First() const { return head_; }
     T* First() const { return head_; }
-    
+
     /// Return last element, or null if empty.
     /// Return last element, or null if empty.
     T* Last() const
     T* Last() const
     {
     {
@@ -156,13 +162,13 @@ public:
         }
         }
         return element;
         return element;
     }
     }
-    
+
     /// Return next element, or null if no more elements.
     /// Return next element, or null if no more elements.
     T* Next(T* element) const { return element ? static_cast<T*>(element->next_) : 0; }
     T* Next(T* element) const { return element ? static_cast<T*>(element->next_) : 0; }
-    
+
     /// Return whether is empty.
     /// Return whether is empty.
     bool Empty() const { return head_ == 0; }
     bool Empty() const { return head_ == 0; }
-    
+
 private:
 private:
     /// First element.
     /// First element.
     T* head_;
     T* head_;

+ 140 - 74
Source/Urho3D/Container/List.h

@@ -38,22 +38,23 @@ public:
         Node()
         Node()
         {
         {
         }
         }
-        
+
         /// Construct with value.
         /// Construct with value.
         Node(const T& value) :
         Node(const T& value) :
             value_(value)
             value_(value)
         {
         {
         }
         }
-        
+
         /// Node value.
         /// Node value.
         T value_;
         T value_;
-        
+
         /// Return next node.
         /// Return next node.
         Node* Next() const { return static_cast<Node*>(next_); }
         Node* Next() const { return static_cast<Node*>(next_); }
+
         /// Return previous node.
         /// Return previous node.
         Node* Prev() { return static_cast<Node*>(prev_); }
         Node* Prev() { return static_cast<Node*>(prev_); }
     };
     };
-    
+
     /// %List iterator.
     /// %List iterator.
     struct Iterator : public ListIteratorBase
     struct Iterator : public ListIteratorBase
     {
     {
@@ -61,28 +62,50 @@ public:
         Iterator()
         Iterator()
         {
         {
         }
         }
-        
+
         /// Construct with a node pointer.
         /// Construct with a node pointer.
         explicit Iterator(Node* ptr) :
         explicit Iterator(Node* ptr) :
             ListIteratorBase(ptr)
             ListIteratorBase(ptr)
         {
         {
         }
         }
-        
+
         /// Preincrement the pointer.
         /// Preincrement the pointer.
-        Iterator& operator ++ () { GotoNext(); return *this; }
+        Iterator& operator ++()
+        {
+            GotoNext();
+            return *this;
+        }
+
         /// Postincrement the pointer.
         /// Postincrement the pointer.
-        Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
+        Iterator operator ++(int)
+        {
+            Iterator it = *this;
+            GotoNext();
+            return it;
+        }
+
         /// Predecrement the pointer.
         /// Predecrement the pointer.
-        Iterator& operator -- () { GotoPrev(); return *this; }
+        Iterator& operator --()
+        {
+            GotoPrev();
+            return *this;
+        }
+
         /// Postdecrement the pointer.
         /// Postdecrement the pointer.
-        Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
-        
+        Iterator operator --(int)
+        {
+            Iterator it = *this;
+            GotoPrev();
+            return it;
+        }
+
         /// Point to the node value.
         /// Point to the node value.
-        T* operator -> () const { return &(static_cast<Node*>(ptr_))->value_; }
+        T* operator ->() const { return &(static_cast<Node*>(ptr_))->value_; }
+
         /// Dereference the node value.
         /// Dereference the node value.
-        T& operator * () const { return (static_cast<Node*>(ptr_))->value_; }
+        T& operator *() const { return (static_cast<Node*>(ptr_))->value_; }
     };
     };
-    
+
     /// %List const iterator.
     /// %List const iterator.
     struct ConstIterator : public ListIteratorBase
     struct ConstIterator : public ListIteratorBase
     {
     {
@@ -90,52 +113,79 @@ public:
         ConstIterator()
         ConstIterator()
         {
         {
         }
         }
-        
+
         /// Construct with a node pointer.
         /// Construct with a node pointer.
         explicit ConstIterator(Node* ptr) :
         explicit ConstIterator(Node* ptr) :
             ListIteratorBase(ptr)
             ListIteratorBase(ptr)
         {
         {
         }
         }
-        
+
         /// Construct from a non-const iterator.
         /// Construct from a non-const iterator.
         ConstIterator(const Iterator& rhs) :
         ConstIterator(const Iterator& rhs) :
             ListIteratorBase(rhs.ptr_)
             ListIteratorBase(rhs.ptr_)
         {
         {
         }
         }
-        
+
         /// Assign from a non-const iterator.
         /// Assign from a non-const iterator.
-        ConstIterator& operator = (const Iterator& rhs) { ptr_ = rhs.ptr_; return *this; }
+        ConstIterator& operator =(const Iterator& rhs)
+        {
+            ptr_ = rhs.ptr_;
+            return *this;
+        }
+
         /// Preincrement the pointer.
         /// Preincrement the pointer.
-        ConstIterator& operator ++ () { GotoNext(); return *this; }
+        ConstIterator& operator ++()
+        {
+            GotoNext();
+            return *this;
+        }
+
         /// Postincrement the pointer.
         /// Postincrement the pointer.
-        ConstIterator operator ++ (int) { ConstIterator it = *this; GotoNext(); return it; }
+        ConstIterator operator ++(int)
+        {
+            ConstIterator it = *this;
+            GotoNext();
+            return it;
+        }
+
         /// Predecrement the pointer.
         /// Predecrement the pointer.
-        ConstIterator& operator -- () { GotoPrev(); return *this; }
+        ConstIterator& operator --()
+        {
+            GotoPrev();
+            return *this;
+        }
+
         /// Postdecrement the pointer.
         /// Postdecrement the pointer.
-        ConstIterator operator -- (int) { ConstIterator it = *this; GotoPrev(); return it; }
-        
+        ConstIterator operator --(int)
+        {
+            ConstIterator it = *this;
+            GotoPrev();
+            return it;
+        }
+
         /// Point to the node value.
         /// Point to the node value.
-        const T* operator -> () const { return &(static_cast<Node*>(ptr_))->value_; }
+        const T* operator ->() const { return &(static_cast<Node*>(ptr_))->value_; }
+
         /// Dereference the node value.
         /// Dereference the node value.
-        const T& operator * () const { return (static_cast<Node*>(ptr_))->value_; }
+        const T& operator *() const { return (static_cast<Node*>(ptr_))->value_; }
     };
     };
 
 
     /// Construct empty.
     /// Construct empty.
     List()
     List()
     {
     {
-        allocator_ = AllocatorInitialize(sizeof(Node));
+        allocator_ = AllocatorInitialize((unsigned)sizeof(Node));
         head_ = tail_ = ReserveNode();
         head_ = tail_ = ReserveNode();
     }
     }
-    
+
     /// Construct from another list.
     /// Construct from another list.
     List(const List<T>& list)
     List(const List<T>& list)
     {
     {
         // Reserve the tail node + initial capacity according to the list's size
         // Reserve the tail node + initial capacity according to the list's size
-        allocator_ = AllocatorInitialize(sizeof(Node), list.Size() + 1);
+        allocator_ = AllocatorInitialize((unsigned)sizeof(Node), list.Size() + 1);
         head_ = tail_ = ReserveNode();
         head_ = tail_ = ReserveNode();
         *this = list;
         *this = list;
     }
     }
-    
+
     /// Destruct.
     /// Destruct.
     ~List()
     ~List()
     {
     {
@@ -143,36 +193,36 @@ public:
         FreeNode(Tail());
         FreeNode(Tail());
         AllocatorUninitialize(allocator_);
         AllocatorUninitialize(allocator_);
     }
     }
-    
+
     /// Assign from another list.
     /// Assign from another list.
-    List& operator = (const List<T>& rhs)
+    List& operator =(const List<T>& rhs)
     {
     {
         // Clear, then insert the nodes of the other list
         // Clear, then insert the nodes of the other list
         Clear();
         Clear();
         Insert(End(), rhs);
         Insert(End(), rhs);
         return *this;
         return *this;
     }
     }
-    
+
     /// Add-assign an element.
     /// Add-assign an element.
-    List& operator += (const T& rhs)
+    List& operator +=(const T& rhs)
     {
     {
         Push(rhs);
         Push(rhs);
         return *this;
         return *this;
     }
     }
-    
+
     /// Add-assign a list.
     /// Add-assign a list.
-    List& operator += (const List<T>& rhs)
+    List& operator +=(const List<T>& rhs)
     {
     {
         Insert(End(), rhs);
         Insert(End(), rhs);
         return *this;
         return *this;
     }
     }
-    
+
     /// Test for equality with another list.
     /// Test for equality with another list.
-    bool operator == (const List<T>& rhs) const
+    bool operator ==(const List<T>& rhs) const
     {
     {
         if (rhs.size_ != size_)
         if (rhs.size_ != size_)
             return false;
             return false;
-        
+
         ConstIterator i = Begin();
         ConstIterator i = Begin();
         ConstIterator j = rhs.Begin();
         ConstIterator j = rhs.Begin();
         while (i != End())
         while (i != End())
@@ -182,16 +232,16 @@ public:
             ++i;
             ++i;
             ++j;
             ++j;
         }
         }
-        
+
         return true;
         return true;
     }
     }
-    
+
     /// Test for inequality with another list.
     /// Test for inequality with another list.
-    bool operator != (const List<T>& rhs) const
+    bool operator !=(const List<T>& rhs) const
     {
     {
         if (rhs.size_ != size_)
         if (rhs.size_ != size_)
             return true;
             return true;
-        
+
         ConstIterator i = Begin();
         ConstIterator i = Begin();
         ConstIterator j = rhs.Begin();
         ConstIterator j = rhs.Begin();
         while (i != End())
         while (i != End())
@@ -201,17 +251,19 @@ public:
             ++i;
             ++i;
             ++j;
             ++j;
         }
         }
-        
+
         return false;
         return false;
     }
     }
-    
+
     /// Insert an element to the end.
     /// Insert an element to the end.
     void Push(const T& value) { InsertNode(Tail(), value); }
     void Push(const T& value) { InsertNode(Tail(), value); }
+
     /// Insert an element to the beginning.
     /// Insert an element to the beginning.
     void PushFront(const T& value) { InsertNode(Head(), value); }
     void PushFront(const T& value) { InsertNode(Head(), value); }
+
     /// Insert an element at position.
     /// Insert an element at position.
     void Insert(const Iterator& dest, const T& value) { InsertNode(static_cast<Node*>(dest.ptr_), value); }
     void Insert(const Iterator& dest, const T& value) { InsertNode(static_cast<Node*>(dest.ptr_), value); }
-    
+
     /// Insert a list at position.
     /// Insert a list at position.
     void Insert(const Iterator& dest, const List<T>& list)
     void Insert(const Iterator& dest, const List<T>& list)
     {
     {
@@ -221,7 +273,7 @@ public:
         while (it != end)
         while (it != end)
             InsertNode(destNode, *it++);
             InsertNode(destNode, *it++);
     }
     }
-    
+
     /// Insert elements by iterators.
     /// Insert elements by iterators.
     void Insert(const Iterator& dest, const ConstIterator& start, const ConstIterator& end)
     void Insert(const Iterator& dest, const ConstIterator& start, const ConstIterator& end)
     {
     {
@@ -230,7 +282,7 @@ public:
         while (it != end)
         while (it != end)
             InsertNode(destNode, *it++);
             InsertNode(destNode, *it++);
     }
     }
-    
+
     /// Insert elements.
     /// Insert elements.
     void Insert(const Iterator& dest, const T* start, const T* end)
     void Insert(const Iterator& dest, const T* start, const T* end)
     {
     {
@@ -239,63 +291,63 @@ public:
         while (ptr != end)
         while (ptr != end)
             InsertNode(destNode, *ptr++);
             InsertNode(destNode, *ptr++);
     }
     }
-    
+
     /// Erase the last element.
     /// Erase the last element.
     void Pop()
     void Pop()
     {
     {
         if (size_)
         if (size_)
             Erase(--End());
             Erase(--End());
     }
     }
-    
+
     /// Erase the first element.
     /// Erase the first element.
     void PopFront()
     void PopFront()
     {
     {
         if (size_)
         if (size_)
             Erase(Begin());
             Erase(Begin());
     }
     }
-    
+
     /// Erase an element by iterator. Return iterator to the next element.
     /// Erase an element by iterator. Return iterator to the next element.
     Iterator Erase(Iterator it)
     Iterator Erase(Iterator it)
     {
     {
         return Iterator(EraseNode(static_cast<Node*>(it.ptr_)));
         return Iterator(EraseNode(static_cast<Node*>(it.ptr_)));
     }
     }
-    
+
     /// Erase a range by iterators. Return an iterator to the next element.
     /// Erase a range by iterators. Return an iterator to the next element.
     Iterator Erase(const Iterator& start, const Iterator& end)
     Iterator Erase(const Iterator& start, const Iterator& end)
     {
     {
         Iterator it = start;
         Iterator it = start;
         while (it != end)
         while (it != end)
-            it = EraseNode(static_cast<Node*>(it.ptr_));
-        
+            it = Erase(it);
+
         return it;
         return it;
     }
     }
-    
+
     /// Clear the list.
     /// Clear the list.
     void Clear()
     void Clear()
     {
     {
         if (Size())
         if (Size())
         {
         {
-            for (Iterator i = Begin(); i != End(); )
+            for (Iterator i = Begin(); i != End();)
             {
             {
                 FreeNode(static_cast<Node*>(i++.ptr_));
                 FreeNode(static_cast<Node*>(i++.ptr_));
                 i.ptr_->prev_ = 0;
                 i.ptr_->prev_ = 0;
             }
             }
-            
+
             head_ = tail_;
             head_ = tail_;
             size_ = 0;
             size_ = 0;
         }
         }
     }
     }
-    
+
     /// Resize the list by removing or adding items at the end.
     /// Resize the list by removing or adding items at the end.
     void Resize(unsigned newSize)
     void Resize(unsigned newSize)
     {
     {
         while (size_ > newSize)
         while (size_ > newSize)
             Pop();
             Pop();
-        
+
         while (size_ < newSize)
         while (size_ < newSize)
             InsertNode(Tail(), T());
             InsertNode(Tail(), T());
     }
     }
-    
+
     /// Return iterator to value, or to the end if not found.
     /// Return iterator to value, or to the end if not found.
     Iterator Find(const T& value)
     Iterator Find(const T& value)
     {
     {
@@ -304,7 +356,7 @@ public:
             ++it;
             ++it;
         return it;
         return it;
     }
     }
-    
+
     /// Return const iterator to value, or to the end if not found.
     /// Return const iterator to value, or to the end if not found.
     ConstIterator Find(const T& value) const
     ConstIterator Find(const T& value) const
     {
     {
@@ -313,42 +365,53 @@ public:
             ++it;
             ++it;
         return it;
         return it;
     }
     }
-    
+
     /// Return whether contains a specific value.
     /// Return whether contains a specific value.
     bool Contains(const T& value) const { return Find(value) != End(); }
     bool Contains(const T& value) const { return Find(value) != End(); }
+
     /// Return iterator to the first element.
     /// Return iterator to the first element.
     Iterator Begin() { return Iterator(Head()); }
     Iterator Begin() { return Iterator(Head()); }
+
     /// Return iterator to the first element.
     /// Return iterator to the first element.
     ConstIterator Begin() const { return ConstIterator(Head()); }
     ConstIterator Begin() const { return ConstIterator(Head()); }
+
     /// Return iterator to the end.
     /// Return iterator to the end.
     Iterator End() { return Iterator(Tail()); }
     Iterator End() { return Iterator(Tail()); }
+
     /// Return iterator to the end.
     /// Return iterator to the end.
     ConstIterator End() const { return ConstIterator(Tail()); }
     ConstIterator End() const { return ConstIterator(Tail()); }
+
     /// Return first element.
     /// Return first element.
     T& Front() { return *Begin(); }
     T& Front() { return *Begin(); }
+
     /// Return const first element.
     /// Return const first element.
     const T& Front() const { return *Begin(); }
     const T& Front() const { return *Begin(); }
+
     /// Return last element.
     /// Return last element.
     T& Back() { return *(--End()); }
     T& Back() { return *(--End()); }
+
     /// Return const last element.
     /// Return const last element.
     const T& Back() const { return *(--End()); }
     const T& Back() const { return *(--End()); }
+
     /// Return number of elements.
     /// Return number of elements.
     unsigned Size() const { return size_; }
     unsigned Size() const { return size_; }
+
     /// Return whether list is empty.
     /// Return whether list is empty.
     bool Empty() const { return size_ == 0; }
     bool Empty() const { return size_ == 0; }
-    
+
 private:
 private:
     /// Return the head node.
     /// Return the head node.
     Node* Head() const { return static_cast<Node*>(head_); }
     Node* Head() const { return static_cast<Node*>(head_); }
+
     /// Return the tail node.
     /// Return the tail node.
     Node* Tail() const { return static_cast<Node*>(tail_); }
     Node* Tail() const { return static_cast<Node*>(tail_); }
-    
+
     /// Allocate and insert a node into the list.
     /// Allocate and insert a node into the list.
     void InsertNode(Node* dest, const T& value)
     void InsertNode(Node* dest, const T& value)
     {
     {
         if (!dest)
         if (!dest)
             return;
             return;
-        
+
         Node* newNode = ReserveNode(value);
         Node* newNode = ReserveNode(value);
         Node* prev = dest->Prev();
         Node* prev = dest->Prev();
         newNode->next_ = dest;
         newNode->next_ = dest;
@@ -356,37 +419,37 @@ private:
         if (prev)
         if (prev)
             prev->next_ = newNode;
             prev->next_ = newNode;
         dest->prev_ = newNode;
         dest->prev_ = newNode;
-        
+
         // Reassign the head node if necessary
         // Reassign the head node if necessary
         if (dest == Head())
         if (dest == Head())
             head_ = newNode;
             head_ = newNode;
-        
+
         ++size_;
         ++size_;
     }
     }
-    
+
     /// Erase and free a node. Return pointer to the next node, or to the end if could not erase.
     /// Erase and free a node. Return pointer to the next node, or to the end if could not erase.
     Node* EraseNode(Node* node)
     Node* EraseNode(Node* node)
     {
     {
         // The tail node can not be removed
         // The tail node can not be removed
         if (!node || node == tail_)
         if (!node || node == tail_)
             return Tail();
             return Tail();
-        
+
         Node* prev = node->Prev();
         Node* prev = node->Prev();
         Node* next = node->Next();
         Node* next = node->Next();
         if (prev)
         if (prev)
             prev->next_ = next;
             prev->next_ = next;
         next->prev_ = prev;
         next->prev_ = prev;
-        
+
         // Reassign the head node if necessary
         // Reassign the head node if necessary
         if (node == Head())
         if (node == Head())
             head_ = next;
             head_ = next;
-        
+
         FreeNode(node);
         FreeNode(node);
         --size_;
         --size_;
-        
+
         return next;
         return next;
     }
     }
-    
+
     /// Reserve a node.
     /// Reserve a node.
     Node* ReserveNode()
     Node* ReserveNode()
     {
     {
@@ -394,7 +457,7 @@ private:
         new(newNode) Node();
         new(newNode) Node();
         return newNode;
         return newNode;
     }
     }
-    
+
     /// Reserve a node with initial value.
     /// Reserve a node with initial value.
     Node* ReserveNode(const T& value)
     Node* ReserveNode(const T& value)
     {
     {
@@ -402,7 +465,7 @@ private:
         new(newNode) Node(value);
         new(newNode) Node(value);
         return newNode;
         return newNode;
     }
     }
-    
+
     /// Free a node.
     /// Free a node.
     void FreeNode(Node* node)
     void FreeNode(Node* node)
     {
     {
@@ -417,8 +480,11 @@ namespace std
 {
 {
 
 
 template <class T> typename Urho3D::List<T>::ConstIterator begin(const Urho3D::List<T>& v) { return v.Begin(); }
 template <class T> typename Urho3D::List<T>::ConstIterator begin(const Urho3D::List<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::List<T>::ConstIterator end(const Urho3D::List<T>& v) { return v.End(); }
 template <class T> typename Urho3D::List<T>::ConstIterator end(const Urho3D::List<T>& v) { return v.End(); }
+
 template <class T> typename Urho3D::List<T>::Iterator begin(Urho3D::List<T>& v) { return v.Begin(); }
 template <class T> typename Urho3D::List<T>::Iterator begin(Urho3D::List<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::List<T>::Iterator end(Urho3D::List<T>& v) { return v.End(); }
 template <class T> typename Urho3D::List<T>::Iterator end(Urho3D::List<T>& v) { return v.End(); }
 
 
 }
 }

+ 17 - 10
Source/Urho3D/Container/ListBase.h

@@ -22,6 +22,12 @@
 
 
 #pragma once
 #pragma once
 
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 #include "../Container/Allocator.h"
 #include "../Container/Allocator.h"
 #include "../Container/Swap.h"
 #include "../Container/Swap.h"
 
 
@@ -37,7 +43,7 @@ struct ListNodeBase
         next_(0)
         next_(0)
     {
     {
     }
     }
-    
+
     /// Previous node.
     /// Previous node.
     ListNodeBase* prev_;
     ListNodeBase* prev_;
     /// Next node.
     /// Next node.
@@ -52,32 +58,33 @@ struct ListIteratorBase
         ptr_(0)
         ptr_(0)
     {
     {
     }
     }
-    
+
     /// Construct with a node pointer.
     /// Construct with a node pointer.
     explicit ListIteratorBase(ListNodeBase* ptr) :
     explicit ListIteratorBase(ListNodeBase* ptr) :
         ptr_(ptr)
         ptr_(ptr)
     {
     {
     }
     }
-    
+
     /// Test for equality with another iterator.
     /// Test for equality with another iterator.
-    bool operator == (const ListIteratorBase& rhs) const { return ptr_ == rhs.ptr_; }
+    bool operator ==(const ListIteratorBase& rhs) const { return ptr_ == rhs.ptr_; }
+
     /// Test for inequality with another iterator.
     /// Test for inequality with another iterator.
-    bool operator != (const ListIteratorBase& rhs) const { return ptr_ != rhs.ptr_; }
-    
+    bool operator !=(const ListIteratorBase& rhs) const { return ptr_ != rhs.ptr_; }
+
     /// Go to the next node.
     /// Go to the next node.
     void GotoNext()
     void GotoNext()
     {
     {
         if (ptr_)
         if (ptr_)
             ptr_ = ptr_->next_;
             ptr_ = ptr_->next_;
     }
     }
-    
+
     /// Go to the previous node.
     /// Go to the previous node.
     void GotoPrev()
     void GotoPrev()
     {
     {
         if (ptr_)
         if (ptr_)
             ptr_ = ptr_->prev_;
             ptr_ = ptr_->prev_;
     }
     }
-    
+
     /// Node pointer.
     /// Node pointer.
     ListNodeBase* ptr_;
     ListNodeBase* ptr_;
 };
 };
@@ -92,7 +99,7 @@ public:
         size_(0)
         size_(0)
     {
     {
     }
     }
-    
+
     /// Swap with another linked list.
     /// Swap with another linked list.
     void Swap(ListBase& rhs)
     void Swap(ListBase& rhs)
     {
     {
@@ -101,7 +108,7 @@ public:
         Urho3D::Swap(allocator_, rhs.allocator_);
         Urho3D::Swap(allocator_, rhs.allocator_);
         Urho3D::Swap(size_, rhs.size_);
         Urho3D::Swap(size_, rhs.size_);
     }
     }
-    
+
 protected:
 protected:
     /// Head node pointer.
     /// Head node pointer.
     ListNodeBase* head_;
     ListNodeBase* head_;

+ 11 - 10
Source/Urho3D/Container/Pair.h

@@ -35,21 +35,22 @@ public:
     Pair()
     Pair()
     {
     {
     }
     }
-    
+
     /// Construct with values.
     /// Construct with values.
     Pair(const T& first, const U& second) :
     Pair(const T& first, const U& second) :
         first_(first),
         first_(first),
         second_(second)
         second_(second)
     {
     {
     }
     }
-    
+
     /// Test for equality with another pair.
     /// Test for equality with another pair.
-    bool operator == (const Pair<T, U>& rhs) const { return first_ == rhs.first_ && second_ == rhs.second_; }
+    bool operator ==(const Pair<T, U>& rhs) const { return first_ == rhs.first_ && second_ == rhs.second_; }
+
     /// Test for inequality with another pair.
     /// Test for inequality with another pair.
-    bool operator != (const Pair<T, U>& rhs) const { return first_ != rhs.first_ || second_ != rhs.second_; }
-    
+    bool operator !=(const Pair<T, U>& rhs) const { return first_ != rhs.first_ || second_ != rhs.second_; }
+
     /// Test for less than with another pair.
     /// Test for less than with another pair.
-    bool operator < (const Pair<T, U>& rhs) const
+    bool operator <(const Pair<T, U>& rhs) const
     {
     {
         if (first_ < rhs.first_)
         if (first_ < rhs.first_)
             return true;
             return true;
@@ -57,9 +58,9 @@ public:
             return false;
             return false;
         return second_ < rhs.second_;
         return second_ < rhs.second_;
     }
     }
-    
+
     /// Test for greater than with another pair.
     /// Test for greater than with another pair.
-    bool operator > (const Pair<T, U>& rhs) const
+    bool operator >(const Pair<T, U>& rhs) const
     {
     {
         if (first_ > rhs.first_)
         if (first_ > rhs.first_)
             return true;
             return true;
@@ -67,10 +68,10 @@ public:
             return false;
             return false;
         return second_ > rhs.second_;
         return second_ > rhs.second_;
     }
     }
-    
+
     /// Return hash value for HashSet & HashMap.
     /// Return hash value for HashSet & HashMap.
     unsigned ToHash() const { return (MakeHash(first_) & 0xffff) | (MakeHash(second_) << 16); }
     unsigned ToHash() const { return (MakeHash(first_) & 0xffff) | (MakeHash(second_) << 16); }
-    
+
     /// First value.
     /// First value.
     T first_;
     T first_;
     /// Second value.
     /// Second value.

+ 106 - 75
Source/Urho3D/Container/Ptr.h

@@ -39,71 +39,89 @@ public:
         ptr_(0)
         ptr_(0)
     {
     {
     }
     }
-    
+
     /// Copy-construct from another shared pointer.
     /// Copy-construct from another shared pointer.
     SharedPtr(const SharedPtr<T>& rhs) :
     SharedPtr(const SharedPtr<T>& rhs) :
         ptr_(rhs.ptr_)
         ptr_(rhs.ptr_)
     {
     {
         AddRef();
         AddRef();
     }
     }
-    
+
     /// Construct from a raw pointer.
     /// Construct from a raw pointer.
     explicit SharedPtr(T* ptr) :
     explicit SharedPtr(T* ptr) :
         ptr_(ptr)
         ptr_(ptr)
     {
     {
         AddRef();
         AddRef();
     }
     }
-    
+
     /// Destruct. Release the object reference.
     /// Destruct. Release the object reference.
     ~SharedPtr()
     ~SharedPtr()
     {
     {
         ReleaseRef();
         ReleaseRef();
     }
     }
-    
+
     /// Assign from another shared pointer.
     /// Assign from another shared pointer.
-    SharedPtr<T>& operator = (const SharedPtr<T>& rhs)
+    SharedPtr<T>& operator =(const SharedPtr<T>& rhs)
     {
     {
         if (ptr_ == rhs.ptr_)
         if (ptr_ == rhs.ptr_)
             return *this;
             return *this;
-        
+
         ReleaseRef();
         ReleaseRef();
         ptr_ = rhs.ptr_;
         ptr_ = rhs.ptr_;
         AddRef();
         AddRef();
-        
+
         return *this;
         return *this;
     }
     }
-    
+
     /// Assign from a raw pointer.
     /// Assign from a raw pointer.
-    SharedPtr<T>& operator = (T* ptr)
+    SharedPtr<T>& operator =(T* ptr)
     {
     {
         if (ptr_ == ptr)
         if (ptr_ == ptr)
             return *this;
             return *this;
-        
+
         ReleaseRef();
         ReleaseRef();
         ptr_ = ptr;
         ptr_ = ptr;
         AddRef();
         AddRef();
-        
+
         return *this;
         return *this;
     }
     }
-    
+
     /// Point to the object.
     /// Point to the object.
-    T* operator -> () const { assert(ptr_); return ptr_; }
+    T* operator ->() const
+    {
+        assert(ptr_);
+        return ptr_;
+    }
+
     /// Dereference the object.
     /// Dereference the object.
-    T& operator * () const { assert(ptr_); return *ptr_; }
+    T& operator *() const
+    {
+        assert(ptr_);
+        return *ptr_;
+    }
+
     /// Subscript the object if applicable.
     /// Subscript the object if applicable.
-    T& operator [] (const int index) { assert(ptr_); return ptr_[index]; }
+    T& operator [](const int index)
+    {
+        assert(ptr_);
+        return ptr_[index];
+    }
+
     /// Test for less than with another shared pointer.
     /// Test for less than with another shared pointer.
-    bool operator < (const SharedPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+    bool operator <(const SharedPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+
     /// Test for equality with another shared pointer.
     /// Test for equality with another shared pointer.
-    bool operator == (const SharedPtr<T>& rhs) const { return ptr_ == rhs.ptr_; }
+    bool operator ==(const SharedPtr<T>& rhs) const { return ptr_ == rhs.ptr_; }
+
     /// Test for inequality with another shared pointer.
     /// Test for inequality with another shared pointer.
-    bool operator != (const SharedPtr<T>& rhs) const { return ptr_ != rhs.ptr_; }
+    bool operator !=(const SharedPtr<T>& rhs) const { return ptr_ != rhs.ptr_; }
+
     /// Convert to a raw pointer.
     /// Convert to a raw pointer.
-    operator T* () const { return ptr_; }
-    
+    operator T*() const { return ptr_; }
+
     /// Reset to null and release the object reference.
     /// Reset to null and release the object reference.
     void Reset() { ReleaseRef(); }
     void Reset() { ReleaseRef(); }
-    
+
     /// Detach without destroying the object even if the refcount goes zero. To be used for scripting language interoperation.
     /// Detach without destroying the object even if the refcount goes zero. To be used for scripting language interoperation.
     void Detach()
     void Detach()
     {
     {
@@ -115,7 +133,7 @@ public:
             --refCount->refs_; // 0 refs
             --refCount->refs_; // 0 refs
         }
         }
     }
     }
-    
+
     /// Perform a static cast from a shared pointer of another type.
     /// Perform a static cast from a shared pointer of another type.
     template <class U> void StaticCast(const SharedPtr<U>& rhs)
     template <class U> void StaticCast(const SharedPtr<U>& rhs)
     {
     {
@@ -123,7 +141,7 @@ public:
         ptr_ = static_cast<T*>(rhs.Get());
         ptr_ = static_cast<T*>(rhs.Get());
         AddRef();
         AddRef();
     }
     }
-    
+
     /// Perform a dynamic cast from a shared pointer of another type.
     /// Perform a dynamic cast from a shared pointer of another type.
     template <class U> void DynamicCast(const SharedPtr<U>& rhs)
     template <class U> void DynamicCast(const SharedPtr<U>& rhs)
     {
     {
@@ -131,33 +149,39 @@ public:
         ptr_ = dynamic_cast<T*>(rhs.Get());
         ptr_ = dynamic_cast<T*>(rhs.Get());
         AddRef();
         AddRef();
     }
     }
-    
+
     /// Check if the pointer is null.
     /// Check if the pointer is null.
     bool Null() const { return ptr_ == 0; }
     bool Null() const { return ptr_ == 0; }
+
     /// Check if the pointer is not null.
     /// Check if the pointer is not null.
     bool NotNull() const { return ptr_ != 0; }
     bool NotNull() const { return ptr_ != 0; }
+
     /// Return the raw pointer.
     /// Return the raw pointer.
     T* Get() const { return ptr_; }
     T* Get() const { return ptr_; }
+
     /// Return the object's reference count, or 0 if the pointer is null.
     /// Return the object's reference count, or 0 if the pointer is null.
     int Refs() const { return ptr_ ? ptr_->Refs() : 0; }
     int Refs() const { return ptr_ ? ptr_->Refs() : 0; }
+
     /// Return the object's weak reference count, or 0 if the pointer is null.
     /// Return the object's weak reference count, or 0 if the pointer is null.
     int WeakRefs() const { return ptr_ ? ptr_->WeakRefs() : 0; }
     int WeakRefs() const { return ptr_ ? ptr_->WeakRefs() : 0; }
+
     /// Return pointer to the RefCount structure.
     /// Return pointer to the RefCount structure.
     RefCount* RefCountPtr() const { return ptr_ ? ptr_->RefCountPtr() : 0; }
     RefCount* RefCountPtr() const { return ptr_ ? ptr_->RefCountPtr() : 0; }
+
     /// Return hash value for HashSet & HashMap.
     /// Return hash value for HashSet & HashMap.
-    unsigned ToHash() const { return ((unsigned)(size_t)ptr_) / sizeof(T); }
-    
+    unsigned ToHash() const { return (unsigned)((size_t)ptr_ / sizeof(T)); }
+
 private:
 private:
     /// Prevent direct assignment from a shared pointer of another type.
     /// Prevent direct assignment from a shared pointer of another type.
-    template <class U> SharedPtr<T>& operator = (const SharedPtr<U>& rhs);
-    
+    template <class U> SharedPtr<T>& operator =(const SharedPtr<U>& rhs);
+
     /// Add a reference to the object pointed to.
     /// Add a reference to the object pointed to.
     void AddRef()
     void AddRef()
     {
     {
         if (ptr_)
         if (ptr_)
             ptr_->AddRef();
             ptr_->AddRef();
     }
     }
-    
+
     /// Release the object reference and delete it if necessary.
     /// Release the object reference and delete it if necessary.
     void ReleaseRef()
     void ReleaseRef()
     {
     {
@@ -167,7 +191,7 @@ private:
             ptr_ = 0;
             ptr_ = 0;
         }
         }
     }
     }
-    
+
     /// Pointer to the object.
     /// Pointer to the object.
     T* ptr_;
     T* ptr_;
 };
 };
@@ -198,7 +222,7 @@ public:
         refCount_(0)
         refCount_(0)
     {
     {
     }
     }
-    
+
     /// Copy-construct from another weak pointer.
     /// Copy-construct from another weak pointer.
     WeakPtr(const WeakPtr<T>& rhs) :
     WeakPtr(const WeakPtr<T>& rhs) :
         ptr_(rhs.ptr_),
         ptr_(rhs.ptr_),
@@ -206,7 +230,7 @@ public:
     {
     {
         AddRef();
         AddRef();
     }
     }
-    
+
     /// Construct from a shared pointer.
     /// Construct from a shared pointer.
     WeakPtr(const SharedPtr<T>& rhs) :
     WeakPtr(const SharedPtr<T>& rhs) :
         ptr_(rhs.Get()),
         ptr_(rhs.Get()),
@@ -214,7 +238,7 @@ public:
     {
     {
         AddRef();
         AddRef();
     }
     }
-    
+
     /// Construct from a raw pointer.
     /// Construct from a raw pointer.
     explicit WeakPtr(T* ptr) :
     explicit WeakPtr(T* ptr) :
         ptr_(ptr),
         ptr_(ptr),
@@ -222,57 +246,57 @@ public:
     {
     {
         AddRef();
         AddRef();
     }
     }
-    
+
     /// Destruct. Release the weak reference to the object.
     /// Destruct. Release the weak reference to the object.
     ~WeakPtr()
     ~WeakPtr()
     {
     {
         ReleaseRef();
         ReleaseRef();
     }
     }
-    
+
     /// Assign from a shared pointer.
     /// Assign from a shared pointer.
-    WeakPtr<T>& operator = (const SharedPtr<T>& rhs)
+    WeakPtr<T>& operator =(const SharedPtr<T>& rhs)
     {
     {
         if (ptr_ == rhs.Get() && refCount_ == rhs.RefCountPtr())
         if (ptr_ == rhs.Get() && refCount_ == rhs.RefCountPtr())
             return *this;
             return *this;
-        
+
         ReleaseRef();
         ReleaseRef();
         ptr_ = rhs.Get();
         ptr_ = rhs.Get();
         refCount_ = rhs.RefCountPtr();
         refCount_ = rhs.RefCountPtr();
         AddRef();
         AddRef();
-        
+
         return *this;
         return *this;
     }
     }
-    
+
     /// Assign from a weak pointer.
     /// Assign from a weak pointer.
-    WeakPtr<T>& operator = (const WeakPtr<T>& rhs)
+    WeakPtr<T>& operator =(const WeakPtr<T>& rhs)
     {
     {
         if (ptr_ == rhs.ptr_ && refCount_ == rhs.refCount_)
         if (ptr_ == rhs.ptr_ && refCount_ == rhs.refCount_)
             return *this;
             return *this;
-        
+
         ReleaseRef();
         ReleaseRef();
         ptr_ = rhs.ptr_;
         ptr_ = rhs.ptr_;
         refCount_ = rhs.refCount_;
         refCount_ = rhs.refCount_;
         AddRef();
         AddRef();
-        
+
         return *this;
         return *this;
     }
     }
-    
+
     /// Assign from a raw pointer.
     /// Assign from a raw pointer.
-    WeakPtr<T>& operator = (T* ptr)
+    WeakPtr<T>& operator =(T* ptr)
     {
     {
         RefCount* refCount = ptr ? ptr->RefCountPtr() : 0;
         RefCount* refCount = ptr ? ptr->RefCountPtr() : 0;
-        
+
         if (ptr_ == ptr && refCount_ == refCount)
         if (ptr_ == ptr && refCount_ == refCount)
             return *this;
             return *this;
-        
+
         ReleaseRef();
         ReleaseRef();
         ptr_ = ptr;
         ptr_ = ptr;
         refCount_ = refCount;
         refCount_ = refCount;
         AddRef();
         AddRef();
-        
+
         return *this;
         return *this;
     }
     }
-    
+
     /// Convert to a shared pointer. If expired, return a null shared pointer.
     /// Convert to a shared pointer. If expired, return a null shared pointer.
     SharedPtr<T> Lock() const
     SharedPtr<T> Lock() const
     {
     {
@@ -281,7 +305,7 @@ public:
         else
         else
             return SharedPtr<T>(ptr_);
             return SharedPtr<T>(ptr_);
     }
     }
-    
+
     /// Return raw pointer. If expired, return null.
     /// Return raw pointer. If expired, return null.
     T* Get() const
     T* Get() const
     {
     {
@@ -290,43 +314,46 @@ public:
         else
         else
             return ptr_;
             return ptr_;
     }
     }
-    
+
     /// Point to the object.
     /// Point to the object.
-    T* operator -> () const
+    T* operator ->() const
     {
     {
         T* rawPtr = Get();
         T* rawPtr = Get();
         assert(rawPtr);
         assert(rawPtr);
         return rawPtr;
         return rawPtr;
     }
     }
-    
+
     /// Dereference the object.
     /// Dereference the object.
-    T& operator * () const
+    T& operator *() const
     {
     {
         T* rawPtr = Get();
         T* rawPtr = Get();
         assert(rawPtr);
         assert(rawPtr);
         return *rawPtr;
         return *rawPtr;
     }
     }
-    
+
     /// Subscript the object if applicable.
     /// Subscript the object if applicable.
-    T& operator [] (const int index)
+    T& operator [](const int index)
     {
     {
         T* rawPtr = Get();
         T* rawPtr = Get();
         assert(rawPtr);
         assert(rawPtr);
         return (*rawPtr)[index];
         return (*rawPtr)[index];
     }
     }
-    
+
     /// Test for equality with another weak pointer.
     /// Test for equality with another weak pointer.
-    bool operator == (const WeakPtr<T>& rhs) const { return ptr_ == rhs.ptr_ && refCount_ == rhs.refCount_; }
+    bool operator ==(const WeakPtr<T>& rhs) const { return ptr_ == rhs.ptr_ && refCount_ == rhs.refCount_; }
+
     /// Test for inequality with another weak pointer.
     /// Test for inequality with another weak pointer.
-    bool operator != (const WeakPtr<T>& rhs) const { return ptr_ != rhs.ptr_ || refCount_ != rhs.refCount_; }
+    bool operator !=(const WeakPtr<T>& rhs) const { return ptr_ != rhs.ptr_ || refCount_ != rhs.refCount_; }
+
     /// Test for less than with another weak pointer.
     /// Test for less than with another weak pointer.
-    bool operator < (const WeakPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+    bool operator <(const WeakPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+
     /// Convert to a raw pointer, null if the object is expired.
     /// Convert to a raw pointer, null if the object is expired.
-    operator T* () const { return Get(); }
-    
+    operator T*() const { return Get(); }
+
     /// Reset to null and release the weak reference.
     /// Reset to null and release the weak reference.
     void Reset() { ReleaseRef(); }
     void Reset() { ReleaseRef(); }
-    
+
     /// Perform a static cast from a weak pointer of another type.
     /// Perform a static cast from a weak pointer of another type.
     template <class U> void StaticCast(const WeakPtr<U>& rhs)
     template <class U> void StaticCast(const WeakPtr<U>& rhs)
     {
     {
@@ -335,13 +362,13 @@ public:
         refCount_ = rhs.refCount_;
         refCount_ = rhs.refCount_;
         AddRef();
         AddRef();
     }
     }
-    
+
     /// Perform a dynamic cast from a weak pointer of another type.
     /// Perform a dynamic cast from a weak pointer of another type.
     template <class U> void DynamicCast(const WeakPtr<U>& rhs)
     template <class U> void DynamicCast(const WeakPtr<U>& rhs)
     {
     {
         ReleaseRef();
         ReleaseRef();
         ptr_ = dynamic_cast<T*>(rhs.Get());
         ptr_ = dynamic_cast<T*>(rhs.Get());
-        
+
         if (ptr_)
         if (ptr_)
         {
         {
             refCount_ = rhs.refCount_;
             refCount_ = rhs.refCount_;
@@ -350,14 +377,16 @@ public:
         else
         else
             refCount_ = 0;
             refCount_ = 0;
     }
     }
-    
+
     /// Check if the pointer is null.
     /// Check if the pointer is null.
     bool Null() const { return refCount_ == 0; }
     bool Null() const { return refCount_ == 0; }
+
     /// Check if the pointer is not null.
     /// Check if the pointer is not null.
     bool NotNull() const { return refCount_ != 0; }
     bool NotNull() const { return refCount_ != 0; }
+
     /// Return the object's reference count, or 0 if null pointer or if object has expired.
     /// Return the object's reference count, or 0 if null pointer or if object has expired.
     int Refs() const { return (refCount_ && refCount_->refs_ >= 0) ? refCount_->refs_ : 0; }
     int Refs() const { return (refCount_ && refCount_->refs_ >= 0) ? refCount_->refs_ : 0; }
-    
+
     /// Return the object's weak reference count.
     /// Return the object's weak reference count.
     int WeakRefs() const
     int WeakRefs() const
     {
     {
@@ -366,18 +395,20 @@ public:
         else
         else
             return refCount_ ? refCount_->weakRefs_ : 0;
             return refCount_ ? refCount_->weakRefs_ : 0;
     }
     }
-    
+
     /// Return whether the object has expired. If null pointer, always return true.
     /// Return whether the object has expired. If null pointer, always return true.
     bool Expired() const { return refCount_ ? refCount_->refs_ < 0 : true; }
     bool Expired() const { return refCount_ ? refCount_->refs_ < 0 : true; }
+
     /// Return pointer to the RefCount structure.
     /// Return pointer to the RefCount structure.
     RefCount* RefCountPtr() const { return refCount_; }
     RefCount* RefCountPtr() const { return refCount_; }
+
     /// Return hash value for HashSet & HashMap.
     /// Return hash value for HashSet & HashMap.
-    unsigned ToHash() const { return ((unsigned)(size_t)ptr_) / sizeof(T); }
-    
+    unsigned ToHash() const { return (unsigned)((size_t)ptr_ / sizeof(T)); }
+
 private:
 private:
     /// Prevent direct assignment from a weak pointer of different type.
     /// Prevent direct assignment from a weak pointer of different type.
-    template <class U> WeakPtr<T>& operator = (const WeakPtr<U>& rhs);
-    
+    template <class U> WeakPtr<T>& operator =(const WeakPtr<U>& rhs);
+
     /// Add a weak reference to the object pointed to.
     /// Add a weak reference to the object pointed to.
     void AddRef()
     void AddRef()
     {
     {
@@ -387,7 +418,7 @@ private:
             ++(refCount_->weakRefs_);
             ++(refCount_->weakRefs_);
         }
         }
     }
     }
-    
+
     /// Release the weak reference. Delete the Refcount structure if necessary.
     /// Release the weak reference. Delete the Refcount structure if necessary.
     void ReleaseRef()
     void ReleaseRef()
     {
     {
@@ -395,15 +426,15 @@ private:
         {
         {
             assert(refCount_->weakRefs_ > 0);
             assert(refCount_->weakRefs_ > 0);
             --(refCount_->weakRefs_);
             --(refCount_->weakRefs_);
-            
+
             if (Expired() && !refCount_->weakRefs_)
             if (Expired() && !refCount_->weakRefs_)
                 delete refCount_;
                 delete refCount_;
         }
         }
-        
+
         ptr_ = 0;
         ptr_ = 0;
         refCount_ = 0;
         refCount_ = 0;
     }
     }
-    
+
     /// Pointer to the object.
     /// Pointer to the object.
     T* ptr_;
     T* ptr_;
     /// Pointer to the RefCount structure.
     /// Pointer to the RefCount structure.

+ 4 - 4
Source/Urho3D/Container/RefCounted.cpp

@@ -20,9 +20,9 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
-#include "../Container/RefCounted.h"
+#include "../Precompiled.h"
 
 
-#include <cassert>
+#include "../Container/RefCounted.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -41,13 +41,13 @@ RefCounted::~RefCounted()
     assert(refCount_);
     assert(refCount_);
     assert(refCount_->refs_ == 0);
     assert(refCount_->refs_ == 0);
     assert(refCount_->weakRefs_ > 0);
     assert(refCount_->weakRefs_ > 0);
-    
+
     // Mark object as expired, release the self weak ref and delete the refcount if no other weak refs exist
     // Mark object as expired, release the self weak ref and delete the refcount if no other weak refs exist
     refCount_->refs_ = -1;
     refCount_->refs_ = -1;
     (refCount_->weakRefs_)--;
     (refCount_->weakRefs_)--;
     if (!refCount_->weakRefs_)
     if (!refCount_->weakRefs_)
         delete refCount_;
         delete refCount_;
-    
+
     refCount_ = 0;
     refCount_ = 0;
 }
 }
 
 

+ 13 - 6
Source/Urho3D/Container/RefCounted.h

@@ -22,6 +22,12 @@
 
 
 #pragma once
 #pragma once
 
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 namespace Urho3D
 namespace Urho3D
 {
 {
 
 
@@ -34,7 +40,7 @@ struct RefCount
         weakRefs_(0)
         weakRefs_(0)
     {
     {
     }
     }
-    
+
     /// Destruct.
     /// Destruct.
     ~RefCount()
     ~RefCount()
     {
     {
@@ -42,7 +48,7 @@ struct RefCount
         refs_ = -1;
         refs_ = -1;
         weakRefs_ = -1;
         weakRefs_ = -1;
     }
     }
-    
+
     /// Reference count. If below zero, the object has been destroyed.
     /// Reference count. If below zero, the object has been destroyed.
     int refs_;
     int refs_;
     /// Weak reference count.
     /// Weak reference count.
@@ -57,7 +63,7 @@ public:
     RefCounted();
     RefCounted();
     /// Destruct. Mark as expired and also delete the reference count structure if no outside weak references exist.
     /// Destruct. Mark as expired and also delete the reference count structure if no outside weak references exist.
     virtual ~RefCounted();
     virtual ~RefCounted();
-    
+
     /// Increment reference count. Can also be called outside of a SharedPtr for traditional reference counting.
     /// Increment reference count. Can also be called outside of a SharedPtr for traditional reference counting.
     void AddRef();
     void AddRef();
     /// Decrement reference count and delete self if no more references. Can also be called outside of a SharedPtr for traditional reference counting.
     /// Decrement reference count and delete self if no more references. Can also be called outside of a SharedPtr for traditional reference counting.
@@ -66,15 +72,16 @@ public:
     int Refs() const;
     int Refs() const;
     /// Return weak reference count.
     /// Return weak reference count.
     int WeakRefs() const;
     int WeakRefs() const;
+
     /// Return pointer to the reference count structure.
     /// Return pointer to the reference count structure.
     RefCount* RefCountPtr() { return refCount_; }
     RefCount* RefCountPtr() { return refCount_; }
-    
+
 private:
 private:
     /// Prevent copy construction.
     /// Prevent copy construction.
     RefCounted(const RefCounted& rhs);
     RefCounted(const RefCounted& rhs);
     /// Prevent assignment.
     /// Prevent assignment.
-    RefCounted& operator = (const RefCounted& rhs);
-    
+    RefCounted& operator =(const RefCounted& rhs);
+
     /// Pointer to the reference count structure.
     /// Pointer to the reference count structure.
     RefCount* refCount_;
     RefCount* refCount_;
 };
 };

+ 4 - 4
Source/Urho3D/Container/Sort.h

@@ -76,7 +76,7 @@ template <class T> void InitialQuickSort(RandomAccessIterator<T> begin, RandomAc
             pivot = begin;
             pivot = begin;
         else if (*(end - 1) < *pivot && *begin < *(end - 1))
         else if (*(end - 1) < *pivot && *begin < *(end - 1))
             pivot = end - 1;
             pivot = end - 1;
-        
+
         // Partition and sort recursively
         // Partition and sort recursively
         RandomAccessIterator<T> i = begin - 1;
         RandomAccessIterator<T> i = begin - 1;
         RandomAccessIterator<T> j = end;
         RandomAccessIterator<T> j = end;
@@ -90,7 +90,7 @@ template <class T> void InitialQuickSort(RandomAccessIterator<T> begin, RandomAc
             else
             else
                 break;
                 break;
         }
         }
-        
+
         InitialQuickSort(begin, j + 1);
         InitialQuickSort(begin, j + 1);
         begin = j + 1;
         begin = j + 1;
     }
     }
@@ -107,7 +107,7 @@ template <class T, class U> void InitialQuickSort(RandomAccessIterator<T> begin,
             pivot = begin;
             pivot = begin;
         else if (compare(*(end - 1), *pivot) && compare(*begin, *(end - 1)))
         else if (compare(*(end - 1), *pivot) && compare(*begin, *(end - 1)))
             pivot = end - 1;
             pivot = end - 1;
-        
+
         // Partition and sort recursively
         // Partition and sort recursively
         RandomAccessIterator<T> i = begin - 1;
         RandomAccessIterator<T> i = begin - 1;
         RandomAccessIterator<T> j = end;
         RandomAccessIterator<T> j = end;
@@ -121,7 +121,7 @@ template <class T, class U> void InitialQuickSort(RandomAccessIterator<T> begin,
             else
             else
                 break;
                 break;
         }
         }
-        
+
         InitialQuickSort(begin, j + 1, compare);
         InitialQuickSort(begin, j + 1, compare);
         begin = j + 1;
         begin = j + 1;
     }
     }

Dosya farkı çok büyük olduğundan ihmal edildi
+ 167 - 163
Source/Urho3D/Container/Str.cpp


+ 156 - 92
Source/Urho3D/Container/Str.h

@@ -24,8 +24,8 @@
 
 
 #include "../Container/Vector.h"
 #include "../Container/Vector.h"
 
 
-#include <cstring>
 #include <cstdarg>
 #include <cstdarg>
+#include <cstring>
 #include <cctype>
 #include <cctype>
 
 
 namespace Urho3D
 namespace Urho3D
@@ -42,7 +42,7 @@ class URHO3D_API String
 public:
 public:
     typedef RandomAccessIterator<char> Iterator;
     typedef RandomAccessIterator<char> Iterator;
     typedef RandomAccessConstIterator<char> ConstIterator;
     typedef RandomAccessConstIterator<char> ConstIterator;
-    
+
     /// Construct empty.
     /// Construct empty.
     String() :
     String() :
         length_(0),
         length_(0),
@@ -50,7 +50,7 @@ public:
         buffer_(&endZero)
         buffer_(&endZero)
     {
     {
     }
     }
-    
+
     /// Construct from another string.
     /// Construct from another string.
     String(const String& str) :
     String(const String& str) :
         length_(0),
         length_(0),
@@ -59,7 +59,7 @@ public:
     {
     {
         *this = str;
         *this = str;
     }
     }
-    
+
     /// Construct from a C string.
     /// Construct from a C string.
     String(const char* str) :
     String(const char* str) :
         length_(0),
         length_(0),
@@ -68,7 +68,7 @@ public:
     {
     {
         *this = str;
         *this = str;
     }
     }
-    
+
     /// Construct from a C string.
     /// Construct from a C string.
     String(char* str) :
     String(char* str) :
         length_(0),
         length_(0),
@@ -77,7 +77,7 @@ public:
     {
     {
         *this = (const char*)str;
         *this = (const char*)str;
     }
     }
-    
+
     /// Construct from a char array and length.
     /// Construct from a char array and length.
     String(const char* str, unsigned length) :
     String(const char* str, unsigned length) :
         length_(0),
         length_(0),
@@ -87,7 +87,7 @@ public:
         Resize(length);
         Resize(length);
         CopyChars(buffer_, str, length);
         CopyChars(buffer_, str, length);
     }
     }
-    
+
     /// Construct from a null-terminated wide character array.
     /// Construct from a null-terminated wide character array.
     String(const wchar_t* str) :
     String(const wchar_t* str) :
         length_(0),
         length_(0),
@@ -96,7 +96,7 @@ public:
     {
     {
         SetUTF8FromWChar(str);
         SetUTF8FromWChar(str);
     }
     }
-    
+
     /// Construct from a null-terminated wide character array.
     /// Construct from a null-terminated wide character array.
     String(wchar_t* str) :
     String(wchar_t* str) :
         length_(0),
         length_(0),
@@ -105,10 +105,10 @@ public:
     {
     {
         SetUTF8FromWChar(str);
         SetUTF8FromWChar(str);
     }
     }
-    
+
     /// Construct from a wide character string.
     /// Construct from a wide character string.
     String(const WString& str);
     String(const WString& str);
-    
+
     /// Construct from an integer.
     /// Construct from an integer.
     explicit String(int value);
     explicit String(int value);
     /// Construct from a short integer.
     /// Construct from a short integer.
@@ -135,7 +135,7 @@ public:
     explicit String(char value);
     explicit String(char value);
     /// Construct from a character and fill length.
     /// Construct from a character and fill length.
     explicit String(char value, unsigned length);
     explicit String(char value, unsigned length);
-    
+
     /// Construct from a convertable value.
     /// Construct from a convertable value.
     template <class T> explicit String(const T& value) :
     template <class T> explicit String(const T& value) :
         length_(0),
         length_(0),
@@ -144,144 +144,172 @@ public:
     {
     {
         *this = value.ToString();
         *this = value.ToString();
     }
     }
-    
+
     /// Destruct.
     /// Destruct.
     ~String()
     ~String()
     {
     {
         if (capacity_)
         if (capacity_)
             delete[] buffer_;
             delete[] buffer_;
     }
     }
-    
+
     /// Assign a string.
     /// Assign a string.
-    String& operator = (const String& rhs)
+    String& operator =(const String& rhs)
     {
     {
         Resize(rhs.length_);
         Resize(rhs.length_);
         CopyChars(buffer_, rhs.buffer_, rhs.length_);
         CopyChars(buffer_, rhs.buffer_, rhs.length_);
-        
+
         return *this;
         return *this;
     }
     }
-    
+
     /// Assign a C string.
     /// Assign a C string.
-    String& operator = (const char* rhs)
+    String& operator =(const char* rhs)
     {
     {
         unsigned rhsLength = CStringLength(rhs);
         unsigned rhsLength = CStringLength(rhs);
         Resize(rhsLength);
         Resize(rhsLength);
         CopyChars(buffer_, rhs, rhsLength);
         CopyChars(buffer_, rhs, rhsLength);
-        
+
         return *this;
         return *this;
     }
     }
-    
+
     /// Add-assign a string.
     /// Add-assign a string.
-    String& operator += (const String& rhs)
+    String& operator +=(const String& rhs)
     {
     {
         unsigned oldLength = length_;
         unsigned oldLength = length_;
         Resize(length_ + rhs.length_);
         Resize(length_ + rhs.length_);
         CopyChars(buffer_ + oldLength, rhs.buffer_, rhs.length_);
         CopyChars(buffer_ + oldLength, rhs.buffer_, rhs.length_);
-        
+
         return *this;
         return *this;
     }
     }
-    
+
     /// Add-assign a C string.
     /// Add-assign a C string.
-    String& operator += (const char* rhs)
+    String& operator +=(const char* rhs)
     {
     {
         unsigned rhsLength = CStringLength(rhs);
         unsigned rhsLength = CStringLength(rhs);
         unsigned oldLength = length_;
         unsigned oldLength = length_;
         Resize(length_ + rhsLength);
         Resize(length_ + rhsLength);
         CopyChars(buffer_ + oldLength, rhs, rhsLength);
         CopyChars(buffer_ + oldLength, rhs, rhsLength);
-        
+
         return *this;
         return *this;
     }
     }
-    
+
     /// Add-assign a character.
     /// Add-assign a character.
-    String& operator += (char rhs)
+    String& operator +=(char rhs)
     {
     {
         unsigned oldLength = length_;
         unsigned oldLength = length_;
         Resize(length_ + 1);
         Resize(length_ + 1);
-        buffer_[oldLength]  = rhs;
-        
+        buffer_[oldLength] = rhs;
+
         return *this;
         return *this;
     }
     }
-    
+
     /// Add-assign an integer.
     /// Add-assign an integer.
-    String& operator += (int rhs);
+    String& operator +=(int rhs);
     /// Add-assign a short integer.
     /// Add-assign a short integer.
-    String& operator += (short rhs);
+    String& operator +=(short rhs);
     /// Add-assign a long integer.
     /// Add-assign a long integer.
-    String& operator += (long rhs);
+    String& operator +=(long rhs);
     /// Add-assign a long long integer.
     /// Add-assign a long long integer.
-    String& operator += (long long rhs);
+    String& operator +=(long long rhs);
     /// Add-assign an unsigned integer.
     /// Add-assign an unsigned integer.
-    String& operator += (unsigned rhs);
+    String& operator +=(unsigned rhs);
     /// Add-assign a short unsigned integer.
     /// Add-assign a short unsigned integer.
-    String& operator += (unsigned short rhs);
+    String& operator +=(unsigned short rhs);
     /// Add-assign a long unsigned integer.
     /// Add-assign a long unsigned integer.
-    String& operator += (unsigned long rhs);
+    String& operator +=(unsigned long rhs);
     /// Add-assign a long long unsigned integer.
     /// Add-assign a long long unsigned integer.
-    String& operator += (unsigned long long rhs);
+    String& operator +=(unsigned long long rhs);
     /// Add-assign a float.
     /// Add-assign a float.
-    String& operator += (float rhs);
+    String& operator +=(float rhs);
     /// Add-assign a bool.
     /// Add-assign a bool.
-    String& operator += (bool rhs);
+    String& operator +=(bool rhs);
+
     /// Add-assign an arbitraty type.
     /// Add-assign an arbitraty type.
-    template <class T> String operator += (const T& rhs) { return *this += rhs.ToString(); }
-    
+    template <class T> String operator +=(const T& rhs) { return *this += rhs.ToString(); }
+
     /// Add a string.
     /// Add a string.
-    String operator + (const String& rhs) const
+    String operator +(const String& rhs) const
     {
     {
         String ret;
         String ret;
         ret.Resize(length_ + rhs.length_);
         ret.Resize(length_ + rhs.length_);
         CopyChars(ret.buffer_, buffer_, length_);
         CopyChars(ret.buffer_, buffer_, length_);
         CopyChars(ret.buffer_ + length_, rhs.buffer_, rhs.length_);
         CopyChars(ret.buffer_ + length_, rhs.buffer_, rhs.length_);
-        
+
         return ret;
         return ret;
     }
     }
-    
+
     /// Add a C string.
     /// Add a C string.
-    String operator + (const char* rhs) const
+    String operator +(const char* rhs) const
     {
     {
         unsigned rhsLength = CStringLength(rhs);
         unsigned rhsLength = CStringLength(rhs);
         String ret;
         String ret;
         ret.Resize(length_ + rhsLength);
         ret.Resize(length_ + rhsLength);
         CopyChars(ret.buffer_, buffer_, length_);
         CopyChars(ret.buffer_, buffer_, length_);
         CopyChars(ret.buffer_ + length_, rhs, rhsLength);
         CopyChars(ret.buffer_ + length_, rhs, rhsLength);
-        
+
         return ret;
         return ret;
     }
     }
-    
+
     /// Add a character.
     /// Add a character.
-    String operator + (char rhs) const
+    String operator +(char rhs) const
     {
     {
         String ret(*this);
         String ret(*this);
         ret += rhs;
         ret += rhs;
-        
+
         return ret;
         return ret;
     }
     }
-    
+
     /// Test for equality with another string.
     /// Test for equality with another string.
-    bool operator == (const String& rhs) const { return strcmp(CString(), rhs.CString()) == 0; }
+    bool operator ==(const String& rhs) const { return strcmp(CString(), rhs.CString()) == 0; }
+
     /// Test for inequality with another string.
     /// Test for inequality with another string.
-    bool operator != (const String& rhs) const { return strcmp(CString(), rhs.CString()) != 0; }
+    bool operator !=(const String& rhs) const { return strcmp(CString(), rhs.CString()) != 0; }
+
     /// Test if string is less than another string.
     /// Test if string is less than another string.
-    bool operator < (const String& rhs) const { return strcmp(CString(), rhs.CString()) < 0; }
+    bool operator <(const String& rhs) const { return strcmp(CString(), rhs.CString()) < 0; }
+
     /// Test if string is greater than another string.
     /// Test if string is greater than another string.
-    bool operator > (const String& rhs) const { return strcmp(CString(), rhs.CString()) > 0; }
+    bool operator >(const String& rhs) const { return strcmp(CString(), rhs.CString()) > 0; }
+
     /// Test for equality with a C string.
     /// Test for equality with a C string.
-    bool operator == (const char* rhs) const { return strcmp(CString(), rhs) == 0; }
+    bool operator ==(const char* rhs) const { return strcmp(CString(), rhs) == 0; }
+
     /// Test for inequality with a C string.
     /// Test for inequality with a C string.
-    bool operator != (const char* rhs) const { return strcmp(CString(), rhs) != 0; }
+    bool operator !=(const char* rhs) const { return strcmp(CString(), rhs) != 0; }
+
     /// Test if string is less than a C string.
     /// Test if string is less than a C string.
-    bool operator < (const char* rhs) const { return strcmp(CString(), rhs) < 0; }
+    bool operator <(const char* rhs) const { return strcmp(CString(), rhs) < 0; }
+
     /// Test if string is greater than a C string.
     /// Test if string is greater than a C string.
-    bool operator > (const char* rhs) const { return strcmp(CString(), rhs) > 0; }
+    bool operator >(const char* rhs) const { return strcmp(CString(), rhs) > 0; }
+
     /// Return char at index.
     /// Return char at index.
-    char& operator [] (unsigned index) { assert(index < length_); return buffer_[index]; }
+    char& operator [](unsigned index)
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Return const char at index.
     /// Return const char at index.
-    const char& operator [] (unsigned index) const { assert(index < length_); return buffer_[index]; }
+    const char& operator [](unsigned index) const
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Return char at index.
     /// Return char at index.
-    char& At(unsigned index) { assert(index < length_); return buffer_[index]; }
+    char& At(unsigned index)
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Return const char at index.
     /// Return const char at index.
-    const char& At(unsigned index) const { assert(index < length_); return buffer_[index]; }
-    
+    const char& At(unsigned index) const
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Replace all occurrences of a character.
     /// Replace all occurrences of a character.
     void Replace(char replaceThis, char replaceWith, bool caseSensitive = true);
     void Replace(char replaceThis, char replaceWith, bool caseSensitive = true);
     /// Replace all occurrences of a string.
     /// Replace all occurrences of a string.
@@ -330,19 +358,25 @@ public:
     void Clear();
     void Clear();
     /// Swap with another string.
     /// Swap with another string.
     void Swap(String& str);
     void Swap(String& str);
-    
+
     /// Return iterator to the beginning.
     /// Return iterator to the beginning.
     Iterator Begin() { return Iterator(buffer_); }
     Iterator Begin() { return Iterator(buffer_); }
+
     /// Return const iterator to the beginning.
     /// Return const iterator to the beginning.
     ConstIterator Begin() const { return ConstIterator(buffer_); }
     ConstIterator Begin() const { return ConstIterator(buffer_); }
+
     /// Return iterator to the end.
     /// Return iterator to the end.
     Iterator End() { return Iterator(buffer_ + length_); }
     Iterator End() { return Iterator(buffer_ + length_); }
+
     /// Return const iterator to the end.
     /// Return const iterator to the end.
     ConstIterator End() const { return ConstIterator(buffer_ + length_); }
     ConstIterator End() const { return ConstIterator(buffer_ + length_); }
+
     /// Return first char, or 0 if empty.
     /// Return first char, or 0 if empty.
     char Front() const { return buffer_[0]; }
     char Front() const { return buffer_[0]; }
+
     /// Return last char, or 0 if empty.
     /// Return last char, or 0 if empty.
     char Back() const { return length_ ? buffer_[length_ - 1] : buffer_[0]; }
     char Back() const { return length_ ? buffer_[length_ - 1] : buffer_[0]; }
+
     /// Return a substring from position to end.
     /// Return a substring from position to end.
     String Substring(unsigned pos) const;
     String Substring(unsigned pos) const;
     /// Return a substring with length from position.
     /// Return a substring with length from position.
@@ -369,20 +403,27 @@ public:
     bool StartsWith(const String& str, bool caseSensitive = true) const;
     bool StartsWith(const String& str, bool caseSensitive = true) const;
     /// Return whether ends with a string.
     /// Return whether ends with a string.
     bool EndsWith(const String& str, bool caseSensitive = true) const;
     bool EndsWith(const String& str, bool caseSensitive = true) const;
+
     /// Return the C string.
     /// Return the C string.
     const char* CString() const { return buffer_; }
     const char* CString() const { return buffer_; }
+
     /// Return length.
     /// Return length.
     unsigned Length() const { return length_; }
     unsigned Length() const { return length_; }
+
     /// Return buffer capacity.
     /// Return buffer capacity.
     unsigned Capacity() const { return capacity_; }
     unsigned Capacity() const { return capacity_; }
+
     /// Return whether the string is empty.
     /// Return whether the string is empty.
     bool Empty() const { return length_ == 0; }
     bool Empty() const { return length_ == 0; }
+
     /// Return comparison result with a string.
     /// Return comparison result with a string.
     int Compare(const String& str, bool caseSensitive = true) const;
     int Compare(const String& str, bool caseSensitive = true) const;
     /// Return comparison result with a C string.
     /// Return comparison result with a C string.
     int Compare(const char* str, bool caseSensitive = true) const;
     int Compare(const char* str, bool caseSensitive = true) const;
+
     /// Return whether contains a specific occurence of a string.
     /// Return whether contains a specific occurence of a string.
     bool Contains(const String& str, bool caseSensitive = true) const { return Find(str, 0, caseSensitive) != NPOS; }
     bool Contains(const String& str, bool caseSensitive = true) const { return Find(str, 0, caseSensitive) != NPOS; }
+
     /// Return whether contains a specific character.
     /// Return whether contains a specific character.
     bool Contains(char c, bool caseSensitive = true) const { return Find(c, 0, caseSensitive) != NPOS; }
     bool Contains(char c, bool caseSensitive = true) const { return Find(c, 0, caseSensitive) != NPOS; }
 
 
@@ -406,7 +447,7 @@ public:
     String SubstringUTF8(unsigned pos) const;
     String SubstringUTF8(unsigned pos) const;
     /// Return a UTF8 substring with length from position.
     /// Return a UTF8 substring with length from position.
     String SubstringUTF8(unsigned pos, unsigned length) const;
     String SubstringUTF8(unsigned pos, unsigned length) const;
-    
+
     /// Return hash value for HashSet & HashMap.
     /// Return hash value for HashSet & HashMap.
     unsigned ToHash() const
     unsigned ToHash() const
     {
     {
@@ -417,10 +458,10 @@ public:
             hash = *ptr + (hash << 6) + (hash << 16) - hash;
             hash = *ptr + (hash << 6) + (hash << 16) - hash;
             ++ptr;
             ++ptr;
         }
         }
-        
+
         return hash;
         return hash;
     }
     }
-    
+
     /// Return substrings split by a separator char.
     /// Return substrings split by a separator char.
     static Vector<String> Split(const char* str, char separator);
     static Vector<String> Split(const char* str, char separator);
     /// Return a string by joining substrings with a 'glue' string.
     /// Return a string by joining substrings with a 'glue' string.
@@ -429,43 +470,43 @@ public:
     static void EncodeUTF8(char*& dest, unsigned unicodeChar);
     static void EncodeUTF8(char*& dest, unsigned unicodeChar);
     /// Decode Unicode character from UTF8. Pointer will be incremented.
     /// Decode Unicode character from UTF8. Pointer will be incremented.
     static unsigned DecodeUTF8(const char*& src);
     static unsigned DecodeUTF8(const char*& src);
-    #ifdef WIN32
+#ifdef WIN32
     /// Encode Unicode character to UTF16. Pointer will be incremented.
     /// Encode Unicode character to UTF16. Pointer will be incremented.
     static void EncodeUTF16(wchar_t*& dest, unsigned unicodeChar);
     static void EncodeUTF16(wchar_t*& dest, unsigned unicodeChar);
     /// Decode Unicode character from UTF16. Pointer will be incremented.
     /// Decode Unicode character from UTF16. Pointer will be incremented.
     static unsigned DecodeUTF16(const wchar_t*& src);
     static unsigned DecodeUTF16(const wchar_t*& src);
     #endif
     #endif
-    
+
     /// Return length of a C string.
     /// Return length of a C string.
     static unsigned CStringLength(const char* str)
     static unsigned CStringLength(const char* str)
     {
     {
         if (!str)
         if (!str)
             return 0;
             return 0;
-        #ifdef _MSC_VER
+#ifdef _MSC_VER
         return (unsigned)strlen(str);
         return (unsigned)strlen(str);
-        #else
+#else
         const char* ptr = str;
         const char* ptr = str;
         while (*ptr)
         while (*ptr)
             ++ptr;
             ++ptr;
         return (unsigned)(ptr - str);
         return (unsigned)(ptr - str);
-        #endif
+#endif
     }
     }
-    
+
     /// Append to string using formatting.
     /// Append to string using formatting.
-    String& AppendWithFormat(const char* formatString, ... );
+    String& AppendWithFormat(const char* formatString, ...);
     /// Append to string using variable arguments.
     /// Append to string using variable arguments.
     String& AppendWithFormatArgs(const char* formatString, va_list args);
     String& AppendWithFormatArgs(const char* formatString, va_list args);
-    
+
     /// Compare two C strings.
     /// Compare two C strings.
     static int Compare(const char* str1, const char* str2, bool caseSensitive);
     static int Compare(const char* str1, const char* str2, bool caseSensitive);
-    
+
     /// Position for "not found."
     /// Position for "not found."
     static const unsigned NPOS = 0xffffffff;
     static const unsigned NPOS = 0xffffffff;
     /// Initial dynamic allocation size.
     /// Initial dynamic allocation size.
     static const unsigned MIN_CAPACITY = 8;
     static const unsigned MIN_CAPACITY = 8;
     /// Empty string.
     /// Empty string.
     static const String EMPTY;
     static const String EMPTY;
-    
+
 private:
 private:
     /// Move a range of characters within the string.
     /// Move a range of characters within the string.
     void MoveRange(unsigned dest, unsigned src, unsigned count)
     void MoveRange(unsigned dest, unsigned src, unsigned count)
@@ -473,14 +514,14 @@ private:
         if (count)
         if (count)
             memmove(buffer_ + dest, buffer_ + src, count);
             memmove(buffer_ + dest, buffer_ + src, count);
     }
     }
-    
+
     /// Copy chars from one buffer to another.
     /// Copy chars from one buffer to another.
     static void CopyChars(char* dest, const char* src, unsigned count)
     static void CopyChars(char* dest, const char* src, unsigned count)
     {
     {
-        #ifdef _MSC_VER
+#ifdef _MSC_VER
         if (count)
         if (count)
             memcpy(dest, src, count);
             memcpy(dest, src, count);
-        #else
+#else
         char* end = dest + count;
         char* end = dest + count;
         while (dest != end)
         while (dest != end)
         {
         {
@@ -488,25 +529,25 @@ private:
             ++dest;
             ++dest;
             ++src;
             ++src;
         }
         }
-        #endif
+#endif
     }
     }
-    
+
     /// Replace a substring with another substring.
     /// Replace a substring with another substring.
     void Replace(unsigned pos, unsigned length, const char* srcStart, unsigned srcLength);
     void Replace(unsigned pos, unsigned length, const char* srcStart, unsigned srcLength);
-    
+
     /// String length.
     /// String length.
     unsigned length_;
     unsigned length_;
     /// Capacity, zero if buffer not allocated.
     /// Capacity, zero if buffer not allocated.
     unsigned capacity_;
     unsigned capacity_;
     /// String buffer, null if not allocated.
     /// String buffer, null if not allocated.
     char* buffer_;
     char* buffer_;
-    
+
     /// End zero for empty strings.
     /// End zero for empty strings.
     static char endZero;
     static char endZero;
 };
 };
 
 
 /// Add a string to a C string.
 /// Add a string to a C string.
-inline String operator + (const char* lhs, const String& rhs)
+inline String operator +(const char* lhs, const String& rhs)
 {
 {
     String ret(lhs);
     String ret(lhs);
     ret += rhs;
     ret += rhs;
@@ -514,7 +555,7 @@ inline String operator + (const char* lhs, const String& rhs)
 }
 }
 
 
 /// Add a string to a wide char C string.
 /// Add a string to a wide char C string.
-inline String operator + (const wchar_t* lhs, const String& rhs)
+inline String operator +(const wchar_t* lhs, const String& rhs)
 {
 {
     String ret(lhs);
     String ret(lhs);
     ret += rhs;
     ret += rhs;
@@ -531,24 +572,47 @@ public:
     WString(const String& str);
     WString(const String& str);
     /// Destruct.
     /// Destruct.
     ~WString();
     ~WString();
-    
+
     /// Return char at index.
     /// Return char at index.
-    wchar_t& operator [] (unsigned index) { assert(index < length_); return buffer_[index]; }
+    wchar_t& operator [](unsigned index)
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Return const char at index.
     /// Return const char at index.
-    const wchar_t& operator [] (unsigned index) const { assert(index < length_); return buffer_[index]; }
+    const wchar_t& operator [](unsigned index) const
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Return char at index.
     /// Return char at index.
-    wchar_t& At(unsigned index) { assert(index < length_); return buffer_[index]; }
+    wchar_t& At(unsigned index)
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Return const char at index.
     /// Return const char at index.
-    const wchar_t& At(unsigned index) const { assert(index < length_); return buffer_[index]; }
+    const wchar_t& At(unsigned index) const
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Resize the string.
     /// Resize the string.
     void Resize(unsigned newLength);
     void Resize(unsigned newLength);
+
     /// Return whether the string is empty.
     /// Return whether the string is empty.
     bool Empty() const { return length_ == 0; }
     bool Empty() const { return length_ == 0; }
+
     /// Return length.
     /// Return length.
     unsigned Length() const { return length_; }
     unsigned Length() const { return length_; }
+
     /// Return character data.
     /// Return character data.
     const wchar_t* CString() const { return buffer_; }
     const wchar_t* CString() const { return buffer_; }
-    
+
 private:
 private:
     /// String length.
     /// String length.
     unsigned length_;
     unsigned length_;

+ 6 - 7
Source/Urho3D/Container/Swap.cpp

@@ -20,30 +20,29 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
-#include "../Container/HashBase.h"
+#include "../Precompiled.h"
+
 #include "../Container/ListBase.h"
 #include "../Container/ListBase.h"
-#include "../Container/Str.h"
-#include "../Container/VectorBase.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {
 
 
-template<> void Swap<String>(String& first, String& second)
+template <> void Swap<String>(String& first, String& second)
 {
 {
     first.Swap(second);
     first.Swap(second);
 }
 }
 
 
-template<> void Swap<VectorBase>(VectorBase& first, VectorBase& second)
+template <> void Swap<VectorBase>(VectorBase& first, VectorBase& second)
 {
 {
     first.Swap(second);
     first.Swap(second);
 }
 }
 
 
-template<> void Swap<ListBase>(ListBase& first, ListBase& second)
+template <> void Swap<ListBase>(ListBase& first, ListBase& second)
 {
 {
     first.Swap(second);
     first.Swap(second);
 }
 }
 
 
-template<> void Swap<HashBase>(HashBase& first, HashBase& second)
+template <> void Swap<HashBase>(HashBase& first, HashBase& second)
 {
 {
     first.Swap(second);
     first.Swap(second);
 }
 }

+ 5 - 5
Source/Urho3D/Container/Swap.h

@@ -31,16 +31,16 @@ class String;
 class VectorBase;
 class VectorBase;
 
 
 /// Swap two values.
 /// Swap two values.
-template<class T> inline void Swap(T& first, T& second)
+template <class T> inline void Swap(T& first, T& second)
 {
 {
     T temp = first;
     T temp = first;
     first = second;
     first = second;
     second = temp;
     second = temp;
 }
 }
 
 
-template<> void Swap<String>(String& first, String& second);
-template<> void Swap<VectorBase>(VectorBase& first, VectorBase& second);
-template<> void Swap<ListBase>(ListBase& first, ListBase& second);
-template<> void Swap<HashBase>(HashBase& first, HashBase& second);
+template <> void Swap<String>(String& first, String& second);
+template <> void Swap<VectorBase>(VectorBase& first, VectorBase& second);
+template <> void Swap<ListBase>(ListBase& first, ListBase& second);
+template <> void Swap<HashBase>(HashBase& first, HashBase& second);
 
 
 }
 }

+ 249 - 158
Source/Urho3D/Container/Vector.h

@@ -38,81 +38,81 @@ public:
     typedef T ValueType;
     typedef T ValueType;
     typedef RandomAccessIterator<T> Iterator;
     typedef RandomAccessIterator<T> Iterator;
     typedef RandomAccessConstIterator<T> ConstIterator;
     typedef RandomAccessConstIterator<T> ConstIterator;
-    
+
     /// Construct empty.
     /// Construct empty.
     Vector()
     Vector()
     {
     {
     }
     }
-    
+
     /// Construct with initial size.
     /// Construct with initial size.
     explicit Vector(unsigned size)
     explicit Vector(unsigned size)
     {
     {
         Resize(size, 0);
         Resize(size, 0);
     }
     }
-    
+
     /// Construct with initial data.
     /// Construct with initial data.
     Vector(const T* data, unsigned size)
     Vector(const T* data, unsigned size)
     {
     {
         Resize(size, data);
         Resize(size, data);
     }
     }
-    
+
     /// Construct from another vector.
     /// Construct from another vector.
     Vector(const Vector<T>& vector)
     Vector(const Vector<T>& vector)
     {
     {
         *this = vector;
         *this = vector;
     }
     }
-    
+
     /// Destruct.
     /// Destruct.
     ~Vector()
     ~Vector()
     {
     {
         Clear();
         Clear();
         delete[] buffer_;
         delete[] buffer_;
     }
     }
-    
+
     /// Assign from another vector.
     /// Assign from another vector.
-    Vector<T>& operator = (const Vector<T>& rhs)
+    Vector<T>& operator =(const Vector<T>& rhs)
     {
     {
         Clear();
         Clear();
         Resize(rhs.size_, rhs.Buffer());
         Resize(rhs.size_, rhs.Buffer());
         return *this;
         return *this;
     }
     }
-    
+
     /// Add-assign an element.
     /// Add-assign an element.
-    Vector<T>& operator += (const T& rhs)
+    Vector<T>& operator +=(const T& rhs)
     {
     {
         Push(rhs);
         Push(rhs);
         return *this;
         return *this;
     }
     }
-    
+
     /// Add-assign another vector.
     /// Add-assign another vector.
-    Vector<T>& operator += (const Vector<T>& rhs)
+    Vector<T>& operator +=(const Vector<T>& rhs)
     {
     {
         Push(rhs);
         Push(rhs);
         return *this;
         return *this;
     }
     }
-    
+
     /// Add an element.
     /// Add an element.
-    Vector<T> operator + (const T& rhs) const
+    Vector<T> operator +(const T& rhs) const
     {
     {
         Vector<T> ret(*this);
         Vector<T> ret(*this);
         ret.Push(rhs);
         ret.Push(rhs);
         return ret;
         return ret;
     }
     }
-    
+
     /// Add another vector.
     /// Add another vector.
-    Vector<T> operator + (const Vector<T>& rhs) const
+    Vector<T> operator +(const Vector<T>& rhs) const
     {
     {
         Vector<T> ret(*this);
         Vector<T> ret(*this);
         ret.Push(rhs);
         ret.Push(rhs);
         return ret;
         return ret;
     }
     }
-    
+
     /// Test for equality with another vector.
     /// Test for equality with another vector.
-    bool operator == (const Vector<T>& rhs) const
+    bool operator ==(const Vector<T>& rhs) const
     {
     {
         if (rhs.size_ != size_)
         if (rhs.size_ != size_)
             return false;
             return false;
-        
+
         T* buffer = Buffer();
         T* buffer = Buffer();
         T* rhsBuffer = rhs.Buffer();
         T* rhsBuffer = rhs.Buffer();
         for (unsigned i = 0; i < size_; ++i)
         for (unsigned i = 0; i < size_; ++i)
@@ -120,16 +120,16 @@ public:
             if (buffer[i] != rhsBuffer[i])
             if (buffer[i] != rhsBuffer[i])
                 return false;
                 return false;
         }
         }
-        
+
         return true;
         return true;
     }
     }
-    
+
     /// Test for inequality with another vector.
     /// Test for inequality with another vector.
-    bool operator != (const Vector<T>& rhs) const
+    bool operator !=(const Vector<T>& rhs) const
     {
     {
         if (rhs.size_ != size_)
         if (rhs.size_ != size_)
             return true;
             return true;
-        
+
         T* buffer = Buffer();
         T* buffer = Buffer();
         T* rhsBuffer = rhs.Buffer();
         T* rhsBuffer = rhs.Buffer();
         for (unsigned i = 0; i < size_; ++i)
         for (unsigned i = 0; i < size_; ++i)
@@ -137,145 +137,165 @@ public:
             if (buffer[i] != rhsBuffer[i])
             if (buffer[i] != rhsBuffer[i])
                 return true;
                 return true;
         }
         }
-        
+
         return false;
         return false;
     }
     }
-    
+
     /// Return element at index.
     /// Return element at index.
-    T& operator [] (unsigned index) { assert(index < size_); return Buffer()[index]; }
+    T& operator [](unsigned index)
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
+
     /// Return const element at index.
     /// Return const element at index.
-    const T& operator [] (unsigned index) const { assert(index < size_); return Buffer()[index]; }
+    const T& operator [](unsigned index) const
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
+
     /// Return element at index.
     /// Return element at index.
-    T& At(unsigned index) { assert(index < size_); return Buffer()[index]; }
+    T& At(unsigned index)
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
+
     /// Return const element at index.
     /// Return const element at index.
-    const T& At(unsigned index) const { assert(index < size_); return Buffer()[index]; }
+    const T& At(unsigned index) const
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
 
 
     /// Add an element at the end.
     /// Add an element at the end.
     void Push(const T& value) { Resize(size_ + 1, &value); }
     void Push(const T& value) { Resize(size_ + 1, &value); }
+
     /// Add another vector at the end.
     /// Add another vector at the end.
     void Push(const Vector<T>& vector) { Resize(size_ + vector.size_, vector.Buffer()); }
     void Push(const Vector<T>& vector) { Resize(size_ + vector.size_, vector.Buffer()); }
-    
+
     /// Remove the last element.
     /// Remove the last element.
     void Pop()
     void Pop()
     {
     {
         if (size_)
         if (size_)
             Resize(size_ - 1, 0);
             Resize(size_ - 1, 0);
     }
     }
-    
+
     /// Insert an element at position.
     /// Insert an element at position.
     void Insert(unsigned pos, const T& value)
     void Insert(unsigned pos, const T& value)
     {
     {
         if (pos > size_)
         if (pos > size_)
             pos = size_;
             pos = size_;
-        
+
         unsigned oldSize = size_;
         unsigned oldSize = size_;
         Resize(size_ + 1, 0);
         Resize(size_ + 1, 0);
         MoveRange(pos + 1, pos, oldSize - pos);
         MoveRange(pos + 1, pos, oldSize - pos);
         Buffer()[pos] = value;
         Buffer()[pos] = value;
     }
     }
-    
+
     /// Insert another vector at position.
     /// Insert another vector at position.
     void Insert(unsigned pos, const Vector<T>& vector)
     void Insert(unsigned pos, const Vector<T>& vector)
     {
     {
         if (pos > size_)
         if (pos > size_)
             pos = size_;
             pos = size_;
-        
+
         unsigned oldSize = size_;
         unsigned oldSize = size_;
         Resize(size_ + vector.size_, 0);
         Resize(size_ + vector.size_, 0);
         MoveRange(pos + vector.size_, pos, oldSize - pos);
         MoveRange(pos + vector.size_, pos, oldSize - pos);
         CopyElements(Buffer() + pos, vector.Buffer(), vector.size_);
         CopyElements(Buffer() + pos, vector.Buffer(), vector.size_);
     }
     }
-    
+
     /// Insert an element by iterator.
     /// Insert an element by iterator.
     Iterator Insert(const Iterator& dest, const T& value)
     Iterator Insert(const Iterator& dest, const T& value)
     {
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
         if (pos > size_)
             pos = size_;
             pos = size_;
         Insert(pos, value);
         Insert(pos, value);
-        
+
         return Begin() + pos;
         return Begin() + pos;
     }
     }
-    
+
     /// Insert a vector by iterator.
     /// Insert a vector by iterator.
     Iterator Insert(const Iterator& dest, const Vector<T>& vector)
     Iterator Insert(const Iterator& dest, const Vector<T>& vector)
     {
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
         if (pos > size_)
             pos = size_;
             pos = size_;
         Insert(pos, vector);
         Insert(pos, vector);
-        
+
         return Begin() + pos;
         return Begin() + pos;
     }
     }
-    
+
     /// Insert a vector partially by iterators.
     /// Insert a vector partially by iterators.
     Iterator Insert(const Iterator& dest, const ConstIterator& start, const ConstIterator& end)
     Iterator Insert(const Iterator& dest, const ConstIterator& start, const ConstIterator& end)
     {
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
         if (pos > size_)
             pos = size_;
             pos = size_;
         unsigned length = (unsigned)(end - start);
         unsigned length = (unsigned)(end - start);
         Resize(size_ + length, 0);
         Resize(size_ + length, 0);
         MoveRange(pos + length, pos, size_ - pos - length);
         MoveRange(pos + length, pos, size_ - pos - length);
-        
+
         T* destPtr = Buffer() + pos;
         T* destPtr = Buffer() + pos;
         for (ConstIterator it = start; it != end; ++it)
         for (ConstIterator it = start; it != end; ++it)
             *destPtr++ = *it;
             *destPtr++ = *it;
-        
+
         return Begin() + pos;
         return Begin() + pos;
     }
     }
-    
+
     /// Insert elements.
     /// Insert elements.
     Iterator Insert(const Iterator& dest, const T* start, const T* end)
     Iterator Insert(const Iterator& dest, const T* start, const T* end)
     {
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
         if (pos > size_)
             pos = size_;
             pos = size_;
         unsigned length = (unsigned)(end - start);
         unsigned length = (unsigned)(end - start);
         Resize(size_ + length, 0);
         Resize(size_ + length, 0);
         MoveRange(pos + length, pos, size_ - pos - length);
         MoveRange(pos + length, pos, size_ - pos - length);
-        
+
         T* destPtr = Buffer() + pos;
         T* destPtr = Buffer() + pos;
         for (const T* i = start; i != end; ++i)
         for (const T* i = start; i != end; ++i)
             *destPtr++ = *i;
             *destPtr++ = *i;
-        
+
         return Begin() + pos;
         return Begin() + pos;
     }
     }
-    
+
     /// Erase a range of elements.
     /// Erase a range of elements.
     void Erase(unsigned pos, unsigned length = 1)
     void Erase(unsigned pos, unsigned length = 1)
     {
     {
         // Return if the range is illegal
         // Return if the range is illegal
         if (pos + length > size_ || !length)
         if (pos + length > size_ || !length)
             return;
             return;
-        
+
         MoveRange(pos, pos + length, size_ - pos - length);
         MoveRange(pos, pos + length, size_ - pos - length);
         Resize(size_ - length, 0);
         Resize(size_ - length, 0);
     }
     }
-    
+
     /// Erase an element by iterator. Return iterator to the next element.
     /// Erase an element by iterator. Return iterator to the next element.
     Iterator Erase(const Iterator& it)
     Iterator Erase(const Iterator& it)
     {
     {
-        unsigned pos = it - Begin();
+        unsigned pos = (unsigned)(it - Begin());
         if (pos >= size_)
         if (pos >= size_)
             return End();
             return End();
         Erase(pos);
         Erase(pos);
-        
+
         return Begin() + pos;
         return Begin() + pos;
     }
     }
-    
+
     /// Erase a range by iterators. Return iterator to the next element.
     /// Erase a range by iterators. Return iterator to the next element.
     Iterator Erase(const Iterator& start, const Iterator& end)
     Iterator Erase(const Iterator& start, const Iterator& end)
     {
     {
-        unsigned pos = start - Begin();
+        unsigned pos = (unsigned)(start - Begin());
         if (pos >= size_)
         if (pos >= size_)
             return End();
             return End();
         unsigned length = (unsigned)(end - start);
         unsigned length = (unsigned)(end - start);
         Erase(pos, length);
         Erase(pos, length);
-        
+
         return Begin() + pos;
         return Begin() + pos;
     }
     }
-    
+
     /// Erase an element if found.
     /// Erase an element if found.
     bool Remove(const T& value)
     bool Remove(const T& value)
     {
     {
@@ -288,40 +308,41 @@ public:
         else
         else
             return false;
             return false;
     }
     }
-    
+
     /// Clear the vector.
     /// Clear the vector.
     void Clear() { Resize(0); }
     void Clear() { Resize(0); }
+
     /// Resize the vector.
     /// Resize the vector.
     void Resize(unsigned newSize) { Resize(newSize, 0); }
     void Resize(unsigned newSize) { Resize(newSize, 0); }
-    
+
     /// Set new capacity.
     /// Set new capacity.
     void Reserve(unsigned newCapacity)
     void Reserve(unsigned newCapacity)
     {
     {
         if (newCapacity < size_)
         if (newCapacity < size_)
             newCapacity = size_;
             newCapacity = size_;
-        
+
         if (newCapacity != capacity_)
         if (newCapacity != capacity_)
         {
         {
             T* newBuffer = 0;
             T* newBuffer = 0;
             capacity_ = newCapacity;
             capacity_ = newCapacity;
-            
+
             if (capacity_)
             if (capacity_)
             {
             {
-                newBuffer = reinterpret_cast<T*>(AllocateBuffer(capacity_ * sizeof(T)));
+                newBuffer = reinterpret_cast<T*>(AllocateBuffer((unsigned)(capacity_ * sizeof(T))));
                 // Move the data into the new buffer
                 // Move the data into the new buffer
                 ConstructElements(newBuffer, Buffer(), size_);
                 ConstructElements(newBuffer, Buffer(), size_);
             }
             }
-            
+
             // Delete the old buffer
             // Delete the old buffer
             DestructElements(Buffer(), size_);
             DestructElements(Buffer(), size_);
             delete[] buffer_;
             delete[] buffer_;
             buffer_ = reinterpret_cast<unsigned char*>(newBuffer);
             buffer_ = reinterpret_cast<unsigned char*>(newBuffer);
         }
         }
     }
     }
-    
+
     /// Reallocate so that no extra memory is used.
     /// Reallocate so that no extra memory is used.
     void Compact() { Reserve(size_); }
     void Compact() { Reserve(size_); }
-    
+
     /// Return iterator to value, or to the end if not found.
     /// Return iterator to value, or to the end if not found.
     Iterator Find(const T& value)
     Iterator Find(const T& value)
     {
     {
@@ -330,7 +351,7 @@ public:
             ++it;
             ++it;
         return it;
         return it;
     }
     }
-    
+
     /// Return const iterator to value, or to the end if not found.
     /// Return const iterator to value, or to the end if not found.
     ConstIterator Find(const T& value) const
     ConstIterator Find(const T& value) const
     {
     {
@@ -339,38 +360,64 @@ public:
             ++it;
             ++it;
         return it;
         return it;
     }
     }
-    
+
     /// Return whether contains a specific value.
     /// Return whether contains a specific value.
     bool Contains(const T& value) const { return Find(value) != End(); }
     bool Contains(const T& value) const { return Find(value) != End(); }
-    
+
     /// Return iterator to the beginning.
     /// Return iterator to the beginning.
     Iterator Begin() { return Iterator(Buffer()); }
     Iterator Begin() { return Iterator(Buffer()); }
+
     /// Return const iterator to the beginning.
     /// Return const iterator to the beginning.
     ConstIterator Begin() const { return ConstIterator(Buffer()); }
     ConstIterator Begin() const { return ConstIterator(Buffer()); }
+
     /// Return iterator to the end.
     /// Return iterator to the end.
     Iterator End() { return Iterator(Buffer() + size_); }
     Iterator End() { return Iterator(Buffer() + size_); }
+
     /// Return const iterator to the end.
     /// Return const iterator to the end.
     ConstIterator End() const { return ConstIterator(Buffer() + size_); }
     ConstIterator End() const { return ConstIterator(Buffer() + size_); }
+
     /// Return first element.
     /// Return first element.
-    T& Front() { assert(size_); return Buffer()[0]; }
+    T& Front()
+    {
+        assert(size_);
+        return Buffer()[0];
+    }
+
     /// Return const first element.
     /// Return const first element.
-    const T& Front() const { assert(size_); return Buffer()[0]; }
+    const T& Front() const
+    {
+        assert(size_);
+        return Buffer()[0];
+    }
+
     /// Return last element.
     /// Return last element.
-    T& Back() { assert(size_); return Buffer()[size_ - 1]; }
+    T& Back()
+    {
+        assert(size_);
+        return Buffer()[size_ - 1];
+    }
+
     /// Return const last element.
     /// Return const last element.
-    const T& Back() const { assert(size_); return Buffer()[size_ - 1]; }
+    const T& Back() const
+    {
+        assert(size_);
+        return Buffer()[size_ - 1];
+    }
+
     /// Return size of vector.
     /// Return size of vector.
     unsigned Size() const { return size_; }
     unsigned Size() const { return size_; }
+
     /// Return capacity of vector.
     /// Return capacity of vector.
     unsigned Capacity() const { return capacity_; }
     unsigned Capacity() const { return capacity_; }
+
     /// Return whether vector is empty.
     /// Return whether vector is empty.
     bool Empty() const { return size_ == 0; }
     bool Empty() const { return size_ == 0; }
-    
+
 private:
 private:
     /// Return the buffer with right type.
     /// Return the buffer with right type.
     T* Buffer() const { return reinterpret_cast<T*>(buffer_); }
     T* Buffer() const { return reinterpret_cast<T*>(buffer_); }
-    
-   /// Resize the vector and create/remove new elements as necessary.
+
+    /// Resize the vector and create/remove new elements as necessary.
     void Resize(unsigned newSize, const T* src)
     void Resize(unsigned newSize, const T* src)
     {
     {
         // If size shrinks, destruct the removed elements
         // If size shrinks, destruct the removed elements
@@ -388,8 +435,8 @@ private:
                     while (capacity_ < newSize)
                     while (capacity_ < newSize)
                         capacity_ += (capacity_ + 1) >> 1;
                         capacity_ += (capacity_ + 1) >> 1;
                 }
                 }
-                
-                unsigned char* newBuffer = AllocateBuffer(capacity_ * sizeof(T));
+
+                unsigned char* newBuffer = AllocateBuffer((unsigned)(capacity_ * sizeof(T)));
                 if (buffer_)
                 if (buffer_)
                 {
                 {
                     ConstructElements(reinterpret_cast<T*>(newBuffer), Buffer(), size_);
                     ConstructElements(reinterpret_cast<T*>(newBuffer), Buffer(), size_);
@@ -398,14 +445,14 @@ private:
                 }
                 }
                 buffer_ = newBuffer;
                 buffer_ = newBuffer;
             }
             }
-            
+
             // Initialize the new elements
             // Initialize the new elements
             ConstructElements(Buffer() + size_, src, newSize - size_);
             ConstructElements(Buffer() + size_, src, newSize - size_);
         }
         }
-        
+
         size_ = newSize;
         size_ = newSize;
     }
     }
-    
+
     /// Move a range of elements within the vector.
     /// Move a range of elements within the vector.
     void MoveRange(unsigned dest, unsigned src, unsigned count)
     void MoveRange(unsigned dest, unsigned src, unsigned count)
     {
     {
@@ -421,7 +468,7 @@ private:
                 buffer[dest + i] = buffer[src + i];
                 buffer[dest + i] = buffer[src + i];
         }
         }
     }
     }
-    
+
     /// Construct elements, optionally with source data.
     /// Construct elements, optionally with source data.
     static void ConstructElements(T* dest, const T* src, unsigned count)
     static void ConstructElements(T* dest, const T* src, unsigned count)
     {
     {
@@ -436,14 +483,14 @@ private:
                 new(dest + i) T(*(src + i));
                 new(dest + i) T(*(src + i));
         }
         }
     }
     }
-    
+
     /// Copy elements from one buffer to another.
     /// Copy elements from one buffer to another.
     static void CopyElements(T* dest, const T* src, unsigned count)
     static void CopyElements(T* dest, const T* src, unsigned count)
     {
     {
         while (count--)
         while (count--)
             *dest++ = *src++;
             *dest++ = *src++;
     }
     }
-    
+
     // Call the elements' destructors.
     // Call the elements' destructors.
     static void DestructElements(T* dest, unsigned count)
     static void DestructElements(T* dest, unsigned count)
     {
     {
@@ -462,81 +509,81 @@ public:
     typedef T ValueType;
     typedef T ValueType;
     typedef RandomAccessIterator<T> Iterator;
     typedef RandomAccessIterator<T> Iterator;
     typedef RandomAccessConstIterator<T> ConstIterator;
     typedef RandomAccessConstIterator<T> ConstIterator;
-    
+
     /// Construct empty.
     /// Construct empty.
     PODVector()
     PODVector()
     {
     {
     }
     }
-    
+
     /// Construct with initial size.
     /// Construct with initial size.
     explicit PODVector(unsigned size)
     explicit PODVector(unsigned size)
     {
     {
         Resize(size);
         Resize(size);
     }
     }
-    
+
     /// Construct with initial data.
     /// Construct with initial data.
     PODVector(const T* data, unsigned size)
     PODVector(const T* data, unsigned size)
     {
     {
         Resize(size);
         Resize(size);
         CopyElements(Buffer(), data, size);
         CopyElements(Buffer(), data, size);
     }
     }
-    
+
     /// Construct from another vector.
     /// Construct from another vector.
     PODVector(const PODVector<T>& vector)
     PODVector(const PODVector<T>& vector)
     {
     {
         *this = vector;
         *this = vector;
     }
     }
-    
+
     /// Destruct.
     /// Destruct.
     ~PODVector()
     ~PODVector()
     {
     {
         delete[] buffer_;
         delete[] buffer_;
     }
     }
-    
+
     /// Assign from another vector.
     /// Assign from another vector.
-    PODVector<T>& operator = (const PODVector<T>& rhs)
+    PODVector<T>& operator =(const PODVector<T>& rhs)
     {
     {
         Resize(rhs.size_);
         Resize(rhs.size_);
         CopyElements(Buffer(), rhs.Buffer(), rhs.size_);
         CopyElements(Buffer(), rhs.Buffer(), rhs.size_);
         return *this;
         return *this;
     }
     }
-    
+
     /// Add-assign an element.
     /// Add-assign an element.
-    PODVector<T>& operator += (const T& rhs)
+    PODVector<T>& operator +=(const T& rhs)
     {
     {
         Push(rhs);
         Push(rhs);
         return *this;
         return *this;
     }
     }
-    
+
     /// Add-assign another vector.
     /// Add-assign another vector.
-    PODVector<T>& operator += (const PODVector<T>& rhs)
+    PODVector<T>& operator +=(const PODVector<T>& rhs)
     {
     {
         Push(rhs);
         Push(rhs);
         return *this;
         return *this;
     }
     }
-    
+
     /// Add an element.
     /// Add an element.
-    PODVector<T> operator + (const T& rhs) const
+    PODVector<T> operator +(const T& rhs) const
     {
     {
         PODVector<T> ret(*this);
         PODVector<T> ret(*this);
         ret.Push(rhs);
         ret.Push(rhs);
         return ret;
         return ret;
     }
     }
-    
+
     /// Add another vector.
     /// Add another vector.
-    PODVector<T> operator + (const PODVector<T>& rhs) const
+    PODVector<T> operator +(const PODVector<T>& rhs) const
     {
     {
         PODVector<T> ret(*this);
         PODVector<T> ret(*this);
         ret.Push(rhs);
         ret.Push(rhs);
         return ret;
         return ret;
     }
     }
-    
+
     /// Test for equality with another vector.
     /// Test for equality with another vector.
-    bool operator == (const PODVector<T>& rhs) const
+    bool operator ==(const PODVector<T>& rhs) const
     {
     {
         if (rhs.size_ != size_)
         if (rhs.size_ != size_)
             return false;
             return false;
-        
+
         T* buffer = Buffer();
         T* buffer = Buffer();
         T* rhsBuffer = rhs.Buffer();
         T* rhsBuffer = rhs.Buffer();
         for (unsigned i = 0; i < size_; ++i)
         for (unsigned i = 0; i < size_; ++i)
@@ -544,16 +591,16 @@ public:
             if (buffer[i] != rhsBuffer[i])
             if (buffer[i] != rhsBuffer[i])
                 return false;
                 return false;
         }
         }
-        
+
         return true;
         return true;
     }
     }
-    
+
     /// Test for inequality with another vector.
     /// Test for inequality with another vector.
-    bool operator != (const PODVector<T>& rhs) const
+    bool operator !=(const PODVector<T>& rhs) const
     {
     {
         if (rhs.size_ != size_)
         if (rhs.size_ != size_)
             return true;
             return true;
-        
+
         T* buffer = Buffer();
         T* buffer = Buffer();
         T* rhsBuffer = rhs.Buffer();
         T* rhsBuffer = rhs.Buffer();
         for (unsigned i = 0; i < size_; ++i)
         for (unsigned i = 0; i < size_; ++i)
@@ -561,19 +608,38 @@ public:
             if (buffer[i] != rhsBuffer[i])
             if (buffer[i] != rhsBuffer[i])
                 return true;
                 return true;
         }
         }
-        
+
         return false;
         return false;
     }
     }
-    
+
     /// Return element at index.
     /// Return element at index.
-    T& operator [] (unsigned index) { assert(index < size_); return Buffer()[index]; }
+    T& operator [](unsigned index)
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
+
     /// Return const element at index.
     /// Return const element at index.
-    const T& operator [] (unsigned index) const { assert(index < size_); return Buffer()[index]; }
+    const T& operator [](unsigned index) const
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
+
     /// Return element at index.
     /// Return element at index.
-    T& At(unsigned index) { assert(index < size_); return Buffer()[index]; }
+    T& At(unsigned index)
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
+
     /// Return const element at index.
     /// Return const element at index.
-    const T& At(unsigned index) const { assert(index < size_); return Buffer()[index]; }
-    
+    const T& At(unsigned index) const
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
+
     /// Add an element at the end.
     /// Add an element at the end.
     void Push(const T& value)
     void Push(const T& value)
     {
     {
@@ -583,7 +649,7 @@ public:
             Resize(size_ + 1);
             Resize(size_ + 1);
         Back() = value;
         Back() = value;
     }
     }
-    
+
     /// Add another vector at the end.
     /// Add another vector at the end.
     void Push(const PODVector<T>& vector)
     void Push(const PODVector<T>& vector)
     {
     {
@@ -591,125 +657,125 @@ public:
         Resize(size_ + vector.size_);
         Resize(size_ + vector.size_);
         CopyElements(Buffer() + oldSize, vector.Buffer(), vector.size_);
         CopyElements(Buffer() + oldSize, vector.Buffer(), vector.size_);
     }
     }
-    
+
     /// Remove the last element.
     /// Remove the last element.
     void Pop()
     void Pop()
     {
     {
         if (size_)
         if (size_)
             Resize(size_ - 1);
             Resize(size_ - 1);
     }
     }
-    
+
     /// Insert an element at position.
     /// Insert an element at position.
     void Insert(unsigned pos, const T& value)
     void Insert(unsigned pos, const T& value)
     {
     {
         if (pos > size_)
         if (pos > size_)
             pos = size_;
             pos = size_;
-        
+
         unsigned oldSize = size_;
         unsigned oldSize = size_;
         Resize(size_ + 1);
         Resize(size_ + 1);
         MoveRange(pos + 1, pos, oldSize - pos);
         MoveRange(pos + 1, pos, oldSize - pos);
         Buffer()[pos] = value;
         Buffer()[pos] = value;
     }
     }
-    
+
     /// Insert another vector at position.
     /// Insert another vector at position.
     void Insert(unsigned pos, const PODVector<T>& vector)
     void Insert(unsigned pos, const PODVector<T>& vector)
     {
     {
         if (pos > size_)
         if (pos > size_)
             pos = size_;
             pos = size_;
-        
+
         unsigned oldSize = size_;
         unsigned oldSize = size_;
         Resize(size_ + vector.size_);
         Resize(size_ + vector.size_);
         MoveRange(pos + vector.size_, pos, oldSize - pos);
         MoveRange(pos + vector.size_, pos, oldSize - pos);
         CopyElements(Buffer() + pos, vector.Buffer(), vector.size_);
         CopyElements(Buffer() + pos, vector.Buffer(), vector.size_);
     }
     }
-    
+
     /// Insert an element by iterator.
     /// Insert an element by iterator.
     Iterator Insert(const Iterator& dest, const T& value)
     Iterator Insert(const Iterator& dest, const T& value)
     {
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
         if (pos > size_)
             pos = size_;
             pos = size_;
         Insert(pos, value);
         Insert(pos, value);
-        
+
         return Begin() + pos;
         return Begin() + pos;
     }
     }
-    
+
     /// Insert a vector by iterator.
     /// Insert a vector by iterator.
     Iterator Insert(const Iterator& dest, const PODVector<T>& vector)
     Iterator Insert(const Iterator& dest, const PODVector<T>& vector)
     {
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
         if (pos > size_)
             pos = size_;
             pos = size_;
         Insert(pos, vector);
         Insert(pos, vector);
-        
+
         return Begin() + pos;
         return Begin() + pos;
     }
     }
-    
+
     /// Insert a vector partially by iterators.
     /// Insert a vector partially by iterators.
     Iterator Insert(const Iterator& dest, const ConstIterator& start, const ConstIterator& end)
     Iterator Insert(const Iterator& dest, const ConstIterator& start, const ConstIterator& end)
     {
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
         if (pos > size_)
             pos = size_;
             pos = size_;
         unsigned length = (unsigned)(end - start);
         unsigned length = (unsigned)(end - start);
         Resize(size_ + length);
         Resize(size_ + length);
         MoveRange(pos + length, pos, size_ - pos - length);
         MoveRange(pos + length, pos, size_ - pos - length);
         CopyElements(Buffer() + pos, &(*start), length);
         CopyElements(Buffer() + pos, &(*start), length);
-        
+
         return Begin() + pos;
         return Begin() + pos;
     }
     }
-    
+
     /// Insert elements.
     /// Insert elements.
     Iterator Insert(const Iterator& dest, const T* start, const T* end)
     Iterator Insert(const Iterator& dest, const T* start, const T* end)
     {
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
         if (pos > size_)
             pos = size_;
             pos = size_;
         unsigned length = (unsigned)(end - start);
         unsigned length = (unsigned)(end - start);
         Resize(size_ + length);
         Resize(size_ + length);
         MoveRange(pos + length, pos, size_ - pos - length);
         MoveRange(pos + length, pos, size_ - pos - length);
-        
+
         T* destPtr = Buffer() + pos;
         T* destPtr = Buffer() + pos;
         for (const T* i = start; i != end; ++i)
         for (const T* i = start; i != end; ++i)
             *destPtr++ = *i;
             *destPtr++ = *i;
-        
+
         return Begin() + pos;
         return Begin() + pos;
     }
     }
-    
+
     /// Erase a range of elements.
     /// Erase a range of elements.
     void Erase(unsigned pos, unsigned length = 1)
     void Erase(unsigned pos, unsigned length = 1)
     {
     {
         // Return if the range is illegal
         // Return if the range is illegal
         if (!length || pos + length > size_)
         if (!length || pos + length > size_)
             return;
             return;
-        
+
         MoveRange(pos, pos + length, size_ - pos - length);
         MoveRange(pos, pos + length, size_ - pos - length);
         Resize(size_ - length);
         Resize(size_ - length);
     }
     }
-    
+
     /// Erase an element by iterator. Return iterator to the next element.
     /// Erase an element by iterator. Return iterator to the next element.
     Iterator Erase(const Iterator& it)
     Iterator Erase(const Iterator& it)
     {
     {
-        unsigned pos = it - Begin();
+        unsigned pos = (unsigned)(it - Begin());
         if (pos >= size_)
         if (pos >= size_)
             return End();
             return End();
         Erase(pos);
         Erase(pos);
-        
+
         return Begin() + pos;
         return Begin() + pos;
     }
     }
-    
+
     /// Erase a range by iterators. Return iterator to the next element.
     /// Erase a range by iterators. Return iterator to the next element.
     Iterator Erase(const Iterator& start, const Iterator& end)
     Iterator Erase(const Iterator& start, const Iterator& end)
     {
     {
-        unsigned pos = start - Begin();
+        unsigned pos = (unsigned)(start - Begin());
         if (pos >= size_)
         if (pos >= size_)
             return End();
             return End();
         unsigned length = (unsigned)(end - start);
         unsigned length = (unsigned)(end - start);
         Erase(pos, length);
         Erase(pos, length);
-        
+
         return Begin() + pos;
         return Begin() + pos;
     }
     }
-    
+
     /// Erase an element if found.
     /// Erase an element if found.
     bool Remove(const T& value)
     bool Remove(const T& value)
     {
     {
@@ -722,10 +788,10 @@ public:
         else
         else
             return false;
             return false;
     }
     }
-    
+
     /// Clear the vector.
     /// Clear the vector.
     void Clear() { Resize(0); }
     void Clear() { Resize(0); }
-    
+
     /// Resize the vector.
     /// Resize the vector.
     void Resize(unsigned newSize)
     void Resize(unsigned newSize)
     {
     {
@@ -738,8 +804,8 @@ public:
                 while (capacity_ < newSize)
                 while (capacity_ < newSize)
                     capacity_ += (capacity_ + 1) >> 1;
                     capacity_ += (capacity_ + 1) >> 1;
             }
             }
-            
-            unsigned char* newBuffer = AllocateBuffer(capacity_ * sizeof(T));
+
+            unsigned char* newBuffer = AllocateBuffer((unsigned)(capacity_ * sizeof(T)));
             // Move the data into the new buffer and delete the old
             // Move the data into the new buffer and delete the old
             if (buffer_)
             if (buffer_)
             {
             {
@@ -748,37 +814,37 @@ public:
             }
             }
             buffer_ = newBuffer;
             buffer_ = newBuffer;
         }
         }
-        
+
         size_ = newSize;
         size_ = newSize;
     }
     }
-    
+
     /// Set new capacity.
     /// Set new capacity.
     void Reserve(unsigned newCapacity)
     void Reserve(unsigned newCapacity)
     {
     {
         if (newCapacity < size_)
         if (newCapacity < size_)
             newCapacity = size_;
             newCapacity = size_;
-        
+
         if (newCapacity != capacity_)
         if (newCapacity != capacity_)
         {
         {
             unsigned char* newBuffer = 0;
             unsigned char* newBuffer = 0;
             capacity_ = newCapacity;
             capacity_ = newCapacity;
-            
+
             if (capacity_)
             if (capacity_)
             {
             {
-                newBuffer = AllocateBuffer(capacity_ * sizeof(T));
+                newBuffer = AllocateBuffer((unsigned)(capacity_ * sizeof(T)));
                 // Move the data into the new buffer
                 // Move the data into the new buffer
                 CopyElements(reinterpret_cast<T*>(newBuffer), Buffer(), size_);
                 CopyElements(reinterpret_cast<T*>(newBuffer), Buffer(), size_);
             }
             }
-            
+
             // Delete the old buffer
             // Delete the old buffer
             delete[] buffer_;
             delete[] buffer_;
             buffer_ = newBuffer;
             buffer_ = newBuffer;
         }
         }
     }
     }
-    
+
     /// Reallocate so that no extra memory is used.
     /// Reallocate so that no extra memory is used.
     void Compact() { Reserve(size_); }
     void Compact() { Reserve(size_); }
-    
+
     /// Return iterator to value, or to the end if not found.
     /// Return iterator to value, or to the end if not found.
     Iterator Find(const T& value)
     Iterator Find(const T& value)
     {
     {
@@ -787,7 +853,7 @@ public:
             ++it;
             ++it;
         return it;
         return it;
     }
     }
-    
+
     /// Return const iterator to value, or to the end if not found.
     /// Return const iterator to value, or to the end if not found.
     ConstIterator Find(const T& value) const
     ConstIterator Find(const T& value) const
     {
     {
@@ -796,43 +862,62 @@ public:
             ++it;
             ++it;
         return it;
         return it;
     }
     }
-    
+
     /// Return whether contains a specific value.
     /// Return whether contains a specific value.
     bool Contains(const T& value) const { return Find(value) != End(); }
     bool Contains(const T& value) const { return Find(value) != End(); }
+
     /// Return iterator to the beginning.
     /// Return iterator to the beginning.
     Iterator Begin() { return Iterator(Buffer()); }
     Iterator Begin() { return Iterator(Buffer()); }
+
     /// Return const iterator to the beginning.
     /// Return const iterator to the beginning.
     ConstIterator Begin() const { return ConstIterator(Buffer()); }
     ConstIterator Begin() const { return ConstIterator(Buffer()); }
+
     /// Return iterator to the end.
     /// Return iterator to the end.
     Iterator End() { return Iterator(Buffer() + size_); }
     Iterator End() { return Iterator(Buffer() + size_); }
+
     /// Return const iterator to the end.
     /// Return const iterator to the end.
     ConstIterator End() const { return ConstIterator(Buffer() + size_); }
     ConstIterator End() const { return ConstIterator(Buffer() + size_); }
+
     /// Return first element.
     /// Return first element.
     T& Front() { return Buffer()[0]; }
     T& Front() { return Buffer()[0]; }
+
     /// Return const first element.
     /// Return const first element.
     const T& Front() const { return Buffer()[0]; }
     const T& Front() const { return Buffer()[0]; }
+
     /// Return last element.
     /// Return last element.
-    T& Back() { assert(size_); return Buffer()[size_ - 1]; }
+    T& Back()
+    {
+        assert(size_);
+        return Buffer()[size_ - 1];
+    }
+
     /// Return const last element.
     /// Return const last element.
-    const T& Back() const { assert(size_); return Buffer()[size_ - 1]; }
+    const T& Back() const
+    {
+        assert(size_);
+        return Buffer()[size_ - 1];
+    }
+
     /// Return number of elements.
     /// Return number of elements.
     unsigned Size() const { return size_; }
     unsigned Size() const { return size_; }
+
     /// Return capacity of vector.
     /// Return capacity of vector.
     unsigned Capacity() const { return capacity_; }
     unsigned Capacity() const { return capacity_; }
+
     /// Return whether vector is empty.
     /// Return whether vector is empty.
     bool Empty() const { return size_ == 0; }
     bool Empty() const { return size_ == 0; }
-    
+
 private:
 private:
     /// Return the buffer with right type.
     /// Return the buffer with right type.
     T* Buffer() const { return reinterpret_cast<T*>(buffer_); }
     T* Buffer() const { return reinterpret_cast<T*>(buffer_); }
-    
+
     /// Move a range of elements within the vector.
     /// Move a range of elements within the vector.
     void MoveRange(unsigned dest, unsigned src, unsigned count)
     void MoveRange(unsigned dest, unsigned src, unsigned count)
     {
     {
         if (count)
         if (count)
             memmove(Buffer() + dest, Buffer() + src, count * sizeof(T));
             memmove(Buffer() + dest, Buffer() + src, count * sizeof(T));
     }
     }
-    
+
     /// Copy elements from one buffer to another.
     /// Copy elements from one buffer to another.
     static void CopyElements(T* dest, const T* src, unsigned count)
     static void CopyElements(T* dest, const T* src, unsigned count)
     {
     {
@@ -847,13 +932,19 @@ namespace std
 {
 {
 
 
 template <class T> typename Urho3D::Vector<T>::ConstIterator begin(const Urho3D::Vector<T>& v) { return v.Begin(); }
 template <class T> typename Urho3D::Vector<T>::ConstIterator begin(const Urho3D::Vector<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::Vector<T>::ConstIterator end(const Urho3D::Vector<T>& v) { return v.End(); }
 template <class T> typename Urho3D::Vector<T>::ConstIterator end(const Urho3D::Vector<T>& v) { return v.End(); }
+
 template <class T> typename Urho3D::Vector<T>::Iterator begin(Urho3D::Vector<T>& v) { return v.Begin(); }
 template <class T> typename Urho3D::Vector<T>::Iterator begin(Urho3D::Vector<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::Vector<T>::Iterator end(Urho3D::Vector<T>& v) { return v.End(); }
 template <class T> typename Urho3D::Vector<T>::Iterator end(Urho3D::Vector<T>& v) { return v.End(); }
 
 
 template <class T> typename Urho3D::PODVector<T>::ConstIterator begin(const Urho3D::PODVector<T>& v) { return v.Begin(); }
 template <class T> typename Urho3D::PODVector<T>::ConstIterator begin(const Urho3D::PODVector<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::PODVector<T>::ConstIterator end(const Urho3D::PODVector<T>& v) { return v.End(); }
 template <class T> typename Urho3D::PODVector<T>::ConstIterator end(const Urho3D::PODVector<T>& v) { return v.End(); }
+
 template <class T> typename Urho3D::PODVector<T>::Iterator begin(Urho3D::PODVector<T>& v) { return v.Begin(); }
 template <class T> typename Urho3D::PODVector<T>::Iterator begin(Urho3D::PODVector<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::PODVector<T>::Iterator end(Urho3D::PODVector<T>& v) { return v.End(); }
 template <class T> typename Urho3D::PODVector<T>::Iterator end(Urho3D::PODVector<T>& v) { return v.End(); }
 
 
 }
 }

+ 2 - 0
Source/Urho3D/Container/VectorBase.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Container/VectorBase.h"
 #include "../Container/VectorBase.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"

+ 140 - 45
Source/Urho3D/Container/VectorBase.h

@@ -22,6 +22,12 @@
 
 
 #pragma once
 #pragma once
 
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 #include "../Container/Swap.h"
 #include "../Container/Swap.h"
 
 
 namespace Urho3D
 namespace Urho3D
@@ -35,48 +41,90 @@ template <class T> struct RandomAccessIterator
         ptr_(0)
         ptr_(0)
     {
     {
     }
     }
-    
+
     /// Construct with an object pointer.
     /// Construct with an object pointer.
     explicit RandomAccessIterator(T* ptr) :
     explicit RandomAccessIterator(T* ptr) :
         ptr_(ptr)
         ptr_(ptr)
     {
     {
     }
     }
-    
+
     /// Point to the object.
     /// Point to the object.
-    T* operator -> () const { return ptr_; }
+    T* operator ->() const { return ptr_; }
+
     /// Dereference the object.
     /// Dereference the object.
-    T& operator * () const { return *ptr_; }
+    T& operator *() const { return *ptr_; }
+
     /// Preincrement the pointer.
     /// Preincrement the pointer.
-    RandomAccessIterator<T>& operator ++ () { ++ptr_; return *this; }
+    RandomAccessIterator<T>& operator ++()
+    {
+        ++ptr_;
+        return *this;
+    }
+
     /// Postincrement the pointer.
     /// Postincrement the pointer.
-    RandomAccessIterator<T> operator ++ (int) { RandomAccessIterator<T> it = *this; ++ptr_; return it; }
+    RandomAccessIterator<T> operator ++(int)
+    {
+        RandomAccessIterator<T> it = *this;
+        ++ptr_;
+        return it;
+    }
+
     /// Predecrement the pointer.
     /// Predecrement the pointer.
-    RandomAccessIterator<T>& operator -- () { --ptr_; return *this; }
+    RandomAccessIterator<T>& operator --()
+    {
+        --ptr_;
+        return *this;
+    }
+
     /// Postdecrement the pointer.
     /// Postdecrement the pointer.
-    RandomAccessIterator<T> operator -- (int) { RandomAccessIterator<T> it = *this; --ptr_; return it; }
+    RandomAccessIterator<T> operator --(int)
+    {
+        RandomAccessIterator<T> it = *this;
+        --ptr_;
+        return it;
+    }
+
     /// Add an offset to the pointer.
     /// Add an offset to the pointer.
-    RandomAccessIterator<T>& operator += (int value) { ptr_ += value; return *this; }
+    RandomAccessIterator<T>& operator +=(int value)
+    {
+        ptr_ += value;
+        return *this;
+    }
+
     /// Subtract an offset from the pointer.
     /// Subtract an offset from the pointer.
-    RandomAccessIterator<T>& operator -= (int value) { ptr_ -= value; return *this; }
+    RandomAccessIterator<T>& operator -=(int value)
+    {
+        ptr_ -= value;
+        return *this;
+    }
+
     /// Add an offset to the pointer.
     /// Add an offset to the pointer.
-    RandomAccessIterator<T> operator + (int value) const { return RandomAccessIterator<T>(ptr_ + value); }
+    RandomAccessIterator<T> operator +(int value) const { return RandomAccessIterator<T>(ptr_ + value); }
+
     /// Subtract an offset from the pointer.
     /// Subtract an offset from the pointer.
-    RandomAccessIterator<T> operator - (int value) const { return RandomAccessIterator<T>(ptr_ - value); }
+    RandomAccessIterator<T> operator -(int value) const { return RandomAccessIterator<T>(ptr_ - value); }
+
     /// Calculate offset to another iterator.
     /// Calculate offset to another iterator.
-    int operator - (const RandomAccessIterator& rhs) const { return (int)(ptr_ - rhs.ptr_); }
+    int operator -(const RandomAccessIterator& rhs) const { return (int)(ptr_ - rhs.ptr_); }
+
     /// Test for equality with another iterator.
     /// Test for equality with another iterator.
-    bool operator == (const RandomAccessIterator& rhs) const { return ptr_ == rhs.ptr_; }
+    bool operator ==(const RandomAccessIterator& rhs) const { return ptr_ == rhs.ptr_; }
+
     /// Test for inequality with another iterator.
     /// Test for inequality with another iterator.
-    bool operator != (const RandomAccessIterator& rhs) const { return ptr_ != rhs.ptr_; }
+    bool operator !=(const RandomAccessIterator& rhs) const { return ptr_ != rhs.ptr_; }
+
     /// Test for less than with another iterator.
     /// Test for less than with another iterator.
-    bool operator < (const RandomAccessIterator& rhs) const { return ptr_ < rhs.ptr_; }
+    bool operator <(const RandomAccessIterator& rhs) const { return ptr_ < rhs.ptr_; }
+
     /// Test for greater than with another iterator.
     /// Test for greater than with another iterator.
-    bool operator > (const RandomAccessIterator& rhs) const { return ptr_ > rhs.ptr_; }
+    bool operator >(const RandomAccessIterator& rhs) const { return ptr_ > rhs.ptr_; }
+
     /// Test for less than or equal with another iterator.
     /// Test for less than or equal with another iterator.
-    bool operator <= (const RandomAccessIterator& rhs) const { return ptr_ <= rhs.ptr_; }
+    bool operator <=(const RandomAccessIterator& rhs) const { return ptr_ <= rhs.ptr_; }
+
     /// Test for greater than or equal with another iterator.
     /// Test for greater than or equal with another iterator.
-    bool operator >= (const RandomAccessIterator& rhs) const { return ptr_ >= rhs.ptr_; }
-    
+    bool operator >=(const RandomAccessIterator& rhs) const { return ptr_ >= rhs.ptr_; }
+
     /// Pointer.
     /// Pointer.
     T* ptr_;
     T* ptr_;
 };
 };
@@ -89,56 +137,103 @@ template <class T> struct RandomAccessConstIterator
         ptr_(0)
         ptr_(0)
     {
     {
     }
     }
-    
+
     /// Construct with an object pointer.
     /// Construct with an object pointer.
     explicit RandomAccessConstIterator(T* ptr) :
     explicit RandomAccessConstIterator(T* ptr) :
         ptr_(ptr)
         ptr_(ptr)
     {
     {
     }
     }
-    
+
     /// Construct from a non-const iterator.
     /// Construct from a non-const iterator.
     RandomAccessConstIterator(const RandomAccessIterator<T>& rhs) :
     RandomAccessConstIterator(const RandomAccessIterator<T>& rhs) :
         ptr_(rhs.ptr_)
         ptr_(rhs.ptr_)
     {
     {
     }
     }
-    
+
     /// Assign from a non-const iterator.
     /// Assign from a non-const iterator.
-    RandomAccessConstIterator<T>& operator = (const RandomAccessIterator<T>& rhs) { ptr_ = rhs.ptr_; return *this; }
+    RandomAccessConstIterator<T>& operator =(const RandomAccessIterator<T>& rhs)
+    {
+        ptr_ = rhs.ptr_;
+        return *this;
+    }
+
     /// Point to the object.
     /// Point to the object.
-    const T* operator -> () const { return ptr_; }
+    const T* operator ->() const { return ptr_; }
+
     /// Dereference the object.
     /// Dereference the object.
-    const T& operator * () const { return *ptr_; }
+    const T& operator *() const { return *ptr_; }
+
     /// Preincrement the pointer.
     /// Preincrement the pointer.
-    RandomAccessConstIterator<T>& operator ++ () { ++ptr_; return *this; }
+    RandomAccessConstIterator<T>& operator ++()
+    {
+        ++ptr_;
+        return *this;
+    }
+
     /// Postincrement the pointer.
     /// Postincrement the pointer.
-    RandomAccessConstIterator<T> operator ++ (int) { RandomAccessConstIterator<T> it = *this; ++ptr_; return it; }
+    RandomAccessConstIterator<T> operator ++(int)
+    {
+        RandomAccessConstIterator<T> it = *this;
+        ++ptr_;
+        return it;
+    }
+
     /// Predecrement the pointer.
     /// Predecrement the pointer.
-    RandomAccessConstIterator<T>& operator -- () { --ptr_; return *this; }
+    RandomAccessConstIterator<T>& operator --()
+    {
+        --ptr_;
+        return *this;
+    }
+
     /// Postdecrement the pointer.
     /// Postdecrement the pointer.
-    RandomAccessConstIterator<T> operator -- (int) { RandomAccessConstIterator<T> it = *this; --ptr_; return it; }
+    RandomAccessConstIterator<T> operator --(int)
+    {
+        RandomAccessConstIterator<T> it = *this;
+        --ptr_;
+        return it;
+    }
+
     /// Add an offset to the pointer.
     /// Add an offset to the pointer.
-    RandomAccessConstIterator<T>& operator += (int value) { ptr_ += value; return *this; }
+    RandomAccessConstIterator<T>& operator +=(int value)
+    {
+        ptr_ += value;
+        return *this;
+    }
+
     /// Subtract an offset from the pointer.
     /// Subtract an offset from the pointer.
-    RandomAccessConstIterator<T>& operator -= (int value) { ptr_ -= value; return *this; }
+    RandomAccessConstIterator<T>& operator -=(int value)
+    {
+        ptr_ -= value;
+        return *this;
+    }
+
     /// Add an offset to the pointer.
     /// Add an offset to the pointer.
-    RandomAccessConstIterator<T> operator + (int value) const { return RandomAccessConstIterator<T>(ptr_ + value); }
+    RandomAccessConstIterator<T> operator +(int value) const { return RandomAccessConstIterator<T>(ptr_ + value); }
+
     /// Subtract an offset from the pointer.
     /// Subtract an offset from the pointer.
-    RandomAccessConstIterator<T> operator - (int value) const { return RandomAccessConstIterator<T>(ptr_ - value); }
+    RandomAccessConstIterator<T> operator -(int value) const { return RandomAccessConstIterator<T>(ptr_ - value); }
+
     /// Calculate offset to another iterator.
     /// Calculate offset to another iterator.
-    int operator - (const RandomAccessConstIterator& rhs) const { return (int)(ptr_ - rhs.ptr_); }
+    int operator -(const RandomAccessConstIterator& rhs) const { return (int)(ptr_ - rhs.ptr_); }
+
     /// Test for equality with another iterator.
     /// Test for equality with another iterator.
-    bool operator == (const RandomAccessConstIterator& rhs) const { return ptr_ == rhs.ptr_; }
+    bool operator ==(const RandomAccessConstIterator& rhs) const { return ptr_ == rhs.ptr_; }
+
     /// Test for inequality with another iterator.
     /// Test for inequality with another iterator.
-    bool operator != (const RandomAccessConstIterator& rhs) const { return ptr_ != rhs.ptr_; }
+    bool operator !=(const RandomAccessConstIterator& rhs) const { return ptr_ != rhs.ptr_; }
+
     /// Test for less than with another iterator.
     /// Test for less than with another iterator.
-    bool operator < (const RandomAccessConstIterator& rhs) const { return ptr_ < rhs.ptr_; }
+    bool operator <(const RandomAccessConstIterator& rhs) const { return ptr_ < rhs.ptr_; }
+
     /// Test for greater than with another iterator.
     /// Test for greater than with another iterator.
-    bool operator > (const RandomAccessConstIterator& rhs) const { return ptr_ > rhs.ptr_; }
+    bool operator >(const RandomAccessConstIterator& rhs) const { return ptr_ > rhs.ptr_; }
+
     /// Test for less than or equal with another iterator.
     /// Test for less than or equal with another iterator.
-    bool operator <= (const RandomAccessConstIterator& rhs) const { return ptr_ <= rhs.ptr_; }
+    bool operator <=(const RandomAccessConstIterator& rhs) const { return ptr_ <= rhs.ptr_; }
+
     /// Test for greater than or equal with another iterator.
     /// Test for greater than or equal with another iterator.
-    bool operator >= (const RandomAccessConstIterator& rhs) const { return ptr_ >= rhs.ptr_; }
-    
+    bool operator >=(const RandomAccessConstIterator& rhs) const { return ptr_ >= rhs.ptr_; }
+
     /// Pointer.
     /// Pointer.
     T* ptr_;
     T* ptr_;
 };
 };
@@ -157,7 +252,7 @@ public:
         buffer_(0)
         buffer_(0)
     {
     {
     }
     }
-    
+
     /// Swap with another vector.
     /// Swap with another vector.
     void Swap(VectorBase& rhs)
     void Swap(VectorBase& rhs)
     {
     {
@@ -165,10 +260,10 @@ public:
         Urho3D::Swap(capacity_, rhs.capacity_);
         Urho3D::Swap(capacity_, rhs.capacity_);
         Urho3D::Swap(buffer_, rhs.buffer_);
         Urho3D::Swap(buffer_, rhs.buffer_);
     }
     }
-    
+
 protected:
 protected:
     static unsigned char* AllocateBuffer(unsigned size);
     static unsigned char* AllocateBuffer(unsigned size);
-    
+
     /// Size of vector.
     /// Size of vector.
     unsigned size_;
     unsigned size_;
     /// Buffer capacity.
     /// Buffer capacity.

+ 7 - 6
Source/Urho3D/Core/Attribute.h

@@ -71,7 +71,7 @@ struct AttributeInfo
         ptr_(0)
         ptr_(0)
     {
     {
     }
     }
-    
+
     /// Construct offset attribute.
     /// Construct offset attribute.
     AttributeInfo(VariantType type, const char* name, size_t offset, const Variant& defaultValue, unsigned mode) :
     AttributeInfo(VariantType type, const char* name, size_t offset, const Variant& defaultValue, unsigned mode) :
         type_(type),
         type_(type),
@@ -83,7 +83,7 @@ struct AttributeInfo
         ptr_(0)
         ptr_(0)
     {
     {
     }
     }
-    
+
     /// Construct offset enum attribute.
     /// Construct offset enum attribute.
     AttributeInfo(const char* name, size_t offset, const char** enumNames, const Variant& defaultValue, unsigned mode) :
     AttributeInfo(const char* name, size_t offset, const char** enumNames, const Variant& defaultValue, unsigned mode) :
         type_(VAR_INT),
         type_(VAR_INT),
@@ -95,7 +95,7 @@ struct AttributeInfo
         ptr_(0)
         ptr_(0)
     {
     {
     }
     }
-    
+
     /// Construct accessor attribute.
     /// Construct accessor attribute.
     AttributeInfo(VariantType type, const char* name, AttributeAccessor* accessor, const Variant& defaultValue, unsigned mode) :
     AttributeInfo(VariantType type, const char* name, AttributeAccessor* accessor, const Variant& defaultValue, unsigned mode) :
         type_(type),
         type_(type),
@@ -108,9 +108,10 @@ struct AttributeInfo
         ptr_(0)
         ptr_(0)
     {
     {
     }
     }
-    
+
     /// Construct accessor enum attribute.
     /// Construct accessor enum attribute.
-    AttributeInfo(const char* name, AttributeAccessor* accessor, const char** enumNames, const Variant& defaultValue, unsigned mode) :
+    AttributeInfo(const char* name, AttributeAccessor* accessor, const char** enumNames, const Variant& defaultValue,
+        unsigned mode) :
         type_(VAR_INT),
         type_(VAR_INT),
         name_(name),
         name_(name),
         offset_(0),
         offset_(0),
@@ -121,7 +122,7 @@ struct AttributeInfo
         ptr_(0)
         ptr_(0)
     {
     {
     }
     }
-    
+
     /// Attribute type.
     /// Attribute type.
     VariantType type_;
     VariantType type_;
     /// Name.
     /// Name.

+ 8 - 2
Source/Urho3D/Core/Condition.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Core/Condition.h"
 #include "../Core/Condition.h"
 
 
 #ifdef WIN32
 #ifdef WIN32
@@ -32,6 +34,7 @@ namespace Urho3D
 {
 {
 
 
 #ifdef WIN32
 #ifdef WIN32
+
 Condition::Condition() :
 Condition::Condition() :
     event_(0)
     event_(0)
 {
 {
@@ -53,7 +56,9 @@ void Condition::Wait()
 {
 {
     WaitForSingleObject((HANDLE)event_, INFINITE);
     WaitForSingleObject((HANDLE)event_, INFINITE);
 }
 }
+
 #else
 #else
+
 Condition::Condition() :
 Condition::Condition() :
     mutex_(new pthread_mutex_t),
     mutex_(new pthread_mutex_t),
     event_(new pthread_cond_t)
     event_(new pthread_cond_t)
@@ -66,7 +71,7 @@ Condition::~Condition()
 {
 {
     pthread_cond_t* cond = (pthread_cond_t*)event_;
     pthread_cond_t* cond = (pthread_cond_t*)event_;
     pthread_mutex_t* mutex = (pthread_mutex_t*)mutex_;
     pthread_mutex_t* mutex = (pthread_mutex_t*)mutex_;
-    
+
     pthread_cond_destroy(cond);
     pthread_cond_destroy(cond);
     pthread_mutex_destroy(mutex);
     pthread_mutex_destroy(mutex);
     delete cond;
     delete cond;
@@ -84,11 +89,12 @@ void Condition::Wait()
 {
 {
     pthread_cond_t* cond = (pthread_cond_t*)event_;
     pthread_cond_t* cond = (pthread_cond_t*)event_;
     pthread_mutex_t* mutex = (pthread_mutex_t*)mutex_;
     pthread_mutex_t* mutex = (pthread_mutex_t*)mutex_;
-    
+
     pthread_mutex_lock(mutex);
     pthread_mutex_lock(mutex);
     pthread_cond_wait(cond, mutex);
     pthread_cond_wait(cond, mutex);
     pthread_mutex_unlock(mutex);
     pthread_mutex_unlock(mutex);
 }
 }
+
 #endif
 #endif
 
 
 }
 }

+ 12 - 6
Source/Urho3D/Core/Condition.h

@@ -22,6 +22,12 @@
 
 
 #pragma once
 #pragma once
 
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 namespace Urho3D
 namespace Urho3D
 {
 {
 
 
@@ -31,21 +37,21 @@ class URHO3D_API Condition
 public:
 public:
     /// Construct.
     /// Construct.
     Condition();
     Condition();
-    
+
     /// Destruct.
     /// Destruct.
     ~Condition();
     ~Condition();
-    
+
     /// Set the condition. Will be automatically reset once a waiting thread wakes up.
     /// Set the condition. Will be automatically reset once a waiting thread wakes up.
     void Set();
     void Set();
-    
+
     /// Wait on the condition.
     /// Wait on the condition.
     void Wait();
     void Wait();
-    
+
 private:
 private:
-    #ifndef WIN32
+#ifndef WIN32
     /// Mutex for the event, necessary for pthreads-based implementation.
     /// Mutex for the event, necessary for pthreads-based implementation.
     void* mutex_;
     void* mutex_;
-    #endif
+#endif
     /// Operating system specific event.
     /// Operating system specific event.
     void* event_;
     void* event_;
 };
 };

+ 8 - 6
Source/Urho3D/Core/Context.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Core/Context.h"
 #include "../Core/Context.h"
 #include "../Core/Thread.h"
 #include "../Core/Thread.h"
 
 
@@ -53,11 +55,11 @@ void RemoveNamedAttribute(HashMap<StringHash, Vector<AttributeInfo> >& attribute
 Context::Context() :
 Context::Context() :
     eventHandler_(0)
     eventHandler_(0)
 {
 {
-    #ifdef ANDROID
+#ifdef ANDROID
     // Always reset the random seed on Android, as the Urho3D library might not be unloaded between runs
     // Always reset the random seed on Android, as the Urho3D library might not be unloaded between runs
     SetRandomSeed(1);
     SetRandomSeed(1);
-    #endif
-    
+#endif
+
     // Set the main thread ID (assuming the Context is created in it)
     // Set the main thread ID (assuming the Context is created in it)
     Thread::SetMainThread();
     Thread::SetMainThread();
 }
 }
@@ -71,10 +73,10 @@ Context::~Context()
     RemoveSubsystem("Input");
     RemoveSubsystem("Input");
     RemoveSubsystem("Renderer");
     RemoveSubsystem("Renderer");
     RemoveSubsystem("Graphics");
     RemoveSubsystem("Graphics");
-    
+
     subsystems_.Clear();
     subsystems_.Clear();
     factories_.Clear();
     factories_.Clear();
-    
+
     // Delete allocated event data maps
     // Delete allocated event data maps
     for (PODVector<VariantMap*>::Iterator i = eventDataMaps_.Begin(); i != eventDataMaps_.End(); ++i)
     for (PODVector<VariantMap*>::Iterator i = eventDataMaps_.Begin(); i != eventDataMaps_.End(); ++i)
         delete *i;
         delete *i;
@@ -153,7 +155,7 @@ VariantMap& Context::GetEventDataMap()
     unsigned nestingLevel = eventSenders_.Size();
     unsigned nestingLevel = eventSenders_.Size();
     while (eventDataMaps_.Size() < nestingLevel + 1)
     while (eventDataMaps_.Size() < nestingLevel + 1)
         eventDataMaps_.Push(new VariantMap());
         eventDataMaps_.Push(new VariantMap());
-    
+
     VariantMap& ret = *eventDataMaps_[nestingLevel];
     VariantMap& ret = *eventDataMaps_[nestingLevel];
     ret.Clear();
     ret.Clear();
     return ret;
     return ret;

+ 25 - 2
Source/Urho3D/Core/Context.h

@@ -78,16 +78,22 @@ public:
 
 
     /// Return subsystem by type.
     /// Return subsystem by type.
     Object* GetSubsystem(StringHash type) const;
     Object* GetSubsystem(StringHash type) const;
+
     /// Return all subsystems.
     /// Return all subsystems.
     const HashMap<StringHash, SharedPtr<Object> >& GetSubsystems() const { return subsystems_; }
     const HashMap<StringHash, SharedPtr<Object> >& GetSubsystems() const { return subsystems_; }
+
     /// Return all object factories.
     /// Return all object factories.
     const HashMap<StringHash, SharedPtr<ObjectFactory> >& GetObjectFactories() const { return factories_; }
     const HashMap<StringHash, SharedPtr<ObjectFactory> >& GetObjectFactories() const { return factories_; }
+
     /// Return all object categories.
     /// Return all object categories.
     const HashMap<String, Vector<StringHash> >& GetObjectCategories() const { return objectCategories_; }
     const HashMap<String, Vector<StringHash> >& GetObjectCategories() const { return objectCategories_; }
+
     /// Return active event sender. Null outside event handling.
     /// Return active event sender. Null outside event handling.
     Object* GetEventSender() const;
     Object* GetEventSender() const;
+
     /// Return active event handler. Set by Object. Null outside event handling.
     /// Return active event handler. Set by Object. Null outside event handling.
     EventHandler* GetEventHandler() const { return eventHandler_; }
     EventHandler* GetEventHandler() const { return eventHandler_; }
+
     /// Return object type name from hash, or empty if unknown.
     /// Return object type name from hash, or empty if unknown.
     const String& GetTypeName(StringHash objectType) const;
     const String& GetTypeName(StringHash objectType) const;
     /// Return a specific attribute description for an object, or null if not found.
     /// Return a specific attribute description for an object, or null if not found.
@@ -145,10 +151,13 @@ private:
     void RemoveEventReceiver(Object* receiver, Object* sender, StringHash eventType);
     void RemoveEventReceiver(Object* receiver, Object* sender, StringHash eventType);
     /// Remove event receiver from non-specific events.
     /// Remove event receiver from non-specific events.
     void RemoveEventReceiver(Object* receiver, StringHash eventType);
     void RemoveEventReceiver(Object* receiver, StringHash eventType);
+
     /// Set current event handler. Called by Object.
     /// Set current event handler. Called by Object.
     void SetEventHandler(EventHandler* handler) { eventHandler_ = handler; }
     void SetEventHandler(EventHandler* handler) { eventHandler_ = handler; }
+
     /// Begin event send.
     /// Begin event send.
     void BeginSendEvent(Object* sender) { eventSenders_.Push(sender); }
     void BeginSendEvent(Object* sender) { eventSenders_.Push(sender); }
+
     /// End event send. Clean up event receivers removed in the meanwhile.
     /// End event send. Clean up event receivers removed in the meanwhile.
     void EndSendEvent() { eventSenders_.Pop(); }
     void EndSendEvent() { eventSenders_.Pop(); }
 
 
@@ -175,13 +184,27 @@ private:
 };
 };
 
 
 template <class T> void Context::RegisterFactory() { RegisterFactory(new ObjectFactoryImpl<T>(this)); }
 template <class T> void Context::RegisterFactory() { RegisterFactory(new ObjectFactoryImpl<T>(this)); }
-template <class T> void Context::RegisterFactory(const char* category) { RegisterFactory(new ObjectFactoryImpl<T>(this), category); }
+
+template <class T> void Context::RegisterFactory(const char* category)
+{
+    RegisterFactory(new ObjectFactoryImpl<T>(this), category);
+}
+
 template <class T> void Context::RemoveSubsystem() { RemoveSubsystem(T::GetTypeStatic()); }
 template <class T> void Context::RemoveSubsystem() { RemoveSubsystem(T::GetTypeStatic()); }
+
 template <class T> void Context::RegisterAttribute(const AttributeInfo& attr) { RegisterAttribute(T::GetTypeStatic(), attr); }
 template <class T> void Context::RegisterAttribute(const AttributeInfo& attr) { RegisterAttribute(T::GetTypeStatic(), attr); }
+
 template <class T> void Context::RemoveAttribute(const char* name) { RemoveAttribute(T::GetTypeStatic(), name); }
 template <class T> void Context::RemoveAttribute(const char* name) { RemoveAttribute(T::GetTypeStatic(), name); }
+
 template <class T, class U> void Context::CopyBaseAttributes() { CopyBaseAttributes(T::GetTypeStatic(), U::GetTypeStatic()); }
 template <class T, class U> void Context::CopyBaseAttributes() { CopyBaseAttributes(T::GetTypeStatic(), U::GetTypeStatic()); }
+
 template <class T> T* Context::GetSubsystem() const { return static_cast<T*>(GetSubsystem(T::GetTypeStatic())); }
 template <class T> T* Context::GetSubsystem() const { return static_cast<T*>(GetSubsystem(T::GetTypeStatic())); }
+
 template <class T> AttributeInfo* Context::GetAttribute(const char* name) { return GetAttribute(T::GetTypeStatic(), name); }
 template <class T> AttributeInfo* Context::GetAttribute(const char* name) { return GetAttribute(T::GetTypeStatic(), name); }
-template <class T> void Context::UpdateAttributeDefaultValue(const char* name, const Variant& defaultValue) { UpdateAttributeDefaultValue(T::GetTypeStatic(), name, defaultValue); }
+
+template <class T> void Context::UpdateAttributeDefaultValue(const char* name, const Variant& defaultValue)
+{
+    UpdateAttributeDefaultValue(T::GetTypeStatic(), name, defaultValue);
+}
 
 
 }
 }

+ 3 - 1
Source/Urho3D/Core/MiniDump.cpp

@@ -20,9 +20,10 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
-
 #if defined(_MSC_VER) && defined(URHO3D_MINIDUMPS)
 #if defined(_MSC_VER) && defined(URHO3D_MINIDUMPS)
 
 
+#include "../Precompiled.h"
+
 #include "../Core/ProcessUtils.h"
 #include "../Core/ProcessUtils.h"
 
 
 #include <cstdio>
 #include <cstdio>
@@ -83,4 +84,5 @@ URHO3D_API int WriteMiniDump(const char* applicationName, void* exceptionPointer
 }
 }
 
 
 }
 }
+
 #endif
 #endif

+ 6 - 0
Source/Urho3D/Core/Mutex.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Core/Mutex.h"
 #include "../Core/Mutex.h"
 
 
 #ifdef WIN32
 #ifdef WIN32
@@ -34,6 +36,7 @@ namespace Urho3D
 {
 {
 
 
 #ifdef WIN32
 #ifdef WIN32
+
 Mutex::Mutex() :
 Mutex::Mutex() :
     handle_(new CRITICAL_SECTION)
     handle_(new CRITICAL_SECTION)
 {
 {
@@ -57,7 +60,9 @@ void Mutex::Release()
 {
 {
     LeaveCriticalSection((CRITICAL_SECTION*)handle_);
     LeaveCriticalSection((CRITICAL_SECTION*)handle_);
 }
 }
+
 #else
 #else
+
 Mutex::Mutex() :
 Mutex::Mutex() :
     handle_(new pthread_mutex_t)
     handle_(new pthread_mutex_t)
 {
 {
@@ -85,6 +90,7 @@ void Mutex::Release()
 {
 {
     pthread_mutex_unlock((pthread_mutex_t*)handle_);
     pthread_mutex_unlock((pthread_mutex_t*)handle_);
 }
 }
+
 #endif
 #endif
 
 
 MutexLock::MutexLock(Mutex& mutex) :
 MutexLock::MutexLock(Mutex& mutex) :

+ 11 - 5
Source/Urho3D/Core/Mutex.h

@@ -22,6 +22,12 @@
 
 
 #pragma once
 #pragma once
 
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 namespace Urho3D
 namespace Urho3D
 {
 {
 
 
@@ -33,12 +39,12 @@ public:
     Mutex();
     Mutex();
     /// Destruct.
     /// Destruct.
     ~Mutex();
     ~Mutex();
-    
+
     /// Acquire the mutex. Block if already acquired.
     /// Acquire the mutex. Block if already acquired.
     void Acquire();
     void Acquire();
     /// Release the mutex.
     /// Release the mutex.
     void Release();
     void Release();
-    
+
 private:
 private:
     /// Mutex handle.
     /// Mutex handle.
     void* handle_;
     void* handle_;
@@ -52,13 +58,13 @@ public:
     MutexLock(Mutex& mutex);
     MutexLock(Mutex& mutex);
     /// Destruct. Release the mutex.
     /// Destruct. Release the mutex.
     ~MutexLock();
     ~MutexLock();
-    
+
 private:
 private:
     /// Prevent copy construction.
     /// Prevent copy construction.
     MutexLock(const MutexLock& rhs);
     MutexLock(const MutexLock& rhs);
     /// Prevent assignment.
     /// Prevent assignment.
-    MutexLock& operator = (const MutexLock& rhs);
-    
+    MutexLock& operator =(const MutexLock& rhs);
+
     /// Mutex reference.
     /// Mutex reference.
     Mutex& mutex_;
     Mutex& mutex_;
 };
 };

+ 40 - 38
Source/Urho3D/Core/Object.cpp

@@ -20,9 +20,11 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Core/Context.h"
 #include "../Core/Context.h"
-#include "../IO/Log.h"
 #include "../Core/Thread.h"
 #include "../Core/Thread.h"
+#include "../IO/Log.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -47,7 +49,7 @@ void Object::OnEvent(Object* sender, StringHash eventType, VariantMap& eventData
     Context* context = context_;
     Context* context = context_;
     EventHandler* specific = 0;
     EventHandler* specific = 0;
     EventHandler* nonSpecific = 0;
     EventHandler* nonSpecific = 0;
-    
+
     EventHandler* handler = eventHandlers_.First();
     EventHandler* handler = eventHandlers_.First();
     while (handler)
     while (handler)
     {
     {
@@ -63,7 +65,7 @@ void Object::OnEvent(Object* sender, StringHash eventType, VariantMap& eventData
         }
         }
         handler = eventHandlers_.Next(handler);
         handler = eventHandlers_.Next(handler);
     }
     }
-    
+
     // Specific event handlers have priority, so if found, invoke first
     // Specific event handlers have priority, so if found, invoke first
     if (specific)
     if (specific)
     {
     {
@@ -72,7 +74,7 @@ void Object::OnEvent(Object* sender, StringHash eventType, VariantMap& eventData
         context->SetEventHandler(0);
         context->SetEventHandler(0);
         return;
         return;
     }
     }
-    
+
     if (nonSpecific)
     if (nonSpecific)
     {
     {
         context->SetEventHandler(nonSpecific);
         context->SetEventHandler(nonSpecific);
@@ -85,16 +87,16 @@ void Object::SubscribeToEvent(StringHash eventType, EventHandler* handler)
 {
 {
     if (!handler)
     if (!handler)
         return;
         return;
-    
+
     handler->SetSenderAndEventType(0, eventType);
     handler->SetSenderAndEventType(0, eventType);
     // Remove old event handler first
     // Remove old event handler first
     EventHandler* previous;
     EventHandler* previous;
     EventHandler* oldHandler = FindSpecificEventHandler(0, eventType, &previous);
     EventHandler* oldHandler = FindSpecificEventHandler(0, eventType, &previous);
     if (oldHandler)
     if (oldHandler)
         eventHandlers_.Erase(oldHandler, previous);
         eventHandlers_.Erase(oldHandler, previous);
-    
+
     eventHandlers_.InsertFront(handler);
     eventHandlers_.InsertFront(handler);
-    
+
     context_->AddEventReceiver(this, eventType);
     context_->AddEventReceiver(this, eventType);
 }
 }
 
 
@@ -106,16 +108,16 @@ void Object::SubscribeToEvent(Object* sender, StringHash eventType, EventHandler
         delete handler;
         delete handler;
         return;
         return;
     }
     }
-    
+
     handler->SetSenderAndEventType(sender, eventType);
     handler->SetSenderAndEventType(sender, eventType);
     // Remove old event handler first
     // Remove old event handler first
     EventHandler* previous;
     EventHandler* previous;
     EventHandler* oldHandler = FindSpecificEventHandler(sender, eventType, &previous);
     EventHandler* oldHandler = FindSpecificEventHandler(sender, eventType, &previous);
     if (oldHandler)
     if (oldHandler)
         eventHandlers_.Erase(oldHandler, previous);
         eventHandlers_.Erase(oldHandler, previous);
-    
+
     eventHandlers_.InsertFront(handler);
     eventHandlers_.InsertFront(handler);
-    
+
     context_->AddEventReceiver(this, sender, eventType);
     context_->AddEventReceiver(this, sender, eventType);
 }
 }
 
 
@@ -142,7 +144,7 @@ void Object::UnsubscribeFromEvent(Object* sender, StringHash eventType)
 {
 {
     if (!sender)
     if (!sender)
         return;
         return;
-    
+
     EventHandler* previous;
     EventHandler* previous;
     EventHandler* handler = FindSpecificEventHandler(sender, eventType, &previous);
     EventHandler* handler = FindSpecificEventHandler(sender, eventType, &previous);
     if (handler)
     if (handler)
@@ -156,7 +158,7 @@ void Object::UnsubscribeFromEvents(Object* sender)
 {
 {
     if (!sender)
     if (!sender)
         return;
         return;
-    
+
     for (;;)
     for (;;)
     {
     {
         EventHandler* previous;
         EventHandler* previous;
@@ -193,18 +195,18 @@ void Object::UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& excepti
 {
 {
     EventHandler* handler = eventHandlers_.First();
     EventHandler* handler = eventHandlers_.First();
     EventHandler* previous = 0;
     EventHandler* previous = 0;
-    
+
     while (handler)
     while (handler)
     {
     {
         EventHandler* next = eventHandlers_.Next(handler);
         EventHandler* next = eventHandlers_.Next(handler);
-        
+
         if ((!onlyUserData || handler->GetUserData()) && !exceptions.Contains(handler->GetEventType()))
         if ((!onlyUserData || handler->GetUserData()) && !exceptions.Contains(handler->GetEventType()))
         {
         {
             if (handler->GetSender())
             if (handler->GetSender())
                 context_->RemoveEventReceiver(this, handler->GetSender(), handler->GetEventType());
                 context_->RemoveEventReceiver(this, handler->GetSender(), handler->GetEventType());
             else
             else
                 context_->RemoveEventReceiver(this, handler->GetEventType());
                 context_->RemoveEventReceiver(this, handler->GetEventType());
-            
+
             eventHandlers_.Erase(handler, previous);
             eventHandlers_.Erase(handler, previous);
         }
         }
         else
         else
@@ -217,7 +219,7 @@ void Object::UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& excepti
 void Object::SendEvent(StringHash eventType)
 void Object::SendEvent(StringHash eventType)
 {
 {
     VariantMap noEventData;
     VariantMap noEventData;
-    
+
     SendEvent(eventType, noEventData);
     SendEvent(eventType, noEventData);
 }
 }
 
 
@@ -228,14 +230,14 @@ void Object::SendEvent(StringHash eventType, VariantMap& eventData)
         LOGERROR("Sending events is only supported from the main thread");
         LOGERROR("Sending events is only supported from the main thread");
         return;
         return;
     }
     }
-    
+
     // Make a weak pointer to self to check for destruction during event handling
     // Make a weak pointer to self to check for destruction during event handling
     WeakPtr<Object> self(this);
     WeakPtr<Object> self(this);
     Context* context = context_;
     Context* context = context_;
     HashSet<Object*> processed;
     HashSet<Object*> processed;
-    
+
     context->BeginSendEvent(this);
     context->BeginSendEvent(this);
-    
+
     // Check first the specific event receivers
     // Check first the specific event receivers
     const HashSet<Object*>* group = context->GetEventReceivers(this, eventType);
     const HashSet<Object*>* group = context->GetEventReceivers(this, eventType);
     if (group)
     if (group)
@@ -247,26 +249,26 @@ void Object::SendEvent(StringHash eventType, VariantMap& eventData)
             Object* next = 0;
             Object* next = 0;
             if (i != group->End())
             if (i != group->End())
                 next = *i;
                 next = *i;
-            
+
             unsigned oldSize = group->Size();
             unsigned oldSize = group->Size();
             receiver->OnEvent(this, eventType, eventData);
             receiver->OnEvent(this, eventType, eventData);
-            
+
             // If self has been destroyed as a result of event handling, exit
             // If self has been destroyed as a result of event handling, exit
             if (self.Expired())
             if (self.Expired())
             {
             {
                 context->EndSendEvent();
                 context->EndSendEvent();
                 return;
                 return;
             }
             }
-            
+
             // If group has changed size during iteration (removed/added subscribers) try to recover
             // If group has changed size during iteration (removed/added subscribers) try to recover
             /// \todo This is not entirely foolproof, as a subscriber could have been added to make up for the removed one
             /// \todo This is not entirely foolproof, as a subscriber could have been added to make up for the removed one
             if (group->Size() != oldSize)
             if (group->Size() != oldSize)
                 i = group->Find(next);
                 i = group->Find(next);
-            
+
             processed.Insert(receiver);
             processed.Insert(receiver);
         }
         }
     }
     }
-    
+
     // Then the non-specific receivers
     // Then the non-specific receivers
     group = context->GetEventReceivers(eventType);
     group = context->GetEventReceivers(eventType);
     if (group)
     if (group)
@@ -280,16 +282,16 @@ void Object::SendEvent(StringHash eventType, VariantMap& eventData)
                 Object* next = 0;
                 Object* next = 0;
                 if (i != group->End())
                 if (i != group->End())
                     next = *i;
                     next = *i;
-                
+
                 unsigned oldSize = group->Size();
                 unsigned oldSize = group->Size();
                 receiver->OnEvent(this, eventType, eventData);
                 receiver->OnEvent(this, eventType, eventData);
-                
+
                 if (self.Expired())
                 if (self.Expired())
                 {
                 {
                     context->EndSendEvent();
                     context->EndSendEvent();
                     return;
                     return;
                 }
                 }
-                
+
                 if (group->Size() != oldSize)
                 if (group->Size() != oldSize)
                     i = group->Find(next);
                     i = group->Find(next);
             }
             }
@@ -304,25 +306,25 @@ void Object::SendEvent(StringHash eventType, VariantMap& eventData)
                 Object* next = 0;
                 Object* next = 0;
                 if (i != group->End())
                 if (i != group->End())
                     next = *i;
                     next = *i;
-                
+
                 if (!processed.Contains(receiver))
                 if (!processed.Contains(receiver))
                 {
                 {
                     unsigned oldSize = group->Size();
                     unsigned oldSize = group->Size();
                     receiver->OnEvent(this, eventType, eventData);
                     receiver->OnEvent(this, eventType, eventData);
-                    
+
                     if (self.Expired())
                     if (self.Expired())
                     {
                     {
                         context->EndSendEvent();
                         context->EndSendEvent();
                         return;
                         return;
                     }
                     }
-                    
+
                     if (group->Size() != oldSize)
                     if (group->Size() != oldSize)
                         i = group->Find(next);
                         i = group->Find(next);
                 }
                 }
             }
             }
         }
         }
     }
     }
-    
+
     context->EndSendEvent();
     context->EndSendEvent();
 }
 }
 
 
@@ -376,7 +378,7 @@ EventHandler* Object::FindEventHandler(StringHash eventType, EventHandler** prev
     EventHandler* handler = eventHandlers_.First();
     EventHandler* handler = eventHandlers_.First();
     if (previous)
     if (previous)
         *previous = 0;
         *previous = 0;
-    
+
     while (handler)
     while (handler)
     {
     {
         if (handler->GetEventType() == eventType)
         if (handler->GetEventType() == eventType)
@@ -385,7 +387,7 @@ EventHandler* Object::FindEventHandler(StringHash eventType, EventHandler** prev
             *previous = handler;
             *previous = handler;
         handler = eventHandlers_.Next(handler);
         handler = eventHandlers_.Next(handler);
     }
     }
-    
+
     return 0;
     return 0;
 }
 }
 
 
@@ -394,7 +396,7 @@ EventHandler* Object::FindSpecificEventHandler(Object* sender, EventHandler** pr
     EventHandler* handler = eventHandlers_.First();
     EventHandler* handler = eventHandlers_.First();
     if (previous)
     if (previous)
         *previous = 0;
         *previous = 0;
-    
+
     while (handler)
     while (handler)
     {
     {
         if (handler->GetSender() == sender)
         if (handler->GetSender() == sender)
@@ -403,7 +405,7 @@ EventHandler* Object::FindSpecificEventHandler(Object* sender, EventHandler** pr
             *previous = handler;
             *previous = handler;
         handler = eventHandlers_.Next(handler);
         handler = eventHandlers_.Next(handler);
     }
     }
-    
+
     return 0;
     return 0;
 }
 }
 
 
@@ -412,7 +414,7 @@ EventHandler* Object::FindSpecificEventHandler(Object* sender, StringHash eventT
     EventHandler* handler = eventHandlers_.First();
     EventHandler* handler = eventHandlers_.First();
     if (previous)
     if (previous)
         *previous = 0;
         *previous = 0;
-    
+
     while (handler)
     while (handler)
     {
     {
         if (handler->GetSender() == sender && handler->GetEventType() == eventType)
         if (handler->GetSender() == sender && handler->GetEventType() == eventType)
@@ -421,7 +423,7 @@ EventHandler* Object::FindSpecificEventHandler(Object* sender, StringHash eventT
             *previous = handler;
             *previous = handler;
         handler = eventHandlers_.Next(handler);
         handler = eventHandlers_.Next(handler);
     }
     }
-    
+
     return 0;
     return 0;
 }
 }
 
 
@@ -429,7 +431,7 @@ void Object::RemoveEventSender(Object* sender)
 {
 {
     EventHandler* handler = eventHandlers_.First();
     EventHandler* handler = eventHandlers_.First();
     EventHandler* previous = 0;
     EventHandler* previous = 0;
-    
+
     while (handler)
     while (handler)
     {
     {
         if (handler->GetSender() == sender)
         if (handler->GetSender() == sender)

+ 33 - 24
Source/Urho3D/Core/Object.h

@@ -48,15 +48,15 @@ class EventHandler;
 class URHO3D_API Object : public RefCounted
 class URHO3D_API Object : public RefCounted
 {
 {
     BASEOBJECT(Object);
     BASEOBJECT(Object);
-    
+
     friend class Context;
     friend class Context;
-    
+
 public:
 public:
     /// Construct.
     /// Construct.
     Object(Context* context);
     Object(Context* context);
     /// Destruct. Clean up self from event sender & receiver structures.
     /// Destruct. Clean up self from event sender & receiver structures.
     virtual ~Object();
     virtual ~Object();
-    
+
     /// Return type hash.
     /// Return type hash.
     virtual Urho3D::StringHash GetType() const = 0;
     virtual Urho3D::StringHash GetType() const = 0;
     /// Return base class type hash.
     /// Return base class type hash.
@@ -65,7 +65,7 @@ public:
     virtual const Urho3D::String& GetTypeName() const = 0;
     virtual const Urho3D::String& GetTypeName() const = 0;
     /// Handle event.
     /// Handle event.
     virtual void OnEvent(Object* sender, StringHash eventType, VariantMap& eventData);
     virtual void OnEvent(Object* sender, StringHash eventType, VariantMap& eventData);
-    
+
     /// Subscribe to an event that can be sent by any sender.
     /// Subscribe to an event that can be sent by any sender.
     void SubscribeToEvent(StringHash eventType, EventHandler* handler);
     void SubscribeToEvent(StringHash eventType, EventHandler* handler);
     /// Subscribe to a specific sender's event.
     /// Subscribe to a specific sender's event.
@@ -86,9 +86,10 @@ public:
     void SendEvent(StringHash eventType, VariantMap& eventData);
     void SendEvent(StringHash eventType, VariantMap& eventData);
     /// Return a preallocated map for event data. Used for optimization to avoid constant re-allocation of event data maps.
     /// Return a preallocated map for event data. Used for optimization to avoid constant re-allocation of event data maps.
     VariantMap& GetEventDataMap() const;
     VariantMap& GetEventDataMap() const;
-    
+
     /// Return execution context.
     /// Return execution context.
     Context* GetContext() const { return context_; }
     Context* GetContext() const { return context_; }
+
     /// Return subsystem by type.
     /// Return subsystem by type.
     Object* GetSubsystem(StringHash type) const;
     Object* GetSubsystem(StringHash type) const;
     /// Return active event sender. Null outside event handling.
     /// Return active event sender. Null outside event handling.
@@ -99,17 +100,19 @@ public:
     bool HasSubscribedToEvent(StringHash eventType) const;
     bool HasSubscribedToEvent(StringHash eventType) const;
     /// Return whether has subscribed to a specific sender's event.
     /// Return whether has subscribed to a specific sender's event.
     bool HasSubscribedToEvent(Object* sender, StringHash eventType) const;
     bool HasSubscribedToEvent(Object* sender, StringHash eventType) const;
+
     /// Return whether has subscribed to any event.
     /// Return whether has subscribed to any event.
     bool HasEventHandlers() const { return !eventHandlers_.Empty(); }
     bool HasEventHandlers() const { return !eventHandlers_.Empty(); }
+
     /// Template version of returning a subsystem.
     /// Template version of returning a subsystem.
     template <class T> T* GetSubsystem() const;
     template <class T> T* GetSubsystem() const;
     /// Return object category. Categories are (optionally) registered along with the object factory. Return an empty string if the object category is not registered.
     /// Return object category. Categories are (optionally) registered along with the object factory. Return an empty string if the object category is not registered.
     const String& GetCategory() const;
     const String& GetCategory() const;
-    
+
 protected:
 protected:
     /// Execution context.
     /// Execution context.
     Context* context_;
     Context* context_;
-    
+
 private:
 private:
     /// Find the first event handler with no specific sender.
     /// Find the first event handler with no specific sender.
     EventHandler* FindEventHandler(StringHash eventType, EventHandler** previous = 0) const;
     EventHandler* FindEventHandler(StringHash eventType, EventHandler** previous = 0) const;
@@ -119,7 +122,7 @@ private:
     EventHandler* FindSpecificEventHandler(Object* sender, StringHash eventType, EventHandler** previous = 0) const;
     EventHandler* FindSpecificEventHandler(Object* sender, StringHash eventType, EventHandler** previous = 0) const;
     /// Remove event handlers related to a specific sender.
     /// Remove event handlers related to a specific sender.
     void RemoveEventSender(Object* sender);
     void RemoveEventSender(Object* sender);
-    
+
     /// Event handlers. Sender is null for non-specific handlers.
     /// Event handlers. Sender is null for non-specific handlers.
     LinkedList<EventHandler> eventHandlers_;
     LinkedList<EventHandler> eventHandlers_;
 };
 };
@@ -136,19 +139,22 @@ public:
     {
     {
         assert(context_);
         assert(context_);
     }
     }
-    
+
     /// Create an object. Implemented in templated subclasses.
     /// Create an object. Implemented in templated subclasses.
     virtual SharedPtr<Object> CreateObject() = 0;
     virtual SharedPtr<Object> CreateObject() = 0;
-    
+
     /// Return execution context.
     /// Return execution context.
     Context* GetContext() const { return context_; }
     Context* GetContext() const { return context_; }
+
     /// Return type hash of objects created by this factory.
     /// Return type hash of objects created by this factory.
     StringHash GetType() const { return type_; }
     StringHash GetType() const { return type_; }
+
     /// Return base type hash of objects created by this factory.
     /// Return base type hash of objects created by this factory.
     StringHash GetBaseType() const { return baseType_; }
     StringHash GetBaseType() const { return baseType_; }
+
     /// Return type name of objects created by this factory.
     /// Return type name of objects created by this factory.
     const String& GetTypeName() const { return typeName_; }
     const String& GetTypeName() const { return typeName_; }
-    
+
 protected:
 protected:
     /// Execution context.
     /// Execution context.
     Context* context_;
     Context* context_;
@@ -172,7 +178,7 @@ public:
         baseType_ = T::GetBaseTypeStatic();
         baseType_ = T::GetBaseTypeStatic();
         typeName_ = T::GetTypeNameStatic();
         typeName_ = T::GetTypeNameStatic();
     }
     }
-    
+
     /// Create an object of the specific type.
     /// Create an object of the specific type.
     virtual SharedPtr<Object> CreateObject() { return SharedPtr<Object>(new T(context_)); }
     virtual SharedPtr<Object> CreateObject() { return SharedPtr<Object>(new T(context_)); }
 };
 };
@@ -189,7 +195,7 @@ public:
     {
     {
         assert(receiver_);
         assert(receiver_);
     }
     }
-    
+
     /// Construct with specified receiver and userdata.
     /// Construct with specified receiver and userdata.
     EventHandler(Object* receiver, void* userData) :
     EventHandler(Object* receiver, void* userData) :
         receiver_(receiver),
         receiver_(receiver),
@@ -198,31 +204,34 @@ public:
     {
     {
         assert(receiver_);
         assert(receiver_);
     }
     }
-    
+
     /// Destruct.
     /// Destruct.
-    virtual ~EventHandler() {}
-    
+    virtual ~EventHandler() { }
+
     /// Set sender and event type.
     /// Set sender and event type.
     void SetSenderAndEventType(Object* sender, StringHash eventType)
     void SetSenderAndEventType(Object* sender, StringHash eventType)
     {
     {
         sender_ = sender;
         sender_ = sender;
         eventType_ = eventType;
         eventType_ = eventType;
     }
     }
-    
+
     /// Invoke event handler function.
     /// Invoke event handler function.
     virtual void Invoke(VariantMap& eventData) = 0;
     virtual void Invoke(VariantMap& eventData) = 0;
     /// Return a unique copy of the event handler.
     /// Return a unique copy of the event handler.
     virtual EventHandler* Clone() const = 0;
     virtual EventHandler* Clone() const = 0;
-    
+
     /// Return event receiver.
     /// Return event receiver.
     Object* GetReceiver() const { return receiver_; }
     Object* GetReceiver() const { return receiver_; }
+
     /// Return event sender. Null if the handler is non-specific.
     /// Return event sender. Null if the handler is non-specific.
     Object* GetSender() const { return sender_; }
     Object* GetSender() const { return sender_; }
+
     /// Return event type.
     /// Return event type.
     const StringHash& GetEventType() const { return eventType_; }
     const StringHash& GetEventType() const { return eventType_; }
+
     /// Return userdata.
     /// Return userdata.
     void* GetUserData() const { return userData_; }
     void* GetUserData() const { return userData_; }
-    
+
 protected:
 protected:
     /// Event receiver.
     /// Event receiver.
     Object* receiver_;
     Object* receiver_;
@@ -239,7 +248,7 @@ template <class T> class EventHandlerImpl : public EventHandler
 {
 {
 public:
 public:
     typedef void (T::*HandlerFunctionPtr)(StringHash, VariantMap&);
     typedef void (T::*HandlerFunctionPtr)(StringHash, VariantMap&);
-    
+
     /// Construct with receiver and function pointers.
     /// Construct with receiver and function pointers.
     EventHandlerImpl(T* receiver, HandlerFunctionPtr function) :
     EventHandlerImpl(T* receiver, HandlerFunctionPtr function) :
         EventHandler(receiver),
         EventHandler(receiver),
@@ -247,7 +256,7 @@ public:
     {
     {
         assert(function_);
         assert(function_);
     }
     }
-    
+
     /// Construct with receiver and function pointers and userdata.
     /// Construct with receiver and function pointers and userdata.
     EventHandlerImpl(T* receiver, HandlerFunctionPtr function, void* userData) :
     EventHandlerImpl(T* receiver, HandlerFunctionPtr function, void* userData) :
         EventHandler(receiver, userData),
         EventHandler(receiver, userData),
@@ -255,20 +264,20 @@ public:
     {
     {
         assert(function_);
         assert(function_);
     }
     }
-    
+
     /// Invoke event handler function.
     /// Invoke event handler function.
     virtual void Invoke(VariantMap& eventData)
     virtual void Invoke(VariantMap& eventData)
     {
     {
         T* receiver = static_cast<T*>(receiver_);
         T* receiver = static_cast<T*>(receiver_);
         (receiver->*function_)(eventType_, eventData);
         (receiver->*function_)(eventType_, eventData);
     }
     }
-    
+
     /// Return a unique copy of the event handler.
     /// Return a unique copy of the event handler.
     virtual EventHandler* Clone() const
     virtual EventHandler* Clone() const
     {
     {
         return new EventHandlerImpl(static_cast<T*>(receiver_), function_, userData_);
         return new EventHandlerImpl(static_cast<T*>(receiver_), function_, userData_);
     }
     }
-    
+
 private:
 private:
     /// Class-specific pointer to handler function.
     /// Class-specific pointer to handler function.
     HandlerFunctionPtr function_;
     HandlerFunctionPtr function_;

+ 56 - 52
Source/Urho3D/Core/ProcessUtils.cpp

@@ -20,9 +20,9 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
-#include "../Core/Mutex.h"
+#include "../Precompiled.h"
+
 #include "../Core/ProcessUtils.h"
 #include "../Core/ProcessUtils.h"
-#include "../Math/MathDefs.h"
 
 
 #include <cstdio>
 #include <cstdio>
 #include <fcntl.h>
 #include <fcntl.h>
@@ -32,6 +32,7 @@
 #endif
 #endif
 
 
 #if defined(IOS)
 #if defined(IOS)
+#include "../Math/MathDefs.h"
 #include <mach/mach_host.h>
 #include <mach/mach_host.h>
 #elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN)
 #elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN)
 #include <LibCpuId/libcpuid.h>
 #include <LibCpuId/libcpuid.h>
@@ -70,6 +71,7 @@ inline void SetFPUState(unsigned control)
 {
 {
     __asm__ __volatile__ ("fldcw %0" : : "m" (control));
     __asm__ __volatile__ ("fldcw %0" : : "m" (control));
 }
 }
+
 #endif
 #endif
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
@@ -91,6 +93,7 @@ static void GetCPUData(host_basic_info_data_t* data)
     host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)data, &infoCount);
     host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)data, &infoCount);
 }
 }
 #elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN)
 #elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN)
+
 static void GetCPUData(struct cpu_id_t* data)
 static void GetCPUData(struct cpu_id_t* data)
 {
 {
     if (cpu_identify(0, data) < 0)
     if (cpu_identify(0, data) < 0)
@@ -99,31 +102,32 @@ static void GetCPUData(struct cpu_id_t* data)
         data->num_cores = 1;
         data->num_cores = 1;
     }
     }
 }
 }
+
 #endif
 #endif
 
 
 void InitFPU()
 void InitFPU()
 {
 {
-    #if !defined(URHO3D_LUAJIT) && !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(__x86_64__) && !defined(_M_AMD64) && !defined(EMSCRIPTEN)
+#if !defined(URHO3D_LUAJIT) && !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(__x86_64__) && !defined(_M_AMD64) && !defined(EMSCRIPTEN)
     // Make sure FPU is in round-to-nearest, single precision mode
     // Make sure FPU is in round-to-nearest, single precision mode
     // This ensures Direct3D and OpenGL behave similarly, and all threads behave similarly
     // This ensures Direct3D and OpenGL behave similarly, and all threads behave similarly
-    #ifdef _MSC_VER
+#ifdef _MSC_VER
     _controlfp(_RC_NEAR | _PC_24, _MCW_RC | _MCW_PC);
     _controlfp(_RC_NEAR | _PC_24, _MCW_RC | _MCW_PC);
-    #else
+#else
     unsigned control = GetFPUState();
     unsigned control = GetFPUState();
     control &= ~(FPU_CW_PREC_MASK | FPU_CW_ROUND_MASK);
     control &= ~(FPU_CW_PREC_MASK | FPU_CW_ROUND_MASK);
     control |= (FPU_CW_PREC_SINGLE | FPU_CW_ROUND_NEAR);
     control |= (FPU_CW_PREC_SINGLE | FPU_CW_ROUND_NEAR);
     SetFPUState(control);
     SetFPUState(control);
-    #endif
-    #endif
+#endif
+#endif
 }
 }
 
 
 void ErrorDialog(const String& title, const String& message)
 void ErrorDialog(const String& title, const String& message)
 {
 {
-    #ifdef WIN32
+#ifdef WIN32
     MessageBoxW(0, WString(message).CString(), WString(title).CString(), 0);
     MessageBoxW(0, WString(message).CString(), WString(title).CString(), 0);
-    #else
+#else
     PrintLine(message, true);
     PrintLine(message, true);
-    #endif
+#endif
 }
 }
 
 
 void ErrorExit(const String& message, int exitCode)
 void ErrorExit(const String& message, int exitCode)
@@ -136,7 +140,7 @@ void ErrorExit(const String& message, int exitCode)
 
 
 void OpenConsoleWindow()
 void OpenConsoleWindow()
 {
 {
-    #ifdef WIN32
+#ifdef WIN32
     if (consoleOpened)
     if (consoleOpened)
         return;
         return;
 
 
@@ -155,13 +159,13 @@ void OpenConsoleWindow()
     *stdin = *inFile;
     *stdin = *inFile;
 
 
     consoleOpened = true;
     consoleOpened = true;
-    #endif
+#endif
 }
 }
 
 
 void PrintUnicode(const String& str, bool error)
 void PrintUnicode(const String& str, bool error)
 {
 {
-    #if !defined(ANDROID) && !defined(IOS)
-    #ifdef WIN32
+#if !defined(ANDROID) && !defined(IOS)
+#ifdef WIN32
     // If the output stream has been redirected, use fprintf instead of WriteConsoleW,
     // If the output stream has been redirected, use fprintf instead of WriteConsoleW,
     // though it means that proper Unicode output will not work
     // though it means that proper Unicode output will not work
     FILE* out = error ? stderr : stdout;
     FILE* out = error ? stderr : stdout;
@@ -176,10 +180,10 @@ void PrintUnicode(const String& str, bool error)
         DWORD charsWritten;
         DWORD charsWritten;
         WriteConsoleW(stream, strW.CString(), strW.Length(), &charsWritten, 0);
         WriteConsoleW(stream, strW.CString(), strW.Length(), &charsWritten, 0);
     }
     }
-    #else
+#else
     fprintf(error ? stderr : stdout, "%s", str.CString());
     fprintf(error ? stderr : stdout, "%s", str.CString());
-    #endif
-    #endif
+#endif
+#endif
 }
 }
 
 
 void PrintUnicodeLine(const String& str, bool error)
 void PrintUnicodeLine(const String& str, bool error)
@@ -189,9 +193,9 @@ void PrintUnicodeLine(const String& str, bool error)
 
 
 void PrintLine(const String& str, bool error)
 void PrintLine(const String& str, bool error)
 {
 {
-    #if !defined(ANDROID) && !defined(IOS)
-    fprintf(error ? stderr: stdout, "%s\n", str.CString());
-    #endif
+#if !defined(ANDROID) && !defined(IOS)
+    fprintf(error ? stderr : stdout, "%s\n", str.CString());
+#endif
 }
 }
 
 
 const Vector<String>& ParseArguments(const String& cmdLine, bool skipFirstArgument)
 const Vector<String>& ParseArguments(const String& cmdLine, bool skipFirstArgument)
@@ -274,12 +278,12 @@ const Vector<String>& GetArguments()
 String GetConsoleInput()
 String GetConsoleInput()
 {
 {
     String ret;
     String ret;
-    #ifdef URHO3D_TESTING
+#ifdef URHO3D_TESTING
     // When we are running automated tests, reading the console may block. Just return empty in that case
     // When we are running automated tests, reading the console may block. Just return empty in that case
     return ret;
     return ret;
-    #endif
+#endif
 
 
-    #ifdef WIN32
+#ifdef WIN32
     HANDLE input = GetStdHandle(STD_INPUT_HANDLE);
     HANDLE input = GetStdHandle(STD_INPUT_HANDLE);
     HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
     HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
     if (input == INVALID_HANDLE_VALUE || output == INVALID_HANDLE_VALUE)
     if (input == INVALID_HANDLE_VALUE || output == INVALID_HANDLE_VALUE)
@@ -328,7 +332,7 @@ String GetConsoleInput()
             }
             }
         }
         }
     }
     }
-    #elif !defined(ANDROID) && !defined(IOS)
+#elif !defined(ANDROID) && !defined(IOS)
     int flags = fcntl(STDIN_FILENO, F_GETFL);
     int flags = fcntl(STDIN_FILENO, F_GETFL);
     fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
     fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
     for (;;)
     for (;;)
@@ -339,30 +343,30 @@ String GetConsoleInput()
         else
         else
             break;
             break;
     }
     }
-    #endif
+#endif
 
 
     return ret;
     return ret;
 }
 }
 
 
 String GetPlatform()
 String GetPlatform()
 {
 {
-    #if defined(ANDROID)
+#if defined(ANDROID)
     return "Android";
     return "Android";
-    #elif defined(IOS)
+#elif defined(IOS)
     return "iOS";
     return "iOS";
-    #elif defined(WIN32)
+#elif defined(WIN32)
     return "Windows";
     return "Windows";
-    #elif defined(__APPLE__)
+#elif defined(__APPLE__)
     return "Mac OS X";
     return "Mac OS X";
-    #elif defined(RPI)
+#elif defined(RPI)
     return "Raspberry Pi";
     return "Raspberry Pi";
-    #elif defined(EMSCRIPTEN)
+#elif defined(EMSCRIPTEN)
     return "HTML5";
     return "HTML5";
-    #elif defined(__linux__)
+#elif defined(__linux__)
     return "Linux";
     return "Linux";
-    #else
+#else
     return String::EMPTY;
     return String::EMPTY;
-    #endif
+#endif
 }
 }
 
 
 #if defined(ANDROID) || defined(RPI)
 #if defined(ANDROID) || defined(RPI)
@@ -391,47 +395,47 @@ static unsigned GetArmCPUCount()
 
 
 unsigned GetNumPhysicalCPUs()
 unsigned GetNumPhysicalCPUs()
 {
 {
-    #if defined(IOS)
+#if defined(IOS)
     host_basic_info_data_t data;
     host_basic_info_data_t data;
     GetCPUData(&data);
     GetCPUData(&data);
-    #if defined(TARGET_IPHONE_SIMULATOR)
+#if defined(TARGET_IPHONE_SIMULATOR)
     // Hardcoded to dual-core on simulator mode even if the host has more
     // Hardcoded to dual-core on simulator mode even if the host has more
     return Min(2, data.physical_cpu);
     return Min(2, data.physical_cpu);
-    #else
+#else
     return data.physical_cpu;
     return data.physical_cpu;
-    #endif
-    #elif defined(ANDROID) || defined(RPI)
+#endif
+#elif defined(ANDROID) || defined(RPI)
     return GetArmCPUCount();
     return GetArmCPUCount();
-    #elif !defined(EMSCRIPTEN)
+#elif !defined(EMSCRIPTEN)
     struct cpu_id_t data;
     struct cpu_id_t data;
     GetCPUData(&data);
     GetCPUData(&data);
-    return data.num_cores;
-    #else
+    return (unsigned)data.num_cores;
+#else
     /// \todo Implement properly
     /// \todo Implement properly
     return 1;
     return 1;
-    #endif
+#endif
 }
 }
 
 
 unsigned GetNumLogicalCPUs()
 unsigned GetNumLogicalCPUs()
 {
 {
-    #if defined(IOS)
+#if defined(IOS)
     host_basic_info_data_t data;
     host_basic_info_data_t data;
     GetCPUData(&data);
     GetCPUData(&data);
-    #if defined(TARGET_IPHONE_SIMULATOR)
+#if defined(TARGET_IPHONE_SIMULATOR)
     return Min(2, data.logical_cpu);
     return Min(2, data.logical_cpu);
-    #else
+#else
     return data.logical_cpu;
     return data.logical_cpu;
-    #endif
-    #elif defined(ANDROID) || defined (RPI)
+#endif
+#elif defined(ANDROID) || defined (RPI)
     return GetArmCPUCount();
     return GetArmCPUCount();
-    #elif !defined(EMSCRIPTEN)
+#elif !defined(EMSCRIPTEN)
     struct cpu_id_t data;
     struct cpu_id_t data;
     GetCPUData(&data);
     GetCPUData(&data);
-    return data.num_logical_cpus;
-    #else
+    return (unsigned)data.num_logical_cpus;
+#else
     /// \todo Implement properly
     /// \todo Implement properly
     return 1;
     return 1;
-    #endif
+#endif
 }
 }
 
 
 }
 }

+ 23 - 21
Source/Urho3D/Core/Profiler.cpp

@@ -20,11 +20,12 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Core/CoreEvents.h"
 #include "../Core/CoreEvents.h"
 #include "../Core/Profiler.h"
 #include "../Core/Profiler.h"
 
 
 #include <cstdio>
 #include <cstdio>
-#include <cstring>
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -55,7 +56,7 @@ void Profiler::BeginFrame()
 {
 {
     // End the previous frame if any
     // End the previous frame if any
     EndFrame();
     EndFrame();
-    
+
     BeginBlock("RunFrame");
     BeginBlock("RunFrame");
 }
 }
 
 
@@ -82,33 +83,34 @@ void Profiler::BeginInterval()
 String Profiler::GetData(bool showUnused, bool showTotal, unsigned maxDepth) const
 String Profiler::GetData(bool showUnused, bool showTotal, unsigned maxDepth) const
 {
 {
     String output;
     String output;
-    
+
     if (!showTotal)
     if (!showTotal)
-        output += String("Block                            Cnt     Avg      Max     Frame     Total\n\n");
+        output += "Block                            Cnt     Avg      Max     Frame     Total\n\n";
     else
     else
     {
     {
-        output += String("Block                                       Last frame                       Whole execution time\n\n");
-        output += String("                                 Cnt     Avg      Max      Total      Cnt      Avg       Max        Total\n\n");
+        output += "Block                                       Last frame                       Whole execution time\n\n";
+        output += "                                 Cnt     Avg      Max      Total      Cnt      Avg       Max        Total\n\n";
     }
     }
-    
+
     if (!maxDepth)
     if (!maxDepth)
         maxDepth = 1;
         maxDepth = 1;
-    
+
     GetData(root_, output, 0, maxDepth, showUnused, showTotal);
     GetData(root_, output, 0, maxDepth, showUnused, showTotal);
-    
+
     return output;
     return output;
 }
 }
 
 
-void Profiler::GetData(ProfilerBlock* block, String& output, unsigned depth, unsigned maxDepth, bool showUnused, bool showTotal) const
+void Profiler::GetData(ProfilerBlock* block, String& output, unsigned depth, unsigned maxDepth, bool showUnused,
+    bool showTotal) const
 {
 {
     char line[LINE_MAX_LENGTH];
     char line[LINE_MAX_LENGTH];
     char indentedName[LINE_MAX_LENGTH];
     char indentedName[LINE_MAX_LENGTH];
-    
-    unsigned intervalFrames = Max(intervalFrames_, 1);
-    
+
+    unsigned intervalFrames = (unsigned)Max(intervalFrames_, 1);
+
     if (depth >= maxDepth)
     if (depth >= maxDepth)
         return;
         return;
-    
+
     // Do not print the root block as it does not collect any actual data
     // Do not print the root block as it does not collect any actual data
     if (block != root_)
     if (block != root_)
     {
     {
@@ -119,14 +121,14 @@ void Profiler::GetData(ProfilerBlock* block, String& output, unsigned depth, uns
             strcat(indentedName, block->name_);
             strcat(indentedName, block->name_);
             indentedName[strlen(indentedName)] = ' ';
             indentedName[strlen(indentedName)] = ' ';
             indentedName[NAME_MAX_LENGTH] = 0;
             indentedName[NAME_MAX_LENGTH] = 0;
-            
+
             if (!showTotal)
             if (!showTotal)
             {
             {
                 float avg = (block->intervalCount_ ? block->intervalTime_ / block->intervalCount_ : 0.0f) / 1000.0f;
                 float avg = (block->intervalCount_ ? block->intervalTime_ / block->intervalCount_ : 0.0f) / 1000.0f;
                 float max = block->intervalMaxTime_ / 1000.0f;
                 float max = block->intervalMaxTime_ / 1000.0f;
                 float frame = block->intervalTime_ / intervalFrames / 1000.0f;
                 float frame = block->intervalTime_ / intervalFrames / 1000.0f;
                 float all = block->intervalTime_ / 1000.0f;
                 float all = block->intervalTime_ / 1000.0f;
-        
+
                 sprintf(line, "%s %5u %8.3f %8.3f %8.3f %9.3f\n", indentedName, Min(block->intervalCount_, 99999),
                 sprintf(line, "%s %5u %8.3f %8.3f %8.3f %9.3f\n", indentedName, Min(block->intervalCount_, 99999),
                     avg, max, frame, all);
                     avg, max, frame, all);
             }
             }
@@ -135,21 +137,21 @@ void Profiler::GetData(ProfilerBlock* block, String& output, unsigned depth, uns
                 float avg = (block->frameCount_ ? block->frameTime_ / block->frameCount_ : 0.0f) / 1000.0f;
                 float avg = (block->frameCount_ ? block->frameTime_ / block->frameCount_ : 0.0f) / 1000.0f;
                 float max = block->frameMaxTime_ / 1000.0f;
                 float max = block->frameMaxTime_ / 1000.0f;
                 float all = block->frameTime_ / 1000.0f;
                 float all = block->frameTime_ / 1000.0f;
-                
+
                 float totalAvg = (block->totalCount_ ? block->totalTime_ / block->totalCount_ : 0.0f) / 1000.0f;
                 float totalAvg = (block->totalCount_ ? block->totalTime_ / block->totalCount_ : 0.0f) / 1000.0f;
                 float totalMax = block->totalMaxTime_ / 1000.0f;
                 float totalMax = block->totalMaxTime_ / 1000.0f;
                 float totalAll = block->totalTime_ / 1000.0f;
                 float totalAll = block->totalTime_ / 1000.0f;
-                
+
                 sprintf(line, "%s %5u %8.3f %8.3f %9.3f  %7u %9.3f %9.3f %11.3f\n", indentedName, Min(block->frameCount_, 99999),
                 sprintf(line, "%s %5u %8.3f %8.3f %9.3f  %7u %9.3f %9.3f %11.3f\n", indentedName, Min(block->frameCount_, 99999),
                     avg, max, all, Min(block->totalCount_, 99999), totalAvg, totalMax, totalAll);
                     avg, max, all, Min(block->totalCount_, 99999), totalAvg, totalMax, totalAll);
             }
             }
-            
+
             output += String(line);
             output += String(line);
         }
         }
-        
+
         ++depth;
         ++depth;
     }
     }
-    
+
     for (PODVector<ProfilerBlock*>::ConstIterator i = block->children_.Begin(); i != block->children_.End(); ++i)
     for (PODVector<ProfilerBlock*>::ConstIterator i = block->children_.Begin(); i != block->children_.End(); ++i)
         GetData(*i, output, depth, maxDepth, showUnused, showTotal);
         GetData(*i, output, depth, maxDepth, showUnused, showTotal);
 }
 }

+ 13 - 8
Source/Urho3D/Core/Spline.cpp

@@ -20,8 +20,10 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
-#include "../IO/Log.h"
+#include "../Precompiled.h"
+
 #include "../Core/Spline.h"
 #include "../Core/Spline.h"
+#include "../IO/Log.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {
@@ -84,22 +86,24 @@ void Spline::SetKnot(const Variant& knot, unsigned index)
         else if (knots_.Empty())
         else if (knots_.Empty())
             knots_.Push(knot);
             knots_.Push(knot);
         else
         else
-            LOGERRORF("Attempted to set a Spline's Knot value of type %s where elements are already using %s", knot.GetTypeName().CString(), knots_[0].GetTypeName().CString());
+            LOGERRORF("Attempted to set a Spline's Knot value of type %s where elements are already using %s",
+                knot.GetTypeName().CString(), knots_[0].GetTypeName().CString());
     }
     }
 }
 }
 
 
-void Spline::AddKnot(const Variant& knot) 
-{ 
+void Spline::AddKnot(const Variant& knot)
+{
     if (knots_.Size() > 0 && knots_[0].GetType() == knot.GetType())
     if (knots_.Size() > 0 && knots_[0].GetType() == knot.GetType())
         knots_.Push(knot);
         knots_.Push(knot);
     else if (knots_.Empty())
     else if (knots_.Empty())
         knots_.Push(knot);
         knots_.Push(knot);
     else
     else
-        LOGERRORF("Attempted to add Knot to Spline of type %s where elements are already using %s", knot.GetTypeName().CString(), knots_[0].GetTypeName().CString());
+        LOGERRORF("Attempted to add Knot to Spline of type %s where elements are already using %s", knot.GetTypeName().CString(),
+            knots_[0].GetTypeName().CString());
 }
 }
 
 
-void Spline::AddKnot(const Variant& knot, unsigned index) 
-{ 
+void Spline::AddKnot(const Variant& knot, unsigned index)
+{
     if (index > knots_.Size())
     if (index > knots_.Size())
         index = knots_.Size();
         index = knots_.Size();
 
 
@@ -108,7 +112,8 @@ void Spline::AddKnot(const Variant& knot, unsigned index)
     else if (knots_.Empty())
     else if (knots_.Empty())
         knots_.Push(knot);
         knots_.Push(knot);
     else
     else
-        LOGERRORF("Attempted to add Knot to Spline of type %s where elements are already using %s", knot.GetTypeName().CString(), knots_[0].GetTypeName().CString());
+        LOGERRORF("Attempted to add Knot to Spline of type %s where elements are already using %s", knot.GetTypeName().CString(),
+            knots_[0].GetTypeName().CString());
 }
 }
 
 
 Variant Spline::BezierInterpolation(const Vector<Variant>& knots, float t) const
 Variant Spline::BezierInterpolation(const Vector<Variant>& knots, float t) const

+ 15 - 4
Source/Urho3D/Core/Spline.h

@@ -22,8 +22,8 @@
 
 
 #pragma once
 #pragma once
 
 
-#include "../Math/Color.h"
 #include "../Core/Variant.h"
 #include "../Core/Variant.h"
+#include "../Math/Color.h"
 #include "../Math/Vector2.h"
 #include "../Math/Vector2.h"
 #include "../Math/Vector3.h"
 #include "../Math/Vector3.h"
 #include "../Math/Vector4.h"
 #include "../Math/Vector4.h"
@@ -50,44 +50,55 @@ public:
     Spline(const Spline& rhs);
     Spline(const Spline& rhs);
 
 
     /// Copy operator.
     /// Copy operator.
-    void operator= (const Spline& rhs)
+    void operator =(const Spline& rhs)
     {
     {
         knots_ = rhs.knots_;
         knots_ = rhs.knots_;
         interpolationMode_ = rhs.interpolationMode_;
         interpolationMode_ = rhs.interpolationMode_;
     }
     }
+
     /// Equality operator.
     /// Equality operator.
-    bool operator== (const Spline& rhs) const
+    bool operator ==(const Spline& rhs) const
     {
     {
         return (knots_ == rhs.knots_ && interpolationMode_ == rhs.interpolationMode_);
         return (knots_ == rhs.knots_ && interpolationMode_ == rhs.interpolationMode_);
     }
     }
+
     /// Non Equality operator.
     /// Non Equality operator.
-    bool operator!= (const Spline& rhs) const
+    bool operator !=(const Spline& rhs) const
     {
     {
         return !(*this == rhs);
         return !(*this == rhs);
     }
     }
 
 
     /// Return the ImplementationMode.
     /// Return the ImplementationMode.
     InterpolationMode GetInterpolationMode() const { return interpolationMode_; }
     InterpolationMode GetInterpolationMode() const { return interpolationMode_; }
+
     /// Return the Knots of the Spline.
     /// Return the Knots of the Spline.
     const VariantVector& GetKnots() const { return knots_; }
     const VariantVector& GetKnots() const { return knots_; }
+
     /// Return the Knot at the specific index.
     /// Return the Knot at the specific index.
     Variant GetKnot(unsigned index) const { return knots_[index]; }
     Variant GetKnot(unsigned index) const { return knots_[index]; }
+
     /// Return the T of the point of the Spline at f from 0.f - 1.f.
     /// Return the T of the point of the Spline at f from 0.f - 1.f.
     Variant GetPoint(float f) const;
     Variant GetPoint(float f) const;
+
     /// Set the InterpolationMode of the Spline.
     /// Set the InterpolationMode of the Spline.
     void SetInterpolationMode(InterpolationMode interpolationMode) { interpolationMode_ = interpolationMode; }
     void SetInterpolationMode(InterpolationMode interpolationMode) { interpolationMode_ = interpolationMode; }
+
     /// Set the Knots of the Spline.
     /// Set the Knots of the Spline.
     void SetKnots(const Vector<Variant>& knots) { knots_ = knots; }
     void SetKnots(const Vector<Variant>& knots) { knots_ = knots; }
+
     /// Set the Knot value of an existing Knot.
     /// Set the Knot value of an existing Knot.
     void SetKnot(const Variant& knot, unsigned index);
     void SetKnot(const Variant& knot, unsigned index);
     /// Add a Knot to the end of the Spline.
     /// Add a Knot to the end of the Spline.
     void AddKnot(const Variant& knot);
     void AddKnot(const Variant& knot);
     /// Add a Knot to the Spline at a specific index.
     /// Add a Knot to the Spline at a specific index.
     void AddKnot(const Variant& knot, unsigned index);
     void AddKnot(const Variant& knot, unsigned index);
+
     /// Remove the last Knot on the Spline.
     /// Remove the last Knot on the Spline.
     void RemoveKnot() { knots_.Pop(); }
     void RemoveKnot() { knots_.Pop(); }
+
     /// Remove the Knot at the specific index.
     /// Remove the Knot at the specific index.
     void RemoveKnot(unsigned index) { knots_.Erase(index); }
     void RemoveKnot(unsigned index) { knots_.Erase(index); }
+
     /// Clear the Spline.
     /// Clear the Spline.
     void Clear() { knots_.Clear(); }
     void Clear() { knots_.Clear(); }
 
 

+ 19 - 13
Source/Urho3D/Core/StringUtils.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Core/StringUtils.h"
 #include "../Core/StringUtils.h"
 
 
 #include <cstdio>
 #include <cstdio>
@@ -91,7 +93,7 @@ bool ToBool(const char* source)
 
 
     for (unsigned i = 0; i < length; ++i)
     for (unsigned i = 0; i < length; ++i)
     {
     {
-        char c = tolower(source[i]);
+        char c = (char)tolower(source[i]);
         if (c == 't' || c == 'y' || c == '1')
         if (c == 't' || c == 'y' || c == '1')
             return true;
             return true;
         else if (c != ' ' && c != '\t')
         else if (c != ' ' && c != '\t')
@@ -112,7 +114,7 @@ int ToInt(const char* source)
         return 0;
         return 0;
 
 
     // Explicitly ask for base 10 to prevent source starts with '0' or '0x' from being converted to base 8 or base 16, respectively
     // Explicitly ask for base 10 to prevent source starts with '0' or '0x' from being converted to base 8 or base 16, respectively
-    return strtol(source, 0, 10);
+    return (int)strtol(source, 0, 10);
 }
 }
 
 
 unsigned ToUInt(const String& source)
 unsigned ToUInt(const String& source)
@@ -125,7 +127,7 @@ unsigned ToUInt(const char* source)
     if (!source)
     if (!source)
         return 0;
         return 0;
 
 
-    return strtoul(source, 0, 10);
+    return (unsigned)strtoul(source, 0, 10);
 }
 }
 
 
 float ToFloat(const String& source)
 float ToFloat(const String& source)
@@ -395,6 +397,10 @@ Variant ToVectorVariant(const char* source)
     case 16:
     case 16:
         ret.FromString(VAR_MATRIX4, source);
         ret.FromString(VAR_MATRIX4, source);
         break;
         break;
+
+    default:
+        assert(false);  // Should not get here
+        break;
     }
     }
 
 
     return ret;
     return ret;
@@ -538,14 +544,14 @@ void BufferToString(String& dest, const void* data, unsigned size)
         }
         }
         else if (bytes[i] < 100)
         else if (bytes[i] < 100)
         {
         {
-            dest[index++] = '0' + bytes[i] / 10;
-            dest[index++] = '0' + bytes[i] % 10;
+            dest[index++] = (char)('0' + bytes[i] / 10);
+            dest[index++] = (char)('0' + bytes[i] % 10);
         }
         }
         else
         else
         {
         {
-            dest[index++] = '0' + bytes[i] / 100;
-            dest[index++] = '0' + bytes[i] % 100 / 10;
-            dest[index++] = '0' + bytes[i] % 10;
+            dest[index++] = (char)('0' + bytes[i] / 100);
+            dest[index++] = (char)('0' + bytes[i] % 100 / 10);
+            dest[index++] = (char)('0' + bytes[i] % 10);
         }
         }
     }
     }
 }
 }
@@ -577,7 +583,7 @@ void StringToBuffer(PODVector<unsigned char>& dest, const char* source)
         if (inSpace && *ptr != ' ')
         if (inSpace && *ptr != ' ')
         {
         {
             inSpace = false;
             inSpace = false;
-            value = *ptr - '0';
+            value = (unsigned)(*ptr - '0');
         }
         }
         else if (!inSpace && *ptr != ' ')
         else if (!inSpace && *ptr != ' ')
         {
         {
@@ -586,7 +592,7 @@ void StringToBuffer(PODVector<unsigned char>& dest, const char* source)
         }
         }
         else if (!inSpace && *ptr == ' ')
         else if (!inSpace && *ptr == ' ')
         {
         {
-            dest[index++] = value;
+            dest[index++] = (unsigned char)value;
             inSpace = true;
             inSpace = true;
         }
         }
 
 
@@ -595,7 +601,7 @@ void StringToBuffer(PODVector<unsigned char>& dest, const char* source)
 
 
     // Write the final value
     // Write the final value
     if (!inSpace && index < size)
     if (!inSpace && index < size)
-        dest[index] = value;
+        dest[index] = (unsigned char)value;
 }
 }
 
 
 unsigned GetStringListIndex(const String& value, const String* strings, unsigned defaultIndex, bool caseSensitive)
 unsigned GetStringListIndex(const String& value, const String* strings, unsigned defaultIndex, bool caseSensitive)
@@ -653,12 +659,12 @@ bool IsDigit(unsigned ch)
 
 
 unsigned ToUpper(unsigned ch)
 unsigned ToUpper(unsigned ch)
 {
 {
-    return toupper(ch);
+    return (unsigned)toupper(ch);
 }
 }
 
 
 unsigned ToLower(unsigned ch)
 unsigned ToLower(unsigned ch)
 {
 {
-    return tolower(ch);
+    return (unsigned)tolower(ch);
 }
 }
 
 
 }
 }

+ 27 - 23
Source/Urho3D/Core/Thread.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Core/Thread.h"
 #include "../Core/Thread.h"
 
 
 #ifdef WIN32
 #ifdef WIN32
@@ -34,24 +36,28 @@ namespace Urho3D
 {
 {
 
 
 #ifdef WIN32
 #ifdef WIN32
+
 DWORD WINAPI ThreadFunctionStatic(void* data)
 DWORD WINAPI ThreadFunctionStatic(void* data)
 {
 {
     Thread* thread = static_cast<Thread*>(data);
     Thread* thread = static_cast<Thread*>(data);
     thread->ThreadFunction();
     thread->ThreadFunction();
     return 0;
     return 0;
 }
 }
+
 #else
 #else
+
 void* ThreadFunctionStatic(void* data)
 void* ThreadFunctionStatic(void* data)
 {
 {
     Thread* thread = static_cast<Thread*>(data);
     Thread* thread = static_cast<Thread*>(data);
     thread->ThreadFunction();
     thread->ThreadFunction();
 #ifdef EMSCRIPTEN
 #ifdef EMSCRIPTEN
-// note: emscripten doesn't have this function but doesn't use threading anyway
-// so #ifdef it out to prevent linker warnings
+    // note: emscripten doesn't have this function but doesn't use threading anyway
+    // so #ifdef it out to prevent linker warnings
     pthread_exit((void*)0);
     pthread_exit((void*)0);
 #endif
 #endif
     return 0;
     return 0;
 }
 }
+
 #endif
 #endif
 
 
 ThreadID Thread::mainThreadID;
 ThreadID Thread::mainThreadID;
@@ -72,20 +78,19 @@ bool Thread::Run()
     // Check if already running
     // Check if already running
     if (handle_)
     if (handle_)
         return false;
         return false;
-    
+
     shouldRun_ = true;
     shouldRun_ = true;
-    #ifdef WIN32
+#ifdef WIN32
     handle_ = CreateThread(0, 0, ThreadFunctionStatic, this, 0, 0);
     handle_ = CreateThread(0, 0, ThreadFunctionStatic, this, 0, 0);
-//    #else
-    #elif !defined(EMSCRIPTEN)
-// note: emscripten doesn't have this function but doesn't use
-// threading anyway so #ifdef it out to prevent linker warnings
+#elif !defined(EMSCRIPTEN)
+    // note: emscripten doesn't have this function but doesn't use
+    // threading anyway so #ifdef it out to prevent linker warnings
     handle_ = new pthread_t;
     handle_ = new pthread_t;
     pthread_attr_t type;
     pthread_attr_t type;
     pthread_attr_init(&type);
     pthread_attr_init(&type);
     pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE);
     pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE);
     pthread_create((pthread_t*)handle_, &type, ThreadFunctionStatic, this);
     pthread_create((pthread_t*)handle_, &type, ThreadFunctionStatic, this);
-    #endif
+#endif
     return handle_ != 0;
     return handle_ != 0;
 }
 }
 
 
@@ -94,34 +99,33 @@ void Thread::Stop()
     // Check if already stopped
     // Check if already stopped
     if (!handle_)
     if (!handle_)
         return;
         return;
-    
+
     shouldRun_ = false;
     shouldRun_ = false;
-    #ifdef WIN32
+#ifdef WIN32
     WaitForSingleObject((HANDLE)handle_, INFINITE);
     WaitForSingleObject((HANDLE)handle_, INFINITE);
     CloseHandle((HANDLE)handle_);
     CloseHandle((HANDLE)handle_);
-//    #else
-    #elif !defined(EMSCRIPTEN)
- // note: emscripten doesn't have this function but doesn't use
- // threading anyway so #ifdef it out to prevent linker warnings
+#elif !defined(EMSCRIPTEN)
+    // note: emscripten doesn't have this function but doesn't use
+    // threading anyway so #ifdef it out to prevent linker warnings
     pthread_t* thread = (pthread_t*)handle_;
     pthread_t* thread = (pthread_t*)handle_;
     if (thread)
     if (thread)
         pthread_join(*thread, 0);
         pthread_join(*thread, 0);
     delete thread;
     delete thread;
-    #endif
+#endif
     handle_ = 0;
     handle_ = 0;
 }
 }
 
 
 void Thread::SetPriority(int priority)
 void Thread::SetPriority(int priority)
 {
 {
-    #ifdef WIN32
+#ifdef WIN32
     if (handle_)
     if (handle_)
         SetThreadPriority((HANDLE)handle_, priority);
         SetThreadPriority((HANDLE)handle_, priority);
-    #endif
-    #if defined(__linux__) && !defined(ANDROID) && !defined(EMSCRIPTEN)
+#endif
+#if defined(__linux__) && !defined(ANDROID) && !defined(EMSCRIPTEN)
     pthread_t* thread = (pthread_t*)handle_;
     pthread_t* thread = (pthread_t*)handle_;
     if (thread)
     if (thread)
         pthread_setschedprio(*thread, priority);
         pthread_setschedprio(*thread, priority);
-    #endif
+#endif
 }
 }
 
 
 void Thread::SetMainThread()
 void Thread::SetMainThread()
@@ -131,11 +135,11 @@ void Thread::SetMainThread()
 
 
 ThreadID Thread::GetCurrentThreadID()
 ThreadID Thread::GetCurrentThreadID()
 {
 {
-    #ifdef WIN32
+#ifdef WIN32
     return GetCurrentThreadId();
     return GetCurrentThreadId();
-    #else
+#else
     return pthread_self();
     return pthread_self();
-    #endif
+#endif
 }
 }
 
 
 bool Thread::IsMainThread()
 bool Thread::IsMainThread()

+ 11 - 5
Source/Urho3D/Core/Thread.h

@@ -22,6 +22,12 @@
 
 
 #pragma once
 #pragma once
 
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 #ifndef WIN32
 #ifndef WIN32
 #include <pthread.h>
 #include <pthread.h>
 typedef pthread_t ThreadID;
 typedef pthread_t ThreadID;
@@ -40,17 +46,17 @@ public:
     Thread();
     Thread();
     /// Destruct. If running, stop and wait for thread to finish.
     /// Destruct. If running, stop and wait for thread to finish.
     virtual ~Thread();
     virtual ~Thread();
-    
+
     /// The function to run in the thread.
     /// The function to run in the thread.
     virtual void ThreadFunction() = 0;
     virtual void ThreadFunction() = 0;
-    
+
     /// Start running the thread. Return true if successful, or false if already running or if can not create the thread.
     /// Start running the thread. Return true if successful, or false if already running or if can not create the thread.
     bool Run();
     bool Run();
     /// Set the running flag to false and wait for the thread to finish.
     /// Set the running flag to false and wait for the thread to finish.
     void Stop();
     void Stop();
     /// Set thread priority. The thread must have been started first.
     /// Set thread priority. The thread must have been started first.
     void SetPriority(int priority);
     void SetPriority(int priority);
-    
+
     /// Return whether thread exists.
     /// Return whether thread exists.
     bool IsStarted() const { return handle_ != 0; }
     bool IsStarted() const { return handle_ != 0; }
 
 
@@ -60,13 +66,13 @@ public:
     static ThreadID GetCurrentThreadID();
     static ThreadID GetCurrentThreadID();
     /// Return whether is executing in the main thread.
     /// Return whether is executing in the main thread.
     static bool IsMainThread();
     static bool IsMainThread();
-    
+
 protected:
 protected:
     /// Thread handle.
     /// Thread handle.
     void* handle_;
     void* handle_;
     /// Running flag.
     /// Running flag.
     volatile bool shouldRun_;
     volatile bool shouldRun_;
-    
+
     /// Main thread's thread ID.
     /// Main thread's thread ID.
     static ThreadID mainThreadID;
     static ThreadID mainThreadID;
 };
 };

+ 25 - 24
Source/Urho3D/Core/Timer.cpp

@@ -20,9 +20,10 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Core/CoreEvents.h"
 #include "../Core/CoreEvents.h"
 #include "../Core/Profiler.h"
 #include "../Core/Profiler.h"
-#include "../Core/Timer.h"
 
 
 #include <ctime>
 #include <ctime>
 
 
@@ -48,17 +49,17 @@ Time::Time(Context* context) :
     timeStep_(0.0f),
     timeStep_(0.0f),
     timerPeriod_(0)
     timerPeriod_(0)
 {
 {
-    #ifdef WIN32
+#ifdef WIN32
     LARGE_INTEGER frequency;
     LARGE_INTEGER frequency;
     if (QueryPerformanceFrequency(&frequency))
     if (QueryPerformanceFrequency(&frequency))
     {
     {
         HiresTimer::frequency = frequency.QuadPart;
         HiresTimer::frequency = frequency.QuadPart;
         HiresTimer::supported = true;
         HiresTimer::supported = true;
     }
     }
-    #else
+#else
     HiresTimer::frequency = 1000000;
     HiresTimer::frequency = 1000000;
     HiresTimer::supported = true;
     HiresTimer::supported = true;
-    #endif
+#endif
 }
 }
 
 
 Time::~Time()
 Time::~Time()
@@ -107,7 +108,7 @@ void Time::EndFrame()
 
 
 void Time::SetTimerPeriod(unsigned mSec)
 void Time::SetTimerPeriod(unsigned mSec)
 {
 {
-    #ifdef WIN32
+#ifdef WIN32
     if (timerPeriod_ > 0)
     if (timerPeriod_ > 0)
         timeEndPeriod(timerPeriod_);
         timeEndPeriod(timerPeriod_);
 
 
@@ -115,7 +116,7 @@ void Time::SetTimerPeriod(unsigned mSec)
 
 
     if (timerPeriod_ > 0)
     if (timerPeriod_ > 0)
         timeBeginPeriod(timerPeriod_);
         timeBeginPeriod(timerPeriod_);
-    #endif
+#endif
 }
 }
 
 
 float Time::GetElapsedTime()
 float Time::GetElapsedTime()
@@ -125,13 +126,13 @@ float Time::GetElapsedTime()
 
 
 unsigned Time::GetSystemTime()
 unsigned Time::GetSystemTime()
 {
 {
-    #ifdef WIN32
+#ifdef WIN32
     unsigned currentTime = (unsigned)timeGetTime();
     unsigned currentTime = (unsigned)timeGetTime();
-    #else
+#else
     struct timeval time;
     struct timeval time;
     gettimeofday(&time, NULL);
     gettimeofday(&time, NULL);
     unsigned currentTime = (unsigned)(time.tv_sec * 1000 + time.tv_usec / 1000);
     unsigned currentTime = (unsigned)(time.tv_sec * 1000 + time.tv_usec / 1000);
-    #endif
+#endif
 
 
     return currentTime;
     return currentTime;
 }
 }
@@ -151,11 +152,11 @@ String Time::GetTimeStamp()
 
 
 void Time::Sleep(unsigned mSec)
 void Time::Sleep(unsigned mSec)
 {
 {
-    #ifdef WIN32
+#ifdef WIN32
     ::Sleep(mSec);
     ::Sleep(mSec);
-    #else
+#else
     usleep(mSec * 1000);
     usleep(mSec * 1000);
-    #endif
+#endif
 }
 }
 
 
 Timer::Timer()
 Timer::Timer()
@@ -165,13 +166,13 @@ Timer::Timer()
 
 
 unsigned Timer::GetMSec(bool reset)
 unsigned Timer::GetMSec(bool reset)
 {
 {
-    #ifdef WIN32
+#ifdef WIN32
     unsigned currentTime = (unsigned)timeGetTime();
     unsigned currentTime = (unsigned)timeGetTime();
-    #else
+#else
     struct timeval time;
     struct timeval time;
     gettimeofday(&time, NULL);
     gettimeofday(&time, NULL);
     unsigned currentTime = (unsigned)(time.tv_sec * 1000 + time.tv_usec / 1000);
     unsigned currentTime = (unsigned)(time.tv_sec * 1000 + time.tv_usec / 1000);
-    #endif
+#endif
 
 
     unsigned elapsedTime = currentTime - startTime_;
     unsigned elapsedTime = currentTime - startTime_;
     if (reset)
     if (reset)
@@ -182,13 +183,13 @@ unsigned Timer::GetMSec(bool reset)
 
 
 void Timer::Reset()
 void Timer::Reset()
 {
 {
-    #ifdef WIN32
+#ifdef WIN32
     startTime_ = (unsigned)timeGetTime();
     startTime_ = (unsigned)timeGetTime();
-    #else
+#else
     struct timeval time;
     struct timeval time;
     gettimeofday(&time, NULL);
     gettimeofday(&time, NULL);
     startTime_ = (unsigned)(time.tv_sec * 1000 + time.tv_usec / 1000);
     startTime_ = (unsigned)(time.tv_sec * 1000 + time.tv_usec / 1000);
-    #endif
+#endif
 }
 }
 
 
 HiresTimer::HiresTimer()
 HiresTimer::HiresTimer()
@@ -200,7 +201,7 @@ long long HiresTimer::GetUSec(bool reset)
 {
 {
     long long currentTime;
     long long currentTime;
 
 
-    #ifdef WIN32
+#ifdef WIN32
     if (supported)
     if (supported)
     {
     {
         LARGE_INTEGER counter;
         LARGE_INTEGER counter;
@@ -209,11 +210,11 @@ long long HiresTimer::GetUSec(bool reset)
     }
     }
     else
     else
         currentTime = timeGetTime();
         currentTime = timeGetTime();
-    #else
+#else
     struct timeval time;
     struct timeval time;
     gettimeofday(&time, NULL);
     gettimeofday(&time, NULL);
     currentTime = time.tv_sec * 1000000LL + time.tv_usec;
     currentTime = time.tv_sec * 1000000LL + time.tv_usec;
-    #endif
+#endif
 
 
     long long elapsedTime = currentTime - startTime_;
     long long elapsedTime = currentTime - startTime_;
 
 
@@ -229,7 +230,7 @@ long long HiresTimer::GetUSec(bool reset)
 
 
 void HiresTimer::Reset()
 void HiresTimer::Reset()
 {
 {
-    #ifdef WIN32
+#ifdef WIN32
     if (supported)
     if (supported)
     {
     {
         LARGE_INTEGER counter;
         LARGE_INTEGER counter;
@@ -238,11 +239,11 @@ void HiresTimer::Reset()
     }
     }
     else
     else
         startTime_ = timeGetTime();
         startTime_ = timeGetTime();
-    #else
+#else
     struct timeval time;
     struct timeval time;
     gettimeofday(&time, NULL);
     gettimeofday(&time, NULL);
     startTime_ = time.tv_sec * 1000000LL + time.tv_usec;
     startTime_ = time.tv_sec * 1000000LL + time.tv_usec;
-    #endif
+#endif
 }
 }
 
 
 }
 }

+ 17 - 13
Source/Urho3D/Core/Timer.h

@@ -33,12 +33,12 @@ class URHO3D_API Timer
 public:
 public:
     /// Construct. Get the starting clock value.
     /// Construct. Get the starting clock value.
     Timer();
     Timer();
-    
+
     /// Return elapsed milliseconds and optionally reset.
     /// Return elapsed milliseconds and optionally reset.
     unsigned GetMSec(bool reset);
     unsigned GetMSec(bool reset);
     /// Reset the timer.
     /// Reset the timer.
     void Reset();
     void Reset();
-    
+
 private:
 private:
     /// Starting clock value in milliseconds.
     /// Starting clock value in milliseconds.
     unsigned startTime_;
     unsigned startTime_;
@@ -48,26 +48,27 @@ private:
 class URHO3D_API HiresTimer
 class URHO3D_API HiresTimer
 {
 {
     friend class Time;
     friend class Time;
-    
+
 public:
 public:
     /// Construct. Get the starting high-resolution clock value.
     /// Construct. Get the starting high-resolution clock value.
     HiresTimer();
     HiresTimer();
-    
+
     /// Return elapsed microseconds and optionally reset.
     /// Return elapsed microseconds and optionally reset.
     long long GetUSec(bool reset);
     long long GetUSec(bool reset);
     /// Reset the timer.
     /// Reset the timer.
     void Reset();
     void Reset();
-    
+
     /// Return if high-resolution timer is supported.
     /// Return if high-resolution timer is supported.
     static bool IsSupported() { return supported; }
     static bool IsSupported() { return supported; }
+
     /// Return high-resolution timer frequency if supported.
     /// Return high-resolution timer frequency if supported.
     static long long GetFrequency() { return frequency; }
     static long long GetFrequency() { return frequency; }
-    
+
 private:
 private:
     /// Starting clock value in CPU ticks.
     /// Starting clock value in CPU ticks.
     long long startTime_;
     long long startTime_;
-    
-     /// High-resolution timer support flag.
+
+    /// High-resolution timer support flag.
     static bool supported;
     static bool supported;
     /// High-resolution timer frequency.
     /// High-resolution timer frequency.
     static long long frequency;
     static long long frequency;
@@ -77,29 +78,32 @@ private:
 class URHO3D_API Time : public Object
 class URHO3D_API Time : public Object
 {
 {
     OBJECT(Time);
     OBJECT(Time);
-    
+
 public:
 public:
     /// Construct.
     /// Construct.
     Time(Context* context);
     Time(Context* context);
     /// Destruct. Reset the low-resolution timer period if set.
     /// Destruct. Reset the low-resolution timer period if set.
     virtual ~Time();
     virtual ~Time();
-    
+
     /// Begin new frame, with (last) frame duration in seconds and send frame start event.
     /// Begin new frame, with (last) frame duration in seconds and send frame start event.
     void BeginFrame(float timeStep);
     void BeginFrame(float timeStep);
     /// End frame. Increment total time and send frame end event.
     /// End frame. Increment total time and send frame end event.
     void EndFrame();
     void EndFrame();
     /// Set the low-resolution timer period in milliseconds. 0 resets to the default period.
     /// Set the low-resolution timer period in milliseconds. 0 resets to the default period.
     void SetTimerPeriod(unsigned mSec);
     void SetTimerPeriod(unsigned mSec);
-    
+
     /// Return frame number, starting from 1 once BeginFrame() is called for the first time.
     /// Return frame number, starting from 1 once BeginFrame() is called for the first time.
     unsigned GetFrameNumber() const { return frameNumber_; }
     unsigned GetFrameNumber() const { return frameNumber_; }
+
     /// Return current frame timestep as seconds.
     /// Return current frame timestep as seconds.
     float GetTimeStep() const { return timeStep_; }
     float GetTimeStep() const { return timeStep_; }
+
     /// Return current low-resolution timer period in milliseconds.
     /// Return current low-resolution timer period in milliseconds.
     unsigned GetTimerPeriod() const { return timerPeriod_; }
     unsigned GetTimerPeriod() const { return timerPeriod_; }
+
     /// Return elapsed time from program start as seconds.
     /// Return elapsed time from program start as seconds.
     float GetElapsedTime();
     float GetElapsedTime();
-    
+
     /// Get system time as milliseconds.
     /// Get system time as milliseconds.
     static unsigned GetSystemTime();
     static unsigned GetSystemTime();
     /// Get system time as seconds since 1.1.1970.
     /// Get system time as seconds since 1.1.1970.
@@ -108,7 +112,7 @@ public:
     static String GetTimeStamp();
     static String GetTimeStamp();
     /// Sleep for a number of milliseconds.
     /// Sleep for a number of milliseconds.
     static void Sleep(unsigned mSec);
     static void Sleep(unsigned mSec);
-    
+
 private:
 private:
     /// Elapsed time since program start.
     /// Elapsed time since program start.
     Timer elapsedTime_;
     Timer elapsedTime_;

+ 91 - 88
Source/Urho3D/Core/Variant.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Core/StringUtils.h"
 #include "../Core/StringUtils.h"
 
 
 #include <cstring>
 #include <cstring>
@@ -62,7 +64,7 @@ static const char* typeNames[] =
     0
     0
 };
 };
 
 
-Variant& Variant::operator = (const Variant& rhs)
+Variant& Variant::operator =(const Variant& rhs)
 {
 {
     SetType(rhs.GetType());
     SetType(rhs.GetType());
 
 
@@ -95,19 +97,19 @@ Variant& Variant::operator = (const Variant& rhs)
     case VAR_PTR:
     case VAR_PTR:
         *(reinterpret_cast<WeakPtr<RefCounted>*>(&value_)) = *(reinterpret_cast<const WeakPtr<RefCounted>*>(&rhs.value_));
         *(reinterpret_cast<WeakPtr<RefCounted>*>(&value_)) = *(reinterpret_cast<const WeakPtr<RefCounted>*>(&rhs.value_));
         break;
         break;
-        
+
     case VAR_MATRIX3:
     case VAR_MATRIX3:
         *(reinterpret_cast<Matrix3*>(value_.ptr_)) = *(reinterpret_cast<const Matrix3*>(rhs.value_.ptr_));
         *(reinterpret_cast<Matrix3*>(value_.ptr_)) = *(reinterpret_cast<const Matrix3*>(rhs.value_.ptr_));
         break;
         break;
-        
+
     case VAR_MATRIX3X4:
     case VAR_MATRIX3X4:
         *(reinterpret_cast<Matrix3x4*>(value_.ptr_)) = *(reinterpret_cast<const Matrix3x4*>(rhs.value_.ptr_));
         *(reinterpret_cast<Matrix3x4*>(value_.ptr_)) = *(reinterpret_cast<const Matrix3x4*>(rhs.value_.ptr_));
         break;
         break;
-        
+
     case VAR_MATRIX4:
     case VAR_MATRIX4:
         *(reinterpret_cast<Matrix4*>(value_.ptr_)) = *(reinterpret_cast<const Matrix4*>(rhs.value_.ptr_));
         *(reinterpret_cast<Matrix4*>(value_.ptr_)) = *(reinterpret_cast<const Matrix4*>(rhs.value_.ptr_));
         break;
         break;
-        
+
     default:
     default:
         value_ = rhs.value_;
         value_ = rhs.value_;
         break;
         break;
@@ -116,13 +118,13 @@ Variant& Variant::operator = (const Variant& rhs)
     return *this;
     return *this;
 }
 }
 
 
-bool Variant::operator == (const Variant& rhs) const
+bool Variant::operator ==(const Variant& rhs) const
 {
 {
     if (type_ == VAR_VOIDPTR || type_ == VAR_PTR)
     if (type_ == VAR_VOIDPTR || type_ == VAR_PTR)
         return GetVoidPtr() == rhs.GetVoidPtr();
         return GetVoidPtr() == rhs.GetVoidPtr();
     else if (type_ != rhs.type_)
     else if (type_ != rhs.type_)
         return false;
         return false;
-    
+
     switch (type_)
     switch (type_)
     {
     {
     case VAR_INT:
     case VAR_INT:
@@ -150,7 +152,8 @@ bool Variant::operator == (const Variant& rhs) const
         return *(reinterpret_cast<const String*>(&value_)) == *(reinterpret_cast<const String*>(&rhs.value_));
         return *(reinterpret_cast<const String*>(&value_)) == *(reinterpret_cast<const String*>(&rhs.value_));
 
 
     case VAR_BUFFER:
     case VAR_BUFFER:
-        return *(reinterpret_cast<const PODVector<unsigned char>*>(&value_)) == *(reinterpret_cast<const PODVector<unsigned char>*>(&rhs.value_));
+        return *(reinterpret_cast<const PODVector<unsigned char>*>(&value_)) ==
+               *(reinterpret_cast<const PODVector<unsigned char>*>(&rhs.value_));
 
 
     case VAR_RESOURCEREF:
     case VAR_RESOURCEREF:
         return *(reinterpret_cast<const ResourceRef*>(&value_)) == *(reinterpret_cast<const ResourceRef*>(&rhs.value_));
         return *(reinterpret_cast<const ResourceRef*>(&value_)) == *(reinterpret_cast<const ResourceRef*>(&rhs.value_));
@@ -243,11 +246,11 @@ void Variant::FromString(VariantType type, const char* value)
         break;
         break;
 
 
     case VAR_BUFFER:
     case VAR_BUFFER:
-        {
-            SetType(VAR_BUFFER);
-            PODVector<unsigned char>& buffer = *(reinterpret_cast<PODVector<unsigned char>*>(&value_));
-            StringToBuffer(buffer, value);
-        }
+    {
+        SetType(VAR_BUFFER);
+        PODVector<unsigned char>& buffer = *(reinterpret_cast<PODVector<unsigned char>*>(&value_));
+        StringToBuffer(buffer, value);
+    }
         break;
         break;
 
 
     case VAR_VOIDPTR:
     case VAR_VOIDPTR:
@@ -256,31 +259,31 @@ void Variant::FromString(VariantType type, const char* value)
         break;
         break;
 
 
     case VAR_RESOURCEREF:
     case VAR_RESOURCEREF:
+    {
+        Vector<String> values = String::Split(value, ';');
+        if (values.Size() == 2)
         {
         {
-            Vector<String> values = String::Split(value, ';');
-            if (values.Size() == 2)
-            {
-                SetType(VAR_RESOURCEREF);
-                ResourceRef& ref = *(reinterpret_cast<ResourceRef*>(&value_));
-                ref.type_ = values[0];
-                ref.name_ = values[1];
-            }
+            SetType(VAR_RESOURCEREF);
+            ResourceRef& ref = *(reinterpret_cast<ResourceRef*>(&value_));
+            ref.type_ = values[0];
+            ref.name_ = values[1];
         }
         }
+    }
         break;
         break;
 
 
     case VAR_RESOURCEREFLIST:
     case VAR_RESOURCEREFLIST:
+    {
+        Vector<String> values = String::Split(value, ';');
+        if (values.Size() >= 1)
         {
         {
-            Vector<String> values = String::Split(value, ';');
-            if (values.Size() >= 1)
-            {
-                SetType(VAR_RESOURCEREFLIST);
-                ResourceRefList& refList = *(reinterpret_cast<ResourceRefList*>(&value_));
-                refList.type_ = values[0];
-                refList.names_.Resize(values.Size() - 1);
-                for (unsigned i = 1; i < values.Size(); ++i)
-                    refList.names_[i - 1] = values[i];
-            }
+            SetType(VAR_RESOURCEREFLIST);
+            ResourceRefList& refList = *(reinterpret_cast<ResourceRefList*>(&value_));
+            refList.type_ = values[0];
+            refList.names_.Resize(values.Size() - 1);
+            for (unsigned i = 1; i < values.Size(); ++i)
+                refList.names_[i - 1] = values[i];
         }
         }
+    }
         break;
         break;
 
 
     case VAR_INTRECT:
     case VAR_INTRECT:
@@ -295,15 +298,15 @@ void Variant::FromString(VariantType type, const char* value)
         // From string to RefCounted pointer not supported, set to null
         // From string to RefCounted pointer not supported, set to null
         *this = (RefCounted*)0;
         *this = (RefCounted*)0;
         break;
         break;
-        
+
     case VAR_MATRIX3:
     case VAR_MATRIX3:
         *this = ToMatrix3(value);
         *this = ToMatrix3(value);
         break;
         break;
-        
+
     case VAR_MATRIX3X4:
     case VAR_MATRIX3X4:
         *this = ToMatrix3x4(value);
         *this = ToMatrix3x4(value);
         break;
         break;
-        
+
     case VAR_MATRIX4:
     case VAR_MATRIX4:
         *this = ToMatrix4(value);
         *this = ToMatrix4(value);
         break;
         break;
@@ -366,12 +369,12 @@ String Variant::ToString() const
         return *(reinterpret_cast<const String*>(&value_));
         return *(reinterpret_cast<const String*>(&value_));
 
 
     case VAR_BUFFER:
     case VAR_BUFFER:
-        {
-            const PODVector<unsigned char>& buffer = *(reinterpret_cast<const PODVector<unsigned char>*>(&value_));
-            String ret;
-            BufferToString(ret, buffer.Begin().ptr_, buffer.Size());
-            return ret;
-        }
+    {
+        const PODVector<unsigned char>& buffer = *(reinterpret_cast<const PODVector<unsigned char>*>(&value_));
+        String ret;
+        BufferToString(ret, buffer.Begin().ptr_, buffer.Size());
+        return ret;
+    }
 
 
     case VAR_VOIDPTR:
     case VAR_VOIDPTR:
     case VAR_PTR:
     case VAR_PTR:
@@ -395,7 +398,7 @@ String Variant::ToString() const
 
 
     case VAR_MATRIX3X4:
     case VAR_MATRIX3X4:
         return (reinterpret_cast<const Matrix3x4*>(value_.ptr_))->ToString();
         return (reinterpret_cast<const Matrix3x4*>(value_.ptr_))->ToString();
-        
+
     case VAR_MATRIX4:
     case VAR_MATRIX4:
         return (reinterpret_cast<const Matrix4*>(value_.ptr_))->ToString();
         return (reinterpret_cast<const Matrix4*>(value_.ptr_))->ToString();
 
 
@@ -470,13 +473,13 @@ bool Variant::IsZero() const
 
 
     case VAR_PTR:
     case VAR_PTR:
         return *reinterpret_cast<const WeakPtr<RefCounted>*>(&value_) == (RefCounted*)0;
         return *reinterpret_cast<const WeakPtr<RefCounted>*>(&value_) == (RefCounted*)0;
-        
+
     case VAR_MATRIX3:
     case VAR_MATRIX3:
         return *reinterpret_cast<const Matrix3*>(value_.ptr_) == Matrix3::IDENTITY;
         return *reinterpret_cast<const Matrix3*>(value_.ptr_) == Matrix3::IDENTITY;
-        
+
     case VAR_MATRIX3X4:
     case VAR_MATRIX3X4:
         return *reinterpret_cast<const Matrix3x4*>(value_.ptr_) == Matrix3x4::IDENTITY;
         return *reinterpret_cast<const Matrix3x4*>(value_.ptr_) == Matrix3x4::IDENTITY;
-        
+
     case VAR_MATRIX4:
     case VAR_MATRIX4:
         return *reinterpret_cast<const Matrix4*>(value_.ptr_) == Matrix4::IDENTITY;
         return *reinterpret_cast<const Matrix4*>(value_.ptr_) == Matrix4::IDENTITY;
         
         
@@ -522,19 +525,19 @@ void Variant::SetType(VariantType newType)
     case VAR_PTR:
     case VAR_PTR:
         (reinterpret_cast<WeakPtr<RefCounted>*>(&value_))->~WeakPtr<RefCounted>();
         (reinterpret_cast<WeakPtr<RefCounted>*>(&value_))->~WeakPtr<RefCounted>();
         break;
         break;
-        
+
     case VAR_MATRIX3:
     case VAR_MATRIX3:
         delete reinterpret_cast<Matrix3*>(value_.ptr_);
         delete reinterpret_cast<Matrix3*>(value_.ptr_);
         break;
         break;
-        
+
     case VAR_MATRIX3X4:
     case VAR_MATRIX3X4:
         delete reinterpret_cast<Matrix3x4*>(value_.ptr_);
         delete reinterpret_cast<Matrix3x4*>(value_.ptr_);
         break;
         break;
-        
+
     case VAR_MATRIX4:
     case VAR_MATRIX4:
         delete reinterpret_cast<Matrix4*>(value_.ptr_);
         delete reinterpret_cast<Matrix4*>(value_.ptr_);
         break;
         break;
-        
+
     default:
     default:
         break;
         break;
     }
     }
@@ -570,200 +573,200 @@ void Variant::SetType(VariantType newType)
     case VAR_PTR:
     case VAR_PTR:
         new(reinterpret_cast<WeakPtr<RefCounted>*>(&value_)) WeakPtr<RefCounted>();
         new(reinterpret_cast<WeakPtr<RefCounted>*>(&value_)) WeakPtr<RefCounted>();
         break;
         break;
-        
+
     case VAR_MATRIX3:
     case VAR_MATRIX3:
         value_.ptr_ = new Matrix3();
         value_.ptr_ = new Matrix3();
         break;
         break;
-        
+
     case VAR_MATRIX3X4:
     case VAR_MATRIX3X4:
         value_.ptr_ = new Matrix3x4();
         value_.ptr_ = new Matrix3x4();
         break;
         break;
-        
+
     case VAR_MATRIX4:
     case VAR_MATRIX4:
         value_.ptr_ = new Matrix4();
         value_.ptr_ = new Matrix4();
         break;
         break;
-        
+
     default:
     default:
         break;
         break;
     }
     }
 }
 }
 
 
-template<> int Variant::Get<int>() const
+template <> int Variant::Get<int>() const
 {
 {
     return GetInt();
     return GetInt();
 }
 }
 
 
-template<> unsigned Variant::Get<unsigned>() const
+template <> unsigned Variant::Get<unsigned>() const
 {
 {
     return GetUInt();
     return GetUInt();
 }
 }
 
 
-template<> StringHash Variant::Get<StringHash>() const
+template <> StringHash Variant::Get<StringHash>() const
 {
 {
     return GetStringHash();
     return GetStringHash();
 }
 }
 
 
-template<> bool Variant::Get<bool>() const
+template <> bool Variant::Get<bool>() const
 {
 {
     return GetBool();
     return GetBool();
 }
 }
 
 
-template<> float Variant::Get<float>() const
+template <> float Variant::Get<float>() const
 {
 {
     return GetFloat();
     return GetFloat();
 }
 }
 
 
-template<> double Variant::Get<double>() const
+template <> double Variant::Get<double>() const
 {
 {
     return GetDouble();
     return GetDouble();
 }
 }
 
 
-template<> const Vector2& Variant::Get<const Vector2&>() const
+template <> const Vector2& Variant::Get<const Vector2&>() const
 {
 {
     return GetVector2();
     return GetVector2();
 }
 }
 
 
-template<> const Vector3& Variant::Get<const Vector3&>() const
+template <> const Vector3& Variant::Get<const Vector3&>() const
 {
 {
     return GetVector3();
     return GetVector3();
 }
 }
 
 
-template<> const Vector4& Variant::Get<const Vector4&>() const
+template <> const Vector4& Variant::Get<const Vector4&>() const
 {
 {
     return GetVector4();
     return GetVector4();
 }
 }
 
 
-template<> const Quaternion& Variant::Get<const Quaternion&>() const
+template <> const Quaternion& Variant::Get<const Quaternion&>() const
 {
 {
     return GetQuaternion();
     return GetQuaternion();
 }
 }
 
 
-template<> const Color& Variant::Get<const Color&>() const
+template <> const Color& Variant::Get<const Color&>() const
 {
 {
     return GetColor();
     return GetColor();
 }
 }
 
 
-template<> const String& Variant::Get<const String&>() const
+template <> const String& Variant::Get<const String&>() const
 {
 {
     return GetString();
     return GetString();
 }
 }
 
 
-template<> const IntRect& Variant::Get<const IntRect&>() const
+template <> const IntRect& Variant::Get<const IntRect&>() const
 {
 {
     return GetIntRect();
     return GetIntRect();
 }
 }
 
 
-template<> const IntVector2& Variant::Get<const IntVector2&>() const
+template <> const IntVector2& Variant::Get<const IntVector2&>() const
 {
 {
     return GetIntVector2();
     return GetIntVector2();
 }
 }
 
 
-template<> const PODVector<unsigned char>& Variant::Get<const PODVector<unsigned char>& >() const
+template <> const PODVector<unsigned char>& Variant::Get<const PODVector<unsigned char>&>() const
 {
 {
     return GetBuffer();
     return GetBuffer();
 }
 }
 
 
-template<> void* Variant::Get<void*>() const
+template <> void* Variant::Get<void*>() const
 {
 {
     return GetVoidPtr();
     return GetVoidPtr();
 }
 }
 
 
-template<> RefCounted* Variant::Get<RefCounted*>() const
+template <> RefCounted* Variant::Get<RefCounted*>() const
 {
 {
     return GetPtr();
     return GetPtr();
 }
 }
 
 
-template<> const Matrix3& Variant::Get<const Matrix3&>() const
+template <> const Matrix3& Variant::Get<const Matrix3&>() const
 {
 {
     return GetMatrix3();
     return GetMatrix3();
 }
 }
 
 
-template<> const Matrix3x4& Variant::Get<const Matrix3x4&>() const
+template <> const Matrix3x4& Variant::Get<const Matrix3x4&>() const
 {
 {
     return GetMatrix3x4();
     return GetMatrix3x4();
 }
 }
 
 
-template<> const Matrix4& Variant::Get<const Matrix4&>() const
+template <> const Matrix4& Variant::Get<const Matrix4&>() const
 {
 {
     return GetMatrix4();
     return GetMatrix4();
 }
 }
 
 
-template<> ResourceRef Variant::Get<ResourceRef>() const
+template <> ResourceRef Variant::Get<ResourceRef>() const
 {
 {
     return GetResourceRef();
     return GetResourceRef();
 }
 }
 
 
-template<> ResourceRefList Variant::Get<ResourceRefList>() const
+template <> ResourceRefList Variant::Get<ResourceRefList>() const
 {
 {
     return GetResourceRefList();
     return GetResourceRefList();
 }
 }
 
 
-template<> VariantVector Variant::Get<VariantVector>() const
+template <> VariantVector Variant::Get<VariantVector>() const
 {
 {
     return GetVariantVector();
     return GetVariantVector();
 }
 }
 
 
-template<> VariantMap Variant::Get<VariantMap>() const
+template <> VariantMap Variant::Get<VariantMap>() const
 {
 {
     return GetVariantMap();
     return GetVariantMap();
 }
 }
 
 
-template<> Vector2 Variant::Get<Vector2>() const
+template <> Vector2 Variant::Get<Vector2>() const
 {
 {
     return GetVector2();
     return GetVector2();
 }
 }
 
 
-template<> Vector3 Variant::Get<Vector3>() const
+template <> Vector3 Variant::Get<Vector3>() const
 {
 {
     return GetVector3();
     return GetVector3();
 }
 }
 
 
-template<> Vector4 Variant::Get<Vector4>() const
+template <> Vector4 Variant::Get<Vector4>() const
 {
 {
     return GetVector4();
     return GetVector4();
 }
 }
 
 
-template<> Quaternion Variant::Get<Quaternion>() const
+template <> Quaternion Variant::Get<Quaternion>() const
 {
 {
     return GetQuaternion();
     return GetQuaternion();
 }
 }
 
 
-template<> Color Variant::Get<Color>() const
+template <> Color Variant::Get<Color>() const
 {
 {
     return GetColor();
     return GetColor();
 }
 }
 
 
-template<> String Variant::Get<String>() const
+template <> String Variant::Get<String>() const
 {
 {
     return GetString();
     return GetString();
 }
 }
 
 
-template<> IntRect Variant::Get<IntRect>() const
+template <> IntRect Variant::Get<IntRect>() const
 {
 {
     return GetIntRect();
     return GetIntRect();
 }
 }
 
 
-template<> IntVector2 Variant::Get<IntVector2>() const
+template <> IntVector2 Variant::Get<IntVector2>() const
 {
 {
     return GetIntVector2();
     return GetIntVector2();
 }
 }
 
 
-template<> PODVector<unsigned char> Variant::Get<PODVector<unsigned char> >() const
+template <> PODVector<unsigned char> Variant::Get<PODVector<unsigned char> >() const
 {
 {
     return GetBuffer();
     return GetBuffer();
 }
 }
 
 
-template<> Matrix3 Variant::Get<Matrix3>() const
+template <> Matrix3 Variant::Get<Matrix3>() const
 {
 {
     return GetMatrix3();
     return GetMatrix3();
 }
 }
 
 
-template<> Matrix3x4 Variant::Get<Matrix3x4>() const
+template <> Matrix3x4 Variant::Get<Matrix3x4>() const
 {
 {
     return GetMatrix3x4();
     return GetMatrix3x4();
 }
 }
 
 
-template<> Matrix4 Variant::Get<Matrix4>() const
+template <> Matrix4 Variant::Get<Matrix4>() const
 {
 {
     return GetMatrix4();
     return GetMatrix4();
 }
 }

+ 309 - 131
Source/Urho3D/Core/Variant.h

@@ -22,11 +22,11 @@
 
 
 #pragma once
 #pragma once
 
 
-#include "../Math/Color.h"
 #include "../Container/HashMap.h"
 #include "../Container/HashMap.h"
+#include "../Container/Ptr.h"
+#include "../Math/Color.h"
 #include "../Math/Matrix3.h"
 #include "../Math/Matrix3.h"
 #include "../Math/Matrix3x4.h"
 #include "../Math/Matrix3x4.h"
-#include "../Container/Ptr.h"
 #include "../Math/Rect.h"
 #include "../Math/Rect.h"
 #include "../Math/StringHash.h"
 #include "../Math/StringHash.h"
 
 
@@ -129,9 +129,10 @@ struct URHO3D_API ResourceRef
     String name_;
     String name_;
 
 
     /// Test for equality with another reference.
     /// Test for equality with another reference.
-    bool operator == (const ResourceRef& rhs) const { return type_ == rhs.type_ && name_ == rhs.name_; }
+    bool operator ==(const ResourceRef& rhs) const { return type_ == rhs.type_ && name_ == rhs.name_; }
+
     /// Test for inequality with another reference.
     /// Test for inequality with another reference.
-    bool operator != (const ResourceRef& rhs) const { return type_ != rhs.type_ || name_ != rhs.name_; }
+    bool operator !=(const ResourceRef& rhs) const { return type_ != rhs.type_ || name_ != rhs.name_; }
 };
 };
 
 
 /// %List of typed resource references.
 /// %List of typed resource references.
@@ -147,6 +148,7 @@ struct URHO3D_API ResourceRefList
         type_(type)
         type_(type)
     {
     {
     }
     }
+
     /// Construct with type and id list.
     /// Construct with type and id list.
     ResourceRefList(StringHash type, const Vector<String>& names) :
     ResourceRefList(StringHash type, const Vector<String>& names) :
         type_(type),
         type_(type),
@@ -160,9 +162,10 @@ struct URHO3D_API ResourceRefList
     Vector<String> names_;
     Vector<String> names_;
 
 
     /// Test for equality with another reference list.
     /// Test for equality with another reference list.
-    bool operator == (const ResourceRefList& rhs) const { return type_ == rhs.type_ && names_ == rhs.names_; }
+    bool operator ==(const ResourceRefList& rhs) const { return type_ == rhs.type_ && names_ == rhs.names_; }
+
     /// Test for inequality with another reference list.
     /// Test for inequality with another reference list.
-    bool operator != (const ResourceRefList& rhs) const { return type_ != rhs.type_ || names_ != rhs.names_; }
+    bool operator !=(const ResourceRefList& rhs) const { return type_ != rhs.type_ || names_ != rhs.names_; }
 };
 };
 
 
 class Variant;
 class Variant;
@@ -329,7 +332,7 @@ public:
     {
     {
         *this = value;
         *this = value;
     }
     }
-    
+
     /// Construct from a RefCounted pointer. The object will be stored internally in a WeakPtr so that its expiration can be detected safely.
     /// Construct from a RefCounted pointer. The object will be stored internally in a WeakPtr so that its expiration can be detected safely.
     Variant(RefCounted* value) :
     Variant(RefCounted* value) :
         type_(VAR_NONE)
         type_(VAR_NONE)
@@ -357,7 +360,7 @@ public:
     {
     {
         *this = value;
         *this = value;
     }
     }
-    
+
     /// Construct from type and value.
     /// Construct from type and value.
     Variant(const String& type, const String& value) :
     Variant(const String& type, const String& value) :
         type_(VAR_NONE)
         type_(VAR_NONE)
@@ -406,10 +409,10 @@ public:
     }
     }
 
 
     /// Assign from another variant.
     /// Assign from another variant.
-    Variant& operator = (const Variant& rhs);
+    Variant& operator =(const Variant& rhs);
 
 
     /// Assign from an integer.
     /// Assign from an integer.
-    Variant& operator = (int rhs)
+    Variant& operator =(int rhs)
     {
     {
         SetType(VAR_INT);
         SetType(VAR_INT);
         value_.int_ = rhs;
         value_.int_ = rhs;
@@ -417,7 +420,7 @@ public:
     }
     }
 
 
     /// Assign from an unsigned integer.
     /// Assign from an unsigned integer.
-    Variant& operator = (unsigned rhs)
+    Variant& operator =(unsigned rhs)
     {
     {
         SetType(VAR_INT);
         SetType(VAR_INT);
         value_.int_ = (int)rhs;
         value_.int_ = (int)rhs;
@@ -425,7 +428,7 @@ public:
     }
     }
 
 
     /// Assign from a StringHash (convert to integer.)
     /// Assign from a StringHash (convert to integer.)
-    Variant& operator = (const StringHash& rhs)
+    Variant& operator =(const StringHash& rhs)
     {
     {
         SetType(VAR_INT);
         SetType(VAR_INT);
         value_.int_ = (int)rhs.Value();
         value_.int_ = (int)rhs.Value();
@@ -433,7 +436,7 @@ public:
     }
     }
 
 
     /// Assign from a bool.
     /// Assign from a bool.
-    Variant& operator = (bool rhs)
+    Variant& operator =(bool rhs)
     {
     {
         SetType(VAR_BOOL);
         SetType(VAR_BOOL);
         value_.bool_ = rhs;
         value_.bool_ = rhs;
@@ -441,7 +444,7 @@ public:
     }
     }
 
 
     /// Assign from a float.
     /// Assign from a float.
-    Variant& operator = (float rhs)
+    Variant& operator =(float rhs)
     {
     {
         SetType(VAR_FLOAT);
         SetType(VAR_FLOAT);
         value_.float_ = rhs;
         value_.float_ = rhs;
@@ -457,7 +460,7 @@ public:
     }
     }
 
 
     /// Assign from a Vector2.
     /// Assign from a Vector2.
-    Variant& operator = (const Vector2& rhs)
+    Variant& operator =(const Vector2& rhs)
     {
     {
         SetType(VAR_VECTOR2);
         SetType(VAR_VECTOR2);
         *(reinterpret_cast<Vector2*>(&value_)) = rhs;
         *(reinterpret_cast<Vector2*>(&value_)) = rhs;
@@ -465,7 +468,7 @@ public:
     }
     }
 
 
     /// Assign from a Vector3.
     /// Assign from a Vector3.
-    Variant& operator = (const Vector3& rhs)
+    Variant& operator =(const Vector3& rhs)
     {
     {
         SetType(VAR_VECTOR3);
         SetType(VAR_VECTOR3);
         *(reinterpret_cast<Vector3*>(&value_)) = rhs;
         *(reinterpret_cast<Vector3*>(&value_)) = rhs;
@@ -473,7 +476,7 @@ public:
     }
     }
 
 
     /// Assign from a Vector4.
     /// Assign from a Vector4.
-    Variant& operator = (const Vector4& rhs)
+    Variant& operator =(const Vector4& rhs)
     {
     {
         SetType(VAR_VECTOR4);
         SetType(VAR_VECTOR4);
         *(reinterpret_cast<Vector4*>(&value_)) = rhs;
         *(reinterpret_cast<Vector4*>(&value_)) = rhs;
@@ -481,7 +484,7 @@ public:
     }
     }
 
 
     /// Assign from a quaternion.
     /// Assign from a quaternion.
-    Variant& operator = (const Quaternion& rhs)
+    Variant& operator =(const Quaternion& rhs)
     {
     {
         SetType(VAR_QUATERNION);
         SetType(VAR_QUATERNION);
         *(reinterpret_cast<Quaternion*>(&value_)) = rhs;
         *(reinterpret_cast<Quaternion*>(&value_)) = rhs;
@@ -489,7 +492,7 @@ public:
     }
     }
 
 
     /// Assign from a color.
     /// Assign from a color.
-    Variant& operator = (const Color& rhs)
+    Variant& operator =(const Color& rhs)
     {
     {
         SetType(VAR_COLOR);
         SetType(VAR_COLOR);
         *(reinterpret_cast<Color*>(&value_)) = rhs;
         *(reinterpret_cast<Color*>(&value_)) = rhs;
@@ -497,7 +500,7 @@ public:
     }
     }
 
 
     /// Assign from a string.
     /// Assign from a string.
-    Variant& operator = (const String& rhs)
+    Variant& operator =(const String& rhs)
     {
     {
         SetType(VAR_STRING);
         SetType(VAR_STRING);
         *(reinterpret_cast<String*>(&value_)) = rhs;
         *(reinterpret_cast<String*>(&value_)) = rhs;
@@ -505,7 +508,7 @@ public:
     }
     }
 
 
     /// Assign from a C string.
     /// Assign from a C string.
-    Variant& operator = (const char* rhs)
+    Variant& operator =(const char* rhs)
     {
     {
         SetType(VAR_STRING);
         SetType(VAR_STRING);
         *(reinterpret_cast<String*>(&value_)) = String(rhs);
         *(reinterpret_cast<String*>(&value_)) = String(rhs);
@@ -513,7 +516,7 @@ public:
     }
     }
 
 
     /// Assign from a buffer.
     /// Assign from a buffer.
-    Variant& operator = (const PODVector<unsigned char>& rhs)
+    Variant& operator =(const PODVector<unsigned char>& rhs)
     {
     {
         SetType(VAR_BUFFER);
         SetType(VAR_BUFFER);
         *(reinterpret_cast<PODVector<unsigned char>*>(&value_)) = rhs;
         *(reinterpret_cast<PODVector<unsigned char>*>(&value_)) = rhs;
@@ -521,7 +524,7 @@ public:
     }
     }
 
 
     /// Assign from a void pointer.
     /// Assign from a void pointer.
-    Variant& operator = (void* rhs)
+    Variant& operator =(void* rhs)
     {
     {
         SetType(VAR_VOIDPTR);
         SetType(VAR_VOIDPTR);
         value_.ptr_ = rhs;
         value_.ptr_ = rhs;
@@ -529,7 +532,7 @@ public:
     }
     }
 
 
     /// Assign from a resource reference.
     /// Assign from a resource reference.
-    Variant& operator = (const ResourceRef& rhs)
+    Variant& operator =(const ResourceRef& rhs)
     {
     {
         SetType(VAR_RESOURCEREF);
         SetType(VAR_RESOURCEREF);
         *(reinterpret_cast<ResourceRef*>(&value_)) = rhs;
         *(reinterpret_cast<ResourceRef*>(&value_)) = rhs;
@@ -537,7 +540,7 @@ public:
     }
     }
 
 
     /// Assign from a resource reference list.
     /// Assign from a resource reference list.
-    Variant& operator = (const ResourceRefList& rhs)
+    Variant& operator =(const ResourceRefList& rhs)
     {
     {
         SetType(VAR_RESOURCEREFLIST);
         SetType(VAR_RESOURCEREFLIST);
         *(reinterpret_cast<ResourceRefList*>(&value_)) = rhs;
         *(reinterpret_cast<ResourceRefList*>(&value_)) = rhs;
@@ -545,7 +548,7 @@ public:
     }
     }
 
 
     /// Assign from a variant vector.
     /// Assign from a variant vector.
-    Variant& operator = (const VariantVector& rhs)
+    Variant& operator =(const VariantVector& rhs)
     {
     {
         SetType(VAR_VARIANTVECTOR);
         SetType(VAR_VARIANTVECTOR);
         *(reinterpret_cast<VariantVector*>(&value_)) = rhs;
         *(reinterpret_cast<VariantVector*>(&value_)) = rhs;
@@ -553,7 +556,7 @@ public:
     }
     }
 
 
     /// Assign from a variant map.
     /// Assign from a variant map.
-    Variant& operator = (const VariantMap& rhs)
+    Variant& operator =(const VariantMap& rhs)
     {
     {
         SetType(VAR_VARIANTMAP);
         SetType(VAR_VARIANTMAP);
         *(reinterpret_cast<VariantMap*>(&value_)) = rhs;
         *(reinterpret_cast<VariantMap*>(&value_)) = rhs;
@@ -561,7 +564,7 @@ public:
     }
     }
 
 
     /// Assign from an integer rect.
     /// Assign from an integer rect.
-    Variant& operator = (const IntRect& rhs)
+    Variant& operator =(const IntRect& rhs)
     {
     {
         SetType(VAR_INTRECT);
         SetType(VAR_INTRECT);
         *(reinterpret_cast<IntRect*>(&value_)) = rhs;
         *(reinterpret_cast<IntRect*>(&value_)) = rhs;
@@ -569,74 +572,107 @@ public:
     }
     }
 
 
     /// Assign from an IntVector2.
     /// Assign from an IntVector2.
-    Variant& operator = (const IntVector2& rhs)
+    Variant& operator =(const IntVector2& rhs)
     {
     {
         SetType(VAR_INTVECTOR2);
         SetType(VAR_INTVECTOR2);
         *(reinterpret_cast<IntVector2*>(&value_)) = rhs;
         *(reinterpret_cast<IntVector2*>(&value_)) = rhs;
         return *this;
         return *this;
     }
     }
-    
+
     /// Assign from a RefCounted pointer. The object will be stored internally in a WeakPtr so that its expiration can be detected safely.
     /// Assign from a RefCounted pointer. The object will be stored internally in a WeakPtr so that its expiration can be detected safely.
-    Variant& operator = (RefCounted* rhs)
+    Variant& operator =(RefCounted* rhs)
     {
     {
         SetType(VAR_PTR);
         SetType(VAR_PTR);
         *(reinterpret_cast<WeakPtr<RefCounted>*>(&value_)) = rhs;
         *(reinterpret_cast<WeakPtr<RefCounted>*>(&value_)) = rhs;
         return *this;
         return *this;
     }
     }
-    
+
     /// Assign from a Matrix3.
     /// Assign from a Matrix3.
-    Variant& operator = (const Matrix3& rhs)
+    Variant& operator =(const Matrix3& rhs)
     {
     {
         SetType(VAR_MATRIX3);
         SetType(VAR_MATRIX3);
         *(reinterpret_cast<Matrix3*>(value_.ptr_)) = rhs;
         *(reinterpret_cast<Matrix3*>(value_.ptr_)) = rhs;
         return *this;
         return *this;
     }
     }
-    
+
     /// Assign from a Matrix3x4.
     /// Assign from a Matrix3x4.
-    Variant& operator = (const Matrix3x4& rhs)
+    Variant& operator =(const Matrix3x4& rhs)
     {
     {
         SetType(VAR_MATRIX3X4);
         SetType(VAR_MATRIX3X4);
         *(reinterpret_cast<Matrix3x4*>(value_.ptr_)) = rhs;
         *(reinterpret_cast<Matrix3x4*>(value_.ptr_)) = rhs;
         return *this;
         return *this;
     }
     }
-    
+
     /// Assign from a Matrix4.
     /// Assign from a Matrix4.
-    Variant& operator = (const Matrix4& rhs)
+    Variant& operator =(const Matrix4& rhs)
     {
     {
         SetType(VAR_MATRIX4);
         SetType(VAR_MATRIX4);
         *(reinterpret_cast<Matrix4*>(value_.ptr_)) = rhs;
         *(reinterpret_cast<Matrix4*>(value_.ptr_)) = rhs;
         return *this;
         return *this;
     }
     }
-    
+
     /// Test for equality with another variant.
     /// Test for equality with another variant.
-    bool operator == (const Variant& rhs) const;
+    bool operator ==(const Variant& rhs) const;
+
     /// Test for equality with an integer. To return true, both the type and value must match.
     /// Test for equality with an integer. To return true, both the type and value must match.
-    bool operator == (int rhs) const { return type_ == VAR_INT ? value_.int_ == rhs : false; }
+    bool operator ==(int rhs) const { return type_ == VAR_INT ? value_.int_ == rhs : false; }
+
     /// Test for equality with an unsigned integer. To return true, both the type and value must match.
     /// Test for equality with an unsigned integer. To return true, both the type and value must match.
-    bool operator == (unsigned rhs) const { return type_ == VAR_INT ? value_.int_ == (int)rhs : false; }
+    bool operator ==(unsigned rhs) const { return type_ == VAR_INT ? value_.int_ == (int)rhs : false; }
+
     /// Test for equality with a bool. To return true, both the type and value must match.
     /// Test for equality with a bool. To return true, both the type and value must match.
-    bool operator == (bool rhs) const { return type_ == VAR_BOOL ? value_.bool_ == rhs : false; }
+    bool operator ==(bool rhs) const { return type_ == VAR_BOOL ? value_.bool_ == rhs : false; }
+
     /// Test for equality with a float. To return true, both the type and value must match.
     /// Test for equality with a float. To return true, both the type and value must match.
-    bool operator == (float rhs) const { return type_ == VAR_FLOAT ? value_.float_ == rhs : false; }
+    bool operator ==(float rhs) const { return type_ == VAR_FLOAT ? value_.float_ == rhs : false; }
+
     /// Test for equality with a double. To return true, both the type and value must match.
     /// Test for equality with a double. To return true, both the type and value must match.
-    bool operator == (double rhs) const { return type_ == VAR_DOUBLE ? *(reinterpret_cast<const double*>(&value_)) == rhs : false; }
+    bool operator ==(double rhs) const { return type_ == VAR_DOUBLE ? *(reinterpret_cast<const double*>(&value_)) == rhs : false; }
+
     /// Test for equality with a Vector2. To return true, both the type and value must match.
     /// Test for equality with a Vector2. To return true, both the type and value must match.
-    bool operator == (const Vector2& rhs) const { return type_ == VAR_VECTOR2 ? *(reinterpret_cast<const Vector2*>(&value_)) == rhs : false; }
+    bool operator ==(const Vector2& rhs) const
+    {
+        return type_ == VAR_VECTOR2 ? *(reinterpret_cast<const Vector2*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a Vector3. To return true, both the type and value must match.
     /// Test for equality with a Vector3. To return true, both the type and value must match.
-    bool operator == (const Vector3& rhs) const { return type_ == VAR_VECTOR3 ? *(reinterpret_cast<const Vector3*>(&value_)) == rhs : false; }
+    bool operator ==(const Vector3& rhs) const
+    {
+        return type_ == VAR_VECTOR3 ? *(reinterpret_cast<const Vector3*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a Vector4. To return true, both the type and value must match.
     /// Test for equality with a Vector4. To return true, both the type and value must match.
-    bool operator == (const Vector4& rhs) const { return type_ == VAR_VECTOR4 ? *(reinterpret_cast<const Vector4*>(&value_)) == rhs : false; }
+    bool operator ==(const Vector4& rhs) const
+    {
+        return type_ == VAR_VECTOR4 ? *(reinterpret_cast<const Vector4*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a quaternion. To return true, both the type and value must match.
     /// Test for equality with a quaternion. To return true, both the type and value must match.
-    bool operator == (const Quaternion& rhs) const { return type_ == VAR_QUATERNION ? *(reinterpret_cast<const Quaternion*>(&value_)) == rhs : false; }
+    bool operator ==(const Quaternion& rhs) const
+    {
+        return type_ == VAR_QUATERNION ? *(reinterpret_cast<const Quaternion*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a color. To return true, both the type and value must match.
     /// Test for equality with a color. To return true, both the type and value must match.
-    bool operator == (const Color& rhs) const { return type_ == VAR_COLOR ? *(reinterpret_cast<const Color*>(&value_)) == rhs : false; }
+    bool operator ==(const Color& rhs) const
+    {
+        return type_ == VAR_COLOR ? *(reinterpret_cast<const Color*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a string. To return true, both the type and value must match.
     /// Test for equality with a string. To return true, both the type and value must match.
-    bool operator == (const String& rhs) const { return type_ == VAR_STRING ? *(reinterpret_cast<const String*>(&value_)) == rhs : false; }
+    bool operator ==(const String& rhs) const
+    {
+        return type_ == VAR_STRING ? *(reinterpret_cast<const String*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a buffer. To return true, both the type and value must match.
     /// Test for equality with a buffer. To return true, both the type and value must match.
-    bool operator == (const PODVector<unsigned char>& rhs) const { return type_ == VAR_BUFFER ? *(reinterpret_cast<const PODVector<unsigned char>*>(&value_)) == rhs : false; }
-    
+    bool operator ==(const PODVector<unsigned char>& rhs) const
+    {
+        return type_ == VAR_BUFFER ? *(reinterpret_cast<const PODVector<unsigned char>*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a void pointer. To return true, both the type and value must match, with the exception that a RefCounted pointer is also allowed.
     /// Test for equality with a void pointer. To return true, both the type and value must match, with the exception that a RefCounted pointer is also allowed.
-    bool operator == (void* rhs) const
+    bool operator ==(void* rhs) const
     {
     {
         if (type_ == VAR_VOIDPTR)
         if (type_ == VAR_VOIDPTR)
             return value_.ptr_ == rhs;
             return value_.ptr_ == rhs;
@@ -645,24 +681,48 @@ public:
         else
         else
             return false;
             return false;
     }
     }
-    
+
     /// Test for equality with a resource reference. To return true, both the type and value must match.
     /// Test for equality with a resource reference. To return true, both the type and value must match.
-    bool operator == (const ResourceRef& rhs) const { return type_ == VAR_RESOURCEREF ? *(reinterpret_cast<const ResourceRef*>(&value_)) == rhs : false; }
+    bool operator ==(const ResourceRef& rhs) const
+    {
+        return type_ == VAR_RESOURCEREF ? *(reinterpret_cast<const ResourceRef*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a resource reference list. To return true, both the type and value must match.
     /// Test for equality with a resource reference list. To return true, both the type and value must match.
-    bool operator == (const ResourceRefList& rhs) const { return type_ == VAR_RESOURCEREFLIST ? *(reinterpret_cast<const ResourceRefList*>(&value_)) == rhs : false; }
+    bool operator ==(const ResourceRefList& rhs) const
+    {
+        return type_ == VAR_RESOURCEREFLIST ? *(reinterpret_cast<const ResourceRefList*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a variant vector. To return true, both the type and value must match.
     /// Test for equality with a variant vector. To return true, both the type and value must match.
-    bool operator == (const VariantVector& rhs) const { return type_ == VAR_VARIANTVECTOR ? *(reinterpret_cast<const VariantVector*>(&value_)) == rhs : false; }
+    bool operator ==(const VariantVector& rhs) const
+    {
+        return type_ == VAR_VARIANTVECTOR ? *(reinterpret_cast<const VariantVector*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a variant map. To return true, both the type and value must match.
     /// Test for equality with a variant map. To return true, both the type and value must match.
-    bool operator == (const VariantMap& rhs) const { return type_ == VAR_VARIANTMAP ? *(reinterpret_cast<const VariantMap*>(&value_)) == rhs : false; }
+    bool operator ==(const VariantMap& rhs) const
+    {
+        return type_ == VAR_VARIANTMAP ? *(reinterpret_cast<const VariantMap*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with an integer rect. To return true, both the type and value must match.
     /// Test for equality with an integer rect. To return true, both the type and value must match.
-    bool operator == (const IntRect& rhs) const { return type_ == VAR_INTRECT ? *(reinterpret_cast<const IntRect*>(&value_)) == rhs : false; }
+    bool operator ==(const IntRect& rhs) const
+    {
+        return type_ == VAR_INTRECT ? *(reinterpret_cast<const IntRect*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with an IntVector2. To return true, both the type and value must match.
     /// Test for equality with an IntVector2. To return true, both the type and value must match.
-    bool operator == (const IntVector2& rhs) const { return type_ == VAR_INTVECTOR2 ? *(reinterpret_cast<const IntVector2*>(&value_)) == rhs : false; }
+    bool operator ==(const IntVector2& rhs) const
+    {
+        return type_ == VAR_INTVECTOR2 ? *(reinterpret_cast<const IntVector2*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a StringHash. To return true, both the type and value must match.
     /// Test for equality with a StringHash. To return true, both the type and value must match.
-    bool operator == (const StringHash& rhs) const { return type_ == VAR_INT ? (unsigned)value_.int_ == rhs.Value() : false; }
-    
+    bool operator ==(const StringHash& rhs) const { return type_ == VAR_INT ? (unsigned)value_.int_ == rhs.Value() : false; }
+
     /// Test for equality with a RefCounted pointer. To return true, both the type and value must match, with the exception that void pointer is also allowed.
     /// Test for equality with a RefCounted pointer. To return true, both the type and value must match, with the exception that void pointer is also allowed.
-    bool operator == (RefCounted* rhs) const
+    bool operator ==(RefCounted* rhs) const
     {
     {
         if (type_ == VAR_PTR)
         if (type_ == VAR_PTR)
             return *(reinterpret_cast<const WeakPtr<RefCounted>*>(&value_)) == rhs;
             return *(reinterpret_cast<const WeakPtr<RefCounted>*>(&value_)) == rhs;
@@ -671,63 +731,97 @@ public:
         else
         else
             return false;
             return false;
     }
     }
-    
+
     /// Test for equality with a Matrix3. To return true, both the type and value must match.
     /// Test for equality with a Matrix3. To return true, both the type and value must match.
-    bool operator == (const Matrix3& rhs) const { return type_ == VAR_MATRIX3 ? *(reinterpret_cast<const Matrix3*>(value_.ptr_)) == rhs : false; }
+    bool operator ==(const Matrix3& rhs) const
+    {
+        return type_ == VAR_MATRIX3 ? *(reinterpret_cast<const Matrix3*>(value_.ptr_)) == rhs : false;
+    }
+
     /// Test for equality with a Matrix3x4. To return true, both the type and value must match.
     /// Test for equality with a Matrix3x4. To return true, both the type and value must match.
-    bool operator == (const Matrix3x4& rhs) const { return type_ == VAR_MATRIX3X4 ? *(reinterpret_cast<const Matrix3x4*>(value_.ptr_)) == rhs : false; }
+    bool operator ==(const Matrix3x4& rhs) const
+    {
+        return type_ == VAR_MATRIX3X4 ? *(reinterpret_cast<const Matrix3x4*>(value_.ptr_)) == rhs : false;
+    }
+
     /// Test for equality with a Matrix4. To return true, both the type and value must match.
     /// Test for equality with a Matrix4. To return true, both the type and value must match.
-    bool operator == (const Matrix4& rhs) const { return type_ == VAR_MATRIX4 ? *(reinterpret_cast<const Matrix4*>(value_.ptr_)) == rhs : false; }
-    
+    bool operator ==(const Matrix4& rhs) const
+    {
+        return type_ == VAR_MATRIX4 ? *(reinterpret_cast<const Matrix4*>(value_.ptr_)) == rhs : false;
+    }
+
     /// Test for inequality with another variant.
     /// Test for inequality with another variant.
-    bool operator != (const Variant& rhs) const { return !(*this == rhs); }
+    bool operator !=(const Variant& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with an integer.
     /// Test for inequality with an integer.
-    bool operator != (int rhs) const { return !(*this == rhs); }
+    bool operator !=(int rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with an unsigned integer.
     /// Test for inequality with an unsigned integer.
-    bool operator != (unsigned rhs) const { return !(*this == rhs); }
+    bool operator !=(unsigned rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a bool.
     /// Test for inequality with a bool.
-    bool operator != (bool rhs) const { return !(*this == rhs); }
+    bool operator !=(bool rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a float.
     /// Test for inequality with a float.
-    bool operator != (float rhs) const { return !(*this == rhs); }
+    bool operator !=(float rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a double.
     /// Test for inequality with a double.
-    bool operator != (double rhs) const { return !(*this == rhs); }
+    bool operator !=(double rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a Vector2.
     /// Test for inequality with a Vector2.
-    bool operator != (const Vector2& rhs) const { return !(*this == rhs); }
+    bool operator !=(const Vector2& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a Vector3.
     /// Test for inequality with a Vector3.
-    bool operator != (const Vector3& rhs) const { return !(*this == rhs); }
+    bool operator !=(const Vector3& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with an Vector4.
     /// Test for inequality with an Vector4.
-    bool operator != (const Vector4& rhs) const { return !(*this == rhs); }
+    bool operator !=(const Vector4& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a Quaternion.
     /// Test for inequality with a Quaternion.
-    bool operator != (const Quaternion& rhs) const { return !(*this == rhs); }
+    bool operator !=(const Quaternion& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a string.
     /// Test for inequality with a string.
-    bool operator != (const String& rhs) const { return !(*this == rhs); }
+    bool operator !=(const String& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a buffer.
     /// Test for inequality with a buffer.
-    bool operator != (const PODVector<unsigned char>& rhs) const { return !(*this == rhs); }
+    bool operator !=(const PODVector<unsigned char>& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a pointer.
     /// Test for inequality with a pointer.
-    bool operator != (void* rhs) const { return !(*this == rhs); }
+    bool operator !=(void* rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a resource reference.
     /// Test for inequality with a resource reference.
-    bool operator != (const ResourceRef& rhs) const { return !(*this == rhs); }
+    bool operator !=(const ResourceRef& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a resource reference list.
     /// Test for inequality with a resource reference list.
-    bool operator != (const ResourceRefList& rhs) const { return !(*this == rhs); }
+    bool operator !=(const ResourceRefList& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a variant vector.
     /// Test for inequality with a variant vector.
-    bool operator != (const VariantVector& rhs) const { return !(*this == rhs); }
+    bool operator !=(const VariantVector& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a variant map.
     /// Test for inequality with a variant map.
-    bool operator != (const VariantMap& rhs) const { return !(*this == rhs); }
+    bool operator !=(const VariantMap& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with an integer rect.
     /// Test for inequality with an integer rect.
-    bool operator != (const IntRect& rhs) const { return !(*this == rhs); }
+    bool operator !=(const IntRect& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with an IntVector2.
     /// Test for inequality with an IntVector2.
-    bool operator != (const IntVector2& rhs) const { return !(*this == rhs); }
+    bool operator !=(const IntVector2& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a StringHash.
     /// Test for inequality with a StringHash.
-    bool operator != (const StringHash& rhs) const { return !(*this == rhs); }
+    bool operator !=(const StringHash& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a RefCounted pointer.
     /// Test for inequality with a RefCounted pointer.
-    bool operator != (RefCounted* rhs) const { return !(*this == rhs); }
+    bool operator !=(RefCounted* rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a Matrix3.
     /// Test for inequality with a Matrix3.
-    bool operator != (const Matrix3& rhs) const { return !(*this == rhs); }
+    bool operator !=(const Matrix3& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a Matrix3x4.
     /// Test for inequality with a Matrix3x4.
-    bool operator != (const Matrix3x4& rhs) const { return !(*this == rhs); }
+    bool operator !=(const Matrix3x4& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a Matrix4.
     /// Test for inequality with a Matrix4.
-    bool operator != (const Matrix4& rhs) const { return !(*this == rhs); }
-    
+    bool operator !=(const Matrix4& rhs) const { return !(*this == rhs); }
+
     /// Set from typename and value strings. Pointers will be set to null, and VariantBuffer or VariantMap types are not supported.
     /// Set from typename and value strings. Pointers will be set to null, and VariantBuffer or VariantMap types are not supported.
     void FromString(const String& type, const String& value);
     void FromString(const String& type, const String& value);
     /// Set from typename and value strings. Pointers will be set to null, and VariantBuffer or VariantMap types are not supported.
     /// Set from typename and value strings. Pointers will be set to null, and VariantBuffer or VariantMap types are not supported.
@@ -741,31 +835,49 @@ public:
 
 
     /// Return int or zero on type mismatch.
     /// Return int or zero on type mismatch.
     int GetInt() const { return type_ == VAR_INT ? value_.int_ : 0; }
     int GetInt() const { return type_ == VAR_INT ? value_.int_ : 0; }
+
     /// Return unsigned int or zero on type mismatch.
     /// Return unsigned int or zero on type mismatch.
     unsigned GetUInt() const { return type_ == VAR_INT ? (unsigned)value_.int_ : 0; }
     unsigned GetUInt() const { return type_ == VAR_INT ? (unsigned)value_.int_ : 0; }
+
     /// Return StringHash or zero on type mismatch.
     /// Return StringHash or zero on type mismatch.
     StringHash GetStringHash() const { return StringHash(GetUInt()); }
     StringHash GetStringHash() const { return StringHash(GetUInt()); }
+
     /// Return bool or false on type mismatch.
     /// Return bool or false on type mismatch.
     bool GetBool() const { return type_ == VAR_BOOL ? value_.bool_ : false; }
     bool GetBool() const { return type_ == VAR_BOOL ? value_.bool_ : false; }
+
     /// Return float or zero on type mismatch.
     /// Return float or zero on type mismatch.
     float GetFloat() const { return type_ == VAR_FLOAT ? value_.float_ : 0.0f; }
     float GetFloat() const { return type_ == VAR_FLOAT ? value_.float_ : 0.0f; }
+
     /// Return double or zero on type mismatch.
     /// Return double or zero on type mismatch.
     double GetDouble() const { return type_ == VAR_DOUBLE ? *reinterpret_cast<const double*>(&value_) : 0.0; }
     double GetDouble() const { return type_ == VAR_DOUBLE ? *reinterpret_cast<const double*>(&value_) : 0.0; }
+
     /// Return Vector2 or zero on type mismatch.
     /// Return Vector2 or zero on type mismatch.
     const Vector2& GetVector2() const { return type_ == VAR_VECTOR2 ? *reinterpret_cast<const Vector2*>(&value_) : Vector2::ZERO; }
     const Vector2& GetVector2() const { return type_ == VAR_VECTOR2 ? *reinterpret_cast<const Vector2*>(&value_) : Vector2::ZERO; }
+
     /// Return Vector3 or zero on type mismatch.
     /// Return Vector3 or zero on type mismatch.
     const Vector3& GetVector3() const { return type_ == VAR_VECTOR3 ? *reinterpret_cast<const Vector3*>(&value_) : Vector3::ZERO; }
     const Vector3& GetVector3() const { return type_ == VAR_VECTOR3 ? *reinterpret_cast<const Vector3*>(&value_) : Vector3::ZERO; }
+
     /// Return Vector4 or zero on type mismatch.
     /// Return Vector4 or zero on type mismatch.
     const Vector4& GetVector4() const { return type_ == VAR_VECTOR4 ? *reinterpret_cast<const Vector4*>(&value_) : Vector4::ZERO; }
     const Vector4& GetVector4() const { return type_ == VAR_VECTOR4 ? *reinterpret_cast<const Vector4*>(&value_) : Vector4::ZERO; }
+
     /// Return quaternion or identity on type mismatch.
     /// Return quaternion or identity on type mismatch.
-    const Quaternion& GetQuaternion() const { return type_ == VAR_QUATERNION ? *reinterpret_cast<const Quaternion*>(&value_) : Quaternion::IDENTITY; }
+    const Quaternion& GetQuaternion() const
+    {
+        return type_ == VAR_QUATERNION ? *reinterpret_cast<const Quaternion*>(&value_) : Quaternion::IDENTITY;
+    }
+
     /// Return color or default on type mismatch.
     /// Return color or default on type mismatch.
     const Color& GetColor() const { return type_ == VAR_COLOR ? *reinterpret_cast<const Color*>(&value_) : Color::WHITE; }
     const Color& GetColor() const { return type_ == VAR_COLOR ? *reinterpret_cast<const Color*>(&value_) : Color::WHITE; }
+
     /// Return string or empty on type mismatch.
     /// Return string or empty on type mismatch.
     const String& GetString() const { return type_ == VAR_STRING ? *reinterpret_cast<const String*>(&value_) : String::EMPTY; }
     const String& GetString() const { return type_ == VAR_STRING ? *reinterpret_cast<const String*>(&value_) : String::EMPTY; }
+
     /// Return buffer or empty on type mismatch.
     /// Return buffer or empty on type mismatch.
-    const PODVector<unsigned char>& GetBuffer() const { return type_ == VAR_BUFFER ? *reinterpret_cast<const PODVector<unsigned char>*>(&value_) : emptyBuffer; }
-    
+    const PODVector<unsigned char>& GetBuffer() const
+    {
+        return type_ == VAR_BUFFER ? *reinterpret_cast<const PODVector<unsigned char>*>(&value_) : emptyBuffer;
+    }
+
     /// Return void pointer or null on type mismatch. RefCounted pointer will be converted.
     /// Return void pointer or null on type mismatch. RefCounted pointer will be converted.
     void* GetVoidPtr() const
     void* GetVoidPtr() const
     {
     {
@@ -776,44 +888,89 @@ public:
         else
         else
             return 0;
             return 0;
     }
     }
-    
+
     /// Return a resource reference or empty on type mismatch.
     /// Return a resource reference or empty on type mismatch.
-    const ResourceRef& GetResourceRef() const { return type_ == VAR_RESOURCEREF ? *reinterpret_cast<const ResourceRef*>(&value_) : emptyResourceRef; }
+    const ResourceRef& GetResourceRef() const
+    {
+        return type_ == VAR_RESOURCEREF ? *reinterpret_cast<const ResourceRef*>(&value_) : emptyResourceRef;
+    }
+
     /// Return a resource reference list or empty on type mismatch.
     /// Return a resource reference list or empty on type mismatch.
-    const ResourceRefList& GetResourceRefList() const { return type_ == VAR_RESOURCEREFLIST ? *reinterpret_cast<const ResourceRefList*>(&value_) : emptyResourceRefList; }
+    const ResourceRefList& GetResourceRefList() const
+    {
+        return type_ == VAR_RESOURCEREFLIST ? *reinterpret_cast<const ResourceRefList*>(&value_) : emptyResourceRefList;
+    }
+
     /// Return a variant vector or empty on type mismatch.
     /// Return a variant vector or empty on type mismatch.
-    const VariantVector& GetVariantVector() const { return type_ == VAR_VARIANTVECTOR ? *reinterpret_cast<const VariantVector*>(&value_) : emptyVariantVector; }
+    const VariantVector& GetVariantVector() const
+    {
+        return type_ == VAR_VARIANTVECTOR ? *reinterpret_cast<const VariantVector*>(&value_) : emptyVariantVector;
+    }
+
     /// Return a variant map or empty on type mismatch.
     /// Return a variant map or empty on type mismatch.
-    const VariantMap& GetVariantMap() const { return type_ == VAR_VARIANTMAP ? *reinterpret_cast<const VariantMap*>(&value_) : emptyVariantMap; }
+    const VariantMap& GetVariantMap() const
+    {
+        return type_ == VAR_VARIANTMAP ? *reinterpret_cast<const VariantMap*>(&value_) : emptyVariantMap;
+    }
+
     /// Return an integer rect or empty on type mismatch.
     /// Return an integer rect or empty on type mismatch.
     const IntRect& GetIntRect() const { return type_ == VAR_INTRECT ? *reinterpret_cast<const IntRect*>(&value_) : IntRect::ZERO; }
     const IntRect& GetIntRect() const { return type_ == VAR_INTRECT ? *reinterpret_cast<const IntRect*>(&value_) : IntRect::ZERO; }
+
     /// Return an IntVector2 or empty on type mismatch.
     /// Return an IntVector2 or empty on type mismatch.
-    const IntVector2& GetIntVector2() const { return type_ == VAR_INTVECTOR2 ? *reinterpret_cast<const IntVector2*>(&value_) : IntVector2::ZERO; }
+    const IntVector2& GetIntVector2() const
+    {
+        return type_ == VAR_INTVECTOR2 ? *reinterpret_cast<const IntVector2*>(&value_) : IntVector2::ZERO;
+    }
+
     /// Return a RefCounted pointer or null on type mismatch. Will return null if holding a void pointer, as it can not be safely verified that the object is a RefCounted.
     /// Return a RefCounted pointer or null on type mismatch. Will return null if holding a void pointer, as it can not be safely verified that the object is a RefCounted.
-    RefCounted* GetPtr() const { return type_ == VAR_PTR ? *reinterpret_cast<const WeakPtr<RefCounted>*>(&value_) : (RefCounted*)0; }
+    RefCounted* GetPtr() const
+    {
+        return type_ == VAR_PTR ? *reinterpret_cast<const WeakPtr<RefCounted>*>(&value_) : (RefCounted*)0;
+    }
+
     /// Return a Matrix3 or identity on type mismatch.
     /// Return a Matrix3 or identity on type mismatch.
-    const Matrix3& GetMatrix3() const { return type_ == VAR_MATRIX3 ? *(reinterpret_cast<const Matrix3*>(value_.ptr_)) : Matrix3::IDENTITY; }
+    const Matrix3& GetMatrix3() const
+    {
+        return type_ == VAR_MATRIX3 ? *(reinterpret_cast<const Matrix3*>(value_.ptr_)) : Matrix3::IDENTITY;
+    }
+
     /// Return a Matrix3x4 or identity on type mismatch.
     /// Return a Matrix3x4 or identity on type mismatch.
-    const Matrix3x4& GetMatrix3x4() const { return type_ == VAR_MATRIX3X4 ? *(reinterpret_cast<const Matrix3x4*>(value_.ptr_)) : Matrix3x4::IDENTITY; }
+    const Matrix3x4& GetMatrix3x4() const
+    {
+        return type_ == VAR_MATRIX3X4 ? *(reinterpret_cast<const Matrix3x4*>(value_.ptr_)) : Matrix3x4::IDENTITY;
+    }
+
     /// Return a Matrix4 or identity on type mismatch.
     /// Return a Matrix4 or identity on type mismatch.
-    const Matrix4& GetMatrix4() const { return type_ == VAR_MATRIX4 ? *(reinterpret_cast<const Matrix4*>(value_.ptr_)) : Matrix4::IDENTITY; }
+    const Matrix4& GetMatrix4() const
+    {
+        return type_ == VAR_MATRIX4 ? *(reinterpret_cast<const Matrix4*>(value_.ptr_)) : Matrix4::IDENTITY;
+    }
+
     /// Return value's type.
     /// Return value's type.
     VariantType GetType() const { return type_; }
     VariantType GetType() const { return type_; }
+
     /// Return value's type name.
     /// Return value's type name.
     String GetTypeName() const;
     String GetTypeName() const;
     /// Convert value to string. Pointers are returned as null, and VariantBuffer or VariantMap are not supported and return empty.
     /// Convert value to string. Pointers are returned as null, and VariantBuffer or VariantMap are not supported and return empty.
     String ToString() const;
     String ToString() const;
     /// Return true when the variant value is considered zero according to its actual type.
     /// Return true when the variant value is considered zero according to its actual type.
     bool IsZero() const;
     bool IsZero() const;
+
     /// Return true when the variant is empty (i.e. not initialized yet).
     /// Return true when the variant is empty (i.e. not initialized yet).
     bool IsEmpty() const { return type_ == VAR_NONE; }
     bool IsEmpty() const { return type_ == VAR_NONE; }
+
     /// Return the value, template version.
     /// Return the value, template version.
     template <class T> T Get() const;
     template <class T> T Get() const;
-    
+
     /// Return a pointer to a modifiable buffer or null on type mismatch.
     /// Return a pointer to a modifiable buffer or null on type mismatch.
-    PODVector<unsigned char>* GetBufferPtr() { return type_ == VAR_BUFFER ? reinterpret_cast<PODVector<unsigned char>*>(&value_) : 0; }
+    PODVector<unsigned char>* GetBufferPtr()
+    {
+        return type_ == VAR_BUFFER ? reinterpret_cast<PODVector<unsigned char>*>(&value_) : 0;
+    }
+
     /// Return a pointer to a modifiable variant vector or null on type mismatch.
     /// Return a pointer to a modifiable variant vector or null on type mismatch.
     VariantVector* GetVariantVectorPtr() { return type_ == VAR_VARIANTVECTOR ? reinterpret_cast<VariantVector*>(&value_) : 0; }
     VariantVector* GetVariantVectorPtr() { return type_ == VAR_VARIANTVECTOR ? reinterpret_cast<VariantVector*>(&value_) : 0; }
+
     /// Return a pointer to a modifiable variant map or null on type mismatch.
     /// Return a pointer to a modifiable variant map or null on type mismatch.
     VariantMap* GetVariantMapPtr() { return type_ == VAR_VARIANTMAP ? reinterpret_cast<VariantMap*>(&value_) : 0; }
     VariantMap* GetVariantMapPtr() { return type_ == VAR_VARIANTMAP ? reinterpret_cast<VariantMap*>(&value_) : 0; }
 
 
@@ -848,30 +1005,51 @@ private:
 };
 };
 
 
 /// Return variant type from type.
 /// Return variant type from type.
-template<typename T> VariantType GetVariantType();
+template <typename T> VariantType GetVariantType();
 
 
 /// Return variant type from concrete types.
 /// Return variant type from concrete types.
-template<> inline VariantType GetVariantType<int>() { return VAR_INT; }
-template<> inline VariantType GetVariantType<unsigned>() { return VAR_INT; }
-template<> inline VariantType GetVariantType<bool>() { return VAR_BOOL; }
-template<> inline VariantType GetVariantType<float>() { return VAR_FLOAT; }
-template<> inline VariantType GetVariantType<double>() { return VAR_DOUBLE; }
-template<> inline VariantType GetVariantType<Vector2>() { return VAR_VECTOR2; }
-template<> inline VariantType GetVariantType<Vector3>() { return VAR_VECTOR3; }
-template<> inline VariantType GetVariantType<Vector4>() { return VAR_VECTOR4; }
-template<> inline VariantType GetVariantType<Quaternion>() { return VAR_QUATERNION; }
-template<> inline VariantType GetVariantType<Color>() { return VAR_COLOR; }
-template<> inline VariantType GetVariantType<String>() { return VAR_STRING; }
-template<> inline VariantType GetVariantType<StringHash>() { return VAR_INT; }
-template<> inline VariantType GetVariantType<PODVector<unsigned char> >() { return VAR_BUFFER; }
-template<> inline VariantType GetVariantType<ResourceRef>() { return VAR_RESOURCEREF; }
-template<> inline VariantType GetVariantType<ResourceRefList>() { return VAR_RESOURCEREFLIST; }
-template<> inline VariantType GetVariantType<VariantVector>() { return VAR_VARIANTVECTOR; }
-template<> inline VariantType GetVariantType<VariantMap>() { return VAR_VARIANTMAP; }
-template<> inline VariantType GetVariantType<IntRect>() { return VAR_INTRECT; }
-template<> inline VariantType GetVariantType<IntVector2>() { return VAR_INTVECTOR2; }
-template<> inline VariantType GetVariantType<Matrix3>() { return VAR_MATRIX3; }
-template<> inline VariantType GetVariantType<Matrix3x4>() { return VAR_MATRIX3X4; }
-template<> inline VariantType GetVariantType<Matrix4>() { return VAR_MATRIX4; }
+template <> inline VariantType GetVariantType<int>() { return VAR_INT; }
+
+template <> inline VariantType GetVariantType<unsigned>() { return VAR_INT; }
+
+template <> inline VariantType GetVariantType<bool>() { return VAR_BOOL; }
+
+template <> inline VariantType GetVariantType<float>() { return VAR_FLOAT; }
+
+template <> inline VariantType GetVariantType<double>() { return VAR_DOUBLE; }
+
+template <> inline VariantType GetVariantType<Vector2>() { return VAR_VECTOR2; }
+
+template <> inline VariantType GetVariantType<Vector3>() { return VAR_VECTOR3; }
+
+template <> inline VariantType GetVariantType<Vector4>() { return VAR_VECTOR4; }
+
+template <> inline VariantType GetVariantType<Quaternion>() { return VAR_QUATERNION; }
+
+template <> inline VariantType GetVariantType<Color>() { return VAR_COLOR; }
+
+template <> inline VariantType GetVariantType<String>() { return VAR_STRING; }
+
+template <> inline VariantType GetVariantType<StringHash>() { return VAR_INT; }
+
+template <> inline VariantType GetVariantType<PODVector<unsigned char> >() { return VAR_BUFFER; }
+
+template <> inline VariantType GetVariantType<ResourceRef>() { return VAR_RESOURCEREF; }
+
+template <> inline VariantType GetVariantType<ResourceRefList>() { return VAR_RESOURCEREFLIST; }
+
+template <> inline VariantType GetVariantType<VariantVector>() { return VAR_VARIANTVECTOR; }
+
+template <> inline VariantType GetVariantType<VariantMap>() { return VAR_VARIANTMAP; }
+
+template <> inline VariantType GetVariantType<IntRect>() { return VAR_INTRECT; }
+
+template <> inline VariantType GetVariantType<IntVector2>() { return VAR_INTVECTOR2; }
+
+template <> inline VariantType GetVariantType<Matrix3>() { return VAR_MATRIX3; }
+
+template <> inline VariantType GetVariantType<Matrix3x4>() { return VAR_MATRIX3X4; }
+
+template <> inline VariantType GetVariantType<Matrix4>() { return VAR_MATRIX4; }
 
 
 }
 }

+ 29 - 29
Source/Urho3D/Core/WorkQueue.cpp

@@ -20,13 +20,13 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Core/CoreEvents.h"
 #include "../Core/CoreEvents.h"
-#include "../IO/Log.h"
 #include "../Core/ProcessUtils.h"
 #include "../Core/ProcessUtils.h"
 #include "../Core/Profiler.h"
 #include "../Core/Profiler.h"
-#include "../Core/Thread.h"
-#include "../Core/Timer.h"
 #include "../Core/WorkQueue.h"
 #include "../Core/WorkQueue.h"
+#include "../IO/Log.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {
@@ -41,7 +41,7 @@ public:
         index_(index)
         index_(index)
     {
     {
     }
     }
-    
+
     /// Process work items until stopped.
     /// Process work items until stopped.
     virtual void ThreadFunction()
     virtual void ThreadFunction()
     {
     {
@@ -49,10 +49,10 @@ public:
         InitFPU();
         InitFPU();
         owner_->ProcessItems(index_);
         owner_->ProcessItems(index_);
     }
     }
-    
+
     /// Return thread index.
     /// Return thread index.
     unsigned GetIndex() const { return index_; }
     unsigned GetIndex() const { return index_; }
-    
+
 private:
 private:
     /// Work queue.
     /// Work queue.
     WorkQueue* owner_;
     WorkQueue* owner_;
@@ -77,7 +77,7 @@ WorkQueue::~WorkQueue()
     // Stop the worker threads. First make sure they are not waiting for work items
     // Stop the worker threads. First make sure they are not waiting for work items
     shutDown_ = true;
     shutDown_ = true;
     Resume();
     Resume();
-    
+
     for (unsigned i = 0; i < threads_.Size(); ++i)
     for (unsigned i = 0; i < threads_.Size(); ++i)
         threads_[i]->Stop();
         threads_[i]->Stop();
 }
 }
@@ -88,10 +88,10 @@ void WorkQueue::CreateThreads(unsigned numThreads)
     // Therefore allow creating the threads only once, after which the amount is fixed
     // Therefore allow creating the threads only once, after which the amount is fixed
     if (!threads_.Empty())
     if (!threads_.Empty())
         return;
         return;
-    
+
     // Start threads in paused mode
     // Start threads in paused mode
     Pause();
     Pause();
-    
+
     for (unsigned i = 0; i < numThreads; ++i)
     for (unsigned i = 0; i < numThreads; ++i)
     {
     {
         SharedPtr<WorkerThread> thread(new WorkerThread(this, i + 1));
         SharedPtr<WorkerThread> thread(new WorkerThread(this, i + 1));
@@ -124,10 +124,10 @@ void WorkQueue::AddWorkItem(SharedPtr<WorkItem> item)
         LOGERROR("Null work item submitted to the work queue");
         LOGERROR("Null work item submitted to the work queue");
         return;
         return;
     }
     }
-    
+
     // Check for duplicate items.
     // Check for duplicate items.
     assert(!workItems_.Contains(item));
     assert(!workItems_.Contains(item));
-    
+
     // Push to the main thread list to keep item alive
     // Push to the main thread list to keep item alive
     // Clear completed flag in case item is reused
     // Clear completed flag in case item is reused
     workItems_.Push(item);
     workItems_.Push(item);
@@ -136,7 +136,7 @@ void WorkQueue::AddWorkItem(SharedPtr<WorkItem> item)
     // Make sure worker threads' list is safe to modify
     // Make sure worker threads' list is safe to modify
     if (threads_.Size() && !paused_)
     if (threads_.Size() && !paused_)
         queueMutex_.Acquire();
         queueMutex_.Acquire();
-    
+
     // Find position for new item
     // Find position for new item
     if (queue_.Empty())
     if (queue_.Empty())
         queue_.Push(item);
         queue_.Push(item);
@@ -151,7 +151,7 @@ void WorkQueue::AddWorkItem(SharedPtr<WorkItem> item)
             }
             }
         }
         }
     }
     }
-    
+
     if (threads_.Size())
     if (threads_.Size())
     {
     {
         queueMutex_.Release();
         queueMutex_.Release();
@@ -165,7 +165,7 @@ bool WorkQueue::RemoveWorkItem(SharedPtr<WorkItem> item)
         return false;
         return false;
 
 
     MutexLock lock(queueMutex_);
     MutexLock lock(queueMutex_);
-    
+
     // Can only remove successfully if the item was not yet taken by threads for execution
     // Can only remove successfully if the item was not yet taken by threads for execution
     List<WorkItem*>::Iterator i = queue_.Find(item.Get());
     List<WorkItem*>::Iterator i = queue_.Find(item.Get());
     if (i != queue_.End())
     if (i != queue_.End())
@@ -212,10 +212,10 @@ void WorkQueue::Pause()
     if (!paused_)
     if (!paused_)
     {
     {
         pausing_ = true;
         pausing_ = true;
-        
+
         queueMutex_.Acquire();
         queueMutex_.Acquire();
         paused_ = true;
         paused_ = true;
-        
+
         pausing_ = false;
         pausing_ = false;
     }
     }
 }
 }
@@ -235,7 +235,7 @@ void WorkQueue::Complete(unsigned priority)
     if (threads_.Size())
     if (threads_.Size())
     {
     {
         Resume();
         Resume();
-        
+
         // Take work items also in the main thread until queue empty or no high-priority items anymore
         // Take work items also in the main thread until queue empty or no high-priority items anymore
         while (!queue_.Empty())
         while (!queue_.Empty())
         {
         {
@@ -254,12 +254,12 @@ void WorkQueue::Complete(unsigned priority)
                 break;
                 break;
             }
             }
         }
         }
-        
+
         // Wait for threaded work to complete
         // Wait for threaded work to complete
         while (!IsCompleted(priority))
         while (!IsCompleted(priority))
         {
         {
         }
         }
-        
+
         // If no work at all remaining, pause worker threads by leaving the mutex locked
         // If no work at all remaining, pause worker threads by leaving the mutex locked
         if (queue_.Empty())
         if (queue_.Empty())
             Pause();
             Pause();
@@ -275,7 +275,7 @@ void WorkQueue::Complete(unsigned priority)
             item->completed_ = true;
             item->completed_ = true;
         }
         }
     }
     }
-    
+
     PurgeCompleted(priority);
     PurgeCompleted(priority);
 }
 }
 
 
@@ -286,19 +286,19 @@ bool WorkQueue::IsCompleted(unsigned priority) const
         if ((*i)->priority_ >= priority && !(*i)->completed_)
         if ((*i)->priority_ >= priority && !(*i)->completed_)
             return false;
             return false;
     }
     }
-    
+
     return true;
     return true;
 }
 }
 
 
 void WorkQueue::ProcessItems(unsigned threadIndex)
 void WorkQueue::ProcessItems(unsigned threadIndex)
 {
 {
     bool wasActive = false;
     bool wasActive = false;
-    
+
     for (;;)
     for (;;)
     {
     {
         if (shutDown_)
         if (shutDown_)
             return;
             return;
-        
+
         if (pausing_ && !wasActive)
         if (pausing_ && !wasActive)
             Time::Sleep(0);
             Time::Sleep(0);
         else
         else
@@ -307,7 +307,7 @@ void WorkQueue::ProcessItems(unsigned threadIndex)
             if (!queue_.Empty())
             if (!queue_.Empty())
             {
             {
                 wasActive = true;
                 wasActive = true;
-                
+
                 WorkItem* item = queue_.Front();
                 WorkItem* item = queue_.Front();
                 queue_.PopFront();
                 queue_.PopFront();
                 queueMutex_.Release();
                 queueMutex_.Release();
@@ -317,7 +317,7 @@ void WorkQueue::ProcessItems(unsigned threadIndex)
             else
             else
             {
             {
                 wasActive = false;
                 wasActive = false;
-                
+
                 queueMutex_.Release();
                 queueMutex_.Release();
                 Time::Sleep(0);
                 Time::Sleep(0);
             }
             }
@@ -337,7 +337,7 @@ void WorkQueue::PurgeCompleted(unsigned priority)
             if ((*i)->sendEvent_)
             if ((*i)->sendEvent_)
             {
             {
                 using namespace WorkItemCompleted;
                 using namespace WorkItemCompleted;
-                
+
                 VariantMap& eventData = GetEventDataMap();
                 VariantMap& eventData = GetEventDataMap();
                 eventData[P_ITEM] = i->Get();
                 eventData[P_ITEM] = i->Get();
                 SendEvent(E_WORKITEMCOMPLETED, eventData);
                 SendEvent(E_WORKITEMCOMPLETED, eventData);
@@ -390,9 +390,9 @@ void WorkQueue::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
     if (threads_.Empty() && !queue_.Empty())
     if (threads_.Empty() && !queue_.Empty())
     {
     {
         PROFILE(CompleteWorkNonthreaded);
         PROFILE(CompleteWorkNonthreaded);
-        
+
         HiresTimer timer;
         HiresTimer timer;
-        
+
         while (!queue_.Empty() && timer.GetUSec(false) < maxNonThreadedWorkMs_ * 1000)
         while (!queue_.Empty() && timer.GetUSec(false) < maxNonThreadedWorkMs_ * 1000)
         {
         {
             WorkItem* item = queue_.Front();
             WorkItem* item = queue_.Front();
@@ -401,7 +401,7 @@ void WorkQueue::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
             item->completed_ = true;
             item->completed_ = true;
         }
         }
     }
     }
-    
+
     // Complete and signal items down to the lowest priority
     // Complete and signal items down to the lowest priority
     PurgeCompleted(0);
     PurgeCompleted(0);
     PurgePool();
     PurgePool();

+ 13 - 8
Source/Urho3D/Core/WorkQueue.h

@@ -51,9 +51,9 @@ public:
         pooled_(false)
         pooled_(false)
     {
     {
     }
     }
-    
+
     /// Work function. Called with the work item and thread index (0 = main thread) as parameters.
     /// Work function. Called with the work item and thread index (0 = main thread) as parameters.
-    void (*workFunction_)(const WorkItem*, unsigned);
+    void (* workFunction_)(const WorkItem*, unsigned);
     /// Data start pointer.
     /// Data start pointer.
     void* start_;
     void* start_;
     /// Data end pointer.
     /// Data end pointer.
@@ -75,15 +75,15 @@ private:
 class URHO3D_API WorkQueue : public Object
 class URHO3D_API WorkQueue : public Object
 {
 {
     OBJECT(WorkQueue);
     OBJECT(WorkQueue);
-    
+
     friend class WorkerThread;
     friend class WorkerThread;
-    
+
 public:
 public:
     /// Construct.
     /// Construct.
     WorkQueue(Context* context);
     WorkQueue(Context* context);
     /// Destruct.
     /// Destruct.
     ~WorkQueue();
     ~WorkQueue();
-    
+
     /// Create worker threads. Can only be called once.
     /// Create worker threads. Can only be called once.
     void CreateThreads(unsigned numThreads);
     void CreateThreads(unsigned numThreads);
     /// Get pointer to an usable WorkItem from the item pool. Allocate one if no more free items.
     /// Get pointer to an usable WorkItem from the item pool. Allocate one if no more free items.
@@ -100,20 +100,25 @@ public:
     void Resume();
     void Resume();
     /// Finish all queued work which has at least the specified priority. Main thread will also execute priority work. Pause worker threads if no more work remains.
     /// Finish all queued work which has at least the specified priority. Main thread will also execute priority work. Pause worker threads if no more work remains.
     void Complete(unsigned priority);
     void Complete(unsigned priority);
+
     /// Set the pool telerance before it starts deleting pool items.
     /// Set the pool telerance before it starts deleting pool items.
     void SetTolerance(int tolerance) { tolerance_ = tolerance; }
     void SetTolerance(int tolerance) { tolerance_ = tolerance; }
+
     /// Set how many milliseconds maximum per frame to spend on low-priority work, when there are no worker threads.
     /// Set how many milliseconds maximum per frame to spend on low-priority work, when there are no worker threads.
     void SetNonThreadedWorkMs(int ms) { maxNonThreadedWorkMs_ = Max(ms, 1); }
     void SetNonThreadedWorkMs(int ms) { maxNonThreadedWorkMs_ = Max(ms, 1); }
-    
+
     /// Return number of worker threads.
     /// Return number of worker threads.
     unsigned GetNumThreads() const { return threads_.Size(); }
     unsigned GetNumThreads() const { return threads_.Size(); }
+
     /// Return whether all work with at least the specified priority is finished.
     /// Return whether all work with at least the specified priority is finished.
     bool IsCompleted(unsigned priority) const;
     bool IsCompleted(unsigned priority) const;
+
     /// Return the pool tolerance.
     /// Return the pool tolerance.
     int GetTolerance() const { return tolerance_; }
     int GetTolerance() const { return tolerance_; }
+
     /// Return how many milliseconds maximum to spend on non-threaded low-priority work.
     /// Return how many milliseconds maximum to spend on non-threaded low-priority work.
     int GetNonThreadedWorkMs() const { return maxNonThreadedWorkMs_; }
     int GetNonThreadedWorkMs() const { return maxNonThreadedWorkMs_; }
-    
+
 private:
 private:
     /// Process work items until shut down. Called by the worker threads.
     /// Process work items until shut down. Called by the worker threads.
     void ProcessItems(unsigned threadIndex);
     void ProcessItems(unsigned threadIndex);
@@ -125,7 +130,7 @@ private:
     void ReturnToPool(SharedPtr<WorkItem>& item);
     void ReturnToPool(SharedPtr<WorkItem>& item);
     /// Handle frame start event. Purge completed work from the main thread queue, and perform work if no threads at all.
     /// Handle frame start event. Purge completed work from the main thread queue, and perform work if no threads at all.
     void HandleBeginFrame(StringHash eventType, VariantMap& eventData);
     void HandleBeginFrame(StringHash eventType, VariantMap& eventData);
-    
+
     /// Worker threads.
     /// Worker threads.
     Vector<SharedPtr<WorkerThread> > threads_;
     Vector<SharedPtr<WorkerThread> > threads_;
     /// Work item pool for reuse to cut down on allocation. The bool is a flag for item pooling and whether it is available or not.
     /// Work item pool for reuse to cut down on allocation. The bool is a flag for item pooling and whether it is available or not.

+ 10 - 11
Source/Urho3D/Engine/Application.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Engine/Application.h"
 #include "../Engine/Application.h"
 #include "../Engine/Engine.h"
 #include "../Engine/Engine.h"
 #ifdef IOS
 #ifdef IOS
@@ -28,9 +30,6 @@
 #endif
 #endif
 #include "../IO/IOEvents.h"
 #include "../IO/IOEvents.h"
 #include "../IO/Log.h"
 #include "../IO/Log.h"
-#include "../Core/ProcessUtils.h"
-
-#include <exception>
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -83,20 +82,20 @@ int Application::Run()
             return exitCode_;
             return exitCode_;
 
 
         // Platforms other than iOS and EMSCRIPTEN run a blocking main loop
         // Platforms other than iOS and EMSCRIPTEN run a blocking main loop
-        #if !defined(IOS) && !defined(EMSCRIPTEN)
+#if !defined(IOS) && !defined(EMSCRIPTEN)
         while (!engine_->IsExiting())
         while (!engine_->IsExiting())
             engine_->RunFrame();
             engine_->RunFrame();
 
 
         Stop();
         Stop();
         // iOS will setup a timer for running animation frames so eg. Game Center can run. In this case we do not
         // iOS will setup a timer for running animation frames so eg. Game Center can run. In this case we do not
         // support calling the Stop() function, as the application will never stop manually
         // support calling the Stop() function, as the application will never stop manually
-        #else
-        #if defined(IOS)
+#else
+#if defined(IOS)
         SDL_iPhoneSetAnimationCallback(GetSubsystem<Graphics>()->GetImpl()->GetWindow(), 1, &RunFrame, engine_);
         SDL_iPhoneSetAnimationCallback(GetSubsystem<Graphics>()->GetImpl()->GetWindow(), 1, &RunFrame, engine_);
-        #elif defined(EMSCRIPTEN)
+#elif defined(EMSCRIPTEN)
         emscripten_set_main_loop_arg(RunFrame, engine_, 0, 1);
         emscripten_set_main_loop_arg(RunFrame, engine_, 0, 1);
-        #endif
-        #endif
+#endif
+#endif
 
 
         return exitCode_;
         return exitCode_;
     }
     }
@@ -115,10 +114,10 @@ void Application::ErrorExit(const String& message)
     // Only for WIN32, otherwise the error messages would be double posted on Mac OS X and Linux platforms
     // Only for WIN32, otherwise the error messages would be double posted on Mac OS X and Linux platforms
     if (!message.Length())
     if (!message.Length())
     {
     {
-        #ifdef WIN32
+#ifdef WIN32
         ErrorDialog(GetTypeName(), startupErrors_.Length() ? startupErrors_ :
         ErrorDialog(GetTypeName(), startupErrors_.Length() ? startupErrors_ :
             "Application has been terminated due to unexpected error.");
             "Application has been terminated due to unexpected error.");
-        #endif
+#endif
     }
     }
     else
     else
         ErrorDialog(GetTypeName(), message);
         ErrorDialog(GetTypeName(), message);

+ 8 - 6
Source/Urho3D/Engine/Application.h

@@ -35,17 +35,19 @@ class Engine;
 class URHO3D_API Application : public Object
 class URHO3D_API Application : public Object
 {
 {
     OBJECT(Application);
     OBJECT(Application);
-    
+
 public:
 public:
     /// Construct. Parse default engine parameters from the command line, and create the engine in an uninitialized state.
     /// Construct. Parse default engine parameters from the command line, and create the engine in an uninitialized state.
     Application(Context* context);
     Application(Context* context);
 
 
     /// Setup before engine initialization. This is a chance to eg. modify the engine parameters. Call ErrorExit() to terminate without initializing the engine. Called by Application.
     /// Setup before engine initialization. This is a chance to eg. modify the engine parameters. Call ErrorExit() to terminate without initializing the engine. Called by Application.
-    virtual void Setup() {}
+    virtual void Setup() { }
+
     /// Setup after engine initialization and before running the main loop. Call ErrorExit() to terminate without running the main loop. Called by Application.
     /// Setup after engine initialization and before running the main loop. Call ErrorExit() to terminate without running the main loop. Called by Application.
-    virtual void Start() {}
+    virtual void Start() { }
+
     /// Cleanup after the main loop. Called by Application.
     /// Cleanup after the main loop. Called by Application.
-    virtual void Stop() {}
+    virtual void Stop() { }
 
 
     /// Initialize the engine and run the main loop, then return the application exit code. Catch out-of-memory exceptions while running.
     /// Initialize the engine and run the main loop, then return the application exit code. Catch out-of-memory exceptions while running.
     int Run();
     int Run();
@@ -55,7 +57,7 @@ public:
 protected:
 protected:
     /// Handle log message.
     /// Handle log message.
     void HandleLogMessage(StringHash eventType, VariantMap& eventData);
     void HandleLogMessage(StringHash eventType, VariantMap& eventData);
-    
+
     /// Urho3D engine.
     /// Urho3D engine.
     SharedPtr<Engine> engine_;
     SharedPtr<Engine> engine_;
     /// Engine parameters map.
     /// Engine parameters map.
@@ -87,5 +89,5 @@ int RunApplication() \
 } \
 } \
 DEFINE_MAIN(RunApplication());
 DEFINE_MAIN(RunApplication());
 #endif
 #endif
-    
+
 }
 }

+ 24 - 20
Source/Urho3D/Engine/Console.cpp

@@ -20,21 +20,22 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
-#include "../Engine/Console.h"
+#include "../Precompiled.h"
+
 #include "../Core/Context.h"
 #include "../Core/Context.h"
 #include "../Core/CoreEvents.h"
 #include "../Core/CoreEvents.h"
-#include "../UI/DropDownList.h"
+#include "../Engine/Console.h"
 #include "../Engine/EngineEvents.h"
 #include "../Engine/EngineEvents.h"
-#include "../UI/Font.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/GraphicsEvents.h"
 #include "../Graphics/GraphicsEvents.h"
 #include "../Input/Input.h"
 #include "../Input/Input.h"
-#include "../Input/InputEvents.h"
 #include "../IO/IOEvents.h"
 #include "../IO/IOEvents.h"
-#include "../UI/LineEdit.h"
-#include "../UI/ListView.h"
 #include "../IO/Log.h"
 #include "../IO/Log.h"
 #include "../Resource/ResourceCache.h"
 #include "../Resource/ResourceCache.h"
+#include "../UI/DropDownList.h"
+#include "../UI/Font.h"
+#include "../UI/LineEdit.h"
+#include "../UI/ListView.h"
 #include "../UI/ScrollBar.h"
 #include "../UI/ScrollBar.h"
 #include "../UI/Text.h"
 #include "../UI/Text.h"
 #include "../UI/UI.h"
 #include "../UI/UI.h"
@@ -120,7 +121,7 @@ void Console::SetDefaultStyle(XMLFile* style)
 
 
     closeButton_->SetDefaultStyle(style);
     closeButton_->SetDefaultStyle(style);
     closeButton_->SetStyle("CloseButton");
     closeButton_->SetStyle("CloseButton");
-    
+
     UpdateElements();
     UpdateElements();
 }
 }
 
 
@@ -202,7 +203,7 @@ void Console::SetNumRows(unsigned rows)
     displayedRows_ = rows;
     displayedRows_ = rows;
     if (GetNumBufferedRows() < rows)
     if (GetNumBufferedRows() < rows)
         SetNumBufferedRows(rows);
         SetNumBufferedRows(rows);
-    
+
     UpdateElements();
     UpdateElements();
 }
 }
 
 
@@ -226,7 +227,8 @@ void Console::UpdateElements()
     const IntRect& border = background_->GetLayoutBorder();
     const IntRect& border = background_->GetLayoutBorder();
     const IntRect& panelBorder = rowContainer_->GetScrollPanel()->GetClipBorder();
     const IntRect& panelBorder = rowContainer_->GetScrollPanel()->GetClipBorder();
     rowContainer_->SetFixedWidth(width - border.left_ - border.right_);
     rowContainer_->SetFixedWidth(width - border.left_ - border.right_);
-    rowContainer_->SetFixedHeight(displayedRows_ * rowContainer_->GetItem((unsigned)0)->GetHeight() + panelBorder.top_ + panelBorder.bottom_ +
+    rowContainer_->SetFixedHeight(
+        displayedRows_ * rowContainer_->GetItem((unsigned)0)->GetHeight() + panelBorder.top_ + panelBorder.bottom_ +
         (rowContainer_->GetHorizontalScrollBar()->IsVisible() ? rowContainer_->GetHorizontalScrollBar()->GetHeight() : 0));
         (rowContainer_->GetHorizontalScrollBar()->IsVisible() ? rowContainer_->GetHorizontalScrollBar()->GetHeight() : 0));
     background_->SetFixedWidth(width);
     background_->SetFixedWidth(width);
     background_->SetHeight(background_->GetMinHeight());
     background_->SetHeight(background_->GetMinHeight());
@@ -314,10 +316,10 @@ void Console::HandleTextFinished(StringHash eventType, VariantMap& eventData)
         // Send the command as an event for script subsystem
         // Send the command as an event for script subsystem
         using namespace ConsoleCommand;
         using namespace ConsoleCommand;
 
 
-        VariantMap& eventData = GetEventDataMap();
-        eventData[P_COMMAND] = line;
-        eventData[P_ID] = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
-        SendEvent(E_CONSOLECOMMAND, eventData);
+        VariantMap& newEventData = GetEventDataMap();
+        newEventData[P_COMMAND] = line;
+        newEventData[P_ID] = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
+        SendEvent(E_CONSOLECOMMAND, newEventData);
 
 
         // Store to history, then clear the lineedit
         // Store to history, then clear the lineedit
         history_.Push(line);
         history_.Push(line);
@@ -358,6 +360,8 @@ void Console::HandleLineEditKey(StringHash eventType, VariantMap& eventData)
             changed = true;
             changed = true;
         }
         }
         break;
         break;
+
+    default: break;
     }
     }
 
 
     if (changed)
     if (changed)
@@ -384,13 +388,13 @@ void Console::HandleLogMessage(StringHash eventType, VariantMap& eventData)
     // If printing a log message causes more messages to be logged (error accessing font), disregard them
     // If printing a log message causes more messages to be logged (error accessing font), disregard them
     if (printing_)
     if (printing_)
         return;
         return;
-    
+
     using namespace LogMessage;
     using namespace LogMessage;
 
 
     int level = eventData[P_LEVEL].GetInt();
     int level = eventData[P_LEVEL].GetInt();
     // The message may be multi-line, so split to rows in that case
     // The message may be multi-line, so split to rows in that case
     Vector<String> rows = eventData[P_MESSAGE].GetString().Split('\n');
     Vector<String> rows = eventData[P_MESSAGE].GetString().Split('\n');
-    
+
     for (unsigned i = 0; i < rows.Size(); ++i)
     for (unsigned i = 0; i < rows.Size(); ++i)
         pendingRows_.Push(MakePair(level, rows[i]));
         pendingRows_.Push(MakePair(level, rows[i]));
 
 
@@ -411,11 +415,11 @@ void Console::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
 
 
     if (!rowContainer_->GetNumItems() || pendingRows_.Empty())
     if (!rowContainer_->GetNumItems() || pendingRows_.Empty())
         return;
         return;
-    
+
     printing_ = true;
     printing_ = true;
     rowContainer_->DisableLayoutUpdate();
     rowContainer_->DisableLayoutUpdate();
-    
-    Text* text;
+
+    Text* text = 0;
     for (unsigned i = 0; i < pendingRows_.Size(); ++i)
     for (unsigned i = 0; i < pendingRows_.Size(); ++i)
     {
     {
         rowContainer_->RemoveItem((unsigned)0);
         rowContainer_->RemoveItem((unsigned)0);
@@ -425,9 +429,9 @@ void Console::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
         text->SetStyle(pendingRows_[i].first_ == LOG_ERROR ? "ConsoleHighlightedText" : "ConsoleText");
         text->SetStyle(pendingRows_[i].first_ == LOG_ERROR ? "ConsoleHighlightedText" : "ConsoleText");
         rowContainer_->AddItem(text);
         rowContainer_->AddItem(text);
     }
     }
-    
+
     pendingRows_.Clear();
     pendingRows_.Clear();
-    
+
     rowContainer_->EnsureItemVisibility(text);
     rowContainer_->EnsureItemVisibility(text);
     rowContainer_->EnableLayoutUpdate();
     rowContainer_->EnableLayoutUpdate();
     rowContainer_->UpdateLayout();
     rowContainer_->UpdateLayout();

+ 16 - 0
Source/Urho3D/Engine/Console.h

@@ -55,10 +55,13 @@ public:
     void SetVisible(bool enable);
     void SetVisible(bool enable);
     /// Toggle visibility.
     /// Toggle visibility.
     void Toggle();
     void Toggle();
+
     /// Automatically set console to visible when receiving an error log message.
     /// Automatically set console to visible when receiving an error log message.
     void SetAutoVisibleOnError(bool enable) { autoVisibleOnError_ = enable; }
     void SetAutoVisibleOnError(bool enable) { autoVisibleOnError_ = enable; }
+
     /// Set the command interpreter.
     /// Set the command interpreter.
     void SetCommandInterpreter(const String& interpreter) { commandInterpreter_ = interpreter; }
     void SetCommandInterpreter(const String& interpreter) { commandInterpreter_ = interpreter; }
+
     /// Set number of buffered rows.
     /// Set number of buffered rows.
     void SetNumBufferedRows(unsigned rows);
     void SetNumBufferedRows(unsigned rows);
     /// Set number of displayed rows.
     /// Set number of displayed rows.
@@ -72,30 +75,43 @@ public:
 
 
     /// Return the UI style file.
     /// Return the UI style file.
     XMLFile* GetDefaultStyle() const;
     XMLFile* GetDefaultStyle() const;
+
     /// Return the background element.
     /// Return the background element.
     BorderImage* GetBackground() const { return background_; }
     BorderImage* GetBackground() const { return background_; }
+
     /// Return the line edit element.
     /// Return the line edit element.
     LineEdit* GetLineEdit() const { return lineEdit_; }
     LineEdit* GetLineEdit() const { return lineEdit_; }
+
     /// Return the close butoon element.
     /// Return the close butoon element.
     Button* GetCloseButton() const { return closeButton_; }
     Button* GetCloseButton() const { return closeButton_; }
+
     /// Return whether is visible.
     /// Return whether is visible.
     bool IsVisible() const;
     bool IsVisible() const;
+
     /// Return true when console is set to automatically visible when receiving an error log message.
     /// Return true when console is set to automatically visible when receiving an error log message.
     bool IsAutoVisibleOnError() const { return autoVisibleOnError_; }
     bool IsAutoVisibleOnError() const { return autoVisibleOnError_; }
+
     /// Return the last used command interpreter.
     /// Return the last used command interpreter.
     const String& GetCommandInterpreter() const { return commandInterpreter_; }
     const String& GetCommandInterpreter() const { return commandInterpreter_; }
+
     /// Return number of buffered rows.
     /// Return number of buffered rows.
     unsigned GetNumBufferedRows() const;
     unsigned GetNumBufferedRows() const;
+
     /// Return number of displayed rows.
     /// Return number of displayed rows.
     unsigned GetNumRows() const { return displayedRows_; }
     unsigned GetNumRows() const { return displayedRows_; }
+
     /// Copy selected rows to system clipboard.
     /// Copy selected rows to system clipboard.
     void CopySelectedRows() const;
     void CopySelectedRows() const;
+
     /// Return history maximum size.
     /// Return history maximum size.
     unsigned GetNumHistoryRows() const { return historyRows_; }
     unsigned GetNumHistoryRows() const { return historyRows_; }
+
     /// Return current history position.
     /// Return current history position.
     unsigned GetHistoryPosition() const { return historyPosition_; }
     unsigned GetHistoryPosition() const { return historyPosition_; }
+
     /// Return history row at index.
     /// Return history row at index.
     const String& GetHistoryRow(unsigned index) const;
     const String& GetHistoryRow(unsigned index) const;
+
     /// Return whether automatically focuses the line edit when showing.
     /// Return whether automatically focuses the line edit when showing.
     bool GetFocusOnShow() const { return focusOnShow_; }
     bool GetFocusOnShow() const { return focusOnShow_; }
 
 

+ 6 - 4
Source/Urho3D/Engine/DebugHud.cpp

@@ -20,14 +20,16 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Core/CoreEvents.h"
 #include "../Core/CoreEvents.h"
+#include "../Core/Profiler.h"
 #include "../Engine/DebugHud.h"
 #include "../Engine/DebugHud.h"
 #include "../Engine/Engine.h"
 #include "../Engine/Engine.h"
-#include "../UI/Font.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/Graphics.h"
-#include "../IO/Log.h"
-#include "../Core/Profiler.h"
 #include "../Graphics/Renderer.h"
 #include "../Graphics/Renderer.h"
+#include "../IO/Log.h"
+#include "../UI/Font.h"
 #include "../UI/Text.h"
 #include "../UI/Text.h"
 #include "../UI/UI.h"
 #include "../UI/UI.h"
 
 
@@ -203,7 +205,7 @@ void DebugHud::SetProfilerMaxDepth(unsigned depth)
 
 
 void DebugHud::SetProfilerInterval(float interval)
 void DebugHud::SetProfilerInterval(float interval)
 {
 {
-    profilerInterval_ = Max((int)(interval * 1000.0f), 0);
+    profilerInterval_ = (unsigned)Max((int)(interval * 1000.0f), 0);
 }
 }
 
 
 void DebugHud::SetUseRendererStats(bool enable)
 void DebugHud::SetUseRendererStats(bool enable)

+ 7 - 0
Source/Urho3D/Engine/DebugHud.h

@@ -69,21 +69,28 @@ public:
 
 
     /// Return the UI style file.
     /// Return the UI style file.
     XMLFile* GetDefaultStyle() const;
     XMLFile* GetDefaultStyle() const;
+
     /// Return rendering stats text.
     /// Return rendering stats text.
     Text* GetStatsText() const { return statsText_; }
     Text* GetStatsText() const { return statsText_; }
+
     /// Return rendering mode text.
     /// Return rendering mode text.
     Text* GetModeText() const { return modeText_; }
     Text* GetModeText() const { return modeText_; }
+
     /// Return profiler text.
     /// Return profiler text.
     Text* GetProfilerText() const { return profilerText_; }
     Text* GetProfilerText() const { return profilerText_; }
+
     /// Return currently shown elements.
     /// Return currently shown elements.
     unsigned GetMode() const { return mode_; }
     unsigned GetMode() const { return mode_; }
+
     /// Return maximum profiler block depth.
     /// Return maximum profiler block depth.
     unsigned GetProfilerMaxDepth() const { return profilerMaxDepth_; }
     unsigned GetProfilerMaxDepth() const { return profilerMaxDepth_; }
+
     /// Return profiler accumulation interval in seconds
     /// Return profiler accumulation interval in seconds
     float GetProfilerInterval() const;
     float GetProfilerInterval() const;
 
 
     /// Return whether showing 3D geometry primitive/batch count only.
     /// Return whether showing 3D geometry primitive/batch count only.
     bool GetUseRendererStats() const { return useRendererStats_; }
     bool GetUseRendererStats() const { return useRendererStats_; }
+
     /// Set application-specific stats.
     /// Set application-specific stats.
     void SetAppStats(const String& label, const Variant& stats);
     void SetAppStats(const String& label, const Variant& stats);
     /// Set application-specific stats.
     /// Set application-specific stats.

+ 67 - 55
Source/Urho3D/Engine/Engine.cpp

@@ -20,30 +20,32 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Audio/Audio.h"
 #include "../Audio/Audio.h"
-#include "../Engine/Console.h"
 #include "../Core/Context.h"
 #include "../Core/Context.h"
 #include "../Core/CoreEvents.h"
 #include "../Core/CoreEvents.h"
+#include "../Core/ProcessUtils.h"
+#include "../Core/Profiler.h"
+#include "../Core/WorkQueue.h"
+#include "../Engine/Console.h"
 #include "../Engine/DebugHud.h"
 #include "../Engine/DebugHud.h"
 #include "../Engine/Engine.h"
 #include "../Engine/Engine.h"
-#include "../IO/FileSystem.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/Graphics.h"
+#include "../Graphics/Renderer.h"
+#include "../IO/FileSystem.h"
 #include "../Input/Input.h"
 #include "../Input/Input.h"
-#include "../Input/InputEvents.h"
 #include "../IO/Log.h"
 #include "../IO/Log.h"
+#include "../IO/PackageFile.h"
 #ifdef URHO3D_NAVIGATION
 #ifdef URHO3D_NAVIGATION
 #include "../Navigation/NavigationMesh.h"
 #include "../Navigation/NavigationMesh.h"
 #endif
 #endif
 #ifdef URHO3D_NETWORK
 #ifdef URHO3D_NETWORK
 #include "../Network/Network.h"
 #include "../Network/Network.h"
 #endif
 #endif
-#include "../IO/PackageFile.h"
 #ifdef URHO3D_PHYSICS
 #ifdef URHO3D_PHYSICS
 #include "../Physics/PhysicsWorld.h"
 #include "../Physics/PhysicsWorld.h"
 #endif
 #endif
-#include "../Core/ProcessUtils.h"
-#include "../Core/Profiler.h"
-#include "../Graphics/Renderer.h"
 #include "../Resource/ResourceCache.h"
 #include "../Resource/ResourceCache.h"
 #include "../Scene/Scene.h"
 #include "../Scene/Scene.h"
 #include "../Scene/SceneEvents.h"
 #include "../Scene/SceneEvents.h"
@@ -51,8 +53,6 @@
 #ifdef URHO3D_URHO2D
 #ifdef URHO3D_URHO2D
 #include "../Urho2D/Urho2D.h"
 #include "../Urho2D/Urho2D.h"
 #endif
 #endif
-#include "../Core/WorkQueue.h"
-#include "../Resource/XMLFile.h"
 
 
 #if defined(EMSCRIPTEN) && defined(URHO3D_TESTING)
 #if defined(EMSCRIPTEN) && defined(URHO3D_TESTING)
 #include <emscripten.h>
 #include <emscripten.h>
@@ -87,15 +87,15 @@ Engine::Engine(Context* context) :
     timeStep_(0.0f),
     timeStep_(0.0f),
     timeStepSmoothing_(2),
     timeStepSmoothing_(2),
     minFps_(10),
     minFps_(10),
-    #if defined(ANDROID) || defined(IOS) || defined(RPI)
+#if defined(ANDROID) || defined(IOS) || defined(RPI)
     maxFps_(60),
     maxFps_(60),
     maxInactiveFps_(10),
     maxInactiveFps_(10),
     pauseMinimized_(true),
     pauseMinimized_(true),
-    #else
+#else
     maxFps_(200),
     maxFps_(200),
     maxInactiveFps_(60),
     maxInactiveFps_(60),
     pauseMinimized_(false),
     pauseMinimized_(false),
-    #endif
+#endif
 #ifdef URHO3D_TESTING
 #ifdef URHO3D_TESTING
     timeOut_(0),
     timeOut_(0),
 #endif
 #endif
@@ -111,17 +111,17 @@ Engine::Engine(Context* context) :
     // Create subsystems which do not depend on engine initialization or startup parameters
     // Create subsystems which do not depend on engine initialization or startup parameters
     context_->RegisterSubsystem(new Time(context_));
     context_->RegisterSubsystem(new Time(context_));
     context_->RegisterSubsystem(new WorkQueue(context_));
     context_->RegisterSubsystem(new WorkQueue(context_));
-    #ifdef URHO3D_PROFILING
+#ifdef URHO3D_PROFILING
     context_->RegisterSubsystem(new Profiler(context_));
     context_->RegisterSubsystem(new Profiler(context_));
-    #endif
+#endif
     context_->RegisterSubsystem(new FileSystem(context_));
     context_->RegisterSubsystem(new FileSystem(context_));
-    #ifdef URHO3D_LOGGING
+#ifdef URHO3D_LOGGING
     context_->RegisterSubsystem(new Log(context_));
     context_->RegisterSubsystem(new Log(context_));
-    #endif
+#endif
     context_->RegisterSubsystem(new ResourceCache(context_));
     context_->RegisterSubsystem(new ResourceCache(context_));
-    #ifdef URHO3D_NETWORK
+#ifdef URHO3D_NETWORK
     context_->RegisterSubsystem(new Network(context_));
     context_->RegisterSubsystem(new Network(context_));
-    #endif
+#endif
     context_->RegisterSubsystem(new Input(context_));
     context_->RegisterSubsystem(new Input(context_));
     context_->RegisterSubsystem(new Audio(context_));
     context_->RegisterSubsystem(new Audio(context_));
     context_->RegisterSubsystem(new UI(context_));
     context_->RegisterSubsystem(new UI(context_));
@@ -202,7 +202,8 @@ bool Engine::Initialize(const VariantMap& parameters)
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     FileSystem* fileSystem = GetSubsystem<FileSystem>();
     FileSystem* fileSystem = GetSubsystem<FileSystem>();
 
 
-    String resourcePrefixPath = AddTrailingSlash(GetParameter(parameters, "ResourcePrefixPath", getenv("URHO3D_PREFIX_PATH")).GetString());
+    String resourcePrefixPath =
+        AddTrailingSlash(GetParameter(parameters, "ResourcePrefixPath", getenv("URHO3D_PREFIX_PATH")).GetString());
     if (resourcePrefixPath.Empty())
     if (resourcePrefixPath.Empty())
         resourcePrefixPath = fileSystem->GetProgramDir();
         resourcePrefixPath = fileSystem->GetProgramDir();
     else if (!IsAbsolutePath(resourcePrefixPath))
     else if (!IsAbsolutePath(resourcePrefixPath))
@@ -238,7 +239,8 @@ bool Engine::Initialize(const VariantMap& parameters)
 
 
         if (!success)
         if (!success)
         {
         {
-            LOGERRORF("Failed to add resource path '%s', check the documentation on how to set the 'resource prefix path'", resourcePaths[i].CString());
+            LOGERRORF("Failed to add resource path '%s', check the documentation on how to set the 'resource prefix path'",
+                resourcePaths[i].CString());
             return false;
             return false;
         }
         }
     }
     }
@@ -251,12 +253,15 @@ bool Engine::Initialize(const VariantMap& parameters)
         {
         {
             if (!cache->AddPackageFile(packageName))
             if (!cache->AddPackageFile(packageName))
             {
             {
-                LOGERRORF("Failed to add resource package '%s', check the documentation on how to set the 'resource prefix path'", resourcePackages[i].CString());
+                LOGERRORF("Failed to add resource package '%s', check the documentation on how to set the 'resource prefix path'",
+                    resourcePackages[i].CString());
                 return false;
                 return false;
             }
             }
         }
         }
         else
         else
-            LOGDEBUGF("Skip specified resource package '%s' as it does not exist, check the documentation on how to set the 'resource prefix path'", resourcePackages[i].CString());
+            LOGDEBUGF(
+                "Skip specified resource package '%s' as it does not exist, check the documentation on how to set the 'resource prefix path'",
+                resourcePackages[i].CString());
     }
     }
 
 
     // Add auto load folders. Prioritize these (if exist) before the default folders
     // Add auto load folders. Prioritize these (if exist) before the default folders
@@ -280,7 +285,9 @@ bool Engine::Initialize(const VariantMap& parameters)
                 String autoResourceDir = autoLoadPath + "/" + dir;
                 String autoResourceDir = autoLoadPath + "/" + dir;
                 if (!cache->AddResourceDir(autoResourceDir, 0))
                 if (!cache->AddResourceDir(autoResourceDir, 0))
                 {
                 {
-                    LOGERRORF("Failed to add resource directory '%s' in autoload path %s, check the documentation on how to set the 'resource prefix path'", dir.CString(), autoLoadPaths[i].CString());
+                    LOGERRORF(
+                        "Failed to add resource directory '%s' in autoload path %s, check the documentation on how to set the 'resource prefix path'",
+                        dir.CString(), autoLoadPaths[i].CString());
                     return false;
                     return false;
                 }
                 }
             }
             }
@@ -297,13 +304,17 @@ bool Engine::Initialize(const VariantMap& parameters)
                 String autoPackageName = autoLoadPath + "/" + pak;
                 String autoPackageName = autoLoadPath + "/" + pak;
                 if (!cache->AddPackageFile(autoPackageName, 0))
                 if (!cache->AddPackageFile(autoPackageName, 0))
                 {
                 {
-                    LOGERRORF("Failed to add package file '%s' in autoload path %s, check the documentation on how to set the 'resource prefix path'", pak.CString(), autoLoadPaths[i].CString());
+                    LOGERRORF(
+                        "Failed to add package file '%s' in autoload path %s, check the documentation on how to set the 'resource prefix path'",
+                        pak.CString(), autoLoadPaths[i].CString());
                     return false;
                     return false;
                 }
                 }
             }
             }
         }
         }
         else
         else
-            LOGDEBUGF("Skipped autoload path '%s' as it does not exist, check the documentation on how to set the 'resource prefix path'", autoLoadPaths[i].CString());
+            LOGDEBUGF(
+                "Skipped autoload path '%s' as it does not exist, check the documentation on how to set the 'resource prefix path'",
+                autoLoadPaths[i].CString());
     }
     }
 
 
     // Initialize graphics & audio output
     // Initialize graphics & audio output
@@ -320,12 +331,13 @@ bool Engine::Initialize(const VariantMap& parameters)
         graphics->SetOrientations(GetParameter(parameters, "Orientations", "LandscapeLeft LandscapeRight").GetString());
         graphics->SetOrientations(GetParameter(parameters, "Orientations", "LandscapeLeft LandscapeRight").GetString());
 
 
         if (HasParameter(parameters, "WindowPositionX") && HasParameter(parameters, "WindowPositionY"))
         if (HasParameter(parameters, "WindowPositionX") && HasParameter(parameters, "WindowPositionY"))
-            graphics->SetWindowPosition(GetParameter(parameters, "WindowPositionX").GetInt(), GetParameter(parameters, "WindowPositionY").GetInt());
+            graphics->SetWindowPosition(GetParameter(parameters, "WindowPositionX").GetInt(),
+                GetParameter(parameters, "WindowPositionY").GetInt());
 
 
-        #ifdef URHO3D_OPENGL
+#ifdef URHO3D_OPENGL
         if (HasParameter(parameters, "ForceGL2"))
         if (HasParameter(parameters, "ForceGL2"))
             graphics->SetForceGL2(GetParameter(parameters, "ForceGL2").GetBool());
             graphics->SetForceGL2(GetParameter(parameters, "ForceGL2").GetBool());
-        #endif
+#endif
 
 
         if (!graphics->SetMode(
         if (!graphics->SetMode(
             GetParameter(parameters, "WindowWidth", 0).GetInt(),
             GetParameter(parameters, "WindowWidth", 0).GetInt(),
@@ -370,20 +382,20 @@ bool Engine::Initialize(const VariantMap& parameters)
     if (HasParameter(parameters, "TouchEmulation"))
     if (HasParameter(parameters, "TouchEmulation"))
         GetSubsystem<Input>()->SetTouchEmulation(GetParameter(parameters, "TouchEmulation").GetBool());
         GetSubsystem<Input>()->SetTouchEmulation(GetParameter(parameters, "TouchEmulation").GetBool());
 
 
-    #ifdef URHO3D_TESTING
+#ifdef URHO3D_TESTING
     if (HasParameter(parameters, "TimeOut"))
     if (HasParameter(parameters, "TimeOut"))
         timeOut_ = GetParameter(parameters, "TimeOut", 0).GetInt() * 1000000LL;
         timeOut_ = GetParameter(parameters, "TimeOut", 0).GetInt() * 1000000LL;
-    #endif
+#endif
 
 
     // In debug mode, check now that all factory created objects can be created without crashing
     // In debug mode, check now that all factory created objects can be created without crashing
-    #ifdef _DEBUG
+#ifdef _DEBUG
     if (!resourcePaths.Empty())
     if (!resourcePaths.Empty())
     {
     {
         const HashMap<StringHash, SharedPtr<ObjectFactory> >& factories = context_->GetObjectFactories();
         const HashMap<StringHash, SharedPtr<ObjectFactory> >& factories = context_->GetObjectFactories();
         for (HashMap<StringHash, SharedPtr<ObjectFactory> >::ConstIterator i = factories.Begin(); i != factories.End(); ++i)
         for (HashMap<StringHash, SharedPtr<ObjectFactory> >::ConstIterator i = factories.Begin(); i != factories.End(); ++i)
             SharedPtr<Object> object = i->second_->CreateObject();
             SharedPtr<Object> object = i->second_->CreateObject();
     }
     }
-    #endif
+#endif
 
 
     frameTimer_.Reset();
     frameTimer_.Reset();
 
 
@@ -459,7 +471,7 @@ DebugHud* Engine::CreateDebugHud()
     if (headless_ || !initialized_)
     if (headless_ || !initialized_)
         return 0;
         return 0;
 
 
-     // Return existing debug HUD if possible
+    // Return existing debug HUD if possible
     DebugHud* debugHud = GetSubsystem<DebugHud>();
     DebugHud* debugHud = GetSubsystem<DebugHud>();
     if (!debugHud)
     if (!debugHud)
     {
     {
@@ -472,22 +484,22 @@ DebugHud* Engine::CreateDebugHud()
 
 
 void Engine::SetTimeStepSmoothing(int frames)
 void Engine::SetTimeStepSmoothing(int frames)
 {
 {
-    timeStepSmoothing_ = Clamp(frames, 1, 20);
+    timeStepSmoothing_ = (unsigned)Clamp(frames, 1, 20);
 }
 }
 
 
 void Engine::SetMinFps(int fps)
 void Engine::SetMinFps(int fps)
 {
 {
-    minFps_ = Max(fps, 0);
+    minFps_ = (unsigned)Max(fps, 0);
 }
 }
 
 
 void Engine::SetMaxFps(int fps)
 void Engine::SetMaxFps(int fps)
 {
 {
-    maxFps_ = Max(fps, 0);
+    maxFps_ = (unsigned)Max(fps, 0);
 }
 }
 
 
 void Engine::SetMaxInactiveFps(int fps)
 void Engine::SetMaxInactiveFps(int fps)
 {
 {
-    maxInactiveFps_ = Max(fps, 0);
+    maxInactiveFps_ = (unsigned)Max(fps, 0);
 }
 }
 
 
 void Engine::SetPauseMinimized(bool enable)
 void Engine::SetPauseMinimized(bool enable)
@@ -527,7 +539,7 @@ void Engine::DumpProfiler()
 
 
 void Engine::DumpResources(bool dumpFileName)
 void Engine::DumpResources(bool dumpFileName)
 {
 {
-    #ifdef URHO3D_LOGGING
+#ifdef URHO3D_LOGGING
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     const HashMap<StringHash, ResourceGroup>& resourceGroups = cache->GetAllResources();
     const HashMap<StringHash, ResourceGroup>& resourceGroups = cache->GetAllResources();
     LOGRAW("\n");
     LOGRAW("\n");
@@ -538,13 +550,13 @@ void Engine::DumpResources(bool dumpFileName)
     }
     }
 
 
     for (HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups.Begin();
     for (HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups.Begin();
-        i != resourceGroups.End(); ++i)
+         i != resourceGroups.End(); ++i)
     {
     {
         const HashMap<StringHash, SharedPtr<Resource> >& resources = i->second_.resources_;
         const HashMap<StringHash, SharedPtr<Resource> >& resources = i->second_.resources_;
         if (dumpFileName)
         if (dumpFileName)
         {
         {
             for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator j = resources.Begin();
             for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator j = resources.Begin();
-                j != resources.End(); ++j)
+                 j != resources.End(); ++j)
             {
             {
                 LOGRAW(j->second_->GetName() + "\n");
                 LOGRAW(j->second_->GetName() + "\n");
             }
             }
@@ -558,7 +570,7 @@ void Engine::DumpResources(bool dumpFileName)
             if (num)
             if (num)
             {
             {
                 LOGRAW("Resource type " + resources.Begin()->second_->GetTypeName() +
                 LOGRAW("Resource type " + resources.Begin()->second_->GetTypeName() +
-                    ": count " + String(num) + " memory use " + String(memoryUse) + "\n");
+                       ": count " + String(num) + " memory use " + String(memoryUse) + "\n");
             }
             }
         }
         }
     }
     }
@@ -567,13 +579,13 @@ void Engine::DumpResources(bool dumpFileName)
     {
     {
         LOGRAW("Total memory use of all resources " + String(cache->GetTotalMemoryUse()) + "\n\n");
         LOGRAW("Total memory use of all resources " + String(cache->GetTotalMemoryUse()) + "\n\n");
     }
     }
-    #endif
+#endif
 }
 }
 
 
 void Engine::DumpMemory()
 void Engine::DumpMemory()
 {
 {
-    #ifdef URHO3D_LOGGING
-    #if defined(_MSC_VER) && defined(_DEBUG)
+#ifdef URHO3D_LOGGING
+#if defined(_MSC_VER) && defined(_DEBUG)
     _CrtMemState state;
     _CrtMemState state;
     _CrtMemCheckpoint(&state);
     _CrtMemCheckpoint(&state);
     _CrtMemBlockHeader* block = state.pBlockHeader;
     _CrtMemBlockHeader* block = state.pBlockHeader;
@@ -604,10 +616,10 @@ void Engine::DumpMemory()
     }
     }
 
 
     LOGRAW("Total allocated memory " + String(total) + " bytes in " + String(blocks) + " blocks\n\n");
     LOGRAW("Total allocated memory " + String(total) + " bytes in " + String(blocks) + " blocks\n\n");
-    #else
+#else
     LOGRAW("DumpMemory() supported on MSVC debug mode only\n\n");
     LOGRAW("DumpMemory() supported on MSVC debug mode only\n\n");
-    #endif
-    #endif
+#endif
+#endif
 }
 }
 
 
 void Engine::Update()
 void Engine::Update()
@@ -683,14 +695,14 @@ void Engine::ApplyFrameLimit()
     }
     }
 
 
     elapsed = frameTimer_.GetUSec(true);
     elapsed = frameTimer_.GetUSec(true);
-    #ifdef URHO3D_TESTING
+#ifdef URHO3D_TESTING
     if (timeOut_ > 0)
     if (timeOut_ > 0)
     {
     {
         timeOut_ -= elapsed;
         timeOut_ -= elapsed;
         if (timeOut_ <= 0)
         if (timeOut_ <= 0)
             Exit();
             Exit();
     }
     }
-    #endif
+#endif
 
 
     // If FPS lower than minimum, clamp elapsed time
     // If FPS lower than minimum, clamp elapsed time
     if (minFps_)
     if (minFps_)
@@ -773,8 +785,8 @@ VariantMap Engine::ParseParameters(const Vector<String>& arguments)
                 ret["LogQuiet"] = true;
                 ret["LogQuiet"] = true;
             else if (argument == "log" && !value.Empty())
             else if (argument == "log" && !value.Empty())
             {
             {
-                int logLevel = GetStringListIndex(value.CString(), logLevelPrefixes, -1);
-                if (logLevel != -1)
+                unsigned logLevel = GetStringListIndex(value.CString(), logLevelPrefixes, M_MAX_UNSIGNED);
+                if (logLevel != M_MAX_UNSIGNED)
                 {
                 {
                     ret["LogLevel"] = logLevel;
                     ret["LogLevel"] = logLevel;
                     ++i;
                     ++i;
@@ -853,13 +865,13 @@ VariantMap Engine::ParseParameters(const Vector<String>& arguments)
             }
             }
             else if (argument == "touch")
             else if (argument == "touch")
                 ret["TouchEmulation"] = true;
                 ret["TouchEmulation"] = true;
-            #ifdef URHO3D_TESTING
+#ifdef URHO3D_TESTING
             else if (argument == "timeout" && !value.Empty())
             else if (argument == "timeout" && !value.Empty())
             {
             {
                 ret["TimeOut"] = ToInt(value);
                 ret["TimeOut"] = ToInt(value);
                 ++i;
                 ++i;
             }
             }
-            #endif
+#endif
         }
         }
     }
     }
 
 
@@ -896,9 +908,9 @@ void Engine::DoExit()
         graphics->Close();
         graphics->Close();
 
 
     exiting_ = true;
     exiting_ = true;
-    #if defined(EMSCRIPTEN) && defined(URHO3D_TESTING)
+#if defined(EMSCRIPTEN) && defined(URHO3D_TESTING)
     emscripten_force_exit(EXIT_SUCCESS);    // Some how this is required to signal emrun to stop
     emscripten_force_exit(EXIT_SUCCESS);    // Some how this is required to signal emrun to stop
-    #endif
+#endif
 }
 }
 
 
 }
 }

+ 18 - 8
Source/Urho3D/Engine/Engine.h

@@ -35,13 +35,13 @@ class DebugHud;
 class URHO3D_API Engine : public Object
 class URHO3D_API Engine : public Object
 {
 {
     OBJECT(Engine);
     OBJECT(Engine);
-    
+
 public:
 public:
     /// Construct.
     /// Construct.
     Engine(Context* context);
     Engine(Context* context);
     /// Destruct. Free all subsystems.
     /// Destruct. Free all subsystems.
     virtual ~Engine();
     virtual ~Engine();
-    
+
     /// Initialize engine using parameters given and show the application window. Return true if successful.
     /// Initialize engine using parameters given and show the application window. Return true if successful.
     bool Initialize(const VariantMap& parameters);
     bool Initialize(const VariantMap& parameters);
     /// Run one frame.
     /// Run one frame.
@@ -72,48 +72,58 @@ public:
     void DumpResources(bool dumpFileName = false);
     void DumpResources(bool dumpFileName = false);
     /// Dump information of all memory allocations to the log. Supported in MSVC debug mode only.
     /// Dump information of all memory allocations to the log. Supported in MSVC debug mode only.
     void DumpMemory();
     void DumpMemory();
-    
+
     /// Get timestep of the next frame. Updated by ApplyFrameLimit().
     /// Get timestep of the next frame. Updated by ApplyFrameLimit().
     float GetNextTimeStep() const { return timeStep_; }
     float GetNextTimeStep() const { return timeStep_; }
+
     /// Return the minimum frames per second.
     /// Return the minimum frames per second.
     int GetMinFps() const { return minFps_; }
     int GetMinFps() const { return minFps_; }
+
     /// Return the maximum frames per second.
     /// Return the maximum frames per second.
     int GetMaxFps() const { return maxFps_; }
     int GetMaxFps() const { return maxFps_; }
+
     /// Return the maximum frames per second when the application does not have input focus.
     /// Return the maximum frames per second when the application does not have input focus.
     int GetMaxInactiveFps() const { return maxInactiveFps_; }
     int GetMaxInactiveFps() const { return maxInactiveFps_; }
+
     /// Return how many frames to average for timestep smoothing.
     /// Return how many frames to average for timestep smoothing.
     int GetTimeStepSmoothing() const { return timeStepSmoothing_; }
     int GetTimeStepSmoothing() const { return timeStepSmoothing_; }
+
     /// Return whether to pause update events and audio when minimized.
     /// Return whether to pause update events and audio when minimized.
     bool GetPauseMinimized() const { return pauseMinimized_; }
     bool GetPauseMinimized() const { return pauseMinimized_; }
+
     /// Return whether to exit automatically on exit request.
     /// Return whether to exit automatically on exit request.
     bool GetAutoExit() const { return autoExit_; }
     bool GetAutoExit() const { return autoExit_; }
+
     /// Return whether engine has been initialized.
     /// Return whether engine has been initialized.
     bool IsInitialized() const { return initialized_; }
     bool IsInitialized() const { return initialized_; }
+
     /// Return whether exit has been requested.
     /// Return whether exit has been requested.
     bool IsExiting() const { return exiting_; }
     bool IsExiting() const { return exiting_; }
+
     /// Return whether the engine has been created in headless mode.
     /// Return whether the engine has been created in headless mode.
     bool IsHeadless() const { return headless_; }
     bool IsHeadless() const { return headless_; }
-    
+
     /// Send frame update events.
     /// Send frame update events.
     void Update();
     void Update();
     /// Render after frame update.
     /// Render after frame update.
     void Render();
     void Render();
     /// Get the timestep for the next frame and sleep for frame limiting if necessary.
     /// Get the timestep for the next frame and sleep for frame limiting if necessary.
     void ApplyFrameLimit();
     void ApplyFrameLimit();
-    
+
     /// Parse the engine startup parameters map from command line arguments.
     /// Parse the engine startup parameters map from command line arguments.
     static VariantMap ParseParameters(const Vector<String>& arguments);
     static VariantMap ParseParameters(const Vector<String>& arguments);
     /// Return whether startup parameters contains a specific parameter.
     /// Return whether startup parameters contains a specific parameter.
     static bool HasParameter(const VariantMap& parameters, const String& parameter);
     static bool HasParameter(const VariantMap& parameters, const String& parameter);
     /// Get an engine startup parameter, with default value if missing.
     /// Get an engine startup parameter, with default value if missing.
-    static const Variant& GetParameter(const VariantMap& parameters, const String& parameter, const Variant& defaultValue = Variant::EMPTY);
-    
+    static const Variant
+        & GetParameter(const VariantMap& parameters, const String& parameter, const Variant& defaultValue = Variant::EMPTY);
+
 private:
 private:
     /// Handle exit requested event. Auto-exit if enabled.
     /// Handle exit requested event. Auto-exit if enabled.
     void HandleExitRequested(StringHash eventType, VariantMap& eventData);
     void HandleExitRequested(StringHash eventType, VariantMap& eventData);
     /// Actually perform the exit actions.
     /// Actually perform the exit actions.
     void DoExit();
     void DoExit();
-    
+
     /// Frame update timer.
     /// Frame update timer.
     HiresTimer frameTimer_;
     HiresTimer frameTimer_;
     /// Previous timesteps for smoothing.
     /// Previous timesteps for smoothing.

+ 22 - 14
Source/Urho3D/Graphics/AnimatedModel.cpp

@@ -20,26 +20,27 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
+#include "../Core/Context.h"
+#include "../Core/Profiler.h"
 #include "../Graphics/AnimatedModel.h"
 #include "../Graphics/AnimatedModel.h"
 #include "../Graphics/Animation.h"
 #include "../Graphics/Animation.h"
 #include "../Graphics/AnimationState.h"
 #include "../Graphics/AnimationState.h"
 #include "../Graphics/Batch.h"
 #include "../Graphics/Batch.h"
 #include "../Graphics/Camera.h"
 #include "../Graphics/Camera.h"
-#include "../Core/Context.h"
 #include "../Graphics/DebugRenderer.h"
 #include "../Graphics/DebugRenderer.h"
 #include "../Graphics/DrawableEvents.h"
 #include "../Graphics/DrawableEvents.h"
 #include "../Graphics/Geometry.h"
 #include "../Graphics/Geometry.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/IndexBuffer.h"
 #include "../Graphics/IndexBuffer.h"
-#include "../IO/Log.h"
 #include "../Graphics/Material.h"
 #include "../Graphics/Material.h"
 #include "../Graphics/Octree.h"
 #include "../Graphics/Octree.h"
-#include "../Core/Profiler.h"
+#include "../Graphics/VertexBuffer.h"
+#include "../IO/Log.h"
 #include "../Resource/ResourceCache.h"
 #include "../Resource/ResourceCache.h"
 #include "../Resource/ResourceEvents.h"
 #include "../Resource/ResourceEvents.h"
 #include "../Scene/Scene.h"
 #include "../Scene/Scene.h"
-#include "../Container/Sort.h"
-#include "../Graphics/VertexBuffer.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -92,7 +93,8 @@ void AnimatedModel::RegisterObject(Context* context)
 
 
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
     MIXED_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
     MIXED_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
-    ACCESSOR_ATTRIBUTE("Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()), AM_DEFAULT);
+    ACCESSOR_ATTRIBUTE("Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()),
+        AM_DEFAULT);
     ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
     ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
     ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
     ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
@@ -102,9 +104,12 @@ void AnimatedModel::RegisterObject(Context* context)
     ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
     COPY_BASE_ATTRIBUTES(Drawable);
     COPY_BASE_ATTRIBUTES(Drawable);
-    MIXED_ACCESSOR_ATTRIBUTE("Bone Animation Enabled", GetBonesEnabledAttr, SetBonesEnabledAttr, VariantVector, Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
-    MIXED_ACCESSOR_ATTRIBUTE("Animation States", GetAnimationStatesAttr, SetAnimationStatesAttr, VariantVector, Variant::emptyVariantVector, AM_FILE);
-    ACCESSOR_ATTRIBUTE("Morphs", GetMorphsAttr, SetMorphsAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_DEFAULT | AM_NOEDIT);
+    MIXED_ACCESSOR_ATTRIBUTE("Bone Animation Enabled", GetBonesEnabledAttr, SetBonesEnabledAttr, VariantVector,
+        Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
+    MIXED_ACCESSOR_ATTRIBUTE("Animation States", GetAnimationStatesAttr, SetAnimationStatesAttr, VariantVector,
+        Variant::emptyVariantVector, AM_FILE);
+    ACCESSOR_ATTRIBUTE("Morphs", GetMorphsAttr, SetMorphsAttr, PODVector<unsigned char>, Variant::emptyBuffer,
+        AM_DEFAULT | AM_NOEDIT);
 }
 }
 
 
 bool AnimatedModel::Load(Deserializer& source, bool setInstanceDefault)
 bool AnimatedModel::Load(Deserializer& source, bool setInstanceDefault)
@@ -332,7 +337,8 @@ void AnimatedModel::SetModel(Model* model, bool createBones)
             newMorph.nameHash_ = morphs[i].nameHash_;
             newMorph.nameHash_ = morphs[i].nameHash_;
             newMorph.weight_ = 0.0f;
             newMorph.weight_ = 0.0f;
             newMorph.buffers_ = morphs[i].buffers_;
             newMorph.buffers_ = morphs[i].buffers_;
-            for (HashMap<unsigned, VertexBufferMorph>::ConstIterator j = morphs[i].buffers_.Begin(); j != morphs[i].buffers_.End(); ++j)
+            for (HashMap<unsigned, VertexBufferMorph>::ConstIterator j = morphs[i].buffers_.Begin();
+                 j != morphs[i].buffers_.End(); ++j)
                 morphElementMask_ |= j->second_.elementMask_;
                 morphElementMask_ |= j->second_.elementMask_;
             morphs_.Push(newMorph);
             morphs_.Push(newMorph);
         }
         }
@@ -660,7 +666,7 @@ void AnimatedModel::SetSkeleton(const Skeleton& skeleton, bool createBones)
             for (unsigned i = 0; i < destBones.Size(); ++i)
             for (unsigned i = 0; i < destBones.Size(); ++i)
             {
             {
                 if (destBones[i].node_ && destBones[i].name_ == srcBones[i].name_ && destBones[i].parentIndex_ ==
                 if (destBones[i].node_ && destBones[i].name_ == srcBones[i].name_ && destBones[i].parentIndex_ ==
-                    srcBones[i].parentIndex_)
+                                                                                     srcBones[i].parentIndex_)
                 {
                 {
                     // If compatible, just copy the values and retain the old node and animated status
                     // If compatible, just copy the values and retain the old node and animated status
                     Node* boneNode = destBones[i].node_;
                     Node* boneNode = destBones[i].node_;
@@ -789,7 +795,7 @@ void AnimatedModel::SetAnimationStatesAttr(const VariantVector& value)
             newState->SetLooped(value[index++].GetBool());
             newState->SetLooped(value[index++].GetBool());
             newState->SetWeight(value[index++].GetFloat());
             newState->SetWeight(value[index++].GetFloat());
             newState->SetTime(value[index++].GetFloat());
             newState->SetTime(value[index++].GetFloat());
-            newState->SetLayer(value[index++].GetInt());
+            newState->SetLayer((unsigned char)value[index++].GetInt());
         }
         }
         else
         else
         {
         {
@@ -1039,7 +1045,8 @@ void AnimatedModel::CloneGeometries()
     MarkMorphsDirty();
     MarkMorphsDirty();
 }
 }
 
 
-void AnimatedModel::CopyMorphVertices(void* destVertexData, void* srcVertexData, unsigned vertexCount, VertexBuffer* destBuffer, VertexBuffer* srcBuffer)
+void AnimatedModel::CopyMorphVertices(void* destVertexData, void* srcVertexData, unsigned vertexCount, VertexBuffer* destBuffer,
+    VertexBuffer* srcBuffer)
 {
 {
     unsigned mask = destBuffer->GetElementMask() & srcBuffer->GetElementMask();
     unsigned mask = destBuffer->GetElementMask() & srcBuffer->GetElementMask();
     unsigned normalOffset = srcBuffer->GetElementOffset(ELEMENT_NORMAL);
     unsigned normalOffset = srcBuffer->GetElementOffset(ELEMENT_NORMAL);
@@ -1266,7 +1273,8 @@ void AnimatedModel::UpdateMorphs()
     morphsDirty_ = false;
     morphsDirty_ = false;
 }
 }
 
 
-void AnimatedModel::ApplyMorph(VertexBuffer* buffer, void* destVertexData, unsigned morphRangeStart, const VertexBufferMorph& morph, float weight)
+void AnimatedModel::ApplyMorph(VertexBuffer* buffer, void* destVertexData, unsigned morphRangeStart, const VertexBufferMorph& morph,
+    float weight)
 {
 {
     unsigned elementMask = morph.elementMask_ & buffer->GetElementMask();
     unsigned elementMask = morph.elementMask_ & buffer->GetElementMask();
     unsigned vertexCount = morph.vertexCount_;
     unsigned vertexCount = morph.vertexCount_;

+ 14 - 1
Source/Urho3D/Graphics/AnimatedModel.h

@@ -97,10 +97,13 @@ public:
 
 
     /// Return skeleton.
     /// Return skeleton.
     Skeleton& GetSkeleton() { return skeleton_; }
     Skeleton& GetSkeleton() { return skeleton_; }
+
     /// Return all animation states.
     /// Return all animation states.
     const Vector<SharedPtr<AnimationState> >& GetAnimationStates() const { return animationStates_; }
     const Vector<SharedPtr<AnimationState> >& GetAnimationStates() const { return animationStates_; }
+
     /// Return number of animation states.
     /// Return number of animation states.
     unsigned GetNumAnimationStates() const { return animationStates_.Size(); }
     unsigned GetNumAnimationStates() const { return animationStates_.Size(); }
+
     /// Return animation state by animation pointer.
     /// Return animation state by animation pointer.
     AnimationState* GetAnimationState(Animation* animation) const;
     AnimationState* GetAnimationState(Animation* animation) const;
     /// Return animation state by animation name.
     /// Return animation state by animation name.
@@ -109,22 +112,29 @@ public:
     AnimationState* GetAnimationState(const StringHash animationNameHash) const;
     AnimationState* GetAnimationState(const StringHash animationNameHash) const;
     /// Return animation state by index.
     /// Return animation state by index.
     AnimationState* GetAnimationState(unsigned index) const;
     AnimationState* GetAnimationState(unsigned index) const;
+
     /// Return animation LOD bias.
     /// Return animation LOD bias.
     float GetAnimationLodBias() const { return animationLodBias_; }
     float GetAnimationLodBias() const { return animationLodBias_; }
+
     /// Return whether to update animation when not visible.
     /// Return whether to update animation when not visible.
     bool GetUpdateInvisible() const { return updateInvisible_; }
     bool GetUpdateInvisible() const { return updateInvisible_; }
+
     /// Return all vertex morphs.
     /// Return all vertex morphs.
     const Vector<ModelMorph>& GetMorphs() const { return morphs_; }
     const Vector<ModelMorph>& GetMorphs() const { return morphs_; }
+
     /// Return all morph vertex buffers.
     /// Return all morph vertex buffers.
     const Vector<SharedPtr<VertexBuffer> >& GetMorphVertexBuffers() const { return morphVertexBuffers_; }
     const Vector<SharedPtr<VertexBuffer> >& GetMorphVertexBuffers() const { return morphVertexBuffers_; }
+
     /// Return number of vertex morphs.
     /// Return number of vertex morphs.
     unsigned GetNumMorphs() const { return morphs_.Size(); }
     unsigned GetNumMorphs() const { return morphs_.Size(); }
+
     /// Return vertex morph weight by index.
     /// Return vertex morph weight by index.
     float GetMorphWeight(unsigned index) const;
     float GetMorphWeight(unsigned index) const;
     /// Return vertex morph weight by name.
     /// Return vertex morph weight by name.
     float GetMorphWeight(const String& name) const;
     float GetMorphWeight(const String& name) const;
     /// Return vertex morph weight by name hash.
     /// Return vertex morph weight by name hash.
     float GetMorphWeight(StringHash nameHash) const;
     float GetMorphWeight(StringHash nameHash) const;
+
     /// Return whether is the master (first) animated model.
     /// Return whether is the master (first) animated model.
     bool IsMaster() const { return isMaster_; }
     bool IsMaster() const { return isMaster_; }
 
 
@@ -144,8 +154,10 @@ public:
     VariantVector GetAnimationStatesAttr() const;
     VariantVector GetAnimationStatesAttr() const;
     /// Return morphs attribute.
     /// Return morphs attribute.
     const PODVector<unsigned char>& GetMorphsAttr() const;
     const PODVector<unsigned char>& GetMorphsAttr() const;
+
     /// Return per-geometry bone mappings.
     /// Return per-geometry bone mappings.
     const Vector<PODVector<unsigned> >& GetGeometryBoneMappings() const { return geometryBoneMappings_; }
     const Vector<PODVector<unsigned> >& GetGeometryBoneMappings() const { return geometryBoneMappings_; }
+
     /// Return per-geometry skin matrices. If empty, uses global skinning
     /// Return per-geometry skin matrices. If empty, uses global skinning
     const Vector<PODVector<Matrix3x4> >& GetGeometrySkinMatrices() const { return geometrySkinMatrices_; }
     const Vector<PODVector<Matrix3x4> >& GetGeometrySkinMatrices() const { return geometrySkinMatrices_; }
 
 
@@ -185,7 +197,8 @@ private:
     /// Reapply all vertex morphs.
     /// Reapply all vertex morphs.
     void UpdateMorphs();
     void UpdateMorphs();
     /// Apply a vertex morph.
     /// Apply a vertex morph.
-    void ApplyMorph(VertexBuffer* buffer, void* destVertexData, unsigned morphRangeStart, const VertexBufferMorph& morph, float weight);
+    void ApplyMorph
+        (VertexBuffer* buffer, void* destVertexData, unsigned morphRangeStart, const VertexBufferMorph& morph, float weight);
     /// Handle model reload finished.
     /// Handle model reload finished.
     void HandleModelReloadFinished(StringHash eventType, VariantMap& eventData);
     void HandleModelReloadFinished(StringHash eventType, VariantMap& eventData);
 
 

+ 28 - 26
Source/Urho3D/Graphics/Animation.cpp

@@ -20,14 +20,16 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
-#include "../Graphics/Animation.h"
+#include "../Precompiled.h"
+
 #include "../Core/Context.h"
 #include "../Core/Context.h"
+#include "../Core/Profiler.h"
+#include "../Graphics/Animation.h"
 #include "../IO/Deserializer.h"
 #include "../IO/Deserializer.h"
 #include "../IO/FileSystem.h"
 #include "../IO/FileSystem.h"
 #include "../IO/Log.h"
 #include "../IO/Log.h"
-#include "../Core/Profiler.h"
-#include "../Resource/ResourceCache.h"
 #include "../IO/Serializer.h"
 #include "../IO/Serializer.h"
+#include "../Resource/ResourceCache.h"
 #include "../Resource/XMLFile.h"
 #include "../Resource/XMLFile.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
@@ -44,14 +46,14 @@ void AnimationTrack::GetKeyFrameIndex(float time, unsigned& index) const
 {
 {
     if (time < 0.0f)
     if (time < 0.0f)
         time = 0.0f;
         time = 0.0f;
-    
+
     if (index >= keyFrames_.Size())
     if (index >= keyFrames_.Size())
         index = keyFrames_.Size() - 1;
         index = keyFrames_.Size() - 1;
-    
+
     // Check for being too far ahead
     // Check for being too far ahead
     while (index && time < keyFrames_[index].time_)
     while (index && time < keyFrames_[index].time_)
         --index;
         --index;
-    
+
     // Check for being too far behind
     // Check for being too far behind
     while (index < keyFrames_.Size() - 1 && time >= keyFrames_[index + 1].time_)
     while (index < keyFrames_.Size() - 1 && time >= keyFrames_[index + 1].time_)
         ++index;
         ++index;
@@ -75,24 +77,24 @@ void Animation::RegisterObject(Context* context)
 bool Animation::BeginLoad(Deserializer& source)
 bool Animation::BeginLoad(Deserializer& source)
 {
 {
     unsigned memoryUse = sizeof(Animation);
     unsigned memoryUse = sizeof(Animation);
-    
+
     // Check ID
     // Check ID
     if (source.ReadFileID() != "UANI")
     if (source.ReadFileID() != "UANI")
     {
     {
         LOGERROR(source.GetName() + " is not a valid animation file");
         LOGERROR(source.GetName() + " is not a valid animation file");
         return false;
         return false;
     }
     }
-    
+
     // Read name and length
     // Read name and length
     animationName_ = source.ReadString();
     animationName_ = source.ReadString();
     animationNameHash_ = animationName_;
     animationNameHash_ = animationName_;
     length_ = source.ReadFloat();
     length_ = source.ReadFloat();
     tracks_.Clear();
     tracks_.Clear();
-    
+
     unsigned tracks = source.ReadUInt();
     unsigned tracks = source.ReadUInt();
     tracks_.Resize(tracks);
     tracks_.Resize(tracks);
     memoryUse += tracks * sizeof(AnimationTrack);
     memoryUse += tracks * sizeof(AnimationTrack);
-    
+
     // Read tracks
     // Read tracks
     for (unsigned i = 0; i < tracks; ++i)
     for (unsigned i = 0; i < tracks; ++i)
     {
     {
@@ -100,11 +102,11 @@ bool Animation::BeginLoad(Deserializer& source)
         newTrack.name_ = source.ReadString();
         newTrack.name_ = source.ReadString();
         newTrack.nameHash_ = newTrack.name_;
         newTrack.nameHash_ = newTrack.name_;
         newTrack.channelMask_ = source.ReadUByte();
         newTrack.channelMask_ = source.ReadUByte();
-        
+
         unsigned keyFrames = source.ReadUInt();
         unsigned keyFrames = source.ReadUInt();
         newTrack.keyFrames_.Resize(keyFrames);
         newTrack.keyFrames_.Resize(keyFrames);
         memoryUse += keyFrames * sizeof(AnimationKeyFrame);
         memoryUse += keyFrames * sizeof(AnimationKeyFrame);
-        
+
         // Read keyframes of the track
         // Read keyframes of the track
         for (unsigned j = 0; j < keyFrames; ++j)
         for (unsigned j = 0; j < keyFrames; ++j)
         {
         {
@@ -118,11 +120,11 @@ bool Animation::BeginLoad(Deserializer& source)
                 newKeyFrame.scale_ = source.ReadVector3();
                 newKeyFrame.scale_ = source.ReadVector3();
         }
         }
     }
     }
-    
+
     // Optionally read triggers from an XML file
     // Optionally read triggers from an XML file
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     String xmlName = ReplaceExtension(GetName(), ".xml");
     String xmlName = ReplaceExtension(GetName(), ".xml");
-    
+
     SharedPtr<XMLFile> file(cache->GetTempResource<XMLFile>(xmlName, false));
     SharedPtr<XMLFile> file(cache->GetTempResource<XMLFile>(xmlName, false));
     if (file)
     if (file)
     {
     {
@@ -134,13 +136,13 @@ bool Animation::BeginLoad(Deserializer& source)
                 AddTrigger(triggerElem.GetFloat("normalizedtime"), true, triggerElem.GetVariant());
                 AddTrigger(triggerElem.GetFloat("normalizedtime"), true, triggerElem.GetVariant());
             else if (triggerElem.HasAttribute("time"))
             else if (triggerElem.HasAttribute("time"))
                 AddTrigger(triggerElem.GetFloat("time"), false, triggerElem.GetVariant());
                 AddTrigger(triggerElem.GetFloat("time"), false, triggerElem.GetVariant());
-            
+
             triggerElem = triggerElem.GetNext("trigger");
             triggerElem = triggerElem.GetNext("trigger");
         }
         }
 
 
         memoryUse += triggers_.Size() * sizeof(AnimationTriggerPoint);
         memoryUse += triggers_.Size() * sizeof(AnimationTriggerPoint);
     }
     }
-    
+
     SetMemoryUse(memoryUse);
     SetMemoryUse(memoryUse);
     return true;
     return true;
 }
 }
@@ -151,7 +153,7 @@ bool Animation::Save(Serializer& dest) const
     dest.WriteFileID("UANI");
     dest.WriteFileID("UANI");
     dest.WriteString(animationName_);
     dest.WriteString(animationName_);
     dest.WriteFloat(length_);
     dest.WriteFloat(length_);
-    
+
     // Write tracks
     // Write tracks
     dest.WriteUInt(tracks_.Size());
     dest.WriteUInt(tracks_.Size());
     for (unsigned i = 0; i < tracks_.Size(); ++i)
     for (unsigned i = 0; i < tracks_.Size(); ++i)
@@ -160,7 +162,7 @@ bool Animation::Save(Serializer& dest) const
         dest.WriteString(track.name_);
         dest.WriteString(track.name_);
         dest.WriteUByte(track.channelMask_);
         dest.WriteUByte(track.channelMask_);
         dest.WriteUInt(track.keyFrames_.Size());
         dest.WriteUInt(track.keyFrames_.Size());
-        
+
         // Write keyframes of the track
         // Write keyframes of the track
         for (unsigned j = 0; j < track.keyFrames_.Size(); ++j)
         for (unsigned j = 0; j < track.keyFrames_.Size(); ++j)
         {
         {
@@ -174,7 +176,7 @@ bool Animation::Save(Serializer& dest) const
                 dest.WriteVector3(keyFrame.scale_);
                 dest.WriteVector3(keyFrame.scale_);
         }
         }
     }
     }
-    
+
     // If triggers have been defined, write an XML file for them
     // If triggers have been defined, write an XML file for them
     if (triggers_.Size())
     if (triggers_.Size())
     {
     {
@@ -182,24 +184,24 @@ bool Animation::Save(Serializer& dest) const
         if (destFile)
         if (destFile)
         {
         {
             String xmlName = ReplaceExtension(destFile->GetName(), ".xml");
             String xmlName = ReplaceExtension(destFile->GetName(), ".xml");
-            
+
             SharedPtr<XMLFile> xml(new XMLFile(context_));
             SharedPtr<XMLFile> xml(new XMLFile(context_));
             XMLElement rootElem = xml->CreateRoot("animation");
             XMLElement rootElem = xml->CreateRoot("animation");
-            
+
             for (unsigned i = 0; i < triggers_.Size(); ++i)
             for (unsigned i = 0; i < triggers_.Size(); ++i)
             {
             {
                 XMLElement triggerElem = rootElem.CreateChild("trigger");
                 XMLElement triggerElem = rootElem.CreateChild("trigger");
                 triggerElem.SetFloat("time", triggers_[i].time_);
                 triggerElem.SetFloat("time", triggers_[i].time_);
                 triggerElem.SetVariant(triggers_[i].data_);
                 triggerElem.SetVariant(triggers_[i].data_);
             }
             }
-            
+
             File xmlFile(context_, xmlName, FILE_WRITE);
             File xmlFile(context_, xmlName, FILE_WRITE);
             xml->Save(xmlFile);
             xml->Save(xmlFile);
         }
         }
         else
         else
             LOGWARNING("Can not save animation trigger data when not saving into a file");
             LOGWARNING("Can not save animation trigger data when not saving into a file");
     }
     }
-    
+
     return true;
     return true;
 }
 }
 
 
@@ -225,7 +227,7 @@ void Animation::AddTrigger(float time, bool timeIsNormalized, const Variant& dat
     newTrigger.time_ = timeIsNormalized ? time * length_ : time;
     newTrigger.time_ = timeIsNormalized ? time * length_ : time;
     newTrigger.data_ = data;
     newTrigger.data_ = data;
     triggers_.Push(newTrigger);
     triggers_.Push(newTrigger);
-    
+
     Sort(triggers_.Begin(), triggers_.End(), CompareTriggers);
     Sort(triggers_.Begin(), triggers_.End(), CompareTriggers);
 }
 }
 
 
@@ -257,7 +259,7 @@ const AnimationTrack* Animation::GetTrack(const String& name) const
         if (i->name_ == name)
         if (i->name_ == name)
             return &(*i);
             return &(*i);
     }
     }
-    
+
     return 0;
     return 0;
 }
 }
 
 
@@ -268,7 +270,7 @@ const AnimationTrack* Animation::GetTrack(StringHash nameHash) const
         if (i->nameHash_ == nameHash)
         if (i->nameHash_ == nameHash)
             return &(*i);
             return &(*i);
     }
     }
-    
+
     return 0;
     return 0;
 }
 }
 
 

+ 17 - 10
Source/Urho3D/Graphics/Animation.h

@@ -22,10 +22,10 @@
 
 
 #pragma once
 #pragma once
 
 
-#include "../Math/Quaternion.h"
-#include "../Resource/Resource.h"
 #include "../Container/Ptr.h"
 #include "../Container/Ptr.h"
+#include "../Math/Quaternion.h"
 #include "../Math/Vector3.h"
 #include "../Math/Vector3.h"
+#include "../Resource/Resource.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {
@@ -48,7 +48,7 @@ struct AnimationTrack
 {
 {
     /// Return keyframe index based on time and previous index.
     /// Return keyframe index based on time and previous index.
     void GetKeyFrameIndex(float time, unsigned& index) const;
     void GetKeyFrameIndex(float time, unsigned& index) const;
-    
+
     /// Bone name.
     /// Bone name.
     String name_;
     String name_;
     /// Bone name hash.
     /// Bone name hash.
@@ -67,7 +67,7 @@ struct AnimationTriggerPoint
         time_(0.0f)
         time_(0.0f)
     {
     {
     }
     }
-    
+
     /// Trigger time.
     /// Trigger time.
     float time_;
     float time_;
     /// Trigger data.
     /// Trigger data.
@@ -82,7 +82,7 @@ static const unsigned char CHANNEL_SCALE = 0x4;
 class URHO3D_API Animation : public Resource
 class URHO3D_API Animation : public Resource
 {
 {
     OBJECT(Animation);
     OBJECT(Animation);
-    
+
 public:
 public:
     /// Construct.
     /// Construct.
     Animation(Context* context);
     Animation(Context* context);
@@ -90,12 +90,12 @@ public:
     virtual ~Animation();
     virtual ~Animation();
     /// Register object factory.
     /// Register object factory.
     static void RegisterObject(Context* context);
     static void RegisterObject(Context* context);
-    
+
     /// Load resource from stream. May be called from a worker thread. Return true if successful.
     /// Load resource from stream. May be called from a worker thread. Return true if successful.
     virtual bool BeginLoad(Deserializer& source);
     virtual bool BeginLoad(Deserializer& source);
     /// Save resource. Return true if successful.
     /// Save resource. Return true if successful.
     virtual bool Save(Serializer& dest) const;
     virtual bool Save(Serializer& dest) const;
-    
+
     /// Set animation name.
     /// Set animation name.
     void SetAnimationName(const String& name);
     void SetAnimationName(const String& name);
     /// Set animation length.
     /// Set animation length.
@@ -110,28 +110,35 @@ public:
     void RemoveAllTriggers();
     void RemoveAllTriggers();
     /// Resize trigger point vector.
     /// Resize trigger point vector.
     void SetNumTriggers(unsigned num);
     void SetNumTriggers(unsigned num);
-    
+
     /// Return animation name.
     /// Return animation name.
     const String& GetAnimationName() const { return animationName_; }
     const String& GetAnimationName() const { return animationName_; }
+
     /// Return animation name hash.
     /// Return animation name hash.
     StringHash GetAnimationNameHash() const { return animationNameHash_; }
     StringHash GetAnimationNameHash() const { return animationNameHash_; }
+
     /// Return animation length.
     /// Return animation length.
     float GetLength() const { return length_; }
     float GetLength() const { return length_; }
+
     /// Return all animation tracks.
     /// Return all animation tracks.
     const Vector<AnimationTrack>& GetTracks() const { return tracks_; }
     const Vector<AnimationTrack>& GetTracks() const { return tracks_; }
+
     /// Return number of animation tracks.
     /// Return number of animation tracks.
     unsigned GetNumTracks() const { return tracks_.Size(); }
     unsigned GetNumTracks() const { return tracks_.Size(); }
+
     /// Return animation track by index.
     /// Return animation track by index.
     const AnimationTrack* GetTrack(unsigned index) const;
     const AnimationTrack* GetTrack(unsigned index) const;
     /// Return animation track by bone name.
     /// Return animation track by bone name.
     const AnimationTrack* GetTrack(const String& name) const;
     const AnimationTrack* GetTrack(const String& name) const;
     /// Return animation track by bone name hash.
     /// Return animation track by bone name hash.
     const AnimationTrack* GetTrack(StringHash nameHash) const;
     const AnimationTrack* GetTrack(StringHash nameHash) const;
+
     /// Return animation trigger points.
     /// Return animation trigger points.
     const Vector<AnimationTriggerPoint>& GetTriggers() const { return triggers_; }
     const Vector<AnimationTriggerPoint>& GetTriggers() const { return triggers_; }
+
     /// Return number of animation trigger points.
     /// Return number of animation trigger points.
-    unsigned GetNumTriggers() const {return triggers_.Size(); }
-    
+    unsigned GetNumTriggers() const { return triggers_.Size(); }
+
 private:
 private:
     /// Animation name.
     /// Animation name.
     String animationName_;
     String animationName_;

+ 12 - 7
Source/Urho3D/Graphics/AnimationController.cpp

@@ -20,14 +20,16 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
+#include "../Core/Context.h"
+#include "../Core/Profiler.h"
 #include "../Graphics/AnimatedModel.h"
 #include "../Graphics/AnimatedModel.h"
 #include "../Graphics/Animation.h"
 #include "../Graphics/Animation.h"
 #include "../Graphics/AnimationController.h"
 #include "../Graphics/AnimationController.h"
 #include "../Graphics/AnimationState.h"
 #include "../Graphics/AnimationState.h"
-#include "../Core/Context.h"
 #include "../IO/Log.h"
 #include "../IO/Log.h"
 #include "../IO/MemoryBuffer.h"
 #include "../IO/MemoryBuffer.h"
-#include "../Core/Profiler.h"
 #include "../Resource/ResourceCache.h"
 #include "../Resource/ResourceCache.h"
 #include "../Scene/Scene.h"
 #include "../Scene/Scene.h"
 #include "../Scene/SceneEvents.h"
 #include "../Scene/SceneEvents.h"
@@ -62,9 +64,12 @@ void AnimationController::RegisterObject(Context* context)
     context->RegisterFactory<AnimationController>(LOGIC_CATEGORY);
     context->RegisterFactory<AnimationController>(LOGIC_CATEGORY);
 
 
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
-    MIXED_ACCESSOR_ATTRIBUTE("Animations", GetAnimationsAttr, SetAnimationsAttr, VariantVector, Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
-    ACCESSOR_ATTRIBUTE("Network Animations", GetNetAnimationsAttr, SetNetAnimationsAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT);
-    MIXED_ACCESSOR_ATTRIBUTE("Node Animation States", GetNodeAnimationStatesAttr, SetNodeAnimationStatesAttr, VariantVector, Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
+    MIXED_ACCESSOR_ATTRIBUTE("Animations", GetAnimationsAttr, SetAnimationsAttr, VariantVector, Variant::emptyVariantVector,
+        AM_FILE | AM_NOEDIT);
+    ACCESSOR_ATTRIBUTE("Network Animations", GetNetAnimationsAttr, SetNetAnimationsAttr, PODVector<unsigned char>,
+        Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT);
+    MIXED_ACCESSOR_ATTRIBUTE("Node Animation States", GetNodeAnimationStatesAttr, SetNodeAnimationStatesAttr, VariantVector,
+        Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
 }
 }
 
 
 void AnimationController::OnSetEnabled()
 void AnimationController::OnSetEnabled()
@@ -409,7 +414,7 @@ bool AnimationController::IsFadingOut(const String& name) const
         return false;
         return false;
 
 
     return (animations_[index].fadeTime_ && animations_[index].targetWeight_ < state->GetWeight())
     return (animations_[index].fadeTime_ && animations_[index].targetWeight_ < state->GetWeight())
-        || (!state->IsLooped() && state->GetTime() >= state->GetLength() && animations_[index].autoFadeTime_);
+           || (!state->IsLooped() && state->GetTime() >= state->GetLength() && animations_[index].autoFadeTime_);
 }
 }
 
 
 bool AnimationController::IsAtEnd(const String& name) const
 bool AnimationController::IsAtEnd(const String& name) const
@@ -426,7 +431,7 @@ bool AnimationController::IsAtEnd(const String& name) const
 unsigned char AnimationController::GetLayer(const String& name) const
 unsigned char AnimationController::GetLayer(const String& name) const
 {
 {
     AnimationState* state = GetAnimationState(name);
     AnimationState* state = GetAnimationState(name);
-    return state ? state->GetLayer() : 0;
+    return (unsigned char)(state ? state->GetLayer() : 0);
 }
 }
 
 
 Bone* AnimationController::GetStartBone(const String& name) const
 Bone* AnimationController::GetStartBone(const String& name) const

+ 1 - 1
Source/Urho3D/Graphics/AnimationController.h

@@ -22,8 +22,8 @@
 
 
 #pragma once
 #pragma once
 
 
-#include "../Scene/Component.h"
 #include "../IO/VectorBuffer.h"
 #include "../IO/VectorBuffer.h"
+#include "../Scene/Component.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {

+ 43 - 43
Source/Urho3D/Graphics/AnimationState.cpp

@@ -20,13 +20,13 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Graphics/AnimatedModel.h"
 #include "../Graphics/AnimatedModel.h"
 #include "../Graphics/Animation.h"
 #include "../Graphics/Animation.h"
 #include "../Graphics/AnimationState.h"
 #include "../Graphics/AnimationState.h"
-#include "../IO/Deserializer.h"
 #include "../Graphics/DrawableEvents.h"
 #include "../Graphics/DrawableEvents.h"
 #include "../IO/Log.h"
 #include "../IO/Log.h"
-#include "../IO/Serializer.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -74,7 +74,7 @@ AnimationState::AnimationState(Node* node, Animation* animation) :
         {
         {
             const Vector<AnimationTrack>& tracks = animation_->GetTracks();
             const Vector<AnimationTrack>& tracks = animation_->GetTracks();
             stateTracks_.Clear();
             stateTracks_.Clear();
-            
+
             for (unsigned i = 0; i < tracks.Size(); ++i)
             for (unsigned i = 0; i < tracks.Size(); ++i)
             {
             {
                 const StringHash& nameHash = tracks[i].nameHash_;
                 const StringHash& nameHash = tracks[i].nameHash_;
@@ -108,7 +108,7 @@ void AnimationState::SetStartBone(Bone* startBone)
 {
 {
     if (!model_ || !animation_)
     if (!model_ || !animation_)
         return;
         return;
-    
+
     Skeleton& skeleton = model_->GetSkeleton();
     Skeleton& skeleton = model_->GetSkeleton();
     if (!startBone)
     if (!startBone)
     {
     {
@@ -117,28 +117,28 @@ void AnimationState::SetStartBone(Bone* startBone)
             return;
             return;
         startBone = rootBone;
         startBone = rootBone;
     }
     }
-    
+
     // Do not reassign if the start bone did not actually change, and we already have valid bone nodes
     // Do not reassign if the start bone did not actually change, and we already have valid bone nodes
     if (startBone == startBone_ && !stateTracks_.Empty())
     if (startBone == startBone_ && !stateTracks_.Empty())
         return;
         return;
-    
+
     startBone_ = startBone;
     startBone_ = startBone;
-    
+
     const Vector<AnimationTrack>& tracks = animation_->GetTracks();
     const Vector<AnimationTrack>& tracks = animation_->GetTracks();
     stateTracks_.Clear();
     stateTracks_.Clear();
-    
+
     if (!startBone->node_)
     if (!startBone->node_)
         return;
         return;
-    
+
     for (unsigned i = 0; i < tracks.Size(); ++i)
     for (unsigned i = 0; i < tracks.Size(); ++i)
     {
     {
         AnimationStateTrack stateTrack;
         AnimationStateTrack stateTrack;
         stateTrack.track_ = &tracks[i];
         stateTrack.track_ = &tracks[i];
-        
+
         // Include those tracks that are either the start bone itself, or its children
         // Include those tracks that are either the start bone itself, or its children
         Bone* trackBone = 0;
         Bone* trackBone = 0;
         const StringHash& nameHash = tracks[i].nameHash_;
         const StringHash& nameHash = tracks[i].nameHash_;
-        
+
         if (nameHash == startBone->nameHash_)
         if (nameHash == startBone->nameHash_)
             trackBone = startBone;
             trackBone = startBone;
         else
         else
@@ -147,7 +147,7 @@ void AnimationState::SetStartBone(Bone* startBone)
             if (trackBoneNode)
             if (trackBoneNode)
                 trackBone = skeleton.GetBone(nameHash);
                 trackBone = skeleton.GetBone(nameHash);
         }
         }
-        
+
         if (trackBone && trackBone->node_)
         if (trackBone && trackBone->node_)
         {
         {
             stateTrack.bone_ = trackBone;
             stateTrack.bone_ = trackBone;
@@ -155,7 +155,7 @@ void AnimationState::SetStartBone(Bone* startBone)
             stateTracks_.Push(stateTrack);
             stateTracks_.Push(stateTrack);
         }
         }
     }
     }
-    
+
     model_->MarkAnimationDirty();
     model_->MarkAnimationDirty();
 }
 }
 
 
@@ -182,7 +182,7 @@ void AnimationState::SetTime(float time)
 {
 {
     if (!animation_)
     if (!animation_)
         return;
         return;
-    
+
     time = Clamp(time, 0.0f, animation_->GetLength());
     time = Clamp(time, 0.0f, animation_->GetLength());
     if (time != time_)
     if (time != time_)
     {
     {
@@ -196,16 +196,16 @@ void AnimationState::SetBoneWeight(unsigned index, float weight, bool recursive)
 {
 {
     if (index >= stateTracks_.Size())
     if (index >= stateTracks_.Size())
         return;
         return;
-    
+
     weight = Clamp(weight, 0.0f, 1.0f);
     weight = Clamp(weight, 0.0f, 1.0f);
-    
+
     if (weight != stateTracks_[index].weight_)
     if (weight != stateTracks_[index].weight_)
     {
     {
         stateTracks_[index].weight_ = weight;
         stateTracks_[index].weight_ = weight;
         if (model_)
         if (model_)
             model_->MarkAnimationDirty();
             model_->MarkAnimationDirty();
     }
     }
-    
+
     if (recursive)
     if (recursive)
     {
     {
         Node* boneNode = stateTracks_[index].node_;
         Node* boneNode = stateTracks_[index].node_;
@@ -236,7 +236,7 @@ void AnimationState::AddWeight(float delta)
 {
 {
     if (delta == 0.0f)
     if (delta == 0.0f)
         return;
         return;
-    
+
     SetWeight(GetWeight() + delta);
     SetWeight(GetWeight() + delta);
 }
 }
 
 
@@ -244,11 +244,11 @@ void AnimationState::AddTime(float delta)
 {
 {
     if (!animation_ || (!model_ && !node_))
     if (!animation_ || (!model_ && !node_))
         return;
         return;
-    
+
     float length = animation_->GetLength();
     float length = animation_->GetLength();
     if (delta == 0.0f || length == 0.0f)
     if (delta == 0.0f || length == 0.0f)
         return;
         return;
-    
+
     float oldTime = GetTime();
     float oldTime = GetTime();
     float time = oldTime + delta;
     float time = oldTime + delta;
     if (looped_)
     if (looped_)
@@ -258,14 +258,14 @@ void AnimationState::AddTime(float delta)
         while (time < 0.0f)
         while (time < 0.0f)
             time += length;
             time += length;
     }
     }
-    
+
     SetTime(time);
     SetTime(time);
-    
+
     // Process animation triggers
     // Process animation triggers
     if (animation_->GetNumTriggers())
     if (animation_->GetNumTriggers())
     {
     {
         bool wrap = false;
         bool wrap = false;
-        
+
         if (delta > 0.0f)
         if (delta > 0.0f)
         {
         {
             if (oldTime > time)
             if (oldTime > time)
@@ -284,20 +284,20 @@ void AnimationState::AddTime(float delta)
         }
         }
         if (oldTime > time)
         if (oldTime > time)
             Swap(oldTime, time);
             Swap(oldTime, time);
-        
+
         const Vector<AnimationTriggerPoint>& triggers = animation_->GetTriggers();
         const Vector<AnimationTriggerPoint>& triggers = animation_->GetTriggers();
         for (Vector<AnimationTriggerPoint>::ConstIterator i = triggers.Begin(); i != triggers.End(); ++i)
         for (Vector<AnimationTriggerPoint>::ConstIterator i = triggers.Begin(); i != triggers.End(); ++i)
         {
         {
             float frameTime = i->time_;
             float frameTime = i->time_;
             if (looped_ && wrap)
             if (looped_ && wrap)
                 frameTime = fmodf(frameTime, length);
                 frameTime = fmodf(frameTime, length);
-            
+
             if (oldTime <= frameTime && time > frameTime)
             if (oldTime <= frameTime && time > frameTime)
             {
             {
                 using namespace AnimationTrigger;
                 using namespace AnimationTrigger;
-                
+
                 Node* senderNode = model_ ? model_->GetNode() : node_;
                 Node* senderNode = model_ ? model_->GetNode() : node_;
-                
+
                 VariantMap& eventData = senderNode->GetEventDataMap();
                 VariantMap& eventData = senderNode->GetEventDataMap();
                 eventData[P_NODE] = senderNode;
                 eventData[P_NODE] = senderNode;
                 eventData[P_NAME] = animation_->GetAnimationName();
                 eventData[P_NAME] = animation_->GetAnimationName();
@@ -357,7 +357,7 @@ unsigned AnimationState::GetTrackIndex(const String& name) const
         if (node && node->GetName() == name)
         if (node && node->GetName() == name)
             return i;
             return i;
     }
     }
-    
+
     return M_MAX_UNSIGNED;
     return M_MAX_UNSIGNED;
 }
 }
 
 
@@ -393,7 +393,7 @@ void AnimationState::Apply()
 {
 {
     if (!animation_ || !IsEnabled())
     if (!animation_ || !IsEnabled())
         return;
         return;
-    
+
     if (model_)
     if (model_)
         ApplyToModel();
         ApplyToModel();
     else
     else
@@ -406,11 +406,11 @@ void AnimationState::ApplyToModel()
     {
     {
         AnimationStateTrack& stateTrack = *i;
         AnimationStateTrack& stateTrack = *i;
         float finalWeight = weight_ * stateTrack.weight_;
         float finalWeight = weight_ * stateTrack.weight_;
-        
+
         // Do not apply if zero effective weight or the bone has animation disabled
         // Do not apply if zero effective weight or the bone has animation disabled
         if (Equals(finalWeight, 0.0f) || !stateTrack.bone_->animated_)
         if (Equals(finalWeight, 0.0f) || !stateTrack.bone_->animated_)
             continue;
             continue;
-        
+
         if (Equals(finalWeight, 1.0f))
         if (Equals(finalWeight, 1.0f))
             ApplyTrackFullWeightSilent(stateTrack);
             ApplyTrackFullWeightSilent(stateTrack);
         else
         else
@@ -429,13 +429,13 @@ void AnimationState::ApplyTrackFullWeight(AnimationStateTrack& stateTrack)
 {
 {
     const AnimationTrack* track = stateTrack.track_;
     const AnimationTrack* track = stateTrack.track_;
     Node* node = stateTrack.node_;
     Node* node = stateTrack.node_;
-    
+
     if (track->keyFrames_.Empty() || !node)
     if (track->keyFrames_.Empty() || !node)
         return;
         return;
-    
+
     unsigned& frame = stateTrack.keyFrame_;
     unsigned& frame = stateTrack.keyFrame_;
     track->GetKeyFrameIndex(time_, frame);
     track->GetKeyFrameIndex(time_, frame);
-    
+
     // Check if next frame to interpolate to is valid, or if wrapping is needed (looping animation only)
     // Check if next frame to interpolate to is valid, or if wrapping is needed (looping animation only)
     unsigned nextFrame = frame + 1;
     unsigned nextFrame = frame + 1;
     bool interpolate = true;
     bool interpolate = true;
@@ -449,10 +449,10 @@ void AnimationState::ApplyTrackFullWeight(AnimationStateTrack& stateTrack)
         else
         else
             nextFrame = 0;
             nextFrame = 0;
     }
     }
-    
+
     const AnimationKeyFrame* keyFrame = &track->keyFrames_[frame];
     const AnimationKeyFrame* keyFrame = &track->keyFrames_[frame];
     unsigned char channelMask = track->channelMask_;
     unsigned char channelMask = track->channelMask_;
-    
+
     if (!interpolate)
     if (!interpolate)
     {
     {
         // No interpolation, full weight
         // No interpolation, full weight
@@ -470,7 +470,7 @@ void AnimationState::ApplyTrackFullWeight(AnimationStateTrack& stateTrack)
         if (timeInterval < 0.0f)
         if (timeInterval < 0.0f)
             timeInterval += animation_->GetLength();
             timeInterval += animation_->GetLength();
         float t = timeInterval > 0.0f ? (time_ - keyFrame->time_) / timeInterval : 1.0f;
         float t = timeInterval > 0.0f ? (time_ - keyFrame->time_) / timeInterval : 1.0f;
-        
+
         // Interpolation, full weight
         // Interpolation, full weight
         if (channelMask & CHANNEL_POSITION)
         if (channelMask & CHANNEL_POSITION)
             node->SetPosition(keyFrame->position_.Lerp(nextKeyFrame->position_, t));
             node->SetPosition(keyFrame->position_.Lerp(nextKeyFrame->position_, t));
@@ -541,13 +541,13 @@ void AnimationState::ApplyTrackBlendedSilent(AnimationStateTrack& stateTrack, fl
 {
 {
     const AnimationTrack* track = stateTrack.track_;
     const AnimationTrack* track = stateTrack.track_;
     Node* node = stateTrack.node_;
     Node* node = stateTrack.node_;
-    
+
     if (track->keyFrames_.Empty() || !node)
     if (track->keyFrames_.Empty() || !node)
         return;
         return;
-    
+
     unsigned& frame = stateTrack.keyFrame_;
     unsigned& frame = stateTrack.keyFrame_;
     track->GetKeyFrameIndex(time_, frame);
     track->GetKeyFrameIndex(time_, frame);
-    
+
     // Check if next frame to interpolate to is valid, or if wrapping is needed (looping animation only)
     // Check if next frame to interpolate to is valid, or if wrapping is needed (looping animation only)
     unsigned nextFrame = frame + 1;
     unsigned nextFrame = frame + 1;
     bool interpolate = true;
     bool interpolate = true;
@@ -561,10 +561,10 @@ void AnimationState::ApplyTrackBlendedSilent(AnimationStateTrack& stateTrack, fl
         else
         else
             nextFrame = 0;
             nextFrame = 0;
     }
     }
-    
+
     const AnimationKeyFrame* keyFrame = &track->keyFrames_[frame];
     const AnimationKeyFrame* keyFrame = &track->keyFrames_[frame];
     unsigned char channelMask = track->channelMask_;
     unsigned char channelMask = track->channelMask_;
-    
+
     if (!interpolate)
     if (!interpolate)
     {
     {
         // No interpolation, blend between old transform & animation
         // No interpolation, blend between old transform & animation
@@ -582,7 +582,7 @@ void AnimationState::ApplyTrackBlendedSilent(AnimationStateTrack& stateTrack, fl
         if (timeInterval < 0.0f)
         if (timeInterval < 0.0f)
             timeInterval += animation_->GetLength();
             timeInterval += animation_->GetLength();
         float t = timeInterval > 0.0f ? (time_ - keyFrame->time_) / timeInterval : 1.0f;
         float t = timeInterval > 0.0f ? (time_ - keyFrame->time_) / timeInterval : 1.0f;
-        
+
         // Interpolation, blend between old transform & animation
         // Interpolation, blend between old transform & animation
         if (channelMask & CHANNEL_POSITION)
         if (channelMask & CHANNEL_POSITION)
         {
         {

+ 12 - 5
Source/Urho3D/Graphics/AnimationState.h

@@ -43,7 +43,7 @@ struct AnimationStateTrack
     AnimationStateTrack();
     AnimationStateTrack();
     /// Destruct
     /// Destruct
     ~AnimationStateTrack();
     ~AnimationStateTrack();
-    
+
     /// Animation track.
     /// Animation track.
     const AnimationTrack* track_;
     const AnimationTrack* track_;
     /// Bone pointer.
     /// Bone pointer.
@@ -66,7 +66,7 @@ public:
     AnimationState(Node* node, Animation* animation);
     AnimationState(Node* node, Animation* animation);
     /// Destruct.
     /// Destruct.
     ~AnimationState();
     ~AnimationState();
-    
+
     /// Set start bone. Not supported in node animation mode. Resets any assigned per-bone weights.
     /// Set start bone. Not supported in node animation mode. Resets any assigned per-bone weights.
     void SetStartBone(Bone* bone);
     void SetStartBone(Bone* bone);
     /// Set looping enabled/disabled.
     /// Set looping enabled/disabled.
@@ -87,9 +87,10 @@ public:
     void AddTime(float delta);
     void AddTime(float delta);
     /// Set blending layer.
     /// Set blending layer.
     void SetLayer(unsigned char layer);
     void SetLayer(unsigned char layer);
-    
+
     /// Return animation.
     /// Return animation.
     Animation* GetAnimation() const { return animation_; }
     Animation* GetAnimation() const { return animation_; }
+
     /// Return animated model this state belongs to (model mode.)
     /// Return animated model this state belongs to (model mode.)
     AnimatedModel* GetModel() const;
     AnimatedModel* GetModel() const;
     /// Return root scene node this state controls (node hierarchy mode.)
     /// Return root scene node this state controls (node hierarchy mode.)
@@ -108,22 +109,28 @@ public:
     unsigned GetTrackIndex(const String& name) const;
     unsigned GetTrackIndex(const String& name) const;
     /// Return track index by bone name hash, or M_MAX_UNSIGNED if not found.
     /// Return track index by bone name hash, or M_MAX_UNSIGNED if not found.
     unsigned GetTrackIndex(StringHash nameHash) const;
     unsigned GetTrackIndex(StringHash nameHash) const;
+
     /// Return whether weight is nonzero.
     /// Return whether weight is nonzero.
     bool IsEnabled() const { return weight_ > 0.0f; }
     bool IsEnabled() const { return weight_ > 0.0f; }
+
     /// Return whether looped.
     /// Return whether looped.
     bool IsLooped() const { return looped_; }
     bool IsLooped() const { return looped_; }
+
     /// Return blending weight.
     /// Return blending weight.
     float GetWeight() const { return weight_; }
     float GetWeight() const { return weight_; }
+
     /// Return time position.
     /// Return time position.
     float GetTime() const { return time_; }
     float GetTime() const { return time_; }
+
     /// Return animation length.
     /// Return animation length.
     float GetLength() const;
     float GetLength() const;
+
     /// Return blending layer.
     /// Return blending layer.
     unsigned char GetLayer() const { return layer_; }
     unsigned char GetLayer() const { return layer_; }
-    
+
     /// Apply the animation at the current time position.
     /// Apply the animation at the current time position.
     void Apply();
     void Apply();
-    
+
 private:
 private:
     /// Apply animation to a skeleton. Transform changes are applied silently, so the model needs to dirty its root model afterward.
     /// Apply animation to a skeleton. Transform changes are applied silently, so the model needs to dirty its root model afterward.
     void ApplyToModel();
     void ApplyToModel();

+ 174 - 174
Source/Urho3D/Graphics/Batch.cpp

@@ -20,22 +20,20 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
 #include "../Graphics/Camera.h"
 #include "../Graphics/Camera.h"
 #include "../Graphics/Geometry.h"
 #include "../Graphics/Geometry.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/GraphicsImpl.h"
 #include "../Graphics/GraphicsImpl.h"
 #include "../Graphics/Material.h"
 #include "../Graphics/Material.h"
-#include "../Scene/Node.h"
 #include "../Graphics/Renderer.h"
 #include "../Graphics/Renderer.h"
-#include "../Core/Profiler.h"
-#include "../Scene/Scene.h"
 #include "../Graphics/ShaderVariation.h"
 #include "../Graphics/ShaderVariation.h"
-#include "../Container/Sort.h"
 #include "../Graphics/Technique.h"
 #include "../Graphics/Technique.h"
 #include "../Graphics/Texture2D.h"
 #include "../Graphics/Texture2D.h"
 #include "../Graphics/VertexBuffer.h"
 #include "../Graphics/VertexBuffer.h"
 #include "../Graphics/View.h"
 #include "../Graphics/View.h"
-#include "../Graphics/Zone.h"
+#include "../Scene/Scene.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -75,25 +73,25 @@ void CalculateShadowMatrix(Matrix4& dest, LightBatchQueue* queue, unsigned split
 {
 {
     Camera* shadowCamera = queue->shadowSplits_[split].shadowCamera_;
     Camera* shadowCamera = queue->shadowSplits_[split].shadowCamera_;
     const IntRect& viewport = queue->shadowSplits_[split].shadowViewport_;
     const IntRect& viewport = queue->shadowSplits_[split].shadowViewport_;
-    
+
     Matrix3x4 posAdjust(translation, Quaternion::IDENTITY, 1.0f);
     Matrix3x4 posAdjust(translation, Quaternion::IDENTITY, 1.0f);
     Matrix3x4 shadowView(shadowCamera->GetView());
     Matrix3x4 shadowView(shadowCamera->GetView());
     Matrix4 shadowProj(shadowCamera->GetProjection());
     Matrix4 shadowProj(shadowCamera->GetProjection());
     Matrix4 texAdjust(Matrix4::IDENTITY);
     Matrix4 texAdjust(Matrix4::IDENTITY);
-    
+
     Texture2D* shadowMap = queue->shadowMap_;
     Texture2D* shadowMap = queue->shadowMap_;
     if (!shadowMap)
     if (!shadowMap)
         return;
         return;
-    
+
     float width = (float)shadowMap->GetWidth();
     float width = (float)shadowMap->GetWidth();
     float height = (float)shadowMap->GetHeight();
     float height = (float)shadowMap->GetHeight();
-    
+
     Vector3 offset(
     Vector3 offset(
         (float)viewport.left_ / width,
         (float)viewport.left_ / width,
         (float)viewport.top_ / height,
         (float)viewport.top_ / height,
         0.0f
         0.0f
     );
     );
-    
+
     Vector3 scale(
     Vector3 scale(
         0.5f * (float)viewport.Width() / width,
         0.5f * (float)viewport.Width() / width,
         0.5f * (float)viewport.Height() / height,
         0.5f * (float)viewport.Height() / height,
@@ -105,13 +103,13 @@ void CalculateShadowMatrix(Matrix4& dest, LightBatchQueue* queue, unsigned split
     offset.x_ += scale.x_ + pixelUVOffset.x_ / width;
     offset.x_ += scale.x_ + pixelUVOffset.x_ / width;
     offset.y_ += scale.y_ + pixelUVOffset.y_ / height;
     offset.y_ += scale.y_ + pixelUVOffset.y_ / height;
 
 
-    #ifdef URHO3D_OPENGL
+#ifdef URHO3D_OPENGL
     offset.z_ = 0.5f;
     offset.z_ = 0.5f;
     scale.z_ = 0.5f;
     scale.z_ = 0.5f;
     offset.y_ = 1.0f - offset.y_;
     offset.y_ = 1.0f - offset.y_;
-    #else
+#else
     scale.y_ = -scale.y_;
     scale.y_ = -scale.y_;
-    #endif
+#endif
 
 
     // If using 4 shadow samples, offset the position diagonally by half pixel
     // If using 4 shadow samples, offset the position diagonally by half pixel
     if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
     if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
@@ -121,7 +119,7 @@ void CalculateShadowMatrix(Matrix4& dest, LightBatchQueue* queue, unsigned split
     }
     }
     texAdjust.SetTranslation(offset);
     texAdjust.SetTranslation(offset);
     texAdjust.SetScale(scale);
     texAdjust.SetScale(scale);
-    
+
     dest = texAdjust * shadowProj * shadowView * posAdjust;
     dest = texAdjust * shadowProj * shadowView * posAdjust;
 }
 }
 
 
@@ -132,7 +130,7 @@ void CalculateSpotMatrix(Matrix4& dest, Light* light, const Vector3& translation
     Matrix3x4 spotView = Matrix3x4(lightNode->GetWorldPosition(), lightNode->GetWorldRotation(), 1.0f).Inverse();
     Matrix3x4 spotView = Matrix3x4(lightNode->GetWorldPosition(), lightNode->GetWorldRotation(), 1.0f).Inverse();
     Matrix4 spotProj(Matrix4::ZERO);
     Matrix4 spotProj(Matrix4::ZERO);
     Matrix4 texAdjust(Matrix4::IDENTITY);
     Matrix4 texAdjust(Matrix4::IDENTITY);
-    
+
     // Make the projected light slightly smaller than the shadow map to prevent light spill
     // Make the projected light slightly smaller than the shadow map to prevent light spill
     float h = 1.005f / tanf(light->GetFov() * M_DEGTORAD * 0.5f);
     float h = 1.005f / tanf(light->GetFov() * M_DEGTORAD * 0.5f);
     float w = h / light->GetAspectRatio();
     float w = h / light->GetAspectRatio();
@@ -140,39 +138,41 @@ void CalculateSpotMatrix(Matrix4& dest, Light* light, const Vector3& translation
     spotProj.m11_ = h;
     spotProj.m11_ = h;
     spotProj.m22_ = 1.0f / Max(light->GetRange(), M_EPSILON);
     spotProj.m22_ = 1.0f / Max(light->GetRange(), M_EPSILON);
     spotProj.m32_ = 1.0f;
     spotProj.m32_ = 1.0f;
-    
-    #ifdef URHO3D_OPENGL
+
+#ifdef URHO3D_OPENGL
     texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
     texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
     texAdjust.SetScale(Vector3(0.5f, -0.5f, 0.5f));
     texAdjust.SetScale(Vector3(0.5f, -0.5f, 0.5f));
-    #else
+#else
     texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.0f));
     texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.0f));
     texAdjust.SetScale(Vector3(0.5f, -0.5f, 1.0f));
     texAdjust.SetScale(Vector3(0.5f, -0.5f, 1.0f));
-    #endif
-    
+#endif
+
     dest = texAdjust * spotProj * spotView * posAdjust;
     dest = texAdjust * spotProj * spotView * posAdjust;
 }
 }
 
 
 void Batch::CalculateSortKey()
 void Batch::CalculateSortKey()
 {
 {
-    unsigned shaderID = ((*((unsigned*)&vertexShader_) / sizeof(ShaderVariation)) + (*((unsigned*)&pixelShader_) / sizeof(ShaderVariation))) & 0x3fff;
+    unsigned shaderID = (unsigned)(
+        ((*((unsigned*)&vertexShader_) / sizeof(ShaderVariation)) + (*((unsigned*)&pixelShader_) / sizeof(ShaderVariation))) &
+        0x3fff);
     if (!isBase_)
     if (!isBase_)
         shaderID |= 0x8000;
         shaderID |= 0x8000;
     if (pass_ && pass_->GetAlphaMask())
     if (pass_ && pass_->GetAlphaMask())
         shaderID |= 0x4000;
         shaderID |= 0x4000;
-    
-    unsigned lightQueueID = (*((unsigned*)&lightQueue_) / sizeof(LightBatchQueue)) & 0xffff;
-    unsigned materialID = (*((unsigned*)&material_) / sizeof(Material)) & 0xffff;
-    unsigned geometryID = (*((unsigned*)&geometry_) / sizeof(Geometry)) & 0xffff;
-    
+
+    unsigned lightQueueID = (unsigned)((*((unsigned*)&lightQueue_) / sizeof(LightBatchQueue)) & 0xffff);
+    unsigned materialID = (unsigned)((*((unsigned*)&material_) / sizeof(Material)) & 0xffff);
+    unsigned geometryID = (unsigned)((*((unsigned*)&geometry_) / sizeof(Geometry)) & 0xffff);
+
     sortKey_ = (((unsigned long long)shaderID) << 48) | (((unsigned long long)lightQueueID) << 32) |
     sortKey_ = (((unsigned long long)shaderID) << 48) | (((unsigned long long)lightQueueID) << 32) |
-        (((unsigned long long)materialID) << 16) | geometryID;
+               (((unsigned long long)materialID) << 16) | geometryID;
 }
 }
 
 
 void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) const
 void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) const
 {
 {
     if (!vertexShader_ || !pixelShader_)
     if (!vertexShader_ || !pixelShader_)
         return;
         return;
-    
+
     Graphics* graphics = view->GetGraphics();
     Graphics* graphics = view->GetGraphics();
     Renderer* renderer = view->GetRenderer();
     Renderer* renderer = view->GetRenderer();
     Node* cameraNode = camera_ ? camera_->GetNode() : 0;
     Node* cameraNode = camera_ ? camera_->GetNode() : 0;
@@ -209,34 +209,34 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
         graphics->SetDepthTest(pass_->GetDepthTestMode());
         graphics->SetDepthTest(pass_->GetDepthTestMode());
         graphics->SetDepthWrite(pass_->GetDepthWrite() && allowDepthWrite);
         graphics->SetDepthWrite(pass_->GetDepthWrite() && allowDepthWrite);
     }
     }
-    
+
     // Set global (per-frame) shader parameters
     // Set global (per-frame) shader parameters
     if (graphics->NeedParameterUpdate(SP_FRAME, (void*)0))
     if (graphics->NeedParameterUpdate(SP_FRAME, (void*)0))
         view->SetGlobalShaderParameters();
         view->SetGlobalShaderParameters();
-    
+
     // Set camera & viewport shader parameters
     // Set camera & viewport shader parameters
     unsigned cameraHash = (unsigned)(size_t)camera_;
     unsigned cameraHash = (unsigned)(size_t)camera_;
     IntRect viewport = graphics->GetViewport();
     IntRect viewport = graphics->GetViewport();
     IntVector2 viewSize = IntVector2(viewport.Width(), viewport.Height());
     IntVector2 viewSize = IntVector2(viewport.Width(), viewport.Height());
-    unsigned viewportHash = viewSize.x_ | (viewSize.y_ << 16);
+    unsigned viewportHash = (unsigned)(viewSize.x_ | (viewSize.y_ << 16));
     if (graphics->NeedParameterUpdate(SP_CAMERA, reinterpret_cast<const void*>(cameraHash + viewportHash)))
     if (graphics->NeedParameterUpdate(SP_CAMERA, reinterpret_cast<const void*>(cameraHash + viewportHash)))
     {
     {
         view->SetCameraShaderParameters(camera_, true);
         view->SetCameraShaderParameters(camera_, true);
         // During renderpath commands the G-Buffer or viewport texture is assumed to always be viewport-sized
         // During renderpath commands the G-Buffer or viewport texture is assumed to always be viewport-sized
         view->SetGBufferShaderParameters(viewSize, IntRect(0, 0, viewSize.x_, viewSize.y_));
         view->SetGBufferShaderParameters(viewSize, IntRect(0, 0, viewSize.x_, viewSize.y_));
     }
     }
-    
+
     // Set model or skinning transforms
     // Set model or skinning transforms
     if (setModelTransform && graphics->NeedParameterUpdate(SP_OBJECT, worldTransform_))
     if (setModelTransform && graphics->NeedParameterUpdate(SP_OBJECT, worldTransform_))
     {
     {
         if (geometryType_ == GEOM_SKINNED)
         if (geometryType_ == GEOM_SKINNED)
         {
         {
-            graphics->SetShaderParameter(VSP_SKINMATRICES, reinterpret_cast<const float*>(worldTransform_), 
+            graphics->SetShaderParameter(VSP_SKINMATRICES, reinterpret_cast<const float*>(worldTransform_),
                 12 * numWorldTransforms_);
                 12 * numWorldTransforms_);
         }
         }
         else
         else
             graphics->SetShaderParameter(VSP_MODEL, *worldTransform_);
             graphics->SetShaderParameter(VSP_MODEL, *worldTransform_);
-        
+
         // Set the orientation for billboards, either from the object itself or from the camera
         // Set the orientation for billboards, either from the object itself or from the camera
         if (geometryType_ == GEOM_BILLBOARD)
         if (geometryType_ == GEOM_BILLBOARD)
         {
         {
@@ -246,7 +246,7 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
                 graphics->SetShaderParameter(VSP_BILLBOARDROT, cameraNode->GetWorldRotation().RotationMatrix());
                 graphics->SetShaderParameter(VSP_BILLBOARDROT, cameraNode->GetWorldRotation().RotationMatrix());
         }
         }
     }
     }
-    
+
     // Set zone-related shader parameters
     // Set zone-related shader parameters
     BlendMode blend = graphics->GetBlendMode();
     BlendMode blend = graphics->GetBlendMode();
     // If the pass is additive, override fog color to black so that shaders do not need a separate additive path
     // If the pass is additive, override fog color to black so that shaders do not need a separate additive path
@@ -257,8 +257,9 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
     if (zone_ && graphics->NeedParameterUpdate(SP_ZONE, reinterpret_cast<const void*>(zoneHash)))
     if (zone_ && graphics->NeedParameterUpdate(SP_ZONE, reinterpret_cast<const void*>(zoneHash)))
     {
     {
         graphics->SetShaderParameter(VSP_AMBIENTSTARTCOLOR, zone_->GetAmbientStartColor());
         graphics->SetShaderParameter(VSP_AMBIENTSTARTCOLOR, zone_->GetAmbientStartColor());
-        graphics->SetShaderParameter(VSP_AMBIENTENDCOLOR, zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4());
-        
+        graphics->SetShaderParameter(VSP_AMBIENTENDCOLOR,
+            zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4());
+
         const BoundingBox& box = zone_->GetBoundingBox();
         const BoundingBox& box = zone_->GetBoundingBox();
         Vector3 boxSize = box.Size();
         Vector3 boxSize = box.Size();
         Matrix3x4 adjust(Matrix3x4::IDENTITY);
         Matrix3x4 adjust(Matrix3x4::IDENTITY);
@@ -266,10 +267,10 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
         adjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
         adjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
         Matrix3x4 zoneTransform = adjust * zone_->GetInverseWorldTransform();
         Matrix3x4 zoneTransform = adjust * zone_->GetInverseWorldTransform();
         graphics->SetShaderParameter(VSP_ZONE, zoneTransform);
         graphics->SetShaderParameter(VSP_ZONE, zoneTransform);
-        
+
         graphics->SetShaderParameter(PSP_AMBIENTCOLOR, zone_->GetAmbientColor());
         graphics->SetShaderParameter(PSP_AMBIENTCOLOR, zone_->GetAmbientColor());
         graphics->SetShaderParameter(PSP_FOGCOLOR, overrideFogColorToBlack ? Color::BLACK : zone_->GetFogColor());
         graphics->SetShaderParameter(PSP_FOGCOLOR, overrideFogColorToBlack ? Color::BLACK : zone_->GetFogColor());
-        
+
         float farClip = camera_->GetFarClip();
         float farClip = camera_->GetFarClip();
         float fogStart = Min(zone_->GetFogStart(), farClip);
         float fogStart = Min(zone_->GetFogStart(), farClip);
         float fogEnd = Min(zone_->GetFogEnd(), farClip);
         float fogEnd = Min(zone_->GetFogEnd(), farClip);
@@ -277,7 +278,7 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
             fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
             fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
         float fogRange = Max(fogEnd - fogStart, M_EPSILON);
         float fogRange = Max(fogEnd - fogStart, M_EPSILON);
         Vector4 fogParams(fogEnd / farClip, farClip / fogRange, 0.0f, 0.0f);
         Vector4 fogParams(fogEnd / farClip, farClip / fogRange, 0.0f, 0.0f);
-        
+
         Node* zoneNode = zone_->GetNode();
         Node* zoneNode = zone_->GetNode();
         if (zone_->GetHeightFog() && zoneNode)
         if (zone_->GetHeightFog() && zoneNode)
         {
         {
@@ -285,10 +286,10 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
             fogParams.z_ = worldFogHeightVec.y_;
             fogParams.z_ = worldFogHeightVec.y_;
             fogParams.w_ = zone_->GetFogHeightScale() / Max(zoneNode->GetWorldScale().y_, M_EPSILON);
             fogParams.w_ = zone_->GetFogHeightScale() / Max(zoneNode->GetWorldScale().y_, M_EPSILON);
         }
         }
-        
+
         graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams);
         graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams);
     }
     }
-    
+
     // Set light-related shader parameters
     // Set light-related shader parameters
     if (lightQueue_)
     if (lightQueue_)
     {
     {
@@ -313,42 +314,42 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
                 switch (light->GetLightType())
                 switch (light->GetLightType())
                 {
                 {
                 case LIGHT_DIRECTIONAL:
                 case LIGHT_DIRECTIONAL:
-                {
-                    Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
-                    unsigned numSplits = Min(MAX_CASCADE_SPLITS, (int)lightQueue_->shadowSplits_.Size());
+                    {
+                        Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
+                        unsigned numSplits = (unsigned)Min(MAX_CASCADE_SPLITS, (int)lightQueue_->shadowSplits_.Size());
 
 
-                    for (unsigned i = 0; i < numSplits; ++i)
-                        CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, Vector3::ZERO);
+                        for (unsigned i = 0; i < numSplits; ++i)
+                            CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, Vector3::ZERO);
 
 
-                    graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
-                }
-                break;
+                        graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
+                    }
+                    break;
 
 
                 case LIGHT_SPOT:
                 case LIGHT_SPOT:
-                {
-                    Matrix4 shadowMatrices[2];
+                    {
+                        Matrix4 shadowMatrices[2];
 
 
-                    CalculateSpotMatrix(shadowMatrices[0], light, Vector3::ZERO);
-                    bool isShadowed = shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP);
-                    if (isShadowed)
-                        CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, Vector3::ZERO);
+                        CalculateSpotMatrix(shadowMatrices[0], light, Vector3::ZERO);
+                        bool isShadowed = shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP);
+                        if (isShadowed)
+                            CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, Vector3::ZERO);
 
 
-                    graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
-                }
-                break;
+                        graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
+                    }
+                    break;
 
 
                 case LIGHT_POINT:
                 case LIGHT_POINT:
-                {
-                    Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
-                    // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
-                    // the next parameter
-                    #ifdef URHO3D_OPENGL
-                    graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 16);
-                    #else
-                    graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 12);
-                    #endif
-                }
-                break;
+                    {
+                        Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
+                        // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
+                        // the next parameter
+#ifdef URHO3D_OPENGL
+                        graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 16);
+#else
+                        graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 12);
+#endif
+                    }
+                    break;
                 }
                 }
             }
             }
 
 
@@ -364,55 +365,56 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
             graphics->SetShaderParameter(PSP_LIGHTCOLOR, Color(light->GetEffectiveColor().Abs(),
             graphics->SetShaderParameter(PSP_LIGHTCOLOR, Color(light->GetEffectiveColor().Abs(),
                 light->GetEffectiveSpecularIntensity()) * fade);
                 light->GetEffectiveSpecularIntensity()) * fade);
             graphics->SetShaderParameter(PSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
             graphics->SetShaderParameter(PSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
-            graphics->SetShaderParameter(PSP_LIGHTPOS, Vector4((isLightVolume ? (lightNode->GetWorldPosition() -
-                cameraEffectivePos) : lightNode->GetWorldPosition()), atten));
+            graphics->SetShaderParameter(PSP_LIGHTPOS,
+                Vector4((isLightVolume ? (lightNode->GetWorldPosition() - cameraEffectivePos) : lightNode->GetWorldPosition()),
+                    atten));
 
 
             if (graphics->HasShaderParameter(PSP_LIGHTMATRICES))
             if (graphics->HasShaderParameter(PSP_LIGHTMATRICES))
             {
             {
                 switch (light->GetLightType())
                 switch (light->GetLightType())
                 {
                 {
                 case LIGHT_DIRECTIONAL:
                 case LIGHT_DIRECTIONAL:
-                {
-                    Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
-                    unsigned numSplits = Min(MAX_CASCADE_SPLITS, (int)lightQueue_->shadowSplits_.Size());
-
-                    for (unsigned i = 0; i < numSplits; ++i)
                     {
                     {
-                        CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, isLightVolume ? cameraEffectivePos :
-                            Vector3::ZERO);
+                        Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
+                        unsigned numSplits = (unsigned)Min(MAX_CASCADE_SPLITS, (int)lightQueue_->shadowSplits_.Size());
+
+                        for (unsigned i = 0; i < numSplits; ++i)
+                        {
+                            CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, isLightVolume ? cameraEffectivePos :
+                                Vector3::ZERO);
+                        }
+                        graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
                     }
                     }
-                    graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
-                }
-                break;
+                    break;
 
 
                 case LIGHT_SPOT:
                 case LIGHT_SPOT:
-                {
-                    Matrix4 shadowMatrices[2];
-
-                    CalculateSpotMatrix(shadowMatrices[0], light, cameraEffectivePos);
-                    bool isShadowed = lightQueue_->shadowMap_ != 0;
-                    if (isShadowed)
                     {
                     {
-                        CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, isLightVolume ? cameraEffectivePos :
-                            Vector3::ZERO);
-                    }
+                        Matrix4 shadowMatrices[2];
 
 
-                    graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
-                }
-                break;
+                        CalculateSpotMatrix(shadowMatrices[0], light, cameraEffectivePos);
+                        bool isShadowed = lightQueue_->shadowMap_ != 0;
+                        if (isShadowed)
+                        {
+                            CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, isLightVolume ? cameraEffectivePos :
+                                Vector3::ZERO);
+                        }
+
+                        graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
+                    }
+                    break;
 
 
                 case LIGHT_POINT:
                 case LIGHT_POINT:
-                {
-                    Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
-                    // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
-                    // the next parameter
-                    #ifdef URHO3D_OPENGL
-                    graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 16);
-                    #else
-                    graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 12);
-                    #endif
-                }
-                break;
+                    {
+                        Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
+                        // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
+                        // the next parameter
+#ifdef URHO3D_OPENGL
+                        graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 16);
+#else
+                        graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 12);
+#endif
+                    }
+                    break;
                 }
                 }
             }
             }
 
 
@@ -421,21 +423,21 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
             {
             {
                 {
                 {
                     // Calculate point light shadow sampling offsets (unrolled cube map)
                     // Calculate point light shadow sampling offsets (unrolled cube map)
-                    unsigned faceWidth = shadowMap->GetWidth() / 2;
-                    unsigned faceHeight = shadowMap->GetHeight() / 3;
+                    unsigned faceWidth = (unsigned)(shadowMap->GetWidth() / 2);
+                    unsigned faceHeight = (unsigned)(shadowMap->GetHeight() / 3);
                     float width = (float)shadowMap->GetWidth();
                     float width = (float)shadowMap->GetWidth();
                     float height = (float)shadowMap->GetHeight();
                     float height = (float)shadowMap->GetHeight();
-                    #ifdef URHO3D_OPENGL
+#ifdef URHO3D_OPENGL
                     float mulX = (float)(faceWidth - 3) / width;
                     float mulX = (float)(faceWidth - 3) / width;
                     float mulY = (float)(faceHeight - 3) / height;
                     float mulY = (float)(faceHeight - 3) / height;
                     float addX = 1.5f / width;
                     float addX = 1.5f / width;
                     float addY = 1.5f / height;
                     float addY = 1.5f / height;
-                    #else
+#else
                     float mulX = (float)(faceWidth - 4) / width;
                     float mulX = (float)(faceWidth - 4) / width;
                     float mulY = (float)(faceHeight - 4) / height;
                     float mulY = (float)(faceHeight - 4) / height;
                     float addX = 2.5f / width;
                     float addX = 2.5f / width;
                     float addY = 2.5f / height;
                     float addY = 2.5f / height;
-                    #endif
+#endif
                     // If using 4 shadow samples, offset the position diagonally by half pixel
                     // If using 4 shadow samples, offset the position diagonally by half pixel
                     if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
                     if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
                     {
                     {
@@ -469,7 +471,8 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
                     float fadeStart = light->GetShadowFadeDistance();
                     float fadeStart = light->GetShadowFadeDistance();
                     float fadeEnd = light->GetShadowDistance();
                     float fadeEnd = light->GetShadowDistance();
                     if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
                     if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
-                        intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
+                        intensity =
+                            Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
                     float pcfValues = (1.0f - intensity);
                     float pcfValues = (1.0f - intensity);
                     float samples = renderer->GetShadowQuality() >= SHADOWQUALITY_HIGH_16BIT ? 4.0f : 1.0f;
                     float samples = renderer->GetShadowQuality() >= SHADOWQUALITY_HIGH_16BIT ? 4.0f : 1.0f;
 
 
@@ -492,17 +495,17 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
             }
             }
         }
         }
         else if (lightQueue_->vertexLights_.Size() && graphics->HasShaderParameter(VSP_VERTEXLIGHTS) &&
         else if (lightQueue_->vertexLights_.Size() && graphics->HasShaderParameter(VSP_VERTEXLIGHTS) &&
-            graphics->NeedParameterUpdate(SP_LIGHT, lightQueue_))
+                 graphics->NeedParameterUpdate(SP_LIGHT, lightQueue_))
         {
         {
             Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3];
             Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3];
             const PODVector<Light*>& lights = lightQueue_->vertexLights_;
             const PODVector<Light*>& lights = lightQueue_->vertexLights_;
-            
+
             for (unsigned i = 0; i < lights.Size(); ++i)
             for (unsigned i = 0; i < lights.Size(); ++i)
             {
             {
                 Light* vertexLight = lights[i];
                 Light* vertexLight = lights[i];
                 Node* vertexLightNode = vertexLight->GetNode();
                 Node* vertexLightNode = vertexLight->GetNode();
                 LightType type = vertexLight->GetLightType();
                 LightType type = vertexLight->GetLightType();
-                
+
                 // Attenuation
                 // Attenuation
                 float invRange, cutoff, invCutoff;
                 float invRange, cutoff, invCutoff;
                 if (type == LIGHT_DIRECTIONAL)
                 if (type == LIGHT_DIRECTIONAL)
@@ -519,26 +522,26 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
                     cutoff = -1.0f;
                     cutoff = -1.0f;
                     invCutoff = 1.0f;
                     invCutoff = 1.0f;
                 }
                 }
-                
+
                 // Color
                 // Color
                 float fade = 1.0f;
                 float fade = 1.0f;
                 float fadeEnd = vertexLight->GetDrawDistance();
                 float fadeEnd = vertexLight->GetDrawDistance();
                 float fadeStart = vertexLight->GetFadeDistance();
                 float fadeStart = vertexLight->GetFadeDistance();
-                
+
                 // Do fade calculation for light if both fade & draw distance defined
                 // Do fade calculation for light if both fade & draw distance defined
                 if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
                 if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
                     fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
                     fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
-                
+
                 Color color = vertexLight->GetEffectiveColor() * fade;
                 Color color = vertexLight->GetEffectiveColor() * fade;
                 vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange);
                 vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange);
-                
+
                 // Direction
                 // Direction
                 vertexLights[i * 3 + 1] = Vector4(-(vertexLightNode->GetWorldDirection()), cutoff);
                 vertexLights[i * 3 + 1] = Vector4(-(vertexLightNode->GetWorldDirection()), cutoff);
-                
+
                 // Position
                 // Position
                 vertexLights[i * 3 + 2] = Vector4(vertexLightNode->GetWorldPosition(), invCutoff);
                 vertexLights[i * 3 + 2] = Vector4(vertexLightNode->GetWorldPosition(), invCutoff);
             }
             }
-            
+
             graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].Data(), lights.Size() * 3 * 4);
             graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].Data(), lights.Size() * 3 * 4);
         }
         }
     }
     }
@@ -552,7 +555,7 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
             for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
             for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
                 graphics->SetShaderParameter(i->first_, i->second_.value_);
                 graphics->SetShaderParameter(i->first_, i->second_.value_);
         }
         }
-        
+
         const HashMap<TextureUnit, SharedPtr<Texture> >& textures = material_->GetTextures();
         const HashMap<TextureUnit, SharedPtr<Texture> >& textures = material_->GetTextures();
         for (HashMap<TextureUnit, SharedPtr<Texture> >::ConstIterator i = textures.Begin(); i != textures.End(); ++i)
         for (HashMap<TextureUnit, SharedPtr<Texture> >::ConstIterator i = textures.Begin(); i != textures.End(); ++i)
         {
         {
@@ -560,7 +563,7 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
                 graphics->SetTexture(i->first_, i->second_.Get());
                 graphics->SetTexture(i->first_, i->second_.Get());
         }
         }
     }
     }
-    
+
     // Set light-related textures
     // Set light-related textures
     if (light)
     if (light)
     {
     {
@@ -581,12 +584,12 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
             graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture);
             graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture);
         }
         }
     }
     }
-    
+
     // Set zone texture if necessary
     // Set zone texture if necessary
-    #ifdef DESKTOP_GRAPHICS
+#ifdef DESKTOP_GRAPHICS
     if (zone_ && graphics->HasTextureUnit(TU_ZONE))
     if (zone_ && graphics->HasTextureUnit(TU_ZONE))
         graphics->SetTexture(TU_ZONE, zone_->GetZoneTexture());
         graphics->SetTexture(TU_ZONE, zone_->GetZoneTexture());
-    #endif
+#endif
 }
 }
 
 
 void Batch::Draw(View* view, bool allowDepthWrite) const
 void Batch::Draw(View* view, bool allowDepthWrite) const
@@ -603,14 +606,14 @@ void BatchGroup::SetTransforms(void* lockedData, unsigned& freeIndex)
     // Do not use up buffer space if not going to draw as instanced
     // Do not use up buffer space if not going to draw as instanced
     if (geometryType_ != GEOM_INSTANCED)
     if (geometryType_ != GEOM_INSTANCED)
         return;
         return;
-    
+
     startIndex_ = freeIndex;
     startIndex_ = freeIndex;
     Matrix3x4* dest = (Matrix3x4*)lockedData;
     Matrix3x4* dest = (Matrix3x4*)lockedData;
     dest += freeIndex;
     dest += freeIndex;
-    
+
     for (unsigned i = 0; i < instances_.Size(); ++i)
     for (unsigned i = 0; i < instances_.Size(); ++i)
         *dest++ = *instances_[i].worldTransform_;
         *dest++ = *instances_[i].worldTransform_;
-    
+
     freeIndex += instances_.Size();
     freeIndex += instances_.Size();
 }
 }
 
 
@@ -618,7 +621,7 @@ void BatchGroup::Draw(View* view, bool allowDepthWrite) const
 {
 {
     Graphics* graphics = view->GetGraphics();
     Graphics* graphics = view->GetGraphics();
     Renderer* renderer = view->GetRenderer();
     Renderer* renderer = view->GetRenderer();
-    
+
     if (instances_.Size() && !geometry_->IsEmpty())
     if (instances_.Size() && !geometry_->IsEmpty())
     {
     {
         // Draw as individual objects if instancing not supported or could not fill the instancing buffer
         // Draw as individual objects if instancing not supported or could not fill the instancing buffer
@@ -626,15 +629,15 @@ void BatchGroup::Draw(View* view, bool allowDepthWrite) const
         if (!instanceBuffer || geometryType_ != GEOM_INSTANCED || startIndex_ == M_MAX_UNSIGNED)
         if (!instanceBuffer || geometryType_ != GEOM_INSTANCED || startIndex_ == M_MAX_UNSIGNED)
         {
         {
             Batch::Prepare(view, false, allowDepthWrite);
             Batch::Prepare(view, false, allowDepthWrite);
-            
+
             graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
             graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
             graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks());
             graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks());
-            
+
             for (unsigned i = 0; i < instances_.Size(); ++i)
             for (unsigned i = 0; i < instances_.Size(); ++i)
             {
             {
                 if (graphics->NeedParameterUpdate(SP_OBJECT, instances_[i].worldTransform_))
                 if (graphics->NeedParameterUpdate(SP_OBJECT, instances_[i].worldTransform_))
                     graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_);
                     graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_);
-                
+
                 graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
                 graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
                     geometry_->GetVertexStart(), geometry_->GetVertexCount());
                     geometry_->GetVertexStart(), geometry_->GetVertexCount());
             }
             }
@@ -642,20 +645,20 @@ void BatchGroup::Draw(View* view, bool allowDepthWrite) const
         else
         else
         {
         {
             Batch::Prepare(view, false, allowDepthWrite);
             Batch::Prepare(view, false, allowDepthWrite);
-            
+
             // Get the geometry vertex buffers, then add the instancing stream buffer
             // Get the geometry vertex buffers, then add the instancing stream buffer
             // Hack: use a const_cast to avoid dynamic allocation of new temp vectors
             // Hack: use a const_cast to avoid dynamic allocation of new temp vectors
-            Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>
-                (geometry_->GetVertexBuffers());
+            Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>(
+                geometry_->GetVertexBuffers());
             PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks());
             PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks());
             vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer));
             vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer));
             elementMasks.Push(instanceBuffer->GetElementMask());
             elementMasks.Push(instanceBuffer->GetElementMask());
-            
+
             graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
             graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
             graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_);
             graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_);
             graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
             graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
                 geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size());
                 geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size());
-            
+
             // Remove the instancing buffer & element mask now
             // Remove the instancing buffer & element mask now
             vertexBuffers.Pop();
             vertexBuffers.Pop();
             elementMasks.Pop();
             elementMasks.Pop();
@@ -665,11 +668,8 @@ void BatchGroup::Draw(View* view, bool allowDepthWrite) const
 
 
 unsigned BatchGroupKey::ToHash() const
 unsigned BatchGroupKey::ToHash() const
 {
 {
-    return ((unsigned)(size_t)zone_) / sizeof(Zone) +
-        ((unsigned)(size_t)lightQueue_) / sizeof(LightBatchQueue) +
-        ((unsigned)(size_t)pass_) / sizeof(Pass) +
-        ((unsigned)(size_t)material_) / sizeof(Material) +
-        ((unsigned)(size_t)geometry_) / sizeof(Geometry);
+    return (unsigned)((size_t)zone_ / sizeof(Zone) + (size_t)lightQueue_ / sizeof(LightBatchQueue) + (size_t)pass_ / sizeof(Pass) +
+                      (size_t)material_ / sizeof(Material) + (size_t)geometry_ / sizeof(Geometry));
 }
 }
 
 
 void BatchQueue::Clear(int maxSortedInstances)
 void BatchQueue::Clear(int maxSortedInstances)
@@ -677,21 +677,21 @@ void BatchQueue::Clear(int maxSortedInstances)
     batches_.Clear();
     batches_.Clear();
     sortedBatches_.Clear();
     sortedBatches_.Clear();
     batchGroups_.Clear();
     batchGroups_.Clear();
-    maxSortedInstances_ = maxSortedInstances;
+    maxSortedInstances_ = (unsigned)maxSortedInstances;
 }
 }
 
 
 void BatchQueue::SortBackToFront()
 void BatchQueue::SortBackToFront()
 {
 {
     sortedBatches_.Resize(batches_.Size());
     sortedBatches_.Resize(batches_.Size());
-    
+
     for (unsigned i = 0; i < batches_.Size(); ++i)
     for (unsigned i = 0; i < batches_.Size(); ++i)
         sortedBatches_[i] = &batches_[i];
         sortedBatches_[i] = &batches_[i];
-    
+
     Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesBackToFront);
     Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesBackToFront);
-    
+
     // Do not actually sort batch groups, just list them
     // Do not actually sort batch groups, just list them
     sortedBatchGroups_.Resize(batchGroups_.Size());
     sortedBatchGroups_.Resize(batchGroups_.Size());
-    
+
     unsigned index = 0;
     unsigned index = 0;
     for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
     for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
         sortedBatchGroups_[index++] = &i->second_;
         sortedBatchGroups_[index++] = &i->second_;
@@ -700,12 +700,12 @@ void BatchQueue::SortBackToFront()
 void BatchQueue::SortFrontToBack()
 void BatchQueue::SortFrontToBack()
 {
 {
     sortedBatches_.Clear();
     sortedBatches_.Clear();
-    
+
     for (unsigned i = 0; i < batches_.Size(); ++i)
     for (unsigned i = 0; i < batches_.Size(); ++i)
         sortedBatches_.Push(&batches_[i]);
         sortedBatches_.Push(&batches_[i]);
-    
+
     SortFrontToBack2Pass(sortedBatches_);
     SortFrontToBack2Pass(sortedBatches_);
-    
+
     // Sort each group front to back
     // Sort each group front to back
     for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
     for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
     {
     {
@@ -723,13 +723,13 @@ void BatchQueue::SortFrontToBack()
             i->second_.distance_ = minDistance;
             i->second_.distance_ = minDistance;
         }
         }
     }
     }
-    
+
     sortedBatchGroups_.Resize(batchGroups_.Size());
     sortedBatchGroups_.Resize(batchGroups_.Size());
-    
+
     unsigned index = 0;
     unsigned index = 0;
     for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
     for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
         sortedBatchGroups_[index++] = &i->second_;
         sortedBatchGroups_[index++] = &i->second_;
-    
+
     SortFrontToBack2Pass(reinterpret_cast<PODVector<Batch*>& >(sortedBatchGroups_));
     SortFrontToBack2Pass(reinterpret_cast<PODVector<Batch*>& >(sortedBatchGroups_));
 }
 }
 
 
@@ -737,21 +737,21 @@ void BatchQueue::SortFrontToBack2Pass(PODVector<Batch*>& batches)
 {
 {
     // Mobile devices likely use a tiled deferred approach, with which front-to-back sorting is irrelevant. The 2-pass
     // Mobile devices likely use a tiled deferred approach, with which front-to-back sorting is irrelevant. The 2-pass
     // method is also time consuming, so just sort with state having priority
     // method is also time consuming, so just sort with state having priority
-    #ifdef GL_ES_VERSION_2_0
+#ifdef GL_ES_VERSION_2_0
     Sort(batches.Begin(), batches.End(), CompareBatchesState);
     Sort(batches.Begin(), batches.End(), CompareBatchesState);
-    #else
+#else
     // For desktop, first sort by distance and remap shader/material/geometry IDs in the sort key
     // For desktop, first sort by distance and remap shader/material/geometry IDs in the sort key
     Sort(batches.Begin(), batches.End(), CompareBatchesFrontToBack);
     Sort(batches.Begin(), batches.End(), CompareBatchesFrontToBack);
-    
+
     unsigned freeShaderID = 0;
     unsigned freeShaderID = 0;
     unsigned short freeMaterialID = 0;
     unsigned short freeMaterialID = 0;
     unsigned short freeGeometryID = 0;
     unsigned short freeGeometryID = 0;
-    
+
     for (PODVector<Batch*>::Iterator i = batches.Begin(); i != batches.End(); ++i)
     for (PODVector<Batch*>::Iterator i = batches.Begin(); i != batches.End(); ++i)
     {
     {
         Batch* batch = *i;
         Batch* batch = *i;
-        
-        unsigned shaderID = (batch->sortKey_ >> 32);
+
+        unsigned shaderID = (unsigned)(batch->sortKey_ >> 32);
         HashMap<unsigned, unsigned>::ConstIterator j = shaderRemapping_.Find(shaderID);
         HashMap<unsigned, unsigned>::ConstIterator j = shaderRemapping_.Find(shaderID);
         if (j != shaderRemapping_.End())
         if (j != shaderRemapping_.End())
             shaderID = j->second_;
             shaderID = j->second_;
@@ -760,7 +760,7 @@ void BatchQueue::SortFrontToBack2Pass(PODVector<Batch*>& batches)
             shaderID = shaderRemapping_[shaderID] = freeShaderID | (shaderID & 0xc0000000);
             shaderID = shaderRemapping_[shaderID] = freeShaderID | (shaderID & 0xc0000000);
             ++freeShaderID;
             ++freeShaderID;
         }
         }
-        
+
         unsigned short materialID = (unsigned short)(batch->sortKey_ & 0xffff0000);
         unsigned short materialID = (unsigned short)(batch->sortKey_ & 0xffff0000);
         HashMap<unsigned short, unsigned short>::ConstIterator k = materialRemapping_.Find(materialID);
         HashMap<unsigned short, unsigned short>::ConstIterator k = materialRemapping_.Find(materialID);
         if (k != materialRemapping_.End())
         if (k != materialRemapping_.End())
@@ -770,7 +770,7 @@ void BatchQueue::SortFrontToBack2Pass(PODVector<Batch*>& batches)
             materialID = materialRemapping_[materialID] = freeMaterialID;
             materialID = materialRemapping_[materialID] = freeMaterialID;
             ++freeMaterialID;
             ++freeMaterialID;
         }
         }
-        
+
         unsigned short geometryID = (unsigned short)(batch->sortKey_ & 0xffff);
         unsigned short geometryID = (unsigned short)(batch->sortKey_ & 0xffff);
         HashMap<unsigned short, unsigned short>::ConstIterator l = geometryRemapping_.Find(geometryID);
         HashMap<unsigned short, unsigned short>::ConstIterator l = geometryRemapping_.Find(geometryID);
         if (l != geometryRemapping_.End())
         if (l != geometryRemapping_.End())
@@ -780,17 +780,17 @@ void BatchQueue::SortFrontToBack2Pass(PODVector<Batch*>& batches)
             geometryID = geometryRemapping_[geometryID] = freeGeometryID;
             geometryID = geometryRemapping_[geometryID] = freeGeometryID;
             ++freeGeometryID;
             ++freeGeometryID;
         }
         }
-        
-        batch->sortKey_ = (((unsigned long long)shaderID) << 32) || (((unsigned long long)materialID) << 16) | geometryID;
+
+        batch->sortKey_ = (((unsigned long long)shaderID) << 32) | (((unsigned long long)materialID) << 16) | geometryID;
     }
     }
-    
+
     shaderRemapping_.Clear();
     shaderRemapping_.Clear();
     materialRemapping_.Clear();
     materialRemapping_.Clear();
     geometryRemapping_.Clear();
     geometryRemapping_.Clear();
-    
+
     // Finally sort again with the rewritten ID's
     // Finally sort again with the rewritten ID's
     Sort(batches.Begin(), batches.End(), CompareBatchesState);
     Sort(batches.Begin(), batches.End(), CompareBatchesState);
-    #endif
+#endif
 }
 }
 
 
 void BatchQueue::SetTransforms(void* lockedData, unsigned& freeIndex)
 void BatchQueue::SetTransforms(void* lockedData, unsigned& freeIndex)
@@ -803,24 +803,24 @@ void BatchQueue::Draw(View* view, bool markToStencil, bool usingLightOptimizatio
 {
 {
     Graphics* graphics = view->GetGraphics();
     Graphics* graphics = view->GetGraphics();
     Renderer* renderer = view->GetRenderer();
     Renderer* renderer = view->GetRenderer();
-    
+
     // If View has set up its own light optimizations, do not disturb the stencil/scissor test settings
     // If View has set up its own light optimizations, do not disturb the stencil/scissor test settings
     if (!usingLightOptimization)
     if (!usingLightOptimization)
     {
     {
         graphics->SetScissorTest(false);
         graphics->SetScissorTest(false);
-        
+
         // During G-buffer rendering, mark opaque pixels' lightmask to stencil buffer if requested
         // During G-buffer rendering, mark opaque pixels' lightmask to stencil buffer if requested
         if (!markToStencil)
         if (!markToStencil)
             graphics->SetStencilTest(false);
             graphics->SetStencilTest(false);
     }
     }
-    
+
     // Instanced
     // Instanced
     for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
     for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
     {
     {
         BatchGroup* group = *i;
         BatchGroup* group = *i;
         if (markToStencil)
         if (markToStencil)
             graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
             graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
-        
+
         group->Draw(view, allowDepthWrite);
         group->Draw(view, allowDepthWrite);
     }
     }
     // Non-instanced
     // Non-instanced
@@ -837,7 +837,7 @@ void BatchQueue::Draw(View* view, bool markToStencil, bool usingLightOptimizatio
             else
             else
                 graphics->SetScissorTest(false);
                 graphics->SetScissorTest(false);
         }
         }
-        
+
         batch->Draw(view, allowDepthWrite);
         batch->Draw(view, allowDepthWrite);
     }
     }
 }
 }
@@ -845,13 +845,13 @@ void BatchQueue::Draw(View* view, bool markToStencil, bool usingLightOptimizatio
 unsigned BatchQueue::GetNumInstances() const
 unsigned BatchQueue::GetNumInstances() const
 {
 {
     unsigned total = 0;
     unsigned total = 0;
-    
+
     for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
     for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
     {
     {
-       if (i->second_.geometryType_ == GEOM_INSTANCED)
+        if (i->second_.geometryType_ == GEOM_INSTANCED)
             total += i->second_.instances_.Size();
             total += i->second_.instances_.Size();
     }
     }
-    
+
     return total;
     return total;
 }
 }
 
 

+ 29 - 19
Source/Urho3D/Graphics/Batch.h

@@ -22,10 +22,10 @@
 
 
 #pragma once
 #pragma once
 
 
+#include "../Container/Ptr.h"
 #include "../Graphics/Drawable.h"
 #include "../Graphics/Drawable.h"
 #include "../Math/MathDefs.h"
 #include "../Math/MathDefs.h"
 #include "../Math/Matrix3x4.h"
 #include "../Math/Matrix3x4.h"
-#include "../Container/Ptr.h"
 #include "../Math/Rect.h"
 #include "../Math/Rect.h"
 
 
 namespace Urho3D
 namespace Urho3D
@@ -54,7 +54,7 @@ struct Batch
         isBase_(false)
         isBase_(false)
     {
     {
     }
     }
-    
+
     /// Construct from a drawable's source batch.
     /// Construct from a drawable's source batch.
     Batch(const SourceBatch& rhs) :
     Batch(const SourceBatch& rhs) :
         distance_(rhs.distance_),
         distance_(rhs.distance_),
@@ -67,14 +67,14 @@ struct Batch
         isBase_(false)
         isBase_(false)
     {
     {
     }
     }
-    
+
     /// Calculate state sorting key, which consists of base pass flag, light, pass and geometry.
     /// Calculate state sorting key, which consists of base pass flag, light, pass and geometry.
     void CalculateSortKey();
     void CalculateSortKey();
     /// Prepare for rendering.
     /// Prepare for rendering.
     void Prepare(View* view, bool setModelTransform, bool allowDepthWrite) const;
     void Prepare(View* view, bool setModelTransform, bool allowDepthWrite) const;
     /// Prepare and draw.
     /// Prepare and draw.
     void Draw(View* view, bool allowDepthWrite) const;
     void Draw(View* view, bool allowDepthWrite) const;
-    
+
     /// State sorting key.
     /// State sorting key.
     unsigned long long sortKey_;
     unsigned long long sortKey_;
     /// Distance from camera.
     /// Distance from camera.
@@ -114,14 +114,14 @@ struct InstanceData
     InstanceData()
     InstanceData()
     {
     {
     }
     }
-    
+
     /// Construct with transform and distance.
     /// Construct with transform and distance.
     InstanceData(const Matrix3x4* worldTransform, float distance) :
     InstanceData(const Matrix3x4* worldTransform, float distance) :
         worldTransform_(worldTransform),
         worldTransform_(worldTransform),
         distance_(distance)
         distance_(distance)
     {
     {
     }
     }
-    
+
     /// World transform.
     /// World transform.
     const Matrix3x4* worldTransform_;
     const Matrix3x4* worldTransform_;
     /// Distance from camera.
     /// Distance from camera.
@@ -136,7 +136,7 @@ struct BatchGroup : public Batch
         startIndex_(M_MAX_UNSIGNED)
         startIndex_(M_MAX_UNSIGNED)
     {
     {
     }
     }
-    
+
     /// Construct from a batch.
     /// Construct from a batch.
     BatchGroup(const Batch& batch) :
     BatchGroup(const Batch& batch) :
         Batch(batch),
         Batch(batch),
@@ -148,25 +148,25 @@ struct BatchGroup : public Batch
     ~BatchGroup()
     ~BatchGroup()
     {
     {
     }
     }
-    
+
     /// Add world transform(s) from a batch.
     /// Add world transform(s) from a batch.
     void AddTransforms(const Batch& batch)
     void AddTransforms(const Batch& batch)
     {
     {
         InstanceData newInstance;
         InstanceData newInstance;
         newInstance.distance_ = batch.distance_;
         newInstance.distance_ = batch.distance_;
-        
+
         for (unsigned i = 0; i < batch.numWorldTransforms_; ++i)
         for (unsigned i = 0; i < batch.numWorldTransforms_; ++i)
         {
         {
             newInstance.worldTransform_ = &batch.worldTransform_[i];
             newInstance.worldTransform_ = &batch.worldTransform_[i];
             instances_.Push(newInstance);
             instances_.Push(newInstance);
         }
         }
     }
     }
-    
+
     /// Pre-set the instance transforms. Buffer must be big enough to hold all transforms.
     /// Pre-set the instance transforms. Buffer must be big enough to hold all transforms.
     void SetTransforms(void* lockedData, unsigned& freeIndex);
     void SetTransforms(void* lockedData, unsigned& freeIndex);
     /// Prepare and draw.
     /// Prepare and draw.
     void Draw(View* view, bool allowDepthWrite) const;
     void Draw(View* view, bool allowDepthWrite) const;
-    
+
     /// Instance data.
     /// Instance data.
     PODVector<InstanceData> instances_;
     PODVector<InstanceData> instances_;
     /// Instance stream start index, or M_MAX_UNSIGNED if transforms not pre-set.
     /// Instance stream start index, or M_MAX_UNSIGNED if transforms not pre-set.
@@ -180,7 +180,7 @@ struct BatchGroupKey
     BatchGroupKey()
     BatchGroupKey()
     {
     {
     }
     }
-    
+
     /// Construct from a batch.
     /// Construct from a batch.
     BatchGroupKey(const Batch& batch) :
     BatchGroupKey(const Batch& batch) :
         zone_(batch.zone_),
         zone_(batch.zone_),
@@ -190,7 +190,7 @@ struct BatchGroupKey
         geometry_(batch.geometry_)
         geometry_(batch.geometry_)
     {
     {
     }
     }
-    
+
     /// Zone.
     /// Zone.
     Zone* zone_;
     Zone* zone_;
     /// Light properties.
     /// Light properties.
@@ -201,12 +201,21 @@ struct BatchGroupKey
     Material* material_;
     Material* material_;
     /// Geometry.
     /// Geometry.
     Geometry* geometry_;
     Geometry* geometry_;
-    
+
     /// Test for equality with another batch group key.
     /// Test for equality with another batch group key.
-    bool operator == (const BatchGroupKey& rhs) const { return zone_ == rhs.zone_ && lightQueue_ == rhs.lightQueue_ && pass_ == rhs.pass_ && material_ == rhs.material_ && geometry_ == rhs.geometry_; }
+    bool operator ==(const BatchGroupKey& rhs) const
+    {
+        return zone_ == rhs.zone_ && lightQueue_ == rhs.lightQueue_ && pass_ == rhs.pass_ && material_ == rhs.material_ &&
+               geometry_ == rhs.geometry_;
+    }
+
     /// Test for inequality with another batch group key.
     /// Test for inequality with another batch group key.
-    bool operator != (const BatchGroupKey& rhs) const { return zone_ != rhs.zone_ || lightQueue_ != rhs.lightQueue_ || pass_ != rhs.pass_ || material_ != rhs.material_ || geometry_ != rhs.geometry_; }
-    
+    bool operator !=(const BatchGroupKey& rhs) const
+    {
+        return zone_ != rhs.zone_ || lightQueue_ != rhs.lightQueue_ || pass_ != rhs.pass_ || material_ != rhs.material_ ||
+               geometry_ != rhs.geometry_;
+    }
+
     /// Return hash value.
     /// Return hash value.
     unsigned ToHash() const;
     unsigned ToHash() const;
 };
 };
@@ -229,9 +238,10 @@ public:
     void Draw(View* view, bool markToStencil, bool usingLightOptimization, bool allowDepthWrite) const;
     void Draw(View* view, bool markToStencil, bool usingLightOptimization, bool allowDepthWrite) const;
     /// Return the combined amount of instances.
     /// Return the combined amount of instances.
     unsigned GetNumInstances() const;
     unsigned GetNumInstances() const;
+
     /// Return whether the batch group is empty.
     /// Return whether the batch group is empty.
     bool IsEmpty() const { return batches_.Empty() && batchGroups_.Empty(); }
     bool IsEmpty() const { return batches_.Empty() && batchGroups_.Empty(); }
-    
+
     /// Instanced draw calls.
     /// Instanced draw calls.
     HashMap<BatchGroupKey, BatchGroup> batchGroups_;
     HashMap<BatchGroupKey, BatchGroup> batchGroups_;
     /// Shader remapping table for 2-pass state and distance sort.
     /// Shader remapping table for 2-pass state and distance sort.
@@ -240,7 +250,7 @@ public:
     HashMap<unsigned short, unsigned short> materialRemapping_;
     HashMap<unsigned short, unsigned short> materialRemapping_;
     /// Geometry remapping table for 2-pass state and distance sort.
     /// Geometry remapping table for 2-pass state and distance sort.
     HashMap<unsigned short, unsigned short> geometryRemapping_;
     HashMap<unsigned short, unsigned short> geometryRemapping_;
-    
+
     /// Unsorted non-instanced draw calls.
     /// Unsorted non-instanced draw calls.
     PODVector<Batch> batches_;
     PODVector<Batch> batches_;
     /// Sorted non-instanced draw calls.
     /// Sorted non-instanced draw calls.

+ 43 - 23
Source/Urho3D/Graphics/BillboardSet.cpp

@@ -20,21 +20,22 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
+#include "../Core/Context.h"
+#include "../Core/Profiler.h"
 #include "../Graphics/Batch.h"
 #include "../Graphics/Batch.h"
 #include "../Graphics/BillboardSet.h"
 #include "../Graphics/BillboardSet.h"
 #include "../Graphics/Camera.h"
 #include "../Graphics/Camera.h"
-#include "../Core/Context.h"
 #include "../Graphics/Geometry.h"
 #include "../Graphics/Geometry.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/IndexBuffer.h"
 #include "../Graphics/IndexBuffer.h"
 #include "../Graphics/Material.h"
 #include "../Graphics/Material.h"
-#include "../IO/MemoryBuffer.h"
-#include "../Scene/Node.h"
 #include "../Graphics/OctreeQuery.h"
 #include "../Graphics/OctreeQuery.h"
-#include "../Core/Profiler.h"
-#include "../Resource/ResourceCache.h"
-#include "../Container/Sort.h"
 #include "../Graphics/VertexBuffer.h"
 #include "../Graphics/VertexBuffer.h"
+#include "../IO/MemoryBuffer.h"
+#include "../Resource/ResourceCache.h"
+#include "../Scene/Node.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -96,7 +97,8 @@ void BillboardSet::RegisterObject(Context* context)
     context->RegisterFactory<BillboardSet>(GEOMETRY_CATEGORY);
     context->RegisterFactory<BillboardSet>(GEOMETRY_CATEGORY);
 
 
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
-    MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()), AM_DEFAULT);
+    MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()),
+        AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Relative Position", IsRelative, SetRelative, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Relative Position", IsRelative, SetRelative, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Relative Scale", IsScaled, SetScaled, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Relative Scale", IsScaled, SetScaled, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Sort By Distance", IsSorted, SetSorted, bool, false, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Sort By Distance", IsSorted, SetSorted, bool, false, AM_DEFAULT);
@@ -107,8 +109,10 @@ void BillboardSet::RegisterObject(Context* context)
     ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
     COPY_BASE_ATTRIBUTES(Drawable);
     COPY_BASE_ATTRIBUTES(Drawable);
-    MIXED_ACCESSOR_ATTRIBUTE("Billboards", GetBillboardsAttr, SetBillboardsAttr, VariantVector, Variant::emptyVariantVector, AM_FILE);
-    ACCESSOR_ATTRIBUTE("Network Billboards", GetNetBillboardsAttr, SetNetBillboardsAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_NOEDIT);
+    MIXED_ACCESSOR_ATTRIBUTE("Billboards", GetBillboardsAttr, SetBillboardsAttr, VariantVector, Variant::emptyVariantVector,
+        AM_FILE);
+    ACCESSOR_ATTRIBUTE("Network Billboards", GetNetBillboardsAttr, SetNetBillboardsAttr, PODVector<unsigned char>,
+        Variant::emptyBuffer, AM_NET | AM_NOEDIT);
 }
 }
 
 
 void BillboardSet::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
 void BillboardSet::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
@@ -162,13 +166,13 @@ void BillboardSet::UpdateBatches(const FrameInfo& frame)
         sortThisFrame_ = false;
         sortThisFrame_ = false;
         sortFrameNumber_ = frame.frameNumber_;
         sortFrameNumber_ = frame.frameNumber_;
     }
     }
-    
+
     Vector3 worldPos = node_->GetWorldPosition();
     Vector3 worldPos = node_->GetWorldPosition();
     Vector3 offset = (worldPos - frame.camera_->GetNode()->GetWorldPosition());
     Vector3 offset = (worldPos - frame.camera_->GetNode()->GetWorldPosition());
     // Sort if position relative to camera has changed
     // Sort if position relative to camera has changed
     if (offset != previousOffset_ & sorted_)
     if (offset != previousOffset_ & sorted_)
         sortThisFrame_ = true;
         sortThisFrame_ = true;
-    
+
     distance_ = frame.camera_->GetDistance(GetWorldBoundingBox().Center());
     distance_ = frame.camera_->GetDistance(GetWorldBoundingBox().Center());
 
 
     // Calculate scaled distance for animation LOD
     // Calculate scaled distance for animation LOD
@@ -195,7 +199,7 @@ void BillboardSet::UpdateGeometry(const FrameInfo& frame)
 
 
     if (bufferDirty_ || sortThisFrame_ || vertexBuffer_->IsDataLost())
     if (bufferDirty_ || sortThisFrame_ || vertexBuffer_->IsDataLost())
         UpdateVertexBuffer(frame);
         UpdateVertexBuffer(frame);
-    
+
     // If using camera facing, re-update the rotation for the current view now
     // If using camera facing, re-update the rotation for the current view now
     if (faceCameraMode_ != FC_NONE)
     if (faceCameraMode_ != FC_NONE)
     {
     {
@@ -432,8 +436,12 @@ void BillboardSet::UpdateBufferSize()
     unsigned vertexIndex = 0;
     unsigned vertexIndex = 0;
     while (numBillboards--)
     while (numBillboards--)
     {
     {
-        dest[0] = vertexIndex; dest[1] = vertexIndex + 1; dest[2] = vertexIndex + 2;
-        dest[3] = vertexIndex + 2; dest[4] = vertexIndex + 3; dest[5] = vertexIndex;
+        dest[0] = (unsigned short)vertexIndex;
+        dest[1] = (unsigned short)(vertexIndex + 1);
+        dest[2] = (unsigned short)(vertexIndex + 2);
+        dest[3] = (unsigned short)(vertexIndex + 2);
+        dest[4] = (unsigned short)(vertexIndex + 3);
+        dest[5] = (unsigned short)vertexIndex;
 
 
         dest += 6;
         dest += 6;
         vertexIndex += 4;
         vertexIndex += 4;
@@ -501,7 +509,7 @@ void BillboardSet::UpdateVertexBuffer(const FrameInfo& frame)
         // Store the "last sorted position" now
         // Store the "last sorted position" now
         previousOffset_ = (worldPos - frame.camera_->GetNode()->GetWorldPosition());
         previousOffset_ = (worldPos - frame.camera_->GetNode()->GetWorldPosition());
     }
     }
-    
+
     float* dest = (float*)vertexBuffer_->Lock(0, enabledBillboards * 4, true);
     float* dest = (float*)vertexBuffer_->Lock(0, enabledBillboards * 4, true);
     if (!dest)
     if (!dest)
         return;
         return;
@@ -519,27 +527,39 @@ void BillboardSet::UpdateVertexBuffer(const FrameInfo& frame)
         rotationMatrix[1][0] = -rotationMatrix[0][1];
         rotationMatrix[1][0] = -rotationMatrix[0][1];
         rotationMatrix[1][1] = rotationMatrix[0][0];
         rotationMatrix[1][1] = rotationMatrix[0][0];
 
 
-        dest[0] = billboard.position_.x_; dest[1] = billboard.position_.y_; dest[2] = billboard.position_.z_;
+        dest[0] = billboard.position_.x_;
+        dest[1] = billboard.position_.y_;
+        dest[2] = billboard.position_.z_;
         ((unsigned&)dest[3]) = color;
         ((unsigned&)dest[3]) = color;
-        dest[4] = billboard.uv_.min_.x_; dest[5] = billboard.uv_.min_.y_;
+        dest[4] = billboard.uv_.min_.x_;
+        dest[5] = billboard.uv_.min_.y_;
         dest[6] = -size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
         dest[6] = -size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
         dest[7] = -size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
         dest[7] = -size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
 
 
-        dest[8] = billboard.position_.x_; dest[9] = billboard.position_.y_; dest[10] = billboard.position_.z_;
+        dest[8] = billboard.position_.x_;
+        dest[9] = billboard.position_.y_;
+        dest[10] = billboard.position_.z_;
         ((unsigned&)dest[11]) = color;
         ((unsigned&)dest[11]) = color;
-        dest[12] = billboard.uv_.max_.x_; dest[13] = billboard.uv_.min_.y_;
+        dest[12] = billboard.uv_.max_.x_;
+        dest[13] = billboard.uv_.min_.y_;
         dest[14] = size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
         dest[14] = size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
         dest[15] = size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
         dest[15] = size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
 
 
-        dest[16] = billboard.position_.x_; dest[17] = billboard.position_.y_; dest[18] = billboard.position_.z_;
+        dest[16] = billboard.position_.x_;
+        dest[17] = billboard.position_.y_;
+        dest[18] = billboard.position_.z_;
         ((unsigned&)dest[19]) = color;
         ((unsigned&)dest[19]) = color;
-        dest[20] = billboard.uv_.max_.x_; dest[21] = billboard.uv_.max_.y_;
+        dest[20] = billboard.uv_.max_.x_;
+        dest[21] = billboard.uv_.max_.y_;
         dest[22] = size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
         dest[22] = size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
         dest[23] = size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
         dest[23] = size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
 
 
-        dest[24] = billboard.position_.x_; dest[25] = billboard.position_.y_; dest[26] = billboard.position_.z_;
+        dest[24] = billboard.position_.x_;
+        dest[25] = billboard.position_.y_;
+        dest[26] = billboard.position_.z_;
         ((unsigned&)dest[27]) = color;
         ((unsigned&)dest[27]) = color;
-        dest[28] = billboard.uv_.min_.x_; dest[29] = billboard.uv_.max_.y_;
+        dest[28] = billboard.uv_.min_.x_;
+        dest[29] = billboard.uv_.max_.y_;
         dest[30] = -size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
         dest[30] = -size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
         dest[31] = -size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
         dest[31] = -size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
 
 

+ 10 - 2
Source/Urho3D/Graphics/BillboardSet.h

@@ -22,11 +22,11 @@
 
 
 #pragma once
 #pragma once
 
 
-#include "../Math/Color.h"
 #include "../Graphics/Drawable.h"
 #include "../Graphics/Drawable.h"
+#include "../IO/VectorBuffer.h"
+#include "../Math/Color.h"
 #include "../Math/Matrix3x4.h"
 #include "../Math/Matrix3x4.h"
 #include "../Math/Rect.h"
 #include "../Math/Rect.h"
-#include "../IO/VectorBuffer.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {
@@ -96,20 +96,28 @@ public:
 
 
     /// Return material.
     /// Return material.
     Material* GetMaterial() const;
     Material* GetMaterial() const;
+
     /// Return number of billboards.
     /// Return number of billboards.
     unsigned GetNumBillboards() const { return billboards_.Size(); }
     unsigned GetNumBillboards() const { return billboards_.Size(); }
+
     /// Return all billboards.
     /// Return all billboards.
     PODVector<Billboard>& GetBillboards() { return billboards_; }
     PODVector<Billboard>& GetBillboards() { return billboards_; }
+
     /// Return billboard by index.
     /// Return billboard by index.
     Billboard* GetBillboard(unsigned index);
     Billboard* GetBillboard(unsigned index);
+
     /// Return whether billboards are relative to the scene node.
     /// Return whether billboards are relative to the scene node.
     bool IsRelative() const { return relative_; }
     bool IsRelative() const { return relative_; }
+
     /// Return whether scene node scale affects billboards' size.
     /// Return whether scene node scale affects billboards' size.
     bool IsScaled() const { return scaled_; }
     bool IsScaled() const { return scaled_; }
+
     /// Return whether billboards are sorted.
     /// Return whether billboards are sorted.
     bool IsSorted() const { return sorted_; }
     bool IsSorted() const { return sorted_; }
+
     /// Return how the billboards rotate in relation to the camera.
     /// Return how the billboards rotate in relation to the camera.
     FaceCameraMode GetFaceCameraMode() const { return faceCameraMode_; }
     FaceCameraMode GetFaceCameraMode() const { return faceCameraMode_; }
+
     /// Return animation LOD bias.
     /// Return animation LOD bias.
     float GetAnimationLodBias() const { return animationLodBias_; }
     float GetAnimationLodBias() const { return animationLodBias_; }
 
 

+ 11 - 7
Source/Urho3D/Graphics/Camera.cpp

@@ -20,8 +20,10 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
-#include "../Graphics/Camera.h"
+#include "../Precompiled.h"
+
 #include "../Core/Context.h"
 #include "../Core/Context.h"
+#include "../Graphics/Camera.h"
 #include "../Graphics/DebugRenderer.h"
 #include "../Graphics/DebugRenderer.h"
 #include "../Graphics/Drawable.h"
 #include "../Graphics/Drawable.h"
 #include "../Scene/Node.h"
 #include "../Scene/Node.h"
@@ -97,8 +99,10 @@ void Camera::RegisterObject(Context* context)
     ATTRIBUTE("View Mask", int, viewMask_, DEFAULT_VIEWMASK, AM_DEFAULT);
     ATTRIBUTE("View Mask", int, viewMask_, DEFAULT_VIEWMASK, AM_DEFAULT);
     ATTRIBUTE("View Override Flags", int, viewOverrideFlags_, VO_NONE, AM_DEFAULT);
     ATTRIBUTE("View Override Flags", int, viewOverrideFlags_, VO_NONE, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Projection Offset", GetProjectionOffset, SetProjectionOffset, Vector2, Vector2::ZERO, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Projection Offset", GetProjectionOffset, SetProjectionOffset, Vector2, Vector2::ZERO, AM_DEFAULT);
-    MIXED_ACCESSOR_ATTRIBUTE("Reflection Plane", GetReflectionPlaneAttr, SetReflectionPlaneAttr, Vector4, Vector4(0.0f, 1.0f, 0.0f, 0.0f), AM_DEFAULT);
-    MIXED_ACCESSOR_ATTRIBUTE("Clip Plane", GetClipPlaneAttr, SetClipPlaneAttr, Vector4, Vector4(0.0f, 1.0f, 0.0f, 0.0f), AM_DEFAULT);
+    MIXED_ACCESSOR_ATTRIBUTE("Reflection Plane", GetReflectionPlaneAttr, SetReflectionPlaneAttr, Vector4,
+        Vector4(0.0f, 1.0f, 0.0f, 0.0f), AM_DEFAULT);
+    MIXED_ACCESSOR_ATTRIBUTE("Clip Plane", GetClipPlaneAttr, SetClipPlaneAttr, Vector4, Vector4(0.0f, 1.0f, 0.0f, 0.0f),
+        AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Use Reflection", GetUseReflection, SetUseReflection, bool, false, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Use Reflection", GetUseReflection, SetUseReflection, bool, false, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Use Clipping", GetUseClipping, SetUseClipping, bool, false, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Use Clipping", GetUseClipping, SetUseClipping, bool, false, AM_DEFAULT);
 }
 }
@@ -336,7 +340,7 @@ Vector2 Camera::WorldToScreenPoint(const Vector3& worldPos) const
     Vector3 eyeSpacePos = GetView() * worldPos;
     Vector3 eyeSpacePos = GetView() * worldPos;
     Vector2 ret;
     Vector2 ret;
 
 
-    if(eyeSpacePos.z_ > 0.0f)
+    if (eyeSpacePos.z_ > 0.0f)
     {
     {
         Vector3 screenSpacePos = GetProjection(false) * eyeSpacePos;
         Vector3 screenSpacePos = GetProjection(false) * eyeSpacePos;
         ret.x_ = screenSpacePos.x_;
         ret.x_ = screenSpacePos.x_;
@@ -392,11 +396,11 @@ Matrix4 Camera::GetProjection(bool apiSpecific) const
     Matrix4 ret(Matrix4::ZERO);
     Matrix4 ret(Matrix4::ZERO);
 
 
     // Whether to construct matrix using OpenGL or Direct3D clip space convention
     // Whether to construct matrix using OpenGL or Direct3D clip space convention
-    #ifdef URHO3D_OPENGL
+#ifdef URHO3D_OPENGL
     bool openGLFormat = apiSpecific;
     bool openGLFormat = apiSpecific;
-    #else
+#else
     bool openGLFormat = false;
     bool openGLFormat = false;
-    #endif
+#endif
 
 
     if (!orthographic_)
     if (!orthographic_)
     {
     {

+ 22 - 2
Source/Urho3D/Graphics/Camera.h

@@ -22,10 +22,10 @@
 
 
 #pragma once
 #pragma once
 
 
-#include "../Math/Frustum.h"
-#include "../Scene/Component.h"
 #include "../Graphics/GraphicsDefs.h"
 #include "../Graphics/GraphicsDefs.h"
+#include "../Math/Frustum.h"
 #include "../Math/Ray.h"
 #include "../Math/Ray.h"
+#include "../Scene/Component.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {
@@ -97,28 +97,40 @@ public:
 
 
     /// Return far clip distance.
     /// Return far clip distance.
     float GetFarClip() const { return farClip_; }
     float GetFarClip() const { return farClip_; }
+
     /// Return near clip distance.
     /// Return near clip distance.
     float GetNearClip() const;
     float GetNearClip() const;
+
     /// Return vertical field of view in degrees.
     /// Return vertical field of view in degrees.
     float GetFov() const { return fov_; }
     float GetFov() const { return fov_; }
+
     /// Return orthographic mode size.
     /// Return orthographic mode size.
     float GetOrthoSize() const { return orthoSize_; }
     float GetOrthoSize() const { return orthoSize_; }
+
     /// Return aspect ratio.
     /// Return aspect ratio.
     float GetAspectRatio() const { return aspectRatio_; }
     float GetAspectRatio() const { return aspectRatio_; }
+
     /// Return zoom.
     /// Return zoom.
     float GetZoom() const { return zoom_; }
     float GetZoom() const { return zoom_; }
+
     /// Return LOD bias.
     /// Return LOD bias.
     float GetLodBias() const { return lodBias_; }
     float GetLodBias() const { return lodBias_; }
+
     /// Return view mask.
     /// Return view mask.
     unsigned GetViewMask() const { return viewMask_; }
     unsigned GetViewMask() const { return viewMask_; }
+
     /// Return view override flags.
     /// Return view override flags.
     unsigned GetViewOverrideFlags() const { return viewOverrideFlags_; }
     unsigned GetViewOverrideFlags() const { return viewOverrideFlags_; }
+
     /// Return fill mode.
     /// Return fill mode.
     FillMode GetFillMode() const { return fillMode_; }
     FillMode GetFillMode() const { return fillMode_; }
+
     /// Return orthographic flag.
     /// Return orthographic flag.
     bool IsOrthographic() const { return orthographic_; }
     bool IsOrthographic() const { return orthographic_; }
+
     /// Return auto aspect ratio flag.
     /// Return auto aspect ratio flag.
     bool GetAutoAspectRatio() const { return autoAspectRatio_; }
     bool GetAutoAspectRatio() const { return autoAspectRatio_; }
+
     /// Return frustum in world space.
     /// Return frustum in world space.
     const Frustum& GetFrustum() const;
     const Frustum& GetFrustum() const;
     /// Return API-specific projection matrix.
     /// Return API-specific projection matrix.
@@ -143,20 +155,28 @@ public:
     Vector2 WorldToScreenPoint(const Vector3& worldPos) const;
     Vector2 WorldToScreenPoint(const Vector3& worldPos) const;
     // Convert normalized screen coordinates (0.0 - 1.0) and depth to a world space point.
     // Convert normalized screen coordinates (0.0 - 1.0) and depth to a world space point.
     Vector3 ScreenToWorldPoint(const Vector3& screenPos) const;
     Vector3 ScreenToWorldPoint(const Vector3& screenPos) const;
+
     /// Return projection offset.
     /// Return projection offset.
     const Vector2& GetProjectionOffset() const { return projectionOffset_; }
     const Vector2& GetProjectionOffset() const { return projectionOffset_; }
+
     /// Return whether is using reflection.
     /// Return whether is using reflection.
     bool GetUseReflection() const { return useReflection_; }
     bool GetUseReflection() const { return useReflection_; }
+
     /// Return the reflection plane.
     /// Return the reflection plane.
     const Plane& GetReflectionPlane() const { return reflectionPlane_; }
     const Plane& GetReflectionPlane() const { return reflectionPlane_; }
+
     /// Return whether is using a custom clipping plane.
     /// Return whether is using a custom clipping plane.
     bool GetUseClipping() const { return useClipping_; }
     bool GetUseClipping() const { return useClipping_; }
+
     /// Return the custom clipping plane.
     /// Return the custom clipping plane.
     const Plane& GetClipPlane() const { return clipPlane_; }
     const Plane& GetClipPlane() const { return clipPlane_; }
+
     /// Return vertical flipping mode.
     /// Return vertical flipping mode.
     bool GetFlipVertical() const { return flipVertical_; }
     bool GetFlipVertical() const { return flipVertical_; }
+
     /// Return whether to reverse culling; affected by vertical flipping and reflection.
     /// Return whether to reverse culling; affected by vertical flipping and reflection.
     bool GetReverseCulling() const { return flipVertical_ ^ useReflection_; }
     bool GetReverseCulling() const { return flipVertical_ ^ useReflection_; }
+
     /// Return distance to position. In orthographic mode uses only Z coordinate.
     /// Return distance to position. In orthographic mode uses only Z coordinate.
     float GetDistance(const Vector3& worldPos) const;
     float GetDistance(const Vector3& worldPos) const;
     /// Return squared distance to position. In orthographic mode uses only Z coordinate.
     /// Return squared distance to position. In orthographic mode uses only Z coordinate.

+ 59 - 48
Source/Urho3D/Graphics/CustomGeometry.cpp

@@ -20,21 +20,22 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
+#include "../Core/Context.h"
+#include "../Core/Profiler.h"
 #include "../Graphics/Batch.h"
 #include "../Graphics/Batch.h"
 #include "../Graphics/Camera.h"
 #include "../Graphics/Camera.h"
-#include "../Core/Context.h"
 #include "../Graphics/CustomGeometry.h"
 #include "../Graphics/CustomGeometry.h"
 #include "../Graphics/Geometry.h"
 #include "../Graphics/Geometry.h"
-#include "../IO/Log.h"
 #include "../Graphics/Material.h"
 #include "../Graphics/Material.h"
-#include "../IO/MemoryBuffer.h"
-#include "../Scene/Node.h"
 #include "../Graphics/OcclusionBuffer.h"
 #include "../Graphics/OcclusionBuffer.h"
 #include "../Graphics/OctreeQuery.h"
 #include "../Graphics/OctreeQuery.h"
-#include "../Core/Profiler.h"
-#include "../Resource/ResourceCache.h"
-#include "../IO/VectorBuffer.h"
 #include "../Graphics/VertexBuffer.h"
 #include "../Graphics/VertexBuffer.h"
+#include "../IO/Log.h"
+#include "../IO/MemoryBuffer.h"
+#include "../Resource/ResourceCache.h"
+#include "../Scene/Node.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -65,8 +66,10 @@ void CustomGeometry::RegisterObject(Context* context)
 
 
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
     ATTRIBUTE("Dynamic Vertex Buffer", bool, dynamic_, false, AM_DEFAULT);
     ATTRIBUTE("Dynamic Vertex Buffer", bool, dynamic_, false, AM_DEFAULT);
-    MIXED_ACCESSOR_ATTRIBUTE("Geometry Data", GetGeometryDataAttr, SetGeometryDataAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_FILE|AM_NOEDIT);
-    ACCESSOR_ATTRIBUTE("Materials", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()), AM_DEFAULT);
+    MIXED_ACCESSOR_ATTRIBUTE("Geometry Data", GetGeometryDataAttr, SetGeometryDataAttr, PODVector<unsigned char>,
+        Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
+    ACCESSOR_ATTRIBUTE("Materials", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()),
+        AM_DEFAULT);
     ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
     ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
     ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
     ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
@@ -88,43 +91,49 @@ void CustomGeometry::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQ
 
 
     case RAY_OBB:
     case RAY_OBB:
     case RAY_TRIANGLE:
     case RAY_TRIANGLE:
-        Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
-        Ray localRay = query.ray_.Transformed(inverse);
-        float distance = localRay.HitDistance(boundingBox_);
-        Vector3 normal = -query.ray_.direction_;
-
-        if (level == RAY_TRIANGLE && distance < query.maxDistance_)
         {
         {
-            distance = M_INFINITY;
+            Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
+            Ray localRay = query.ray_.Transformed(inverse);
+            float distance = localRay.HitDistance(boundingBox_);
+            Vector3 normal = -query.ray_.direction_;
 
 
-            for (unsigned i = 0; i < batches_.Size(); ++i)
+            if (level == RAY_TRIANGLE && distance < query.maxDistance_)
             {
             {
-                Geometry* geometry = batches_[i].geometry_;
-                if (geometry)
+                distance = M_INFINITY;
+
+                for (unsigned i = 0; i < batches_.Size(); ++i)
                 {
                 {
-                    Vector3 geometryNormal;
-                    float geometryDistance = geometry->GetHitDistance(localRay, &geometryNormal);
-                    if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
+                    Geometry* geometry = batches_[i].geometry_;
+                    if (geometry)
                     {
                     {
-                        distance = geometryDistance;
-                        normal = (node_->GetWorldTransform() * Vector4(geometryNormal, 0.0f)).Normalized();
+                        Vector3 geometryNormal;
+                        float geometryDistance = geometry->GetHitDistance(localRay, &geometryNormal);
+                        if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
+                        {
+                            distance = geometryDistance;
+                            normal = (node_->GetWorldTransform() * Vector4(geometryNormal, 0.0f)).Normalized();
+                        }
                     }
                     }
                 }
                 }
             }
             }
-        }
 
 
-        if (distance < query.maxDistance_)
-        {
-            RayQueryResult result;
-            result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
-            result.normal_ = normal;
-            result.distance_ = distance;
-            result.drawable_ = this;
-            result.node_ = node_;
-            result.subObject_ = M_MAX_UNSIGNED;
-            results.Push(result);
+            if (distance < query.maxDistance_)
+            {
+                RayQueryResult result;
+                result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
+                result.normal_ = normal;
+                result.distance_ = distance;
+                result.drawable_ = this;
+                result.node_ = node_;
+                result.subObject_ = M_MAX_UNSIGNED;
+                results.Push(result);
+            }
         }
         }
         break;
         break;
+
+    case RAY_TRIANGLE_UV:
+        LOGWARNING("RAY_TRIANGLE_UV query level is not supported for CustomGeometry component");
+        break;
     }
     }
 }
 }
 
 
@@ -187,7 +196,8 @@ bool CustomGeometry::DrawOcclusion(OcclusionBuffer* buffer)
             continue;
             continue;
 
 
         // Draw and check for running out of triangles
         // Draw and check for running out of triangles
-        success = buffer->Draw(node_->GetWorldTransform(), vertexData, vertexSize, geometry->GetVertexStart(), geometry->GetVertexCount());
+        success = buffer->Draw(node_->GetWorldTransform(), vertexData, vertexSize, geometry->GetVertexStart(),
+            geometry->GetVertexCount());
 
 
         if (!success)
         if (!success)
             break;
             break;
@@ -290,7 +300,8 @@ void CustomGeometry::DefineTangent(const Vector4& tangent)
     elementMask_ |= MASK_TANGENT;
     elementMask_ |= MASK_TANGENT;
 }
 }
 
 
-void CustomGeometry::DefineGeometry(unsigned index, PrimitiveType type, unsigned numVertices, bool hasNormals, bool hasColors, bool hasTexCoords, bool hasTangents)
+void CustomGeometry::DefineGeometry(unsigned index, PrimitiveType type, unsigned numVertices, bool hasNormals, bool hasColors,
+    bool hasTexCoords, bool hasTangents)
 {
 {
     if (index > geometries_.Size())
     if (index > geometries_.Size())
     {
     {
@@ -431,7 +442,7 @@ Material* CustomGeometry::GetMaterial(unsigned index) const
 CustomGeometryVertex* CustomGeometry::GetVertex(unsigned geometryIndex, unsigned vertexNum)
 CustomGeometryVertex* CustomGeometry::GetVertex(unsigned geometryIndex, unsigned vertexNum)
 {
 {
     return (geometryIndex < vertices_.Size() && vertexNum < vertices_[geometryIndex].Size()) ?
     return (geometryIndex < vertices_.Size() && vertexNum < vertices_[geometryIndex].Size()) ?
-        &vertices_[geometryIndex][vertexNum] : (CustomGeometryVertex*)0;
+           &vertices_[geometryIndex][vertexNum] : (CustomGeometryVertex*)0;
 }
 }
 
 
 void CustomGeometry::SetGeometryDataAttr(const PODVector<unsigned char>& value)
 void CustomGeometry::SetGeometryDataAttr(const PODVector<unsigned char>& value)
@@ -452,15 +463,15 @@ void CustomGeometry::SetGeometryDataAttr(const PODVector<unsigned char>& value)
 
 
         for (unsigned j = 0; j < numVertices; ++j)
         for (unsigned j = 0; j < numVertices; ++j)
         {
         {
-             if (elementMask_ & MASK_POSITION)
+            if (elementMask_ & MASK_POSITION)
                 vertices_[i][j].position_ = buffer.ReadVector3();
                 vertices_[i][j].position_ = buffer.ReadVector3();
-             if (elementMask_ & MASK_NORMAL)
+            if (elementMask_ & MASK_NORMAL)
                 vertices_[i][j].normal_ = buffer.ReadVector3();
                 vertices_[i][j].normal_ = buffer.ReadVector3();
-             if (elementMask_ & MASK_COLOR)
+            if (elementMask_ & MASK_COLOR)
                 vertices_[i][j].color_ = buffer.ReadUInt();
                 vertices_[i][j].color_ = buffer.ReadUInt();
-             if (elementMask_ & MASK_TEXCOORD1)
+            if (elementMask_ & MASK_TEXCOORD1)
                 vertices_[i][j].texCoord_ = buffer.ReadVector2();
                 vertices_[i][j].texCoord_ = buffer.ReadVector2();
-             if (elementMask_ & MASK_TANGENT)
+            if (elementMask_ & MASK_TANGENT)
                 vertices_[i][j].tangent_ = buffer.ReadVector4();
                 vertices_[i][j].tangent_ = buffer.ReadVector4();
         }
         }
     }
     }
@@ -490,15 +501,15 @@ PODVector<unsigned char> CustomGeometry::GetGeometryDataAttr() const
 
 
         for (unsigned j = 0; j < numVertices; ++j)
         for (unsigned j = 0; j < numVertices; ++j)
         {
         {
-             if (elementMask_ & MASK_POSITION)
+            if (elementMask_ & MASK_POSITION)
                 ret.WriteVector3(vertices_[i][j].position_);
                 ret.WriteVector3(vertices_[i][j].position_);
-             if (elementMask_ & MASK_NORMAL)
+            if (elementMask_ & MASK_NORMAL)
                 ret.WriteVector3(vertices_[i][j].normal_);
                 ret.WriteVector3(vertices_[i][j].normal_);
-             if (elementMask_ & MASK_COLOR)
+            if (elementMask_ & MASK_COLOR)
                 ret.WriteUInt(vertices_[i][j].color_);
                 ret.WriteUInt(vertices_[i][j].color_);
-             if (elementMask_ & MASK_TEXCOORD1)
+            if (elementMask_ & MASK_TEXCOORD1)
                 ret.WriteVector2(vertices_[i][j].texCoord_);
                 ret.WriteVector2(vertices_[i][j].texCoord_);
-             if (elementMask_ & MASK_TANGENT)
+            if (elementMask_ & MASK_TANGENT)
                 ret.WriteVector4(vertices_[i][j].tangent_);
                 ret.WriteVector4(vertices_[i][j].tangent_);
         }
         }
     }
     }

+ 8 - 1
Source/Urho3D/Graphics/CustomGeometry.h

@@ -85,7 +85,9 @@ public:
     /// Define a vertex tangent.
     /// Define a vertex tangent.
     void DefineTangent(const Vector4& tangent);
     void DefineTangent(const Vector4& tangent);
     /// Set the primitive type, number of vertices and elements in a geometry, after which the vertices can be edited with GetVertex(). An alternative to BeginGeometry() / DefineVertex().
     /// Set the primitive type, number of vertices and elements in a geometry, after which the vertices can be edited with GetVertex(). An alternative to BeginGeometry() / DefineVertex().
-    void DefineGeometry(unsigned index, PrimitiveType type, unsigned numVertices, bool hasNormals, bool hasColors, bool hasTexCoords, bool hasTangents);
+    void DefineGeometry
+        (unsigned index, PrimitiveType type, unsigned numVertices, bool hasNormals, bool hasColors, bool hasTexCoords,
+            bool hasTangents);
     /// Update vertex buffer and calculate the bounding box. Call after finishing defining geometry.
     /// Update vertex buffer and calculate the bounding box. Call after finishing defining geometry.
     void Commit();
     void Commit();
     /// Set material on all geometries.
     /// Set material on all geometries.
@@ -95,14 +97,19 @@ public:
 
 
     /// Return number of geometries.
     /// Return number of geometries.
     unsigned GetNumGeometries() const { return geometries_.Size(); }
     unsigned GetNumGeometries() const { return geometries_.Size(); }
+
     /// Return number of vertices in a geometry.
     /// Return number of vertices in a geometry.
     unsigned GetNumVertices(unsigned index) const;
     unsigned GetNumVertices(unsigned index) const;
+
     /// Return whether vertex buffer dynamic mode is enabled.
     /// Return whether vertex buffer dynamic mode is enabled.
     bool IsDynamic() const { return dynamic_; }
     bool IsDynamic() const { return dynamic_; }
+
     /// Return material by geometry index.
     /// Return material by geometry index.
     Material* GetMaterial(unsigned index = 0) const;
     Material* GetMaterial(unsigned index = 0) const;
+
     /// Return all vertices. These can be edited; calling Commit() updates the vertex buffer.
     /// Return all vertices. These can be edited; calling Commit() updates the vertex buffer.
     Vector<PODVector<CustomGeometryVertex> >& GetVertices() { return vertices_; }
     Vector<PODVector<CustomGeometryVertex> >& GetVertices() { return vertices_; }
+
     /// Return a vertex in a geometry for editing, or null if out of bounds. After the edits are finished, calling Commit() updates  the vertex buffer.
     /// Return a vertex in a geometry for editing, or null if out of bounds. After the edits are finished, calling Commit() updates  the vertex buffer.
     CustomGeometryVertex* GetVertex(unsigned geometryIndex, unsigned vertexNum);
     CustomGeometryVertex* GetVertex(unsigned geometryIndex, unsigned vertexNum);
 
 

+ 44 - 23
Source/Urho3D/Graphics/DebugRenderer.cpp

@@ -20,19 +20,20 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
 
 
-#include "../Graphics/AnimatedModel.h"
-#include "../Graphics/Camera.h"
 #include "../Core/Context.h"
 #include "../Core/Context.h"
 #include "../Core/CoreEvents.h"
 #include "../Core/CoreEvents.h"
+#include "../Core/Profiler.h"
+#include "../Graphics/AnimatedModel.h"
+#include "../Graphics/Camera.h"
 #include "../Graphics/DebugRenderer.h"
 #include "../Graphics/DebugRenderer.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/Light.h"
 #include "../Graphics/Light.h"
-#include "../Math/Polyhedron.h"
-#include "../Core/Profiler.h"
-#include "../Resource/ResourceCache.h"
 #include "../Graphics/ShaderVariation.h"
 #include "../Graphics/ShaderVariation.h"
 #include "../Graphics/VertexBuffer.h"
 #include "../Graphics/VertexBuffer.h"
+#include "../Math/Polyhedron.h"
+#include "../Resource/ResourceCache.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -89,7 +90,7 @@ void DebugRenderer::AddLine(const Vector3& start, const Vector3& end, unsigned c
         noDepthLines_.Push(DebugLine(start, end, color));
         noDepthLines_.Push(DebugLine(start, end, color));
 }
 }
 
 
-void DebugRenderer::AddTriangle(const Vector3& v1, const Vector3& v2, const Vector3& v3,  const Color& color, bool depthTest)
+void DebugRenderer::AddTriangle(const Vector3& v1, const Vector3& v2, const Vector3& v3, const Color& color, bool depthTest)
 {
 {
     AddTriangle(v1, v2, v3, color.ToUInt(), depthTest);
     AddTriangle(v1, v2, v3, color.ToUInt(), depthTest);
 }
 }
@@ -223,7 +224,7 @@ static Vector3 PointOnSphere(const Sphere& sphere, unsigned theta, unsigned phi)
 void DebugRenderer::AddSphere(const Sphere& sphere, const Color& color, bool depthTest)
 void DebugRenderer::AddSphere(const Sphere& sphere, const Color& color, bool depthTest)
 {
 {
     unsigned uintColor = color.ToUInt();
     unsigned uintColor = color.ToUInt();
-    
+
     for (unsigned j = 0; j < 180; j += 45)
     for (unsigned j = 0; j < 180; j += 45)
     {
     {
         for (unsigned i = 0; i < 360; i += 45)
         for (unsigned i = 0; i < 360; i += 45)
@@ -232,7 +233,7 @@ void DebugRenderer::AddSphere(const Sphere& sphere, const Color& color, bool dep
             Vector3 p2 = PointOnSphere(sphere, i + 45, j);
             Vector3 p2 = PointOnSphere(sphere, i + 45, j);
             Vector3 p3 = PointOnSphere(sphere, i, j + 45);
             Vector3 p3 = PointOnSphere(sphere, i, j + 45);
             Vector3 p4 = PointOnSphere(sphere, i + 45, j + 45);
             Vector3 p4 = PointOnSphere(sphere, i + 45, j + 45);
-            
+
             AddLine(p1, p2, uintColor, depthTest);
             AddLine(p1, p2, uintColor, depthTest);
             AddLine(p3, p4, uintColor, depthTest);
             AddLine(p3, p4, uintColor, depthTest);
             AddLine(p1, p3, uintColor, depthTest);
             AddLine(p1, p3, uintColor, depthTest);
@@ -352,7 +353,7 @@ void DebugRenderer::Render()
 
 
     ShaderVariation* vs = graphics->GetShader(VS, "Basic", "VERTEXCOLOR");
     ShaderVariation* vs = graphics->GetShader(VS, "Basic", "VERTEXCOLOR");
     ShaderVariation* ps = graphics->GetShader(PS, "Basic", "VERTEXCOLOR");
     ShaderVariation* ps = graphics->GetShader(PS, "Basic", "VERTEXCOLOR");
-    
+
     unsigned numVertices = (lines_.Size() + noDepthLines_.Size()) * 2 + (triangles_.Size() + noDepthTriangles_.Size()) * 3;
     unsigned numVertices = (lines_.Size() + noDepthLines_.Size()) * 2 + (triangles_.Size() + noDepthTriangles_.Size()) * 3;
     // Resize the vertex buffer if too small or much too large
     // Resize the vertex buffer if too small or much too large
     if (vertexBuffer_->GetVertexCount() < numVertices || vertexBuffer_->GetVertexCount() > numVertices * 2)
     if (vertexBuffer_->GetVertexCount() < numVertices || vertexBuffer_->GetVertexCount() > numVertices * 2)
@@ -366,9 +367,13 @@ void DebugRenderer::Render()
     {
     {
         const DebugLine& line = lines_[i];
         const DebugLine& line = lines_[i];
 
 
-        dest[0] = line.start_.x_; dest[1] = line.start_.y_; dest[2] = line.start_.z_;
+        dest[0] = line.start_.x_;
+        dest[1] = line.start_.y_;
+        dest[2] = line.start_.z_;
         ((unsigned&)dest[3]) = line.color_;
         ((unsigned&)dest[3]) = line.color_;
-        dest[4] = line.end_.x_; dest[5] = line.end_.y_; dest[6] = line.end_.z_;
+        dest[4] = line.end_.x_;
+        dest[5] = line.end_.y_;
+        dest[6] = line.end_.z_;
         ((unsigned&)dest[7]) = line.color_;
         ((unsigned&)dest[7]) = line.color_;
 
 
         dest += 8;
         dest += 8;
@@ -378,9 +383,13 @@ void DebugRenderer::Render()
     {
     {
         const DebugLine& line = noDepthLines_[i];
         const DebugLine& line = noDepthLines_[i];
 
 
-        dest[0] = line.start_.x_; dest[1] = line.start_.y_; dest[2] = line.start_.z_;
+        dest[0] = line.start_.x_;
+        dest[1] = line.start_.y_;
+        dest[2] = line.start_.z_;
         ((unsigned&)dest[3]) = line.color_;
         ((unsigned&)dest[3]) = line.color_;
-        dest[4] = line.end_.x_; dest[5] = line.end_.y_; dest[6] = line.end_.z_;
+        dest[4] = line.end_.x_;
+        dest[5] = line.end_.y_;
+        dest[6] = line.end_.z_;
         ((unsigned&)dest[7]) = line.color_;
         ((unsigned&)dest[7]) = line.color_;
 
 
         dest += 8;
         dest += 8;
@@ -390,13 +399,19 @@ void DebugRenderer::Render()
     {
     {
         const DebugTriangle& triangle = triangles_[i];
         const DebugTriangle& triangle = triangles_[i];
 
 
-        dest[0] = triangle.v1_.x_; dest[1] = triangle.v1_.y_; dest[2] = triangle.v1_.z_;
+        dest[0] = triangle.v1_.x_;
+        dest[1] = triangle.v1_.y_;
+        dest[2] = triangle.v1_.z_;
         ((unsigned&)dest[3]) = triangle.color_;
         ((unsigned&)dest[3]) = triangle.color_;
 
 
-        dest[4] = triangle.v2_.x_; dest[5] = triangle.v2_.y_; dest[6] = triangle.v2_.z_;
+        dest[4] = triangle.v2_.x_;
+        dest[5] = triangle.v2_.y_;
+        dest[6] = triangle.v2_.z_;
         ((unsigned&)dest[7]) = triangle.color_;
         ((unsigned&)dest[7]) = triangle.color_;
-        
-        dest[8] = triangle.v3_.x_; dest[9] = triangle.v3_.y_; dest[10] = triangle.v3_.z_;
+
+        dest[8] = triangle.v3_.x_;
+        dest[9] = triangle.v3_.y_;
+        dest[10] = triangle.v3_.z_;
         ((unsigned&)dest[11]) = triangle.color_;
         ((unsigned&)dest[11]) = triangle.color_;
 
 
         dest += 12;
         dest += 12;
@@ -406,13 +421,19 @@ void DebugRenderer::Render()
     {
     {
         const DebugTriangle& triangle = noDepthTriangles_[i];
         const DebugTriangle& triangle = noDepthTriangles_[i];
 
 
-        dest[0] = triangle.v1_.x_; dest[1] = triangle.v1_.y_; dest[2] = triangle.v1_.z_;
+        dest[0] = triangle.v1_.x_;
+        dest[1] = triangle.v1_.y_;
+        dest[2] = triangle.v1_.z_;
         ((unsigned&)dest[3]) = triangle.color_;
         ((unsigned&)dest[3]) = triangle.color_;
 
 
-        dest[4] = triangle.v2_.x_; dest[5] = triangle.v2_.y_; dest[6] = triangle.v2_.z_;
+        dest[4] = triangle.v2_.x_;
+        dest[5] = triangle.v2_.y_;
+        dest[6] = triangle.v2_.z_;
         ((unsigned&)dest[7]) = triangle.color_;
         ((unsigned&)dest[7]) = triangle.color_;
 
 
-        dest[8] = triangle.v3_.x_; dest[9] = triangle.v3_.y_; dest[10] = triangle.v3_.z_;
+        dest[8] = triangle.v3_.x_;
+        dest[9] = triangle.v3_.y_;
+        dest[10] = triangle.v3_.z_;
         ((unsigned&)dest[11]) = triangle.color_;
         ((unsigned&)dest[11]) = triangle.color_;
 
 
         dest += 12;
         dest += 12;
@@ -448,9 +469,9 @@ void DebugRenderer::Render()
         graphics->Draw(LINE_LIST, start, count);
         graphics->Draw(LINE_LIST, start, count);
         start += count;
         start += count;
     }
     }
-    
+
     graphics->SetBlendMode(BLEND_ALPHA);
     graphics->SetBlendMode(BLEND_ALPHA);
-    
+
     if (triangles_.Size())
     if (triangles_.Size())
     {
     {
         count = triangles_.Size() * 3;
         count = triangles_.Size() * 3;
@@ -473,7 +494,7 @@ bool DebugRenderer::IsInside(const BoundingBox& box) const
 
 
 bool DebugRenderer::HasContent() const
 bool DebugRenderer::HasContent() const
 {
 {
-    return (lines_.Empty() && noDepthLines_.Empty() && triangles_.Empty() && noDepthTriangles_.Empty()) ? false : true;
+    return !(lines_.Empty() && noDepthLines_.Empty() && triangles_.Empty() && noDepthTriangles_.Empty());
 }
 }
 
 
 void DebugRenderer::HandleEndFrame(StringHash eventType, VariantMap& eventData)
 void DebugRenderer::HandleEndFrame(StringHash eventType, VariantMap& eventData)

+ 14 - 9
Source/Urho3D/Graphics/DebugRenderer.h

@@ -23,8 +23,8 @@
 #pragma once
 #pragma once
 
 
 #include "../Math/Color.h"
 #include "../Math/Color.h"
-#include "../Scene/Component.h"
 #include "../Math/Frustum.h"
 #include "../Math/Frustum.h"
+#include "../Scene/Component.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {
@@ -47,7 +47,7 @@ struct DebugLine
     DebugLine()
     DebugLine()
     {
     {
     }
     }
-    
+
     /// Construct with start and end positions and color.
     /// Construct with start and end positions and color.
     DebugLine(const Vector3& start, const Vector3& end, unsigned color) :
     DebugLine(const Vector3& start, const Vector3& end, unsigned color) :
         start_(start),
         start_(start),
@@ -55,7 +55,7 @@ struct DebugLine
         color_(color)
         color_(color)
     {
     {
     }
     }
-    
+
     /// Start position.
     /// Start position.
     Vector3 start_;
     Vector3 start_;
     /// End position.
     /// End position.
@@ -95,7 +95,7 @@ struct DebugTriangle
 class URHO3D_API DebugRenderer : public Component
 class URHO3D_API DebugRenderer : public Component
 {
 {
     OBJECT(DebugRenderer);
     OBJECT(DebugRenderer);
-    
+
 public:
 public:
     /// Construct.
     /// Construct.
     DebugRenderer(Context* context);
     DebugRenderer(Context* context);
@@ -103,7 +103,7 @@ public:
     virtual ~DebugRenderer();
     virtual ~DebugRenderer();
     /// Register object factory.
     /// Register object factory.
     static void RegisterObject(Context* context);
     static void RegisterObject(Context* context);
-    
+
     /// Set the camera viewpoint. Call before rendering, or before adding geometry if you want to use culling.
     /// Set the camera viewpoint. Call before rendering, or before adding geometry if you want to use culling.
     void SetView(Camera* camera);
     void SetView(Camera* camera);
     /// Add a line.
     /// Add a line.
@@ -131,25 +131,30 @@ public:
     /// Add a skeleton.
     /// Add a skeleton.
     void AddSkeleton(const Skeleton& skeleton, const Color& color, bool depthTest = true);
     void AddSkeleton(const Skeleton& skeleton, const Color& color, bool depthTest = true);
     /// Add a triangle mesh.
     /// Add a triangle mesh.
-    void AddTriangleMesh(const void* vertexData, unsigned vertexSize, const void* indexData, unsigned indexSize, unsigned indexStart, unsigned indexCount, const Matrix3x4& transform, const Color& color, bool depthTest = true);
+    void AddTriangleMesh
+        (const void* vertexData, unsigned vertexSize, const void* indexData, unsigned indexSize, unsigned indexStart,
+            unsigned indexCount, const Matrix3x4& transform, const Color& color, bool depthTest = true);
     /// Update vertex buffer and render all debug lines. The viewport and rendertarget should be set before.
     /// Update vertex buffer and render all debug lines. The viewport and rendertarget should be set before.
     void Render();
     void Render();
-    
+
     /// Return the view transform.
     /// Return the view transform.
     const Matrix3x4& GetView() const { return view_; }
     const Matrix3x4& GetView() const { return view_; }
+
     /// Return the projection transform.
     /// Return the projection transform.
     const Matrix4& GetProjection() const { return projection_; }
     const Matrix4& GetProjection() const { return projection_; }
+
     /// Return the view frustum.
     /// Return the view frustum.
     const Frustum& GetFrustum() const { return frustum_; }
     const Frustum& GetFrustum() const { return frustum_; }
+
     /// Check whether a bounding box is inside the view frustum.
     /// Check whether a bounding box is inside the view frustum.
     bool IsInside(const BoundingBox& box) const;
     bool IsInside(const BoundingBox& box) const;
     /// Return whether has something to render.
     /// Return whether has something to render.
     bool HasContent() const;
     bool HasContent() const;
-    
+
 private:
 private:
     /// Handle end of frame. Clear debug geometry.
     /// Handle end of frame. Clear debug geometry.
     void HandleEndFrame(StringHash eventType, VariantMap& eventData);
     void HandleEndFrame(StringHash eventType, VariantMap& eventData);
-    
+
     /// Lines rendered with depth test.
     /// Lines rendered with depth test.
     PODVector<DebugLine> lines_;
     PODVector<DebugLine> lines_;
     /// Lines rendered without depth test.
     /// Lines rendered without depth test.

+ 21 - 19
Source/Urho3D/Graphics/DecalSet.cpp

@@ -20,25 +20,25 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../Precompiled.h"
+
+#include "../Core/Context.h"
+#include "../Core/Profiler.h"
 #include "../Graphics/AnimatedModel.h"
 #include "../Graphics/AnimatedModel.h"
 #include "../Graphics/Batch.h"
 #include "../Graphics/Batch.h"
 #include "../Graphics/Camera.h"
 #include "../Graphics/Camera.h"
-#include "../Core/Context.h"
 #include "../Graphics/DecalSet.h"
 #include "../Graphics/DecalSet.h"
 #include "../Graphics/Geometry.h"
 #include "../Graphics/Geometry.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/IndexBuffer.h"
 #include "../Graphics/IndexBuffer.h"
-#include "../IO/Log.h"
 #include "../Graphics/Material.h"
 #include "../Graphics/Material.h"
+#include "../Graphics/Tangent.h"
+#include "../Graphics/VertexBuffer.h"
+#include "../IO/Log.h"
 #include "../IO/MemoryBuffer.h"
 #include "../IO/MemoryBuffer.h"
-#include "../Scene/Node.h"
-#include "../Core/Profiler.h"
 #include "../Resource/ResourceCache.h"
 #include "../Resource/ResourceCache.h"
 #include "../Scene/Scene.h"
 #include "../Scene/Scene.h"
 #include "../Scene/SceneEvents.h"
 #include "../Scene/SceneEvents.h"
-#include "../Graphics/Tangent.h"
-#include "../IO/VectorBuffer.h"
-#include "../Graphics/VertexBuffer.h"
 
 
 #include "../DebugNew.h"
 #include "../DebugNew.h"
 
 
@@ -54,7 +54,7 @@ static const unsigned DEFAULT_MAX_VERTICES = 512;
 static const unsigned DEFAULT_MAX_INDICES = 1024;
 static const unsigned DEFAULT_MAX_INDICES = 1024;
 static const unsigned STATIC_ELEMENT_MASK = MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT;
 static const unsigned STATIC_ELEMENT_MASK = MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT;
 static const unsigned SKINNED_ELEMENT_MASK = MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT | MASK_BLENDWEIGHTS |
 static const unsigned SKINNED_ELEMENT_MASK = MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT | MASK_BLENDWEIGHTS |
-    MASK_BLENDINDICES;
+                                             MASK_BLENDINDICES;
 
 
 static DecalVertex ClipEdge(const DecalVertex& v0, const DecalVertex& v1, float d0, float d1, bool skinned)
 static DecalVertex ClipEdge(const DecalVertex& v0, const DecalVertex& v1, float d0, float d1, bool skinned)
 {
 {
@@ -91,7 +91,7 @@ static DecalVertex ClipEdge(const DecalVertex& v0, const DecalVertex& v1, float
 
 
 static void ClipPolygon(PODVector<DecalVertex>& dest, const PODVector<DecalVertex>& src, const Plane& plane, bool skinned)
 static void ClipPolygon(PODVector<DecalVertex>& dest, const PODVector<DecalVertex>& src, const Plane& plane, bool skinned)
 {
 {
-    unsigned last;
+    unsigned last = 0;
     float lastDistance = 0.0f;
     float lastDistance = 0.0f;
     dest.Clear();
     dest.Clear();
 
 
@@ -130,12 +130,12 @@ void Decal::AddVertex(const DecalVertex& vertex)
     {
     {
         if (vertex.position_.Equals(vertices_[i].position_) && vertex.normal_.Equals(vertices_[i].normal_))
         if (vertex.position_.Equals(vertices_[i].position_) && vertex.normal_.Equals(vertices_[i].normal_))
         {
         {
-            indices_.Push(i);
+            indices_.Push((unsigned short)i);
             return;
             return;
         }
         }
     }
     }
 
 
-    unsigned short newIndex = vertices_.Size();
+    unsigned short newIndex = (unsigned short)vertices_.Size();
     vertices_.Push(vertex);
     vertices_.Push(vertex);
     indices_.Push(newIndex);
     indices_.Push(newIndex);
 }
 }
@@ -180,13 +180,15 @@ void DecalSet::RegisterObject(Context* context)
     context->RegisterFactory<DecalSet>(GEOMETRY_CATEGORY);
     context->RegisterFactory<DecalSet>(GEOMETRY_CATEGORY);
 
 
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
-    MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()), AM_DEFAULT);
+    MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()),
+        AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Max Vertices", GetMaxVertices, SetMaxVertices, unsigned, DEFAULT_MAX_VERTICES, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Max Vertices", GetMaxVertices, SetMaxVertices, unsigned, DEFAULT_MAX_VERTICES, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Max Indices", GetMaxIndices, SetMaxIndices, unsigned, DEFAULT_MAX_INDICES, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Max Indices", GetMaxIndices, SetMaxIndices, unsigned, DEFAULT_MAX_INDICES, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
     COPY_BASE_ATTRIBUTES(Drawable);
     COPY_BASE_ATTRIBUTES(Drawable);
-    MIXED_ACCESSOR_ATTRIBUTE("Decals", GetDecalsAttr, SetDecalsAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
+    MIXED_ACCESSOR_ATTRIBUTE("Decals", GetDecalsAttr, SetDecalsAttr, PODVector<unsigned char>, Variant::emptyBuffer,
+        AM_FILE | AM_NOEDIT);
 }
 }
 
 
 void DecalSet::ApplyAttributes()
 void DecalSet::ApplyAttributes()
@@ -252,7 +254,7 @@ void DecalSet::SetMaterial(Material* material)
 void DecalSet::SetMaxVertices(unsigned num)
 void DecalSet::SetMaxVertices(unsigned num)
 {
 {
     // Never expand to 32 bit indices
     // Never expand to 32 bit indices
-    num = Clamp((int)num, MIN_VERTICES, MAX_VERTICES);
+    num = (unsigned)Clamp((int)num, MIN_VERTICES, MAX_VERTICES);
 
 
     if (num != maxVertices_)
     if (num != maxVertices_)
     {
     {
@@ -329,8 +331,8 @@ bool DecalSet::AddDecal(Drawable* target, const Vector3& worldPosition, const Qu
                 continue;
                 continue;
 
 
             // Represent the decal as a sphere, try to find the biggest colliding bone
             // Represent the decal as a sphere, try to find the biggest colliding bone
-            Sphere decalSphere(bone->node_->GetWorldTransform().Inverse() * worldPosition, 0.5f * size /
-                bone->node_->GetWorldScale().Length());
+            Sphere decalSphere
+                (bone->node_->GetWorldTransform().Inverse() * worldPosition, 0.5f * size / bone->node_->GetWorldScale().Length());
 
 
             if (bone->collisionMask_ & BONECOLLISION_BOX)
             if (bone->collisionMask_ & BONECOLLISION_BOX)
             {
             {
@@ -421,14 +423,14 @@ bool DecalSet::AddDecal(Drawable* target, const Vector3& worldPosition, const Qu
     if (newDecal.vertices_.Size() > maxVertices_)
     if (newDecal.vertices_.Size() > maxVertices_)
     {
     {
         LOGWARNING("Can not add decal, vertex count " + String(newDecal.vertices_.Size()) + " exceeds maximum " +
         LOGWARNING("Can not add decal, vertex count " + String(newDecal.vertices_.Size()) + " exceeds maximum " +
-            String(maxVertices_));
+                   String(maxVertices_));
         decals_.Pop();
         decals_.Pop();
         return false;
         return false;
     }
     }
     if (newDecal.indices_.Size() > maxIndices_)
     if (newDecal.indices_.Size() > maxIndices_)
     {
     {
         LOGWARNING("Can not add decal, index count " + String(newDecal.indices_.Size()) + " exceeds maximum " +
         LOGWARNING("Can not add decal, index count " + String(newDecal.indices_.Size()) + " exceeds maximum " +
-            String(maxIndices_));
+                   String(maxIndices_));
         decals_.Pop();
         decals_.Pop();
         return false;
         return false;
     }
     }
@@ -932,7 +934,7 @@ bool DecalSet::GetBones(Drawable* target, unsigned batchIndex, const float* blen
                 }
                 }
             }
             }
 
 
-            newBlendIndices[i] = index;
+            newBlendIndices[i] = (unsigned char)index;
         }
         }
         else
         else
             newBlendIndices[i] = 0;
             newBlendIndices[i] = 0;

+ 21 - 7
Source/Urho3D/Graphics/DecalSet.h

@@ -22,10 +22,10 @@
 
 
 #pragma once
 #pragma once
 
 
-#include "../Graphics/Drawable.h"
-#include "../Math/Frustum.h"
 #include "../Container/List.h"
 #include "../Container/List.h"
+#include "../Graphics/Drawable.h"
 #include "../Graphics/Skeleton.h"
 #include "../Graphics/Skeleton.h"
+#include "../Math/Frustum.h"
 
 
 namespace Urho3D
 namespace Urho3D
 {
 {
@@ -134,7 +134,9 @@ public:
     /// Set maximum number of decal vertex indices.
     /// Set maximum number of decal vertex indices.
     void SetMaxIndices(unsigned num);
     void SetMaxIndices(unsigned num);
     /// Add a decal at world coordinates, using a target drawable's geometry for reference. If the decal needs to move with the target, the decal component should be created to the target's node. Return true if successful.
     /// Add a decal at world coordinates, using a target drawable's geometry for reference. If the decal needs to move with the target, the decal component should be created to the target's node. Return true if successful.
-    bool AddDecal(Drawable* target, const Vector3& worldPosition, const Quaternion& worldRotation, float size, float aspectRatio, float depth, const Vector2& topLeftUV, const Vector2& bottomRightUV, float timeToLive = 0.0f, float normalCutoff = 0.1f, unsigned subGeometry = M_MAX_UNSIGNED);
+    bool AddDecal(Drawable* target, const Vector3& worldPosition, const Quaternion& worldRotation, float size, float aspectRatio,
+        float depth, const Vector2& topLeftUV, const Vector2& bottomRightUV, float timeToLive = 0.0f, float normalCutoff = 0.1f,
+        unsigned subGeometry = M_MAX_UNSIGNED);
     /// Remove n oldest decals.
     /// Remove n oldest decals.
     void RemoveDecals(unsigned num);
     void RemoveDecals(unsigned num);
     /// Remove all decals.
     /// Remove all decals.
@@ -142,14 +144,19 @@ public:
 
 
     /// Return material.
     /// Return material.
     Material* GetMaterial() const;
     Material* GetMaterial() const;
+
     /// Return number of decals.
     /// Return number of decals.
     unsigned GetNumDecals() const { return decals_.Size(); }
     unsigned GetNumDecals() const { return decals_.Size(); }
+
     /// Retur number of vertices in the decals.
     /// Retur number of vertices in the decals.
     unsigned GetNumVertices() const { return numVertices_; }
     unsigned GetNumVertices() const { return numVertices_; }
+
     /// Retur number of vertex indices in the decals.
     /// Retur number of vertex indices in the decals.
     unsigned GetNumIndices() const { return numIndices_; }
     unsigned GetNumIndices() const { return numIndices_; }
+
     /// Return maximum number of decal vertices.
     /// Return maximum number of decal vertices.
     unsigned GetMaxVertices() const { return maxVertices_; }
     unsigned GetMaxVertices() const { return maxVertices_; }
+
     /// Return maximum number of decal vertex indices.
     /// Return maximum number of decal vertex indices.
     unsigned GetMaxIndices() const { return maxIndices_; }
     unsigned GetMaxIndices() const { return maxIndices_; }
 
 
@@ -170,13 +177,20 @@ protected:
 
 
 private:
 private:
     /// Get triangle faces from the target geometry.
     /// Get triangle faces from the target geometry.
-    void GetFaces(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, const Frustum& frustum, const Vector3& decalNormal, float normalCutoff);
+    void GetFaces(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, const Frustum& frustum,
+        const Vector3& decalNormal, float normalCutoff);
     /// Get triangle face from the target geometry.
     /// Get triangle face from the target geometry.
-    void GetFace(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, unsigned i0, unsigned i1, unsigned i2, const unsigned char* positionData, const unsigned char* normalData, const unsigned char* skinningData, unsigned positionStride, unsigned normalStride, unsigned skinningStride, const Frustum& frustum, const Vector3& decalNormal, float normalCutoff);
+    void GetFace
+        (Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, unsigned i0, unsigned i1, unsigned i2,
+            const unsigned char* positionData, const unsigned char* normalData, const unsigned char* skinningData,
+            unsigned positionStride, unsigned normalStride, unsigned skinningStride, const Frustum& frustum,
+            const Vector3& decalNormal, float normalCutoff);
     /// Get bones referenced by skinning data and remap the skinning indices. Return true if successful.
     /// Get bones referenced by skinning data and remap the skinning indices. Return true if successful.
-    bool GetBones(Drawable* target, unsigned batchIndex, const float* blendWeights, const unsigned char* blendIndices, unsigned char* newBlendIndices);
+    bool GetBones(Drawable* target, unsigned batchIndex, const float* blendWeights, const unsigned char* blendIndices,
+        unsigned char* newBlendIndices);
     /// Calculate UV coordinates for the decal.
     /// Calculate UV coordinates for the decal.
-    void CalculateUVs(Decal& decal, const Matrix3x4& view, const Matrix4& projection, const Vector2& topLeftUV, const Vector2& bottomRightUV);
+    void CalculateUVs
+        (Decal& decal, const Matrix3x4& view, const Matrix4& projection, const Vector2& topLeftUV, const Vector2& bottomRightUV);
     /// Transform decal's vertices from the target geometry to the decal set local space.
     /// Transform decal's vertices from the target geometry to the decal set local space.
     void TransformVertices(Decal& decal, const Matrix3x4& transform);
     void TransformVertices(Decal& decal, const Matrix3x4& transform);
     /// Remove a decal by iterator and return iterator to the next decal.
     /// Remove a decal by iterator and return iterator to the next decal.

+ 2 - 0
Source/Urho3D/Graphics/Direct3D11/D3D11ConstantBuffer.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../../Precompiled.h"
+
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/GraphicsImpl.h"
 #include "../../Graphics/GraphicsImpl.h"
 #include "../../IO/Log.h"
 #include "../../IO/Log.h"

+ 0 - 3
Source/Urho3D/Graphics/Direct3D11/D3D11ConstantBuffer.h

@@ -59,9 +59,6 @@ public:
     bool IsDirty() const { return dirty_; }
     bool IsDirty() const { return dirty_; }
 
 
 private:
 private:
-    /// Create buffer.
-    bool Create();
-
     /// Shadow data.
     /// Shadow data.
     SharedArrayPtr<unsigned char> shadowData_;
     SharedArrayPtr<unsigned char> shadowData_;
     /// Buffer byte size.
     /// Buffer byte size.

+ 2 - 0
Source/Urho3D/Graphics/Direct3D11/D3D11GPUObject.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../../Precompiled.h"
+
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/GraphicsImpl.h"
 #include "../../Graphics/GraphicsImpl.h"
 #include "../../Graphics/GPUObject.h"
 #include "../../Graphics/GPUObject.h"

+ 2 - 0
Source/Urho3D/Graphics/Direct3D11/D3D11Graphics.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../../Precompiled.h"
+
 #include "../../Graphics/AnimatedModel.h"
 #include "../../Graphics/AnimatedModel.h"
 #include "../../Graphics/Animation.h"
 #include "../../Graphics/Animation.h"
 #include "../../Graphics/AnimationController.h"
 #include "../../Graphics/AnimationController.h"

+ 2 - 0
Source/Urho3D/Graphics/Direct3D11/D3D11GraphicsImpl.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../../Precompiled.h"
+
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/GraphicsEvents.h"
 #include "../../Graphics/GraphicsEvents.h"
 #include "../../Graphics/GraphicsImpl.h"
 #include "../../Graphics/GraphicsImpl.h"

+ 2 - 0
Source/Urho3D/Graphics/Direct3D11/D3D11IndexBuffer.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../../Precompiled.h"
+
 #include "../../Core/Context.h"
 #include "../../Core/Context.h"
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/GraphicsImpl.h"
 #include "../../Graphics/GraphicsImpl.h"

+ 2 - 0
Source/Urho3D/Graphics/Direct3D11/D3D11RenderSurface.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../../Precompiled.h"
+
 #include "../../Graphics/Camera.h"
 #include "../../Graphics/Camera.h"
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/GraphicsImpl.h"
 #include "../../Graphics/GraphicsImpl.h"

+ 2 - 0
Source/Urho3D/Graphics/Direct3D11/D3D11ShaderVariation.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 // THE SOFTWARE.
 //
 //
 
 
+#include "../../Precompiled.h"
+
 #include "../../IO/File.h"
 #include "../../IO/File.h"
 #include "../../IO/FileSystem.h"
 #include "../../IO/FileSystem.h"
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/Graphics.h"

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor