| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253 |
- // Copyright (c) 2008-2023 the Urho3D project
- // License: MIT
- #include "../Precompiled.h"
- #include "../Core/Context.h"
- #include "../Core/Profiler.h"
- #include "../IO/Log.h"
- #include "../IO/MemoryBuffer.h"
- #include "../Resource/XMLFile.h"
- #include "../Resource/JSONFile.h"
- #include "../Scene/Component.h"
- #include "../Scene/ObjectAnimation.h"
- #include "../Scene/ReplicationState.h"
- #include "../Scene/Scene.h"
- #include "../Scene/SceneEvents.h"
- #include "../Scene/SmoothedTransform.h"
- #include "../Scene/UnknownComponent.h"
- #include "../DebugNew.h"
- using namespace std;
- namespace Urho3D
- {
- Node::Node(Context* context) :
- Animatable(context),
- worldTransform_(Matrix3x4::IDENTITY),
- dirty_(false),
- enabled_(true),
- enabledPrev_(true),
- networkUpdate_(false),
- parent_(nullptr),
- scene_(nullptr),
- id_(0),
- position_(Vector3::ZERO),
- rotation_(Quaternion::IDENTITY),
- scale_(Vector3::ONE),
- worldRotation_(Quaternion::IDENTITY)
- {
- impl_ = make_unique<NodeImpl>();
- impl_->owner_ = nullptr;
- }
- Node::~Node()
- {
- RemoveAllChildren();
- RemoveAllComponents();
- // Remove from the scene
- if (scene_)
- scene_->NodeRemoved(this);
- }
- void Node::RegisterObject(Context* context)
- {
- context->RegisterFactory<Node>();
- URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, true, AM_DEFAULT);
- URHO3D_ACCESSOR_ATTRIBUTE("Name", GetName, SetName, String::EMPTY, AM_DEFAULT);
- URHO3D_ACCESSOR_ATTRIBUTE("Tags", GetTags, SetTags, Variant::emptyStringVector, AM_DEFAULT);
- URHO3D_ACCESSOR_ATTRIBUTE("Position", GetPosition, SetPosition, Vector3::ZERO, AM_FILE);
- URHO3D_ACCESSOR_ATTRIBUTE("Rotation", GetRotation, SetRotation, Quaternion::IDENTITY, AM_FILE);
- URHO3D_ACCESSOR_ATTRIBUTE("Scale", GetScale, SetScale, Vector3::ONE, AM_DEFAULT);
- URHO3D_ATTRIBUTE("Variables", vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
- URHO3D_ACCESSOR_ATTRIBUTE("Network Position", GetNetPositionAttr, SetNetPositionAttr, Vector3::ZERO,
- AM_NET | AM_LATESTDATA | AM_NOEDIT);
- URHO3D_ACCESSOR_ATTRIBUTE("Network Rotation", GetNetRotationAttr, SetNetRotationAttr, Variant::emptyBuffer,
- AM_NET | AM_LATESTDATA | AM_NOEDIT);
- URHO3D_ACCESSOR_ATTRIBUTE("Network Parent Node", GetNetParentAttr, SetNetParentAttr, Variant::emptyBuffer,
- AM_NET | AM_NOEDIT);
- }
- bool Node::Load(Deserializer& source)
- {
- SceneResolver resolver;
- // Read own ID. Will not be applied, only stored for resolving possible references
- NodeId nodeID = source.ReadU32();
- resolver.AddNode(nodeID, this);
- // Read attributes, components and child nodes
- bool success = Load(source, resolver);
- if (success)
- {
- resolver.Resolve();
- ApplyAttributes();
- }
- return success;
- }
- bool Node::Save(Serializer& dest) const
- {
- // Write node ID
- if (!dest.WriteU32(id_))
- return false;
- // Write attributes
- if (!Animatable::Save(dest))
- return false;
- // Write components
- dest.WriteVLE(GetNumPersistentComponents());
- for (const SharedPtr<Component>& component : components_)
- {
- if (component->IsTemporary())
- continue;
- // Create a separate buffer to be able to skip failing components during deserialization
- VectorBuffer compBuffer;
- if (!component->Save(compBuffer))
- return false;
- dest.WriteVLE(compBuffer.GetSize());
- dest.Write(compBuffer.GetData(), compBuffer.GetSize());
- }
- // Write child nodes
- dest.WriteVLE(GetNumPersistentChildren());
- for (const SharedPtr<Node>& node : children_)
- {
- if (node->IsTemporary())
- continue;
- if (!node->Save(dest))
- return false;
- }
- return true;
- }
- bool Node::LoadXML(const XMLElement& source)
- {
- SceneResolver resolver;
- // Read own ID. Will not be applied, only stored for resolving possible references
- NodeId nodeID = source.GetU32("id");
- resolver.AddNode(nodeID, this);
- // Read attributes, components and child nodes
- bool success = LoadXML(source, resolver);
- if (success)
- {
- resolver.Resolve();
- ApplyAttributes();
- }
- return success;
- }
- bool Node::LoadJSON(const JSONValue& source)
- {
- SceneResolver resolver;
- // Read own ID. Will not be applied, only stored for resolving possible references
- NodeId nodeID = source.Get("id").GetU32();
- resolver.AddNode(nodeID, this);
- // Read attributes, components and child nodes
- bool success = LoadJSON(source, resolver);
- if (success)
- {
- resolver.Resolve();
- ApplyAttributes();
- }
- return success;
- }
- bool Node::SaveXML(XMLElement& dest) const
- {
- // Write node ID
- if (!dest.SetU32("id", id_))
- return false;
- // Write attributes
- if (!Animatable::SaveXML(dest))
- return false;
- // Write components
- for (const SharedPtr<Component>& component : components_)
- {
- if (component->IsTemporary())
- continue;
- XMLElement compElem = dest.CreateChild("component");
- if (!component->SaveXML(compElem))
- return false;
- }
- // Write child nodes
- for (const SharedPtr<Node>& node : children_)
- {
- if (node->IsTemporary())
- continue;
- XMLElement childElem = dest.CreateChild("node");
- if (!node->SaveXML(childElem))
- return false;
- }
- return true;
- }
- bool Node::SaveJSON(JSONValue& dest) const
- {
- // Write node ID
- dest.Set("id", id_);
- // Write attributes
- if (!Animatable::SaveJSON(dest))
- return false;
- // Write components
- JSONArray componentsArray;
- componentsArray.Reserve(components_.Size());
- for (const SharedPtr<Component>& component : components_)
- {
- if (component->IsTemporary())
- continue;
- JSONValue compVal;
- if (!component->SaveJSON(compVal))
- return false;
- componentsArray.Push(compVal);
- }
- dest.Set("components", componentsArray);
- // Write child nodes
- JSONArray childrenArray;
- childrenArray.Reserve(children_.Size());
- for (const SharedPtr<Node>& node : children_)
- {
- if (node->IsTemporary())
- continue;
- JSONValue childVal;
- if (!node->SaveJSON(childVal))
- return false;
- childrenArray.Push(childVal);
- }
- dest.Set("children", childrenArray);
- return true;
- }
- void Node::ApplyAttributes()
- {
- for (const SharedPtr<Component>& component : components_)
- component->ApplyAttributes();
- for (const SharedPtr<Node>& child : children_)
- child->ApplyAttributes();
- }
- void Node::MarkNetworkUpdate()
- {
- if (!networkUpdate_ && scene_ && IsReplicated())
- {
- scene_->MarkNetworkUpdate(this);
- networkUpdate_ = true;
- }
- }
- void Node::AddReplicationState(NodeReplicationState* state)
- {
- if (!networkState_)
- AllocateNetworkState();
- networkState_->replicationStates_.Push(state);
- }
- bool Node::SaveXML(Serializer& dest, const String& indentation) const
- {
- SharedPtr<XMLFile> xml(new XMLFile(context_));
- XMLElement rootElem = xml->CreateRoot("node");
- if (!SaveXML(rootElem))
- return false;
- return xml->Save(dest, indentation);
- }
- bool Node::SaveJSON(Serializer& dest, const String& indentation) const
- {
- SharedPtr<JSONFile> json(new JSONFile(context_));
- JSONValue& rootElem = json->GetRoot();
- if (!SaveJSON(rootElem))
- return false;
- return json->Save(dest, indentation);
- }
- void Node::SetName(const String& name)
- {
- if (name != impl_->name_)
- {
- impl_->name_ = name;
- impl_->nameHash_ = name;
- MarkNetworkUpdate();
- // Send change event
- if (scene_)
- {
- using namespace NodeNameChanged;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = scene_;
- eventData[P_NODE] = this;
- scene_->SendEvent(E_NODENAMECHANGED, eventData);
- }
- }
- }
- void Node::SetTags(const StringVector& tags)
- {
- RemoveAllTags();
- AddTags(tags);
- // MarkNetworkUpdate() already called in RemoveAllTags() / AddTags()
- }
- void Node::AddTag(const String& tag)
- {
- // Check if tag empty or already added
- if (tag.Empty() || HasTag(tag))
- return;
- // Add tag
- impl_->tags_.Push(tag);
- // Cache
- if (scene_)
- {
- scene_->NodeTagAdded(this, tag);
- // Send event
- using namespace NodeTagAdded;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = scene_;
- eventData[P_NODE] = this;
- eventData[P_TAG] = tag;
- scene_->SendEvent(E_NODETAGADDED, eventData);
- }
- // Sync
- MarkNetworkUpdate();
- }
- void Node::AddTags(const String& tags, char separator)
- {
- StringVector tagVector = tags.Split(separator);
- AddTags(tagVector);
- }
- void Node::AddTags(const StringVector& tags)
- {
- // This is OK, as MarkNetworkUpdate() early-outs when called multiple times
- for (const String& tag : tags)
- AddTag(tag);
- }
- bool Node::RemoveTag(const String& tag)
- {
- bool removed = impl_->tags_.Remove(tag);
- // Nothing to do
- if (!removed)
- return false;
- // Scene cache update
- if (scene_)
- {
- scene_->NodeTagRemoved(this, tag);
- // Send event
- using namespace NodeTagRemoved;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = scene_;
- eventData[P_NODE] = this;
- eventData[P_TAG] = tag;
- scene_->SendEvent(E_NODETAGREMOVED, eventData);
- }
- // Sync
- MarkNetworkUpdate();
- return true;
- }
- void Node::RemoveAllTags()
- {
- // Clear old scene cache
- if (scene_)
- {
- for (const String& tag : impl_->tags_)
- {
- scene_->NodeTagRemoved(this, tag);
- // Send event
- using namespace NodeTagRemoved;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = scene_;
- eventData[P_NODE] = this;
- eventData[P_TAG] = tag;
- scene_->SendEvent(E_NODETAGREMOVED, eventData);
- }
- }
- impl_->tags_.Clear();
- // Sync
- MarkNetworkUpdate();
- }
- void Node::SetPosition(const Vector3& position)
- {
- position_ = position;
- MarkDirty();
- MarkNetworkUpdate();
- }
- void Node::SetRotation(const Quaternion& rotation)
- {
- rotation_ = rotation;
- MarkDirty();
- MarkNetworkUpdate();
- }
- void Node::SetDirection(const Vector3& direction)
- {
- SetRotation(Quaternion(Vector3::FORWARD, direction));
- }
- void Node::SetScale(float scale)
- {
- SetScale(Vector3(scale, scale, scale));
- }
- void Node::SetScale(const Vector3& scale)
- {
- scale_ = scale;
- // Prevent exact zero scale e.g. from momentary edits as this may cause division by zero
- // when decomposing the world transform matrix
- if (scale_.x_ == 0.0f)
- scale_.x_ = M_EPSILON;
- if (scale_.y_ == 0.0f)
- scale_.y_ = M_EPSILON;
- if (scale_.z_ == 0.0f)
- scale_.z_ = M_EPSILON;
- MarkDirty();
- MarkNetworkUpdate();
- }
- void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
- {
- position_ = position;
- rotation_ = rotation;
- MarkDirty();
- MarkNetworkUpdate();
- }
- void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
- {
- SetTransform(position, rotation, Vector3(scale, scale, scale));
- }
- void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
- {
- position_ = position;
- rotation_ = rotation;
- scale_ = scale;
- MarkDirty();
- MarkNetworkUpdate();
- }
- void Node::SetTransform(const Matrix3x4& matrix)
- {
- SetTransform(matrix.Translation(), matrix.Rotation(), matrix.Scale());
- }
- void Node::SetWorldPosition(const Vector3& position)
- {
- SetPosition((parent_ == scene_ || !parent_) ? position : parent_->GetWorldTransform().Inverse() * position);
- }
- void Node::SetWorldRotation(const Quaternion& rotation)
- {
- SetRotation((parent_ == scene_ || !parent_) ? rotation : parent_->GetWorldRotation().Inverse() * rotation);
- }
- void Node::SetWorldDirection(const Vector3& direction)
- {
- Vector3 localDirection = (parent_ == scene_ || !parent_) ? direction : parent_->GetWorldRotation().Inverse() * direction;
- SetRotation(Quaternion(Vector3::FORWARD, localDirection));
- }
- void Node::SetWorldScale(float scale)
- {
- SetWorldScale(Vector3(scale, scale, scale));
- }
- void Node::SetWorldScale(const Vector3& scale)
- {
- SetScale((parent_ == scene_ || !parent_) ? scale : scale / parent_->GetWorldScale());
- }
- void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
- {
- SetWorldPosition(position);
- SetWorldRotation(rotation);
- }
- void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
- {
- SetWorldPosition(position);
- SetWorldRotation(rotation);
- SetWorldScale(scale);
- }
- void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
- {
- SetWorldPosition(position);
- SetWorldRotation(rotation);
- SetWorldScale(scale);
- }
- void Node::SetWorldTransform(const Matrix3x4& worldTransform)
- {
- SetWorldTransform(worldTransform.Translation(), worldTransform.Rotation(), worldTransform.Scale());
- }
- void Node::Translate(const Vector3& delta, TransformSpace space)
- {
- switch (space)
- {
- case TransformSpace::Local:
- // Note: local space translation disregards local scale for scale-independent movement speed
- position_ += rotation_ * delta;
- break;
- case TransformSpace::Parent:
- position_ += delta;
- break;
- case TransformSpace::World:
- position_ += (parent_ == scene_ || !parent_) ? delta : parent_->GetWorldTransform().Inverse() * Vector4(delta, 0.0f);
- break;
- }
- MarkDirty();
- MarkNetworkUpdate();
- }
- void Node::Rotate(const Quaternion& delta, TransformSpace space)
- {
- switch (space)
- {
- case TransformSpace::Local:
- rotation_ = (rotation_ * delta).Normalized();
- break;
- case TransformSpace::Parent:
- rotation_ = (delta * rotation_).Normalized();
- break;
- case TransformSpace::World:
- if (parent_ == scene_ || !parent_)
- rotation_ = (delta * rotation_).Normalized();
- else
- {
- Quaternion worldRotation = GetWorldRotation();
- rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation;
- }
- break;
- }
- MarkDirty();
- MarkNetworkUpdate();
- }
- void Node::RotateAround(const Vector3& point, const Quaternion& delta, TransformSpace space)
- {
- Vector3 parentSpacePoint;
- Quaternion oldRotation = rotation_;
- switch (space)
- {
- case TransformSpace::Local:
- parentSpacePoint = GetTransform() * point;
- rotation_ = (rotation_ * delta).Normalized();
- break;
- case TransformSpace::Parent:
- parentSpacePoint = point;
- rotation_ = (delta * rotation_).Normalized();
- break;
- case TransformSpace::World:
- if (parent_ == scene_ || !parent_)
- {
- parentSpacePoint = point;
- rotation_ = (delta * rotation_).Normalized();
- }
- else
- {
- parentSpacePoint = parent_->GetWorldTransform().Inverse() * point;
- Quaternion worldRotation = GetWorldRotation();
- rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation;
- }
- break;
- }
- Vector3 oldRelativePos = oldRotation.Inverse() * (position_ - parentSpacePoint);
- position_ = rotation_ * oldRelativePos + parentSpacePoint;
- MarkDirty();
- MarkNetworkUpdate();
- }
- void Node::Yaw(float angle, TransformSpace space)
- {
- Rotate(Quaternion(angle, Vector3::UP), space);
- }
- void Node::Pitch(float angle, TransformSpace space)
- {
- Rotate(Quaternion(angle, Vector3::RIGHT), space);
- }
- void Node::Roll(float angle, TransformSpace space)
- {
- Rotate(Quaternion(angle, Vector3::FORWARD), space);
- }
- bool Node::LookAt(const Vector3& target, const Vector3& up, TransformSpace space)
- {
- Vector3 worldSpaceTarget;
- switch (space)
- {
- case TransformSpace::Local:
- worldSpaceTarget = GetWorldTransform() * target;
- break;
- case TransformSpace::Parent:
- worldSpaceTarget = (parent_ == scene_ || !parent_) ? target : parent_->GetWorldTransform() * target;
- break;
- case TransformSpace::World:
- worldSpaceTarget = target;
- break;
- }
- Vector3 lookDir = worldSpaceTarget - GetWorldPosition();
- // Check if target is very close, in that case can not reliably calculate lookat direction
- if (lookDir.Equals(Vector3::ZERO))
- return false;
- Quaternion newRotation;
- // Do nothing if setting look rotation failed
- if (!newRotation.FromLookRotation(lookDir, up))
- return false;
- SetWorldRotation(newRotation);
- return true;
- }
- void Node::Scale(float scale)
- {
- Scale(Vector3(scale, scale, scale));
- }
- void Node::Scale(const Vector3& scale)
- {
- scale_ *= scale;
- MarkDirty();
- MarkNetworkUpdate();
- }
- void Node::SetEnabled(bool enable)
- {
- SetEnabled(enable, false, true);
- }
- void Node::SetDeepEnabled(bool enable)
- {
- SetEnabled(enable, true, false);
- }
- void Node::ResetDeepEnabled()
- {
- SetEnabled(enabledPrev_, false, false);
- for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- (*i)->ResetDeepEnabled();
- }
- void Node::SetEnabledRecursive(bool enable)
- {
- SetEnabled(enable, true, true);
- }
- void Node::SetOwner(Connection* owner)
- {
- impl_->owner_ = owner;
- }
- void Node::MarkDirty()
- {
- Node *cur = this;
- for (;;)
- {
- // Precondition:
- // a) whenever a node is marked dirty, all its children are marked dirty as well.
- // b) whenever a node is cleared from being dirty, all its parents must have been
- // cleared as well.
- // Therefore if we are recursing here to mark this node dirty, and it already was,
- // then all children of this node must also be already dirty, and we don't need to
- // reflag them again.
- if (cur->dirty_)
- return;
- cur->dirty_ = true;
- // Notify listener components first, then mark child nodes
- for (Vector<WeakPtr<Component>>::Iterator i = cur->listeners_.Begin(); i != cur->listeners_.End();)
- {
- Component *c = *i;
- if (c)
- {
- c->OnMarkedDirty(cur);
- ++i;
- }
- // If listener has expired, erase from list (swap with the last element to avoid O(n^2) behavior)
- else
- {
- *i = cur->listeners_.Back();
- cur->listeners_.Pop();
- }
- }
- // Tail call optimization: Don't recurse to mark the first child dirty, but
- // instead process it in the context of the current function. If there are more
- // than one child, then recurse to the excess children.
- Vector<SharedPtr<Node>>::Iterator i = cur->children_.Begin();
- if (i != cur->children_.End())
- {
- Node *next = *i;
- for (++i; i != cur->children_.End(); ++i)
- (*i)->MarkDirty();
- cur = next;
- }
- else
- return;
- }
- }
- Node* Node::CreateChild(const String& name, CreateMode mode, NodeId id, bool temporary)
- {
- Node* newNode = CreateChild(id, mode, temporary);
- newNode->SetName(name);
- return newNode;
- }
- Node* Node::CreateTemporaryChild(const String& name, CreateMode mode, NodeId id)
- {
- return CreateChild(name, mode, id, true);
- }
- void Node::AddChild(Node* node, i32 index)
- {
- assert((index >= 0 && index <= children_.Size()) || index == ENDPOS);
- // Check for illegal or redundant parent assignment
- if (!node || node == this || node->parent_ == this)
- return;
- // Check for possible cyclic parent assignment
- if (IsChildOf(node))
- return;
- // Keep a shared ptr to the node while transferring
- SharedPtr<Node> nodeShared(node);
- Node* oldParent = node->parent_;
- if (oldParent)
- {
- // If old parent is in different scene, perform the full removal
- if (oldParent->GetScene() != scene_)
- oldParent->RemoveChild(node);
- else
- {
- if (scene_)
- {
- // Otherwise do not remove from the scene during reparenting, just send the necessary change event
- using namespace NodeRemoved;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = scene_;
- eventData[P_PARENT] = oldParent;
- eventData[P_NODE] = node;
- scene_->SendEvent(E_NODEREMOVED, eventData);
- }
- oldParent->children_.Remove(nodeShared);
- }
- }
- // Add to the child vector, then add to the scene if not added yet
- children_.Insert(index, nodeShared);
- if (scene_ && node->GetScene() != scene_)
- scene_->NodeAdded(node);
- node->parent_ = this;
- node->MarkDirty();
- node->MarkNetworkUpdate();
- // If the child node has components, also mark network update on them to ensure they have a valid NetworkState
- for (Vector<SharedPtr<Component>>::Iterator i = node->components_.Begin(); i != node->components_.End(); ++i)
- (*i)->MarkNetworkUpdate();
- // Send change event
- if (scene_)
- {
- using namespace NodeAdded;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = scene_;
- eventData[P_PARENT] = this;
- eventData[P_NODE] = node;
- scene_->SendEvent(E_NODEADDED, eventData);
- }
- }
- void Node::RemoveChild(Node* node)
- {
- if (!node)
- return;
- for (Vector<SharedPtr<Node>>::Iterator i = children_.Begin(); i != children_.End(); ++i)
- {
- if (*i == node)
- {
- RemoveChild(i);
- return;
- }
- }
- }
- void Node::RemoveAllChildren()
- {
- RemoveChildren(true, true, true);
- }
- void Node::RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive)
- {
- i32 numRemoved = 0;
- for (i32 i = children_.Size() - 1; i >= 0; --i)
- {
- bool remove = false;
- Node* childNode = children_[i];
- if (recursive)
- childNode->RemoveChildren(removeReplicated, removeLocal, true);
- if (childNode->IsReplicated() && removeReplicated)
- remove = true;
- else if (!childNode->IsReplicated() && removeLocal)
- remove = true;
- if (remove)
- {
- RemoveChild(children_.Begin() + i);
- ++numRemoved;
- }
- }
- // Mark node dirty in all replication states
- if (numRemoved)
- MarkReplicationDirty();
- }
- Component* Node::CreateComponent(StringHash type, CreateMode mode, ComponentId id)
- {
- // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
- // as replicated components are synced over
- if (mode == REPLICATED && !IsReplicated())
- mode = LOCAL;
- // Check that creation succeeds and that the object in fact is a component
- SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
- if (!newComponent)
- {
- URHO3D_LOGERROR("Could not create unknown component type " + type.ToString());
- return nullptr;
- }
- AddComponent(newComponent, id, mode);
- return newComponent;
- }
- Component* Node::GetOrCreateComponent(StringHash type, CreateMode mode, ComponentId id)
- {
- Component* oldComponent = GetComponent(type);
- if (oldComponent)
- return oldComponent;
- else
- return CreateComponent(type, mode, id);
- }
- Component* Node::CloneComponent(Component* component, ComponentId id)
- {
- if (!component)
- {
- URHO3D_LOGERROR("Null source component given for CloneComponent");
- return nullptr;
- }
- return CloneComponent(component, component->IsReplicated() ? REPLICATED : LOCAL, id);
- }
- Component* Node::CloneComponent(Component* component, CreateMode mode, ComponentId id)
- {
- if (!component)
- {
- URHO3D_LOGERROR("Null source component given for CloneComponent");
- return nullptr;
- }
- Component* cloneComponent = SafeCreateComponent(component->GetTypeName(), component->GetType(), mode, 0);
- if (!cloneComponent)
- {
- URHO3D_LOGERROR("Could not clone component " + component->GetTypeName());
- return nullptr;
- }
- const Vector<AttributeInfo>* compAttributes = component->GetAttributes();
- const Vector<AttributeInfo>* cloneAttributes = cloneComponent->GetAttributes();
- if (compAttributes)
- {
- for (i32 i = 0; i < compAttributes->Size() && i < cloneAttributes->Size(); ++i)
- {
- const AttributeInfo& attr = compAttributes->At(i);
- const AttributeInfo& cloneAttr = cloneAttributes->At(i);
- if (attr.mode_ & AM_FILE)
- {
- Variant value;
- component->OnGetAttribute(attr, value);
- // Note: when eg. a ScriptInstance component is cloned, its script object attributes are unique and therefore we
- // can not simply refer to the source component's AttributeInfo
- cloneComponent->OnSetAttribute(cloneAttr, value);
- }
- }
- cloneComponent->ApplyAttributes();
- }
- if (scene_)
- {
- using namespace ComponentCloned;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = scene_;
- eventData[P_COMPONENT] = component;
- eventData[P_CLONECOMPONENT] = cloneComponent;
- scene_->SendEvent(E_COMPONENTCLONED, eventData);
- }
- return cloneComponent;
- }
- void Node::RemoveComponent(Component* component)
- {
- for (Vector<SharedPtr<Component>>::Iterator i = components_.Begin(); i != components_.End(); ++i)
- {
- if (*i == component)
- {
- RemoveComponent(i);
- // Mark node dirty in all replication states
- MarkReplicationDirty();
- return;
- }
- }
- }
- void Node::RemoveComponent(StringHash type)
- {
- for (Vector<SharedPtr<Component>>::Iterator i = components_.Begin(); i != components_.End(); ++i)
- {
- if ((*i)->GetType() == type)
- {
- RemoveComponent(i);
- // Mark node dirty in all replication states
- MarkReplicationDirty();
- return;
- }
- }
- }
- void Node::RemoveComponents(bool removeReplicated, bool removeLocal)
- {
- i32 numRemoved = 0;
- for (i32 i = components_.Size() - 1; i >= 0; --i)
- {
- bool remove = false;
- Component* component = components_[i];
- if (component->IsReplicated() && removeReplicated)
- remove = true;
- else if (!component->IsReplicated() && removeLocal)
- remove = true;
- if (remove)
- {
- RemoveComponent(components_.Begin() + i);
- ++numRemoved;
- }
- }
- // Mark node dirty in all replication states
- if (numRemoved)
- MarkReplicationDirty();
- }
- void Node::RemoveComponents(StringHash type)
- {
- i32 numRemoved = 0;
- for (i32 i = components_.Size() - 1; i >= 0; --i)
- {
- if (components_[i]->GetType() == type)
- {
- RemoveComponent(components_.Begin() + i);
- ++numRemoved;
- }
- }
- // Mark node dirty in all replication states
- if (numRemoved)
- MarkReplicationDirty();
- }
- void Node::RemoveAllComponents()
- {
- RemoveComponents(true, true);
- }
- void Node::ReorderComponent(Component* component, i32 index)
- {
- assert((index >= 0 && index < components_.Size()) || index == ENDPOS);
- if (!component || component->GetNode() != this)
- return;
- for (Vector<SharedPtr<Component>>::Iterator i = components_.Begin(); i != components_.End(); ++i)
- {
- if (*i == component)
- {
- // Need shared ptr to insert. Also, prevent destruction when removing first
- SharedPtr<Component> componentShared(component);
- components_.Erase(i);
- components_.Insert(index, componentShared);
- return;
- }
- }
- }
- Node* Node::Clone(CreateMode mode)
- {
- // The scene itself can not be cloned
- if (this == scene_ || !parent_)
- {
- URHO3D_LOGERROR("Can not clone node without a parent");
- return nullptr;
- }
- URHO3D_PROFILE(CloneNode);
- SceneResolver resolver;
- Node* clone = CloneRecursive(parent_, resolver, mode);
- resolver.Resolve();
- clone->ApplyAttributes();
- return clone;
- }
- void Node::Remove()
- {
- if (parent_)
- parent_->RemoveChild(this);
- }
- void Node::SetParent(Node* parent)
- {
- if (parent)
- {
- Matrix3x4 oldWorldTransform = GetWorldTransform();
- parent->AddChild(this);
- if (parent != scene_)
- {
- Matrix3x4 newTransform = parent->GetWorldTransform().Inverse() * oldWorldTransform;
- SetTransform(newTransform.Translation(), newTransform.Rotation(), newTransform.Scale());
- }
- else
- {
- // The root node is assumed to have identity transform, so can disregard it
- SetTransform(oldWorldTransform.Translation(), oldWorldTransform.Rotation(), oldWorldTransform.Scale());
- }
- }
- }
- void Node::SetVar(StringHash key, const Variant& value)
- {
- vars_[key] = value;
- MarkNetworkUpdate();
- }
- void Node::AddListener(Component* component)
- {
- if (!component)
- return;
- // Check for not adding twice
- for (Vector<WeakPtr<Component>>::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
- {
- if (*i == component)
- return;
- }
- listeners_.Push(WeakPtr<Component>(component));
- // If the node is currently dirty, notify immediately
- if (dirty_)
- component->OnMarkedDirty(this);
- }
- void Node::RemoveListener(Component* component)
- {
- for (Vector<WeakPtr<Component>>::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
- {
- if (*i == component)
- {
- listeners_.Erase(i);
- return;
- }
- }
- }
- Vector3 Node::GetSignedWorldScale() const
- {
- if (dirty_)
- UpdateWorldTransform();
- return worldTransform_.SignedScale(worldRotation_.RotationMatrix());
- }
- Vector3 Node::LocalToWorld(const Vector3& position) const
- {
- return GetWorldTransform() * position;
- }
- Vector3 Node::LocalToWorld(const Vector4& vector) const
- {
- return GetWorldTransform() * vector;
- }
- Vector2 Node::LocalToWorld2D(const Vector2& vector) const
- {
- Vector3 result = LocalToWorld(Vector3(vector));
- return Vector2(result.x_, result.y_);
- }
- Vector3 Node::WorldToLocal(const Vector3& position) const
- {
- return GetWorldTransform().Inverse() * position;
- }
- Vector3 Node::WorldToLocal(const Vector4& vector) const
- {
- return GetWorldTransform().Inverse() * vector;
- }
- Vector2 Node::WorldToLocal2D(const Vector2& vector) const
- {
- Vector3 result = WorldToLocal(Vector3(vector));
- return Vector2(result.x_, result.y_);
- }
- i32 Node::GetNumChildren(bool recursive) const
- {
- if (!recursive)
- return children_.Size();
- i32 allChildren = children_.Size();
- for (const SharedPtr<Node>& child : children_)
- allChildren += child->GetNumChildren(true);
- return allChildren;
- }
- void Node::GetChildren(Vector<Node*>& dest, bool recursive) const
- {
- dest.Clear();
- if (!recursive)
- {
- for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- dest.Push(*i);
- }
- else
- GetChildrenRecursive(dest);
- }
- Vector<Node*> Node::GetChildren(bool recursive) const
- {
- Vector<Node*> dest;
- GetChildren(dest, recursive);
- return dest;
- }
- void Node::GetChildrenWithComponent(Vector<Node*>& dest, StringHash type, bool recursive) const
- {
- dest.Clear();
- if (!recursive)
- {
- for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- {
- if ((*i)->HasComponent(type))
- dest.Push(*i);
- }
- }
- else
- GetChildrenWithComponentRecursive(dest, type);
- }
- Vector<Node*> Node::GetChildrenWithComponent(StringHash type, bool recursive) const
- {
- Vector<Node*> dest;
- GetChildrenWithComponent(dest, type, recursive);
- return dest;
- }
- void Node::GetChildrenWithTag(Vector<Node*>& dest, const String& tag, bool recursive /*= true*/) const
- {
- dest.Clear();
- if (!recursive)
- {
- for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- {
- if ((*i)->HasTag(tag))
- dest.Push(*i);
- }
- }
- else
- GetChildrenWithTagRecursive(dest, tag);
- }
- Vector<Node*> Node::GetChildrenWithTag(const String& tag, bool recursive) const
- {
- Vector<Node*> dest;
- GetChildrenWithTag(dest, tag, recursive);
- return dest;
- }
- Node* Node::GetChild(i32 index) const
- {
- assert(index >= 0);
- if (index < 0 || index >= children_.Size())
- {
- URHO3D_LOGWARNING("Node* Node::GetChild(i32 index) const: index out of range");
- return nullptr;
- }
- return children_[index].Get();
- }
- Node* Node::GetChild(const String& name, bool recursive) const
- {
- return GetChild(StringHash(name), recursive);
- }
- Node* Node::GetChild(const char* name, bool recursive) const
- {
- return GetChild(StringHash(name), recursive);
- }
- Node* Node::GetChild(StringHash nameHash, bool recursive) const
- {
- for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- {
- if ((*i)->GetNameHash() == nameHash)
- return *i;
- if (recursive)
- {
- Node* node = (*i)->GetChild(nameHash, true);
- if (node)
- return node;
- }
- }
- return nullptr;
- }
- i32 Node::GetNumNetworkComponents() const
- {
- i32 num = 0;
- for (const SharedPtr<Component>& component : components_)
- {
- if (component->IsReplicated())
- ++num;
- }
- return num;
- }
- void Node::GetComponents(Vector<Component*>& dest, StringHash type, bool recursive) const
- {
- dest.Clear();
- if (!recursive)
- {
- for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
- {
- if ((*i)->GetType() == type)
- dest.Push(*i);
- }
- }
- else
- GetComponentsRecursive(dest, type);
- }
- bool Node::HasComponent(StringHash type) const
- {
- for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
- {
- if ((*i)->GetType() == type)
- return true;
- }
- return false;
- }
- bool Node::IsReplicated() const
- {
- return Scene::IsReplicatedID(id_);
- }
- bool Node::HasTag(const String& tag) const
- {
- return impl_->tags_.Contains(tag);
- }
- bool Node::IsChildOf(Node* node) const
- {
- Node* parent = parent_;
- while (parent)
- {
- if (parent == node)
- return true;
- parent = parent->parent_;
- }
- return false;
- }
- const Variant& Node::GetVar(StringHash key) const
- {
- VariantMap::ConstIterator i = vars_.Find(key);
- return i != vars_.End() ? i->second_ : Variant::EMPTY;
- }
- Component* Node::GetComponent(StringHash type, bool recursive) const
- {
- for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
- {
- if ((*i)->GetType() == type)
- return *i;
- }
- if (recursive)
- {
- for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- {
- Component* component = (*i)->GetComponent(type, true);
- if (component)
- return component;
- }
- }
- return nullptr;
- }
- Component* Node::GetParentComponent(StringHash type, bool fullTraversal) const
- {
- Node* current = GetParent();
- while (current)
- {
- Component* soughtComponent = current->GetComponent(type);
- if (soughtComponent)
- return soughtComponent;
- if (fullTraversal)
- current = current->GetParent();
- else
- break;
- }
- return nullptr;
- }
- void Node::SetID(NodeId id)
- {
- id_ = id;
- }
- void Node::SetScene(Scene* scene)
- {
- scene_ = scene;
- }
- void Node::ResetScene()
- {
- SetID(0);
- SetScene(nullptr);
- SetOwner(nullptr);
- }
- void Node::SetNetPositionAttr(const Vector3& value)
- {
- auto* transform = GetComponent<SmoothedTransform>();
- if (transform)
- transform->SetTargetPosition(value);
- else
- SetPosition(value);
- }
- void Node::SetNetRotationAttr(const Vector<byte>& value)
- {
- MemoryBuffer buf(value);
- auto* transform = GetComponent<SmoothedTransform>();
- if (transform)
- transform->SetTargetRotation(buf.ReadPackedQuaternion());
- else
- SetRotation(buf.ReadPackedQuaternion());
- }
- void Node::SetNetParentAttr(const Vector<byte>& value)
- {
- Scene* scene = GetScene();
- if (!scene)
- return;
- MemoryBuffer buf(value);
- // If nothing in the buffer, parent is the root node
- if (buf.IsEof())
- {
- scene->AddChild(this);
- return;
- }
- NodeId baseNodeID = buf.ReadNetID();
- Node* baseNode = scene->GetNode(baseNodeID);
- if (!baseNode)
- {
- URHO3D_LOGWARNING("Failed to find parent node " + String(baseNodeID));
- return;
- }
- // If buffer contains just an ID, the parent is replicated and we are done
- if (buf.IsEof())
- baseNode->AddChild(this);
- else
- {
- // Else the parent is local and we must find it recursively by name hash
- StringHash nameHash = buf.ReadStringHash();
- Node* parentNode = baseNode->GetChild(nameHash, true);
- if (!parentNode)
- URHO3D_LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
- else
- parentNode->AddChild(this);
- }
- }
- const Vector3& Node::GetNetPositionAttr() const
- {
- return position_;
- }
- const Vector<byte>& Node::GetNetRotationAttr() const
- {
- impl_->attrBuffer_.Clear();
- impl_->attrBuffer_.WritePackedQuaternion(rotation_);
- return impl_->attrBuffer_.GetBuffer();
- }
- const Vector<byte>& Node::GetNetParentAttr() const
- {
- impl_->attrBuffer_.Clear();
- Scene* scene = GetScene();
- if (scene && parent_ && parent_ != scene)
- {
- // If parent is replicated, can write the ID directly
- NodeId parentID = parent_->GetID();
- if (Scene::IsReplicatedID(parentID))
- impl_->attrBuffer_.WriteNetID(parentID);
- else
- {
- // Parent is local: traverse hierarchy to find a non-local base node
- // This iteration always stops due to the scene (root) being non-local
- Node* current = parent_;
- while (!current->IsReplicated())
- current = current->GetParent();
- // Then write the base node ID and the parent's name hash
- impl_->attrBuffer_.WriteNetID(current->GetID());
- impl_->attrBuffer_.WriteStringHash(parent_->GetNameHash());
- }
- }
- return impl_->attrBuffer_.GetBuffer();
- }
- bool Node::Load(Deserializer& source, SceneResolver& resolver, bool loadChildren, bool rewriteIDs, CreateMode mode)
- {
- // Remove all children and components first in case this is not a fresh load
- RemoveAllChildren();
- RemoveAllComponents();
- // ID has been read at the parent level
- if (!Animatable::Load(source))
- return false;
- i32 numComponents = source.ReadVLE();
- for (i32 i = 0; i < numComponents; ++i)
- {
- VectorBuffer compBuffer(source, source.ReadVLE());
- StringHash compType = compBuffer.ReadStringHash();
- ComponentId compID = compBuffer.ReadU32();
- Component* newComponent = SafeCreateComponent(String::EMPTY, compType,
- (mode == REPLICATED && Scene::IsReplicatedID(compID)) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
- if (newComponent)
- {
- resolver.AddComponent(compID, newComponent);
- // Do not abort if component fails to load, as the component buffer is nested and we can skip to the next
- newComponent->Load(compBuffer);
- }
- }
- if (!loadChildren)
- return true;
- i32 numChildren = source.ReadVLE();
- for (i32 i = 0; i < numChildren; ++i)
- {
- NodeId nodeID = source.ReadU32();
- Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && Scene::IsReplicatedID(nodeID)) ? REPLICATED :
- LOCAL);
- resolver.AddNode(nodeID, newNode);
- if (!newNode->Load(source, resolver, loadChildren, rewriteIDs, mode))
- return false;
- }
- return true;
- }
- bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool loadChildren, bool rewriteIDs, CreateMode mode)
- {
- // Remove all children and components first in case this is not a fresh load
- RemoveAllChildren();
- RemoveAllComponents();
- if (!Animatable::LoadXML(source))
- return false;
- XMLElement compElem = source.GetChild("component");
- while (compElem)
- {
- String typeName = compElem.GetAttribute("type");
- ComponentId compID = compElem.GetU32("id");
- Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
- (mode == REPLICATED && Scene::IsReplicatedID(compID)) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
- if (newComponent)
- {
- resolver.AddComponent(compID, newComponent);
- if (!newComponent->LoadXML(compElem))
- return false;
- }
- compElem = compElem.GetNext("component");
- }
- if (!loadChildren)
- return true;
- XMLElement childElem = source.GetChild("node");
- while (childElem)
- {
- NodeId nodeID = childElem.GetU32("id");
- Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && Scene::IsReplicatedID(nodeID)) ? REPLICATED :
- LOCAL);
- resolver.AddNode(nodeID, newNode);
- if (!newNode->LoadXML(childElem, resolver, loadChildren, rewriteIDs, mode))
- return false;
- childElem = childElem.GetNext("node");
- }
- return true;
- }
- bool Node::LoadJSON(const JSONValue& source, SceneResolver& resolver, bool loadChildren, bool rewriteIDs, CreateMode mode)
- {
- // Remove all children and components first in case this is not a fresh load
- RemoveAllChildren();
- RemoveAllComponents();
- if (!Animatable::LoadJSON(source))
- return false;
- const JSONArray& componentsArray = source.Get("components").GetArray();
- for (i32 i = 0; i < componentsArray.Size(); i++)
- {
- const JSONValue& compVal = componentsArray.At(i);
- String typeName = compVal.Get("type").GetString();
- ComponentId compID = compVal.Get("id").GetU32();
- Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
- (mode == REPLICATED && Scene::IsReplicatedID(compID)) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
- if (newComponent)
- {
- resolver.AddComponent(compID, newComponent);
- if (!newComponent->LoadJSON(compVal))
- return false;
- }
- }
- if (!loadChildren)
- return true;
- const JSONArray& childrenArray = source.Get("children").GetArray();
- for (i32 i = 0; i < childrenArray.Size(); i++)
- {
- const JSONValue& childVal = childrenArray.At(i);
- NodeId nodeID = childVal.Get("id").GetU32();
- Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && Scene::IsReplicatedID(nodeID)) ? REPLICATED :
- LOCAL);
- resolver.AddNode(nodeID, newNode);
- if (!newNode->LoadJSON(childVal, resolver, loadChildren, rewriteIDs, mode))
- return false;
- }
- return true;
- }
- void Node::PrepareNetworkUpdate()
- {
- // Update dependency nodes list first
- impl_->dependencyNodes_.Clear();
- // Add the parent node, but if it is local, traverse to the first non-local node
- if (parent_ && parent_ != scene_)
- {
- Node* current = parent_;
- while (!current->IsReplicated())
- current = current->parent_;
- if (current && current != scene_)
- impl_->dependencyNodes_.Push(current);
- }
- // Let the components add their dependencies
- for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
- {
- Component* component = *i;
- if (component->IsReplicated())
- component->GetDependencyNodes(impl_->dependencyNodes_);
- }
- // Then check for node attribute changes
- if (!networkState_)
- AllocateNetworkState();
- const Vector<AttributeInfo>* attributes = networkState_->attributes_;
- i32 numAttributes = attributes->Size();
- // Check for attribute changes
- for (i32 i = 0; i < numAttributes; ++i)
- {
- const AttributeInfo& attr = attributes->At(i);
- if (animationEnabled_ && IsAnimatedNetworkAttribute(attr))
- continue;
- OnGetAttribute(attr, networkState_->currentValues_[i]);
- if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
- {
- networkState_->previousValues_[i] = networkState_->currentValues_[i];
- // Mark the attribute dirty in all replication states that are tracking this node
- for (Vector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
- j != networkState_->replicationStates_.End(); ++j)
- {
- auto* nodeState = static_cast<NodeReplicationState*>(*j);
- nodeState->dirtyAttributes_.Set(i);
- // Add node to the dirty set if not added yet
- if (!nodeState->markedDirty_)
- {
- nodeState->markedDirty_ = true;
- nodeState->sceneState_->dirtyNodes_.Insert(id_);
- }
- }
- }
- }
- // Finally check for user var changes
- for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
- {
- VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
- if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
- {
- networkState_->previousVars_[i->first_] = i->second_;
- // Mark the var dirty in all replication states that are tracking this node
- for (Vector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
- j != networkState_->replicationStates_.End(); ++j)
- {
- auto* nodeState = static_cast<NodeReplicationState*>(*j);
- nodeState->dirtyVars_.Insert(i->first_);
- if (!nodeState->markedDirty_)
- {
- nodeState->markedDirty_ = true;
- nodeState->sceneState_->dirtyNodes_.Insert(id_);
- }
- }
- }
- }
- networkUpdate_ = false;
- }
- void Node::CleanupConnection(Connection* connection)
- {
- if (impl_->owner_ == connection)
- impl_->owner_ = nullptr;
- if (networkState_)
- {
- for (i32 i = networkState_->replicationStates_.Size() - 1; i >= 0; --i)
- {
- if (networkState_->replicationStates_[i]->connection_ == connection)
- networkState_->replicationStates_.Erase(i);
- }
- }
- }
- void Node::MarkReplicationDirty()
- {
- if (networkState_)
- {
- for (Vector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
- j != networkState_->replicationStates_.End(); ++j)
- {
- auto* nodeState = static_cast<NodeReplicationState*>(*j);
- if (!nodeState->markedDirty_)
- {
- nodeState->markedDirty_ = true;
- nodeState->sceneState_->dirtyNodes_.Insert(id_);
- }
- }
- }
- }
- Node* Node::CreateChild(NodeId id, CreateMode mode, bool temporary)
- {
- SharedPtr<Node> newNode(new Node(context_));
- newNode->SetTemporary(temporary);
- // If zero ID specified, or the ID is already taken, let the scene assign
- if (scene_)
- {
- if (!id || scene_->GetNode(id))
- id = scene_->GetFreeNodeID(mode);
- newNode->SetID(id);
- }
- else
- newNode->SetID(id);
- AddChild(newNode);
- return newNode;
- }
- void Node::AddComponent(Component* component, ComponentId id, CreateMode mode)
- {
- if (!component)
- return;
- components_.Push(SharedPtr<Component>(component));
- if (component->GetNode())
- URHO3D_LOGWARNING("Component " + component->GetTypeName() + " already belongs to a node!");
- component->SetNode(this);
- // If zero ID specified, or the ID is already taken, let the scene assign
- if (scene_)
- {
- if (!id || scene_->GetComponent(id))
- id = scene_->GetFreeComponentID(mode);
- component->SetID(id);
- scene_->ComponentAdded(component);
- }
- else
- component->SetID(id);
- component->OnMarkedDirty(this);
- // Check attributes of the new component on next network update, and mark node dirty in all replication states
- component->MarkNetworkUpdate();
- MarkNetworkUpdate();
- MarkReplicationDirty();
- // Send change event
- if (scene_)
- {
- using namespace ComponentAdded;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = scene_;
- eventData[P_NODE] = this;
- eventData[P_COMPONENT] = component;
- scene_->SendEvent(E_COMPONENTADDED, eventData);
- }
- }
- i32 Node::GetNumPersistentChildren() const
- {
- i32 ret = 0;
- for (const SharedPtr<Node>& child : children_)
- {
- if (!child->IsTemporary())
- ++ret;
- }
- return ret;
- }
- i32 Node::GetNumPersistentComponents() const
- {
- i32 ret = 0;
- for (const SharedPtr<Component>& component : components_)
- {
- if (!component->IsTemporary())
- ++ret;
- }
- return ret;
- }
- void Node::SetTransformSilent(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
- {
- position_ = position;
- rotation_ = rotation;
- scale_ = scale;
- }
- void Node::OnAttributeAnimationAdded()
- {
- if (attributeAnimationInfos_.Size() == 1)
- SubscribeToEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE, URHO3D_HANDLER(Node, HandleAttributeAnimationUpdate));
- }
- void Node::OnAttributeAnimationRemoved()
- {
- if (attributeAnimationInfos_.Empty())
- UnsubscribeFromEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE);
- }
- Animatable* Node::FindAttributeAnimationTarget(const String& name, String& outName)
- {
- Vector<String> names = name.Split('/');
- // Only attribute name
- if (names.Size() == 1)
- {
- outName = name;
- return this;
- }
- else
- {
- // Name must in following format: "#0/#1/@component#0/attribute"
- Node* node = this;
- i32 i = 0;
- for (; i < names.Size() - 1; ++i)
- {
- if (names[i].Front() != '#')
- break;
- String name = names[i].Substring(1, names[i].Length() - 1);
- char s = name.Front();
- if (s >= '0' && s <= '9')
- {
- i32 index = ToI32(name);
- node = node->GetChild(index);
- }
- else
- {
- node = node->GetChild(name, true);
- }
- if (!node)
- {
- URHO3D_LOGERROR("Could not find node by name " + name);
- return nullptr;
- }
- }
- if (i == names.Size() - 1)
- {
- outName = names.Back();
- return node;
- }
- if (i != names.Size() - 2 || names[i].Front() != '@')
- {
- URHO3D_LOGERROR("Invalid name " + name);
- return nullptr;
- }
- String componentName = names[i].Substring(1, names[i].Length() - 1);
- Vector<String> componentNames = componentName.Split('#');
- if (componentNames.Size() == 1)
- {
- Component* component = node->GetComponent(StringHash(componentNames.Front()));
- if (!component)
- {
- URHO3D_LOGERROR("Could not find component by name " + name);
- return nullptr;
- }
- outName = names.Back();
- return component;
- }
- else
- {
- i32 index = ToI32(componentNames[1]);
- Vector<Component*> components;
- node->GetComponents(components, StringHash(componentNames.Front()));
- if (index >= components.Size())
- {
- URHO3D_LOGERROR("Could not find component by name " + name);
- return nullptr;
- }
- outName = names.Back();
- return components[index];
- }
- }
- }
- void Node::SetEnabled(bool enable, bool recursive, bool storeSelf)
- {
- // The enabled state of the whole scene can not be changed. SetUpdateEnabled() is used instead to start/stop updates.
- if (GetType() == Scene::GetTypeStatic())
- {
- URHO3D_LOGERROR("Can not change enabled state of the Scene");
- return;
- }
- if (storeSelf)
- enabledPrev_ = enable;
- if (enable != enabled_)
- {
- enabled_ = enable;
- MarkNetworkUpdate();
- // Notify listener components of the state change
- for (Vector<WeakPtr<Component>>::Iterator i = listeners_.Begin(); i != listeners_.End();)
- {
- if (*i)
- {
- (*i)->OnNodeSetEnabled(this);
- ++i;
- }
- // If listener has expired, erase from list
- else
- i = listeners_.Erase(i);
- }
- // Send change event
- if (scene_)
- {
- using namespace NodeEnabledChanged;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = scene_;
- eventData[P_NODE] = this;
- scene_->SendEvent(E_NODEENABLEDCHANGED, eventData);
- }
- for (Vector<SharedPtr<Component>>::Iterator i = components_.Begin(); i != components_.End(); ++i)
- {
- (*i)->OnSetEnabled();
- // Send change event for the component
- if (scene_)
- {
- using namespace ComponentEnabledChanged;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = scene_;
- eventData[P_NODE] = this;
- eventData[P_COMPONENT] = (*i);
- scene_->SendEvent(E_COMPONENTENABLEDCHANGED, eventData);
- }
- }
- }
- if (recursive)
- {
- for (Vector<SharedPtr<Node>>::Iterator i = children_.Begin(); i != children_.End(); ++i)
- (*i)->SetEnabled(enable, recursive, storeSelf);
- }
- }
- Component* Node::SafeCreateComponent(const String& typeName, StringHash type, CreateMode mode, ComponentId id)
- {
- // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
- // as replicated components are synced over
- if (mode == REPLICATED && !IsReplicated())
- mode = LOCAL;
- // First check if factory for type exists
- if (!context_->GetTypeName(type).Empty())
- return CreateComponent(type, mode, id);
- else
- {
- URHO3D_LOGWARNING("Component type " + type.ToString() + " not known, creating UnknownComponent as placeholder");
- // Else create as UnknownComponent
- SharedPtr<UnknownComponent> newComponent(new UnknownComponent(context_));
- if (typeName.Empty() || typeName.StartsWith("Unknown", false))
- newComponent->SetType(type);
- else
- newComponent->SetTypeName(typeName);
- AddComponent(newComponent, id, mode);
- return newComponent;
- }
- }
- void Node::UpdateWorldTransform() const
- {
- Matrix3x4 transform = GetTransform();
- // Assume the root node (scene) has identity transform
- if (parent_ == scene_ || !parent_)
- {
- worldTransform_ = transform;
- worldRotation_ = rotation_;
- }
- else
- {
- worldTransform_ = parent_->GetWorldTransform() * transform;
- worldRotation_ = parent_->GetWorldRotation() * rotation_;
- }
- dirty_ = false;
- }
- void Node::RemoveChild(Vector<SharedPtr<Node>>::Iterator i)
- {
- // Keep a shared pointer to the child about to be removed, to make sure the erase from container completes first. Otherwise
- // it would be possible that other child nodes get removed as part of the node's components' cleanup, causing a re-entrant
- // erase and a crash
- SharedPtr<Node> child(*i);
- // Send change event. Do not send when this node is already being destroyed
- if (Refs() > 0 && scene_)
- {
- using namespace NodeRemoved;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = scene_;
- eventData[P_PARENT] = this;
- eventData[P_NODE] = child;
- scene_->SendEvent(E_NODEREMOVED, eventData);
- }
- child->parent_ = nullptr;
- child->MarkDirty();
- child->MarkNetworkUpdate();
- if (scene_)
- scene_->NodeRemoved(child);
- children_.Erase(i);
- }
- void Node::GetChildrenRecursive(Vector<Node*>& dest) const
- {
- for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- {
- Node* node = *i;
- dest.Push(node);
- if (!node->children_.Empty())
- node->GetChildrenRecursive(dest);
- }
- }
- void Node::GetChildrenWithComponentRecursive(Vector<Node*>& dest, StringHash type) const
- {
- for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- {
- Node* node = *i;
- if (node->HasComponent(type))
- dest.Push(node);
- if (!node->children_.Empty())
- node->GetChildrenWithComponentRecursive(dest, type);
- }
- }
- void Node::GetComponentsRecursive(Vector<Component*>& dest, StringHash type) const
- {
- for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
- {
- if ((*i)->GetType() == type)
- dest.Push(*i);
- }
- for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- (*i)->GetComponentsRecursive(dest, type);
- }
- void Node::GetChildrenWithTagRecursive(Vector<Node*>& dest, const String& tag) const
- {
- for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- {
- Node* node = *i;
- if (node->HasTag(tag))
- dest.Push(node);
- if (!node->children_.Empty())
- node->GetChildrenWithTagRecursive(dest, tag);
- }
- }
- Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
- {
- // Create clone node
- Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && IsReplicated()) ? REPLICATED : LOCAL);
- resolver.AddNode(id_, cloneNode);
- // Copy attributes
- const Vector<AttributeInfo>* attributes = GetAttributes();
- for (i32 j = 0; j < attributes->Size(); ++j)
- {
- const AttributeInfo& attr = attributes->At(j);
- // Do not copy network-only attributes, as they may have unintended side effects
- if (attr.mode_ & AM_FILE)
- {
- Variant value;
- OnGetAttribute(attr, value);
- cloneNode->OnSetAttribute(attr, value);
- }
- }
- // Clone components
- for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
- {
- Component* component = *i;
- if (component->IsTemporary())
- continue;
- Component* cloneComponent = cloneNode->CloneComponent(component,
- (mode == REPLICATED && component->IsReplicated()) ? REPLICATED : LOCAL, 0);
- if (cloneComponent)
- resolver.AddComponent(component->GetID(), cloneComponent);
- }
- // Clone child nodes recursively
- for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
- {
- Node* node = *i;
- if (node->IsTemporary())
- continue;
- node->CloneRecursive(cloneNode, resolver, mode);
- }
- if (scene_)
- {
- using namespace NodeCloned;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = scene_;
- eventData[P_NODE] = this;
- eventData[P_CLONENODE] = cloneNode;
- scene_->SendEvent(E_NODECLONED, eventData);
- }
- return cloneNode;
- }
- void Node::RemoveComponent(Vector<SharedPtr<Component>>::Iterator i)
- {
- // Send node change event. Do not send when already being destroyed
- if (Refs() > 0 && scene_)
- {
- using namespace ComponentRemoved;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SCENE] = scene_;
- eventData[P_NODE] = this;
- eventData[P_COMPONENT] = (*i).Get();
- scene_->SendEvent(E_COMPONENTREMOVED, eventData);
- }
- RemoveListener(*i);
- if (scene_)
- scene_->ComponentRemoved(*i);
- (*i)->SetNode(nullptr);
- components_.Erase(i);
- }
- void Node::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
- {
- using namespace AttributeAnimationUpdate;
- UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
- }
- }
|