| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238 |
- //
- // Copyright (c) 2008-2014 the Urho3D project.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to deal
- // in the Software without restriction, including without limitation the rights
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- // copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- // THE SOFTWARE.
- //
- #include "Precompiled.h"
- #include "Component.h"
- #include "Context.h"
- #include "CoreEvents.h"
- #include "File.h"
- #include "Log.h"
- #include "ObjectAnimation.h"
- #include "PackageFile.h"
- #include "Profiler.h"
- #include "ReplicationState.h"
- #include "ResourceCache.h"
- #include "ResourceEvents.h"
- #include "Scene.h"
- #include "SceneEvents.h"
- #include "SmoothedTransform.h"
- #include "SplinePath.h"
- #include "UnknownComponent.h"
- #include "ValueAnimation.h"
- #include "WorkQueue.h"
- #include "XMLFile.h"
- #include "DebugNew.h"
- namespace Urho3D
- {
- const char* SCENE_CATEGORY = "Scene";
- const char* LOGIC_CATEGORY = "Logic";
- const char* SUBSYSTEM_CATEGORY = "Subsystem";
- static const float DEFAULT_SMOOTHING_CONSTANT = 50.0f;
- static const float DEFAULT_SNAP_THRESHOLD = 5.0f;
- Scene::Scene(Context* context) :
- Node(context),
- replicatedNodeID_(FIRST_REPLICATED_ID),
- replicatedComponentID_(FIRST_REPLICATED_ID),
- localNodeID_(FIRST_LOCAL_ID),
- localComponentID_(FIRST_LOCAL_ID),
- checksum_(0),
- asyncLoadingMs_(5),
- timeScale_(1.0f),
- elapsedTime_(0),
- smoothingConstant_(DEFAULT_SMOOTHING_CONSTANT),
- snapThreshold_(DEFAULT_SNAP_THRESHOLD),
- updateEnabled_(true),
- asyncLoading_(false),
- threadedUpdate_(false)
- {
- // Assign an ID to self so that nodes can refer to this node as a parent
- SetID(GetFreeNodeID(REPLICATED));
- NodeAdded(this);
- SubscribeToEvent(E_UPDATE, HANDLER(Scene, HandleUpdate));
- SubscribeToEvent(E_RESOURCEBACKGROUNDLOADED, HANDLER(Scene, HandleResourceBackgroundLoaded));
- }
- Scene::~Scene()
- {
- // Remove root-level components first, so that scene subsystems such as the octree destroy themselves. This will speed up
- // the removal of child nodes' components
- RemoveAllComponents();
- RemoveAllChildren();
- // Remove scene reference and owner from all nodes that still exist
- for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
- i->second_->ResetScene();
- for (HashMap<unsigned, Node*>::Iterator i = localNodes_.Begin(); i != localNodes_.End(); ++i)
- i->second_->ResetScene();
- }
- void Scene::RegisterObject(Context* context)
- {
- context->RegisterFactory<Scene>();
- ACCESSOR_ATTRIBUTE("Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
- ACCESSOR_ATTRIBUTE("Time Scale", GetTimeScale, SetTimeScale, float, 1.0f, AM_DEFAULT);
- ACCESSOR_ATTRIBUTE("Smoothing Constant", GetSmoothingConstant, SetSmoothingConstant, float, DEFAULT_SMOOTHING_CONSTANT, AM_DEFAULT);
- ACCESSOR_ATTRIBUTE("Snap Threshold", GetSnapThreshold, SetSnapThreshold, float, DEFAULT_SNAP_THRESHOLD, AM_DEFAULT);
- ACCESSOR_ATTRIBUTE("Elapsed Time", GetElapsedTime, SetElapsedTime, float, 0.0f, AM_FILE);
- ATTRIBUTE("Next Replicated Node ID", int, replicatedNodeID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
- ATTRIBUTE("Next Replicated Component ID", int, replicatedComponentID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
- ATTRIBUTE("Next Local Node ID", int, localNodeID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
- ATTRIBUTE("Next Local Component ID", int, localComponentID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
- ATTRIBUTE("Variables", VariantMap, vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
- MIXED_ACCESSOR_ATTRIBUTE("Variable Names", GetVarNamesAttr, SetVarNamesAttr, String, String::EMPTY, AM_FILE | AM_NOEDIT);
- }
- bool Scene::Load(Deserializer& source, bool setInstanceDefault)
- {
- PROFILE(LoadScene);
- StopAsyncLoading();
- // Check ID
- if (source.ReadFileID() != "USCN")
- {
- LOGERROR(source.GetName() + " is not a valid scene file");
- return false;
- }
- LOGINFO("Loading scene from " + source.GetName());
- Clear();
- // Load the whole scene, then perform post-load if successfully loaded
- if (Node::Load(source, setInstanceDefault))
- {
- FinishLoading(&source);
- return true;
- }
- else
- return false;
- }
- bool Scene::Save(Serializer& dest) const
- {
- PROFILE(SaveScene);
- // Write ID first
- if (!dest.WriteFileID("USCN"))
- {
- LOGERROR("Could not save scene, writing to stream failed");
- return false;
- }
- Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
- if (ptr)
- LOGINFO("Saving scene to " + ptr->GetName());
- if (Node::Save(dest))
- {
- FinishSaving(&dest);
- return true;
- }
- else
- return false;
- }
- bool Scene::LoadXML(const XMLElement& source, bool setInstanceDefault)
- {
- PROFILE(LoadSceneXML);
- StopAsyncLoading();
- // Load the whole scene, then perform post-load if successfully loaded
- // Note: the scene filename and checksum can not be set, as we only used an XML element
- if (Node::LoadXML(source, setInstanceDefault))
- {
- FinishLoading(0);
- return true;
- }
- else
- return false;
- }
- void Scene::MarkNetworkUpdate()
- {
- if (!networkUpdate_)
- {
- MarkNetworkUpdate(this);
- networkUpdate_ = true;
- }
- }
- void Scene::AddReplicationState(NodeReplicationState* state)
- {
- Node::AddReplicationState(state);
- // This is the first update for a new connection. Mark all replicated nodes dirty
- for (HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
- state->sceneState_->dirtyNodes_.Insert(i->first_);
- }
- bool Scene::LoadXML(Deserializer& source)
- {
- PROFILE(LoadSceneXML);
- StopAsyncLoading();
- SharedPtr<XMLFile> xml(new XMLFile(context_));
- if (!xml->Load(source))
- return false;
- LOGINFO("Loading scene from " + source.GetName());
- Clear();
- if (Node::LoadXML(xml->GetRoot()))
- {
- FinishLoading(&source);
- return true;
- }
- else
- return false;
- }
- bool Scene::SaveXML(Serializer& dest) const
- {
- PROFILE(SaveSceneXML);
- SharedPtr<XMLFile> xml(new XMLFile(context_));
- XMLElement rootElem = xml->CreateRoot("scene");
- if (!SaveXML(rootElem))
- return false;
- Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
- if (ptr)
- LOGINFO("Saving scene to " + ptr->GetName());
- if (xml->Save(dest))
- {
- FinishSaving(&dest);
- return true;
- }
- else
- return false;
- }
- bool Scene::LoadAsync(File* file, LoadMode mode)
- {
- if (!file)
- {
- LOGERROR("Null file for async loading");
- return false;
- }
- StopAsyncLoading();
- // Check ID
- bool isSceneFile = file->ReadFileID() == "USCN";
- if (!isSceneFile)
- {
- // In resource load mode can load also object prefabs, which have no identifier
- if (mode > LOAD_RESOURCES_ONLY)
- {
- LOGERROR(file->GetName() + " is not a valid scene file");
- return false;
- }
- else
- file->Seek(0);
- }
- if (mode > LOAD_RESOURCES_ONLY)
- {
- LOGINFO("Loading scene from " + file->GetName());
- Clear();
- }
- asyncLoading_ = true;
- asyncProgress_.file_ = file;
- asyncProgress_.mode_ = mode;
- asyncProgress_.loadedNodes_ = asyncProgress_.totalNodes_ = asyncProgress_.loadedResources_ = asyncProgress_.totalResources_ = 0;
- asyncProgress_.resources_.Clear();
- if (mode > LOAD_RESOURCES_ONLY)
- {
- // Preload resources if appropriate, then return to the original position for loading the scene content
- if (mode != LOAD_SCENE)
- {
- PROFILE(FindResourcesToPreload);
- unsigned currentPos = file->GetPosition();
- PreloadResources(file, isSceneFile);
- file->Seek(currentPos);
- }
- // Store own old ID for resolving possible root node references
- unsigned nodeID = file->ReadUInt();
- resolver_.AddNode(nodeID, this);
- // Load root level components first
- if (!Node::Load(*file, resolver_, false))
- {
- StopAsyncLoading();
- return false;
- }
- // Then prepare to load child nodes in the async updates
- asyncProgress_.totalNodes_ = file->ReadVLE();
- }
- else
- {
- PROFILE(FindResourcesToPreload);
- LOGINFO("Preloading resources from " + file->GetName());
- PreloadResources(file, isSceneFile);
- }
- return true;
- }
- bool Scene::LoadAsyncXML(File* file, LoadMode mode)
- {
- if (!file)
- {
- LOGERROR("Null file for async loading");
- return false;
- }
- StopAsyncLoading();
- SharedPtr<XMLFile> xml(new XMLFile(context_));
- if (!xml->Load(*file))
- return false;
- if (mode > LOAD_RESOURCES_ONLY)
- {
- LOGINFO("Loading scene from " + file->GetName());
- Clear();
- }
- asyncLoading_ = true;
- asyncProgress_.xmlFile_ = xml;
- asyncProgress_.file_ = file;
- asyncProgress_.mode_ = mode;
- asyncProgress_.loadedNodes_ = asyncProgress_.totalNodes_ = asyncProgress_.loadedResources_ = asyncProgress_.totalResources_ = 0;
- asyncProgress_.resources_.Clear();
- if (mode > LOAD_RESOURCES_ONLY)
- {
- XMLElement rootElement = xml->GetRoot();
- // Preload resources if appropriate
- if (mode != LOAD_SCENE)
- {
- PROFILE(FindResourcesToPreload);
- PreloadResourcesXML(rootElement);
- }
- // Store own old ID for resolving possible root node references
- unsigned nodeID = rootElement.GetInt("id");
- resolver_.AddNode(nodeID, this);
- // Load the root level components first
- if (!Node::LoadXML(rootElement, resolver_, false))
- return false;
- // Then prepare for loading all root level child nodes in the async update
- XMLElement childNodeElement = rootElement.GetChild("node");
- asyncProgress_.xmlElement_ = childNodeElement;
- // Count the amount of child nodes
- while (childNodeElement)
- {
- ++asyncProgress_.totalNodes_;
- childNodeElement = childNodeElement.GetNext("node");
- }
- }
- else
- {
- PROFILE(FindResourcesToPreload);
- LOGINFO("Preloading resources from " + file->GetName());
- PreloadResourcesXML(xml->GetRoot());
- }
- return true;
- }
- void Scene::StopAsyncLoading()
- {
- asyncLoading_ = false;
- asyncProgress_.file_.Reset();
- asyncProgress_.xmlFile_.Reset();
- asyncProgress_.xmlElement_ = XMLElement::EMPTY;
- asyncProgress_.resources_.Clear();
- resolver_.Reset();
- }
- Node* Scene::Instantiate(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
- {
- PROFILE(Instantiate);
- SceneResolver resolver;
- unsigned nodeID = source.ReadInt();
- // Rewrite IDs when instantiating
- Node* node = CreateChild(0, mode);
- resolver.AddNode(nodeID, node);
- if (node->Load(source, resolver, true, true, mode))
- {
- resolver.Resolve();
- node->ApplyAttributes();
- node->SetTransform(position, rotation);
- return node;
- }
- else
- {
- node->Remove();
- return 0;
- }
- }
- Node* Scene::InstantiateXML(const XMLElement& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
- {
- PROFILE(InstantiateXML);
- SceneResolver resolver;
- unsigned nodeID = source.GetInt("id");
- // Rewrite IDs when instantiating
- Node* node = CreateChild(0, mode);
- resolver.AddNode(nodeID, node);
- if (node->LoadXML(source, resolver, true, true, mode))
- {
- resolver.Resolve();
- node->ApplyAttributes();
- node->SetTransform(position, rotation);
- return node;
- }
- else
- {
- node->Remove();
- return 0;
- }
- }
- Node* Scene::InstantiateXML(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
- {
- SharedPtr<XMLFile> xml(new XMLFile(context_));
- if (!xml->Load(source))
- return 0;
- return InstantiateXML(xml->GetRoot(), position, rotation, mode);
- }
- void Scene::Clear(bool clearReplicated, bool clearLocal)
- {
- StopAsyncLoading();
- RemoveChildren(clearReplicated, clearLocal, true);
- RemoveComponents(clearReplicated, clearLocal);
- // Only clear name etc. if clearing completely
- if (clearReplicated && clearLocal)
- {
- UnregisterAllVars();
- SetName(String::EMPTY);
- fileName_.Clear();
- checksum_ = 0;
- }
- // Reset ID generators
- if (clearReplicated)
- {
- replicatedNodeID_ = FIRST_REPLICATED_ID;
- replicatedComponentID_ = FIRST_REPLICATED_ID;
- }
- if (clearLocal)
- {
- localNodeID_ = FIRST_LOCAL_ID;
- localComponentID_ = FIRST_LOCAL_ID;
- }
- }
- void Scene::SetUpdateEnabled(bool enable)
- {
- updateEnabled_ = enable;
- }
- void Scene::SetTimeScale(float scale)
- {
- timeScale_ = Max(scale, M_EPSILON);
- Node::MarkNetworkUpdate();
- }
- void Scene::SetSmoothingConstant(float constant)
- {
- smoothingConstant_ = Max(constant, M_EPSILON);
- Node::MarkNetworkUpdate();
- }
- void Scene::SetSnapThreshold(float threshold)
- {
- snapThreshold_ = Max(threshold, 0.0f);
- Node::MarkNetworkUpdate();
- }
- void Scene::SetAsyncLoadingMs(int ms)
- {
- asyncLoadingMs_ = Max(ms, 1);
- }
- void Scene::SetElapsedTime(float time)
- {
- elapsedTime_ = time;
- }
- void Scene::AddRequiredPackageFile(PackageFile* package)
- {
- // Do not add packages that failed to load
- if (!package || !package->GetNumFiles())
- return;
- requiredPackageFiles_.Push(SharedPtr<PackageFile>(package));
- }
- void Scene::ClearRequiredPackageFiles()
- {
- requiredPackageFiles_.Clear();
- }
- void Scene::RegisterVar(const String& name)
- {
- varNames_[name] = name;
- }
- void Scene::UnregisterVar(const String& name)
- {
- varNames_.Erase(name);
- }
- void Scene::UnregisterAllVars()
- {
- varNames_.Clear();
- }
- Node* Scene::GetNode(unsigned id) const
- {
- if (id < FIRST_LOCAL_ID)
- {
- HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Find(id);
- if (i != replicatedNodes_.End())
- return i->second_;
- else
- return 0;
- }
- else
- {
- HashMap<unsigned, Node*>::ConstIterator i = localNodes_.Find(id);
- if (i != localNodes_.End())
- return i->second_;
- else
- return 0;
- }
- }
- Component* Scene::GetComponent(unsigned id) const
- {
- if (id < FIRST_LOCAL_ID)
- {
- HashMap<unsigned, Component*>::ConstIterator i = replicatedComponents_.Find(id);
- if (i != replicatedComponents_.End())
- return i->second_;
- else
- return 0;
- }
- else
- {
- HashMap<unsigned, Component*>::ConstIterator i = localComponents_.Find(id);
- if (i != localComponents_.End())
- return i->second_;
- else
- return 0;
- }
- }
- float Scene::GetAsyncProgress() const
- {
- if (!asyncLoading_ || asyncProgress_.totalNodes_ + asyncProgress_.totalResources_ == 0)
- return 1.0f;
- else
- {
- return (float)(asyncProgress_.loadedNodes_ + asyncProgress_.loadedResources_) / (float)(asyncProgress_.totalNodes_ +
- asyncProgress_.totalResources_);
- }
- }
- const String& Scene::GetVarName(StringHash hash) const
- {
- HashMap<StringHash, String>::ConstIterator i = varNames_.Find(hash);
- return i != varNames_.End() ? i->second_ : String::EMPTY;
- }
- void Scene::Update(float timeStep)
- {
- if (asyncLoading_)
- {
- UpdateAsyncLoading();
- // If only preloading resources, scene update can continue
- if (asyncProgress_.mode_ > LOAD_RESOURCES_ONLY)
- return;
- }
- PROFILE(UpdateScene);
- timeStep *= timeScale_;
- using namespace SceneUpdate;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = this;
- eventData[P_TIMESTEP] = timeStep;
- // Update variable timestep logic
- SendEvent(E_SCENEUPDATE, eventData);
- // Update scene attribute animation.
- SendEvent(E_ATTRIBUTEANIMATIONUPDATE, eventData);
- // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
- SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
- // Update transform smoothing
- {
- PROFILE(UpdateSmoothing);
- float constant = 1.0f - Clamp(powf(2.0f, -timeStep * smoothingConstant_), 0.0f, 1.0f);
- float squaredSnapThreshold = snapThreshold_ * snapThreshold_;
- using namespace UpdateSmoothing;
- smoothingData_[P_CONSTANT] = constant;
- smoothingData_[P_SQUAREDSNAPTHRESHOLD] = squaredSnapThreshold;
- SendEvent(E_UPDATESMOOTHING, smoothingData_);
- }
- // Post-update variable timestep logic
- SendEvent(E_SCENEPOSTUPDATE, eventData);
- // Note: using a float for elapsed time accumulation is inherently inaccurate. The purpose of this value is
- // primarily to update material animation effects, as it is available to shaders. It can be reset by calling
- // SetElapsedTime()
- elapsedTime_ += timeStep;
- }
- void Scene::BeginThreadedUpdate()
- {
- // Check the work queue subsystem whether it actually has created worker threads. If not, do not enter threaded mode.
- if (GetSubsystem<WorkQueue>()->GetNumThreads())
- threadedUpdate_ = true;
- }
- void Scene::EndThreadedUpdate()
- {
- if (!threadedUpdate_)
- return;
- threadedUpdate_ = false;
- if (!delayedDirtyComponents_.Empty())
- {
- PROFILE(EndThreadedUpdate);
- for (PODVector<Component*>::ConstIterator i = delayedDirtyComponents_.Begin(); i != delayedDirtyComponents_.End(); ++i)
- (*i)->OnMarkedDirty((*i)->GetNode());
- delayedDirtyComponents_.Clear();
- }
- }
- void Scene::DelayedMarkedDirty(Component* component)
- {
- MutexLock lock(sceneMutex_);
- delayedDirtyComponents_.Push(component);
- }
- unsigned Scene::GetFreeNodeID(CreateMode mode)
- {
- if (mode == REPLICATED)
- {
- for (;;)
- {
- unsigned ret = replicatedNodeID_;
- if (replicatedNodeID_ < LAST_REPLICATED_ID)
- ++replicatedNodeID_;
- else
- replicatedNodeID_ = FIRST_REPLICATED_ID;
- if (!replicatedNodes_.Contains(ret))
- return ret;
- }
- }
- else
- {
- for (;;)
- {
- unsigned ret = localNodeID_;
- if (localNodeID_ < LAST_LOCAL_ID)
- ++localNodeID_;
- else
- localNodeID_ = FIRST_LOCAL_ID;
- if (!localNodes_.Contains(ret))
- return ret;
- }
- }
- }
- unsigned Scene::GetFreeComponentID(CreateMode mode)
- {
- if (mode == REPLICATED)
- {
- for (;;)
- {
- unsigned ret = replicatedComponentID_;
- if (replicatedComponentID_ < LAST_REPLICATED_ID)
- ++replicatedComponentID_;
- else
- replicatedComponentID_ = FIRST_REPLICATED_ID;
- if (!replicatedComponents_.Contains(ret))
- return ret;
- }
- }
- else
- {
- for (;;)
- {
- unsigned ret = localComponentID_;
- if (localComponentID_ < LAST_LOCAL_ID)
- ++localComponentID_;
- else
- localComponentID_ = FIRST_LOCAL_ID;
- if (!localComponents_.Contains(ret))
- return ret;
- }
- }
- }
- void Scene::NodeAdded(Node* node)
- {
- if (!node || node->GetScene() == this)
- return;
- // If node already exists in another scene, remove. This is unsupported, as components will not reinitialize themselves
- // to use the new scene
- Scene* oldScene = node->GetScene();
- if (oldScene)
- {
- LOGERROR("Moving a node from one scene to another is unsupported");
- oldScene->NodeRemoved(node);
- }
- node->SetScene(this);
- // If the new node has an ID of zero (default), assign a replicated ID now
- unsigned id = node->GetID();
- if (!id)
- {
- id = GetFreeNodeID(REPLICATED);
- node->SetID(id);
- }
- // If node with same ID exists, remove the scene reference from it and overwrite with the new node
- if (id < FIRST_LOCAL_ID)
- {
- HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Find(id);
- if (i != replicatedNodes_.End() && i->second_ != node)
- {
- LOGWARNING("Overwriting node with ID " + String(id));
- i->second_->ResetScene();
- }
- replicatedNodes_[id] = node;
- MarkNetworkUpdate(node);
- MarkReplicationDirty(node);
- }
- else
- {
- HashMap<unsigned, Node*>::Iterator i = localNodes_.Find(id);
- if (i != localNodes_.End() && i->second_ != node)
- {
- LOGWARNING("Overwriting node with ID " + String(id));
- i->second_->ResetScene();
- }
- localNodes_[id] = node;
- }
- }
- void Scene::NodeRemoved(Node* node)
- {
- if (!node || node->GetScene() != this)
- return;
- unsigned id = node->GetID();
- if (id < FIRST_LOCAL_ID)
- {
- replicatedNodes_.Erase(id);
- MarkReplicationDirty(node);
- }
- else
- localNodes_.Erase(id);
- node->SetID(0);
- node->SetScene(0);
- // Remove components and child nodes as well
- const Vector<SharedPtr<Component> >& components = node->GetComponents();
- for (Vector<SharedPtr<Component> >::ConstIterator i = components.Begin(); i != components.End(); ++i)
- ComponentRemoved(*i);
- const Vector<SharedPtr<Node> >& children = node->GetChildren();
- for (Vector<SharedPtr<Node> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
- NodeRemoved(*i);
- }
- void Scene::ComponentAdded(Component* component)
- {
- if (!component)
- return;
- unsigned id = component->GetID();
- if (id < FIRST_LOCAL_ID)
- {
- HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Find(id);
- if (i != replicatedComponents_.End() && i->second_ != component)
- {
- LOGWARNING("Overwriting component with ID " + String(id));
- i->second_->SetID(0);
- }
- replicatedComponents_[id] = component;
- }
- else
- {
- HashMap<unsigned, Component*>::Iterator i = localComponents_.Find(id);
- if (i != localComponents_.End() && i->second_ != component)
- {
- LOGWARNING("Overwriting component with ID " + String(id));
- i->second_->SetID(0);
- }
- localComponents_[id] = component;
- }
- }
- void Scene::ComponentRemoved(Component* component)
- {
- if (!component)
- return;
- unsigned id = component->GetID();
- if (id < FIRST_LOCAL_ID)
- replicatedComponents_.Erase(id);
- else
- localComponents_.Erase(id);
- component->SetID(0);
- }
- void Scene::SetVarNamesAttr(const String& value)
- {
- Vector<String> varNames = value.Split(';');
- varNames_.Clear();
- for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
- varNames_[*i] = *i;
- }
- String Scene::GetVarNamesAttr() const
- {
- String ret;
- if (!varNames_.Empty())
- {
- for (HashMap<StringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
- ret += i->second_ + ';';
- ret.Resize(ret.Length() - 1);
- }
- return ret;
- }
- void Scene::PrepareNetworkUpdate()
- {
- for (HashSet<unsigned>::Iterator i = networkUpdateNodes_.Begin(); i != networkUpdateNodes_.End(); ++i)
- {
- Node* node = GetNode(*i);
- if (node)
- node->PrepareNetworkUpdate();
- }
- for (HashSet<unsigned>::Iterator i = networkUpdateComponents_.Begin(); i != networkUpdateComponents_.End(); ++i)
- {
- Component* component = GetComponent(*i);
- if (component)
- component->PrepareNetworkUpdate();
- }
- networkUpdateNodes_.Clear();
- networkUpdateComponents_.Clear();
- }
- void Scene::CleanupConnection(Connection* connection)
- {
- Node::CleanupConnection(connection);
- for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
- i->second_->CleanupConnection(connection);
- for (HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Begin(); i != replicatedComponents_.End(); ++i)
- i->second_->CleanupConnection(connection);
- }
- void Scene::MarkNetworkUpdate(Node* node)
- {
- if (node)
- {
- if (!threadedUpdate_)
- networkUpdateNodes_.Insert(node->GetID());
- else
- {
- MutexLock lock(sceneMutex_);
- networkUpdateNodes_.Insert(node->GetID());
- }
- }
- }
- void Scene::MarkNetworkUpdate(Component* component)
- {
- if (component)
- {
- if (!threadedUpdate_)
- networkUpdateComponents_.Insert(component->GetID());
- else
- {
- MutexLock lock(sceneMutex_);
- networkUpdateComponents_.Insert(component->GetID());
- }
- }
- }
- void Scene::MarkReplicationDirty(Node* node)
- {
- unsigned id = node->GetID();
- if (id < FIRST_LOCAL_ID && networkState_)
- {
- for (PODVector<ReplicationState*>::Iterator i = networkState_->replicationStates_.Begin(); i !=
- networkState_->replicationStates_.End(); ++i)
- {
- NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*i);
- nodeState->sceneState_->dirtyNodes_.Insert(id);
- }
- }
- }
- void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
- {
- using namespace Update;
- if (updateEnabled_)
- Update(eventData[P_TIMESTEP].GetFloat());
- }
- void Scene::HandleResourceBackgroundLoaded(StringHash eventType, VariantMap& eventData)
- {
- using namespace ResourceBackgroundLoaded;
- if (asyncLoading_)
- {
- Resource* resource = static_cast<Resource*>(eventData[P_RESOURCE].GetPtr());
- if (asyncProgress_.resources_.Contains(resource->GetNameHash()))
- {
- asyncProgress_.resources_.Erase(resource->GetNameHash());
- ++asyncProgress_.loadedResources_;
- }
- }
- }
- void Scene::UpdateAsyncLoading()
- {
- PROFILE(UpdateAsyncLoading);
- // If resources left to load, do not load nodes yet
- if (asyncProgress_.loadedResources_ < asyncProgress_.totalResources_)
- return;
- HiresTimer asyncLoadTimer;
- for (;;)
- {
- if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
- {
- FinishAsyncLoading();
- return;
- }
- // Read one child node with its full sub-hierarchy either from binary or XML
- /// \todo Works poorly in scenes where one root-level child node contains all content
- if (!asyncProgress_.xmlFile_)
- {
- unsigned nodeID = asyncProgress_.file_->ReadUInt();
- Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
- resolver_.AddNode(nodeID, newNode);
- newNode->Load(*asyncProgress_.file_, resolver_);
- }
- else
- {
- unsigned nodeID = asyncProgress_.xmlElement_.GetInt("id");
- Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
- resolver_.AddNode(nodeID, newNode);
- newNode->LoadXML(asyncProgress_.xmlElement_, resolver_);
- asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
- }
- ++asyncProgress_.loadedNodes_;
- // Break if time limit exceeded, so that we keep sufficient FPS
- if (asyncLoadTimer.GetUSec(false) >= asyncLoadingMs_ * 1000)
- break;
- }
- using namespace AsyncLoadProgress;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = this;
- eventData[P_PROGRESS] = GetAsyncProgress();
- eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
- eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
- eventData[P_LOADEDRESOURCES] = asyncProgress_.loadedResources_;
- eventData[P_TOTALRESOURCES] = asyncProgress_.totalResources_;
- SendEvent(E_ASYNCLOADPROGRESS, eventData);
- }
- void Scene::FinishAsyncLoading()
- {
- if (asyncProgress_.mode_ > LOAD_RESOURCES_ONLY)
- {
- resolver_.Resolve();
- ApplyAttributes();
- FinishLoading(asyncProgress_.file_);
- }
- StopAsyncLoading();
- using namespace AsyncLoadFinished;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = this;
- SendEvent(E_ASYNCLOADFINISHED, eventData);
- }
- void Scene::FinishLoading(Deserializer* source)
- {
- if (source)
- {
- fileName_ = source->GetName();
- checksum_ = source->GetChecksum();
- }
- }
- void Scene::FinishSaving(Serializer* dest) const
- {
- Deserializer* ptr = dynamic_cast<Deserializer*>(dest);
- if (ptr)
- {
- fileName_ = ptr->GetName();
- checksum_ = ptr->GetChecksum();
- }
- }
- void Scene::PreloadResources(File* file, bool isSceneFile)
- {
- ResourceCache* cache = GetSubsystem<ResourceCache>();
- // Read node ID (not needed)
- /*unsigned nodeID = */file->ReadUInt();
- // Read Node or Scene attributes; these do not include any resources
- const Vector<AttributeInfo>* attributes = context_->GetAttributes(isSceneFile ? Scene::GetTypeStatic() : Node::GetTypeStatic());
- assert(attributes);
- for (unsigned i = 0; i < attributes->Size(); ++i)
- {
- const AttributeInfo& attr = attributes->At(i);
- if (!(attr.mode_ & AM_FILE))
- continue;
- Variant varValue = file->ReadVariant(attr.type_);
- }
- // Read component attributes
- unsigned numComponents = file->ReadVLE();
- for (unsigned i = 0; i < numComponents; ++i)
- {
- VectorBuffer compBuffer(*file, file->ReadVLE());
- StringHash compType = compBuffer.ReadStringHash();
- // Read component ID (not needed)
- /*unsigned compID = */compBuffer.ReadUInt();
- attributes = context_->GetAttributes(compType);
- if (attributes)
- {
- for (unsigned j = 0; j < attributes->Size(); ++j)
- {
- const AttributeInfo& attr = attributes->At(j);
- if (!(attr.mode_ & AM_FILE))
- continue;
- Variant varValue = compBuffer.ReadVariant(attr.type_);
- if (attr.type_ == VAR_RESOURCEREF)
- {
- const ResourceRef& ref = varValue.GetResourceRef();
- // Sanitate resource name beforehand so that when we get the background load event, the name matches exactly
- String name = cache->SanitateResourceName(ref.name_);
- bool success = cache->BackgroundLoadResource(ref.type_, name);
- if (success)
- {
- ++asyncProgress_.totalResources_;
- asyncProgress_.resources_.Insert(StringHash(name));
- }
- }
- else if (attr.type_ == VAR_RESOURCEREFLIST)
- {
- const ResourceRefList& refList = varValue.GetResourceRefList();
- for (unsigned k = 0; k < refList.names_.Size(); ++k)
- {
- String name = cache->SanitateResourceName(refList.names_[k]);
- bool success = cache->BackgroundLoadResource(refList.type_, name);
- if (success)
- {
- ++asyncProgress_.totalResources_;
- asyncProgress_.resources_.Insert(StringHash(name));
- }
- }
- }
- }
- }
- }
- // Read child nodes
- unsigned numChildren = file->ReadVLE();
- for (unsigned i = 0; i < numChildren; ++i)
- PreloadResources(file, false);
- }
- void Scene::PreloadResourcesXML(const XMLElement& element)
- {
- ResourceCache* cache = GetSubsystem<ResourceCache>();
- // Node or Scene attributes do not include any resources; therefore skip to the components
- XMLElement compElem = element.GetChild("component");
- while (compElem)
- {
- String typeName = compElem.GetAttribute("type");
- const Vector<AttributeInfo>* attributes = context_->GetAttributes(StringHash(typeName));
- if (attributes)
- {
- XMLElement attrElem = compElem.GetChild("attribute");
- unsigned startIndex = 0;
- while (attrElem)
- {
- String name = attrElem.GetAttribute("name");
- unsigned i = startIndex;
- unsigned attempts = attributes->Size();
- while (attempts)
- {
- const AttributeInfo& attr = attributes->At(i);
- if ((attr.mode_ & AM_FILE) && !attr.name_.Compare(name, true))
- {
- if (attr.type_ == VAR_RESOURCEREF)
- {
- ResourceRef ref = attrElem.GetVariantValue(attr.type_).GetResourceRef();
- String name = cache->SanitateResourceName(ref.name_);
- bool success = cache->BackgroundLoadResource(ref.type_, name);
- if (success)
- {
- ++asyncProgress_.totalResources_;
- asyncProgress_.resources_.Insert(StringHash(name));
- }
- }
- else if (attr.type_ == VAR_RESOURCEREFLIST)
- {
- ResourceRefList refList = attrElem.GetVariantValue(attr.type_).GetResourceRefList();
- for (unsigned k = 0; k < refList.names_.Size(); ++k)
- {
- String name = cache->SanitateResourceName(refList.names_[k]);
- bool success = cache->BackgroundLoadResource(refList.type_, name);
- if (success)
- {
- ++asyncProgress_.totalResources_;
- asyncProgress_.resources_.Insert(StringHash(name));
- }
- }
- }
- startIndex = (i + 1) % attributes->Size();
- break;
- }
- else
- {
- i = (i + 1) % attributes->Size();
- --attempts;
- }
- }
- attrElem = attrElem.GetNext("attribute");
- }
- }
- compElem = compElem.GetNext("component");
- }
- XMLElement childElem = element.GetChild("node");
- while (childElem)
- {
- PreloadResourcesXML(childElem);
- childElem = childElem.GetNext("node");
- }
- }
- void RegisterSceneLibrary(Context* context)
- {
- ValueAnimation::RegisterObject(context);
- ObjectAnimation::RegisterObject(context);
- Node::RegisterObject(context);
- Scene::RegisterObject(context);
- SmoothedTransform::RegisterObject(context);
- UnknownComponent::RegisterObject(context);
- SplinePath::RegisterObject(context);
- }
- }
|