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