diff --git a/assignment-client/src/audio/AudioMixer.cpp b/assignment-client/src/audio/AudioMixer.cpp index 407a64d7a8..5fd9efedd7 100644 --- a/assignment-client/src/audio/AudioMixer.cpp +++ b/assignment-client/src/audio/AudioMixer.cpp @@ -21,12 +21,10 @@ #include #ifdef _WIN32 -#include "Systime.h" #include #else #include #include -#include #include #endif //_WIN32 @@ -389,9 +387,8 @@ void AudioMixer::run() { nodeList->linkedDataCreateCallback = attachNewBufferToNode; int nextFrame = 0; - timeval startTime; - - gettimeofday(&startTime, NULL); + QElapsedTimer timer; + timer.start(); char* clientMixBuffer = new char[NETWORK_BUFFER_LENGTH_BYTES_STEREO + numBytesForPacketHeaderGivenPacketType(PacketTypeMixedAudio)]; @@ -490,7 +487,7 @@ void AudioMixer::run() { break; } - usecToSleep = usecTimestamp(&startTime) + (++nextFrame * BUFFER_SEND_INTERVAL_USECS) - usecTimestampNow(); + usecToSleep = (++nextFrame * BUFFER_SEND_INTERVAL_USECS) - timer.nsecsElapsed() / 1000; // ns to us if (usecToSleep > 0) { usleep(usecToSleep); diff --git a/assignment-client/src/main.cpp b/assignment-client/src/main.cpp index 24d19ddef6..7132b5c38a 100644 --- a/assignment-client/src/main.cpp +++ b/assignment-client/src/main.cpp @@ -17,6 +17,7 @@ #include "AssignmentClientMonitor.h" int main(int argc, char* argv[]) { + initialiseUsecTimestampNow(); #ifndef WIN32 setvbuf(stdout, NULL, _IOLBF, 0); diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index eb62dacf79..e65f3968e0 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -449,7 +449,7 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif if (nodeInterestList.size() > 0) { DTLSServerSession* dtlsSession = _isUsingDTLS ? _dtlsSessions[senderSockAddr] : NULL; - unsigned int dataMTU = dtlsSession ? gnutls_dtls_get_data_mtu(*dtlsSession->getGnuTLSSession()) : MAX_PACKET_SIZE; + int dataMTU = dtlsSession ? (int)gnutls_dtls_get_data_mtu(*dtlsSession->getGnuTLSSession()) : MAX_PACKET_SIZE; // if the node has any interest types, send back those nodes as well foreach (const SharedNodePointer& otherNode, nodeList->getNodeHash()) { diff --git a/domain-server/src/main.cpp b/domain-server/src/main.cpp index bdb10cb56f..871c16a215 100644 --- a/domain-server/src/main.cpp +++ b/domain-server/src/main.cpp @@ -18,10 +18,12 @@ #include #include +#include #include "DomainServer.h" int main(int argc, char* argv[]) { + initialiseUsecTimestampNow(); #ifndef WIN32 setvbuf(stdout, NULL, _IOLBF, 0); diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 5f8555055c..63fa687e4f 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -9,10 +9,6 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifdef WIN32 -#include -#endif - #include #include @@ -134,7 +130,7 @@ QString& Application::resourcesPath() { return staticResourcePath; } -Application::Application(int& argc, char** argv, timeval &startup_time) : +Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : QApplication(argc, argv), _window(new QMainWindow(desktop())), _glWidget(new GLCanvas()), @@ -507,7 +503,7 @@ void Application::initializeGL() { _idleLoopStdev.reset(); if (_justStarted) { - float startupTime = (usecTimestampNow() - usecTimestamp(&_applicationStartupTime)) / 1000000.0; + float startupTime = (float)_applicationStartupTime.elapsed() / 1000.0; _justStarted = false; qDebug("Startup time: %4.2f seconds.", startupTime); const char LOGSTASH_INTERFACE_START_TIME_KEY[] = "interface-start-time"; @@ -1222,7 +1218,6 @@ void Application::touchEndEvent(QTouchEvent* event) { if (_controllerScriptingInterface.isTouchCaptured()) { return; } - // put any application specific touch behavior below here.. _touchDragStartedAvgX = _touchAvgX; _touchDragStartedAvgY = _touchAvgY; @@ -1276,21 +1271,21 @@ void Application::sendPingPackets() { // Every second, check the frame rates and other stuff void Application::timer() { - gettimeofday(&_timerEnd, NULL); - if (Menu::getInstance()->isOptionChecked(MenuOption::TestPing)) { sendPingPackets(); } + + float diffTime = (float)_timerStart.nsecsElapsed() / 1000000000.0f; - _fps = (float)_frameCount / ((float)diffclock(&_timerStart, &_timerEnd) / 1000.f); + _fps = (float)_frameCount / diffTime; - _packetsPerSecond = (float) _datagramProcessor.getPacketCount() / ((float)diffclock(&_timerStart, &_timerEnd) / 1000.f); - _bytesPerSecond = (float) _datagramProcessor.getByteCount() / ((float)diffclock(&_timerStart, &_timerEnd) / 1000.f); + _packetsPerSecond = (float) _datagramProcessor.getPacketCount() / diffTime; + _bytesPerSecond = (float) _datagramProcessor.getByteCount() / diffTime; _frameCount = 0; _datagramProcessor.resetCounters(); - gettimeofday(&_timerStart, NULL); + _timerStart.start(); // ask the node list to check in with the domain server NodeList::getInstance()->sendDomainServerCheckIn(); @@ -1303,13 +1298,11 @@ void Application::idle() { bool showWarnings = getLogger()->extraDebugging(); PerformanceWarning warn(showWarnings, "Application::idle()"); - timeval check; - gettimeofday(&check, NULL); - // Only run simulation code if more than IDLE_SIMULATE_MSECS have passed since last time we ran - double timeSinceLastUpdate = diffclock(&_lastTimeUpdated, &check); + double timeSinceLastUpdate = (double)_lastTimeUpdated.nsecsElapsed() / 1000000.0; if (timeSinceLastUpdate > IDLE_SIMULATE_MSECS) { + _lastTimeUpdated.start(); { PerformanceWarning warn(showWarnings, "Application::idle()... update()"); const float BIGGEST_DELTA_TIME_SECS = 0.25f; @@ -1321,7 +1314,6 @@ void Application::idle() { } { PerformanceWarning warn(showWarnings, "Application::idle()... rest of it"); - _lastTimeUpdated = check; _idleLoopStdev.addValue(timeSinceLastUpdate); // Record standard deviation and reset counter if needed @@ -1637,8 +1629,8 @@ void Application::init() { Qt::QueuedConnection); } - gettimeofday(&_timerStart, NULL); - gettimeofday(&_lastTimeUpdated, NULL); + _timerStart.start(); + _lastTimeUpdated.start(); Menu::getInstance()->loadSettings(); if (Menu::getInstance()->getAudioJitterBufferSamples() != 0) { diff --git a/interface/src/Application.h b/interface/src/Application.h index 63df216a34..e2cdb55f87 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -118,7 +118,7 @@ public: static Application* getInstance() { return static_cast(QCoreApplication::instance()); } static QString& resourcesPath(); - Application(int& argc, char** argv, timeval &startup_time); + Application(int& argc, char** argv, QElapsedTimer &startup_time); ~Application(); void restoreSizeAndPosition(); @@ -393,9 +393,9 @@ private: int _frameCount; float _fps; - timeval _applicationStartupTime; - timeval _timerStart, _timerEnd; - timeval _lastTimeUpdated; + QElapsedTimer _applicationStartupTime; + QElapsedTimer _timerStart; + QElapsedTimer _lastTimeUpdated; bool _justStarted; Stars _stars; diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index eb4a751356..c182f6e842 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -480,7 +480,7 @@ void Audio::handleAudioInput() { float thisSample = 0; int samplesOverNoiseGate = 0; - const float NOISE_GATE_HEIGHT = 7.f; + const float NOISE_GATE_HEIGHT = 7.0f; const int NOISE_GATE_WIDTH = 5; const int NOISE_GATE_CLOSE_FRAME_DELAY = 5; const int NOISE_GATE_FRAMES_TO_AVERAGE = 5; @@ -490,7 +490,7 @@ void Audio::handleAudioInput() { // // Check clipping, adjust DC offset, and check if should open noise gate // - float measuredDcOffset = 0.f; + float measuredDcOffset = 0.0f; // Increment the time since the last clip if (_timeSinceLastClip >= 0.0f) { _timeSinceLastClip += (float) NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL / (float) SAMPLE_RATE; @@ -500,7 +500,7 @@ void Audio::handleAudioInput() { measuredDcOffset += monoAudioSamples[i]; monoAudioSamples[i] -= (int16_t) _dcOffset; thisSample = fabsf(monoAudioSamples[i]); - if (thisSample >= (32767.f * CLIPPING_THRESHOLD)) { + if (thisSample >= (32767.0f * CLIPPING_THRESHOLD)) { _timeSinceLastClip = 0.0f; } loudness += thisSample; @@ -511,18 +511,18 @@ void Audio::handleAudioInput() { } measuredDcOffset /= NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; - if (_dcOffset == 0.f) { + if (_dcOffset == 0.0f) { // On first frame, copy over measured offset _dcOffset = measuredDcOffset; } else { - _dcOffset = DC_OFFSET_AVERAGING * _dcOffset + (1.f - DC_OFFSET_AVERAGING) * measuredDcOffset; + _dcOffset = DC_OFFSET_AVERAGING * _dcOffset + (1.0f - DC_OFFSET_AVERAGING) * measuredDcOffset; } // Add tone injection if enabled - const float TONE_FREQ = 220.f / SAMPLE_RATE * TWO_PI; - const float QUARTER_VOLUME = 8192.f; + const float TONE_FREQ = 220.0f / SAMPLE_RATE * TWO_PI; + const float QUARTER_VOLUME = 8192.0f; if (_toneInjectionEnabled) { - loudness = 0.f; + loudness = 0.0f; for (int i = 0; i < NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; i++) { monoAudioSamples[i] = QUARTER_VOLUME * sinf(TONE_FREQ * (float)(i + _proceduralEffectSample)); loudness += fabsf(monoAudioSamples[i]); @@ -532,7 +532,7 @@ void Audio::handleAudioInput() { // If Noise Gate is enabled, check and turn the gate on and off if (!_toneInjectionEnabled && _noiseGateEnabled) { - float averageOfAllSampleFrames = 0.f; + float averageOfAllSampleFrames = 0.0f; _noiseSampleFrames[_noiseGateSampleCounter++] = _lastInputLoudness; if (_noiseGateSampleCounter == NUMBER_OF_NOISE_SAMPLE_FRAMES) { float smallestSample = FLT_MAX; @@ -643,13 +643,12 @@ void Audio::handleAudioInput() { void Audio::addReceivedAudioToBuffer(const QByteArray& audioByteArray) { const int NUM_INITIAL_PACKETS_DISCARD = 3; const int STANDARD_DEVIATION_SAMPLE_COUNT = 500; - - timeval currentReceiveTime; - gettimeofday(¤tReceiveTime, NULL); + + _timeSinceLastRecieved.start(); _totalPacketsReceived++; - - double timeDiff = diffclock(&_lastReceiveTime, ¤tReceiveTime); - + + double timeDiff = (double)_timeSinceLastRecieved.nsecsElapsed() / 1000000.0; // ns to ms + // Discard first few received packets for computing jitter (often they pile up on start) if (_totalPacketsReceived > NUM_INITIAL_PACKETS_DISCARD) { _stdev.addValue(timeDiff); @@ -660,9 +659,9 @@ void Audio::addReceivedAudioToBuffer(const QByteArray& audioByteArray) { _stdev.reset(); // Set jitter buffer to be a multiple of the measured standard deviation const int MAX_JITTER_BUFFER_SAMPLES = _ringBuffer.getSampleCapacity() / 2; - const float NUM_STANDARD_DEVIATIONS = 3.f; + const float NUM_STANDARD_DEVIATIONS = 3.0f; if (Menu::getInstance()->getAudioJitterBufferSamples() == 0) { - float newJitterBufferSamples = (NUM_STANDARD_DEVIATIONS * _measuredJitter) / 1000.f * SAMPLE_RATE; + float newJitterBufferSamples = (NUM_STANDARD_DEVIATIONS * _measuredJitter) / 1000.0f * SAMPLE_RATE; setJitterBufferSamples(glm::clamp((int)newJitterBufferSamples, 0, MAX_JITTER_BUFFER_SAMPLES)); } } @@ -673,8 +672,6 @@ void Audio::addReceivedAudioToBuffer(const QByteArray& audioByteArray) { } Application::getInstance()->getBandwidthMeter()->inputStream(BandwidthMeter::AUDIO).updateValue(audioByteArray.size()); - - _lastReceiveTime = currentReceiveTime; } // NOTE: numSamples is the total number of single channel samples, since callers will always call this with stereo @@ -903,10 +900,10 @@ void Audio::toggleAudioSpatialProcessing() { void Audio::addProceduralSounds(int16_t* monoInput, int numSamples) { float sample; const float COLLISION_SOUND_CUTOFF_LEVEL = 0.01f; - const float COLLISION_SOUND_MAX_VOLUME = 1000.f; + const float COLLISION_SOUND_MAX_VOLUME = 1000.0f; const float UP_MAJOR_FIFTH = powf(1.5f, 4.0f); - const float DOWN_TWO_OCTAVES = 4.f; - const float DOWN_FOUR_OCTAVES = 16.f; + const float DOWN_TWO_OCTAVES = 4.0f; + const float DOWN_FOUR_OCTAVES = 16.0f; float t; if (_collisionSoundMagnitude > COLLISION_SOUND_CUTOFF_LEVEL) { for (int i = 0; i < numSamples; i++) { @@ -936,12 +933,12 @@ void Audio::addProceduralSounds(int16_t* monoInput, int numSamples) { _proceduralEffectSample += numSamples; // Add a drum sound - const float MAX_VOLUME = 32000.f; - const float MAX_DURATION = 2.f; + const float MAX_VOLUME = 32000.0f; + const float MAX_DURATION = 2.0f; const float MIN_AUDIBLE_VOLUME = 0.001f; const float NOISE_MAGNITUDE = 0.02f; float frequency = (_drumSoundFrequency / SAMPLE_RATE) * TWO_PI; - if (_drumSoundVolume > 0.f) { + if (_drumSoundVolume > 0.0f) { for (int i = 0; i < numSamples; i++) { t = (float) _drumSoundSample + (float) i; sample = sinf(t * frequency); @@ -961,12 +958,12 @@ void Audio::addProceduralSounds(int16_t* monoInput, int numSamples) { _localProceduralSamples[i] = glm::clamp(_localProceduralSamples[i] + collisionSample, MIN_SAMPLE_VALUE, MAX_SAMPLE_VALUE); - _drumSoundVolume *= (1.f - _drumSoundDecay); + _drumSoundVolume *= (1.0f - _drumSoundDecay); } _drumSoundSample += numSamples; - _drumSoundDuration = glm::clamp(_drumSoundDuration - (AUDIO_CALLBACK_MSECS / 1000.f), 0.f, MAX_DURATION); - if (_drumSoundDuration == 0.f || (_drumSoundVolume < MIN_AUDIBLE_VOLUME)) { - _drumSoundVolume = 0.f; + _drumSoundDuration = glm::clamp(_drumSoundDuration - (AUDIO_CALLBACK_MSECS / 1000.0f), 0.0f, MAX_DURATION); + if (_drumSoundDuration == 0.0f || (_drumSoundVolume < MIN_AUDIBLE_VOLUME)) { + _drumSoundVolume = 0.0f; } } } @@ -999,7 +996,7 @@ void Audio::renderToolBox(int x, int y, bool boxed) { if (boxed) { - bool isClipping = ((getTimeSinceLastClip() > 0.f) && (getTimeSinceLastClip() < 1.f)); + bool isClipping = ((getTimeSinceLastClip() > 0.0f) && (getTimeSinceLastClip() < 1.0f)); const int BOX_LEFT_PADDING = 5; const int BOX_TOP_PADDING = 10; const int BOX_WIDTH = 266; @@ -1010,9 +1007,9 @@ void Audio::renderToolBox(int x, int y, bool boxed) { glBindTexture(GL_TEXTURE_2D, _boxTextureId); if (isClipping) { - glColor3f(1.f,0.f,0.f); + glColor3f(1.0f, 0.0f, 0.0f); } else { - glColor3f(.41f,.41f,.41f); + glColor3f(0.41f, 0.41f, 0.41f); } glBegin(GL_QUADS); @@ -1089,10 +1086,8 @@ void Audio::addBufferToScope( // Short int pointer to mapped samples in byte array int16_t* destination = (int16_t*) byteArray.data(); - for (int i = 0; i < NETWORK_SAMPLES_PER_FRAME; i++) { - + for (unsigned int i = 0; i < NETWORK_SAMPLES_PER_FRAME; i++) { sample = (float)source[i * sourceNumberOfChannels + sourceChannel]; - if (sample > 0) { value = (int16_t)(multiplier * logf(sample)); } else if (sample < 0) { @@ -1100,7 +1095,6 @@ void Audio::addBufferToScope( } else { value = 0; } - destination[i + frameOffset] = value; } } @@ -1271,13 +1265,13 @@ bool Audio::switchOutputToAudioDevice(const QAudioDeviceInfo& outputDeviceInfo) // setup a procedural audio output device _proceduralAudioOutput = new QAudioOutput(outputDeviceInfo, _outputFormat, this); - gettimeofday(&_lastReceiveTime, NULL); + _timeSinceLastRecieved.start(); // setup spatial audio ringbuffer int numFrameSamples = _outputFormat.sampleRate() * _desiredOutputFormat.channelCount(); _spatialAudioRingBuffer.resizeForFrameSize(numFrameSamples); _spatialAudioStart = _spatialAudioFinish = 0; - + supportedFormat = true; } } diff --git a/interface/src/Audio.h b/interface/src/Audio.h index ebd7f8612a..e1b8a7dddc 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -12,10 +12,6 @@ #ifndef hifi_Audio_h #define hifi_Audio_h -#ifdef _WIN32 -#include -#endif - #include #include @@ -23,6 +19,7 @@ #include #include +#include #include #include #include @@ -132,7 +129,7 @@ private: QString _outputAudioDeviceName; StDev _stdev; - timeval _lastReceiveTime; + QElapsedTimer _timeSinceLastRecieved; float _averagedLatency; float _measuredJitter; int16_t _jitterBufferSamples; diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 84b17fddca..a7012d838d 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -335,6 +335,8 @@ Menu::Menu() : addCheckableActionToQMenuAndActionHash(handOptionsMenu, MenuOption::DisplayHandTargets, 0, false); addCheckableActionToQMenuAndActionHash(handOptionsMenu, MenuOption::PlaySlaps, 0, false); addCheckableActionToQMenuAndActionHash(handOptionsMenu, MenuOption::HandsCollideWithSelf, 0, false); + addCheckableActionToQMenuAndActionHash(handOptionsMenu, MenuOption::ShowIKConstraints, 0, false); + addCheckableActionToQMenuAndActionHash(handOptionsMenu, MenuOption::AlignForearmsWithWrists, 0, true); addDisabledActionAndSeparator(developerMenu, "Testing"); diff --git a/interface/src/Menu.h b/interface/src/Menu.h index a1e6cded2a..09b5fabfc8 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -256,6 +256,7 @@ private: namespace MenuOption { const QString AboutApp = "About Interface"; + const QString AlignForearmsWithWrists = "Align Forearms with Wrists"; const QString AmbientOcclusion = "Ambient Occlusion"; const QString Atmosphere = "Atmosphere"; const QString AudioNoiseReduction = "Audio Noise Reduction"; @@ -354,6 +355,7 @@ namespace MenuOption { const QString SettingsImport = "Import Settings"; const QString Shadows = "Shadows"; const QString ShowCulledSharedFaces = "Show Culled Shared Voxel Faces"; + const QString ShowIKConstraints = "Show IK Constraints"; const QString Stars = "Stars"; const QString Stats = "Stats"; const QString StopAllScripts = "Stop All Scripts"; diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index febcb2f36e..79a2e31d80 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -172,14 +172,6 @@ void renderWorldBox() { } -double diffclock(timeval *clock1,timeval *clock2) -{ - double diffms = (clock2->tv_sec - clock1->tv_sec) * 1000.0; - diffms += (clock2->tv_usec - clock1->tv_usec) / 1000.0; // us to ms - - return diffms; -} - // Return a random vector of average length 1 const glm::vec3 randVector() { return glm::vec3(randFloat() - 0.5f, randFloat() - 0.5f, randFloat() - 0.5f) * 2.f; @@ -411,69 +403,63 @@ void runTimingTests() { int iResults[numTests]; float fTest = 1.0; float fResults[numTests]; - timeval startTime, endTime; - float elapsedMsecs; - gettimeofday(&startTime, NULL); - for (int i = 1; i < numTests; i++) { - gettimeofday(&endTime, NULL); - } - elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("gettimeofday() usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); + QElapsedTimer startTime; + startTime.start(); + float elapsedUsecs; + + float NSEC_TO_USEC = 1.0f / 1000.0f; + elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; + qDebug("QElapsedTimer::nsecElapsed() usecs: %f", elapsedUsecs / (float) numTests); // Random number generation - gettimeofday(&startTime, NULL); + startTime.start(); for (int i = 1; i < numTests; i++) { iResults[i] = rand(); } - gettimeofday(&endTime, NULL); - elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("rand() stored in array usecs: %f, first result:%d", 1000.0f * elapsedMsecs / (float) numTests, iResults[0]); + elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; + qDebug("rand() stored in array usecs: %f, first result:%d", elapsedUsecs / (float) numTests, iResults[0]); // Random number generation using randFloat() - gettimeofday(&startTime, NULL); + startTime.start(); for (int i = 1; i < numTests; i++) { fResults[i] = randFloat(); } - gettimeofday(&endTime, NULL); - elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("randFloat() stored in array usecs: %f, first result: %f", 1000.0f * elapsedMsecs / (float) numTests, fResults[0]); + elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; + qDebug("randFloat() stored in array usecs: %f, first result: %f", elapsedUsecs / (float) numTests, fResults[0]); // PowF function fTest = 1145323.2342f; - gettimeofday(&startTime, NULL); + startTime.start(); for (int i = 1; i < numTests; i++) { fTest = powf(fTest, 0.5f); } - gettimeofday(&endTime, NULL); - elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("powf(f, 0.5) usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); + elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; + qDebug("powf(f, 0.5) usecs: %f", elapsedUsecs / (float) numTests); // Vector Math float distance; glm::vec3 pointA(randVector()), pointB(randVector()); - gettimeofday(&startTime, NULL); + startTime.start(); for (int i = 1; i < numTests; i++) { //glm::vec3 temp = pointA - pointB; //float distanceSquared = glm::dot(temp, temp); distance = glm::distance(pointA, pointB); } - gettimeofday(&endTime, NULL); - elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("vector math usecs: %f [%f msecs total for %d tests], last result:%f", - 1000.0f * elapsedMsecs / (float) numTests, elapsedMsecs, numTests, distance); + elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; + qDebug("vector math usecs: %f [%f usecs total for %d tests], last result:%f", + elapsedUsecs / (float) numTests, elapsedUsecs, numTests, distance); // Vec3 test glm::vec3 vecA(randVector()), vecB(randVector()); float result; - - gettimeofday(&startTime, NULL); + + startTime.start(); for (int i = 1; i < numTests; i++) { glm::vec3 temp = vecA-vecB; result = glm::dot(temp,temp); } - gettimeofday(&endTime, NULL); - elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("vec3 assign and dot() usecs: %f, last result:%f", 1000.0f * elapsedMsecs / (float) numTests, result); + elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; + qDebug("vec3 assign and dot() usecs: %f, last result:%f", elapsedUsecs / (float) numTests, result); } float loadSetting(QSettings* settings, const char* name, float defaultValue) { diff --git a/interface/src/Util.h b/interface/src/Util.h index 4bd1ed604c..02cfd99f9a 100644 --- a/interface/src/Util.h +++ b/interface/src/Util.h @@ -12,12 +12,6 @@ #ifndef hifi_Util_h #define hifi_Util_h -#ifdef _WIN32 -#include "Systime.h" -#else -#include -#endif - #include #include #include @@ -44,8 +38,6 @@ void drawVector(glm::vec3* vector); void printVector(glm::vec3 vec); -double diffclock(timeval *clock1,timeval *clock2); - void renderCollisionOverlay(int width, int height, float magnitude, float red = 0, float blue = 0, float green = 0); void renderOrientationDirections( glm::vec3 position, const glm::quat& orientation, float size ); diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 317f408aa7..fb547da13e 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -335,15 +335,17 @@ void MyAvatar::simulate(float deltaTime) { radius = myCamera->getAspectRatio() * (myCamera->getNearClip() / cos(myCamera->getFieldOfView() / 2.0f)); radius *= COLLISION_RADIUS_SCALAR; } - - if (_collisionFlags & COLLISION_GROUP_ENVIRONMENT) { - updateCollisionWithEnvironment(deltaTime, radius); - } - if (_collisionFlags & COLLISION_GROUP_VOXELS) { - updateCollisionWithVoxels(deltaTime, radius); - } - if (_collisionFlags & COLLISION_GROUP_AVATARS) { - updateCollisionWithAvatars(deltaTime); + if (_collisionFlags) { + updateShapePositions(); + if (_collisionFlags & COLLISION_GROUP_ENVIRONMENT) { + updateCollisionWithEnvironment(deltaTime, radius); + } + if (_collisionFlags & COLLISION_GROUP_VOXELS) { + updateCollisionWithVoxels(deltaTime, radius); + } + if (_collisionFlags & COLLISION_GROUP_AVATARS) { + updateCollisionWithAvatars(deltaTime); + } } } @@ -460,6 +462,9 @@ void MyAvatar::render(const glm::vec3& cameraPosition, RenderMode renderMode) { return; // exit early } Avatar::render(cameraPosition, renderMode); + if (Menu::getInstance()->isOptionChecked(MenuOption::ShowIKConstraints)) { + _skeletonModel.renderIKConstraints(); + } } void MyAvatar::renderHeadMouse() const { @@ -795,19 +800,21 @@ void MyAvatar::updateCollisionWithEnvironment(float deltaTime, float radius) { } } +static CollisionList myCollisions(64); + void MyAvatar::updateCollisionWithVoxels(float deltaTime, float radius) { - const float VOXEL_ELASTICITY = 0.4f; - const float VOXEL_DAMPING = 0.0f; - const float VOXEL_COLLISION_FREQUENCY = 0.5f; - glm::vec3 penetration; - float pelvisFloatingHeight = getPelvisFloatingHeight(); - if (Application::getInstance()->getVoxelTree()->findCapsulePenetration( - _position - glm::vec3(0.0f, pelvisFloatingHeight - radius, 0.0f), - _position + glm::vec3(0.0f, getSkeletonHeight() - pelvisFloatingHeight + radius, 0.0f), radius, penetration)) { - _lastCollisionPosition = _position; - updateCollisionSound(penetration, deltaTime, VOXEL_COLLISION_FREQUENCY); - applyHardCollision(penetration, VOXEL_ELASTICITY, VOXEL_DAMPING); - } + myCollisions.clear(); + const CapsuleShape& boundingShape = _skeletonModel.getBoundingShape(); + if (Application::getInstance()->getVoxelTree()->findShapeCollisions(&boundingShape, myCollisions)) { + const float VOXEL_ELASTICITY = 0.4f; + const float VOXEL_DAMPING = 0.0f; + for (int i = 0; i < myCollisions.size(); ++i) { + CollisionInfo* collision = myCollisions[i]; + applyHardCollision(collision->_penetration, VOXEL_ELASTICITY, VOXEL_DAMPING); + } + const float VOXEL_COLLISION_FREQUENCY = 0.5f; + updateCollisionSound(myCollisions[0]->_penetration, deltaTime, VOXEL_COLLISION_FREQUENCY); + } } void MyAvatar::applyHardCollision(const glm::vec3& penetration, float elasticity, float damping) { @@ -912,7 +919,6 @@ void MyAvatar::updateCollisionWithAvatars(float deltaTime) { // no need to compute a bunch of stuff if we have one or fewer avatars return; } - updateShapePositions(); float myBoundingRadius = getBoundingRadius(); const float BODY_COLLISION_RESOLUTION_FACTOR = glm::max(1.0f, deltaTime / BODY_COLLISION_RESOLUTION_TIMESCALE); diff --git a/interface/src/avatar/SkeletonModel.cpp b/interface/src/avatar/SkeletonModel.cpp index b9ac280711..f8ebba676f 100644 --- a/interface/src/avatar/SkeletonModel.cpp +++ b/interface/src/avatar/SkeletonModel.cpp @@ -103,6 +103,11 @@ void SkeletonModel::getBodyShapes(QVector& shapes) const { shapes.push_back(&_boundingShape); } +void SkeletonModel::renderIKConstraints() { + renderJointConstraints(getRightHandJointIndex()); + renderJointConstraints(getLeftHandJointIndex()); +} + class IndexValue { public: int index; @@ -133,7 +138,7 @@ void SkeletonModel::applyHandPosition(int jointIndex, const glm::vec3& position) // align hand with forearm float sign = (jointIndex == geometry.rightHandJointIndex) ? 1.0f : -1.0f; - applyRotationDelta(jointIndex, rotationBetween(handRotation * glm::vec3(-sign, 0.0f, 0.0f), forearmVector), false); + applyRotationDelta(jointIndex, rotationBetween(handRotation * glm::vec3(-sign, 0.0f, 0.0f), forearmVector)); } void SkeletonModel::applyPalmData(int jointIndex, const QVector& fingerJointIndices, @@ -148,12 +153,15 @@ void SkeletonModel::applyPalmData(int jointIndex, const QVector& fingerJoin return; } - // rotate forearm to align with palm direction + // rotate palm to align with palm direction glm::quat palmRotation; - getJointRotation(parentJointIndex, palmRotation, true); - applyRotationDelta(parentJointIndex, rotationBetween(palmRotation * geometry.palmDirection, palm.getNormal()), false); - getJointRotation(parentJointIndex, palmRotation, true); - + if (Menu::getInstance()->isOptionChecked(MenuOption::AlignForearmsWithWrists)) { + getJointRotation(parentJointIndex, palmRotation, true); + } else { + getJointRotation(jointIndex, palmRotation, true); + } + palmRotation = rotationBetween(palmRotation * geometry.palmDirection, palm.getNormal()) * palmRotation; + // sort the finger indices by raw x, get the average direction QVector fingerIndices; glm::vec3 direction; @@ -173,17 +181,20 @@ void SkeletonModel::applyPalmData(int jointIndex, const QVector& fingerJoin float directionLength = glm::length(direction); const unsigned int MIN_ROTATION_FINGERS = 3; if (directionLength > EPSILON && palm.getNumFingers() >= MIN_ROTATION_FINGERS) { - applyRotationDelta(parentJointIndex, rotationBetween(palmRotation * glm::vec3(-sign, 0.0f, 0.0f), direction), false); - getJointRotation(parentJointIndex, palmRotation, true); + palmRotation = rotationBetween(palmRotation * glm::vec3(-sign, 0.0f, 0.0f), direction) * palmRotation; } - // let wrist inherit forearm rotation - _jointStates[jointIndex].rotation = glm::quat(); - - // set elbow position from wrist position - glm::vec3 forearmVector = palmRotation * glm::vec3(sign, 0.0f, 0.0f); - setJointPosition(parentJointIndex, palm.getPosition() + forearmVector * - geometry.joints.at(jointIndex).distanceToParent * extractUniformScale(_scale)); + // set hand position, rotation + if (Menu::getInstance()->isOptionChecked(MenuOption::AlignForearmsWithWrists)) { + glm::vec3 forearmVector = palmRotation * glm::vec3(sign, 0.0f, 0.0f); + setJointPosition(parentJointIndex, palm.getPosition() + forearmVector * + geometry.joints.at(jointIndex).distanceToParent * extractUniformScale(_scale)); + setJointRotation(parentJointIndex, palmRotation, true); + _jointStates[jointIndex].rotation = glm::quat(); + + } else { + setJointPosition(jointIndex, palm.getPosition(), palmRotation, true); + } } void SkeletonModel::updateJointState(int index) { @@ -210,3 +221,59 @@ void SkeletonModel::maybeUpdateLeanRotation(const JointState& parentState, const glm::normalize(inverse * axes[0])) * joint.rotation; } +void SkeletonModel::renderJointConstraints(int jointIndex) { + if (jointIndex == -1) { + return; + } + const FBXGeometry& geometry = _geometry->getFBXGeometry(); + const float BASE_DIRECTION_SIZE = 300.0f; + float directionSize = BASE_DIRECTION_SIZE * extractUniformScale(_scale); + glLineWidth(3.0f); + do { + const FBXJoint& joint = geometry.joints.at(jointIndex); + const JointState& jointState = _jointStates.at(jointIndex); + glm::vec3 position = extractTranslation(jointState.transform) + _translation; + + glPushMatrix(); + glTranslatef(position.x, position.y, position.z); + glm::quat parentRotation = (joint.parentIndex == -1) ? _rotation : _jointStates.at(joint.parentIndex).combinedRotation; + glm::vec3 rotationAxis = glm::axis(parentRotation); + glRotatef(glm::degrees(glm::angle(parentRotation)), rotationAxis.x, rotationAxis.y, rotationAxis.z); + float fanScale = directionSize * 0.75f; + glScalef(fanScale, fanScale, fanScale); + const int AXIS_COUNT = 3; + for (int i = 0; i < AXIS_COUNT; i++) { + if (joint.rotationMin[i] <= -PI + EPSILON && joint.rotationMax[i] >= PI - EPSILON) { + continue; // unconstrained + } + glm::vec3 axis; + axis[i] = 1.0f; + + glm::vec3 otherAxis; + if (i == 0) { + otherAxis.y = 1.0f; + } else { + otherAxis.x = 1.0f; + } + glColor4f(otherAxis.r, otherAxis.g, otherAxis.b, 0.75f); + + glBegin(GL_TRIANGLE_FAN); + glVertex3f(0.0f, 0.0f, 0.0f); + const int FAN_SEGMENTS = 16; + for (int j = 0; j < FAN_SEGMENTS; j++) { + glm::vec3 rotated = glm::angleAxis(glm::mix(joint.rotationMin[i], joint.rotationMax[i], + (float)j / (FAN_SEGMENTS - 1)), axis) * otherAxis; + glVertex3f(rotated.x, rotated.y, rotated.z); + } + glEnd(); + } + glPopMatrix(); + + renderOrientationDirections(position, jointState.combinedRotation, directionSize); + jointIndex = joint.parentIndex; + + } while (jointIndex != -1 && geometry.joints.at(jointIndex).isFree); + + glLineWidth(1.0f); +} + diff --git a/interface/src/avatar/SkeletonModel.h b/interface/src/avatar/SkeletonModel.h index 2020ccf3b2..0a87fcf89d 100644 --- a/interface/src/avatar/SkeletonModel.h +++ b/interface/src/avatar/SkeletonModel.h @@ -33,6 +33,8 @@ public: /// \param shapes[out] list of shapes for body collisions void getBodyShapes(QVector& shapes) const; + void renderIKConstraints(); + protected: void applyHandPosition(int jointIndex, const glm::vec3& position); @@ -46,6 +48,8 @@ protected: virtual void maybeUpdateLeanRotation(const JointState& parentState, const FBXJoint& joint, JointState& state); private: + + void renderJointConstraints(int jointIndex); Avatar* _owningAvatar; }; diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index d3da8fe7c3..854b19236d 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -11,10 +11,6 @@ #include "InterfaceConfig.h" -#ifdef WIN32 -#include -#endif - #include #include diff --git a/interface/src/devices/TV3DManager.cpp b/interface/src/devices/TV3DManager.cpp index fcbef0385c..b5cc28b07f 100644 --- a/interface/src/devices/TV3DManager.cpp +++ b/interface/src/devices/TV3DManager.cpp @@ -15,11 +15,6 @@ #include - -#ifdef WIN32 -#include -#endif - #include "Application.h" #include "TV3DManager.h" diff --git a/interface/src/main.cpp b/interface/src/main.cpp index 40e2a9ab27..6f9dc5e3bd 100644 --- a/interface/src/main.cpp +++ b/interface/src/main.cpp @@ -16,8 +16,9 @@ #include int main(int argc, const char * argv[]) { - timeval startup_time; - gettimeofday(&startup_time, NULL); + initialiseUsecTimestampNow(); + QElapsedTimer startupTime; + startupTime.start(); // Debug option to demonstrate that the client's local time does not // need to be in sync with any other network node. This forces clock @@ -33,7 +34,7 @@ int main(int argc, const char * argv[]) { int exitCode; { QSettings::setDefaultFormat(QSettings::IniFormat); - Application app(argc, const_cast(argv), startup_time); + Application app(argc, const_cast(argv), startupTime); QTranslator translator; translator.load("interface_en"); diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index ef0911f673..3484ac5fc8 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -882,12 +882,12 @@ bool Model::getJointRotation(int jointIndex, glm::quat& rotation, bool fromBind) return true; } -bool Model::setJointPosition(int jointIndex, const glm::vec3& position, int lastFreeIndex, - bool allIntermediatesFree, const glm::vec3& alignment) { +bool Model::setJointPosition(int jointIndex, const glm::vec3& translation, const glm::quat& rotation, bool useRotation, + int lastFreeIndex, bool allIntermediatesFree, const glm::vec3& alignment) { if (jointIndex == -1 || _jointStates.isEmpty()) { return false; } - glm::vec3 relativePosition = position - _translation; + glm::vec3 relativePosition = translation - _translation; const FBXGeometry& geometry = _geometry->getFBXGeometry(); const QVector& freeLineage = geometry.joints.at(jointIndex).freeLineage; if (freeLineage.isEmpty()) { @@ -896,13 +896,21 @@ bool Model::setJointPosition(int jointIndex, const glm::vec3& position, int last if (lastFreeIndex == -1) { lastFreeIndex = freeLineage.last(); } - + // this is a cyclic coordinate descent algorithm: see // http://www.ryanjuckett.com/programming/animation/21-cyclic-coordinate-descent-in-2d const int ITERATION_COUNT = 1; glm::vec3 worldAlignment = _rotation * alignment; for (int i = 0; i < ITERATION_COUNT; i++) { - // first, we go from the joint upwards, rotating the end as close as possible to the target + // first, try to rotate the end effector as close as possible to the target rotation, if any + glm::quat endRotation; + if (useRotation) { + getJointRotation(jointIndex, endRotation, true); + applyRotationDelta(jointIndex, rotation * glm::inverse(endRotation)); + getJointRotation(jointIndex, endRotation, true); + } + + // then, we go from the joint upwards, rotating the end as close as possible to the target glm::vec3 endPosition = extractTranslation(_jointStates[jointIndex].transform); for (int j = 1; freeLineage.at(j - 1) != lastFreeIndex; j++) { int index = freeLineage.at(j); @@ -914,8 +922,17 @@ bool Model::setJointPosition(int jointIndex, const glm::vec3& position, int last glm::vec3 jointPosition = extractTranslation(state.transform); glm::vec3 jointVector = endPosition - jointPosition; glm::quat oldCombinedRotation = state.combinedRotation; - applyRotationDelta(index, rotationBetween(jointVector, relativePosition - jointPosition)); - endPosition = state.combinedRotation * glm::inverse(oldCombinedRotation) * jointVector + jointPosition; + glm::quat combinedDelta; + float combinedWeight; + if (useRotation) { + combinedDelta = safeMix(rotation * glm::inverse(endRotation), + rotationBetween(jointVector, relativePosition - jointPosition), 0.5f); + combinedWeight = 2.0f; + + } else { + combinedDelta = rotationBetween(jointVector, relativePosition - jointPosition); + combinedWeight = 1.0f; + } if (alignment != glm::vec3() && j > 1) { jointVector = endPosition - jointPosition; glm::vec3 positionSum; @@ -929,9 +946,16 @@ bool Model::setJointPosition(int jointIndex, const glm::vec3& position, int last glm::vec3 projectedAlignment = glm::cross(jointVector, glm::cross(worldAlignment, jointVector)); const float LENGTH_EPSILON = 0.001f; if (glm::length(projectedCenterOfMass) > LENGTH_EPSILON && glm::length(projectedAlignment) > LENGTH_EPSILON) { - applyRotationDelta(index, rotationBetween(projectedCenterOfMass, projectedAlignment)); + combinedDelta = safeMix(combinedDelta, rotationBetween(projectedCenterOfMass, projectedAlignment), + 1.0f / (combinedWeight + 1.0f)); } } + applyRotationDelta(index, combinedDelta); + glm::quat actualDelta = state.combinedRotation * glm::inverse(oldCombinedRotation); + endPosition = actualDelta * jointVector + jointPosition; + if (useRotation) { + endRotation = actualDelta * endRotation; + } } } @@ -1012,8 +1036,9 @@ void Model::applyRotationDelta(int jointIndex, const glm::quat& delta, bool cons state.combinedRotation = delta * state.combinedRotation; return; } - glm::quat newRotation = glm::quat(glm::clamp(safeEulerAngles(state.rotation * - glm::inverse(state.combinedRotation) * delta * state.combinedRotation), joint.rotationMin, joint.rotationMax)); + glm::quat targetRotation = delta * state.combinedRotation; + glm::vec3 eulers = safeEulerAngles(state.rotation * glm::inverse(state.combinedRotation) * targetRotation); + glm::quat newRotation = glm::quat(glm::clamp(eulers, joint.rotationMin, joint.rotationMax)); state.combinedRotation = state.combinedRotation * glm::inverse(state.rotation) * newRotation; state.rotation = newRotation; } @@ -1141,7 +1166,7 @@ void Model::applyCollision(CollisionInfo& collision) { getJointPosition(jointIndex, end); glm::vec3 newEnd = start + glm::angleAxis(angle, axis) * (end - start); // try to move it - setJointPosition(jointIndex, newEnd, -1, true); + setJointPosition(jointIndex, newEnd, glm::quat(), false, -1, true); } } } diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 65b79fffdd..64295cb915 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -193,6 +193,8 @@ public: /// Sets blended vertices computed in a separate thread. void setBlendedVertices(const QVector& vertices, const QVector& normals); + const CapsuleShape& getBoundingShape() const { return _boundingShape; } + protected: QSharedPointer _geometry; @@ -240,8 +242,9 @@ protected: bool getJointPosition(int jointIndex, glm::vec3& position) const; bool getJointRotation(int jointIndex, glm::quat& rotation, bool fromBind = false) const; - bool setJointPosition(int jointIndex, const glm::vec3& position, int lastFreeIndex = -1, - bool allIntermediatesFree = false, const glm::vec3& alignment = glm::vec3(0.0f, -1.0f, 0.0f)); + bool setJointPosition(int jointIndex, const glm::vec3& translation, const glm::quat& rotation = glm::quat(), + bool useRotation = false, int lastFreeIndex = -1, bool allIntermediatesFree = false, + const glm::vec3& alignment = glm::vec3(0.0f, -1.0f, 0.0f)); bool setJointRotation(int jointIndex, const glm::quat& rotation, bool fromBind = false); void setJointTranslation(int jointIndex, const glm::vec3& translation); diff --git a/interface/src/starfield/Controller.cpp b/interface/src/starfield/Controller.cpp index 771029c689..2279a68422 100755 --- a/interface/src/starfield/Controller.cpp +++ b/interface/src/starfield/Controller.cpp @@ -9,24 +9,23 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifdef _WIN32 -#include -#endif +#include #include "starfield/Controller.h" using namespace starfield; bool Controller::computeStars(unsigned numStars, unsigned seed) { - timeval startTime; - gettimeofday(&startTime, NULL); + QElapsedTimer startTime; + startTime.start(); Generator::computeStarPositions(_inputSequence, numStars, seed); this->retile(numStars, _tileResolution); - qDebug() << "Total time to retile and generate stars: " - << ((usecTimestampNow() - usecTimestamp(&startTime)) / 1000) << "msec"; + double NSEC_TO_MSEC = 1.0 / 1000000.0; + double timeDiff = (double)startTime.nsecsElapsed() * NSEC_TO_MSEC; + qDebug() << "Total time to retile and generate stars: " << timeDiff << "msec"; return true; } diff --git a/interface/src/starfield/Generator.cpp b/interface/src/starfield/Generator.cpp index b18e1834be..d9773e4452 100644 --- a/interface/src/starfield/Generator.cpp +++ b/interface/src/starfield/Generator.cpp @@ -9,9 +9,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifdef _WIN32 -#include -#endif +#include #include "starfield/Generator.h" @@ -24,8 +22,8 @@ void Generator::computeStarPositions(InputVertices& destination, unsigned limit, InputVertices* vertices = & destination; //_limit = limit; - timeval startTime; - gettimeofday(&startTime, NULL); + QElapsedTimer startTime; + startTime.start(); srand(seed); @@ -70,7 +68,8 @@ void Generator::computeStarPositions(InputVertices& destination, unsigned limit, vertices->push_back(InputVertex(azimuth, altitude, computeStarColor(STAR_COLORIZATION))); } - qDebug() << "Total time to generate stars: " << ((usecTimestampNow() - usecTimestamp(&startTime)) / 1000) << " msec"; + double timeDiff = (double)startTime.nsecsElapsed() / 1000000.0; // ns to ms + qDebug() << "Total time to generate stars: " << timeDiff << " msec"; } // computeStarColor diff --git a/interface/src/ui/BandwidthMeter.cpp b/interface/src/ui/BandwidthMeter.cpp index 3ed66c53e1..0f41a1a5cf 100644 --- a/interface/src/ui/BandwidthMeter.cpp +++ b/interface/src/ui/BandwidthMeter.cpp @@ -62,26 +62,21 @@ BandwidthMeter::~BandwidthMeter() { free(_channels); } -BandwidthMeter::Stream::Stream(float msToAverage) : - _value(0.0f), - _msToAverage(msToAverage) { - - gettimeofday(& _prevTime, NULL); +BandwidthMeter::Stream::Stream(float msToAverage) : _value(0.0f), _msToAverage(msToAverage) { + _prevTime.start(); } void BandwidthMeter::Stream::updateValue(double amount) { // Determine elapsed time - timeval now; - gettimeofday(& now, NULL); - double dt = diffclock(& _prevTime, & now); + double dt = (double)_prevTime.nsecsElapsed() / 1000000.0; // ns to ms // Ignore this value when timer imprecision yields dt = 0 if (dt == 0.0) { return; } - memcpy(& _prevTime, & now, sizeof(timeval)); + _prevTime.start(); // Compute approximate average _value = glm::mix(_value, amount / dt, diff --git a/interface/src/ui/BandwidthMeter.h b/interface/src/ui/BandwidthMeter.h index 6838f28c70..c6a28a21c3 100644 --- a/interface/src/ui/BandwidthMeter.h +++ b/interface/src/ui/BandwidthMeter.h @@ -12,9 +12,7 @@ #ifndef hifi_BandwidthMeter_h #define hifi_BandwidthMeter_h -#ifdef _WIN32 -#include -#endif +#include #include @@ -59,7 +57,7 @@ public: private: double _value; // Current value. double _msToAverage; // Milliseconds to average. - timeval _prevTime; // Time of last feed. + QElapsedTimer _prevTime; // Time of last feed. }; // Data model accessors diff --git a/interface/src/ui/ScriptEditorWidget.cpp b/interface/src/ui/ScriptEditorWidget.cpp index 1765a5ea1a..3f9b0137ef 100644 --- a/interface/src/ui/ScriptEditorWidget.cpp +++ b/interface/src/ui/ScriptEditorWidget.cpp @@ -39,7 +39,8 @@ ScriptEditorWidget::ScriptEditorWidget() : setTitleBarWidget(new QWidget()); QFontMetrics fm(_scriptEditorWidgetUI->scriptEdit->font()); _scriptEditorWidgetUI->scriptEdit->setTabStopWidth(fm.width('0') * 4); - ScriptHighlighting* highlighting = new ScriptHighlighting(_scriptEditorWidgetUI->scriptEdit->document()); + // We create a new ScriptHighligting QObject and provide it with a parent so this is NOT a memory leak. + new ScriptHighlighting(_scriptEditorWidgetUI->scriptEdit->document()); QTimer::singleShot(0, _scriptEditorWidgetUI->scriptEdit, SLOT(setFocus())); } diff --git a/libraries/audio/src/AudioInjector.cpp b/libraries/audio/src/AudioInjector.cpp index 6370e51826..eed41ac849 100644 --- a/libraries/audio/src/AudioInjector.cpp +++ b/libraries/audio/src/AudioInjector.cpp @@ -71,8 +71,8 @@ void AudioInjector::injectAudio() { quint8 volume = MAX_INJECTOR_VOLUME * _options.getVolume(); packetStream << volume; - timeval startTime = {}; - gettimeofday(&startTime, NULL); + QElapsedTimer timer; + timer.start(); int nextFrame = 0; int currentSendPosition = 0; @@ -104,7 +104,7 @@ void AudioInjector::injectAudio() { if (currentSendPosition != bytesToCopy && currentSendPosition < soundByteArray.size()) { // not the first packet and not done // sleep for the appropriate time - int usecToSleep = usecTimestamp(&startTime) + (++nextFrame * BUFFER_SEND_INTERVAL_USECS) - usecTimestampNow(); + int usecToSleep = (++nextFrame * BUFFER_SEND_INTERVAL_USECS) - timer.nsecsElapsed() / 1000; if (usecToSleep > 0) { usleep(usecToSleep); diff --git a/libraries/networking/src/Assignment.h b/libraries/networking/src/Assignment.h index 041121f760..f0f7e8db1a 100644 --- a/libraries/networking/src/Assignment.h +++ b/libraries/networking/src/Assignment.h @@ -12,12 +12,6 @@ #ifndef hifi_Assignment_h #define hifi_Assignment_h -#ifdef _WIN32 -#include "Systime.h" -#else -#include -#endif - #include #include "NodeList.h" diff --git a/libraries/octree/src/Octree.cpp b/libraries/octree/src/Octree.cpp index d7fc7713cf..ebfb954bd8 100644 --- a/libraries/octree/src/Octree.cpp +++ b/libraries/octree/src/Octree.cpp @@ -20,18 +20,20 @@ #include -#include "CoverageMap.h" #include -#include "OctalCode.h" +#include #include #include +#include +#include //#include "Tags.h" -#include "ViewFrustum.h" +#include "CoverageMap.h" #include "OctreeConstants.h" #include "OctreeElementBag.h" #include "Octree.h" +#include "ViewFrustum.h" float boundaryDistanceForRenderLevel(unsigned int renderLevel, float voxelSizeScale) { return voxelSizeScale / powf(2, renderLevel); @@ -676,6 +678,13 @@ public: bool found; }; +class ShapeArgs { +public: + const Shape* shape; + CollisionList& collisions; + bool found; +}; + bool findCapsulePenetrationOp(OctreeElement* node, void* extraData) { CapsuleArgs* args = static_cast(extraData); @@ -697,6 +706,27 @@ bool findCapsulePenetrationOp(OctreeElement* node, void* extraData) { return false; } +bool findShapeCollisionsOp(OctreeElement* node, void* extraData) { + ShapeArgs* args = static_cast(extraData); + + // coarse check against bounds + AABox cube = node->getAABox(); + cube.scale(TREE_SCALE); + if (!cube.expandedContains(args->shape->getPosition(), args->shape->getBoundingRadius())) { + return false; + } + if (!node->isLeaf()) { + return true; // recurse on children + } + if (node->hasContent()) { + if (ShapeCollider::collideShapeWithAACube(args->shape, cube.calcCenter(), cube.getScale(), args->collisions)) { + args->found = true; + return true; + } + } + return false; +} + bool Octree::findCapsulePenetration(const glm::vec3& start, const glm::vec3& end, float radius, glm::vec3& penetration, Octree::lockType lockType) { @@ -727,6 +757,29 @@ bool Octree::findCapsulePenetration(const glm::vec3& start, const glm::vec3& end return args.found; } +bool Octree::findShapeCollisions(const Shape* shape, CollisionList& collisions, Octree::lockType lockType) { + + ShapeArgs args = { shape, collisions, false }; + + bool gotLock = false; + if (lockType == Octree::Lock) { + lockForRead(); + gotLock = true; + } else if (lockType == Octree::TryLock) { + gotLock = tryLockForRead(); + if (!gotLock) { + return args.found; // if we wanted to tryLock, and we couldn't then just bail... + } + } + + recurseTreeWithOperation(findShapeCollisionsOp, &args); + + if (gotLock) { + unlock(); + } + return args.found; +} + class GetElementEnclosingArgs { public: OctreeElement* element; diff --git a/libraries/octree/src/Octree.h b/libraries/octree/src/Octree.h index 3c868ab172..0b9f1657ee 100644 --- a/libraries/octree/src/Octree.h +++ b/libraries/octree/src/Octree.h @@ -21,6 +21,7 @@ class Octree; class OctreeElement; class OctreeElementBag; class OctreePacketData; +class Shape; #include "JurisdictionMap.h" @@ -30,6 +31,8 @@ class OctreePacketData; #include "OctreePacketData.h" #include "OctreeSceneStats.h" +#include + #include #include @@ -246,6 +249,8 @@ public: bool findCapsulePenetration(const glm::vec3& start, const glm::vec3& end, float radius, glm::vec3& penetration, Octree::lockType lockType = Octree::TryLock); + bool findShapeCollisions(const Shape* shape, CollisionList& collisions, Octree::lockType = Octree::TryLock); + OctreeElement* getElementEnclosingPoint(const glm::vec3& point, Octree::lockType lockType = Octree::TryLock); // Note: this assumes the fileFormat is the HIO individual voxels code files diff --git a/libraries/octree/src/OctreeElement.cpp b/libraries/octree/src/OctreeElement.cpp index 96311ceabd..846cf564c2 100644 --- a/libraries/octree/src/OctreeElement.cpp +++ b/libraries/octree/src/OctreeElement.cpp @@ -21,10 +21,10 @@ #include "AABox.h" #include "OctalCode.h" -#include "SharedUtil.h" #include "OctreeConstants.h" #include "OctreeElement.h" #include "Octree.h" +#include "SharedUtil.h" quint64 OctreeElement::_voxelMemoryUsage = 0; quint64 OctreeElement::_octcodeMemoryUsage = 0; diff --git a/libraries/octree/src/OctreeElement.h b/libraries/octree/src/OctreeElement.h index 682516cf0a..c5eec1c9e2 100644 --- a/libraries/octree/src/OctreeElement.h +++ b/libraries/octree/src/OctreeElement.h @@ -19,6 +19,7 @@ #include #include + #include "AABox.h" #include "ViewFrustum.h" #include "OctreeConstants.h" diff --git a/libraries/octree/src/ViewFrustum.h b/libraries/octree/src/ViewFrustum.h index 5c9d7f06c2..acd5c639f7 100644 --- a/libraries/octree/src/ViewFrustum.h +++ b/libraries/octree/src/ViewFrustum.h @@ -19,7 +19,6 @@ #include "AABox.h" #include "Plane.h" - #include "OctreeConstants.h" #include "OctreeProjectedPolygon.h" diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index 2e92567fe7..09c3c63ebd 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -286,8 +286,8 @@ void ScriptEngine::run() { emit errorMessage("Uncaught exception at line" + QString::number(line) + ":" + result.toString()); } - timeval startTime; - gettimeofday(&startTime, NULL); + QElapsedTimer startTime; + startTime.start(); int thisFrame = 0; @@ -296,7 +296,7 @@ void ScriptEngine::run() { qint64 lastUpdate = usecTimestampNow(); while (!_isFinished) { - int usecToSleep = usecTimestamp(&startTime) + (thisFrame++ * SCRIPT_DATA_CALLBACK_USECS) - usecTimestampNow(); + int usecToSleep = (thisFrame++ * SCRIPT_DATA_CALLBACK_USECS) - startTime.nsecsElapsed() / 1000; // nsec to usec if (usecToSleep > 0) { usleep(usecToSleep); } @@ -561,4 +561,4 @@ void ScriptEngine::include(const QString& includeFile) { qDebug() << "Uncaught exception at (" << includeFile << ") line" << line << ":" << result.toString(); emit errorMessage("Uncaught exception at (" + includeFile + ") line" + QString::number(line) + ":" + result.toString()); } -} \ No newline at end of file +} diff --git a/libraries/shared/src/CollisionInfo.cpp b/libraries/shared/src/CollisionInfo.cpp index 5a4188a1ef..5d97842530 100644 --- a/libraries/shared/src/CollisionInfo.cpp +++ b/libraries/shared/src/CollisionInfo.cpp @@ -48,3 +48,6 @@ void CollisionList::clear() { _size = 0; } +CollisionInfo* CollisionList::operator[](int index) { + return (index > -1 && index < _size) ? &(_collisions[index]) : NULL; +} diff --git a/libraries/shared/src/CollisionInfo.h b/libraries/shared/src/CollisionInfo.h index f575dd8595..7db965fe64 100644 --- a/libraries/shared/src/CollisionInfo.h +++ b/libraries/shared/src/CollisionInfo.h @@ -95,6 +95,8 @@ public: /// Clear valid collisions. void clear(); + CollisionInfo* operator[](int index); + private: int _maxSize; // the container cannot get larger than this int _size; // the current number of valid collisions in the list diff --git a/libraries/shared/src/PerfStat.h b/libraries/shared/src/PerfStat.h index 478c9afead..22cf14f207 100644 --- a/libraries/shared/src/PerfStat.h +++ b/libraries/shared/src/PerfStat.h @@ -18,12 +18,6 @@ #include #include "SharedUtil.h" -#ifdef _WIN32 -#include "Systime.h" -#else -#include -#endif - #include #include #include diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index c53c7fab7d..31d57f14ad 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -92,6 +92,29 @@ bool collideShapesCoarse(const QVector& shapesA, const QVectorgetType(); + if (typeA == Shape::SPHERE_SHAPE) { + return sphereAACube(static_cast(shapeA), cubeCenter, cubeSide, collisions); + } else if (typeA == Shape::CAPSULE_SHAPE) { + return capsuleAACube(static_cast(shapeA), cubeCenter, cubeSide, collisions); + } else if (typeA == Shape::LIST_SHAPE) { + const ListShape* listA = static_cast(shapeA); + bool touching = false; + for (int i = 0; i < listA->size() && !collisions.isFull(); ++i) { + const Shape* subShape = listA->getSubShape(i); + int subType = subShape->getType(); + if (subType == Shape::SPHERE_SHAPE) { + touching = sphereAACube(static_cast(subShape), cubeCenter, cubeSide, collisions) || touching; + } else if (subType == Shape::CAPSULE_SHAPE) { + touching = capsuleAACube(static_cast(subShape), cubeCenter, cubeSide, collisions) || touching; + } + } + return touching; + } + return false; +} + bool sphereSphere(const SphereShape* sphereA, const SphereShape* sphereB, CollisionList& collisions) { glm::vec3 BA = sphereB->getPosition() - sphereA->getPosition(); float distanceSquared = glm::dot(BA, BA); @@ -567,4 +590,103 @@ bool listList(const ListShape* listA, const ListShape* listB, CollisionList& col return touching; } +// helper function +bool sphereAACube(const glm::vec3& sphereCenter, float sphereRadius, const glm::vec3& cubeCenter, float cubeSide, CollisionList& collisions) { + glm::vec3 BA = cubeCenter - sphereCenter; + float distance = glm::length(BA); + if (distance > EPSILON) { + BA /= distance; // BA is now normalized + // compute the nearest point on sphere + glm::vec3 surfaceA = sphereCenter + sphereRadius * BA; + // compute the nearest point on cube + float maxBA = glm::max(glm::max(fabs(BA.x), fabs(BA.y)), fabs(BA.z)); + glm::vec3 surfaceB = cubeCenter - (0.5f * cubeSide / maxBA) * BA; + // collision happens when "vector to surfaceA from surfaceB" dots with BA to produce a positive value + glm::vec3 surfaceAB = surfaceA - surfaceB; + if (glm::dot(surfaceAB, BA) > 0.f) { + CollisionInfo* collision = collisions.getNewCollision(); + if (collision) { + /* KEEP THIS CODE -- this is how to collide the cube with stark face normals (no rounding). + * We might want to use this code later for sealing boundaries between adjacent voxels. + // penetration is parallel to box side direction + BA /= maxBA; + glm::vec3 direction; + glm::modf(BA, direction); + direction = glm::normalize(direction); + */ + + // For rounded normals at edges and corners: + // At this point imagine that sphereCenter touches a "normalized" cube with rounded edges. + // This cube has a sidelength of 2 and its smoothing radius is sphereRadius/maxBA. + // We're going to try to compute the "negative normal" (and hence direction of penetration) + // of this surface. + + float radius = sphereRadius / (distance * maxBA); // normalized radius + float shortLength = maxBA - radius; + glm::vec3 direction = BA; + if (shortLength > 0.0f) { + direction = glm::abs(BA) - glm::vec3(shortLength); + // Set any negative components to zero, and adopt the sign of the original BA component. + // Unfortunately there isn't an easy way to make this fast. + if (direction.x < 0.0f) { + direction.x = 0.f; + } else if (BA.x < 0.f) { + direction.x = -direction.x; + } + if (direction.y < 0.0f) { + direction.y = 0.f; + } else if (BA.y < 0.f) { + direction.y = -direction.y; + } + if (direction.z < 0.0f) { + direction.z = 0.f; + } else if (BA.z < 0.f) { + direction.z = -direction.z; + } + } + direction = glm::normalize(direction); + + // penetration is the projection of surfaceAB on direction + collision->_penetration = glm::dot(surfaceAB, direction) * direction; + // contactPoint is on surface of A + collision->_contactPoint = sphereCenter - sphereRadius * direction; + return true; + } + } + } else if (sphereRadius + 0.5f * cubeSide > distance) { + // NOTE: for cocentric approximation we collide sphere and cube as two spheres which means + // this algorithm will probably be wrong when both sphere and cube are very small (both ~EPSILON) + CollisionInfo* collision = collisions.getNewCollision(); + if (collision) { + // the penetration and contactPoint are undefined, so we pick a penetration direction (-yAxis) + collision->_penetration = (sphereRadius + 0.5f * cubeSide) * glm::vec3(0.0f, -1.0f, 0.0f); + // contactPoint is on surface of A + collision->_contactPoint = sphereCenter + collision->_penetration; + return true; + } + } + return false; +} + +bool sphereAACube(const SphereShape* sphereA, const glm::vec3& cubeCenter, float cubeSide, CollisionList& collisions) { + return sphereAACube(sphereA->getPosition(), sphereA->getRadius(), cubeCenter, cubeSide, collisions); +} + +bool capsuleAACube(const CapsuleShape* capsuleA, const glm::vec3& cubeCenter, float cubeSide, CollisionList& collisions) { + // find nerest approach of capsule line segment to cube + glm::vec3 capsuleAxis; + capsuleA->computeNormalizedAxis(capsuleAxis); + float offset = glm::dot(cubeCenter - capsuleA->getPosition(), capsuleAxis); + float halfHeight = capsuleA->getHalfHeight(); + if (offset > halfHeight) { + offset = halfHeight; + } else if (offset < -halfHeight) { + offset = -halfHeight; + } + glm::vec3 nearestApproach = capsuleA->getPosition() + offset * capsuleAxis; + // collide nearest approach like a sphere at that point + return sphereAACube(nearestApproach, capsuleA->getRadius(), cubeCenter, cubeSide, collisions); +} + + } // namespace ShapeCollider diff --git a/libraries/shared/src/ShapeCollider.h b/libraries/shared/src/ShapeCollider.h index d554775e7b..9e83e31571 100644 --- a/libraries/shared/src/ShapeCollider.h +++ b/libraries/shared/src/ShapeCollider.h @@ -33,6 +33,13 @@ namespace ShapeCollider { /// \return true if any shapes collide bool collideShapesCoarse(const QVector& shapesA, const QVector& shapesB, CollisionInfo& collision); + /// \param shapeA a pointer to a shape + /// \param cubeCenter center of cube + /// \param cubeSide lenght of side of cube + /// \param collisions[out] average collision details + /// \return true if shapeA collides with axis aligned cube + bool collideShapeWithAACube(const Shape* shapeA, const glm::vec3& cubeCenter, float cubeSide, CollisionList& collisions); + /// \param sphereA pointer to first shape /// \param sphereB pointer to second shape /// \param[out] collisions where to append collision details @@ -129,6 +136,20 @@ namespace ShapeCollider { /// \return true if shapes collide bool listList(const ListShape* listA, const ListShape* listB, CollisionList& collisions); + /// \param sphereA pointer to sphere + /// \param cubeCenter center of cube + /// \param cubeSide lenght of side of cube + /// \param[out] collisions where to append collision details + /// \return true if sphereA collides with axis aligned cube + bool sphereAACube(const SphereShape* sphereA, const glm::vec3& cubeCenter, float cubeSide, CollisionList& collisions); + + /// \param capsuleA pointer to capsule + /// \param cubeCenter center of cube + /// \param cubeSide lenght of side of cube + /// \param[out] collisions where to append collision details + /// \return true if capsuleA collides with axis aligned cube + bool capsuleAACube(const CapsuleShape* capsuleA, const glm::vec3& cubeCenter, float cubeSide, CollisionList& collisions); + } // namespace ShapeCollider #endif // hifi_ShapeCollider_h diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index f4e4b28f93..bbb73cae4c 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -15,28 +15,44 @@ #include #include +#ifdef _WIN32 +#include +#endif + #ifdef __APPLE__ #include #endif #include +#include +#include #include "OctalCode.h" #include "SharedUtil.h" -quint64 usecTimestamp(const timeval *time) { - return (time->tv_sec * 1000000 + time->tv_usec); + +static qint64 TIME_REFERENCE = 0; // in usec +static QElapsedTimer timestampTimer; +static int usecTimestampNowAdjust = 0; // in usec + +void initialiseUsecTimestampNow() { + static bool initialised = false; + if (initialised) { + qDebug() << "[WARNING] Double initialisation of usecTimestampNow()."; + return; + } + + TIME_REFERENCE = QDateTime::currentMSecsSinceEpoch() * 1000; // ms to usec + initialised = true; } -int usecTimestampNowAdjust = 0; void usecTimestampNowForceClockSkew(int clockSkew) { ::usecTimestampNowAdjust = clockSkew; } quint64 usecTimestampNow() { - timeval now; - gettimeofday(&now, NULL); - return (now.tv_sec * 1000000 + now.tv_usec) + ::usecTimestampNowAdjust; + // usec nsec to usec usec + return TIME_REFERENCE + timestampTimer.nsecsElapsed() / 1000 + ::usecTimestampNowAdjust; } float randFloat() { @@ -640,27 +656,59 @@ void debug::checkDeadBeef(void* memoryVoid, int size) { // https://github.com/threerings/clyde/blob/master/src/main/java/com/threerings/math/Quaternion.java) glm::vec3 safeEulerAngles(const glm::quat& q) { float sy = 2.0f * (q.y * q.w - q.x * q.z); + glm::vec3 eulers; if (sy < 1.0f - EPSILON) { if (sy > -1.0f + EPSILON) { - return glm::vec3( + eulers = glm::vec3( atan2f(q.y * q.z + q.x * q.w, 0.5f - (q.x * q.x + q.y * q.y)), asinf(sy), atan2f(q.x * q.y + q.z * q.w, 0.5f - (q.y * q.y + q.z * q.z))); } else { // not a unique solution; x + z = atan2(-m21, m11) - return glm::vec3( + eulers = glm::vec3( 0.0f, - PI_OVER_TWO, atan2f(q.x * q.w - q.y * q.z, 0.5f - (q.x * q.x + q.z * q.z))); } } else { // not a unique solution; x - z = atan2(-m21, m11) - return glm::vec3( + eulers = glm::vec3( 0.0f, PI_OVER_TWO, -atan2f(q.x * q.w - q.y * q.z, 0.5f - (q.x * q.x + q.z * q.z))); } + + // adjust so that z, rather than y, is in [-pi/2, pi/2] + if (eulers.z < -PI_OVER_TWO) { + if (eulers.x < 0.0f) { + eulers.x += PI; + } else { + eulers.x -= PI; + } + eulers.y = -eulers.y; + if (eulers.y < 0.0f) { + eulers.y += PI; + } else { + eulers.y -= PI; + } + eulers.z += PI; + + } else if (eulers.z > PI_OVER_TWO) { + if (eulers.x < 0.0f) { + eulers.x += PI; + } else { + eulers.x -= PI; + } + eulers.y = -eulers.y; + if (eulers.y < 0.0f) { + eulers.y += PI; + } else { + eulers.y -= PI; + } + eulers.z -= PI; + } + return eulers; } // Helper function returns the positive angle (in radians) between two 3D vectors diff --git a/libraries/shared/src/SharedUtil.h b/libraries/shared/src/SharedUtil.h index a8403d617c..54d599070d 100644 --- a/libraries/shared/src/SharedUtil.h +++ b/libraries/shared/src/SharedUtil.h @@ -24,12 +24,6 @@ #include -#ifdef _WIN32 -#include "Systime.h" -#else -#include -#endif - const int BYTES_PER_COLOR = 3; const int BYTES_PER_FLAGS = 1; typedef unsigned char rgbColor[BYTES_PER_COLOR]; @@ -66,7 +60,7 @@ static const quint64 USECS_PER_SECOND = USECS_PER_MSEC * MSECS_PER_SECOND; const int BITS_IN_BYTE = 8; -quint64 usecTimestamp(const timeval *time); +void initialiseUsecTimestampNow(); quint64 usecTimestampNow(); void usecTimestampNowForceClockSkew(int clockSkew); diff --git a/libraries/shared/src/Systime.cpp b/libraries/shared/src/Systime.cpp deleted file mode 100644 index ab32821a0f..0000000000 --- a/libraries/shared/src/Systime.cpp +++ /dev/null @@ -1,61 +0,0 @@ -// -// Systime.cpp -// libraries/shared/src -// -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#ifdef WIN32 - -#include "Systime.h" - -/** - * gettimeofday - * Implementation according to: - * The Open Group Base Specifications Issue 6 - * IEEE Std 1003.1, 2004 Edition - */ - -/** - * THIS SOFTWARE IS NOT COPYRIGHTED - * - * This source code is offered for use in the public domain. You may - * use, modify or distribute it freely. - * - * This code is distributed in the hope that it will be useful but - * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY - * DISCLAIMED. This includes but is not limited to warranties of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * Contributed by: - * Danny Smith - */ - -#define WIN32_LEAN_AND_MEAN -#include - -/** Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */ -#define _W32_FT_OFFSET (116444736000000000ULL) - -int gettimeofday(timeval* p_tv, timezone* p_tz) { - - union { - unsigned long long ns100; /**time since 1 Jan 1601 in 100ns units */ - FILETIME ft; - } _now; - - if (p_tv) { - GetSystemTimeAsFileTime (&_now.ft); - p_tv->tv_usec=(long)((_now.ns100 / 10ULL) % 1000000ULL ); - p_tv->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000ULL); - } - - /** Always return 0 as per Open Group Base Specifications Issue 6. - Do not set errno on error. */ - return 0; -} - -#endif \ No newline at end of file diff --git a/libraries/shared/src/Systime.h b/libraries/shared/src/Systime.h deleted file mode 100644 index 3098f09ecd..0000000000 --- a/libraries/shared/src/Systime.h +++ /dev/null @@ -1,27 +0,0 @@ -// -// Systime.h -// libraries/shared/src -// -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#ifndef hifi_Systime_h -#define hifi_Systime_h - -#ifdef WIN32 - -#include - -struct timezone { - int tz_minuteswest; /* minutes west of Greenwich */ - int tz_dsttime; /* type of dst correction */ -}; - -int gettimeofday(struct timeval* p_tv, struct timezone* p_tz); - -#endif - -#endif // hifi_Systime_h \ No newline at end of file diff --git a/libraries/voxels/src/VoxelTreeElement.h b/libraries/voxels/src/VoxelTreeElement.h index 140744afb0..8733987df4 100644 --- a/libraries/voxels/src/VoxelTreeElement.h +++ b/libraries/voxels/src/VoxelTreeElement.h @@ -18,10 +18,10 @@ #include +#include #include #include -#include "AABox.h" #include "ViewFrustum.h" #include "VoxelConstants.h" diff --git a/tests/physics/src/ShapeColliderTests.cpp b/tests/physics/src/ShapeColliderTests.cpp index f9e76bac0b..3f952236e2 100644 --- a/tests/physics/src/ShapeColliderTests.cpp +++ b/tests/physics/src/ShapeColliderTests.cpp @@ -23,18 +23,18 @@ #include "ShapeColliderTests.h" -const glm::vec3 origin(0.f); -static const glm::vec3 xAxis(1.f, 0.f, 0.f); -static const glm::vec3 yAxis(0.f, 1.f, 0.f); -static const glm::vec3 zAxis(0.f, 0.f, 1.f); +const glm::vec3 origin(0.0f); +static const glm::vec3 xAxis(1.0f, 0.0f, 0.0f); +static const glm::vec3 yAxis(0.0f, 1.0f, 0.0f); +static const glm::vec3 zAxis(0.0f, 0.0f, 1.0f); void ShapeColliderTests::sphereMissesSphere() { // non-overlapping spheres of unequal size - float radiusA = 7.f; - float radiusB = 3.f; + float radiusA = 7.0f; + float radiusB = 3.0f; float alpha = 1.2f; float beta = 1.3f; - glm::vec3 offsetDirection = glm::normalize(glm::vec3(1.f, 2.f, 3.f)); + glm::vec3 offsetDirection = glm::normalize(glm::vec3(1.0f, 2.0f, 3.0f)); float offsetDistance = alpha * radiusA + beta * radiusB; SphereShape sphereA(radiusA, origin); @@ -77,13 +77,13 @@ void ShapeColliderTests::sphereMissesSphere() { void ShapeColliderTests::sphereTouchesSphere() { // overlapping spheres of unequal size - float radiusA = 7.f; - float radiusB = 3.f; + float radiusA = 7.0f; + float radiusB = 3.0f; float alpha = 0.2f; float beta = 0.3f; - glm::vec3 offsetDirection = glm::normalize(glm::vec3(1.f, 2.f, 3.f)); + glm::vec3 offsetDirection = glm::normalize(glm::vec3(1.0f, 2.0f, 3.0f)); float offsetDistance = alpha * radiusA + beta * radiusB; - float expectedPenetrationDistance = (1.f - alpha) * radiusA + (1.f - beta) * radiusB; + float expectedPenetrationDistance = (1.0f - alpha) * radiusA + (1.0f - beta) * radiusB; glm::vec3 expectedPenetration = expectedPenetrationDistance * offsetDirection; SphereShape sphereA(radiusA, origin); @@ -118,8 +118,7 @@ void ShapeColliderTests::sphereTouchesSphere() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of sphereA @@ -129,8 +128,7 @@ void ShapeColliderTests::sphereTouchesSphere() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } } @@ -150,8 +148,7 @@ void ShapeColliderTests::sphereTouchesSphere() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of sphereA @@ -161,8 +158,7 @@ void ShapeColliderTests::sphereTouchesSphere() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } } } @@ -181,7 +177,7 @@ void ShapeColliderTests::sphereMissesCapsule() { // give the capsule some arbirary transform float angle = 37.8f; - glm::vec3 axis = glm::normalize( glm::vec3(-7.f, 2.8f, 9.3f) ); + glm::vec3 axis = glm::normalize( glm::vec3(-7.0f, 2.8f, 9.3f) ); glm::quat rotation = glm::angleAxis(angle, axis); glm::vec3 translation(15.1f, -27.1f, -38.6f); capsuleB.setRotation(rotation); @@ -190,7 +186,7 @@ void ShapeColliderTests::sphereMissesCapsule() { CollisionList collisions(16); // walk sphereA along the local yAxis next to, but not touching, capsuleB - glm::vec3 localStartPosition(radialOffset, axialOffset, 0.f); + glm::vec3 localStartPosition(radialOffset, axialOffset, 0.0f); int numberOfSteps = 10; float delta = 1.3f * (totalRadius + halfHeightB) / (numberOfSteps - 1); for (int i = 0; i < numberOfSteps; ++i) { @@ -224,10 +220,10 @@ void ShapeColliderTests::sphereMissesCapsule() { void ShapeColliderTests::sphereTouchesCapsule() { // overlapping sphere and capsule - float radiusA = 2.f; - float radiusB = 1.f; + float radiusA = 2.0f; + float radiusB = 1.0f; float totalRadius = radiusA + radiusB; - float halfHeightB = 2.f; + float halfHeightB = 2.0f; float alpha = 0.5f; float beta = 0.5f; float radialOffset = alpha * radiusA + beta * radiusB; @@ -257,8 +253,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of sphereA @@ -267,8 +262,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } // capsuleB collides with sphereA @@ -288,8 +282,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of capsuleB @@ -300,8 +293,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } } { // sphereA hits end cap at axis @@ -319,13 +311,12 @@ void ShapeColliderTests::sphereTouchesCapsule() { // penetration points from sphereA into capsuleB CollisionInfo* collision = collisions.getCollision(numCollisions - 1); - glm::vec3 expectedPenetration = - ((1.f - alpha) * radiusA + (1.f - beta) * radiusB) * yAxis; + glm::vec3 expectedPenetration = - ((1.0f - alpha) * radiusA + (1.0f - beta) * radiusB) * yAxis; float inaccuracy = glm::length(collision->_penetration - expectedPenetration); if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of sphereA @@ -334,8 +325,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } // capsuleB collides with sphereA @@ -350,13 +340,12 @@ void ShapeColliderTests::sphereTouchesCapsule() { // penetration points from sphereA into capsuleB collision = collisions.getCollision(numCollisions - 1); - expectedPenetration = ((1.f - alpha) * radiusA + (1.f - beta) * radiusB) * yAxis; + expectedPenetration = ((1.0f - alpha) * radiusA + (1.0f - beta) * radiusB) * yAxis; inaccuracy = glm::length(collision->_penetration - expectedPenetration); if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of capsuleB @@ -367,8 +356,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } } { // sphereA hits start cap at axis @@ -386,13 +374,12 @@ void ShapeColliderTests::sphereTouchesCapsule() { // penetration points from sphereA into capsuleB CollisionInfo* collision = collisions.getCollision(numCollisions - 1); - glm::vec3 expectedPenetration = ((1.f - alpha) * radiusA + (1.f - beta) * radiusB) * yAxis; + glm::vec3 expectedPenetration = ((1.0f - alpha) * radiusA + (1.0f - beta) * radiusB) * yAxis; float inaccuracy = glm::length(collision->_penetration - expectedPenetration); if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of sphereA @@ -401,8 +388,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } // capsuleB collides with sphereA @@ -417,13 +403,12 @@ void ShapeColliderTests::sphereTouchesCapsule() { // penetration points from sphereA into capsuleB collision = collisions.getCollision(numCollisions - 1); - expectedPenetration = - ((1.f - alpha) * radiusA + (1.f - beta) * radiusB) * yAxis; + expectedPenetration = - ((1.0f - alpha) * radiusA + (1.0f - beta) * radiusB) * yAxis; inaccuracy = glm::length(collision->_penetration - expectedPenetration); if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of capsuleB @@ -434,8 +419,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } } if (collisions.size() != numCollisions) { @@ -447,10 +431,10 @@ void ShapeColliderTests::sphereTouchesCapsule() { void ShapeColliderTests::capsuleMissesCapsule() { // non-overlapping capsules - float radiusA = 2.f; - float halfHeightA = 3.f; - float radiusB = 3.f; - float halfHeightB = 4.f; + float radiusA = 2.0f; + float halfHeightA = 3.0f; + float radiusB = 3.0f; + float halfHeightB = 4.0f; float totalRadius = radiusA + radiusB; float totalHalfLength = totalRadius + halfHeightA + halfHeightB; @@ -516,10 +500,10 @@ void ShapeColliderTests::capsuleMissesCapsule() { void ShapeColliderTests::capsuleTouchesCapsule() { // overlapping capsules - float radiusA = 2.f; - float halfHeightA = 3.f; - float radiusB = 3.f; - float halfHeightB = 4.f; + float radiusA = 2.0f; + float halfHeightA = 3.0f; + float radiusB = 3.0f; + float halfHeightB = 4.0f; float totalRadius = radiusA + radiusB; float totalHalfLength = totalRadius + halfHeightA + halfHeightB; @@ -617,8 +601,7 @@ void ShapeColliderTests::capsuleTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } glm::vec3 expectedContactPoint = capsuleA.getPosition() + radiusA * xAxis; @@ -626,8 +609,7 @@ void ShapeColliderTests::capsuleTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } // capsuleB vs capsuleA @@ -699,6 +681,116 @@ void ShapeColliderTests::capsuleTouchesCapsule() { } } +void ShapeColliderTests::sphereTouchesAACube() { + CollisionList collisions(16); + + glm::vec3 cubeCenter(1.23f, 4.56f, 7.89f); + float cubeSide = 2.0f; + + float sphereRadius = 1.0f; + glm::vec3 sphereCenter(0.0f); + SphereShape sphere(sphereRadius, sphereCenter); + + float sphereOffset = (0.5f * cubeSide + sphereRadius - 0.25f); + + // top + sphereCenter = cubeCenter + sphereOffset * yAxis; + sphere.setPosition(sphereCenter); + if (!ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should collide with cube" << std::endl; + } + + // bottom + sphereCenter = cubeCenter - sphereOffset * yAxis; + sphere.setPosition(sphereCenter); + if (!ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should collide with cube" << std::endl; + } + + // left + sphereCenter = cubeCenter + sphereOffset * xAxis; + sphere.setPosition(sphereCenter); + if (!ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should collide with cube" << std::endl; + } + + // right + sphereCenter = cubeCenter - sphereOffset * xAxis; + sphere.setPosition(sphereCenter); + if (!ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should collide with cube" << std::endl; + } + + // forward + sphereCenter = cubeCenter + sphereOffset * zAxis; + sphere.setPosition(sphereCenter); + if (!ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should collide with cube" << std::endl; + } + + // back + sphereCenter = cubeCenter - sphereOffset * zAxis; + sphere.setPosition(sphereCenter); + if (!ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should collide with cube" << std::endl; + } +} + +void ShapeColliderTests::sphereMissesAACube() { + CollisionList collisions(16); + + glm::vec3 cubeCenter(1.23f, 4.56f, 7.89f); + float cubeSide = 2.0f; + + float sphereRadius = 1.0f; + glm::vec3 sphereCenter(0.0f); + SphereShape sphere(sphereRadius, sphereCenter); + + float sphereOffset = (0.5f * cubeSide + sphereRadius + 0.25f); + + // top + sphereCenter = cubeCenter + sphereOffset * yAxis; + sphere.setPosition(sphereCenter); + if (ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should NOT collide with cube" << std::endl; + } + + // bottom + sphereCenter = cubeCenter - sphereOffset * yAxis; + sphere.setPosition(sphereCenter); + if (ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should NOT collide with cube" << std::endl; + } + + // left + sphereCenter = cubeCenter + sphereOffset * xAxis; + sphere.setPosition(sphereCenter); + if (ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should NOT collide with cube" << std::endl; + } + + // right + sphereCenter = cubeCenter - sphereOffset * xAxis; + sphere.setPosition(sphereCenter); + if (ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should NOT collide with cube" << std::endl; + } + + // forward + sphereCenter = cubeCenter + sphereOffset * zAxis; + sphere.setPosition(sphereCenter); + if (ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should NOT collide with cube" << std::endl; + } + + // back + sphereCenter = cubeCenter - sphereOffset * zAxis; + sphere.setPosition(sphereCenter); + if (ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should NOT collide with cube" << std::endl; + } +} + void ShapeColliderTests::runAllTests() { sphereMissesSphere(); @@ -709,4 +801,7 @@ void ShapeColliderTests::runAllTests() { capsuleMissesCapsule(); capsuleTouchesCapsule(); + + sphereTouchesAACube(); + sphereMissesAACube(); } diff --git a/tests/physics/src/ShapeColliderTests.h b/tests/physics/src/ShapeColliderTests.h index 1d468a65d2..a94f5050ff 100644 --- a/tests/physics/src/ShapeColliderTests.h +++ b/tests/physics/src/ShapeColliderTests.h @@ -23,6 +23,9 @@ namespace ShapeColliderTests { void capsuleMissesCapsule(); void capsuleTouchesCapsule(); + void sphereTouchesAACube(); + void sphereMissesAACube(); + void runAllTests(); }