From 5e2a08b3c2f503a8e115a5a7b8f0bbf0b828d01e Mon Sep 17 00:00:00 2001
From: Andrew Meadows <andrew@highfidelity.io>
Date: Mon, 25 Jun 2018 10:36:36 -0700
Subject: [PATCH] handle deactivation of avatar entities differently

---
 .../physics/src/PhysicalEntitySimulation.cpp  | 21 ++++++++++++++++---
 .../physics/src/PhysicalEntitySimulation.h    |  8 +++++++
 2 files changed, 26 insertions(+), 3 deletions(-)

diff --git a/libraries/physics/src/PhysicalEntitySimulation.cpp b/libraries/physics/src/PhysicalEntitySimulation.cpp
index 4d31067c20..b990d3612b 100644
--- a/libraries/physics/src/PhysicalEntitySimulation.cpp
+++ b/libraries/physics/src/PhysicalEntitySimulation.cpp
@@ -312,11 +312,26 @@ void PhysicalEntitySimulation::handleDeactivatedMotionStates(const VectorOfMotio
         assert(state);
         if (state->getType() == MOTIONSTATE_TYPE_ENTITY) {
             EntityMotionState* entityState = static_cast<EntityMotionState*>(state);
-            if (!serverlessMode) {
-                entityState->handleDeactivation();
-            }
             EntityItemPointer entity = entityState->getEntity();
             _entitiesToSort.insert(entity);
+            if (!serverlessMode) {
+                if (entity->getClientOnly()) {
+                    switch (entityState->getOwnershipState()) {
+                        case EntityMotionState::OwnershipState::PendingBid:
+                            _bids.removeFirst(entityState);
+                            entityState->clearOwnershipState();
+                            break;
+                        case EntityMotionState::OwnershipState::LocallyOwned:
+                            _owned.removeFirst(entityState);
+                            entityState->clearOwnershipState();
+                            break;
+                        default:
+                            break;
+                    }
+                } else {
+                    entityState->handleDeactivation();
+                }
+            }
         }
     }
 }
diff --git a/libraries/physics/src/PhysicalEntitySimulation.h b/libraries/physics/src/PhysicalEntitySimulation.h
index 3f04347f18..fdf996df25 100644
--- a/libraries/physics/src/PhysicalEntitySimulation.h
+++ b/libraries/physics/src/PhysicalEntitySimulation.h
@@ -37,6 +37,14 @@ public:
         }
         pop_back();
     }
+    void removeFirst(EntityMotionState* state) {
+        for (uint32_t i = 0; i < size(); ++i) {
+            if ((*this)[i] == state) {
+                remove(i);
+                break;
+            }
+        }
+    }
 };
 
 class PhysicalEntitySimulation : public EntitySimulation {