CryEdit.cpp 120 KB

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