From 538fc897392e9e16e3ab2e1500bc017970f6d56d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sun, 26 May 2013 13:11:54 -0700 Subject: [PATCH 01/81] first cut at dirty bit sending support --- libraries/voxels/src/VoxelNode.cpp | 10 ++++++++++ libraries/voxels/src/VoxelNode.h | 4 ++++ libraries/voxels/src/VoxelTree.cpp | 13 ++++++++----- libraries/voxels/src/VoxelTree.h | 6 ++++-- voxel-server/src/VoxelAgentData.cpp | 7 +++++++ voxel-server/src/VoxelAgentData.h | 4 ++++ voxel-server/src/main.cpp | 3 ++- 7 files changed, 39 insertions(+), 8 deletions(-) diff --git a/libraries/voxels/src/VoxelNode.cpp b/libraries/voxels/src/VoxelNode.cpp index f542fe0dd4..a9a1f4eb12 100644 --- a/libraries/voxels/src/VoxelNode.cpp +++ b/libraries/voxels/src/VoxelNode.cpp @@ -47,6 +47,8 @@ void VoxelNode::init(unsigned char * octalCode) { _shouldRender = false; _isStagedForDeletion = false; + _lastChanged = usecTimestampNow(); + calculateAABox(); } @@ -66,6 +68,7 @@ void VoxelNode::setShouldRender(bool shouldRender) { if (shouldRender != _shouldRender) { _shouldRender = shouldRender; _isDirty = true; + _lastChanged = usecTimestampNow(); } } @@ -89,6 +92,7 @@ void VoxelNode::deleteChildAtIndex(int childIndex) { delete _children[childIndex]; _children[childIndex] = NULL; _isDirty = true; + _lastChanged = usecTimestampNow(); _childCount--; } } @@ -99,6 +103,7 @@ VoxelNode* VoxelNode::removeChildAtIndex(int childIndex) { if (_children[childIndex]) { _children[childIndex] = NULL; _isDirty = true; + _lastChanged = usecTimestampNow(); _childCount--; } return returnedChild; @@ -108,6 +113,7 @@ void VoxelNode::addChildAtIndex(int childIndex) { if (!_children[childIndex]) { _children[childIndex] = new VoxelNode(childOctalCode(_octalCode, childIndex)); _isDirty = true; + _lastChanged = usecTimestampNow(); _childCount++; } } @@ -135,6 +141,7 @@ void VoxelNode::safeDeepDeleteChildAtIndex(int childIndex, bool& stagedForDeleti deleteChildAtIndex(childIndex); _isDirty = true; } + _lastChanged = usecTimestampNow(); } } @@ -178,6 +185,7 @@ void VoxelNode::setFalseColor(colorPart red, colorPart green, colorPart blue) { _currentColor[2] = blue; _currentColor[3] = 1; // XXXBHG - False colors are always considered set _isDirty = true; + _lastChanged = usecTimestampNow(); } } @@ -189,6 +197,7 @@ void VoxelNode::setFalseColored(bool isFalseColored) { } _falseColored = isFalseColored; _isDirty = true; + _lastChanged = usecTimestampNow(); } }; @@ -202,6 +211,7 @@ void VoxelNode::setColor(const nodeColor& color) { memcpy(&_currentColor,&color,sizeof(nodeColor)); } _isDirty = true; + _lastChanged = usecTimestampNow(); } } #endif diff --git a/libraries/voxels/src/VoxelNode.h b/libraries/voxels/src/VoxelNode.h index 1b21962261..ca00260ace 100644 --- a/libraries/voxels/src/VoxelNode.h +++ b/libraries/voxels/src/VoxelNode.h @@ -36,6 +36,8 @@ private: void calculateAABox(); void init(unsigned char * octalCode); + + double _lastChanged; public: VoxelNode(); // root node constructor @@ -75,6 +77,8 @@ public: void printDebugDetails(const char* label) const; bool isDirty() const { return _isDirty; }; void clearDirtyBit() { _isDirty = false; }; + bool hasChangedSince(double time) const { return (_lastChanged > time); }; + glBufferIndex getBufferIndex() const { return _glBufferIndex; }; bool isKnownBufferIndex() const { return (_glBufferIndex != GLBUFFER_INDEX_UNKNOWN); }; void setBufferIndex(glBufferIndex index) { _glBufferIndex = index; }; diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index 798b447d6c..41782a3d2b 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -862,7 +862,8 @@ int VoxelTree::searchForColoredNodesRecursion(int maxSearchLevel, int& currentSe int VoxelTree::encodeTreeBitstream(int maxEncodeLevel, VoxelNode* node, unsigned char* outputBuffer, int availableBytes, VoxelNodeBag& bag, const ViewFrustum* viewFrustum, bool includeColor, bool includeExistsBits, - bool deltaViewFrustum, const ViewFrustum* lastViewFrustum) const { + bool deltaViewFrustum, const ViewFrustum* lastViewFrustum, + double lastViewFrustumSent) const { // How many bytes have we written so far at this level; int bytesWritten = 0; @@ -883,7 +884,7 @@ int VoxelTree::encodeTreeBitstream(int maxEncodeLevel, VoxelNode* node, unsigned int currentEncodeLevel = 0; int childBytesWritten = encodeTreeBitstreamRecursion(maxEncodeLevel, currentEncodeLevel, node, outputBuffer, availableBytes, bag, viewFrustum, includeColor, includeExistsBits, - deltaViewFrustum, lastViewFrustum); + deltaViewFrustum, lastViewFrustum, lastViewFrustumSent); // if childBytesWritten == 1 then something went wrong... that's not possible assert(childBytesWritten != 1); @@ -907,7 +908,8 @@ int VoxelTree::encodeTreeBitstream(int maxEncodeLevel, VoxelNode* node, unsigned int VoxelTree::encodeTreeBitstreamRecursion(int maxEncodeLevel, int& currentEncodeLevel, VoxelNode* node, unsigned char* outputBuffer, int availableBytes, VoxelNodeBag& bag, const ViewFrustum* viewFrustum, bool includeColor, bool includeExistsBits, - bool deltaViewFrustum, const ViewFrustum* lastViewFrustum) const { + bool deltaViewFrustum, const ViewFrustum* lastViewFrustum, + double lastViewFrustumSent) const { // How many bytes have we written so far at this level; int bytesAtThisLevel = 0; @@ -992,7 +994,8 @@ int VoxelTree::encodeTreeBitstreamRecursion(int maxEncodeLevel, int& currentEnco (lastViewFrustum && ViewFrustum::INSIDE == childNode->inFrustum(*lastViewFrustum))); // track children with actual color, only if the child wasn't previously in view! - if (childNode && childNode->isColored() && !childWasInView) { + if (childNode && childNode->isColored() && + (!childWasInView || childNode->hasChangedSince(lastViewFrustumSent) )) { childrenColoredBits += (1 << (7 - i)); inViewWithColorCount++; } @@ -1063,7 +1066,7 @@ int VoxelTree::encodeTreeBitstreamRecursion(int maxEncodeLevel, int& currentEnco int childTreeBytesOut = encodeTreeBitstreamRecursion(maxEncodeLevel, thisLevel, childNode, outputBuffer, availableBytes, bag, viewFrustum, includeColor, includeExistsBits, - deltaViewFrustum, lastViewFrustum); + deltaViewFrustum, lastViewFrustum, lastViewFrustumSent); // if the child wrote 0 bytes, it means that nothing below exists or was in view, or we ran out of space, // basically, the children below don't contain any info. diff --git a/libraries/voxels/src/VoxelTree.h b/libraries/voxels/src/VoxelTree.h index 0643b1038e..0d774ebbad 100644 --- a/libraries/voxels/src/VoxelTree.h +++ b/libraries/voxels/src/VoxelTree.h @@ -71,7 +71,8 @@ public: int encodeTreeBitstream(int maxEncodeLevel, VoxelNode* node, unsigned char* outputBuffer, int availableBytes, VoxelNodeBag& bag, const ViewFrustum* viewFrustum, bool includeColor = WANT_COLOR, bool includeExistsBits = WANT_EXISTS_BITS, - bool deltaViewFrustum = false, const ViewFrustum* lastViewFrustum = NULL) const; + bool deltaViewFrustum = false, const ViewFrustum* lastViewFrustum = NULL, + double lastViewFrustumSent = 0) const; int searchForColoredNodes(int maxSearchLevel, VoxelNode* node, const ViewFrustum& viewFrustum, VoxelNodeBag& bag, bool deltaViewFrustum = false, const ViewFrustum* lastViewFrustum = NULL); @@ -100,7 +101,8 @@ private: int encodeTreeBitstreamRecursion(int maxEncodeLevel, int& currentEncodeLevel, VoxelNode* node, unsigned char* outputBuffer, int availableBytes, VoxelNodeBag& bag, const ViewFrustum* viewFrustum, bool includeColor, bool includeExistsBits, - bool deltaViewFrustum, const ViewFrustum* lastViewFrustum) const; + bool deltaViewFrustum, const ViewFrustum* lastViewFrustum, + double lastViewFrustumSent) const; int searchForColoredNodesRecursion(int maxSearchLevel, int& currentSearchLevel, VoxelNode* node, const ViewFrustum& viewFrustum, VoxelNodeBag& bag, diff --git a/voxel-server/src/VoxelAgentData.cpp b/voxel-server/src/VoxelAgentData.cpp index 082fc5e7fc..0ca7778a94 100644 --- a/voxel-server/src/VoxelAgentData.cpp +++ b/voxel-server/src/VoxelAgentData.cpp @@ -8,6 +8,7 @@ #include "PacketHeaders.h" #include "VoxelAgentData.h" +#include "SharedUtil.h" #include #include @@ -20,6 +21,7 @@ VoxelAgentData::VoxelAgentData(Agent* owningAgent) : { _voxelPacket = new unsigned char[MAX_VOXEL_PACKET_SIZE]; _voxelPacketAt = _voxelPacket; + _lastViewFrustumSent = 0; resetVoxelPacket(); } @@ -72,5 +74,10 @@ void VoxelAgentData::updateLastKnownViewFrustum() { // save our currentViewFrustum into our lastKnownViewFrustum _lastKnownViewFrustum = _currentViewFrustum; } + + // save that we know the view has been sent. + double now = usecTimestampNow(); + printf("updateLastKnownViewFrustum() setLastViewSent() to %lf\n", now); + setLastViewSent(now); } diff --git a/voxel-server/src/VoxelAgentData.h b/voxel-server/src/VoxelAgentData.h index 2afc64a6c8..04da24ea6b 100644 --- a/voxel-server/src/VoxelAgentData.h +++ b/voxel-server/src/VoxelAgentData.h @@ -48,6 +48,9 @@ public: bool getViewSent() const { return _viewSent; }; void setViewSent(bool viewSent) { _viewSent = viewSent; } + double getLastViewSent() const { return _lastViewFrustumSent; }; + void setLastViewSent(double viewSent) { _lastViewFrustumSent = viewSent; } + private: VoxelAgentData(const VoxelAgentData &); VoxelAgentData& operator= (const VoxelAgentData&); @@ -61,6 +64,7 @@ private: int _maxLevelReachedInLastSearch; ViewFrustum _currentViewFrustum; ViewFrustum _lastKnownViewFrustum; + double _lastViewFrustumSent; }; diff --git a/voxel-server/src/main.cpp b/voxel-server/src/main.cpp index 1a93021f09..098596f02e 100644 --- a/voxel-server/src/main.cpp +++ b/voxel-server/src/main.cpp @@ -314,7 +314,7 @@ void deepestLevelVoxelDistributor(AgentList* agentList, &tempOutputBuffer[0], MAX_VOXEL_PACKET_SIZE - 1, agentData->nodeBag, &agentData->getCurrentViewFrustum(), agentData->getWantColor(), WANT_EXISTS_BITS, - wantDelta, lastViewFrustum); + wantDelta, lastViewFrustum, agentData->getLastViewSent()); if (agentData->getAvailable() >= bytesWritten) { agentData->writeToPacket(&tempOutputBuffer[0], bytesWritten); @@ -370,6 +370,7 @@ void deepestLevelVoxelDistributor(AgentList* agentList, // if after sending packets we've emptied our bag, then we want to remember that we've sent all // the voxels from the current view frustum if (agentData->nodeBag.isEmpty()) { +printf("agentData->nodeBag.isEmpty()...\n"); agentData->updateLastKnownViewFrustum(); agentData->setViewSent(true); } From 12dc11fbfae108f170b05ef5aa9b00e610c2dd0c Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 27 May 2013 09:56:35 -0700 Subject: [PATCH 02/81] Optimize View Frustum wire format. - Changed View frstum orientaton to be a quaternion - Implemented packing formats for Orientation Quats, Ratios, and Clipping values - Changed wire format for View Frustum details to be more efficient 28 bytes vs 64 bytes --- interface/src/Application.cpp | 8 +- interface/src/Avatar.cpp | 2 +- interface/src/Head.cpp | 4 +- libraries/avatars/src/AvatarData.cpp | 167 +++++++++++++++++++-------- libraries/avatars/src/AvatarData.h | 50 +++++--- libraries/shared/src/SharedUtil.cpp | 1 + libraries/shared/src/SharedUtil.h | 1 + libraries/voxels/src/ViewFrustum.cpp | 42 +++++-- libraries/voxels/src/ViewFrustum.h | 29 ++--- voxel-server/src/VoxelAgentData.cpp | 2 +- 10 files changed, 210 insertions(+), 96 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index a0979eb4b9..790a7f9495 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1092,7 +1092,7 @@ static void sendVoxelEditMessage(PACKET_HEADER header, VoxelDetail& detail) { void Application::addVoxelInFrontOfAvatar() { VoxelDetail detail; - glm::vec3 position = (_myAvatar.getPosition() + _myAvatar.getCameraDirection()) * (1.0f / TREE_SCALE); + glm::vec3 position = (_myAvatar.getPosition() + _myAvatar.calculateCameraDirection()) * (1.0f / TREE_SCALE); detail.s = _mouseVoxelScale; detail.x = detail.s * floor(position.x / detail.s); @@ -1347,9 +1347,7 @@ void Application::updateAvatar(float deltaTime) { // to the server. loadViewFrustum(_myCamera, _viewFrustum); _myAvatar.setCameraPosition(_viewFrustum.getPosition()); - _myAvatar.setCameraDirection(_viewFrustum.getDirection()); - _myAvatar.setCameraUp(_viewFrustum.getUp()); - _myAvatar.setCameraRight(_viewFrustum.getRight()); + _myAvatar.setCameraOrientation(_viewFrustum.getOrientation()); _myAvatar.setCameraFov(_viewFrustum.getFieldOfView()); _myAvatar.setCameraAspectRatio(_viewFrustum.getAspectRatio()); _myAvatar.setCameraNearClip(_viewFrustum.getNearClip()); @@ -1435,7 +1433,7 @@ void Application::loadViewFrustum(Camera& camera, ViewFrustum& viewFrustum) { // Set the viewFrustum up with the correct position and orientation of the camera viewFrustum.setPosition(position); - viewFrustum.setOrientation(direction,up,right); + viewFrustum.setOrientation(o.getQuat()); // Also make sure it's got the correct lens details from the camera viewFrustum.setFieldOfView(fov); diff --git a/interface/src/Avatar.cpp b/interface/src/Avatar.cpp index 8ce1abb05b..fce56ff670 100644 --- a/interface/src/Avatar.cpp +++ b/interface/src/Avatar.cpp @@ -80,8 +80,8 @@ Avatar::Avatar(Agent* owningAgent) : _bodyRollDelta(0.0f), _movedHandOffset(0.0f, 0.0f, 0.0f), _rotation(0.0f, 0.0f, 0.0f, 0.0f), - _cameraPosition(0.0f, 0.0f, 0.0f), _mode(AVATAR_MODE_STANDING), + _cameraPosition(0.0f, 0.0f, 0.0f), _handHoldingPosition(0.0f, 0.0f, 0.0f), _velocity(0.0f, 0.0f, 0.0f), _thrust(0.0f, 0.0f, 0.0f), diff --git a/interface/src/Head.cpp b/interface/src/Head.cpp index 1486013c9c..736534f087 100644 --- a/interface/src/Head.cpp +++ b/interface/src/Head.cpp @@ -62,9 +62,9 @@ Head::Head(Avatar* owningAvatar) : _audioAttack(0.0f), _returnSpringScale(1.0f), _bodyRotation(0.0f, 0.0f, 0.0f), + _renderLookatVectors(false), _mohawkTriangleFan(NULL), - _mohawkColors(NULL), - _renderLookatVectors(false) { + _mohawkColors(NULL) { for (int t = 0; t < NUM_HAIR_TUFTS; t ++) { _hairTuft[t].length = HAIR_LENGTH; diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index 4b97a2a047..fa0a8d1e20 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -17,20 +17,6 @@ using namespace std; -int packFloatAngleToTwoByte(unsigned char* buffer, float angle) { - const float ANGLE_CONVERSION_RATIO = (std::numeric_limits::max() / 360.0); - - uint16_t angleHolder = floorf((angle + 180) * ANGLE_CONVERSION_RATIO); - memcpy(buffer, &angleHolder, sizeof(uint16_t)); - - return sizeof(uint16_t); -} - -int unpackFloatAngleFromTwoByte(uint16_t* byteAnglePointer, float* destinationPointer) { - *destinationPointer = (*byteAnglePointer / (float) std::numeric_limits::max()) * 360.0 - 180; - return sizeof(uint16_t); -} - AvatarData::AvatarData(Agent* owningAgent) : AgentData(owningAgent), _handPosition(0,0,0), @@ -40,9 +26,7 @@ AvatarData::AvatarData(Agent* owningAgent) : _audioLoudness(0), _handState(0), _cameraPosition(0,0,0), - _cameraDirection(0,0,0), - _cameraUp(0,0,0), - _cameraRight(0,0,0), + _cameraOrientation(), _cameraFov(0.0f), _cameraAspectRatio(0.0f), _cameraNearClip(0.0f), @@ -110,20 +94,11 @@ int AvatarData::getBroadcastData(unsigned char* destinationBuffer) { // camera details memcpy(destinationBuffer, &_cameraPosition, sizeof(_cameraPosition)); destinationBuffer += sizeof(_cameraPosition); - memcpy(destinationBuffer, &_cameraDirection, sizeof(_cameraDirection)); - destinationBuffer += sizeof(_cameraDirection); - memcpy(destinationBuffer, &_cameraRight, sizeof(_cameraRight)); - destinationBuffer += sizeof(_cameraRight); - memcpy(destinationBuffer, &_cameraUp, sizeof(_cameraUp)); - destinationBuffer += sizeof(_cameraUp); - memcpy(destinationBuffer, &_cameraFov, sizeof(_cameraFov)); - destinationBuffer += sizeof(_cameraFov); - memcpy(destinationBuffer, &_cameraAspectRatio, sizeof(_cameraAspectRatio)); - destinationBuffer += sizeof(_cameraAspectRatio); - memcpy(destinationBuffer, &_cameraNearClip, sizeof(_cameraNearClip)); - destinationBuffer += sizeof(_cameraNearClip); - memcpy(destinationBuffer, &_cameraFarClip, sizeof(_cameraFarClip)); - destinationBuffer += sizeof(_cameraFarClip); + destinationBuffer += packOrientationQuatToBytes(destinationBuffer, _cameraOrientation); + destinationBuffer += packFloatAngleToTwoByte(destinationBuffer, _cameraFov); + destinationBuffer += packFloatRatioToTwoByte(destinationBuffer, _cameraAspectRatio); + destinationBuffer += packClipValueToTwoByte(destinationBuffer, _cameraNearClip); + destinationBuffer += packClipValueToTwoByte(destinationBuffer, _cameraFarClip); // key state *destinationBuffer++ = _keyState; @@ -204,21 +179,12 @@ int AvatarData::parseData(unsigned char* sourceBuffer, int numBytes) { // camera details memcpy(&_cameraPosition, sourceBuffer, sizeof(_cameraPosition)); sourceBuffer += sizeof(_cameraPosition); - memcpy(&_cameraDirection, sourceBuffer, sizeof(_cameraDirection)); - sourceBuffer += sizeof(_cameraDirection); - memcpy(&_cameraRight, sourceBuffer, sizeof(_cameraRight)); - sourceBuffer += sizeof(_cameraRight); - memcpy(&_cameraUp, sourceBuffer, sizeof(_cameraUp)); - sourceBuffer += sizeof(_cameraUp); - memcpy(&_cameraFov, sourceBuffer, sizeof(_cameraFov)); - sourceBuffer += sizeof(_cameraFov); - memcpy(&_cameraAspectRatio, sourceBuffer, sizeof(_cameraAspectRatio)); - sourceBuffer += sizeof(_cameraAspectRatio); - memcpy(&_cameraNearClip, sourceBuffer, sizeof(_cameraNearClip)); - sourceBuffer += sizeof(_cameraNearClip); - memcpy(&_cameraFarClip, sourceBuffer, sizeof(_cameraFarClip)); - sourceBuffer += sizeof(_cameraFarClip); - + sourceBuffer += unpackOrientationQuatFromBytes(sourceBuffer, _cameraOrientation); + sourceBuffer += unpackFloatAngleFromTwoByte((uint16_t*) sourceBuffer, &_cameraFov); + sourceBuffer += unpackFloatRatioFromTwoByte(sourceBuffer,_cameraAspectRatio); + sourceBuffer += unpackClipValueFromTwoByte(sourceBuffer,_cameraNearClip); + sourceBuffer += unpackClipValueFromTwoByte(sourceBuffer,_cameraFarClip); + // key state _keyState = (KeyState)*sourceBuffer++; @@ -236,3 +202,112 @@ int AvatarData::parseData(unsigned char* sourceBuffer, int numBytes) { return sourceBuffer - startPosition; } + +glm::vec3 AvatarData::calculateCameraDirection() const { + const glm::vec3 IDENTITY_FRONT = glm::vec3( 0.0f, 0.0f, 1.0f); + glm::mat4 rotationMatrix = glm::mat4_cast(_cameraOrientation); + glm::vec3 direction = glm::vec3(glm::vec4(IDENTITY_FRONT, 0.0f) * rotationMatrix); + return direction; +} + + +int packFloatAngleToTwoByte(unsigned char* buffer, float angle) { + const float ANGLE_CONVERSION_RATIO = (std::numeric_limits::max() / 360.0); + + uint16_t angleHolder = floorf((angle + 180) * ANGLE_CONVERSION_RATIO); + memcpy(buffer, &angleHolder, sizeof(uint16_t)); + + return sizeof(uint16_t); +} + +int unpackFloatAngleFromTwoByte(uint16_t* byteAnglePointer, float* destinationPointer) { + *destinationPointer = (*byteAnglePointer / (float) std::numeric_limits::max()) * 360.0 - 180; + return sizeof(uint16_t); +} + +int packOrientationQuatToBytes(unsigned char* buffer, const glm::quat& quatInput) { + const float QUAT_PART_CONVERSION_RATIO = (std::numeric_limits::max() / 2.0); + uint16_t quatParts[4]; + quatParts[0] = floorf((quatInput.x + 1.0) * QUAT_PART_CONVERSION_RATIO); + quatParts[1] = floorf((quatInput.y + 1.0) * QUAT_PART_CONVERSION_RATIO); + quatParts[2] = floorf((quatInput.z + 1.0) * QUAT_PART_CONVERSION_RATIO); + quatParts[3] = floorf((quatInput.w + 1.0) * QUAT_PART_CONVERSION_RATIO); + + memcpy(buffer, &quatParts, sizeof(quatParts)); + return sizeof(quatParts); +} + +int unpackOrientationQuatFromBytes(unsigned char* buffer, glm::quat& quatOutput) { + uint16_t quatParts[4]; + memcpy(&quatParts, buffer, sizeof(quatParts)); + + quatOutput.x = ((quatParts[0] / (float) std::numeric_limits::max()) * 2.0) - 1.0; + quatOutput.y = ((quatParts[1] / (float) std::numeric_limits::max()) * 2.0) - 1.0; + quatOutput.z = ((quatParts[2] / (float) std::numeric_limits::max()) * 2.0) - 1.0; + quatOutput.w = ((quatParts[3] / (float) std::numeric_limits::max()) * 2.0) - 1.0; + + return sizeof(quatParts); +} + +float SMALL_LIMIT = 10.0; +float LARGE_LIMIT = 1000.0; + +int packFloatRatioToTwoByte(unsigned char* buffer, float ratio) { + // if the ratio is less than 10, then encode it as a positive number scaled from 0 to int16::max() + int16_t ratioHolder; + + if (ratio < SMALL_LIMIT) { + const float SMALL_RATIO_CONVERSION_RATIO = (std::numeric_limits::max() / SMALL_LIMIT); + ratioHolder = floorf(ratio * SMALL_RATIO_CONVERSION_RATIO); + } else { + const float LARGE_RATIO_CONVERSION_RATIO = std::numeric_limits::min() / LARGE_LIMIT; + ratioHolder = floorf((std::min(ratio,LARGE_LIMIT) - SMALL_LIMIT) * LARGE_RATIO_CONVERSION_RATIO); + } + memcpy(buffer, &ratioHolder, sizeof(ratioHolder)); + return sizeof(ratioHolder); +} + +int unpackFloatRatioFromTwoByte(unsigned char* buffer, float& ratio) { + int16_t ratioHolder; + memcpy(&ratioHolder, buffer, sizeof(ratioHolder)); + + // If it's positive, than the original ratio was less than SMALL_LIMIT + if (ratioHolder > 0) { + ratio = (ratioHolder / (float) std::numeric_limits::max()) * SMALL_LIMIT; + } else { + // If it's negative, than the original ratio was between SMALL_LIMIT and LARGE_LIMIT + ratio = ((ratioHolder / (float) std::numeric_limits::min()) * LARGE_LIMIT) + SMALL_LIMIT; + } + return sizeof(ratioHolder); +} + +int packClipValueToTwoByte(unsigned char* buffer, float clipValue) { + // Clip values must be less than max signed 16bit integers + assert(clipValue < std::numeric_limits::max()); + int16_t holder; + + // if the clip is less than 10, then encode it as a positive number scaled from 0 to int16::max() + if (clipValue < SMALL_LIMIT) { + const float SMALL_RATIO_CONVERSION_RATIO = (std::numeric_limits::max() / SMALL_LIMIT); + holder = floorf(clipValue * SMALL_RATIO_CONVERSION_RATIO); + } else { + // otherwise we store it as a negative integer + holder = -1 * floorf(clipValue); + } + memcpy(buffer, &holder, sizeof(holder)); + return sizeof(holder); +} + +int unpackClipValueFromTwoByte(unsigned char* buffer, float& clipValue) { + int16_t holder; + memcpy(&holder, buffer, sizeof(holder)); + + // If it's positive, than the original clipValue was less than SMALL_LIMIT + if (holder > 0) { + clipValue = (holder / (float) std::numeric_limits::max()) * SMALL_LIMIT; + } else { + // If it's negative, than the original holder can be found as the opposite sign of holder + clipValue = -1.0f * holder; + } + return sizeof(holder); +} diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index 5773dedffd..d86cc6078b 100644 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -12,6 +12,7 @@ #include #include +#include #include #include "HeadData.h" @@ -58,23 +59,21 @@ public: // getters for camera details const glm::vec3& getCameraPosition() const { return _cameraPosition; }; - const glm::vec3& getCameraDirection() const { return _cameraDirection; } - const glm::vec3& getCameraUp() const { return _cameraUp; } - const glm::vec3& getCameraRight() const { return _cameraRight; } + const glm::quat& getCameraOrientation() const { return _cameraOrientation; } float getCameraFov() const { return _cameraFov; } float getCameraAspectRatio() const { return _cameraAspectRatio; } float getCameraNearClip() const { return _cameraNearClip; } float getCameraFarClip() const { return _cameraFarClip; } + glm::vec3 calculateCameraDirection() const; + // setters for camera details - void setCameraPosition(const glm::vec3& position) { _cameraPosition = position; }; - void setCameraDirection(const glm::vec3& direction) { _cameraDirection = direction; } - void setCameraUp(const glm::vec3& up) { _cameraUp = up; } - void setCameraRight(const glm::vec3& right) { _cameraRight = right; } - void setCameraFov(float fov) { _cameraFov = fov; } - void setCameraAspectRatio(float aspectRatio) { _cameraAspectRatio = aspectRatio; } - void setCameraNearClip(float nearClip) { _cameraNearClip = nearClip; } - void setCameraFarClip(float farClip) { _cameraFarClip = farClip; } + void setCameraPosition(const glm::vec3& position) { _cameraPosition = position; } + void setCameraOrientation(const glm::quat& orientation) { _cameraOrientation = orientation; } + void setCameraFov(float fov) { _cameraFov = fov; } + void setCameraAspectRatio(float aspectRatio) { _cameraAspectRatio = aspectRatio; } + void setCameraNearClip(float nearClip) { _cameraNearClip = nearClip; } + void setCameraFarClip(float farClip) { _cameraFarClip = farClip; } // key state void setKeyState(KeyState s) { _keyState = s; } @@ -111,11 +110,7 @@ protected: // camera details for the avatar glm::vec3 _cameraPosition; - - // can we describe this in less space? For example, a Quaternion? or Euler angles? - glm::vec3 _cameraDirection; - glm::vec3 _cameraUp; - glm::vec3 _cameraRight; + glm::quat _cameraOrientation; float _cameraFov; float _cameraAspectRatio; float _cameraNearClip; @@ -139,4 +134,27 @@ private: AvatarData& operator= (const AvatarData&); }; + +// These pack/unpack functions are designed to start specific known types in as efficient a manner +// as possible. Taking advantage of the known characteristics of the semantic types. + +// Angles are known to be between 0 and 360deg, this allows us to encode in 16bits with great accuracy +int packFloatAngleToTwoByte(unsigned char* buffer, float angle); +int unpackFloatAngleFromTwoByte(uint16_t* byteAnglePointer, float* destinationPointer); + +// Orientation Quats are known to have 4 normalized components be between -1.0 and 1.0 +// this allows us to encode each component in 16bits with great accuracy +int packOrientationQuatToBytes(unsigned char* buffer, const glm::quat& quatInput); +int unpackOrientationQuatFromBytes(unsigned char* buffer, glm::quat& quatOutput); + +// Ratios need the be highly accurate when less than 10, but not very accurate above 10, and they +// are never greater than 1000 to 1, this allows us to encode each component in 16bits +int packFloatRatioToTwoByte(unsigned char* buffer, float ratio); +int unpackFloatRatioFromTwoByte(unsigned char* buffer, float& ratio); + +// Near/Far Clip values need the be highly accurate when less than 10, but only integer accuracy above 10 and +// they are never greater than 16,000, this allows us to encode each component in 16bits +int packClipValueToTwoByte(unsigned char* buffer, float clipValue); +int unpackClipValueFromTwoByte(unsigned char* buffer, float& clipValue); + #endif /* defined(__hifi__AvatarData__) */ diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index 5829bbe34a..ca31cdd994 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -421,3 +421,4 @@ int insertIntoSortedArrays(void* value, float key, int originalIndex, } return -1; // error case } + diff --git a/libraries/shared/src/SharedUtil.h b/libraries/shared/src/SharedUtil.h index 8da9d7beca..9d858f11e0 100644 --- a/libraries/shared/src/SharedUtil.h +++ b/libraries/shared/src/SharedUtil.h @@ -87,4 +87,5 @@ class debug { public: static const char* valueOf(bool checkValue) { return checkValue ? "yes" : "no"; }; }; + #endif /* defined(__hifi__SharedUtil__) */ diff --git a/libraries/voxels/src/ViewFrustum.cpp b/libraries/voxels/src/ViewFrustum.cpp index 061727b003..0f10428b23 100644 --- a/libraries/voxels/src/ViewFrustum.cpp +++ b/libraries/voxels/src/ViewFrustum.cpp @@ -19,22 +19,40 @@ using namespace std; ViewFrustum::ViewFrustum() : - _position(glm::vec3(0,0,0)), - _direction(glm::vec3(0,0,0)), - _up(glm::vec3(0,0,0)), - _right(glm::vec3(0,0,0)), + _position(0,0,0), + _orientation(), + _direction(0,0,0), + _up(0,0,0), + _right(0,0,0), _fieldOfView(0.0), _aspectRatio(1.0), _nearClip(0.1), _farClip(500.0), - _farTopLeft(glm::vec3(0,0,0)), - _farTopRight(glm::vec3(0,0,0)), - _farBottomLeft(glm::vec3(0,0,0)), - _farBottomRight(glm::vec3(0,0,0)), - _nearTopLeft(glm::vec3(0,0,0)), - _nearTopRight(glm::vec3(0,0,0)), - _nearBottomLeft(glm::vec3(0,0,0)), - _nearBottomRight(glm::vec3(0,0,0)) { } + _farTopLeft(0,0,0), + _farTopRight(0,0,0), + _farBottomLeft(0,0,0), + _farBottomRight(0,0,0), + _nearTopLeft(0,0,0), + _nearTopRight(0,0,0), + _nearBottomLeft(0,0,0), + _nearBottomRight(0,0,0) { } + +void ViewFrustum::setOrientation(const glm::quat& orientationAsQuaternion) { + glm::quat quat; + quat = quat * orientationAsQuaternion; + + // this is where the coordinate system is represented + const glm::vec3 IDENTITY_RIGHT = glm::vec3(-1.0f, 0.0f, 0.0f); + const glm::vec3 IDENTITY_UP = glm::vec3( 0.0f, 1.0f, 0.0f); + const glm::vec3 IDENTITY_FRONT = glm::vec3( 0.0f, 0.0f, 1.0f); + + glm::mat4 rotationMatrix = glm::mat4_cast(quat); + + _orientation = orientationAsQuaternion; + _right = glm::vec3(glm::vec4(IDENTITY_RIGHT, 0.0f) * rotationMatrix); + _up = glm::vec3(glm::vec4(IDENTITY_UP, 0.0f) * rotationMatrix); + _direction = glm::vec3(glm::vec4(IDENTITY_FRONT, 0.0f) * rotationMatrix); +} ///////////////////////////////////////////////////////////////////////////////////// // ViewFrustum::calculateViewFrustum() diff --git a/libraries/voxels/src/ViewFrustum.h b/libraries/voxels/src/ViewFrustum.h index 1ae33d55ad..1c61160566 100644 --- a/libraries/voxels/src/ViewFrustum.h +++ b/libraries/voxels/src/ViewFrustum.h @@ -21,6 +21,9 @@ private: // camera location/orientation attributes glm::vec3 _position; + glm::quat _orientation; + + // calculated for orientation glm::vec3 _direction; glm::vec3 _up; glm::vec3 _right; @@ -53,23 +56,23 @@ private: public: // setters for camera attributes - void setPosition (const glm::vec3& p) { _position = p; } - void setOrientation (const glm::vec3& d, const glm::vec3& u, const glm::vec3& r ) - { _direction = d; _up = u; _right = r; } + void setPosition (const glm::vec3& p) { _position = p; }; + void setOrientation (const glm::quat& orientationAsQuaternion); // getters for camera attributes - const glm::vec3& getPosition() const { return _position; }; - const glm::vec3& getDirection() const { return _direction; }; - const glm::vec3& getUp() const { return _up; }; - const glm::vec3& getRight() const { return _right; }; + const glm::vec3& getPosition() const { return _position; }; + const glm::quat& getOrientation() const { return _orientation; }; + const glm::vec3& getDirection() const { return _direction; }; + const glm::vec3& getUp() const { return _up; }; + const glm::vec3& getRight() const { return _right; }; // setters for lens attributes - void setFieldOfView ( float f ) { _fieldOfView = f; } - void setAspectRatio ( float a ) { _aspectRatio = a; } - void setNearClip ( float n ) { _nearClip = n; } - void setFarClip ( float f ) { _farClip = f; } - void setEyeOffsetPosition (const glm::vec3& p) { _eyeOffsetPosition = p; } - void setEyeOffsetOrientation (const glm::quat& o) { _eyeOffsetOrientation = o; } + void setFieldOfView ( float f ) { _fieldOfView = f; }; + void setAspectRatio ( float a ) { _aspectRatio = a; }; + void setNearClip ( float n ) { _nearClip = n; }; + void setFarClip ( float f ) { _farClip = f; }; + void setEyeOffsetPosition (const glm::vec3& p) { _eyeOffsetPosition = p; }; + void setEyeOffsetOrientation (const glm::quat& o) { _eyeOffsetOrientation = o; }; // getters for lens attributes diff --git a/voxel-server/src/VoxelAgentData.cpp b/voxel-server/src/VoxelAgentData.cpp index 0ca7778a94..acb185fb5f 100644 --- a/voxel-server/src/VoxelAgentData.cpp +++ b/voxel-server/src/VoxelAgentData.cpp @@ -50,7 +50,7 @@ bool VoxelAgentData::updateCurrentViewFrustum() { ViewFrustum newestViewFrustum; // get position and orientation details from the camera newestViewFrustum.setPosition(getCameraPosition()); - newestViewFrustum.setOrientation(getCameraDirection(), getCameraUp(), getCameraRight()); + newestViewFrustum.setOrientation(getCameraOrientation()); // Also make sure it's got the correct lens details from the camera newestViewFrustum.setFieldOfView(getCameraFov()); From 20917c37b86915d5f04338309f0aeb84ca635e24 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 27 May 2013 09:59:53 -0700 Subject: [PATCH 03/81] removed extra comment --- libraries/avatars/src/AvatarData.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index fa0a8d1e20..b5ef015c7b 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -108,7 +108,6 @@ int AvatarData::getBroadcastData(unsigned char* destinationBuffer) { memcpy(destinationBuffer, _chatMessage.data(), _chatMessage.size() * sizeof(char)); destinationBuffer += _chatMessage.size() * sizeof(char); - // voxel sending features... // voxel sending features... unsigned char wantItems = 0; if (_wantResIn) { setAtBit(wantItems,WANT_RESIN_AT_BIT); } From 06e98d2c43f2d78b67f54e279fbd2a1a8563728d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 27 May 2013 14:10:51 -0700 Subject: [PATCH 04/81] Optimize wire-format for AvatarData - moved HandState into semi-nibble in bitItems - moved KeyState into semi-nibble in bitItems - moved AudioLoudness into scaled float stored as byte - overall savings - 5 bytes --- interface/src/AvatarTouch.h | 2 +- libraries/avatars/src/AvatarData.cpp | 72 ++++++++++++++++------------ libraries/avatars/src/AvatarData.h | 12 ++++- libraries/shared/src/SharedUtil.cpp | 9 ++++ libraries/shared/src/SharedUtil.h | 4 ++ 5 files changed, 66 insertions(+), 33 deletions(-) diff --git a/interface/src/AvatarTouch.h b/interface/src/AvatarTouch.h index 2111c0ecf1..cc4d21ae82 100644 --- a/interface/src/AvatarTouch.h +++ b/interface/src/AvatarTouch.h @@ -12,7 +12,7 @@ enum AvatarHandState { - HAND_STATE_NULL = -1, + HAND_STATE_NULL = 0, HAND_STATE_OPEN, HAND_STATE_GRASPING, HAND_STATE_POINTING, diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index b5ef015c7b..1c126b7587 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -83,13 +83,8 @@ int AvatarData::getBroadcastData(unsigned char* destinationBuffer) { memcpy(destinationBuffer, &_headData->_lookAtPosition, sizeof(_headData->_lookAtPosition)); destinationBuffer += sizeof(_headData->_lookAtPosition); - // Hand State (0 = not grabbing, 1 = grabbing) - memcpy(destinationBuffer, &_handState, sizeof(char)); - destinationBuffer += sizeof(char); - // Instantaneous audio loudness (used to drive facial animation) - memcpy(destinationBuffer, &_audioLoudness, sizeof(float)); - destinationBuffer += sizeof(float); + destinationBuffer += packFloatToByte(destinationBuffer, std::min(MAX_AUDIO_LOUDNESS, _audioLoudness), MAX_AUDIO_LOUDNESS); // camera details memcpy(destinationBuffer, &_cameraPosition, sizeof(_cameraPosition)); @@ -100,20 +95,22 @@ int AvatarData::getBroadcastData(unsigned char* destinationBuffer) { destinationBuffer += packClipValueToTwoByte(destinationBuffer, _cameraNearClip); destinationBuffer += packClipValueToTwoByte(destinationBuffer, _cameraFarClip); - // key state - *destinationBuffer++ = _keyState; - // chat message *destinationBuffer++ = _chatMessage.size(); memcpy(destinationBuffer, _chatMessage.data(), _chatMessage.size() * sizeof(char)); destinationBuffer += _chatMessage.size() * sizeof(char); - // voxel sending features... - unsigned char wantItems = 0; - if (_wantResIn) { setAtBit(wantItems,WANT_RESIN_AT_BIT); } - if (_wantColor) { setAtBit(wantItems,WANT_COLOR_AT_BIT); } - if (_wantDelta) { setAtBit(wantItems,WANT_DELTA_AT_BIT); } - *destinationBuffer++ = wantItems; + // bitMask of less than byte wide items + unsigned char bitItems = 0; + if (_wantResIn) { setAtBit(bitItems,WANT_RESIN_AT_BIT); } + if (_wantColor) { setAtBit(bitItems,WANT_COLOR_AT_BIT); } + if (_wantDelta) { setAtBit(bitItems,WANT_DELTA_AT_BIT); } + + // key state + setSemiNibbleAt(bitItems,KEY_STATE_START_BIT,_keyState); + // hand state + setSemiNibbleAt(bitItems,HAND_STATE_START_BIT,_handState); + *destinationBuffer++ = bitItems; return destinationBuffer - bufferStart; } @@ -162,18 +159,13 @@ int AvatarData::parseData(unsigned char* sourceBuffer, int numBytes) { // Hand Position memcpy(&_handPosition, sourceBuffer, sizeof(float) * 3); sourceBuffer += sizeof(float) * 3; - + // Lookat Position memcpy(&_headData->_lookAtPosition, sourceBuffer, sizeof(_headData->_lookAtPosition)); sourceBuffer += sizeof(_headData->_lookAtPosition); - - // Hand State - memcpy(&_handState, sourceBuffer, sizeof(char)); - sourceBuffer += sizeof(char); - + // Instantaneous audio loudness (used to drive facial animation) - memcpy(&_audioLoudness, sourceBuffer, sizeof(float)); - sourceBuffer += sizeof(float); + sourceBuffer += unpackFloatFromByte(sourceBuffer, _audioLoudness, MAX_AUDIO_LOUDNESS); // camera details memcpy(&_cameraPosition, sourceBuffer, sizeof(_cameraPosition)); @@ -184,20 +176,23 @@ int AvatarData::parseData(unsigned char* sourceBuffer, int numBytes) { sourceBuffer += unpackClipValueFromTwoByte(sourceBuffer,_cameraNearClip); sourceBuffer += unpackClipValueFromTwoByte(sourceBuffer,_cameraFarClip); - // key state - _keyState = (KeyState)*sourceBuffer++; - // the rest is a chat message int chatMessageSize = *sourceBuffer++; _chatMessage = string((char*)sourceBuffer, chatMessageSize); sourceBuffer += chatMessageSize * sizeof(char); // voxel sending features... - unsigned char wantItems = 0; - wantItems = (unsigned char)*sourceBuffer++; - _wantResIn = oneAtBit(wantItems,WANT_RESIN_AT_BIT); - _wantColor = oneAtBit(wantItems,WANT_COLOR_AT_BIT); - _wantDelta = oneAtBit(wantItems,WANT_DELTA_AT_BIT); + unsigned char bitItems = 0; + bitItems = (unsigned char)*sourceBuffer++; + _wantResIn = oneAtBit(bitItems,WANT_RESIN_AT_BIT); + _wantColor = oneAtBit(bitItems,WANT_COLOR_AT_BIT); + _wantDelta = oneAtBit(bitItems,WANT_DELTA_AT_BIT); + + // key state, stored as a semi-nibble in the bitItems + _keyState = (KeyState)getSemiNibbleAt(bitItems,KEY_STATE_START_BIT); + + // hand state, stored as a semi-nibble in the bitItems + _handState = getSemiNibbleAt(bitItems,HAND_STATE_START_BIT); return sourceBuffer - startPosition; } @@ -310,3 +305,18 @@ int unpackClipValueFromTwoByte(unsigned char* buffer, float& clipValue) { } return sizeof(holder); } + +int packFloatToByte(unsigned char* buffer, float value, float scaleBy) { + unsigned char holder; + const float CONVERSION_RATIO = (255 / scaleBy); + holder = floorf(value * CONVERSION_RATIO); + memcpy(buffer, &holder, sizeof(holder)); + return sizeof(holder); +} + +int unpackFloatFromByte(unsigned char* buffer, float& value, float scaleBy) { + unsigned char holder; + memcpy(&holder, buffer, sizeof(holder)); + value = ((float)holder / (float) 255) * scaleBy; + return sizeof(holder); +} diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index d86cc6078b..04bc7e6ad5 100644 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -20,10 +20,15 @@ const int WANT_RESIN_AT_BIT = 0; const int WANT_COLOR_AT_BIT = 1; const int WANT_DELTA_AT_BIT = 2; +const int KEY_STATE_START_BIT = 3; // 4th and 5th bits +const int HAND_STATE_START_BIT = 5; // 6th and 7th bits + +const float MAX_AUDIO_LOUDNESS = 1000.0; // close enough for mouth animation + enum KeyState { - NO_KEY_DOWN, + NO_KEY_DOWN = 0, INSERT_KEY_DOWN, DELETE_KEY_DOWN }; @@ -157,4 +162,9 @@ int unpackFloatRatioFromTwoByte(unsigned char* buffer, float& ratio); int packClipValueToTwoByte(unsigned char* buffer, float clipValue); int unpackClipValueFromTwoByte(unsigned char* buffer, float& clipValue); +// Positive floats that don't need to be very precise +int packFloatToByte(unsigned char* buffer, float value, float scaleBy); +int unpackFloatFromByte(unsigned char* buffer, float& value, float scaleBy); + + #endif /* defined(__hifi__AvatarData__) */ diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index ca31cdd994..10967ea3e7 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -101,6 +101,15 @@ void setAtBit(unsigned char& byte, int bitIndex) { byte += (1 << (7 - bitIndex)); } +int getSemiNibbleAt(unsigned char& byte, int bitIndex) { + return (byte >> (7 - bitIndex) & 3); // semi-nibbles store 00, 01, 10, or 11 +} + +void setSemiNibbleAt(unsigned char& byte, int bitIndex, int value) { + assert(value <= 3 && value >= 0); + byte += ((value & 3) << (7 - bitIndex)); // semi-nibbles store 00, 01, 10, or 11 +} + void switchToResourcesParentIfRequired() { #ifdef __APPLE__ diff --git a/libraries/shared/src/SharedUtil.h b/libraries/shared/src/SharedUtil.h index 9d858f11e0..75c00c71f7 100644 --- a/libraries/shared/src/SharedUtil.h +++ b/libraries/shared/src/SharedUtil.h @@ -53,6 +53,10 @@ int numberOfOnes(unsigned char byte); bool oneAtBit(unsigned char byte, int bitIndex); void setAtBit(unsigned char& byte, int bitIndex); +int getSemiNibbleAt(unsigned char& byte, int bitIndex); +void setSemiNibbleAt(unsigned char& byte, int bitIndex, int value); + + void switchToResourcesParentIfRequired(); void loadRandomIdentifier(unsigned char* identifierBuffer, int numBytes); From b250289749bd8b0115e447d2193d2486c6e5b543 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 3 Jun 2013 21:41:23 -0700 Subject: [PATCH 05/81] removed debug --- voxel-server/src/main.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/voxel-server/src/main.cpp b/voxel-server/src/main.cpp index 098596f02e..f0c87f8ada 100644 --- a/voxel-server/src/main.cpp +++ b/voxel-server/src/main.cpp @@ -370,7 +370,6 @@ void deepestLevelVoxelDistributor(AgentList* agentList, // if after sending packets we've emptied our bag, then we want to remember that we've sent all // the voxels from the current view frustum if (agentData->nodeBag.isEmpty()) { -printf("agentData->nodeBag.isEmpty()...\n"); agentData->updateLastKnownViewFrustum(); agentData->setViewSent(true); } From 8f58f9f424203d825f22a18eff59f23f30978428 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 4 Jun 2013 10:48:45 -0700 Subject: [PATCH 06/81] merge cleanup --- interface/src/Application.cpp | 5 +---- libraries/voxels/src/VoxelTree.h | 4 +++- voxel-server/src/main.cpp | 2 +- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 3ce4d7b9f3..6a37fe6ae2 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1749,13 +1749,10 @@ void Application::loadViewFrustum(Camera& camera, ViewFrustum& viewFrustum) { float farClip = camera.getFarClip(); glm::quat rotation = camera.getRotation(); - glm::vec3 direction = rotation * AVATAR_FRONT; - glm::vec3 up = rotation * AVATAR_UP; - glm::vec3 right = rotation * AVATAR_RIGHT; // Set the viewFrustum up with the correct position and orientation of the camera viewFrustum.setPosition(position); - viewFrustum.setOrientation(o.getQuat()); + viewFrustum.setOrientation(rotation); // Also make sure it's got the correct lens details from the camera viewFrustum.setFieldOfView(fov); diff --git a/libraries/voxels/src/VoxelTree.h b/libraries/voxels/src/VoxelTree.h index b276b6e47f..fce051eda9 100644 --- a/libraries/voxels/src/VoxelTree.h +++ b/libraries/voxels/src/VoxelTree.h @@ -28,6 +28,7 @@ typedef enum {GRADIENT, RANDOM, NATURAL} creationMode; #define ACTUALLY_DELETE false #define COLLAPSE_EMPTY_TREE true #define DONT_COLLAPSE false +#define DONT_CHOP_LEVELS 0 class VoxelTree { public: @@ -71,7 +72,8 @@ public: int encodeTreeBitstream(int maxEncodeLevel, VoxelNode* node, unsigned char* outputBuffer, int availableBytes, VoxelNodeBag& bag, const ViewFrustum* viewFrustum, - bool includeColor = WANT_COLOR, bool includeExistsBits = WANT_EXISTS_BITS, int chopLevels = 0, + bool includeColor = WANT_COLOR, bool includeExistsBits = WANT_EXISTS_BITS, + int chopLevels = DONT_CHOP_LEVELS, bool deltaViewFrustum = false, const ViewFrustum* lastViewFrustum = NULL, double lastViewFrustumSent = 0) const; diff --git a/voxel-server/src/main.cpp b/voxel-server/src/main.cpp index ef9e7cd257..fe4276955b 100644 --- a/voxel-server/src/main.cpp +++ b/voxel-server/src/main.cpp @@ -313,7 +313,7 @@ void deepestLevelVoxelDistributor(AgentList* agentList, bytesWritten = randomTree.encodeTreeBitstream(INT_MAX, subTree, &tempOutputBuffer[0], MAX_VOXEL_PACKET_SIZE - 1, agentData->nodeBag, &agentData->getCurrentViewFrustum(), - agentData->getWantColor(), WANT_EXISTS_BITS, + agentData->getWantColor(), WANT_EXISTS_BITS, DONT_CHOP_LEVELS, wantDelta, lastViewFrustum, agentData->getLastViewSent()); if (agentData->getAvailable() >= bytesWritten) { From 93e5991c68c0b453eb71599b54c4b93a6db311f0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 5 Jun 2013 10:31:24 -0700 Subject: [PATCH 07/81] add markWithChangedTime() method as public method --- libraries/voxels/src/VoxelNode.cpp | 20 +++++++++----------- libraries/voxels/src/VoxelNode.h | 2 ++ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/libraries/voxels/src/VoxelNode.cpp b/libraries/voxels/src/VoxelNode.cpp index a9a1f4eb12..0a4d813ec7 100644 --- a/libraries/voxels/src/VoxelNode.cpp +++ b/libraries/voxels/src/VoxelNode.cpp @@ -46,9 +46,7 @@ void VoxelNode::init(unsigned char * octalCode) { _isDirty = true; _shouldRender = false; _isStagedForDeletion = false; - - _lastChanged = usecTimestampNow(); - + markWithChangedTime(); calculateAABox(); } @@ -68,7 +66,7 @@ void VoxelNode::setShouldRender(bool shouldRender) { if (shouldRender != _shouldRender) { _shouldRender = shouldRender; _isDirty = true; - _lastChanged = usecTimestampNow(); + markWithChangedTime(); } } @@ -92,7 +90,7 @@ void VoxelNode::deleteChildAtIndex(int childIndex) { delete _children[childIndex]; _children[childIndex] = NULL; _isDirty = true; - _lastChanged = usecTimestampNow(); + markWithChangedTime(); _childCount--; } } @@ -103,7 +101,7 @@ VoxelNode* VoxelNode::removeChildAtIndex(int childIndex) { if (_children[childIndex]) { _children[childIndex] = NULL; _isDirty = true; - _lastChanged = usecTimestampNow(); + markWithChangedTime(); _childCount--; } return returnedChild; @@ -113,7 +111,7 @@ void VoxelNode::addChildAtIndex(int childIndex) { if (!_children[childIndex]) { _children[childIndex] = new VoxelNode(childOctalCode(_octalCode, childIndex)); _isDirty = true; - _lastChanged = usecTimestampNow(); + markWithChangedTime(); _childCount++; } } @@ -141,7 +139,7 @@ void VoxelNode::safeDeepDeleteChildAtIndex(int childIndex, bool& stagedForDeleti deleteChildAtIndex(childIndex); _isDirty = true; } - _lastChanged = usecTimestampNow(); + markWithChangedTime(); } } @@ -185,7 +183,7 @@ void VoxelNode::setFalseColor(colorPart red, colorPart green, colorPart blue) { _currentColor[2] = blue; _currentColor[3] = 1; // XXXBHG - False colors are always considered set _isDirty = true; - _lastChanged = usecTimestampNow(); + markWithChangedTime(); } } @@ -197,7 +195,7 @@ void VoxelNode::setFalseColored(bool isFalseColored) { } _falseColored = isFalseColored; _isDirty = true; - _lastChanged = usecTimestampNow(); + markWithChangedTime(); } }; @@ -211,7 +209,7 @@ void VoxelNode::setColor(const nodeColor& color) { memcpy(&_currentColor,&color,sizeof(nodeColor)); } _isDirty = true; - _lastChanged = usecTimestampNow(); + markWithChangedTime(); } } #endif diff --git a/libraries/voxels/src/VoxelNode.h b/libraries/voxels/src/VoxelNode.h index ca00260ace..39fc38925c 100644 --- a/libraries/voxels/src/VoxelNode.h +++ b/libraries/voxels/src/VoxelNode.h @@ -9,6 +9,7 @@ #ifndef __hifi__VoxelNode__ #define __hifi__VoxelNode__ +#include #include "AABox.h" #include "ViewFrustum.h" #include "VoxelConstants.h" @@ -78,6 +79,7 @@ public: bool isDirty() const { return _isDirty; }; void clearDirtyBit() { _isDirty = false; }; bool hasChangedSince(double time) const { return (_lastChanged > time); }; + void markWithChangedTime() { _lastChanged = usecTimestampNow(); }; glBufferIndex getBufferIndex() const { return _glBufferIndex; }; bool isKnownBufferIndex() const { return (_glBufferIndex != GLBUFFER_INDEX_UNKNOWN); }; From 00c29e5edafc547aff3e931e198a4a8ee972d1f3 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 5 Jun 2013 10:32:36 -0700 Subject: [PATCH 08/81] changed deleteVoxelCodeFromTree() to use recursion to allow for proper unwinding, updating of parent path --- libraries/voxels/src/VoxelTree.cpp | 132 +++++++++++++++++++++-------- libraries/voxels/src/VoxelTree.h | 3 +- 2 files changed, 99 insertions(+), 36 deletions(-) diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index 904826f440..e6960bf159 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -264,61 +264,123 @@ void VoxelTree::deleteVoxelAt(float x, float y, float z, float s, bool stage) { reaverageVoxelColors(rootNode); } +class DeleteVoxelCodeFromTreeArgs { +public: + bool stage; + bool collapseEmptyTrees; + unsigned char* codeBuffer; + int lengthOfCode; + bool deleteLastChild; + bool pathChanged; +}; // Note: uses the codeColorBuffer format, but the color's are ignored, because // this only finds and deletes the node from the tree. void VoxelTree::deleteVoxelCodeFromTree(unsigned char* codeBuffer, bool stage, bool collapseEmptyTrees) { - VoxelNode* parentNode = NULL; - VoxelNode* nodeToDelete = nodeForOctalCode(rootNode, codeBuffer, &parentNode); - // If the node exists... - int lengthInBytes = bytesRequiredForCodeLength(*codeBuffer); // includes octet count, not color! - // if the code we got back matches our target, then we know we can actually delete it - if (memcmp(nodeToDelete->getOctalCode(), codeBuffer, lengthInBytes) == 0) { - if (parentNode) { - int childIndex = branchIndexWithDescendant(parentNode->getOctalCode(), codeBuffer); - if (stage) { - nodeToDelete->stageForDeletion(); - } else { - parentNode->deleteChildAtIndex(childIndex); - if (_shouldReaverage) { - parentNode->setColorFromAverageOfChildren(); - } - } + // recurse the tree while decoding the codeBuffer, once you find the node in question, recurse + // back and implement color reaveraging, and marking of lastChanged + DeleteVoxelCodeFromTreeArgs args; + args.stage = stage; + args.collapseEmptyTrees = collapseEmptyTrees; + args.codeBuffer = codeBuffer; + args.lengthOfCode = numberOfThreeBitSectionsInCode(codeBuffer); + args.deleteLastChild = false; + args.pathChanged = false; + + VoxelNode* node = rootNode; + deleteVoxelCodeFromTreeRecursion(node, &args); +} - // If we're in collapseEmptyTrees mode, and we're the last child of this parent, then delete the parent. - // This will collapse the empty tree above us. - if (collapseEmptyTrees && parentNode->getChildCount() == 0) { - // Can't delete the root this way. - if (parentNode != rootNode) { - deleteVoxelCodeFromTree(parentNode->getOctalCode(), stage, collapseEmptyTrees); - } - } - _isDirty = true; - } - } else if (nodeToDelete->isLeaf()) { +void VoxelTree::deleteVoxelCodeFromTreeRecursion(VoxelNode* node, void* extraData) { + DeleteVoxelCodeFromTreeArgs* args = (DeleteVoxelCodeFromTreeArgs*)extraData; + + int lengthOfNodeCode = numberOfThreeBitSectionsInCode(node->getOctalCode()); + + // Since we traverse the tree in code order, we know that if our code + // matches, then we've reached our target node. + if (lengthOfNodeCode == args->lengthOfCode) { + // we've reached our target, depending on how we're called we may be able to operate on it + // if we're in "stage" mode, then we can could have the node staged, otherwise we can't really delete + // it here, we need to recurse up, and delete it there. So we handle these cases the same to keep + // the logic consistent. + args->deleteLastChild = true; + return; + } + + // Ok, we know we haven't reached our target node yet, so keep looking + int childIndex = branchIndexWithDescendant(node->getOctalCode(), args->codeBuffer); + VoxelNode* childNode = node->getChildAtIndex(childIndex); + + // If there is no child at the target location, then it likely means we were asked to delete a child out + // of a larger leaf voxel. We support this by breaking up the parent voxel into smaller pieces. + if (!childNode) { // we need to break up ancestors until we get to the right level - VoxelNode* ancestorNode = nodeToDelete; + VoxelNode* ancestorNode = node; while (true) { - int index = branchIndexWithDescendant(ancestorNode->getOctalCode(), codeBuffer); - for (int i = 0; i < 8; i++) { + int index = branchIndexWithDescendant(ancestorNode->getOctalCode(), args->codeBuffer); + for (int i = 0; i < NUMBER_OF_CHILDREN; i++) { if (i != index) { ancestorNode->addChildAtIndex(i); - if (nodeToDelete->isColored()) { - ancestorNode->getChildAtIndex(i)->setColor(nodeToDelete->getColor()); + if (node->isColored()) { + ancestorNode->getChildAtIndex(i)->setColor(node->getColor()); } } } - if (*ancestorNode->getOctalCode() == *codeBuffer - 1) { + int lengthOfancestorNode = numberOfThreeBitSectionsInCode(ancestorNode->getOctalCode()); + + // If we've reached the parent of the target, then stop breaking up children + if (lengthOfancestorNode == (args->lengthOfCode - 1)) { break; } ancestorNode->addChildAtIndex(index); ancestorNode = ancestorNode->getChildAtIndex(index); - if (nodeToDelete->isColored()) { - ancestorNode->setColor(nodeToDelete->getColor()); + if (node->isColored()) { + ancestorNode->setColor(node->getColor()); } } _isDirty = true; + args->pathChanged = true; + + // ends recursion, unwinds up stack + return; + } + + // recurse... + deleteVoxelCodeFromTreeRecursion(childNode, args); + + // If the lower level determined it needs to be deleted, then we should delete now. + if (args->deleteLastChild) { + if (args->stage) { + childNode->stageForDeletion(); + } else { + node->deleteChildAtIndex(childIndex); // note: this will track dirtiness and lastChanged for this node + if (_shouldReaverage) { + node->setColorFromAverageOfChildren(); + } + } + + // track our tree dirtiness + _isDirty = true; + + // track that path has changed + args->pathChanged = true; + + // If we're in collapseEmptyTrees mode, and this was the last child of this node, then we also want + // to delete this node. This will collapse the empty tree above us. + if (args->collapseEmptyTrees && node->getChildCount() == 0) { + // Can't delete the root this way. + if (node == rootNode) { + args->deleteLastChild = false; // reset so that further up the unwinding chain we don't do anything + } + } else { + args->deleteLastChild = false; // reset so that further up the unwinding chain we don't do anything + } + } + + // If the lower level did some work, then we need to track our lastChanged status. + if (args->pathChanged) { + node->markWithChangedTime(); } } diff --git a/libraries/voxels/src/VoxelTree.h b/libraries/voxels/src/VoxelTree.h index fce051eda9..db7ad55ef7 100644 --- a/libraries/voxels/src/VoxelTree.h +++ b/libraries/voxels/src/VoxelTree.h @@ -10,7 +10,6 @@ #define __hifi__VoxelTree__ #include "SimpleMovingAverage.h" - #include "ViewFrustum.h" #include "VoxelNode.h" #include "VoxelNodeBag.h" @@ -104,6 +103,8 @@ public: void copyFromTreeIntoSubTree(VoxelTree* sourceTree, VoxelNode* destinationNode); private: + void deleteVoxelCodeFromTreeRecursion(VoxelNode* node, void* extraData); + int encodeTreeBitstreamRecursion(int maxEncodeLevel, int& currentEncodeLevel, VoxelNode* node, unsigned char* outputBuffer, int availableBytes, VoxelNodeBag& bag, const ViewFrustum* viewFrustum, bool includeColor, bool includeExistsBits, From 736e38ceb0e03995148dcfb5f2575e68ffc3cdaf Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 7 Jun 2013 10:04:30 -0700 Subject: [PATCH 09/81] fix merge issue --- libraries/voxels/src/VoxelNode.h | 2 -- libraries/voxels/src/VoxelTree.cpp | 10 ---------- 2 files changed, 12 deletions(-) diff --git a/libraries/voxels/src/VoxelNode.h b/libraries/voxels/src/VoxelNode.h index adb0744e10..9250d76594 100644 --- a/libraries/voxels/src/VoxelNode.h +++ b/libraries/voxels/src/VoxelNode.h @@ -41,8 +41,6 @@ private: void init(unsigned char * octalCode); - double _lastChanged; - public: VoxelNode(); // root node constructor VoxelNode(unsigned char * octalCode); // regular constructor diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index cd3c0565a5..bc4d7569bf 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -274,16 +274,6 @@ public: bool pathChanged; }; -class DeleteVoxelCodeFromTreeArgs { -public: - bool stage; - bool collapseEmptyTrees; - unsigned char* codeBuffer; - int lengthOfCode; - bool deleteLastChild; - bool pathChanged; -}; - // Note: uses the codeColorBuffer format, but the color's are ignored, because // this only finds and deletes the node from the tree. void VoxelTree::deleteVoxelCodeFromTree(unsigned char* codeBuffer, bool stage, bool collapseEmptyTrees) { From e6b751e53840b2caad5203b4068146a2866c41a4 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Fri, 12 Jul 2013 14:32:14 -0700 Subject: [PATCH 10/81] more work on particle system --- interface/src/Application.cpp | 4 +- interface/src/ParticleSystem.cpp | 178 +++++++++++++++++++++---------- interface/src/ParticleSystem.h | 17 ++- 3 files changed, 138 insertions(+), 61 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 6f70c89f3b..591889a83a 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -73,7 +73,7 @@ using namespace std; static char STAR_FILE[] = "https://s3-us-west-1.amazonaws.com/highfidelity/stars.txt"; static char STAR_CACHE_FILE[] = "cachedStars.txt"; -static const bool TESTING_PARTICLE_SYSTEM = false; +static const bool TESTING_PARTICLE_SYSTEM = true; static const int BANDWIDTH_METER_CLICK_MAX_DRAG_LENGTH = 6; // farther dragged clicks are ignored @@ -2010,6 +2010,8 @@ void Application::update(float deltaTime) { #endif if (TESTING_PARTICLE_SYSTEM) { + glm::vec3 particleEmitterPosition = glm::vec3(5.0f, 1.0f, 5.0f); + _particleSystem.setEmitterPosition(0, particleEmitterPosition); _particleSystem.simulate(deltaTime); } } diff --git a/interface/src/ParticleSystem.cpp b/interface/src/ParticleSystem.cpp index 3c27f3a8df..383f3eeecb 100644 --- a/interface/src/ParticleSystem.cpp +++ b/interface/src/ParticleSystem.cpp @@ -8,59 +8,91 @@ #include #include "InterfaceConfig.h" #include - #include "ParticleSystem.h" +#include "Application.h" ParticleSystem::ParticleSystem() { - _numberOfParticles = 1500; - assert(_numberOfParticles <= MAX_PARTICLES); - - _bounce = 0.9f; - _timer = 0.0f; - _airFriction = 6.0f; - _jitter = 0.1f; - _homeAttraction = 0.0f; - _tornadoForce = 0.0f; - _neighborAttraction = 0.02f; - _neighborRepulsion = 0.9f; - _tornadoAxis = glm::normalize(glm::vec3(0.1f, 1.0f, 0.1f)); - _home = glm::vec3(5.0f, 1.0f, 5.0f); - - _TEST_bigSphereRadius = 0.5f; + _gravity = 0.005; + _numEmitters = 1; + _bounce = 0.9f; + _timer = 0.0f; + _airFriction = 6.0f; + _jitter = 0.1f; + _homeAttraction = 0.0f; + _tornadoForce = 0.0f; + _neighborAttraction = 0.02f; + _neighborRepulsion = 0.9f; + _TEST_bigSphereRadius = 0.5f; _TEST_bigSpherePosition = glm::vec3( 5.0f, _TEST_bigSphereRadius, 5.0f); - - for (unsigned int p = 0; p < _numberOfParticles; p++) { - _particle[p].position = _home; - _particle[p].velocity = glm::vec3(0.0f, 0.0f, 0.0f); + _numParticles = 1500; + + for (unsigned int e = 0; e < _numEmitters; e++) { + + _emitter[e].position = glm::vec3(0.0f, 0.0f, 0.0f); + _emitter[e].rotation = glm::quat(); + _emitter[e].right = IDENTITY_RIGHT; + _emitter[e].up = IDENTITY_UP; + _emitter[e].front = IDENTITY_FRONT; + }; + + for (unsigned int p = 0; p < _numParticles; p++) { - float radian = ((float)p / (float)_numberOfParticles) * PI_TIMES_TWO; + float radian = ((float)p / (float)_numParticles) * PI_TIMES_TWO; float wave = sinf(radian); float red = 0.5f + 0.5f * wave; float green = 0.3f + 0.3f * wave; float blue = 0.2f - 0.2f * wave; - _particle[p].color = glm::vec3(red, green, blue); - _particle[p].age = 0.0f; - _particle[p].radius = 0.01f; + _particle[p].color = glm::vec3(red, green, blue); + _particle[p].age = 0.0f; + _particle[p].radius = 0.01f; + _particle[p].emitterIndex = 0; + _particle[p].position = glm::vec3(0.0f, 0.0f, 0.0f); + _particle[p].velocity = glm::vec3(0.0f, 0.0f, 0.0f); } + + assert(_numParticles <= MAX_PARTICLES); + assert(_numEmitters <= MAX_EMITTERS ); } + void ParticleSystem::simulate(float deltaTime) { - runSpecialEffectsTest(deltaTime); - - for (unsigned int p = 0; p < _numberOfParticles; p++) { + // update emitters + for (unsigned int e = 0; e < _numEmitters; e++) { + updateEmitter(e, deltaTime); + } + + // update particles + for (unsigned int p = 0; p < _numParticles; p++) { updateParticle(p, deltaTime); } + + // apply special effects + runSpecialEffectsTest(deltaTime); } +void ParticleSystem::updateEmitter(int e, float deltaTime) { + _emitter[e].front = _emitter[e].rotation * IDENTITY_FRONT; + _emitter[e].right = _emitter[e].rotation * IDENTITY_RIGHT; + _emitter[e].up = _emitter[e].rotation * IDENTITY_UP; +} void ParticleSystem::runSpecialEffectsTest(float deltaTime) { - + _timer += deltaTime; + + glm::vec3 tilt = glm::vec3 + ( + 30.0f * sinf( _timer * 0.55f ), + 0.0f, + 30.0f * cosf( _timer * 0.75f ) + ); + + _emitter[0].rotation = glm::quat(glm::radians(tilt)); _gravity = 0.01f + 0.01f * sinf( _timer * 0.52f ); _airFriction = 3.0f + 2.0f * sinf( _timer * 0.32f ); @@ -69,13 +101,6 @@ void ParticleSystem::runSpecialEffectsTest(float deltaTime) { _tornadoForce = 0.0f + 0.03f * sinf( _timer * 0.7f ); _neighborAttraction = 0.1f + 0.1f * cosf( _timer * 0.8f ); _neighborRepulsion = 0.4f + 0.3f * sinf( _timer * 0.4f ); - - _tornadoAxis = glm::vec3 - ( - 0.0f + 0.5f * sinf( _timer * 0.55f ), - 1.0f, - 0.0f + 0.5f * cosf( _timer * 0.75f ) - ); } @@ -95,12 +120,12 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { // apply attraction to home position - glm::vec3 vectorToHome = _home - _particle[p].position; + glm::vec3 vectorToHome = _emitter[_particle[p].emitterIndex].position - _particle[p].position; _particle[p].velocity += vectorToHome * _homeAttraction * deltaTime; // apply neighbor attraction int neighbor = p + 1; - if (neighbor == _numberOfParticles ) { + if (neighbor == _numParticles ) { neighbor = 0; } glm::vec3 vectorToNeighbor = _particle[p].position - _particle[neighbor].position; @@ -113,8 +138,9 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { } // apply tornado force - glm::vec3 tornadoDirection = glm::cross(vectorToHome, _tornadoAxis); - _particle[p].velocity += tornadoDirection * _tornadoForce * deltaTime; + //glm::vec3 tornadoDirection = glm::cross(vectorToHome, _emitter[_particle[p].emitterIndex].up); + //_particle[p].velocity += tornadoDirection * _tornadoForce * deltaTime; + //_particle[p].velocity += _emitter[_particle[p].emitterIndex].up * _tornadoForce * deltaTime; // apply air friction float drag = 1.0 - _airFriction * deltaTime; @@ -155,29 +181,69 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { void ParticleSystem::render() { - for (unsigned int p = 0; p < _numberOfParticles; p++) { - glColor3f(_particle[p].color.x, _particle[p].color.y, _particle[p].color.z); - glPushMatrix(); - glTranslatef(_particle[p].position.x, _particle[p].position.y, _particle[p].position.z); - glutSolidSphere(_particle[p].radius, 6, 6); - glPopMatrix(); - - // render velocity lines - glColor4f( _particle[p].color.x, _particle[p].color.y, _particle[p].color.z, 0.5f); - glm::vec3 end = _particle[p].position - _particle[p].velocity * 2.0f; - glBegin(GL_LINES); - glVertex3f(_particle[p].position.x, _particle[p].position.y, _particle[p].position.z); - glVertex3f(end.x, end.y, end.z); - - glEnd(); - + // render the emitters + for (unsigned int e = 0; e < _numEmitters; e++) { + renderEmitter(e, 0.2f); + }; + + // render the particles + for (unsigned int p = 0; p < _numParticles; p++) { + renderParticle(p); } } +void ParticleSystem::renderParticle(int p) { + + glColor3f(_particle[p].color.x, _particle[p].color.y, _particle[p].color.z); + glPushMatrix(); + glTranslatef(_particle[p].position.x, _particle[p].position.y, _particle[p].position.z); + glutSolidSphere(_particle[p].radius, 6, 6); + glPopMatrix(); + + // render velocity lines + glColor4f( _particle[p].color.x, _particle[p].color.y, _particle[p].color.z, 0.5f); + glm::vec3 end = _particle[p].position - _particle[p].velocity * 2.0f; + glBegin(GL_LINES); + glVertex3f(_particle[p].position.x, _particle[p].position.y, _particle[p].position.z); + glVertex3f(end.x, end.y, end.z); + + glEnd(); +} + + + +void ParticleSystem::renderEmitter(int e, float size) { + + glm::vec3 r = _emitter[e].right * size; + glm::vec3 u = _emitter[e].up * size; + glm::vec3 f = _emitter[e].front * size; + + glLineWidth(2.0f); + + glColor3f(0.8f, 0.4, 0.4); + glBegin(GL_LINES); + glVertex3f(_emitter[e].position.x, _emitter[e].position.y, _emitter[e].position.z); + glVertex3f(_emitter[e].position.x + r.x, _emitter[e].position.y + r.y, _emitter[e].position.z + r.z); + glEnd(); + + glColor3f(0.4f, 0.8, 0.4); + glBegin(GL_LINES); + glVertex3f(_emitter[e].position.x, _emitter[e].position.y, _emitter[e].position.z); + glVertex3f(_emitter[e].position.x + u.x, _emitter[e].position.y + u.y, _emitter[e].position.z + u.z); + glEnd(); + + glColor3f(0.4f, 0.4, 0.8); + glBegin(GL_LINES); + glVertex3f(_emitter[e].position.x, _emitter[e].position.y, _emitter[e].position.z); + glVertex3f(_emitter[e].position.x + f.x, _emitter[e].position.y + f.y, _emitter[e].position.z + f.z); + glEnd(); +} + + + - diff --git a/interface/src/ParticleSystem.h b/interface/src/ParticleSystem.h index 38eb0a1777..79dfeb4752 100644 --- a/interface/src/ParticleSystem.h +++ b/interface/src/ParticleSystem.h @@ -9,6 +9,8 @@ #ifndef hifi_ParticleSystem_h #define hifi_ParticleSystem_h +#include + const int MAX_PARTICLES = 5000; const int MAX_EMITTERS = 10; @@ -16,6 +18,7 @@ class ParticleSystem { public: ParticleSystem(); + void setEmitterPosition(int e, glm::vec3 position) { _emitter[e].position = position; } void simulate(float deltaTime); void render(); @@ -27,11 +30,15 @@ private: glm::vec3 color; float age; float radius; + int emitterIndex; }; struct Emitter { glm::vec3 position; - glm::vec3 direction; + glm::quat rotation; + glm::vec3 right; + glm::vec3 up; + glm::vec3 front; }; float _bounce; @@ -39,9 +46,8 @@ private: float _timer; Emitter _emitter[MAX_EMITTERS]; Particle _particle[MAX_PARTICLES]; - int _numberOfParticles; - glm::vec3 _home; - glm::vec3 _tornadoAxis; + int _numParticles; + int _numEmitters; float _airFriction; float _jitter; float _homeAttraction; @@ -52,8 +58,11 @@ private: glm::vec3 _TEST_bigSpherePosition; // private methods + void updateEmitter(int e, float deltaTime); void updateParticle(int index, float deltaTime); void runSpecialEffectsTest(float deltaTime); + void renderEmitter(int emitterIndex, float size); + void renderParticle(int p); }; #endif From 3649c89c1292cae62c66eac3f13ba78f10a5c790 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Fri, 12 Jul 2013 16:19:31 -0700 Subject: [PATCH 11/81] more developing on the API for the particle system --- interface/src/Application.cpp | 28 +++++-- interface/src/Application.h | 1 + interface/src/ParticleSystem.cpp | 137 +++++++++++++++++++++---------- interface/src/ParticleSystem.h | 16 ++-- 4 files changed, 127 insertions(+), 55 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 591889a83a..209282b926 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -172,6 +172,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : _frameCount(0), _fps(120.0f), _justStarted(true), + _particleSystemInitialized(false), _wantToKillLocalVoxels(false), _frustumDrawingMode(FRUSTUM_DRAW_MODE_ALL), _viewFrustumOffsetYaw(-135.0), @@ -1749,9 +1750,10 @@ void Application::init() { _palette.addTool(&_swatch); _palette.addAction(_colorVoxelMode, 0, 2); _palette.addAction(_eyedropperMode, 0, 3); - _palette.addAction(_selectVoxelMode, 0, 4); + _palette.addAction(_selectVoxelMode, 0, 4); } + const float MAX_AVATAR_EDIT_VELOCITY = 1.0f; const float MAX_VOXEL_EDIT_DISTANCE = 20.0f; const float HEAD_SPHERE_RADIUS = 0.07; @@ -2010,9 +2012,23 @@ void Application::update(float deltaTime) { #endif if (TESTING_PARTICLE_SYSTEM) { - glm::vec3 particleEmitterPosition = glm::vec3(5.0f, 1.0f, 5.0f); - _particleSystem.setEmitterPosition(0, particleEmitterPosition); - _particleSystem.simulate(deltaTime); + if (_particleSystemInitialized) { + _particleSystem.simulate(deltaTime); + } else { + int coolDemoEmitter = _particleSystem.addEmitter(); + + if (coolDemoEmitter != -1) { + glm::vec3 particleEmitterPosition = glm::vec3(5.0f, 1.3f, 5.0f); + _particleSystem.setEmitterPosition(coolDemoEmitter, particleEmitterPosition); + _particleSystem.emitParticlesNow(coolDemoEmitter, 1500); + } + + glm::vec3 collisionSpherePosition = glm::vec3( 5.0f, 0.5f, 5.0f ); + float collisionSphereRadius = 0.5f; + _particleSystem.setCollisionSphere(collisionSpherePosition, collisionSphereRadius); + _particleSystemInitialized = true; + _particleSystem.useOrangeBlueColorPalette(); + } } } @@ -2459,7 +2475,9 @@ void Application::displaySide(Camera& whichCamera) { } if (TESTING_PARTICLE_SYSTEM) { - _particleSystem.render(); + if (_particleSystemInitialized) { + _particleSystem.render(); + } } // Render the world box diff --git a/interface/src/Application.h b/interface/src/Application.h index c6bbd4eec2..37a8b40964 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -278,6 +278,7 @@ private: timeval _timerStart, _timerEnd; timeval _lastTimeUpdated; bool _justStarted; + bool _particleSystemInitialized; Stars _stars; diff --git a/interface/src/ParticleSystem.cpp b/interface/src/ParticleSystem.cpp index 383f3eeecb..0e762fdb0e 100644 --- a/interface/src/ParticleSystem.cpp +++ b/interface/src/ParticleSystem.cpp @@ -13,22 +13,22 @@ ParticleSystem::ParticleSystem() { - _gravity = 0.005; - _numEmitters = 1; - _bounce = 0.9f; - _timer = 0.0f; - _airFriction = 6.0f; - _jitter = 0.1f; - _homeAttraction = 0.0f; - _tornadoForce = 0.0f; - _neighborAttraction = 0.02f; - _neighborRepulsion = 0.9f; - _TEST_bigSphereRadius = 0.5f; - _TEST_bigSpherePosition = glm::vec3( 5.0f, _TEST_bigSphereRadius, 5.0f); - _numParticles = 1500; - - for (unsigned int e = 0; e < _numEmitters; e++) { + _gravity = 0.005; + _numEmitters = 0; + _bounce = 0.9f; + _timer = 0.0f; + _airFriction = 6.0f; + _jitter = 0.1f; + _homeAttraction = 0.0f; + _tornadoForce = 0.0f; + _neighborAttraction = 0.02f; + _neighborRepulsion = 0.9f; + _collisionSphereRadius = 0.0f; + _collisionSpherePosition = glm::vec3(0.0f, 0.0f, 0.0f); + _numParticles = 0; + _usingCollisionSphere = false; + for (unsigned int e = 0; e < MAX_EMITTERS; e++) { _emitter[e].position = glm::vec3(0.0f, 0.0f, 0.0f); _emitter[e].rotation = glm::quat(); _emitter[e].right = IDENTITY_RIGHT; @@ -36,25 +36,25 @@ ParticleSystem::ParticleSystem() { _emitter[e].front = IDENTITY_FRONT; }; - for (unsigned int p = 0; p < _numParticles; p++) { - - float radian = ((float)p / (float)_numParticles) * PI_TIMES_TWO; - float wave = sinf(radian); - - float red = 0.5f + 0.5f * wave; - float green = 0.3f + 0.3f * wave; - float blue = 0.2f - 0.2f * wave; - - _particle[p].color = glm::vec3(red, green, blue); + for (unsigned int p = 0; p < MAX_PARTICLES; p++) { + _particle[p].alive = false; _particle[p].age = 0.0f; _particle[p].radius = 0.01f; _particle[p].emitterIndex = 0; _particle[p].position = glm::vec3(0.0f, 0.0f, 0.0f); _particle[p].velocity = glm::vec3(0.0f, 0.0f, 0.0f); + } +} + + +int ParticleSystem::addEmitter() { + _numEmitters ++; + + if (_numEmitters > MAX_EMITTERS) { + return -1; } - assert(_numParticles <= MAX_PARTICLES); - assert(_numEmitters <= MAX_EMITTERS ); + return _numEmitters - 1; } @@ -67,9 +67,11 @@ void ParticleSystem::simulate(float deltaTime) { // update particles for (unsigned int p = 0; p < _numParticles; p++) { - updateParticle(p, deltaTime); + if (_particle[p].alive) { + updateParticle(p, deltaTime); + } } - + // apply special effects runSpecialEffectsTest(deltaTime); } @@ -81,6 +83,40 @@ void ParticleSystem::updateEmitter(int e, float deltaTime) { _emitter[e].up = _emitter[e].rotation * IDENTITY_UP; } + + +void ParticleSystem::emitParticlesNow(int e, int num) { + + _numParticles = num; + + if (_numParticles > MAX_PARTICLES) { + _numParticles = MAX_PARTICLES; + } + + for (unsigned int p = 0; p < num; p++) { + _particle[p].alive = true; + _particle[p].position = _emitter[e].position; + } +} + +void ParticleSystem::useOrangeBlueColorPalette() { + + for (unsigned int p = 0; p < _numParticles; p++) { + + float radian = ((float)p / (float)_numParticles) * PI_TIMES_TWO; + float wave = sinf(radian); + float red = 0.5f + 0.5f * wave; + float green = 0.3f + 0.3f * wave; + float blue = 0.2f - 0.2f * wave; + _particle[p].color = glm::vec3(red, green, blue); + } +} + + + + + + void ParticleSystem::runSpecialEffectsTest(float deltaTime) { _timer += deltaTime; @@ -93,14 +129,18 @@ void ParticleSystem::runSpecialEffectsTest(float deltaTime) { ); _emitter[0].rotation = glm::quat(glm::radians(tilt)); - - _gravity = 0.01f + 0.01f * sinf( _timer * 0.52f ); - _airFriction = 3.0f + 2.0f * sinf( _timer * 0.32f ); + + _gravity = 0.0f + 0.02f * sinf( _timer * 0.52f ); + _airFriction = 3.0f + 1.0f * sinf( _timer * 0.32f ); _jitter = 0.05f + 0.05f * sinf( _timer * 0.42f ); _homeAttraction = 0.01f + 0.01f * cosf( _timer * 0.6f ); _tornadoForce = 0.0f + 0.03f * sinf( _timer * 0.7f ); _neighborAttraction = 0.1f + 0.1f * cosf( _timer * 0.8f ); _neighborRepulsion = 0.4f + 0.3f * sinf( _timer * 0.4f ); + + if (_gravity < 0.0f) { + _gravity = 0.0f; + } } @@ -118,7 +158,6 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { -_jitter * ONE_HALF + _jitter * randFloat() ) * deltaTime; - // apply attraction to home position glm::vec3 vectorToHome = _emitter[_particle[p].emitterIndex].position - _particle[p].position; _particle[p].velocity += vectorToHome * _homeAttraction * deltaTime; @@ -138,9 +177,8 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { } // apply tornado force - //glm::vec3 tornadoDirection = glm::cross(vectorToHome, _emitter[_particle[p].emitterIndex].up); - //_particle[p].velocity += tornadoDirection * _tornadoForce * deltaTime; - //_particle[p].velocity += _emitter[_particle[p].emitterIndex].up * _tornadoForce * deltaTime; + glm::vec3 tornadoDirection = glm::cross(vectorToHome, _emitter[_particle[p].emitterIndex].up); + _particle[p].velocity += tornadoDirection * _tornadoForce * deltaTime; // apply air friction float drag = 1.0 - _airFriction * deltaTime; @@ -166,18 +204,25 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { } // collision with sphere - glm::vec3 vectorToSphereCenter = _TEST_bigSpherePosition - _particle[p].position; - float distanceToSphereCenter = glm::length(vectorToSphereCenter); - float combinedRadius = _TEST_bigSphereRadius + _particle[p].radius; - if (distanceToSphereCenter < combinedRadius) { - - if (distanceToSphereCenter > 0.0f){ - glm::vec3 directionToSphereCenter = vectorToSphereCenter / distanceToSphereCenter; - _particle[p].position = _TEST_bigSpherePosition - directionToSphereCenter * combinedRadius; + if (_usingCollisionSphere) { + glm::vec3 vectorToSphereCenter = _collisionSpherePosition - _particle[p].position; + float distanceToSphereCenter = glm::length(vectorToSphereCenter); + float combinedRadius = _collisionSphereRadius + _particle[p].radius; + if (distanceToSphereCenter < combinedRadius) { + + if (distanceToSphereCenter > 0.0f){ + glm::vec3 directionToSphereCenter = vectorToSphereCenter / distanceToSphereCenter; + _particle[p].position = _collisionSpherePosition - directionToSphereCenter * combinedRadius; + } } } } +void ParticleSystem::setCollisionSphere(glm::vec3 position, float radius) { + _usingCollisionSphere = true; + _collisionSpherePosition = position; + _collisionSphereRadius = radius; +} void ParticleSystem::render() { @@ -188,7 +233,9 @@ void ParticleSystem::render() { // render the particles for (unsigned int p = 0; p < _numParticles; p++) { - renderParticle(p); + if (_particle[p].alive) { + renderParticle(p); + } } } diff --git a/interface/src/ParticleSystem.h b/interface/src/ParticleSystem.h index 79dfeb4752..701d1c85b7 100644 --- a/interface/src/ParticleSystem.h +++ b/interface/src/ParticleSystem.h @@ -18,13 +18,18 @@ class ParticleSystem { public: ParticleSystem(); - void setEmitterPosition(int e, glm::vec3 position) { _emitter[e].position = position; } - void simulate(float deltaTime); - void render(); + int addEmitter(); // add (create) an emitter and get its unique id + void useOrangeBlueColorPalette(); // apply a nice preset color palette to the particles + void setCollisionSphere(glm::vec3 position, float radius); // specify a sphere for the particles to collide with + void emitParticlesNow(int e, int numParticles); // tell this emitter to generate this many particles right now + void simulate(float deltaTime); // run it + void render(); // show it + void setEmitterPosition(int e, glm::vec3 position) { _emitter[e].position = position; } // set the position of this emitter private: struct Particle { + bool alive; glm::vec3 position; glm::vec3 velocity; glm::vec3 color; @@ -54,8 +59,9 @@ private: float _tornadoForce; float _neighborAttraction; float _neighborRepulsion; - float _TEST_bigSphereRadius; - glm::vec3 _TEST_bigSpherePosition; + bool _usingCollisionSphere; + glm::vec3 _collisionSpherePosition; + float _collisionSphereRadius; // private methods void updateEmitter(int e, float deltaTime); From ae99ca5ec8846b12ecb496c57945078bcdce944c Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Fri, 12 Jul 2013 18:55:42 -0700 Subject: [PATCH 12/81] added more API for the particle system --- interface/src/Application.cpp | 26 ++++++-- interface/src/ParticleSystem.cpp | 111 +++++++++++++++++++------------ interface/src/ParticleSystem.h | 45 +++++++------ 3 files changed, 116 insertions(+), 66 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 209282b926..6ec2f7a2e2 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2011,23 +2011,37 @@ void Application::update(float deltaTime) { _audio.eventuallyAnalyzePing(); #endif + if (TESTING_PARTICLE_SYSTEM) { if (_particleSystemInitialized) { - _particleSystem.simulate(deltaTime); - } else { - int coolDemoEmitter = _particleSystem.addEmitter(); + // update the particle system + _particleSystem.setUpDirection(glm::vec3(0.0f, 1.0f, 0.0f)); + _particleSystem.simulate(deltaTime); + _particleSystem.runSpecialEffectsTest(deltaTime); + } else { + // create a stable test emitter and spit out a bunch of particles + int coolDemoEmitter = _particleSystem.addEmitter(); if (coolDemoEmitter != -1) { - glm::vec3 particleEmitterPosition = glm::vec3(5.0f, 1.3f, 5.0f); + glm::vec3 particleEmitterPosition = glm::vec3(5.0f, 1.0f, 5.0f); _particleSystem.setEmitterPosition(coolDemoEmitter, particleEmitterPosition); - _particleSystem.emitParticlesNow(coolDemoEmitter, 1500); + float radius = 0.01f; + glm::vec4 color(0.0f, 0.0f, 0.0f, 1.0f); + glm::vec3 velocity(0.0f, 0.1f, 0.0f); + float lifespan = 100000.0f; + _particleSystem.emitParticlesNow(coolDemoEmitter, 1500, radius, color, velocity, lifespan); } + // determine a collision sphere glm::vec3 collisionSpherePosition = glm::vec3( 5.0f, 0.5f, 5.0f ); float collisionSphereRadius = 0.5f; _particleSystem.setCollisionSphere(collisionSpherePosition, collisionSphereRadius); + + // signal that the particle system has been initialized _particleSystemInitialized = true; - _particleSystem.useOrangeBlueColorPalette(); + + // apply a preset color palette + _particleSystem.setOrangeBlueColorPalette(); } } } diff --git a/interface/src/ParticleSystem.cpp b/interface/src/ParticleSystem.cpp index 0e762fdb0e..e6a3bfef7b 100644 --- a/interface/src/ParticleSystem.cpp +++ b/interface/src/ParticleSystem.cpp @@ -11,22 +11,28 @@ #include "ParticleSystem.h" #include "Application.h" +const float DEFAULT_PARTICLE_BOUNCE = 1.0f; +const float DEFAULT_PARTICLE_AIR_FRICTION = 2.0f; +const float DEFAULT_PARTICLE_JITTER = 0.05f; +const float DEFAULT_PARTICLE_GRAVITY = 0.05f; + ParticleSystem::ParticleSystem() { - _gravity = 0.005; - _numEmitters = 0; - _bounce = 0.9f; _timer = 0.0f; - _airFriction = 6.0f; - _jitter = 0.1f; - _homeAttraction = 0.0f; + _numEmitters = 0; + _gravity = DEFAULT_PARTICLE_GRAVITY; + _bounce = DEFAULT_PARTICLE_BOUNCE; + _airFriction = DEFAULT_PARTICLE_AIR_FRICTION; + _jitter = DEFAULT_PARTICLE_JITTER; + _emitterAttraction = 0.0f; _tornadoForce = 0.0f; - _neighborAttraction = 0.02f; - _neighborRepulsion = 0.9f; + _neighborAttraction = 0.0f; + _neighborRepulsion = 0.0f; _collisionSphereRadius = 0.0f; _collisionSpherePosition = glm::vec3(0.0f, 0.0f, 0.0f); _numParticles = 0; _usingCollisionSphere = false; + _upDirection = glm::vec3(0.0f, 1.0f, 0.0f); // default for (unsigned int e = 0; e < MAX_EMITTERS; e++) { _emitter[e].position = glm::vec3(0.0f, 0.0f, 0.0f); @@ -39,7 +45,8 @@ ParticleSystem::ParticleSystem() { for (unsigned int p = 0; p < MAX_PARTICLES; p++) { _particle[p].alive = false; _particle[p].age = 0.0f; - _particle[p].radius = 0.01f; + _particle[p].lifespan = 0.0f; + _particle[p].radius = 0.0f; _particle[p].emitterIndex = 0; _particle[p].position = glm::vec3(0.0f, 0.0f, 0.0f); _particle[p].velocity = glm::vec3(0.0f, 0.0f, 0.0f); @@ -71,9 +78,6 @@ void ParticleSystem::simulate(float deltaTime) { updateParticle(p, deltaTime); } } - - // apply special effects - runSpecialEffectsTest(deltaTime); } void ParticleSystem::updateEmitter(int e, float deltaTime) { @@ -84,39 +88,63 @@ void ParticleSystem::updateEmitter(int e, float deltaTime) { } - -void ParticleSystem::emitParticlesNow(int e, int num) { - - _numParticles = num; - - if (_numParticles > MAX_PARTICLES) { - _numParticles = MAX_PARTICLES; - } +void ParticleSystem::emitParticlesNow(int e, int num, float radius, glm::vec4 color, glm::vec3 velocity, float lifespan) { for (unsigned int p = 0; p < num; p++) { - _particle[p].alive = true; - _particle[p].position = _emitter[e].position; + createParticle(_emitter[e].position, velocity, radius, color, lifespan); } } -void ParticleSystem::useOrangeBlueColorPalette() { +void ParticleSystem::createParticle(glm::vec3 position, glm::vec3 velocity, float radius, glm::vec4 color, float lifespan) { + + for (unsigned int p = 0; p < MAX_PARTICLES; p++) { + if (!_particle[p].alive) { + + _particle[p].lifespan = lifespan; + _particle[p].alive = true; + _particle[p].age = 0.0f; + _particle[p].position = position; + _particle[p].velocity = velocity; + _particle[p].radius = radius; + _particle[p].color = color; + + _numParticles ++; + + assert(_numParticles <= MAX_PARTICLES); + + return; + } + } +} + +void ParticleSystem::killParticle(int p) { + + assert( p >= 0); + assert( p < MAX_PARTICLES); + assert( _numParticles > 0); + + _particle[p].alive = false; + _numParticles --; +} + + +void ParticleSystem::setOrangeBlueColorPalette() { for (unsigned int p = 0; p < _numParticles; p++) { float radian = ((float)p / (float)_numParticles) * PI_TIMES_TWO; float wave = sinf(radian); + float red = 0.5f + 0.5f * wave; float green = 0.3f + 0.3f * wave; float blue = 0.2f - 0.2f * wave; - _particle[p].color = glm::vec3(red, green, blue); + float alpha = 1.0f; + + _particle[p].color = glm::vec4(red, green, blue, alpha); } } - - - - void ParticleSystem::runSpecialEffectsTest(float deltaTime) { _timer += deltaTime; @@ -130,13 +158,13 @@ void ParticleSystem::runSpecialEffectsTest(float deltaTime) { _emitter[0].rotation = glm::quat(glm::radians(tilt)); - _gravity = 0.0f + 0.02f * sinf( _timer * 0.52f ); - _airFriction = 3.0f + 1.0f * sinf( _timer * 0.32f ); - _jitter = 0.05f + 0.05f * sinf( _timer * 0.42f ); - _homeAttraction = 0.01f + 0.01f * cosf( _timer * 0.6f ); - _tornadoForce = 0.0f + 0.03f * sinf( _timer * 0.7f ); - _neighborAttraction = 0.1f + 0.1f * cosf( _timer * 0.8f ); - _neighborRepulsion = 0.4f + 0.3f * sinf( _timer * 0.4f ); + _gravity = 0.0f + DEFAULT_PARTICLE_GRAVITY * sinf( _timer * 0.52f ); + _airFriction = (DEFAULT_PARTICLE_AIR_FRICTION + 0.5f) + 2.0f * sinf( _timer * 0.32f ); + _jitter = DEFAULT_PARTICLE_JITTER + DEFAULT_PARTICLE_JITTER * sinf( _timer * 0.42f ); + _emitterAttraction = 0.015f + 0.015f * cosf( _timer * 0.6f ); + _tornadoForce = 0.0f + 0.03f * sinf( _timer * 0.7f ); + _neighborAttraction = 0.1f + 0.1f * cosf( _timer * 0.8f ); + _neighborRepulsion = 0.2f + 0.2f * sinf( _timer * 0.4f ); if (_gravity < 0.0f) { _gravity = 0.0f; @@ -144,10 +172,13 @@ void ParticleSystem::runSpecialEffectsTest(float deltaTime) { } - void ParticleSystem::updateParticle(int p, float deltaTime) { _particle[p].age += deltaTime; + + if (_particle[p].age > _particle[p].lifespan) { + killParticle(p); + } // apply random jitter _particle[p].velocity += @@ -160,7 +191,7 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { // apply attraction to home position glm::vec3 vectorToHome = _emitter[_particle[p].emitterIndex].position - _particle[p].position; - _particle[p].velocity += vectorToHome * _homeAttraction * deltaTime; + _particle[p].velocity += vectorToHome * _emitterAttraction * deltaTime; // apply neighbor attraction int neighbor = p + 1; @@ -189,7 +220,7 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { } // apply gravity - _particle[p].velocity.y -= _gravity * deltaTime; + _particle[p].velocity -= _upDirection * _gravity * deltaTime; // update position by velocity _particle[p].position += _particle[p].velocity; @@ -239,11 +270,9 @@ void ParticleSystem::render() { } } - - void ParticleSystem::renderParticle(int p) { - glColor3f(_particle[p].color.x, _particle[p].color.y, _particle[p].color.z); + glColor4f(_particle[p].color.r, _particle[p].color.g, _particle[p].color.b, _particle[p].color.a ); glPushMatrix(); glTranslatef(_particle[p].position.x, _particle[p].position.y, _particle[p].position.z); glutSolidSphere(_particle[p].radius, 6, 6); diff --git a/interface/src/ParticleSystem.h b/interface/src/ParticleSystem.h index 701d1c85b7..f7f0063dbc 100644 --- a/interface/src/ParticleSystem.h +++ b/interface/src/ParticleSystem.h @@ -11,33 +11,27 @@ #include -const int MAX_PARTICLES = 5000; +const int MAX_PARTICLES = 10000; const int MAX_EMITTERS = 10; class ParticleSystem { public: ParticleSystem(); - int addEmitter(); // add (create) an emitter and get its unique id - void useOrangeBlueColorPalette(); // apply a nice preset color palette to the particles + int addEmitter(); // add (create) an emitter and get its unique id + void emitParticlesNow(int e, int numParticles, float radius, glm::vec4 color, glm::vec3 velocity, float lifespan); + void simulate(float deltaTime); + void render(); + void runSpecialEffectsTest(float deltaTime); // for debugging and artistic exploration + + void setOrangeBlueColorPalette(); // apply a nice preset color palette to the particles void setCollisionSphere(glm::vec3 position, float radius); // specify a sphere for the particles to collide with - void emitParticlesNow(int e, int numParticles); // tell this emitter to generate this many particles right now - void simulate(float deltaTime); // run it - void render(); // show it void setEmitterPosition(int e, glm::vec3 position) { _emitter[e].position = position; } // set the position of this emitter + void setEmitterRotation(int e, glm::quat rotation) { _emitter[e].rotation = rotation; } // set the rotation of this emitter + void setUpDirection(glm::vec3 upDirection) {_upDirection = upDirection;} // tell particle system which direction is up private: - struct Particle { - bool alive; - glm::vec3 position; - glm::vec3 velocity; - glm::vec3 color; - float age; - float radius; - int emitterIndex; - }; - struct Emitter { glm::vec3 position; glm::quat rotation; @@ -45,7 +39,19 @@ private: glm::vec3 up; glm::vec3 front; }; - + + struct Particle { + bool alive; // is the particle active? + glm::vec3 position; // position + glm::vec3 velocity; // velocity + glm::vec4 color; // color (rgba) + float age; // age in seconds + float radius; // radius + float lifespan; // how long this particle stays alive (in seconds) + int emitterIndex; // which emitter created this particle? + }; + + glm::vec3 _upDirection; float _bounce; float _gravity; float _timer; @@ -55,7 +61,7 @@ private: int _numEmitters; float _airFriction; float _jitter; - float _homeAttraction; + float _emitterAttraction; float _tornadoForce; float _neighborAttraction; float _neighborRepulsion; @@ -66,7 +72,8 @@ private: // private methods void updateEmitter(int e, float deltaTime); void updateParticle(int index, float deltaTime); - void runSpecialEffectsTest(float deltaTime); + void createParticle(glm::vec3 position, glm::vec3 velocity, float radius, glm::vec4 color, float lifespan); + void killParticle(int p); void renderEmitter(int emitterIndex, float size); void renderParticle(int p); }; From 3bc6b4c0d4648c7cf190bee683fc44f2fb871672 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Fri, 12 Jul 2013 18:56:54 -0700 Subject: [PATCH 13/81] merge --- interface/src/Avatar.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 interface/src/Avatar.cpp diff --git a/interface/src/Avatar.cpp b/interface/src/Avatar.cpp old mode 100755 new mode 100644 From 8b9e0426b24e6ec01ca53b9ec75683aadbb8fbcc Mon Sep 17 00:00:00 2001 From: Philip Rosedale Date: Fri, 12 Jul 2013 21:34:48 -0700 Subject: [PATCH 14/81] Simple glassy collision sound --- interface/src/Application.h | 1 + interface/src/Audio.cpp | 25 ++++++++++++++++++++++--- interface/src/Audio.h | 6 +++++- interface/src/Avatar.cpp | 8 ++++++++ 4 files changed, 36 insertions(+), 4 deletions(-) diff --git a/interface/src/Application.h b/interface/src/Application.h index c6bbd4eec2..9e8e359479 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -84,6 +84,7 @@ public: const glm::vec3 getMouseVoxelWorldCoordinates(const VoxelDetail _mouseVoxel); Avatar* getAvatar() { return &_myAvatar; } + Audio* getAudio() { return &_audio; } Camera* getCamera() { return &_myCamera; } ViewFrustum* getViewFrustum() { return &_viewFrustum; } VoxelSystem* getVoxels() { return &_voxels; } diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 7af42478d5..540e7b1e1e 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -326,7 +326,9 @@ Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples) : _lastYawMeasuredMaximum(0), _flangeIntensity(0.0f), _flangeRate(0.0f), - _flangeWeight(0.0f) + _flangeWeight(0.0f), + _collisionSoundMagnitude(0.0f), + _proceduralEffectSample(0) { outputPortAudioError(Pa_Initialize()); @@ -591,12 +593,29 @@ void Audio::addProceduralSounds(int16_t* inputBuffer, int numSamples) { float speed = glm::length(_lastVelocity); float volume = VOLUME_BASELINE * (1.f - speed / MAX_AUDIBLE_VELOCITY); + // Test tone (should be continuous!) + /* + for (int i = 0; i < numSamples; i++) { + inputBuffer[i] += (int16_t) (_proceduralEffectSample + i)%16 * 10; + }*/ + // Add a noise-modulated sinewave with volume that tapers off with speed increasing - if ((speed > MIN_AUDIBLE_VELOCITY) && (speed < MAX_AUDIBLE_VELOCITY)) { + if (0) { //((speed > MIN_AUDIBLE_VELOCITY) && (speed < MAX_AUDIBLE_VELOCITY)) { for (int i = 0; i < numSamples; i++) { - inputBuffer[i] += (int16_t)((sinf((float) i / SOUND_PITCH * speed) * randFloat()) * volume * speed); + inputBuffer[i] += (int16_t)((sinf((float) (_proceduralEffectSample + i) / SOUND_PITCH * speed) * (1.f + randFloat() * 0.0f)) * volume * speed); } } + const float COLLISION_SOUND_CUTOFF_LEVEL = 5.0f; + const float COLLISION_SOUND_PITCH_1 = 2.0f; + const float COLLISION_SOUND_DECAY = 1.f/1024.f; + const float COLLISION_VOLUME_BASELINE = 10.f; + if (_collisionSoundMagnitude > COLLISION_SOUND_CUTOFF_LEVEL) { + for (int i = 0; i < numSamples; i++) { + inputBuffer[i] += (int16_t) ((sinf((float) (_proceduralEffectSample + i) / COLLISION_SOUND_PITCH_1) * COLLISION_VOLUME_BASELINE * _collisionSoundMagnitude)); + _collisionSoundMagnitude *= (1.f - COLLISION_SOUND_DECAY); + } + } + _proceduralEffectSample += numSamples; } // ----------------------------------------------------------- diff --git a/interface/src/Audio.h b/interface/src/Audio.h index a3c8cf1046..78b298644b 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -44,6 +44,8 @@ public: void lowPassFilter(int16_t* inputBuffer); + void setCollisionSoundMagnitude(float collisionSoundMagnitude) { _collisionSoundMagnitude = collisionSoundMagnitude; } + void ping(); // Call periodically to eventually perform round trip time analysis, @@ -81,7 +83,9 @@ private: float _flangeIntensity; float _flangeRate; float _flangeWeight; - + float _collisionSoundMagnitude; + int _proceduralEffectSample; + // Audio callback in class context. inline void performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* outputRight); diff --git a/interface/src/Avatar.cpp b/interface/src/Avatar.cpp index 881b436bf2..7d306b307a 100755 --- a/interface/src/Avatar.cpp +++ b/interface/src/Avatar.cpp @@ -873,6 +873,7 @@ void Avatar::updateCollisionWithEnvironment() { _position - up * (_pelvisFloatingHeight - radius), _position + up * (_height - _pelvisFloatingHeight - radius), radius, penetration)) { applyHardCollision(penetration, ENVIRONMENT_SURFACE_ELASTICITY, ENVIRONMENT_SURFACE_DAMPING); + } } @@ -910,6 +911,13 @@ void Avatar::applyHardCollision(const glm::vec3& penetration, float elasticity, // If moving really slowly after a collision, and not applying forces, stop altogether _velocity *= 0.f; } + // Push the collision into the audio system for procedural effects + const float AUDIBLE_COLLISION_THRESHOLD = 200.f; + const float COLLISION_VOLUME = 10000.f; + float collisionSoundLevel = penetrationLength * COLLISION_VOLUME; + if (collisionSoundLevel > AUDIBLE_COLLISION_THRESHOLD) { + Application::getInstance()->getAudio()->setCollisionSoundMagnitude(collisionSoundLevel); + } } } From 84b6adf5b05f5a725fa04371002579dc4febd5f0 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Mon, 15 Jul 2013 13:57:39 -0700 Subject: [PATCH 15/81] more work on particle emitter API --- interface/src/Application.cpp | 88 ++++++++++++++---- interface/src/Application.h | 2 + interface/src/ParticleSystem.cpp | 154 ++++++++++++++++--------------- interface/src/ParticleSystem.h | 35 +++---- 4 files changed, 171 insertions(+), 108 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 6ec2f7a2e2..6f5fffd68c 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -172,7 +172,9 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : _frameCount(0), _fps(120.0f), _justStarted(true), - _particleSystemInitialized(false), + _particleSystemInitialized(false), + _coolDemoParticleEmitter(-1), + _fingerParticleEmitter(-1), _wantToKillLocalVoxels(false), _frustumDrawingMode(FRUSTUM_DRAW_MODE_ALL), _viewFrustumOffsetYaw(-135.0), @@ -2013,35 +2015,89 @@ void Application::update(float deltaTime) { if (TESTING_PARTICLE_SYSTEM) { - if (_particleSystemInitialized) { + if (!_particleSystemInitialized) { - // update the particle system - _particleSystem.setUpDirection(glm::vec3(0.0f, 1.0f, 0.0f)); - _particleSystem.simulate(deltaTime); - _particleSystem.runSpecialEffectsTest(deltaTime); - } else { // create a stable test emitter and spit out a bunch of particles - int coolDemoEmitter = _particleSystem.addEmitter(); - if (coolDemoEmitter != -1) { + _coolDemoParticleEmitter = _particleSystem.addEmitter(); + _fingerParticleEmitter = _particleSystem.addEmitter(); + + if (_coolDemoParticleEmitter != -1) { + _particleSystem.setShowingEmitter(_coolDemoParticleEmitter, true); glm::vec3 particleEmitterPosition = glm::vec3(5.0f, 1.0f, 5.0f); - _particleSystem.setEmitterPosition(coolDemoEmitter, particleEmitterPosition); + _particleSystem.setEmitterPosition(_coolDemoParticleEmitter, particleEmitterPosition); float radius = 0.01f; glm::vec4 color(0.0f, 0.0f, 0.0f, 1.0f); glm::vec3 velocity(0.0f, 0.1f, 0.0f); float lifespan = 100000.0f; - _particleSystem.emitParticlesNow(coolDemoEmitter, 1500, radius, color, velocity, lifespan); + + // determine a collision sphere + glm::vec3 collisionSpherePosition = glm::vec3( 5.0f, 0.5f, 5.0f ); + float collisionSphereRadius = 0.5f; + _particleSystem.setCollisionSphere(_coolDemoParticleEmitter, collisionSpherePosition, collisionSphereRadius); + _particleSystem.emitParticlesNow(_coolDemoParticleEmitter, 1500, radius, color, velocity, lifespan); + } + + if (_fingerParticleEmitter != -1) { + _particleSystem.setShowingEmitter(_fingerParticleEmitter, false); } - // determine a collision sphere - glm::vec3 collisionSpherePosition = glm::vec3( 5.0f, 0.5f, 5.0f ); - float collisionSphereRadius = 0.5f; - _particleSystem.setCollisionSphere(collisionSpherePosition, collisionSphereRadius); // signal that the particle system has been initialized _particleSystemInitialized = true; // apply a preset color palette - _particleSystem.setOrangeBlueColorPalette(); + _particleSystem.setOrangeBlueColorPalette(); + } else { + // update the particle system + + + static float t = 0.0f; + t += deltaTime; + + + if (_coolDemoParticleEmitter != -1) { + + glm::vec3 tilt = glm::vec3 + ( + 30.0f * sinf( t * 0.55f ), + 0.0f, + 30.0f * cosf( t * 0.75f ) + ); + + _particleSystem.setEmitterRotation(_coolDemoParticleEmitter, glm::quat(glm::radians(tilt))); + } + + if (_fingerParticleEmitter != -1) { + + glm::vec3 particleEmitterPosition = + glm::vec3 + ( + 3.0f + sinf(t * 8.0f) * 0.02f, + 1.0f + cosf(t * 9.0f) * 0.02f, + 3.0f + sinf(t * 7.0f) * 0.02f + ); + + glm::vec3 tilt = glm::vec3 + ( + 30.0f * sinf( t * 0.55f ), + 0.0f, + 30.0f * cosf( t * 0.75f ) + ); + + glm::quat particleEmitterRotation = glm::quat(glm::radians(tilt)); + + _particleSystem.setEmitterPosition(_fingerParticleEmitter, particleEmitterPosition); + _particleSystem.setEmitterRotation(_fingerParticleEmitter, particleEmitterRotation); + + float radius = 0.01f; + glm::vec4 color(1.0f, 1.0f, 1.0f, 1.0f); + glm::vec3 velocity(0.0f, 0.01f, 0.0f); + float lifespan = 0.4f; + _particleSystem.emitParticlesNow(_fingerParticleEmitter, 1, radius, color, velocity, lifespan); + } + + _particleSystem.setUpDirection(glm::vec3(0.0f, 1.0f, 0.0f)); + _particleSystem.simulate(deltaTime); } } } diff --git a/interface/src/Application.h b/interface/src/Application.h index 37a8b40964..879f039f8c 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -279,6 +279,8 @@ private: timeval _lastTimeUpdated; bool _justStarted; bool _particleSystemInitialized; + int _coolDemoParticleEmitter; + int _fingerParticleEmitter; Stars _stars; diff --git a/interface/src/ParticleSystem.cpp b/interface/src/ParticleSystem.cpp index e6a3bfef7b..14aaedbac9 100644 --- a/interface/src/ParticleSystem.cpp +++ b/interface/src/ParticleSystem.cpp @@ -13,33 +13,34 @@ const float DEFAULT_PARTICLE_BOUNCE = 1.0f; const float DEFAULT_PARTICLE_AIR_FRICTION = 2.0f; -const float DEFAULT_PARTICLE_JITTER = 0.05f; const float DEFAULT_PARTICLE_GRAVITY = 0.05f; ParticleSystem::ParticleSystem() { - _timer = 0.0f; - _numEmitters = 0; - _gravity = DEFAULT_PARTICLE_GRAVITY; - _bounce = DEFAULT_PARTICLE_BOUNCE; - _airFriction = DEFAULT_PARTICLE_AIR_FRICTION; - _jitter = DEFAULT_PARTICLE_JITTER; - _emitterAttraction = 0.0f; - _tornadoForce = 0.0f; - _neighborAttraction = 0.0f; - _neighborRepulsion = 0.0f; - _collisionSphereRadius = 0.0f; - _collisionSpherePosition = glm::vec3(0.0f, 0.0f, 0.0f); - _numParticles = 0; - _usingCollisionSphere = false; - _upDirection = glm::vec3(0.0f, 1.0f, 0.0f); // default - + _timer = 0.0f; + _numEmitters = 0; + _numParticles = 0; + _upDirection = glm::vec3(0.0f, 1.0f, 0.0f); // default + for (unsigned int e = 0; e < MAX_EMITTERS; e++) { - _emitter[e].position = glm::vec3(0.0f, 0.0f, 0.0f); - _emitter[e].rotation = glm::quat(); - _emitter[e].right = IDENTITY_RIGHT; - _emitter[e].up = IDENTITY_UP; - _emitter[e].front = IDENTITY_FRONT; + _emitter[e].position = glm::vec3(0.0f, 0.0f, 0.0f); + _emitter[e].rotation = glm::quat(); + _emitter[e].right = IDENTITY_RIGHT; + _emitter[e].up = IDENTITY_UP; + _emitter[e].front = IDENTITY_FRONT; + _emitter[e].bounce = DEFAULT_PARTICLE_BOUNCE; + _emitter[e].airFriction = DEFAULT_PARTICLE_AIR_FRICTION; + _emitter[e].gravity = DEFAULT_PARTICLE_GRAVITY; + _emitter[e].jitter = 0.0f; + _emitter[e].emitterAttraction = 0.0f; + _emitter[e].tornadoForce = 0.0f; + _emitter[e].neighborAttraction = 0.0f; + _emitter[e].neighborRepulsion = 0.0f; + _emitter[e].collisionSphereRadius = 0.0f; + _emitter[e].collisionSpherePosition = glm::vec3(0.0f, 0.0f, 0.0f); + _emitter[e].usingCollisionSphere = false; + _emitter[e].showingEmitter = false; + }; for (unsigned int p = 0; p < MAX_PARTICLES; p++) { @@ -69,9 +70,11 @@ void ParticleSystem::simulate(float deltaTime) { // update emitters for (unsigned int e = 0; e < _numEmitters; e++) { - updateEmitter(e, deltaTime); + updateEmitter(e, deltaTime); } + runSpecialEffectsTest(0, deltaTime); + // update particles for (unsigned int p = 0; p < _numParticles; p++) { if (_particle[p].alive) { @@ -91,22 +94,23 @@ void ParticleSystem::updateEmitter(int e, float deltaTime) { void ParticleSystem::emitParticlesNow(int e, int num, float radius, glm::vec4 color, glm::vec3 velocity, float lifespan) { for (unsigned int p = 0; p < num; p++) { - createParticle(_emitter[e].position, velocity, radius, color, lifespan); + createParticle(e, _emitter[e].position, velocity, radius, color, lifespan); } } -void ParticleSystem::createParticle(glm::vec3 position, glm::vec3 velocity, float radius, glm::vec4 color, float lifespan) { +void ParticleSystem::createParticle(int e, glm::vec3 position, glm::vec3 velocity, float radius, glm::vec4 color, float lifespan) { for (unsigned int p = 0; p < MAX_PARTICLES; p++) { if (!_particle[p].alive) { - _particle[p].lifespan = lifespan; - _particle[p].alive = true; - _particle[p].age = 0.0f; - _particle[p].position = position; - _particle[p].velocity = velocity; - _particle[p].radius = radius; - _particle[p].color = color; + _particle[p].emitterIndex = e; + _particle[p].lifespan = lifespan; + _particle[p].alive = true; + _particle[p].age = 0.0f; + _particle[p].position = position; + _particle[p].velocity = velocity; + _particle[p].radius = radius; + _particle[p].color = color; _numParticles ++; @@ -145,29 +149,20 @@ void ParticleSystem::setOrangeBlueColorPalette() { } -void ParticleSystem::runSpecialEffectsTest(float deltaTime) { +void ParticleSystem::runSpecialEffectsTest(int e, float deltaTime) { _timer += deltaTime; - - glm::vec3 tilt = glm::vec3 - ( - 30.0f * sinf( _timer * 0.55f ), - 0.0f, - 30.0f * cosf( _timer * 0.75f ) - ); - - _emitter[0].rotation = glm::quat(glm::radians(tilt)); - - _gravity = 0.0f + DEFAULT_PARTICLE_GRAVITY * sinf( _timer * 0.52f ); - _airFriction = (DEFAULT_PARTICLE_AIR_FRICTION + 0.5f) + 2.0f * sinf( _timer * 0.32f ); - _jitter = DEFAULT_PARTICLE_JITTER + DEFAULT_PARTICLE_JITTER * sinf( _timer * 0.42f ); - _emitterAttraction = 0.015f + 0.015f * cosf( _timer * 0.6f ); - _tornadoForce = 0.0f + 0.03f * sinf( _timer * 0.7f ); - _neighborAttraction = 0.1f + 0.1f * cosf( _timer * 0.8f ); - _neighborRepulsion = 0.2f + 0.2f * sinf( _timer * 0.4f ); + + _emitter[e].gravity = 0.0f + DEFAULT_PARTICLE_GRAVITY * sinf( _timer * 0.52f ); + _emitter[e].airFriction = (DEFAULT_PARTICLE_AIR_FRICTION + 0.5f) + 2.0f * sinf( _timer * 0.32f ); + _emitter[e].jitter = 0.05f + 0.05f * sinf( _timer * 0.42f ); + _emitter[e].emitterAttraction = 0.015f + 0.015f * cosf( _timer * 0.6f ); + _emitter[e].tornadoForce = 0.0f + 0.03f * sinf( _timer * 0.7f ); + _emitter[e].neighborAttraction = 0.1f + 0.1f * cosf( _timer * 0.8f ); + _emitter[e].neighborRepulsion = 0.2f + 0.2f * sinf( _timer * 0.4f ); - if (_gravity < 0.0f) { - _gravity = 0.0f; + if (_emitter[e].gravity < 0.0f) { + _emitter[e].gravity = 0.0f; } } @@ -179,40 +174,45 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { if (_particle[p].age > _particle[p].lifespan) { killParticle(p); } + + Emitter myEmitter = _emitter[_particle[p].emitterIndex]; // apply random jitter _particle[p].velocity += glm::vec3 ( - -_jitter * ONE_HALF + _jitter * randFloat(), - -_jitter * ONE_HALF + _jitter * randFloat(), - -_jitter * ONE_HALF + _jitter * randFloat() + -myEmitter.jitter * ONE_HALF + myEmitter.jitter * randFloat(), + -myEmitter.jitter * ONE_HALF + myEmitter.jitter * randFloat(), + -myEmitter.jitter * ONE_HALF + myEmitter.jitter * randFloat() ) * deltaTime; // apply attraction to home position - glm::vec3 vectorToHome = _emitter[_particle[p].emitterIndex].position - _particle[p].position; - _particle[p].velocity += vectorToHome * _emitterAttraction * deltaTime; + glm::vec3 vectorToHome = myEmitter.position - _particle[p].position; + _particle[p].velocity += vectorToHome * myEmitter.emitterAttraction * deltaTime; // apply neighbor attraction int neighbor = p + 1; if (neighbor == _numParticles ) { neighbor = 0; } - glm::vec3 vectorToNeighbor = _particle[p].position - _particle[neighbor].position; - _particle[p].velocity -= vectorToNeighbor * _neighborAttraction * deltaTime; + if ( _particle[neighbor].emitterIndex == _particle[p].emitterIndex) { + glm::vec3 vectorToNeighbor = _particle[p].position - _particle[neighbor].position; + + _particle[p].velocity -= vectorToNeighbor * myEmitter.neighborAttraction * deltaTime; - float distanceToNeighbor = glm::length(vectorToNeighbor); - if (distanceToNeighbor > 0.0f) { - _particle[neighbor].velocity += (vectorToNeighbor / ( 1.0f + distanceToNeighbor * distanceToNeighbor)) * _neighborRepulsion * deltaTime; + float distanceToNeighbor = glm::length(vectorToNeighbor); + if (distanceToNeighbor > 0.0f) { + _particle[neighbor].velocity += (vectorToNeighbor / ( 1.0f + distanceToNeighbor * distanceToNeighbor)) * myEmitter.neighborRepulsion * deltaTime; + } } // apply tornado force - glm::vec3 tornadoDirection = glm::cross(vectorToHome, _emitter[_particle[p].emitterIndex].up); - _particle[p].velocity += tornadoDirection * _tornadoForce * deltaTime; + glm::vec3 tornadoDirection = glm::cross(vectorToHome, myEmitter.up); + _particle[p].velocity += tornadoDirection * myEmitter.tornadoForce * deltaTime; // apply air friction - float drag = 1.0 - _airFriction * deltaTime; + float drag = 1.0 - myEmitter.airFriction * deltaTime; if (drag < 0.0f) { _particle[p].velocity = glm::vec3(0.0f, 0.0f, 0.0f); } else { @@ -220,7 +220,7 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { } // apply gravity - _particle[p].velocity -= _upDirection * _gravity * deltaTime; + _particle[p].velocity -= _upDirection * myEmitter.gravity * deltaTime; // update position by velocity _particle[p].position += _particle[p].velocity; @@ -230,36 +230,38 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { _particle[p].position.y = _particle[p].radius; if (_particle[p].velocity.y < 0.0f) { - _particle[p].velocity.y *= -_bounce; + _particle[p].velocity.y *= -myEmitter.bounce; } } // collision with sphere - if (_usingCollisionSphere) { - glm::vec3 vectorToSphereCenter = _collisionSpherePosition - _particle[p].position; + if (myEmitter.usingCollisionSphere) { + glm::vec3 vectorToSphereCenter = myEmitter.collisionSpherePosition - _particle[p].position; float distanceToSphereCenter = glm::length(vectorToSphereCenter); - float combinedRadius = _collisionSphereRadius + _particle[p].radius; + float combinedRadius = myEmitter.collisionSphereRadius + _particle[p].radius; if (distanceToSphereCenter < combinedRadius) { if (distanceToSphereCenter > 0.0f){ glm::vec3 directionToSphereCenter = vectorToSphereCenter / distanceToSphereCenter; - _particle[p].position = _collisionSpherePosition - directionToSphereCenter * combinedRadius; + _particle[p].position = myEmitter.collisionSpherePosition - directionToSphereCenter * combinedRadius; } } } } -void ParticleSystem::setCollisionSphere(glm::vec3 position, float radius) { - _usingCollisionSphere = true; - _collisionSpherePosition = position; - _collisionSphereRadius = radius; +void ParticleSystem::setCollisionSphere(int e, glm::vec3 position, float radius) { + _emitter[e].usingCollisionSphere = true; + _emitter[e].collisionSpherePosition = position; + _emitter[e].collisionSphereRadius = radius; } void ParticleSystem::render() { // render the emitters for (unsigned int e = 0; e < _numEmitters; e++) { - renderEmitter(e, 0.2f); + if (_emitter[e].showingEmitter) { + renderEmitter(e, 0.2f); + } }; // render the particles diff --git a/interface/src/ParticleSystem.h b/interface/src/ParticleSystem.h index f7f0063dbc..3b8826d697 100644 --- a/interface/src/ParticleSystem.h +++ b/interface/src/ParticleSystem.h @@ -11,8 +11,8 @@ #include -const int MAX_PARTICLES = 10000; -const int MAX_EMITTERS = 10; +const int MAX_PARTICLES = 5000; +const int MAX_EMITTERS = 20; class ParticleSystem { public: @@ -22,13 +22,14 @@ public: void emitParticlesNow(int e, int numParticles, float radius, glm::vec4 color, glm::vec3 velocity, float lifespan); void simulate(float deltaTime); void render(); - void runSpecialEffectsTest(float deltaTime); // for debugging and artistic exploration void setOrangeBlueColorPalette(); // apply a nice preset color palette to the particles - void setCollisionSphere(glm::vec3 position, float radius); // specify a sphere for the particles to collide with + void setCollisionSphere(int e, glm::vec3 position, float radius); // specify a sphere for the particles to collide with void setEmitterPosition(int e, glm::vec3 position) { _emitter[e].position = position; } // set the position of this emitter void setEmitterRotation(int e, glm::quat rotation) { _emitter[e].rotation = rotation; } // set the rotation of this emitter void setUpDirection(glm::vec3 upDirection) {_upDirection = upDirection;} // tell particle system which direction is up + void setShowingEmitter(int e, bool showing) { _emitter[e].showingEmitter = showing;} + private: @@ -38,6 +39,18 @@ private: glm::vec3 right; glm::vec3 up; glm::vec3 front; + float bounce; + float gravity; + float airFriction; + float jitter; + float emitterAttraction; + float tornadoForce; + float neighborAttraction; + float neighborRepulsion; + bool usingCollisionSphere; + glm::vec3 collisionSpherePosition; + float collisionSphereRadius; + bool showingEmitter; }; struct Particle { @@ -52,27 +65,17 @@ private: }; glm::vec3 _upDirection; - float _bounce; - float _gravity; float _timer; Emitter _emitter[MAX_EMITTERS]; Particle _particle[MAX_PARTICLES]; int _numParticles; int _numEmitters; - float _airFriction; - float _jitter; - float _emitterAttraction; - float _tornadoForce; - float _neighborAttraction; - float _neighborRepulsion; - bool _usingCollisionSphere; - glm::vec3 _collisionSpherePosition; - float _collisionSphereRadius; // private methods void updateEmitter(int e, float deltaTime); void updateParticle(int index, float deltaTime); - void createParticle(glm::vec3 position, glm::vec3 velocity, float radius, glm::vec4 color, float lifespan); + void createParticle(int e, glm::vec3 position, glm::vec3 velocity, float radius, glm::vec4 color, float lifespan); + void runSpecialEffectsTest(int e, float deltaTime); // for debugging and artistic exploration void killParticle(int p); void renderEmitter(int emitterIndex, float size); void renderParticle(int p); From 83c779ad766e32caaea1ef846c2768041d2385bf Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Mon, 15 Jul 2013 14:08:04 -0700 Subject: [PATCH 16/81] merge --- libraries/shared/src/PacketHeaders.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/shared/src/PacketHeaders.cpp b/libraries/shared/src/PacketHeaders.cpp index 230ca5bacc..f983b91d0b 100644 --- a/libraries/shared/src/PacketHeaders.cpp +++ b/libraries/shared/src/PacketHeaders.cpp @@ -63,4 +63,4 @@ int numBytesForPacketHeader(unsigned char* packetHeader) { // currently this need not be dynamic - there are 2 bytes for each packet header return 2; -} +} \ No newline at end of file From f8f6b295597bc0a747b6c0cc62d22932ed3e0d7b Mon Sep 17 00:00:00 2001 From: Philip Rosedale Date: Mon, 15 Jul 2013 14:24:21 -0700 Subject: [PATCH 17/81] Audio collision sounds are played locally as well as injected --- interface/src/Audio.cpp | 39 ++++++++++++++++++++++++--------------- interface/src/Audio.h | 2 +- interface/src/Head.cpp | 6 ++++-- 3 files changed, 29 insertions(+), 18 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 540e7b1e1e..a724f7b288 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -75,9 +75,12 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o NodeList* nodeList = NodeList::getInstance(); Application* interface = Application::getInstance(); Avatar* interfaceAvatar = interface->getAvatar(); - + + memset(outputLeft, 0, PACKET_LENGTH_BYTES_PER_CHANNEL); + memset(outputRight, 0, PACKET_LENGTH_BYTES_PER_CHANNEL); + // Add Procedural effects to input samples - addProceduralSounds(inputLeft, BUFFER_LENGTH_SAMPLES_PER_CHANNEL); + addProceduralSounds(inputLeft, outputLeft, outputRight, BUFFER_LENGTH_SAMPLES_PER_CHANNEL); if (nodeList && inputLeft) { @@ -129,12 +132,8 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o interface->getBandwidthMeter()->outputStream(BandwidthMeter::AUDIO) .updateValue(BUFFER_LENGTH_BYTES_PER_CHANNEL + leadingBytes); } - } - - memset(outputLeft, 0, PACKET_LENGTH_BYTES_PER_CHANNEL); - memset(outputRight, 0, PACKET_LENGTH_BYTES_PER_CHANNEL); - + AudioRingBuffer* ringBuffer = &_ringBuffer; // if there is anything in the ring buffer, decide what to do: @@ -245,11 +244,11 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o } } #ifndef TEST_AUDIO_LOOPBACK - outputLeft[s] = leftSample; - outputRight[s] = rightSample; + outputLeft[s] += leftSample; + outputRight[s] += rightSample; #else - outputLeft[s] = inputLeft[s]; - outputRight[s] = inputLeft[s]; + outputLeft[s] += inputLeft[s]; + outputRight[s] += inputLeft[s]; #endif } ringBuffer->setNextOutput(ringBuffer->getNextOutput() + PACKET_LENGTH_SAMPLES); @@ -584,7 +583,10 @@ void Audio::lowPassFilter(int16_t* inputBuffer) { } // Take a pointer to the acquired microphone input samples and add procedural sounds -void Audio::addProceduralSounds(int16_t* inputBuffer, int numSamples) { +void Audio::addProceduralSounds(int16_t* inputBuffer, + int16_t* outputLeft, + int16_t* outputRight, + int numSamples) { const float MAX_AUDIBLE_VELOCITY = 6.0; const float MIN_AUDIBLE_VELOCITY = 0.1; const int VOLUME_BASELINE = 400; @@ -600,18 +602,25 @@ void Audio::addProceduralSounds(int16_t* inputBuffer, int numSamples) { }*/ // Add a noise-modulated sinewave with volume that tapers off with speed increasing - if (0) { //((speed > MIN_AUDIBLE_VELOCITY) && (speed < MAX_AUDIBLE_VELOCITY)) { + if ((speed > MIN_AUDIBLE_VELOCITY) && (speed < MAX_AUDIBLE_VELOCITY)) { for (int i = 0; i < numSamples; i++) { - inputBuffer[i] += (int16_t)((sinf((float) (_proceduralEffectSample + i) / SOUND_PITCH * speed) * (1.f + randFloat() * 0.0f)) * volume * speed); + //inputBuffer[i] += (int16_t)((sinf((float) (_proceduralEffectSample + i) / SOUND_PITCH * speed) * (1.f + randFloat() * 0.0f)) * volume * speed); + inputBuffer[i] += (int16_t)(sinf((float) (_proceduralEffectSample + i) / SOUND_PITCH ) * volume * (1.f + randFloat() * 0.25f) * speed); + + } } const float COLLISION_SOUND_CUTOFF_LEVEL = 5.0f; const float COLLISION_SOUND_PITCH_1 = 2.0f; const float COLLISION_SOUND_DECAY = 1.f/1024.f; const float COLLISION_VOLUME_BASELINE = 10.f; + int sample; if (_collisionSoundMagnitude > COLLISION_SOUND_CUTOFF_LEVEL) { for (int i = 0; i < numSamples; i++) { - inputBuffer[i] += (int16_t) ((sinf((float) (_proceduralEffectSample + i) / COLLISION_SOUND_PITCH_1) * COLLISION_VOLUME_BASELINE * _collisionSoundMagnitude)); + sample = (int16_t) ((sinf((float) (_proceduralEffectSample + i) / COLLISION_SOUND_PITCH_1) * COLLISION_VOLUME_BASELINE * _collisionSoundMagnitude)); + inputBuffer[i] += sample; + outputLeft[i] += sample; + outputRight[i] += sample; _collisionSoundMagnitude *= (1.f - COLLISION_SOUND_DECAY); } } diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 78b298644b..715cfeafc8 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -97,7 +97,7 @@ private: inline void analyzePing(); // Add sounds that we want the user to not hear themselves, by adding on top of mic input signal - void addProceduralSounds(int16_t* inputBuffer, int numSamples); + void addProceduralSounds(int16_t* inputBuffer, int16_t* outputLeft, int16_t* outputRight, int numSamples); // Audio callback called by portaudio. Calls 'performIO'. diff --git a/interface/src/Head.cpp b/interface/src/Head.cpp index 44d62e695d..18141bc2b4 100644 --- a/interface/src/Head.cpp +++ b/interface/src/Head.cpp @@ -227,7 +227,8 @@ void Head::simulate(float deltaTime, bool isMine) { const float CAMERA_FOLLOW_HEAD_RATE_MAX = 0.5f; const float CAMERA_FOLLOW_HEAD_RATE_RAMP_RATE = 1.05f; const float CAMERA_STOP_TOLERANCE_DEGREES = 0.1f; - const float CAMERA_START_TOLERANCE_DEGREES = 2.0f; + const float CAMERA_PITCH_START_TOLERANCE_DEGREES = 10.0f; + const float CAMERA_YAW_START_TOLERANCE_DEGREES = 3.0f; float cameraHeadAngleDifference = glm::length(glm::vec2(_pitch - _cameraPitch, _yaw - _cameraYaw)); if (_isCameraMoving) { _cameraFollowHeadRate = glm::clamp(_cameraFollowHeadRate * CAMERA_FOLLOW_HEAD_RATE_RAMP_RATE, @@ -240,7 +241,8 @@ void Head::simulate(float deltaTime, bool isMine) { _isCameraMoving = false; } } else { - if (cameraHeadAngleDifference > CAMERA_START_TOLERANCE_DEGREES) { + if ((fabs(_pitch - _cameraPitch) > CAMERA_PITCH_START_TOLERANCE_DEGREES) || + (fabs(_yaw - _cameraYaw) > CAMERA_YAW_START_TOLERANCE_DEGREES)) { _isCameraMoving = true; _cameraFollowHeadRate = CAMERA_FOLLOW_HEAD_RATE_START; } From c0f319f077f4bec5a40a3780521f57a2cc23fd52 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Mon, 15 Jul 2013 14:36:11 -0700 Subject: [PATCH 18/81] merge --- interface/src/Application.cpp | 8 +++++++- libraries/avatars/src/HandData.h | 0 2 files changed, 7 insertions(+), 1 deletion(-) mode change 100755 => 100644 libraries/avatars/src/HandData.h diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 44c2bc5200..d7ff6fe959 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2037,7 +2037,6 @@ void Application::update(float deltaTime) { _audio.eventuallyAnalyzePing(); #endif - if (TESTING_PARTICLE_SYSTEM) { if (!_particleSystemInitialized) { @@ -2100,6 +2099,13 @@ void Application::update(float deltaTime) { 1.0f + cosf(t * 9.0f) * 0.02f, 3.0f + sinf(t * 7.0f) * 0.02f ); + + +//_myAvatar.getHand().setLeapFingers(LeapManager::getFingerTips(), LeapManager::getFingerRoots()); +//_myAvatar.getHand().setLeapHands(LeapManager::getHandPositions(), LeapManager::getHandNormals()); + + + glm::vec3 tilt = glm::vec3 ( diff --git a/libraries/avatars/src/HandData.h b/libraries/avatars/src/HandData.h old mode 100755 new mode 100644 From 56d0c7d7e4954b7607f33204e1cc52be6bc4dc33 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Mon, 15 Jul 2013 15:45:31 -0700 Subject: [PATCH 19/81] added array of finger emitters for particle system --- interface/src/Application.cpp | 79 +++++++++++++++----------------- interface/src/Application.h | 2 +- interface/src/Hand.h | 1 + interface/src/LeapManager.cpp | 0 interface/src/ParticleSystem.cpp | 24 ++++++---- 5 files changed, 56 insertions(+), 50 deletions(-) mode change 100755 => 100644 interface/src/LeapManager.cpp diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index d7ff6fe959..1b050bc874 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -174,7 +174,6 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : _justStarted(true), _particleSystemInitialized(false), _coolDemoParticleEmitter(-1), - _fingerParticleEmitter(-1), _wantToKillLocalVoxels(false), _frustumDrawingMode(FRUSTUM_DRAW_MODE_ALL), _viewFrustumOffsetYaw(-135.0), @@ -210,6 +209,12 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : _bytesCount(0), _swatch(NULL) { + + // initialize all finger particle emitters with an invalid id as default + for (int f = 0; f< NUM_FINGERS_PER_HAND; f ++ ) { + _fingerParticleEmitter[f] = -1; + } + _applicationStartupTime = startup_time; _window->setWindowTitle("Interface"); printLog("Interface Startup:\n"); @@ -2042,8 +2047,7 @@ void Application::update(float deltaTime) { // create a stable test emitter and spit out a bunch of particles _coolDemoParticleEmitter = _particleSystem.addEmitter(); - _fingerParticleEmitter = _particleSystem.addEmitter(); - + if (_coolDemoParticleEmitter != -1) { _particleSystem.setShowingEmitter(_coolDemoParticleEmitter, true); glm::vec3 particleEmitterPosition = glm::vec3(5.0f, 1.0f, 5.0f); @@ -2060,11 +2064,11 @@ void Application::update(float deltaTime) { _particleSystem.emitParticlesNow(_coolDemoParticleEmitter, 1500, radius, color, velocity, lifespan); } - if (_fingerParticleEmitter != -1) { - _particleSystem.setShowingEmitter(_fingerParticleEmitter, false); + for ( int f = 0; f< NUM_FINGERS_PER_HAND; f ++ ) { + _fingerParticleEmitter[f] = _particleSystem.addEmitter(); + _particleSystem.setShowingEmitter(_fingerParticleEmitter[f], true); } - - + // signal that the particle system has been initialized _particleSystemInitialized = true; @@ -2073,11 +2077,9 @@ void Application::update(float deltaTime) { } else { // update the particle system - static float t = 0.0f; t += deltaTime; - if (_coolDemoParticleEmitter != -1) { glm::vec3 tilt = glm::vec3 @@ -2090,40 +2092,35 @@ void Application::update(float deltaTime) { _particleSystem.setEmitterRotation(_coolDemoParticleEmitter, glm::quat(glm::radians(tilt))); } - if (_fingerParticleEmitter != -1) { - - glm::vec3 particleEmitterPosition = - glm::vec3 - ( - 3.0f + sinf(t * 8.0f) * 0.02f, - 1.0f + cosf(t * 9.0f) * 0.02f, - 3.0f + sinf(t * 7.0f) * 0.02f - ); - - -//_myAvatar.getHand().setLeapFingers(LeapManager::getFingerTips(), LeapManager::getFingerRoots()); -//_myAvatar.getHand().setLeapHands(LeapManager::getHandPositions(), LeapManager::getHandNormals()); - - - - - glm::vec3 tilt = glm::vec3 - ( - 30.0f * sinf( t * 0.55f ), - 0.0f, - 30.0f * cosf( t * 0.75f ) - ); - - glm::quat particleEmitterRotation = glm::quat(glm::radians(tilt)); + const std::vector& fingerTips = _myAvatar.getHand().getFingerTips(); + const std::vector& fingerRoots = _myAvatar.getHand().getFingerRoots(); + const std::vector& handPositions = _myAvatar.getHand().getHandPositions(); + const std::vector& handNormals = _myAvatar.getHand().getHandNormals(); - _particleSystem.setEmitterPosition(_fingerParticleEmitter, particleEmitterPosition); - _particleSystem.setEmitterRotation(_fingerParticleEmitter, particleEmitterRotation); + for ( int f = 0; f< fingerTips.size(); f ++ ) { - float radius = 0.01f; - glm::vec4 color(1.0f, 1.0f, 1.0f, 1.0f); - glm::vec3 velocity(0.0f, 0.01f, 0.0f); - float lifespan = 0.4f; - _particleSystem.emitParticlesNow(_fingerParticleEmitter, 1, radius, color, velocity, lifespan); + if (_fingerParticleEmitter[f] != -1) { + + glm::vec3 particleEmitterPosition = _myAvatar.getHand().leapPositionToWorldPosition(fingerTips[f]); + + glm::vec3 tilt = glm::vec3 + ( + 30.0f * sinf( t * 0.55f ), + 0.0f, + 30.0f * cosf( t * 0.75f ) + ); + + glm::quat particleEmitterRotation = glm::quat(glm::radians(tilt)); + + _particleSystem.setEmitterPosition(_fingerParticleEmitter[0], particleEmitterPosition); + _particleSystem.setEmitterRotation(_fingerParticleEmitter[0], particleEmitterRotation); + + float radius = 0.01f; + glm::vec4 color(1.0f, 1.0f, 1.0f, 1.0f); + glm::vec3 velocity(0.0f, 0.01f, 0.0f); + float lifespan = 0.4f; + _particleSystem.emitParticlesNow(_fingerParticleEmitter[0], 1, radius, color, velocity, lifespan); + } } _particleSystem.setUpDirection(glm::vec3(0.0f, 1.0f, 0.0f)); diff --git a/interface/src/Application.h b/interface/src/Application.h index 789b18e011..2800904c3f 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -285,7 +285,7 @@ private: bool _justStarted; bool _particleSystemInitialized; int _coolDemoParticleEmitter; - int _fingerParticleEmitter; + int _fingerParticleEmitter[NUM_FINGERS_PER_HAND]; Stars _stars; diff --git a/interface/src/Hand.h b/interface/src/Hand.h index 1c25c85fbc..7056911871 100755 --- a/interface/src/Hand.h +++ b/interface/src/Hand.h @@ -18,6 +18,7 @@ #include #include +const int NUM_FINGERS_PER_HAND = 5; class Avatar; class ProgramObject; diff --git a/interface/src/LeapManager.cpp b/interface/src/LeapManager.cpp old mode 100755 new mode 100644 diff --git a/interface/src/ParticleSystem.cpp b/interface/src/ParticleSystem.cpp index 14aaedbac9..7364f215af 100644 --- a/interface/src/ParticleSystem.cpp +++ b/interface/src/ParticleSystem.cpp @@ -13,7 +13,6 @@ const float DEFAULT_PARTICLE_BOUNCE = 1.0f; const float DEFAULT_PARTICLE_AIR_FRICTION = 2.0f; -const float DEFAULT_PARTICLE_GRAVITY = 0.05f; ParticleSystem::ParticleSystem() { @@ -30,7 +29,7 @@ ParticleSystem::ParticleSystem() { _emitter[e].front = IDENTITY_FRONT; _emitter[e].bounce = DEFAULT_PARTICLE_BOUNCE; _emitter[e].airFriction = DEFAULT_PARTICLE_AIR_FRICTION; - _emitter[e].gravity = DEFAULT_PARTICLE_GRAVITY; + _emitter[e].gravity = 0.0f; _emitter[e].jitter = 0.0f; _emitter[e].emitterAttraction = 0.0f; _emitter[e].tornadoForce = 0.0f; @@ -56,11 +55,20 @@ ParticleSystem::ParticleSystem() { int ParticleSystem::addEmitter() { + + printf( "\n" ); + printf( "ParticleSystem::addEmitter\n" ); + _numEmitters ++; if (_numEmitters > MAX_EMITTERS) { + + printf( "Oops! _numEmitters > MAX_EMITTERS... returning -1\n" ); + return -1; } + + printf( "ok, _numEmitters is %d,and the index of this newly added emitter is %d.\n", _numEmitters, _numEmitters-1 ); return _numEmitters - 1; } @@ -153,13 +161,13 @@ void ParticleSystem::runSpecialEffectsTest(int e, float deltaTime) { _timer += deltaTime; - _emitter[e].gravity = 0.0f + DEFAULT_PARTICLE_GRAVITY * sinf( _timer * 0.52f ); + _emitter[e].gravity = 0.0f + 0.05f * sinf( _timer * 0.52f ); _emitter[e].airFriction = (DEFAULT_PARTICLE_AIR_FRICTION + 0.5f) + 2.0f * sinf( _timer * 0.32f ); - _emitter[e].jitter = 0.05f + 0.05f * sinf( _timer * 0.42f ); - _emitter[e].emitterAttraction = 0.015f + 0.015f * cosf( _timer * 0.6f ); - _emitter[e].tornadoForce = 0.0f + 0.03f * sinf( _timer * 0.7f ); - _emitter[e].neighborAttraction = 0.1f + 0.1f * cosf( _timer * 0.8f ); - _emitter[e].neighborRepulsion = 0.2f + 0.2f * sinf( _timer * 0.4f ); + _emitter[e].jitter = 0.05f + 0.05f * sinf( _timer * 0.42f ); + _emitter[e].emitterAttraction = 0.015f + 0.015f * cosf( _timer * 0.6f ); + _emitter[e].tornadoForce = 0.0f + 0.03f * sinf( _timer * 0.7f ); + _emitter[e].neighborAttraction = 0.1f + 0.1f * cosf( _timer * 0.8f ); + _emitter[e].neighborRepulsion = 0.2f + 0.2f * sinf( _timer * 0.4f ); if (_emitter[e].gravity < 0.0f) { _emitter[e].gravity = 0.0f; From 26c0eb2dea0556bf0bd011d08a0c576d429b3c3e Mon Sep 17 00:00:00 2001 From: Philip Rosedale Date: Mon, 15 Jul 2013 16:27:46 -0700 Subject: [PATCH 20/81] Start to add heartbeat --- interface/src/Audio.cpp | 10 +++++++++- interface/src/Audio.h | 1 + 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index a724f7b288..a2b3f08535 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -327,7 +327,8 @@ Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples) : _flangeRate(0.0f), _flangeWeight(0.0f), _collisionSoundMagnitude(0.0f), - _proceduralEffectSample(0) + _proceduralEffectSample(0), + _heartbeatMagnitude(0.0f) { outputPortAudioError(Pa_Initialize()); @@ -601,6 +602,9 @@ void Audio::addProceduralSounds(int16_t* inputBuffer, inputBuffer[i] += (int16_t) (_proceduralEffectSample + i)%16 * 10; }*/ + // + // Travelling noise + // // Add a noise-modulated sinewave with volume that tapers off with speed increasing if ((speed > MIN_AUDIBLE_VELOCITY) && (speed < MAX_AUDIBLE_VELOCITY)) { for (int i = 0; i < numSamples; i++) { @@ -624,6 +628,10 @@ void Audio::addProceduralSounds(int16_t* inputBuffer, _collisionSoundMagnitude *= (1.f - COLLISION_SOUND_DECAY); } } + + //if (_heartbeatMagnitude > 0.0f) { + // + //} _proceduralEffectSample += numSamples; } diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 715cfeafc8..1ab671a30b 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -85,6 +85,7 @@ private: float _flangeWeight; float _collisionSoundMagnitude; int _proceduralEffectSample; + float _heartbeatMagnitude; // Audio callback in class context. inline void performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* outputRight); From 0481a81ca7639127b494267a71e0fbba93f20588 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Mon, 15 Jul 2013 17:58:17 -0700 Subject: [PATCH 21/81] moved finger particles over to hand.cpp --- interface/src/Application.cpp | 169 ++++++++++++++----------------- interface/src/Application.h | 3 +- interface/src/Hand.cpp | 61 ++++++++++- interface/src/Hand.h | 10 +- interface/src/ParticleSystem.cpp | 106 +++++++++---------- interface/src/ParticleSystem.h | 52 +++++----- 6 files changed, 225 insertions(+), 176 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 1b050bc874..16af90ef12 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -73,7 +73,7 @@ using namespace std; static char STAR_FILE[] = "https://s3-us-west-1.amazonaws.com/highfidelity/stars.txt"; static char STAR_CACHE_FILE[] = "cachedStars.txt"; -static const bool TESTING_PARTICLE_SYSTEM = true; +static const bool TESTING_PARTICLE_SYSTEM = false; static const int BANDWIDTH_METER_CLICK_MAX_DRAG_LENGTH = 6; // farther dragged clicks are ignored @@ -209,12 +209,6 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : _bytesCount(0), _swatch(NULL) { - - // initialize all finger particle emitters with an invalid id as default - for (int f = 0; f< NUM_FINGERS_PER_HAND; f ++ ) { - _fingerParticleEmitter[f] = -1; - } - _applicationStartupTime = startup_time; _window->setWindowTitle("Interface"); printLog("Interface Startup:\n"); @@ -1995,6 +1989,8 @@ void Application::update(float deltaTime) { _myAvatar.simulate(deltaTime, NULL); } + _myAvatar.getHand().simulate(deltaTime, true); + if (!OculusManager::isConnected()) { if (_lookingInMirror->isChecked()) { if (_myCamera.getMode() != CAMERA_MODE_MIRROR) { @@ -2043,90 +2039,8 @@ void Application::update(float deltaTime) { #endif if (TESTING_PARTICLE_SYSTEM) { - if (!_particleSystemInitialized) { - - // create a stable test emitter and spit out a bunch of particles - _coolDemoParticleEmitter = _particleSystem.addEmitter(); - - if (_coolDemoParticleEmitter != -1) { - _particleSystem.setShowingEmitter(_coolDemoParticleEmitter, true); - glm::vec3 particleEmitterPosition = glm::vec3(5.0f, 1.0f, 5.0f); - _particleSystem.setEmitterPosition(_coolDemoParticleEmitter, particleEmitterPosition); - float radius = 0.01f; - glm::vec4 color(0.0f, 0.0f, 0.0f, 1.0f); - glm::vec3 velocity(0.0f, 0.1f, 0.0f); - float lifespan = 100000.0f; - - // determine a collision sphere - glm::vec3 collisionSpherePosition = glm::vec3( 5.0f, 0.5f, 5.0f ); - float collisionSphereRadius = 0.5f; - _particleSystem.setCollisionSphere(_coolDemoParticleEmitter, collisionSpherePosition, collisionSphereRadius); - _particleSystem.emitParticlesNow(_coolDemoParticleEmitter, 1500, radius, color, velocity, lifespan); - } - - for ( int f = 0; f< NUM_FINGERS_PER_HAND; f ++ ) { - _fingerParticleEmitter[f] = _particleSystem.addEmitter(); - _particleSystem.setShowingEmitter(_fingerParticleEmitter[f], true); - } - - // signal that the particle system has been initialized - _particleSystemInitialized = true; - - // apply a preset color palette - _particleSystem.setOrangeBlueColorPalette(); - } else { - // update the particle system - - static float t = 0.0f; - t += deltaTime; - - if (_coolDemoParticleEmitter != -1) { - - glm::vec3 tilt = glm::vec3 - ( - 30.0f * sinf( t * 0.55f ), - 0.0f, - 30.0f * cosf( t * 0.75f ) - ); - - _particleSystem.setEmitterRotation(_coolDemoParticleEmitter, glm::quat(glm::radians(tilt))); - } - - const std::vector& fingerTips = _myAvatar.getHand().getFingerTips(); - const std::vector& fingerRoots = _myAvatar.getHand().getFingerRoots(); - const std::vector& handPositions = _myAvatar.getHand().getHandPositions(); - const std::vector& handNormals = _myAvatar.getHand().getHandNormals(); - - for ( int f = 0; f< fingerTips.size(); f ++ ) { - - if (_fingerParticleEmitter[f] != -1) { - - glm::vec3 particleEmitterPosition = _myAvatar.getHand().leapPositionToWorldPosition(fingerTips[f]); - - glm::vec3 tilt = glm::vec3 - ( - 30.0f * sinf( t * 0.55f ), - 0.0f, - 30.0f * cosf( t * 0.75f ) - ); - - glm::quat particleEmitterRotation = glm::quat(glm::radians(tilt)); - - _particleSystem.setEmitterPosition(_fingerParticleEmitter[0], particleEmitterPosition); - _particleSystem.setEmitterRotation(_fingerParticleEmitter[0], particleEmitterRotation); - - float radius = 0.01f; - glm::vec4 color(1.0f, 1.0f, 1.0f, 1.0f); - glm::vec3 velocity(0.0f, 0.01f, 0.0f); - float lifespan = 0.4f; - _particleSystem.emitParticlesNow(_fingerParticleEmitter[0], 1, radius, color, velocity, lifespan); - } - } - - _particleSystem.setUpDirection(glm::vec3(0.0f, 1.0f, 0.0f)); - _particleSystem.simulate(deltaTime); - } - } + updateParticleSystem(deltaTime); + } } void Application::updateAvatar(float deltaTime) { @@ -3471,3 +3385,76 @@ void Application::exportSettings() { } + +void Application::updateParticleSystem(float deltaTime) { + + if (!_particleSystemInitialized) { + // create a stable test emitter and spit out a bunch of particles + _coolDemoParticleEmitter = _particleSystem.addEmitter(); + + if (_coolDemoParticleEmitter != -1) { + _particleSystem.setShowingEmitter(_coolDemoParticleEmitter, true); + glm::vec3 particleEmitterPosition = glm::vec3(5.0f, 1.0f, 5.0f); + _particleSystem.setEmitterPosition(_coolDemoParticleEmitter, particleEmitterPosition); + float radius = 0.01f; + glm::vec4 color(0.0f, 0.0f, 0.0f, 1.0f); + glm::vec3 velocity(0.0f, 0.1f, 0.0f); + float lifespan = 100000.0f; + + // determine a collision sphere + glm::vec3 collisionSpherePosition = glm::vec3( 5.0f, 0.5f, 5.0f ); + float collisionSphereRadius = 0.5f; + _particleSystem.setCollisionSphere(_coolDemoParticleEmitter, collisionSpherePosition, collisionSphereRadius); + _particleSystem.emitParticlesNow(_coolDemoParticleEmitter, 1500, radius, color, velocity, lifespan); + } + + // signal that the particle system has been initialized + _particleSystemInitialized = true; + + // apply a preset color palette + _particleSystem.setOrangeBlueColorPalette(); + } else { + // update the particle system + + static float t = 0.0f; + t += deltaTime; + + if (_coolDemoParticleEmitter != -1) { + + glm::vec3 tilt = glm::vec3 + ( + 30.0f * sinf( t * 0.55f ), + 0.0f, + 30.0f * cosf( t * 0.75f ) + ); + + _particleSystem.setEmitterRotation(_coolDemoParticleEmitter, glm::quat(glm::radians(tilt))); + + ParticleSystem::ParticleAttributes attributes; + + attributes.gravity = 0.0f + 0.05f * sinf( t * 0.52f ); + attributes.airFriction = 2.5 + 2.0f * sinf( t * 0.32f ); + attributes.jitter = 0.05f + 0.05f * sinf( t * 0.42f ); + attributes.emitterAttraction = 0.015f + 0.015f * cosf( t * 0.6f ); + attributes.tornadoForce = 0.0f + 0.03f * sinf( t * 0.7f ); + attributes.neighborAttraction = 0.1f + 0.1f * cosf( t * 0.8f ); + attributes.neighborRepulsion = 0.2f + 0.2f * sinf( t * 0.4f ); + attributes.bounce = 1.0f; + attributes.usingCollisionSphere = true; + attributes.collisionSpherePosition = glm::vec3( 5.0f, 0.5f, 5.0f ); + attributes.collisionSphereRadius = 0.5f; + + if (attributes.gravity < 0.0f) { + attributes.gravity = 0.0f; + } + + _particleSystem.setParticleAttributesForEmitter(_coolDemoParticleEmitter, attributes); + } + + _particleSystem.setUpDirection(glm::vec3(0.0f, 1.0f, 0.0f)); + _particleSystem.simulate(deltaTime); + } +} + + + diff --git a/interface/src/Application.h b/interface/src/Application.h index 2800904c3f..7ecee0cbec 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -83,6 +83,8 @@ public: const glm::vec3 getMouseVoxelWorldCoordinates(const VoxelDetail _mouseVoxel); + void updateParticleSystem(float deltaTime); + Avatar* getAvatar() { return &_myAvatar; } Camera* getCamera() { return &_myCamera; } ViewFrustum* getViewFrustum() { return &_viewFrustum; } @@ -285,7 +287,6 @@ private: bool _justStarted; bool _particleSystemInitialized; int _coolDemoParticleEmitter; - int _fingerParticleEmitter[NUM_FINGERS_PER_HAND]; Stars _stars; diff --git a/interface/src/Hand.cpp b/interface/src/Hand.cpp index 29a2c32bf1..fa08db7f27 100755 --- a/interface/src/Hand.cpp +++ b/interface/src/Hand.cpp @@ -23,8 +23,13 @@ Hand::Hand(Avatar* owningAvatar) : _lookingInMirror(false), _ballColor(0.0, 0.0, 0.4), _position(0.0, 0.4, 0.0), - _orientation(0.0, 0.0, 0.0, 1.0) + _orientation(0.0, 0.0, 0.0, 1.0), + _particleSystemInitialized(false) { + // initialize all finger particle emitters with an invalid id as default + for (int f = 0; f< NUM_FINGERS_PER_HAND; f ++ ) { + _fingerParticleEmitter[f] = -1; + } } void Hand::init() { @@ -40,6 +45,7 @@ void Hand::reset() { } void Hand::simulate(float deltaTime, bool isMine) { + updateFingerParticles(deltaTime); } glm::vec3 Hand::leapPositionToWorldPosition(const glm::vec3& leapPosition) { @@ -69,6 +75,10 @@ void Hand::calculateGeometry() { void Hand::render(bool lookingInMirror) { + if (_particleSystemInitialized) { + _particleSystem.render(); + } + _renderAlpha = 1.0; _lookingInMirror = lookingInMirror; @@ -132,3 +142,52 @@ void Hand::setLeapHands(const std::vector& handPositions, } +void Hand::updateFingerParticles(float deltaTime) { + + if (!_particleSystemInitialized) { + for ( int f = 0; f< NUM_FINGERS_PER_HAND; f ++ ) { + _fingerParticleEmitter[f] = _particleSystem.addEmitter(); + _particleSystem.setShowingEmitter(_fingerParticleEmitter[f], true); + } + _particleSystemInitialized = true; + } else { + // update the particles + + static float t = 0.0f; + t += deltaTime; + + for ( int f = 0; f< _fingerTips.size(); f ++ ) { + + if (_fingerParticleEmitter[f] != -1) { + + glm::vec3 particleEmitterPosition = leapPositionToWorldPosition(_fingerTips[f]); + + // this aspect is still being designed.... + + glm::vec3 tilt = glm::vec3 + ( + 30.0f * sinf( t * 0.55f ), + 0.0f, + 30.0f * cosf( t * 0.75f ) + ); + + glm::quat particleEmitterRotation = glm::quat(glm::radians(tilt)); + + _particleSystem.setEmitterPosition(_fingerParticleEmitter[0], particleEmitterPosition); + _particleSystem.setEmitterRotation(_fingerParticleEmitter[0], particleEmitterRotation); + + float radius = 0.005f; + glm::vec4 color(1.0f, 0.6f, 0.0f, 0.5f); + glm::vec3 velocity(0.0f, 0.005f, 0.0f); + float lifespan = 0.3f; + _particleSystem.emitParticlesNow(_fingerParticleEmitter[0], 1, radius, color, velocity, lifespan); + } + } + + _particleSystem.setUpDirection(glm::vec3(0.0f, 1.0f, 0.0f)); + _particleSystem.simulate(deltaTime); + } +} + + + diff --git a/interface/src/Hand.h b/interface/src/Hand.h index 7056911871..f9c451ff84 100755 --- a/interface/src/Hand.h +++ b/interface/src/Hand.h @@ -15,6 +15,7 @@ #include "world.h" #include "InterfaceConfig.h" #include "SerialInterface.h" +#include "ParticleSystem.h" #include #include @@ -47,7 +48,9 @@ public: const std::vector& fingerRoots); void setLeapHands (const std::vector& handPositions, const std::vector& handNormals); - + + void updateFingerParticles(float deltaTime); + // getters const glm::vec3& getLeapBallPosition (int ball) const { return _leapBalls[ball].position;} @@ -58,6 +61,8 @@ private: // disallow copies of the Hand, copy of owning Avatar is disallowed too Hand(const Hand&); Hand& operator= (const Hand&); + + ParticleSystem _particleSystem; Avatar* _owningAvatar; float _renderAlpha; @@ -67,6 +72,9 @@ private: glm::quat _orientation; std::vector _leapBalls; + bool _particleSystemInitialized; + int _fingerParticleEmitter[NUM_FINGERS_PER_HAND]; + // private methods void renderHandSpheres(); void calculateGeometry(); diff --git a/interface/src/ParticleSystem.cpp b/interface/src/ParticleSystem.cpp index 7364f215af..fcc24a2663 100644 --- a/interface/src/ParticleSystem.cpp +++ b/interface/src/ParticleSystem.cpp @@ -22,24 +22,23 @@ ParticleSystem::ParticleSystem() { _upDirection = glm::vec3(0.0f, 1.0f, 0.0f); // default for (unsigned int e = 0; e < MAX_EMITTERS; e++) { - _emitter[e].position = glm::vec3(0.0f, 0.0f, 0.0f); - _emitter[e].rotation = glm::quat(); - _emitter[e].right = IDENTITY_RIGHT; - _emitter[e].up = IDENTITY_UP; - _emitter[e].front = IDENTITY_FRONT; - _emitter[e].bounce = DEFAULT_PARTICLE_BOUNCE; - _emitter[e].airFriction = DEFAULT_PARTICLE_AIR_FRICTION; - _emitter[e].gravity = 0.0f; - _emitter[e].jitter = 0.0f; - _emitter[e].emitterAttraction = 0.0f; - _emitter[e].tornadoForce = 0.0f; - _emitter[e].neighborAttraction = 0.0f; - _emitter[e].neighborRepulsion = 0.0f; - _emitter[e].collisionSphereRadius = 0.0f; - _emitter[e].collisionSpherePosition = glm::vec3(0.0f, 0.0f, 0.0f); - _emitter[e].usingCollisionSphere = false; - _emitter[e].showingEmitter = false; - + _emitter[e].position = glm::vec3(0.0f, 0.0f, 0.0f); + _emitter[e].rotation = glm::quat(); + _emitter[e].right = IDENTITY_RIGHT; + _emitter[e].up = IDENTITY_UP; + _emitter[e].front = IDENTITY_FRONT; + _emitter[e].showingEmitter = false; + _emitter[e].particleAttributes.bounce = DEFAULT_PARTICLE_BOUNCE; + _emitter[e].particleAttributes.airFriction = DEFAULT_PARTICLE_AIR_FRICTION; + _emitter[e].particleAttributes.gravity = 0.0f; + _emitter[e].particleAttributes.jitter = 0.0f; + _emitter[e].particleAttributes.emitterAttraction = 0.0f; + _emitter[e].particleAttributes.tornadoForce = 0.0f; + _emitter[e].particleAttributes.neighborAttraction = 0.0f; + _emitter[e].particleAttributes.neighborRepulsion = 0.0f; + _emitter[e].particleAttributes.collisionSphereRadius = 0.0f; + _emitter[e].particleAttributes.collisionSpherePosition = glm::vec3(0.0f, 0.0f, 0.0f); + _emitter[e].particleAttributes.usingCollisionSphere = false; }; for (unsigned int p = 0; p < MAX_PARTICLES; p++) { @@ -56,19 +55,11 @@ ParticleSystem::ParticleSystem() { int ParticleSystem::addEmitter() { - printf( "\n" ); - printf( "ParticleSystem::addEmitter\n" ); - _numEmitters ++; if (_numEmitters > MAX_EMITTERS) { - - printf( "Oops! _numEmitters > MAX_EMITTERS... returning -1\n" ); - return -1; } - - printf( "ok, _numEmitters is %d,and the index of this newly added emitter is %d.\n", _numEmitters, _numEmitters-1 ); return _numEmitters - 1; } @@ -81,8 +72,6 @@ void ParticleSystem::simulate(float deltaTime) { updateEmitter(e, deltaTime); } - runSpecialEffectsTest(0, deltaTime); - // update particles for (unsigned int p = 0; p < _numParticles; p++) { if (_particle[p].alive) { @@ -157,24 +146,23 @@ void ParticleSystem::setOrangeBlueColorPalette() { } -void ParticleSystem::runSpecialEffectsTest(int e, float deltaTime) { +void ParticleSystem::setParticleAttributesForEmitter(int emitterIndex, ParticleAttributes attributes) { - _timer += deltaTime; - - _emitter[e].gravity = 0.0f + 0.05f * sinf( _timer * 0.52f ); - _emitter[e].airFriction = (DEFAULT_PARTICLE_AIR_FRICTION + 0.5f) + 2.0f * sinf( _timer * 0.32f ); - _emitter[e].jitter = 0.05f + 0.05f * sinf( _timer * 0.42f ); - _emitter[e].emitterAttraction = 0.015f + 0.015f * cosf( _timer * 0.6f ); - _emitter[e].tornadoForce = 0.0f + 0.03f * sinf( _timer * 0.7f ); - _emitter[e].neighborAttraction = 0.1f + 0.1f * cosf( _timer * 0.8f ); - _emitter[e].neighborRepulsion = 0.2f + 0.2f * sinf( _timer * 0.4f ); - - if (_emitter[e].gravity < 0.0f) { - _emitter[e].gravity = 0.0f; - } + _emitter[emitterIndex].particleAttributes.bounce = attributes.bounce; + _emitter[emitterIndex].particleAttributes.gravity = attributes.gravity; + _emitter[emitterIndex].particleAttributes.airFriction = attributes.airFriction; + _emitter[emitterIndex].particleAttributes.jitter = attributes.jitter; + _emitter[emitterIndex].particleAttributes.emitterAttraction = attributes.emitterAttraction; + _emitter[emitterIndex].particleAttributes.tornadoForce = attributes.tornadoForce; + _emitter[emitterIndex].particleAttributes.neighborAttraction = attributes.neighborAttraction; + _emitter[emitterIndex].particleAttributes.neighborRepulsion = attributes.neighborRepulsion; + _emitter[emitterIndex].particleAttributes.usingCollisionSphere = attributes.usingCollisionSphere; + _emitter[emitterIndex].particleAttributes.collisionSpherePosition = attributes.collisionSpherePosition; + _emitter[emitterIndex].particleAttributes.collisionSphereRadius = attributes.collisionSphereRadius; } + void ParticleSystem::updateParticle(int p, float deltaTime) { _particle[p].age += deltaTime; @@ -189,14 +177,14 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { _particle[p].velocity += glm::vec3 ( - -myEmitter.jitter * ONE_HALF + myEmitter.jitter * randFloat(), - -myEmitter.jitter * ONE_HALF + myEmitter.jitter * randFloat(), - -myEmitter.jitter * ONE_HALF + myEmitter.jitter * randFloat() + -myEmitter.particleAttributes.jitter * ONE_HALF + myEmitter.particleAttributes.jitter * randFloat(), + -myEmitter.particleAttributes.jitter * ONE_HALF + myEmitter.particleAttributes.jitter * randFloat(), + -myEmitter.particleAttributes.jitter * ONE_HALF + myEmitter.particleAttributes.jitter * randFloat() ) * deltaTime; // apply attraction to home position glm::vec3 vectorToHome = myEmitter.position - _particle[p].position; - _particle[p].velocity += vectorToHome * myEmitter.emitterAttraction * deltaTime; + _particle[p].velocity += vectorToHome * myEmitter.particleAttributes.emitterAttraction * deltaTime; // apply neighbor attraction int neighbor = p + 1; @@ -207,20 +195,20 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { if ( _particle[neighbor].emitterIndex == _particle[p].emitterIndex) { glm::vec3 vectorToNeighbor = _particle[p].position - _particle[neighbor].position; - _particle[p].velocity -= vectorToNeighbor * myEmitter.neighborAttraction * deltaTime; + _particle[p].velocity -= vectorToNeighbor * myEmitter.particleAttributes.neighborAttraction * deltaTime; float distanceToNeighbor = glm::length(vectorToNeighbor); if (distanceToNeighbor > 0.0f) { - _particle[neighbor].velocity += (vectorToNeighbor / ( 1.0f + distanceToNeighbor * distanceToNeighbor)) * myEmitter.neighborRepulsion * deltaTime; + _particle[neighbor].velocity += (vectorToNeighbor / ( 1.0f + distanceToNeighbor * distanceToNeighbor)) * myEmitter.particleAttributes.neighborRepulsion * deltaTime; } } // apply tornado force glm::vec3 tornadoDirection = glm::cross(vectorToHome, myEmitter.up); - _particle[p].velocity += tornadoDirection * myEmitter.tornadoForce * deltaTime; + _particle[p].velocity += tornadoDirection * myEmitter.particleAttributes.tornadoForce * deltaTime; // apply air friction - float drag = 1.0 - myEmitter.airFriction * deltaTime; + float drag = 1.0 - myEmitter.particleAttributes.airFriction * deltaTime; if (drag < 0.0f) { _particle[p].velocity = glm::vec3(0.0f, 0.0f, 0.0f); } else { @@ -228,7 +216,7 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { } // apply gravity - _particle[p].velocity -= _upDirection * myEmitter.gravity * deltaTime; + _particle[p].velocity -= _upDirection * myEmitter.particleAttributes.gravity * deltaTime; // update position by velocity _particle[p].position += _particle[p].velocity; @@ -238,29 +226,29 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { _particle[p].position.y = _particle[p].radius; if (_particle[p].velocity.y < 0.0f) { - _particle[p].velocity.y *= -myEmitter.bounce; + _particle[p].velocity.y *= -myEmitter.particleAttributes.bounce; } } // collision with sphere - if (myEmitter.usingCollisionSphere) { - glm::vec3 vectorToSphereCenter = myEmitter.collisionSpherePosition - _particle[p].position; + if (myEmitter.particleAttributes.usingCollisionSphere) { + glm::vec3 vectorToSphereCenter = myEmitter.particleAttributes.collisionSpherePosition - _particle[p].position; float distanceToSphereCenter = glm::length(vectorToSphereCenter); - float combinedRadius = myEmitter.collisionSphereRadius + _particle[p].radius; + float combinedRadius = myEmitter.particleAttributes.collisionSphereRadius + _particle[p].radius; if (distanceToSphereCenter < combinedRadius) { if (distanceToSphereCenter > 0.0f){ glm::vec3 directionToSphereCenter = vectorToSphereCenter / distanceToSphereCenter; - _particle[p].position = myEmitter.collisionSpherePosition - directionToSphereCenter * combinedRadius; + _particle[p].position = myEmitter.particleAttributes.collisionSpherePosition - directionToSphereCenter * combinedRadius; } } } } void ParticleSystem::setCollisionSphere(int e, glm::vec3 position, float radius) { - _emitter[e].usingCollisionSphere = true; - _emitter[e].collisionSpherePosition = position; - _emitter[e].collisionSphereRadius = radius; + _emitter[e].particleAttributes.usingCollisionSphere = true; + _emitter[e].particleAttributes.collisionSpherePosition = position; + _emitter[e].particleAttributes.collisionSphereRadius = radius; } void ParticleSystem::render() { diff --git a/interface/src/ParticleSystem.h b/interface/src/ParticleSystem.h index 3b8826d697..c94acd03ba 100644 --- a/interface/src/ParticleSystem.h +++ b/interface/src/ParticleSystem.h @@ -16,29 +16,8 @@ const int MAX_EMITTERS = 20; class ParticleSystem { public: - ParticleSystem(); - - int addEmitter(); // add (create) an emitter and get its unique id - void emitParticlesNow(int e, int numParticles, float radius, glm::vec4 color, glm::vec3 velocity, float lifespan); - void simulate(float deltaTime); - void render(); - - void setOrangeBlueColorPalette(); // apply a nice preset color palette to the particles - void setCollisionSphere(int e, glm::vec3 position, float radius); // specify a sphere for the particles to collide with - void setEmitterPosition(int e, glm::vec3 position) { _emitter[e].position = position; } // set the position of this emitter - void setEmitterRotation(int e, glm::quat rotation) { _emitter[e].rotation = rotation; } // set the rotation of this emitter - void setUpDirection(glm::vec3 upDirection) {_upDirection = upDirection;} // tell particle system which direction is up - void setShowingEmitter(int e, bool showing) { _emitter[e].showingEmitter = showing;} - - -private: - struct Emitter { - glm::vec3 position; - glm::quat rotation; - glm::vec3 right; - glm::vec3 up; - glm::vec3 front; + struct ParticleAttributes { float bounce; float gravity; float airFriction; @@ -50,7 +29,34 @@ private: bool usingCollisionSphere; glm::vec3 collisionSpherePosition; float collisionSphereRadius; + }; + + ParticleSystem(); + + int addEmitter(); // add (create) an emitter and get its unique id + void emitParticlesNow(int e, int numParticles, float radius, glm::vec4 color, glm::vec3 velocity, float lifespan); + void simulate(float deltaTime); + void render(); + + void setParticleAttributesForEmitter(int emitterIndex, ParticleAttributes attributes); + void setOrangeBlueColorPalette(); // apply a nice preset color palette to the particles + void setUpDirection(glm::vec3 upDirection) {_upDirection = upDirection;} // tell particle system which direction is up + + void setCollisionSphere(int emitterIndex, glm::vec3 position, float radius); // specify a sphere for the particles to collide with + void setEmitterPosition(int emitterIndex, glm::vec3 position) { _emitter[emitterIndex].position = position; } // set position of emitter + void setEmitterRotation(int emitterIndex, glm::quat rotation) { _emitter[emitterIndex].rotation = rotation; } // set rotation of emitter + void setShowingEmitter (int emitterIndex, bool showing ) { _emitter[emitterIndex].showingEmitter = showing; } // set its visibiity + +private: + + struct Emitter { + glm::vec3 position; + glm::quat rotation; + glm::vec3 right; + glm::vec3 up; + glm::vec3 front; bool showingEmitter; + ParticleAttributes particleAttributes; }; struct Particle { @@ -75,7 +81,7 @@ private: void updateEmitter(int e, float deltaTime); void updateParticle(int index, float deltaTime); void createParticle(int e, glm::vec3 position, glm::vec3 velocity, float radius, glm::vec4 color, float lifespan); - void runSpecialEffectsTest(int e, float deltaTime); // for debugging and artistic exploration + //void runSpecialEffectsTest(int e, float deltaTime); // for debugging and artistic exploration void killParticle(int p); void renderEmitter(int emitterIndex, float size); void renderParticle(int p); From edf031b98566e73efe3dee0499e26bce90193c81 Mon Sep 17 00:00:00 2001 From: Philip Rosedale Date: Mon, 15 Jul 2013 22:42:55 -0700 Subject: [PATCH 22/81] improve collision sounds, difference between ground and voxels --- interface/src/Audio.cpp | 18 +++++++++++++----- interface/src/Audio.h | 5 +++++ interface/src/Avatar.cpp | 34 +++++++++++++++++++++++++++------- interface/src/Avatar.h | 1 + 4 files changed, 46 insertions(+), 12 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 1e04e563a2..8b2856a7c9 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -333,6 +333,9 @@ Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples) : _flangeRate(0.0f), _flangeWeight(0.0f), _collisionSoundMagnitude(0.0f), + _collisionSoundFrequency(0.0f), + _collisionSoundNoise(0.0f), + _collisionSoundDuration(0.0f), _proceduralEffectSample(0), _heartbeatMagnitude(0.0f) { @@ -621,17 +624,16 @@ void Audio::addProceduralSounds(int16_t* inputBuffer, } } const float COLLISION_SOUND_CUTOFF_LEVEL = 5.0f; - const float COLLISION_SOUND_PITCH_1 = 2.0f; - const float COLLISION_SOUND_DECAY = 1.f/1024.f; - const float COLLISION_VOLUME_BASELINE = 10.f; int sample; if (_collisionSoundMagnitude > COLLISION_SOUND_CUTOFF_LEVEL) { for (int i = 0; i < numSamples; i++) { - sample = (int16_t) ((sinf((float) (_proceduralEffectSample + i) / COLLISION_SOUND_PITCH_1) * COLLISION_VOLUME_BASELINE * _collisionSoundMagnitude)); + sample = (int16_t) (((sinf(((float)_proceduralEffectSample + (float)i) * _collisionSoundFrequency) * (1.f - _collisionSoundNoise) + + ((randFloat() * 2.f - 1.0f) * _collisionSoundNoise)) + * _collisionSoundMagnitude)); inputBuffer[i] += sample; outputLeft[i] += sample; outputRight[i] += sample; - _collisionSoundMagnitude *= (1.f - COLLISION_SOUND_DECAY); + _collisionSoundMagnitude *= _collisionSoundDuration; } } @@ -641,6 +643,12 @@ void Audio::addProceduralSounds(int16_t* inputBuffer, _proceduralEffectSample += numSamples; } +void Audio::startCollisionSound(float magnitude, float frequency, float noise, float duration) { + _collisionSoundMagnitude = magnitude; + _collisionSoundFrequency = frequency; + _collisionSoundNoise = noise; + _collisionSoundDuration = duration; +} // ----------------------------------------------------------- // Accoustic ping (audio system round trip time determination) // ----------------------------------------------------------- diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 1ab671a30b..a43e05e3ec 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -46,6 +46,8 @@ public: void setCollisionSoundMagnitude(float collisionSoundMagnitude) { _collisionSoundMagnitude = collisionSoundMagnitude; } + void startCollisionSound(float magnitude, float frequency, float noise, float duration); + void ping(); // Call periodically to eventually perform round trip time analysis, @@ -84,6 +86,9 @@ private: float _flangeRate; float _flangeWeight; float _collisionSoundMagnitude; + float _collisionSoundFrequency; + float _collisionSoundNoise; + float _collisionSoundDuration; int _proceduralEffectSample; float _heartbeatMagnitude; diff --git a/interface/src/Avatar.cpp b/interface/src/Avatar.cpp index 289d5548c4..b3868f6ea7 100755 --- a/interface/src/Avatar.cpp +++ b/interface/src/Avatar.cpp @@ -873,12 +873,15 @@ void Avatar::updateCollisionWithEnvironment() { float radius = _height * 0.125f; const float ENVIRONMENT_SURFACE_ELASTICITY = 1.0f; const float ENVIRONMENT_SURFACE_DAMPING = 0.01; + const float ENVIRONMENT_COLLISION_FREQUENCY = 0.05f; glm::vec3 penetration; if (Application::getInstance()->getEnvironment()->findCapsulePenetration( _position - up * (_pelvisFloatingHeight - radius), _position + up * (_height - _pelvisFloatingHeight - radius), radius, penetration)) { + createCollisionSound(penetration, ENVIRONMENT_COLLISION_FREQUENCY); applyHardCollision(penetration, ENVIRONMENT_SURFACE_ELASTICITY, ENVIRONMENT_SURFACE_DAMPING); + } } @@ -887,10 +890,12 @@ void Avatar::updateCollisionWithVoxels() { float radius = _height * 0.125f; const float VOXEL_ELASTICITY = 1.4f; const float VOXEL_DAMPING = 0.0; + const float VOXEL_COLLISION_FREQUENCY = 0.5f; glm::vec3 penetration; if (Application::getInstance()->getVoxels()->findCapsulePenetration( _position - glm::vec3(0.0f, _pelvisFloatingHeight - radius, 0.0f), _position + glm::vec3(0.0f, _height - _pelvisFloatingHeight - radius, 0.0f), radius, penetration)) { + createCollisionSound(penetration, VOXEL_COLLISION_FREQUENCY); applyHardCollision(penetration, VOXEL_ELASTICITY, VOXEL_DAMPING); } } @@ -916,16 +921,31 @@ void Avatar::applyHardCollision(const glm::vec3& penetration, float elasticity, // If moving really slowly after a collision, and not applying forces, stop altogether _velocity *= 0.f; } - // Push the collision into the audio system for procedural effects - const float AUDIBLE_COLLISION_THRESHOLD = 200.f; - const float COLLISION_VOLUME = 10000.f; - float collisionSoundLevel = penetrationLength * COLLISION_VOLUME; - if (collisionSoundLevel > AUDIBLE_COLLISION_THRESHOLD) { - Application::getInstance()->getAudio()->setCollisionSoundMagnitude(collisionSoundLevel); - } } } +void Avatar::createCollisionSound(const glm::vec3 &penetration, float frequency) { + // Push the collision into the audio system for procedural effects + const float AUDIBLE_COLLISION_THRESHOLD = 0.2f; + const float COLLISION_VOLUME = 1000.f; + const float MAX_COLLISION_VOLUME = 15000.f; + const float DURATION_SCALING = 0.004f; + float velocityTowardCollision = glm::dot(_velocity, glm::normalize(penetration)); + float velocityTangentToCollision = glm::length(_velocity) - velocityTowardCollision; + if (velocityTowardCollision > AUDIBLE_COLLISION_THRESHOLD) { + Application::getInstance()->getAudio()->startCollisionSound( + fmax(COLLISION_VOLUME * velocityTowardCollision, MAX_COLLISION_VOLUME), + frequency, + fmin(velocityTangentToCollision / velocityTowardCollision, 1.f), + 1.f - DURATION_SCALING * powf(frequency, 0.5f) / velocityTowardCollision); + + } + //float collisionSoundLevel = penetrationLength * COLLISION_VOLUME; + //if (collisionSoundLevel > AUDIBLE_COLLISION_THRESHOLD) { + // Application::getInstance()->getAudio()->setCollisionSoundMagnitude(collisionSoundLevel); + //} +} + void Avatar::updateAvatarCollisions(float deltaTime) { // Reset detector for nearest avatar diff --git a/interface/src/Avatar.h b/interface/src/Avatar.h index 643a187a67..31c9b573b8 100755 --- a/interface/src/Avatar.h +++ b/interface/src/Avatar.h @@ -262,6 +262,7 @@ private: void updateCollisionWithEnvironment(); void updateCollisionWithVoxels(); void applyHardCollision(const glm::vec3& penetration, float elasticity, float damping); + void createCollisionSound(const glm::vec3& penetration, float frequency); void applyCollisionWithOtherAvatar( Avatar * other, float deltaTime ); void checkForMouseRayTouching(); }; From 7becb943570a98c957f335f3fc6fba7a9067615d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Jul 2013 09:41:34 -0700 Subject: [PATCH 23/81] reworking time stamps from doubles --- voxel-server/src/VoxelNodeData.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/voxel-server/src/VoxelNodeData.cpp b/voxel-server/src/VoxelNodeData.cpp index 28796435b5..2218724c79 100644 --- a/voxel-server/src/VoxelNodeData.cpp +++ b/voxel-server/src/VoxelNodeData.cpp @@ -84,8 +84,7 @@ void VoxelNodeData::updateLastKnownViewFrustum() { } // save that we know the view has been sent. - double now = usecTimestampNow(); - printf("updateLastKnownViewFrustum() setLastViewSent() to %lf\n", now); - setLastViewSent(now); + uint64_t now = usecTimestampNow(); + setLastTimeBagEmpty(now); // is this what we want? poor names } From afe49bc75617e0fd3b61799ac8e397352ec55335 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 16 Jul 2013 11:07:22 -0700 Subject: [PATCH 24/81] switch calls to printLog to QDebug --- animation-server/CMakeLists.txt | 2 +- audio-mixer/CMakeLists.txt | 2 +- avatar-mixer/CMakeLists.txt | 2 +- cmake/macros/SetupHifiLibrary.cmake | 10 ++- cmake/macros/SetupHifiProject.cmake | 12 ++- domain-server/CMakeLists.txt | 2 +- eve/CMakeLists.txt | 2 +- injector/CMakeLists.txt | 2 +- interface/src/Application.cpp | 26 +++--- interface/src/Application.h | 19 +++-- interface/src/Audio.cpp | 47 ++++++----- interface/src/Audio.h | 1 - interface/src/Avatar.cpp | 17 ++-- interface/src/Avatar.h | 11 ++- interface/src/AvatarVoxelSystem.cpp | 4 +- interface/src/BandwidthMeter.cpp | 1 - interface/src/Camera.cpp | 3 +- interface/src/LogDisplay.cpp | 31 +------ interface/src/LogDisplay.h | 10 +-- interface/src/SerialInterface.cpp | 30 ++++++- interface/src/SerialInterface.h | 39 +++------ interface/src/Transmitter.cpp | 8 +- interface/src/Util.cpp | 25 +++--- interface/src/VoxelSystem.cpp | 61 +++++++------- interface/src/Webcam.cpp | 21 +++-- interface/src/main.cpp | 7 +- interface/src/starfield/Config.h | 1 - interface/src/starfield/Loader.h | 10 +-- interface/src/ui/BandwidthDialog.cpp | 2 - libraries/shared/src/Log.cpp | 15 ---- libraries/shared/src/Log.h | 21 ----- libraries/shared/src/Node.cpp | 31 ++++--- libraries/shared/src/Node.h | 9 +- libraries/shared/src/NodeList.cpp | 19 ++--- libraries/shared/src/OctalCode.cpp | 10 ++- libraries/shared/src/PacketHeaders.cpp | 5 +- libraries/shared/src/PerfStat.cpp | 23 ++--- libraries/shared/src/SharedUtil.cpp | 27 +++--- libraries/shared/src/UDPSocket.cpp | 15 ++-- libraries/shared/src/UrlReader.cpp | 5 +- libraries/voxels/src/CoverageMap.cpp | 83 ++++++++++--------- libraries/voxels/src/CoverageMapV2.cpp | 20 +++-- libraries/voxels/src/GeometryUtil.cpp | 3 +- libraries/voxels/src/Plane.cpp | 2 - libraries/voxels/src/Tags.cpp | 11 ++- libraries/voxels/src/ViewFrustum.cpp | 51 ++++++------ libraries/voxels/src/ViewFrustum.h | 8 +- libraries/voxels/src/VoxelNode.cpp | 22 ++--- .../voxels/src/VoxelProjectedPolygon.cpp | 13 +-- libraries/voxels/src/VoxelTree.cpp | 66 ++++++++------- pairing-server/CMakeLists.txt | 2 +- space-server/CMakeLists.txt | 2 +- voxel-edit/CMakeLists.txt | 2 +- voxel-server/CMakeLists.txt | 2 +- 54 files changed, 420 insertions(+), 455 deletions(-) delete mode 100644 libraries/shared/src/Log.cpp delete mode 100644 libraries/shared/src/Log.h diff --git a/animation-server/CMakeLists.txt b/animation-server/CMakeLists.txt index e9662366af..de04acd8f7 100644 --- a/animation-server/CMakeLists.txt +++ b/animation-server/CMakeLists.txt @@ -14,7 +14,7 @@ include_glm(${TARGET_NAME} ${ROOT_DIR}) include(${MACRO_DIR}/SetupHifiProject.cmake) -setup_hifi_project(${TARGET_NAME}) +setup_hifi_project(${TARGET_NAME} TRUE) # link in the shared library include(${MACRO_DIR}/LinkHifiLibrary.cmake) diff --git a/audio-mixer/CMakeLists.txt b/audio-mixer/CMakeLists.txt index 7e83e6fc1a..472327de42 100644 --- a/audio-mixer/CMakeLists.txt +++ b/audio-mixer/CMakeLists.txt @@ -9,7 +9,7 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/../cmake set(TARGET_NAME audio-mixer) include(${MACRO_DIR}/SetupHifiProject.cmake) -setup_hifi_project(${TARGET_NAME}) +setup_hifi_project(${TARGET_NAME} TRUE) # set up the external glm library include(${MACRO_DIR}/IncludeGLM.cmake) diff --git a/avatar-mixer/CMakeLists.txt b/avatar-mixer/CMakeLists.txt index da25b6e981..33f603e228 100644 --- a/avatar-mixer/CMakeLists.txt +++ b/avatar-mixer/CMakeLists.txt @@ -10,7 +10,7 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/../cmake # setup the project include(${MACRO_DIR}/SetupHifiProject.cmake) -setup_hifi_project(${TARGET_NAME}) +setup_hifi_project(${TARGET_NAME} TRUE) # include glm include(${MACRO_DIR}/IncludeGLM.cmake) diff --git a/cmake/macros/SetupHifiLibrary.cmake b/cmake/macros/SetupHifiLibrary.cmake index 156ca186b2..b7d0af7499 100644 --- a/cmake/macros/SetupHifiLibrary.cmake +++ b/cmake/macros/SetupHifiLibrary.cmake @@ -1,9 +1,15 @@ MACRO(SETUP_HIFI_LIBRARY TARGET) - project(${TARGET_NAME}) + project(${TARGET}) # grab the implemenation and header files file(GLOB LIB_SRCS src/*.h src/*.cpp) # create a library and set the property so it can be referenced later - add_library(${TARGET_NAME} ${LIB_SRCS}) + add_library(${TARGET} ${LIB_SRCS}) + + find_package(Qt4 REQUIRED QtCore) + include(${QT_USE_FILE}) + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -isystem ${QT_QTGUI_INCLUDE_DIR}") + + target_link_libraries(${TARGET} ${QT_LIBRARIES}) ENDMACRO(SETUP_HIFI_LIBRARY _target) \ No newline at end of file diff --git a/cmake/macros/SetupHifiProject.cmake b/cmake/macros/SetupHifiProject.cmake index 3b6f130073..8360dc66b6 100644 --- a/cmake/macros/SetupHifiProject.cmake +++ b/cmake/macros/SetupHifiProject.cmake @@ -1,4 +1,4 @@ -MACRO(SETUP_HIFI_PROJECT TARGET) +MACRO(SETUP_HIFI_PROJECT TARGET INCLUDE_QT) project(${TARGET}) # grab the implemenation and header files @@ -6,4 +6,12 @@ MACRO(SETUP_HIFI_PROJECT TARGET) # add the executable add_executable(${TARGET} ${TARGET_SRCS}) -ENDMACRO(SETUP_HIFI_PROJECT _target) \ No newline at end of file + + IF (${INCLUDE_QT}) + find_package(Qt4 REQUIRED QtCore) + include(${QT_USE_FILE}) + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -isystem ${QT_QTGUI_INCLUDE_DIR}") + ENDIF() + + target_link_libraries(${TARGET} ${QT_LIBRARIES}) +ENDMACRO(SETUP_HIFI_PROJECT _target _include_qt) \ No newline at end of file diff --git a/domain-server/CMakeLists.txt b/domain-server/CMakeLists.txt index 27863f01df..4e1f0de298 100644 --- a/domain-server/CMakeLists.txt +++ b/domain-server/CMakeLists.txt @@ -6,7 +6,7 @@ set(MACRO_DIR ${ROOT_DIR}/cmake/macros) set(TARGET_NAME domain-server) include(${MACRO_DIR}/SetupHifiProject.cmake) -setup_hifi_project(${TARGET_NAME}) +setup_hifi_project(${TARGET_NAME} TRUE) # link the shared hifi library include(${MACRO_DIR}/LinkHifiLibrary.cmake) diff --git a/eve/CMakeLists.txt b/eve/CMakeLists.txt index acca9520ed..0a7691b781 100644 --- a/eve/CMakeLists.txt +++ b/eve/CMakeLists.txt @@ -9,7 +9,7 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/../cmake set(TARGET_NAME eve) include(${MACRO_DIR}/SetupHifiProject.cmake) -setup_hifi_project(${TARGET_NAME}) +setup_hifi_project(${TARGET_NAME} TRUE) include(${MACRO_DIR}/IncludeGLM.cmake) include_glm(${TARGET_NAME} ${ROOT_DIR}) diff --git a/injector/CMakeLists.txt b/injector/CMakeLists.txt index 2c022b0e92..ae9ed3d8ad 100644 --- a/injector/CMakeLists.txt +++ b/injector/CMakeLists.txt @@ -9,7 +9,7 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/../cmake set(TARGET_NAME injector) include(${MACRO_DIR}/SetupHifiProject.cmake) -setup_hifi_project(${TARGET_NAME}) +setup_hifi_project(${TARGET_NAME} TRUE) # set up the external glm library include(${MACRO_DIR}/IncludeGLM.cmake) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 4ea6e0bf84..a85fad9060 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -210,7 +210,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : { _applicationStartupTime = startup_time; _window->setWindowTitle("Interface"); - printLog("Interface Startup:\n"); + qDebug("Interface Startup:\n"); unsigned int listenPort = 0; // bind to an ephemeral port by default const char** constArgv = const_cast(argv); @@ -233,7 +233,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : // Handle Local Domain testing with the --local command line if (cmdOptionExists(argc, constArgv, "--local")) { - printLog("Local Domain MODE!\n"); + qDebug("Local Domain MODE!\n"); NodeList::getInstance()->setDomainIPToLocalhost(); } @@ -297,7 +297,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : } void Application::initializeGL() { - printLog( "Created Display Window.\n" ); + qDebug( "Created Display Window.\n" ); // initialize glut for shape drawing; Qt apparently initializes it on OS X #ifndef __APPLE__ @@ -312,10 +312,10 @@ void Application::initializeGL() { _viewFrustumOffsetCamera.setFarClip(500.0 * TREE_SCALE); initDisplay(); - printLog( "Initialized Display.\n" ); + qDebug( "Initialized Display.\n" ); init(); - printLog( "Init() complete.\n" ); + qDebug( "Init() complete.\n" ); // Check to see if the user passed in a command line option for randomizing colors bool wantColorRandomizer = !arguments().contains("--NoColorRandomizer"); @@ -324,13 +324,13 @@ void Application::initializeGL() { // Voxel File. If so, load it now. if (!_voxelsFilename.isEmpty()) { _voxels.loadVoxelsFile(_voxelsFilename.constData(), wantColorRandomizer); - printLog("Local Voxel File loaded.\n"); + qDebug("Local Voxel File loaded.\n"); } // create thread for receipt of data via UDP if (_enableNetworkThread) { pthread_create(&_networkReceiveThread, NULL, networkReceive, NULL); - printLog("Network receive thread created.\n"); + qDebug("Network receive thread created.\n"); } // call terminate before exiting @@ -352,7 +352,7 @@ void Application::initializeGL() { _justStarted = false; char title[50]; sprintf(title, "Interface: %4.2f seconds\n", startupTime); - printLog("%s", title); + qDebug("%s", title); _window->setWindowTitle(title); const char LOGSTASH_INTERFACE_START_TIME_KEY[] = "interface-start-time"; @@ -1446,7 +1446,7 @@ void Application::importVoxels() { if (fileNameString.endsWith(".png", Qt::CaseInsensitive)) { QImage pngImage = QImage(fileName); if (pngImage.height() != pngImage.width()) { - printLog("ERROR: Bad PNG size: height != width.\n"); + qDebug("ERROR: Bad PNG size: height != width.\n"); return; } @@ -1758,7 +1758,7 @@ void Application::init() { _audio.setJitterBufferSamples(_audioJitterBufferSamples); } - printLog("Loaded settings.\n"); + qDebug("Loaded settings.\n"); sendAvatarVoxelURLMessage(_myAvatar.getVoxels()->getVoxelURL()); @@ -2771,7 +2771,7 @@ glm::vec2 Application::getScaledScreenPoint(glm::vec2 projectedPoint) { // render the coverage map on screen void Application::renderCoverageMapV2() { - //printLog("renderCoverageMap()\n"); + //qDebug("renderCoverageMap()\n"); glDisable(GL_LIGHTING); glLineWidth(2.0); @@ -2816,7 +2816,7 @@ void Application::renderCoverageMapsV2Recursively(CoverageMapV2* map) { // render the coverage map on screen void Application::renderCoverageMap() { - //printLog("renderCoverageMap()\n"); + //qDebug("renderCoverageMap()\n"); glDisable(GL_LIGHTING); glLineWidth(2.0); @@ -3147,7 +3147,7 @@ void Application::eyedropperVoxelUnderCursor() { } void Application::goHome() { - printLog("Going Home!\n"); + qDebug("Going Home!\n"); _myAvatar.setPosition(START_LOCATION); } diff --git a/interface/src/Application.h b/interface/src/Application.h index 4e4101408f..f6332aef64 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -21,27 +21,28 @@ #include -#include "BandwidthMeter.h" -#include "ui/BandwidthDialog.h" - #ifndef _WIN32 #include "Audio.h" #endif +#include "Avatar.h" +#include "BandwidthMeter.h" #include "Camera.h" #include "Environment.h" #include "HandControl.h" +#include "PacketHeaders.h" +#include "ParticleSystem.h" +#include "renderer/GeometryCache.h" #include "SerialInterface.h" #include "Stars.h" +#include "Swatch.h" +#include "ToolsPalette.h" +#include "ui/ChatEntry.h" +#include "ui/BandwidthDialog.h" #include "ViewFrustum.h" #include "VoxelSystem.h" -#include "PacketHeaders.h" #include "Webcam.h" -#include "renderer/GeometryCache.h" -#include "ui/ChatEntry.h" -#include "ToolsPalette.h" -#include "Swatch.h" -#include "ParticleSystem.h" + class QAction; class QActionGroup; diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 63fc24f56d..4c707de938 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -7,24 +7,25 @@ // #ifndef _WIN32 -#include +#include #include + +#include #include #include -#include -#include -#include -#include -#include + +#include #include #include -#include +#include +#include +#include +#include #include "Application.h" #include "Audio.h" #include "Util.h" -#include "Log.h" // Uncomment the following definition to test audio device latency by copying output to input //#define TEST_AUDIO_LOOPBACK @@ -151,7 +152,7 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o // If not enough audio has arrived to start playback, keep waiting // #ifdef SHOW_AUDIO_DEBUG - printLog("%i,%i,%i,%i\n", + qDebug("%i,%i,%i,%i\n", _packetsReceivedThisPlayback, ringBuffer->diffLastWriteNextOutput(), PACKET_LENGTH_SAMPLES, @@ -168,7 +169,7 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o _packetsReceivedThisPlayback = 0; _wasStarved = 10; // Frames for which to render the indication that the system was starved. #ifdef SHOW_AUDIO_DEBUG - printLog("Starved, remaining samples = %d\n", + qDebug("Starved, remaining samples = %d\n", ringBuffer->diffLastWriteNextOutput()); #endif @@ -179,7 +180,7 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o if (!ringBuffer->isStarted()) { ringBuffer->setStarted(true); #ifdef SHOW_AUDIO_DEBUG - printLog("starting playback %0.1f msecs delayed, jitter = %d, pkts recvd: %d \n", + qDebug("starting playback %0.1f msecs delayed, jitter = %d, pkts recvd: %d \n", (usecTimestampNow() - usecTimestamp(&_firstPacketReceivedTime))/1000.0, _jitterBufferSamples, _packetsReceivedThisPlayback); @@ -299,8 +300,8 @@ int Audio::audioCallback (const void* inputBuffer, static void outputPortAudioError(PaError error) { if (error != paNoError) { - printLog("-- portaudio termination error --\n"); - printLog("PortAudio error (%d): %s\n", error, Pa_GetErrorText(error)); + qDebug("-- portaudio termination error --\n"); + qDebug("PortAudio error (%d): %s\n", error, Pa_GetErrorText(error)); } } @@ -349,7 +350,7 @@ Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples) : outputParameters.device = Pa_GetDefaultOutputDevice(); if (inputParameters.device == -1 || outputParameters.device == -1) { - printLog("Audio: Missing device.\n"); + qDebug("Audio: Missing device.\n"); outputPortAudioError(Pa_Terminate()); return; } @@ -384,12 +385,12 @@ Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples) : outputPortAudioError(Pa_StartStream(_stream)); // Uncomment these lines to see the system-reported latency - //printLog("Default low input, output latency (secs): %0.4f, %0.4f\n", + //qDebug("Default low input, output latency (secs): %0.4f, %0.4f\n", // Pa_GetDeviceInfo(Pa_GetDefaultInputDevice())->defaultLowInputLatency, // Pa_GetDeviceInfo(Pa_GetDefaultOutputDevice())->defaultLowOutputLatency); const PaStreamInfo* streamInfo = Pa_GetStreamInfo(_stream); - printLog("Started audio with reported latency msecs In/Out: %.0f, %.0f\n", streamInfo->inputLatency * 1000.f, + qDebug("Started audio with reported latency msecs In/Out: %.0f, %.0f\n", streamInfo->inputLatency * 1000.f, streamInfo->outputLatency * 1000.f); gettimeofday(&_lastReceiveTime, NULL); @@ -650,7 +651,7 @@ inline void Audio::eventuallySendRecvPing(int16_t* inputLeft, int16_t* outputLef // As of the next frame, we'll be recoding PING_FRAMES_TO_RECORD from // the mic (pointless to start now as we can't record unsent audio). _isSendingEchoPing = false; - printLog("Send audio ping\n"); + qDebug("Send audio ping\n"); } else if (_pingFramesToRecord > 0) { @@ -664,7 +665,7 @@ inline void Audio::eventuallySendRecvPing(int16_t* inputLeft, int16_t* outputLef if (_pingFramesToRecord == 0) { _pingAnalysisPending = true; - printLog("Received ping echo\n"); + qDebug("Received ping echo\n"); } } } @@ -688,25 +689,25 @@ inline void Audio::analyzePing() { // Determine extrema int botAt = findExtremum(_echoSamplesLeft, PING_SAMPLES_TO_ANALYZE, -1); if (botAt == -1) { - printLog("Audio Ping: Minimum not found.\n"); + qDebug("Audio Ping: Minimum not found.\n"); return; } int topAt = findExtremum(_echoSamplesLeft, PING_SAMPLES_TO_ANALYZE, 1); if (topAt == -1) { - printLog("Audio Ping: Maximum not found.\n"); + qDebug("Audio Ping: Maximum not found.\n"); return; } // Determine peak amplitude - warn if low int ampli = (_echoSamplesLeft[topAt] - _echoSamplesLeft[botAt]) / 2; if (ampli < PING_MIN_AMPLI) { - printLog("Audio Ping unreliable - low amplitude %d.\n", ampli); + qDebug("Audio Ping unreliable - low amplitude %d.\n", ampli); } // Determine period - warn if doesn't look like our signal int halfPeriod = abs(topAt - botAt); if (abs(halfPeriod-PING_HALF_PERIOD) > PING_MAX_PERIOD_DIFFERENCE) { - printLog("Audio Ping unreliable - peak distance %d vs. %d\n", halfPeriod, PING_HALF_PERIOD); + qDebug("Audio Ping unreliable - peak distance %d vs. %d\n", halfPeriod, PING_HALF_PERIOD); } // Ping is sent: @@ -747,7 +748,7 @@ inline void Audio::analyzePing() { int delay = (botAt + topAt) / 2 + PING_PERIOD; - printLog("\n| Audio Ping results:\n+----- ---- --- - - - - -\n\n" + qDebug("\n| Audio Ping results:\n+----- ---- --- - - - - -\n\n" "Delay = %d samples (%d ms)\nPeak amplitude = %d\n\n", delay, (delay * 1000) / int(SAMPLE_RATE), ampli); } diff --git a/interface/src/Audio.h b/interface/src/Audio.h index a3c8cf1046..d11a14444a 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -14,7 +14,6 @@ #include #include "Oscilloscope.h" -#include "Avatar.h" static const int NUM_AUDIO_CHANNELS = 2; diff --git a/interface/src/Avatar.cpp b/interface/src/Avatar.cpp index a1175e3b23..27ec1dd671 100755 --- a/interface/src/Avatar.cpp +++ b/interface/src/Avatar.cpp @@ -5,24 +5,25 @@ // Created by Philip Rosedale on 9/11/12. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +#include + #include #include #include -#include + +#include +#include +#include +#include #include -#include "world.h" + #include "Application.h" #include "Avatar.h" #include "Hand.h" #include "Head.h" -#include "Log.h" #include "Physics.h" +#include "world.h" #include "ui/TextRenderer.h" -#include -#include -#include -#include - using namespace std; diff --git a/interface/src/Avatar.h b/interface/src/Avatar.h index 643a187a67..f41094173c 100755 --- a/interface/src/Avatar.h +++ b/interface/src/Avatar.h @@ -10,18 +10,21 @@ #include #include -#include + #include -#include "world.h" + +#include + #include "AvatarTouch.h" #include "AvatarVoxelSystem.h" -#include "InterfaceConfig.h" -#include "SerialInterface.h" #include "Balls.h" #include "Hand.h" #include "Head.h" +#include "InterfaceConfig.h" #include "Skeleton.h" +#include "SerialInterface.h" #include "Transmitter.h" +#include "world.h" const float BODY_BALL_RADIUS_PELVIS = 0.07; const float BODY_BALL_RADIUS_TORSO = 0.065; diff --git a/interface/src/AvatarVoxelSystem.cpp b/interface/src/AvatarVoxelSystem.cpp index 99514ce7d0..c85ea1a343 100644 --- a/interface/src/AvatarVoxelSystem.cpp +++ b/interface/src/AvatarVoxelSystem.cpp @@ -93,7 +93,7 @@ const Mode MODES[] = { void AvatarVoxelSystem::cycleMode() { _mode = (_mode + 1) % (sizeof(MODES) / sizeof(MODES[0])); - printLog("Voxeltar bind mode %d.\n", _mode); + qDebug("Voxeltar bind mode %d.\n", _mode); // rebind QUrl url = _voxelURL; @@ -255,7 +255,7 @@ void AvatarVoxelSystem::handleVoxelDownloadProgress(qint64 bytesReceived, qint64 } void AvatarVoxelSystem::handleVoxelReplyError() { - printLog("%s\n", _voxelReply->errorString().toAscii().constData()); + qDebug("%s\n", _voxelReply->errorString().toAscii().constData()); _voxelReply->disconnect(this); _voxelReply->deleteLater(); diff --git a/interface/src/BandwidthMeter.cpp b/interface/src/BandwidthMeter.cpp index 5e0d63d6c5..1c1fa62297 100644 --- a/interface/src/BandwidthMeter.cpp +++ b/interface/src/BandwidthMeter.cpp @@ -9,7 +9,6 @@ #include "BandwidthMeter.h" #include "InterfaceConfig.h" -#include "Log.h" #include "Util.h" namespace { // .cpp-local diff --git a/interface/src/Camera.cpp b/interface/src/Camera.cpp index 8aaec5b899..a9db96e65c 100644 --- a/interface/src/Camera.cpp +++ b/interface/src/Camera.cpp @@ -5,9 +5,10 @@ // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. #include + #include #include -#include "Log.h" + #include "Camera.h" #include "Util.h" diff --git a/interface/src/LogDisplay.cpp b/interface/src/LogDisplay.cpp index 6a65c30021..708bb192d3 100644 --- a/interface/src/LogDisplay.cpp +++ b/interface/src/LogDisplay.cpp @@ -26,9 +26,7 @@ LogDisplay LogDisplay::instance; // State management // -LogDisplay::LogDisplay() : - - +LogDisplay::LogDisplay() : _textRenderer(SANS_FONT_FAMILY, -1, -1, false, TextRenderer::SHADOW_EFFECT), _stream(DEFAULT_STREAM), _chars(0l), @@ -53,8 +51,6 @@ LogDisplay::LogDisplay() : memset(_lines, 0, LINE_BUFFER_SIZE * sizeof(char*)); setCharacterSize(DEFAULT_CHAR_WIDTH, DEFAULT_CHAR_HEIGHT); - - printLog = & printLogHandler; } @@ -92,31 +88,6 @@ void LogDisplay::setCharacterSize(unsigned width, unsigned height) { // Logging // -int LogDisplay::printLogHandler(char const* fmt, ...) { - - va_list args; - int n; - char buf[MAX_MESSAGE_LENGTH]; - va_start(args,fmt); - - // print to buffer - n = vsnprintf(buf, MAX_MESSAGE_LENGTH, fmt, args); - if (n > 0) { - - // all fine? log the message - instance.addMessage(buf); - - } else { - - // error? -> mutter on stream or stderr - fprintf(instance._stream != 0l ? instance._stream : stderr, - "Log: Failed to log message with format string = \"%s\".\n", fmt); - } - - va_end(args); - return n; -} - inline void LogDisplay::addMessage(char const* ptr) { pthread_mutex_lock(& _mutex); diff --git a/interface/src/LogDisplay.h b/interface/src/LogDisplay.h index f699cb5279..bb74872dbd 100644 --- a/interface/src/LogDisplay.h +++ b/interface/src/LogDisplay.h @@ -12,7 +12,6 @@ #include #include -#include "Log.h" #include "ui/TextRenderer.h" class LogDisplay { @@ -21,6 +20,9 @@ public: static LogDisplay instance; void render(unsigned screenWidth, unsigned screenHeight); + + // log formatted message + inline void addMessage(char const*); // settings @@ -50,12 +52,6 @@ private: LogDisplay(LogDisplay const&); // = delete; LogDisplay& operator=(LogDisplay const&); // = delete; - // format and log message - entrypoint used to replace global 'printLog' - static int printLogHandler(char const* fmt, ...); - - // log formatted message (called by printLogHandler) - inline void addMessage(char const*); - TextRenderer _textRenderer; FILE* _stream; // FILE as secondary destination for log messages char* _chars; // character buffer base address diff --git a/interface/src/SerialInterface.cpp b/interface/src/SerialInterface.cpp index aac1f8f1f2..0f90ee8dd7 100644 --- a/interface/src/SerialInterface.cpp +++ b/interface/src/SerialInterface.cpp @@ -36,6 +36,28 @@ const int LONG_TERM_RATE_SAMPLES = 1000; const bool USING_INVENSENSE_MPU9150 = 1; +SerialInterface::SerialInterface() : + _active(false), + _gravity(0, 0, 0), + _averageRotationRates(0, 0, 0), + _averageAcceleration(0, 0, 0), + _estimatedRotation(0, 0, 0), + _estimatedPosition(0, 0, 0), + _estimatedVelocity(0, 0, 0), + _lastAcceleration(0, 0, 0), + _lastRotationRates(0, 0, 0), + _compassMinima(-211, -132, -186), + _compassMaxima(89, 95, 98), + _angularVelocityToLinearAccel(0.003f, -0.001f, -0.006f, + -0.005f, -0.001f, -0.006f, + 0.010f, 0.004f, 0.007f), + _angularAccelToLinearAccel(0.0f, 0.0f, 0.002f, + 0.0f, 0.0f, 0.001f, + -0.002f, -0.002f, 0.0f) +{ + +} + void SerialInterface::pair() { #ifndef _WIN32 @@ -75,10 +97,10 @@ void SerialInterface::initializePort(char* portname) { #ifndef _WIN32 _serialDescriptor = open(portname, O_RDWR | O_NOCTTY | O_NDELAY); - printLog("Opening SerialUSB %s: ", portname); + qDebug("Opening SerialUSB %s: ", portname); if (_serialDescriptor == -1) { - printLog("Failed.\n"); + qDebug("Failed.\n"); return; } @@ -112,7 +134,7 @@ void SerialInterface::initializePort(char* portname) { mpu_set_sensors(INV_XYZ_GYRO | INV_XYZ_ACCEL | INV_XYZ_COMPASS); } - printLog("Connected.\n"); + qDebug("Connected.\n"); resetSerial(); _active = true; @@ -351,7 +373,7 @@ void SerialInterface::readData(float deltaTime) { gettimeofday(&now, NULL); if (diffclock(&lastGoodRead, &now) > NO_READ_MAXIMUM_MSECS) { - printLog("No data - Shutting down SerialInterface.\n"); + qDebug("No data - Shutting down SerialInterface.\n"); resetSerial(); } } else { diff --git a/interface/src/SerialInterface.h b/interface/src/SerialInterface.h index 6398953456..711ff56757 100644 --- a/interface/src/SerialInterface.h +++ b/interface/src/SerialInterface.h @@ -1,17 +1,14 @@ // // SerialInterface.h -// - +// hifi +// +// Created by Stephen Birarda on 2/15/13. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// #ifndef __interface__SerialInterface__ #define __interface__SerialInterface__ -#include -#include "Util.h" -#include "world.h" -#include "InterfaceConfig.h" -#include "Log.h" - // These includes are for serial port reading/writing #ifndef _WIN32 #include @@ -20,30 +17,16 @@ #include #endif +#include + +#include "InterfaceConfig.h" +#include "Util.h" + extern const bool USING_INVENSENSE_MPU9150; class SerialInterface { public: - SerialInterface() : _active(false), - _gravity(0, 0, 0), - _averageRotationRates(0, 0, 0), - _averageAcceleration(0, 0, 0), - _estimatedRotation(0, 0, 0), - _estimatedPosition(0, 0, 0), - _estimatedVelocity(0, 0, 0), - _lastAcceleration(0, 0, 0), - _lastRotationRates(0, 0, 0), - _compassMinima(-211, -132, -186), - _compassMaxima(89, 95, 98), - _angularVelocityToLinearAccel( - 0.003f, -0.001f, -0.006f, - -0.005f, -0.001f, -0.006f, - 0.010f, 0.004f, 0.007f), - _angularAccelToLinearAccel( - 0.0f, 0.0f, 0.002f, - 0.0f, 0.0f, 0.001f, - -0.002f, -0.002f, 0.0f) - {} + SerialInterface(); void pair(); void readData(float deltaTime); diff --git a/interface/src/Transmitter.cpp b/interface/src/Transmitter.cpp index b16fb79295..eac769ead7 100644 --- a/interface/src/Transmitter.cpp +++ b/interface/src/Transmitter.cpp @@ -13,11 +13,9 @@ #include #include "InterfaceConfig.h" -#include "Log.h" #include "Transmitter.h" #include "Util.h" - const float DELTA_TIME = 1.f / 60.f; const float DECAY_RATE = 0.15f; @@ -40,7 +38,7 @@ void Transmitter::checkForLostTransmitter() { int msecsSinceLast = diffclock(_lastReceivedPacket, &now); if (msecsSinceLast > TIME_TO_ASSUME_LOST_MSECS) { resetLevels(); - printLog("Transmitter signal lost.\n"); + qDebug("Transmitter signal lost.\n"); } } } @@ -95,12 +93,12 @@ void Transmitter::processIncomingData(unsigned char* packetData, int numBytes) { _estimatedRotation.y *= (1.f - DECAY_RATE * DELTA_TIME); if (!_isConnected) { - printLog("Transmitter Connected.\n"); + qDebug("Transmitter Connected.\n"); _isConnected = true; _estimatedRotation *= 0.0; } } else { - printLog("Transmitter packet read error, %d bytes.\n", numBytes); + qDebug("Transmitter packet read error, %d bytes.\n", numBytes); } } diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 65a277b623..20f33f924a 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -6,7 +6,6 @@ // Copyright (c) 2012 High Fidelity, Inc. All rights reserved. // -#include "InterfaceConfig.h" #include #include #include @@ -15,16 +14,16 @@ #include #include #include + #include #include -#include "Log.h" +#include "InterfaceConfig.h" #include "ui/TextRenderer.h" -#include "world.h" -#include "Util.h" - - #include "VoxelConstants.h" +#include "world.h" + +#include "Util.h" using namespace std; @@ -452,7 +451,7 @@ void renderOrientationDirections(glm::vec3 position, const glm::quat& orientatio bool closeEnoughForGovernmentWork(float a, float b) { float distance = std::abs(a-b); - //printLog("closeEnoughForGovernmentWork() a=%1.10f b=%1.10f distance=%1.10f\n",a,b,distance); + //qDebug("closeEnoughForGovernmentWork() a=%1.10f b=%1.10f distance=%1.10f\n",a,b,distance); return (distance < 0.00001f); } @@ -470,7 +469,7 @@ void runTimingTests() { gettimeofday(&endTime, NULL); } elapsedMsecs = diffclock(&startTime, &endTime); - printLog("gettimeofday() usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("gettimeofday() usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); // Random number generation gettimeofday(&startTime, NULL); @@ -479,7 +478,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - printLog("rand() stored in array usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("rand() stored in array usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); // Random number generation using randFloat() gettimeofday(&startTime, NULL); @@ -488,7 +487,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - printLog("randFloat() stored in array usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("randFloat() stored in array usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); // PowF function fTest = 1145323.2342f; @@ -498,7 +497,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - printLog("powf(f, 0.5) usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("powf(f, 0.5) usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); // Vector Math float distance; @@ -511,7 +510,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - printLog("vector math usecs: %f [%f msecs total for %d tests]\n", + qDebug("vector math usecs: %f [%f msecs total for %d tests]\n", 1000.0f * elapsedMsecs / (float) numTests, elapsedMsecs, numTests); // Vec3 test @@ -525,7 +524,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - printLog("vec3 assign and dot() usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("vec3 assign and dot() usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); } diff --git a/interface/src/VoxelSystem.cpp b/interface/src/VoxelSystem.cpp index 2801d16748..f219e38dc6 100644 --- a/interface/src/VoxelSystem.cpp +++ b/interface/src/VoxelSystem.cpp @@ -5,28 +5,31 @@ // Created by Philip on 12/31/12. // Copyright (c) 2012 High Fidelity, Inc. All rights reserved. // + #ifdef _WIN32 #define _timeval_ #define _USE_MATH_DEFINES #endif + #include #include #include // to load voxels from file #include // to load voxels from file +#include + #include -#include + +#include #include #include -#include -#include +#include + #include "Application.h" -#include "Log.h" -#include "VoxelConstants.h" #include "CoverageMap.h" #include "CoverageMapV2.h" #include "InterfaceConfig.h" #include "renderer/ProgramObject.h" - +#include "VoxelConstants.h" #include "VoxelSystem.h" float identityVertices[] = { 0,0,0, 1,0,0, 1,1,0, 0,1,0, 0,0,1, 1,0,1, 1,1,1, 0,1,1, @@ -141,16 +144,16 @@ int VoxelSystem::parseData(unsigned char* sourceBuffer, int numBytes) { int commandLength = strlen(command); // commands are null terminated strings int totalLength = 1+commandLength+1; - printLog("got Z message len(%d)= %s\n", numBytes, command); + qDebug("got Z message len(%d)= %s\n", numBytes, command); while (totalLength <= numBytes) { if (0==strcmp(command,(char*)"erase all")) { - printLog("got Z message == erase all\n"); + qDebug("got Z message == erase all\n"); _tree->eraseAllVoxels(); _voxelsInReadArrays = _voxelsInWriteArrays = 0; // better way to do this?? } if (0==strcmp(command,(char*)"add scene")) { - printLog("got Z message == add scene - NOT SUPPORTED ON INTERFACE\n"); + qDebug("got Z message == add scene - NOT SUPPORTED ON INTERFACE\n"); } totalLength += commandLength+1; } @@ -705,7 +708,7 @@ bool VoxelSystem::randomColorOperation(VoxelNode* node, void* extraData) { void VoxelSystem::randomizeVoxelColors() { _nodeCount = 0; _tree->recurseTreeWithOperation(randomColorOperation); - printLog("setting randomized true color for %d nodes\n", _nodeCount); + qDebug("setting randomized true color for %d nodes\n", _nodeCount); setupNewVoxelsForDrawing(); } @@ -719,7 +722,7 @@ bool VoxelSystem::falseColorizeRandomOperation(VoxelNode* node, void* extraData) void VoxelSystem::falseColorizeRandom() { _nodeCount = 0; _tree->recurseTreeWithOperation(falseColorizeRandomOperation); - printLog("setting randomized false color for %d nodes\n", _nodeCount); + qDebug("setting randomized false color for %d nodes\n", _nodeCount); setupNewVoxelsForDrawing(); } @@ -733,7 +736,7 @@ void VoxelSystem::trueColorize() { PerformanceWarning warn(true, "trueColorize()",true); _nodeCount = 0; _tree->recurseTreeWithOperation(trueColorizeOperation); - printLog("setting true color for %d nodes\n", _nodeCount); + qDebug("setting true color for %d nodes\n", _nodeCount); setupNewVoxelsForDrawing(); } @@ -753,7 +756,7 @@ bool VoxelSystem::falseColorizeInViewOperation(VoxelNode* node, void* extraData) void VoxelSystem::falseColorizeInView(ViewFrustum* viewFrustum) { _nodeCount = 0; _tree->recurseTreeWithOperation(falseColorizeInViewOperation,(void*)viewFrustum); - printLog("setting in view false color for %d nodes\n", _nodeCount); + qDebug("setting in view false color for %d nodes\n", _nodeCount); setupNewVoxelsForDrawing(); } @@ -803,10 +806,10 @@ void VoxelSystem::falseColorizeDistanceFromView(ViewFrustum* viewFrustum) { _maxDistance = 0.0; _minDistance = FLT_MAX; _tree->recurseTreeWithOperation(getDistanceFromViewRangeOperation,(void*)viewFrustum); - printLog("determining distance range for %d nodes\n", _nodeCount); + qDebug("determining distance range for %d nodes\n", _nodeCount); _nodeCount = 0; _tree->recurseTreeWithOperation(falseColorizeDistanceFromViewOperation,(void*)viewFrustum); - printLog("setting in distance false color for %d nodes\n", _nodeCount); + qDebug("setting in distance false color for %d nodes\n", _nodeCount); setupNewVoxelsForDrawing(); } @@ -918,7 +921,7 @@ void VoxelSystem::removeOutOfView() { } bool showRemoveDebugDetails = false; if (showRemoveDebugDetails) { - printLog("removeOutOfView() scanned=%ld removed=%ld inside=%ld intersect=%ld outside=%ld _removedVoxels.count()=%d \n", + qDebug("removeOutOfView() scanned=%ld removed=%ld inside=%ld intersect=%ld outside=%ld _removedVoxels.count()=%d \n", args.nodesScanned, args.nodesRemoved, args.nodesInside, args.nodesIntersect, args.nodesOutside, _removedVoxels.count() ); @@ -984,7 +987,7 @@ bool VoxelSystem::falseColorizeRandomEveryOtherOperation(VoxelNode* node, void* void VoxelSystem::falseColorizeRandomEveryOther() { falseColorizeRandomEveryOtherArgs args; _tree->recurseTreeWithOperation(falseColorizeRandomEveryOtherOperation,&args); - printLog("randomized false color for every other node: total %ld, colorable %ld, colored %ld\n", + qDebug("randomized false color for every other node: total %ld, colorable %ld, colored %ld\n", args.totalNodes, args.colorableNodes, args.coloredNodes); setupNewVoxelsForDrawing(); } @@ -1045,7 +1048,7 @@ bool VoxelSystem::collectStatsForTreesAndVBOsOperation(VoxelNode* node, void* ex unsigned long nodeIndex = node->getBufferIndex(); if (args->hasIndexFound[nodeIndex]) { args->duplicateVBOIndex++; - printLog("duplicateVBO found... index=%ld, isDirty=%s, shouldRender=%s \n", nodeIndex, + qDebug("duplicateVBO found... index=%ld, isDirty=%s, shouldRender=%s \n", nodeIndex, debug::valueOf(node->isDirty()), debug::valueOf(node->getShouldRender())); } else { args->hasIndexFound[nodeIndex] = true; @@ -1080,13 +1083,13 @@ void VoxelSystem::collectStatsForTreesAndVBOs() { args.expectedMax = _voxelsInWriteArrays; _tree->recurseTreeWithOperation(collectStatsForTreesAndVBOsOperation,&args); - printLog("Local Voxel Tree Statistics:\n total nodes %ld \n leaves %ld \n dirty %ld \n colored %ld \n shouldRender %ld \n", + qDebug("Local Voxel Tree Statistics:\n total nodes %ld \n leaves %ld \n dirty %ld \n colored %ld \n shouldRender %ld \n", args.totalNodes, args.leafNodes, args.dirtyNodes, args.coloredNodes, args.shouldRenderNodes); - printLog(" _voxelsDirty=%s \n _voxelsInWriteArrays=%ld \n minDirty=%ld \n maxDirty=%ld \n", debug::valueOf(_voxelsDirty), + qDebug(" _voxelsDirty=%s \n _voxelsInWriteArrays=%ld \n minDirty=%ld \n maxDirty=%ld \n", debug::valueOf(_voxelsDirty), _voxelsInWriteArrays, minDirty, maxDirty); - printLog(" inVBO %ld \n nodesInVBOOverExpectedMax %ld \n duplicateVBOIndex %ld \n nodesInVBONotShouldRender %ld \n", + qDebug(" inVBO %ld \n nodesInVBOOverExpectedMax %ld \n duplicateVBOIndex %ld \n nodesInVBONotShouldRender %ld \n", args.nodesInVBO, args.nodesInVBOOverExpectedMax, args.duplicateVBOIndex, args.nodesInVBONotShouldRender); glBufferIndex minInVBO = GLBUFFER_INDEX_UNKNOWN; @@ -1099,7 +1102,7 @@ void VoxelSystem::collectStatsForTreesAndVBOs() { } } - printLog(" minInVBO=%ld \n maxInVBO=%ld \n _voxelsInWriteArrays=%ld \n _voxelsInReadArrays=%ld \n", + qDebug(" minInVBO=%ld \n maxInVBO=%ld \n _voxelsInWriteArrays=%ld \n _voxelsInReadArrays=%ld \n", minInVBO, maxInVBO, _voxelsInWriteArrays, _voxelsInReadArrays); } @@ -1124,7 +1127,7 @@ void VoxelSystem::createVoxel(float x, float y, float z, float s, unsigned char red, unsigned char green, unsigned char blue, bool destructive) { pthread_mutex_lock(&_treeLock); - //printLog("VoxelSystem::createVoxel(%f,%f,%f,%f)\n",x,y,z,s); + //qDebug("VoxelSystem::createVoxel(%f,%f,%f,%f)\n",x,y,z,s); _tree->createVoxel(x, y, z, s, red, green, blue, destructive); setupNewVoxelsForDrawing(); @@ -1250,9 +1253,9 @@ bool VoxelSystem::falseColorizeOccludedOperation(VoxelNode* node, void* extraDat args->occludedVoxels++; } else if (result == STORED) { args->notOccludedVoxels++; - //printLog("***** falseColorizeOccludedOperation() NODE is STORED *****\n"); + //qDebug("***** falseColorizeOccludedOperation() NODE is STORED *****\n"); } else if (result == DOESNT_FIT) { - //printLog("***** falseColorizeOccludedOperation() NODE DOESNT_FIT???? *****\n"); + //qDebug("***** falseColorizeOccludedOperation() NODE DOESNT_FIT???? *****\n"); } } return true; // keep going! @@ -1285,7 +1288,7 @@ void VoxelSystem::falseColorizeOccluded() { _tree->recurseTreeWithOperationDistanceSorted(falseColorizeOccludedOperation, position, (void*)&args); - printLog("falseColorizeOccluded()\n position=(%f,%f)\n total=%ld\n colored=%ld\n occluded=%ld\n notOccluded=%ld\n outOfView=%ld\n subtreeVoxelsSkipped=%ld\n stagedForDeletion=%ld\n nonLeaves=%ld\n nonLeavesOutOfView=%ld\n nonLeavesOccluded=%ld\n pointInside_calls=%ld\n occludes_calls=%ld\n intersects_calls=%ld\n", + qDebug("falseColorizeOccluded()\n position=(%f,%f)\n total=%ld\n colored=%ld\n occluded=%ld\n notOccluded=%ld\n outOfView=%ld\n subtreeVoxelsSkipped=%ld\n stagedForDeletion=%ld\n nonLeaves=%ld\n nonLeavesOutOfView=%ld\n nonLeavesOccluded=%ld\n pointInside_calls=%ld\n occludes_calls=%ld\n intersects_calls=%ld\n", position.x, position.y, args.totalVoxels, args.coloredVoxels, args.occludedVoxels, args.notOccludedVoxels, args.outOfView, args.subtreeVoxelsSkipped, @@ -1371,9 +1374,9 @@ bool VoxelSystem::falseColorizeOccludedV2Operation(VoxelNode* node, void* extraD args->occludedVoxels++; } else if (result == V2_STORED) { args->notOccludedVoxels++; - //printLog("***** falseColorizeOccludedOperation() NODE is STORED *****\n"); + //qDebug("***** falseColorizeOccludedOperation() NODE is STORED *****\n"); } else if (result == V2_DOESNT_FIT) { - //printLog("***** falseColorizeOccludedOperation() NODE DOESNT_FIT???? *****\n"); + //qDebug("***** falseColorizeOccludedOperation() NODE DOESNT_FIT???? *****\n"); } delete voxelPolygon; // V2 maps don't store polygons, so we're always in charge of freeing } @@ -1410,7 +1413,7 @@ void VoxelSystem::falseColorizeOccludedV2() { _tree->recurseTreeWithOperationDistanceSorted(falseColorizeOccludedV2Operation, position, (void*)&args); - printLog("falseColorizeOccludedV2()\n position=(%f,%f)\n total=%ld\n colored=%ld\n occluded=%ld\n notOccluded=%ld\n outOfView=%ld\n subtreeVoxelsSkipped=%ld\n stagedForDeletion=%ld\n nonLeaves=%ld\n nonLeavesOutOfView=%ld\n nonLeavesOccluded=%ld\n pointInside_calls=%ld\n occludes_calls=%ld\n intersects_calls=%ld\n", + qDebug("falseColorizeOccludedV2()\n position=(%f,%f)\n total=%ld\n colored=%ld\n occluded=%ld\n notOccluded=%ld\n outOfView=%ld\n subtreeVoxelsSkipped=%ld\n stagedForDeletion=%ld\n nonLeaves=%ld\n nonLeavesOutOfView=%ld\n nonLeavesOccluded=%ld\n pointInside_calls=%ld\n occludes_calls=%ld\n intersects_calls=%ld\n", position.x, position.y, args.totalVoxels, args.coloredVoxels, args.occludedVoxels, args.notOccludedVoxels, args.outOfView, args.subtreeVoxelsSkipped, diff --git a/interface/src/Webcam.cpp b/interface/src/Webcam.cpp index 0d417583d2..f9dd5ffe2c 100644 --- a/interface/src/Webcam.cpp +++ b/interface/src/Webcam.cpp @@ -8,7 +8,6 @@ #include #include -#include #include #ifdef __APPLE__ @@ -157,7 +156,7 @@ void Webcam::setFrame(const Mat& frame, int format, const Mat& depth, const Rota glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, _frameWidth = image.width, _frameHeight = image.height, 0, format, GL_UNSIGNED_BYTE, image.imageData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - printLog("Capturing video at %dx%d.\n", _frameWidth, _frameHeight); + qDebug("Capturing video at %dx%d.\n", _frameWidth, _frameHeight); } else { glBindTexture(GL_TEXTURE_2D, _frameTextureID); @@ -173,7 +172,7 @@ void Webcam::setFrame(const Mat& frame, int format, const Mat& depth, const Rota glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, _depthWidth = depthImage.width, _depthHeight = depthImage.height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, depthImage.imageData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - printLog("Capturing depth at %dx%d.\n", _depthWidth, _depthHeight); + qDebug("Capturing depth at %dx%d.\n", _depthWidth, _depthHeight); } else { glBindTexture(GL_TEXTURE_2D, _depthTextureID); @@ -331,26 +330,26 @@ static glm::quat xnToGLM(const XnMatrix3X3& matrix) { } static void XN_CALLBACK_TYPE newUser(UserGenerator& generator, XnUserID id, void* cookie) { - printLog("Found user %d.\n", id); + qDebug("Found user %d.\n", id); generator.GetSkeletonCap().RequestCalibration(id, false); } static void XN_CALLBACK_TYPE lostUser(UserGenerator& generator, XnUserID id, void* cookie) { - printLog("Lost user %d.\n", id); + qDebug("Lost user %d.\n", id); } static void XN_CALLBACK_TYPE calibrationStarted(SkeletonCapability& capability, XnUserID id, void* cookie) { - printLog("Calibration started for user %d.\n", id); + qDebug("Calibration started for user %d.\n", id); } static void XN_CALLBACK_TYPE calibrationCompleted(SkeletonCapability& capability, XnUserID id, XnCalibrationStatus status, void* cookie) { if (status == XN_CALIBRATION_STATUS_OK) { - printLog("Calibration completed for user %d.\n", id); + qDebug("Calibration completed for user %d.\n", id); capability.StartTracking(id); } else { - printLog("Calibration failed to user %d.\n", id); + qDebug("Calibration failed to user %d.\n", id); capability.RequestCalibration(id, true); } } @@ -439,7 +438,7 @@ void FrameGrabber::grabFrame() { // make sure it's in the format we expect if (image->nChannels != 3 || image->depth != IPL_DEPTH_8U || image->dataOrder != IPL_DATA_ORDER_PIXEL || image->origin != 0) { - printLog("Invalid webcam image format.\n"); + qDebug("Invalid webcam image format.\n"); return; } frame = image; @@ -486,7 +485,7 @@ bool FrameGrabber::init() { // load our face cascade switchToResourcesParentIfRequired(); if (_faceCascade.empty() && !_faceCascade.load("resources/haarcascades/haarcascade_frontalface_alt.xml")) { - printLog("Failed to load Haar cascade for face tracking.\n"); + qDebug("Failed to load Haar cascade for face tracking.\n"); return false; } @@ -514,7 +513,7 @@ bool FrameGrabber::init() { // next, an ordinary webcam if ((_capture = cvCaptureFromCAM(-1)) == 0) { - printLog("Failed to open webcam.\n"); + qDebug("Failed to open webcam.\n"); return false; } const int IDEAL_FRAME_WIDTH = 320; diff --git a/interface/src/main.cpp b/interface/src/main.cpp index 20347014f0..98ed4fb231 100644 --- a/interface/src/main.cpp +++ b/interface/src/main.cpp @@ -16,15 +16,16 @@ // #include "Application.h" -#include "Log.h" + +#include int main(int argc, const char * argv[]) { timeval startup_time; gettimeofday(&startup_time, NULL); Application app(argc, const_cast(argv), startup_time); - printLog( "Created QT Application.\n" ); + qDebug( "Created QT Application.\n" ); int exitCode = app.exec(); - printLog("Normal exit.\n"); + qDebug("Normal exit.\n"); return exitCode; } diff --git a/interface/src/starfield/Config.h b/interface/src/starfield/Config.h index c11fe68e38..3cbff171c7 100644 --- a/interface/src/starfield/Config.h +++ b/interface/src/starfield/Config.h @@ -39,7 +39,6 @@ #include "InterfaceConfig.h" #include "renderer/ProgramObject.h" -#include "Log.h" #include #include diff --git a/interface/src/starfield/Loader.h b/interface/src/starfield/Loader.h index e4e87516ea..e2f6105f33 100644 --- a/interface/src/starfield/Loader.h +++ b/interface/src/starfield/Loader.h @@ -38,12 +38,12 @@ namespace starfield { if (! UrlReader::readUrl(url, *this, cacheFile)) { - printLog("%s:%d: %s\n", + qDebug("%s:%d: %s\n", _urlStr, _lineNo, getError()); return false; } - printLog("Loaded %u stars.\n", _recordsRead); + qDebug("Loaded %u stars.\n", _recordsRead); return true; } @@ -63,7 +63,7 @@ namespace starfield { _vertices->clear(); _vertices->reserve(_limit); -// printLog("Stars.cpp: loader begin %s\n", url); +// qDebug("Stars.cpp: loader begin %s\n", url); } size_t transfer(char* input, size_t bytes) { @@ -103,7 +103,7 @@ namespace starfield { } else { - printLog("Stars.cpp:%d: Bad input from %s\n", + qDebug("Stars.cpp:%d: Bad input from %s\n", _lineNo, _urlStr); } @@ -128,7 +128,7 @@ namespace starfield { // remember the brightness at its top if (_recordsRead == _limit) { -// printLog("Stars.cpp: vertex limit reached -> heap mode\n"); +// qDebug("Stars.cpp: vertex limit reached -> heap mode\n"); make_heap( _vertices->begin(), _vertices->end(), diff --git a/interface/src/ui/BandwidthDialog.cpp b/interface/src/ui/BandwidthDialog.cpp index 1e0e2e616e..4ff9a9878e 100644 --- a/interface/src/ui/BandwidthDialog.cpp +++ b/interface/src/ui/BandwidthDialog.cpp @@ -7,8 +7,6 @@ #include #include -#include "Log.h" - BandwidthDialog::BandwidthDialog(QWidget* parent, BandwidthMeter* model) : QDialog(parent, Qt::Window | Qt::WindowCloseButtonHint | Qt::WindowStaysOnTopHint), _model(model) { diff --git a/libraries/shared/src/Log.cpp b/libraries/shared/src/Log.cpp deleted file mode 100644 index 2db1ab4288..0000000000 --- a/libraries/shared/src/Log.cpp +++ /dev/null @@ -1,15 +0,0 @@ -// -// Log.cpp -// hifi -// -// Created by Tobias Schwinger on 4/17/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. -// - -#include "Log.h" - -#include - -using namespace std; -int (* printLog)(char const*, ...) = & printf; - diff --git a/libraries/shared/src/Log.h b/libraries/shared/src/Log.h deleted file mode 100644 index e2bc77e1e8..0000000000 --- a/libraries/shared/src/Log.h +++ /dev/null @@ -1,21 +0,0 @@ -// -// Log.h -// hifi -// -// Created by Tobias Schwinger on 4/17/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. -// - -#ifndef __hifi__shared_Log__ -#define __hifi__shared_Log__ - -// -// Pointer to log function -// -// An application may reset this variable to receive the log messages -// issued using 'printLog'. It defaults to a pointer to 'printf'. -// -extern int (* printLog)(char const*, ...); - -#endif /* defined(__hifi__shared_Log__) */ - diff --git a/libraries/shared/src/Node.cpp b/libraries/shared/src/Node.cpp index f7c9758fd0..41936d3a99 100644 --- a/libraries/shared/src/Node.cpp +++ b/libraries/shared/src/Node.cpp @@ -6,15 +6,9 @@ // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. // -#include "stdio.h" - -#include -#include "Node.h" -#include "NodeTypes.h" #include -#include "Log.h" -#include "UDPSocket.h" -#include "SharedUtil.h" +#include +#include #ifdef _WIN32 #include "Syssocket.h" @@ -22,6 +16,13 @@ #include #endif +#include "Node.h" +#include "NodeTypes.h" +#include "SharedUtil.h" +#include "UDPSocket.h" + +#include + int unpackNodeId(unsigned char* packedData, uint16_t* nodeId) { memcpy(nodeId, packedData, sizeof(uint16_t)); return sizeof(uint16_t); @@ -140,18 +141,14 @@ float Node::getAverageKilobitsPerSecond() { } } -void Node::printLog(Node const& node) { - +QDebug operator<<(QDebug debug, const Node &node) { char publicAddressBuffer[16] = {'\0'}; - unsigned short publicAddressPort = loadBufferWithSocketInfo(publicAddressBuffer, node._publicSocket); + unsigned short publicAddressPort = loadBufferWithSocketInfo(publicAddressBuffer, node.getPublicSocket()); //char localAddressBuffer[16] = {'\0'}; //unsigned short localAddressPort = loadBufferWithSocketInfo(localAddressBuffer, node.localSocket); - ::printLog("# %d %s (%c) @ %s:%d\n", - node._nodeID, - node.getTypeName(), - node._type, - publicAddressBuffer, - publicAddressPort); + debug << "#" << node.getNodeID() << node.getTypeName() << node.getType(); + debug.nospace() << publicAddressBuffer << ":" << publicAddressPort; + return debug.space(); } diff --git a/libraries/shared/src/Node.h b/libraries/shared/src/Node.h index aa88cb158c..46bf90ed43 100644 --- a/libraries/shared/src/Node.h +++ b/libraries/shared/src/Node.h @@ -9,8 +9,8 @@ #ifndef __hifi__Node__ #define __hifi__Node__ -#include #include +#include #ifdef _WIN32 #include "Syssocket.h" @@ -18,8 +18,10 @@ #include #endif -#include "SimpleMovingAverage.h" +#include + #include "NodeData.h" +#include "SimpleMovingAverage.h" class Node { public: @@ -89,8 +91,9 @@ private: pthread_mutex_t _mutex; }; - int unpackNodeId(unsigned char *packedData, uint16_t *nodeId); int packNodeId(unsigned char *packStore, uint16_t nodeId); +QDebug operator<<(QDebug debug, const Node &message); + #endif /* defined(__hifi__Node__) */ diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 004568584d..6ba71613de 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -11,11 +11,12 @@ #include #include +#include + #include "NodeList.h" #include "NodeTypes.h" #include "PacketHeaders.h" #include "SharedUtil.h" -#include "Log.h" #ifdef _WIN32 #include "Syssocket.h" @@ -42,7 +43,7 @@ NodeList* NodeList::createInstance(char ownerType, unsigned int socketListenPort if (!_sharedInstance) { _sharedInstance = new NodeList(ownerType, socketListenPort); } else { - printLog("NodeList createInstance called with existing instance.\n"); + qDebug("NodeList createInstance called with existing instance.\n"); } return _sharedInstance; @@ -50,7 +51,7 @@ NodeList* NodeList::createInstance(char ownerType, unsigned int socketListenPort NodeList* NodeList::getInstance() { if (!_sharedInstance) { - printLog("NodeList getInstance called before call to createInstance. Returning NULL pointer.\n"); + qDebug("NodeList getInstance called before call to createInstance. Returning NULL pointer.\n"); } return _sharedInstance; @@ -274,12 +275,12 @@ void NodeList::sendDomainServerCheckIn() { sockaddr_in tempAddress; memcpy(&tempAddress.sin_addr, pHostInfo->h_addr_list[0], pHostInfo->h_length); strcpy(_domainIP, inet_ntoa(tempAddress.sin_addr)); - printLog("Domain Server: %s \n", _domainHostname); + qDebug("Domain Server: %s \n", _domainHostname); } else { - printLog("Failed domain server lookup\n"); + qDebug("Failed domain server lookup\n"); } } else if (!printedDomainServerIP) { - printLog("Domain Server IP: %s\n", _domainIP); + qDebug("Domain Server IP: %s\n", _domainIP); printedDomainServerIP = true; } @@ -418,8 +419,7 @@ void NodeList::addNodeToList(Node* newNode) { ++_numNodes; - printLog("Added "); - Node::printLog(*newNode); + qDebug() << "Added " << *newNode; } unsigned NodeList::broadcastToNodes(unsigned char *broadcastData, size_t dataBytes, const char* nodeTypes, int numNodeTypes) { @@ -474,8 +474,7 @@ void *removeSilentNodes(void *args) { if ((checkTimeUSecs - node->getLastHeardMicrostamp()) > NODE_SILENCE_THRESHOLD_USECS && node->getType() != NODE_TYPE_VOXEL_SERVER) { - printLog("Killed "); - Node::printLog(*node); + qDebug() << "Killed" << *node; node->setAlive(false); } diff --git a/libraries/shared/src/OctalCode.cpp b/libraries/shared/src/OctalCode.cpp index e9eaa1c49a..3b92869104 100644 --- a/libraries/shared/src/OctalCode.cpp +++ b/libraries/shared/src/OctalCode.cpp @@ -6,12 +6,14 @@ // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. // -#include #include // std:min +#include #include + +#include + #include "SharedUtil.h" #include "OctalCode.h" -#include "Log.h" int numberOfThreeBitSectionsInCode(unsigned char * octalCode) { if (*octalCode == 255) { @@ -23,12 +25,12 @@ int numberOfThreeBitSectionsInCode(unsigned char * octalCode) { void printOctalCode(unsigned char * octalCode) { if (!octalCode) { - printLog("NULL\n"); + qDebug("NULL\n"); } else { for (int i = 0; i < bytesRequiredForCodeLength(*octalCode); i++) { outputBits(octalCode[i],false); } - printLog("\n"); + qDebug("\n"); } } diff --git a/libraries/shared/src/PacketHeaders.cpp b/libraries/shared/src/PacketHeaders.cpp index 230ca5bacc..7b4a0509f3 100644 --- a/libraries/shared/src/PacketHeaders.cpp +++ b/libraries/shared/src/PacketHeaders.cpp @@ -8,8 +8,9 @@ #include +#include + #include "PacketHeaders.h" -#include "Log.h" PACKET_VERSION versionForPacketType(PACKET_TYPE type) { switch (type) { @@ -28,7 +29,7 @@ bool packetVersionMatch(unsigned char* packetHeader) { if (packetHeader[1] == versionForPacketType(packetHeader[0])) { return true; } else { - printLog("There is a packet version mismatch for packet with header %c\n", packetHeader[0]); + qDebug("There is a packet version mismatch for packet with header %c\n", packetHeader[0]); return false; } } diff --git a/libraries/shared/src/PerfStat.cpp b/libraries/shared/src/PerfStat.cpp index d3547b384e..86985eb038 100644 --- a/libraries/shared/src/PerfStat.cpp +++ b/libraries/shared/src/PerfStat.cpp @@ -10,12 +10,13 @@ // // -#include "PerfStat.h" #include -#include #include +#include -#include "Log.h" +#include + +#include "PerfStat.h" // Static class members initialization here! std::map > PerfStat::groupHistoryMap; @@ -58,11 +59,11 @@ PerfStat::~PerfStat() { } if (wantDebugOut) { - printLog("PerfStats: %s elapsed:%f average:%lf count:%ld total:%lf ut:%d us:%d ue:%d t:%ld s:%ld e:%ld\n", - this->group.c_str(),elapsed,average,count,totalTime, - (end.tv_usec-start.tv_usec),start.tv_usec,end.tv_usec, - (end.tv_sec-start.tv_sec),start.tv_sec,end.tv_sec - ); + qDebug("PerfStats: %s elapsed:%f average:%lf count:%ld total:%lf ut:%d us:%d ue:%d t:%ld s:%ld e:%ld\n", + this->group.c_str(),elapsed,average,count,totalTime, + (end.tv_usec-start.tv_usec),start.tv_usec,end.tv_usec, + (end.tv_sec-start.tv_sec),start.tv_sec,end.tv_sec + ); } }; @@ -110,12 +111,12 @@ PerformanceWarning::~PerformanceWarning() { if ((_alwaysDisplay || _renderWarningsOn) && elapsedmsec > 1) { if (elapsedmsec > 1000) { double elapsedsec = (end - _start) / 1000000.0; - printLog("%s%s took %lf seconds\n", (_alwaysDisplay ? "" : "WARNING!"), _message, elapsedsec); + qDebug("%s%s took %lf seconds\n", (_alwaysDisplay ? "" : "WARNING!"), _message, elapsedsec); } else { - printLog("%s%s took %lf milliseconds\n", (_alwaysDisplay ? "" : "WARNING!"), _message, elapsedmsec); + qDebug("%s%s took %lf milliseconds\n", (_alwaysDisplay ? "" : "WARNING!"), _message, elapsedmsec); } } else if (_alwaysDisplay) { - printLog("%s took %lf milliseconds\n", _message, elapsedmsec); + qDebug("%s took %lf milliseconds\n", _message, elapsedmsec); } }; diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index eb46458b2c..23b889bdab 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -20,7 +20,8 @@ #include #endif -#include "Log.h" +#include + #include "OctalCode.h" #include "PacketHeaders.h" #include "SharedUtil.h" @@ -64,24 +65,24 @@ void outputBufferBits(unsigned char* buffer, int length, bool withNewLine) { outputBits(buffer[i], false); } if (withNewLine) { - printLog("\n"); + qDebug("\n"); } } void outputBits(unsigned char byte, bool withNewLine) { if (isalnum(byte)) { - printLog("[ %d (%c): ", byte, byte); + qDebug("[ %d (%c): ", byte, byte); } else { - printLog("[ %d (0x%x): ", byte, byte); + qDebug("[ %d (0x%x): ", byte, byte); } for (int i = 0; i < 8; i++) { - printLog("%d", byte >> (7 - i) & 1); + qDebug("%d", byte >> (7 - i) & 1); } - printLog(" ] "); + qDebug(" ] "); if (withNewLine) { - printLog("\n"); + qDebug("\n"); } } @@ -385,14 +386,14 @@ void printVoxelCode(unsigned char* voxelCode) { unsigned int voxelSizeInOctets = (voxelSizeInBits/3); unsigned int voxelBufferSize = voxelSizeInBytes+1+3; // 1 for size, 3 for color - printLog("octets=%d\n",octets); - printLog("voxelSizeInBits=%d\n",voxelSizeInBits); - printLog("voxelSizeInBytes=%d\n",voxelSizeInBytes); - printLog("voxelSizeInOctets=%d\n",voxelSizeInOctets); - printLog("voxelBufferSize=%d\n",voxelBufferSize); + qDebug("octets=%d\n",octets); + qDebug("voxelSizeInBits=%d\n",voxelSizeInBits); + qDebug("voxelSizeInBytes=%d\n",voxelSizeInBytes); + qDebug("voxelSizeInOctets=%d\n",voxelSizeInOctets); + qDebug("voxelBufferSize=%d\n",voxelBufferSize); for(int i=0;i #include #include +#include #include #ifdef _WIN32 @@ -21,7 +20,9 @@ #include #endif -#include "Log.h" +#include + +#include "UDPSocket.h" sockaddr_in destSockaddr, senderAddress; @@ -123,7 +124,7 @@ UDPSocket::UDPSocket(int listeningPort) : listeningPort(listeningPort), blocking handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (handle <= 0) { - printLog("Failed to create socket.\n"); + qDebug("Failed to create socket.\n"); return; } @@ -136,7 +137,7 @@ UDPSocket::UDPSocket(int listeningPort) : listeningPort(listeningPort), blocking bind_address.sin_port = htons((uint16_t) listeningPort); if (bind(handle, (const sockaddr*) &bind_address, sizeof(sockaddr_in)) < 0) { - printLog("Failed to bind socket to port %d.\n", listeningPort); + qDebug("Failed to bind socket to port %d.\n", listeningPort); return; } @@ -153,7 +154,7 @@ UDPSocket::UDPSocket(int listeningPort) : listeningPort(listeningPort), blocking tv.tv_usec = 500000; setsockopt(handle, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof tv); - printLog("Created UDP socket listening on port %d.\n", listeningPort); + qDebug("Created UDP socket listening on port %d.\n", listeningPort); } UDPSocket::~UDPSocket() { @@ -233,7 +234,7 @@ int UDPSocket::send(sockaddr* destAddress, const void* data, size_t byteLength) 0, (sockaddr *) destAddress, sizeof(sockaddr_in)); if (sent_bytes != byteLength) { - printLog("Failed to send packet: %s\n", strerror(errno)); + qDebug("Failed to send packet: %s\n", strerror(errno)); return false; } diff --git a/libraries/shared/src/UrlReader.cpp b/libraries/shared/src/UrlReader.cpp index 638134f4dd..3f98326726 100644 --- a/libraries/shared/src/UrlReader.cpp +++ b/libraries/shared/src/UrlReader.cpp @@ -6,20 +6,17 @@ // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. // -#include "UrlReader.h" - #include #include #include -#include "Log.h" - #ifndef _WIN32 // (Windows port is incomplete and the build files do not support CURL, yet) #include +#include "UrlReader.h" // // ATTENTION: A certain part of the implementation lives in inlined code diff --git a/libraries/voxels/src/CoverageMap.cpp b/libraries/voxels/src/CoverageMap.cpp index d30e0a4290..31bcfb64cb 100644 --- a/libraries/voxels/src/CoverageMap.cpp +++ b/libraries/voxels/src/CoverageMap.cpp @@ -6,10 +6,13 @@ // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. // -#include "CoverageMap.h" -#include #include -#include "Log.h" + +#include + +#include + +#include "CoverageMap.h" int CoverageMap::_mapCount = 0; int CoverageMap::_checkMapRootCalls = 0; @@ -60,7 +63,7 @@ CoverageMap::CoverageMap(BoundingBox boundingBox, bool isRoot, bool managePolygo { _mapCount++; init(); - //printLog("CoverageMap created... _mapCount=%d\n",_mapCount); + //qDebug("CoverageMap created... _mapCount=%d\n",_mapCount); }; CoverageMap::~CoverageMap() { @@ -68,19 +71,19 @@ CoverageMap::~CoverageMap() { }; void CoverageMap::printStats() { - printLog("CoverageMap::printStats()...\n"); - printLog("MINIMUM_POLYGON_AREA_TO_STORE=%f\n",MINIMUM_POLYGON_AREA_TO_STORE); - printLog("_mapCount=%d\n",_mapCount); - printLog("_checkMapRootCalls=%d\n",_checkMapRootCalls); - printLog("_notAllInView=%d\n",_notAllInView); - printLog("_maxPolygonsUsed=%d\n",CoverageRegion::_maxPolygonsUsed); - printLog("_totalPolygons=%d\n",CoverageRegion::_totalPolygons); - printLog("_occlusionTests=%d\n",CoverageRegion::_occlusionTests); - printLog("_regionSkips=%d\n",CoverageRegion::_regionSkips); - printLog("_tooSmallSkips=%d\n",CoverageRegion::_tooSmallSkips); - printLog("_regionFullSkips=%d\n",CoverageRegion::_regionFullSkips); - printLog("_outOfOrderPolygon=%d\n",CoverageRegion::_outOfOrderPolygon); - printLog("_clippedPolygons=%d\n",CoverageRegion::_clippedPolygons); + qDebug("CoverageMap::printStats()...\n"); + qDebug("MINIMUM_POLYGON_AREA_TO_STORE=%f\n",MINIMUM_POLYGON_AREA_TO_STORE); + qDebug("_mapCount=%d\n",_mapCount); + qDebug("_checkMapRootCalls=%d\n",_checkMapRootCalls); + qDebug("_notAllInView=%d\n",_notAllInView); + qDebug("_maxPolygonsUsed=%d\n",CoverageRegion::_maxPolygonsUsed); + qDebug("_totalPolygons=%d\n",CoverageRegion::_totalPolygons); + qDebug("_occlusionTests=%d\n",CoverageRegion::_occlusionTests); + qDebug("_regionSkips=%d\n",CoverageRegion::_regionSkips); + qDebug("_tooSmallSkips=%d\n",CoverageRegion::_tooSmallSkips); + qDebug("_regionFullSkips=%d\n",CoverageRegion::_regionFullSkips); + qDebug("_outOfOrderPolygon=%d\n",CoverageRegion::_outOfOrderPolygon); + qDebug("_clippedPolygons=%d\n",CoverageRegion::_clippedPolygons); } void CoverageMap::erase() { @@ -99,7 +102,7 @@ void CoverageMap::erase() { } if (_isRoot && wantDebugging) { - printLog("CoverageMap last to be deleted...\n"); + qDebug("CoverageMap last to be deleted...\n"); printStats(); CoverageRegion::_maxPolygonsUsed = 0; @@ -184,7 +187,7 @@ CoverageMapStorageResult CoverageMap::checkMap(VoxelProjectedPolygon* polygon, b if (_isRoot) { _checkMapRootCalls++; - //printLog("CoverageMap::checkMap()... storeIt=%s\n", debug::valueOf(storeIt)); + //qDebug("CoverageMap::checkMap()... storeIt=%s\n", debug::valueOf(storeIt)); //polygon->printDebugDetails(); } @@ -193,7 +196,7 @@ CoverageMapStorageResult CoverageMap::checkMap(VoxelProjectedPolygon* polygon, b // not in view, then we just discard it with a DOESNT_FIT, this saves us time checking values later. if (!polygon->getAllInView()) { _notAllInView++; - //printLog("CoverageMap2::checkMap()... V2_OCCLUDED\n"); + //qDebug("CoverageMap2::checkMap()... V2_OCCLUDED\n"); return DOESNT_FIT; } @@ -240,9 +243,9 @@ CoverageMapStorageResult CoverageMap::checkMap(VoxelProjectedPolygon* polygon, b /* if (result == STORED) - printLog("CoverageMap2::checkMap()... STORED\n"); + qDebug("CoverageMap2::checkMap()... STORED\n"); else - printLog("CoverageMap2::checkMap()... OCCLUDED\n"); + qDebug("CoverageMap2::checkMap()... OCCLUDED\n"); */ return result; @@ -265,16 +268,16 @@ CoverageMapStorageResult CoverageMap::checkMap(VoxelProjectedPolygon* polygon, b /* switch (result) { case STORED: - printLog("checkMap() = STORED\n"); + qDebug("checkMap() = STORED\n"); break; case NOT_STORED: - printLog("checkMap() = NOT_STORED\n"); + qDebug("checkMap() = NOT_STORED\n"); break; case OCCLUDED: - printLog("checkMap() = OCCLUDED\n"); + qDebug("checkMap() = OCCLUDED\n"); break; default: - printLog("checkMap() = ????? \n"); + qDebug("checkMap() = ????? \n"); break; } */ @@ -287,27 +290,27 @@ CoverageMapStorageResult CoverageMap::checkMap(VoxelProjectedPolygon* polygon, b // any of our child bounding boxes, so we should add it here. if (storeIt) { if (polygon->getBoundingBox().area() > CoverageMap::MINIMUM_POLYGON_AREA_TO_STORE) { - //printLog("storing polygon of area: %f\n",polygon->getBoundingBox().area()); + //qDebug("storing polygon of area: %f\n",polygon->getBoundingBox().area()); if (storeIn->getPolygonCount() < MAX_POLYGONS_PER_REGION) { storeIn->storeInArray(polygon); - //printLog("CoverageMap2::checkMap()... STORED\n"); + //qDebug("CoverageMap2::checkMap()... STORED\n"); return STORED; } else { CoverageRegion::_regionFullSkips++; - //printLog("CoverageMap2::checkMap()... NOT_STORED\n"); + //qDebug("CoverageMap2::checkMap()... NOT_STORED\n"); return NOT_STORED; } } else { CoverageRegion::_tooSmallSkips++; - //printLog("CoverageMap2::checkMap()... NOT_STORED\n"); + //qDebug("CoverageMap2::checkMap()... NOT_STORED\n"); return NOT_STORED; } } else { - //printLog("CoverageMap2::checkMap()... NOT_STORED\n"); + //qDebug("CoverageMap2::checkMap()... NOT_STORED\n"); return NOT_STORED; } } - //printLog("CoverageMap2::checkMap()... DOESNT_FIT\n"); + //qDebug("CoverageMap2::checkMap()... DOESNT_FIT\n"); return DOESNT_FIT; } @@ -338,11 +341,11 @@ void CoverageRegion::erase() { /** if (_polygonCount) { - printLog("CoverageRegion::erase()...\n"); - printLog("_polygonCount=%d\n",_polygonCount); + qDebug("CoverageRegion::erase()...\n"); + qDebug("_polygonCount=%d\n",_polygonCount); _myBoundingBox.printDebugDetails(getRegionName()); //for (int i = 0; i < _polygonCount; i++) { - // printLog("_polygons[%d]=",i); + // qDebug("_polygons[%d]=",i); // _polygons[i]->getBoundingBox().printDebugDetails(); //} } @@ -390,7 +393,7 @@ void CoverageRegion::growPolygonArray() { _polygonDistances = newDistances; _polygonSizes = newSizes; _polygonArraySize = _polygonArraySize + DEFAULT_GROW_SIZE; - //printLog("CoverageMap::growPolygonArray() _polygonArraySize=%d...\n",_polygonArraySize); + //qDebug("CoverageMap::growPolygonArray() _polygonArraySize=%d...\n",_polygonArraySize); } const char* CoverageRegion::getRegionName() const { @@ -435,7 +438,7 @@ bool CoverageRegion::mergeItemsInArray(VoxelProjectedPolygon* seed, bool seedInA _totalPolygons--; } - //printLog("_polygonCount=%d\n",_polygonCount); + //qDebug("_polygonCount=%d\n",_polygonCount); // clean up if (_managePolygons) { @@ -483,7 +486,7 @@ void CoverageRegion::storeInArray(VoxelProjectedPolygon* polygon) { // insertion point in this array, and shift the array accordingly float area = polygon->getBoundingBox().area(); float reverseArea = 4.0f - area; - //printLog("store by size area=%f reverse area=%f\n", area, reverseArea); + //qDebug("store by size area=%f reverse area=%f\n", area, reverseArea); _polygonCount = insertIntoSortedArrays((void*)polygon, reverseArea, IGNORED, (void**)_polygons, _polygonSizes, IGNORED, _polygonCount, _polygonArraySize); @@ -497,10 +500,10 @@ void CoverageRegion::storeInArray(VoxelProjectedPolygon* polygon) { // Debugging and Optimization Tuning code. if (_polygonCount > _maxPolygonsUsed) { _maxPolygonsUsed = _polygonCount; - //printLog("CoverageRegion new _maxPolygonsUsed reached=%d region=%s\n",_maxPolygonsUsed, getRegionName()); + //qDebug("CoverageRegion new _maxPolygonsUsed reached=%d region=%s\n",_maxPolygonsUsed, getRegionName()); //_myBoundingBox.printDebugDetails("map._myBoundingBox"); } else { - //printLog("CoverageRegion::storeInArray() _polygonCount=%d region=%s\n",_polygonCount, getRegionName()); + //qDebug("CoverageRegion::storeInArray() _polygonCount=%d region=%s\n",_polygonCount, getRegionName()); } } diff --git a/libraries/voxels/src/CoverageMapV2.cpp b/libraries/voxels/src/CoverageMapV2.cpp index f5591bb324..0e382d7f12 100644 --- a/libraries/voxels/src/CoverageMapV2.cpp +++ b/libraries/voxels/src/CoverageMapV2.cpp @@ -7,11 +7,13 @@ // #include +#include + +#include + +#include #include "CoverageMapV2.h" -#include -#include -#include "Log.h" int CoverageMapV2::_mapCount = 0; int CoverageMapV2::_checkMapRootCalls = 0; @@ -59,7 +61,7 @@ CoverageMapV2::CoverageMapV2(BoundingBox boundingBox, bool isRoot, bool isCovere { _mapCount++; init(); - //printLog("CoverageMapV2 created... _mapCount=%d\n",_mapCount); + //qDebug("CoverageMapV2 created... _mapCount=%d\n",_mapCount); }; CoverageMapV2::~CoverageMapV2() { @@ -76,11 +78,11 @@ void CoverageMapV2::erase() { } if (_isRoot && wantDebugging) { - printLog("CoverageMapV2 last to be deleted...\n"); - printLog("MINIMUM_POLYGON_AREA_TO_STORE=%f\n",MINIMUM_POLYGON_AREA_TO_STORE); - printLog("_mapCount=%d\n",_mapCount); - printLog("_checkMapRootCalls=%d\n",_checkMapRootCalls); - printLog("_notAllInView=%d\n",_notAllInView); + qDebug("CoverageMapV2 last to be deleted...\n"); + qDebug("MINIMUM_POLYGON_AREA_TO_STORE=%f\n",MINIMUM_POLYGON_AREA_TO_STORE); + qDebug("_mapCount=%d\n",_mapCount); + qDebug("_checkMapRootCalls=%d\n",_checkMapRootCalls); + qDebug("_notAllInView=%d\n",_notAllInView); _mapCount = 0; _checkMapRootCalls = 0; _notAllInView = 0; diff --git a/libraries/voxels/src/GeometryUtil.cpp b/libraries/voxels/src/GeometryUtil.cpp index af2a6dfc95..894f43ee3c 100644 --- a/libraries/voxels/src/GeometryUtil.cpp +++ b/libraries/voxels/src/GeometryUtil.cpp @@ -7,7 +7,8 @@ #include -#include +#include + #include #include "GeometryUtil.h" diff --git a/libraries/voxels/src/Plane.cpp b/libraries/voxels/src/Plane.cpp index 5a99bf29c4..0a1a7ed86c 100755 --- a/libraries/voxels/src/Plane.cpp +++ b/libraries/voxels/src/Plane.cpp @@ -12,8 +12,6 @@ #include -#include "Log.h" - // These are some useful utilities that vec3 is missing void printVec3(const char* name, const glm::vec3& v) { printf("%s x=%f y=%f z=%f\n", name, v.x, v.y, v.z); diff --git a/libraries/voxels/src/Tags.cpp b/libraries/voxels/src/Tags.cpp index 8f7dab5390..e6875f36a6 100644 --- a/libraries/voxels/src/Tags.cpp +++ b/libraries/voxels/src/Tags.cpp @@ -6,14 +6,13 @@ // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. // -#include "Tags.h" -#include - -#include -#include - #include +#include +#include + +#include "Tags.h" + Tag::Tag(int tagId, std::stringstream &ss) : _tagId(tagId) { int size = ss.get() << 8 | ss.get(); diff --git a/libraries/voxels/src/ViewFrustum.cpp b/libraries/voxels/src/ViewFrustum.cpp index dd4562cd8d..c13da815f8 100644 --- a/libraries/voxels/src/ViewFrustum.cpp +++ b/libraries/voxels/src/ViewFrustum.cpp @@ -3,24 +3,23 @@ // hifi // // Created by Brad Hefta-Gaub on 04/11/13. +// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. // // Simple view frustum class. // -// #include #include -#include "SharedUtil.h" -#include "Log.h" +#include #include "CoverageMap.h" #include "GeometryUtil.h" +#include "SharedUtil.h" #include "ViewFrustum.h" #include "VoxelConstants.h" - using namespace std; ViewFrustum::ViewFrustum() : @@ -323,40 +322,40 @@ bool ViewFrustum::matches(const ViewFrustum& compareTo, bool debug) const { testMatches(compareTo._eyeOffsetOrientation, _eyeOffsetOrientation); if (!result && debug) { - printLog("ViewFrustum::matches()... result=%s\n", debug::valueOf(result)); - printLog("%s -- compareTo._position=%f,%f,%f _position=%f,%f,%f\n", + qDebug("ViewFrustum::matches()... result=%s\n", debug::valueOf(result)); + qDebug("%s -- compareTo._position=%f,%f,%f _position=%f,%f,%f\n", (testMatches(compareTo._position,_position) ? "MATCHES " : "NO MATCH"), compareTo._position.x, compareTo._position.y, compareTo._position.z, _position.x, _position.y, _position.z ); - printLog("%s -- compareTo._direction=%f,%f,%f _direction=%f,%f,%f\n", + qDebug("%s -- compareTo._direction=%f,%f,%f _direction=%f,%f,%f\n", (testMatches(compareTo._direction, _direction) ? "MATCHES " : "NO MATCH"), compareTo._direction.x, compareTo._direction.y, compareTo._direction.z, _direction.x, _direction.y, _direction.z ); - printLog("%s -- compareTo._up=%f,%f,%f _up=%f,%f,%f\n", + qDebug("%s -- compareTo._up=%f,%f,%f _up=%f,%f,%f\n", (testMatches(compareTo._up, _up) ? "MATCHES " : "NO MATCH"), compareTo._up.x, compareTo._up.y, compareTo._up.z, _up.x, _up.y, _up.z ); - printLog("%s -- compareTo._right=%f,%f,%f _right=%f,%f,%f\n", + qDebug("%s -- compareTo._right=%f,%f,%f _right=%f,%f,%f\n", (testMatches(compareTo._right, _right) ? "MATCHES " : "NO MATCH"), compareTo._right.x, compareTo._right.y, compareTo._right.z, _right.x, _right.y, _right.z ); - printLog("%s -- compareTo._fieldOfView=%f _fieldOfView=%f\n", + qDebug("%s -- compareTo._fieldOfView=%f _fieldOfView=%f\n", (testMatches(compareTo._fieldOfView, _fieldOfView) ? "MATCHES " : "NO MATCH"), compareTo._fieldOfView, _fieldOfView); - printLog("%s -- compareTo._aspectRatio=%f _aspectRatio=%f\n", + qDebug("%s -- compareTo._aspectRatio=%f _aspectRatio=%f\n", (testMatches(compareTo._aspectRatio, _aspectRatio) ? "MATCHES " : "NO MATCH"), compareTo._aspectRatio, _aspectRatio); - printLog("%s -- compareTo._nearClip=%f _nearClip=%f\n", + qDebug("%s -- compareTo._nearClip=%f _nearClip=%f\n", (testMatches(compareTo._nearClip, _nearClip) ? "MATCHES " : "NO MATCH"), compareTo._nearClip, _nearClip); - printLog("%s -- compareTo._farClip=%f _farClip=%f\n", + qDebug("%s -- compareTo._farClip=%f _farClip=%f\n", (testMatches(compareTo._farClip, _farClip) ? "MATCHES " : "NO MATCH"), compareTo._farClip, _farClip); - printLog("%s -- compareTo._eyeOffsetPosition=%f,%f,%f _eyeOffsetPosition=%f,%f,%f\n", + qDebug("%s -- compareTo._eyeOffsetPosition=%f,%f,%f _eyeOffsetPosition=%f,%f,%f\n", (testMatches(compareTo._eyeOffsetPosition, _eyeOffsetPosition) ? "MATCHES " : "NO MATCH"), compareTo._eyeOffsetPosition.x, compareTo._eyeOffsetPosition.y, compareTo._eyeOffsetPosition.z, _eyeOffsetPosition.x, _eyeOffsetPosition.y, _eyeOffsetPosition.z); - printLog("%s -- compareTo._eyeOffsetOrientation=%f,%f,%f,%f _eyeOffsetOrientation=%f,%f,%f,%f\n", + qDebug("%s -- compareTo._eyeOffsetOrientation=%f,%f,%f,%f _eyeOffsetOrientation=%f,%f,%f,%f\n", (testMatches(compareTo._eyeOffsetOrientation, _eyeOffsetOrientation) ? "MATCHES " : "NO MATCH"), compareTo._eyeOffsetOrientation.x, compareTo._eyeOffsetOrientation.y, compareTo._eyeOffsetOrientation.z, compareTo._eyeOffsetOrientation.w, @@ -419,17 +418,17 @@ void ViewFrustum::computeOffAxisFrustum(float& left, float& right, float& bottom } void ViewFrustum::printDebugDetails() const { - printLog("ViewFrustum::printDebugDetails()... \n"); - printLog("_position=%f,%f,%f\n", _position.x, _position.y, _position.z ); - printLog("_direction=%f,%f,%f\n", _direction.x, _direction.y, _direction.z ); - printLog("_up=%f,%f,%f\n", _up.x, _up.y, _up.z ); - printLog("_right=%f,%f,%f\n", _right.x, _right.y, _right.z ); - printLog("_fieldOfView=%f\n", _fieldOfView); - printLog("_aspectRatio=%f\n", _aspectRatio); - printLog("_nearClip=%f\n", _nearClip); - printLog("_farClip=%f\n", _farClip); - printLog("_eyeOffsetPosition=%f,%f,%f\n", _eyeOffsetPosition.x, _eyeOffsetPosition.y, _eyeOffsetPosition.z ); - printLog("_eyeOffsetOrientation=%f,%f,%f,%f\n", _eyeOffsetOrientation.x, _eyeOffsetOrientation.y, _eyeOffsetOrientation.z, + qDebug("ViewFrustum::printDebugDetails()... \n"); + qDebug("_position=%f,%f,%f\n", _position.x, _position.y, _position.z ); + qDebug("_direction=%f,%f,%f\n", _direction.x, _direction.y, _direction.z ); + qDebug("_up=%f,%f,%f\n", _up.x, _up.y, _up.z ); + qDebug("_right=%f,%f,%f\n", _right.x, _right.y, _right.z ); + qDebug("_fieldOfView=%f\n", _fieldOfView); + qDebug("_aspectRatio=%f\n", _aspectRatio); + qDebug("_nearClip=%f\n", _nearClip); + qDebug("_farClip=%f\n", _farClip); + qDebug("_eyeOffsetPosition=%f,%f,%f\n", _eyeOffsetPosition.x, _eyeOffsetPosition.y, _eyeOffsetPosition.z ); + qDebug("_eyeOffsetOrientation=%f,%f,%f,%f\n", _eyeOffsetOrientation.x, _eyeOffsetOrientation.y, _eyeOffsetOrientation.z, _eyeOffsetOrientation.w ); } diff --git a/libraries/voxels/src/ViewFrustum.h b/libraries/voxels/src/ViewFrustum.h index e364816c59..188b85c0de 100644 --- a/libraries/voxels/src/ViewFrustum.h +++ b/libraries/voxels/src/ViewFrustum.h @@ -3,18 +3,20 @@ // hifi // // Created by Brad Hefta-Gaub on 04/11/13. +// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. // // Simple view frustum class. // -// #ifndef __hifi__ViewFrustum__ #define __hifi__ViewFrustum__ #include #include -#include "Plane.h" + #include "AABox.h" +#include "Plane.h" + #include "VoxelProjectedPolygon.h" const float DEFAULT_KEYHOLE_RADIUS = 3.0f; @@ -135,7 +137,7 @@ private: glm::vec3 _nearBottomLeft; glm::vec3 _nearBottomRight; enum { TOP_PLANE = 0, BOTTOM_PLANE, LEFT_PLANE, RIGHT_PLANE, NEAR_PLANE, FAR_PLANE }; - Plane _planes[6]; // How will this be used? + ::Plane _planes[6]; // How will this be used? const char* debugPlaneName (int plane) const; diff --git a/libraries/voxels/src/VoxelNode.cpp b/libraries/voxels/src/VoxelNode.cpp index 61a174f90b..76fae500dd 100644 --- a/libraries/voxels/src/VoxelNode.cpp +++ b/libraries/voxels/src/VoxelNode.cpp @@ -3,19 +3,21 @@ // hifi // // Created by Stephen Birarda on 3/13/13. -// +// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. // -#include #include #include +#include + +#include + +#include "AABox.h" +#include "OctalCode.h" #include "SharedUtil.h" -#include "Log.h" +#include "VoxelConstants.h" #include "VoxelNode.h" #include "VoxelTree.h" -#include "VoxelConstants.h" -#include "OctalCode.h" -#include "AABox.h" VoxelNode::VoxelNode() { unsigned char* rootCode = new unsigned char[1]; @@ -257,7 +259,7 @@ bool VoxelNode::collapseIdenticalLeaves() { // if no child, child isn't a leaf, or child doesn't have a color if (!_children[i] || _children[i]->isStagedForDeletion() || !_children[i]->isLeaf() || !_children[i]->isColored()) { allChildrenMatch=false; - //printLog("SADNESS child missing or not colored! i=%d\n",i); + //qDebug("SADNESS child missing or not colored! i=%d\n",i); break; } else { if (i==0) { @@ -274,7 +276,7 @@ bool VoxelNode::collapseIdenticalLeaves() { if (allChildrenMatch) { - //printLog("allChildrenMatch: pruning tree\n"); + //qDebug("allChildrenMatch: pruning tree\n"); for (int i = 0; i < NUMBER_OF_CHILDREN; i++) { delete _children[i]; // delete all the child nodes _children[i]=NULL; // set it to NULL @@ -308,13 +310,13 @@ void VoxelNode::printDebugDetails(const char* label) const { } } - printLog("%s - Voxel at corner=(%f,%f,%f) size=%f\n isLeaf=%s isColored=%s (%d,%d,%d,%d) isDirty=%s shouldRender=%s\n children=", label, + qDebug("%s - Voxel at corner=(%f,%f,%f) size=%f\n isLeaf=%s isColored=%s (%d,%d,%d,%d) isDirty=%s shouldRender=%s\n children=", label, _box.getCorner().x, _box.getCorner().y, _box.getCorner().z, _box.getSize().x, debug::valueOf(isLeaf()), debug::valueOf(isColored()), getColor()[0], getColor()[1], getColor()[2], getColor()[3], debug::valueOf(isDirty()), debug::valueOf(getShouldRender())); outputBits(childBits, false); - printLog("\n octalCode="); + qDebug("\n octalCode="); printOctalCode(_octalCode); } diff --git a/libraries/voxels/src/VoxelProjectedPolygon.cpp b/libraries/voxels/src/VoxelProjectedPolygon.cpp index 95c66b6821..8a39d7f358 100644 --- a/libraries/voxels/src/VoxelProjectedPolygon.cpp +++ b/libraries/voxels/src/VoxelProjectedPolygon.cpp @@ -6,10 +6,13 @@ // #include -#include "VoxelProjectedPolygon.h" + +#include + #include "GeometryUtil.h" -#include "Log.h" #include "SharedUtil.h" +#include "VoxelProjectedPolygon.h" + glm::vec2 BoundingBox::getVertex(int vertexNumber) const { switch (vertexNumber) { @@ -88,11 +91,11 @@ void BoundingBox::explandToInclude(const BoundingBox& box) { void BoundingBox::printDebugDetails(const char* label) const { if (label) { - printLog(label); + qDebug() << label; } else { - printLog("BoundingBox"); + qDebug("BoundingBox"); } - printLog("\n _set=%s\n corner=%f,%f size=%f,%f\n bounds=[(%f,%f) to (%f,%f)]\n", + qDebug("\n _set=%s\n corner=%f,%f size=%f,%f\n bounds=[(%f,%f) to (%f,%f)]\n", debug::valueOf(_set), corner.x, corner.y, size.x, size.y, corner.x, corner.y, corner.x+size.x, corner.y+size.y); } diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index b84b374309..803bea8038 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -9,26 +9,28 @@ #ifdef _WIN32 #define _USE_MATH_DEFINES #endif + #include #include #include -#include "SharedUtil.h" -#include "Log.h" -#include "PacketHeaders.h" -#include "OctalCode.h" -#include "GeometryUtil.h" -#include "VoxelTree.h" -#include "VoxelNodeBag.h" -#include "ViewFrustum.h" #include // to load voxels from file -#include "VoxelConstants.h" -#include "CoverageMap.h" -#include "SquarePixelMap.h" -#include "Tags.h" - #include +#include + +#include "CoverageMap.h" +#include "GeometryUtil.h" +#include "OctalCode.h" +#include "PacketHeaders.h" +#include "SharedUtil.h" +#include "SquarePixelMap.h" +#include "Tags.h" +#include "ViewFrustum.h" +#include "VoxelConstants.h" +#include "VoxelNodeBag.h" +#include "VoxelTree.h" + float boundaryDistanceForRenderLevel(unsigned int renderLevel) { const float voxelSizeScale = 50000.0f; return voxelSizeScale / powf(2, renderLevel); @@ -155,7 +157,7 @@ void VoxelTree::recurseNodeWithOperationDistanceSorted(VoxelNode* node, RecurseV if (childNode) { // chance to optimize, doesn't need to be actual distance!! Could be distance squared float distanceSquared = childNode->distanceSquareToPoint(point); - //printLog("recurseNodeWithOperationDistanceSorted() CHECKING child[%d] point=%f,%f center=%f,%f distance=%f...\n", i, point.x, point.y, center.x, center.y, distance); + //qDebug("recurseNodeWithOperationDistanceSorted() CHECKING child[%d] point=%f,%f center=%f,%f distance=%f...\n", i, point.x, point.y, center.x, center.y, distance); //childNode->printDebugDetails(""); currentCount = insertIntoSortedArrays((void*)childNode, distanceSquared, i, (void**)&sortedChildren, (float*)&distancesToChildren, @@ -166,7 +168,7 @@ void VoxelTree::recurseNodeWithOperationDistanceSorted(VoxelNode* node, RecurseV for (int i = 0; i < currentCount; i++) { VoxelNode* childNode = sortedChildren[i]; if (childNode) { - //printLog("recurseNodeWithOperationDistanceSorted() PROCESSING child[%d] distance=%f...\n", i, distancesToChildren[i]); + //qDebug("recurseNodeWithOperationDistanceSorted() PROCESSING child[%d] distance=%f...\n", i, distancesToChildren[i]); //childNode->printDebugDetails(""); recurseNodeWithOperationDistanceSorted(childNode, operation, point, extraData); } @@ -458,7 +460,7 @@ void VoxelTree::deleteVoxelCodeFromTreeRecursion(VoxelNode* node, void* extraDat // isn't a colored leaf, and the child branch doesn't exist, so there's nothing to do below and // we can safely return, ending the recursion and unwinding if (!childNode) { - //printLog("new___deleteVoxelCodeFromTree() child branch doesn't exist, but parent is not a leaf, just unwind\n"); + //qDebug("new___deleteVoxelCodeFromTree() child branch doesn't exist, but parent is not a leaf, just unwind\n"); return; } @@ -546,7 +548,7 @@ void VoxelTree::readCodeColorBufferToTreeRecursion(VoxelNode* node, void* extraD } } else { if (!node->isLeaf()) { - printLog("WARNING! operation would require deleting children, add Voxel ignored!\n "); + qDebug("WARNING! operation would require deleting children, add Voxel ignored!\n "); } } @@ -619,13 +621,13 @@ void VoxelTree::printTreeForDebugging(VoxelNode *startNode) { } } - printLog("color mask: "); + qDebug("color mask: "); outputBits(colorMask); // output the colors we have for (int j = 0; j < NUMBER_OF_CHILDREN; j++) { if (startNode->getChildAtIndex(j) && startNode->getChildAtIndex(j)->isColored()) { - printLog("color %d : ",j); + qDebug("color %d : ",j); for (int c = 0; c < 3; c++) { outputBits(startNode->getChildAtIndex(j)->getTrueColor()[c],false); } @@ -641,7 +643,7 @@ void VoxelTree::printTreeForDebugging(VoxelNode *startNode) { } } - printLog("child mask: "); + qDebug("child mask: "); outputBits(childMask); if (childMask > 0) { @@ -686,7 +688,7 @@ void VoxelTree::loadVoxelsFile(const char* fileName, bool wantColorRandomizer) { int totalBytesRead = 0; if(file.is_open()) { - printLog("loading file...\n"); + qDebug("loading file...\n"); bool bail = false; while (!file.eof() && !bail) { file.get(octets); @@ -711,14 +713,14 @@ void VoxelTree::loadVoxelsFile(const char* fileName, bool wantColorRandomizer) { file.get(colorRead); blue = (unsigned char)colorRead; - printLog("voxel color from file red:%d, green:%d, blue:%d \n",red,green,blue); + qDebug("voxel color from file red:%d, green:%d, blue:%d \n",red,green,blue); vCount++; int colorRandomizer = wantColorRandomizer ? randIntInRange (-5, 5) : 0; voxelData[lengthInBytes+1] = std::max(0,std::min(255,red + colorRandomizer)); voxelData[lengthInBytes+2] = std::max(0,std::min(255,green + colorRandomizer)); voxelData[lengthInBytes+3] = std::max(0,std::min(255,blue + colorRandomizer)); - printLog("voxel color after rand red:%d, green:%d, blue:%d\n", + qDebug("voxel color after rand red:%d, green:%d, blue:%d\n", voxelData[lengthInBytes+1], voxelData[lengthInBytes+2], voxelData[lengthInBytes+3]); //printVoxelCode(voxelData); @@ -819,7 +821,7 @@ void VoxelTree::createSphere(float radius, float xc, float yc, float zc, float v if (debug) { int percentComplete = 100 * (thisRadius/radius); - printLog("percentComplete=%d\n",percentComplete); + qDebug("percentComplete=%d\n",percentComplete); } for (float theta=0.0; theta <= 2 * M_PI; theta += angleDelta) { @@ -835,7 +837,7 @@ void VoxelTree::createSphere(float radius, float xc, float yc, float zc, float v // 2) In all modes, we will use our "outer" color to draw the voxels. Otherwise we will use the average color if (lastLayer) { if (false && debug) { - printLog("adding candy shell: theta=%f phi=%f thisRadius=%f radius=%f\n", + qDebug("adding candy shell: theta=%f phi=%f thisRadius=%f radius=%f\n", theta, phi, thisRadius,radius); } switch (mode) { @@ -859,7 +861,7 @@ void VoxelTree::createSphere(float radius, float xc, float yc, float zc, float v green = (unsigned char)std::min(255, std::max(0, (int)(g1 + ((g2 - g1) * gradient)))); blue = (unsigned char)std::min(255, std::max(0, (int)(b1 + ((b2 - b1) * gradient)))); if (debug) { - printLog("perlin=%f gradient=%f color=(%d,%d,%d)\n",perlin, gradient, red, green, blue); + qDebug("perlin=%f gradient=%f color=(%d,%d,%d)\n",perlin, gradient, red, green, blue); } } break; } @@ -1176,7 +1178,7 @@ int VoxelTree::encodeTreeBitstreamRecursion(VoxelNode* node, unsigned char* outp if (childNode) { // chance to optimize, doesn't need to be actual distance!! Could be distance squared //float distanceSquared = childNode->distanceSquareToPoint(point); - //printLog("recurseNodeWithOperationDistanceSorted() CHECKING child[%d] point=%f,%f center=%f,%f distance=%f...\n", i, point.x, point.y, center.x, center.y, distance); + //qDebug("recurseNodeWithOperationDistanceSorted() CHECKING child[%d] point=%f,%f center=%f,%f distance=%f...\n", i, point.x, point.y, center.x, center.y, distance); //childNode->printDebugDetails(""); float distance = params.viewFrustum ? childNode->distanceToCamera(*params.viewFrustum) : 0; @@ -1432,7 +1434,7 @@ int VoxelTree::encodeTreeBitstreamRecursion(VoxelNode* node, unsigned char* outp bool VoxelTree::readFromSVOFile(const char* fileName) { std::ifstream file(fileName, std::ios::in|std::ios::binary|std::ios::ate); if(file.is_open()) { - printLog("loading file %s...\n", fileName); + qDebug("loading file %s...\n", fileName); // get file length.... unsigned long fileLength = file.tellg(); @@ -1460,14 +1462,14 @@ bool VoxelTree::readFromSchematicFile(const char *fileName) { std::stringstream ss; int err = retrieveData(fileName, ss); if (err && ss.get() != TAG_Compound) { - printLog("[ERROR] Invalid schematic file.\n"); + qDebug("[ERROR] Invalid schematic file.\n"); return false; } ss.get(); TagCompound schematics(ss); if (!schematics.getBlocksId() || !schematics.getBlocksData()) { - printLog("[ERROR] Invalid schematic file.\n"); + qDebug("[ERROR] Invalid schematic file.\n"); return false; } @@ -1530,7 +1532,7 @@ bool VoxelTree::readFromSchematicFile(const char *fileName) { } } - printLog("Created %d voxels from minecraft import.\n", count); + qDebug("Created %d voxels from minecraft import.\n", count); return true; } @@ -1540,7 +1542,7 @@ void VoxelTree::writeToSVOFile(const char* fileName, VoxelNode* node) const { std::ofstream file(fileName, std::ios::out|std::ios::binary); if(file.is_open()) { - printLog("saving to file %s...\n", fileName); + qDebug("saving to file %s...\n", fileName); VoxelNodeBag nodeBag; // If we were given a specific node, start from there, otherwise start from root diff --git a/pairing-server/CMakeLists.txt b/pairing-server/CMakeLists.txt index 9feb1aa424..5e0adcb378 100644 --- a/pairing-server/CMakeLists.txt +++ b/pairing-server/CMakeLists.txt @@ -6,7 +6,7 @@ set(MACRO_DIR ${ROOT_DIR}/cmake/macros) set(TARGET_NAME pairing-server) include(${MACRO_DIR}/SetupHifiProject.cmake) -setup_hifi_project(${TARGET_NAME}) +setup_hifi_project(${TARGET_NAME} TRUE) # link the shared hifi library include(${MACRO_DIR}/LinkHifiLibrary.cmake) diff --git a/space-server/CMakeLists.txt b/space-server/CMakeLists.txt index 5b34f86a4c..c821992378 100644 --- a/space-server/CMakeLists.txt +++ b/space-server/CMakeLists.txt @@ -7,7 +7,7 @@ set(TARGET_NAME space-server) include(${MACRO_DIR}/SetupHifiProject.cmake) -setup_hifi_project(${TARGET_NAME}) +setup_hifi_project(${TARGET_NAME} TRUE) include(${MACRO_DIR}/LinkHifiLibrary.cmake) link_hifi_library(shared ${TARGET_NAME} ${ROOT_DIR}) \ No newline at end of file diff --git a/voxel-edit/CMakeLists.txt b/voxel-edit/CMakeLists.txt index f7acb26e92..de056cdd86 100644 --- a/voxel-edit/CMakeLists.txt +++ b/voxel-edit/CMakeLists.txt @@ -14,7 +14,7 @@ include_glm(${TARGET_NAME} ${ROOT_DIR}) include(${MACRO_DIR}/SetupHifiProject.cmake) -setup_hifi_project(${TARGET_NAME}) +setup_hifi_project(${TARGET_NAME} FALSE) # link in the shared library include(${MACRO_DIR}/LinkHifiLibrary.cmake) diff --git a/voxel-server/CMakeLists.txt b/voxel-server/CMakeLists.txt index 2bdba8f6e3..c401a8033c 100644 --- a/voxel-server/CMakeLists.txt +++ b/voxel-server/CMakeLists.txt @@ -14,7 +14,7 @@ include_glm(${TARGET_NAME} ${ROOT_DIR}) include(${MACRO_DIR}/SetupHifiProject.cmake) -setup_hifi_project(${TARGET_NAME}) +setup_hifi_project(${TARGET_NAME} TRUE) # link in the shared library include(${MACRO_DIR}/LinkHifiLibrary.cmake) From 89d3cfdb6fe3b3f694ff623d4d08f6d2b7b4dac7 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 16 Jul 2013 11:16:51 -0700 Subject: [PATCH 25/81] remove now extraneous newlines after switch to QDebug --- interface/src/Application.cpp | 26 +++---- interface/src/Audio.cpp | 44 ++++++------ interface/src/AvatarVoxelSystem.cpp | 4 +- interface/src/SerialInterface.cpp | 6 +- interface/src/Transmitter.cpp | 6 +- interface/src/Util.cpp | 14 ++-- interface/src/VoxelSystem.cpp | 46 ++++++------ interface/src/Webcam.cpp | 20 +++--- interface/src/main.cpp | 4 +- interface/src/starfield/Loader.h | 10 +-- libraries/shared/src/NodeList.cpp | 12 ++-- libraries/shared/src/OctalCode.cpp | 4 +- libraries/shared/src/PacketHeaders.cpp | 2 +- libraries/shared/src/PerfStat.cpp | 8 +-- libraries/shared/src/SharedUtil.cpp | 14 ++-- libraries/shared/src/UDPSocket.cpp | 8 +-- libraries/voxels/src/CoverageMap.cpp | 72 +++++++++---------- libraries/voxels/src/CoverageMapV2.cpp | 12 ++-- libraries/voxels/src/ViewFrustum.cpp | 44 ++++++------ libraries/voxels/src/VoxelNode.cpp | 8 +-- .../voxels/src/VoxelProjectedPolygon.cpp | 2 +- libraries/voxels/src/VoxelTree.cpp | 32 ++++----- 22 files changed, 199 insertions(+), 199 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index a85fad9060..a32832318a 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -210,7 +210,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : { _applicationStartupTime = startup_time; _window->setWindowTitle("Interface"); - qDebug("Interface Startup:\n"); + qDebug("Interface Startup:"); unsigned int listenPort = 0; // bind to an ephemeral port by default const char** constArgv = const_cast(argv); @@ -233,7 +233,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : // Handle Local Domain testing with the --local command line if (cmdOptionExists(argc, constArgv, "--local")) { - qDebug("Local Domain MODE!\n"); + qDebug("Local Domain MODE!"); NodeList::getInstance()->setDomainIPToLocalhost(); } @@ -297,7 +297,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : } void Application::initializeGL() { - qDebug( "Created Display Window.\n" ); + qDebug( "Created Display Window." ); // initialize glut for shape drawing; Qt apparently initializes it on OS X #ifndef __APPLE__ @@ -312,10 +312,10 @@ void Application::initializeGL() { _viewFrustumOffsetCamera.setFarClip(500.0 * TREE_SCALE); initDisplay(); - qDebug( "Initialized Display.\n" ); + qDebug( "Initialized Display." ); init(); - qDebug( "Init() complete.\n" ); + qDebug( "Init() complete." ); // Check to see if the user passed in a command line option for randomizing colors bool wantColorRandomizer = !arguments().contains("--NoColorRandomizer"); @@ -324,13 +324,13 @@ void Application::initializeGL() { // Voxel File. If so, load it now. if (!_voxelsFilename.isEmpty()) { _voxels.loadVoxelsFile(_voxelsFilename.constData(), wantColorRandomizer); - qDebug("Local Voxel File loaded.\n"); + qDebug("Local Voxel File loaded."); } // create thread for receipt of data via UDP if (_enableNetworkThread) { pthread_create(&_networkReceiveThread, NULL, networkReceive, NULL); - qDebug("Network receive thread created.\n"); + qDebug("Network receive thread created."); } // call terminate before exiting @@ -351,7 +351,7 @@ void Application::initializeGL() { float startupTime = (usecTimestampNow() - usecTimestamp(&_applicationStartupTime)) / 1000000.0; _justStarted = false; char title[50]; - sprintf(title, "Interface: %4.2f seconds\n", startupTime); + sprintf(title, "Interface: %4.2f seconds", startupTime); qDebug("%s", title); _window->setWindowTitle(title); @@ -1446,7 +1446,7 @@ void Application::importVoxels() { if (fileNameString.endsWith(".png", Qt::CaseInsensitive)) { QImage pngImage = QImage(fileName); if (pngImage.height() != pngImage.width()) { - qDebug("ERROR: Bad PNG size: height != width.\n"); + qDebug("ERROR: Bad PNG size: height != width."); return; } @@ -1758,7 +1758,7 @@ void Application::init() { _audio.setJitterBufferSamples(_audioJitterBufferSamples); } - qDebug("Loaded settings.\n"); + qDebug("Loaded settings."); sendAvatarVoxelURLMessage(_myAvatar.getVoxels()->getVoxelURL()); @@ -2771,7 +2771,7 @@ glm::vec2 Application::getScaledScreenPoint(glm::vec2 projectedPoint) { // render the coverage map on screen void Application::renderCoverageMapV2() { - //qDebug("renderCoverageMap()\n"); + //qDebug("renderCoverageMap()"); glDisable(GL_LIGHTING); glLineWidth(2.0); @@ -2816,7 +2816,7 @@ void Application::renderCoverageMapsV2Recursively(CoverageMapV2* map) { // render the coverage map on screen void Application::renderCoverageMap() { - //qDebug("renderCoverageMap()\n"); + //qDebug("renderCoverageMap()"); glDisable(GL_LIGHTING); glLineWidth(2.0); @@ -3147,7 +3147,7 @@ void Application::eyedropperVoxelUnderCursor() { } void Application::goHome() { - qDebug("Going Home!\n"); + qDebug("Going Home!"); _myAvatar.setPosition(START_LOCATION); } diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 4c707de938..4bacc274ad 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -152,11 +152,11 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o // If not enough audio has arrived to start playback, keep waiting // #ifdef SHOW_AUDIO_DEBUG - qDebug("%i,%i,%i,%i\n", - _packetsReceivedThisPlayback, - ringBuffer->diffLastWriteNextOutput(), - PACKET_LENGTH_SAMPLES, - _jitterBufferSamples); + qDebug("%i,%i,%i,%i", + _packetsReceivedThisPlayback, + ringBuffer->diffLastWriteNextOutput(), + PACKET_LENGTH_SAMPLES, + _jitterBufferSamples); #endif } else if (ringBuffer->isStarted() && ringBuffer->diffLastWriteNextOutput() == 0) { // @@ -169,7 +169,7 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o _packetsReceivedThisPlayback = 0; _wasStarved = 10; // Frames for which to render the indication that the system was starved. #ifdef SHOW_AUDIO_DEBUG - qDebug("Starved, remaining samples = %d\n", + qDebug("Starved, remaining samples = %d", ringBuffer->diffLastWriteNextOutput()); #endif @@ -180,10 +180,10 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o if (!ringBuffer->isStarted()) { ringBuffer->setStarted(true); #ifdef SHOW_AUDIO_DEBUG - qDebug("starting playback %0.1f msecs delayed, jitter = %d, pkts recvd: %d \n", - (usecTimestampNow() - usecTimestamp(&_firstPacketReceivedTime))/1000.0, - _jitterBufferSamples, - _packetsReceivedThisPlayback); + qDebug("starting playback %0.1f msecs delayed, jitter = %d, pkts recvd: %d", + (usecTimestampNow() - usecTimestamp(&_firstPacketReceivedTime))/1000.0, + _jitterBufferSamples, + _packetsReceivedThisPlayback); #endif } @@ -300,8 +300,8 @@ int Audio::audioCallback (const void* inputBuffer, static void outputPortAudioError(PaError error) { if (error != paNoError) { - qDebug("-- portaudio termination error --\n"); - qDebug("PortAudio error (%d): %s\n", error, Pa_GetErrorText(error)); + qDebug("-- portaudio termination error --"); + qDebug("PortAudio error (%d): %s", error, Pa_GetErrorText(error)); } } @@ -350,7 +350,7 @@ Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples) : outputParameters.device = Pa_GetDefaultOutputDevice(); if (inputParameters.device == -1 || outputParameters.device == -1) { - qDebug("Audio: Missing device.\n"); + qDebug("Audio: Missing device."); outputPortAudioError(Pa_Terminate()); return; } @@ -385,12 +385,12 @@ Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples) : outputPortAudioError(Pa_StartStream(_stream)); // Uncomment these lines to see the system-reported latency - //qDebug("Default low input, output latency (secs): %0.4f, %0.4f\n", + //qDebug("Default low input, output latency (secs): %0.4f, %0.4f", // Pa_GetDeviceInfo(Pa_GetDefaultInputDevice())->defaultLowInputLatency, // Pa_GetDeviceInfo(Pa_GetDefaultOutputDevice())->defaultLowOutputLatency); const PaStreamInfo* streamInfo = Pa_GetStreamInfo(_stream); - qDebug("Started audio with reported latency msecs In/Out: %.0f, %.0f\n", streamInfo->inputLatency * 1000.f, + qDebug("Started audio with reported latency msecs In/Out: %.0f, %.0f", streamInfo->inputLatency * 1000.f, streamInfo->outputLatency * 1000.f); gettimeofday(&_lastReceiveTime, NULL); @@ -651,7 +651,7 @@ inline void Audio::eventuallySendRecvPing(int16_t* inputLeft, int16_t* outputLef // As of the next frame, we'll be recoding PING_FRAMES_TO_RECORD from // the mic (pointless to start now as we can't record unsent audio). _isSendingEchoPing = false; - qDebug("Send audio ping\n"); + qDebug("Send audio ping"); } else if (_pingFramesToRecord > 0) { @@ -665,7 +665,7 @@ inline void Audio::eventuallySendRecvPing(int16_t* inputLeft, int16_t* outputLef if (_pingFramesToRecord == 0) { _pingAnalysisPending = true; - qDebug("Received ping echo\n"); + qDebug("Received ping echo"); } } } @@ -689,25 +689,25 @@ inline void Audio::analyzePing() { // Determine extrema int botAt = findExtremum(_echoSamplesLeft, PING_SAMPLES_TO_ANALYZE, -1); if (botAt == -1) { - qDebug("Audio Ping: Minimum not found.\n"); + qDebug("Audio Ping: Minimum not found."); return; } int topAt = findExtremum(_echoSamplesLeft, PING_SAMPLES_TO_ANALYZE, 1); if (topAt == -1) { - qDebug("Audio Ping: Maximum not found.\n"); + qDebug("Audio Ping: Maximum not found."); return; } // Determine peak amplitude - warn if low int ampli = (_echoSamplesLeft[topAt] - _echoSamplesLeft[botAt]) / 2; if (ampli < PING_MIN_AMPLI) { - qDebug("Audio Ping unreliable - low amplitude %d.\n", ampli); + qDebug("Audio Ping unreliable - low amplitude %d.", ampli); } // Determine period - warn if doesn't look like our signal int halfPeriod = abs(topAt - botAt); if (abs(halfPeriod-PING_HALF_PERIOD) > PING_MAX_PERIOD_DIFFERENCE) { - qDebug("Audio Ping unreliable - peak distance %d vs. %d\n", halfPeriod, PING_HALF_PERIOD); + qDebug("Audio Ping unreliable - peak distance %d vs. %d", halfPeriod, PING_HALF_PERIOD); } // Ping is sent: @@ -748,7 +748,7 @@ inline void Audio::analyzePing() { int delay = (botAt + topAt) / 2 + PING_PERIOD; - qDebug("\n| Audio Ping results:\n+----- ---- --- - - - - -\n\n" + qDebug("\n| Audio Ping results:\n+----- ---- --- - - - - -\n" "Delay = %d samples (%d ms)\nPeak amplitude = %d\n\n", delay, (delay * 1000) / int(SAMPLE_RATE), ampli); } diff --git a/interface/src/AvatarVoxelSystem.cpp b/interface/src/AvatarVoxelSystem.cpp index c85ea1a343..a341ecaa38 100644 --- a/interface/src/AvatarVoxelSystem.cpp +++ b/interface/src/AvatarVoxelSystem.cpp @@ -93,7 +93,7 @@ const Mode MODES[] = { void AvatarVoxelSystem::cycleMode() { _mode = (_mode + 1) % (sizeof(MODES) / sizeof(MODES[0])); - qDebug("Voxeltar bind mode %d.\n", _mode); + qDebug("Voxeltar bind mode %d.", _mode); // rebind QUrl url = _voxelURL; @@ -255,7 +255,7 @@ void AvatarVoxelSystem::handleVoxelDownloadProgress(qint64 bytesReceived, qint64 } void AvatarVoxelSystem::handleVoxelReplyError() { - qDebug("%s\n", _voxelReply->errorString().toAscii().constData()); + qDebug("%s", _voxelReply->errorString().toAscii().constData()); _voxelReply->disconnect(this); _voxelReply->deleteLater(); diff --git a/interface/src/SerialInterface.cpp b/interface/src/SerialInterface.cpp index 0f90ee8dd7..e17feb48d7 100644 --- a/interface/src/SerialInterface.cpp +++ b/interface/src/SerialInterface.cpp @@ -100,7 +100,7 @@ void SerialInterface::initializePort(char* portname) { qDebug("Opening SerialUSB %s: ", portname); if (_serialDescriptor == -1) { - qDebug("Failed.\n"); + qDebug("Failed."); return; } @@ -134,7 +134,7 @@ void SerialInterface::initializePort(char* portname) { mpu_set_sensors(INV_XYZ_GYRO | INV_XYZ_ACCEL | INV_XYZ_COMPASS); } - qDebug("Connected.\n"); + qDebug("Connected."); resetSerial(); _active = true; @@ -373,7 +373,7 @@ void SerialInterface::readData(float deltaTime) { gettimeofday(&now, NULL); if (diffclock(&lastGoodRead, &now) > NO_READ_MAXIMUM_MSECS) { - qDebug("No data - Shutting down SerialInterface.\n"); + qDebug("No data - Shutting down SerialInterface."); resetSerial(); } } else { diff --git a/interface/src/Transmitter.cpp b/interface/src/Transmitter.cpp index eac769ead7..ce0180e501 100644 --- a/interface/src/Transmitter.cpp +++ b/interface/src/Transmitter.cpp @@ -38,7 +38,7 @@ void Transmitter::checkForLostTransmitter() { int msecsSinceLast = diffclock(_lastReceivedPacket, &now); if (msecsSinceLast > TIME_TO_ASSUME_LOST_MSECS) { resetLevels(); - qDebug("Transmitter signal lost.\n"); + qDebug("Transmitter signal lost."); } } } @@ -93,12 +93,12 @@ void Transmitter::processIncomingData(unsigned char* packetData, int numBytes) { _estimatedRotation.y *= (1.f - DECAY_RATE * DELTA_TIME); if (!_isConnected) { - qDebug("Transmitter Connected.\n"); + qDebug("Transmitter Connected."); _isConnected = true; _estimatedRotation *= 0.0; } } else { - qDebug("Transmitter packet read error, %d bytes.\n", numBytes); + qDebug("Transmitter packet read error, %d bytes.", numBytes); } } diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 20f33f924a..7bc4e50d96 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -451,7 +451,7 @@ void renderOrientationDirections(glm::vec3 position, const glm::quat& orientatio bool closeEnoughForGovernmentWork(float a, float b) { float distance = std::abs(a-b); - //qDebug("closeEnoughForGovernmentWork() a=%1.10f b=%1.10f distance=%1.10f\n",a,b,distance); + //qDebug("closeEnoughForGovernmentWork() a=%1.10f b=%1.10f distance=%1.10f",a,b,distance); return (distance < 0.00001f); } @@ -469,7 +469,7 @@ void runTimingTests() { gettimeofday(&endTime, NULL); } elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("gettimeofday() usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("gettimeofday() usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); // Random number generation gettimeofday(&startTime, NULL); @@ -478,7 +478,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("rand() stored in array usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("rand() stored in array usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); // Random number generation using randFloat() gettimeofday(&startTime, NULL); @@ -487,7 +487,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("randFloat() stored in array usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("randFloat() stored in array usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); // PowF function fTest = 1145323.2342f; @@ -497,7 +497,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("powf(f, 0.5) usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("powf(f, 0.5) usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); // Vector Math float distance; @@ -510,7 +510,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("vector math usecs: %f [%f msecs total for %d tests]\n", + qDebug("vector math usecs: %f [%f msecs total for %d tests]", 1000.0f * elapsedMsecs / (float) numTests, elapsedMsecs, numTests); // Vec3 test @@ -524,7 +524,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("vec3 assign and dot() usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("vec3 assign and dot() usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); } diff --git a/interface/src/VoxelSystem.cpp b/interface/src/VoxelSystem.cpp index f219e38dc6..0b4777a12f 100644 --- a/interface/src/VoxelSystem.cpp +++ b/interface/src/VoxelSystem.cpp @@ -144,16 +144,16 @@ int VoxelSystem::parseData(unsigned char* sourceBuffer, int numBytes) { int commandLength = strlen(command); // commands are null terminated strings int totalLength = 1+commandLength+1; - qDebug("got Z message len(%d)= %s\n", numBytes, command); + qDebug("got Z message len(%d)= %s", numBytes, command); while (totalLength <= numBytes) { if (0==strcmp(command,(char*)"erase all")) { - qDebug("got Z message == erase all\n"); + qDebug("got Z message == erase all"); _tree->eraseAllVoxels(); _voxelsInReadArrays = _voxelsInWriteArrays = 0; // better way to do this?? } if (0==strcmp(command,(char*)"add scene")) { - qDebug("got Z message == add scene - NOT SUPPORTED ON INTERFACE\n"); + qDebug("got Z message == add scene - NOT SUPPORTED ON INTERFACE"); } totalLength += commandLength+1; } @@ -708,7 +708,7 @@ bool VoxelSystem::randomColorOperation(VoxelNode* node, void* extraData) { void VoxelSystem::randomizeVoxelColors() { _nodeCount = 0; _tree->recurseTreeWithOperation(randomColorOperation); - qDebug("setting randomized true color for %d nodes\n", _nodeCount); + qDebug("setting randomized true color for %d nodes", _nodeCount); setupNewVoxelsForDrawing(); } @@ -722,7 +722,7 @@ bool VoxelSystem::falseColorizeRandomOperation(VoxelNode* node, void* extraData) void VoxelSystem::falseColorizeRandom() { _nodeCount = 0; _tree->recurseTreeWithOperation(falseColorizeRandomOperation); - qDebug("setting randomized false color for %d nodes\n", _nodeCount); + qDebug("setting randomized false color for %d nodes", _nodeCount); setupNewVoxelsForDrawing(); } @@ -736,7 +736,7 @@ void VoxelSystem::trueColorize() { PerformanceWarning warn(true, "trueColorize()",true); _nodeCount = 0; _tree->recurseTreeWithOperation(trueColorizeOperation); - qDebug("setting true color for %d nodes\n", _nodeCount); + qDebug("setting true color for %d nodes", _nodeCount); setupNewVoxelsForDrawing(); } @@ -756,7 +756,7 @@ bool VoxelSystem::falseColorizeInViewOperation(VoxelNode* node, void* extraData) void VoxelSystem::falseColorizeInView(ViewFrustum* viewFrustum) { _nodeCount = 0; _tree->recurseTreeWithOperation(falseColorizeInViewOperation,(void*)viewFrustum); - qDebug("setting in view false color for %d nodes\n", _nodeCount); + qDebug("setting in view false color for %d nodes", _nodeCount); setupNewVoxelsForDrawing(); } @@ -806,10 +806,10 @@ void VoxelSystem::falseColorizeDistanceFromView(ViewFrustum* viewFrustum) { _maxDistance = 0.0; _minDistance = FLT_MAX; _tree->recurseTreeWithOperation(getDistanceFromViewRangeOperation,(void*)viewFrustum); - qDebug("determining distance range for %d nodes\n", _nodeCount); + qDebug("determining distance range for %d nodes", _nodeCount); _nodeCount = 0; _tree->recurseTreeWithOperation(falseColorizeDistanceFromViewOperation,(void*)viewFrustum); - qDebug("setting in distance false color for %d nodes\n", _nodeCount); + qDebug("setting in distance false color for %d nodes", _nodeCount); setupNewVoxelsForDrawing(); } @@ -921,7 +921,7 @@ void VoxelSystem::removeOutOfView() { } bool showRemoveDebugDetails = false; if (showRemoveDebugDetails) { - qDebug("removeOutOfView() scanned=%ld removed=%ld inside=%ld intersect=%ld outside=%ld _removedVoxels.count()=%d \n", + qDebug("removeOutOfView() scanned=%ld removed=%ld inside=%ld intersect=%ld outside=%ld _removedVoxels.count()=%d ", args.nodesScanned, args.nodesRemoved, args.nodesInside, args.nodesIntersect, args.nodesOutside, _removedVoxels.count() ); @@ -987,7 +987,7 @@ bool VoxelSystem::falseColorizeRandomEveryOtherOperation(VoxelNode* node, void* void VoxelSystem::falseColorizeRandomEveryOther() { falseColorizeRandomEveryOtherArgs args; _tree->recurseTreeWithOperation(falseColorizeRandomEveryOtherOperation,&args); - qDebug("randomized false color for every other node: total %ld, colorable %ld, colored %ld\n", + qDebug("randomized false color for every other node: total %ld, colorable %ld, colored %ld", args.totalNodes, args.colorableNodes, args.coloredNodes); setupNewVoxelsForDrawing(); } @@ -1048,7 +1048,7 @@ bool VoxelSystem::collectStatsForTreesAndVBOsOperation(VoxelNode* node, void* ex unsigned long nodeIndex = node->getBufferIndex(); if (args->hasIndexFound[nodeIndex]) { args->duplicateVBOIndex++; - qDebug("duplicateVBO found... index=%ld, isDirty=%s, shouldRender=%s \n", nodeIndex, + qDebug("duplicateVBO found... index=%ld, isDirty=%s, shouldRender=%s ", nodeIndex, debug::valueOf(node->isDirty()), debug::valueOf(node->getShouldRender())); } else { args->hasIndexFound[nodeIndex] = true; @@ -1083,13 +1083,13 @@ void VoxelSystem::collectStatsForTreesAndVBOs() { args.expectedMax = _voxelsInWriteArrays; _tree->recurseTreeWithOperation(collectStatsForTreesAndVBOsOperation,&args); - qDebug("Local Voxel Tree Statistics:\n total nodes %ld \n leaves %ld \n dirty %ld \n colored %ld \n shouldRender %ld \n", + qDebug("Local Voxel Tree Statistics:\n total nodes %ld \n leaves %ld \n dirty %ld \n colored %ld \n shouldRender %ld ", args.totalNodes, args.leafNodes, args.dirtyNodes, args.coloredNodes, args.shouldRenderNodes); - qDebug(" _voxelsDirty=%s \n _voxelsInWriteArrays=%ld \n minDirty=%ld \n maxDirty=%ld \n", debug::valueOf(_voxelsDirty), + qDebug(" _voxelsDirty=%s \n _voxelsInWriteArrays=%ld \n minDirty=%ld \n maxDirty=%ld ", debug::valueOf(_voxelsDirty), _voxelsInWriteArrays, minDirty, maxDirty); - qDebug(" inVBO %ld \n nodesInVBOOverExpectedMax %ld \n duplicateVBOIndex %ld \n nodesInVBONotShouldRender %ld \n", + qDebug(" inVBO %ld \n nodesInVBOOverExpectedMax %ld \n duplicateVBOIndex %ld \n nodesInVBONotShouldRender %ld ", args.nodesInVBO, args.nodesInVBOOverExpectedMax, args.duplicateVBOIndex, args.nodesInVBONotShouldRender); glBufferIndex minInVBO = GLBUFFER_INDEX_UNKNOWN; @@ -1102,7 +1102,7 @@ void VoxelSystem::collectStatsForTreesAndVBOs() { } } - qDebug(" minInVBO=%ld \n maxInVBO=%ld \n _voxelsInWriteArrays=%ld \n _voxelsInReadArrays=%ld \n", + qDebug(" minInVBO=%ld \n maxInVBO=%ld \n _voxelsInWriteArrays=%ld \n _voxelsInReadArrays=%ld ", minInVBO, maxInVBO, _voxelsInWriteArrays, _voxelsInReadArrays); } @@ -1127,7 +1127,7 @@ void VoxelSystem::createVoxel(float x, float y, float z, float s, unsigned char red, unsigned char green, unsigned char blue, bool destructive) { pthread_mutex_lock(&_treeLock); - //qDebug("VoxelSystem::createVoxel(%f,%f,%f,%f)\n",x,y,z,s); + //qDebug("VoxelSystem::createVoxel(%f,%f,%f,%f)",x,y,z,s); _tree->createVoxel(x, y, z, s, red, green, blue, destructive); setupNewVoxelsForDrawing(); @@ -1253,9 +1253,9 @@ bool VoxelSystem::falseColorizeOccludedOperation(VoxelNode* node, void* extraDat args->occludedVoxels++; } else if (result == STORED) { args->notOccludedVoxels++; - //qDebug("***** falseColorizeOccludedOperation() NODE is STORED *****\n"); + //qDebug("***** falseColorizeOccludedOperation() NODE is STORED *****"); } else if (result == DOESNT_FIT) { - //qDebug("***** falseColorizeOccludedOperation() NODE DOESNT_FIT???? *****\n"); + //qDebug("***** falseColorizeOccludedOperation() NODE DOESNT_FIT???? *****"); } } return true; // keep going! @@ -1288,7 +1288,7 @@ void VoxelSystem::falseColorizeOccluded() { _tree->recurseTreeWithOperationDistanceSorted(falseColorizeOccludedOperation, position, (void*)&args); - qDebug("falseColorizeOccluded()\n position=(%f,%f)\n total=%ld\n colored=%ld\n occluded=%ld\n notOccluded=%ld\n outOfView=%ld\n subtreeVoxelsSkipped=%ld\n stagedForDeletion=%ld\n nonLeaves=%ld\n nonLeavesOutOfView=%ld\n nonLeavesOccluded=%ld\n pointInside_calls=%ld\n occludes_calls=%ld\n intersects_calls=%ld\n", + qDebug("falseColorizeOccluded()\n position=(%f,%f)\n total=%ld\n colored=%ld\n occluded=%ld\n notOccluded=%ld\n outOfView=%ld\n subtreeVoxelsSkipped=%ld\n stagedForDeletion=%ld\n nonLeaves=%ld\n nonLeavesOutOfView=%ld\n nonLeavesOccluded=%ld\n pointInside_calls=%ld\n occludes_calls=%ld\n intersects_calls=%ld", position.x, position.y, args.totalVoxels, args.coloredVoxels, args.occludedVoxels, args.notOccludedVoxels, args.outOfView, args.subtreeVoxelsSkipped, @@ -1374,9 +1374,9 @@ bool VoxelSystem::falseColorizeOccludedV2Operation(VoxelNode* node, void* extraD args->occludedVoxels++; } else if (result == V2_STORED) { args->notOccludedVoxels++; - //qDebug("***** falseColorizeOccludedOperation() NODE is STORED *****\n"); + //qDebug("***** falseColorizeOccludedOperation() NODE is STORED *****"); } else if (result == V2_DOESNT_FIT) { - //qDebug("***** falseColorizeOccludedOperation() NODE DOESNT_FIT???? *****\n"); + //qDebug("***** falseColorizeOccludedOperation() NODE DOESNT_FIT???? *****"); } delete voxelPolygon; // V2 maps don't store polygons, so we're always in charge of freeing } @@ -1413,7 +1413,7 @@ void VoxelSystem::falseColorizeOccludedV2() { _tree->recurseTreeWithOperationDistanceSorted(falseColorizeOccludedV2Operation, position, (void*)&args); - qDebug("falseColorizeOccludedV2()\n position=(%f,%f)\n total=%ld\n colored=%ld\n occluded=%ld\n notOccluded=%ld\n outOfView=%ld\n subtreeVoxelsSkipped=%ld\n stagedForDeletion=%ld\n nonLeaves=%ld\n nonLeavesOutOfView=%ld\n nonLeavesOccluded=%ld\n pointInside_calls=%ld\n occludes_calls=%ld\n intersects_calls=%ld\n", + qDebug("falseColorizeOccludedV2()\n position=(%f,%f)\n total=%ld\n colored=%ld\n occluded=%ld\n notOccluded=%ld\n outOfView=%ld\n subtreeVoxelsSkipped=%ld\n stagedForDeletion=%ld\n nonLeaves=%ld\n nonLeavesOutOfView=%ld\n nonLeavesOccluded=%ld\n pointInside_calls=%ld\n occludes_calls=%ld\n intersects_calls=%ld", position.x, position.y, args.totalVoxels, args.coloredVoxels, args.occludedVoxels, args.notOccludedVoxels, args.outOfView, args.subtreeVoxelsSkipped, diff --git a/interface/src/Webcam.cpp b/interface/src/Webcam.cpp index f9dd5ffe2c..3831f39893 100644 --- a/interface/src/Webcam.cpp +++ b/interface/src/Webcam.cpp @@ -156,7 +156,7 @@ void Webcam::setFrame(const Mat& frame, int format, const Mat& depth, const Rota glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, _frameWidth = image.width, _frameHeight = image.height, 0, format, GL_UNSIGNED_BYTE, image.imageData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - qDebug("Capturing video at %dx%d.\n", _frameWidth, _frameHeight); + qDebug("Capturing video at %dx%d.", _frameWidth, _frameHeight); } else { glBindTexture(GL_TEXTURE_2D, _frameTextureID); @@ -172,7 +172,7 @@ void Webcam::setFrame(const Mat& frame, int format, const Mat& depth, const Rota glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, _depthWidth = depthImage.width, _depthHeight = depthImage.height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, depthImage.imageData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - qDebug("Capturing depth at %dx%d.\n", _depthWidth, _depthHeight); + qDebug("Capturing depth at %dx%d.", _depthWidth, _depthHeight); } else { glBindTexture(GL_TEXTURE_2D, _depthTextureID); @@ -330,26 +330,26 @@ static glm::quat xnToGLM(const XnMatrix3X3& matrix) { } static void XN_CALLBACK_TYPE newUser(UserGenerator& generator, XnUserID id, void* cookie) { - qDebug("Found user %d.\n", id); + qDebug("Found user %d.", id); generator.GetSkeletonCap().RequestCalibration(id, false); } static void XN_CALLBACK_TYPE lostUser(UserGenerator& generator, XnUserID id, void* cookie) { - qDebug("Lost user %d.\n", id); + qDebug("Lost user %d.", id); } static void XN_CALLBACK_TYPE calibrationStarted(SkeletonCapability& capability, XnUserID id, void* cookie) { - qDebug("Calibration started for user %d.\n", id); + qDebug("Calibration started for user %d.", id); } static void XN_CALLBACK_TYPE calibrationCompleted(SkeletonCapability& capability, XnUserID id, XnCalibrationStatus status, void* cookie) { if (status == XN_CALIBRATION_STATUS_OK) { - qDebug("Calibration completed for user %d.\n", id); + qDebug("Calibration completed for user %d.", id); capability.StartTracking(id); } else { - qDebug("Calibration failed to user %d.\n", id); + qDebug("Calibration failed to user %d.", id); capability.RequestCalibration(id, true); } } @@ -438,7 +438,7 @@ void FrameGrabber::grabFrame() { // make sure it's in the format we expect if (image->nChannels != 3 || image->depth != IPL_DEPTH_8U || image->dataOrder != IPL_DATA_ORDER_PIXEL || image->origin != 0) { - qDebug("Invalid webcam image format.\n"); + qDebug("Invalid webcam image format."); return; } frame = image; @@ -485,7 +485,7 @@ bool FrameGrabber::init() { // load our face cascade switchToResourcesParentIfRequired(); if (_faceCascade.empty() && !_faceCascade.load("resources/haarcascades/haarcascade_frontalface_alt.xml")) { - qDebug("Failed to load Haar cascade for face tracking.\n"); + qDebug("Failed to load Haar cascade for face tracking."); return false; } @@ -513,7 +513,7 @@ bool FrameGrabber::init() { // next, an ordinary webcam if ((_capture = cvCaptureFromCAM(-1)) == 0) { - qDebug("Failed to open webcam.\n"); + qDebug("Failed to open webcam."); return false; } const int IDEAL_FRAME_WIDTH = 320; diff --git a/interface/src/main.cpp b/interface/src/main.cpp index 98ed4fb231..7bcef42e88 100644 --- a/interface/src/main.cpp +++ b/interface/src/main.cpp @@ -24,8 +24,8 @@ int main(int argc, const char * argv[]) { gettimeofday(&startup_time, NULL); Application app(argc, const_cast(argv), startup_time); - qDebug( "Created QT Application.\n" ); + qDebug( "Created QT Application." ); int exitCode = app.exec(); - qDebug("Normal exit.\n"); + qDebug("Normal exit."); return exitCode; } diff --git a/interface/src/starfield/Loader.h b/interface/src/starfield/Loader.h index e2f6105f33..8aa1527ad5 100644 --- a/interface/src/starfield/Loader.h +++ b/interface/src/starfield/Loader.h @@ -38,12 +38,12 @@ namespace starfield { if (! UrlReader::readUrl(url, *this, cacheFile)) { - qDebug("%s:%d: %s\n", + qDebug("%s:%d: %s", _urlStr, _lineNo, getError()); return false; } - qDebug("Loaded %u stars.\n", _recordsRead); + qDebug("Loaded %u stars.", _recordsRead); return true; } @@ -63,7 +63,7 @@ namespace starfield { _vertices->clear(); _vertices->reserve(_limit); -// qDebug("Stars.cpp: loader begin %s\n", url); +// qDebug("Stars.cpp: loader begin %s", url); } size_t transfer(char* input, size_t bytes) { @@ -103,7 +103,7 @@ namespace starfield { } else { - qDebug("Stars.cpp:%d: Bad input from %s\n", + qDebug("Stars.cpp:%d: Bad input from %s", _lineNo, _urlStr); } @@ -128,7 +128,7 @@ namespace starfield { // remember the brightness at its top if (_recordsRead == _limit) { -// qDebug("Stars.cpp: vertex limit reached -> heap mode\n"); +// qDebug("Stars.cpp: vertex limit reached -> heap mode"); make_heap( _vertices->begin(), _vertices->end(), diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 6ba71613de..0781d8ed1b 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -43,7 +43,7 @@ NodeList* NodeList::createInstance(char ownerType, unsigned int socketListenPort if (!_sharedInstance) { _sharedInstance = new NodeList(ownerType, socketListenPort); } else { - qDebug("NodeList createInstance called with existing instance.\n"); + qDebug("NodeList createInstance called with existing instance."); } return _sharedInstance; @@ -51,7 +51,7 @@ NodeList* NodeList::createInstance(char ownerType, unsigned int socketListenPort NodeList* NodeList::getInstance() { if (!_sharedInstance) { - qDebug("NodeList getInstance called before call to createInstance. Returning NULL pointer.\n"); + qDebug("NodeList getInstance called before call to createInstance. Returning NULL pointer."); } return _sharedInstance; @@ -275,12 +275,12 @@ void NodeList::sendDomainServerCheckIn() { sockaddr_in tempAddress; memcpy(&tempAddress.sin_addr, pHostInfo->h_addr_list[0], pHostInfo->h_length); strcpy(_domainIP, inet_ntoa(tempAddress.sin_addr)); - qDebug("Domain Server: %s \n", _domainHostname); + qDebug("Domain Server: %s ", _domainHostname); } else { - qDebug("Failed domain server lookup\n"); + qDebug("Failed domain server lookup"); } } else if (!printedDomainServerIP) { - qDebug("Domain Server IP: %s\n", _domainIP); + qDebug("Domain Server IP: %s", _domainIP); printedDomainServerIP = true; } @@ -419,7 +419,7 @@ void NodeList::addNodeToList(Node* newNode) { ++_numNodes; - qDebug() << "Added " << *newNode; + qDebug() << "Added" << *newNode; } unsigned NodeList::broadcastToNodes(unsigned char *broadcastData, size_t dataBytes, const char* nodeTypes, int numNodeTypes) { diff --git a/libraries/shared/src/OctalCode.cpp b/libraries/shared/src/OctalCode.cpp index 3b92869104..336c89093e 100644 --- a/libraries/shared/src/OctalCode.cpp +++ b/libraries/shared/src/OctalCode.cpp @@ -25,12 +25,12 @@ int numberOfThreeBitSectionsInCode(unsigned char * octalCode) { void printOctalCode(unsigned char * octalCode) { if (!octalCode) { - qDebug("NULL\n"); + qDebug("NULL"); } else { for (int i = 0; i < bytesRequiredForCodeLength(*octalCode); i++) { outputBits(octalCode[i],false); } - qDebug("\n"); + qDebug(""); } } diff --git a/libraries/shared/src/PacketHeaders.cpp b/libraries/shared/src/PacketHeaders.cpp index 7b4a0509f3..a91fd1f351 100644 --- a/libraries/shared/src/PacketHeaders.cpp +++ b/libraries/shared/src/PacketHeaders.cpp @@ -29,7 +29,7 @@ bool packetVersionMatch(unsigned char* packetHeader) { if (packetHeader[1] == versionForPacketType(packetHeader[0])) { return true; } else { - qDebug("There is a packet version mismatch for packet with header %c\n", packetHeader[0]); + qDebug("There is a packet version mismatch for packet with header %c", packetHeader[0]); return false; } } diff --git a/libraries/shared/src/PerfStat.cpp b/libraries/shared/src/PerfStat.cpp index 86985eb038..344e9885e6 100644 --- a/libraries/shared/src/PerfStat.cpp +++ b/libraries/shared/src/PerfStat.cpp @@ -59,7 +59,7 @@ PerfStat::~PerfStat() { } if (wantDebugOut) { - qDebug("PerfStats: %s elapsed:%f average:%lf count:%ld total:%lf ut:%d us:%d ue:%d t:%ld s:%ld e:%ld\n", + qDebug("PerfStats: %s elapsed:%f average:%lf count:%ld total:%lf ut:%d us:%d ue:%d t:%ld s:%ld e:%ld", this->group.c_str(),elapsed,average,count,totalTime, (end.tv_usec-start.tv_usec),start.tv_usec,end.tv_usec, (end.tv_sec-start.tv_sec),start.tv_sec,end.tv_sec @@ -111,12 +111,12 @@ PerformanceWarning::~PerformanceWarning() { if ((_alwaysDisplay || _renderWarningsOn) && elapsedmsec > 1) { if (elapsedmsec > 1000) { double elapsedsec = (end - _start) / 1000000.0; - qDebug("%s%s took %lf seconds\n", (_alwaysDisplay ? "" : "WARNING!"), _message, elapsedsec); + qDebug("%s%s took %lf seconds", (_alwaysDisplay ? "" : "WARNING!"), _message, elapsedsec); } else { - qDebug("%s%s took %lf milliseconds\n", (_alwaysDisplay ? "" : "WARNING!"), _message, elapsedmsec); + qDebug("%s%s took %lf milliseconds", (_alwaysDisplay ? "" : "WARNING!"), _message, elapsedmsec); } } else if (_alwaysDisplay) { - qDebug("%s took %lf milliseconds\n", _message, elapsedmsec); + qDebug("%s took %lf milliseconds", _message, elapsedmsec); } }; diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index 23b889bdab..fdcf142d4d 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -65,7 +65,7 @@ void outputBufferBits(unsigned char* buffer, int length, bool withNewLine) { outputBits(buffer[i], false); } if (withNewLine) { - qDebug("\n"); + qDebug(""); } } @@ -82,7 +82,7 @@ void outputBits(unsigned char byte, bool withNewLine) { qDebug(" ] "); if (withNewLine) { - qDebug("\n"); + qDebug(""); } } @@ -386,11 +386,11 @@ void printVoxelCode(unsigned char* voxelCode) { unsigned int voxelSizeInOctets = (voxelSizeInBits/3); unsigned int voxelBufferSize = voxelSizeInBytes+1+3; // 1 for size, 3 for color - qDebug("octets=%d\n",octets); - qDebug("voxelSizeInBits=%d\n",voxelSizeInBits); - qDebug("voxelSizeInBytes=%d\n",voxelSizeInBytes); - qDebug("voxelSizeInOctets=%d\n",voxelSizeInOctets); - qDebug("voxelBufferSize=%d\n",voxelBufferSize); + qDebug("octets=%d",octets); + qDebug("voxelSizeInBits=%d",voxelSizeInBits); + qDebug("voxelSizeInBytes=%d",voxelSizeInBytes); + qDebug("voxelSizeInOctets=%d",voxelSizeInOctets); + qDebug("voxelBufferSize=%d",voxelBufferSize); for(int i=0;iprintDebugDetails(); } @@ -196,7 +196,7 @@ CoverageMapStorageResult CoverageMap::checkMap(VoxelProjectedPolygon* polygon, b // not in view, then we just discard it with a DOESNT_FIT, this saves us time checking values later. if (!polygon->getAllInView()) { _notAllInView++; - //qDebug("CoverageMap2::checkMap()... V2_OCCLUDED\n"); + //qDebug("CoverageMap2::checkMap()... V2_OCCLUDED"); return DOESNT_FIT; } @@ -243,9 +243,9 @@ CoverageMapStorageResult CoverageMap::checkMap(VoxelProjectedPolygon* polygon, b /* if (result == STORED) - qDebug("CoverageMap2::checkMap()... STORED\n"); + qDebug("CoverageMap2::checkMap()... STORED"); else - qDebug("CoverageMap2::checkMap()... OCCLUDED\n"); + qDebug("CoverageMap2::checkMap()... OCCLUDED"); */ return result; @@ -268,16 +268,16 @@ CoverageMapStorageResult CoverageMap::checkMap(VoxelProjectedPolygon* polygon, b /* switch (result) { case STORED: - qDebug("checkMap() = STORED\n"); + qDebug("checkMap() = STORED"); break; case NOT_STORED: - qDebug("checkMap() = NOT_STORED\n"); + qDebug("checkMap() = NOT_STORED"); break; case OCCLUDED: - qDebug("checkMap() = OCCLUDED\n"); + qDebug("checkMap() = OCCLUDED"); break; default: - qDebug("checkMap() = ????? \n"); + qDebug("checkMap() = ????? "); break; } */ @@ -290,27 +290,27 @@ CoverageMapStorageResult CoverageMap::checkMap(VoxelProjectedPolygon* polygon, b // any of our child bounding boxes, so we should add it here. if (storeIt) { if (polygon->getBoundingBox().area() > CoverageMap::MINIMUM_POLYGON_AREA_TO_STORE) { - //qDebug("storing polygon of area: %f\n",polygon->getBoundingBox().area()); + //qDebug("storing polygon of area: %f",polygon->getBoundingBox().area()); if (storeIn->getPolygonCount() < MAX_POLYGONS_PER_REGION) { storeIn->storeInArray(polygon); - //qDebug("CoverageMap2::checkMap()... STORED\n"); + //qDebug("CoverageMap2::checkMap()... STORED"); return STORED; } else { CoverageRegion::_regionFullSkips++; - //qDebug("CoverageMap2::checkMap()... NOT_STORED\n"); + //qDebug("CoverageMap2::checkMap()... NOT_STORED"); return NOT_STORED; } } else { CoverageRegion::_tooSmallSkips++; - //qDebug("CoverageMap2::checkMap()... NOT_STORED\n"); + //qDebug("CoverageMap2::checkMap()... NOT_STORED"); return NOT_STORED; } } else { - //qDebug("CoverageMap2::checkMap()... NOT_STORED\n"); + //qDebug("CoverageMap2::checkMap()... NOT_STORED"); return NOT_STORED; } } - //qDebug("CoverageMap2::checkMap()... DOESNT_FIT\n"); + //qDebug("CoverageMap2::checkMap()... DOESNT_FIT"); return DOESNT_FIT; } @@ -341,8 +341,8 @@ void CoverageRegion::erase() { /** if (_polygonCount) { - qDebug("CoverageRegion::erase()...\n"); - qDebug("_polygonCount=%d\n",_polygonCount); + qDebug("CoverageRegion::erase()..."); + qDebug("_polygonCount=%d",_polygonCount); _myBoundingBox.printDebugDetails(getRegionName()); //for (int i = 0; i < _polygonCount; i++) { // qDebug("_polygons[%d]=",i); @@ -393,7 +393,7 @@ void CoverageRegion::growPolygonArray() { _polygonDistances = newDistances; _polygonSizes = newSizes; _polygonArraySize = _polygonArraySize + DEFAULT_GROW_SIZE; - //qDebug("CoverageMap::growPolygonArray() _polygonArraySize=%d...\n",_polygonArraySize); + //qDebug("CoverageMap::growPolygonArray() _polygonArraySize=%d...",_polygonArraySize); } const char* CoverageRegion::getRegionName() const { @@ -438,7 +438,7 @@ bool CoverageRegion::mergeItemsInArray(VoxelProjectedPolygon* seed, bool seedInA _totalPolygons--; } - //qDebug("_polygonCount=%d\n",_polygonCount); + //qDebug("_polygonCount=%d",_polygonCount); // clean up if (_managePolygons) { @@ -486,7 +486,7 @@ void CoverageRegion::storeInArray(VoxelProjectedPolygon* polygon) { // insertion point in this array, and shift the array accordingly float area = polygon->getBoundingBox().area(); float reverseArea = 4.0f - area; - //qDebug("store by size area=%f reverse area=%f\n", area, reverseArea); + //qDebug("store by size area=%f reverse area=%f", area, reverseArea); _polygonCount = insertIntoSortedArrays((void*)polygon, reverseArea, IGNORED, (void**)_polygons, _polygonSizes, IGNORED, _polygonCount, _polygonArraySize); @@ -500,10 +500,10 @@ void CoverageRegion::storeInArray(VoxelProjectedPolygon* polygon) { // Debugging and Optimization Tuning code. if (_polygonCount > _maxPolygonsUsed) { _maxPolygonsUsed = _polygonCount; - //qDebug("CoverageRegion new _maxPolygonsUsed reached=%d region=%s\n",_maxPolygonsUsed, getRegionName()); + //qDebug("CoverageRegion new _maxPolygonsUsed reached=%d region=%s",_maxPolygonsUsed, getRegionName()); //_myBoundingBox.printDebugDetails("map._myBoundingBox"); } else { - //qDebug("CoverageRegion::storeInArray() _polygonCount=%d region=%s\n",_polygonCount, getRegionName()); + //qDebug("CoverageRegion::storeInArray() _polygonCount=%d region=%s",_polygonCount, getRegionName()); } } diff --git a/libraries/voxels/src/CoverageMapV2.cpp b/libraries/voxels/src/CoverageMapV2.cpp index 0e382d7f12..9d4e92fd17 100644 --- a/libraries/voxels/src/CoverageMapV2.cpp +++ b/libraries/voxels/src/CoverageMapV2.cpp @@ -61,7 +61,7 @@ CoverageMapV2::CoverageMapV2(BoundingBox boundingBox, bool isRoot, bool isCovere { _mapCount++; init(); - //qDebug("CoverageMapV2 created... _mapCount=%d\n",_mapCount); + //qDebug("CoverageMapV2 created... _mapCount=%d",_mapCount); }; CoverageMapV2::~CoverageMapV2() { @@ -78,11 +78,11 @@ void CoverageMapV2::erase() { } if (_isRoot && wantDebugging) { - qDebug("CoverageMapV2 last to be deleted...\n"); - qDebug("MINIMUM_POLYGON_AREA_TO_STORE=%f\n",MINIMUM_POLYGON_AREA_TO_STORE); - qDebug("_mapCount=%d\n",_mapCount); - qDebug("_checkMapRootCalls=%d\n",_checkMapRootCalls); - qDebug("_notAllInView=%d\n",_notAllInView); + qDebug("CoverageMapV2 last to be deleted..."); + qDebug("MINIMUM_POLYGON_AREA_TO_STORE=%f",MINIMUM_POLYGON_AREA_TO_STORE); + qDebug("_mapCount=%d",_mapCount); + qDebug("_checkMapRootCalls=%d",_checkMapRootCalls); + qDebug("_notAllInView=%d",_notAllInView); _mapCount = 0; _checkMapRootCalls = 0; _notAllInView = 0; diff --git a/libraries/voxels/src/ViewFrustum.cpp b/libraries/voxels/src/ViewFrustum.cpp index c13da815f8..3a871f37b9 100644 --- a/libraries/voxels/src/ViewFrustum.cpp +++ b/libraries/voxels/src/ViewFrustum.cpp @@ -322,40 +322,40 @@ bool ViewFrustum::matches(const ViewFrustum& compareTo, bool debug) const { testMatches(compareTo._eyeOffsetOrientation, _eyeOffsetOrientation); if (!result && debug) { - qDebug("ViewFrustum::matches()... result=%s\n", debug::valueOf(result)); - qDebug("%s -- compareTo._position=%f,%f,%f _position=%f,%f,%f\n", + qDebug("ViewFrustum::matches()... result=%s", debug::valueOf(result)); + qDebug("%s -- compareTo._position=%f,%f,%f _position=%f,%f,%f", (testMatches(compareTo._position,_position) ? "MATCHES " : "NO MATCH"), compareTo._position.x, compareTo._position.y, compareTo._position.z, _position.x, _position.y, _position.z ); - qDebug("%s -- compareTo._direction=%f,%f,%f _direction=%f,%f,%f\n", + qDebug("%s -- compareTo._direction=%f,%f,%f _direction=%f,%f,%f", (testMatches(compareTo._direction, _direction) ? "MATCHES " : "NO MATCH"), compareTo._direction.x, compareTo._direction.y, compareTo._direction.z, _direction.x, _direction.y, _direction.z ); - qDebug("%s -- compareTo._up=%f,%f,%f _up=%f,%f,%f\n", + qDebug("%s -- compareTo._up=%f,%f,%f _up=%f,%f,%f", (testMatches(compareTo._up, _up) ? "MATCHES " : "NO MATCH"), compareTo._up.x, compareTo._up.y, compareTo._up.z, _up.x, _up.y, _up.z ); - qDebug("%s -- compareTo._right=%f,%f,%f _right=%f,%f,%f\n", + qDebug("%s -- compareTo._right=%f,%f,%f _right=%f,%f,%f", (testMatches(compareTo._right, _right) ? "MATCHES " : "NO MATCH"), compareTo._right.x, compareTo._right.y, compareTo._right.z, _right.x, _right.y, _right.z ); - qDebug("%s -- compareTo._fieldOfView=%f _fieldOfView=%f\n", + qDebug("%s -- compareTo._fieldOfView=%f _fieldOfView=%f", (testMatches(compareTo._fieldOfView, _fieldOfView) ? "MATCHES " : "NO MATCH"), compareTo._fieldOfView, _fieldOfView); - qDebug("%s -- compareTo._aspectRatio=%f _aspectRatio=%f\n", + qDebug("%s -- compareTo._aspectRatio=%f _aspectRatio=%f", (testMatches(compareTo._aspectRatio, _aspectRatio) ? "MATCHES " : "NO MATCH"), compareTo._aspectRatio, _aspectRatio); - qDebug("%s -- compareTo._nearClip=%f _nearClip=%f\n", + qDebug("%s -- compareTo._nearClip=%f _nearClip=%f", (testMatches(compareTo._nearClip, _nearClip) ? "MATCHES " : "NO MATCH"), compareTo._nearClip, _nearClip); - qDebug("%s -- compareTo._farClip=%f _farClip=%f\n", + qDebug("%s -- compareTo._farClip=%f _farClip=%f", (testMatches(compareTo._farClip, _farClip) ? "MATCHES " : "NO MATCH"), compareTo._farClip, _farClip); - qDebug("%s -- compareTo._eyeOffsetPosition=%f,%f,%f _eyeOffsetPosition=%f,%f,%f\n", + qDebug("%s -- compareTo._eyeOffsetPosition=%f,%f,%f _eyeOffsetPosition=%f,%f,%f", (testMatches(compareTo._eyeOffsetPosition, _eyeOffsetPosition) ? "MATCHES " : "NO MATCH"), compareTo._eyeOffsetPosition.x, compareTo._eyeOffsetPosition.y, compareTo._eyeOffsetPosition.z, _eyeOffsetPosition.x, _eyeOffsetPosition.y, _eyeOffsetPosition.z); - qDebug("%s -- compareTo._eyeOffsetOrientation=%f,%f,%f,%f _eyeOffsetOrientation=%f,%f,%f,%f\n", + qDebug("%s -- compareTo._eyeOffsetOrientation=%f,%f,%f,%f _eyeOffsetOrientation=%f,%f,%f,%f", (testMatches(compareTo._eyeOffsetOrientation, _eyeOffsetOrientation) ? "MATCHES " : "NO MATCH"), compareTo._eyeOffsetOrientation.x, compareTo._eyeOffsetOrientation.y, compareTo._eyeOffsetOrientation.z, compareTo._eyeOffsetOrientation.w, @@ -418,17 +418,17 @@ void ViewFrustum::computeOffAxisFrustum(float& left, float& right, float& bottom } void ViewFrustum::printDebugDetails() const { - qDebug("ViewFrustum::printDebugDetails()... \n"); - qDebug("_position=%f,%f,%f\n", _position.x, _position.y, _position.z ); - qDebug("_direction=%f,%f,%f\n", _direction.x, _direction.y, _direction.z ); - qDebug("_up=%f,%f,%f\n", _up.x, _up.y, _up.z ); - qDebug("_right=%f,%f,%f\n", _right.x, _right.y, _right.z ); - qDebug("_fieldOfView=%f\n", _fieldOfView); - qDebug("_aspectRatio=%f\n", _aspectRatio); - qDebug("_nearClip=%f\n", _nearClip); - qDebug("_farClip=%f\n", _farClip); - qDebug("_eyeOffsetPosition=%f,%f,%f\n", _eyeOffsetPosition.x, _eyeOffsetPosition.y, _eyeOffsetPosition.z ); - qDebug("_eyeOffsetOrientation=%f,%f,%f,%f\n", _eyeOffsetOrientation.x, _eyeOffsetOrientation.y, _eyeOffsetOrientation.z, + qDebug("ViewFrustum::printDebugDetails()... "); + qDebug("_position=%f,%f,%f", _position.x, _position.y, _position.z ); + qDebug("_direction=%f,%f,%f", _direction.x, _direction.y, _direction.z ); + qDebug("_up=%f,%f,%f", _up.x, _up.y, _up.z ); + qDebug("_right=%f,%f,%f", _right.x, _right.y, _right.z ); + qDebug("_fieldOfView=%f", _fieldOfView); + qDebug("_aspectRatio=%f", _aspectRatio); + qDebug("_nearClip=%f", _nearClip); + qDebug("_farClip=%f", _farClip); + qDebug("_eyeOffsetPosition=%f,%f,%f", _eyeOffsetPosition.x, _eyeOffsetPosition.y, _eyeOffsetPosition.z ); + qDebug("_eyeOffsetOrientation=%f,%f,%f,%f", _eyeOffsetOrientation.x, _eyeOffsetOrientation.y, _eyeOffsetOrientation.z, _eyeOffsetOrientation.w ); } diff --git a/libraries/voxels/src/VoxelNode.cpp b/libraries/voxels/src/VoxelNode.cpp index 76fae500dd..e94c9756d9 100644 --- a/libraries/voxels/src/VoxelNode.cpp +++ b/libraries/voxels/src/VoxelNode.cpp @@ -259,7 +259,7 @@ bool VoxelNode::collapseIdenticalLeaves() { // if no child, child isn't a leaf, or child doesn't have a color if (!_children[i] || _children[i]->isStagedForDeletion() || !_children[i]->isLeaf() || !_children[i]->isColored()) { allChildrenMatch=false; - //qDebug("SADNESS child missing or not colored! i=%d\n",i); + //qDebug("SADNESS child missing or not colored! i=%d",i); break; } else { if (i==0) { @@ -276,7 +276,7 @@ bool VoxelNode::collapseIdenticalLeaves() { if (allChildrenMatch) { - //qDebug("allChildrenMatch: pruning tree\n"); + //qDebug("allChildrenMatch: pruning tree"); for (int i = 0; i < NUMBER_OF_CHILDREN; i++) { delete _children[i]; // delete all the child nodes _children[i]=NULL; // set it to NULL @@ -310,13 +310,13 @@ void VoxelNode::printDebugDetails(const char* label) const { } } - qDebug("%s - Voxel at corner=(%f,%f,%f) size=%f\n isLeaf=%s isColored=%s (%d,%d,%d,%d) isDirty=%s shouldRender=%s\n children=", label, + qDebug("%s - Voxel at corner=(%f,%f,%f) size=%f\n isLeaf=%s isColored=%s (%d,%d,%d,%d) isDirty=%s shouldRender=%s children=", label, _box.getCorner().x, _box.getCorner().y, _box.getCorner().z, _box.getSize().x, debug::valueOf(isLeaf()), debug::valueOf(isColored()), getColor()[0], getColor()[1], getColor()[2], getColor()[3], debug::valueOf(isDirty()), debug::valueOf(getShouldRender())); outputBits(childBits, false); - qDebug("\n octalCode="); + qDebug(" octalCode="); printOctalCode(_octalCode); } diff --git a/libraries/voxels/src/VoxelProjectedPolygon.cpp b/libraries/voxels/src/VoxelProjectedPolygon.cpp index 8a39d7f358..71f43a0c04 100644 --- a/libraries/voxels/src/VoxelProjectedPolygon.cpp +++ b/libraries/voxels/src/VoxelProjectedPolygon.cpp @@ -95,7 +95,7 @@ void BoundingBox::printDebugDetails(const char* label) const { } else { qDebug("BoundingBox"); } - qDebug("\n _set=%s\n corner=%f,%f size=%f,%f\n bounds=[(%f,%f) to (%f,%f)]\n", + qDebug("\n _set=%s\n corner=%f,%f size=%f,%f\n bounds=[(%f,%f) to (%f,%f)]", debug::valueOf(_set), corner.x, corner.y, size.x, size.y, corner.x, corner.y, corner.x+size.x, corner.y+size.y); } diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index 803bea8038..62191bad2b 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -157,7 +157,7 @@ void VoxelTree::recurseNodeWithOperationDistanceSorted(VoxelNode* node, RecurseV if (childNode) { // chance to optimize, doesn't need to be actual distance!! Could be distance squared float distanceSquared = childNode->distanceSquareToPoint(point); - //qDebug("recurseNodeWithOperationDistanceSorted() CHECKING child[%d] point=%f,%f center=%f,%f distance=%f...\n", i, point.x, point.y, center.x, center.y, distance); + //qDebug("recurseNodeWithOperationDistanceSorted() CHECKING child[%d] point=%f,%f center=%f,%f distance=%f...", i, point.x, point.y, center.x, center.y, distance); //childNode->printDebugDetails(""); currentCount = insertIntoSortedArrays((void*)childNode, distanceSquared, i, (void**)&sortedChildren, (float*)&distancesToChildren, @@ -168,7 +168,7 @@ void VoxelTree::recurseNodeWithOperationDistanceSorted(VoxelNode* node, RecurseV for (int i = 0; i < currentCount; i++) { VoxelNode* childNode = sortedChildren[i]; if (childNode) { - //qDebug("recurseNodeWithOperationDistanceSorted() PROCESSING child[%d] distance=%f...\n", i, distancesToChildren[i]); + //qDebug("recurseNodeWithOperationDistanceSorted() PROCESSING child[%d] distance=%f...", i, distancesToChildren[i]); //childNode->printDebugDetails(""); recurseNodeWithOperationDistanceSorted(childNode, operation, point, extraData); } @@ -460,7 +460,7 @@ void VoxelTree::deleteVoxelCodeFromTreeRecursion(VoxelNode* node, void* extraDat // isn't a colored leaf, and the child branch doesn't exist, so there's nothing to do below and // we can safely return, ending the recursion and unwinding if (!childNode) { - //qDebug("new___deleteVoxelCodeFromTree() child branch doesn't exist, but parent is not a leaf, just unwind\n"); + //qDebug("new___deleteVoxelCodeFromTree() child branch doesn't exist, but parent is not a leaf, just unwind"); return; } @@ -548,7 +548,7 @@ void VoxelTree::readCodeColorBufferToTreeRecursion(VoxelNode* node, void* extraD } } else { if (!node->isLeaf()) { - qDebug("WARNING! operation would require deleting children, add Voxel ignored!\n "); + qDebug("WARNING! operation would require deleting children, add Voxel ignored! "); } } @@ -688,7 +688,7 @@ void VoxelTree::loadVoxelsFile(const char* fileName, bool wantColorRandomizer) { int totalBytesRead = 0; if(file.is_open()) { - qDebug("loading file...\n"); + qDebug("loading file..."); bool bail = false; while (!file.eof() && !bail) { file.get(octets); @@ -713,14 +713,14 @@ void VoxelTree::loadVoxelsFile(const char* fileName, bool wantColorRandomizer) { file.get(colorRead); blue = (unsigned char)colorRead; - qDebug("voxel color from file red:%d, green:%d, blue:%d \n",red,green,blue); + qDebug("voxel color from file red:%d, green:%d, blue:%d ",red,green,blue); vCount++; int colorRandomizer = wantColorRandomizer ? randIntInRange (-5, 5) : 0; voxelData[lengthInBytes+1] = std::max(0,std::min(255,red + colorRandomizer)); voxelData[lengthInBytes+2] = std::max(0,std::min(255,green + colorRandomizer)); voxelData[lengthInBytes+3] = std::max(0,std::min(255,blue + colorRandomizer)); - qDebug("voxel color after rand red:%d, green:%d, blue:%d\n", + qDebug("voxel color after rand red:%d, green:%d, blue:%d", voxelData[lengthInBytes+1], voxelData[lengthInBytes+2], voxelData[lengthInBytes+3]); //printVoxelCode(voxelData); @@ -821,7 +821,7 @@ void VoxelTree::createSphere(float radius, float xc, float yc, float zc, float v if (debug) { int percentComplete = 100 * (thisRadius/radius); - qDebug("percentComplete=%d\n",percentComplete); + qDebug("percentComplete=%d",percentComplete); } for (float theta=0.0; theta <= 2 * M_PI; theta += angleDelta) { @@ -837,7 +837,7 @@ void VoxelTree::createSphere(float radius, float xc, float yc, float zc, float v // 2) In all modes, we will use our "outer" color to draw the voxels. Otherwise we will use the average color if (lastLayer) { if (false && debug) { - qDebug("adding candy shell: theta=%f phi=%f thisRadius=%f radius=%f\n", + qDebug("adding candy shell: theta=%f phi=%f thisRadius=%f radius=%f", theta, phi, thisRadius,radius); } switch (mode) { @@ -861,7 +861,7 @@ void VoxelTree::createSphere(float radius, float xc, float yc, float zc, float v green = (unsigned char)std::min(255, std::max(0, (int)(g1 + ((g2 - g1) * gradient)))); blue = (unsigned char)std::min(255, std::max(0, (int)(b1 + ((b2 - b1) * gradient)))); if (debug) { - qDebug("perlin=%f gradient=%f color=(%d,%d,%d)\n",perlin, gradient, red, green, blue); + qDebug("perlin=%f gradient=%f color=(%d,%d,%d)",perlin, gradient, red, green, blue); } } break; } @@ -1178,7 +1178,7 @@ int VoxelTree::encodeTreeBitstreamRecursion(VoxelNode* node, unsigned char* outp if (childNode) { // chance to optimize, doesn't need to be actual distance!! Could be distance squared //float distanceSquared = childNode->distanceSquareToPoint(point); - //qDebug("recurseNodeWithOperationDistanceSorted() CHECKING child[%d] point=%f,%f center=%f,%f distance=%f...\n", i, point.x, point.y, center.x, center.y, distance); + //qDebug("recurseNodeWithOperationDistanceSorted() CHECKING child[%d] point=%f,%f center=%f,%f distance=%f...", i, point.x, point.y, center.x, center.y, distance); //childNode->printDebugDetails(""); float distance = params.viewFrustum ? childNode->distanceToCamera(*params.viewFrustum) : 0; @@ -1434,7 +1434,7 @@ int VoxelTree::encodeTreeBitstreamRecursion(VoxelNode* node, unsigned char* outp bool VoxelTree::readFromSVOFile(const char* fileName) { std::ifstream file(fileName, std::ios::in|std::ios::binary|std::ios::ate); if(file.is_open()) { - qDebug("loading file %s...\n", fileName); + qDebug("loading file %s...", fileName); // get file length.... unsigned long fileLength = file.tellg(); @@ -1462,14 +1462,14 @@ bool VoxelTree::readFromSchematicFile(const char *fileName) { std::stringstream ss; int err = retrieveData(fileName, ss); if (err && ss.get() != TAG_Compound) { - qDebug("[ERROR] Invalid schematic file.\n"); + qDebug("[ERROR] Invalid schematic file."); return false; } ss.get(); TagCompound schematics(ss); if (!schematics.getBlocksId() || !schematics.getBlocksData()) { - qDebug("[ERROR] Invalid schematic file.\n"); + qDebug("[ERROR] Invalid schematic file."); return false; } @@ -1532,7 +1532,7 @@ bool VoxelTree::readFromSchematicFile(const char *fileName) { } } - qDebug("Created %d voxels from minecraft import.\n", count); + qDebug("Created %d voxels from minecraft import.", count); return true; } @@ -1542,7 +1542,7 @@ void VoxelTree::writeToSVOFile(const char* fileName, VoxelNode* node) const { std::ofstream file(fileName, std::ios::out|std::ios::binary); if(file.is_open()) { - qDebug("saving to file %s...\n", fileName); + qDebug("saving to file %s...", fileName); VoxelNodeBag nodeBag; // If we were given a specific node, start from there, otherwise start from root From 51d1e6ae80a38d559d0944f162c53b9830bdb1f4 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 16 Jul 2013 11:50:40 -0700 Subject: [PATCH 26/81] add a message handler to send messages over to LogDisplay --- interface/src/Application.cpp | 7 +++++++ interface/src/LogDisplay.cpp | 4 ++-- interface/src/LogDisplay.h | 4 ++-- libraries/shared/src/NodeList.cpp | 8 ++++---- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index a32832318a..d537f9b8c1 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -164,6 +164,11 @@ void GLCanvas::wheelEvent(QWheelEvent* event) { Application::getInstance()->wheelEvent(event); } +void messageHandler(QtMsgType type, const char* message) { + printf("%s\n", message); + LogDisplay::instance.addMessage(message); +} + Application::Application(int& argc, char** argv, timeval &startup_time) : QApplication(argc, argv), _window(new QMainWindow(desktop())), @@ -212,6 +217,8 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : _window->setWindowTitle("Interface"); qDebug("Interface Startup:"); + qInstallMsgHandler(messageHandler); + unsigned int listenPort = 0; // bind to an ephemeral port by default const char** constArgv = const_cast(argv); const char* portStr = getCmdOption(argc, constArgv, "--listenPort"); diff --git a/interface/src/LogDisplay.cpp b/interface/src/LogDisplay.cpp index 708bb192d3..247ea4beb5 100644 --- a/interface/src/LogDisplay.cpp +++ b/interface/src/LogDisplay.cpp @@ -15,7 +15,7 @@ #include "Util.h" using namespace std; -FILE* const LogDisplay::DEFAULT_STREAM = stdout; +FILE* const LogDisplay::DEFAULT_STREAM = 0l; // // Singleton constructor @@ -88,7 +88,7 @@ void LogDisplay::setCharacterSize(unsigned width, unsigned height) { // Logging // -inline void LogDisplay::addMessage(char const* ptr) { +void LogDisplay::addMessage(const char* ptr) { pthread_mutex_lock(& _mutex); diff --git a/interface/src/LogDisplay.h b/interface/src/LogDisplay.h index bb74872dbd..6f90df3724 100644 --- a/interface/src/LogDisplay.h +++ b/interface/src/LogDisplay.h @@ -21,8 +21,8 @@ public: void render(unsigned screenWidth, unsigned screenHeight); - // log formatted message - inline void addMessage(char const*); + // log formatted message + void addMessage(const char* message); // settings diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 0781d8ed1b..87a3f5f70b 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -43,7 +43,7 @@ NodeList* NodeList::createInstance(char ownerType, unsigned int socketListenPort if (!_sharedInstance) { _sharedInstance = new NodeList(ownerType, socketListenPort); } else { - qDebug("NodeList createInstance called with existing instance."); + qDebug("NodeList createInstance called with existing instance.\n"); } return _sharedInstance; @@ -51,7 +51,7 @@ NodeList* NodeList::createInstance(char ownerType, unsigned int socketListenPort NodeList* NodeList::getInstance() { if (!_sharedInstance) { - qDebug("NodeList getInstance called before call to createInstance. Returning NULL pointer."); + qDebug("NodeList getInstance called before call to createInstance. Returning NULL pointer.\n"); } return _sharedInstance; @@ -275,9 +275,9 @@ void NodeList::sendDomainServerCheckIn() { sockaddr_in tempAddress; memcpy(&tempAddress.sin_addr, pHostInfo->h_addr_list[0], pHostInfo->h_length); strcpy(_domainIP, inet_ntoa(tempAddress.sin_addr)); - qDebug("Domain Server: %s ", _domainHostname); + qDebug("Domain Server: %s", _domainHostname); } else { - qDebug("Failed domain server lookup"); + qDebug("Failed domain server lookup\n"); } } else if (!printedDomainServerIP) { qDebug("Domain Server IP: %s", _domainIP); From 063094f96c8c8f36bea2512a8f04e2ec379e832d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 16 Jul 2013 12:00:14 -0700 Subject: [PATCH 27/81] correctly break on end of qDebug message in LogDisplay --- interface/src/LogDisplay.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/interface/src/LogDisplay.cpp b/interface/src/LogDisplay.cpp index 247ea4beb5..49e4886b00 100644 --- a/interface/src/LogDisplay.cpp +++ b/interface/src/LogDisplay.cpp @@ -97,8 +97,9 @@ void LogDisplay::addMessage(const char* ptr) { fprintf(_stream, "%s", ptr); } - while (*ptr != '\0') { + while (true) { // process the characters + bool isEndOfMessage = (*ptr == '\0'); char c = *ptr++; if (c == '\t') { @@ -150,6 +151,10 @@ void LogDisplay::addMessage(const char* ptr) { _writeLineStartPos = _writePos; _writtenInLine = 0; } + + if (isEndOfMessage) { + break; + } } pthread_mutex_unlock(& _mutex); From 8626c95a20e14e585f7710767a599ef050670f06 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Jul 2013 12:01:09 -0700 Subject: [PATCH 28/81] whitespace fix --- libraries/voxels/src/VoxelNode.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/voxels/src/VoxelNode.h b/libraries/voxels/src/VoxelNode.h index 131371c02b..461a723a8a 100644 --- a/libraries/voxels/src/VoxelNode.h +++ b/libraries/voxels/src/VoxelNode.h @@ -41,7 +41,7 @@ private: void calculateAABox(); void init(unsigned char * octalCode); - + public: VoxelNode(); // root node constructor VoxelNode(unsigned char * octalCode); // regular constructor From 13762da7d822a63dfe28d25b9fd5345a24aa5bb2 Mon Sep 17 00:00:00 2001 From: atlante45 Date: Tue, 16 Jul 2013 12:03:07 -0700 Subject: [PATCH 29/81] Changed shortcuts to ALT+ +/- --- interface/src/Application.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 644d5524f0..67763ae3bf 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1669,8 +1669,8 @@ void Application::initMenu() { "First Person", this, SLOT(setRenderFirstPerson(bool)), Qt::Key_P))->setCheckable(true); (_manualThirdPerson = renderMenu->addAction( "Third Person", this, SLOT(setRenderThirdPerson(bool))))->setCheckable(true); - renderMenu->addAction("Increase Avatar Size", this, SLOT(increaseAvatarSize()), Qt::SHIFT | Qt::Key_Plus); - renderMenu->addAction("Decrease Avatar Size", this, SLOT(decreaseAvatarSize()), Qt::SHIFT | Qt::Key_Minus); + renderMenu->addAction("Increase Avatar Size", this, SLOT(increaseAvatarSize()), Qt::ALT | Qt::Key_Plus); + renderMenu->addAction("Decrease Avatar Size", this, SLOT(decreaseAvatarSize()), Qt::ALT | Qt::Key_Minus); QMenu* toolsMenu = menuBar->addMenu("Tools"); From f713bb961db2fbb1f34cd1ee2416fb447705abcf Mon Sep 17 00:00:00 2001 From: atlante45 Date: Tue, 16 Jul 2013 12:04:22 -0700 Subject: [PATCH 30/81] Adapt avatar message size to the avatars --- interface/src/Avatar.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/Avatar.cpp b/interface/src/Avatar.cpp index a1175e3b23..d67a2ffdb9 100755 --- a/interface/src/Avatar.cpp +++ b/interface/src/Avatar.cpp @@ -1047,7 +1047,7 @@ void Avatar::render(bool lookingInMirror, bool renderAvatarBalls) { } glPushMatrix(); - glm::vec3 chatPosition = _bodyBall[BODY_BALL_HEAD_BASE].position + getBodyUpDirection() * chatMessageHeight; + glm::vec3 chatPosition = _bodyBall[BODY_BALL_HEAD_BASE].position + getBodyUpDirection() * chatMessageHeight * _scale; glTranslatef(chatPosition.x, chatPosition.y, chatPosition.z); glm::quat chatRotation = Application::getInstance()->getCamera()->getRotation(); glm::vec3 chatAxis = glm::axis(chatRotation); @@ -1057,7 +1057,7 @@ void Avatar::render(bool lookingInMirror, bool renderAvatarBalls) { glColor3f(0, 0.8, 0); glRotatef(180, 0, 1, 0); glRotatef(180, 0, 0, 1); - glScalef(chatMessageScale, chatMessageScale, 1.0f); + glScalef(_scale * chatMessageScale, _scale * chatMessageScale, 1.0f); glDisable(GL_LIGHTING); glDepthMask(false); From 1b48d4f0fc414ea94611a01cf0948db4c44621d6 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 16 Jul 2013 12:46:32 -0700 Subject: [PATCH 31/81] revert removal of extraneous newlines --- interface/src/Application.cpp | 26 +++---- interface/src/Audio.cpp | 44 ++++++------ interface/src/AvatarVoxelSystem.cpp | 4 +- interface/src/SerialInterface.cpp | 6 +- interface/src/Transmitter.cpp | 6 +- interface/src/Util.cpp | 14 ++-- interface/src/VoxelSystem.cpp | 46 ++++++------ interface/src/Webcam.cpp | 20 +++--- interface/src/main.cpp | 4 +- interface/src/starfield/Loader.h | 10 +-- libraries/shared/src/NodeList.cpp | 7 +- libraries/shared/src/OctalCode.cpp | 4 +- libraries/shared/src/PacketHeaders.cpp | 2 +- libraries/shared/src/PerfStat.cpp | 8 +-- libraries/shared/src/SharedUtil.cpp | 14 ++-- libraries/shared/src/UDPSocket.cpp | 8 +-- libraries/voxels/src/CoverageMap.cpp | 72 +++++++++---------- libraries/voxels/src/CoverageMapV2.cpp | 12 ++-- libraries/voxels/src/ViewFrustum.cpp | 44 ++++++------ libraries/voxels/src/VoxelNode.cpp | 8 +-- .../voxels/src/VoxelProjectedPolygon.cpp | 2 +- libraries/voxels/src/VoxelTree.cpp | 32 ++++----- 22 files changed, 197 insertions(+), 196 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index d537f9b8c1..e5455eb604 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -215,7 +215,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : { _applicationStartupTime = startup_time; _window->setWindowTitle("Interface"); - qDebug("Interface Startup:"); + qDebug("Interface Startup:\n"); qInstallMsgHandler(messageHandler); @@ -240,7 +240,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : // Handle Local Domain testing with the --local command line if (cmdOptionExists(argc, constArgv, "--local")) { - qDebug("Local Domain MODE!"); + qDebug("Local Domain MODE!\n"); NodeList::getInstance()->setDomainIPToLocalhost(); } @@ -304,7 +304,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : } void Application::initializeGL() { - qDebug( "Created Display Window." ); + qDebug( "Created Display Window.\n" ); // initialize glut for shape drawing; Qt apparently initializes it on OS X #ifndef __APPLE__ @@ -319,10 +319,10 @@ void Application::initializeGL() { _viewFrustumOffsetCamera.setFarClip(500.0 * TREE_SCALE); initDisplay(); - qDebug( "Initialized Display." ); + qDebug( "Initialized Display.\n" ); init(); - qDebug( "Init() complete." ); + qDebug( "Init() complete.\n" ); // Check to see if the user passed in a command line option for randomizing colors bool wantColorRandomizer = !arguments().contains("--NoColorRandomizer"); @@ -331,13 +331,13 @@ void Application::initializeGL() { // Voxel File. If so, load it now. if (!_voxelsFilename.isEmpty()) { _voxels.loadVoxelsFile(_voxelsFilename.constData(), wantColorRandomizer); - qDebug("Local Voxel File loaded."); + qDebug("Local Voxel File loaded.\n"); } // create thread for receipt of data via UDP if (_enableNetworkThread) { pthread_create(&_networkReceiveThread, NULL, networkReceive, NULL); - qDebug("Network receive thread created."); + qDebug("Network receive thread created.\n"); } // call terminate before exiting @@ -358,7 +358,7 @@ void Application::initializeGL() { float startupTime = (usecTimestampNow() - usecTimestamp(&_applicationStartupTime)) / 1000000.0; _justStarted = false; char title[50]; - sprintf(title, "Interface: %4.2f seconds", startupTime); + sprintf(title, "Interface: %4.2f seconds\n", startupTime); qDebug("%s", title); _window->setWindowTitle(title); @@ -1453,7 +1453,7 @@ void Application::importVoxels() { if (fileNameString.endsWith(".png", Qt::CaseInsensitive)) { QImage pngImage = QImage(fileName); if (pngImage.height() != pngImage.width()) { - qDebug("ERROR: Bad PNG size: height != width."); + qDebug("ERROR: Bad PNG size: height != width.\n"); return; } @@ -1765,7 +1765,7 @@ void Application::init() { _audio.setJitterBufferSamples(_audioJitterBufferSamples); } - qDebug("Loaded settings."); + qDebug("Loaded settings.\n"); sendAvatarVoxelURLMessage(_myAvatar.getVoxels()->getVoxelURL()); @@ -2778,7 +2778,7 @@ glm::vec2 Application::getScaledScreenPoint(glm::vec2 projectedPoint) { // render the coverage map on screen void Application::renderCoverageMapV2() { - //qDebug("renderCoverageMap()"); + //qDebug("renderCoverageMap()\n"); glDisable(GL_LIGHTING); glLineWidth(2.0); @@ -2823,7 +2823,7 @@ void Application::renderCoverageMapsV2Recursively(CoverageMapV2* map) { // render the coverage map on screen void Application::renderCoverageMap() { - //qDebug("renderCoverageMap()"); + //qDebug("renderCoverageMap()\n"); glDisable(GL_LIGHTING); glLineWidth(2.0); @@ -3154,7 +3154,7 @@ void Application::eyedropperVoxelUnderCursor() { } void Application::goHome() { - qDebug("Going Home!"); + qDebug("Going Home!\n"); _myAvatar.setPosition(START_LOCATION); } diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 4bacc274ad..4c707de938 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -152,11 +152,11 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o // If not enough audio has arrived to start playback, keep waiting // #ifdef SHOW_AUDIO_DEBUG - qDebug("%i,%i,%i,%i", - _packetsReceivedThisPlayback, - ringBuffer->diffLastWriteNextOutput(), - PACKET_LENGTH_SAMPLES, - _jitterBufferSamples); + qDebug("%i,%i,%i,%i\n", + _packetsReceivedThisPlayback, + ringBuffer->diffLastWriteNextOutput(), + PACKET_LENGTH_SAMPLES, + _jitterBufferSamples); #endif } else if (ringBuffer->isStarted() && ringBuffer->diffLastWriteNextOutput() == 0) { // @@ -169,7 +169,7 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o _packetsReceivedThisPlayback = 0; _wasStarved = 10; // Frames for which to render the indication that the system was starved. #ifdef SHOW_AUDIO_DEBUG - qDebug("Starved, remaining samples = %d", + qDebug("Starved, remaining samples = %d\n", ringBuffer->diffLastWriteNextOutput()); #endif @@ -180,10 +180,10 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o if (!ringBuffer->isStarted()) { ringBuffer->setStarted(true); #ifdef SHOW_AUDIO_DEBUG - qDebug("starting playback %0.1f msecs delayed, jitter = %d, pkts recvd: %d", - (usecTimestampNow() - usecTimestamp(&_firstPacketReceivedTime))/1000.0, - _jitterBufferSamples, - _packetsReceivedThisPlayback); + qDebug("starting playback %0.1f msecs delayed, jitter = %d, pkts recvd: %d \n", + (usecTimestampNow() - usecTimestamp(&_firstPacketReceivedTime))/1000.0, + _jitterBufferSamples, + _packetsReceivedThisPlayback); #endif } @@ -300,8 +300,8 @@ int Audio::audioCallback (const void* inputBuffer, static void outputPortAudioError(PaError error) { if (error != paNoError) { - qDebug("-- portaudio termination error --"); - qDebug("PortAudio error (%d): %s", error, Pa_GetErrorText(error)); + qDebug("-- portaudio termination error --\n"); + qDebug("PortAudio error (%d): %s\n", error, Pa_GetErrorText(error)); } } @@ -350,7 +350,7 @@ Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples) : outputParameters.device = Pa_GetDefaultOutputDevice(); if (inputParameters.device == -1 || outputParameters.device == -1) { - qDebug("Audio: Missing device."); + qDebug("Audio: Missing device.\n"); outputPortAudioError(Pa_Terminate()); return; } @@ -385,12 +385,12 @@ Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples) : outputPortAudioError(Pa_StartStream(_stream)); // Uncomment these lines to see the system-reported latency - //qDebug("Default low input, output latency (secs): %0.4f, %0.4f", + //qDebug("Default low input, output latency (secs): %0.4f, %0.4f\n", // Pa_GetDeviceInfo(Pa_GetDefaultInputDevice())->defaultLowInputLatency, // Pa_GetDeviceInfo(Pa_GetDefaultOutputDevice())->defaultLowOutputLatency); const PaStreamInfo* streamInfo = Pa_GetStreamInfo(_stream); - qDebug("Started audio with reported latency msecs In/Out: %.0f, %.0f", streamInfo->inputLatency * 1000.f, + qDebug("Started audio with reported latency msecs In/Out: %.0f, %.0f\n", streamInfo->inputLatency * 1000.f, streamInfo->outputLatency * 1000.f); gettimeofday(&_lastReceiveTime, NULL); @@ -651,7 +651,7 @@ inline void Audio::eventuallySendRecvPing(int16_t* inputLeft, int16_t* outputLef // As of the next frame, we'll be recoding PING_FRAMES_TO_RECORD from // the mic (pointless to start now as we can't record unsent audio). _isSendingEchoPing = false; - qDebug("Send audio ping"); + qDebug("Send audio ping\n"); } else if (_pingFramesToRecord > 0) { @@ -665,7 +665,7 @@ inline void Audio::eventuallySendRecvPing(int16_t* inputLeft, int16_t* outputLef if (_pingFramesToRecord == 0) { _pingAnalysisPending = true; - qDebug("Received ping echo"); + qDebug("Received ping echo\n"); } } } @@ -689,25 +689,25 @@ inline void Audio::analyzePing() { // Determine extrema int botAt = findExtremum(_echoSamplesLeft, PING_SAMPLES_TO_ANALYZE, -1); if (botAt == -1) { - qDebug("Audio Ping: Minimum not found."); + qDebug("Audio Ping: Minimum not found.\n"); return; } int topAt = findExtremum(_echoSamplesLeft, PING_SAMPLES_TO_ANALYZE, 1); if (topAt == -1) { - qDebug("Audio Ping: Maximum not found."); + qDebug("Audio Ping: Maximum not found.\n"); return; } // Determine peak amplitude - warn if low int ampli = (_echoSamplesLeft[topAt] - _echoSamplesLeft[botAt]) / 2; if (ampli < PING_MIN_AMPLI) { - qDebug("Audio Ping unreliable - low amplitude %d.", ampli); + qDebug("Audio Ping unreliable - low amplitude %d.\n", ampli); } // Determine period - warn if doesn't look like our signal int halfPeriod = abs(topAt - botAt); if (abs(halfPeriod-PING_HALF_PERIOD) > PING_MAX_PERIOD_DIFFERENCE) { - qDebug("Audio Ping unreliable - peak distance %d vs. %d", halfPeriod, PING_HALF_PERIOD); + qDebug("Audio Ping unreliable - peak distance %d vs. %d\n", halfPeriod, PING_HALF_PERIOD); } // Ping is sent: @@ -748,7 +748,7 @@ inline void Audio::analyzePing() { int delay = (botAt + topAt) / 2 + PING_PERIOD; - qDebug("\n| Audio Ping results:\n+----- ---- --- - - - - -\n" + qDebug("\n| Audio Ping results:\n+----- ---- --- - - - - -\n\n" "Delay = %d samples (%d ms)\nPeak amplitude = %d\n\n", delay, (delay * 1000) / int(SAMPLE_RATE), ampli); } diff --git a/interface/src/AvatarVoxelSystem.cpp b/interface/src/AvatarVoxelSystem.cpp index a341ecaa38..c85ea1a343 100644 --- a/interface/src/AvatarVoxelSystem.cpp +++ b/interface/src/AvatarVoxelSystem.cpp @@ -93,7 +93,7 @@ const Mode MODES[] = { void AvatarVoxelSystem::cycleMode() { _mode = (_mode + 1) % (sizeof(MODES) / sizeof(MODES[0])); - qDebug("Voxeltar bind mode %d.", _mode); + qDebug("Voxeltar bind mode %d.\n", _mode); // rebind QUrl url = _voxelURL; @@ -255,7 +255,7 @@ void AvatarVoxelSystem::handleVoxelDownloadProgress(qint64 bytesReceived, qint64 } void AvatarVoxelSystem::handleVoxelReplyError() { - qDebug("%s", _voxelReply->errorString().toAscii().constData()); + qDebug("%s\n", _voxelReply->errorString().toAscii().constData()); _voxelReply->disconnect(this); _voxelReply->deleteLater(); diff --git a/interface/src/SerialInterface.cpp b/interface/src/SerialInterface.cpp index e17feb48d7..0f90ee8dd7 100644 --- a/interface/src/SerialInterface.cpp +++ b/interface/src/SerialInterface.cpp @@ -100,7 +100,7 @@ void SerialInterface::initializePort(char* portname) { qDebug("Opening SerialUSB %s: ", portname); if (_serialDescriptor == -1) { - qDebug("Failed."); + qDebug("Failed.\n"); return; } @@ -134,7 +134,7 @@ void SerialInterface::initializePort(char* portname) { mpu_set_sensors(INV_XYZ_GYRO | INV_XYZ_ACCEL | INV_XYZ_COMPASS); } - qDebug("Connected."); + qDebug("Connected.\n"); resetSerial(); _active = true; @@ -373,7 +373,7 @@ void SerialInterface::readData(float deltaTime) { gettimeofday(&now, NULL); if (diffclock(&lastGoodRead, &now) > NO_READ_MAXIMUM_MSECS) { - qDebug("No data - Shutting down SerialInterface."); + qDebug("No data - Shutting down SerialInterface.\n"); resetSerial(); } } else { diff --git a/interface/src/Transmitter.cpp b/interface/src/Transmitter.cpp index ce0180e501..eac769ead7 100644 --- a/interface/src/Transmitter.cpp +++ b/interface/src/Transmitter.cpp @@ -38,7 +38,7 @@ void Transmitter::checkForLostTransmitter() { int msecsSinceLast = diffclock(_lastReceivedPacket, &now); if (msecsSinceLast > TIME_TO_ASSUME_LOST_MSECS) { resetLevels(); - qDebug("Transmitter signal lost."); + qDebug("Transmitter signal lost.\n"); } } } @@ -93,12 +93,12 @@ void Transmitter::processIncomingData(unsigned char* packetData, int numBytes) { _estimatedRotation.y *= (1.f - DECAY_RATE * DELTA_TIME); if (!_isConnected) { - qDebug("Transmitter Connected."); + qDebug("Transmitter Connected.\n"); _isConnected = true; _estimatedRotation *= 0.0; } } else { - qDebug("Transmitter packet read error, %d bytes.", numBytes); + qDebug("Transmitter packet read error, %d bytes.\n", numBytes); } } diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 7bc4e50d96..20f33f924a 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -451,7 +451,7 @@ void renderOrientationDirections(glm::vec3 position, const glm::quat& orientatio bool closeEnoughForGovernmentWork(float a, float b) { float distance = std::abs(a-b); - //qDebug("closeEnoughForGovernmentWork() a=%1.10f b=%1.10f distance=%1.10f",a,b,distance); + //qDebug("closeEnoughForGovernmentWork() a=%1.10f b=%1.10f distance=%1.10f\n",a,b,distance); return (distance < 0.00001f); } @@ -469,7 +469,7 @@ void runTimingTests() { gettimeofday(&endTime, NULL); } elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("gettimeofday() usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("gettimeofday() usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); // Random number generation gettimeofday(&startTime, NULL); @@ -478,7 +478,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("rand() stored in array usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("rand() stored in array usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); // Random number generation using randFloat() gettimeofday(&startTime, NULL); @@ -487,7 +487,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("randFloat() stored in array usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("randFloat() stored in array usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); // PowF function fTest = 1145323.2342f; @@ -497,7 +497,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("powf(f, 0.5) usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("powf(f, 0.5) usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); // Vector Math float distance; @@ -510,7 +510,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("vector math usecs: %f [%f msecs total for %d tests]", + qDebug("vector math usecs: %f [%f msecs total for %d tests]\n", 1000.0f * elapsedMsecs / (float) numTests, elapsedMsecs, numTests); // Vec3 test @@ -524,7 +524,7 @@ void runTimingTests() { } gettimeofday(&endTime, NULL); elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("vec3 assign and dot() usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); + qDebug("vec3 assign and dot() usecs: %f\n", 1000.0f * elapsedMsecs / (float) numTests); } diff --git a/interface/src/VoxelSystem.cpp b/interface/src/VoxelSystem.cpp index 0b4777a12f..f219e38dc6 100644 --- a/interface/src/VoxelSystem.cpp +++ b/interface/src/VoxelSystem.cpp @@ -144,16 +144,16 @@ int VoxelSystem::parseData(unsigned char* sourceBuffer, int numBytes) { int commandLength = strlen(command); // commands are null terminated strings int totalLength = 1+commandLength+1; - qDebug("got Z message len(%d)= %s", numBytes, command); + qDebug("got Z message len(%d)= %s\n", numBytes, command); while (totalLength <= numBytes) { if (0==strcmp(command,(char*)"erase all")) { - qDebug("got Z message == erase all"); + qDebug("got Z message == erase all\n"); _tree->eraseAllVoxels(); _voxelsInReadArrays = _voxelsInWriteArrays = 0; // better way to do this?? } if (0==strcmp(command,(char*)"add scene")) { - qDebug("got Z message == add scene - NOT SUPPORTED ON INTERFACE"); + qDebug("got Z message == add scene - NOT SUPPORTED ON INTERFACE\n"); } totalLength += commandLength+1; } @@ -708,7 +708,7 @@ bool VoxelSystem::randomColorOperation(VoxelNode* node, void* extraData) { void VoxelSystem::randomizeVoxelColors() { _nodeCount = 0; _tree->recurseTreeWithOperation(randomColorOperation); - qDebug("setting randomized true color for %d nodes", _nodeCount); + qDebug("setting randomized true color for %d nodes\n", _nodeCount); setupNewVoxelsForDrawing(); } @@ -722,7 +722,7 @@ bool VoxelSystem::falseColorizeRandomOperation(VoxelNode* node, void* extraData) void VoxelSystem::falseColorizeRandom() { _nodeCount = 0; _tree->recurseTreeWithOperation(falseColorizeRandomOperation); - qDebug("setting randomized false color for %d nodes", _nodeCount); + qDebug("setting randomized false color for %d nodes\n", _nodeCount); setupNewVoxelsForDrawing(); } @@ -736,7 +736,7 @@ void VoxelSystem::trueColorize() { PerformanceWarning warn(true, "trueColorize()",true); _nodeCount = 0; _tree->recurseTreeWithOperation(trueColorizeOperation); - qDebug("setting true color for %d nodes", _nodeCount); + qDebug("setting true color for %d nodes\n", _nodeCount); setupNewVoxelsForDrawing(); } @@ -756,7 +756,7 @@ bool VoxelSystem::falseColorizeInViewOperation(VoxelNode* node, void* extraData) void VoxelSystem::falseColorizeInView(ViewFrustum* viewFrustum) { _nodeCount = 0; _tree->recurseTreeWithOperation(falseColorizeInViewOperation,(void*)viewFrustum); - qDebug("setting in view false color for %d nodes", _nodeCount); + qDebug("setting in view false color for %d nodes\n", _nodeCount); setupNewVoxelsForDrawing(); } @@ -806,10 +806,10 @@ void VoxelSystem::falseColorizeDistanceFromView(ViewFrustum* viewFrustum) { _maxDistance = 0.0; _minDistance = FLT_MAX; _tree->recurseTreeWithOperation(getDistanceFromViewRangeOperation,(void*)viewFrustum); - qDebug("determining distance range for %d nodes", _nodeCount); + qDebug("determining distance range for %d nodes\n", _nodeCount); _nodeCount = 0; _tree->recurseTreeWithOperation(falseColorizeDistanceFromViewOperation,(void*)viewFrustum); - qDebug("setting in distance false color for %d nodes", _nodeCount); + qDebug("setting in distance false color for %d nodes\n", _nodeCount); setupNewVoxelsForDrawing(); } @@ -921,7 +921,7 @@ void VoxelSystem::removeOutOfView() { } bool showRemoveDebugDetails = false; if (showRemoveDebugDetails) { - qDebug("removeOutOfView() scanned=%ld removed=%ld inside=%ld intersect=%ld outside=%ld _removedVoxels.count()=%d ", + qDebug("removeOutOfView() scanned=%ld removed=%ld inside=%ld intersect=%ld outside=%ld _removedVoxels.count()=%d \n", args.nodesScanned, args.nodesRemoved, args.nodesInside, args.nodesIntersect, args.nodesOutside, _removedVoxels.count() ); @@ -987,7 +987,7 @@ bool VoxelSystem::falseColorizeRandomEveryOtherOperation(VoxelNode* node, void* void VoxelSystem::falseColorizeRandomEveryOther() { falseColorizeRandomEveryOtherArgs args; _tree->recurseTreeWithOperation(falseColorizeRandomEveryOtherOperation,&args); - qDebug("randomized false color for every other node: total %ld, colorable %ld, colored %ld", + qDebug("randomized false color for every other node: total %ld, colorable %ld, colored %ld\n", args.totalNodes, args.colorableNodes, args.coloredNodes); setupNewVoxelsForDrawing(); } @@ -1048,7 +1048,7 @@ bool VoxelSystem::collectStatsForTreesAndVBOsOperation(VoxelNode* node, void* ex unsigned long nodeIndex = node->getBufferIndex(); if (args->hasIndexFound[nodeIndex]) { args->duplicateVBOIndex++; - qDebug("duplicateVBO found... index=%ld, isDirty=%s, shouldRender=%s ", nodeIndex, + qDebug("duplicateVBO found... index=%ld, isDirty=%s, shouldRender=%s \n", nodeIndex, debug::valueOf(node->isDirty()), debug::valueOf(node->getShouldRender())); } else { args->hasIndexFound[nodeIndex] = true; @@ -1083,13 +1083,13 @@ void VoxelSystem::collectStatsForTreesAndVBOs() { args.expectedMax = _voxelsInWriteArrays; _tree->recurseTreeWithOperation(collectStatsForTreesAndVBOsOperation,&args); - qDebug("Local Voxel Tree Statistics:\n total nodes %ld \n leaves %ld \n dirty %ld \n colored %ld \n shouldRender %ld ", + qDebug("Local Voxel Tree Statistics:\n total nodes %ld \n leaves %ld \n dirty %ld \n colored %ld \n shouldRender %ld \n", args.totalNodes, args.leafNodes, args.dirtyNodes, args.coloredNodes, args.shouldRenderNodes); - qDebug(" _voxelsDirty=%s \n _voxelsInWriteArrays=%ld \n minDirty=%ld \n maxDirty=%ld ", debug::valueOf(_voxelsDirty), + qDebug(" _voxelsDirty=%s \n _voxelsInWriteArrays=%ld \n minDirty=%ld \n maxDirty=%ld \n", debug::valueOf(_voxelsDirty), _voxelsInWriteArrays, minDirty, maxDirty); - qDebug(" inVBO %ld \n nodesInVBOOverExpectedMax %ld \n duplicateVBOIndex %ld \n nodesInVBONotShouldRender %ld ", + qDebug(" inVBO %ld \n nodesInVBOOverExpectedMax %ld \n duplicateVBOIndex %ld \n nodesInVBONotShouldRender %ld \n", args.nodesInVBO, args.nodesInVBOOverExpectedMax, args.duplicateVBOIndex, args.nodesInVBONotShouldRender); glBufferIndex minInVBO = GLBUFFER_INDEX_UNKNOWN; @@ -1102,7 +1102,7 @@ void VoxelSystem::collectStatsForTreesAndVBOs() { } } - qDebug(" minInVBO=%ld \n maxInVBO=%ld \n _voxelsInWriteArrays=%ld \n _voxelsInReadArrays=%ld ", + qDebug(" minInVBO=%ld \n maxInVBO=%ld \n _voxelsInWriteArrays=%ld \n _voxelsInReadArrays=%ld \n", minInVBO, maxInVBO, _voxelsInWriteArrays, _voxelsInReadArrays); } @@ -1127,7 +1127,7 @@ void VoxelSystem::createVoxel(float x, float y, float z, float s, unsigned char red, unsigned char green, unsigned char blue, bool destructive) { pthread_mutex_lock(&_treeLock); - //qDebug("VoxelSystem::createVoxel(%f,%f,%f,%f)",x,y,z,s); + //qDebug("VoxelSystem::createVoxel(%f,%f,%f,%f)\n",x,y,z,s); _tree->createVoxel(x, y, z, s, red, green, blue, destructive); setupNewVoxelsForDrawing(); @@ -1253,9 +1253,9 @@ bool VoxelSystem::falseColorizeOccludedOperation(VoxelNode* node, void* extraDat args->occludedVoxels++; } else if (result == STORED) { args->notOccludedVoxels++; - //qDebug("***** falseColorizeOccludedOperation() NODE is STORED *****"); + //qDebug("***** falseColorizeOccludedOperation() NODE is STORED *****\n"); } else if (result == DOESNT_FIT) { - //qDebug("***** falseColorizeOccludedOperation() NODE DOESNT_FIT???? *****"); + //qDebug("***** falseColorizeOccludedOperation() NODE DOESNT_FIT???? *****\n"); } } return true; // keep going! @@ -1288,7 +1288,7 @@ void VoxelSystem::falseColorizeOccluded() { _tree->recurseTreeWithOperationDistanceSorted(falseColorizeOccludedOperation, position, (void*)&args); - qDebug("falseColorizeOccluded()\n position=(%f,%f)\n total=%ld\n colored=%ld\n occluded=%ld\n notOccluded=%ld\n outOfView=%ld\n subtreeVoxelsSkipped=%ld\n stagedForDeletion=%ld\n nonLeaves=%ld\n nonLeavesOutOfView=%ld\n nonLeavesOccluded=%ld\n pointInside_calls=%ld\n occludes_calls=%ld\n intersects_calls=%ld", + qDebug("falseColorizeOccluded()\n position=(%f,%f)\n total=%ld\n colored=%ld\n occluded=%ld\n notOccluded=%ld\n outOfView=%ld\n subtreeVoxelsSkipped=%ld\n stagedForDeletion=%ld\n nonLeaves=%ld\n nonLeavesOutOfView=%ld\n nonLeavesOccluded=%ld\n pointInside_calls=%ld\n occludes_calls=%ld\n intersects_calls=%ld\n", position.x, position.y, args.totalVoxels, args.coloredVoxels, args.occludedVoxels, args.notOccludedVoxels, args.outOfView, args.subtreeVoxelsSkipped, @@ -1374,9 +1374,9 @@ bool VoxelSystem::falseColorizeOccludedV2Operation(VoxelNode* node, void* extraD args->occludedVoxels++; } else if (result == V2_STORED) { args->notOccludedVoxels++; - //qDebug("***** falseColorizeOccludedOperation() NODE is STORED *****"); + //qDebug("***** falseColorizeOccludedOperation() NODE is STORED *****\n"); } else if (result == V2_DOESNT_FIT) { - //qDebug("***** falseColorizeOccludedOperation() NODE DOESNT_FIT???? *****"); + //qDebug("***** falseColorizeOccludedOperation() NODE DOESNT_FIT???? *****\n"); } delete voxelPolygon; // V2 maps don't store polygons, so we're always in charge of freeing } @@ -1413,7 +1413,7 @@ void VoxelSystem::falseColorizeOccludedV2() { _tree->recurseTreeWithOperationDistanceSorted(falseColorizeOccludedV2Operation, position, (void*)&args); - qDebug("falseColorizeOccludedV2()\n position=(%f,%f)\n total=%ld\n colored=%ld\n occluded=%ld\n notOccluded=%ld\n outOfView=%ld\n subtreeVoxelsSkipped=%ld\n stagedForDeletion=%ld\n nonLeaves=%ld\n nonLeavesOutOfView=%ld\n nonLeavesOccluded=%ld\n pointInside_calls=%ld\n occludes_calls=%ld\n intersects_calls=%ld", + qDebug("falseColorizeOccludedV2()\n position=(%f,%f)\n total=%ld\n colored=%ld\n occluded=%ld\n notOccluded=%ld\n outOfView=%ld\n subtreeVoxelsSkipped=%ld\n stagedForDeletion=%ld\n nonLeaves=%ld\n nonLeavesOutOfView=%ld\n nonLeavesOccluded=%ld\n pointInside_calls=%ld\n occludes_calls=%ld\n intersects_calls=%ld\n", position.x, position.y, args.totalVoxels, args.coloredVoxels, args.occludedVoxels, args.notOccludedVoxels, args.outOfView, args.subtreeVoxelsSkipped, diff --git a/interface/src/Webcam.cpp b/interface/src/Webcam.cpp index 3831f39893..f9dd5ffe2c 100644 --- a/interface/src/Webcam.cpp +++ b/interface/src/Webcam.cpp @@ -156,7 +156,7 @@ void Webcam::setFrame(const Mat& frame, int format, const Mat& depth, const Rota glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, _frameWidth = image.width, _frameHeight = image.height, 0, format, GL_UNSIGNED_BYTE, image.imageData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - qDebug("Capturing video at %dx%d.", _frameWidth, _frameHeight); + qDebug("Capturing video at %dx%d.\n", _frameWidth, _frameHeight); } else { glBindTexture(GL_TEXTURE_2D, _frameTextureID); @@ -172,7 +172,7 @@ void Webcam::setFrame(const Mat& frame, int format, const Mat& depth, const Rota glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, _depthWidth = depthImage.width, _depthHeight = depthImage.height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, depthImage.imageData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - qDebug("Capturing depth at %dx%d.", _depthWidth, _depthHeight); + qDebug("Capturing depth at %dx%d.\n", _depthWidth, _depthHeight); } else { glBindTexture(GL_TEXTURE_2D, _depthTextureID); @@ -330,26 +330,26 @@ static glm::quat xnToGLM(const XnMatrix3X3& matrix) { } static void XN_CALLBACK_TYPE newUser(UserGenerator& generator, XnUserID id, void* cookie) { - qDebug("Found user %d.", id); + qDebug("Found user %d.\n", id); generator.GetSkeletonCap().RequestCalibration(id, false); } static void XN_CALLBACK_TYPE lostUser(UserGenerator& generator, XnUserID id, void* cookie) { - qDebug("Lost user %d.", id); + qDebug("Lost user %d.\n", id); } static void XN_CALLBACK_TYPE calibrationStarted(SkeletonCapability& capability, XnUserID id, void* cookie) { - qDebug("Calibration started for user %d.", id); + qDebug("Calibration started for user %d.\n", id); } static void XN_CALLBACK_TYPE calibrationCompleted(SkeletonCapability& capability, XnUserID id, XnCalibrationStatus status, void* cookie) { if (status == XN_CALIBRATION_STATUS_OK) { - qDebug("Calibration completed for user %d.", id); + qDebug("Calibration completed for user %d.\n", id); capability.StartTracking(id); } else { - qDebug("Calibration failed to user %d.", id); + qDebug("Calibration failed to user %d.\n", id); capability.RequestCalibration(id, true); } } @@ -438,7 +438,7 @@ void FrameGrabber::grabFrame() { // make sure it's in the format we expect if (image->nChannels != 3 || image->depth != IPL_DEPTH_8U || image->dataOrder != IPL_DATA_ORDER_PIXEL || image->origin != 0) { - qDebug("Invalid webcam image format."); + qDebug("Invalid webcam image format.\n"); return; } frame = image; @@ -485,7 +485,7 @@ bool FrameGrabber::init() { // load our face cascade switchToResourcesParentIfRequired(); if (_faceCascade.empty() && !_faceCascade.load("resources/haarcascades/haarcascade_frontalface_alt.xml")) { - qDebug("Failed to load Haar cascade for face tracking."); + qDebug("Failed to load Haar cascade for face tracking.\n"); return false; } @@ -513,7 +513,7 @@ bool FrameGrabber::init() { // next, an ordinary webcam if ((_capture = cvCaptureFromCAM(-1)) == 0) { - qDebug("Failed to open webcam."); + qDebug("Failed to open webcam.\n"); return false; } const int IDEAL_FRAME_WIDTH = 320; diff --git a/interface/src/main.cpp b/interface/src/main.cpp index 7bcef42e88..98ed4fb231 100644 --- a/interface/src/main.cpp +++ b/interface/src/main.cpp @@ -24,8 +24,8 @@ int main(int argc, const char * argv[]) { gettimeofday(&startup_time, NULL); Application app(argc, const_cast(argv), startup_time); - qDebug( "Created QT Application." ); + qDebug( "Created QT Application.\n" ); int exitCode = app.exec(); - qDebug("Normal exit."); + qDebug("Normal exit.\n"); return exitCode; } diff --git a/interface/src/starfield/Loader.h b/interface/src/starfield/Loader.h index 8aa1527ad5..e2f6105f33 100644 --- a/interface/src/starfield/Loader.h +++ b/interface/src/starfield/Loader.h @@ -38,12 +38,12 @@ namespace starfield { if (! UrlReader::readUrl(url, *this, cacheFile)) { - qDebug("%s:%d: %s", + qDebug("%s:%d: %s\n", _urlStr, _lineNo, getError()); return false; } - qDebug("Loaded %u stars.", _recordsRead); + qDebug("Loaded %u stars.\n", _recordsRead); return true; } @@ -63,7 +63,7 @@ namespace starfield { _vertices->clear(); _vertices->reserve(_limit); -// qDebug("Stars.cpp: loader begin %s", url); +// qDebug("Stars.cpp: loader begin %s\n", url); } size_t transfer(char* input, size_t bytes) { @@ -103,7 +103,7 @@ namespace starfield { } else { - qDebug("Stars.cpp:%d: Bad input from %s", + qDebug("Stars.cpp:%d: Bad input from %s\n", _lineNo, _urlStr); } @@ -128,7 +128,7 @@ namespace starfield { // remember the brightness at its top if (_recordsRead == _limit) { -// qDebug("Stars.cpp: vertex limit reached -> heap mode"); +// qDebug("Stars.cpp: vertex limit reached -> heap mode\n"); make_heap( _vertices->begin(), _vertices->end(), diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 87a3f5f70b..2f811f48c2 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -275,12 +275,13 @@ void NodeList::sendDomainServerCheckIn() { sockaddr_in tempAddress; memcpy(&tempAddress.sin_addr, pHostInfo->h_addr_list[0], pHostInfo->h_length); strcpy(_domainIP, inet_ntoa(tempAddress.sin_addr)); - qDebug("Domain Server: %s", _domainHostname); + + qDebug("Domain Server: %s\n", _domainHostname); } else { qDebug("Failed domain server lookup\n"); } } else if (!printedDomainServerIP) { - qDebug("Domain Server IP: %s", _domainIP); + qDebug("Domain Server IP: %s\n", _domainIP); printedDomainServerIP = true; } @@ -419,7 +420,7 @@ void NodeList::addNodeToList(Node* newNode) { ++_numNodes; - qDebug() << "Added" << *newNode; + qDebug() << "Added " << *newNode; } unsigned NodeList::broadcastToNodes(unsigned char *broadcastData, size_t dataBytes, const char* nodeTypes, int numNodeTypes) { diff --git a/libraries/shared/src/OctalCode.cpp b/libraries/shared/src/OctalCode.cpp index 336c89093e..3b92869104 100644 --- a/libraries/shared/src/OctalCode.cpp +++ b/libraries/shared/src/OctalCode.cpp @@ -25,12 +25,12 @@ int numberOfThreeBitSectionsInCode(unsigned char * octalCode) { void printOctalCode(unsigned char * octalCode) { if (!octalCode) { - qDebug("NULL"); + qDebug("NULL\n"); } else { for (int i = 0; i < bytesRequiredForCodeLength(*octalCode); i++) { outputBits(octalCode[i],false); } - qDebug(""); + qDebug("\n"); } } diff --git a/libraries/shared/src/PacketHeaders.cpp b/libraries/shared/src/PacketHeaders.cpp index a91fd1f351..7b4a0509f3 100644 --- a/libraries/shared/src/PacketHeaders.cpp +++ b/libraries/shared/src/PacketHeaders.cpp @@ -29,7 +29,7 @@ bool packetVersionMatch(unsigned char* packetHeader) { if (packetHeader[1] == versionForPacketType(packetHeader[0])) { return true; } else { - qDebug("There is a packet version mismatch for packet with header %c", packetHeader[0]); + qDebug("There is a packet version mismatch for packet with header %c\n", packetHeader[0]); return false; } } diff --git a/libraries/shared/src/PerfStat.cpp b/libraries/shared/src/PerfStat.cpp index 344e9885e6..86985eb038 100644 --- a/libraries/shared/src/PerfStat.cpp +++ b/libraries/shared/src/PerfStat.cpp @@ -59,7 +59,7 @@ PerfStat::~PerfStat() { } if (wantDebugOut) { - qDebug("PerfStats: %s elapsed:%f average:%lf count:%ld total:%lf ut:%d us:%d ue:%d t:%ld s:%ld e:%ld", + qDebug("PerfStats: %s elapsed:%f average:%lf count:%ld total:%lf ut:%d us:%d ue:%d t:%ld s:%ld e:%ld\n", this->group.c_str(),elapsed,average,count,totalTime, (end.tv_usec-start.tv_usec),start.tv_usec,end.tv_usec, (end.tv_sec-start.tv_sec),start.tv_sec,end.tv_sec @@ -111,12 +111,12 @@ PerformanceWarning::~PerformanceWarning() { if ((_alwaysDisplay || _renderWarningsOn) && elapsedmsec > 1) { if (elapsedmsec > 1000) { double elapsedsec = (end - _start) / 1000000.0; - qDebug("%s%s took %lf seconds", (_alwaysDisplay ? "" : "WARNING!"), _message, elapsedsec); + qDebug("%s%s took %lf seconds\n", (_alwaysDisplay ? "" : "WARNING!"), _message, elapsedsec); } else { - qDebug("%s%s took %lf milliseconds", (_alwaysDisplay ? "" : "WARNING!"), _message, elapsedmsec); + qDebug("%s%s took %lf milliseconds\n", (_alwaysDisplay ? "" : "WARNING!"), _message, elapsedmsec); } } else if (_alwaysDisplay) { - qDebug("%s took %lf milliseconds", _message, elapsedmsec); + qDebug("%s took %lf milliseconds\n", _message, elapsedmsec); } }; diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index fdcf142d4d..23b889bdab 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -65,7 +65,7 @@ void outputBufferBits(unsigned char* buffer, int length, bool withNewLine) { outputBits(buffer[i], false); } if (withNewLine) { - qDebug(""); + qDebug("\n"); } } @@ -82,7 +82,7 @@ void outputBits(unsigned char byte, bool withNewLine) { qDebug(" ] "); if (withNewLine) { - qDebug(""); + qDebug("\n"); } } @@ -386,11 +386,11 @@ void printVoxelCode(unsigned char* voxelCode) { unsigned int voxelSizeInOctets = (voxelSizeInBits/3); unsigned int voxelBufferSize = voxelSizeInBytes+1+3; // 1 for size, 3 for color - qDebug("octets=%d",octets); - qDebug("voxelSizeInBits=%d",voxelSizeInBits); - qDebug("voxelSizeInBytes=%d",voxelSizeInBytes); - qDebug("voxelSizeInOctets=%d",voxelSizeInOctets); - qDebug("voxelBufferSize=%d",voxelBufferSize); + qDebug("octets=%d\n",octets); + qDebug("voxelSizeInBits=%d\n",voxelSizeInBits); + qDebug("voxelSizeInBytes=%d\n",voxelSizeInBytes); + qDebug("voxelSizeInOctets=%d\n",voxelSizeInOctets); + qDebug("voxelBufferSize=%d\n",voxelBufferSize); for(int i=0;iprintDebugDetails(); } @@ -196,7 +196,7 @@ CoverageMapStorageResult CoverageMap::checkMap(VoxelProjectedPolygon* polygon, b // not in view, then we just discard it with a DOESNT_FIT, this saves us time checking values later. if (!polygon->getAllInView()) { _notAllInView++; - //qDebug("CoverageMap2::checkMap()... V2_OCCLUDED"); + //qDebug("CoverageMap2::checkMap()... V2_OCCLUDED\n"); return DOESNT_FIT; } @@ -243,9 +243,9 @@ CoverageMapStorageResult CoverageMap::checkMap(VoxelProjectedPolygon* polygon, b /* if (result == STORED) - qDebug("CoverageMap2::checkMap()... STORED"); + qDebug("CoverageMap2::checkMap()... STORED\n"); else - qDebug("CoverageMap2::checkMap()... OCCLUDED"); + qDebug("CoverageMap2::checkMap()... OCCLUDED\n"); */ return result; @@ -268,16 +268,16 @@ CoverageMapStorageResult CoverageMap::checkMap(VoxelProjectedPolygon* polygon, b /* switch (result) { case STORED: - qDebug("checkMap() = STORED"); + qDebug("checkMap() = STORED\n"); break; case NOT_STORED: - qDebug("checkMap() = NOT_STORED"); + qDebug("checkMap() = NOT_STORED\n"); break; case OCCLUDED: - qDebug("checkMap() = OCCLUDED"); + qDebug("checkMap() = OCCLUDED\n"); break; default: - qDebug("checkMap() = ????? "); + qDebug("checkMap() = ????? \n"); break; } */ @@ -290,27 +290,27 @@ CoverageMapStorageResult CoverageMap::checkMap(VoxelProjectedPolygon* polygon, b // any of our child bounding boxes, so we should add it here. if (storeIt) { if (polygon->getBoundingBox().area() > CoverageMap::MINIMUM_POLYGON_AREA_TO_STORE) { - //qDebug("storing polygon of area: %f",polygon->getBoundingBox().area()); + //qDebug("storing polygon of area: %f\n",polygon->getBoundingBox().area()); if (storeIn->getPolygonCount() < MAX_POLYGONS_PER_REGION) { storeIn->storeInArray(polygon); - //qDebug("CoverageMap2::checkMap()... STORED"); + //qDebug("CoverageMap2::checkMap()... STORED\n"); return STORED; } else { CoverageRegion::_regionFullSkips++; - //qDebug("CoverageMap2::checkMap()... NOT_STORED"); + //qDebug("CoverageMap2::checkMap()... NOT_STORED\n"); return NOT_STORED; } } else { CoverageRegion::_tooSmallSkips++; - //qDebug("CoverageMap2::checkMap()... NOT_STORED"); + //qDebug("CoverageMap2::checkMap()... NOT_STORED\n"); return NOT_STORED; } } else { - //qDebug("CoverageMap2::checkMap()... NOT_STORED"); + //qDebug("CoverageMap2::checkMap()... NOT_STORED\n"); return NOT_STORED; } } - //qDebug("CoverageMap2::checkMap()... DOESNT_FIT"); + //qDebug("CoverageMap2::checkMap()... DOESNT_FIT\n"); return DOESNT_FIT; } @@ -341,8 +341,8 @@ void CoverageRegion::erase() { /** if (_polygonCount) { - qDebug("CoverageRegion::erase()..."); - qDebug("_polygonCount=%d",_polygonCount); + qDebug("CoverageRegion::erase()...\n"); + qDebug("_polygonCount=%d\n",_polygonCount); _myBoundingBox.printDebugDetails(getRegionName()); //for (int i = 0; i < _polygonCount; i++) { // qDebug("_polygons[%d]=",i); @@ -393,7 +393,7 @@ void CoverageRegion::growPolygonArray() { _polygonDistances = newDistances; _polygonSizes = newSizes; _polygonArraySize = _polygonArraySize + DEFAULT_GROW_SIZE; - //qDebug("CoverageMap::growPolygonArray() _polygonArraySize=%d...",_polygonArraySize); + //qDebug("CoverageMap::growPolygonArray() _polygonArraySize=%d...\n",_polygonArraySize); } const char* CoverageRegion::getRegionName() const { @@ -438,7 +438,7 @@ bool CoverageRegion::mergeItemsInArray(VoxelProjectedPolygon* seed, bool seedInA _totalPolygons--; } - //qDebug("_polygonCount=%d",_polygonCount); + //qDebug("_polygonCount=%d\n",_polygonCount); // clean up if (_managePolygons) { @@ -486,7 +486,7 @@ void CoverageRegion::storeInArray(VoxelProjectedPolygon* polygon) { // insertion point in this array, and shift the array accordingly float area = polygon->getBoundingBox().area(); float reverseArea = 4.0f - area; - //qDebug("store by size area=%f reverse area=%f", area, reverseArea); + //qDebug("store by size area=%f reverse area=%f\n", area, reverseArea); _polygonCount = insertIntoSortedArrays((void*)polygon, reverseArea, IGNORED, (void**)_polygons, _polygonSizes, IGNORED, _polygonCount, _polygonArraySize); @@ -500,10 +500,10 @@ void CoverageRegion::storeInArray(VoxelProjectedPolygon* polygon) { // Debugging and Optimization Tuning code. if (_polygonCount > _maxPolygonsUsed) { _maxPolygonsUsed = _polygonCount; - //qDebug("CoverageRegion new _maxPolygonsUsed reached=%d region=%s",_maxPolygonsUsed, getRegionName()); + //qDebug("CoverageRegion new _maxPolygonsUsed reached=%d region=%s\n",_maxPolygonsUsed, getRegionName()); //_myBoundingBox.printDebugDetails("map._myBoundingBox"); } else { - //qDebug("CoverageRegion::storeInArray() _polygonCount=%d region=%s",_polygonCount, getRegionName()); + //qDebug("CoverageRegion::storeInArray() _polygonCount=%d region=%s\n",_polygonCount, getRegionName()); } } diff --git a/libraries/voxels/src/CoverageMapV2.cpp b/libraries/voxels/src/CoverageMapV2.cpp index 9d4e92fd17..0e382d7f12 100644 --- a/libraries/voxels/src/CoverageMapV2.cpp +++ b/libraries/voxels/src/CoverageMapV2.cpp @@ -61,7 +61,7 @@ CoverageMapV2::CoverageMapV2(BoundingBox boundingBox, bool isRoot, bool isCovere { _mapCount++; init(); - //qDebug("CoverageMapV2 created... _mapCount=%d",_mapCount); + //qDebug("CoverageMapV2 created... _mapCount=%d\n",_mapCount); }; CoverageMapV2::~CoverageMapV2() { @@ -78,11 +78,11 @@ void CoverageMapV2::erase() { } if (_isRoot && wantDebugging) { - qDebug("CoverageMapV2 last to be deleted..."); - qDebug("MINIMUM_POLYGON_AREA_TO_STORE=%f",MINIMUM_POLYGON_AREA_TO_STORE); - qDebug("_mapCount=%d",_mapCount); - qDebug("_checkMapRootCalls=%d",_checkMapRootCalls); - qDebug("_notAllInView=%d",_notAllInView); + qDebug("CoverageMapV2 last to be deleted...\n"); + qDebug("MINIMUM_POLYGON_AREA_TO_STORE=%f\n",MINIMUM_POLYGON_AREA_TO_STORE); + qDebug("_mapCount=%d\n",_mapCount); + qDebug("_checkMapRootCalls=%d\n",_checkMapRootCalls); + qDebug("_notAllInView=%d\n",_notAllInView); _mapCount = 0; _checkMapRootCalls = 0; _notAllInView = 0; diff --git a/libraries/voxels/src/ViewFrustum.cpp b/libraries/voxels/src/ViewFrustum.cpp index 3a871f37b9..c13da815f8 100644 --- a/libraries/voxels/src/ViewFrustum.cpp +++ b/libraries/voxels/src/ViewFrustum.cpp @@ -322,40 +322,40 @@ bool ViewFrustum::matches(const ViewFrustum& compareTo, bool debug) const { testMatches(compareTo._eyeOffsetOrientation, _eyeOffsetOrientation); if (!result && debug) { - qDebug("ViewFrustum::matches()... result=%s", debug::valueOf(result)); - qDebug("%s -- compareTo._position=%f,%f,%f _position=%f,%f,%f", + qDebug("ViewFrustum::matches()... result=%s\n", debug::valueOf(result)); + qDebug("%s -- compareTo._position=%f,%f,%f _position=%f,%f,%f\n", (testMatches(compareTo._position,_position) ? "MATCHES " : "NO MATCH"), compareTo._position.x, compareTo._position.y, compareTo._position.z, _position.x, _position.y, _position.z ); - qDebug("%s -- compareTo._direction=%f,%f,%f _direction=%f,%f,%f", + qDebug("%s -- compareTo._direction=%f,%f,%f _direction=%f,%f,%f\n", (testMatches(compareTo._direction, _direction) ? "MATCHES " : "NO MATCH"), compareTo._direction.x, compareTo._direction.y, compareTo._direction.z, _direction.x, _direction.y, _direction.z ); - qDebug("%s -- compareTo._up=%f,%f,%f _up=%f,%f,%f", + qDebug("%s -- compareTo._up=%f,%f,%f _up=%f,%f,%f\n", (testMatches(compareTo._up, _up) ? "MATCHES " : "NO MATCH"), compareTo._up.x, compareTo._up.y, compareTo._up.z, _up.x, _up.y, _up.z ); - qDebug("%s -- compareTo._right=%f,%f,%f _right=%f,%f,%f", + qDebug("%s -- compareTo._right=%f,%f,%f _right=%f,%f,%f\n", (testMatches(compareTo._right, _right) ? "MATCHES " : "NO MATCH"), compareTo._right.x, compareTo._right.y, compareTo._right.z, _right.x, _right.y, _right.z ); - qDebug("%s -- compareTo._fieldOfView=%f _fieldOfView=%f", + qDebug("%s -- compareTo._fieldOfView=%f _fieldOfView=%f\n", (testMatches(compareTo._fieldOfView, _fieldOfView) ? "MATCHES " : "NO MATCH"), compareTo._fieldOfView, _fieldOfView); - qDebug("%s -- compareTo._aspectRatio=%f _aspectRatio=%f", + qDebug("%s -- compareTo._aspectRatio=%f _aspectRatio=%f\n", (testMatches(compareTo._aspectRatio, _aspectRatio) ? "MATCHES " : "NO MATCH"), compareTo._aspectRatio, _aspectRatio); - qDebug("%s -- compareTo._nearClip=%f _nearClip=%f", + qDebug("%s -- compareTo._nearClip=%f _nearClip=%f\n", (testMatches(compareTo._nearClip, _nearClip) ? "MATCHES " : "NO MATCH"), compareTo._nearClip, _nearClip); - qDebug("%s -- compareTo._farClip=%f _farClip=%f", + qDebug("%s -- compareTo._farClip=%f _farClip=%f\n", (testMatches(compareTo._farClip, _farClip) ? "MATCHES " : "NO MATCH"), compareTo._farClip, _farClip); - qDebug("%s -- compareTo._eyeOffsetPosition=%f,%f,%f _eyeOffsetPosition=%f,%f,%f", + qDebug("%s -- compareTo._eyeOffsetPosition=%f,%f,%f _eyeOffsetPosition=%f,%f,%f\n", (testMatches(compareTo._eyeOffsetPosition, _eyeOffsetPosition) ? "MATCHES " : "NO MATCH"), compareTo._eyeOffsetPosition.x, compareTo._eyeOffsetPosition.y, compareTo._eyeOffsetPosition.z, _eyeOffsetPosition.x, _eyeOffsetPosition.y, _eyeOffsetPosition.z); - qDebug("%s -- compareTo._eyeOffsetOrientation=%f,%f,%f,%f _eyeOffsetOrientation=%f,%f,%f,%f", + qDebug("%s -- compareTo._eyeOffsetOrientation=%f,%f,%f,%f _eyeOffsetOrientation=%f,%f,%f,%f\n", (testMatches(compareTo._eyeOffsetOrientation, _eyeOffsetOrientation) ? "MATCHES " : "NO MATCH"), compareTo._eyeOffsetOrientation.x, compareTo._eyeOffsetOrientation.y, compareTo._eyeOffsetOrientation.z, compareTo._eyeOffsetOrientation.w, @@ -418,17 +418,17 @@ void ViewFrustum::computeOffAxisFrustum(float& left, float& right, float& bottom } void ViewFrustum::printDebugDetails() const { - qDebug("ViewFrustum::printDebugDetails()... "); - qDebug("_position=%f,%f,%f", _position.x, _position.y, _position.z ); - qDebug("_direction=%f,%f,%f", _direction.x, _direction.y, _direction.z ); - qDebug("_up=%f,%f,%f", _up.x, _up.y, _up.z ); - qDebug("_right=%f,%f,%f", _right.x, _right.y, _right.z ); - qDebug("_fieldOfView=%f", _fieldOfView); - qDebug("_aspectRatio=%f", _aspectRatio); - qDebug("_nearClip=%f", _nearClip); - qDebug("_farClip=%f", _farClip); - qDebug("_eyeOffsetPosition=%f,%f,%f", _eyeOffsetPosition.x, _eyeOffsetPosition.y, _eyeOffsetPosition.z ); - qDebug("_eyeOffsetOrientation=%f,%f,%f,%f", _eyeOffsetOrientation.x, _eyeOffsetOrientation.y, _eyeOffsetOrientation.z, + qDebug("ViewFrustum::printDebugDetails()... \n"); + qDebug("_position=%f,%f,%f\n", _position.x, _position.y, _position.z ); + qDebug("_direction=%f,%f,%f\n", _direction.x, _direction.y, _direction.z ); + qDebug("_up=%f,%f,%f\n", _up.x, _up.y, _up.z ); + qDebug("_right=%f,%f,%f\n", _right.x, _right.y, _right.z ); + qDebug("_fieldOfView=%f\n", _fieldOfView); + qDebug("_aspectRatio=%f\n", _aspectRatio); + qDebug("_nearClip=%f\n", _nearClip); + qDebug("_farClip=%f\n", _farClip); + qDebug("_eyeOffsetPosition=%f,%f,%f\n", _eyeOffsetPosition.x, _eyeOffsetPosition.y, _eyeOffsetPosition.z ); + qDebug("_eyeOffsetOrientation=%f,%f,%f,%f\n", _eyeOffsetOrientation.x, _eyeOffsetOrientation.y, _eyeOffsetOrientation.z, _eyeOffsetOrientation.w ); } diff --git a/libraries/voxels/src/VoxelNode.cpp b/libraries/voxels/src/VoxelNode.cpp index e94c9756d9..76fae500dd 100644 --- a/libraries/voxels/src/VoxelNode.cpp +++ b/libraries/voxels/src/VoxelNode.cpp @@ -259,7 +259,7 @@ bool VoxelNode::collapseIdenticalLeaves() { // if no child, child isn't a leaf, or child doesn't have a color if (!_children[i] || _children[i]->isStagedForDeletion() || !_children[i]->isLeaf() || !_children[i]->isColored()) { allChildrenMatch=false; - //qDebug("SADNESS child missing or not colored! i=%d",i); + //qDebug("SADNESS child missing or not colored! i=%d\n",i); break; } else { if (i==0) { @@ -276,7 +276,7 @@ bool VoxelNode::collapseIdenticalLeaves() { if (allChildrenMatch) { - //qDebug("allChildrenMatch: pruning tree"); + //qDebug("allChildrenMatch: pruning tree\n"); for (int i = 0; i < NUMBER_OF_CHILDREN; i++) { delete _children[i]; // delete all the child nodes _children[i]=NULL; // set it to NULL @@ -310,13 +310,13 @@ void VoxelNode::printDebugDetails(const char* label) const { } } - qDebug("%s - Voxel at corner=(%f,%f,%f) size=%f\n isLeaf=%s isColored=%s (%d,%d,%d,%d) isDirty=%s shouldRender=%s children=", label, + qDebug("%s - Voxel at corner=(%f,%f,%f) size=%f\n isLeaf=%s isColored=%s (%d,%d,%d,%d) isDirty=%s shouldRender=%s\n children=", label, _box.getCorner().x, _box.getCorner().y, _box.getCorner().z, _box.getSize().x, debug::valueOf(isLeaf()), debug::valueOf(isColored()), getColor()[0], getColor()[1], getColor()[2], getColor()[3], debug::valueOf(isDirty()), debug::valueOf(getShouldRender())); outputBits(childBits, false); - qDebug(" octalCode="); + qDebug("\n octalCode="); printOctalCode(_octalCode); } diff --git a/libraries/voxels/src/VoxelProjectedPolygon.cpp b/libraries/voxels/src/VoxelProjectedPolygon.cpp index 71f43a0c04..8a39d7f358 100644 --- a/libraries/voxels/src/VoxelProjectedPolygon.cpp +++ b/libraries/voxels/src/VoxelProjectedPolygon.cpp @@ -95,7 +95,7 @@ void BoundingBox::printDebugDetails(const char* label) const { } else { qDebug("BoundingBox"); } - qDebug("\n _set=%s\n corner=%f,%f size=%f,%f\n bounds=[(%f,%f) to (%f,%f)]", + qDebug("\n _set=%s\n corner=%f,%f size=%f,%f\n bounds=[(%f,%f) to (%f,%f)]\n", debug::valueOf(_set), corner.x, corner.y, size.x, size.y, corner.x, corner.y, corner.x+size.x, corner.y+size.y); } diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index 62191bad2b..803bea8038 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -157,7 +157,7 @@ void VoxelTree::recurseNodeWithOperationDistanceSorted(VoxelNode* node, RecurseV if (childNode) { // chance to optimize, doesn't need to be actual distance!! Could be distance squared float distanceSquared = childNode->distanceSquareToPoint(point); - //qDebug("recurseNodeWithOperationDistanceSorted() CHECKING child[%d] point=%f,%f center=%f,%f distance=%f...", i, point.x, point.y, center.x, center.y, distance); + //qDebug("recurseNodeWithOperationDistanceSorted() CHECKING child[%d] point=%f,%f center=%f,%f distance=%f...\n", i, point.x, point.y, center.x, center.y, distance); //childNode->printDebugDetails(""); currentCount = insertIntoSortedArrays((void*)childNode, distanceSquared, i, (void**)&sortedChildren, (float*)&distancesToChildren, @@ -168,7 +168,7 @@ void VoxelTree::recurseNodeWithOperationDistanceSorted(VoxelNode* node, RecurseV for (int i = 0; i < currentCount; i++) { VoxelNode* childNode = sortedChildren[i]; if (childNode) { - //qDebug("recurseNodeWithOperationDistanceSorted() PROCESSING child[%d] distance=%f...", i, distancesToChildren[i]); + //qDebug("recurseNodeWithOperationDistanceSorted() PROCESSING child[%d] distance=%f...\n", i, distancesToChildren[i]); //childNode->printDebugDetails(""); recurseNodeWithOperationDistanceSorted(childNode, operation, point, extraData); } @@ -460,7 +460,7 @@ void VoxelTree::deleteVoxelCodeFromTreeRecursion(VoxelNode* node, void* extraDat // isn't a colored leaf, and the child branch doesn't exist, so there's nothing to do below and // we can safely return, ending the recursion and unwinding if (!childNode) { - //qDebug("new___deleteVoxelCodeFromTree() child branch doesn't exist, but parent is not a leaf, just unwind"); + //qDebug("new___deleteVoxelCodeFromTree() child branch doesn't exist, but parent is not a leaf, just unwind\n"); return; } @@ -548,7 +548,7 @@ void VoxelTree::readCodeColorBufferToTreeRecursion(VoxelNode* node, void* extraD } } else { if (!node->isLeaf()) { - qDebug("WARNING! operation would require deleting children, add Voxel ignored! "); + qDebug("WARNING! operation would require deleting children, add Voxel ignored!\n "); } } @@ -688,7 +688,7 @@ void VoxelTree::loadVoxelsFile(const char* fileName, bool wantColorRandomizer) { int totalBytesRead = 0; if(file.is_open()) { - qDebug("loading file..."); + qDebug("loading file...\n"); bool bail = false; while (!file.eof() && !bail) { file.get(octets); @@ -713,14 +713,14 @@ void VoxelTree::loadVoxelsFile(const char* fileName, bool wantColorRandomizer) { file.get(colorRead); blue = (unsigned char)colorRead; - qDebug("voxel color from file red:%d, green:%d, blue:%d ",red,green,blue); + qDebug("voxel color from file red:%d, green:%d, blue:%d \n",red,green,blue); vCount++; int colorRandomizer = wantColorRandomizer ? randIntInRange (-5, 5) : 0; voxelData[lengthInBytes+1] = std::max(0,std::min(255,red + colorRandomizer)); voxelData[lengthInBytes+2] = std::max(0,std::min(255,green + colorRandomizer)); voxelData[lengthInBytes+3] = std::max(0,std::min(255,blue + colorRandomizer)); - qDebug("voxel color after rand red:%d, green:%d, blue:%d", + qDebug("voxel color after rand red:%d, green:%d, blue:%d\n", voxelData[lengthInBytes+1], voxelData[lengthInBytes+2], voxelData[lengthInBytes+3]); //printVoxelCode(voxelData); @@ -821,7 +821,7 @@ void VoxelTree::createSphere(float radius, float xc, float yc, float zc, float v if (debug) { int percentComplete = 100 * (thisRadius/radius); - qDebug("percentComplete=%d",percentComplete); + qDebug("percentComplete=%d\n",percentComplete); } for (float theta=0.0; theta <= 2 * M_PI; theta += angleDelta) { @@ -837,7 +837,7 @@ void VoxelTree::createSphere(float radius, float xc, float yc, float zc, float v // 2) In all modes, we will use our "outer" color to draw the voxels. Otherwise we will use the average color if (lastLayer) { if (false && debug) { - qDebug("adding candy shell: theta=%f phi=%f thisRadius=%f radius=%f", + qDebug("adding candy shell: theta=%f phi=%f thisRadius=%f radius=%f\n", theta, phi, thisRadius,radius); } switch (mode) { @@ -861,7 +861,7 @@ void VoxelTree::createSphere(float radius, float xc, float yc, float zc, float v green = (unsigned char)std::min(255, std::max(0, (int)(g1 + ((g2 - g1) * gradient)))); blue = (unsigned char)std::min(255, std::max(0, (int)(b1 + ((b2 - b1) * gradient)))); if (debug) { - qDebug("perlin=%f gradient=%f color=(%d,%d,%d)",perlin, gradient, red, green, blue); + qDebug("perlin=%f gradient=%f color=(%d,%d,%d)\n",perlin, gradient, red, green, blue); } } break; } @@ -1178,7 +1178,7 @@ int VoxelTree::encodeTreeBitstreamRecursion(VoxelNode* node, unsigned char* outp if (childNode) { // chance to optimize, doesn't need to be actual distance!! Could be distance squared //float distanceSquared = childNode->distanceSquareToPoint(point); - //qDebug("recurseNodeWithOperationDistanceSorted() CHECKING child[%d] point=%f,%f center=%f,%f distance=%f...", i, point.x, point.y, center.x, center.y, distance); + //qDebug("recurseNodeWithOperationDistanceSorted() CHECKING child[%d] point=%f,%f center=%f,%f distance=%f...\n", i, point.x, point.y, center.x, center.y, distance); //childNode->printDebugDetails(""); float distance = params.viewFrustum ? childNode->distanceToCamera(*params.viewFrustum) : 0; @@ -1434,7 +1434,7 @@ int VoxelTree::encodeTreeBitstreamRecursion(VoxelNode* node, unsigned char* outp bool VoxelTree::readFromSVOFile(const char* fileName) { std::ifstream file(fileName, std::ios::in|std::ios::binary|std::ios::ate); if(file.is_open()) { - qDebug("loading file %s...", fileName); + qDebug("loading file %s...\n", fileName); // get file length.... unsigned long fileLength = file.tellg(); @@ -1462,14 +1462,14 @@ bool VoxelTree::readFromSchematicFile(const char *fileName) { std::stringstream ss; int err = retrieveData(fileName, ss); if (err && ss.get() != TAG_Compound) { - qDebug("[ERROR] Invalid schematic file."); + qDebug("[ERROR] Invalid schematic file.\n"); return false; } ss.get(); TagCompound schematics(ss); if (!schematics.getBlocksId() || !schematics.getBlocksData()) { - qDebug("[ERROR] Invalid schematic file."); + qDebug("[ERROR] Invalid schematic file.\n"); return false; } @@ -1532,7 +1532,7 @@ bool VoxelTree::readFromSchematicFile(const char *fileName) { } } - qDebug("Created %d voxels from minecraft import.", count); + qDebug("Created %d voxels from minecraft import.\n", count); return true; } @@ -1542,7 +1542,7 @@ void VoxelTree::writeToSVOFile(const char* fileName, VoxelNode* node) const { std::ofstream file(fileName, std::ios::out|std::ios::binary); if(file.is_open()) { - qDebug("saving to file %s...", fileName); + qDebug("saving to file %s...\n", fileName); VoxelNodeBag nodeBag; // If we were given a specific node, start from there, otherwise start from root From 16d603e203dca018679bb1bcd1465f114a1d0351 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 16 Jul 2013 12:53:43 -0700 Subject: [PATCH 32/81] clean up extra new lines and LogDisplay line break --- interface/src/Application.cpp | 3 +-- interface/src/LogDisplay.cpp | 7 +------ libraries/shared/src/Node.cpp | 2 +- libraries/shared/src/NodeList.cpp | 4 ++-- 4 files changed, 5 insertions(+), 11 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index e5455eb604..0b29d6714d 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -165,7 +165,7 @@ void GLCanvas::wheelEvent(QWheelEvent* event) { } void messageHandler(QtMsgType type, const char* message) { - printf("%s\n", message); + printf("%s", message); LogDisplay::instance.addMessage(message); } @@ -215,7 +215,6 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : { _applicationStartupTime = startup_time; _window->setWindowTitle("Interface"); - qDebug("Interface Startup:\n"); qInstallMsgHandler(messageHandler); diff --git a/interface/src/LogDisplay.cpp b/interface/src/LogDisplay.cpp index 49e4886b00..247ea4beb5 100644 --- a/interface/src/LogDisplay.cpp +++ b/interface/src/LogDisplay.cpp @@ -97,9 +97,8 @@ void LogDisplay::addMessage(const char* ptr) { fprintf(_stream, "%s", ptr); } - while (true) { + while (*ptr != '\0') { // process the characters - bool isEndOfMessage = (*ptr == '\0'); char c = *ptr++; if (c == '\t') { @@ -151,10 +150,6 @@ void LogDisplay::addMessage(const char* ptr) { _writeLineStartPos = _writePos; _writtenInLine = 0; } - - if (isEndOfMessage) { - break; - } } pthread_mutex_unlock(& _mutex); diff --git a/libraries/shared/src/Node.cpp b/libraries/shared/src/Node.cpp index 41936d3a99..d7cf429558 100644 --- a/libraries/shared/src/Node.cpp +++ b/libraries/shared/src/Node.cpp @@ -150,5 +150,5 @@ QDebug operator<<(QDebug debug, const Node &node) { debug << "#" << node.getNodeID() << node.getTypeName() << node.getType(); debug.nospace() << publicAddressBuffer << ":" << publicAddressPort; - return debug.space(); + return debug.nospace(); } diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 2f811f48c2..87ee133dbb 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -420,7 +420,7 @@ void NodeList::addNodeToList(Node* newNode) { ++_numNodes; - qDebug() << "Added " << *newNode; + qDebug() << "Added" << *newNode << "\n"; } unsigned NodeList::broadcastToNodes(unsigned char *broadcastData, size_t dataBytes, const char* nodeTypes, int numNodeTypes) { @@ -475,7 +475,7 @@ void *removeSilentNodes(void *args) { if ((checkTimeUSecs - node->getLastHeardMicrostamp()) > NODE_SILENCE_THRESHOLD_USECS && node->getType() != NODE_TYPE_VOXEL_SERVER) { - qDebug() << "Killed" << *node; + qDebug() << "Killed" << *node << "\n"; node->setAlive(false); } From ce0c9e2e1a5aa67a885f4411506529dec448c9f2 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 16 Jul 2013 12:58:16 -0700 Subject: [PATCH 33/81] flush stdout in case non new-line output is received --- interface/src/Application.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 0b29d6714d..6ebb4239b4 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -166,6 +166,8 @@ void GLCanvas::wheelEvent(QWheelEvent* event) { void messageHandler(QtMsgType type, const char* message) { printf("%s", message); + fflush(stdout); + LogDisplay::instance.addMessage(message); } From e66c1ca552a840b8980db37eb978ffabd45ed990 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 16 Jul 2013 13:01:46 -0700 Subject: [PATCH 34/81] link Qt to the shared library --- libraries/shared/CMakeLists.txt | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/libraries/shared/CMakeLists.txt b/libraries/shared/CMakeLists.txt index 23f198f730..cf1c603b7d 100644 --- a/libraries/shared/CMakeLists.txt +++ b/libraries/shared/CMakeLists.txt @@ -1,14 +1,13 @@ cmake_minimum_required(VERSION 2.8) +set(ROOT_DIR ../..) +set(MACRO_DIR ${ROOT_DIR}/cmake/macros) + set(TARGET_NAME shared) project(${TARGET_NAME}) -# grab the implemenation and header files -file(GLOB HIFI_SHARED_SRCS src/*.h src/*.cpp) - -# create a library and set the property so it can be referenced later -add_library(${TARGET_NAME} ${HIFI_SHARED_SRCS}) -set(HIFI_SHARED_LIBRARY ${TARGET_NAME}) +include(${MACRO_DIR}/SetupHifiLibrary.cmake) +setup_hifi_library(${TARGET_NAME}) set(EXTERNAL_ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/external) From c78759da16d6e033b400328beb963620f3ff7b66 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 16 Jul 2013 13:37:16 -0700 Subject: [PATCH 35/81] cleanup printLogs reintroduce on merge with upstream master --- interface/src/Application.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 48dffccfc9..77881cd25a 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1421,12 +1421,12 @@ bool Application::sendVoxelsOperation(VoxelNode* node, void* extraData) { uint64_t elapsed = now - args->lastSendTime; int usecToSleep = CLIENT_TO_SERVER_VOXEL_SEND_INTERVAL_USECS - elapsed; if (usecToSleep > 0) { - printLog("sendVoxelsOperation: packet: %d bytes:%ld elapsed %ld usecs, sleeping for %d usecs!\n", - args->packetsSent, args->bytesSent, elapsed, usecToSleep); + qDebug("sendVoxelsOperation: packet: %d bytes:%ld elapsed %lld usecs, sleeping for %d usecs!\n", + args->packetsSent, args->bytesSent, elapsed, usecToSleep); usleep(usecToSleep); } else { - printLog("sendVoxelsOperation: packet: %d bytes:%ld elapsed %ld usecs, no need to sleep!\n", - args->packetsSent, args->bytesSent, elapsed); + qDebug("sendVoxelsOperation: packet: %d bytes:%ld elapsed %lld usecs, no need to sleep!\n", + args->packetsSent, args->bytesSent, elapsed); } args->lastSendTime = now; } @@ -1504,7 +1504,7 @@ void Application::importVoxels() { if (fileNameString.endsWith(".png", Qt::CaseInsensitive)) { QImage pngImage = QImage(fileName); if (pngImage.height() != pngImage.width()) { - printLog("ERROR: Bad PNG size: height != width.\n"); + qDebug("ERROR: Bad PNG size: height != width.\n"); return; } @@ -1609,9 +1609,9 @@ void Application::pasteVoxels() { // If we have voxels left in the packet, then send the packet if (args.bufferInUse > (numBytesPacketHeader + sizeof(unsigned short int))) { controlledBroadcastToNodes(args.messageBuffer, args.bufferInUse, & NODE_TYPE_VOXEL_SERVER, 1); - printLog("sending packet: %d\n", ++args.packetsSent); + qDebug("sending packet: %d\n", ++args.packetsSent); args.bytesSent += args.bufferInUse; - printLog("total bytes sent: %ld\n", args.bytesSent); + qDebug("total bytes sent: %ld\n", args.bytesSent); } if (calculatedOctCode) { From 8464a013fea10a54c3bf35e453665905d13b6dfb Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 16 Jul 2013 13:39:24 -0700 Subject: [PATCH 36/81] fix format string warnings in Application --- interface/src/Application.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 77881cd25a..731bf7fe0f 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1421,11 +1421,11 @@ bool Application::sendVoxelsOperation(VoxelNode* node, void* extraData) { uint64_t elapsed = now - args->lastSendTime; int usecToSleep = CLIENT_TO_SERVER_VOXEL_SEND_INTERVAL_USECS - elapsed; if (usecToSleep > 0) { - qDebug("sendVoxelsOperation: packet: %d bytes:%ld elapsed %lld usecs, sleeping for %d usecs!\n", + qDebug("sendVoxelsOperation: packet: %d bytes:%lld elapsed %lld usecs, sleeping for %d usecs!\n", args->packetsSent, args->bytesSent, elapsed, usecToSleep); usleep(usecToSleep); } else { - qDebug("sendVoxelsOperation: packet: %d bytes:%ld elapsed %lld usecs, no need to sleep!\n", + qDebug("sendVoxelsOperation: packet: %d bytes:%lld elapsed %lld usecs, no need to sleep!\n", args->packetsSent, args->bytesSent, elapsed); } args->lastSendTime = now; @@ -1611,7 +1611,7 @@ void Application::pasteVoxels() { controlledBroadcastToNodes(args.messageBuffer, args.bufferInUse, & NODE_TYPE_VOXEL_SERVER, 1); qDebug("sending packet: %d\n", ++args.packetsSent); args.bytesSent += args.bufferInUse; - qDebug("total bytes sent: %ld\n", args.bytesSent); + qDebug("total bytes sent: %lld\n", args.bytesSent); } if (calculatedOctCode) { From fbc59de0810242feccac5bfbddcf3c4b02e4aafc Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Jul 2013 15:08:09 -0700 Subject: [PATCH 37/81] latest cut at dirty bit sending --- libraries/shared/src/OctalCode.cpp | 2 ++ libraries/voxels/src/VoxelConstants.h | 1 + libraries/voxels/src/VoxelNode.h | 1 + libraries/voxels/src/VoxelTree.cpp | 37 ++++++++++++++++++++++----- libraries/voxels/src/VoxelTree.h | 6 ++++- voxel-server/src/VoxelNodeData.cpp | 2 -- voxel-server/src/main.cpp | 13 +++++++--- 7 files changed, 49 insertions(+), 13 deletions(-) diff --git a/libraries/shared/src/OctalCode.cpp b/libraries/shared/src/OctalCode.cpp index 3b92869104..b085a146a2 100644 --- a/libraries/shared/src/OctalCode.cpp +++ b/libraries/shared/src/OctalCode.cpp @@ -7,6 +7,7 @@ // #include // std:min +#include #include #include @@ -16,6 +17,7 @@ #include "OctalCode.h" int numberOfThreeBitSectionsInCode(unsigned char * octalCode) { + assert(octalCode); if (*octalCode == 255) { return *octalCode + numberOfThreeBitSectionsInCode(octalCode + 1); } else { diff --git a/libraries/voxels/src/VoxelConstants.h b/libraries/voxels/src/VoxelConstants.h index 421c03f3b6..6fdfec1de9 100644 --- a/libraries/voxels/src/VoxelConstants.h +++ b/libraries/voxels/src/VoxelConstants.h @@ -21,6 +21,7 @@ const glm::vec3 IDENTITY_UP = glm::vec3( 0.0f, 1.0f, 0.0f); const glm::vec3 IDENTITY_FRONT = glm::vec3( 0.0f, 0.0f,-1.0f); const bool LOW_RES_MONO = false; // while in "low res mode" do voxels switch to monochrome +const uint64_t CHANGE_FUDGE = 1000*200; // useconds of fudge in determining if we want to resend changed voxels const int TREE_SCALE = 128; diff --git a/libraries/voxels/src/VoxelNode.h b/libraries/voxels/src/VoxelNode.h index 461a723a8a..8e3b9cb5db 100644 --- a/libraries/voxels/src/VoxelNode.h +++ b/libraries/voxels/src/VoxelNode.h @@ -85,6 +85,7 @@ public: void clearDirtyBit() { _isDirty = false; }; bool hasChangedSince(uint64_t time) const { return (_lastChanged > time); }; void markWithChangedTime() { _lastChanged = usecTimestampNow(); }; + uint64_t getLastChanged() const { return _lastChanged; }; void handleSubtreeChanged(VoxelTree* myTree); glBufferIndex getBufferIndex() const { return _glBufferIndex; }; diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index 88c523dbfe..461292a28e 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -1012,12 +1012,18 @@ int VoxelTree::encodeTreeBitstream(VoxelNode* node, unsigned char* outputBuffer, // How many bytes have we written so far at this level; int bytesWritten = 0; + + // These two cases should not ever happen... but if they do, we don't want to crash. + if (!node || !node->getOctalCode()) { + qDebug("VoxelTree::encodeTreeBitstream() BAD VoxelNode! Bailing!"); + return bytesWritten; + } // If we're at a node that is out of view, then we can return, because no nodes below us will be in view! if (params.viewFrustum && !node->isInView(*params.viewFrustum)) { return bytesWritten; } - + // write the octal code int codeLength; if (params.chopLevels) { @@ -1076,7 +1082,7 @@ int VoxelTree::encodeTreeBitstreamRecursion(VoxelNode* node, unsigned char* outp if (currentEncodeLevel >= params.maxEncodeLevel) { return bytesAtThisLevel; } - + // caller can pass NULL as viewFrustum if they want everything if (params.viewFrustum) { float distance = node->distanceToCamera(*params.viewFrustum); @@ -1109,10 +1115,26 @@ int VoxelTree::encodeTreeBitstreamRecursion(VoxelNode* node, unsigned char* outp } } - // If we were in view, then bail out early! - if (wasInView) { + // If we were in view, and haven't changed, then bail out early! + if (wasInView && params.deltaViewFrustum) { + printf("wasInView... params.lastViewFrustumSent=[%lld] getLastChanged()=%lld\n", + params.lastViewFrustumSent, node->getLastChanged()); + } + + if (wasInView && !(params.deltaViewFrustum && node->hasChangedSince(params.lastViewFrustumSent - CHANGE_FUDGE))) { + //if (wasInView) { return bytesAtThisLevel; - } + } + +/** + // now, if we're not in delta sending mode, but the voxel hasn't changed, then we can bail early... + if (!params.deltaViewFrustum && !node->hasChangedSince(params.lastViewFrustumSent - CHANGE_FUDGE)) { + printf("not delta sending, and the node hasn't changed, bail early... params.lastViewFrustumSent=[%lld] getLastChanged()=%lld\n", + params.lastViewFrustumSent, node->getLastChanged()); + return bytesAtThisLevel; + } +**/ + // If the user also asked for occlusion culling, check if this node is occluded, but only if it's not a leaf. // leaf occlusion is handled down below when we check child nodes @@ -1258,7 +1280,6 @@ int VoxelTree::encodeTreeBitstreamRecursion(VoxelNode* node, unsigned char* outp bool shouldRender = !params.viewFrustum ? true : childNode->calculateShouldRender(params.viewFrustum, params.boundaryLevelAdjust); // track children with actual color, only if the child wasn't previously in view! - //(!childWasInView || childNode->hasChangedSince(lastViewFrustumSent) )) { if (shouldRender && !childIsOccluded) { bool childWasInView = false; @@ -1274,7 +1295,9 @@ int VoxelTree::encodeTreeBitstreamRecursion(VoxelNode* node, unsigned char* outp } // If our child wasn't in view (or we're ignoring wasInView) then we add it to our sending items - if (!childWasInView) { + if (!childWasInView || + (params.deltaViewFrustum && + childNode->hasChangedSince(params.lastViewFrustumSent - CHANGE_FUDGE))){ childrenColoredBits += (1 << (7 - originalIndex)); inViewWithColorCount++; } else { diff --git a/libraries/voxels/src/VoxelTree.h b/libraries/voxels/src/VoxelTree.h index 9c8e6e7d16..bab66c5097 100644 --- a/libraries/voxels/src/VoxelTree.h +++ b/libraries/voxels/src/VoxelTree.h @@ -35,6 +35,7 @@ typedef enum {GRADIENT, RANDOM, NATURAL} creationMode; #define DONT_CHOP 0 #define NO_BOUNDARY_ADJUST 0 #define LOW_RES_MOVING_ADJUST 1 +#define IGNORE_LAST_SENT 0 class EncodeBitstreamParams { public: @@ -49,6 +50,7 @@ public: bool wantOcclusionCulling; long childWasInViewDiscarded; int boundaryLevelAdjust; + uint64_t lastViewFrustumSent; CoverageMap* map; @@ -62,7 +64,8 @@ public: const ViewFrustum* lastViewFrustum = IGNORE_VIEW_FRUSTUM, bool wantOcclusionCulling= NO_OCCLUSION_CULLING, CoverageMap* map = IGNORE_COVERAGE_MAP, - int boundaryLevelAdjust = NO_BOUNDARY_ADJUST) : + int boundaryLevelAdjust = NO_BOUNDARY_ADJUST, + uint64_t lastViewFrustumSent = IGNORE_LAST_SENT) : maxEncodeLevel (maxEncodeLevel), maxLevelReached (0), viewFrustum (viewFrustum), @@ -74,6 +77,7 @@ public: wantOcclusionCulling (wantOcclusionCulling), childWasInViewDiscarded (0), boundaryLevelAdjust (boundaryLevelAdjust), + lastViewFrustumSent (lastViewFrustumSent), map (map) {} }; diff --git a/voxel-server/src/VoxelNodeData.cpp b/voxel-server/src/VoxelNodeData.cpp index 2218724c79..f3d87948aa 100644 --- a/voxel-server/src/VoxelNodeData.cpp +++ b/voxel-server/src/VoxelNodeData.cpp @@ -24,8 +24,6 @@ VoxelNodeData::VoxelNodeData(Node* owningNode) : { _voxelPacket = new unsigned char[MAX_VOXEL_PACKET_SIZE]; _voxelPacketAt = _voxelPacket; - _lastViewFrustumSent = 0; - resetVoxelPacket(); } diff --git a/voxel-server/src/main.cpp b/voxel-server/src/main.cpp index df7011585d..bfb0e4505c 100644 --- a/voxel-server/src/main.cpp +++ b/voxel-server/src/main.cpp @@ -173,10 +173,10 @@ void deepestLevelVoxelDistributor(NodeList* nodeList, // If the current view frustum has changed OR we have nothing to send, then search against // the current view frustum for things to send. if (viewFrustumChanged || nodeData->nodeBag.isEmpty()) { + uint64_t now = usecTimestampNow(); if (::debugVoxelSending) { printf("(viewFrustumChanged=%s || nodeData->nodeBag.isEmpty() =%s)...\n", debug::valueOf(viewFrustumChanged), debug::valueOf(nodeData->nodeBag.isEmpty())); - uint64_t now = usecTimestampNow(); if (nodeData->getLastTimeBagEmpty() > 0) { float elapsedSceneSend = (now - nodeData->getLastTimeBagEmpty()) / 1000000.0f; if (viewFrustumChanged) { @@ -188,13 +188,19 @@ void deepestLevelVoxelDistributor(NodeList* nodeList, debug::valueOf(nodeData->getWantOcclusionCulling()), debug::valueOf(wantDelta), debug::valueOf(wantColor)); } - nodeData->setLastTimeBagEmpty(now); // huh? why is this inside debug? probably not what we want } // if our view has changed, we need to reset these things... if (viewFrustumChanged) { nodeData->nodeBag.deleteAll(); nodeData->map.erase(); + } + + if (!viewFrustumChanged && !nodeData->getWantDelta()) { + // only set our last sent time if we weren't resetting due to frustum change + uint64_t now = usecTimestampNow(); + nodeData->setLastTimeBagEmpty(now); + printf("ENTIRE SCENE SENT! nodeData->setLastTimeBagEmpty(now=[%lld])\n", now); } nodeData->nodeBag.insert(serverTree.rootNode); @@ -233,7 +239,8 @@ void deepestLevelVoxelDistributor(NodeList* nodeList, EncodeBitstreamParams params(INT_MAX, &nodeData->getCurrentViewFrustum(), wantColor, WANT_EXISTS_BITS, DONT_CHOP, wantDelta, lastViewFrustum, - wantOcclusionCulling, coverageMap, boundaryLevelAdjust); + wantOcclusionCulling, coverageMap, boundaryLevelAdjust, + nodeData->getLastTimeBagEmpty()); bytesWritten = serverTree.encodeTreeBitstream(subTree, &tempOutputBuffer[0], MAX_VOXEL_PACKET_SIZE - 1, nodeData->nodeBag, params); From 7cec2f5ffd3c74978249e0eceb79ce16105853c7 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 16 Jul 2013 15:27:14 -0700 Subject: [PATCH 38/81] use fprintf instead of printf and flush for qDebug --- interface/src/Application.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index b5d59ddd9c..1bfba999b1 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -165,9 +165,7 @@ void GLCanvas::wheelEvent(QWheelEvent* event) { } void messageHandler(QtMsgType type, const char* message) { - printf("%s", message); - fflush(stdout); - + fprintf(stdout, "%s", message); LogDisplay::instance.addMessage(message); } From fa155adc8c8bc0a021706c05bfdef8dd02042810 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 16 Jul 2013 15:50:37 -0700 Subject: [PATCH 39/81] register the shared message handler to fix voxel-server output --- libraries/shared/src/SharedUtil.cpp | 4 ++++ libraries/shared/src/SharedUtil.h | 6 +++++- voxel-server/src/main.cpp | 4 +++- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index 23b889bdab..72b5b02f15 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -188,6 +188,10 @@ bool cmdOptionExists(int argc, const char * argv[],const char* option) { return false; } +void sharedMessageHandler(QtMsgType type, const char* message) { + fprintf(stdout, "%s", message); +} + ////////////////////////////////////////////////////////////////////////////////////////// // Function: createVoxelEditMessage() // Description: creates an "insert" or "remove" voxel message for a voxel code diff --git a/libraries/shared/src/SharedUtil.h b/libraries/shared/src/SharedUtil.h index 6973e4cec4..37443c2778 100644 --- a/libraries/shared/src/SharedUtil.h +++ b/libraries/shared/src/SharedUtil.h @@ -9,9 +9,11 @@ #ifndef __hifi__SharedUtil__ #define __hifi__SharedUtil__ +#include #include #include -#include + +#include #ifdef _WIN32 #include "Systime.h" @@ -66,6 +68,8 @@ void loadRandomIdentifier(unsigned char* identifierBuffer, int numBytes); const char* getCmdOption(int argc, const char * argv[],const char* option); bool cmdOptionExists(int argc, const char * argv[],const char* option); +void sharedMessageHandler(QtMsgType type, const char* message); + struct VoxelDetail { float x; float y; diff --git a/voxel-server/src/main.cpp b/voxel-server/src/main.cpp index df7011585d..40d2777ee6 100644 --- a/voxel-server/src/main.cpp +++ b/voxel-server/src/main.cpp @@ -377,7 +377,9 @@ void attachVoxelNodeDataToNode(Node* newNode) { int main(int argc, const char * argv[]) { pthread_mutex_init(&::treeLock, NULL); - + + qInstallMsgHandler(sharedMessageHandler); + NodeList* nodeList = NodeList::createInstance(NODE_TYPE_VOXEL_SERVER, VOXEL_LISTEN_PORT); setvbuf(stdout, NULL, _IOLBF, 0); From 021344fb790c081565d8e473befabf4cac4612f9 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 16 Jul 2013 15:56:46 -0700 Subject: [PATCH 40/81] link Qt to voxel-edit target now that QDebug is included in shared --- voxel-edit/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/voxel-edit/CMakeLists.txt b/voxel-edit/CMakeLists.txt index de056cdd86..e025099dc5 100644 --- a/voxel-edit/CMakeLists.txt +++ b/voxel-edit/CMakeLists.txt @@ -14,7 +14,7 @@ include_glm(${TARGET_NAME} ${ROOT_DIR}) include(${MACRO_DIR}/SetupHifiProject.cmake) -setup_hifi_project(${TARGET_NAME} FALSE) +setup_hifi_project(${TARGET_NAME} TRUE) # link in the shared library include(${MACRO_DIR}/LinkHifiLibrary.cmake) From 192ae637893c3b22a16cbf3a3504595490cae64d Mon Sep 17 00:00:00 2001 From: Philip Rosedale Date: Tue, 16 Jul 2013 16:40:50 -0700 Subject: [PATCH 41/81] Colliding with ground, voxels makes interesting sounds and flashes your display --- interface/src/Application.cpp | 6 +++- interface/src/Application.h | 7 +++- interface/src/Audio.cpp | 30 ++++++++--------- interface/src/Audio.h | 4 +-- interface/src/Avatar.cpp | 61 +++++++++++++++++++++-------------- interface/src/Avatar.h | 8 +++-- interface/src/Util.cpp | 34 +++++++++++++------ interface/src/Util.h | 5 ++- 8 files changed, 97 insertions(+), 58 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 644d5524f0..a2fe2072c6 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -188,6 +188,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : _isTouchPressed(false), _yawFromTouch(0.0f), _pitchFromTouch(0.0f), + _groundPlaneImpact(0.0f), _mousePressed(false), _mouseVoxelScale(1.0f / 1024.0f), _justEditedVoxel(false), @@ -2516,7 +2517,7 @@ void Application::displaySide(Camera& whichCamera) { //draw a grid ground plane.... if (_renderGroundPlaneOn->isChecked()) { - drawGroundPlaneGrid(EDGE_SIZE_GROUND_PLANE); + renderGroundPlaneGrid(EDGE_SIZE_GROUND_PLANE, _audio.getCollisionSoundMagnitude()); } // Draw voxels if (_renderVoxels->isChecked()) { @@ -2592,6 +2593,9 @@ void Application::displayOverlay() { glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); + // Display a single screen-size quad to + renderCollisionOverlay(_glWidget->width(), _glWidget->height(), _audio.getCollisionSoundMagnitude()); + #ifndef _WIN32 _audio.render(_glWidget->width(), _glWidget->height()); if (_oscilloscopeOn->isChecked()) { diff --git a/interface/src/Application.h b/interface/src/Application.h index b46ee20111..cb1896c4de 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -101,6 +101,9 @@ public: QNetworkAccessManager* getNetworkAccessManager() { return _networkAccessManager; } GeometryCache* getGeometryCache() { return &_geometryCache; } + void setGroundPlaneImpact(float groundPlaneImpact) { _groundPlaneImpact = groundPlaneImpact; } + + private slots: void timer(); @@ -206,7 +209,7 @@ private: void deleteVoxelUnderCursor(); void eyedropperVoxelUnderCursor(); void resetSensors(); - + void setMenuShortcutsEnabled(bool enabled); void updateCursor(); @@ -344,6 +347,8 @@ private: float _yawFromTouch; float _pitchFromTouch; + float _groundPlaneImpact; + VoxelDetail _mouseVoxelDragging; glm::vec3 _voxelThrust; bool _mousePressed; // true if mouse has been pressed (clear when finished) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 8b2856a7c9..dc36968c3b 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -605,11 +605,7 @@ void Audio::addProceduralSounds(int16_t* inputBuffer, float speed = glm::length(_lastVelocity); float volume = VOLUME_BASELINE * (1.f - speed / MAX_AUDIBLE_VELOCITY); - // Test tone (should be continuous!) - /* - for (int i = 0; i < numSamples; i++) { - inputBuffer[i] += (int16_t) (_proceduralEffectSample + i)%16 * 10; - }*/ + int sample; // // Travelling noise @@ -617,32 +613,32 @@ void Audio::addProceduralSounds(int16_t* inputBuffer, // Add a noise-modulated sinewave with volume that tapers off with speed increasing if ((speed > MIN_AUDIBLE_VELOCITY) && (speed < MAX_AUDIBLE_VELOCITY)) { for (int i = 0; i < numSamples; i++) { - //inputBuffer[i] += (int16_t)((sinf((float) (_proceduralEffectSample + i) / SOUND_PITCH * speed) * (1.f + randFloat() * 0.0f)) * volume * speed); inputBuffer[i] += (int16_t)(sinf((float) (_proceduralEffectSample + i) / SOUND_PITCH ) * volume * (1.f + randFloat() * 0.25f) * speed); - - } } - const float COLLISION_SOUND_CUTOFF_LEVEL = 5.0f; - int sample; + const float COLLISION_SOUND_CUTOFF_LEVEL = 0.01f; + const float COLLISION_SOUND_MAX_VOLUME = 1000.f; + const float UP_MAJOR_FIFTH = powf(1.5f, 4.0f); + float t; if (_collisionSoundMagnitude > COLLISION_SOUND_CUTOFF_LEVEL) { for (int i = 0; i < numSamples; i++) { - sample = (int16_t) (((sinf(((float)_proceduralEffectSample + (float)i) * _collisionSoundFrequency) * (1.f - _collisionSoundNoise) - + ((randFloat() * 2.f - 1.0f) * _collisionSoundNoise)) - * _collisionSoundMagnitude)); + t = (float) _proceduralEffectSample + (float) i; + sample = sinf(t * _collisionSoundFrequency) + + sinf(t * _collisionSoundFrequency / 4.f) + + sinf(t * _collisionSoundFrequency / 16.f * UP_MAJOR_FIFTH); + sample *= _collisionSoundMagnitude * COLLISION_SOUND_MAX_VOLUME; inputBuffer[i] += sample; outputLeft[i] += sample; outputRight[i] += sample; _collisionSoundMagnitude *= _collisionSoundDuration; } } - - //if (_heartbeatMagnitude > 0.0f) { - // - //} _proceduralEffectSample += numSamples; } +// +// Starts a collision sound. magnitude is 0-1, with 1 the loudest possible sound. +// void Audio::startCollisionSound(float magnitude, float frequency, float noise, float duration) { _collisionSoundMagnitude = magnitude; _collisionSoundFrequency = frequency; diff --git a/interface/src/Audio.h b/interface/src/Audio.h index a43e05e3ec..5954361444 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -43,10 +43,10 @@ public: int getJitterBufferSamples() { return _jitterBufferSamples; }; void lowPassFilter(int16_t* inputBuffer); - - void setCollisionSoundMagnitude(float collisionSoundMagnitude) { _collisionSoundMagnitude = collisionSoundMagnitude; } void startCollisionSound(float magnitude, float frequency, float noise, float duration); + float getCollisionSoundMagnitude() { return _collisionSoundMagnitude; }; + void ping(); diff --git a/interface/src/Avatar.cpp b/interface/src/Avatar.cpp index b3868f6ea7..e34a4ff194 100755 --- a/interface/src/Avatar.cpp +++ b/interface/src/Avatar.cpp @@ -545,8 +545,8 @@ void Avatar::simulate(float deltaTime, Transmitter* transmitter) { _position += _scale * _gravity * (GRAVITY_EARTH * deltaTime) * deltaTime; } - updateCollisionWithEnvironment(); - updateCollisionWithVoxels(); + updateCollisionWithEnvironment(deltaTime); + updateCollisionWithVoxels(deltaTime); updateAvatarCollisions(deltaTime); } @@ -867,7 +867,7 @@ void Avatar::updateCollisionWithSphere(glm::vec3 position, float radius, float d } } -void Avatar::updateCollisionWithEnvironment() { +void Avatar::updateCollisionWithEnvironment(float deltaTime) { glm::vec3 up = getBodyUpDirection(); float radius = _height * 0.125f; @@ -878,7 +878,12 @@ void Avatar::updateCollisionWithEnvironment() { if (Application::getInstance()->getEnvironment()->findCapsulePenetration( _position - up * (_pelvisFloatingHeight - radius), _position + up * (_height - _pelvisFloatingHeight - radius), radius, penetration)) { - createCollisionSound(penetration, ENVIRONMENT_COLLISION_FREQUENCY); + float velocityTowardCollision = glm::dot(_velocity, glm::normalize(penetration)); + if (velocityTowardCollision > 0.2) { + Application::getInstance()->setGroundPlaneImpact(1.0f); + } + updateCollisionSound(penetration, deltaTime, ENVIRONMENT_COLLISION_FREQUENCY); + applyHardCollision(penetration, ENVIRONMENT_SURFACE_ELASTICITY, ENVIRONMENT_SURFACE_DAMPING); @@ -886,7 +891,7 @@ void Avatar::updateCollisionWithEnvironment() { } -void Avatar::updateCollisionWithVoxels() { +void Avatar::updateCollisionWithVoxels(float deltaTime) { float radius = _height * 0.125f; const float VOXEL_ELASTICITY = 1.4f; const float VOXEL_DAMPING = 0.0; @@ -895,7 +900,7 @@ void Avatar::updateCollisionWithVoxels() { if (Application::getInstance()->getVoxels()->findCapsulePenetration( _position - glm::vec3(0.0f, _pelvisFloatingHeight - radius, 0.0f), _position + glm::vec3(0.0f, _height - _pelvisFloatingHeight - radius, 0.0f), radius, penetration)) { - createCollisionSound(penetration, VOXEL_COLLISION_FREQUENCY); + updateCollisionSound(penetration, deltaTime, VOXEL_COLLISION_FREQUENCY); applyHardCollision(penetration, VOXEL_ELASTICITY, VOXEL_DAMPING); } } @@ -924,26 +929,34 @@ void Avatar::applyHardCollision(const glm::vec3& penetration, float elasticity, } } -void Avatar::createCollisionSound(const glm::vec3 &penetration, float frequency) { - // Push the collision into the audio system for procedural effects - const float AUDIBLE_COLLISION_THRESHOLD = 0.2f; - const float COLLISION_VOLUME = 1000.f; - const float MAX_COLLISION_VOLUME = 15000.f; +void Avatar::updateCollisionSound(const glm::vec3 &penetration, float deltaTime, float frequency) { + // consider whether to have the collision make a sound + const float AUDIBLE_COLLISION_THRESHOLD = 0.02f; + const float COLLISION_LOUDNESS = 1.f; const float DURATION_SCALING = 0.004f; - float velocityTowardCollision = glm::dot(_velocity, glm::normalize(penetration)); - float velocityTangentToCollision = glm::length(_velocity) - velocityTowardCollision; - if (velocityTowardCollision > AUDIBLE_COLLISION_THRESHOLD) { - Application::getInstance()->getAudio()->startCollisionSound( - fmax(COLLISION_VOLUME * velocityTowardCollision, MAX_COLLISION_VOLUME), - frequency, - fmin(velocityTangentToCollision / velocityTowardCollision, 1.f), - 1.f - DURATION_SCALING * powf(frequency, 0.5f) / velocityTowardCollision); - + const float NOISE_SCALING = 0.1f; + glm::vec3 velocity = _velocity; + glm::vec3 gravity = getGravity(); + + if (glm::length(gravity) > EPSILON) { + // If gravity is on, remove the effect of gravity on velocity for this + // frame, so that we are not constantly colliding with the surface + velocity -= _scale * glm::length(gravity) * GRAVITY_EARTH * deltaTime * glm::normalize(gravity); + } + float velocityTowardCollision = glm::dot(velocity, glm::normalize(penetration)); + float velocityTangentToCollision = glm::length(velocity) - velocityTowardCollision; + + if (velocityTowardCollision > AUDIBLE_COLLISION_THRESHOLD) { + // Volume is proportional to collision velocity + // Base frequency is modified upward by the angle of the collision + // Noise is a function of the angle of collision + // Duration of the sound is a function of both base frequency and velocity of impact + Application::getInstance()->getAudio()->startCollisionSound( + fmin(COLLISION_LOUDNESS * velocityTowardCollision, 1.f), + frequency * (1.f + velocityTangentToCollision / velocityTowardCollision), + fmin(velocityTangentToCollision / velocityTowardCollision * NOISE_SCALING, 1.f), + 1.f - DURATION_SCALING * powf(frequency, 0.5f) / velocityTowardCollision); } - //float collisionSoundLevel = penetrationLength * COLLISION_VOLUME; - //if (collisionSoundLevel > AUDIBLE_COLLISION_THRESHOLD) { - // Application::getInstance()->getAudio()->setCollisionSoundMagnitude(collisionSoundLevel); - //} } void Avatar::updateAvatarCollisions(float deltaTime) { diff --git a/interface/src/Avatar.h b/interface/src/Avatar.h index 31c9b573b8..fa605fa425 100755 --- a/interface/src/Avatar.h +++ b/interface/src/Avatar.h @@ -159,6 +159,8 @@ public: glm::quat getOrientation () const; glm::quat getWorldAlignedOrientation() const; + glm::vec3 getGravity () const { return _gravity; } + glm::vec3 getUprightHeadPosition() const; AvatarVoxelSystem* getVoxels() { return &_voxels; } @@ -259,10 +261,10 @@ private: void updateAvatarCollisions(float deltaTime); void updateArmIKAndConstraints( float deltaTime ); void updateCollisionWithSphere( glm::vec3 position, float radius, float deltaTime ); - void updateCollisionWithEnvironment(); - void updateCollisionWithVoxels(); + void updateCollisionWithEnvironment(float deltaTime); + void updateCollisionWithVoxels(float deltaTime); void applyHardCollision(const glm::vec3& penetration, float elasticity, float damping); - void createCollisionSound(const glm::vec3& penetration, float frequency); + void updateCollisionSound(const glm::vec3& penetration, float deltaTime, float frequency); void applyCollisionWithOtherAvatar( Avatar * other, float deltaTime ); void checkForMouseRayTouching(); }; diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 65a277b623..ddce092896 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -326,22 +326,38 @@ void drawvec3(int x, int y, float scale, float rotate, float thick, int mono, gl glPopMatrix(); } +void renderCollisionOverlay(int width, int height, float magnitude) { + const float MIN_VISIBLE_COLLISION = 0.01f; + if (magnitude > MIN_VISIBLE_COLLISION) { + glColor4f(0, 0, 0, magnitude); + glBegin(GL_QUADS); + glVertex2f(0, 0); + glVertex2d(width, 0); + glVertex2d(width, height); + glVertex2d(0, height); + glEnd(); + } +} -void drawGroundPlaneGrid(float size) { - glColor3f(0.4f, 0.5f, 0.3f); +void renderGroundPlaneGrid(float size, float impact) { glLineWidth(2.0); - + glm::vec4 impactColor(1, 0, 0, 1); + glm::vec3 lineColor(0.4, 0.5, 0.3); + glm::vec4 surfaceColor(0.5, 0.5, 0.5, 0.4); + + glColor3fv(&lineColor.x); for (float x = 0; x <= size; x++) { glBegin(GL_LINES); - glVertex3f(x, 0.0f, 0); - glVertex3f(x, 0.0f, size); - glVertex3f(0, 0.0f, x); - glVertex3f(size, 0.0f, x); + glVertex3f(x, 0, 0); + glVertex3f(x, 0, size); + glVertex3f(0, 0, x); + glVertex3f(size, 0, x); glEnd(); } - // Draw a translucent quad just underneath the grid. - glColor4f(0.5, 0.5, 0.5, 0.4); + // Draw the floor, colored for recent impact + glm::vec4 floorColor = impact * impactColor + (1.f - impact) * surfaceColor; + glColor4fv(&floorColor.x); glBegin(GL_QUADS); glVertex3f(0, 0, 0); glVertex3f(size, 0, 0); diff --git a/interface/src/Util.h b/interface/src/Util.h index 37bd0595ec..8bc77a98ea 100644 --- a/interface/src/Util.h +++ b/interface/src/Util.h @@ -57,7 +57,10 @@ glm::quat safeMix(const glm::quat& q1, const glm::quat& q2, float alpha); double diffclock(timeval *clock1,timeval *clock2); -void drawGroundPlaneGrid(float size); +void renderGroundPlaneGrid(float size, float impact); + +void renderCollisionOverlay(int width, int height, float magnitude); + void renderDiskShadow(glm::vec3 position, glm::vec3 upDirection, float radius, float darkness); From 75d052b997b46abbf23b85caff49f7b3ade23736 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Jul 2013 16:46:58 -0700 Subject: [PATCH 42/81] cleanup --- libraries/voxels/src/VoxelTree.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index 461292a28e..d11e26114c 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -449,7 +449,6 @@ void VoxelTree::deleteVoxelCodeFromTreeRecursion(VoxelNode* node, void* extraDat } } - // track our tree dirtiness _isDirty = true; args->pathChanged = true; From d54bae8e763f64fbf15b392523401e240b9cc36d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Jul 2013 16:47:18 -0700 Subject: [PATCH 43/81] cleanup --- libraries/voxels/src/VoxelTree.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index d11e26114c..3b4df380f0 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -448,7 +448,6 @@ void VoxelTree::deleteVoxelCodeFromTreeRecursion(VoxelNode* node, void* extraDat ancestorNode->setColor(node->getColor()); } } - _isDirty = true; args->pathChanged = true; From 5ee691025628e757686c5810e285385595105738 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Jul 2013 16:51:09 -0700 Subject: [PATCH 44/81] cleanup --- libraries/voxels/src/VoxelTree.cpp | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index 3b4df380f0..d9e36b3388 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -1113,26 +1113,21 @@ int VoxelTree::encodeTreeBitstreamRecursion(VoxelNode* node, unsigned char* outp } } - // If we were in view, and haven't changed, then bail out early! - if (wasInView && params.deltaViewFrustum) { - printf("wasInView... params.lastViewFrustumSent=[%lld] getLastChanged()=%lld\n", - params.lastViewFrustumSent, node->getLastChanged()); - } - + // If we were previously in the view, then we normally will return out of here and stop recursing. But + // if we're in deltaViewFrustum mode, and this node has changed since it was last sent, then we do + // need to send it. if (wasInView && !(params.deltaViewFrustum && node->hasChangedSince(params.lastViewFrustumSent - CHANGE_FUDGE))) { - //if (wasInView) { return bytesAtThisLevel; } -/** - // now, if we're not in delta sending mode, but the voxel hasn't changed, then we can bail early... + /** Not ready for production - coming soon. + // If we're not in delta sending mode, but the voxel hasn't changed, then we can also bail early... if (!params.deltaViewFrustum && !node->hasChangedSince(params.lastViewFrustumSent - CHANGE_FUDGE)) { - printf("not delta sending, and the node hasn't changed, bail early... params.lastViewFrustumSent=[%lld] getLastChanged()=%lld\n", + printf("not delta sending, and the node hasn't changed, bail early... lastSent=%lld getLastChanged=%lld\n", params.lastViewFrustumSent, node->getLastChanged()); return bytesAtThisLevel; } -**/ - + **/ // If the user also asked for occlusion culling, check if this node is occluded, but only if it's not a leaf. // leaf occlusion is handled down below when we check child nodes From bdb14fee33b997856967fa493b8de75796b11bfc Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Jul 2013 16:53:15 -0700 Subject: [PATCH 45/81] cleanup --- libraries/voxels/src/VoxelTree.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index d9e36b3388..6ef9f293ee 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -1287,7 +1287,9 @@ int VoxelTree::encodeTreeBitstreamRecursion(VoxelNode* node, unsigned char* outp } } - // If our child wasn't in view (or we're ignoring wasInView) then we add it to our sending items + // If our child wasn't in view (or we're ignoring wasInView) then we add it to our sending items. + // Or if we were previously in the view, but this node has changed since it was last sent, then we do + // need to send it. if (!childWasInView || (params.deltaViewFrustum && childNode->hasChangedSince(params.lastViewFrustumSent - CHANGE_FUDGE))){ From cf38a0e837c65f336c540fd3630b4faf163279bc Mon Sep 17 00:00:00 2001 From: Eric Johnston Date: Tue, 16 Jul 2013 17:02:40 -0700 Subject: [PATCH 46/81] Avatar's arm follows real or simulated Leap glove, if present. This is a tiny change, and the effect is pretty good. It's only active if there's a Leap device connected and you're using it, or else if you've used the Debug menu item to fake a Leap glove. --- interface/src/Avatar.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/interface/src/Avatar.cpp b/interface/src/Avatar.cpp index e3f3032bdf..15ef875c75 100755 --- a/interface/src/Avatar.cpp +++ b/interface/src/Avatar.cpp @@ -819,6 +819,12 @@ void Avatar::updateHandMovementAndTouching(float deltaTime, bool enableHandMovem } else { _avatarTouch.setHasInteractingOther(false); } + + // If there's a leap-interaction hand visible, use that as the endpoint + if (getHand().getHandPositions().size() > 0) { + _skeleton.joint[ AVATAR_JOINT_RIGHT_FINGERTIPS ].position = + getHand().leapPositionToWorldPosition(getHand().getHandPositions()[0]); + } }//if (_isMine) //constrain right arm length and re-adjust elbow position as it bends From adc09cec68acfe6e5693e078f4961633976bde87 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Jul 2013 17:21:28 -0700 Subject: [PATCH 47/81] some CR feedback --- libraries/voxels/src/VoxelConstants.h | 2 +- voxel-server/src/main.cpp | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/libraries/voxels/src/VoxelConstants.h b/libraries/voxels/src/VoxelConstants.h index 6fdfec1de9..452772ff07 100644 --- a/libraries/voxels/src/VoxelConstants.h +++ b/libraries/voxels/src/VoxelConstants.h @@ -21,7 +21,7 @@ const glm::vec3 IDENTITY_UP = glm::vec3( 0.0f, 1.0f, 0.0f); const glm::vec3 IDENTITY_FRONT = glm::vec3( 0.0f, 0.0f,-1.0f); const bool LOW_RES_MONO = false; // while in "low res mode" do voxels switch to monochrome -const uint64_t CHANGE_FUDGE = 1000*200; // useconds of fudge in determining if we want to resend changed voxels +const uint64_t CHANGE_FUDGE = 1000 * 200; // useconds of fudge in determining if we want to resend changed voxels const int TREE_SCALE = 128; diff --git a/voxel-server/src/main.cpp b/voxel-server/src/main.cpp index bfb0e4505c..35bc4816c0 100644 --- a/voxel-server/src/main.cpp +++ b/voxel-server/src/main.cpp @@ -200,7 +200,9 @@ void deepestLevelVoxelDistributor(NodeList* nodeList, // only set our last sent time if we weren't resetting due to frustum change uint64_t now = usecTimestampNow(); nodeData->setLastTimeBagEmpty(now); - printf("ENTIRE SCENE SENT! nodeData->setLastTimeBagEmpty(now=[%lld])\n", now); + if (::debugVoxelSending) { + printf("ENTIRE SCENE SENT! nodeData->setLastTimeBagEmpty(now=[%lld])\n", now); + } } nodeData->nodeBag.insert(serverTree.rootNode); From 39130aef58424cd36e20cf04d2041989df91dc32 Mon Sep 17 00:00:00 2001 From: Eric Johnston Date: Tue, 16 Jul 2013 18:10:54 -0700 Subject: [PATCH 48/81] Rave Glove demo: activation mode and stage (dark backdrop) drawing. --- interface/src/Application.cpp | 1 + interface/src/Hand.cpp | 31 +++++++++++++++++++++++++++++++ interface/src/Hand.h | 4 ++++ 3 files changed, 36 insertions(+) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 1bfba999b1..791353abdb 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2033,6 +2033,7 @@ void Application::update(float deltaTime) { // Leap finger-sensing device LeapManager::enableFakeFingers(_simulateLeapHand->isChecked() || _testRaveGlove->isChecked()); LeapManager::nextFrame(); + _myAvatar.getHand().setRaveGloveActive(_testRaveGlove->isChecked()); _myAvatar.getHand().setLeapFingers(LeapManager::getFingerTips(), LeapManager::getFingerRoots()); _myAvatar.getHand().setLeapHands(LeapManager::getHandPositions(), LeapManager::getHandNormals()); diff --git a/interface/src/Hand.cpp b/interface/src/Hand.cpp index 29a2c32bf1..d0ff0abd5a 100755 --- a/interface/src/Hand.cpp +++ b/interface/src/Hand.cpp @@ -74,12 +74,43 @@ void Hand::render(bool lookingInMirror) { calculateGeometry(); + if (_isRaveGloveActive) + renderRaveGloveStage(); + glEnable(GL_DEPTH_TEST); glEnable(GL_RESCALE_NORMAL); renderHandSpheres(); } +void Hand::renderRaveGloveStage() { + if (_owningAvatar && _owningAvatar->isMyAvatar()) { + Head& head = _owningAvatar->getHead(); + glm::quat headOrientation = head.getOrientation(); + glm::vec3 headPosition = head.getPosition(); + float scale = 100.0f; + glm::vec3 vc = headOrientation * glm::vec3( 0.0f, 0.0f, -30.0f) + headPosition; + glm::vec3 v0 = headOrientation * (glm::vec3(-1.0f, -1.0f, 0.0f) * scale) + vc; + glm::vec3 v1 = headOrientation * (glm::vec3( 1.0f, -1.0f, 0.0f) * scale) + vc; + glm::vec3 v2 = headOrientation * (glm::vec3( 1.0f, 1.0f, 0.0f) * scale) + vc; + glm::vec3 v3 = headOrientation * (glm::vec3(-1.0f, 1.0f, 0.0f) * scale) + vc; + + glDisable(GL_DEPTH_TEST); + glEnable(GL_BLEND); + glBegin(GL_TRIANGLE_FAN); + glColor4f(0.0f, 0.0f, 0.0f, 1.0f); + glVertex3fv((float*)&vc); + glColor4f(0.0f, 0.0f, 0.0f, 0.5f); + glVertex3fv((float*)&v0); + glVertex3fv((float*)&v1); + glVertex3fv((float*)&v2); + glVertex3fv((float*)&v3); + glVertex3fv((float*)&v0); + glEnd(); + glEnable(GL_DEPTH_TEST); + } +} + void Hand::renderHandSpheres() { glPushMatrix(); // Draw the leap balls diff --git a/interface/src/Hand.h b/interface/src/Hand.h index 1c25c85fbc..e1b0dc9ff0 100755 --- a/interface/src/Hand.h +++ b/interface/src/Hand.h @@ -46,9 +46,11 @@ public: const std::vector& fingerRoots); void setLeapHands (const std::vector& handPositions, const std::vector& handNormals); + void setRaveGloveActive(bool active) { _isRaveGloveActive = active; } // getters const glm::vec3& getLeapBallPosition (int ball) const { return _leapBalls[ball].position;} + bool isRaveGloveActive () const { return _isRaveGloveActive; } // position conversion glm::vec3 leapPositionToWorldPosition(const glm::vec3& leapPosition); @@ -61,12 +63,14 @@ private: Avatar* _owningAvatar; float _renderAlpha; bool _lookingInMirror; + bool _isRaveGloveActive; glm::vec3 _ballColor; glm::vec3 _position; glm::quat _orientation; std::vector _leapBalls; // private methods + void renderRaveGloveStage(); void renderHandSpheres(); void calculateGeometry(); }; From f21d2a477db893186f9e876e16a95380d189bfe6 Mon Sep 17 00:00:00 2001 From: Eric Johnston Date: Wed, 17 Jul 2013 08:29:50 -0700 Subject: [PATCH 49/81] Rave Glove Demo: Restructuring palm and finger data structures --- interface/src/Hand.cpp | 17 ++++--------- interface/src/Hand.h | 7 ++--- libraries/avatars/src/HandData.cpp | 24 ++++++++++++++++- libraries/avatars/src/HandData.h | 41 ++++++++++++++++++++++++++++++ 4 files changed, 71 insertions(+), 18 deletions(-) diff --git a/interface/src/Hand.cpp b/interface/src/Hand.cpp index d0ff0abd5a..80af40fbbb 100755 --- a/interface/src/Hand.cpp +++ b/interface/src/Hand.cpp @@ -21,9 +21,7 @@ Hand::Hand(Avatar* owningAvatar) : _owningAvatar(owningAvatar), _renderAlpha(1.0), _lookingInMirror(false), - _ballColor(0.0, 0.0, 0.4), - _position(0.0, 0.4, 0.0), - _orientation(0.0, 0.0, 0.0, 1.0) + _ballColor(0.0, 0.0, 0.4) { } @@ -42,23 +40,18 @@ void Hand::reset() { void Hand::simulate(float deltaTime, bool isMine) { } -glm::vec3 Hand::leapPositionToWorldPosition(const glm::vec3& leapPosition) { - float unitScale = 0.001; // convert mm to meters - return _position + _orientation * (leapPosition * unitScale); -} - void Hand::calculateGeometry() { - glm::vec3 offset(0.2, -0.2, -0.3); // place the hand in front of the face where we can see it + glm::vec3 handOffset(0.2, -0.2, -0.3); // place the hand in front of the face where we can see it Head& head = _owningAvatar->getHead(); - _position = head.getPosition() + head.getOrientation() * offset; - _orientation = head.getOrientation(); + _basePosition = head.getPosition() + head.getOrientation() * handOffset; + _baseOrientation = head.getOrientation(); int numLeapBalls = _fingerTips.size(); _leapBalls.resize(numLeapBalls); for (int i = 0; i < _fingerTips.size(); ++i) { - _leapBalls[i].rotation = _orientation; + _leapBalls[i].rotation = _baseOrientation; _leapBalls[i].position = leapPositionToWorldPosition(_fingerTips[i]); _leapBalls[i].radius = 0.01; _leapBalls[i].touchForce = 0.0; diff --git a/interface/src/Hand.h b/interface/src/Hand.h index e1b0dc9ff0..eb49703468 100755 --- a/interface/src/Hand.h +++ b/interface/src/Hand.h @@ -52,9 +52,6 @@ public: const glm::vec3& getLeapBallPosition (int ball) const { return _leapBalls[ball].position;} bool isRaveGloveActive () const { return _isRaveGloveActive; } - // position conversion - glm::vec3 leapPositionToWorldPosition(const glm::vec3& leapPosition); - private: // disallow copies of the Hand, copy of owning Avatar is disallowed too Hand(const Hand&); @@ -65,8 +62,8 @@ private: bool _lookingInMirror; bool _isRaveGloveActive; glm::vec3 _ballColor; - glm::vec3 _position; - glm::quat _orientation; +// glm::vec3 _position; +// glm::quat _orientation; std::vector _leapBalls; // private methods diff --git a/libraries/avatars/src/HandData.cpp b/libraries/avatars/src/HandData.cpp index 986d030a3c..1eba9d2e4d 100755 --- a/libraries/avatars/src/HandData.cpp +++ b/libraries/avatars/src/HandData.cpp @@ -9,7 +9,29 @@ #include "HandData.h" HandData::HandData(AvatarData* owningAvatar) : + _basePosition(0.0f, 0.0f, 0.0f), + _baseOrientation(0.0f, 0.0f, 0.0f, 1.0f), _owningAvatarData(owningAvatar) { - + for (int i = 0; i < 2; ++i) + _palms.push_back(PalmData(this)); +} + +PalmData::PalmData(HandData* owningHandData) : +_rawPosition(0, 0, 0), +_rawNormal(0, 1, 0), +_isActive(false), +_owningHandData(owningHandData) +{ + for (int i = 0; i < 5; ++i) + _fingers.push_back(FingerData(this, owningHandData)); +} + +FingerData::FingerData(PalmData* owningPalmData, HandData* owningHandData) : +_tipRawPosition(0, 0, 0), +_rootRawPosition(0, 0, 0), +_isActive(false), +_owningPalmData(owningPalmData), +_owningHandData(owningHandData) +{ } diff --git a/libraries/avatars/src/HandData.h b/libraries/avatars/src/HandData.h index 50a4843153..d32498a5a1 100755 --- a/libraries/avatars/src/HandData.h +++ b/libraries/avatars/src/HandData.h @@ -13,8 +13,11 @@ #include #include +#include class AvatarData; +class FingerData; +class PalmData; class HandData { public: @@ -31,17 +34,55 @@ public: void setHandPositions(const std::vector& handPositons) { _handPositions = handPositons; } void setHandNormals(const std::vector& handNormals) { _handNormals = handNormals; } + // position conversion + glm::vec3 leapPositionToWorldPosition(const glm::vec3& leapPosition) { + float unitScale = 0.001; // convert mm to meters + return _basePosition + _baseOrientation * (leapPosition * unitScale); + } + glm::vec3 leapDirectionToWorldDirection(const glm::vec3& leapDirection) { + return glm::normalize(_baseOrientation * leapDirection); + } + friend class AvatarData; protected: std::vector _fingerTips; std::vector _fingerRoots; std::vector _handPositions; std::vector _handNormals; + glm::vec3 _basePosition; // Hands are placed relative to this + glm::quat _baseOrientation; // Hands are placed relative to this AvatarData* _owningAvatarData; + std::vector _palms; private: // privatize copy ctor and assignment operator so copies of this object cannot be made HandData(const HandData&); HandData& operator= (const HandData&); }; +class FingerData { +public: + FingerData(PalmData* owningPalmData, HandData* owningHandData); +private: + glm::vec3 _tipRawPosition; + glm::vec3 _rootRawPosition; + bool _isActive; // This has current valid data + PalmData* _owningPalmData; + HandData* _owningHandData; +}; + +class PalmData { +public: + PalmData(HandData* owningHandData); + glm::vec3 getPosition() const { return _owningHandData->leapPositionToWorldPosition(_rawPosition); } + glm::vec3 getNormal() const { return _owningHandData->leapDirectionToWorldDirection(_rawNormal); } + const glm::vec3& getRawPosition() const { return _rawPosition; } + const glm::vec3& getRawNormal() const { return _rawNormal; } +private: + std::vector _fingers; + glm::vec3 _rawPosition; + glm::vec3 _rawNormal; + bool _isActive; // This has current valid data + HandData* _owningHandData; +}; + #endif /* defined(__hifi__HandData__) */ From 984332e63804da9c0329c96fcfc301abb0ad6935 Mon Sep 17 00:00:00 2001 From: Philip Rosedale Date: Wed, 17 Jul 2013 09:51:04 -0700 Subject: [PATCH 50/81] fixes per review --- interface/src/Audio.cpp | 8 +++++--- interface/src/Avatar.cpp | 3 ++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 9f82559512..41090584f3 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -620,13 +620,15 @@ void Audio::addProceduralSounds(int16_t* inputBuffer, const float COLLISION_SOUND_CUTOFF_LEVEL = 0.01f; const float COLLISION_SOUND_MAX_VOLUME = 1000.f; const float UP_MAJOR_FIFTH = powf(1.5f, 4.0f); + const float DOWN_TWO_OCTAVES = 4.f; + const float DOWN_FOUR_OCTAVES = 16.f; float t; if (_collisionSoundMagnitude > COLLISION_SOUND_CUTOFF_LEVEL) { for (int i = 0; i < numSamples; i++) { t = (float) _proceduralEffectSample + (float) i; sample = sinf(t * _collisionSoundFrequency) + - sinf(t * _collisionSoundFrequency / 4.f) + - sinf(t * _collisionSoundFrequency / 16.f * UP_MAJOR_FIFTH); + sinf(t * _collisionSoundFrequency / DOWN_TWO_OCTAVES) + + sinf(t * _collisionSoundFrequency / DOWN_FOUR_OCTAVES * UP_MAJOR_FIFTH); sample *= _collisionSoundMagnitude * COLLISION_SOUND_MAX_VOLUME; inputBuffer[i] += sample; outputLeft[i] += sample; @@ -638,7 +640,7 @@ void Audio::addProceduralSounds(int16_t* inputBuffer, } // -// Starts a collision sound. magnitude is 0-1, with 1 the loudest possible sound. +// Starts a collision sound. magnitude is 0-1, with 1 the loudest possible sound. // void Audio::startCollisionSound(float magnitude, float frequency, float noise, float duration) { _collisionSoundMagnitude = magnitude; diff --git a/interface/src/Avatar.cpp b/interface/src/Avatar.cpp index ee613f5758..e92394af22 100755 --- a/interface/src/Avatar.cpp +++ b/interface/src/Avatar.cpp @@ -881,12 +881,13 @@ void Avatar::updateCollisionWithEnvironment(float deltaTime) { const float ENVIRONMENT_SURFACE_ELASTICITY = 1.0f; const float ENVIRONMENT_SURFACE_DAMPING = 0.01; const float ENVIRONMENT_COLLISION_FREQUENCY = 0.05f; + const float VISIBLE_GROUND_COLLISION_VELOCITY = 0.2f; glm::vec3 penetration; if (Application::getInstance()->getEnvironment()->findCapsulePenetration( _position - up * (_pelvisFloatingHeight - radius), _position + up * (_height - _pelvisFloatingHeight - radius), radius, penetration)) { float velocityTowardCollision = glm::dot(_velocity, glm::normalize(penetration)); - if (velocityTowardCollision > 0.2) { + if (velocityTowardCollision > VISIBLE_GROUND_COLLISION_VELOCITY) { Application::getInstance()->setGroundPlaneImpact(1.0f); } updateCollisionSound(penetration, deltaTime, ENVIRONMENT_COLLISION_FREQUENCY); From 98dd83dde81b3c53229b662083af7ad3bee2273c Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Wed, 17 Jul 2013 10:02:23 -0700 Subject: [PATCH 51/81] ahibfasubhdf --- interface/src/Application.cpp | 6 ++- interface/src/Application.h | 8 +++- interface/src/Audio.cpp | 70 ++++++++++++++++++++++++++++------- interface/src/Audio.h | 16 ++++++-- interface/src/Avatar.cpp | 50 +++++++++++++++++++++++-- interface/src/Avatar.h | 7 +++- interface/src/Head.cpp | 6 ++- interface/src/Util.cpp | 34 ++++++++++++----- interface/src/Util.h | 5 ++- 9 files changed, 165 insertions(+), 37 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 0bd1826f6b..582bc4fcb4 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -195,6 +195,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : _isTouchPressed(false), _yawFromTouch(0.0f), _pitchFromTouch(0.0f), + _groundPlaneImpact(0.0f), _mousePressed(false), _mouseVoxelScale(1.0f / 1024.0f), _justEditedVoxel(false), @@ -2528,7 +2529,7 @@ void Application::displaySide(Camera& whichCamera) { //draw a grid ground plane.... if (_renderGroundPlaneOn->isChecked()) { - drawGroundPlaneGrid(EDGE_SIZE_GROUND_PLANE); + renderGroundPlaneGrid(EDGE_SIZE_GROUND_PLANE, _audio.getCollisionSoundMagnitude()); } // Draw voxels if (_renderVoxels->isChecked()) { @@ -2606,6 +2607,9 @@ void Application::displayOverlay() { glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); + // Display a single screen-size quad to + renderCollisionOverlay(_glWidget->width(), _glWidget->height(), _audio.getCollisionSoundMagnitude()); + #ifndef _WIN32 _audio.render(_glWidget->width(), _glWidget->height()); if (_oscilloscopeOn->isChecked()) { diff --git a/interface/src/Application.h b/interface/src/Application.h index 37411aa9d5..9333808a27 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -87,6 +87,7 @@ public: void updateParticleSystem(float deltaTime); Avatar* getAvatar() { return &_myAvatar; } + Audio* getAudio() { return &_audio; } Camera* getCamera() { return &_myCamera; } ViewFrustum* getViewFrustum() { return &_viewFrustum; } VoxelSystem* getVoxels() { return &_voxels; } @@ -103,6 +104,9 @@ public: QNetworkAccessManager* getNetworkAccessManager() { return _networkAccessManager; } GeometryCache* getGeometryCache() { return &_geometryCache; } + void setGroundPlaneImpact(float groundPlaneImpact) { _groundPlaneImpact = groundPlaneImpact; } + + private slots: void timer(); @@ -208,7 +212,7 @@ private: void deleteVoxelUnderCursor(); void eyedropperVoxelUnderCursor(); void resetSensors(); - + void setMenuShortcutsEnabled(bool enabled); void updateCursor(); @@ -348,6 +352,8 @@ private: float _yawFromTouch; float _pitchFromTouch; + float _groundPlaneImpact; + VoxelDetail _mouseVoxelDragging; glm::vec3 _voxelThrust; bool _mousePressed; // true if mouse has been pressed (clear when finished) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 4c707de938..41090584f3 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -76,9 +76,12 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o NodeList* nodeList = NodeList::getInstance(); Application* interface = Application::getInstance(); Avatar* interfaceAvatar = interface->getAvatar(); - + + memset(outputLeft, 0, PACKET_LENGTH_BYTES_PER_CHANNEL); + memset(outputRight, 0, PACKET_LENGTH_BYTES_PER_CHANNEL); + // Add Procedural effects to input samples - addProceduralSounds(inputLeft, BUFFER_LENGTH_SAMPLES_PER_CHANNEL); + addProceduralSounds(inputLeft, outputLeft, outputRight, BUFFER_LENGTH_SAMPLES_PER_CHANNEL); if (nodeList && inputLeft) { @@ -135,12 +138,8 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o + leadingBytes); } - } - - memset(outputLeft, 0, PACKET_LENGTH_BYTES_PER_CHANNEL); - memset(outputRight, 0, PACKET_LENGTH_BYTES_PER_CHANNEL); - + AudioRingBuffer* ringBuffer = &_ringBuffer; // if there is anything in the ring buffer, decide what to do: @@ -251,11 +250,11 @@ inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* o } } #ifndef TEST_AUDIO_LOOPBACK - outputLeft[s] = leftSample; - outputRight[s] = rightSample; + outputLeft[s] += leftSample; + outputRight[s] += rightSample; #else - outputLeft[s] = inputLeft[s]; - outputRight[s] = inputLeft[s]; + outputLeft[s] += inputLeft[s]; + outputRight[s] += inputLeft[s]; #endif } ringBuffer->setNextOutput(ringBuffer->getNextOutput() + PACKET_LENGTH_SAMPLES); @@ -333,7 +332,13 @@ Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples) : _lastYawMeasuredMaximum(0), _flangeIntensity(0.0f), _flangeRate(0.0f), - _flangeWeight(0.0f) + _flangeWeight(0.0f), + _collisionSoundMagnitude(0.0f), + _collisionSoundFrequency(0.0f), + _collisionSoundNoise(0.0f), + _collisionSoundDuration(0.0f), + _proceduralEffectSample(0), + _heartbeatMagnitude(0.0f) { outputPortAudioError(Pa_Initialize()); @@ -589,7 +594,10 @@ void Audio::lowPassFilter(int16_t* inputBuffer) { } // Take a pointer to the acquired microphone input samples and add procedural sounds -void Audio::addProceduralSounds(int16_t* inputBuffer, int numSamples) { +void Audio::addProceduralSounds(int16_t* inputBuffer, + int16_t* outputLeft, + int16_t* outputRight, + int numSamples) { const float MAX_AUDIBLE_VELOCITY = 6.0; const float MIN_AUDIBLE_VELOCITY = 0.1; const int VOLUME_BASELINE = 400; @@ -598,14 +606,48 @@ void Audio::addProceduralSounds(int16_t* inputBuffer, int numSamples) { float speed = glm::length(_lastVelocity); float volume = VOLUME_BASELINE * (1.f - speed / MAX_AUDIBLE_VELOCITY); + int sample; + + // + // Travelling noise + // // Add a noise-modulated sinewave with volume that tapers off with speed increasing if ((speed > MIN_AUDIBLE_VELOCITY) && (speed < MAX_AUDIBLE_VELOCITY)) { for (int i = 0; i < numSamples; i++) { - inputBuffer[i] += (int16_t)((sinf((float) i / SOUND_PITCH * speed) * randFloat()) * volume * speed); + inputBuffer[i] += (int16_t)(sinf((float) (_proceduralEffectSample + i) / SOUND_PITCH ) * volume * (1.f + randFloat() * 0.25f) * speed); } } + const float COLLISION_SOUND_CUTOFF_LEVEL = 0.01f; + const float COLLISION_SOUND_MAX_VOLUME = 1000.f; + const float UP_MAJOR_FIFTH = powf(1.5f, 4.0f); + const float DOWN_TWO_OCTAVES = 4.f; + const float DOWN_FOUR_OCTAVES = 16.f; + float t; + if (_collisionSoundMagnitude > COLLISION_SOUND_CUTOFF_LEVEL) { + for (int i = 0; i < numSamples; i++) { + t = (float) _proceduralEffectSample + (float) i; + sample = sinf(t * _collisionSoundFrequency) + + sinf(t * _collisionSoundFrequency / DOWN_TWO_OCTAVES) + + sinf(t * _collisionSoundFrequency / DOWN_FOUR_OCTAVES * UP_MAJOR_FIFTH); + sample *= _collisionSoundMagnitude * COLLISION_SOUND_MAX_VOLUME; + inputBuffer[i] += sample; + outputLeft[i] += sample; + outputRight[i] += sample; + _collisionSoundMagnitude *= _collisionSoundDuration; + } + } + _proceduralEffectSample += numSamples; } +// +// Starts a collision sound. magnitude is 0-1, with 1 the loudest possible sound. +// +void Audio::startCollisionSound(float magnitude, float frequency, float noise, float duration) { + _collisionSoundMagnitude = magnitude; + _collisionSoundFrequency = frequency; + _collisionSoundNoise = noise; + _collisionSoundDuration = duration; +} // ----------------------------------------------------------- // Accoustic ping (audio system round trip time determination) // ----------------------------------------------------------- diff --git a/interface/src/Audio.h b/interface/src/Audio.h index d11a14444a..37db447381 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -42,7 +42,11 @@ public: int getJitterBufferSamples() { return _jitterBufferSamples; }; void lowPassFilter(int16_t* inputBuffer); - + + void startCollisionSound(float magnitude, float frequency, float noise, float duration); + float getCollisionSoundMagnitude() { return _collisionSoundMagnitude; }; + + void ping(); // Call periodically to eventually perform round trip time analysis, @@ -80,7 +84,13 @@ private: float _flangeIntensity; float _flangeRate; float _flangeWeight; - + float _collisionSoundMagnitude; + float _collisionSoundFrequency; + float _collisionSoundNoise; + float _collisionSoundDuration; + int _proceduralEffectSample; + float _heartbeatMagnitude; + // Audio callback in class context. inline void performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* outputRight); @@ -92,7 +102,7 @@ private: inline void analyzePing(); // Add sounds that we want the user to not hear themselves, by adding on top of mic input signal - void addProceduralSounds(int16_t* inputBuffer, int numSamples); + void addProceduralSounds(int16_t* inputBuffer, int16_t* outputLeft, int16_t* outputRight, int numSamples); // Audio callback called by portaudio. Calls 'performIO'. diff --git a/interface/src/Avatar.cpp b/interface/src/Avatar.cpp index 15ef875c75..e92394af22 100644 --- a/interface/src/Avatar.cpp +++ b/interface/src/Avatar.cpp @@ -546,8 +546,8 @@ void Avatar::simulate(float deltaTime, Transmitter* transmitter) { _position += _scale * _gravity * (GRAVITY_EARTH * deltaTime) * deltaTime; } - updateCollisionWithEnvironment(); - updateCollisionWithVoxels(); + updateCollisionWithEnvironment(deltaTime); + updateCollisionWithVoxels(deltaTime); updateAvatarCollisions(deltaTime); } @@ -874,29 +874,41 @@ void Avatar::updateCollisionWithSphere(glm::vec3 position, float radius, float d } } -void Avatar::updateCollisionWithEnvironment() { +void Avatar::updateCollisionWithEnvironment(float deltaTime) { glm::vec3 up = getBodyUpDirection(); float radius = _height * 0.125f; const float ENVIRONMENT_SURFACE_ELASTICITY = 1.0f; const float ENVIRONMENT_SURFACE_DAMPING = 0.01; + const float ENVIRONMENT_COLLISION_FREQUENCY = 0.05f; + const float VISIBLE_GROUND_COLLISION_VELOCITY = 0.2f; glm::vec3 penetration; if (Application::getInstance()->getEnvironment()->findCapsulePenetration( _position - up * (_pelvisFloatingHeight - radius), _position + up * (_height - _pelvisFloatingHeight - radius), radius, penetration)) { + float velocityTowardCollision = glm::dot(_velocity, glm::normalize(penetration)); + if (velocityTowardCollision > VISIBLE_GROUND_COLLISION_VELOCITY) { + Application::getInstance()->setGroundPlaneImpact(1.0f); + } + updateCollisionSound(penetration, deltaTime, ENVIRONMENT_COLLISION_FREQUENCY); + applyHardCollision(penetration, ENVIRONMENT_SURFACE_ELASTICITY, ENVIRONMENT_SURFACE_DAMPING); + + } } -void Avatar::updateCollisionWithVoxels() { +void Avatar::updateCollisionWithVoxels(float deltaTime) { float radius = _height * 0.125f; const float VOXEL_ELASTICITY = 1.4f; const float VOXEL_DAMPING = 0.0; + const float VOXEL_COLLISION_FREQUENCY = 0.5f; glm::vec3 penetration; if (Application::getInstance()->getVoxels()->findCapsulePenetration( _position - glm::vec3(0.0f, _pelvisFloatingHeight - radius, 0.0f), _position + glm::vec3(0.0f, _height - _pelvisFloatingHeight - radius, 0.0f), radius, penetration)) { + updateCollisionSound(penetration, deltaTime, VOXEL_COLLISION_FREQUENCY); applyHardCollision(penetration, VOXEL_ELASTICITY, VOXEL_DAMPING); } } @@ -925,6 +937,36 @@ void Avatar::applyHardCollision(const glm::vec3& penetration, float elasticity, } } +void Avatar::updateCollisionSound(const glm::vec3 &penetration, float deltaTime, float frequency) { + // consider whether to have the collision make a sound + const float AUDIBLE_COLLISION_THRESHOLD = 0.02f; + const float COLLISION_LOUDNESS = 1.f; + const float DURATION_SCALING = 0.004f; + const float NOISE_SCALING = 0.1f; + glm::vec3 velocity = _velocity; + glm::vec3 gravity = getGravity(); + + if (glm::length(gravity) > EPSILON) { + // If gravity is on, remove the effect of gravity on velocity for this + // frame, so that we are not constantly colliding with the surface + velocity -= _scale * glm::length(gravity) * GRAVITY_EARTH * deltaTime * glm::normalize(gravity); + } + float velocityTowardCollision = glm::dot(velocity, glm::normalize(penetration)); + float velocityTangentToCollision = glm::length(velocity) - velocityTowardCollision; + + if (velocityTowardCollision > AUDIBLE_COLLISION_THRESHOLD) { + // Volume is proportional to collision velocity + // Base frequency is modified upward by the angle of the collision + // Noise is a function of the angle of collision + // Duration of the sound is a function of both base frequency and velocity of impact + Application::getInstance()->getAudio()->startCollisionSound( + fmin(COLLISION_LOUDNESS * velocityTowardCollision, 1.f), + frequency * (1.f + velocityTangentToCollision / velocityTowardCollision), + fmin(velocityTangentToCollision / velocityTowardCollision * NOISE_SCALING, 1.f), + 1.f - DURATION_SCALING * powf(frequency, 0.5f) / velocityTowardCollision); + } +} + void Avatar::updateAvatarCollisions(float deltaTime) { // Reset detector for nearest avatar diff --git a/interface/src/Avatar.h b/interface/src/Avatar.h index f41094173c..61207a2d8b 100755 --- a/interface/src/Avatar.h +++ b/interface/src/Avatar.h @@ -162,6 +162,8 @@ public: glm::quat getOrientation () const; glm::quat getWorldAlignedOrientation() const; + glm::vec3 getGravity () const { return _gravity; } + glm::vec3 getUprightHeadPosition() const; AvatarVoxelSystem* getVoxels() { return &_voxels; } @@ -262,9 +264,10 @@ private: void updateAvatarCollisions(float deltaTime); void updateArmIKAndConstraints( float deltaTime ); void updateCollisionWithSphere( glm::vec3 position, float radius, float deltaTime ); - void updateCollisionWithEnvironment(); - void updateCollisionWithVoxels(); + void updateCollisionWithEnvironment(float deltaTime); + void updateCollisionWithVoxels(float deltaTime); void applyHardCollision(const glm::vec3& penetration, float elasticity, float damping); + void updateCollisionSound(const glm::vec3& penetration, float deltaTime, float frequency); void applyCollisionWithOtherAvatar( Avatar * other, float deltaTime ); void checkForMouseRayTouching(); }; diff --git a/interface/src/Head.cpp b/interface/src/Head.cpp index 131e0968cc..84ae9fffe9 100644 --- a/interface/src/Head.cpp +++ b/interface/src/Head.cpp @@ -227,7 +227,8 @@ void Head::simulate(float deltaTime, bool isMine) { const float CAMERA_FOLLOW_HEAD_RATE_MAX = 0.5f; const float CAMERA_FOLLOW_HEAD_RATE_RAMP_RATE = 1.05f; const float CAMERA_STOP_TOLERANCE_DEGREES = 0.1f; - const float CAMERA_START_TOLERANCE_DEGREES = 2.0f; + const float CAMERA_PITCH_START_TOLERANCE_DEGREES = 10.0f; + const float CAMERA_YAW_START_TOLERANCE_DEGREES = 3.0f; float cameraHeadAngleDifference = glm::length(glm::vec2(_pitch - _cameraPitch, _yaw - _cameraYaw)); if (_isCameraMoving) { _cameraFollowHeadRate = glm::clamp(_cameraFollowHeadRate * CAMERA_FOLLOW_HEAD_RATE_RAMP_RATE, @@ -240,7 +241,8 @@ void Head::simulate(float deltaTime, bool isMine) { _isCameraMoving = false; } } else { - if (cameraHeadAngleDifference > CAMERA_START_TOLERANCE_DEGREES) { + if ((fabs(_pitch - _cameraPitch) > CAMERA_PITCH_START_TOLERANCE_DEGREES) || + (fabs(_yaw - _cameraYaw) > CAMERA_YAW_START_TOLERANCE_DEGREES)) { _isCameraMoving = true; _cameraFollowHeadRate = CAMERA_FOLLOW_HEAD_RATE_START; } diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 20f33f924a..6aff15240e 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -325,22 +325,38 @@ void drawvec3(int x, int y, float scale, float rotate, float thick, int mono, gl glPopMatrix(); } +void renderCollisionOverlay(int width, int height, float magnitude) { + const float MIN_VISIBLE_COLLISION = 0.01f; + if (magnitude > MIN_VISIBLE_COLLISION) { + glColor4f(0, 0, 0, magnitude); + glBegin(GL_QUADS); + glVertex2f(0, 0); + glVertex2d(width, 0); + glVertex2d(width, height); + glVertex2d(0, height); + glEnd(); + } +} -void drawGroundPlaneGrid(float size) { - glColor3f(0.4f, 0.5f, 0.3f); +void renderGroundPlaneGrid(float size, float impact) { glLineWidth(2.0); - + glm::vec4 impactColor(1, 0, 0, 1); + glm::vec3 lineColor(0.4, 0.5, 0.3); + glm::vec4 surfaceColor(0.5, 0.5, 0.5, 0.4); + + glColor3fv(&lineColor.x); for (float x = 0; x <= size; x++) { glBegin(GL_LINES); - glVertex3f(x, 0.0f, 0); - glVertex3f(x, 0.0f, size); - glVertex3f(0, 0.0f, x); - glVertex3f(size, 0.0f, x); + glVertex3f(x, 0, 0); + glVertex3f(x, 0, size); + glVertex3f(0, 0, x); + glVertex3f(size, 0, x); glEnd(); } - // Draw a translucent quad just underneath the grid. - glColor4f(0.5, 0.5, 0.5, 0.4); + // Draw the floor, colored for recent impact + glm::vec4 floorColor = impact * impactColor + (1.f - impact) * surfaceColor; + glColor4fv(&floorColor.x); glBegin(GL_QUADS); glVertex3f(0, 0, 0); glVertex3f(size, 0, 0); diff --git a/interface/src/Util.h b/interface/src/Util.h index 37bd0595ec..8bc77a98ea 100644 --- a/interface/src/Util.h +++ b/interface/src/Util.h @@ -57,7 +57,10 @@ glm::quat safeMix(const glm::quat& q1, const glm::quat& q2, float alpha); double diffclock(timeval *clock1,timeval *clock2); -void drawGroundPlaneGrid(float size); +void renderGroundPlaneGrid(float size, float impact); + +void renderCollisionOverlay(int width, int height, float magnitude); + void renderDiskShadow(glm::vec3 position, glm::vec3 upDirection, float radius, float darkness); From c33e4fe6f7860d70033c8e25587bbf931571dee5 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Wed, 17 Jul 2013 10:15:42 -0700 Subject: [PATCH 52/81] file mode reverts --- interface/src/Avatar.cpp | 0 interface/src/LeapManager.cpp | 0 2 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 interface/src/Avatar.cpp mode change 100644 => 100755 interface/src/LeapManager.cpp diff --git a/interface/src/Avatar.cpp b/interface/src/Avatar.cpp old mode 100644 new mode 100755 diff --git a/interface/src/LeapManager.cpp b/interface/src/LeapManager.cpp old mode 100644 new mode 100755 From a501659083610b29673c30172a09c229571566a2 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Wed, 17 Jul 2013 10:16:30 -0700 Subject: [PATCH 53/81] change mode of HandData to 644 --- libraries/avatars/src/HandData.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 libraries/avatars/src/HandData.cpp diff --git a/libraries/avatars/src/HandData.cpp b/libraries/avatars/src/HandData.cpp old mode 100755 new mode 100644 From 2147a823986c8f7c89271a99b07ae667bc748da3 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Wed, 17 Jul 2013 10:16:45 -0700 Subject: [PATCH 54/81] change mode of HandData.cpp to 755 --- libraries/avatars/src/HandData.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 libraries/avatars/src/HandData.cpp diff --git a/libraries/avatars/src/HandData.cpp b/libraries/avatars/src/HandData.cpp old mode 100644 new mode 100755 From 1aa06116c244f30e9f318bb4798f8ed43ede6ed5 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Wed, 17 Jul 2013 10:17:12 -0700 Subject: [PATCH 55/81] change mode of HandData.h to 755 --- libraries/avatars/src/HandData.h | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 libraries/avatars/src/HandData.h diff --git a/libraries/avatars/src/HandData.h b/libraries/avatars/src/HandData.h old mode 100644 new mode 100755 From 9e9b379d66c357cfdd58d77c8a0ddaefb733ae8c Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jul 2013 11:49:42 -0700 Subject: [PATCH 56/81] Fix crashing bug in voxel-server related to animation - added VoxelNodeDeleteHook mechanism that allows users of VoxelNode to register for delete notification call backs - added call back to VoxelNodeBag to remove and nodes from bags when the nodes get deleted. --- libraries/voxels/src/VoxelNode.cpp | 43 +++++++++++++++++++++ libraries/voxels/src/VoxelNode.h | 55 +++++++++++++++++---------- libraries/voxels/src/VoxelNodeBag.cpp | 14 +++++++ libraries/voxels/src/VoxelNodeBag.h | 9 ++--- voxel-server/src/main.cpp | 1 - 5 files changed, 95 insertions(+), 27 deletions(-) diff --git a/libraries/voxels/src/VoxelNode.cpp b/libraries/voxels/src/VoxelNode.cpp index 76fae500dd..1268449ac6 100644 --- a/libraries/voxels/src/VoxelNode.cpp +++ b/libraries/voxels/src/VoxelNode.cpp @@ -54,6 +54,8 @@ void VoxelNode::init(unsigned char * octalCode) { } VoxelNode::~VoxelNode() { + notifyDeleteHooks(); + delete[] _octalCode; // delete all of this node's children @@ -387,3 +389,44 @@ float VoxelNode::distanceToPoint(const glm::vec3& point) const { float distance = sqrtf(glm::dot(temp, temp)); return distance; } + +VoxelNodeDeleteHook VoxelNode::_hooks[VOXEL_NODE_MAX_DELETE_HOOKS]; +void* VoxelNode::_hooksExtraData[VOXEL_NODE_MAX_DELETE_HOOKS]; +int VoxelNode::_hooksInUse = 0; + +int VoxelNode::addDeleteHook(VoxelNodeDeleteHook hook, void* extraData) { + // If first use, initialize the _hooks array + if (_hooksInUse == 0) { + memset(_hooks, 0, sizeof(_hooks)); + memset(_hooksExtraData, 0, sizeof(_hooksExtraData)); + } + // find first available slot + for (int i = 0; i < VOXEL_NODE_MAX_DELETE_HOOKS; i++) { + if (!_hooks[i]) { + _hooks[i] = hook; + _hooksExtraData[i] = extraData; + _hooksInUse++; + return i; + } + } + // if we got here, then we're out of room in our hooks, return error + return VOXEL_NODE_NO_MORE_HOOKS_AVAILABLE; +} + +void VoxelNode::removeDeleteHook(int hookID) { + if (_hooks[hookID]) { + _hooks[hookID] = NULL; + _hooksExtraData[hookID] = NULL; + _hooksInUse--; + } +} + +void VoxelNode::notifyDeleteHooks() { + if (_hooksInUse > 0) { + for (int i = 0; i < VOXEL_NODE_MAX_DELETE_HOOKS; i++) { + if (_hooks[i]) { + _hooks[i](this, _hooksExtraData[i]); + } + } + } +} diff --git a/libraries/voxels/src/VoxelNode.h b/libraries/voxels/src/VoxelNode.h index 8e3b9cb5db..431592c2f9 100644 --- a/libraries/voxels/src/VoxelNode.h +++ b/libraries/voxels/src/VoxelNode.h @@ -15,33 +15,19 @@ #include "VoxelConstants.h" class VoxelTree; // forward delclaration +class VoxelNode; // forward delclaration typedef unsigned char colorPart; typedef unsigned char nodeColor[4]; typedef unsigned char rgbColor[3]; +// Callback function, for delete hook +typedef void (*VoxelNodeDeleteHook)(VoxelNode* node, void* extraData); +const int VOXEL_NODE_MAX_DELETE_HOOKS = 100; +const int VOXEL_NODE_NO_MORE_HOOKS_AVAILABLE = -1; + + class VoxelNode { -private: - nodeColor _trueColor; -#ifndef NO_FALSE_COLOR // !NO_FALSE_COLOR means, does have false color - nodeColor _currentColor; - bool _falseColored; -#endif - glBufferIndex _glBufferIndex; - bool _isDirty; - uint64_t _lastChanged; - bool _shouldRender; - bool _isStagedForDeletion; - AABox _box; - unsigned char* _octalCode; - VoxelNode* _children[8]; - int _childCount; - float _density; // If leaf: density = 1, if internal node: 0-1 density of voxels inside - - void calculateAABox(); - - void init(unsigned char * octalCode); - public: VoxelNode(); // root node constructor VoxelNode(unsigned char * octalCode); // regular constructor @@ -118,6 +104,33 @@ public: const nodeColor& getTrueColor() const { return _trueColor; }; const nodeColor& getColor() const { return _trueColor; }; #endif + + static int addDeleteHook(VoxelNodeDeleteHook hook, void* extraData = NULL); + static void removeDeleteHook(int hookID); +private: + void calculateAABox(); + void init(unsigned char * octalCode); + void notifyDeleteHooks(); + + nodeColor _trueColor; +#ifndef NO_FALSE_COLOR // !NO_FALSE_COLOR means, does have false color + nodeColor _currentColor; + bool _falseColored; +#endif + glBufferIndex _glBufferIndex; + bool _isDirty; + uint64_t _lastChanged; + bool _shouldRender; + bool _isStagedForDeletion; + AABox _box; + unsigned char* _octalCode; + VoxelNode* _children[8]; + int _childCount; + float _density; // If leaf: density = 1, if internal node: 0-1 density of voxels inside + + static VoxelNodeDeleteHook _hooks[VOXEL_NODE_MAX_DELETE_HOOKS]; + static void* _hooksExtraData[VOXEL_NODE_MAX_DELETE_HOOKS]; + static int _hooksInUse; }; #endif /* defined(__hifi__VoxelNode__) */ diff --git a/libraries/voxels/src/VoxelNodeBag.cpp b/libraries/voxels/src/VoxelNodeBag.cpp index 20a469dec8..4f355116e4 100644 --- a/libraries/voxels/src/VoxelNodeBag.cpp +++ b/libraries/voxels/src/VoxelNodeBag.cpp @@ -9,7 +9,15 @@ #include "VoxelNodeBag.h" #include +VoxelNodeBag::VoxelNodeBag() : + _bagElements(NULL), + _elementsInUse(0), + _sizeOfElementsArray(0) { + _hookID = VoxelNode::addDeleteHook(voxelNodeDeleteHook, (void*)this); +}; + VoxelNodeBag::~VoxelNodeBag() { + VoxelNode::removeDeleteHook(_hookID); deleteAll(); } @@ -118,3 +126,9 @@ void VoxelNodeBag::remove(VoxelNode* node) { } } +void VoxelNodeBag::voxelNodeDeleteHook(VoxelNode* node, void* extraData) { + VoxelNodeBag* theBag = (VoxelNodeBag*)extraData; + theBag->remove(node); // note: remove can safely handle nodes that aren't in it, so we don't need to check contains() +} + + diff --git a/libraries/voxels/src/VoxelNodeBag.h b/libraries/voxels/src/VoxelNodeBag.h index ee6e5045d0..27bd4e5b60 100644 --- a/libraries/voxels/src/VoxelNodeBag.h +++ b/libraries/voxels/src/VoxelNodeBag.h @@ -19,11 +19,7 @@ class VoxelNodeBag { public: - VoxelNodeBag() : - _bagElements(NULL), - _elementsInUse(0), - _sizeOfElementsArray(0) {}; - + VoxelNodeBag(); ~VoxelNodeBag(); void insert(VoxelNode* node); // put a node into the bag @@ -36,11 +32,14 @@ public: void deleteAll(); + static void voxelNodeDeleteHook(VoxelNode* node, void* extraData); + private: VoxelNode** _bagElements; int _elementsInUse; int _sizeOfElementsArray; + int _hookID; }; #endif /* defined(__hifi__VoxelNodeBag__) */ diff --git a/voxel-server/src/main.cpp b/voxel-server/src/main.cpp index 5f5befafa6..f171d9b168 100644 --- a/voxel-server/src/main.cpp +++ b/voxel-server/src/main.cpp @@ -384,7 +384,6 @@ void attachVoxelNodeDataToNode(Node* newNode) { } int main(int argc, const char * argv[]) { - pthread_mutex_init(&::treeLock, NULL); qInstallMsgHandler(sharedMessageHandler); From 74eaf72d5301036714d1831ad13e5e6d64dc9d98 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jul 2013 11:52:50 -0700 Subject: [PATCH 57/81] removed bogus code that related to server crash --- libraries/voxels/src/VoxelTree.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index 6ef9f293ee..91a31a6cd1 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -1011,12 +1011,6 @@ int VoxelTree::encodeTreeBitstream(VoxelNode* node, unsigned char* outputBuffer, // How many bytes have we written so far at this level; int bytesWritten = 0; - // These two cases should not ever happen... but if they do, we don't want to crash. - if (!node || !node->getOctalCode()) { - qDebug("VoxelTree::encodeTreeBitstream() BAD VoxelNode! Bailing!"); - return bytesWritten; - } - // If we're at a node that is out of view, then we can return, because no nodes below us will be in view! if (params.viewFrustum && !node->isInView(*params.viewFrustum)) { return bytesWritten; From 46c5383d10a8acf4757a26157560f1c5f8051fca Mon Sep 17 00:00:00 2001 From: Eric Johnston Date: Wed, 17 Jul 2013 12:54:44 -0700 Subject: [PATCH 58/81] minor cleanup --- interface/src/Hand.h | 4 ---- libraries/avatars/src/HandData.cpp | 2 +- libraries/avatars/src/HandData.h | 2 ++ 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/interface/src/Hand.h b/interface/src/Hand.h index 44c7345100..fb6b863458 100755 --- a/interface/src/Hand.h +++ b/interface/src/Hand.h @@ -19,8 +19,6 @@ #include #include -const int NUM_FINGERS_PER_HAND = 5; - class Avatar; class ProgramObject; @@ -68,8 +66,6 @@ private: bool _lookingInMirror; bool _isRaveGloveActive; glm::vec3 _ballColor; -// glm::vec3 _position; -// glm::quat _orientation; std::vector _leapBalls; bool _particleSystemInitialized; diff --git a/libraries/avatars/src/HandData.cpp b/libraries/avatars/src/HandData.cpp index 1eba9d2e4d..a4e8e9560c 100755 --- a/libraries/avatars/src/HandData.cpp +++ b/libraries/avatars/src/HandData.cpp @@ -23,7 +23,7 @@ _rawNormal(0, 1, 0), _isActive(false), _owningHandData(owningHandData) { - for (int i = 0; i < 5; ++i) + for (int i = 0; i < NUM_FINGERS_PER_HAND; ++i) _fingers.push_back(FingerData(this, owningHandData)); } diff --git a/libraries/avatars/src/HandData.h b/libraries/avatars/src/HandData.h index d32498a5a1..ef322261c5 100755 --- a/libraries/avatars/src/HandData.h +++ b/libraries/avatars/src/HandData.h @@ -19,6 +19,8 @@ class AvatarData; class FingerData; class PalmData; +const int NUM_FINGERS_PER_HAND = 5; + class HandData { public: HandData(AvatarData* owningAvatar); From 5a0fcb7f6c2ed9a060c35ab72880b36657e020af Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Wed, 17 Jul 2013 13:47:18 -0700 Subject: [PATCH 59/81] adding more behavior to the particle system --- interface/src/Application.cpp | 4 +- interface/src/Hand.cpp | 24 ++-- interface/src/ParticleSystem.cpp | 185 ++++++++++++++++++++----------- interface/src/ParticleSystem.h | 32 +++--- 4 files changed, 148 insertions(+), 97 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 582bc4fcb4..dc57e83a4e 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2022,7 +2022,7 @@ void Application::update(float deltaTime) { if (_myAvatar.getMode() == AVATAR_MODE_WALKING) { _handControl.stop(); } - + // Update from Touch if (_isTouchPressed) { float TOUCH_YAW_SCALE = -50.0f; @@ -3562,7 +3562,7 @@ void Application::updateParticleSystem(float deltaTime) { attributes.gravity = 0.0f; } - _particleSystem.setParticleAttributesForEmitter(_coolDemoParticleEmitter, attributes); + _particleSystem.setParticleAttributes(_coolDemoParticleEmitter, attributes); } _particleSystem.setUpDirection(glm::vec3(0.0f, 1.0f, 0.0f)); diff --git a/interface/src/Hand.cpp b/interface/src/Hand.cpp index 13365ca8ec..8981819fe5 100755 --- a/interface/src/Hand.cpp +++ b/interface/src/Hand.cpp @@ -178,7 +178,7 @@ void Hand::updateFingerParticles(float deltaTime) { if (!_particleSystemInitialized) { for ( int f = 0; f< NUM_FINGERS_PER_HAND; f ++ ) { _fingerParticleEmitter[f] = _particleSystem.addEmitter(); - _particleSystem.setShowingEmitter(_fingerParticleEmitter[f], true); + //_particleSystem.setShowingEmitter(_fingerParticleEmitter[f], true); } _particleSystemInitialized = true; } else { @@ -193,23 +193,23 @@ void Hand::updateFingerParticles(float deltaTime) { glm::vec3 particleEmitterPosition = leapPositionToWorldPosition(_fingerTips[f]); - // this aspect is still being designed.... - - glm::vec3 tilt = glm::vec3 - ( - 30.0f * sinf( t * 0.55f ), - 0.0f, - 30.0f * cosf( t * 0.75f ) - ); - - glm::quat particleEmitterRotation = glm::quat(glm::radians(tilt)); + glm::vec3 fingerDirection = particleEmitterPosition - leapPositionToWorldPosition(_fingerRoots[f]); + float fingerLength = glm::length(fingerDirection); + + if (fingerLength > 0.0f) { + fingerDirection /= fingerLength; + } else { + fingerDirection = IDENTITY_UP; + } + + glm::quat particleEmitterRotation = rotationBetween(IDENTITY_UP, fingerDirection); _particleSystem.setEmitterPosition(_fingerParticleEmitter[0], particleEmitterPosition); _particleSystem.setEmitterRotation(_fingerParticleEmitter[0], particleEmitterRotation); float radius = 0.005f; glm::vec4 color(1.0f, 0.6f, 0.0f, 0.5f); - glm::vec3 velocity(0.0f, 0.005f, 0.0f); + glm::vec3 velocity = fingerDirection * 0.005f; float lifespan = 0.3f; _particleSystem.emitParticlesNow(_fingerParticleEmitter[0], 1, radius, color, velocity, lifespan); } diff --git a/interface/src/ParticleSystem.cpp b/interface/src/ParticleSystem.cpp index fcc24a2663..bd364959d3 100644 --- a/interface/src/ParticleSystem.cpp +++ b/interface/src/ParticleSystem.cpp @@ -16,29 +16,31 @@ const float DEFAULT_PARTICLE_AIR_FRICTION = 2.0f; ParticleSystem::ParticleSystem() { - _timer = 0.0f; _numEmitters = 0; _numParticles = 0; _upDirection = glm::vec3(0.0f, 1.0f, 0.0f); // default for (unsigned int e = 0; e < MAX_EMITTERS; e++) { - _emitter[e].position = glm::vec3(0.0f, 0.0f, 0.0f); - _emitter[e].rotation = glm::quat(); - _emitter[e].right = IDENTITY_RIGHT; - _emitter[e].up = IDENTITY_UP; - _emitter[e].front = IDENTITY_FRONT; - _emitter[e].showingEmitter = false; - _emitter[e].particleAttributes.bounce = DEFAULT_PARTICLE_BOUNCE; - _emitter[e].particleAttributes.airFriction = DEFAULT_PARTICLE_AIR_FRICTION; - _emitter[e].particleAttributes.gravity = 0.0f; - _emitter[e].particleAttributes.jitter = 0.0f; - _emitter[e].particleAttributes.emitterAttraction = 0.0f; - _emitter[e].particleAttributes.tornadoForce = 0.0f; - _emitter[e].particleAttributes.neighborAttraction = 0.0f; - _emitter[e].particleAttributes.neighborRepulsion = 0.0f; - _emitter[e].particleAttributes.collisionSphereRadius = 0.0f; - _emitter[e].particleAttributes.collisionSpherePosition = glm::vec3(0.0f, 0.0f, 0.0f); - _emitter[e].particleAttributes.usingCollisionSphere = false; + _emitter[e].position = glm::vec3(0.0f, 0.0f, 0.0f); + _emitter[e].rotation = glm::quat(); + _emitter[e].right = IDENTITY_RIGHT; + _emitter[e].up = IDENTITY_UP; + _emitter[e].front = IDENTITY_FRONT; + _emitter[e].visible = false; + + for (int s = 0; s _particle[p].lifespan) { + killParticle(p); + } else { + updateParticle(p, deltaTime); + } } } } + void ParticleSystem::updateEmitter(int e, float deltaTime) { _emitter[e].front = _emitter[e].rotation * IDENTITY_FRONT; @@ -146,45 +152,54 @@ void ParticleSystem::setOrangeBlueColorPalette() { } -void ParticleSystem::setParticleAttributesForEmitter(int emitterIndex, ParticleAttributes attributes) { +void ParticleSystem::setParticleAttributes(int emitterIndex, ParticleAttributes attributes) { - _emitter[emitterIndex].particleAttributes.bounce = attributes.bounce; - _emitter[emitterIndex].particleAttributes.gravity = attributes.gravity; - _emitter[emitterIndex].particleAttributes.airFriction = attributes.airFriction; - _emitter[emitterIndex].particleAttributes.jitter = attributes.jitter; - _emitter[emitterIndex].particleAttributes.emitterAttraction = attributes.emitterAttraction; - _emitter[emitterIndex].particleAttributes.tornadoForce = attributes.tornadoForce; - _emitter[emitterIndex].particleAttributes.neighborAttraction = attributes.neighborAttraction; - _emitter[emitterIndex].particleAttributes.neighborRepulsion = attributes.neighborRepulsion; - _emitter[emitterIndex].particleAttributes.usingCollisionSphere = attributes.usingCollisionSphere; - _emitter[emitterIndex].particleAttributes.collisionSpherePosition = attributes.collisionSpherePosition; - _emitter[emitterIndex].particleAttributes.collisionSphereRadius = attributes.collisionSphereRadius; + for (int lifeStage = 0; lifeStage < NUM_PARTICLE_LIFE_STAGES; lifeStage ++ ) { + setParticleAttributes(emitterIndex, lifeStage, attributes); + } } +void ParticleSystem::setParticleAttributes(int emitterIndex, int lifeStage, ParticleAttributes attributes) { + + ParticleAttributes * a = &_emitter[emitterIndex].particleAttributes[lifeStage]; + + a->bounce = attributes.bounce; + a->gravity = attributes.gravity; + a->airFriction = attributes.airFriction; + a->jitter = attributes.jitter; + a->emitterAttraction = attributes.emitterAttraction; + a->tornadoForce = attributes.tornadoForce; + a->neighborAttraction = attributes.neighborAttraction; + a->neighborRepulsion = attributes.neighborRepulsion; + a->usingCollisionSphere = attributes.usingCollisionSphere; + a->collisionSpherePosition = attributes.collisionSpherePosition; + a->collisionSphereRadius = attributes.collisionSphereRadius; +} void ParticleSystem::updateParticle(int p, float deltaTime) { - _particle[p].age += deltaTime; + assert(_particle[p].age <= _particle[p].lifespan); + + float ageFraction = _particle[p].age / _particle[p].lifespan; - if (_particle[p].age > _particle[p].lifespan) { - killParticle(p); - } + int lifeStage = (int)( ageFraction * NUM_PARTICLE_LIFE_STAGES ); Emitter myEmitter = _emitter[_particle[p].emitterIndex]; // apply random jitter + float j = myEmitter.particleAttributes[lifeStage].jitter; _particle[p].velocity += glm::vec3 ( - -myEmitter.particleAttributes.jitter * ONE_HALF + myEmitter.particleAttributes.jitter * randFloat(), - -myEmitter.particleAttributes.jitter * ONE_HALF + myEmitter.particleAttributes.jitter * randFloat(), - -myEmitter.particleAttributes.jitter * ONE_HALF + myEmitter.particleAttributes.jitter * randFloat() + -j * ONE_HALF + j * randFloat(), + -j * ONE_HALF + j * randFloat(), + -j * ONE_HALF + j * randFloat() ) * deltaTime; // apply attraction to home position glm::vec3 vectorToHome = myEmitter.position - _particle[p].position; - _particle[p].velocity += vectorToHome * myEmitter.particleAttributes.emitterAttraction * deltaTime; + _particle[p].velocity += vectorToHome * myEmitter.particleAttributes[lifeStage].emitterAttraction * deltaTime; // apply neighbor attraction int neighbor = p + 1; @@ -195,20 +210,20 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { if ( _particle[neighbor].emitterIndex == _particle[p].emitterIndex) { glm::vec3 vectorToNeighbor = _particle[p].position - _particle[neighbor].position; - _particle[p].velocity -= vectorToNeighbor * myEmitter.particleAttributes.neighborAttraction * deltaTime; + _particle[p].velocity -= vectorToNeighbor * myEmitter.particleAttributes[lifeStage].neighborAttraction * deltaTime; float distanceToNeighbor = glm::length(vectorToNeighbor); if (distanceToNeighbor > 0.0f) { - _particle[neighbor].velocity += (vectorToNeighbor / ( 1.0f + distanceToNeighbor * distanceToNeighbor)) * myEmitter.particleAttributes.neighborRepulsion * deltaTime; + _particle[neighbor].velocity += (vectorToNeighbor / ( 1.0f + distanceToNeighbor * distanceToNeighbor)) * myEmitter.particleAttributes[lifeStage].neighborRepulsion * deltaTime; } } // apply tornado force glm::vec3 tornadoDirection = glm::cross(vectorToHome, myEmitter.up); - _particle[p].velocity += tornadoDirection * myEmitter.particleAttributes.tornadoForce * deltaTime; + _particle[p].velocity += tornadoDirection * myEmitter.particleAttributes[lifeStage].tornadoForce * deltaTime; // apply air friction - float drag = 1.0 - myEmitter.particleAttributes.airFriction * deltaTime; + float drag = 1.0 - myEmitter.particleAttributes[lifeStage].airFriction * deltaTime; if (drag < 0.0f) { _particle[p].velocity = glm::vec3(0.0f, 0.0f, 0.0f); } else { @@ -216,7 +231,7 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { } // apply gravity - _particle[p].velocity -= _upDirection * myEmitter.particleAttributes.gravity * deltaTime; + _particle[p].velocity -= _upDirection * myEmitter.particleAttributes[lifeStage].gravity * deltaTime; // update position by velocity _particle[p].position += _particle[p].velocity; @@ -226,36 +241,42 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { _particle[p].position.y = _particle[p].radius; if (_particle[p].velocity.y < 0.0f) { - _particle[p].velocity.y *= -myEmitter.particleAttributes.bounce; + _particle[p].velocity.y *= -myEmitter.particleAttributes[lifeStage].bounce; } } // collision with sphere - if (myEmitter.particleAttributes.usingCollisionSphere) { - glm::vec3 vectorToSphereCenter = myEmitter.particleAttributes.collisionSpherePosition - _particle[p].position; + if (myEmitter.particleAttributes[lifeStage].usingCollisionSphere) { + glm::vec3 vectorToSphereCenter = myEmitter.particleAttributes[lifeStage].collisionSpherePosition - _particle[p].position; float distanceToSphereCenter = glm::length(vectorToSphereCenter); - float combinedRadius = myEmitter.particleAttributes.collisionSphereRadius + _particle[p].radius; + float combinedRadius = myEmitter.particleAttributes[lifeStage].collisionSphereRadius + _particle[p].radius; if (distanceToSphereCenter < combinedRadius) { if (distanceToSphereCenter > 0.0f){ glm::vec3 directionToSphereCenter = vectorToSphereCenter / distanceToSphereCenter; - _particle[p].position = myEmitter.particleAttributes.collisionSpherePosition - directionToSphereCenter * combinedRadius; + _particle[p].position = myEmitter.particleAttributes[lifeStage].collisionSpherePosition - directionToSphereCenter * combinedRadius; } } } + + // do this at the end... + _particle[p].age += deltaTime; } void ParticleSystem::setCollisionSphere(int e, glm::vec3 position, float radius) { - _emitter[e].particleAttributes.usingCollisionSphere = true; - _emitter[e].particleAttributes.collisionSpherePosition = position; - _emitter[e].particleAttributes.collisionSphereRadius = radius; + + int lifeStage = 0; + + _emitter[e].particleAttributes[lifeStage].usingCollisionSphere = true; + _emitter[e].particleAttributes[lifeStage].collisionSpherePosition = position; + _emitter[e].particleAttributes[lifeStage].collisionSphereRadius = radius; } void ParticleSystem::render() { // render the emitters for (unsigned int e = 0; e < _numEmitters; e++) { - if (_emitter[e].showingEmitter) { + if (_emitter[e].visible) { renderEmitter(e, 0.2f); } }; @@ -271,19 +292,49 @@ void ParticleSystem::render() { void ParticleSystem::renderParticle(int p) { glColor4f(_particle[p].color.r, _particle[p].color.g, _particle[p].color.b, _particle[p].color.a ); - glPushMatrix(); - glTranslatef(_particle[p].position.x, _particle[p].position.y, _particle[p].position.z); - glutSolidSphere(_particle[p].radius, 6, 6); - glPopMatrix(); - // render velocity lines - glColor4f( _particle[p].color.x, _particle[p].color.y, _particle[p].color.z, 0.5f); - glm::vec3 end = _particle[p].position - _particle[p].velocity * 2.0f; - glBegin(GL_LINES); - glVertex3f(_particle[p].position.x, _particle[p].position.y, _particle[p].position.z); - glVertex3f(end.x, end.y, end.z); - - glEnd(); + if (USE_BILLBOARD_RENDERING) { + glm::vec3 cameraPosition = Application::getInstance()->getCamera()->getPosition(); + glm::vec3 viewVector = _particle[p].position - cameraPosition; + float distance = glm::length(viewVector); + + if (distance >= 0.0f) { + viewVector /= distance; + glm::vec3 up = glm::vec3(viewVector.y, viewVector.z, viewVector.x); + glm::vec3 right = glm::vec3(viewVector.z, viewVector.x, viewVector.y); + + glm::vec3 p0 = _particle[p].position - right * _particle[p].radius - up * _particle[p].radius; + glm::vec3 p1 = _particle[p].position + right * _particle[p].radius - up * _particle[p].radius; + glm::vec3 p2 = _particle[p].position + right * _particle[p].radius + up * _particle[p].radius; + glm::vec3 p3 = _particle[p].position - right * _particle[p].radius + up * _particle[p].radius; + + glBegin(GL_TRIANGLES); + glVertex3f(p0.x, p0.y, p0.z); + glVertex3f(p1.x, p1.y, p1.z); + glVertex3f(p2.x, p2.y, p2.z); + glEnd(); + + glBegin(GL_TRIANGLES); + glVertex3f(p0.x, p0.y, p0.z); + glVertex3f(p2.x, p2.y, p2.z); + glVertex3f(p3.x, p3.y, p3.z); + glEnd(); + } + } else { + glPushMatrix(); + glTranslatef(_particle[p].position.x, _particle[p].position.y, _particle[p].position.z); + glutSolidSphere(_particle[p].radius, 6, 6); + glPopMatrix(); + + // render velocity lines + glColor4f( _particle[p].color.x, _particle[p].color.y, _particle[p].color.z, 0.5f); + glm::vec3 end = _particle[p].position - _particle[p].velocity * 2.0f; + glBegin(GL_LINES); + glVertex3f(_particle[p].position.x, _particle[p].position.y, _particle[p].position.z); + glVertex3f(end.x, end.y, end.z); + + glEnd(); + } } @@ -293,7 +344,7 @@ void ParticleSystem::renderEmitter(int e, float size) { glm::vec3 r = _emitter[e].right * size; glm::vec3 u = _emitter[e].up * size; glm::vec3 f = _emitter[e].front * size; - + glLineWidth(2.0f); glColor3f(0.8f, 0.4, 0.4); diff --git a/interface/src/ParticleSystem.h b/interface/src/ParticleSystem.h index c94acd03ba..37fd5fb9db 100644 --- a/interface/src/ParticleSystem.h +++ b/interface/src/ParticleSystem.h @@ -11,8 +11,10 @@ #include -const int MAX_PARTICLES = 5000; -const int MAX_EMITTERS = 20; +const int MAX_PARTICLES = 5000; +const int MAX_EMITTERS = 20; +const int NUM_PARTICLE_LIFE_STAGES = 3; +const bool USE_BILLBOARD_RENDERING = false; class ParticleSystem { public: @@ -34,29 +36,29 @@ public: ParticleSystem(); int addEmitter(); // add (create) an emitter and get its unique id - void emitParticlesNow(int e, int numParticles, float radius, glm::vec4 color, glm::vec3 velocity, float lifespan); + void emitParticlesNow(int emitterIndex, int numParticles, float radius, glm::vec4 color, glm::vec3 velocity, float lifespan); void simulate(float deltaTime); void render(); - void setParticleAttributesForEmitter(int emitterIndex, ParticleAttributes attributes); void setOrangeBlueColorPalette(); // apply a nice preset color palette to the particles void setUpDirection(glm::vec3 upDirection) {_upDirection = upDirection;} // tell particle system which direction is up - - void setCollisionSphere(int emitterIndex, glm::vec3 position, float radius); // specify a sphere for the particles to collide with - void setEmitterPosition(int emitterIndex, glm::vec3 position) { _emitter[emitterIndex].position = position; } // set position of emitter - void setEmitterRotation(int emitterIndex, glm::quat rotation) { _emitter[emitterIndex].rotation = rotation; } // set rotation of emitter - void setShowingEmitter (int emitterIndex, bool showing ) { _emitter[emitterIndex].showingEmitter = showing; } // set its visibiity + void setParticleAttributes(int emitterIndex, ParticleAttributes attributes); + void setParticleAttributes(int emitterIndex, int lifeStage, ParticleAttributes attributes); + void setCollisionSphere (int emitterIndex, glm::vec3 position, float radius); // specify a sphere for the particles to collide with + void setEmitterPosition (int emitterIndex, glm::vec3 position) { _emitter[emitterIndex].position = position; } // set position of emitter + void setEmitterRotation (int emitterIndex, glm::quat rotation) { _emitter[emitterIndex].rotation = rotation; } // set rotation of emitter + void setShowingEmitter (int emitterIndex, bool showing ) { _emitter[emitterIndex].visible = showing; } // set its visibiity private: struct Emitter { glm::vec3 position; glm::quat rotation; - glm::vec3 right; - glm::vec3 up; - glm::vec3 front; - bool showingEmitter; - ParticleAttributes particleAttributes; + glm::vec3 right; // derived from rotation + glm::vec3 up; // derived from rotation + glm::vec3 front; // derived from rotation + bool visible; + ParticleAttributes particleAttributes[NUM_PARTICLE_LIFE_STAGES]; // the attributes of particles emitted from this emitter }; struct Particle { @@ -71,7 +73,6 @@ private: }; glm::vec3 _upDirection; - float _timer; Emitter _emitter[MAX_EMITTERS]; Particle _particle[MAX_PARTICLES]; int _numParticles; @@ -81,7 +82,6 @@ private: void updateEmitter(int e, float deltaTime); void updateParticle(int index, float deltaTime); void createParticle(int e, glm::vec3 position, glm::vec3 velocity, float radius, glm::vec4 color, float lifespan); - //void runSpecialEffectsTest(int e, float deltaTime); // for debugging and artistic exploration void killParticle(int p); void renderEmitter(int emitterIndex, float size); void renderParticle(int p); From 202fb95102dcb11b3418e24879324e61cebb2241 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Wed, 17 Jul 2013 13:51:00 -0700 Subject: [PATCH 60/81] turned off setShowingEmitter --- interface/src/Application.cpp | 2 +- interface/src/Hand.cpp | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index dc57e83a4e..6ba1134d05 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -73,7 +73,7 @@ using namespace std; static char STAR_FILE[] = "https://s3-us-west-1.amazonaws.com/highfidelity/stars.txt"; static char STAR_CACHE_FILE[] = "cachedStars.txt"; -static const bool TESTING_PARTICLE_SYSTEM = false; +static const bool TESTING_PARTICLE_SYSTEM = true; static const int BANDWIDTH_METER_CLICK_MAX_DRAG_LENGTH = 6; // farther dragged clicks are ignored diff --git a/interface/src/Hand.cpp b/interface/src/Hand.cpp index 8981819fe5..558b4fa886 100755 --- a/interface/src/Hand.cpp +++ b/interface/src/Hand.cpp @@ -178,7 +178,6 @@ void Hand::updateFingerParticles(float deltaTime) { if (!_particleSystemInitialized) { for ( int f = 0; f< NUM_FINGERS_PER_HAND; f ++ ) { _fingerParticleEmitter[f] = _particleSystem.addEmitter(); - //_particleSystem.setShowingEmitter(_fingerParticleEmitter[f], true); } _particleSystemInitialized = true; } else { From 677e2580e17125f55dde74837fdbaf41e76e2197 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jul 2013 14:42:20 -0700 Subject: [PATCH 61/81] make send only changed bits work better --- libraries/voxels/src/VoxelTree.cpp | 10 ++++------ libraries/voxels/src/VoxelTree.h | 6 ++++-- voxel-server/src/VoxelNodeData.cpp | 16 ++++++++++++++++ voxel-server/src/VoxelNodeData.h | 7 ++++++- voxel-server/src/main.cpp | 10 ++++------ 5 files changed, 34 insertions(+), 15 deletions(-) diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index 91a31a6cd1..203ed7e908 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -1114,14 +1114,12 @@ int VoxelTree::encodeTreeBitstreamRecursion(VoxelNode* node, unsigned char* outp return bytesAtThisLevel; } - /** Not ready for production - coming soon. - // If we're not in delta sending mode, but the voxel hasn't changed, then we can also bail early... - if (!params.deltaViewFrustum && !node->hasChangedSince(params.lastViewFrustumSent - CHANGE_FUDGE)) { - printf("not delta sending, and the node hasn't changed, bail early... lastSent=%lld getLastChanged=%lld\n", - params.lastViewFrustumSent, node->getLastChanged()); + // If we're not in delta sending mode, and we weren't asked to do a force send, and the voxel hasn't changed, + // then we can also bail early and save bits + if (!params.forceSendScene && !params.deltaViewFrustum && + !node->hasChangedSince(params.lastViewFrustumSent - CHANGE_FUDGE)) { return bytesAtThisLevel; } - **/ // If the user also asked for occlusion culling, check if this node is occluded, but only if it's not a leaf. // leaf occlusion is handled down below when we check child nodes diff --git a/libraries/voxels/src/VoxelTree.h b/libraries/voxels/src/VoxelTree.h index bab66c5097..e5db6526e9 100644 --- a/libraries/voxels/src/VoxelTree.h +++ b/libraries/voxels/src/VoxelTree.h @@ -51,7 +51,7 @@ public: long childWasInViewDiscarded; int boundaryLevelAdjust; uint64_t lastViewFrustumSent; - + bool forceSendScene; CoverageMap* map; EncodeBitstreamParams( @@ -65,7 +65,8 @@ public: bool wantOcclusionCulling= NO_OCCLUSION_CULLING, CoverageMap* map = IGNORE_COVERAGE_MAP, int boundaryLevelAdjust = NO_BOUNDARY_ADJUST, - uint64_t lastViewFrustumSent = IGNORE_LAST_SENT) : + uint64_t lastViewFrustumSent = IGNORE_LAST_SENT, + bool forceSendScene = true) : maxEncodeLevel (maxEncodeLevel), maxLevelReached (0), viewFrustum (viewFrustum), @@ -78,6 +79,7 @@ public: childWasInViewDiscarded (0), boundaryLevelAdjust (boundaryLevelAdjust), lastViewFrustumSent (lastViewFrustumSent), + forceSendScene (forceSendScene), map (map) {} }; diff --git a/voxel-server/src/VoxelNodeData.cpp b/voxel-server/src/VoxelNodeData.cpp index f3d87948aa..c4b8ee8b79 100644 --- a/voxel-server/src/VoxelNodeData.cpp +++ b/voxel-server/src/VoxelNodeData.cpp @@ -20,6 +20,7 @@ VoxelNodeData::VoxelNodeData(Node* owningNode) : _maxLevelReachedInLastSearch(1), _lastTimeBagEmpty(0), _viewFrustumChanging(false), + _viewFrustumJustStoppedChanging(true), _currentPacketIsColor(true) { _voxelPacket = new unsigned char[MAX_VOXEL_PACKET_SIZE]; @@ -69,10 +70,25 @@ bool VoxelNodeData::updateCurrentViewFrustum() { _currentViewFrustum.calculate(); currentViewFrustumChanged = true; } + + // When we first detect that the view stopped changing, we record this. + // but we don't change it back to false until we've completely sent this + // scene. + if (_viewFrustumChanging && !currentViewFrustumChanged) { + _viewFrustumJustStoppedChanging = true; + } _viewFrustumChanging = currentViewFrustumChanged; return currentViewFrustumChanged; } +void VoxelNodeData::setViewSent(bool viewSent) { + _viewSent = viewSent; + if (viewSent) { + _viewFrustumJustStoppedChanging = false; + } +} + + void VoxelNodeData::updateLastKnownViewFrustum() { bool frustumChanges = !_lastKnownViewFrustum.matches(_currentViewFrustum); diff --git a/voxel-server/src/VoxelNodeData.h b/voxel-server/src/VoxelNodeData.h index 0f96a07c3d..96b61db963 100644 --- a/voxel-server/src/VoxelNodeData.h +++ b/voxel-server/src/VoxelNodeData.h @@ -48,7 +48,11 @@ public: void updateLastKnownViewFrustum(); bool getViewSent() const { return _viewSent; }; - void setViewSent(bool viewSent) { _viewSent = viewSent; } + void setViewSent(bool viewSent); + + bool getViewFrustumChanging() const { return _viewFrustumChanging; }; + bool getViewFrustumJustStoppedChanging() const { return _viewFrustumJustStoppedChanging; }; + uint64_t getLastTimeBagEmpty() const { return _lastTimeBagEmpty; }; void setLastTimeBagEmpty(uint64_t lastTimeBagEmpty) { _lastTimeBagEmpty = lastTimeBagEmpty; }; @@ -69,6 +73,7 @@ private: ViewFrustum _lastKnownViewFrustum; uint64_t _lastTimeBagEmpty; bool _viewFrustumChanging; + bool _viewFrustumJustStoppedChanging; bool _currentPacketIsColor; }; diff --git a/voxel-server/src/main.cpp b/voxel-server/src/main.cpp index f171d9b168..5b1ad57861 100644 --- a/voxel-server/src/main.cpp +++ b/voxel-server/src/main.cpp @@ -205,6 +205,7 @@ void deepestLevelVoxelDistributor(NodeList* nodeList, } } + // This is the start of "resending" the scene. nodeData->nodeBag.insert(serverTree.rootNode); } @@ -242,15 +243,12 @@ void deepestLevelVoxelDistributor(NodeList* nodeList, EncodeBitstreamParams params(INT_MAX, &nodeData->getCurrentViewFrustum(), wantColor, WANT_EXISTS_BITS, DONT_CHOP, wantDelta, lastViewFrustum, wantOcclusionCulling, coverageMap, boundaryLevelAdjust, - nodeData->getLastTimeBagEmpty()); - + nodeData->getLastTimeBagEmpty(), + nodeData->getViewFrustumJustStoppedChanging()); + bytesWritten = serverTree.encodeTreeBitstream(subTree, &tempOutputBuffer[0], MAX_VOXEL_PACKET_SIZE - 1, nodeData->nodeBag, params); - if (::debugVoxelSending && wantDelta) { - printf("encodeTreeBitstream() childWasInViewDiscarded=%ld\n", params.childWasInViewDiscarded); - } - if (nodeData->getAvailable() >= bytesWritten) { nodeData->writeToPacket(&tempOutputBuffer[0], bytesWritten); } else { From d0dffb464bda481c0da5391041b6ee9b0a35a74c Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Wed, 17 Jul 2013 14:51:11 -0700 Subject: [PATCH 62/81] added emitter particle --- interface/src/Application.cpp | 1 + interface/src/Hand.cpp | 32 +++++++++++++++++++- interface/src/ParticleSystem.cpp | 50 ++++++++++++++++++++++++++++++-- interface/src/ParticleSystem.h | 24 ++++++++------- 4 files changed, 93 insertions(+), 14 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 6ba1134d05..4e0a815ef8 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3546,6 +3546,7 @@ void Application::updateParticleSystem(float deltaTime) { ParticleSystem::ParticleAttributes attributes; + attributes.radius = 0.01f; attributes.gravity = 0.0f + 0.05f * sinf( t * 0.52f ); attributes.airFriction = 2.5 + 2.0f * sinf( t * 0.32f ); attributes.jitter = 0.05f + 0.05f * sinf( t * 0.42f ); diff --git a/interface/src/Hand.cpp b/interface/src/Hand.cpp index 558b4fa886..8e16540d55 100755 --- a/interface/src/Hand.cpp +++ b/interface/src/Hand.cpp @@ -176,9 +176,39 @@ void Hand::setLeapHands(const std::vector& handPositions, void Hand::updateFingerParticles(float deltaTime) { if (!_particleSystemInitialized) { + for ( int f = 0; f< NUM_FINGERS_PER_HAND; f ++ ) { + _fingerParticleEmitter[f] = _particleSystem.addEmitter(); + + glm::vec4 color(1.0f, 0.6f, 0.0f, 0.5f); + + //_particleSystem.setEmitterParticle(f, true, 0.012f, color); + + ParticleSystem::ParticleAttributes attributes; + + // set attributes for each life stage of the particle: + attributes.radius = 0.001f; + attributes.gravity = 0.0f; + attributes.airFriction = 0.0f; + attributes.jitter = 0.0f; + attributes.emitterAttraction = 0.0f; + attributes.tornadoForce = 0.0f; + attributes.neighborAttraction = 0.0f; + attributes.neighborRepulsion = 0.0f; + attributes.bounce = 1.0f; + attributes.usingCollisionSphere = false; + _particleSystem.setParticleAttributes(_fingerParticleEmitter[f], 0, attributes); + + attributes.radius = 0.002f; + attributes.jitter = 0.01f; + _particleSystem.setParticleAttributes(_fingerParticleEmitter[f], 1, attributes); + + attributes.radius = 0.007f; + attributes.gravity = -0.01f; + _particleSystem.setParticleAttributes(_fingerParticleEmitter[f], 2, attributes); } + _particleSystemInitialized = true; } else { // update the particles @@ -208,7 +238,7 @@ void Hand::updateFingerParticles(float deltaTime) { float radius = 0.005f; glm::vec4 color(1.0f, 0.6f, 0.0f, 0.5f); - glm::vec3 velocity = fingerDirection * 0.005f; + glm::vec3 velocity = fingerDirection * 0.002f; float lifespan = 0.3f; _particleSystem.emitParticlesNow(_fingerParticleEmitter[0], 1, radius, color, velocity, lifespan); } diff --git a/interface/src/ParticleSystem.cpp b/interface/src/ParticleSystem.cpp index bd364959d3..e4c0c99181 100644 --- a/interface/src/ParticleSystem.cpp +++ b/interface/src/ParticleSystem.cpp @@ -11,6 +11,7 @@ #include "ParticleSystem.h" #include "Application.h" +const float DEFAULT_PARTICLE_RADIUS = 0.01f; const float DEFAULT_PARTICLE_BOUNCE = 1.0f; const float DEFAULT_PARTICLE_AIR_FRICTION = 2.0f; @@ -19,7 +20,7 @@ ParticleSystem::ParticleSystem() { _numEmitters = 0; _numParticles = 0; _upDirection = glm::vec3(0.0f, 1.0f, 0.0f); // default - + for (unsigned int e = 0; e < MAX_EMITTERS; e++) { _emitter[e].position = glm::vec3(0.0f, 0.0f, 0.0f); _emitter[e].rotation = glm::quat(); @@ -27,8 +28,17 @@ ParticleSystem::ParticleSystem() { _emitter[e].up = IDENTITY_UP; _emitter[e].front = IDENTITY_FRONT; _emitter[e].visible = false; - + _emitter[e].baseParticle.alive = false; + _emitter[e].baseParticle.age = 0.0f; + _emitter[e].baseParticle.lifespan = 0.0f; + _emitter[e].baseParticle.radius = 0.0f; + _emitter[e].baseParticle.emitterIndex = 0; + _emitter[e].baseParticle.position = glm::vec3(0.0f, 0.0f, 0.0f); + _emitter[e].baseParticle.velocity = glm::vec3(0.0f, 0.0f, 0.0f); + + for (int s = 0; sradius = attributes.radius; a->bounce = attributes.bounce; a->gravity = attributes.gravity; a->airFriction = attributes.airFriction; @@ -183,8 +195,16 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { float ageFraction = _particle[p].age / _particle[p].lifespan; + + + int lifeStage = (int)( ageFraction * NUM_PARTICLE_LIFE_STAGES ); + + _particle[p].radius = _emitter[_particle[p].emitterIndex].particleAttributes[lifeStage].radius; + + + Emitter myEmitter = _emitter[_particle[p].emitterIndex]; // apply random jitter @@ -272,10 +292,34 @@ void ParticleSystem::setCollisionSphere(int e, glm::vec3 position, float radius) _emitter[e].particleAttributes[lifeStage].collisionSphereRadius = radius; } +void ParticleSystem::setEmitterParticle(int emitterIndex, bool showing ) { + + _emitter[emitterIndex].baseParticle.alive = true; + _emitter[emitterIndex].baseParticle.emitterIndex = emitterIndex; +} + +void ParticleSystem::setEmitterParticle(int emitterIndex, bool showing, float radius, glm::vec4 color ) { + + _emitter[emitterIndex].baseParticle.alive = true; + _emitter[emitterIndex].baseParticle.emitterIndex = emitterIndex; + _emitter[emitterIndex].baseParticle.radius = radius; + _emitter[emitterIndex].baseParticle.color = color; +} + + void ParticleSystem::render() { // render the emitters for (unsigned int e = 0; e < _numEmitters; e++) { + + if (_emitter[e].baseParticle.alive) { + glColor4f(_emitter[e].baseParticle.color.r, _emitter[e].baseParticle.color.g, _emitter[e].baseParticle.color.b, _emitter[e].baseParticle.color.a ); + glPushMatrix(); + glTranslatef(_emitter[e].position.x, _emitter[e].position.y, _emitter[e].position.z); + glutSolidSphere(_emitter[e].baseParticle.radius, 6, 6); + glPopMatrix(); + } + if (_emitter[e].visible) { renderEmitter(e, 0.2f); } diff --git a/interface/src/ParticleSystem.h b/interface/src/ParticleSystem.h index 37fd5fb9db..deffc9a04d 100644 --- a/interface/src/ParticleSystem.h +++ b/interface/src/ParticleSystem.h @@ -20,6 +20,7 @@ class ParticleSystem { public: struct ParticleAttributes { + float radius; float bounce; float gravity; float airFriction; @@ -39,6 +40,8 @@ public: void emitParticlesNow(int emitterIndex, int numParticles, float radius, glm::vec4 color, glm::vec3 velocity, float lifespan); void simulate(float deltaTime); void render(); + void setEmitterParticle(int emitterIndex, bool showing ); + void setEmitterParticle(int emitterIndex, bool showing, float radius, glm::vec4 color ); void setOrangeBlueColorPalette(); // apply a nice preset color palette to the particles void setUpDirection(glm::vec3 upDirection) {_upDirection = upDirection;} // tell particle system which direction is up @@ -51,16 +54,6 @@ public: private: - struct Emitter { - glm::vec3 position; - glm::quat rotation; - glm::vec3 right; // derived from rotation - glm::vec3 up; // derived from rotation - glm::vec3 front; // derived from rotation - bool visible; - ParticleAttributes particleAttributes[NUM_PARTICLE_LIFE_STAGES]; // the attributes of particles emitted from this emitter - }; - struct Particle { bool alive; // is the particle active? glm::vec3 position; // position @@ -72,6 +65,17 @@ private: int emitterIndex; // which emitter created this particle? }; + struct Emitter { + glm::vec3 position; + glm::quat rotation; + glm::vec3 right; // derived from rotation + glm::vec3 up; // derived from rotation + glm::vec3 front; // derived from rotation + bool visible; + Particle baseParticle; // a non-physical particle at the emitter position + ParticleAttributes particleAttributes[NUM_PARTICLE_LIFE_STAGES]; // the attributes of particles emitted from this emitter + }; + glm::vec3 _upDirection; Emitter _emitter[MAX_EMITTERS]; Particle _particle[MAX_PARTICLES]; From 8ebf5fbd6b938f4294763b2b945274e8bdcf72cf Mon Sep 17 00:00:00 2001 From: Eric Johnston Date: Wed, 17 Jul 2013 14:54:18 -0700 Subject: [PATCH 63/81] Rave & Leap: cleanup and move over to new hand/finger structures --- interface/src/Avatar.cpp | 9 +- interface/src/Hand.cpp | 146 ++++++++++++++++--------- libraries/avatars/src/AvatarData.cpp | 63 ++++------- libraries/avatars/src/HandData.cpp | 43 ++++++++ libraries/avatars/src/HandData.h | 43 +++++--- libraries/shared/src/PacketHeaders.cpp | 2 +- 6 files changed, 196 insertions(+), 110 deletions(-) diff --git a/interface/src/Avatar.cpp b/interface/src/Avatar.cpp index e92394af22..26cd241b5c 100755 --- a/interface/src/Avatar.cpp +++ b/interface/src/Avatar.cpp @@ -821,10 +821,13 @@ void Avatar::updateHandMovementAndTouching(float deltaTime, bool enableHandMovem } // If there's a leap-interaction hand visible, use that as the endpoint - if (getHand().getHandPositions().size() > 0) { - _skeleton.joint[ AVATAR_JOINT_RIGHT_FINGERTIPS ].position = - getHand().leapPositionToWorldPosition(getHand().getHandPositions()[0]); + for (size_t i = 0; i < getHand().getPalms().size(); ++i) { + PalmData& palm = getHand().getPalms()[i]; + if (palm.isActive()) { + _skeleton.joint[ AVATAR_JOINT_RIGHT_FINGERTIPS ].position = palm.getPosition(); + } } + }//if (_isMine) //constrain right arm length and re-adjust elbow position as it bends diff --git a/interface/src/Hand.cpp b/interface/src/Hand.cpp index e2b2b66a46..5693ce7e2e 100755 --- a/interface/src/Hand.cpp +++ b/interface/src/Hand.cpp @@ -55,15 +55,23 @@ void Hand::calculateGeometry() { _basePosition = head.getPosition() + head.getOrientation() * offset; _baseOrientation = head.getOrientation(); - int numLeapBalls = _fingerTips.size(); - _leapBalls.resize(numLeapBalls); - - for (int i = 0; i < _fingerTips.size(); ++i) { - _leapBalls[i].rotation = _baseOrientation; - _leapBalls[i].position = leapPositionToWorldPosition(_fingerTips[i]); - _leapBalls[i].radius = 0.01; - _leapBalls[i].touchForce = 0.0; - _leapBalls[i].isCollidable = true; + _leapBalls.clear(); + for (size_t i = 0; i < getNumPalms(); ++i) { + PalmData& palm = getPalms()[i]; + if (palm.isActive()) { + for (size_t f = 0; f < palm.getNumFingers(); ++f) { + FingerData& finger = palm.getFingers()[f]; + if (finger.isActive()) { + _leapBalls.resize(_leapBalls.size() + 1); + HandBall& ball = _leapBalls.back(); + ball.rotation = _baseOrientation; + ball.position = finger.getTipPosition(); + ball.radius = 0.01; + ball.touchForce = 0.0; + ball.isCollidable = true; + } + } + } } } @@ -134,21 +142,28 @@ void Hand::renderHandSpheres() { } // Draw the finger root cones - if (_fingerTips.size() == _fingerRoots.size()) { - for (size_t i = 0; i < _fingerTips.size(); ++i) { - glColor4f(_ballColor.r, _ballColor.g, _ballColor.b, 0.5); - glm::vec3 tip = leapPositionToWorldPosition(_fingerTips[i]); - glm::vec3 root = leapPositionToWorldPosition(_fingerRoots[i]); - Avatar::renderJointConnectingCone(root, tip, 0.001, 0.003); + for (size_t i = 0; i < getNumPalms(); ++i) { + PalmData& palm = getPalms()[i]; + if (palm.isActive()) { + for (size_t f = 0; f < palm.getNumFingers(); ++f) { + FingerData& finger = palm.getFingers()[f]; + if (finger.isActive()) { + glColor4f(_ballColor.r, _ballColor.g, _ballColor.b, 0.5); + glm::vec3 tip = finger.getTipPosition(); + glm::vec3 root = finger.getRootPosition(); + Avatar::renderJointConnectingCone(root, tip, 0.001, 0.003); + } + } } } // Draw the palms - if (_handPositions.size() == _handNormals.size()) { - for (size_t i = 0; i < _handPositions.size(); ++i) { + for (size_t i = 0; i < getNumPalms(); ++i) { + PalmData& palm = getPalms()[i]; + if (palm.isActive()) { glColor4f(_ballColor.r, _ballColor.g, _ballColor.b, 0.25); - glm::vec3 tip = leapPositionToWorldPosition(_handPositions[i]); - glm::vec3 root = leapPositionToWorldPosition(_handPositions[i] + (_handNormals[i] * 2.0f)); + glm::vec3 tip = palm.getPosition(); + glm::vec3 root = palm.getPosition() + palm.getNormal() * 0.002f; Avatar::renderJointConnectingCone(root, tip, 0.05, 0.03); } } @@ -158,14 +173,39 @@ void Hand::renderHandSpheres() { void Hand::setLeapFingers(const std::vector& fingerTips, const std::vector& fingerRoots) { - _fingerTips = fingerTips; - _fingerRoots = fingerRoots; + // TODO: add id-checking here to increase finger stability + + size_t fingerIndex = 0; + for (size_t i = 0; i < getNumPalms(); ++i) { + PalmData& palm = getPalms()[i]; + for (size_t f = 0; f < palm.getNumFingers(); ++f) { + FingerData& finger = palm.getFingers()[f]; + if (fingerIndex < fingerTips.size()) { + finger.setActive(true); + finger.setRawTipPosition(fingerTips[fingerIndex]); + finger.setRawRootPosition(fingerRoots[fingerIndex]); + fingerIndex++; + } + else { + finger.setActive(false); + } + } + } } void Hand::setLeapHands(const std::vector& handPositions, const std::vector& handNormals) { - _handPositions = handPositions; - _handNormals = handNormals; + for (size_t i = 0; i < getNumPalms(); ++i) { + PalmData& palm = getPalms()[i]; + if (i < handPositions.size()) { + palm.setActive(true); + palm.setRawPosition(handPositions[i]); + palm.setRawNormal(handNormals[i]); + } + else { + palm.setActive(false); + } + } } @@ -182,33 +222,41 @@ void Hand::updateFingerParticles(float deltaTime) { static float t = 0.0f; t += deltaTime; - - for ( int f = 0; f< _fingerTips.size(); f ++ ) { - - if (_fingerParticleEmitter[f] != -1) { - - glm::vec3 particleEmitterPosition = leapPositionToWorldPosition(_fingerTips[f]); - - // this aspect is still being designed.... - - glm::vec3 tilt = glm::vec3 - ( - 30.0f * sinf( t * 0.55f ), - 0.0f, - 30.0f * cosf( t * 0.75f ) - ); - - glm::quat particleEmitterRotation = glm::quat(glm::radians(tilt)); - _particleSystem.setEmitterPosition(_fingerParticleEmitter[0], particleEmitterPosition); - _particleSystem.setEmitterRotation(_fingerParticleEmitter[0], particleEmitterRotation); - - float radius = 0.005f; - glm::vec4 color(1.0f, 0.6f, 0.0f, 0.5f); - glm::vec3 velocity(0.0f, 0.005f, 0.0f); - float lifespan = 0.3f; - _particleSystem.emitParticlesNow(_fingerParticleEmitter[0], 1, radius, color, velocity, lifespan); - } + int fingerIndex = 0; + for (size_t i = 0; i < getNumPalms(); ++i) { + PalmData& palm = getPalms()[i]; + if (palm.isActive()) { + for (size_t f = 0; f < palm.getNumFingers(); ++f) { + FingerData& finger = palm.getFingers()[f]; + if (finger.isActive()) { + if (_fingerParticleEmitter[fingerIndex] != -1) { + + glm::vec3 particleEmitterPosition = finger.getTipPosition(); + + // this aspect is still being designed.... + + glm::vec3 tilt = glm::vec3 + ( + 30.0f * sinf( t * 0.55f ), + 0.0f, + 30.0f * cosf( t * 0.75f ) + ); + + glm::quat particleEmitterRotation = glm::quat(glm::radians(tilt)); + + _particleSystem.setEmitterPosition(_fingerParticleEmitter[0], particleEmitterPosition); + _particleSystem.setEmitterRotation(_fingerParticleEmitter[0], particleEmitterRotation); + + float radius = 0.005f; + glm::vec4 color(1.0f, 0.6f, 0.0f, 0.5f); + glm::vec3 velocity(0.0f, 0.005f, 0.0f); + float lifespan = 0.3f; + _particleSystem.emitParticlesNow(_fingerParticleEmitter[0], 1, radius, color, velocity, lifespan); + } + } + } + } } _particleSystem.setUpDirection(glm::vec3(0.0f, 1.0f, 0.0f)); diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index 86895410dd..fa0bffded0 100755 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -127,36 +127,22 @@ int AvatarData::getBroadcastData(unsigned char* destinationBuffer) { *destinationBuffer++ = bitItems; // leap hand data - // In order to make the hand data version-robust, hand data packing is just a series of vec3's, - // with conventions. If a client doesn't know the conventions, they can just get the vec3's - // and render them as balls, or ignore them, without crashing or disrupting anyone. - // Current convention: - // Zero or more fingetTip positions, followed by the same number of fingerRoot positions - - const std::vector& fingerTips = _handData->getFingerTips(); - const std::vector& fingerRoots = _handData->getFingerRoots(); - size_t numFingerVectors = fingerTips.size() + fingerRoots.size(); - if (numFingerVectors > 255) - numFingerVectors = 0; // safety. We shouldn't ever get over 255, so consider that invalid. + std::vector fingerVectors; + _handData->encodeRemoteData(fingerVectors); ///////////////////////////////// // Temporarily disable Leap finger sending, as it's causing a crash whenever someone's got a Leap connected - numFingerVectors = 0; + fingerVectors.clear(); ///////////////////////////////// - - *destinationBuffer++ = (unsigned char)numFingerVectors; - - if (numFingerVectors > 0) { - for (size_t i = 0; i < fingerTips.size(); ++i) { - destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerTips[i].x, 4); - destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerTips[i].y, 4); - destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerTips[i].z, 4); - } - for (size_t i = 0; i < fingerRoots.size(); ++i) { - destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerRoots[i].x, 4); - destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerRoots[i].y, 4); - destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerRoots[i].z, 4); - } + if (fingerVectors.size() > 255) + fingerVectors.clear(); // safety. We shouldn't ever get over 255, so consider that invalid. + + *destinationBuffer++ = (unsigned char)fingerVectors.size(); + + for (size_t i = 0; i < fingerVectors.size(); ++i) { + destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerVectors[i].x, 4); + destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerVectors[i].y, 4); + destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerVectors[i].z, 4); } // skeleton joints @@ -263,25 +249,16 @@ int AvatarData::parseData(unsigned char* sourceBuffer, int numBytes) { // leap hand data if (sourceBuffer - startPosition < numBytes) // safety check { - std::vector fingerTips; - std::vector fingerRoots; unsigned int numFingerVectors = *sourceBuffer++; - unsigned int numFingerTips = numFingerVectors / 2; - unsigned int numFingerRoots = numFingerVectors - numFingerTips; - fingerTips.resize(numFingerTips); - fingerRoots.resize(numFingerRoots); - for (size_t i = 0; i < numFingerTips; ++i) { - sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerTips[i].x), 4); - sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerTips[i].y), 4); - sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerTips[i].z), 4); + if (numFingerVectors > 0) { + std::vector fingerVectors(numFingerVectors); + for (size_t i = 0; i < numFingerVectors; ++i) { + sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerVectors[i].x), 4); + sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerVectors[i].y), 4); + sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerVectors[i].z), 4); + } + _handData->decodeRemoteData(fingerVectors); } - for (size_t i = 0; i < numFingerRoots; ++i) { - sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerRoots[i].x), 4); - sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerRoots[i].y), 4); - sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerRoots[i].z), 4); - } - _handData->setFingerTips(fingerTips); - _handData->setFingerRoots(fingerRoots); } // skeleton joints diff --git a/libraries/avatars/src/HandData.cpp b/libraries/avatars/src/HandData.cpp index a4e8e9560c..f119472fa1 100755 --- a/libraries/avatars/src/HandData.cpp +++ b/libraries/avatars/src/HandData.cpp @@ -35,3 +35,46 @@ _owningPalmData(owningPalmData), _owningHandData(owningHandData) { } + +void HandData::encodeRemoteData(std::vector& fingerVectors) { + fingerVectors.clear(); + for (size_t i = 0; i < getNumPalms(); ++i) { + PalmData& palm = getPalms()[i]; + fingerVectors.push_back(palm.getRawPosition()); + fingerVectors.push_back(palm.getRawNormal()); + for (size_t f = 0; f < palm.getNumFingers(); ++f) { + FingerData& finger = palm.getFingers()[f]; + if (finger.isActive()) { + fingerVectors.push_back(finger.getTipRawPosition()); + fingerVectors.push_back(finger.getRootRawPosition()); + } + else { + fingerVectors.push_back(glm::vec3(0,0,0)); + fingerVectors.push_back(glm::vec3(0,0,0)); + } + } + } +} + +void HandData::decodeRemoteData(const std::vector& fingerVectors) { + size_t vectorIndex = 0; + for (size_t i = 0; i < getNumPalms(); ++i) { + PalmData& palm = getPalms()[i]; + // If a palm is active, there will be + // 1 vector for its position + // 1 vector for normal + // 10 vectors for fingers (5 tip/root pairs) + bool palmActive = fingerVectors.size() >= i * 12; + palm.setActive(palmActive); + if (palmActive) { + palm.setRawPosition(fingerVectors[vectorIndex++]); + palm.setRawNormal(fingerVectors[vectorIndex++]); + for (size_t f = 0; f < NUM_FINGERS_PER_HAND; ++f) { + FingerData& finger = palm.getFingers()[i]; + finger.setRawTipPosition(fingerVectors[vectorIndex++]); + finger.setRawRootPosition(fingerVectors[vectorIndex++]); + } + } + } +} + diff --git a/libraries/avatars/src/HandData.h b/libraries/avatars/src/HandData.h index ef322261c5..ac5c509f55 100755 --- a/libraries/avatars/src/HandData.h +++ b/libraries/avatars/src/HandData.h @@ -27,14 +27,6 @@ public: // These methods return the positions in Leap-relative space. // To convert to world coordinates, use Hand::leapPositionToWorldPosition. - const std::vector& getFingerTips() const { return _fingerTips; } - const std::vector& getFingerRoots() const { return _fingerRoots; } - const std::vector& getHandPositions() const { return _handPositions; } - const std::vector& getHandNormals() const { return _handNormals; } - void setFingerTips(const std::vector& fingerTips) { _fingerTips = fingerTips; } - void setFingerRoots(const std::vector& fingerRoots) { _fingerRoots = fingerRoots; } - void setHandPositions(const std::vector& handPositons) { _handPositions = handPositons; } - void setHandNormals(const std::vector& handNormals) { _handNormals = handNormals; } // position conversion glm::vec3 leapPositionToWorldPosition(const glm::vec3& leapPosition) { @@ -45,12 +37,15 @@ public: return glm::normalize(_baseOrientation * leapDirection); } + std::vector& getPalms() { return _palms; } + size_t getNumPalms() { return _palms.size(); } + + // Use these for sending and receiving hand data + void encodeRemoteData(std::vector& fingerVectors); + void decodeRemoteData(const std::vector& fingerVectors); + friend class AvatarData; protected: - std::vector _fingerTips; - std::vector _fingerRoots; - std::vector _handPositions; - std::vector _handNormals; glm::vec3 _basePosition; // Hands are placed relative to this glm::quat _baseOrientation; // Hands are placed relative to this AvatarData* _owningAvatarData; @@ -64,6 +59,17 @@ private: class FingerData { public: FingerData(PalmData* owningPalmData, HandData* owningHandData); + + glm::vec3 getTipPosition() const { return _owningHandData->leapPositionToWorldPosition(_tipRawPosition); } + glm::vec3 getRootPosition() const { return _owningHandData->leapPositionToWorldPosition(_rootRawPosition); } + const glm::vec3& getTipRawPosition() const { return _tipRawPosition; } + const glm::vec3& getRootRawPosition() const { return _rootRawPosition; } + bool isActive() const { return _isActive; } + + void setActive(bool active) { _isActive = active; } + void setRawTipPosition(const glm::vec3& pos) { _tipRawPosition = pos; } + void setRawRootPosition(const glm::vec3& pos) { _rootRawPosition = pos; } + private: glm::vec3 _tipRawPosition; glm::vec3 _rootRawPosition; @@ -75,10 +81,19 @@ private: class PalmData { public: PalmData(HandData* owningHandData); - glm::vec3 getPosition() const { return _owningHandData->leapPositionToWorldPosition(_rawPosition); } - glm::vec3 getNormal() const { return _owningHandData->leapDirectionToWorldDirection(_rawNormal); } + glm::vec3 getPosition() const { return _owningHandData->leapPositionToWorldPosition(_rawPosition); } + glm::vec3 getNormal() const { return _owningHandData->leapDirectionToWorldDirection(_rawNormal); } const glm::vec3& getRawPosition() const { return _rawPosition; } const glm::vec3& getRawNormal() const { return _rawNormal; } + bool isActive() const { return _isActive; } + + std::vector& getFingers() { return _fingers; } + size_t getNumFingers() { return _fingers.size(); } + + void setActive(bool active) { _isActive = active; } + void setRawPosition(const glm::vec3& pos) { _rawPosition = pos; } + void setRawNormal(const glm::vec3& normal) { _rawNormal = normal; } + private: std::vector _fingers; glm::vec3 _rawPosition; diff --git a/libraries/shared/src/PacketHeaders.cpp b/libraries/shared/src/PacketHeaders.cpp index 7b4a0509f3..821a2d0247 100644 --- a/libraries/shared/src/PacketHeaders.cpp +++ b/libraries/shared/src/PacketHeaders.cpp @@ -15,7 +15,7 @@ PACKET_VERSION versionForPacketType(PACKET_TYPE type) { switch (type) { case PACKET_TYPE_HEAD_DATA: - return 1; + return 2; break; default: return 0; From 4272f4da5721487e1c9863bd6e1edf62555706b2 Mon Sep 17 00:00:00 2001 From: Philip Rosedale Date: Wed, 17 Jul 2013 14:57:29 -0700 Subject: [PATCH 64/81] Tiny sliding with gravity removed --- interface/src/Avatar.cpp | 15 ++++++++------- interface/src/Avatar.h | 5 ++++- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/interface/src/Avatar.cpp b/interface/src/Avatar.cpp index e92394af22..950108a65d 100755 --- a/interface/src/Avatar.cpp +++ b/interface/src/Avatar.cpp @@ -98,6 +98,7 @@ Avatar::Avatar(Node* owningNode) : _elapsedTimeMoving(0.0f), _elapsedTimeStopped(0.0f), _elapsedTimeSinceCollision(0.0f), + _lastCollisionPosition(0, 0, 0), _speedBrakes(false), _isThrustOn(false), _voxels(this) @@ -541,11 +542,12 @@ void Avatar::simulate(float deltaTime, Transmitter* transmitter) { // For gravity, always move the avatar by the amount driven by gravity, so that the collision // routines will detect it and collide every frame when pulled by gravity to a surface // - - _velocity += _scale * _gravity * (GRAVITY_EARTH * deltaTime); - _position += _scale * _gravity * (GRAVITY_EARTH * deltaTime) * deltaTime; + const float MIN_DISTANCE_AFTER_COLLISION_FOR_GRAVITY = 0.01f; + if (glm::length(_position - _lastCollisionPosition) > MIN_DISTANCE_AFTER_COLLISION_FOR_GRAVITY) { + _velocity += _scale * _gravity * (GRAVITY_EARTH * deltaTime); + _position += _scale * _gravity * (GRAVITY_EARTH * deltaTime) * deltaTime; + } } - updateCollisionWithEnvironment(deltaTime); updateCollisionWithVoxels(deltaTime); updateAvatarCollisions(deltaTime); @@ -890,11 +892,9 @@ void Avatar::updateCollisionWithEnvironment(float deltaTime) { if (velocityTowardCollision > VISIBLE_GROUND_COLLISION_VELOCITY) { Application::getInstance()->setGroundPlaneImpact(1.0f); } + _lastCollisionPosition = _position; updateCollisionSound(penetration, deltaTime, ENVIRONMENT_COLLISION_FREQUENCY); - applyHardCollision(penetration, ENVIRONMENT_SURFACE_ELASTICITY, ENVIRONMENT_SURFACE_DAMPING); - - } } @@ -908,6 +908,7 @@ void Avatar::updateCollisionWithVoxels(float deltaTime) { if (Application::getInstance()->getVoxels()->findCapsulePenetration( _position - glm::vec3(0.0f, _pelvisFloatingHeight - radius, 0.0f), _position + glm::vec3(0.0f, _height - _pelvisFloatingHeight - radius, 0.0f), radius, penetration)) { + _lastCollisionPosition = _position; updateCollisionSound(penetration, deltaTime, VOXEL_COLLISION_FREQUENCY); applyHardCollision(penetration, VOXEL_ELASTICITY, VOXEL_DAMPING); } diff --git a/interface/src/Avatar.h b/interface/src/Avatar.h index 61207a2d8b..75e0ab2f9b 100755 --- a/interface/src/Avatar.h +++ b/interface/src/Avatar.h @@ -118,7 +118,8 @@ public: const glm::vec3& amplifyAngle, float yawFromTouch, float pitchFromTouch); - void addBodyYaw(float y) {_bodyYaw += y;}; + void addBodyYaw(float bodyYaw) {_bodyYaw += bodyYaw;}; + void addBodyYawDelta(float bodyYawDelta) {_bodyYawDelta += bodyYawDelta;} void render(bool lookingInMirror, bool renderAvatarBalls); //setters @@ -155,6 +156,7 @@ public: float getElapsedTimeStopped () const { return _elapsedTimeStopped;} float getElapsedTimeMoving () const { return _elapsedTimeMoving;} float getElapsedTimeSinceCollision() const { return _elapsedTimeSinceCollision;} + const glm::vec3& getLastCollisionPosition () const { return _lastCollisionPosition;} float getAbsoluteHeadYaw () const; float getAbsoluteHeadPitch () const; Head& getHead () {return _head; } @@ -245,6 +247,7 @@ private: float _elapsedTimeMoving; // Timers to drive camera transitions when moving float _elapsedTimeStopped; float _elapsedTimeSinceCollision; + glm::vec3 _lastCollisionPosition; bool _speedBrakes; bool _isThrustOn; From 52d8ece38abdd30f3a3f40ee1f5547d512f90b5e Mon Sep 17 00:00:00 2001 From: Philip Rosedale Date: Wed, 17 Jul 2013 15:03:56 -0700 Subject: [PATCH 65/81] remove old pre-movement of avatar in gravity --- interface/src/Avatar.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/interface/src/Avatar.cpp b/interface/src/Avatar.cpp index 950108a65d..c723bb3b8d 100755 --- a/interface/src/Avatar.cpp +++ b/interface/src/Avatar.cpp @@ -542,10 +542,9 @@ void Avatar::simulate(float deltaTime, Transmitter* transmitter) { // For gravity, always move the avatar by the amount driven by gravity, so that the collision // routines will detect it and collide every frame when pulled by gravity to a surface // - const float MIN_DISTANCE_AFTER_COLLISION_FOR_GRAVITY = 0.01f; + const float MIN_DISTANCE_AFTER_COLLISION_FOR_GRAVITY = 0.02f; if (glm::length(_position - _lastCollisionPosition) > MIN_DISTANCE_AFTER_COLLISION_FOR_GRAVITY) { _velocity += _scale * _gravity * (GRAVITY_EARTH * deltaTime); - _position += _scale * _gravity * (GRAVITY_EARTH * deltaTime) * deltaTime; } } updateCollisionWithEnvironment(deltaTime); From 1f1259cec5883158e947d325b1fe675991668700 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Wed, 17 Jul 2013 16:03:10 -0700 Subject: [PATCH 66/81] added particle life stages --- interface/src/Application.cpp | 2 +- interface/src/Hand.cpp | 35 ++++++++++++--------- interface/src/ParticleSystem.cpp | 53 +++++++++++++++++++------------- interface/src/ParticleSystem.h | 8 +++-- 4 files changed, 59 insertions(+), 39 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 4e0a815ef8..6057ae26ed 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -73,7 +73,7 @@ using namespace std; static char STAR_FILE[] = "https://s3-us-west-1.amazonaws.com/highfidelity/stars.txt"; static char STAR_CACHE_FILE[] = "cachedStars.txt"; -static const bool TESTING_PARTICLE_SYSTEM = true; +static const bool TESTING_PARTICLE_SYSTEM = false; static const int BANDWIDTH_METER_CLICK_MAX_DRAG_LENGTH = 6; // farther dragged clicks are ignored diff --git a/interface/src/Hand.cpp b/interface/src/Hand.cpp index 8e16540d55..333ad4f90c 100755 --- a/interface/src/Hand.cpp +++ b/interface/src/Hand.cpp @@ -29,6 +29,9 @@ Hand::Hand(Avatar* owningAvatar) : // initialize all finger particle emitters with an invalid id as default for (int f = 0; f< NUM_FINGERS_PER_HAND; f ++ ) { _fingerParticleEmitter[f] = -1; + + //glm::vec4 color(1.0f, 0.6f, 0.0f, 0.5f); + //_particleSystem.setEmitterBaseParticle(f, true, 0.012f, color); } } @@ -181,17 +184,14 @@ void Hand::updateFingerParticles(float deltaTime) { _fingerParticleEmitter[f] = _particleSystem.addEmitter(); - glm::vec4 color(1.0f, 0.6f, 0.0f, 0.5f); - - //_particleSystem.setEmitterParticle(f, true, 0.012f, color); - ParticleSystem::ParticleAttributes attributes; // set attributes for each life stage of the particle: - attributes.radius = 0.001f; + attributes.radius = 0.0f; + attributes.color = glm::vec4( 1.0f, 1.0f, 0.5f, 0.5f); attributes.gravity = 0.0f; attributes.airFriction = 0.0f; - attributes.jitter = 0.0f; + attributes.jitter = 0.002f; attributes.emitterAttraction = 0.0f; attributes.tornadoForce = 0.0f; attributes.neighborAttraction = 0.0f; @@ -200,13 +200,20 @@ void Hand::updateFingerParticles(float deltaTime) { attributes.usingCollisionSphere = false; _particleSystem.setParticleAttributes(_fingerParticleEmitter[f], 0, attributes); - attributes.radius = 0.002f; - attributes.jitter = 0.01f; + attributes.radius = 0.01f; + attributes.jitter = 0.0f; + attributes.gravity = -0.005f; + attributes.color = glm::vec4( 1.0f, 0.2f, 0.0f, 0.4f); _particleSystem.setParticleAttributes(_fingerParticleEmitter[f], 1, attributes); - attributes.radius = 0.007f; - attributes.gravity = -0.01f; + attributes.radius = 0.01f; + attributes.gravity = 0.0f; + attributes.color = glm::vec4( 0.0f, 0.0f, 0.0f, 0.2f); _particleSystem.setParticleAttributes(_fingerParticleEmitter[f], 2, attributes); + + attributes.radius = 0.02f; + attributes.color = glm::vec4( 0.0f, 0.0f, 0.0f, 0.0f); + _particleSystem.setParticleAttributes(_fingerParticleEmitter[f], 3, attributes); } _particleSystemInitialized = true; @@ -233,14 +240,14 @@ void Hand::updateFingerParticles(float deltaTime) { glm::quat particleEmitterRotation = rotationBetween(IDENTITY_UP, fingerDirection); - _particleSystem.setEmitterPosition(_fingerParticleEmitter[0], particleEmitterPosition); - _particleSystem.setEmitterRotation(_fingerParticleEmitter[0], particleEmitterRotation); + _particleSystem.setEmitterPosition(_fingerParticleEmitter[f], particleEmitterPosition); + _particleSystem.setEmitterRotation(_fingerParticleEmitter[f], particleEmitterRotation); float radius = 0.005f; glm::vec4 color(1.0f, 0.6f, 0.0f, 0.5f); glm::vec3 velocity = fingerDirection * 0.002f; - float lifespan = 0.3f; - _particleSystem.emitParticlesNow(_fingerParticleEmitter[0], 1, radius, color, velocity, lifespan); + float lifespan = 1.0f; + _particleSystem.emitParticlesNow(_fingerParticleEmitter[f], 1, radius, color, velocity, lifespan); } } diff --git a/interface/src/ParticleSystem.cpp b/interface/src/ParticleSystem.cpp index e4c0c99181..15343203e4 100644 --- a/interface/src/ParticleSystem.cpp +++ b/interface/src/ParticleSystem.cpp @@ -39,6 +39,7 @@ ParticleSystem::ParticleSystem() { for (int s = 0; sradius = attributes.radius; + a->color = attributes.color; a->bounce = attributes.bounce; a->gravity = attributes.gravity; a->airFriction = attributes.airFriction; @@ -192,19 +195,27 @@ void ParticleSystem::setParticleAttributes(int emitterIndex, int lifeStage, Part void ParticleSystem::updateParticle(int p, float deltaTime) { assert(_particle[p].age <= _particle[p].lifespan); - + float ageFraction = _particle[p].age / _particle[p].lifespan; + + int lifeStage = (int)( ageFraction * (NUM_PARTICLE_LIFE_STAGES-1) ); + + float lifeStageFraction = ageFraction * ( NUM_PARTICLE_LIFE_STAGES - 1 ) - lifeStage; + /* + if ( p == 0 ) { + printf( "lifespan = %f ageFraction = %f lifeStage = %d lifeStageFraction = %f\n", _particle[p].lifespan, ageFraction, lifeStage, lifeStageFraction ); + } + */ - - - int lifeStage = (int)( ageFraction * NUM_PARTICLE_LIFE_STAGES ); - - - _particle[p].radius = _emitter[_particle[p].emitterIndex].particleAttributes[lifeStage].radius; - - - + _particle[p].radius + = _emitter[_particle[p].emitterIndex].particleAttributes[lifeStage ].radius * (1.0f - lifeStageFraction) + + _emitter[_particle[p].emitterIndex].particleAttributes[lifeStage+1].radius * lifeStageFraction; + + _particle[p].color + = _emitter[_particle[p].emitterIndex].particleAttributes[lifeStage ].color * (1.0f - lifeStageFraction) + + _emitter[_particle[p].emitterIndex].particleAttributes[lifeStage+1].color * lifeStageFraction; + Emitter myEmitter = _emitter[_particle[p].emitterIndex]; // apply random jitter @@ -292,13 +303,13 @@ void ParticleSystem::setCollisionSphere(int e, glm::vec3 position, float radius) _emitter[e].particleAttributes[lifeStage].collisionSphereRadius = radius; } -void ParticleSystem::setEmitterParticle(int emitterIndex, bool showing ) { +void ParticleSystem::setEmitterBaseParticle(int emitterIndex, bool showing ) { _emitter[emitterIndex].baseParticle.alive = true; _emitter[emitterIndex].baseParticle.emitterIndex = emitterIndex; } -void ParticleSystem::setEmitterParticle(int emitterIndex, bool showing, float radius, glm::vec4 color ) { +void ParticleSystem::setEmitterBaseParticle(int emitterIndex, bool showing, float radius, glm::vec4 color ) { _emitter[emitterIndex].baseParticle.alive = true; _emitter[emitterIndex].baseParticle.emitterIndex = emitterIndex; @@ -310,7 +321,7 @@ void ParticleSystem::setEmitterParticle(int emitterIndex, bool showing, float ra void ParticleSystem::render() { // render the emitters - for (unsigned int e = 0; e < _numEmitters; e++) { + for (int e = 0; e < _numEmitters; e++) { if (_emitter[e].baseParticle.alive) { glColor4f(_emitter[e].baseParticle.color.r, _emitter[e].baseParticle.color.g, _emitter[e].baseParticle.color.b, _emitter[e].baseParticle.color.a ); @@ -370,14 +381,14 @@ void ParticleSystem::renderParticle(int p) { glutSolidSphere(_particle[p].radius, 6, 6); glPopMatrix(); - // render velocity lines - glColor4f( _particle[p].color.x, _particle[p].color.y, _particle[p].color.z, 0.5f); - glm::vec3 end = _particle[p].position - _particle[p].velocity * 2.0f; - glBegin(GL_LINES); - glVertex3f(_particle[p].position.x, _particle[p].position.y, _particle[p].position.z); - glVertex3f(end.x, end.y, end.z); - - glEnd(); + if (SHOW_VELOCITY_TAILS) { + glColor4f( _particle[p].color.x, _particle[p].color.y, _particle[p].color.z, 0.5f); + glm::vec3 end = _particle[p].position - _particle[p].velocity * 2.0f; + glBegin(GL_LINES); + glVertex3f(_particle[p].position.x, _particle[p].position.y, _particle[p].position.z); + glVertex3f(end.x, end.y, end.z); + glEnd(); + } } } diff --git a/interface/src/ParticleSystem.h b/interface/src/ParticleSystem.h index deffc9a04d..244b791d39 100644 --- a/interface/src/ParticleSystem.h +++ b/interface/src/ParticleSystem.h @@ -13,14 +13,16 @@ const int MAX_PARTICLES = 5000; const int MAX_EMITTERS = 20; -const int NUM_PARTICLE_LIFE_STAGES = 3; +const int NUM_PARTICLE_LIFE_STAGES = 4; const bool USE_BILLBOARD_RENDERING = false; +const bool SHOW_VELOCITY_TAILS = false; class ParticleSystem { public: struct ParticleAttributes { float radius; + glm::vec4 color; float bounce; float gravity; float airFriction; @@ -40,8 +42,8 @@ public: void emitParticlesNow(int emitterIndex, int numParticles, float radius, glm::vec4 color, glm::vec3 velocity, float lifespan); void simulate(float deltaTime); void render(); - void setEmitterParticle(int emitterIndex, bool showing ); - void setEmitterParticle(int emitterIndex, bool showing, float radius, glm::vec4 color ); + void setEmitterBaseParticle(int emitterIndex, bool showing ); + void setEmitterBaseParticle(int emitterIndex, bool showing, float radius, glm::vec4 color ); void setOrangeBlueColorPalette(); // apply a nice preset color palette to the particles void setUpDirection(glm::vec3 upDirection) {_upDirection = upDirection;} // tell particle system which direction is up From aa0cab2180b943974ccaf3e16ff387be48e892dd Mon Sep 17 00:00:00 2001 From: Eric Johnston Date: Wed, 17 Jul 2013 16:09:24 -0700 Subject: [PATCH 67/81] Code review issues addressed. --- interface/src/Hand.cpp | 27 ++++++++++++++------------- libraries/avatars/src/AvatarData.cpp | 14 ++++++++------ libraries/avatars/src/HandData.cpp | 6 ++++-- libraries/avatars/src/HandData.h | 2 +- 4 files changed, 27 insertions(+), 22 deletions(-) diff --git a/interface/src/Hand.cpp b/interface/src/Hand.cpp index 5693ce7e2e..ec123beede 100755 --- a/interface/src/Hand.cpp +++ b/interface/src/Hand.cpp @@ -62,11 +62,12 @@ void Hand::calculateGeometry() { for (size_t f = 0; f < palm.getNumFingers(); ++f) { FingerData& finger = palm.getFingers()[f]; if (finger.isActive()) { + const float standardBallRadius = 0.01f; _leapBalls.resize(_leapBalls.size() + 1); HandBall& ball = _leapBalls.back(); ball.rotation = _baseOrientation; ball.position = finger.getTipPosition(); - ball.radius = 0.01; + ball.radius = standardBallRadius; ball.touchForce = 0.0; ball.isCollidable = true; } @@ -161,9 +162,10 @@ void Hand::renderHandSpheres() { for (size_t i = 0; i < getNumPalms(); ++i) { PalmData& palm = getPalms()[i]; if (palm.isActive()) { + const float palmThickness = 0.002f; glColor4f(_ballColor.r, _ballColor.g, _ballColor.b, 0.25); glm::vec3 tip = palm.getPosition(); - glm::vec3 root = palm.getPosition() + palm.getNormal() * 0.002f; + glm::vec3 root = palm.getPosition() + palm.getNormal() * palmThickness; Avatar::renderJointConnectingCone(root, tip, 0.05, 0.03); } } @@ -235,23 +237,22 @@ void Hand::updateFingerParticles(float deltaTime) { glm::vec3 particleEmitterPosition = finger.getTipPosition(); // this aspect is still being designed.... - - glm::vec3 tilt = glm::vec3 - ( - 30.0f * sinf( t * 0.55f ), - 0.0f, - 30.0f * cosf( t * 0.75f ) - ); + const float tiltMag = 30.0f; + const float tiltXFreq = 0.55f; + const float tiltZFreq = 0.75f; + glm::vec3 tilt = glm::vec3(tiltMag * sinf( t * tiltXFreq ), + 0.0f, + tiltMag * cosf( t * tiltZFreq )); glm::quat particleEmitterRotation = glm::quat(glm::radians(tilt)); _particleSystem.setEmitterPosition(_fingerParticleEmitter[0], particleEmitterPosition); _particleSystem.setEmitterRotation(_fingerParticleEmitter[0], particleEmitterRotation); - float radius = 0.005f; - glm::vec4 color(1.0f, 0.6f, 0.0f, 0.5f); - glm::vec3 velocity(0.0f, 0.005f, 0.0f); - float lifespan = 0.3f; + const float radius = 0.005f; + const glm::vec4 color(1.0f, 0.6f, 0.0f, 0.5f); + const glm::vec3 velocity(0.0f, 0.005f, 0.0f); + const float lifespan = 0.3f; _particleSystem.emitParticlesNow(_fingerParticleEmitter[0], 1, radius, color, velocity, lifespan); } } diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index fa0bffded0..01907b92f4 100755 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -18,6 +18,8 @@ using namespace std; +static const float fingerVectorRadix = 4; // bits of precision when converting from float<->fixed + AvatarData::AvatarData(Node* owningNode) : NodeData(owningNode), _handPosition(0,0,0), @@ -140,9 +142,9 @@ int AvatarData::getBroadcastData(unsigned char* destinationBuffer) { *destinationBuffer++ = (unsigned char)fingerVectors.size(); for (size_t i = 0; i < fingerVectors.size(); ++i) { - destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerVectors[i].x, 4); - destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerVectors[i].y, 4); - destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerVectors[i].z, 4); + destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerVectors[i].x, fingerVectorRadix); + destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerVectors[i].y, fingerVectorRadix); + destinationBuffer += packFloatScalarToSignedTwoByteFixed(destinationBuffer, fingerVectors[i].z, fingerVectorRadix); } // skeleton joints @@ -253,9 +255,9 @@ int AvatarData::parseData(unsigned char* sourceBuffer, int numBytes) { if (numFingerVectors > 0) { std::vector fingerVectors(numFingerVectors); for (size_t i = 0; i < numFingerVectors; ++i) { - sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerVectors[i].x), 4); - sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerVectors[i].y), 4); - sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerVectors[i].z), 4); + sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerVectors[i].x), fingerVectorRadix); + sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerVectors[i].y), fingerVectorRadix); + sourceBuffer += unpackFloatScalarFromSignedTwoByteFixed((int16_t*) sourceBuffer, &(fingerVectors[i].z), fingerVectorRadix); } _handData->decodeRemoteData(fingerVectors); } diff --git a/libraries/avatars/src/HandData.cpp b/libraries/avatars/src/HandData.cpp index f119472fa1..32e83b352d 100755 --- a/libraries/avatars/src/HandData.cpp +++ b/libraries/avatars/src/HandData.cpp @@ -13,8 +13,9 @@ HandData::HandData(AvatarData* owningAvatar) : _baseOrientation(0.0f, 0.0f, 0.0f, 1.0f), _owningAvatarData(owningAvatar) { - for (int i = 0; i < 2; ++i) + for (int i = 0; i < 2; ++i) { _palms.push_back(PalmData(this)); + } } PalmData::PalmData(HandData* owningHandData) : @@ -23,8 +24,9 @@ _rawNormal(0, 1, 0), _isActive(false), _owningHandData(owningHandData) { - for (int i = 0; i < NUM_FINGERS_PER_HAND; ++i) + for (int i = 0; i < NUM_FINGERS_PER_HAND; ++i) { _fingers.push_back(FingerData(this, owningHandData)); + } } FingerData::FingerData(PalmData* owningPalmData, HandData* owningHandData) : diff --git a/libraries/avatars/src/HandData.h b/libraries/avatars/src/HandData.h index ac5c509f55..65b32ff5c6 100755 --- a/libraries/avatars/src/HandData.h +++ b/libraries/avatars/src/HandData.h @@ -30,7 +30,7 @@ public: // position conversion glm::vec3 leapPositionToWorldPosition(const glm::vec3& leapPosition) { - float unitScale = 0.001; // convert mm to meters + const float unitScale = 0.001; // convert mm to meters return _basePosition + _baseOrientation * (leapPosition * unitScale); } glm::vec3 leapDirectionToWorldDirection(const glm::vec3& leapDirection) { From be5612711be6e2d4284baf68d8989763c0b2d26b Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Wed, 17 Jul 2013 16:43:34 -0700 Subject: [PATCH 68/81] clean up of particle system --- interface/src/Application.cpp | 13 +++---------- interface/src/ParticleSystem.cpp | 13 +++++-------- interface/src/ParticleSystem.h | 16 +++++++--------- 3 files changed, 15 insertions(+), 27 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 6057ae26ed..020a4d9316 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -73,7 +73,7 @@ using namespace std; static char STAR_FILE[] = "https://s3-us-west-1.amazonaws.com/highfidelity/stars.txt"; static char STAR_CACHE_FILE[] = "cachedStars.txt"; -static const bool TESTING_PARTICLE_SYSTEM = false; +static const bool TESTING_PARTICLE_SYSTEM = true; static const int BANDWIDTH_METER_CLICK_MAX_DRAG_LENGTH = 6; // farther dragged clicks are ignored @@ -3514,19 +3514,11 @@ void Application::updateParticleSystem(float deltaTime) { glm::vec4 color(0.0f, 0.0f, 0.0f, 1.0f); glm::vec3 velocity(0.0f, 0.1f, 0.0f); float lifespan = 100000.0f; - - // determine a collision sphere - glm::vec3 collisionSpherePosition = glm::vec3( 5.0f, 0.5f, 5.0f ); - float collisionSphereRadius = 0.5f; - _particleSystem.setCollisionSphere(_coolDemoParticleEmitter, collisionSpherePosition, collisionSphereRadius); _particleSystem.emitParticlesNow(_coolDemoParticleEmitter, 1500, radius, color, velocity, lifespan); } // signal that the particle system has been initialized _particleSystemInitialized = true; - - // apply a preset color palette - _particleSystem.setOrangeBlueColorPalette(); } else { // update the particle system @@ -3547,6 +3539,7 @@ void Application::updateParticleSystem(float deltaTime) { ParticleSystem::ParticleAttributes attributes; attributes.radius = 0.01f; + attributes.color = glm::vec4( 1.0f, 1.0f, 1.0f, 1.0f); attributes.gravity = 0.0f + 0.05f * sinf( t * 0.52f ); attributes.airFriction = 2.5 + 2.0f * sinf( t * 0.32f ); attributes.jitter = 0.05f + 0.05f * sinf( t * 0.42f ); @@ -3563,7 +3556,7 @@ void Application::updateParticleSystem(float deltaTime) { attributes.gravity = 0.0f; } - _particleSystem.setParticleAttributes(_coolDemoParticleEmitter, attributes); + _particleSystem.setParticleAttributes(_coolDemoParticleEmitter, attributes); } _particleSystem.setUpDirection(glm::vec3(0.0f, 1.0f, 0.0f)); diff --git a/interface/src/ParticleSystem.cpp b/interface/src/ParticleSystem.cpp index 15343203e4..fb96492515 100644 --- a/interface/src/ParticleSystem.cpp +++ b/interface/src/ParticleSystem.cpp @@ -147,7 +147,7 @@ void ParticleSystem::killParticle(int p) { _numParticles --; } - +/* void ParticleSystem::setOrangeBlueColorPalette() { for (unsigned int p = 0; p < _numParticles; p++) { @@ -163,6 +163,7 @@ void ParticleSystem::setOrangeBlueColorPalette() { _particle[p].color = glm::vec4(red, green, blue, alpha); } } +*/ void ParticleSystem::setParticleAttributes(int emitterIndex, ParticleAttributes attributes) { @@ -201,13 +202,7 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { int lifeStage = (int)( ageFraction * (NUM_PARTICLE_LIFE_STAGES-1) ); float lifeStageFraction = ageFraction * ( NUM_PARTICLE_LIFE_STAGES - 1 ) - lifeStage; - - /* - if ( p == 0 ) { - printf( "lifespan = %f ageFraction = %f lifeStage = %d lifeStageFraction = %f\n", _particle[p].lifespan, ageFraction, lifeStage, lifeStageFraction ); - } - */ - + _particle[p].radius = _emitter[_particle[p].emitterIndex].particleAttributes[lifeStage ].radius * (1.0f - lifeStageFraction) + _emitter[_particle[p].emitterIndex].particleAttributes[lifeStage+1].radius * lifeStageFraction; @@ -294,6 +289,7 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { _particle[p].age += deltaTime; } +/* void ParticleSystem::setCollisionSphere(int e, glm::vec3 position, float radius) { int lifeStage = 0; @@ -302,6 +298,7 @@ void ParticleSystem::setCollisionSphere(int e, glm::vec3 position, float radius) _emitter[e].particleAttributes[lifeStage].collisionSpherePosition = position; _emitter[e].particleAttributes[lifeStage].collisionSphereRadius = radius; } +*/ void ParticleSystem::setEmitterBaseParticle(int emitterIndex, bool showing ) { diff --git a/interface/src/ParticleSystem.h b/interface/src/ParticleSystem.h index 244b791d39..9b808f746b 100644 --- a/interface/src/ParticleSystem.h +++ b/interface/src/ParticleSystem.h @@ -42,17 +42,15 @@ public: void emitParticlesNow(int emitterIndex, int numParticles, float radius, glm::vec4 color, glm::vec3 velocity, float lifespan); void simulate(float deltaTime); void render(); + + void setUpDirection(glm::vec3 upDirection) {_upDirection = upDirection;} // tell particle system which direction is up void setEmitterBaseParticle(int emitterIndex, bool showing ); void setEmitterBaseParticle(int emitterIndex, bool showing, float radius, glm::vec4 color ); - - void setOrangeBlueColorPalette(); // apply a nice preset color palette to the particles - void setUpDirection(glm::vec3 upDirection) {_upDirection = upDirection;} // tell particle system which direction is up - void setParticleAttributes(int emitterIndex, ParticleAttributes attributes); - void setParticleAttributes(int emitterIndex, int lifeStage, ParticleAttributes attributes); - void setCollisionSphere (int emitterIndex, glm::vec3 position, float radius); // specify a sphere for the particles to collide with - void setEmitterPosition (int emitterIndex, glm::vec3 position) { _emitter[emitterIndex].position = position; } // set position of emitter - void setEmitterRotation (int emitterIndex, glm::quat rotation) { _emitter[emitterIndex].rotation = rotation; } // set rotation of emitter - void setShowingEmitter (int emitterIndex, bool showing ) { _emitter[emitterIndex].visible = showing; } // set its visibiity + void setParticleAttributes (int emitterIndex, ParticleAttributes attributes); + void setParticleAttributes (int emitterIndex, int lifeStage, ParticleAttributes attributes); + void setEmitterPosition (int emitterIndex, glm::vec3 position) { _emitter[emitterIndex].position = position; } // set position of emitter + void setEmitterRotation (int emitterIndex, glm::quat rotation) { _emitter[emitterIndex].rotation = rotation; } // set rotation of emitter + void setShowingEmitter (int emitterIndex, bool showing ) { _emitter[emitterIndex].visible = showing; } // set its visibiity private: From 1264b3ce66bbf2d7c91308d1f0378261e600b448 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Wed, 17 Jul 2013 17:00:18 -0700 Subject: [PATCH 69/81] removed deprecated code --- interface/src/ParticleSystem.cpp | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/interface/src/ParticleSystem.cpp b/interface/src/ParticleSystem.cpp index 076c8f6983..0b0b7a7389 100644 --- a/interface/src/ParticleSystem.cpp +++ b/interface/src/ParticleSystem.cpp @@ -147,24 +147,6 @@ void ParticleSystem::killParticle(int p) { _numParticles --; } -/* -void ParticleSystem::setOrangeBlueColorPalette() { - - for (unsigned int p = 0; p < _numParticles; p++) { - - float radian = ((float)p / (float)_numParticles) * PI_TIMES_TWO; - float wave = sinf(radian); - - float red = 0.5f + 0.5f * wave; - float green = 0.3f + 0.3f * wave; - float blue = 0.2f - 0.2f * wave; - float alpha = 1.0f; - - _particle[p].color = glm::vec4(red, green, blue, alpha); - } -} -*/ - void ParticleSystem::setParticleAttributes(int emitterIndex, ParticleAttributes attributes) { From 9c2ea6e7e4ebe8dea68352083e13a7335bcbb15c Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Wed, 17 Jul 2013 17:07:53 -0700 Subject: [PATCH 70/81] more clean up --- interface/src/Application.cpp | 2 +- interface/src/ParticleSystem.cpp | 11 ----------- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 5814575796..c2a3faa501 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -73,7 +73,7 @@ using namespace std; static char STAR_FILE[] = "https://s3-us-west-1.amazonaws.com/highfidelity/stars.txt"; static char STAR_CACHE_FILE[] = "cachedStars.txt"; -static const bool TESTING_PARTICLE_SYSTEM = true; +static const bool TESTING_PARTICLE_SYSTEM = false; static const int BANDWIDTH_METER_CLICK_MAX_DRAG_LENGTH = 6; // farther dragged clicks are ignored diff --git a/interface/src/ParticleSystem.cpp b/interface/src/ParticleSystem.cpp index 0b0b7a7389..81ed67bf6c 100644 --- a/interface/src/ParticleSystem.cpp +++ b/interface/src/ParticleSystem.cpp @@ -271,17 +271,6 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { _particle[p].age += deltaTime; } -/* -void ParticleSystem::setCollisionSphere(int e, glm::vec3 position, float radius) { - - int lifeStage = 0; - - _emitter[e].particleAttributes[lifeStage].usingCollisionSphere = true; - _emitter[e].particleAttributes[lifeStage].collisionSpherePosition = position; - _emitter[e].particleAttributes[lifeStage].collisionSphereRadius = radius; -} -*/ - void ParticleSystem::setEmitterBaseParticle(int emitterIndex, bool showing ) { _emitter[emitterIndex].baseParticle.alive = true; From f89b1fcd4c347b69770048d995b763f80c3c3139 Mon Sep 17 00:00:00 2001 From: Jeffrey Ventrella Date: Wed, 17 Jul 2013 18:10:30 -0700 Subject: [PATCH 71/81] more clean up of particle system --- interface/src/Application.cpp | 6 +- interface/src/Hand.cpp | 12 ++-- interface/src/ParticleSystem.cpp | 99 ++++++++++++++------------------ interface/src/ParticleSystem.h | 40 ++++++------- 4 files changed, 70 insertions(+), 87 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index c2a3faa501..8f14e8ed57 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -73,7 +73,7 @@ using namespace std; static char STAR_FILE[] = "https://s3-us-west-1.amazonaws.com/highfidelity/stars.txt"; static char STAR_CACHE_FILE[] = "cachedStars.txt"; -static const bool TESTING_PARTICLE_SYSTEM = false; +static const bool TESTING_PARTICLE_SYSTEM = true; static const int BANDWIDTH_METER_CLICK_MAX_DRAG_LENGTH = 6; // farther dragged clicks are ignored @@ -3510,11 +3510,9 @@ void Application::updateParticleSystem(float deltaTime) { _particleSystem.setShowingEmitter(_coolDemoParticleEmitter, true); glm::vec3 particleEmitterPosition = glm::vec3(5.0f, 1.0f, 5.0f); _particleSystem.setEmitterPosition(_coolDemoParticleEmitter, particleEmitterPosition); - float radius = 0.01f; - glm::vec4 color(0.0f, 0.0f, 0.0f, 1.0f); glm::vec3 velocity(0.0f, 0.1f, 0.0f); float lifespan = 100000.0f; - _particleSystem.emitParticlesNow(_coolDemoParticleEmitter, 1500, radius, color, velocity, lifespan); + _particleSystem.emitParticlesNow(_coolDemoParticleEmitter, 1500, velocity, lifespan); } // signal that the particle system has been initialized diff --git a/interface/src/Hand.cpp b/interface/src/Hand.cpp index bbfd58c5b1..69d8ddfaac 100755 --- a/interface/src/Hand.cpp +++ b/interface/src/Hand.cpp @@ -216,9 +216,13 @@ void Hand::updateFingerParticles(float deltaTime) { if (!_particleSystemInitialized) { for ( int f = 0; f< NUM_FINGERS_PER_HAND; f ++ ) { + + _particleSystem.setShowingEmitter(f, true ); _fingerParticleEmitter[f] = _particleSystem.addEmitter(); + assert( _fingerParticleEmitter[f] != -1 ); + ParticleSystem::ParticleAttributes attributes; // set attributes for each life stage of the particle: @@ -277,17 +281,17 @@ void Hand::updateFingerParticles(float deltaTime) { } else { fingerDirection = IDENTITY_UP; } + + glm::quat particleEmitterRotation = rotationBetween(palm.getNormal(), fingerDirection); - glm::quat particleEmitterRotation = rotationBetween(IDENTITY_UP, fingerDirection); + //glm::quat particleEmitterRotation = glm::angleAxis(0.0f, fingerDirection); _particleSystem.setEmitterPosition(_fingerParticleEmitter[f], particleEmitterPosition); _particleSystem.setEmitterRotation(_fingerParticleEmitter[f], particleEmitterRotation); - float radius = 0.005f; - const glm::vec4 color(1.0f, 0.6f, 0.0f, 0.5f); const glm::vec3 velocity = fingerDirection * 0.002f; const float lifespan = 1.0f; - _particleSystem.emitParticlesNow(_fingerParticleEmitter[f], 1, radius, color, velocity, lifespan); + _particleSystem.emitParticlesNow(_fingerParticleEmitter[f], 1, velocity, lifespan); } } } diff --git a/interface/src/ParticleSystem.cpp b/interface/src/ParticleSystem.cpp index 81ed67bf6c..9dcdbe5f06 100644 --- a/interface/src/ParticleSystem.cpp +++ b/interface/src/ParticleSystem.cpp @@ -21,36 +21,35 @@ ParticleSystem::ParticleSystem() { _numParticles = 0; _upDirection = glm::vec3(0.0f, 1.0f, 0.0f); // default - for (unsigned int e = 0; e < MAX_EMITTERS; e++) { - _emitter[e].position = glm::vec3(0.0f, 0.0f, 0.0f); - _emitter[e].rotation = glm::quat(); - _emitter[e].right = IDENTITY_RIGHT; - _emitter[e].up = IDENTITY_UP; - _emitter[e].front = IDENTITY_FRONT; - _emitter[e].visible = false; - _emitter[e].baseParticle.alive = false; - _emitter[e].baseParticle.age = 0.0f; - _emitter[e].baseParticle.lifespan = 0.0f; - _emitter[e].baseParticle.radius = 0.0f; - _emitter[e].baseParticle.emitterIndex = 0; - _emitter[e].baseParticle.position = glm::vec3(0.0f, 0.0f, 0.0f); - _emitter[e].baseParticle.velocity = glm::vec3(0.0f, 0.0f, 0.0f); - + for (unsigned int emitterIndex = 0; emitterIndex < MAX_EMITTERS; emitterIndex++) { + _emitter[emitterIndex].position = glm::vec3(0.0f, 0.0f, 0.0f); + _emitter[emitterIndex].rotation = glm::quat(); + _emitter[emitterIndex].visible = false; + _emitter[emitterIndex].baseParticle.alive = false; + _emitter[emitterIndex].baseParticle.age = 0.0f; + _emitter[emitterIndex].baseParticle.lifespan = 0.0f; + _emitter[emitterIndex].baseParticle.radius = 0.0f; + _emitter[emitterIndex].baseParticle.emitterIndex = 0; + _emitter[emitterIndex].baseParticle.position = glm::vec3(0.0f, 0.0f, 0.0f); + _emitter[emitterIndex].baseParticle.velocity = glm::vec3(0.0f, 0.0f, 0.0f); - for (int s = 0; sradius = DEFAULT_PARTICLE_RADIUS; + a->color = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f); + a->bounce = DEFAULT_PARTICLE_BOUNCE; + a->airFriction = DEFAULT_PARTICLE_AIR_FRICTION; + a->gravity = 0.0f; + a->jitter = 0.0f; + a->emitterAttraction = 0.0f; + a->tornadoForce = 0.0f; + a->neighborAttraction = 0.0f; + a->neighborRepulsion = 0.0f; + a->collisionSphereRadius = 0.0f; + a->collisionSpherePosition = glm::vec3(0.0f, 0.0f, 0.0f); + a->usingCollisionSphere = false; } }; @@ -79,11 +78,6 @@ int ParticleSystem::addEmitter() { void ParticleSystem::simulate(float deltaTime) { - // update emitters - for (unsigned int e = 0; e < _numEmitters; e++) { - updateEmitter(e, deltaTime); - } - // update particles for (unsigned int p = 0; p < _numParticles; p++) { if (_particle[p].alive) { @@ -96,23 +90,14 @@ void ParticleSystem::simulate(float deltaTime) { } } - -void ParticleSystem::updateEmitter(int e, float deltaTime) { - - _emitter[e].front = _emitter[e].rotation * IDENTITY_FRONT; - _emitter[e].right = _emitter[e].rotation * IDENTITY_RIGHT; - _emitter[e].up = _emitter[e].rotation * IDENTITY_UP; -} - - -void ParticleSystem::emitParticlesNow(int e, int num, float radius, glm::vec4 color, glm::vec3 velocity, float lifespan) { +void ParticleSystem::emitParticlesNow(int e, int num, glm::vec3 velocity, float lifespan) { for (unsigned int p = 0; p < num; p++) { - createParticle(e, _emitter[e].position, velocity, radius, color, lifespan); + createParticle(e, velocity, lifespan); } } -void ParticleSystem::createParticle(int e, glm::vec3 position, glm::vec3 velocity, float radius, glm::vec4 color, float lifespan) { +void ParticleSystem::createParticle(int e, glm::vec3 velocity, float lifespan) { for (unsigned int p = 0; p < MAX_PARTICLES; p++) { if (!_particle[p].alive) { @@ -121,12 +106,10 @@ void ParticleSystem::createParticle(int e, glm::vec3 position, glm::vec3 velocit _particle[p].lifespan = lifespan; _particle[p].alive = true; _particle[p].age = 0.0f; - _particle[p].position = position; _particle[p].velocity = velocity; - _particle[p].color = color; - - _particle[p].radius = _emitter[e].particleAttributes[0].radius; - _particle[p].color = _emitter[e].particleAttributes[0].color; + _particle[p].position = _emitter[e].position; + _particle[p].radius = _emitter[e].particleAttributes[0].radius; + _particle[p].color = _emitter[e].particleAttributes[0].color; _numParticles ++; @@ -227,7 +210,11 @@ void ParticleSystem::updateParticle(int p, float deltaTime) { } // apply tornado force - glm::vec3 tornadoDirection = glm::cross(vectorToHome, myEmitter.up); + + + glm::vec3 emitterUp = myEmitter.rotation * IDENTITY_UP; + + glm::vec3 tornadoDirection = glm::cross(vectorToHome, emitterUp); _particle[p].velocity += tornadoDirection * myEmitter.particleAttributes[lifeStage].tornadoForce * deltaTime; // apply air friction @@ -363,10 +350,10 @@ void ParticleSystem::renderParticle(int p) { void ParticleSystem::renderEmitter(int e, float size) { - - glm::vec3 r = _emitter[e].right * size; - glm::vec3 u = _emitter[e].up * size; - glm::vec3 f = _emitter[e].front * size; + + glm::vec3 r = _emitter[e].rotation * IDENTITY_FRONT * size; + glm::vec3 u = _emitter[e].rotation * IDENTITY_RIGHT * size; + glm::vec3 f = _emitter[e].rotation * IDENTITY_UP * size; glLineWidth(2.0f); diff --git a/interface/src/ParticleSystem.h b/interface/src/ParticleSystem.h index 268e11abb6..764800f23e 100644 --- a/interface/src/ParticleSystem.h +++ b/interface/src/ParticleSystem.h @@ -4,7 +4,6 @@ // // Created by Jeffrey on July 10, 2013 // -// #ifndef hifi_ParticleSystem_h #define hifi_ParticleSystem_h @@ -38,15 +37,15 @@ public: ParticleSystem(); - int addEmitter(); // add (create) an emitter and get its unique id - void emitParticlesNow(int emitterIndex, int numParticles, float radius, glm::vec4 color, glm::vec3 velocity, float lifespan); + int addEmitter(); // add (create new) emitter and get its unique id + void emitParticlesNow(int emitterIndex, int numParticles, glm::vec3 velocity, float lifespan); void simulate(float deltaTime); void render(); void setUpDirection(glm::vec3 upDirection) {_upDirection = upDirection;} // tell particle system which direction is up void setEmitterBaseParticle(int emitterIndex, bool showing ); void setEmitterBaseParticle(int emitterIndex, bool showing, float radius, glm::vec4 color ); - void setParticleAttributes (int emitterIndex, ParticleAttributes attributes); + void setParticleAttributes (int emitterIndex, ParticleAttributes attributes); void setParticleAttributes (int emitterIndex, int lifeStage, ParticleAttributes attributes); void setEmitterPosition (int emitterIndex, glm::vec3 position) { _emitter[emitterIndex].position = position; } // set position of emitter void setEmitterRotation (int emitterIndex, glm::quat rotation) { _emitter[emitterIndex].rotation = rotation; } // set rotation of emitter @@ -55,38 +54,33 @@ public: private: struct Particle { - bool alive; // is the particle active? - glm::vec3 position; // position - glm::vec3 velocity; // velocity - glm::vec4 color; // color (rgba) - float age; // age in seconds - float radius; // radius - float lifespan; // how long this particle stays alive (in seconds) - int emitterIndex; // which emitter created this particle? + bool alive; // is the particle active? + glm::vec3 position; // position + glm::vec3 velocity; // velocity + glm::vec4 color; // color (rgba) + float age; // age in seconds + float radius; // radius + float lifespan; // how long this particle stays alive (in seconds) + int emitterIndex; // which emitter created this particle? }; struct Emitter { glm::vec3 position; glm::quat rotation; - glm::vec3 right; // derived from rotation - glm::vec3 up; // derived from rotation - glm::vec3 front; // derived from rotation bool visible; Particle baseParticle; // a non-physical particle at the emitter position ParticleAttributes particleAttributes[NUM_PARTICLE_LIFE_STAGES]; // the attributes of particles emitted from this emitter }; - glm::vec3 _upDirection; - Emitter _emitter[MAX_EMITTERS]; - Particle _particle[MAX_PARTICLES]; - int _numParticles; - int _numEmitters; + glm::vec3 _upDirection; + Emitter _emitter[MAX_EMITTERS]; + Particle _particle[MAX_PARTICLES]; + int _numParticles; + int _numEmitters; // private methods - void updateEmitter(int e, float deltaTime); void updateParticle(int index, float deltaTime); - void createParticle(int e, glm::vec3 position, glm::vec3 velocity, float radius, glm::vec4 color, float lifespan); - //void runSpecialEffectsTest(int e, float deltaTime); // for debugging and artistic exploration + void createParticle(int e, glm::vec3 velocity, float lifespan); void killParticle(int p); void renderEmitter(int emitterIndex, float size); void renderParticle(int p); From 1e421d222d3c13cf1ba1ddf822c9d68f124d351d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 18 Jul 2013 10:20:01 -0700 Subject: [PATCH 72/81] cleaned up some compiler warnings and constants --- libraries/voxels/src/CoverageMap.cpp | 10 +++++----- libraries/voxels/src/VoxelConstants.h | 5 +++-- libraries/voxels/src/VoxelTree.cpp | 5 ++--- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/libraries/voxels/src/CoverageMap.cpp b/libraries/voxels/src/CoverageMap.cpp index 31bcfb64cb..170e30f28d 100644 --- a/libraries/voxels/src/CoverageMap.cpp +++ b/libraries/voxels/src/CoverageMap.cpp @@ -430,7 +430,7 @@ bool CoverageRegion::mergeItemsInArray(VoxelProjectedPolygon* seed, bool seedInA otherPolygon->merge(*seed); if (seedInArray) { - const int IGNORED = NULL; + int* IGNORED = NULL; // remove this otherOtherPolygon for our polygon array _polygonCount = removeFromSortedArrays((void*)seed, (void**)_polygons, _polygonDistances, IGNORED, @@ -479,7 +479,7 @@ void CoverageRegion::storeInArray(VoxelProjectedPolygon* polygon) { // in the list. We still check to see if the polygon is "in front" of the target polygon before we test occlusion. Since // sometimes things come out of order. const bool SORT_BY_SIZE = false; - const int IGNORED = NULL; + int IGNORED = 0; if (SORT_BY_SIZE) { // This old code assumes that polygons will always be added in z-buffer order, but that doesn't seem to // be a good assumption. So instead, we will need to sort this by distance. Use a binary search to find the @@ -488,12 +488,12 @@ void CoverageRegion::storeInArray(VoxelProjectedPolygon* polygon) { float reverseArea = 4.0f - area; //qDebug("store by size area=%f reverse area=%f\n", area, reverseArea); _polygonCount = insertIntoSortedArrays((void*)polygon, reverseArea, IGNORED, - (void**)_polygons, _polygonSizes, IGNORED, + (void**)_polygons, _polygonSizes, &IGNORED, _polygonCount, _polygonArraySize); } else { - const int IGNORED = NULL; + int IGNORED = 0; _polygonCount = insertIntoSortedArrays((void*)polygon, polygon->getDistance(), IGNORED, - (void**)_polygons, _polygonDistances, IGNORED, + (void**)_polygons, _polygonDistances, &IGNORED, _polygonCount, _polygonArraySize); } diff --git a/libraries/voxels/src/VoxelConstants.h b/libraries/voxels/src/VoxelConstants.h index 452772ff07..55dff0c69a 100644 --- a/libraries/voxels/src/VoxelConstants.h +++ b/libraries/voxels/src/VoxelConstants.h @@ -23,7 +23,8 @@ const glm::vec3 IDENTITY_FRONT = glm::vec3( 0.0f, 0.0f,-1.0f); const bool LOW_RES_MONO = false; // while in "low res mode" do voxels switch to monochrome const uint64_t CHANGE_FUDGE = 1000 * 200; // useconds of fudge in determining if we want to resend changed voxels -const int TREE_SCALE = 128; +const int TREE_SCALE = 128; // This is the number of meters of the 0.0 to 1.0 voxel universe +const float VOXEL_SIZE_SCALE = 50000.0f; // This controls the LOD bigger will make smaller voxels visible at greater distance const int NUMBER_OF_CHILDREN = 8; const int MAX_VOXEL_PACKET_SIZE = 1492; @@ -40,4 +41,4 @@ const glBufferIndex GLBUFFER_INDEX_UNKNOWN = ULONG_MAX; const float SIXTY_FPS_IN_MILLISECONDS = 1000.0f / 60.0f; const float VIEW_CULLING_RATE_IN_MILLISECONDS = 1000.0f; // once a second is fine -#endif +#endif \ No newline at end of file diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index 203ed7e908..9cb6a85f93 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -32,12 +32,11 @@ #include "VoxelTree.h" float boundaryDistanceForRenderLevel(unsigned int renderLevel) { - const float voxelSizeScale = 50000.0f; - return voxelSizeScale / powf(2, renderLevel); + return ::VOXEL_SIZE_SCALE / powf(2, renderLevel); } float boundaryDistanceSquaredForRenderLevel(unsigned int renderLevel) { - const float voxelSizeScale = (50000.0f/TREE_SCALE) * (50000.0f/TREE_SCALE); + const float voxelSizeScale = (::VOXEL_SIZE_SCALE/TREE_SCALE) * (::VOXEL_SIZE_SCALE/TREE_SCALE); return voxelSizeScale / powf(2, (2 * renderLevel)); } From 2ad99f3129becd8f51319ceb5e9e280fbf44502d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Jul 2013 10:26:08 -0700 Subject: [PATCH 73/81] point to stars file on non-SSL for easier RV redirect --- interface/src/Application.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index d6e3c1a89f..7b0694695b 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -70,7 +70,7 @@ using namespace std; // Starfield information -static char STAR_FILE[] = "https://s3-us-west-1.amazonaws.com/highfidelity/stars.txt"; +static char STAR_FILE[] = "http://s3-us-west-1.amazonaws.com/highfidelity/stars.txt"; static char STAR_CACHE_FILE[] = "cachedStars.txt"; static const bool TESTING_PARTICLE_SYSTEM = false; From b3b8ef33478883c8e6a034859b4324d9e6f9b534 Mon Sep 17 00:00:00 2001 From: Philip Rosedale Date: Thu, 18 Jul 2013 11:24:39 -0700 Subject: [PATCH 74/81] Gyros don't move view for small head movements --- interface/src/Head.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/interface/src/Head.cpp b/interface/src/Head.cpp index 84ae9fffe9..a477910d67 100644 --- a/interface/src/Head.cpp +++ b/interface/src/Head.cpp @@ -226,9 +226,9 @@ void Head::simulate(float deltaTime, bool isMine) { const float CAMERA_FOLLOW_HEAD_RATE_START = 0.01f; const float CAMERA_FOLLOW_HEAD_RATE_MAX = 0.5f; const float CAMERA_FOLLOW_HEAD_RATE_RAMP_RATE = 1.05f; - const float CAMERA_STOP_TOLERANCE_DEGREES = 0.1f; - const float CAMERA_PITCH_START_TOLERANCE_DEGREES = 10.0f; - const float CAMERA_YAW_START_TOLERANCE_DEGREES = 3.0f; + const float CAMERA_STOP_TOLERANCE_DEGREES = 0.5f; + const float CAMERA_PITCH_START_TOLERANCE_DEGREES = 20.0f; + const float CAMERA_YAW_START_TOLERANCE_DEGREES = 10.0f; float cameraHeadAngleDifference = glm::length(glm::vec2(_pitch - _cameraPitch, _yaw - _cameraYaw)); if (_isCameraMoving) { _cameraFollowHeadRate = glm::clamp(_cameraFollowHeadRate * CAMERA_FOLLOW_HEAD_RATE_RAMP_RATE, From c41f5e27ef9d686836375efba626d3899b0d9f4d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 18 Jul 2013 11:25:01 -0700 Subject: [PATCH 75/81] fixed crash --- libraries/voxels/src/CoverageMap.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/libraries/voxels/src/CoverageMap.cpp b/libraries/voxels/src/CoverageMap.cpp index 170e30f28d..634c67a71c 100644 --- a/libraries/voxels/src/CoverageMap.cpp +++ b/libraries/voxels/src/CoverageMap.cpp @@ -430,10 +430,10 @@ bool CoverageRegion::mergeItemsInArray(VoxelProjectedPolygon* seed, bool seedInA otherPolygon->merge(*seed); if (seedInArray) { - int* IGNORED = NULL; + int* IGNORED_ADDRESS = NULL; // remove this otherOtherPolygon for our polygon array _polygonCount = removeFromSortedArrays((void*)seed, - (void**)_polygons, _polygonDistances, IGNORED, + (void**)_polygons, _polygonDistances, IGNORED_ADDRESS, _polygonCount, _polygonArraySize); _totalPolygons--; } @@ -479,7 +479,8 @@ void CoverageRegion::storeInArray(VoxelProjectedPolygon* polygon) { // in the list. We still check to see if the polygon is "in front" of the target polygon before we test occlusion. Since // sometimes things come out of order. const bool SORT_BY_SIZE = false; - int IGNORED = 0; + const int IGNORED = 0; + int* IGNORED_ADDRESS = NULL; if (SORT_BY_SIZE) { // This old code assumes that polygons will always be added in z-buffer order, but that doesn't seem to // be a good assumption. So instead, we will need to sort this by distance. Use a binary search to find the @@ -488,12 +489,11 @@ void CoverageRegion::storeInArray(VoxelProjectedPolygon* polygon) { float reverseArea = 4.0f - area; //qDebug("store by size area=%f reverse area=%f\n", area, reverseArea); _polygonCount = insertIntoSortedArrays((void*)polygon, reverseArea, IGNORED, - (void**)_polygons, _polygonSizes, &IGNORED, + (void**)_polygons, _polygonSizes, IGNORED_ADDRESS, _polygonCount, _polygonArraySize); } else { - int IGNORED = 0; _polygonCount = insertIntoSortedArrays((void*)polygon, polygon->getDistance(), IGNORED, - (void**)_polygons, _polygonDistances, &IGNORED, + (void**)_polygons, _polygonDistances, IGNORED_ADDRESS, _polygonCount, _polygonArraySize); } From 67e5a6409e9c70f4083598287f55a1415774a772 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Jul 2013 14:07:08 -0700 Subject: [PATCH 76/81] don't not kill NODE_TYPE_VOXEL_SERVER in removeSilentNodes --- libraries/shared/src/NodeList.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 87ee133dbb..91fe1f4a21 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -472,8 +472,7 @@ void *removeSilentNodes(void *args) { for(NodeList::iterator node = nodeList->begin(); node != nodeList->end(); ++node) { - if ((checkTimeUSecs - node->getLastHeardMicrostamp()) > NODE_SILENCE_THRESHOLD_USECS - && node->getType() != NODE_TYPE_VOXEL_SERVER) { + if ((checkTimeUSecs - node->getLastHeardMicrostamp()) > NODE_SILENCE_THRESHOLD_USECS) { qDebug() << "Killed" << *node << "\n"; From 04a2dd3b8612c6fb451a382938298a441782fbaa Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Jul 2013 14:36:55 -0700 Subject: [PATCH 77/81] clear environment data on domain server switch --- interface/src/Application.cpp | 6 +++++- interface/src/Environment.cpp | 5 +++++ interface/src/Environment.h | 1 + 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index adb88147e9..e67d938bf1 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1148,15 +1148,19 @@ void Application::editPreferences() { // check if the domain server hostname is new if (memcmp(NodeList::getInstance()->getDomainHostname(), newHostname, sizeof(&newHostname)) != 0) { - // if so we need to clear the nodelist and delete the local voxels + // if so we need to clear the nodelist and delete the existing voxel and environment data Node *voxelServer = NodeList::getInstance()->soloNodeOfType(NODE_TYPE_VOXEL_SERVER); if (voxelServer) { voxelServer->lock(); } + // kill the local voxels _voxels.killLocalVoxels(); + // reset the environment to default + _environment.resetToDefault(); + if (voxelServer) { voxelServer->unlock(); } diff --git a/interface/src/Environment.cpp b/interface/src/Environment.cpp index 35ed121e38..adfb1cfb3b 100644 --- a/interface/src/Environment.cpp +++ b/interface/src/Environment.cpp @@ -47,6 +47,11 @@ void Environment::init() { _data[getZeroAddress()][0]; } +void Environment::resetToDefault() { + _data.clear(); + _data[getZeroAddress()][0]; +} + void Environment::renderAtmospheres(Camera& camera) { // get the lock for the duration of the call QMutexLocker locker(&_mutex); diff --git a/interface/src/Environment.h b/interface/src/Environment.h index f711f0c38c..7bdbfa600b 100644 --- a/interface/src/Environment.h +++ b/interface/src/Environment.h @@ -24,6 +24,7 @@ class Environment { public: void init(); + void resetToDefault(); void renderAtmospheres(Camera& camera); glm::vec3 getGravity (const glm::vec3& position); From 4dd6afc08f41dcb2a463c196aa6378ad42f55113 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Jul 2013 14:59:11 -0700 Subject: [PATCH 78/81] fix grabbing of domain server hostname from QString --- interface/src/Application.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index e67d938bf1..3a8d6cff48 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1143,8 +1143,7 @@ void Application::editPreferences() { return; } - - const char* newHostname = domainServerHostname->text().toLocal8Bit().data(); + const char* newHostname = domainServerHostname->text().toStdString().c_str(); // check if the domain server hostname is new if (memcmp(NodeList::getInstance()->getDomainHostname(), newHostname, sizeof(&newHostname)) != 0) { From 4f36a0cda1e326ce53bd1f7849c8f7e335c77674 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 18 Jul 2013 15:13:55 -0700 Subject: [PATCH 79/81] adjust server sleep time to allow 60fps (cherry picked from commit 4d1ae4308546214abbd5be295a2cc002fab91d44) --- voxel-server/src/main.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/voxel-server/src/main.cpp b/voxel-server/src/main.cpp index 5b1ad57861..8a8048035b 100644 --- a/voxel-server/src/main.cpp +++ b/voxel-server/src/main.cpp @@ -44,9 +44,9 @@ const int MIN_BRIGHTNESS = 64; const float DEATH_STAR_RADIUS = 4.0; const float MAX_CUBE = 0.05f; -const int VOXEL_SEND_INTERVAL_USECS = 100 * 1000; -int PACKETS_PER_CLIENT_PER_INTERVAL = 30; -const int SENDING_TIME_TO_SPARE = 20 * 1000; // usec of sending interval to spare for calculating voxels +const int VOXEL_SEND_INTERVAL_USECS = 17 * 1000; // approximately 60fps +int PACKETS_PER_CLIENT_PER_INTERVAL = 20; +const int SENDING_TIME_TO_SPARE = 5 * 1000; // usec of sending interval to spare for calculating voxels const int MAX_VOXEL_TREE_DEPTH_LEVELS = 4; From 45d82dc97cbd3c3a8289eb8a01d6332dba6bf419 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Jul 2013 15:20:05 -0700 Subject: [PATCH 80/81] correct reference to new hostname for Qt temp variable changes --- interface/src/Application.cpp | 7 ++++--- libraries/shared/src/NodeList.h | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 3a8d6cff48..f9cebf41b4 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1143,10 +1143,11 @@ void Application::editPreferences() { return; } - const char* newHostname = domainServerHostname->text().toStdString().c_str(); - + char newHostname[MAX_HOSTNAME_BYTES] = {}; + memcpy(newHostname, domainServerHostname->text().toAscii().data(), domainServerHostname->text().size()); + // check if the domain server hostname is new - if (memcmp(NodeList::getInstance()->getDomainHostname(), newHostname, sizeof(&newHostname)) != 0) { + if (memcmp(NodeList::getInstance()->getDomainHostname(), newHostname, strlen(newHostname)) != 0) { // if so we need to clear the nodelist and delete the existing voxel and environment data Node *voxelServer = NodeList::getInstance()->soloNodeOfType(NODE_TYPE_VOXEL_SERVER); diff --git a/libraries/shared/src/NodeList.h b/libraries/shared/src/NodeList.h index 20eaddc738..0c8a68d38c 100644 --- a/libraries/shared/src/NodeList.h +++ b/libraries/shared/src/NodeList.h @@ -32,7 +32,7 @@ const int DOMAIN_SERVER_CHECK_IN_USECS = 1 * 1000000; extern const char SOLO_NODE_TYPES[3]; -const int MAX_HOSTNAME_BYTES = 255; +const int MAX_HOSTNAME_BYTES = 256; extern const char DEFAULT_DOMAIN_HOSTNAME[MAX_HOSTNAME_BYTES]; extern const char DEFAULT_DOMAIN_IP[INET_ADDRSTRLEN]; // IP Address will be re-set by lookup on startup From a00b95666a619dbdd09bd180c0d913940c3b1463 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Jul 2013 15:49:07 -0700 Subject: [PATCH 81/81] don't listen to VS packets not from current VS --- interface/src/Application.cpp | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index f9cebf41b4..eb99feca47 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1148,12 +1148,8 @@ void Application::editPreferences() { // check if the domain server hostname is new if (memcmp(NodeList::getInstance()->getDomainHostname(), newHostname, strlen(newHostname)) != 0) { - // if so we need to clear the nodelist and delete the existing voxel and environment data - Node *voxelServer = NodeList::getInstance()->soloNodeOfType(NODE_TYPE_VOXEL_SERVER); - if (voxelServer) { - voxelServer->lock(); - } + NodeList::getInstance()->clear(); // kill the local voxels _voxels.killLocalVoxels(); @@ -1161,11 +1157,6 @@ void Application::editPreferences() { // reset the environment to default _environment.resetToDefault(); - if (voxelServer) { - voxelServer->unlock(); - } - - NodeList::getInstance()->clear(); NodeList::getInstance()->setDomainHostname(newHostname); } @@ -3356,7 +3347,7 @@ void* Application::networkReceive(void* args) { case PACKET_TYPE_ENVIRONMENT_DATA: { if (app->_renderVoxels->isChecked()) { Node* voxelServer = NodeList::getInstance()->soloNodeOfType(NODE_TYPE_VOXEL_SERVER); - if (voxelServer) { + if (voxelServer && socketMatch(voxelServer->getActiveSocket(), &senderAddress)) { voxelServer->lock(); if (app->_incomingPacket[0] == PACKET_TYPE_ENVIRONMENT_DATA) {