CryEdit.cpp 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520
  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. #ifdef WIN32
  10. AZ_PUSH_DISABLE_WARNING(4458, "-Wunknown-warning-option")
  11. #include <gdiplus.h>
  12. AZ_POP_DISABLE_WARNING
  13. #pragma comment (lib, "Gdiplus.lib")
  14. #include <WinUser.h> // needed for MessageBoxW in the assert handler
  15. #endif
  16. #include <array>
  17. #include <string>
  18. #include <iostream>
  19. #include <fstream>
  20. #include "CryEdit.h"
  21. // Qt
  22. #include <QCommandLineParser>
  23. #include <QSharedMemory>
  24. #include <QSystemSemaphore>
  25. #include <QDesktopServices>
  26. #include <QElapsedTimer>
  27. #include <QProcess>
  28. #include <QScopedValueRollback>
  29. #include <QClipboard>
  30. #include <QMenuBar>
  31. #include <QMessageBox>
  32. #include <QDialogButtonBox>
  33. #include <QUrlQuery>
  34. // AzCore
  35. #include <AzCore/Casting/numeric_cast.h>
  36. #include <AzCore/Component/ComponentApplicationBus.h>
  37. #include <AzCore/Component/ComponentApplicationLifecycle.h>
  38. #include <AzCore/Module/Environment.h>
  39. #include <AzCore/RTTI/BehaviorContext.h>
  40. #include <AzCore/std/smart_ptr/make_shared.h>
  41. #include <AzCore/Settings/SettingsRegistryMergeUtils.h>
  42. #include <AzCore/StringFunc/StringFunc.h>
  43. #include <AzCore/Utils/Utils.h>
  44. #include <AzCore/Console/IConsole.h>
  45. #include <AzCore/EBus/IEventScheduler.h>
  46. #include <AzCore/Name/Name.h>
  47. #include <AzCore/IO/SystemFile.h>
  48. // AzFramework
  49. #include <AzFramework/Components/CameraBus.h>
  50. #include <AzFramework/Process/ProcessWatcher.h>
  51. #include <AzFramework/ProjectManager/ProjectManager.h>
  52. #include <AzFramework/Spawnable/RootSpawnableInterface.h>
  53. // AzToolsFramework
  54. #include <AzToolsFramework/ActionManager/ActionManagerSystemComponent.h>
  55. #include <AzToolsFramework/Component/EditorComponentAPIBus.h>
  56. #include <AzToolsFramework/Component/EditorLevelComponentAPIBus.h>
  57. #include <AzToolsFramework/Editor/ActionManagerUtils.h>
  58. #include <AzToolsFramework/UI/UICore/ProgressShield.hxx>
  59. #include <AzToolsFramework/UI/UICore/WidgetHelpers.h>
  60. #include <AzToolsFramework/ViewportSelection/EditorTransformComponentSelectionRequestBus.h>
  61. #include <AzToolsFramework/API/EditorPythonConsoleBus.h>
  62. #include <AzToolsFramework/API/EditorPythonRunnerRequestsBus.h>
  63. #include <AzToolsFramework/API/ToolsApplicationAPI.h>
  64. #include <AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h>
  65. #include <AzToolsFramework/PythonTerminal/ScriptHelpDialog.h>
  66. #include <AzToolsFramework/Viewport/LocalViewBookmarkLoader.h>
  67. // AzQtComponents
  68. #include <AzQtComponents/Components/StyleManager.h>
  69. #include <AzQtComponents/Utilities/HandleDpiAwareness.h>
  70. #include <AzQtComponents/Components/WindowDecorationWrapper.h>
  71. #include <AzQtComponents/Utilities/QtPluginPaths.h>
  72. // CryCommon
  73. #include <CryCommon/ILevelSystem.h>
  74. // Editor
  75. #include "Settings.h"
  76. #include "GameExporter.h"
  77. #include "GameResourcesExporter.h"
  78. #include "MainWindow.h"
  79. #include "Core/QtEditorApplication.h"
  80. #include "NewLevelDialog.h"
  81. #include "LayoutConfigDialog.h"
  82. #include "ViewManager.h"
  83. #include "FileTypeUtils.h"
  84. #include "PluginManager.h"
  85. #include "IEditorImpl.h"
  86. #include "StartupLogoDialog.h"
  87. #include "DisplaySettings.h"
  88. #include "GameEngine.h"
  89. #include "StartupTraceHandler.h"
  90. #include "ToolsConfigPage.h"
  91. #include "Include/IObjectManager.h"
  92. #include "WaitProgress.h"
  93. #include "ToolBox.h"
  94. #include "EditorPreferencesDialog.h"
  95. #include "AnimationContext.h"
  96. #include "GotoPositionDlg.h"
  97. #include "ConsoleDialog.h"
  98. #include "Controls/ConsoleSCB.h"
  99. #include "ScopedVariableSetter.h"
  100. #include "Util/3DConnexionDriver.h"
  101. #include "Util/AutoDirectoryRestoreFileDialog.h"
  102. #include "Util/EditorAutoLevelLoadTest.h"
  103. #include <AzToolsFramework/PythonTerminal/ScriptHelpDialog.h>
  104. #include "LevelFileDialog.h"
  105. #include "LevelIndependentFileMan.h"
  106. #include "WelcomeScreen/WelcomeScreenDialog.h"
  107. #include "Controls/ReflectedPropertyControl/PropertyCtrl.h"
  108. #include "Controls/ReflectedPropertyControl/ReflectedVar.h"
  109. #include "EditorToolsApplication.h"
  110. #include <AzToolsFramework/Undo/UndoSystem.h>
  111. #if defined(AZ_PLATFORM_WINDOWS)
  112. #include <AzFramework/API/ApplicationAPI_Platform.h>
  113. #endif
  114. #if AZ_TRAIT_OS_PLATFORM_APPLE
  115. #include "WindowObserver_mac.h"
  116. #endif
  117. #include <AzCore/RTTI/BehaviorContext.h>
  118. #include <AzFramework/Render/Intersector.h>
  119. #include <AzCore/std/smart_ptr/make_shared.h>
  120. static const char O3DEEditorClassName[] = "O3DEEditorClass";
  121. static const char O3DEApplicationName[] = "O3DEApplication";
  122. static AZ::EnvironmentVariable<bool> inEditorBatchMode = nullptr;
  123. namespace Platform
  124. {
  125. bool OpenUri(const QUrl& uri);
  126. }
  127. RecentFileList::RecentFileList()
  128. {
  129. m_settings.beginGroup(QStringLiteral("Application"));
  130. m_settings.beginGroup(QStringLiteral("Recent File List"));
  131. ReadList();
  132. }
  133. void RecentFileList::Remove(int index)
  134. {
  135. m_arrNames.removeAt(index);
  136. }
  137. void RecentFileList::Add(const QString& f)
  138. {
  139. QString filename = QDir::toNativeSeparators(f);
  140. m_arrNames.removeAll(filename);
  141. m_arrNames.push_front(filename);
  142. while (m_arrNames.count() > Max)
  143. {
  144. m_arrNames.removeAt(Max);
  145. }
  146. }
  147. int RecentFileList::GetSize()
  148. {
  149. return m_arrNames.count();
  150. }
  151. void RecentFileList::GetDisplayName(QString& name, int index, const QString& curDir)
  152. {
  153. name = m_arrNames[index];
  154. const QDir cur(curDir);
  155. QDir fileDir(name); // actually pointing at file, first cdUp() gets us the parent dir
  156. while (fileDir.cdUp())
  157. {
  158. if (fileDir == cur)
  159. {
  160. name = cur.relativeFilePath(name);
  161. break;
  162. }
  163. }
  164. name = QDir::toNativeSeparators(name);
  165. }
  166. QString& RecentFileList::operator[](int index)
  167. {
  168. return m_arrNames[index];
  169. }
  170. void RecentFileList::ReadList()
  171. {
  172. m_arrNames.clear();
  173. for (int i = 1; i <= Max; ++i)
  174. {
  175. QString f = m_settings.value(QStringLiteral("File%1").arg(i)).toString();
  176. if (!f.isEmpty())
  177. {
  178. m_arrNames.push_back(f);
  179. }
  180. }
  181. }
  182. void RecentFileList::WriteList()
  183. {
  184. m_settings.remove(QString());
  185. int i = 1;
  186. for (auto f : m_arrNames)
  187. {
  188. m_settings.setValue(QStringLiteral("File%1").arg(i++), f);
  189. }
  190. }
  191. #define ERROR_LEN 256
  192. CCryDocManager::CCryDocManager()
  193. {
  194. }
  195. CCrySingleDocTemplate* CCryDocManager::SetDefaultTemplate(CCrySingleDocTemplate* pNew)
  196. {
  197. CCrySingleDocTemplate* pOld = m_pDefTemplate;
  198. m_pDefTemplate = pNew;
  199. m_templateList.clear();
  200. m_templateList.push_back(m_pDefTemplate);
  201. return pOld;
  202. }
  203. // Copied from MFC to get rid of the silly ugly unoverridable doc-type pick dialog
  204. void CCryDocManager::OnFileNew()
  205. {
  206. assert(m_pDefTemplate != nullptr);
  207. m_pDefTemplate->OpenDocumentFile(nullptr);
  208. // if returns NULL, the user has already been alerted
  209. }
  210. bool CCryDocManager::DoPromptFileName(QString& fileName, [[maybe_unused]] UINT nIDSTitle,
  211. [[maybe_unused]] DWORD lFlags, bool bOpenFileDialog, [[maybe_unused]] CDocTemplate* pTemplate)
  212. {
  213. CLevelFileDialog levelFileDialog(bOpenFileDialog);
  214. levelFileDialog.show();
  215. levelFileDialog.adjustSize();
  216. if (levelFileDialog.exec() == QDialog::Accepted)
  217. {
  218. fileName = levelFileDialog.GetFileName();
  219. return true;
  220. }
  221. return false;
  222. }
  223. CCryEditDoc* CCryDocManager::OpenDocumentFile(const char* filename, bool addToMostRecentFileList, COpenSameLevelOptions openSameLevelOptions)
  224. {
  225. assert(filename != nullptr);
  226. const bool reopenIfSame = openSameLevelOptions == COpenSameLevelOptions::ReopenLevelIfSame;
  227. // find the highest confidence
  228. auto pos = m_templateList.begin();
  229. CCrySingleDocTemplate::Confidence bestMatch = CCrySingleDocTemplate::noAttempt;
  230. CCrySingleDocTemplate* pBestTemplate = nullptr;
  231. CCryEditDoc* pOpenDocument = nullptr;
  232. if (filename[0] == '\"')
  233. {
  234. ++filename;
  235. }
  236. QString szPath = QString::fromUtf8(filename);
  237. if (szPath.endsWith('"'))
  238. {
  239. szPath.remove(szPath.length() - 1, 1);
  240. }
  241. while (pos != m_templateList.end())
  242. {
  243. auto pTemplate = *(pos++);
  244. CCrySingleDocTemplate::Confidence match;
  245. assert(pOpenDocument == nullptr);
  246. match = pTemplate->MatchDocType(szPath.toUtf8().data(), pOpenDocument);
  247. if (match > bestMatch)
  248. {
  249. bestMatch = match;
  250. pBestTemplate = pTemplate;
  251. }
  252. if (match == CCrySingleDocTemplate::yesAlreadyOpen)
  253. {
  254. break; // stop here
  255. }
  256. }
  257. if (!reopenIfSame && pOpenDocument != nullptr)
  258. {
  259. return pOpenDocument;
  260. }
  261. if (pBestTemplate == nullptr)
  262. {
  263. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Failed to open document."));
  264. return nullptr;
  265. }
  266. return pBestTemplate->OpenDocumentFile(szPath.toUtf8().data(), addToMostRecentFileList, false);
  267. }
  268. //////////////////////////////////////////////////////////////////////////////
  269. // CCryEditApp
  270. #undef ON_COMMAND
  271. #define ON_COMMAND(id, method) \
  272. MainWindow::instance()->GetActionManager()->RegisterActionHandler(id, this, &CCryEditApp::method);
  273. #undef ON_COMMAND_RANGE
  274. #define ON_COMMAND_RANGE(idStart, idEnd, method) \
  275. for (int i = idStart; i <= idEnd; ++i) \
  276. ON_COMMAND(i, method);
  277. AZ_CVAR_EXTERNED(bool, ed_previewGameInFullscreen_once);
  278. CCryEditApp* CCryEditApp::s_currentInstance = nullptr;
  279. /////////////////////////////////////////////////////////////////////////////
  280. // CCryEditApp construction
  281. CCryEditApp::CCryEditApp()
  282. {
  283. s_currentInstance = this;
  284. m_sPreviewFile[0] = 0;
  285. AzFramework::AssetSystemInfoBus::Handler::BusConnect();
  286. AzFramework::AssetSystemStatusBus::Handler::BusConnect();
  287. m_disableIdleProcessingCounter = 0;
  288. EditorIdleProcessingBus::Handler::BusConnect();
  289. }
  290. //////////////////////////////////////////////////////////////////////////
  291. CCryEditApp::~CCryEditApp()
  292. {
  293. EditorIdleProcessingBus::Handler::BusDisconnect();
  294. AzFramework::AssetSystemStatusBus::Handler::BusDisconnect();
  295. AzFramework::AssetSystemInfoBus::Handler::BusDisconnect();
  296. s_currentInstance = nullptr;
  297. }
  298. CCryEditApp* CCryEditApp::instance()
  299. {
  300. return s_currentInstance;
  301. }
  302. class CEditCommandLineInfo
  303. {
  304. public:
  305. bool m_bTest = false;
  306. bool m_bAutoLoadLevel = false;
  307. bool m_bExport = false;
  308. bool m_bExportTexture = false;
  309. bool m_bConsoleMode = false;
  310. bool m_bNullRenderer = false;
  311. bool m_bDeveloperMode = false;
  312. bool m_bRunPythonScript = false;
  313. bool m_bRunPythonTestScript = false;
  314. bool m_bShowVersionInfo = false;
  315. QString m_exportFile;
  316. QString m_strFileName;
  317. QString m_appRoot;
  318. QString m_logFile;
  319. QString m_pythonArgs;
  320. QString m_pythonTestCase;
  321. QString m_execFile;
  322. QString m_execLineCmd;
  323. bool m_bSkipWelcomeScreenDialog = false;
  324. bool m_bAutotestMode = false;
  325. struct CommandLineStringOption
  326. {
  327. QString name;
  328. QString description;
  329. QString valueName;
  330. };
  331. CEditCommandLineInfo()
  332. {
  333. bool dummy;
  334. QCommandLineParser parser;
  335. parser.addHelpOption();
  336. parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
  337. parser.setApplicationDescription(QObject::tr("O3DE Editor"));
  338. // nsDocumentRevisionDebugMode is an argument that the macOS system passed into an App bundle that is being debugged.
  339. // Need to include it here so that Qt argument parser does not error out.
  340. bool nsDocumentRevisionsDebugMode = false;
  341. const std::vector<std::pair<QString, bool&> > options = {
  342. { "export", m_bExport },
  343. { "exportTexture", m_bExportTexture },
  344. { "test", m_bTest },
  345. { "auto_level_load", m_bAutoLoadLevel },
  346. { "BatchMode", m_bConsoleMode },
  347. { "NullRenderer", m_bNullRenderer },
  348. { "devmode", m_bDeveloperMode },
  349. { "runpython", m_bRunPythonScript },
  350. { "runpythontest", m_bRunPythonTestScript },
  351. { "version", m_bShowVersionInfo },
  352. { "NSDocumentRevisionsDebugMode", nsDocumentRevisionsDebugMode},
  353. { "skipWelcomeScreenDialog", m_bSkipWelcomeScreenDialog},
  354. { "autotest_mode", m_bAutotestMode},
  355. { "regdumpall", dummy },
  356. { "attach-debugger", dummy }, // Attaches a debugger for the current application
  357. { "wait-for-debugger", dummy }, // Waits until a debugger is attached to the current application
  358. };
  359. QString dummyString;
  360. const std::vector<std::pair<CommandLineStringOption, QString&> > stringOptions = {
  361. {{"logfile", "File name of the log file to write out to.", "logfile"}, m_logFile},
  362. {{"runpythonargs", "Command-line argument string to pass to the python script if --runpython or --runpythontest was used.", "runpythonargs"}, m_pythonArgs},
  363. {{"pythontestcase", "Test case name of python test script if --runpythontest was used.", "pythontestcase"}, m_pythonTestCase},
  364. {{"exec", "cfg file to run on startup, used for systems like automation", "exec"}, m_execFile},
  365. {{"rhi", "Command-line argument to force which rhi to use", "rhi"}, dummyString },
  366. {{"rhi-device-validation", "Command-line argument to configure rhi validation", "rhi-device-validation"}, dummyString },
  367. {{"exec_line", "command to run on startup, used for systems like automation", "exec_line"}, m_execLineCmd},
  368. {{"regset", "Command-line argument to override settings registry values", "regset"}, dummyString},
  369. {{"regremove", "Deletes a value within the global settings registry at the JSON pointer path @key", "regremove"}, dummyString},
  370. {{"regdump", "Sets a value within the global settings registry at the JSON pointer path @key with value of @value", "regdump"}, dummyString},
  371. {{"project-path", "Supplies the path to the project that the Editor should use", "project-path"}, dummyString},
  372. {{"engine-path", "Supplies the path to the engine", "engine-path"}, dummyString},
  373. {{"project-cache-path", "Path to the project cache", "project-cache-path"}, dummyString},
  374. {{"project-user-path", "Path to the project user path", "project-user-path"}, dummyString},
  375. {{"project-log-path", "Path to the project log path", "project-log-path"}, dummyString}
  376. // add dummy entries here to prevent QCommandLineParser error-ing out on cmd line args that will be parsed later
  377. };
  378. parser.addPositionalArgument("file", QCoreApplication::translate("main", "file to open"));
  379. for (const auto& option : options)
  380. {
  381. parser.addOption(QCommandLineOption(option.first));
  382. }
  383. for (const auto& option : stringOptions)
  384. {
  385. parser.addOption(QCommandLineOption(option.first.name, option.first.description, option.first.valueName));
  386. }
  387. QStringList args = qApp->arguments();
  388. #ifdef Q_OS_WIN32
  389. for (QString& arg : args)
  390. {
  391. if (!arg.isEmpty() && arg[0] == '/')
  392. {
  393. arg[0] = '-'; // QCommandLineParser only supports - and -- prefixes
  394. }
  395. }
  396. #endif
  397. if (!parser.parse(args))
  398. {
  399. AZ_TracePrintf("QT CommandLine Parser", "QT command line parsing warned with message %s."
  400. " Has the QCommandLineParser had these options added to it", parser.errorText().toUtf8().constData());
  401. }
  402. // Get boolean options
  403. const int numOptions = static_cast<int>(options.size());
  404. for (int i = 0; i < numOptions; ++i)
  405. {
  406. options[i].second = parser.isSet(options[i].first);
  407. }
  408. // Get string options
  409. for (auto& option : stringOptions)
  410. {
  411. option.second = parser.value(option.first.valueName);
  412. }
  413. m_bExport = m_bExport || m_bExportTexture;
  414. const QStringList positionalArgs = parser.positionalArguments();
  415. if (!positionalArgs.isEmpty())
  416. {
  417. m_strFileName = positionalArgs.first();
  418. if (positionalArgs.first().at(0) != '[')
  419. {
  420. m_exportFile = positionalArgs.first();
  421. }
  422. }
  423. }
  424. };
  425. struct SharedData
  426. {
  427. bool raise = false;
  428. char text[_MAX_PATH];
  429. };
  430. /////////////////////////////////////////////////////////////////////////////
  431. // CTheApp::FirstInstance
  432. // FirstInstance checks for an existing instance of the application.
  433. // If one is found, it is activated.
  434. //
  435. // This function uses a technique similar to that described in KB
  436. // article Q141752 to locate the previous instance of the application. .
  437. bool CCryEditApp::FirstInstance(bool bForceNewInstance)
  438. {
  439. QSystemSemaphore sem(QString(O3DEApplicationName) + "_sem", 1);
  440. sem.acquire();
  441. {
  442. FixDanglingSharedMemory(O3DEEditorClassName);
  443. }
  444. sem.release();
  445. m_mutexApplication = new QSharedMemory(O3DEEditorClassName);
  446. if (!m_mutexApplication->create(sizeof(SharedData)) && !bForceNewInstance)
  447. {
  448. m_mutexApplication->attach();
  449. // another instance is already running - activate it
  450. sem.acquire();
  451. SharedData* data = reinterpret_cast<SharedData*>(m_mutexApplication->data());
  452. data->raise = true;
  453. if (m_bPreviewMode)
  454. {
  455. // IF in preview mode send this window copy data message to load new preview file.
  456. azstrcpy(data->text, MAX_PATH, m_sPreviewFile);
  457. }
  458. return false;
  459. }
  460. else
  461. {
  462. m_mutexApplication->attach();
  463. // this is the first instance
  464. sem.acquire();
  465. ::memset(m_mutexApplication->data(), 0, m_mutexApplication->size());
  466. sem.release();
  467. QTimer* t = new QTimer(this);
  468. connect(t, &QTimer::timeout, this, [this]() {
  469. QSystemSemaphore sem(QString(O3DEApplicationName) + "_sem", 1);
  470. sem.acquire();
  471. SharedData* data = reinterpret_cast<SharedData*>(m_mutexApplication->data());
  472. QString preview = QString::fromLatin1(data->text);
  473. if (data->raise)
  474. {
  475. QWidget* w = MainWindow::instance();
  476. w->setWindowState((w->windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
  477. w->raise();
  478. w->activateWindow();
  479. data->raise = false;
  480. }
  481. if (!preview.isEmpty())
  482. {
  483. // Load this file
  484. LoadFile(preview);
  485. data->text[0] = 0;
  486. }
  487. sem.release();
  488. });
  489. t->start(1000);
  490. return true;
  491. }
  492. return true;
  493. }
  494. //////////////////////////////////////////////////////////////////////////
  495. void CCryEditApp::OnFileSave()
  496. {
  497. if (m_savingLevel)
  498. {
  499. return;
  500. }
  501. const QScopedValueRollback<bool> rollback(m_savingLevel, true);
  502. auto* prefabIntegrationInterface = AZ::Interface<AzToolsFramework::Prefab::PrefabIntegrationInterface>::Get();
  503. AZ_Assert(prefabIntegrationInterface != nullptr, "PrefabIntegrationInterface is not found.");
  504. prefabIntegrationInterface->SaveCurrentPrefab();
  505. // when attempting to save, update the last known location using the active camera transform
  506. AzToolsFramework::StoreViewBookmarkLastKnownLocationFromActiveCamera();
  507. }
  508. //////////////////////////////////////////////////////////////////////////
  509. void CCryEditApp::OnUpdateDocumentReady(QAction* action)
  510. {
  511. action->setEnabled(GetIEditor()
  512. && GetIEditor()->GetDocument()
  513. && GetIEditor()->GetDocument()->IsDocumentReady()
  514. && !m_bIsExportingLegacyData
  515. && !m_creatingNewLevel
  516. && !m_openingLevel
  517. && !m_savingLevel);
  518. }
  519. //////////////////////////////////////////////////////////////////////////
  520. void CCryEditApp::OnUpdateFileOpen(QAction* action)
  521. {
  522. action->setEnabled(!m_bIsExportingLegacyData && !m_creatingNewLevel && !m_openingLevel && !m_savingLevel);
  523. }
  524. bool CCryEditApp::ShowEnableDisableGemDialog(const QString& title, const QString& message)
  525. {
  526. const QString informativeMessage = QObject::tr("Please follow the instructions <a href=\"https://www.o3de.org/docs/user-guide/project-config/add-remove-gems/\">here</a>, after which the Editor will be re-launched automatically.");
  527. QMessageBox box(AzToolsFramework::GetActiveWindow());
  528. box.addButton(QObject::tr("Continue"), QMessageBox::AcceptRole);
  529. box.addButton(QObject::tr("Back"), QMessageBox::RejectRole);
  530. box.setWindowTitle(title);
  531. box.setText(message);
  532. box.setInformativeText(informativeMessage);
  533. box.setWindowFlags(box.windowFlags() & ~Qt::WindowContextHelpButtonHint);
  534. if (box.exec() == QMessageBox::AcceptRole)
  535. {
  536. // Called from a modal dialog with the main window as its parent. Best not to close the main window while the dialog is still active.
  537. QTimer::singleShot(0, MainWindow::instance(), &MainWindow::close);
  538. return true;
  539. }
  540. return false;
  541. }
  542. QString CCryEditApp::ShowWelcomeDialog()
  543. {
  544. WelcomeScreenDialog wsDlg(MainWindow::instance());
  545. wsDlg.SetRecentFileList(GetRecentFileList());
  546. wsDlg.exec();
  547. QString levelName = wsDlg.GetLevelPath();
  548. return levelName;
  549. }
  550. //////////////////////////////////////////////////////////////////////////
  551. // Needed to work with custom memory manager.
  552. //////////////////////////////////////////////////////////////////////////
  553. CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(const char* lpszPathName, bool bMakeVisible /*= true*/)
  554. {
  555. return OpenDocumentFile(lpszPathName, true, bMakeVisible);
  556. }
  557. CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(const char* lpszPathName, bool addToMostRecentFileList, [[maybe_unused]] bool bMakeVisible)
  558. {
  559. CCryEditDoc* pCurDoc = GetIEditor()->GetDocument();
  560. if (pCurDoc)
  561. {
  562. if (!pCurDoc->SaveModified())
  563. {
  564. return nullptr;
  565. }
  566. }
  567. if (!pCurDoc)
  568. {
  569. pCurDoc = qobject_cast<CCryEditDoc*>(m_documentClass->newInstance());
  570. if (pCurDoc == nullptr)
  571. return nullptr;
  572. pCurDoc->setParent(this);
  573. }
  574. pCurDoc->SetModifiedFlag(false);
  575. if (lpszPathName == nullptr)
  576. {
  577. pCurDoc->SetTitle(tr("Untitled"));
  578. pCurDoc->OnNewDocument();
  579. }
  580. else
  581. {
  582. pCurDoc->OnOpenDocument(lpszPathName);
  583. pCurDoc->SetPathName(lpszPathName);
  584. if (addToMostRecentFileList)
  585. {
  586. CCryEditApp::instance()->AddToRecentFileList(lpszPathName);
  587. }
  588. }
  589. return pCurDoc;
  590. }
  591. CCrySingleDocTemplate::Confidence CCrySingleDocTemplate::MatchDocType(const char* lpszPathName, CCryEditDoc*& rpDocMatch)
  592. {
  593. assert(lpszPathName != nullptr);
  594. rpDocMatch = nullptr;
  595. // go through all documents
  596. CCryEditDoc* pDoc = GetIEditor()->GetDocument();
  597. if (pDoc)
  598. {
  599. QString prevPathName = pDoc->GetLevelPathName();
  600. // all we need to know here is whether it is the same file as before.
  601. if (!prevPathName.isEmpty())
  602. {
  603. // QFileInfo is guaranteed to return true iff the two paths refer to the same path.
  604. if (QFileInfo(prevPathName) == QFileInfo(QString::fromUtf8(lpszPathName)))
  605. {
  606. // already open
  607. rpDocMatch = pDoc;
  608. return yesAlreadyOpen;
  609. }
  610. }
  611. }
  612. // see if it matches our default suffix
  613. const QString strFilterExt = EditorUtils::LevelFile::GetDefaultFileExtension();
  614. const QString strOldFilterExt = EditorUtils::LevelFile::GetOldCryFileExtension();
  615. // see if extension matches
  616. assert(strFilterExt[0] == '.');
  617. QString strDot = "." + Path::GetExt(lpszPathName);
  618. if (!strDot.isEmpty())
  619. {
  620. if(strDot == strFilterExt || strDot == strOldFilterExt)
  621. {
  622. return yesAttemptNative; // extension matches, looks like ours
  623. }
  624. }
  625. // otherwise we will guess it may work
  626. return yesAttemptForeign;
  627. }
  628. /////////////////////////////////////////////////////////////////////////////
  629. namespace
  630. {
  631. AZStd::mutex g_splashScreenStateLock;
  632. enum ESplashScreenState
  633. {
  634. eSplashScreenState_Init, eSplashScreenState_Started, eSplashScreenState_Destroy
  635. };
  636. ESplashScreenState g_splashScreenState = eSplashScreenState_Init;
  637. IInitializeUIInfo* g_pInitializeUIInfo = nullptr;
  638. QWidget* g_splashScreen = nullptr;
  639. }
  640. QString FormatVersion([[maybe_unused]] const SFileVersion& v)
  641. {
  642. if (QObject::tr("%1").arg(O3DE_BUILD_VERSION) == "0")
  643. {
  644. return QObject::tr("Development Build");
  645. }
  646. return QObject::tr("Version %1").arg(O3DE_BUILD_VERSION);
  647. }
  648. QString FormatRichTextCopyrightNotice()
  649. {
  650. // copyright symbol is HTML Entity = &#xA9;
  651. QString copyrightHtmlSymbol = "&#xA9;";
  652. QString copyrightString = QObject::tr("Copyright %1 Contributors to the Open 3D Engine Project");
  653. return copyrightString.arg(copyrightHtmlSymbol);
  654. }
  655. void CCryEditApp::AssetSystemWaiting()
  656. {
  657. QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
  658. }
  659. /////////////////////////////////////////////////////////////////////////////
  660. void CCryEditApp::ShowSplashScreen(CCryEditApp* app)
  661. {
  662. g_splashScreenStateLock.lock();
  663. CStartupLogoDialog* splashScreen = new CStartupLogoDialog(CStartupLogoDialog::Loading, FormatVersion(app->m_pEditor->GetFileVersion()), FormatRichTextCopyrightNotice());
  664. g_pInitializeUIInfo = splashScreen;
  665. g_splashScreen = splashScreen;
  666. g_splashScreenState = eSplashScreenState_Started;
  667. g_splashScreenStateLock.unlock();
  668. splashScreen->show();
  669. QObject::connect(splashScreen, &QObject::destroyed, splashScreen, [=]
  670. {
  671. AZStd::scoped_lock lock(g_splashScreenStateLock);
  672. g_pInitializeUIInfo = nullptr;
  673. g_splashScreen = nullptr;
  674. });
  675. }
  676. /////////////////////////////////////////////////////////////////////////////
  677. void CCryEditApp::CreateSplashScreen()
  678. {
  679. if (!m_bConsoleMode && !IsInAutotestMode())
  680. {
  681. // Create startup output splash
  682. ShowSplashScreen(this);
  683. GetIEditor()->Notify(eNotify_OnSplashScreenCreated);
  684. }
  685. else
  686. {
  687. // Create console
  688. m_pConsoleDialog = new CConsoleDialog();
  689. m_pConsoleDialog->show();
  690. g_pInitializeUIInfo = m_pConsoleDialog;
  691. }
  692. }
  693. /////////////////////////////////////////////////////////////////////////////
  694. void CCryEditApp::CloseSplashScreen()
  695. {
  696. if (CStartupLogoDialog::instance())
  697. {
  698. delete CStartupLogoDialog::instance();
  699. g_splashScreenStateLock.lock();
  700. g_splashScreenState = eSplashScreenState_Destroy;
  701. g_splashScreenStateLock.unlock();
  702. }
  703. GetIEditor()->Notify(eNotify_OnSplashScreenDestroyed);
  704. }
  705. /////////////////////////////////////////////////////////////////////////////
  706. void CCryEditApp::OutputStartupMessage(QString str)
  707. {
  708. g_splashScreenStateLock.lock();
  709. if (g_pInitializeUIInfo)
  710. {
  711. g_pInitializeUIInfo->SetInfoText(str.toUtf8().data());
  712. }
  713. g_splashScreenStateLock.unlock();
  714. }
  715. //////////////////////////////////////////////////////////////////////////
  716. void CCryEditApp::InitFromCommandLine(CEditCommandLineInfo& cmdInfo)
  717. {
  718. m_bConsoleMode |= cmdInfo.m_bConsoleMode;
  719. inEditorBatchMode = AZ::Environment::CreateVariable<bool>("InEditorBatchMode", m_bConsoleMode);
  720. m_bTestMode |= cmdInfo.m_bTest;
  721. m_bSkipWelcomeScreenDialog = cmdInfo.m_bSkipWelcomeScreenDialog || !cmdInfo.m_execFile.isEmpty() || !cmdInfo.m_execLineCmd.isEmpty() || cmdInfo.m_bAutotestMode;
  722. m_bExportMode = cmdInfo.m_bExport;
  723. m_bRunPythonTestScript = cmdInfo.m_bRunPythonTestScript;
  724. m_bRunPythonScript = cmdInfo.m_bRunPythonScript || cmdInfo.m_bRunPythonTestScript;
  725. m_execFile = cmdInfo.m_execFile;
  726. m_execLineCmd = cmdInfo.m_execLineCmd;
  727. m_bAutotestMode = cmdInfo.m_bAutotestMode || cmdInfo.m_bConsoleMode;
  728. if (m_bExportMode)
  729. {
  730. m_exportFile = cmdInfo.m_exportFile;
  731. }
  732. // Do we have a passed filename ?
  733. if (!cmdInfo.m_strFileName.isEmpty())
  734. {
  735. if (!m_bRunPythonScript && IsPreviewableFileType(cmdInfo.m_strFileName.toUtf8().constData()))
  736. {
  737. m_bPreviewMode = true;
  738. azstrncpy(m_sPreviewFile, _MAX_PATH, cmdInfo.m_strFileName.toUtf8().constData(), _MAX_PATH);
  739. }
  740. }
  741. if (cmdInfo.m_bAutoLoadLevel)
  742. {
  743. m_bLevelLoadTestMode = true;
  744. gEnv->bNoAssertDialog = true;
  745. CEditorAutoLevelLoadTest::Instance();
  746. }
  747. }
  748. /////////////////////////////////////////////////////////////////////////////
  749. AZ::Outcome<void, AZStd::string> CCryEditApp::InitGameSystem(HWND hwndForInputSystem)
  750. {
  751. CGameEngine* pGameEngine = new CGameEngine;
  752. AZ::Outcome<void, AZStd::string> initOutcome = pGameEngine->Init(m_bPreviewMode, m_bTestMode, qApp->arguments().join(" ").toUtf8().data(), g_pInitializeUIInfo, hwndForInputSystem);
  753. if (!initOutcome.IsSuccess())
  754. {
  755. return initOutcome;
  756. }
  757. AZ_Assert(pGameEngine, "Game engine initialization failed, but initOutcome returned success.");
  758. m_pEditor->SetGameEngine(pGameEngine);
  759. // needs to be called after CrySystem has been loaded.
  760. gSettings.LoadDefaultGamePaths();
  761. return AZ::Success();
  762. }
  763. /////////////////////////////////////////////////////////////////////////////
  764. bool CCryEditApp::CheckIfAlreadyRunning()
  765. {
  766. bool bForceNewInstance = false;
  767. if (!m_bPreviewMode)
  768. {
  769. FixDanglingSharedMemory(O3DEApplicationName);
  770. m_mutexApplication = new QSharedMemory(O3DEApplicationName);
  771. if (!m_mutexApplication->create(16))
  772. {
  773. // Don't prompt the user in non-interactive export mode. Instead, default to allowing multiple instances to
  774. // run simultaneously, so that multiple level exports can be run in parallel on the same machine.
  775. // NOTE: If you choose to do this, be sure to export *different* levels, since nothing prevents multiple runs
  776. // from trying to write to the same level at the same time.
  777. // If we're running interactively, let's ask and make sure the user actually intended to do this.
  778. if (!m_bExportMode && QMessageBox::question(AzToolsFramework::GetActiveWindow(), QObject::tr("Too many apps"), QObject::tr("There is already an Open 3D Engine application running\nDo you want to start another one?")) != QMessageBox::Yes)
  779. {
  780. return false;
  781. }
  782. bForceNewInstance = true;
  783. }
  784. }
  785. if (!FirstInstance(bForceNewInstance))
  786. {
  787. return false;
  788. }
  789. return true;
  790. }
  791. /////////////////////////////////////////////////////////////////////////////
  792. bool CCryEditApp::InitGame()
  793. {
  794. if (!m_bPreviewMode)
  795. {
  796. AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath();
  797. Log((QString("project_path = %1").arg(!projectPath.empty() ? projectPath.c_str() : "<not set>")).toUtf8().data());
  798. ICVar* pVar = gEnv->pConsole->GetCVar("sys_localization_folder");
  799. const char* sLocalizationFolder = pVar ? pVar->GetString() : nullptr;
  800. Log((QString("sys_localization_folder = ") + (sLocalizationFolder && sLocalizationFolder[0] ? sLocalizationFolder : "<not set>")).toUtf8().data());
  801. OutputStartupMessage("Starting Game...");
  802. if (!GetIEditor()->GetGameEngine()->InitGame(nullptr))
  803. {
  804. return false;
  805. }
  806. }
  807. //////////////////////////////////////////////////////////////////////////
  808. // Apply settings post engine initialization.
  809. GetIEditor()->GetDisplaySettings()->PostInitApply();
  810. gSettings.PostInitApply();
  811. return true;
  812. }
  813. /////////////////////////////////////////////////////////////////////////////
  814. void CCryEditApp::InitPlugins()
  815. {
  816. OutputStartupMessage("Loading Plugins...");
  817. // Load the plugins
  818. {
  819. GetIEditor()->LoadPlugins();
  820. #if defined(AZ_PLATFORM_WINDOWS)
  821. C3DConnexionDriver* p3DConnexionDriver = new C3DConnexionDriver;
  822. GetIEditor()->GetPluginManager()->RegisterPlugin(0, p3DConnexionDriver);
  823. #endif
  824. }
  825. }
  826. ////////////////////////////////////////////////////////////////////////////
  827. // Be careful when calling this function: it should be called after
  828. // everything else has finished initializing, otherwise, certain things
  829. // aren't set up yet. If in doubt, wrap it in a QTimer::singleShot(0ms);
  830. void CCryEditApp::InitLevel(const CEditCommandLineInfo& cmdInfo)
  831. {
  832. const char* defaultExtension = EditorUtils::LevelFile::GetDefaultFileExtension();
  833. const char* oldExtension = EditorUtils::LevelFile::GetOldCryFileExtension();
  834. if (m_bPreviewMode)
  835. {
  836. // Load geometry object.
  837. if (!cmdInfo.m_strFileName.isEmpty())
  838. {
  839. LoadFile(cmdInfo.m_strFileName);
  840. }
  841. }
  842. else if (m_bExportMode && !m_exportFile.isEmpty())
  843. {
  844. GetIEditor()->SetModifiedFlag(false);
  845. GetIEditor()->SetModifiedModule(eModifiedNothing);
  846. auto pDocument = OpenDocumentFile(m_exportFile.toUtf8().constData());
  847. if (pDocument)
  848. {
  849. GetIEditor()->SetModifiedFlag(false);
  850. GetIEditor()->SetModifiedModule(eModifiedNothing);
  851. ExportLevel(cmdInfo.m_bExport, cmdInfo.m_bExportTexture, true);
  852. // Terminate process.
  853. CLogFile::WriteLine("Editor: Terminate Process after export");
  854. }
  855. // the call to quit() must be posted to the event queue because the app is currently not yet running.
  856. // if we were to call quit() right now directly, the app would ignore it.
  857. QTimer::singleShot(0, QCoreApplication::instance(), &QCoreApplication::quit);
  858. return;
  859. }
  860. else if ((cmdInfo.m_strFileName.endsWith(defaultExtension, Qt::CaseInsensitive))
  861. || (cmdInfo.m_strFileName.endsWith(oldExtension, Qt::CaseInsensitive)))
  862. {
  863. auto pDocument = OpenDocumentFile(cmdInfo.m_strFileName.toUtf8().constData());
  864. if (pDocument)
  865. {
  866. GetIEditor()->SetModifiedFlag(false);
  867. GetIEditor()->SetModifiedModule(eModifiedNothing);
  868. }
  869. }
  870. else
  871. {
  872. //////////////////////////////////////////////////////////////////////////
  873. //It can happen that if you are switching between projects and you have auto load set that
  874. //you could inadvertently load the wrong project and not know it, you would think you are editing
  875. //one level when in fact you are editing the old one. This can happen if both projects have the same
  876. //relative path... which is often the case when branching.
  877. // Ex. D:\cryengine\dev\ gets branched to D:\cryengine\branch\dev
  878. // Now you have gamesdk in both roots and therefore GameSDK\Levels\Singleplayer\Forest in both
  879. // If you execute the branch the m_pRecentFileList will be an absolute path to the old gamesdk,
  880. // then if auto load is set simply takes the old level and loads it in the new branch...
  881. //I would question ever trying to load a level not in our gamesdk, what happens when there are things that
  882. //an not exist in the level when built in a different gamesdk.. does it erase them, most likely, then you
  883. //just screwed up the level for everyone in the other gamesdk...
  884. //So if we are auto loading a level outside our current gamesdk we should act as though the flag
  885. //was unset and pop the dialog which should be in the correct location. This is not fool proof, but at
  886. //least this its a compromise that doesn't automatically do something you probably shouldn't.
  887. bool autoloadLastLevel = gSettings.bAutoloadLastLevelAtStartup;
  888. if (autoloadLastLevel
  889. && GetRecentFileList()
  890. && GetRecentFileList()->GetSize())
  891. {
  892. QString gamePath = Path::GetEditingGameDataFolder().c_str();
  893. Path::ConvertSlashToBackSlash(gamePath);
  894. gamePath = Path::ToUnixPath(gamePath.toLower());
  895. gamePath = Path::AddSlash(gamePath);
  896. QString fullPath = GetRecentFileList()->m_arrNames[0];
  897. Path::ConvertSlashToBackSlash(fullPath);
  898. fullPath = Path::ToUnixPath(fullPath.toLower());
  899. fullPath = Path::AddSlash(fullPath);
  900. if (fullPath.indexOf(gamePath, 0) != 0)
  901. {
  902. autoloadLastLevel = false;
  903. }
  904. }
  905. //////////////////////////////////////////////////////////////////////////
  906. QString levelName;
  907. bool isLevelNameValid = false;
  908. bool doLevelNeedLoading = true;
  909. const bool runningPythonScript = cmdInfo.m_bRunPythonScript || cmdInfo.m_bRunPythonTestScript;
  910. AZ::EBusLogicalResult<bool, AZStd::logical_or<bool> > skipStartupUIProcess(false);
  911. AzToolsFramework::EditorEvents::Bus::BroadcastResult(
  912. skipStartupUIProcess, &AzToolsFramework::EditorEvents::Bus::Events::SkipEditorStartupUI);
  913. if (!skipStartupUIProcess.value)
  914. {
  915. do
  916. {
  917. isLevelNameValid = false;
  918. doLevelNeedLoading = true;
  919. if (gSettings.bShowDashboardAtStartup
  920. && !runningPythonScript
  921. && !m_bConsoleMode
  922. && !m_bSkipWelcomeScreenDialog
  923. && !m_bPreviewMode
  924. && !autoloadLastLevel)
  925. {
  926. levelName = ShowWelcomeDialog();
  927. }
  928. else if (autoloadLastLevel
  929. && GetRecentFileList()
  930. && GetRecentFileList()->GetSize())
  931. {
  932. levelName = GetRecentFileList()->m_arrNames[0];
  933. }
  934. if (levelName.isEmpty())
  935. {
  936. break;
  937. }
  938. if (levelName == "new")
  939. {
  940. //implies that the user has clicked the create new level option
  941. bool wasCreateLevelOperationCancelled = false;
  942. bool isNewLevelCreationSuccess = false;
  943. // This will show the new level dialog until a valid input has been entered by the user or until the user click cancel
  944. while (!isNewLevelCreationSuccess && !wasCreateLevelOperationCancelled)
  945. {
  946. isNewLevelCreationSuccess = CreateLevel(wasCreateLevelOperationCancelled);
  947. if (isNewLevelCreationSuccess == true)
  948. {
  949. doLevelNeedLoading = false;
  950. isLevelNameValid = true;
  951. }
  952. }
  953. ;
  954. }
  955. else
  956. {
  957. //implies that the user wants to open an existing level
  958. doLevelNeedLoading = true;
  959. isLevelNameValid = true;
  960. }
  961. } while (!isLevelNameValid);// if we reach here and levelName is not valid ,it implies that the user has clicked cancel on the create new level dialog
  962. // load level
  963. if (doLevelNeedLoading && !levelName.isEmpty())
  964. {
  965. if (!CFileUtil::Exists(levelName, false))
  966. {
  967. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QObject::tr("Missing level"), QObject::tr("Failed to auto-load last opened level. Level file does not exist:\n\n%1").arg(levelName));
  968. return;
  969. }
  970. QString str;
  971. str = tr("Loading level %1 ...").arg(levelName);
  972. OutputStartupMessage(str);
  973. OpenDocumentFile(levelName.toUtf8().data());
  974. }
  975. }
  976. }
  977. }
  978. /////////////////////////////////////////////////////////////////////////////
  979. bool CCryEditApp::InitConsole()
  980. {
  981. // Execute command from cmdline -exec_line if applicable
  982. if (!m_execLineCmd.isEmpty())
  983. {
  984. gEnv->pConsole->ExecuteString(QString("%1").arg(m_execLineCmd).toLocal8Bit());
  985. }
  986. // Execute cfg from cmdline -exec if applicable
  987. if (!m_execFile.isEmpty())
  988. {
  989. gEnv->pConsole->ExecuteString(QString("exec %1").arg(m_execFile).toLocal8Bit());
  990. }
  991. // Execute special configs.
  992. gEnv->pConsole->ExecuteString("exec editor_autoexec.cfg");
  993. gEnv->pConsole->ExecuteString("exec editor.cfg");
  994. gEnv->pConsole->ExecuteString("exec user.cfg");
  995. GetISystem()->ExecuteCommandLine();
  996. return true;
  997. }
  998. /////////////////////////////////////////////////////////////////////////////
  999. void CCryEditApp::CompileCriticalAssets() const
  1000. {
  1001. // regardless of what is set in the bootstrap wait for AP to be ready
  1002. // wait a maximum of 100 milliseconds and pump the system event loop until empty
  1003. struct AssetsInQueueNotification
  1004. : public AzFramework::AssetSystemInfoBus::Handler
  1005. {
  1006. void CountOfAssetsInQueue(const int& count) override
  1007. {
  1008. CCryEditApp::OutputStartupMessage(QString("Asset Processor working... %1 jobs remaining.").arg(count));
  1009. }
  1010. };
  1011. AssetsInQueueNotification assetsInQueueNotifcation;
  1012. assetsInQueueNotifcation.BusConnect();
  1013. bool ready{};
  1014. while (!ready)
  1015. {
  1016. AzFramework::AssetSystemRequestBus::BroadcastResult(ready, &AzFramework::AssetSystemRequestBus::Events::WaitUntilAssetProcessorReady, AZStd::chrono::milliseconds(100));
  1017. if (!ready)
  1018. {
  1019. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::PumpSystemEventLoopUntilEmpty);
  1020. }
  1021. }
  1022. assetsInQueueNotifcation.BusDisconnect();
  1023. AZ_TracePrintf("Editor", "CriticalAssetsCompiled\n");
  1024. // Signal the "CriticalAssetsCompiled" lifecycle event
  1025. // Also reload the "assetcatalog.xml" if it exists
  1026. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  1027. {
  1028. // Reload the assetcatalog.xml at this point again
  1029. // Start Monitoring Asset changes over the network and load the AssetCatalog
  1030. auto LoadCatalog = [settingsRegistry](AZ::Data::AssetCatalogRequests* assetCatalogRequests)
  1031. {
  1032. if (AZ::IO::FixedMaxPath assetCatalogPath;
  1033. settingsRegistry->Get(assetCatalogPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_CacheRootFolder))
  1034. {
  1035. assetCatalogPath /= "assetcatalog.xml";
  1036. assetCatalogRequests->LoadCatalog(assetCatalogPath.c_str());
  1037. }
  1038. };
  1039. CCryEditApp::OutputStartupMessage(QString("Loading Asset Catalog..."));
  1040. AZ::Data::AssetCatalogRequestBus::Broadcast(AZStd::move(LoadCatalog));
  1041. // Only signal the event *after* the asset catalog has been loaded.
  1042. AZ::ComponentApplicationLifecycle::SignalEvent(*settingsRegistry, "CriticalAssetsCompiled", R"({})");
  1043. }
  1044. CCryEditApp::OutputStartupMessage(QString("Asset Processor is now ready."));
  1045. }
  1046. bool CCryEditApp::ConnectToAssetProcessor() const
  1047. {
  1048. bool connectedToAssetProcessor = false;
  1049. // When the AssetProcessor is already launched it should take less than a second to perform a connection
  1050. // but when the AssetProcessor needs to be launch it could take up to 15 seconds to have the AssetProcessor initialize
  1051. // and able to negotiate a connection when running a debug build
  1052. // and to negotiate a connection
  1053. // Setting the connectTimeout to 3 seconds if not set within the settings registry
  1054. AZStd::chrono::seconds connectTimeout(3);
  1055. // Initialize the launchAssetProcessorTimeout to 15 seconds by default and check the settings registry for an override
  1056. AZStd::chrono::seconds launchAssetProcessorTimeout(15);
  1057. AZ::SettingsRegistryInterface* settingsRegistry = AZ::SettingsRegistry::Get();
  1058. if (settingsRegistry)
  1059. {
  1060. AZ::s64 timeoutValue{};
  1061. if (AZ::SettingsRegistryMergeUtils::PlatformGet(*settingsRegistry, timeoutValue,
  1062. AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey, "connect_ap_timeout"))
  1063. {
  1064. connectTimeout = AZStd::chrono::seconds(timeoutValue);
  1065. }
  1066. // Reset timeout integer
  1067. timeoutValue = {};
  1068. if (AZ::SettingsRegistryMergeUtils::PlatformGet(*settingsRegistry, timeoutValue,
  1069. AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey, "launch_ap_timeout"))
  1070. {
  1071. launchAssetProcessorTimeout = AZStd::chrono::seconds(timeoutValue);
  1072. }
  1073. }
  1074. CCryEditApp::OutputStartupMessage(QString("Connecting to Asset Processor... "));
  1075. AzFramework::AssetSystem::ConnectionSettings connectionSettings;
  1076. AzFramework::AssetSystem::ReadConnectionSettingsFromSettingsRegistry(connectionSettings);
  1077. connectionSettings.m_launchAssetProcessorOnFailedConnection = true;
  1078. connectionSettings.m_connectionDirection = AzFramework::AssetSystem::ConnectionSettings::ConnectionDirection::ConnectToAssetProcessor;
  1079. connectionSettings.m_connectionIdentifier = AzFramework::AssetSystem::ConnectionIdentifiers::Editor;
  1080. connectionSettings.m_loggingCallback = [](AZStd::string_view logData)
  1081. {
  1082. CCryEditApp::OutputStartupMessage(QString::fromUtf8(logData.data(), aznumeric_cast<int>(logData.size())));
  1083. };
  1084. AzFramework::AssetSystemRequestBus::BroadcastResult(connectedToAssetProcessor, &AzFramework::AssetSystemRequestBus::Events::EstablishAssetProcessorConnection, connectionSettings);
  1085. if (connectedToAssetProcessor)
  1086. {
  1087. AZ_TracePrintf("Editor", "Connected to Asset Processor\n");
  1088. CCryEditApp::OutputStartupMessage(QString("Connected to Asset Processor"));
  1089. CompileCriticalAssets();
  1090. return true;
  1091. }
  1092. AZ_TracePrintf("Editor", "Failed to connect to Asset Processor\n");
  1093. CCryEditApp::OutputStartupMessage(QString("Failed to connect to Asset Processor"));
  1094. return false;
  1095. }
  1096. //! This handles the normal logging of Python output in the Editor by outputting
  1097. //! the data to both the Editor Console and the Editor.log file
  1098. struct CCryEditApp::PythonOutputHandler
  1099. : public AzToolsFramework::EditorPythonConsoleNotificationBus::Handler
  1100. {
  1101. PythonOutputHandler()
  1102. {
  1103. AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusConnect();
  1104. }
  1105. ~PythonOutputHandler() override
  1106. {
  1107. AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect();
  1108. }
  1109. int GetOrder() override
  1110. {
  1111. return 0;
  1112. }
  1113. void OnTraceMessage([[maybe_unused]] AZStd::string_view message) override
  1114. {
  1115. AZ_TracePrintf("python_test", "%.*s", static_cast<int>(message.size()), message.data());
  1116. }
  1117. void OnErrorMessage([[maybe_unused]] AZStd::string_view message) override
  1118. {
  1119. AZ_Error("python_test", false, "%.*s", static_cast<int>(message.size()), message.data());
  1120. }
  1121. void OnExceptionMessage([[maybe_unused]] AZStd::string_view message) override
  1122. {
  1123. AZ_Error("python_test", false, "EXCEPTION: %.*s", static_cast<int>(message.size()), message.data());
  1124. }
  1125. };
  1126. //! Outputs Python test script print() to stdout
  1127. //! If an exception happens in a Python test script, the process terminates
  1128. struct PythonTestOutputHandler final
  1129. : public CCryEditApp::PythonOutputHandler
  1130. {
  1131. PythonTestOutputHandler() = default;
  1132. ~PythonTestOutputHandler() override = default;
  1133. void OnTraceMessage(AZStd::string_view message) override
  1134. {
  1135. PythonOutputHandler::OnTraceMessage(message);
  1136. printf("%.*s\n", static_cast<int>(message.size()), message.data());
  1137. }
  1138. void OnErrorMessage(AZStd::string_view message) override
  1139. {
  1140. PythonOutputHandler::OnErrorMessage(message);
  1141. printf("ERROR: %.*s\n", static_cast<int>(message.size()), message.data());
  1142. }
  1143. void OnExceptionMessage(AZStd::string_view message) override
  1144. {
  1145. PythonOutputHandler::OnExceptionMessage(message);
  1146. printf("EXCEPTION: %.*s\n", static_cast<int>(message.size()), message.data());
  1147. }
  1148. };
  1149. void CCryEditApp::RunInitPythonScript(CEditCommandLineInfo& cmdInfo)
  1150. {
  1151. if (cmdInfo.m_bRunPythonTestScript)
  1152. {
  1153. m_pythonOutputHandler = AZStd::make_shared<PythonTestOutputHandler>();
  1154. }
  1155. else
  1156. {
  1157. m_pythonOutputHandler = AZStd::make_shared<PythonOutputHandler>();
  1158. }
  1159. using namespace AzToolsFramework;
  1160. if (cmdInfo.m_bRunPythonScript || cmdInfo.m_bRunPythonTestScript)
  1161. {
  1162. // Separates the compound string of semicolon separated values into a vector of values
  1163. const auto extractSeparatedValues = [](const AZStd::string& compoundValues)
  1164. {
  1165. AZStd::vector<AZStd::string_view> values;
  1166. AZ::StringFunc::TokenizeVisitor(
  1167. compoundValues.c_str(),
  1168. [&values](AZStd::string_view elem)
  1169. {
  1170. values.push_back(elem);
  1171. },
  1172. ';',
  1173. false /* keepEmptyStrings */
  1174. );
  1175. return values;
  1176. };
  1177. // Reads the contents of the specified file and returns a string of said contents
  1178. const auto readFileContents = [](const AZStd::string& path) -> AZStd::string
  1179. {
  1180. const auto fileSize = AZ::IO::SystemFile::Length(path.c_str());
  1181. if (fileSize == 0)
  1182. {
  1183. return "";
  1184. }
  1185. AZStd::vector<char> buffer(fileSize + 1);
  1186. buffer[fileSize] = '\0';
  1187. if (!AZ::IO::SystemFile::Read(path.c_str(), buffer.data()))
  1188. {
  1189. return "";
  1190. }
  1191. return AZStd::string(buffer.begin(), buffer.end());
  1192. };
  1193. // We support specifying multiple files in the cmdline by separating them with ';'
  1194. // If a semicolon list of .py files is provided we look at the arg string
  1195. AZStd::string scriptFileStr;
  1196. if (cmdInfo.m_strFileName.endsWith(".py"))
  1197. {
  1198. // cmdInfo data is only available on startup, copy it
  1199. scriptFileStr = cmdInfo.m_strFileName.toUtf8().constData();
  1200. }
  1201. else if (cmdInfo.m_strFileName.endsWith(".txt"))
  1202. {
  1203. // Otherwise, we look to see if we can read the file for test modules
  1204. // The file is expected to contain a single semicolon separated string of Editor pytest modules
  1205. if (scriptFileStr = readFileContents(cmdInfo.m_strFileName.toUtf8().data()); scriptFileStr.empty())
  1206. {
  1207. AZ_Error(
  1208. "RunInitPythonScript",
  1209. false, "Failed to read the file containing a semi colon separated list of python modules");
  1210. return;
  1211. }
  1212. }
  1213. else
  1214. {
  1215. AZ_Error("RunInitPythonScript", false, "Failed to read Python files from --runpythontest arg. "
  1216. "Expects a semi colon separated list of python modules or a file containing a semi colon separated list of python modules");
  1217. return;
  1218. }
  1219. // Extract the discrete python script files
  1220. const auto fileList = extractSeparatedValues(scriptFileStr);
  1221. if (cmdInfo.m_pythonArgs.length() > 0 || cmdInfo.m_bRunPythonTestScript)
  1222. {
  1223. QByteArray pythonArgsStr = cmdInfo.m_pythonArgs.toUtf8();
  1224. AZStd::vector<AZStd::string_view> pythonArgs;
  1225. AZ::StringFunc::TokenizeVisitor(pythonArgsStr.constData(),
  1226. [&pythonArgs](AZStd::string_view elem)
  1227. {
  1228. pythonArgs.push_back(elem);
  1229. }, ' '
  1230. );
  1231. if (cmdInfo.m_bRunPythonTestScript)
  1232. {
  1233. // We support specifying multiple test case names in the cmdline by separating them
  1234. // with ';', either in a text file or as a string
  1235. AZStd::string testCaseStr;
  1236. if (cmdInfo.m_pythonTestCase.endsWith(".txt"))
  1237. {
  1238. // A path to the file containing the test case names has been provided as the argument
  1239. if (testCaseStr = readFileContents(cmdInfo.m_pythonTestCase.toUtf8().data()); testCaseStr.empty())
  1240. {
  1241. AZ_Error(
  1242. "RunInitPythonScript",
  1243. false,
  1244. "Failed to read Python files from --pythontestcase arg. "
  1245. "Expects a semi colon separated list of python test case names or a file containing a semi colon separated list of "
  1246. "python test case names");
  1247. return;
  1248. }
  1249. }
  1250. else
  1251. {
  1252. // Test case names have been passed as the argument
  1253. testCaseStr = cmdInfo.m_pythonTestCase.toUtf8().data();
  1254. }
  1255. // Extract the discrete python test case names
  1256. const auto testCaseList = extractSeparatedValues(testCaseStr);
  1257. // The number of python script files must match the number of test case names for the test case names
  1258. // to properly correlate with their invoking scripts
  1259. if (fileList.size() != testCaseList.size())
  1260. {
  1261. AZ_Error(
  1262. "RunInitPythonScript",
  1263. false,
  1264. "The number of supplied test scripts (%zu) did not match the number of supplied test case names (%zu)",
  1265. fileList.size(), testCaseList.size());
  1266. return;
  1267. }
  1268. bool success = true;
  1269. auto ExecuteByFilenamesTests = [&pythonArgs, &fileList, &testCaseList, &success](EditorPythonRunnerRequests* pythonRunnerRequests)
  1270. {
  1271. for (int i = 0; i < fileList.size(); ++i)
  1272. {
  1273. bool cur_success = pythonRunnerRequests->ExecuteByFilenameAsTest(fileList[i], testCaseList[i], pythonArgs);
  1274. success = success && cur_success;
  1275. }
  1276. };
  1277. EditorPythonRunnerRequestBus::Broadcast(ExecuteByFilenamesTests);
  1278. if (success)
  1279. {
  1280. // Close the editor gracefully as the test has completed
  1281. GetIEditor()->GetDocument()->SetModifiedFlag(false);
  1282. QTimer::singleShot(0, qApp, &QApplication::closeAllWindows);
  1283. }
  1284. else
  1285. {
  1286. // Close down the application with 0xF exit code indicating failure of the test
  1287. AZ::Debug::Trace::Terminate(0xF);
  1288. }
  1289. }
  1290. else
  1291. {
  1292. auto ExecuteByFilenamesWithArgs = [&pythonArgs, &fileList](EditorPythonRunnerRequests* pythonRunnerRequests)
  1293. {
  1294. for (AZStd::string_view filename : fileList)
  1295. {
  1296. pythonRunnerRequests->ExecuteByFilenameWithArgs(filename, pythonArgs);
  1297. }
  1298. };
  1299. EditorPythonRunnerRequestBus::Broadcast(ExecuteByFilenamesWithArgs);
  1300. }
  1301. }
  1302. else
  1303. {
  1304. auto ExecuteByFilenames = [&fileList](EditorPythonRunnerRequests* pythonRunnerRequests)
  1305. {
  1306. for (AZStd::string_view filename : fileList)
  1307. {
  1308. pythonRunnerRequests->ExecuteByFilename(filename);
  1309. }
  1310. };
  1311. EditorPythonRunnerRequestBus::Broadcast(ExecuteByFilenames);
  1312. }
  1313. }
  1314. }
  1315. /////////////////////////////////////////////////////////////////////////////
  1316. // CCryEditApp initialization
  1317. bool CCryEditApp::InitInstance()
  1318. {
  1319. QElapsedTimer startupTimer;
  1320. startupTimer.start();
  1321. m_pEditor = new CEditorImpl();
  1322. // parameters must be parsed early to capture arguments for test bootstrap
  1323. CEditCommandLineInfo cmdInfo;
  1324. InitFromCommandLine(cmdInfo);
  1325. qobject_cast<Editor::EditorQtApplication*>(qApp)->Initialize(); // Must be done after CEditorImpl() is created
  1326. m_pEditor->Initialize();
  1327. // let anything listening know that they can use the IEditor now
  1328. AzToolsFramework::EditorEvents::Bus::Broadcast(&AzToolsFramework::EditorEvents::NotifyIEditorAvailable, m_pEditor);
  1329. if (cmdInfo.m_bShowVersionInfo)
  1330. {
  1331. CStartupLogoDialog startupDlg(CStartupLogoDialog::About, FormatVersion(m_pEditor->GetFileVersion()), FormatRichTextCopyrightNotice());
  1332. startupDlg.exec();
  1333. return false;
  1334. }
  1335. RegisterReflectedVarHandlers();
  1336. CreateSplashScreen();
  1337. // Register the application's document templates. Document templates
  1338. // serve as the connection between documents, frame windows and views
  1339. CCrySingleDocTemplate* pDocTemplate = CCrySingleDocTemplate::create<CCryEditDoc>();
  1340. m_pDocManager = new CCryDocManager;
  1341. ((CCryDocManager*)m_pDocManager)->SetDefaultTemplate(pDocTemplate);
  1342. auto mainWindow = new MainWindow();
  1343. #ifdef Q_OS_MACOS
  1344. auto mainWindowWrapper = new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionDisabled);
  1345. #else
  1346. auto mainWindowWrapper = new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionAutoTitleBarButtons);
  1347. #endif
  1348. mainWindowWrapper->setGuest(mainWindow);
  1349. HWND mainWindowWrapperHwnd = (HWND)mainWindowWrapper->winId();
  1350. AZ::IO::FixedMaxPath engineRootPath;
  1351. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  1352. {
  1353. settingsRegistry->Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder);
  1354. }
  1355. QDir engineRoot = QString::fromUtf8(engineRootPath.c_str(), aznumeric_cast<int>(engineRootPath.Native().size()));
  1356. AzQtComponents::StyleManager::addSearchPaths(
  1357. QStringLiteral("style"),
  1358. engineRoot.filePath(QStringLiteral("Code/Editor/Style")),
  1359. QStringLiteral(":/Assets/Editor/Style"),
  1360. engineRootPath);
  1361. AzQtComponents::StyleManager::setStyleSheet(mainWindow, QStringLiteral("style:Editor.qss"));
  1362. // Note: we should use getNativeHandle to get the HWND from the widget, but
  1363. // it returns an invalid handle unless the widget has been shown and polished and even then
  1364. // it sometimes returns an invalid handle.
  1365. // So instead, we use winId(), which does consistently work
  1366. //mainWindowWrapperHwnd = QtUtil::getNativeHandle(mainWindowWrapper);
  1367. // Connect to the AssetProcessor at this point
  1368. // It will be launched if not running
  1369. ConnectToAssetProcessor();
  1370. CCryEditApp::OutputStartupMessage(QString("Initializing Game System..."));
  1371. auto initGameSystemOutcome = InitGameSystem(mainWindowWrapperHwnd);
  1372. if (!initGameSystemOutcome.IsSuccess())
  1373. {
  1374. return false;
  1375. }
  1376. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  1377. {
  1378. AZ::ComponentApplicationLifecycle::SignalEvent(*settingsRegistry, "LegacySystemInterfaceCreated", R"({})");
  1379. }
  1380. // Process some queued events come from system init
  1381. // Such as asset catalog loaded notification.
  1382. // There are some systems need to load configurations from assets for post initialization but before loading level
  1383. AZ::TickBus::ExecuteQueuedEvents();
  1384. qobject_cast<Editor::EditorQtApplication*>(qApp)->LoadSettings();
  1385. // Create Sandbox user folder if necessary
  1386. AZ::IO::FileIOBase::GetDirectInstance()->CreatePath(Path::GetUserSandboxFolder().toUtf8().data());
  1387. if (!InitGame())
  1388. {
  1389. if (gEnv && gEnv->pLog)
  1390. {
  1391. gEnv->pLog->LogError("Game can not be initialized, InitGame() failed.");
  1392. }
  1393. if (!cmdInfo.m_bExport)
  1394. {
  1395. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Game can not be initialized, please refer to the editor log file"));
  1396. }
  1397. return false;
  1398. }
  1399. // Meant to be called before MainWindow::Initialize
  1400. InitPlugins();
  1401. CCryEditApp::OutputStartupMessage(QString("Initializing Main Window..."));
  1402. mainWindow->Initialize();
  1403. GetIEditor()->GetCommandManager()->RegisterAutoCommands();
  1404. mainWindowWrapper->enableSaveRestoreGeometry("O3DE", "O3DE", "mainWindowGeometry");
  1405. m_pDocManager->OnFileNew();
  1406. if (MainWindow::instance())
  1407. {
  1408. if (m_bConsoleMode || IsInAutotestMode())
  1409. {
  1410. AZ::Environment::FindVariable<int>("assertVerbosityLevel").Set(1);
  1411. m_pConsoleDialog->raise();
  1412. }
  1413. else
  1414. {
  1415. MainWindow::instance()->show();
  1416. MainWindow::instance()->raise();
  1417. MainWindow::instance()->update();
  1418. MainWindow::instance()->setFocus();
  1419. #if AZ_TRAIT_OS_PLATFORM_APPLE
  1420. QWindow* window = mainWindowWrapper->windowHandle();
  1421. if (window)
  1422. {
  1423. Editor::WindowObserver* observer = new Editor::WindowObserver(window, this);
  1424. connect(observer, &Editor::WindowObserver::windowIsMovingOrResizingChanged, Editor::EditorQtApplication::instance(), &Editor::EditorQtApplication::setIsMovingOrResizing);
  1425. }
  1426. #endif
  1427. }
  1428. }
  1429. if (m_bAutotestMode)
  1430. {
  1431. ICVar* const noErrorReportWindowCVar = gEnv && gEnv->pConsole ? gEnv->pConsole->GetCVar("sys_no_error_report_window") : nullptr;
  1432. if (noErrorReportWindowCVar)
  1433. {
  1434. noErrorReportWindowCVar->Set(true);
  1435. }
  1436. ICVar* const showErrorDialogOnLoadCVar = gEnv && gEnv->pConsole ? gEnv->pConsole->GetCVar("ed_showErrorDialogOnLoad") : nullptr;
  1437. if (showErrorDialogOnLoadCVar)
  1438. {
  1439. showErrorDialogOnLoadCVar->Set(false);
  1440. }
  1441. }
  1442. SetEditorWindowTitle(nullptr, AZ::Utils::GetProjectDisplayName().c_str(), nullptr);
  1443. m_pEditor->InitFinished();
  1444. CCryEditApp::OutputStartupMessage(QString("Activating Python..."));
  1445. // Make sure Python is started before we attempt to restore the Editor layout, since the user
  1446. // might have custom view panes in the saved layout that will need to be registered.
  1447. auto editorPythonEventsInterface = AZ::Interface<AzToolsFramework::EditorPythonEventsInterface>::Get();
  1448. if (editorPythonEventsInterface)
  1449. {
  1450. editorPythonEventsInterface->StartPython();
  1451. }
  1452. CCryEditApp::OutputStartupMessage(QString("")); // add a blank line so that python is not blamed for anything that happens here
  1453. if (!GetIEditor()->IsInConsolewMode())
  1454. {
  1455. bool restoreDefaults = !mainWindowWrapper->restoreGeometryFromSettings();
  1456. QtViewPaneManager::instance()->RestoreLayout(restoreDefaults);
  1457. }
  1458. // Trigger the Action Manager registration hooks once all systems and Gems are initialized and listening.
  1459. AzToolsFramework::ActionManagerSystemComponent::TriggerRegistrationNotifications();
  1460. CloseSplashScreen();
  1461. // DON'T CHANGE ME!
  1462. // Test scripts listen for this line, so please don't touch this without updating them.
  1463. // We consider ourselves "initialized enough" at this stage because all further initialization may be blocked by the modal welcome screen.
  1464. CLogFile::WriteLine(QString("Engine initialized, took %1s.").arg(startupTimer.elapsed() / 1000.0, 0, 'f', 2));
  1465. // Init the level after everything else is finished initializing, otherwise, certain things aren't set up yet
  1466. QTimer::singleShot(0, this, [this, cmdInfo] {
  1467. InitLevel(cmdInfo);
  1468. });
  1469. if (!m_bConsoleMode && !m_bPreviewMode)
  1470. {
  1471. GetIEditor()->UpdateViews();
  1472. if (MainWindow::instance())
  1473. {
  1474. MainWindow::instance()->setFocus();
  1475. }
  1476. }
  1477. if (!InitConsole())
  1478. {
  1479. return true;
  1480. }
  1481. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  1482. {
  1483. AZ::ComponentApplicationLifecycle::SignalEvent(*settingsRegistry, "LegacyCommandLineProcessed", R"({})");
  1484. }
  1485. if (IsInRegularEditorMode())
  1486. {
  1487. int startUpMacroIndex = GetIEditor()->GetToolBoxManager()->GetMacroIndex("startup", true);
  1488. if (startUpMacroIndex >= 0)
  1489. {
  1490. CryLogAlways("Executing the startup macro");
  1491. GetIEditor()->GetToolBoxManager()->ExecuteMacro(startUpMacroIndex, true);
  1492. }
  1493. }
  1494. if (GetIEditor()->GetCommandManager()->IsRegistered("editor.open_lnm_editor"))
  1495. {
  1496. CCommand0::SUIInfo uiInfo;
  1497. [[maybe_unused]] bool ok = GetIEditor()->GetCommandManager()->GetUIInfo("editor.open_lnm_editor", uiInfo);
  1498. assert(ok);
  1499. }
  1500. RunInitPythonScript(cmdInfo);
  1501. return true;
  1502. }
  1503. //////////////////////////////////////////////////////////////////////////
  1504. void CCryEditApp::LoadFile(QString fileName)
  1505. {
  1506. if (GetIEditor()->GetViewManager()->GetViewCount() == 0)
  1507. {
  1508. return;
  1509. }
  1510. if (MainWindow::instance() || m_pConsoleDialog)
  1511. {
  1512. SetEditorWindowTitle(nullptr, AZ::Utils::GetProjectDisplayName().c_str(), GetIEditor()->GetGameEngine()->GetLevelName());
  1513. }
  1514. GetIEditor()->SetModifiedFlag(false);
  1515. GetIEditor()->SetModifiedModule(eModifiedNothing);
  1516. }
  1517. //////////////////////////////////////////////////////////////////////////
  1518. inline void ExtractMenuName(QString& str)
  1519. {
  1520. // eliminate &
  1521. int pos = str.indexOf('&');
  1522. if (pos >= 0)
  1523. {
  1524. str = str.left(pos) + str.right(str.length() - pos - 1);
  1525. }
  1526. // cut the string
  1527. for (int i = 0; i < str.length(); i++)
  1528. {
  1529. if (str[i] == 9)
  1530. {
  1531. str = str.left(i);
  1532. }
  1533. }
  1534. }
  1535. //////////////////////////////////////////////////////////////////////////
  1536. void CCryEditApp::EnableAccelerator([[maybe_unused]] bool bEnable)
  1537. {
  1538. /*
  1539. if (bEnable)
  1540. {
  1541. //LoadAccelTable( MAKEINTRESOURCE(IDR_MAINFRAME) );
  1542. m_AccelManager.UpdateWndTable();
  1543. CLogFile::WriteLine( "Enable Accelerators" );
  1544. }
  1545. else
  1546. {
  1547. CMainFrame *mainFrame = (CMainFrame*)m_pMainWnd;
  1548. if (mainFrame->m_hAccelTable)
  1549. DestroyAcceleratorTable( mainFrame->m_hAccelTable );
  1550. mainFrame->m_hAccelTable = nullptr;
  1551. mainFrame->LoadAccelTable( MAKEINTRESOURCE(IDR_GAMEACCELERATOR) );
  1552. CLogFile::WriteLine( "Disable Accelerators" );
  1553. }
  1554. */
  1555. }
  1556. //////////////////////////////////////////////////////////////////////////
  1557. void CCryEditApp::SaveAutoRemind()
  1558. {
  1559. // Added a static variable here to avoid multiple messageboxes to
  1560. // remind the user of saving the file. Many message boxes would appear as this
  1561. // is triggered by a timer even which does not stop when the message box is called.
  1562. // Used a static variable instead of a member variable because this value is not
  1563. // Needed anywhere else.
  1564. static bool boIsShowingWarning(false);
  1565. // Ingore in game mode, or if no level created, or level not modified
  1566. if (GetIEditor()->IsInGameMode() || !GetIEditor()->GetGameEngine()->IsLevelLoaded() || !GetIEditor()->GetDocument()->IsModified())
  1567. {
  1568. return;
  1569. }
  1570. if (boIsShowingWarning)
  1571. {
  1572. return;
  1573. }
  1574. boIsShowingWarning = true;
  1575. if (QMessageBox::question(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Auto Reminder: You did not save level for at least %1 minute(s)\r\nDo you want to save it now?").arg(gSettings.autoRemindTime), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
  1576. {
  1577. // Save now.
  1578. GetIEditor()->SaveDocument();
  1579. }
  1580. boIsShowingWarning = false;
  1581. }
  1582. //////////////////////////////////////////////////////////////////////////
  1583. void CCryEditApp::WriteConfig()
  1584. {
  1585. IEditor* pEditor = GetIEditor();
  1586. if (pEditor && pEditor->GetDisplaySettings())
  1587. {
  1588. pEditor->GetDisplaySettings()->SaveRegistry();
  1589. }
  1590. }
  1591. // App command to run the dialog
  1592. void CCryEditApp::OnAppAbout()
  1593. {
  1594. auto* dialog = new CStartupLogoDialog(
  1595. CStartupLogoDialog::About, FormatVersion(m_pEditor->GetFileVersion()), FormatRichTextCopyrightNotice());
  1596. auto mainWindow = MainWindow::instance();
  1597. auto geometry = dialog->geometry();
  1598. geometry.moveCenter(mainWindow->mapToGlobal(mainWindow->geometry().center()));
  1599. dialog->setGeometry(geometry);
  1600. dialog->setAttribute(Qt::WA_DeleteOnClose);
  1601. dialog->show();
  1602. }
  1603. // App command to run the Welcome to Open 3D Engine dialog
  1604. void CCryEditApp::OnAppShowWelcomeScreen()
  1605. {
  1606. // This logic is a simplified version of the startup
  1607. // flow that also shows the Welcome dialog
  1608. if (m_bIsExportingLegacyData
  1609. || m_creatingNewLevel
  1610. || m_openingLevel
  1611. || m_savingLevel)
  1612. {
  1613. QMessageBox::warning(AzToolsFramework::GetActiveWindow(), QString(), "The Welcome screen cannot be displayed because a level load/save is in progress.");
  1614. return;
  1615. }
  1616. QString levelName;
  1617. bool showWelcomeDialog = true;
  1618. while (showWelcomeDialog)
  1619. {
  1620. // Keep showing the Welcome dialog as long as the user cancels
  1621. // a level creation/load triggered from the Welcome dialog
  1622. levelName = ShowWelcomeDialog();
  1623. if (levelName == "new")
  1624. {
  1625. // The user has clicked on the create new level option
  1626. bool wasCreateLevelOperationCancelled = false;
  1627. bool isNewLevelCreationSuccess = false;
  1628. // This will show the new level dialog until a valid input has been entered by the user or until the user click cancel
  1629. while (!isNewLevelCreationSuccess && !wasCreateLevelOperationCancelled)
  1630. {
  1631. isNewLevelCreationSuccess = CreateLevel(wasCreateLevelOperationCancelled);
  1632. }
  1633. if (isNewLevelCreationSuccess)
  1634. {
  1635. showWelcomeDialog = false;
  1636. levelName.clear();
  1637. }
  1638. }
  1639. else
  1640. {
  1641. // The user has selected an existing level to open
  1642. showWelcomeDialog = false;
  1643. }
  1644. }
  1645. if (!levelName.isEmpty())
  1646. {
  1647. // load level
  1648. if (!CFileUtil::Exists(levelName, false))
  1649. {
  1650. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QObject::tr("Missing level"), QObject::tr("Failed to auto-load last opened level. Level file does not exist:\n\n%1").arg(levelName));
  1651. }
  1652. else
  1653. {
  1654. OpenDocumentFile(levelName.toUtf8().data());
  1655. }
  1656. }
  1657. }
  1658. void CCryEditApp::OnUpdateShowWelcomeScreen(QAction* action)
  1659. {
  1660. action->setEnabled(!m_bIsExportingLegacyData
  1661. && !m_creatingNewLevel
  1662. && !m_openingLevel
  1663. && !m_savingLevel);
  1664. }
  1665. void CCryEditApp::OnDocumentationTutorials()
  1666. {
  1667. QString webLink = tr("https://o3de.org/docs/learning-guide/");
  1668. QDesktopServices::openUrl(QUrl(webLink));
  1669. }
  1670. void CCryEditApp::OnDocumentationGlossary()
  1671. {
  1672. QString webLink = tr("https://o3de.org/docs/user-guide/appendix/glossary/");
  1673. QDesktopServices::openUrl(QUrl(webLink));
  1674. }
  1675. void CCryEditApp::OnDocumentationO3DE()
  1676. {
  1677. QString webLink = tr("https://o3de.org/docs/");
  1678. QDesktopServices::openUrl(QUrl(webLink));
  1679. }
  1680. void CCryEditApp::OnDocumentationGamelift()
  1681. {
  1682. QString webLink = tr("https://docs.aws.amazon.com/gamelift/");
  1683. QDesktopServices::openUrl(QUrl(webLink));
  1684. }
  1685. void CCryEditApp::OnDocumentationReleaseNotes()
  1686. {
  1687. QString webLink = tr("https://o3de.org/docs/release-notes/");
  1688. QDesktopServices::openUrl(QUrl(webLink));
  1689. }
  1690. void CCryEditApp::OnDocumentationGameDevBlog()
  1691. {
  1692. QString webLink = tr("https://aws.amazon.com/blogs/gamedev");
  1693. QDesktopServices::openUrl(QUrl(webLink));
  1694. }
  1695. void CCryEditApp::OnDocumentationForums()
  1696. {
  1697. QString webLink = tr("https://o3de.org/community/");
  1698. QDesktopServices::openUrl(QUrl(webLink));
  1699. }
  1700. void CCryEditApp::OnDocumentationAWSSupport()
  1701. {
  1702. QString webLink = tr("https://aws.amazon.com/contact-us");
  1703. QDesktopServices::openUrl(QUrl(webLink));
  1704. }
  1705. bool CCryEditApp::FixDanglingSharedMemory(const QString& sharedMemName) const
  1706. {
  1707. QSystemSemaphore sem(sharedMemName + "_sem", 1);
  1708. sem.acquire();
  1709. {
  1710. QSharedMemory fix(sharedMemName);
  1711. if (!fix.attach())
  1712. {
  1713. if (fix.error() != QSharedMemory::NotFound)
  1714. {
  1715. sem.release();
  1716. return false;
  1717. }
  1718. }
  1719. // fix.detach() when destructed, taking out any dangling shared memory
  1720. // on unix
  1721. }
  1722. sem.release();
  1723. return true;
  1724. }
  1725. /////////////////////////////////////////////////////////////////////////////
  1726. // CCryEditApp message handlers
  1727. int CCryEditApp::ExitInstance(int exitCode)
  1728. {
  1729. if (m_pEditor)
  1730. {
  1731. m_pEditor->OnBeginShutdownSequence();
  1732. }
  1733. qobject_cast<Editor::EditorQtApplication*>(qApp)->UnloadSettings();
  1734. if (IsInRegularEditorMode())
  1735. {
  1736. if (GetIEditor())
  1737. {
  1738. int shutDownMacroIndex = GetIEditor()->GetToolBoxManager()->GetMacroIndex("shutdown", true);
  1739. if (shutDownMacroIndex >= 0)
  1740. {
  1741. CryLogAlways("Executing the shutdown macro");
  1742. GetIEditor()->GetToolBoxManager()->ExecuteMacro(shutDownMacroIndex, true);
  1743. }
  1744. }
  1745. }
  1746. if (GetIEditor())
  1747. {
  1748. //Nobody seems to know in what case that kind of exit can happen so instrumented to see if it happens at all
  1749. if (m_pEditor)
  1750. {
  1751. m_pEditor->OnEarlyExitShutdownSequence();
  1752. }
  1753. gEnv->pLog->Flush();
  1754. // note: the intention here is to quit immediately without processing anything further
  1755. // on linux and mac, _exit has that effect
  1756. // however, on windows, _exit() still invokes CRT functions, unloads, and destructors
  1757. // so on windows, we need to use TerminateProcess
  1758. #if defined(AZ_PLATFORM_WINDOWS)
  1759. TerminateProcess(GetCurrentProcess(), exitCode);
  1760. #else
  1761. _exit(exitCode);
  1762. #endif
  1763. }
  1764. SAFE_DELETE(m_pConsoleDialog);
  1765. if (GetIEditor())
  1766. {
  1767. GetIEditor()->Notify(eNotify_OnQuit);
  1768. }
  1769. // if we're aborting due to an unexpected shutdown then don't call into objects that don't exist yet.
  1770. if ((gEnv) && (gEnv->pSystem) && (gEnv->pSystem->GetILevelSystem()))
  1771. {
  1772. gEnv->pSystem->GetILevelSystem()->UnloadLevel();
  1773. }
  1774. if (GetIEditor())
  1775. {
  1776. GetIEditor()->GetDocument()->DeleteTemporaryLevel();
  1777. }
  1778. m_bExiting = true;
  1779. HEAP_CHECK
  1780. ////////////////////////////////////////////////////////////////////////
  1781. // Executed directly before termination of the editor, just write a
  1782. // quick note to the log so that we can later see that the editor
  1783. // terminated flawlessly. Also delete temporary files.
  1784. ////////////////////////////////////////////////////////////////////////
  1785. WriteConfig();
  1786. if (m_pEditor)
  1787. {
  1788. // Ensure component entities are wiped prior to unloading plugins,
  1789. // since components may be implemented in those plugins.
  1790. AzToolsFramework::EditorEntityContextRequestBus::Broadcast(
  1791. &AzToolsFramework::EditorEntityContextRequestBus::Events::ResetEditorContext);
  1792. // vital, so that the Qt integration can unhook itself!
  1793. m_pEditor->UnloadPlugins();
  1794. m_pEditor->Uninitialize();
  1795. }
  1796. //////////////////////////////////////////////////////////////////////////
  1797. // Quick end for editor.
  1798. if (gEnv && gEnv->pSystem)
  1799. {
  1800. gEnv->pSystem->Quit();
  1801. SAFE_RELEASE(gEnv->pSystem);
  1802. }
  1803. //////////////////////////////////////////////////////////////////////////
  1804. if (m_pEditor)
  1805. {
  1806. m_pEditor->DeleteThis();
  1807. m_pEditor = nullptr;
  1808. }
  1809. // save accelerator manager configuration.
  1810. //m_AccelManager.SaveOnExit();
  1811. #ifdef WIN32
  1812. Gdiplus::GdiplusShutdown(m_gdiplusToken);
  1813. #endif
  1814. if (m_mutexApplication)
  1815. {
  1816. delete m_mutexApplication;
  1817. }
  1818. return 0;
  1819. }
  1820. bool CCryEditApp::IsWindowInForeground()
  1821. {
  1822. return Editor::EditorQtApplication::instance()->IsActive();
  1823. }
  1824. void CCryEditApp::DisableIdleProcessing()
  1825. {
  1826. m_disableIdleProcessingCounter++;
  1827. }
  1828. void CCryEditApp::EnableIdleProcessing()
  1829. {
  1830. m_disableIdleProcessingCounter--;
  1831. AZ_Assert(m_disableIdleProcessingCounter >= 0, "m_disableIdleProcessingCounter must be nonnegative");
  1832. }
  1833. bool CCryEditApp::OnIdle([[maybe_unused]] LONG lCount)
  1834. {
  1835. if (0 == m_disableIdleProcessingCounter)
  1836. {
  1837. return IdleProcessing(gSettings.backgroundUpdatePeriod == -1);
  1838. }
  1839. else
  1840. {
  1841. return false;
  1842. }
  1843. }
  1844. int CCryEditApp::IdleProcessing(bool bBackgroundUpdate)
  1845. {
  1846. AZ_Assert(m_disableIdleProcessingCounter == 0, "We should not be in IdleProcessing()");
  1847. //HEAP_CHECK
  1848. if (!MainWindow::instance())
  1849. {
  1850. return 0;
  1851. }
  1852. if (!GetIEditor()->GetSystem())
  1853. {
  1854. return 0;
  1855. }
  1856. // Ensure we don't get called re-entrantly
  1857. // This can occur when a nested Qt event loop fires (e.g. by way of a modal dialog calling exec)
  1858. if (m_idleProcessingRunning)
  1859. {
  1860. return 0;
  1861. }
  1862. QScopedValueRollback<bool> guard(m_idleProcessingRunning, true);
  1863. ////////////////////////////////////////////////////////////////////////
  1864. // Call the update function of the engine
  1865. ////////////////////////////////////////////////////////////////////////
  1866. if (m_bTestMode && !bBackgroundUpdate)
  1867. {
  1868. // Terminate process.
  1869. CLogFile::WriteLine("Editor: Terminate Process");
  1870. exit(0);
  1871. }
  1872. bool bIsAppWindow = IsWindowInForeground();
  1873. bool bActive = false;
  1874. int res = 0;
  1875. if (bIsAppWindow || m_bForceProcessIdle || m_bKeepEditorActive
  1876. // Automated tests must always keep the editor active, or they can get stuck
  1877. || m_bAutotestMode || m_bRunPythonTestScript)
  1878. {
  1879. res = 1;
  1880. bActive = true;
  1881. }
  1882. if (m_bForceProcessIdle && bIsAppWindow)
  1883. {
  1884. m_bForceProcessIdle = false;
  1885. }
  1886. // focus changed
  1887. if (m_bPrevActive != bActive)
  1888. {
  1889. GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_CHANGE_FOCUS, bActive, 0);
  1890. #if defined(AZ_PLATFORM_WINDOWS)
  1891. // This is required for the audio system to be notified of focus changes in the editor. After discussing it
  1892. // with the macOS team, they are working on unifying the system events between the editor and standalone
  1893. // launcher so this is only needed on windows.
  1894. if (bActive)
  1895. {
  1896. AzFramework::WindowsLifecycleEvents::Bus::Broadcast(&AzFramework::WindowsLifecycleEvents::Bus::Events::OnSetFocus);
  1897. }
  1898. else
  1899. {
  1900. AzFramework::WindowsLifecycleEvents::Bus::Broadcast(&AzFramework::WindowsLifecycleEvents::Bus::Events::OnKillFocus);
  1901. }
  1902. #endif
  1903. }
  1904. m_bPrevActive = bActive;
  1905. // Tick System Events, even in the background
  1906. AZ::ComponentApplicationRequests* componentApplicationRequests = AZ::Interface<AZ::ComponentApplicationRequests>::Get();
  1907. if (componentApplicationRequests)
  1908. {
  1909. AZ::ComponentApplication* componentApplication = componentApplicationRequests->GetApplication();
  1910. if (componentApplication)
  1911. {
  1912. componentApplication->TickSystem();
  1913. }
  1914. }
  1915. // Don't tick application if we're doing idle processing during an assert.
  1916. const bool isErrorWindowVisible = (gEnv && gEnv->pSystem->IsAssertDialogVisible());
  1917. if (isErrorWindowVisible)
  1918. {
  1919. if (m_pEditor)
  1920. {
  1921. m_pEditor->Update();
  1922. }
  1923. }
  1924. else if (bActive || (bBackgroundUpdate && !bIsAppWindow))
  1925. {
  1926. // Update Game
  1927. GetIEditor()->GetGameEngine()->Update();
  1928. if (!GetIEditor()->IsInGameMode())
  1929. {
  1930. if (m_pEditor)
  1931. {
  1932. m_pEditor->Update();
  1933. }
  1934. GetIEditor()->Notify(eNotify_OnIdleUpdate);
  1935. }
  1936. }
  1937. else
  1938. {
  1939. if (GetIEditor()->GetSystem() && GetIEditor()->GetSystem()->GetILog())
  1940. {
  1941. GetIEditor()->GetSystem()->GetILog()->Update(); // print messages from other threads
  1942. }
  1943. // If we're backgrounded and not fully background updating, idle to rate limit SystemTick
  1944. static AZ::TimeMs sTimeLastMs = AZ::GetRealElapsedTimeMs();
  1945. const int64_t maxFrameTimeMs = ed_backgroundSystemTickCap;
  1946. if (maxFrameTimeMs > 0)
  1947. {
  1948. const int64_t maxElapsedTimeMs = maxFrameTimeMs + static_cast<int64_t>(sTimeLastMs);
  1949. const int64_t realElapsedTimeMs = static_cast<int64_t>(AZ::GetRealElapsedTimeMs());
  1950. if (maxElapsedTimeMs > realElapsedTimeMs)
  1951. {
  1952. CrySleep(aznumeric_cast<unsigned int>(maxElapsedTimeMs - realElapsedTimeMs));
  1953. }
  1954. }
  1955. sTimeLastMs = AZ::GetRealElapsedTimeMs();
  1956. }
  1957. DisplayLevelLoadErrors();
  1958. if (CConsoleSCB::GetCreatedInstance())
  1959. {
  1960. CConsoleSCB::GetCreatedInstance()->FlushText();
  1961. }
  1962. return res;
  1963. }
  1964. void CCryEditApp::DisplayLevelLoadErrors()
  1965. {
  1966. CCryEditDoc* currentLevel = GetIEditor()->GetDocument();
  1967. if (currentLevel && currentLevel->IsDocumentReady() && !m_levelErrorsHaveBeenDisplayed)
  1968. {
  1969. // Generally it takes a few idle updates for meshes to load and be processed by their components. This value
  1970. // was picked based on examining when mesh components are updated and their materials are checked for
  1971. // errors (2 updates) plus one more for good luck.
  1972. const int IDLE_FRAMES_TO_WAIT = 3;
  1973. ++m_numBeforeDisplayErrorFrames;
  1974. if (m_numBeforeDisplayErrorFrames > IDLE_FRAMES_TO_WAIT)
  1975. {
  1976. GetIEditor()->CommitLevelErrorReport();
  1977. GetIEditor()->GetErrorReport()->Display();
  1978. m_numBeforeDisplayErrorFrames = 0;
  1979. m_levelErrorsHaveBeenDisplayed = true;
  1980. }
  1981. }
  1982. }
  1983. //////////////////////////////////////////////////////////////////////////
  1984. void CCryEditApp::ExportLevel(bool /* bExportToGame */, bool /* bExportTexture */, bool /* bAutoExport */)
  1985. {
  1986. AZ_Assert(false, "Prefab system doesn't require level exports.");
  1987. return;
  1988. }
  1989. //////////////////////////////////////////////////////////////////////////
  1990. void CCryEditApp::OnEditHold()
  1991. {
  1992. GetIEditor()->GetDocument()->Hold(HOLD_FETCH_FILE);
  1993. }
  1994. //////////////////////////////////////////////////////////////////////////
  1995. void CCryEditApp::OnEditFetch()
  1996. {
  1997. GetIEditor()->GetDocument()->Fetch(HOLD_FETCH_FILE);
  1998. }
  1999. //////////////////////////////////////////////////////////////////////////
  2000. bool CCryEditApp::UserExportToGame(bool /* bNoMsgBox */)
  2001. {
  2002. AZ_Assert(false, "Export Level should no longer exist.");
  2003. return false;
  2004. }
  2005. void CCryEditApp::ExportToGame(bool /* bNoMsgBox */)
  2006. {
  2007. AZ_Assert(false, "Prefab system no longer exports levels.");
  2008. return;
  2009. }
  2010. void CCryEditApp::OnFileExportToGameNoSurfaceTexture()
  2011. {
  2012. UserExportToGame(false);
  2013. }
  2014. void CCryEditApp::OnMoveObject()
  2015. {
  2016. ////////////////////////////////////////////////////////////////////////
  2017. // Move the selected object to the marker position
  2018. ////////////////////////////////////////////////////////////////////////
  2019. }
  2020. void CCryEditApp::OnRenameObj()
  2021. {
  2022. }
  2023. void CCryEditApp::OnViewSwitchToGame()
  2024. {
  2025. if (IsInPreviewMode())
  2026. {
  2027. return;
  2028. }
  2029. // If switching on game mode...
  2030. if (!GetIEditor()->IsInGameMode())
  2031. {
  2032. // If simulation mode is enabled...
  2033. uint32 flags = GetIEditor()->GetDisplaySettings()->GetSettings();
  2034. if (flags & SETTINGS_PHYSICS)
  2035. {
  2036. // Disable simulation mode
  2037. OnSwitchPhysics();
  2038. // Schedule for next frame to enable game mode
  2039. AZ::Interface<AZ::IEventScheduler>::Get()->AddCallback(
  2040. [this] { OnViewSwitchToGame(); },
  2041. AZ::Name("Enable Game Mode"), AZ::Time::ZeroTimeMs);
  2042. return;
  2043. }
  2044. }
  2045. // close all open menus
  2046. auto activePopup = qApp->activePopupWidget();
  2047. if (qobject_cast<QMenu*>(activePopup))
  2048. {
  2049. activePopup->hide();
  2050. }
  2051. // TODO: Add your command handler code here
  2052. bool inGame = !GetIEditor()->IsInGameMode();
  2053. GetIEditor()->SetInGameMode(inGame);
  2054. }
  2055. void CCryEditApp::OnViewSwitchToGameFullScreen()
  2056. {
  2057. ed_previewGameInFullscreen_once = true;
  2058. OnViewSwitchToGame();
  2059. }
  2060. //////////////////////////////////////////////////////////////////////////
  2061. void CCryEditApp::OnEditLevelData()
  2062. {
  2063. auto dir = QFileInfo(GetIEditor()->GetDocument()->GetLevelPathName()).dir();
  2064. CFileUtil::EditTextFile(dir.absoluteFilePath("leveldata.xml").toUtf8().data());
  2065. }
  2066. //////////////////////////////////////////////////////////////////////////
  2067. void CCryEditApp::OnFileEditLogFile()
  2068. {
  2069. QString file = CLogFile::GetLogFileName();
  2070. QString fullPathName = Path::GamePathToFullPath(file);
  2071. QDesktopServices::openUrl(QUrl::fromLocalFile(fullPathName));
  2072. }
  2073. //////////////////////////////////////////////////////////////////////////
  2074. void CCryEditApp::OnFileEditEditorini()
  2075. {
  2076. CFileUtil::EditTextFile(EDITOR_CFG_FILE);
  2077. }
  2078. void CCryEditApp::OnPreferences()
  2079. {
  2080. /*
  2081. //////////////////////////////////////////////////////////////////////////////
  2082. // Accels edit by CPropertyPage
  2083. CAcceleratorManager tmpAccelManager;
  2084. tmpAccelManager = m_AccelManager;
  2085. CAccelMapPage page(&tmpAccelManager);
  2086. CPropertySheet sheet;
  2087. sheet.SetTitle( _T("Preferences") );
  2088. sheet.AddPage(&page);
  2089. if (sheet.DoModal() == IDOK) {
  2090. m_AccelManager = tmpAccelManager;
  2091. m_AccelManager.UpdateWndTable();
  2092. }
  2093. */
  2094. }
  2095. void CCryEditApp::OnOpenProjectManagerSettings()
  2096. {
  2097. OpenProjectManager("UpdateProject");
  2098. }
  2099. void CCryEditApp::OnOpenProjectManagerNew()
  2100. {
  2101. OpenProjectManager("CreateProject");
  2102. }
  2103. void CCryEditApp::OnOpenProjectManager()
  2104. {
  2105. OpenProjectManager("Projects");
  2106. }
  2107. void CCryEditApp::OpenProjectManager(const AZStd::string& screen)
  2108. {
  2109. // provide the current project path for in case we want to update the project
  2110. AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath();
  2111. const AZStd::vector<AZStd::string> commandLineOptions {
  2112. "--screen", screen,
  2113. "--project-path", AZStd::string::format(R"("%s")", projectPath.c_str()) };
  2114. bool launchSuccess = AzFramework::ProjectManager::LaunchProjectManager(commandLineOptions);
  2115. if (!launchSuccess)
  2116. {
  2117. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QObject::tr("Failed to launch O3DE Project Manager"), QObject::tr("Failed to find or start the O3dE Project Manager"));
  2118. }
  2119. }
  2120. //////////////////////////////////////////////////////////////////////////
  2121. void CCryEditApp::OnUndo()
  2122. {
  2123. //GetIEditor()->GetObjectManager()->UndoLastOp();
  2124. GetIEditor()->Undo();
  2125. }
  2126. //////////////////////////////////////////////////////////////////////////
  2127. void CCryEditApp::OnRedo()
  2128. {
  2129. GetIEditor()->Redo();
  2130. }
  2131. //////////////////////////////////////////////////////////////////////////
  2132. void CCryEditApp::OnUpdateRedo(QAction* action)
  2133. {
  2134. if (GetIEditor()->GetUndoManager()->IsHaveRedo())
  2135. {
  2136. action->setEnabled(true);
  2137. }
  2138. else
  2139. {
  2140. action->setEnabled(false);
  2141. }
  2142. }
  2143. //////////////////////////////////////////////////////////////////////////
  2144. void CCryEditApp::OnUpdateUndo(QAction* action)
  2145. {
  2146. if (GetIEditor()->GetUndoManager()->IsHaveUndo())
  2147. {
  2148. action->setEnabled(true);
  2149. }
  2150. else
  2151. {
  2152. action->setEnabled(false);
  2153. }
  2154. }
  2155. //////////////////////////////////////////////////////////////////////////
  2156. void CCryEditApp::OnSwitchPhysics()
  2157. {
  2158. if (GetIEditor()->GetGameEngine() && !GetIEditor()->GetGameEngine()->GetSimulationMode() && !GetIEditor()->GetGameEngine()->IsLevelLoaded())
  2159. {
  2160. // Don't allow physics to be toggled on if we haven't loaded a level yet
  2161. return;
  2162. }
  2163. QWaitCursor wait;
  2164. GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_SWITCH_START, 0, 0);
  2165. uint32 flags = GetIEditor()->GetDisplaySettings()->GetSettings();
  2166. if (flags & SETTINGS_PHYSICS)
  2167. {
  2168. flags &= ~SETTINGS_PHYSICS;
  2169. }
  2170. else
  2171. {
  2172. flags |= SETTINGS_PHYSICS;
  2173. }
  2174. GetIEditor()->GetDisplaySettings()->SetSettings(flags);
  2175. if ((flags & SETTINGS_PHYSICS) == 0)
  2176. {
  2177. GetIEditor()->GetGameEngine()->SetSimulationMode(false);
  2178. GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_CHANGED, 0, 0);
  2179. }
  2180. else
  2181. {
  2182. GetIEditor()->GetGameEngine()->SetSimulationMode(true);
  2183. GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_CHANGED, 1, 0);
  2184. }
  2185. GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_SWITCH_END, 0, 0);
  2186. }
  2187. //////////////////////////////////////////////////////////////////////////
  2188. void CCryEditApp::OnSwitchPhysicsUpdate(QAction* action)
  2189. {
  2190. Q_ASSERT(action->isCheckable());
  2191. action->setChecked(!m_bIsExportingLegacyData && GetIEditor()->GetGameEngine()->GetSimulationMode());
  2192. }
  2193. //////////////////////////////////////////////////////////////////////////
  2194. void CCryEditApp::OnSyncPlayer()
  2195. {
  2196. GetIEditor()->GetGameEngine()->SyncPlayerPosition(!GetIEditor()->GetGameEngine()->IsSyncPlayerPosition());
  2197. }
  2198. //////////////////////////////////////////////////////////////////////////
  2199. void CCryEditApp::OnSyncPlayerUpdate(QAction* action)
  2200. {
  2201. Q_ASSERT(action->isCheckable());
  2202. action->setChecked(!GetIEditor()->GetGameEngine()->IsSyncPlayerPosition());
  2203. }
  2204. void CCryEditApp::OnUpdateNonGameMode(QAction* action)
  2205. {
  2206. action->setEnabled(!GetIEditor()->IsInGameMode());
  2207. }
  2208. void CCryEditApp::OnUpdateNewLevel(QAction* action)
  2209. {
  2210. action->setEnabled(!m_bIsExportingLegacyData);
  2211. }
  2212. void CCryEditApp::OnUpdatePlayGame(QAction* action)
  2213. {
  2214. action->setEnabled(!m_bIsExportingLegacyData && GetIEditor()->IsLevelLoaded());
  2215. }
  2216. //////////////////////////////////////////////////////////////////////////
  2217. CCryEditApp::ECreateLevelResult CCryEditApp::CreateLevel(const QString& templateName, const QString& levelName, QString& fullyQualifiedLevelName /* ={} */)
  2218. {
  2219. // If we are creating a new level and we're in simulate mode, then switch it off before we do anything else
  2220. if (GetIEditor()->GetGameEngine() && GetIEditor()->GetGameEngine()->GetSimulationMode())
  2221. {
  2222. // Preserve the modified flag, we don't want this switch of physics to change that flag
  2223. bool bIsDocModified = GetIEditor()->GetDocument()->IsModified();
  2224. OnSwitchPhysics();
  2225. GetIEditor()->GetDocument()->SetModifiedFlag(bIsDocModified);
  2226. auto* rootSpawnableInterface = AzFramework::RootSpawnableInterface::Get();
  2227. if (rootSpawnableInterface)
  2228. {
  2229. rootSpawnableInterface->ProcessSpawnableQueue();
  2230. }
  2231. }
  2232. const QScopedValueRollback<bool> rollback(m_creatingNewLevel);
  2233. m_creatingNewLevel = true;
  2234. GetIEditor()->Notify(eNotify_OnBeginCreate);
  2235. CrySystemEventBus::Broadcast(&CrySystemEventBus::Events::OnCryEditorBeginCreate);
  2236. QString currentLevel = GetIEditor()->GetLevelFolder();
  2237. if (!currentLevel.isEmpty())
  2238. {
  2239. GetIEditor()->GetSystem()->GetIPak()->ClosePacks(currentLevel.toUtf8().data());
  2240. }
  2241. QString cryFileName = levelName.mid(levelName.lastIndexOf('/') + 1, levelName.length() - levelName.lastIndexOf('/') + 1);
  2242. QString levelPath = QStringLiteral("%1/Levels/%2/").arg(Path::GetEditingGameDataFolder().c_str(), levelName);
  2243. fullyQualifiedLevelName = levelPath + cryFileName + EditorUtils::LevelFile::GetDefaultFileExtension();
  2244. //_MAX_PATH includes null terminator, so we actually want to cap at _MAX_PATH-1
  2245. if (fullyQualifiedLevelName.length() >= _MAX_PATH-1)
  2246. {
  2247. GetIEditor()->Notify(eNotify_OnEndCreate);
  2248. return ECLR_MAX_PATH_EXCEEDED;
  2249. }
  2250. // Does the directory already exist ?
  2251. if (QFileInfo(levelPath).exists())
  2252. {
  2253. GetIEditor()->Notify(eNotify_OnEndCreate);
  2254. return ECLR_ALREADY_EXISTS;
  2255. }
  2256. // Create the directory
  2257. CLogFile::WriteLine("Creating level directory");
  2258. if (!CFileUtil::CreatePath(levelPath))
  2259. {
  2260. GetIEditor()->Notify(eNotify_OnEndCreate);
  2261. return ECLR_DIR_CREATION_FAILED;
  2262. }
  2263. if (GetIEditor()->GetDocument()->IsDocumentReady())
  2264. {
  2265. m_pDocManager->OnFileNew();
  2266. }
  2267. ICVar* sv_map = gEnv->pConsole->GetCVar("sv_map");
  2268. if (sv_map)
  2269. {
  2270. sv_map->Set(levelName.toUtf8().data());
  2271. }
  2272. GetIEditor()->GetDocument()->InitEmptyLevel(128, 1);
  2273. GetIEditor()->SetStatusText("Creating Level...");
  2274. // Save the document to this folder
  2275. GetIEditor()->GetDocument()->SetPathName(fullyQualifiedLevelName);
  2276. GetIEditor()->GetGameEngine()->SetLevelPath(levelPath);
  2277. auto* service = AZ::Interface<AzToolsFramework::PrefabEditorEntityOwnershipInterface>::Get();
  2278. if (service)
  2279. {
  2280. const AZStd::string templateNameString(templateName.toUtf8().constData());
  2281. service->CreateNewLevelPrefab(fullyQualifiedLevelName.toUtf8().constData(), templateNameString);
  2282. }
  2283. if (GetIEditor()->GetDocument()->Save())
  2284. {
  2285. GetIEditor()->GetGameEngine()->LoadLevel(true, true);
  2286. GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0);
  2287. GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_END, 0, 0);
  2288. }
  2289. GetIEditor()->GetDocument()->CreateDefaultLevelAssets(128, 1);
  2290. GetIEditor()->GetDocument()->SetDocumentReady(true);
  2291. GetIEditor()->SetStatusText("Ready");
  2292. // At the end of the creating level process, add this level to the MRU list
  2293. CCryEditApp::instance()->AddToRecentFileList(fullyQualifiedLevelName);
  2294. GetIEditor()->Notify(eNotify_OnEndCreate);
  2295. CrySystemEventBus::Broadcast(&CrySystemEventBus::Events::OnCryEditorEndCreate);
  2296. return ECLR_OK;
  2297. }
  2298. //////////////////////////////////////////////////////////////////////////
  2299. void CCryEditApp::OnCreateLevel()
  2300. {
  2301. if (m_creatingNewLevel)
  2302. {
  2303. return;
  2304. }
  2305. bool wasCreateLevelOperationCancelled = false;
  2306. bool isNewLevelCreationSuccess = false;
  2307. // This will show the new level dialog until a valid input has been entered by the user or until the user click cancel
  2308. while (!isNewLevelCreationSuccess && !wasCreateLevelOperationCancelled)
  2309. {
  2310. wasCreateLevelOperationCancelled = false;
  2311. isNewLevelCreationSuccess = CreateLevel(wasCreateLevelOperationCancelled);
  2312. }
  2313. }
  2314. //////////////////////////////////////////////////////////////////////////
  2315. bool CCryEditApp::CreateLevel(bool& wasCreateLevelOperationCancelled)
  2316. {
  2317. bool bIsDocModified = GetIEditor()->GetDocument()->IsModified();
  2318. if (GetIEditor()->GetDocument()->IsDocumentReady() && bIsDocModified)
  2319. {
  2320. auto* prefabEditorEntityOwnershipInterface = AZ::Interface<AzToolsFramework::PrefabEditorEntityOwnershipInterface>::Get();
  2321. auto* prefabIntegrationInterface = AZ::Interface<AzToolsFramework::Prefab::PrefabIntegrationInterface>::Get();
  2322. AZ_Assert(prefabEditorEntityOwnershipInterface != nullptr, "PrefabEditorEntityOwnershipInterface is not found.");
  2323. AZ_Assert(prefabIntegrationInterface != nullptr, "PrefabIntegrationInterface is not found.");
  2324. if (prefabEditorEntityOwnershipInterface == nullptr || prefabIntegrationInterface == nullptr)
  2325. {
  2326. return false;
  2327. }
  2328. AzToolsFramework::Prefab::TemplateId rootPrefabTemplateId = prefabEditorEntityOwnershipInterface->GetRootPrefabTemplateId();
  2329. int prefabSaveSelection = prefabIntegrationInterface->HandleRootPrefabClosure(rootPrefabTemplateId);
  2330. // In order to get the accept and reject codes of QDialog and QDialogButtonBox aligned, we do (1-prefabSaveSelection) here.
  2331. // For example, QDialog::Rejected(0) is emitted when dialog is closed. But the int value corresponds to
  2332. // QDialogButtonBox::AcceptRole(0).
  2333. switch (1 - prefabSaveSelection)
  2334. {
  2335. case QDialogButtonBox::AcceptRole:
  2336. bIsDocModified = false;
  2337. break;
  2338. case QDialogButtonBox::RejectRole:
  2339. wasCreateLevelOperationCancelled = true;
  2340. return false;
  2341. case QDialogButtonBox::InvalidRole:
  2342. // Set Modified flag to false to prevent show Save unchanged dialog again
  2343. GetIEditor()->GetDocument()->SetModifiedFlag(false);
  2344. break;
  2345. }
  2346. }
  2347. const char* temporaryLevelName = GetIEditor()->GetDocument()->GetTemporaryLevelName();
  2348. CNewLevelDialog dlg;
  2349. dlg.m_level = "";
  2350. if (dlg.exec() != QDialog::Accepted)
  2351. {
  2352. wasCreateLevelOperationCancelled = true;
  2353. GetIEditor()->GetDocument()->SetModifiedFlag(bIsDocModified);
  2354. return false;
  2355. }
  2356. if (!GetIEditor()->GetLevelIndependentFileMan()->PromptChangedFiles())
  2357. {
  2358. return false;
  2359. }
  2360. QString levelNameWithPath = dlg.GetLevel();
  2361. QString levelName = levelNameWithPath.mid(levelNameWithPath.lastIndexOf('/') + 1);
  2362. if (levelName == temporaryLevelName && GetIEditor()->GetLevelName() != temporaryLevelName)
  2363. {
  2364. GetIEditor()->GetDocument()->DeleteTemporaryLevel();
  2365. }
  2366. if (levelName.length() == 0 || !AZ::StringFunc::Path::IsValid(levelName.toUtf8().data()))
  2367. {
  2368. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Level name is invalid, please choose another name."));
  2369. return false;
  2370. }
  2371. //Verify that we are not using the temporary level name
  2372. if (QString::compare(levelName, temporaryLevelName) == 0)
  2373. {
  2374. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Please enter a level name that is different from the temporary name."));
  2375. return false;
  2376. }
  2377. // We're about to start creating a level, so start recording errors to display at the end.
  2378. GetIEditor()->StartLevelErrorReportRecording();
  2379. QString fullyQualifiedLevelName;
  2380. ECreateLevelResult result = CreateLevel(dlg.GetTemplateName(), levelNameWithPath, fullyQualifiedLevelName);
  2381. if (result == ECLR_ALREADY_EXISTS)
  2382. {
  2383. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Level with this name already exists, please choose another name."));
  2384. return false;
  2385. }
  2386. else if (result == ECLR_DIR_CREATION_FAILED)
  2387. {
  2388. QString szLevelRoot = QStringLiteral("%1\\Levels\\%2").arg(Path::GetEditingGameDataFolder().c_str(), levelName);
  2389. QByteArray windowsErrorMessage(ERROR_LEN, 0);
  2390. QByteArray cwd(ERROR_LEN, 0);
  2391. DWORD dw = GetLastError();
  2392. #ifdef WIN32
  2393. wchar_t windowsErrorMessageW[ERROR_LEN];
  2394. windowsErrorMessageW[0] = L'\0';
  2395. FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  2396. nullptr,
  2397. dw,
  2398. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  2399. windowsErrorMessageW,
  2400. ERROR_LEN, nullptr);
  2401. _getcwd(cwd.data(), cwd.length());
  2402. AZStd::to_string(windowsErrorMessage.data(), ERROR_LEN, windowsErrorMessageW);
  2403. #else
  2404. windowsErrorMessage = strerror(dw);
  2405. cwd = QDir::currentPath().toUtf8();
  2406. #endif
  2407. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Failed to create level directory: %1\n Error: %2\nCurrent Path: %3").arg(szLevelRoot, windowsErrorMessage, cwd));
  2408. return false;
  2409. }
  2410. else if (result == ECLR_MAX_PATH_EXCEEDED)
  2411. {
  2412. QFileInfo info(fullyQualifiedLevelName);
  2413. const AZStd::string rawProjectDirectory = Path::GetEditingGameDataFolder();
  2414. const QString projectDirectory = QDir::toNativeSeparators(QString::fromUtf8(rawProjectDirectory.data(), static_cast<int>(rawProjectDirectory.size())));
  2415. const QString elidedLevelName = QStringLiteral("%1...%2").arg(levelName.left(10)).arg(levelName.right(10));
  2416. const QString elidedLevelFileName = QStringLiteral("%1...%2").arg(info.fileName().left(10)).arg(info.fileName().right(10));
  2417. const QString message = QObject::tr(
  2418. "The fully-qualified path for the new level exceeds the maximum supported path length of %1 characters (it's %2 characters long). Please choose a smaller name.\n\n"
  2419. "The fully-qualified path is made up of the project folder (\"%3\", %4 characters), the \"Levels\" sub-folder, a folder named for the level (\"%5\", %6 characters) and the level file (\"%7\", %8 characters), plus necessary separators.\n\n"
  2420. "Please also note that on most platforms, individual components of the path (folder/file names can't exceed approximately 255 characters)\n\n"
  2421. "Click \"Copy to Clipboard\" to copy the fully-qualified name and close this message.")
  2422. .arg(_MAX_PATH - 1).arg(fullyQualifiedLevelName.size())
  2423. .arg(projectDirectory).arg(projectDirectory.size())
  2424. .arg(elidedLevelName).arg(levelName.size())
  2425. .arg(elidedLevelFileName).arg(info.fileName().size());
  2426. QMessageBox messageBox(QMessageBox::Critical, QString(), message, QMessageBox::Ok, AzToolsFramework::GetActiveWindow());
  2427. QPushButton* copyButton = messageBox.addButton(QObject::tr("Copy to Clipboard"), QMessageBox::ActionRole);
  2428. QObject::connect(copyButton, &QPushButton::pressed, this, [fullyQualifiedLevelName]() { QGuiApplication::clipboard()->setText(fullyQualifiedLevelName); });
  2429. messageBox.exec();
  2430. return false;
  2431. }
  2432. // force the level being rendered at least once
  2433. m_bForceProcessIdle = true;
  2434. m_levelErrorsHaveBeenDisplayed = false;
  2435. return true;
  2436. }
  2437. //////////////////////////////////////////////////////////////////////////
  2438. void CCryEditApp::OnOpenLevel()
  2439. {
  2440. CLevelFileDialog levelFileDialog(true);
  2441. levelFileDialog.show();
  2442. levelFileDialog.adjustSize();
  2443. if (levelFileDialog.exec() == QDialog::Accepted)
  2444. {
  2445. OpenDocumentFile(levelFileDialog.GetFileName().toUtf8().data(), true, COpenSameLevelOptions::ReopenLevelIfSame);
  2446. }
  2447. }
  2448. //////////////////////////////////////////////////////////////////////////
  2449. CCryEditDoc* CCryEditApp::OpenDocumentFile(const char* filename, bool addToMostRecentFileList, COpenSameLevelOptions openSameLevelOptions)
  2450. {
  2451. if (m_openingLevel)
  2452. {
  2453. return GetIEditor()->GetDocument();
  2454. }
  2455. // If we are loading and we're in simulate mode, then switch it off before we do anything else
  2456. if (GetIEditor()->GetGameEngine() && GetIEditor()->GetGameEngine()->GetSimulationMode())
  2457. {
  2458. // Preserve the modified flag, we don't want this switch of physics to change that flag
  2459. bool bIsDocModified = GetIEditor()->GetDocument()->IsModified();
  2460. OnSwitchPhysics();
  2461. GetIEditor()->GetDocument()->SetModifiedFlag(bIsDocModified);
  2462. auto* rootSpawnableInterface = AzFramework::RootSpawnableInterface::Get();
  2463. if (rootSpawnableInterface)
  2464. {
  2465. rootSpawnableInterface->ProcessSpawnableQueue();
  2466. }
  2467. }
  2468. // We're about to start loading a level, so start recording errors to display at the end.
  2469. GetIEditor()->StartLevelErrorReportRecording();
  2470. const QScopedValueRollback<bool> rollback(m_openingLevel, true);
  2471. MainWindow::instance()->menuBar()->setEnabled(false);
  2472. CCryEditDoc* doc = nullptr;
  2473. bool bVisible = false;
  2474. bool bTriggerConsole = false;
  2475. doc = GetIEditor()->GetDocument();
  2476. bVisible = GetIEditor()->ShowConsole(true);
  2477. bTriggerConsole = true;
  2478. if (GetIEditor()->GetLevelIndependentFileMan()->PromptChangedFiles())
  2479. {
  2480. SandboxEditor::StartupTraceHandler openDocTraceHandler;
  2481. openDocTraceHandler.StartCollection();
  2482. if (m_bAutotestMode)
  2483. {
  2484. openDocTraceHandler.SetShowWindow(false);
  2485. }
  2486. // in this case, we set addToMostRecentFileList to always be true because adding files to the MRU list
  2487. // automatically culls duplicate and normalizes paths anyway
  2488. m_pDocManager->OpenDocumentFile(filename, addToMostRecentFileList, openSameLevelOptions);
  2489. if (openDocTraceHandler.HasAnyErrors())
  2490. {
  2491. doc->SetHasErrors();
  2492. }
  2493. }
  2494. if (bTriggerConsole)
  2495. {
  2496. GetIEditor()->ShowConsole(bVisible);
  2497. }
  2498. MainWindow::instance()->menuBar()->setEnabled(true);
  2499. m_levelErrorsHaveBeenDisplayed = false;
  2500. return doc; // the API wants a CDocument* to be returned. It seems not to be used, though, in our current state.
  2501. }
  2502. //////////////////////////////////////////////////////////////////////////
  2503. void CCryEditApp::OnResourcesReduceworkingset()
  2504. {
  2505. #ifdef WIN32 // no such thing on macOS
  2506. SetProcessWorkingSetSize(GetCurrentProcess(), std::numeric_limits<SIZE_T>::max(), std::numeric_limits<SIZE_T>::max());
  2507. #endif
  2508. }
  2509. void CCryEditApp::OnUpdateWireframe(QAction* action)
  2510. {
  2511. Q_ASSERT(action->isCheckable());
  2512. int nWireframe(R_SOLID_MODE);
  2513. ICVar* r_wireframe(gEnv->pConsole->GetCVar("r_wireframe"));
  2514. if (r_wireframe)
  2515. {
  2516. nWireframe = r_wireframe->GetIVal();
  2517. }
  2518. action->setChecked(nWireframe == R_WIREFRAME_MODE);
  2519. }
  2520. //////////////////////////////////////////////////////////////////////////
  2521. void CCryEditApp::OnViewConfigureLayout()
  2522. {
  2523. if (GetIEditor()->IsInGameMode())
  2524. {
  2525. // you may not change your viewports while game mode is running.
  2526. CryLog("You may not change viewport configuration while in game mode.");
  2527. return;
  2528. }
  2529. CLayoutWnd* layout = GetIEditor()->GetViewManager()->GetLayout();
  2530. if (layout)
  2531. {
  2532. CLayoutConfigDialog dlg;
  2533. dlg.SetLayout(layout->GetLayout());
  2534. if (dlg.exec() == QDialog::Accepted)
  2535. {
  2536. // Will kill this Pane. so must be last line in this function.
  2537. layout->CreateLayout(dlg.GetLayout());
  2538. }
  2539. }
  2540. }
  2541. //////////////////////////////////////////////////////////////////////////
  2542. void CCryEditApp::OnToolsLogMemoryUsage()
  2543. {
  2544. gEnv->pConsole->ExecuteString("SaveLevelStats");
  2545. }
  2546. //////////////////////////////////////////////////////////////////////////
  2547. void CCryEditApp::OnCustomizeKeyboard()
  2548. {
  2549. MainWindow::instance()->OnCustomizeToolbar();
  2550. }
  2551. //////////////////////////////////////////////////////////////////////////
  2552. void CCryEditApp::OnToolsScriptHelp()
  2553. {
  2554. AzToolsFramework::CScriptHelpDialog::GetInstance()->show();
  2555. }
  2556. //////////////////////////////////////////////////////////////////////////
  2557. void CCryEditApp::OnViewCycle2dviewport()
  2558. {
  2559. GetIEditor()->GetViewManager()->Cycle2DViewport();
  2560. }
  2561. //////////////////////////////////////////////////////////////////////////
  2562. void CCryEditApp::OnDisplayGotoPosition()
  2563. {
  2564. GotoPositionDialog dialog;
  2565. dialog.exec();
  2566. }
  2567. //////////////////////////////////////////////////////////////////////////
  2568. void CCryEditApp::OnFileSavelevelresources()
  2569. {
  2570. CGameResourcesExporter saver;
  2571. saver.GatherAllLoadedResources();
  2572. saver.ChooseDirectoryAndSave();
  2573. }
  2574. //////////////////////////////////////////////////////////////////////////
  2575. void CCryEditApp::OnClearRegistryData()
  2576. {
  2577. if (QMessageBox::warning(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Clear all sandbox registry data ?"),
  2578. QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
  2579. {
  2580. QSettings settings;
  2581. settings.clear();
  2582. }
  2583. }
  2584. //////////////////////////////////////////////////////////////////////////
  2585. void CCryEditApp::OnToolsPreferences()
  2586. {
  2587. EditorPreferencesDialog dlg(MainWindow::instance());
  2588. dlg.exec();
  2589. }
  2590. //////////////////////////////////////////////////////////////////////////
  2591. void CCryEditApp::OnSwitchToDefaultCamera()
  2592. {
  2593. }
  2594. //////////////////////////////////////////////////////////////////////////
  2595. void CCryEditApp::OnUpdateSwitchToDefaultCamera(QAction* action)
  2596. {
  2597. Q_ASSERT(action->isCheckable());
  2598. {
  2599. action->setEnabled(false);
  2600. }
  2601. }
  2602. //////////////////////////////////////////////////////////////////////////
  2603. void CCryEditApp::OnSwitchToSequenceCamera()
  2604. {
  2605. }
  2606. //////////////////////////////////////////////////////////////////////////
  2607. void CCryEditApp::OnUpdateSwitchToSequenceCamera(QAction* action)
  2608. {
  2609. Q_ASSERT(action->isCheckable());
  2610. {
  2611. action->setEnabled(false);
  2612. }
  2613. }
  2614. //////////////////////////////////////////////////////////////////////////
  2615. void CCryEditApp::OnSwitchToSelectedcamera()
  2616. {
  2617. }
  2618. //////////////////////////////////////////////////////////////////////////
  2619. void CCryEditApp::OnUpdateSwitchToSelectedCamera(QAction* action)
  2620. {
  2621. Q_ASSERT(action->isCheckable());
  2622. {
  2623. action->setEnabled(false);
  2624. }
  2625. }
  2626. //////////////////////////////////////////////////////////////////////////
  2627. void CCryEditApp::OnSwitchcameraNext()
  2628. {
  2629. }
  2630. //////////////////////////////////////////////////////////////////////////
  2631. void CCryEditApp::OnOpenAssetBrowserView()
  2632. {
  2633. QtViewPaneManager::instance()->OpenPane(LyViewPane::AssetBrowser);
  2634. }
  2635. //////////////////////////////////////////////////////////////////////////
  2636. void CCryEditApp::OnOpenTrackView()
  2637. {
  2638. QtViewPaneManager::instance()->OpenPane(LyViewPane::TrackView);
  2639. }
  2640. //////////////////////////////////////////////////////////////////////////
  2641. void CCryEditApp::OnOpenAudioControlsEditor()
  2642. {
  2643. QtViewPaneManager::instance()->OpenPane(LyViewPane::AudioControlsEditor);
  2644. }
  2645. //////////////////////////////////////////////////////////////////////////
  2646. void CCryEditApp::OnOpenUICanvasEditor()
  2647. {
  2648. QtViewPaneManager::instance()->OpenPane(LyViewPane::UiEditor);
  2649. }
  2650. //////////////////////////////////////////////////////////////////////////
  2651. RecentFileList* CCryEditApp::GetRecentFileList()
  2652. {
  2653. static RecentFileList list;
  2654. return &list;
  2655. };
  2656. //////////////////////////////////////////////////////////////////////////
  2657. void CCryEditApp::AddToRecentFileList(const QString& lpszPathName)
  2658. {
  2659. // In later MFC implementations (WINVER >= 0x0601) files must exist before they can be added to the recent files list.
  2660. // Here we override the new CWinApp::AddToRecentFileList code with the old implementation to remove this requirement.
  2661. if (IsInAutotestMode())
  2662. {
  2663. // Never add to the recent file list when in auto test mode
  2664. // This would cause issues for devs running tests locally impacting their normal workflows/setups
  2665. return;
  2666. }
  2667. if (GetRecentFileList())
  2668. {
  2669. GetRecentFileList()->Add(lpszPathName);
  2670. }
  2671. // write the list immediately so it will be remembered even after a crash
  2672. if (GetRecentFileList())
  2673. {
  2674. GetRecentFileList()->WriteList();
  2675. }
  2676. else
  2677. {
  2678. CLogFile::WriteLine("ERROR: Recent File List is NULL!");
  2679. }
  2680. }
  2681. //////////////////////////////////////////////////////////////////////////
  2682. bool CCryEditApp::IsInRegularEditorMode()
  2683. {
  2684. return !IsInTestMode() && !IsInPreviewMode()
  2685. && !IsInExportMode() && !IsInConsoleMode() && !IsInLevelLoadTestMode();
  2686. }
  2687. void CCryEditApp::SetEditorWindowTitle(QString sTitleStr, QString sPreTitleStr, QString sPostTitleStr)
  2688. {
  2689. if (MainWindow::instance() || m_pConsoleDialog)
  2690. {
  2691. if (sTitleStr.isEmpty())
  2692. {
  2693. sTitleStr = QObject::tr("O3DE Editor [%1]").arg(FormatVersion(m_pEditor->GetFileVersion()));
  2694. }
  2695. if (!sPreTitleStr.isEmpty())
  2696. {
  2697. sTitleStr.insert(sTitleStr.length(), QStringLiteral(" - %1").arg(sPreTitleStr));
  2698. }
  2699. if (!sPostTitleStr.isEmpty())
  2700. {
  2701. sTitleStr.insert(sTitleStr.length(), QStringLiteral(" - %1").arg(sPostTitleStr));
  2702. }
  2703. MainWindow::instance()->setWindowTitle(sTitleStr);
  2704. if (m_pConsoleDialog)
  2705. {
  2706. m_pConsoleDialog->setWindowTitle(sTitleStr);
  2707. }
  2708. }
  2709. }
  2710. bool CCryEditApp::Command_ExportToEngine()
  2711. {
  2712. return CCryEditApp::instance()->UserExportToGame(true);
  2713. }
  2714. CMainFrame * CCryEditApp::GetMainFrame() const
  2715. {
  2716. return MainWindow::instance()->GetOldMainFrame();
  2717. }
  2718. void CCryEditApp::OpenExternalLuaDebugger(AZStd::string_view luaDebuggerUri, AZStd::string_view projectPath, AZStd::string_view enginePath, const char* files)
  2719. {
  2720. // Put together the whole Url Query String:
  2721. QUrlQuery query;
  2722. query.addQueryItem("projectPath", QString::fromUtf8(projectPath.data(), aznumeric_cast<int>(projectPath.size())));
  2723. if (!enginePath.empty())
  2724. {
  2725. query.addQueryItem("enginePath", QString::fromUtf8(enginePath.data(), aznumeric_cast<int>(enginePath.size())));
  2726. }
  2727. auto ParseFilesList = [&](AZStd::string_view filePath)
  2728. {
  2729. bool fullPathFound = false;
  2730. auto GetFullSourcePath = [&]
  2731. (AzToolsFramework::AssetSystem::AssetSystemRequest* assetSystemRequests)
  2732. {
  2733. AZ::IO::Path assetFullPath;
  2734. if(assetSystemRequests->GetFullSourcePathFromRelativeProductPath(filePath, assetFullPath.Native()))
  2735. {
  2736. fullPathFound = true;
  2737. query.addQueryItem("files[]", QString::fromUtf8(assetFullPath.c_str()));
  2738. }
  2739. };
  2740. AzToolsFramework::AssetSystemRequestBus::Broadcast(AZStd::move(GetFullSourcePath));
  2741. // If the full source path could be found through the Asset System, then
  2742. // attempt to resolve the path using the FileIO instance
  2743. if (!fullPathFound)
  2744. {
  2745. AZ::IO::FixedMaxPath resolvedFilePath;
  2746. if (auto fileIo = AZ::IO::FileIOBase::GetInstance();
  2747. fileIo != nullptr && fileIo->ResolvePath(resolvedFilePath, filePath)
  2748. && fileIo->Exists(resolvedFilePath.c_str()))
  2749. {
  2750. query.addQueryItem("files[]", QString::fromUtf8(resolvedFilePath.c_str()));
  2751. }
  2752. }
  2753. };
  2754. AZ::StringFunc::TokenizeVisitor(files, ParseFilesList, "|");
  2755. QUrl luaDebuggerUrl(QString::fromUtf8(luaDebuggerUri.data(), aznumeric_cast<int>(luaDebuggerUri.size())));
  2756. luaDebuggerUrl.setQuery(query);
  2757. AZ_VerifyError("CCryEditApp", Platform::OpenUri(luaDebuggerUrl),
  2758. "Failed to start external lua debugger with URI: %s", luaDebuggerUrl.toString().toUtf8().constData());
  2759. }
  2760. void CCryEditApp::OpenLUAEditor(const char* files)
  2761. {
  2762. AZ::IO::FixedMaxPathString enginePath = AZ::Utils::GetEnginePath();
  2763. AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath();
  2764. auto registry = AZ::SettingsRegistry::Get();
  2765. if (registry)
  2766. {
  2767. AZStd::string luaDebuggerUri;
  2768. if (registry->Get(luaDebuggerUri, LuaDebuggerUriRegistryKey))
  2769. {
  2770. OpenExternalLuaDebugger(luaDebuggerUri, projectPath, enginePath, files);
  2771. return;
  2772. }
  2773. }
  2774. AZStd::string filename = "LuaIDE";
  2775. AZ::IO::FixedMaxPath executablePath = AZ::Utils::GetExecutableDirectory();
  2776. executablePath /= filename + AZ_TRAIT_OS_EXECUTABLE_EXTENSION;
  2777. if (!AZ::IO::SystemFile::Exists(executablePath.c_str()))
  2778. {
  2779. AZ_Error("LuaIDE", false, "%s not found", executablePath.c_str());
  2780. return;
  2781. }
  2782. AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo;
  2783. AZStd::vector<AZStd::string> launchCmd = { executablePath.String() };
  2784. launchCmd.emplace_back("--engine-path");
  2785. launchCmd.emplace_back(AZStd::string_view{ enginePath });
  2786. launchCmd.emplace_back("--project-path");
  2787. launchCmd.emplace_back(AZStd::string_view{ projectPath });
  2788. launchCmd.emplace_back("--launch");
  2789. launchCmd.emplace_back("lua");
  2790. auto ParseFilesList = [&launchCmd](AZStd::string_view filePath)
  2791. {
  2792. bool fullPathFound = false;
  2793. auto GetFullSourcePath = [&launchCmd, &filePath, &fullPathFound]
  2794. (AzToolsFramework::AssetSystem::AssetSystemRequest* assetSystemRequests)
  2795. {
  2796. AZ::IO::Path assetFullPath;
  2797. if(assetSystemRequests->GetFullSourcePathFromRelativeProductPath(filePath, assetFullPath.Native()))
  2798. {
  2799. fullPathFound = true;
  2800. launchCmd.emplace_back("--files");
  2801. launchCmd.emplace_back(AZStd::move(assetFullPath.Native()));
  2802. }
  2803. };
  2804. AzToolsFramework::AssetSystemRequestBus::Broadcast(AZStd::move(GetFullSourcePath));
  2805. // If the full source path could be found through the Asset System, then
  2806. // attempt to resolve the path using the FileIO instance
  2807. if (!fullPathFound)
  2808. {
  2809. AZ::IO::FixedMaxPath resolvedFilePath;
  2810. if (auto fileIo = AZ::IO::FileIOBase::GetInstance();
  2811. fileIo != nullptr && fileIo->ResolvePath(resolvedFilePath, filePath)
  2812. && fileIo->Exists(resolvedFilePath.c_str()))
  2813. {
  2814. launchCmd.emplace_back("--files");
  2815. launchCmd.emplace_back(resolvedFilePath.String());
  2816. }
  2817. }
  2818. };
  2819. AZ::StringFunc::TokenizeVisitor(files, ParseFilesList, "|");
  2820. processLaunchInfo.m_commandlineParameters = AZStd::move(launchCmd);
  2821. AZ_VerifyError("LuaIDE", AzFramework::ProcessLauncher::LaunchUnwatchedProcess(processLaunchInfo),
  2822. "Lua IDE has failed to launch at path %s", executablePath.c_str());
  2823. }
  2824. void CCryEditApp::PrintAlways(const AZStd::string& output)
  2825. {
  2826. m_stdoutRedirection.WriteBypassingRedirect(output.c_str(), static_cast<unsigned int>(output.size()));
  2827. }
  2828. QString CCryEditApp::GetRootEnginePath() const
  2829. {
  2830. return m_rootEnginePath;
  2831. }
  2832. void CCryEditApp::RedirectStdoutToNull()
  2833. {
  2834. m_stdoutRedirection.RedirectTo(AZ::IO::SystemFile::GetNullFilename());
  2835. }
  2836. void CCryEditApp::OnError(AzFramework::AssetSystem::AssetSystemErrors error)
  2837. {
  2838. AZStd::string errorMessage = "";
  2839. switch (error)
  2840. {
  2841. case AzFramework::AssetSystem::ASSETSYSTEM_FAILED_TO_LAUNCH_ASSETPROCESSOR:
  2842. errorMessage = AZStd::string::format("Failed to start the Asset Processor.\r\nPlease make sure that AssetProcessor is available in the same folder the Editor is in.\r\n");
  2843. break;
  2844. case AzFramework::AssetSystem::ASSETSYSTEM_FAILED_TO_CONNECT_TO_ASSETPROCESSOR:
  2845. errorMessage = AZStd::string::format("Failed to connect to the Asset Processor.\r\nPlease make sure that AssetProcessor is available in the same folder the Editor is in and another copy is not already running somewhere else.\r\n");
  2846. break;
  2847. }
  2848. QMessageBox::critical(nullptr,"Error",errorMessage.c_str());
  2849. }
  2850. void CCryEditApp::OnOpenProceduralMaterialEditor()
  2851. {
  2852. QtViewPaneManager::instance()->OpenPane(LyViewPane::SubstanceEditor);
  2853. }
  2854. namespace Editor
  2855. {
  2856. //! This function returns the build system target name
  2857. AZStd::string_view GetBuildTargetName()
  2858. {
  2859. #if !defined (LY_CMAKE_TARGET)
  2860. #error "LY_CMAKE_TARGET must be defined in order to add this source file to a CMake executable target"
  2861. #endif
  2862. return AZStd::string_view{ LY_CMAKE_TARGET };
  2863. }
  2864. }
  2865. #if defined(AZ_PLATFORM_WINDOWS)
  2866. //Due to some laptops not autoswitching to the discrete gpu correctly we are adding these
  2867. //dllspecs as defined in the amd and nvidia white papers to 'force on' the use of the
  2868. //discrete chips. This will be overriden by users setting application profiles
  2869. //and may not work on older drivers or bios. In theory this should be enough to always force on
  2870. //the discrete chips.
  2871. //http://developer.download.nvidia.com/devzone/devcenter/gamegraphics/files/OptimusRenderingPolicies.pdf
  2872. //https://community.amd.com/thread/169965
  2873. // It is unclear if this is also needed for linux or osx at this time(22/02/2017)
  2874. extern "C"
  2875. {
  2876. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  2877. __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
  2878. }
  2879. #endif
  2880. #ifdef Q_OS_WIN
  2881. #pragma comment(lib, "Shell32.lib")
  2882. #endif
  2883. extern "C" int AZ_DLL_EXPORT CryEditMain(int argc, char* argv[])
  2884. {
  2885. // Debugging utilities
  2886. for (int i = 1; i < argc; ++i)
  2887. {
  2888. if (azstricmp(argv[i], "--attach-debugger") == 0)
  2889. {
  2890. AZ::Debug::Trace::AttachDebugger();
  2891. }
  2892. else if (azstricmp(argv[i], "--wait-for-debugger") == 0)
  2893. {
  2894. AZ::Debug::Trace::WaitForDebugger();
  2895. }
  2896. }
  2897. // ensure the EditorEventsBus context gets created inside EditorLib
  2898. [[maybe_unused]] const auto& editorEventsContext = AzToolsFramework::EditorEvents::Bus::GetOrCreateContext();
  2899. // connect relevant buses to global settings
  2900. gSettings.Connect();
  2901. auto theApp = AZStd::make_unique<CCryEditApp>();
  2902. // Must be set before QApplication is initialized, so that we support HighDpi monitors, like the Retina displays
  2903. // on Windows 10
  2904. QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  2905. QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
  2906. QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  2907. // QtOpenGL attributes and surface format setup.
  2908. QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true);
  2909. QSurfaceFormat format = QSurfaceFormat::defaultFormat();
  2910. format.setDepthBufferSize(24);
  2911. format.setStencilBufferSize(8);
  2912. format.setVersion(2, 1);
  2913. format.setProfile(QSurfaceFormat::CoreProfile);
  2914. format.setSamples(8);
  2915. format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
  2916. format.setRenderableType(QSurfaceFormat::OpenGL);
  2917. format.setSwapInterval(0);
  2918. #ifdef AZ_DEBUG_BUILD
  2919. format.setOption(QSurfaceFormat::DebugContext);
  2920. #endif
  2921. QSurfaceFormat::setDefaultFormat(format);
  2922. Editor::EditorQtApplication::InstallQtLogHandler();
  2923. AzQtComponents::Utilities::HandleDpiAwareness(AzQtComponents::Utilities::SystemDpiAware);
  2924. Editor::EditorQtApplication* app = Editor::EditorQtApplication::newInstance(argc, argv);
  2925. QStringList qArgs = app->arguments();
  2926. const bool is_automated_test = AZStd::any_of(qArgs.begin(), qArgs.end(),
  2927. [](const QString& elem)
  2928. {
  2929. return elem.endsWith("autotest_mode") || elem.endsWith("runpythontest");
  2930. }
  2931. );
  2932. if (is_automated_test)
  2933. {
  2934. // Nullroute all stdout to null for automated tests, this way we make sure
  2935. // that the test result output is not polluted with unrelated output data.
  2936. theApp->RedirectStdoutToNull();
  2937. }
  2938. // Hook the trace bus to catch errors, boot the AZ app after the QApplication is up
  2939. int ret = 0;
  2940. // open a scope to contain the AZToolsApp instance;
  2941. {
  2942. EditorInternal::EditorToolsApplication AZToolsApp(&argc, &argv);
  2943. {
  2944. CEditCommandLineInfo cmdInfo;
  2945. if (!cmdInfo.m_bAutotestMode && !cmdInfo.m_bConsoleMode && !cmdInfo.m_bExport && !cmdInfo.m_bExportTexture &&
  2946. !cmdInfo.m_bNullRenderer && !cmdInfo.m_bTest)
  2947. {
  2948. if (auto nativeUI = AZ::Interface<AZ::NativeUI::NativeUIRequests>::Get(); nativeUI != nullptr)
  2949. {
  2950. nativeUI->SetMode(AZ::NativeUI::Mode::ENABLED);
  2951. }
  2952. }
  2953. }
  2954. // The settings registry has been created by the AZ::ComponentApplication constructor at this point
  2955. AZ::SettingsRegistryInterface& registry = *AZ::SettingsRegistry::Get();
  2956. AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_AddBuildSystemTargetSpecialization(
  2957. registry, Editor::GetBuildTargetName());
  2958. AZ::Interface<AZ::IConsole>::Get()->PerformCommand("sv_isDedicated false");
  2959. if (!AZToolsApp.Start())
  2960. {
  2961. return -1;
  2962. }
  2963. AzToolsFramework::EditorEvents::Bus::Broadcast(&AzToolsFramework::EditorEvents::NotifyQtApplicationAvailable, app);
  2964. int exitCode = 0;
  2965. bool didCryEditStart = CCryEditApp::instance()->InitInstance();
  2966. AZ_Error("Editor", didCryEditStart, "O3DE Editor did not initialize correctly, and will close."
  2967. "\nThis could be because of incorrectly configured components, or missing required gems."
  2968. "\nSee other errors for more details.");
  2969. AzToolsFramework::EditorEventsBus::Broadcast(&AzToolsFramework::EditorEvents::NotifyEditorInitialized);
  2970. if (didCryEditStart)
  2971. {
  2972. app->EnableOnIdle();
  2973. ret = app->exec();
  2974. }
  2975. else
  2976. {
  2977. exitCode = 1;
  2978. }
  2979. CCryEditApp::instance()->ExitInstance(exitCode);
  2980. }
  2981. delete app;
  2982. gSettings.Disconnect();
  2983. return ret;
  2984. }
  2985. AZ_DECLARE_MODULE_INITIALIZATION
  2986. #include <moc_CryEdit.cpp>