ObjectManager.cpp 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include "EditorDefs.h"
  9. #include "ObjectManager.h"
  10. // Qt
  11. #include <QMessageBox>
  12. // Editor
  13. #include "Settings.h"
  14. #include "DisplaySettings.h"
  15. #include "EntityObject.h"
  16. #include "Viewport.h"
  17. #include "GizmoManager.h"
  18. #include "AxisGizmo.h"
  19. #include "GameEngine.h"
  20. #include "WaitProgress.h"
  21. #include "Util/Image.h"
  22. #include "ObjectManagerLegacyUndo.h"
  23. #include "Include/HitContext.h"
  24. #include "EditMode/DeepSelection.h"
  25. #include "Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h"
  26. #include <AzCore/Console/Console.h>
  27. AZ_CVAR_EXTERNED(bool, ed_visibility_logTiming);
  28. AZ_CVAR(
  29. bool, ed_visibility_use, true, nullptr, AZ::ConsoleFunctorFlags::Null,
  30. "Enable/disable using the new IVisibilitySystem for Entity visibility determination");
  31. /*!
  32. * Class Description used for object templates.
  33. * This description filled from Xml template files.
  34. */
  35. class CXMLObjectClassDesc
  36. : public CObjectClassDesc
  37. {
  38. public:
  39. CObjectClassDesc* superType;
  40. QString type;
  41. QString category;
  42. QString fileSpec;
  43. GUID guid;
  44. public:
  45. REFGUID ClassID() override
  46. {
  47. return guid;
  48. }
  49. ObjectType GetObjectType() override { return superType->GetObjectType(); };
  50. QString ClassName() override { return type; };
  51. QString Category() override { return category; };
  52. QObject* CreateQObject() const override { return superType->CreateQObject(); }
  53. QString GetTextureIcon() override { return superType->GetTextureIcon(); };
  54. QString GetFileSpec() override
  55. {
  56. if (!fileSpec.isEmpty())
  57. {
  58. return fileSpec;
  59. }
  60. else
  61. {
  62. return superType->GetFileSpec();
  63. }
  64. };
  65. int GameCreationOrder() override { return superType->GameCreationOrder(); };
  66. };
  67. void CBaseObjectsCache::AddObject(CBaseObject* object)
  68. {
  69. m_objects.push_back(object);
  70. if (object->GetType() == OBJTYPE_AZENTITY)
  71. {
  72. auto componentEntityObject = static_cast<CComponentEntityObject*>(object);
  73. m_entityIds.push_back(componentEntityObject->GetAssociatedEntityId());
  74. }
  75. }
  76. //////////////////////////////////////////////////////////////////////////
  77. // CObjectManager implementation.
  78. //////////////////////////////////////////////////////////////////////////
  79. CObjectManager* g_pObjectManager = nullptr;
  80. //////////////////////////////////////////////////////////////////////////
  81. CObjectManager::CObjectManager()
  82. : m_lastHideMask(0)
  83. , m_maxObjectViewDistRatio(0.00001f)
  84. , m_currSelection(&m_defaultSelection)
  85. , m_nLastSelCount(0)
  86. , m_bSelectionChanged(false)
  87. , m_selectCallback(nullptr)
  88. , m_currEditObject(nullptr)
  89. , m_bSingleSelection(false)
  90. , m_createGameObjects(true)
  91. , m_bGenUniqObjectNames(true)
  92. , m_gizmoManager(new CGizmoManager())
  93. , m_pLoadProgress(nullptr)
  94. , m_loadedObjects(0)
  95. , m_totalObjectsToLoad(0)
  96. , m_bExiting(false)
  97. , m_isUpdateVisibilityList(false)
  98. , m_currentHideCount(CBaseObject::s_invalidHiddenID)
  99. , m_bInReloading(false)
  100. , m_bSkipObjectUpdate(false)
  101. , m_bLevelExporting(false)
  102. {
  103. g_pObjectManager = this;
  104. RegisterObjectClasses();
  105. m_objectsByName.reserve(1024);
  106. LoadRegistry();
  107. AzToolsFramework::ComponentModeFramework::EditorComponentModeNotificationBus::Handler::BusConnect(
  108. AzToolsFramework::GetEntityContextId());
  109. }
  110. //////////////////////////////////////////////////////////////////////////
  111. CObjectManager::~CObjectManager()
  112. {
  113. AzToolsFramework::ComponentModeFramework::EditorComponentModeNotificationBus::Handler::BusDisconnect();
  114. m_bExiting = true;
  115. SaveRegistry();
  116. DeleteAllObjects();
  117. delete m_gizmoManager;
  118. }
  119. //////////////////////////////////////////////////////////////////////////
  120. void CObjectManager::RegisterObjectClasses()
  121. {
  122. LoadRegistry();
  123. }
  124. //////////////////////////////////////////////////////////////////////////
  125. void CObjectManager::SaveRegistry()
  126. {
  127. }
  128. void CObjectManager::LoadRegistry()
  129. {
  130. }
  131. //////////////////////////////////////////////////////////////////////////
  132. CBaseObject* CObjectManager::NewObject(CObjectClassDesc* cls, CBaseObject* prev, const QString& file, const char* newObjectName)
  133. {
  134. // Suspend undo operations when initializing object.
  135. GetIEditor()->SuspendUndo();
  136. CBaseObjectPtr obj;
  137. {
  138. obj = qobject_cast<CBaseObject*>(cls->CreateQObject());
  139. obj->SetClassDesc(cls);
  140. obj->InitVariables();
  141. obj->m_guid = AZ::Uuid::CreateRandom(); // generate uniq GUID for this object.
  142. GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(obj);
  143. if (obj->Init(GetIEditor(), prev, file))
  144. {
  145. if ((newObjectName)&&(newObjectName[0]))
  146. {
  147. obj->SetName(newObjectName);
  148. }
  149. else
  150. {
  151. if (obj->GetName().isEmpty())
  152. {
  153. obj->GenerateUniqueName();
  154. }
  155. }
  156. // Create game object itself.
  157. obj->CreateGameObject();
  158. if (!AddObject(obj))
  159. {
  160. obj = nullptr;
  161. }
  162. }
  163. else
  164. {
  165. obj = nullptr;
  166. }
  167. GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(nullptr);
  168. }
  169. GetIEditor()->ResumeUndo();
  170. if (obj != nullptr && GetIEditor()->IsUndoRecording())
  171. {
  172. // AZ entity creations are handled through the AZ undo system.
  173. if (obj->GetType() != OBJTYPE_AZENTITY)
  174. {
  175. GetIEditor()->RecordUndo(new CUndoBaseObjectNew(obj));
  176. // check for script entities
  177. const char* scriptClassName = "";
  178. CEntityObject* entityObj = qobject_cast<CEntityObject*>(obj);
  179. QByteArray entityClass; // Leave it outside of the if. Otherwise buffer is deleted.
  180. if (entityObj)
  181. {
  182. entityClass = entityObj->GetEntityClass().toUtf8();
  183. scriptClassName = entityClass.data();
  184. }
  185. }
  186. }
  187. return obj;
  188. }
  189. //////////////////////////////////////////////////////////////////////////
  190. CBaseObject* CObjectManager::NewObject(CObjectArchive& ar, CBaseObject* pUndoObject, bool bMakeNewId)
  191. {
  192. XmlNodeRef objNode = ar.node;
  193. // Load all objects from XML.
  194. QString typeName;
  195. GUID id = GUID_NULL;
  196. if (!objNode->getAttr("Type", typeName))
  197. {
  198. return nullptr;
  199. }
  200. if (!objNode->getAttr("Id", id))
  201. {
  202. // Make new ID for object that doesn't have if.
  203. id = AZ::Uuid::CreateRandom();
  204. }
  205. if (bMakeNewId)
  206. {
  207. // Make new guid for this object.
  208. GUID newId = AZ::Uuid::CreateRandom();
  209. ar.RemapID(id, newId); // Mark this id remapped.
  210. id = newId;
  211. }
  212. CBaseObjectPtr pObject;
  213. if (pUndoObject)
  214. {
  215. // if undoing restore object pointer.
  216. pObject = pUndoObject;
  217. }
  218. else
  219. {
  220. // New object creation.
  221. // Suspend undo operations when initializing object.
  222. CUndoSuspend undoSuspender;
  223. QString entityClass;
  224. if (objNode->getAttr("EntityClass", entityClass))
  225. {
  226. typeName = typeName + "::" + entityClass;
  227. }
  228. CObjectClassDesc* cls = FindClass(typeName);
  229. if (!cls)
  230. {
  231. CryWarning(VALIDATOR_MODULE_EDITOR, VALIDATOR_ERROR, "RuntimeClass %s not registered", typeName.toUtf8().data());
  232. return nullptr;
  233. }
  234. pObject = qobject_cast<CBaseObject*>(cls->CreateQObject());
  235. assert(pObject);
  236. pObject->SetClassDesc(cls);
  237. pObject->m_guid = id;
  238. pObject->InitVariables();
  239. QString objName;
  240. objNode->getAttr("Name", objName);
  241. pObject->m_name = objName;
  242. CBaseObject* obj = FindObject(pObject->GetId());
  243. if (obj)
  244. {
  245. // If id is taken.
  246. QString error;
  247. error = QObject::tr("[Error] Object %1 already exists in the Object Manager and has been deleted as it is a duplicate of object %2").arg(pObject->m_name, obj->GetName());
  248. CLogFile::WriteLine(error.toUtf8().data());
  249. if (!GetIEditor()->IsInTestMode() && !GetIEditor()->IsInLevelLoadTestMode())
  250. {
  251. CErrorRecord errorRecord;
  252. errorRecord.pObject = obj;
  253. errorRecord.count = 1;
  254. errorRecord.severity = CErrorRecord::ESEVERITY_ERROR;
  255. errorRecord.error = error;
  256. errorRecord.description = "Possible duplicate objects being loaded, potential fix is to remove duplicate objects from level files.";
  257. GetIEditor()->GetErrorReport()->ReportError(errorRecord);
  258. }
  259. return nullptr;
  260. //CoCreateGuid( &pObject->m_guid ); // generate uniq GUID for this object.
  261. }
  262. }
  263. GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(pObject);
  264. if (!pObject->Init(GetIEditor(), nullptr, ""))
  265. {
  266. GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(nullptr);
  267. return nullptr;
  268. }
  269. if (!AddObject(pObject))
  270. {
  271. GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(nullptr);
  272. return nullptr;
  273. }
  274. //pObject->Serialize( ar );
  275. GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(nullptr);
  276. if (pObject != nullptr && pUndoObject == nullptr)
  277. {
  278. // If new object with no undo, record it.
  279. if (CUndo::IsRecording())
  280. {
  281. GetIEditor()->RecordUndo(new CUndoBaseObjectNew(pObject));
  282. }
  283. }
  284. m_loadedObjects++;
  285. if (m_pLoadProgress && m_totalObjectsToLoad > 0)
  286. {
  287. m_pLoadProgress->Step((m_loadedObjects * 100) / m_totalObjectsToLoad);
  288. }
  289. return pObject;
  290. }
  291. //////////////////////////////////////////////////////////////////////////
  292. CBaseObject* CObjectManager::NewObject(const QString& typeName, CBaseObject* prev, const QString& file, const char* newObjectName)
  293. {
  294. // [9/22/2009 evgeny] If it is "Entity", figure out if a CEntity subclass is actually needed
  295. QString fullName = typeName + "::" + file;
  296. CObjectClassDesc* cls = FindClass(fullName);
  297. if (!cls)
  298. {
  299. cls = FindClass(typeName);
  300. }
  301. if (!cls)
  302. {
  303. GetIEditor()->GetSystem()->GetILog()->Log("Warning: RuntimeClass %s (as well as %s) not registered", typeName.toUtf8().data(), fullName.toUtf8().data());
  304. return nullptr;
  305. }
  306. CBaseObject* pObject = NewObject(cls, prev, file, newObjectName);
  307. return pObject;
  308. }
  309. //////////////////////////////////////////////////////////////////////////
  310. void CObjectManager::DeleteObject(CBaseObject* obj)
  311. {
  312. AZ_PROFILE_FUNCTION(Editor);
  313. if (m_currEditObject == obj)
  314. {
  315. EndEditParams();
  316. }
  317. if (!obj)
  318. {
  319. return;
  320. }
  321. // If object already deleted.
  322. if (obj->CheckFlags(OBJFLAG_DELETED))
  323. {
  324. return;
  325. }
  326. NotifyObjectListeners(obj, CBaseObject::ON_PREDELETE);
  327. obj->NotifyListeners(CBaseObject::ON_PREDELETE);
  328. // Must be after object DetachAll to support restoring Parent/Child relations.
  329. // AZ entity deletions are handled through the AZ undo system.
  330. if (CUndo::IsRecording() && obj->GetType() != OBJTYPE_AZENTITY)
  331. {
  332. // Store undo for all child objects.
  333. for (int i = 0; i < obj->GetChildCount(); i++)
  334. {
  335. obj->GetChild(i)->StoreUndo("DeleteParent");
  336. }
  337. CUndo::Record(new CUndoBaseObjectDelete(obj));
  338. }
  339. AABB objAAB;
  340. obj->GetBoundBox(objAAB);
  341. GetIEditor()->GetGameEngine()->OnAreaModified(objAAB);
  342. obj->Done();
  343. NotifyObjectListeners(obj, CBaseObject::ON_DELETE);
  344. RemoveObject(obj);
  345. }
  346. //////////////////////////////////////////////////////////////////////////
  347. void CObjectManager::DeleteSelection(CSelectionGroup* pSelection)
  348. {
  349. AZ_PROFILE_FUNCTION(Editor);
  350. if (pSelection == nullptr)
  351. {
  352. return;
  353. }
  354. // if the object contains an entity which has link, the link information should be recorded for undo separately. p
  355. if (CUndo::IsRecording())
  356. {
  357. for (int i = 0, iSize(pSelection->GetCount()); i < iSize; ++i)
  358. {
  359. CBaseObject* pObj = pSelection->GetObject(i);
  360. if (!qobject_cast<CEntityObject*>(pObj))
  361. {
  362. continue;
  363. }
  364. CEntityObject* pEntity = (CEntityObject*)pObj;
  365. if (pEntity->GetEntityLinkCount() <= 0)
  366. {
  367. continue;
  368. }
  369. CEntityObject::StoreUndoEntityLink(pSelection);
  370. break;
  371. }
  372. }
  373. AzToolsFramework::EntityIdList selectedComponentEntities;
  374. for (int i = 0, iObjSize(pSelection->GetCount()); i < iObjSize; i++)
  375. {
  376. CBaseObject* object = pSelection->GetObject(i);
  377. // AZ::Entity deletion is handled through AZ undo system (DeleteSelected bus call below).
  378. if (object->GetType() != OBJTYPE_AZENTITY)
  379. {
  380. DeleteObject(object);
  381. }
  382. else
  383. {
  384. AZ::EntityId id;
  385. EBUS_EVENT_ID_RESULT(id, object, AzToolsFramework::ComponentEntityObjectRequestBus, GetAssociatedEntityId);
  386. if (id.IsValid())
  387. {
  388. selectedComponentEntities.push_back(id);
  389. }
  390. }
  391. }
  392. // Delete AZ (component) entities.
  393. if (QApplication::keyboardModifiers() & Qt::ShiftModifier)
  394. {
  395. EBUS_EVENT(AzToolsFramework::ToolsApplicationRequests::Bus, DeleteEntities, selectedComponentEntities);
  396. }
  397. else
  398. {
  399. EBUS_EVENT(AzToolsFramework::ToolsApplicationRequests::Bus, DeleteEntitiesAndAllDescendants, selectedComponentEntities);
  400. }
  401. }
  402. //////////////////////////////////////////////////////////////////////////
  403. void CObjectManager::DeleteAllObjects()
  404. {
  405. AZ_PROFILE_FUNCTION(Editor);
  406. EndEditParams();
  407. ClearSelection();
  408. int i;
  409. InvalidateVisibleList();
  410. // Delete all selection groups.
  411. std::vector<CSelectionGroup*> sel;
  412. stl::map_to_vector(m_selections, sel);
  413. for (i = 0; i < sel.size(); i++)
  414. {
  415. delete sel[i];
  416. }
  417. m_selections.clear();
  418. TBaseObjects objectsHolder;
  419. GetAllObjects(objectsHolder);
  420. // Clear map. Need to do this before deleting objects in case someone tries to get object list during shutdown.
  421. m_objects.clear();
  422. m_objectsByName.clear();
  423. for (i = 0; i < objectsHolder.size(); i++)
  424. {
  425. objectsHolder[i]->Done();
  426. }
  427. //! Delete object instances.
  428. objectsHolder.clear();
  429. // Clear name map.
  430. m_nameNumbersMap.clear();
  431. m_animatedAttachedEntities.clear();
  432. }
  433. CBaseObject* CObjectManager::CloneObject(CBaseObject* obj)
  434. {
  435. AZ_PROFILE_FUNCTION(Editor);
  436. assert(obj);
  437. //CRuntimeClass *cls = obj->GetRuntimeClass();
  438. //CBaseObject *clone = (CBaseObject*)cls->CreateObject();
  439. //clone->CloneCopy( obj );
  440. CBaseObject* clone = NewObject(obj->GetClassDesc(), obj);
  441. return clone;
  442. }
  443. //////////////////////////////////////////////////////////////////////////
  444. CBaseObject* CObjectManager::FindObject(REFGUID guid) const
  445. {
  446. CBaseObject* result = stl::find_in_map(m_objects, guid, (CBaseObject*)nullptr);
  447. return result;
  448. }
  449. //////////////////////////////////////////////////////////////////////////
  450. CBaseObject* CObjectManager::FindObject(const QString& sName) const
  451. {
  452. const AZ::Crc32 crc(sName.toUtf8().data(), sName.toUtf8().count(), true);
  453. auto iter = m_objectsByName.find(crc);
  454. if (iter != m_objectsByName.end())
  455. {
  456. return iter->second;
  457. }
  458. return nullptr;
  459. }
  460. //////////////////////////////////////////////////////////////////////////
  461. void CObjectManager::FindObjectsOfType(ObjectType type, std::vector<CBaseObject*>& result)
  462. {
  463. result.clear();
  464. CBaseObjectsArray objects;
  465. GetObjects(objects);
  466. for (size_t i = 0, n = objects.size(); i < n; ++i)
  467. {
  468. if (objects[i]->GetType() == type)
  469. {
  470. result.push_back(objects[i]);
  471. }
  472. }
  473. }
  474. //////////////////////////////////////////////////////////////////////////
  475. void CObjectManager::FindObjectsOfType(const QMetaObject* pClass, std::vector<CBaseObject*>& result)
  476. {
  477. result.clear();
  478. CBaseObjectsArray objects;
  479. GetObjects(objects);
  480. for (size_t i = 0, n = objects.size(); i < n; ++i)
  481. {
  482. CBaseObject* pObject = objects[i];
  483. if (pObject->metaObject() == pClass)
  484. {
  485. result.push_back(pObject);
  486. }
  487. }
  488. }
  489. //////////////////////////////////////////////////////////////////////////
  490. void CObjectManager::FindObjectsInAABB(const AABB& aabb, std::vector<CBaseObject*>& result) const
  491. {
  492. result.clear();
  493. CBaseObjectsArray objects;
  494. GetObjects(objects);
  495. for (size_t i = 0, n = objects.size(); i < n; ++i)
  496. {
  497. CBaseObject* pObject = objects[i];
  498. AABB aabbObj;
  499. pObject->GetBoundBox(aabbObj);
  500. if (aabb.IsIntersectBox(aabbObj))
  501. {
  502. result.push_back(pObject);
  503. }
  504. }
  505. }
  506. //////////////////////////////////////////////////////////////////////////
  507. bool CObjectManager::AddObject(CBaseObject* obj)
  508. {
  509. CBaseObjectPtr p = stl::find_in_map(m_objects, obj->GetId(), nullptr);
  510. if (p)
  511. {
  512. CErrorRecord err;
  513. err.error = QObject::tr("New Object %1 has Duplicate GUID %2, New Object Ignored").arg(obj->GetName()).arg(GuidUtil::ToString(obj->GetId()));
  514. err.severity = CErrorRecord::ESEVERITY_ERROR;
  515. err.pObject = obj;
  516. err.flags = CErrorRecord::FLAG_OBJECTID;
  517. GetIEditor()->GetErrorReport()->ReportError(err);
  518. return false;
  519. }
  520. m_objects[obj->GetId()] = obj;
  521. // Handle adding object to type-specific containers if needed
  522. {
  523. if (CEntityObject* entityObj = qobject_cast<CEntityObject*>(obj))
  524. {
  525. CEntityObject::EAttachmentType attachType = entityObj->GetAttachType();
  526. if (attachType == CEntityObject::EAttachmentType::eAT_GeomCacheNode || attachType == CEntityObject::EAttachmentType::eAT_CharacterBone)
  527. {
  528. m_animatedAttachedEntities.insert(entityObj);
  529. }
  530. }
  531. }
  532. const AZ::Crc32 nameCrc(obj->GetName().toUtf8().data(), obj->GetName().toUtf8().count(), true);
  533. m_objectsByName[nameCrc] = obj;
  534. RegisterObjectName(obj->GetName());
  535. InvalidateVisibleList();
  536. NotifyObjectListeners(obj, CBaseObject::ON_ADD);
  537. return true;
  538. }
  539. //////////////////////////////////////////////////////////////////////////
  540. void CObjectManager::RemoveObject(CBaseObject* obj)
  541. {
  542. assert(obj != 0);
  543. InvalidateVisibleList();
  544. // Handle removing object from type-specific containers if needed
  545. {
  546. if (CEntityObject* entityObj = qobject_cast<CEntityObject*>(obj))
  547. {
  548. m_animatedAttachedEntities.erase(entityObj);
  549. }
  550. }
  551. // Remove this object from selection groups.
  552. m_currSelection->RemoveObject(obj);
  553. std::vector<CSelectionGroup*> sel;
  554. stl::map_to_vector(m_selections, sel);
  555. for (int i = 0; i < sel.size(); i++)
  556. {
  557. sel[i]->RemoveObject(obj);
  558. }
  559. m_objectsByName.erase(AZ::Crc32(obj->GetName().toUtf8().data(), obj->GetName().toUtf8().count(), true));
  560. // Need to erase this last since it is a smart pointer and can end up deleting the object if it is the last reference to it being kept
  561. m_objects.erase(obj->GetId());
  562. }
  563. //////////////////////////////////////////////////////////////////////////
  564. void CObjectManager::GetAllObjects(TBaseObjects& objects) const
  565. {
  566. objects.clear();
  567. objects.reserve(m_objects.size());
  568. for (Objects::const_iterator it = m_objects.begin(); it != m_objects.end(); ++it)
  569. {
  570. objects.push_back(it->second);
  571. }
  572. }
  573. //////////////////////////////////////////////////////////////////////////
  574. void CObjectManager::ChangeObjectId(REFGUID oldGuid, REFGUID newGuid)
  575. {
  576. Objects::iterator it = m_objects.find(oldGuid);
  577. if (it != m_objects.end())
  578. {
  579. CBaseObjectPtr pRemappedObject = (*it).second;
  580. pRemappedObject->SetId(newGuid);
  581. m_objects.erase(it);
  582. m_objects.insert(std::make_pair(newGuid, pRemappedObject));
  583. }
  584. }
  585. //////////////////////////////////////////////////////////////////////////
  586. void CObjectManager::ShowDuplicationMsgWarning(CBaseObject* obj, const QString& newName, bool bShowMsgBox) const
  587. {
  588. CBaseObject* pExisting = FindObject(newName);
  589. if (pExisting)
  590. {
  591. QString sRenameWarning = QObject::tr("%1 \"%2\" was NOT renamed to \"%3\" because %4 with the same name already exists.")
  592. .arg(obj->GetClassDesc()->ClassName())
  593. .arg(obj->GetName())
  594. .arg(newName)
  595. .arg(pExisting->GetClassDesc()->ClassName()
  596. );
  597. // If id is taken.
  598. CryWarning(VALIDATOR_MODULE_EDITOR, VALIDATOR_WARNING, sRenameWarning.toUtf8().data());
  599. if (bShowMsgBox)
  600. {
  601. QMessageBox::critical(QApplication::activeWindow(), QString(), sRenameWarning);
  602. }
  603. }
  604. }
  605. //////////////////////////////////////////////////////////////////////////
  606. void CObjectManager::ChangeObjectName(CBaseObject* obj, const QString& newName)
  607. {
  608. assert(obj);
  609. if (newName != obj->GetName())
  610. {
  611. if (IsDuplicateObjectName(newName))
  612. {
  613. return;
  614. }
  615. // Remove previous name from map
  616. const AZ::Crc32 oldNameCrc(obj->GetName().toUtf8().data(), obj->GetName().count(), true);
  617. m_objectsByName.erase(oldNameCrc);
  618. obj->SetName(newName);
  619. // Add new name to map
  620. const AZ::Crc32 nameCrc(newName.toUtf8().data(), newName.count(), true);
  621. m_objectsByName[nameCrc] = obj;
  622. }
  623. }
  624. //////////////////////////////////////////////////////////////////////////
  625. int CObjectManager::GetObjectCount() const
  626. {
  627. return static_cast<int>(m_objects.size());
  628. }
  629. //////////////////////////////////////////////////////////////////////////
  630. void CObjectManager::GetObjects(CBaseObjectsArray& objects) const
  631. {
  632. objects.clear();
  633. objects.reserve(m_objects.size());
  634. for (Objects::const_iterator it = m_objects.begin(); it != m_objects.end(); ++it)
  635. {
  636. objects.push_back(it->second);
  637. }
  638. }
  639. void CObjectManager::GetObjects(CBaseObjectsArray& objects, BaseObjectFilterFunctor const& filter) const
  640. {
  641. objects.clear();
  642. objects.reserve(m_objects.size());
  643. for (Objects::const_iterator it = m_objects.begin(); it != m_objects.end(); ++it)
  644. {
  645. assert(it->second);
  646. if (filter.first(*it->second, filter.second))
  647. {
  648. objects.push_back(it->second);
  649. }
  650. }
  651. }
  652. //////////////////////////////////////////////////////////////////////////
  653. void CObjectManager::SendEvent(ObjectEvent event)
  654. {
  655. if (event == EVENT_RELOAD_ENTITY)
  656. {
  657. m_bInReloading = true;
  658. }
  659. for (Objects::iterator it = m_objects.begin(); it != m_objects.end(); ++it)
  660. {
  661. CBaseObject* obj = it->second;
  662. obj->OnEvent(event);
  663. }
  664. if (event == EVENT_RELOAD_ENTITY)
  665. {
  666. m_bInReloading = false;
  667. GetIEditor()->Notify(eNotify_OnReloadTrackView);
  668. }
  669. }
  670. //////////////////////////////////////////////////////////////////////////
  671. void CObjectManager::SendEvent(ObjectEvent event, const AABB& bounds)
  672. {
  673. AABB box;
  674. for (Objects::iterator it = m_objects.begin(); it != m_objects.end(); ++it)
  675. {
  676. CBaseObject* obj = it->second;
  677. obj->GetBoundBox(box);
  678. if (bounds.IsIntersectBox(box))
  679. {
  680. obj->OnEvent(event);
  681. }
  682. }
  683. }
  684. //////////////////////////////////////////////////////////////////////////
  685. void CObjectManager::Update()
  686. {
  687. if (m_bSkipObjectUpdate)
  688. {
  689. return;
  690. }
  691. QWidget* prevActiveWindow = QApplication::activeWindow();
  692. // Restore focus if it changed.
  693. if (prevActiveWindow && QApplication::activeWindow() != prevActiveWindow)
  694. {
  695. prevActiveWindow->setFocus();
  696. }
  697. }
  698. //////////////////////////////////////////////////////////////////////////
  699. void CObjectManager::HideObject(CBaseObject* obj, bool hide)
  700. {
  701. assert(obj != 0);
  702. if (hide)
  703. {
  704. obj->SetHidden(hide, ++m_currentHideCount);
  705. }
  706. else
  707. {
  708. obj->SetHidden(false);
  709. }
  710. InvalidateVisibleList();
  711. }
  712. void CObjectManager::ShowLastHiddenObject()
  713. {
  714. uint64 mostRecentID = CBaseObject::s_invalidHiddenID;
  715. CBaseObject* mostRecentObject = nullptr;
  716. for (auto it : m_objects)
  717. {
  718. CBaseObject* obj = it.second;
  719. uint64 hiddenID = obj->GetHideOrder();
  720. if (hiddenID > mostRecentID)
  721. {
  722. mostRecentID = hiddenID;
  723. mostRecentObject = obj;
  724. }
  725. }
  726. if (mostRecentObject != nullptr)
  727. {
  728. mostRecentObject->SetHidden(false);
  729. }
  730. }
  731. //////////////////////////////////////////////////////////////////////////
  732. void CObjectManager::UnhideAll()
  733. {
  734. for (Objects::iterator it = m_objects.begin(); it != m_objects.end(); ++it)
  735. {
  736. CBaseObject* obj = it->second;
  737. obj->SetHidden(false);
  738. }
  739. InvalidateVisibleList();
  740. }
  741. //////////////////////////////////////////////////////////////////////////
  742. void CObjectManager::FreezeObject(CBaseObject* obj, bool freeze)
  743. {
  744. assert(obj != 0);
  745. // Remove object from main object set and put it to hidden set.
  746. obj->SetFrozen(freeze);
  747. InvalidateVisibleList();
  748. }
  749. //////////////////////////////////////////////////////////////////////////
  750. void CObjectManager::UnfreezeAll()
  751. {
  752. for (Objects::iterator it = m_objects.begin(); it != m_objects.end(); ++it)
  753. {
  754. CBaseObject* obj = it->second;
  755. obj->SetFrozen(false);
  756. }
  757. InvalidateVisibleList();
  758. }
  759. //////////////////////////////////////////////////////////////////////////
  760. bool CObjectManager::SelectObject(CBaseObject* obj, bool bUseMask)
  761. {
  762. assert(obj);
  763. if (obj == nullptr)
  764. {
  765. return false;
  766. }
  767. // Check if can be selected.
  768. if (bUseMask && (!(obj->GetType() & gSettings.objectSelectMask)))
  769. {
  770. return false;
  771. }
  772. if (m_selectCallback)
  773. {
  774. if (!m_selectCallback->OnSelectObject(obj))
  775. {
  776. return true;
  777. }
  778. }
  779. m_currSelection->AddObject(obj);
  780. // while in ComponentMode we never explicitly change selection (the entity will always be selected).
  781. // this check is to handle the case where an undo or redo action has occurred and
  782. // the entity has been destroyed and recreated as part of the deserialization step.
  783. // we want the internal state to stay consistent but do not want to notify other systems of the change.
  784. if (AzToolsFramework::ComponentModeFramework::InComponentMode())
  785. {
  786. obj->SetSelected(true);
  787. }
  788. else
  789. {
  790. SetObjectSelected(obj, true);
  791. GetIEditor()->Notify(eNotify_OnSelectionChange);
  792. }
  793. return true;
  794. }
  795. void CObjectManager::SelectEntities(std::set<CEntityObject*>& s)
  796. {
  797. for (std::set<CEntityObject*>::iterator it = s.begin(), end = s.end(); it != end; ++it)
  798. {
  799. SelectObject(*it);
  800. }
  801. }
  802. void CObjectManager::UnselectObject(CBaseObject* obj)
  803. {
  804. // while in ComponentMode we never explicitly change selection (the entity will always be selected).
  805. // this check is to handle the case where an undo or redo action has occurred and
  806. // the entity has been destroyed and recreated as part of the deserialization step.
  807. // we want the internal state to stay consistent but do not want to notify other systems of the change.
  808. if (AzToolsFramework::ComponentModeFramework::InComponentMode())
  809. {
  810. obj->SetSelected(false);
  811. }
  812. else
  813. {
  814. SetObjectSelected(obj, false);
  815. }
  816. m_currSelection->RemoveObject(obj);
  817. }
  818. CSelectionGroup* CObjectManager::GetSelection(const QString& name) const
  819. {
  820. CSelectionGroup* selection = stl::find_in_map(m_selections, name, (CSelectionGroup*)nullptr);
  821. return selection;
  822. }
  823. void CObjectManager::GetNameSelectionStrings(QStringList& names)
  824. {
  825. for (TNameSelectionMap::iterator it = m_selections.begin(); it != m_selections.end(); ++it)
  826. {
  827. names.push_back(it->first);
  828. }
  829. }
  830. void CObjectManager::NameSelection(const QString& name)
  831. {
  832. if (m_currSelection->IsEmpty())
  833. {
  834. return;
  835. }
  836. CSelectionGroup* selection = stl::find_in_map(m_selections, name, (CSelectionGroup*)nullptr);
  837. if (selection)
  838. {
  839. assert(selection != 0);
  840. // Check if trying to rename itself to the same name.
  841. if (selection == m_currSelection)
  842. {
  843. return;
  844. }
  845. m_selections.erase(name);
  846. delete selection;
  847. }
  848. selection = new CSelectionGroup;
  849. selection->Copy(*m_currSelection);
  850. selection->SetName(name);
  851. m_selections[name] = selection;
  852. m_currSelection = selection;
  853. m_defaultSelection.RemoveAll();
  854. }
  855. void CObjectManager::SerializeNameSelection(XmlNodeRef& rootNode, bool bLoading)
  856. {
  857. if (!rootNode)
  858. {
  859. return;
  860. }
  861. _smart_ptr<CSelectionGroup> tmpGroup(nullptr);
  862. QString selRootStr("NameSelection");
  863. QString selNodeStr("NameSelectionNode");
  864. QString selNodeNameStr("name");
  865. QString idStr("id");
  866. QString objAttrStr("obj");
  867. XmlNodeRef startNode = rootNode->findChild(selRootStr.toUtf8().data());
  868. if (bLoading)
  869. {
  870. m_selections.erase(m_selections.begin(), m_selections.end());
  871. if (startNode)
  872. {
  873. for (int selNodeNo = 0; selNodeNo < startNode->getChildCount(); ++selNodeNo)
  874. {
  875. XmlNodeRef selNode = startNode->getChild(selNodeNo);
  876. tmpGroup = new CSelectionGroup;
  877. for (int objIDNodeNo = 0; objIDNodeNo < selNode->getChildCount(); ++objIDNodeNo)
  878. {
  879. GUID curID = GUID_NULL;
  880. XmlNodeRef idNode = selNode->getChild(objIDNodeNo);
  881. if (!idNode->getAttr(idStr.toUtf8().data(), curID))
  882. {
  883. continue;
  884. }
  885. if (curID != GUID_NULL)
  886. {
  887. if (GetIEditor()->GetObjectManager()->FindObject(curID))
  888. {
  889. tmpGroup->AddObject(GetIEditor()->GetObjectManager()->FindObject(curID));
  890. }
  891. }
  892. }
  893. if (tmpGroup->GetCount() > 0)
  894. {
  895. QString nameStr;
  896. if (!selNode->getAttr(selNodeNameStr.toUtf8().data(), nameStr))
  897. {
  898. continue;
  899. }
  900. tmpGroup->SetName(nameStr);
  901. m_selections[nameStr] = tmpGroup;
  902. }
  903. }
  904. }
  905. }
  906. else
  907. {
  908. startNode = rootNode->newChild(selRootStr.toUtf8().data());
  909. CSelectionGroup* objSelection = nullptr;
  910. for (TNameSelectionMap::iterator it = m_selections.begin(); it != m_selections.end(); ++it)
  911. {
  912. XmlNodeRef selectionNameNode = startNode->newChild(selNodeStr.toUtf8().data());
  913. selectionNameNode->setAttr(selNodeNameStr.toUtf8().data(), it->first.toUtf8().data());
  914. objSelection = it->second;
  915. if (!objSelection)
  916. {
  917. continue;
  918. }
  919. if (objSelection->GetCount() == 0)
  920. {
  921. continue;
  922. }
  923. for (int i = 0; i < objSelection->GetCount(); ++i)
  924. {
  925. if (objSelection->GetObject(i))
  926. {
  927. XmlNodeRef objNode = selectionNameNode->newChild(objAttrStr.toUtf8().data());
  928. objNode->setAttr(idStr.toUtf8().data(), GuidUtil::ToString(objSelection->GetObject(i)->GetId()));
  929. }
  930. }
  931. }
  932. }
  933. }
  934. //////////////////////////////////////////////////////////////////////////
  935. int CObjectManager::ClearSelection()
  936. {
  937. AZ_PROFILE_FUNCTION(Editor);
  938. // Make sure to unlock selection.
  939. GetIEditor()->LockSelection(false);
  940. int numSel = m_currSelection->GetCount();
  941. // Handle Undo/Redo of Component Entities
  942. bool isUndoRecording = GetIEditor()->IsUndoRecording();
  943. if (isUndoRecording)
  944. {
  945. m_processingBulkSelect = true;
  946. GetIEditor()->RecordUndo(new CUndoBaseObjectClearSelection(*m_currSelection));
  947. }
  948. // Handle legacy entities separately so the selection group can be cleared safely.
  949. // This prevents every AzEntity from being removed one by one from a vector.
  950. m_currSelection->RemoveAllExceptLegacySet();
  951. // Kick off Deselect for Legacy Entities
  952. for (CBaseObjectPtr legacyObject : m_currSelection->GetLegacyObjects())
  953. {
  954. if (isUndoRecording && legacyObject->IsSelected())
  955. {
  956. GetIEditor()->RecordUndo(new CUndoBaseObjectSelect(legacyObject));
  957. }
  958. SetObjectSelected(legacyObject, false);
  959. }
  960. // Legacy set is cleared
  961. m_defaultSelection.RemoveAll();
  962. m_currSelection = &m_defaultSelection;
  963. m_bSelectionChanged = true;
  964. // Unselect all component entities as one bulk operation instead of individually
  965. AzToolsFramework::ToolsApplicationRequestBus::Broadcast(
  966. &AzToolsFramework::ToolsApplicationRequests::SetSelectedEntities,
  967. AzToolsFramework::EntityIdList());
  968. m_processingBulkSelect = false;
  969. if (!m_bExiting)
  970. {
  971. GetIEditor()->Notify(eNotify_OnSelectionChange);
  972. }
  973. return numSel;
  974. }
  975. //////////////////////////////////////////////////////////////////////////
  976. int CObjectManager::InvertSelection()
  977. {
  978. AZ_PROFILE_FUNCTION(Editor);
  979. int selCount = 0;
  980. // iterate all objects.
  981. for (Objects::const_iterator it = m_objects.begin(); it != m_objects.end(); ++it)
  982. {
  983. CBaseObject* pObj = it->second;
  984. if (pObj->IsSelected())
  985. {
  986. UnselectObject(pObj);
  987. }
  988. else
  989. {
  990. if (SelectObject(pObj))
  991. {
  992. selCount++;
  993. }
  994. }
  995. }
  996. return selCount;
  997. }
  998. void CObjectManager::SetSelection(const QString& name)
  999. {
  1000. AZ_PROFILE_FUNCTION(Editor);
  1001. CSelectionGroup* selection = stl::find_in_map(m_selections, name, (CSelectionGroup*)nullptr);
  1002. if (selection)
  1003. {
  1004. UnselectCurrent();
  1005. assert(selection != 0);
  1006. m_currSelection = selection;
  1007. SelectCurrent();
  1008. }
  1009. }
  1010. void CObjectManager::RemoveSelection(const QString& name)
  1011. {
  1012. AZ_PROFILE_FUNCTION(Editor);
  1013. QString selName = name;
  1014. CSelectionGroup* selection = stl::find_in_map(m_selections, name, (CSelectionGroup*)nullptr);
  1015. if (selection)
  1016. {
  1017. if (selection == m_currSelection)
  1018. {
  1019. UnselectCurrent();
  1020. m_currSelection = &m_defaultSelection;
  1021. m_defaultSelection.RemoveAll();
  1022. }
  1023. delete selection;
  1024. m_selections.erase(selName);
  1025. }
  1026. }
  1027. void CObjectManager::SelectCurrent()
  1028. {
  1029. AZ_PROFILE_FUNCTION(Editor);
  1030. for (int i = 0; i < m_currSelection->GetCount(); i++)
  1031. {
  1032. CBaseObject* obj = m_currSelection->GetObject(i);
  1033. if (GetIEditor()->IsUndoRecording() && !obj->IsSelected())
  1034. {
  1035. GetIEditor()->RecordUndo(new CUndoBaseObjectSelect(obj));
  1036. }
  1037. SetObjectSelected(obj, true);
  1038. }
  1039. }
  1040. void CObjectManager::UnselectCurrent()
  1041. {
  1042. AZ_PROFILE_FUNCTION(Editor);
  1043. // Make sure to unlock selection.
  1044. GetIEditor()->LockSelection(false);
  1045. // Unselect all component entities as one bulk operation instead of individually
  1046. AzToolsFramework::EntityIdList selectedEntities;
  1047. EBUS_EVENT(AzToolsFramework::ToolsApplicationRequests::Bus, SetSelectedEntities, selectedEntities);
  1048. for (int i = 0; i < m_currSelection->GetCount(); i++)
  1049. {
  1050. CBaseObject* obj = m_currSelection->GetObject(i);
  1051. if (GetIEditor()->IsUndoRecording() && obj->IsSelected())
  1052. {
  1053. GetIEditor()->RecordUndo(new CUndoBaseObjectSelect(obj));
  1054. }
  1055. SetObjectSelected(obj, false);
  1056. }
  1057. }
  1058. //////////////////////////////////////////////////////////////////////////
  1059. void CObjectManager::Display(DisplayContext& dc)
  1060. {
  1061. AZ_PROFILE_FUNCTION(Editor);
  1062. int currentHideMask = GetIEditor()->GetDisplaySettings()->GetObjectHideMask();
  1063. if (m_lastHideMask != currentHideMask)
  1064. {
  1065. // a setting has changed which may cause the set of currently visible objects to change, so invalidate the serial number
  1066. // so that viewports and anyone else that needs to update settings knows it has to.
  1067. m_lastHideMask = currentHideMask;
  1068. ++m_visibilitySerialNumber;
  1069. }
  1070. // the object manager itself has a visibility list, so it also has to update its cache when the serial has changed
  1071. if (m_visibilitySerialNumber != m_lastComputedVisibility)
  1072. {
  1073. m_lastComputedVisibility = m_visibilitySerialNumber;
  1074. UpdateVisibilityList();
  1075. }
  1076. bool viewIsDirty = dc.settings->IsDisplayHelpers(); // displaying helpers require computing all the bound boxes and things anyway.
  1077. if (!viewIsDirty)
  1078. {
  1079. if (CBaseObjectsCache* cache = dc.view->GetVisibleObjectsCache())
  1080. {
  1081. // if the current rendering viewport has an out-of-date cache serial number, it needs to be refreshed too.
  1082. // views set their cache empty when they indicate they need to force a refresh.
  1083. if ((cache->GetObjectCount() == 0) || (cache->GetSerialNumber() != m_visibilitySerialNumber))
  1084. {
  1085. viewIsDirty = true;
  1086. }
  1087. }
  1088. }
  1089. if (viewIsDirty)
  1090. {
  1091. FindDisplayableObjects(dc, true); // this also actually draws the helpers.
  1092. // Also broadcast for anyone else that needs to draw global debug to do so now
  1093. AzFramework::DebugDisplayEventBus::Broadcast(&AzFramework::DebugDisplayEvents::DrawGlobalDebugInfo);
  1094. }
  1095. if (m_gizmoManager)
  1096. {
  1097. m_gizmoManager->Display(dc);
  1098. }
  1099. }
  1100. void CObjectManager::ForceUpdateVisibleObjectCache(DisplayContext& dc)
  1101. {
  1102. FindDisplayableObjects(dc, false);
  1103. }
  1104. void CObjectManager::FindDisplayableObjects(DisplayContext& dc, [[maybe_unused]] bool bDisplay)
  1105. {
  1106. // if the new IVisibilitySystem is being used, do not run this logic
  1107. if (ed_visibility_use)
  1108. {
  1109. return;
  1110. }
  1111. AZ_PROFILE_FUNCTION(Editor);
  1112. auto start = std::chrono::steady_clock::now();
  1113. CBaseObjectsCache* pDispayedViewObjects = dc.view->GetVisibleObjectsCache();
  1114. if (!pDispayedViewObjects)
  1115. {
  1116. return;
  1117. }
  1118. pDispayedViewObjects->SetSerialNumber(m_visibilitySerialNumber); // update viewport to be latest serial number
  1119. AABB bbox;
  1120. bbox.min.zero();
  1121. bbox.max.zero();
  1122. pDispayedViewObjects->ClearObjects();
  1123. pDispayedViewObjects->Reserve(static_cast<int>(m_visibleObjects.size()));
  1124. if (dc.flags & DISPLAY_2D)
  1125. {
  1126. int numVis = static_cast<int>(m_visibleObjects.size());
  1127. for (int i = 0; i < numVis; i++)
  1128. {
  1129. CBaseObject* obj = m_visibleObjects[i];
  1130. obj->GetBoundBox(bbox);
  1131. if (dc.box.IsIntersectBox(bbox))
  1132. {
  1133. pDispayedViewObjects->AddObject(obj);
  1134. }
  1135. }
  1136. }
  1137. else
  1138. {
  1139. CSelectionGroup* pSelection = GetSelection();
  1140. if (pSelection && pSelection->GetCount() > 1)
  1141. {
  1142. AABB mergedAABB;
  1143. mergedAABB.Reset();
  1144. for (int i = 0, iCount(pSelection->GetCount()); i < iCount; ++i)
  1145. {
  1146. CBaseObject* pObj(pSelection->GetObject(i));
  1147. if (pObj == nullptr)
  1148. {
  1149. continue;
  1150. }
  1151. AABB aabb;
  1152. pObj->GetBoundBox(aabb);
  1153. mergedAABB.Add(aabb);
  1154. }
  1155. pSelection->GetObject(0)->CBaseObject::DrawDimensions(dc, &mergedAABB);
  1156. }
  1157. int numVis = static_cast<int>(m_visibleObjects.size());
  1158. for (int i = 0; i < numVis; i++)
  1159. {
  1160. CBaseObject* obj = m_visibleObjects[i];
  1161. if (obj)
  1162. {
  1163. if ((dc.flags & DISPLAY_SELECTION_HELPERS) || obj->IsSelected())
  1164. {
  1165. pDispayedViewObjects->AddObject(obj);
  1166. }
  1167. }
  1168. }
  1169. }
  1170. if (ed_visibility_logTiming && !ed_visibility_use)
  1171. {
  1172. auto stop = std::chrono::steady_clock::now();
  1173. std::chrono::duration<double> diff = stop - start;
  1174. AZ_Printf("Visibility", "FindDisplayableObjects (old) - Duration: %f", diff);
  1175. }
  1176. }
  1177. void CObjectManager::BeginEditParams(CBaseObject* obj, int flags)
  1178. {
  1179. assert(obj != 0);
  1180. if (obj == m_currEditObject)
  1181. {
  1182. return;
  1183. }
  1184. if (GetSelection()->GetCount() > 1)
  1185. {
  1186. return;
  1187. }
  1188. QWidget* prevActiveWindow = QApplication::activeWindow();
  1189. if (m_currEditObject)
  1190. {
  1191. //if (obj->GetClassDesc() != m_currEditObject->GetClassDesc())
  1192. if (!obj->IsSameClass(m_currEditObject))
  1193. {
  1194. EndEditParams(flags);
  1195. }
  1196. }
  1197. m_currEditObject = obj;
  1198. if (flags & OBJECT_CREATE)
  1199. {
  1200. // Unselect all other objects.
  1201. ClearSelection();
  1202. // Select this object.
  1203. SelectObject(obj, false);
  1204. }
  1205. m_bSingleSelection = true;
  1206. // Restore focus if it changed.
  1207. // OBJECT_EDIT is used by the EntityOutliner when items are selected. Using it here to prevent shifting focus to the EntityInspector on select.
  1208. if (!(flags & OBJECT_EDIT) && prevActiveWindow && QApplication::activeWindow() != prevActiveWindow)
  1209. {
  1210. prevActiveWindow->setFocus();
  1211. }
  1212. }
  1213. void CObjectManager::EndEditParams([[maybe_unused]] int flags)
  1214. {
  1215. m_bSingleSelection = false;
  1216. m_currEditObject = nullptr;
  1217. //m_bSelectionChanged = false; // don't need to clear for ungroup
  1218. }
  1219. //! Select objects within specified distance from given position.
  1220. int CObjectManager::SelectObjects(const AABB& box, bool bUnselect)
  1221. {
  1222. AZ_PROFILE_FUNCTION(Editor);
  1223. int numSel = 0;
  1224. AABB objBounds;
  1225. for (Objects::iterator it = m_objects.begin(); it != m_objects.end(); ++it)
  1226. {
  1227. CBaseObject* obj = it->second;
  1228. if (obj->IsHidden())
  1229. {
  1230. continue;
  1231. }
  1232. obj->GetBoundBox(objBounds);
  1233. if (box.IsIntersectBox(objBounds))
  1234. {
  1235. numSel++;
  1236. if (!bUnselect)
  1237. {
  1238. SelectObject(obj);
  1239. }
  1240. else
  1241. {
  1242. UnselectObject(obj);
  1243. }
  1244. }
  1245. }
  1246. return numSel;
  1247. }
  1248. //////////////////////////////////////////////////////////////////////////
  1249. int CObjectManager::MoveObjects(const AABB& box, const Vec3& offset, ImageRotationDegrees rotation, [[maybe_unused]] bool bIsCopy)
  1250. {
  1251. AABB objBounds;
  1252. Vec3 src = (box.min + box.max) / 2;
  1253. Vec3 dst = src + offset;
  1254. float alpha = 0.0f;
  1255. switch (rotation)
  1256. {
  1257. case ImageRotationDegrees::Rotate90:
  1258. alpha = gf_halfPI;
  1259. break;
  1260. case ImageRotationDegrees::Rotate180:
  1261. alpha = gf_PI;
  1262. break;
  1263. case ImageRotationDegrees::Rotate270:
  1264. alpha = gf_PI + gf_halfPI;
  1265. break;
  1266. default:
  1267. break;
  1268. }
  1269. float cosa = cos(alpha);
  1270. float sina = sin(alpha);
  1271. for (Objects::iterator it = m_objects.begin(); it != m_objects.end(); ++it)
  1272. {
  1273. CBaseObject* obj = it->second;
  1274. if (obj->GetParent())
  1275. {
  1276. continue;
  1277. }
  1278. obj->GetBoundBox(objBounds);
  1279. if (box.IsIntersectBox(objBounds))
  1280. {
  1281. if (rotation == ImageRotationDegrees::Rotate0)
  1282. {
  1283. obj->SetPos(obj->GetPos() - src + dst);
  1284. }
  1285. else
  1286. {
  1287. Vec3 pos = obj->GetPos() - src;
  1288. Vec3 newPos(pos);
  1289. newPos.x = cosa * pos.x - sina * pos.y;
  1290. newPos.y = sina * pos.x + cosa * pos.y;
  1291. obj->SetPos(newPos + dst);
  1292. Quat q;
  1293. obj->SetRotation(q.CreateRotationZ(alpha) * obj->GetRotation());
  1294. }
  1295. }
  1296. }
  1297. return 0;
  1298. }
  1299. bool CObjectManager::IsObjectDeletionAllowed(CBaseObject* pObject)
  1300. {
  1301. if (!pObject)
  1302. {
  1303. return false;
  1304. }
  1305. return true;
  1306. };
  1307. //////////////////////////////////////////////////////////////////////////
  1308. void CObjectManager::DeleteSelection()
  1309. {
  1310. AZ_PROFILE_FUNCTION(Editor);
  1311. // Make sure to unlock selection.
  1312. GetIEditor()->LockSelection(false);
  1313. CSelectionGroup objects;
  1314. for (int i = 0; i < m_currSelection->GetCount(); i++)
  1315. {
  1316. // Check condition(s) if object could be deleted
  1317. if (!IsObjectDeletionAllowed(m_currSelection->GetObject(i)))
  1318. {
  1319. return;
  1320. }
  1321. objects.AddObject(m_currSelection->GetObject(i));
  1322. }
  1323. RemoveSelection(m_currSelection->GetName());
  1324. m_currSelection = &m_defaultSelection;
  1325. m_defaultSelection.RemoveAll();
  1326. DeleteSelection(&objects);
  1327. }
  1328. //////////////////////////////////////////////////////////////////////////
  1329. bool CObjectManager::HitTestObject(CBaseObject* obj, HitContext& hc)
  1330. {
  1331. AZ_PROFILE_FUNCTION(Editor);
  1332. if (obj->IsFrozen())
  1333. {
  1334. return false;
  1335. }
  1336. if (obj->IsHidden())
  1337. {
  1338. return false;
  1339. }
  1340. // This object is rejected by deep selection.
  1341. if (obj->CheckFlags(OBJFLAG_NO_HITTEST))
  1342. {
  1343. return false;
  1344. }
  1345. ObjectType objType = obj->GetType();
  1346. // Check if this object type is masked for selection.
  1347. if (!(objType & gSettings.objectSelectMask))
  1348. {
  1349. return false;
  1350. }
  1351. const bool bSelectionHelperHit = obj->HitHelperTest(hc);
  1352. if (hc.bUseSelectionHelpers && !bSelectionHelperHit)
  1353. {
  1354. return false;
  1355. }
  1356. if (!bSelectionHelperHit)
  1357. {
  1358. // Fast checking.
  1359. if (hc.camera && !obj->IsInCameraView(*hc.camera))
  1360. {
  1361. return false;
  1362. }
  1363. else if (hc.bounds && !obj->IntersectRectBounds(*hc.bounds))
  1364. {
  1365. return false;
  1366. }
  1367. // Do 2D space testing.
  1368. if (hc.nSubObjFlags == 0)
  1369. {
  1370. Ray ray(hc.raySrc, hc.rayDir);
  1371. if (!obj->IntersectRayBounds(ray))
  1372. {
  1373. return false;
  1374. }
  1375. }
  1376. else if (!obj->HitTestRect(hc))
  1377. {
  1378. return false;
  1379. }
  1380. }
  1381. return (bSelectionHelperHit || obj->HitTest(hc));
  1382. }
  1383. //////////////////////////////////////////////////////////////////////////
  1384. bool CObjectManager::HitTest(HitContext& hitInfo)
  1385. {
  1386. AZ_PROFILE_FUNCTION(Editor);
  1387. hitInfo.object = nullptr;
  1388. hitInfo.dist = FLT_MAX;
  1389. hitInfo.axis = 0;
  1390. hitInfo.manipulatorMode = 0;
  1391. HitContext hcOrg = hitInfo;
  1392. if (hcOrg.view)
  1393. {
  1394. hcOrg.view->GetPerpendicularAxis(nullptr, &hcOrg.b2DViewport);
  1395. }
  1396. hcOrg.rayDir = hcOrg.rayDir.GetNormalized();
  1397. HitContext hc = hcOrg;
  1398. float mindist = FLT_MAX;
  1399. if (!hitInfo.bIgnoreAxis && !hc.bUseSelectionHelpers)
  1400. {
  1401. // Test gizmos.
  1402. if (m_gizmoManager->HitTest(hc))
  1403. {
  1404. if (hc.axis != 0)
  1405. {
  1406. hitInfo.object = hc.object;
  1407. hitInfo.gizmo = hc.gizmo;
  1408. hitInfo.axis = hc.axis;
  1409. hitInfo.manipulatorMode = hc.manipulatorMode;
  1410. hitInfo.dist = hc.dist;
  1411. return true;
  1412. }
  1413. }
  1414. }
  1415. if (hitInfo.bOnlyGizmo)
  1416. {
  1417. return false;
  1418. }
  1419. // Only HitTest objects, that where previously Displayed.
  1420. CBaseObjectsCache* pDispayedViewObjects = hitInfo.view->GetVisibleObjectsCache();
  1421. const bool iconsPrioritized = true; // Force icons to always be prioritized over other things you hit. Can change to be a configurable option in the future.
  1422. CBaseObject* selected = nullptr;
  1423. const char* name = nullptr;
  1424. bool iconHit = false;
  1425. int numVis = pDispayedViewObjects->GetObjectCount();
  1426. for (int i = 0; i < numVis; i++)
  1427. {
  1428. CBaseObject* obj = pDispayedViewObjects->GetObject(i);
  1429. if (obj == hitInfo.pExcludedObject)
  1430. {
  1431. continue;
  1432. }
  1433. if (HitTestObject(obj, hc))
  1434. {
  1435. if (m_selectCallback && !m_selectCallback->CanSelectObject(obj))
  1436. {
  1437. continue;
  1438. }
  1439. // Check if this object is nearest.
  1440. if (hc.axis != 0)
  1441. {
  1442. hitInfo.object = obj;
  1443. hitInfo.axis = hc.axis;
  1444. hitInfo.dist = hc.dist;
  1445. return true;
  1446. }
  1447. // When prioritizing icons, we don't allow non-icon hits to beat icon hits
  1448. if (iconsPrioritized && iconHit && !hc.iconHit)
  1449. {
  1450. continue;
  1451. }
  1452. if (hc.dist < mindist || (!iconHit && hc.iconHit))
  1453. {
  1454. if (hc.iconHit)
  1455. {
  1456. iconHit = true;
  1457. }
  1458. mindist = hc.dist;
  1459. name = hc.name;
  1460. selected = obj;
  1461. }
  1462. // Clear the object pointer if an object was hit, not just if the collision
  1463. // was closer than any previous. Not all paths from HitTestObject set the object pointer and so you could get
  1464. // an object from a previous (rejected) result but with collision information about a closer hit.
  1465. hc.object = nullptr;
  1466. hc.iconHit = false;
  1467. // If use deep selection
  1468. if (hitInfo.pDeepSelection)
  1469. {
  1470. hitInfo.pDeepSelection->AddObject(hc.dist, obj);
  1471. }
  1472. }
  1473. }
  1474. if (selected)
  1475. {
  1476. hitInfo.object = selected;
  1477. hitInfo.dist = mindist;
  1478. hitInfo.name = name;
  1479. hitInfo.iconHit = iconHit;
  1480. return true;
  1481. }
  1482. return false;
  1483. }
  1484. void CObjectManager::FindObjectsInRect(CViewport* view, const QRect& rect, std::vector<GUID>& guids)
  1485. {
  1486. AZ_PROFILE_FUNCTION(Editor);
  1487. if (rect.width() < 1 || rect.height() < 1)
  1488. {
  1489. return;
  1490. }
  1491. HitContext hc;
  1492. hc.view = view;
  1493. hc.b2DViewport = view->GetType() != ET_ViewportCamera;
  1494. hc.rect = rect;
  1495. hc.bUseSelectionHelpers = view->GetAdvancedSelectModeFlag();
  1496. guids.clear();
  1497. CBaseObjectsCache* pDispayedViewObjects = view->GetVisibleObjectsCache();
  1498. int numVis = pDispayedViewObjects->GetObjectCount();
  1499. for (int i = 0; i < numVis; ++i)
  1500. {
  1501. CBaseObject* pObj = pDispayedViewObjects->GetObject(i);
  1502. HitTestObjectAgainstRect(pObj, view, hc, guids);
  1503. }
  1504. }
  1505. //////////////////////////////////////////////////////////////////////////
  1506. void CObjectManager::SelectObjectsInRect(CViewport* view, const QRect& rect, bool bSelect)
  1507. {
  1508. AZ_PROFILE_FUNCTION(Editor);
  1509. // Ignore too small rectangles.
  1510. if (rect.width() < 1 || rect.height() < 1)
  1511. {
  1512. return;
  1513. }
  1514. CUndo undo("Select Object(s)");
  1515. HitContext hc;
  1516. hc.view = view;
  1517. hc.b2DViewport = view->GetType() != ET_ViewportCamera;
  1518. hc.rect = rect;
  1519. hc.bUseSelectionHelpers = view->GetAdvancedSelectModeFlag();
  1520. bool isUndoRecording = GetIEditor()->IsUndoRecording();
  1521. if (isUndoRecording)
  1522. {
  1523. m_processingBulkSelect = true;
  1524. }
  1525. CBaseObjectsCache* displayedViewObjects = view->GetVisibleObjectsCache();
  1526. int numVis = displayedViewObjects->GetObjectCount();
  1527. // Tracking the previous selection allows proper undo/redo functionality of additional
  1528. // selections (CTRL + drag select)
  1529. AZStd::unordered_set<const CBaseObject*> previousSelection;
  1530. for (int i = 0; i < numVis; ++i)
  1531. {
  1532. CBaseObject* object = displayedViewObjects->GetObject(i);
  1533. if (object->IsSelected())
  1534. {
  1535. previousSelection.insert(object);
  1536. }
  1537. else
  1538. {
  1539. // This will update m_currSelection
  1540. SelectObjectInRect(object, view, hc, bSelect);
  1541. // Legacy undo/redo does not go through the Ebus system and must be done individually
  1542. if (isUndoRecording && object->GetType() != OBJTYPE_AZENTITY)
  1543. {
  1544. GetIEditor()->RecordUndo(new CUndoBaseObjectSelect(object, true));
  1545. }
  1546. }
  1547. }
  1548. if (isUndoRecording && m_currSelection)
  1549. {
  1550. // Component Entities can handle undo/redo in bulk due to Ebuses
  1551. GetIEditor()->RecordUndo(new CUndoBaseObjectBulkSelect(previousSelection, *m_currSelection));
  1552. }
  1553. m_processingBulkSelect = false;
  1554. }
  1555. //////////////////////////////////////////////////////////////////////////
  1556. uint16 FindPossibleObjectNameNumber(std::set<uint16>& numberSet)
  1557. {
  1558. const int LIMIT = 65535;
  1559. size_t nSetSize = numberSet.size();
  1560. for (uint16 i = 1; i < LIMIT; ++i)
  1561. {
  1562. uint16 candidateNumber = (i + nSetSize) % LIMIT;
  1563. if (numberSet.find(candidateNumber) == numberSet.end())
  1564. {
  1565. numberSet.insert(candidateNumber);
  1566. return candidateNumber;
  1567. }
  1568. }
  1569. return 0;
  1570. }
  1571. void CObjectManager::RegisterObjectName(const QString& name)
  1572. {
  1573. // Remove all numbers from the end of typename.
  1574. QString typeName = name;
  1575. int nameLen = typeName.length();
  1576. int len = nameLen;
  1577. while (len > 0 && typeName[len - 1].isDigit())
  1578. {
  1579. len--;
  1580. }
  1581. typeName = typeName.left(len);
  1582. uint16 num = 1;
  1583. if (len < nameLen)
  1584. {
  1585. num = (uint16)atoi((const char*)name.toUtf8().data() + len) + 0;
  1586. }
  1587. NameNumbersMap::iterator iNameNumber = m_nameNumbersMap.find(typeName);
  1588. if (iNameNumber == m_nameNumbersMap.end())
  1589. {
  1590. std::set<uint16> numberSet;
  1591. numberSet.insert(num);
  1592. m_nameNumbersMap[typeName] = numberSet;
  1593. }
  1594. else
  1595. {
  1596. std::set<uint16>& numberSet = iNameNumber->second;
  1597. numberSet.insert(num);
  1598. }
  1599. }
  1600. //////////////////////////////////////////////////////////////////////////
  1601. void CObjectManager::UpdateRegisterObjectName(const QString& name)
  1602. {
  1603. // Remove all numbers from the end of typename.
  1604. QString typeName = name;
  1605. int nameLen = typeName.length();
  1606. int len = nameLen;
  1607. while (len > 0 && typeName[len - 1].isDigit())
  1608. {
  1609. len--;
  1610. }
  1611. typeName = typeName.left(len);
  1612. uint16 num = 1;
  1613. if (len < nameLen)
  1614. {
  1615. num = (uint16)atoi((const char*)name.toUtf8().data() + len) + 0;
  1616. }
  1617. NameNumbersMap::iterator it = m_nameNumbersMap.find(typeName);
  1618. if (it != m_nameNumbersMap.end())
  1619. {
  1620. if (it->second.end() != it->second.find(num))
  1621. {
  1622. it->second.erase(num);
  1623. if (it->second.empty())
  1624. {
  1625. m_nameNumbersMap.erase(it);
  1626. }
  1627. }
  1628. }
  1629. }
  1630. //////////////////////////////////////////////////////////////////////////
  1631. QString CObjectManager::GenerateUniqueObjectName(const QString& theTypeName)
  1632. {
  1633. if (!m_bGenUniqObjectNames)
  1634. {
  1635. return theTypeName;
  1636. }
  1637. QString typeName = theTypeName;
  1638. const int subIndex = theTypeName.indexOf("::");
  1639. if (subIndex != -1 && subIndex > typeName.length() - 2)
  1640. {
  1641. typeName.remove(0, subIndex + 2);
  1642. }
  1643. // Remove all numbers from the end of typename.
  1644. int len = typeName.length();
  1645. while (len > 0 && typeName[len - 1].isDigit())
  1646. {
  1647. len--;
  1648. }
  1649. typeName = typeName.left(len);
  1650. NameNumbersMap::iterator ii = m_nameNumbersMap.find(typeName);
  1651. uint16 lastNumber = 1;
  1652. if (ii != m_nameNumbersMap.end())
  1653. {
  1654. lastNumber = FindPossibleObjectNameNumber(ii->second);
  1655. }
  1656. else
  1657. {
  1658. std::set<uint16> numberSet;
  1659. numberSet.insert(lastNumber);
  1660. m_nameNumbersMap[typeName] = numberSet;
  1661. }
  1662. QString str = QStringLiteral("%1%2").arg(typeName).arg(lastNumber);
  1663. return str;
  1664. }
  1665. //////////////////////////////////////////////////////////////////////////
  1666. bool CObjectManager::EnableUniqObjectNames(bool bEnable)
  1667. {
  1668. bool bPrev = m_bGenUniqObjectNames;
  1669. m_bGenUniqObjectNames = bEnable;
  1670. return bPrev;
  1671. }
  1672. //////////////////////////////////////////////////////////////////////////
  1673. CObjectClassDesc* CObjectManager::FindClass(const QString& className)
  1674. {
  1675. IClassDesc* cls = CClassFactory::Instance()->FindClass(className.toUtf8().data());
  1676. if (cls != nullptr && cls->SystemClassID() == ESYSTEM_CLASS_OBJECT)
  1677. {
  1678. return (CObjectClassDesc*)cls;
  1679. }
  1680. return nullptr;
  1681. }
  1682. //////////////////////////////////////////////////////////////////////////
  1683. void CObjectManager::GetClassCategories(QStringList& categories)
  1684. {
  1685. std::vector<IClassDesc*> classes;
  1686. CClassFactory::Instance()->GetClassesBySystemID(ESYSTEM_CLASS_OBJECT, classes);
  1687. std::set<QString> cset;
  1688. for (int i = 0; i < classes.size(); i++)
  1689. {
  1690. QString category = classes[i]->Category();
  1691. if (!category.isEmpty())
  1692. {
  1693. cset.insert(category);
  1694. }
  1695. }
  1696. categories.clear();
  1697. categories.reserve(static_cast<int>(cset.size()));
  1698. for (std::set<QString>::iterator cit = cset.begin(); cit != cset.end(); ++cit)
  1699. {
  1700. categories.push_back(*cit);
  1701. }
  1702. }
  1703. void CObjectManager::GetClassCategoryToolClassNamePairs(std::vector< std::pair<QString, QString> >& categoryToolClassNamePairs)
  1704. {
  1705. std::vector<IClassDesc*> classes;
  1706. CClassFactory::Instance()->GetClassesBySystemID(ESYSTEM_CLASS_OBJECT, classes);
  1707. std::set< std::pair<QString, QString> > cset;
  1708. for (int i = 0; i < classes.size(); i++)
  1709. {
  1710. QString category = classes[i]->Category();
  1711. QString toolClassName = ((CObjectClassDesc*)classes[i])->GetToolClassName();
  1712. if (!category.isEmpty())
  1713. {
  1714. cset.insert(std::pair<QString, QString>(category, toolClassName));
  1715. }
  1716. }
  1717. categoryToolClassNamePairs.clear();
  1718. categoryToolClassNamePairs.reserve(cset.size());
  1719. for (std::set< std::pair<QString, QString> >::iterator cit = cset.begin(); cit != cset.end(); ++cit)
  1720. {
  1721. categoryToolClassNamePairs.push_back(*cit);
  1722. }
  1723. }
  1724. void CObjectManager::GetClassTypes(const QString& category, QStringList& types)
  1725. {
  1726. std::vector<IClassDesc*> classes;
  1727. CClassFactory::Instance()->GetClassesBySystemID(ESYSTEM_CLASS_OBJECT, classes);
  1728. for (int i = 0; i < classes.size(); i++)
  1729. {
  1730. QString cat = classes[i]->Category();
  1731. if (QString::compare(cat, category, Qt::CaseInsensitive) == 0 && classes[i]->IsEnabled())
  1732. {
  1733. types.push_back(classes[i]->ClassName());
  1734. }
  1735. }
  1736. }
  1737. //////////////////////////////////////////////////////////////////////////
  1738. void CObjectManager::RegisterClassTemplate(const XmlNodeRef& templ)
  1739. {
  1740. QString typeName = templ->getTag();
  1741. QString superTypeName;
  1742. if (!templ->getAttr("SuperType", superTypeName))
  1743. {
  1744. return;
  1745. }
  1746. CObjectClassDesc* superType = FindClass(superTypeName);
  1747. if (!superType)
  1748. {
  1749. return;
  1750. }
  1751. QString category, fileSpec, initialName;
  1752. templ->getAttr("Category", category);
  1753. templ->getAttr("File", fileSpec);
  1754. templ->getAttr("Name", initialName);
  1755. CXMLObjectClassDesc* classDesc = new CXMLObjectClassDesc;
  1756. classDesc->superType = superType;
  1757. classDesc->type = typeName;
  1758. classDesc->category = category;
  1759. classDesc->fileSpec = fileSpec;
  1760. classDesc->guid = AZ::Uuid::CreateRandom();
  1761. CClassFactory::Instance()->RegisterClass(classDesc);
  1762. }
  1763. //////////////////////////////////////////////////////////////////////////
  1764. void CObjectManager::LoadClassTemplates(const QString& path)
  1765. {
  1766. QString dir = Path::AddPathSlash(path);
  1767. IFileUtil::FileArray files;
  1768. CFileUtil::ScanDirectory(dir, "*.xml", files, false);
  1769. for (int k = 0; k < files.size(); k++)
  1770. {
  1771. // Construct the full filepath of the current file
  1772. XmlNodeRef node = XmlHelpers::LoadXmlFromFile((dir + files[k].filename).toUtf8().data());
  1773. if (node != nullptr && node->isTag("ObjectTemplates"))
  1774. {
  1775. QString name;
  1776. for (int i = 0; i < node->getChildCount(); i++)
  1777. {
  1778. RegisterClassTemplate(node->getChild(i));
  1779. }
  1780. }
  1781. }
  1782. }
  1783. //////////////////////////////////////////////////////////////////////////
  1784. void CObjectManager::RegisterCVars()
  1785. {
  1786. REGISTER_CVAR2("AxisHelperHitRadius",
  1787. &m_axisHelperHitRadius,
  1788. 20,
  1789. VF_DEV_ONLY,
  1790. "Adjust the hit radius used for axis helpers, like the transform gizmo.");
  1791. }
  1792. //////////////////////////////////////////////////////////////////////////
  1793. void CObjectManager::Serialize(XmlNodeRef& xmlNode, bool bLoading, int flags)
  1794. {
  1795. if (!xmlNode)
  1796. {
  1797. return;
  1798. }
  1799. if (bLoading)
  1800. {
  1801. m_loadedObjects = 0;
  1802. if (flags == SERIALIZE_ONLY_NOTSHARED)
  1803. {
  1804. DeleteNotSharedObjects();
  1805. }
  1806. else if (flags == SERIALIZE_ONLY_SHARED)
  1807. {
  1808. DeleteSharedObjects();
  1809. }
  1810. else
  1811. {
  1812. DeleteAllObjects();
  1813. }
  1814. XmlNodeRef root = xmlNode->findChild("Objects");
  1815. int totalObjects = 0;
  1816. if (root)
  1817. {
  1818. root->getAttr("NumObjects", totalObjects);
  1819. }
  1820. StartObjectsLoading(totalObjects);
  1821. CObjectArchive ar(this, xmlNode, true);
  1822. // Loading.
  1823. if (root)
  1824. {
  1825. ar.node = root;
  1826. LoadObjects(ar, false);
  1827. }
  1828. EndObjectsLoading();
  1829. }
  1830. else
  1831. {
  1832. // Saving.
  1833. XmlNodeRef root = xmlNode->newChild("Objects");
  1834. CObjectArchive ar(this, root, false);
  1835. // Save all objects to XML.
  1836. for (Objects::iterator it = m_objects.begin(); it != m_objects.end(); ++it)
  1837. {
  1838. CBaseObject* obj = it->second;
  1839. if (obj->CheckFlags(OBJFLAG_DONT_SAVE))
  1840. {
  1841. continue;
  1842. }
  1843. if ((flags == SERIALIZE_ONLY_SHARED) && !obj->CheckFlags(OBJFLAG_SHARED))
  1844. {
  1845. continue;
  1846. }
  1847. else if ((flags == SERIALIZE_ONLY_NOTSHARED) && obj->CheckFlags(OBJFLAG_SHARED))
  1848. {
  1849. continue;
  1850. }
  1851. XmlNodeRef objNode = root->newChild("Object");
  1852. ar.node = objNode;
  1853. obj->Serialize(ar);
  1854. }
  1855. }
  1856. }
  1857. //////////////////////////////////////////////////////////////////////////
  1858. void CObjectManager::LoadObjects(CObjectArchive& objectArchive, bool bSelect)
  1859. {
  1860. m_bLoadingObjects = true;
  1861. XmlNodeRef objectsNode = objectArchive.node;
  1862. int numObjects = objectsNode->getChildCount();
  1863. for (int i = 0; i < numObjects; i++)
  1864. {
  1865. objectArchive.node = objectsNode->getChild(i);
  1866. CBaseObject* obj = objectArchive.LoadObject(objectsNode->getChild(i));
  1867. if (obj && bSelect)
  1868. {
  1869. SelectObject(obj);
  1870. }
  1871. }
  1872. EndObjectsLoading(); // End progress bar, here, Resolve objects have his own.
  1873. objectArchive.ResolveObjects();
  1874. InvalidateVisibleList();
  1875. m_bLoadingObjects = false;
  1876. }
  1877. //////////////////////////////////////////////////////////////////////////
  1878. void CObjectManager::Export(const QString& levelPath, XmlNodeRef& rootNode, bool onlyShared)
  1879. {
  1880. // Clear export files.
  1881. QFile::remove(QStringLiteral("%1TagPoints.ini").arg(levelPath));
  1882. QFile::remove(QStringLiteral("%1Volumes.ini").arg(levelPath));
  1883. // Save all objects to XML.
  1884. for (Objects::iterator it = m_objects.begin(); it != m_objects.end(); ++it)
  1885. {
  1886. CBaseObject* obj = it->second;
  1887. // Export Only shared objects.
  1888. if ((obj->CheckFlags(OBJFLAG_SHARED) && onlyShared) ||
  1889. (!obj->CheckFlags(OBJFLAG_SHARED) && !onlyShared))
  1890. {
  1891. obj->Export(levelPath, rootNode);
  1892. }
  1893. }
  1894. }
  1895. //////////////////////////////////////////////////////////////////////////
  1896. void CObjectManager::ExportEntities(XmlNodeRef& rootNode)
  1897. {
  1898. // Save all objects to XML.
  1899. for (Objects::iterator it = m_objects.begin(); it != m_objects.end(); ++it)
  1900. {
  1901. CBaseObject* obj = it->second;
  1902. if (qobject_cast<CEntityObject*>(obj))
  1903. {
  1904. obj->Export("", rootNode);
  1905. }
  1906. }
  1907. }
  1908. void CObjectManager::DeleteNotSharedObjects()
  1909. {
  1910. TBaseObjects objects;
  1911. GetAllObjects(objects);
  1912. for (int i = 0; i < objects.size(); i++)
  1913. {
  1914. CBaseObject* obj = objects[i];
  1915. if (!obj->CheckFlags(OBJFLAG_SHARED))
  1916. {
  1917. DeleteObject(obj);
  1918. }
  1919. }
  1920. }
  1921. void CObjectManager::DeleteSharedObjects()
  1922. {
  1923. TBaseObjects objects;
  1924. GetAllObjects(objects);
  1925. for (int i = 0; i < objects.size(); i++)
  1926. {
  1927. CBaseObject* obj = objects[i];
  1928. if (obj->CheckFlags(OBJFLAG_SHARED))
  1929. {
  1930. DeleteObject(obj);
  1931. }
  1932. }
  1933. }
  1934. //////////////////////////////////////////////////////////////////////////
  1935. IObjectSelectCallback* CObjectManager::SetSelectCallback(IObjectSelectCallback* callback)
  1936. {
  1937. IObjectSelectCallback* prev = m_selectCallback;
  1938. m_selectCallback = callback;
  1939. return prev;
  1940. }
  1941. //////////////////////////////////////////////////////////////////////////
  1942. void CObjectManager::InvalidateVisibleList()
  1943. {
  1944. if (m_isUpdateVisibilityList)
  1945. {
  1946. return;
  1947. }
  1948. ++m_visibilitySerialNumber;
  1949. m_visibleObjects.clear();
  1950. }
  1951. //////////////////////////////////////////////////////////////////////////
  1952. void CObjectManager::UpdateVisibilityList()
  1953. {
  1954. m_isUpdateVisibilityList = true;
  1955. m_visibleObjects.clear();
  1956. bool isInIsolationMode = false;
  1957. AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(
  1958. isInIsolationMode, &AzToolsFramework::ToolsApplicationRequestBus::Events::IsEditorInIsolationMode);
  1959. for (Objects::iterator it = m_objects.begin(); it != m_objects.end(); ++it)
  1960. {
  1961. CBaseObject* obj = it->second;
  1962. bool visible = obj->IsPotentiallyVisible();
  1963. // entities not isolated in Isolation Mode will be invisible
  1964. bool isObjectIsolated = obj->IsIsolated();
  1965. visible = visible && (!isInIsolationMode || isObjectIsolated);
  1966. obj->UpdateVisibility(visible);
  1967. // when the new viewport interaction model is enabled we always want to add objects
  1968. // in the view (frustum) to the visible objects list so we can draw feedback for
  1969. // entities being hidden in the viewport when selected in the entity outliner
  1970. // (EditorVisibleEntityDataCache must be populated even if entities are 'hidden')
  1971. m_visibleObjects.push_back(obj);
  1972. }
  1973. m_isUpdateVisibilityList = false;
  1974. }
  1975. //////////////////////////////////////////////////////////////////////////
  1976. bool CObjectManager::ConvertToType(CBaseObject* pObject, const QString& typeName)
  1977. {
  1978. QString message = QString("Convert ") + pObject->GetName() + " to " + typeName;
  1979. CUndo undo(message.toUtf8().data());
  1980. CBaseObjectPtr pNewObject = GetIEditor()->NewObject(typeName.toUtf8().data());
  1981. if (pNewObject)
  1982. {
  1983. if (pNewObject->ConvertFromObject(pObject))
  1984. {
  1985. DeleteObject(pObject);
  1986. return true;
  1987. }
  1988. DeleteObject(pNewObject);
  1989. }
  1990. Log((message + " is failed.").toUtf8().data());
  1991. return false;
  1992. }
  1993. //////////////////////////////////////////////////////////////////////////
  1994. void CObjectManager::SetObjectSelected(CBaseObject* pObject, bool bSelect)
  1995. {
  1996. AZ_PROFILE_FUNCTION(Editor);
  1997. // Only select/unselect once.
  1998. if ((pObject->IsSelected() && bSelect) || (!pObject->IsSelected() && !bSelect))
  1999. {
  2000. return;
  2001. }
  2002. // Store selection undo.
  2003. if (CUndo::IsRecording() && !m_processingBulkSelect)
  2004. {
  2005. CUndo::Record(new CUndoBaseObjectSelect(pObject));
  2006. }
  2007. pObject->SetSelected(bSelect);
  2008. m_bSelectionChanged = true;
  2009. if (bSelect && !GetIEditor()->GetTransformManipulator())
  2010. {
  2011. if (CAxisGizmo::GetGlobalAxisGizmoCount() < 1 /*legacy axisGizmoMaxCount*/)
  2012. {
  2013. // Create axis gizmo for this object.
  2014. m_gizmoManager->AddGizmo(new CAxisGizmo(pObject));
  2015. }
  2016. }
  2017. if (bSelect)
  2018. {
  2019. NotifyObjectListeners(pObject, CBaseObject::ON_SELECT);
  2020. }
  2021. else
  2022. {
  2023. NotifyObjectListeners(pObject, CBaseObject::ON_UNSELECT);
  2024. }
  2025. }
  2026. //////////////////////////////////////////////////////////////////////////
  2027. void CObjectManager::HideTransformManipulators()
  2028. {
  2029. m_gizmoManager->DeleteAllTransformManipulators();
  2030. }
  2031. //////////////////////////////////////////////////////////////////////////
  2032. //////////////////////////////////////////////////////////////////////////
  2033. void CObjectManager::AddObjectEventListener(EventListener* listener)
  2034. {
  2035. stl::push_back_unique(m_objectEventListeners, listener);
  2036. }
  2037. //////////////////////////////////////////////////////////////////////////
  2038. void CObjectManager::RemoveObjectEventListener(EventListener* listener)
  2039. {
  2040. stl::find_and_erase(m_objectEventListeners, listener);
  2041. }
  2042. //////////////////////////////////////////////////////////////////////////
  2043. void CObjectManager::NotifyObjectListeners(CBaseObject* pObject, CBaseObject::EObjectListenerEvent event)
  2044. {
  2045. std::list<EventListener*>::iterator next;
  2046. for (std::list<EventListener*>::iterator it = m_objectEventListeners.begin(); it != m_objectEventListeners.end(); it = next)
  2047. {
  2048. next = it;
  2049. ++next;
  2050. // Call listener callback.
  2051. (*it)->OnObjectEvent(pObject, event);
  2052. }
  2053. }
  2054. //////////////////////////////////////////////////////////////////////////
  2055. void CObjectManager::StartObjectsLoading(int numObjects)
  2056. {
  2057. if (m_pLoadProgress)
  2058. {
  2059. return;
  2060. }
  2061. m_pLoadProgress = new CWaitProgress("Loading Objects");
  2062. m_totalObjectsToLoad = numObjects;
  2063. m_loadedObjects = 0;
  2064. }
  2065. //////////////////////////////////////////////////////////////////////////
  2066. void CObjectManager::EndObjectsLoading()
  2067. {
  2068. if (m_pLoadProgress)
  2069. {
  2070. delete m_pLoadProgress;
  2071. }
  2072. m_pLoadProgress = nullptr;
  2073. }
  2074. //////////////////////////////////////////////////////////////////////////
  2075. void CObjectManager::GatherUsedResources(CUsedResources& resources)
  2076. {
  2077. CBaseObjectsArray objects;
  2078. GetIEditor()->GetObjectManager()->GetObjects(objects);
  2079. for (int i = 0; i < objects.size(); i++)
  2080. {
  2081. CBaseObject* pObject = objects[i];
  2082. pObject->GatherUsedResources(resources);
  2083. }
  2084. }
  2085. //////////////////////////////////////////////////////////////////////////
  2086. IGizmoManager* CObjectManager::GetGizmoManager()
  2087. {
  2088. return m_gizmoManager;
  2089. }
  2090. //////////////////////////////////////////////////////////////////////////
  2091. bool CObjectManager::IsLightClass(CBaseObject* pObject)
  2092. {
  2093. if (qobject_cast<CEntityObject*>(pObject))
  2094. {
  2095. CEntityObject* pEntity = (CEntityObject*)pObject;
  2096. if (pEntity)
  2097. {
  2098. if (pEntity->GetEntityClass().compare(CLASS_LIGHT) == 0)
  2099. {
  2100. return true;
  2101. }
  2102. if (pEntity->GetEntityClass().compare(CLASS_RIGIDBODY_LIGHT) == 0)
  2103. {
  2104. return true;
  2105. }
  2106. if (pEntity->GetEntityClass().compare(CLASS_DESTROYABLE_LIGHT) == 0)
  2107. {
  2108. return true;
  2109. }
  2110. }
  2111. }
  2112. return false;
  2113. }
  2114. void CObjectManager::FindAndRenameProperty2(const char* property2Name, const QString& oldValue, const QString& newValue)
  2115. {
  2116. CBaseObjectsArray objects;
  2117. GetObjects(objects);
  2118. for (size_t i = 0, n = objects.size(); i < n; ++i)
  2119. {
  2120. CBaseObject* pObject = objects[i];
  2121. if (qobject_cast<CEntityObject*>(pObject))
  2122. {
  2123. CEntityObject* pEntity = static_cast<CEntityObject*>(pObject);
  2124. CVarBlock* pProperties2 = pEntity->GetProperties2();
  2125. if (pProperties2)
  2126. {
  2127. IVariable* pVariable = pProperties2->FindVariable(property2Name);
  2128. if (pVariable)
  2129. {
  2130. QString sValue;
  2131. pVariable->Get(sValue);
  2132. if (sValue == oldValue)
  2133. {
  2134. pEntity->StoreUndo("Rename Property2");
  2135. pVariable->Set(newValue);
  2136. }
  2137. }
  2138. }
  2139. }
  2140. }
  2141. }
  2142. void CObjectManager::FindAndRenameProperty2If(const char* property2Name, const QString& oldValue, const QString& newValue, const char* otherProperty2Name, const QString& otherValue)
  2143. {
  2144. CBaseObjectsArray objects;
  2145. GetObjects(objects);
  2146. for (size_t i = 0, n = objects.size(); i < n; ++i)
  2147. {
  2148. CBaseObject* pObject = objects[i];
  2149. if (qobject_cast<CEntityObject*>(pObject))
  2150. {
  2151. CEntityObject* pEntity = static_cast<CEntityObject*>(pObject);
  2152. CVarBlock* pProperties2 = pEntity->GetProperties2();
  2153. if (pProperties2)
  2154. {
  2155. IVariable* pVariable = pProperties2->FindVariable(property2Name);
  2156. IVariable* pOtherVariable = pProperties2->FindVariable(otherProperty2Name);
  2157. if (pVariable && pOtherVariable)
  2158. {
  2159. QString sValue;
  2160. pVariable->Get(sValue);
  2161. QString sOtherValue;
  2162. pOtherVariable->Get(sOtherValue);
  2163. if ((sValue == oldValue) && (sOtherValue == otherValue))
  2164. {
  2165. pEntity->StoreUndo("Rename Property2 If");
  2166. pVariable->Set(newValue);
  2167. }
  2168. }
  2169. }
  2170. }
  2171. }
  2172. }
  2173. //////////////////////////////////////////////////////////////////////////
  2174. void CObjectManager::HitTestObjectAgainstRect(CBaseObject* pObj, CViewport* view, HitContext hc, std::vector<GUID>& guids)
  2175. {
  2176. if (!pObj->IsSelectable())
  2177. {
  2178. return;
  2179. }
  2180. AABB box;
  2181. // Retrieve world space bound box.
  2182. pObj->GetBoundBox(box);
  2183. // Check if object visible in viewport.
  2184. if (!view->IsBoundsVisible(box))
  2185. {
  2186. return;
  2187. }
  2188. if (pObj->HitTestRect(hc))
  2189. {
  2190. stl::push_back_unique(guids, pObj->GetId());
  2191. }
  2192. }
  2193. //////////////////////////////////////////////////////////////////////////
  2194. void CObjectManager::SelectObjectInRect(CBaseObject* pObj, CViewport* view, HitContext hc, bool bSelect)
  2195. {
  2196. if (!pObj->IsSelectable())
  2197. {
  2198. return;
  2199. }
  2200. AABB box;
  2201. // Retrieve world space bound box.
  2202. pObj->GetBoundBox(box);
  2203. // Check if object visible in viewport.
  2204. if (!view->IsBoundsVisible(box))
  2205. {
  2206. return;
  2207. }
  2208. if (pObj->HitTestRect(hc))
  2209. {
  2210. if (bSelect)
  2211. {
  2212. SelectObject(pObj);
  2213. }
  2214. else
  2215. {
  2216. UnselectObject(pObj);
  2217. }
  2218. }
  2219. }
  2220. void CObjectManager::EnteredComponentMode(const AZStd::vector<AZ::Uuid>& /*componentModeTypes*/)
  2221. {
  2222. // hide current gizmo for entity (translate/rotate/scale)
  2223. IGizmoManager* gizmoManager = GetGizmoManager();
  2224. const size_t gizmoCount = static_cast<size_t>(gizmoManager->GetGizmoCount());
  2225. for (size_t i = 0; i < gizmoCount; ++i)
  2226. {
  2227. gizmoManager->RemoveGizmo(gizmoManager->GetGizmoByIndex(static_cast<int>(i)));
  2228. }
  2229. }
  2230. void CObjectManager::LeftComponentMode(const AZStd::vector<AZ::Uuid>& /*componentModeTypes*/)
  2231. {
  2232. // show translate/rotate/scale gizmo again
  2233. if (IGizmoManager* gizmoManager = GetGizmoManager())
  2234. {
  2235. if (CBaseObject* selectedObject = GetIEditor()->GetSelectedObject())
  2236. {
  2237. gizmoManager->AddGizmo(new CAxisGizmo(selectedObject));
  2238. }
  2239. }
  2240. }
  2241. //////////////////////////////////////////////////////////////////////////
  2242. namespace
  2243. {
  2244. AZStd::vector<AZStd::string> PyGetAllObjects()
  2245. {
  2246. IObjectManager* pObjMgr = GetIEditor()->GetObjectManager();
  2247. CBaseObjectsArray objects;
  2248. pObjMgr->GetObjects(objects);
  2249. int count = pObjMgr->GetObjectCount();
  2250. AZStd::vector<AZStd::string> result;
  2251. for (int i = 0; i < count; ++i)
  2252. {
  2253. result.push_back(objects[i]->GetName().toUtf8().data());
  2254. }
  2255. return result;
  2256. }
  2257. AZStd::vector<AZStd::string> PyGetNamesOfSelectedObjects()
  2258. {
  2259. CSelectionGroup* pSel = GetIEditor()->GetSelection();
  2260. AZStd::vector<AZStd::string> result;
  2261. const int selectionCount = pSel->GetCount();
  2262. result.reserve(selectionCount);
  2263. for (int i = 0; i < selectionCount; i++)
  2264. {
  2265. result.push_back(pSel->GetObject(i)->GetName().toUtf8().data());
  2266. }
  2267. return result;
  2268. }
  2269. void PySelectObject(const char* objName)
  2270. {
  2271. CUndo undo("Select Object");
  2272. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(objName);
  2273. if (pObject)
  2274. {
  2275. GetIEditor()->GetObjectManager()->SelectObject(pObject);
  2276. }
  2277. }
  2278. void PyUnselectObjects(const AZStd::vector<AZStd::string>& names)
  2279. {
  2280. CUndo undo("Unselect Objects");
  2281. std::vector<CBaseObject*> pBaseObjects;
  2282. for (int i = 0; i < names.size(); i++)
  2283. {
  2284. if (!GetIEditor()->GetObjectManager()->FindObject(names[i].c_str()))
  2285. {
  2286. throw std::logic_error((QString("\"") + names[i].c_str() + "\" is an invalid entity.").toUtf8().data());
  2287. }
  2288. pBaseObjects.push_back(GetIEditor()->GetObjectManager()->FindObject(names[i].c_str()));
  2289. }
  2290. for (int i = 0; i < pBaseObjects.size(); i++)
  2291. {
  2292. GetIEditor()->GetObjectManager()->UnselectObject(pBaseObjects[i]);
  2293. }
  2294. }
  2295. void PySelectObjects(const AZStd::vector<AZStd::string>& names)
  2296. {
  2297. CUndo undo("Select Objects");
  2298. CBaseObject* pObject;
  2299. for (size_t i = 0; i < names.size(); ++i)
  2300. {
  2301. pObject = GetIEditor()->GetObjectManager()->FindObject(names[i].c_str());
  2302. if (!pObject)
  2303. {
  2304. throw std::logic_error((QString("\"") + names[i].c_str() + "\" is an invalid entity.").toUtf8().data());
  2305. }
  2306. GetIEditor()->GetObjectManager()->SelectObject(pObject);
  2307. }
  2308. }
  2309. bool PyIsObjectHidden(const char* objName)
  2310. {
  2311. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(objName);
  2312. if (!pObject)
  2313. {
  2314. throw std::logic_error((QString("\"") + objName + "\" is an invalid object name.").toUtf8().data());
  2315. }
  2316. return pObject->IsHidden();
  2317. }
  2318. void PyHideAllObjects()
  2319. {
  2320. CBaseObjectsArray baseObjects;
  2321. GetIEditor()->GetObjectManager()->GetObjects(baseObjects);
  2322. if (baseObjects.size() <= 0)
  2323. {
  2324. throw std::logic_error("Objects not found.");
  2325. }
  2326. CUndo undo("Hide All Objects");
  2327. for (int i = 0; i < baseObjects.size(); i++)
  2328. {
  2329. GetIEditor()->GetObjectManager()->HideObject(baseObjects[i], true);
  2330. }
  2331. }
  2332. void PyUnHideAllObjects()
  2333. {
  2334. CUndo undo("Unhide All Objects");
  2335. GetIEditor()->GetObjectManager()->UnhideAll();
  2336. }
  2337. void PyHideObject(const char* objName)
  2338. {
  2339. CUndo undo("Hide Object");
  2340. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(objName);
  2341. if (pObject)
  2342. {
  2343. GetIEditor()->GetObjectManager()->HideObject(pObject, true);
  2344. }
  2345. }
  2346. void PyUnhideObject(const char* objName)
  2347. {
  2348. CUndo undo("Unhide Object");
  2349. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(objName);
  2350. if (pObject)
  2351. {
  2352. GetIEditor()->GetObjectManager()->HideObject(pObject, false);
  2353. }
  2354. }
  2355. void PyFreezeObject(const char* objName)
  2356. {
  2357. CUndo undo("Freeze Object");
  2358. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(objName);
  2359. if (pObject)
  2360. {
  2361. GetIEditor()->GetObjectManager()->FreezeObject(pObject, true);
  2362. }
  2363. }
  2364. void PyUnfreezeObject(const char* objName)
  2365. {
  2366. CUndo undo("Unfreeze Object");
  2367. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(objName);
  2368. if (pObject)
  2369. {
  2370. GetIEditor()->GetObjectManager()->FreezeObject(pObject, false);
  2371. }
  2372. }
  2373. bool PyIsObjectFrozen(const char* objName)
  2374. {
  2375. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(objName);
  2376. if (!pObject)
  2377. {
  2378. throw std::logic_error((QString("\"") + objName + "\" is an invalid object name.").toUtf8().data());
  2379. }
  2380. return pObject->IsFrozen();
  2381. }
  2382. void PyDeleteObject(const char* objName)
  2383. {
  2384. CUndo undo("Delete Object");
  2385. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(objName);
  2386. if (pObject)
  2387. {
  2388. GetIEditor()->GetObjectManager()->DeleteObject(pObject);
  2389. }
  2390. }
  2391. int PyClearSelection()
  2392. {
  2393. CUndo undo("Clear Selection");
  2394. return GetIEditor()->GetObjectManager()->ClearSelection();
  2395. }
  2396. void PyDeleteSelected()
  2397. {
  2398. CUndo undo("Delete Selected Object");
  2399. GetIEditor()->GetObjectManager()->DeleteSelection();
  2400. }
  2401. int PyGetNumSelectedObjects()
  2402. {
  2403. if (CSelectionGroup* pGroup = GetIEditor()->GetObjectManager()->GetSelection())
  2404. {
  2405. return pGroup->GetCount();
  2406. }
  2407. return 0;
  2408. }
  2409. AZ::Vector3 PyGetSelectionCenter()
  2410. {
  2411. if (CSelectionGroup* pGroup = GetIEditor()->GetObjectManager()->GetSelection())
  2412. {
  2413. if (pGroup->GetCount() == 0)
  2414. {
  2415. throw std::runtime_error("Nothing selected");
  2416. }
  2417. const Vec3 center = pGroup->GetCenter();
  2418. return AZ::Vector3(center.x, center.y, center.z);
  2419. }
  2420. throw std::runtime_error("Nothing selected");
  2421. }
  2422. AZ::Aabb PyGetSelectionAABB()
  2423. {
  2424. if (CSelectionGroup* pGroup = GetIEditor()->GetObjectManager()->GetSelection())
  2425. {
  2426. if (pGroup->GetCount() == 0)
  2427. {
  2428. throw std::runtime_error("Nothing selected");
  2429. }
  2430. const AABB aabb = pGroup->GetBounds();
  2431. AZ::Aabb result;
  2432. result.Set(
  2433. AZ::Vector3(
  2434. aabb.min.x,
  2435. aabb.min.y,
  2436. aabb.min.z
  2437. ),
  2438. AZ::Vector3(
  2439. aabb.max.x,
  2440. aabb.max.y,
  2441. aabb.max.z
  2442. )
  2443. );
  2444. return result;
  2445. }
  2446. throw std::runtime_error("Nothing selected");
  2447. }
  2448. AZ::Vector3 PyGetObjectPosition(const char* pName)
  2449. {
  2450. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(pName);
  2451. if (!pObject)
  2452. {
  2453. throw std::logic_error((QString("\"") + pName + "\" is an invalid object.").toUtf8().data());
  2454. }
  2455. Vec3 position = pObject->GetPos();
  2456. return AZ::Vector3(position.x, position.y, position.z);
  2457. }
  2458. void PySetObjectPosition(const char* pName, float fValueX, float fValueY, float fValueZ)
  2459. {
  2460. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(pName);
  2461. if (!pObject)
  2462. {
  2463. throw std::logic_error((QString("\"") + pName + "\" is an invalid object.").toUtf8().data());
  2464. }
  2465. CUndo undo("Set Object Base Position");
  2466. pObject->SetPos(Vec3(fValueX, fValueY, fValueZ));
  2467. }
  2468. AZ::Vector3 PyGetObjectRotation(const char* pName)
  2469. {
  2470. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(pName);
  2471. if (!pObject)
  2472. {
  2473. throw std::logic_error((QString("\"") + pName + "\" is an invalid object.").toUtf8().data());
  2474. }
  2475. Ang3 ang = RAD2DEG(Ang3(pObject->GetRotation()));
  2476. return AZ::Vector3(ang.x, ang.y, ang.z);
  2477. }
  2478. void PySetObjectRotation(const char* pName, float fValueX, float fValueY, float fValueZ)
  2479. {
  2480. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(pName);
  2481. if (!pObject)
  2482. {
  2483. throw std::logic_error((QString("\"") + pName + "\" is an invalid object.").toUtf8().data());
  2484. }
  2485. CUndo undo("Set Object Rotation");
  2486. pObject->SetRotation(Quat(DEG2RAD(Ang3(fValueX, fValueY, fValueZ))));
  2487. }
  2488. AZ::Vector3 PyGetObjectScale(const char* pName)
  2489. {
  2490. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(pName);
  2491. if (!pObject)
  2492. {
  2493. throw std::logic_error((QString("\"") + pName + "\" is an invalid object.").toUtf8().data());
  2494. }
  2495. Vec3 scaleVec3 = pObject->GetScale();
  2496. return AZ::Vector3(scaleVec3.x, scaleVec3.y, scaleVec3.z);
  2497. }
  2498. void PySetObjectScale(const char* pName, float fValueX, float fValueY, float fValueZ)
  2499. {
  2500. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(pName);
  2501. if (!pObject)
  2502. {
  2503. throw std::logic_error((QString("\"") + pName + "\" is an invalid object.").toUtf8().data());
  2504. }
  2505. CUndo undo("Set Object Scale");
  2506. pObject->SetScale(Vec3(fValueX, fValueY, fValueZ));
  2507. }
  2508. void PyRenameObject(const char* pOldName, const char* pNewName)
  2509. {
  2510. CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(pOldName);
  2511. if (!pObject)
  2512. {
  2513. throw std::runtime_error("Could not find object");
  2514. }
  2515. if (strcmp(pNewName, "") == 0 || GetIEditor()->GetObjectManager()->FindObject(pNewName))
  2516. {
  2517. throw std::runtime_error("Invalid object name.");
  2518. }
  2519. CUndo undo("Rename object");
  2520. pObject->SetName(pNewName);
  2521. }
  2522. }
  2523. namespace AzToolsFramework
  2524. {
  2525. void ObjectManagerFuncsHandler::Reflect(AZ::ReflectContext* context)
  2526. {
  2527. if (auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  2528. {
  2529. // this will put these methods into the 'azlmbr.legacy.general' module
  2530. auto addLegacyGeneral = [](AZ::BehaviorContext::GlobalMethodBuilder methodBuilder)
  2531. {
  2532. methodBuilder->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
  2533. ->Attribute(AZ::Script::Attributes::Category, "Legacy/Editor")
  2534. ->Attribute(AZ::Script::Attributes::Module, "legacy.general");
  2535. };
  2536. addLegacyGeneral(behaviorContext->Method("get_all_objects", PyGetAllObjects, nullptr, "Gets the list of names of all objects in the whole level."));
  2537. addLegacyGeneral(behaviorContext->Method("get_names_of_selected_objects", PyGetNamesOfSelectedObjects, nullptr, "Get the name from selected object/objects."));
  2538. addLegacyGeneral(behaviorContext->Method("select_object", PySelectObject, nullptr, "Selects a specified object."));
  2539. addLegacyGeneral(behaviorContext->Method("unselect_objects", PyUnselectObjects, nullptr, "Unselects a list of objects."));
  2540. addLegacyGeneral(behaviorContext->Method("select_objects", PySelectObjects, nullptr, "Selects a list of objects."));
  2541. addLegacyGeneral(behaviorContext->Method("get_num_selected", PyGetNumSelectedObjects, nullptr, "Returns the number of selected objects."));
  2542. addLegacyGeneral(behaviorContext->Method("clear_selection", PyClearSelection, nullptr, "Clears selection."));
  2543. addLegacyGeneral(behaviorContext->Method("get_selection_center", PyGetSelectionCenter, nullptr, "Returns the center point of the selection group."));
  2544. addLegacyGeneral(behaviorContext->Method("get_selection_aabb", PyGetSelectionAABB, nullptr, "Returns the aabb of the selection group."));
  2545. addLegacyGeneral(behaviorContext->Method("hide_object", PyHideObject, nullptr, "Hides a specified object."));
  2546. addLegacyGeneral(behaviorContext->Method("is_object_hidden", PyIsObjectHidden, nullptr, "Checks if object is hidden and returns a bool value."));
  2547. addLegacyGeneral(behaviorContext->Method("unhide_object", PyUnhideObject, nullptr, "Unhides a specified object."));
  2548. addLegacyGeneral(behaviorContext->Method("hide_all_objects", PyHideAllObjects, nullptr, "Hides all objects."));
  2549. addLegacyGeneral(behaviorContext->Method("unhide_all_objects", PyUnHideAllObjects, nullptr, "Unhides all objects."));
  2550. addLegacyGeneral(behaviorContext->Method("freeze_object", PyFreezeObject, nullptr, "Freezes a specified object."));
  2551. addLegacyGeneral(behaviorContext->Method("is_object_frozen", PyIsObjectFrozen, nullptr, "Checks if object is frozen and returns a bool value."));
  2552. addLegacyGeneral(behaviorContext->Method("unfreeze_object", PyUnfreezeObject, nullptr, "Unfreezes a specified object."));
  2553. addLegacyGeneral(behaviorContext->Method("delete_object", PyDeleteObject, nullptr, "Deletes a specified object."));
  2554. addLegacyGeneral(behaviorContext->Method("delete_selected", PyDeleteSelected, nullptr, "Deletes selected object(s)."));
  2555. addLegacyGeneral(behaviorContext->Method("get_position", PyGetObjectPosition, nullptr, "Gets the position of an object."));
  2556. addLegacyGeneral(behaviorContext->Method("set_position", PySetObjectPosition, nullptr, "Sets the position of an object."));
  2557. addLegacyGeneral(behaviorContext->Method("get_rotation", PyGetObjectRotation, nullptr, "Gets the rotation of an object."));
  2558. addLegacyGeneral(behaviorContext->Method("set_rotation", PySetObjectRotation, nullptr, "Sets the rotation of an object."));
  2559. addLegacyGeneral(behaviorContext->Method("get_scale", PyGetObjectScale, nullptr, "Gets the scale of an object."));
  2560. addLegacyGeneral(behaviorContext->Method("set_scale", PySetObjectScale, nullptr, "Sets the scale of an object."));
  2561. addLegacyGeneral(behaviorContext->Method("rename_object", PyRenameObject, nullptr, "Renames object with oldObjectName to newObjectName."));
  2562. }
  2563. }
  2564. }