guiCanvas.cpp 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "gui/core/guiCanvas.h"
  28. #include "console/console.h"
  29. #include "console/engineAPI.h"
  30. #include "platform/profiler.h"
  31. #include "gfx/gfxDevice.h"
  32. #include "gfx/gfxDrawUtil.h"
  33. #include "gui/core/guiTypes.h"
  34. #include "gui/core/guiControl.h"
  35. #include "gui/editor/guiMenuBar.h"
  36. #include "console/consoleTypes.h"
  37. #include "gfx/screenshot.h"
  38. #include "gfx/video/videoCapture.h"
  39. #include "lighting/lightManager.h"
  40. #include "core/strings/stringUnit.h"
  41. #include "gui/core/guiOffscreenCanvas.h"
  42. #ifndef TORQUE_TGB_ONLY
  43. #include "scene/sceneObject.h"
  44. #endif
  45. #include "gfx/gfxInit.h"
  46. #include "core/util/journal/process.h"
  47. #ifdef TORQUE_GFX_STATE_DEBUG
  48. #include "gfx/gfxDebugStateTracker.h"
  49. #endif
  50. IMPLEMENT_CONOBJECT(GuiCanvas);
  51. ConsoleDocClass( GuiCanvas,
  52. "@brief A canvas on which rendering occurs.\n\n"
  53. "@section GuiCanvas_contents What a GUICanvas Can Contain...\n\n"
  54. "@subsection GuiCanvas_content_contentcontrol Content Control\n"
  55. "A content control is the top level GuiControl for a screen. This GuiControl "
  56. "will be the parent control for all other GuiControls on that particular "
  57. "screen.\n\n"
  58. "@subsection GuiCanvas_content_dialogs Dialogs\n\n"
  59. "A dialog is essentially another screen, only it gets overlaid on top of the "
  60. "current content control, and all input goes to the dialog. This is most akin "
  61. "to the \"Open File\" dialog box found in most operating systems. When you "
  62. "choose to open a file, and the \"Open File\" dialog pops up, you can no longer "
  63. "send input to the application, and must complete or cancel the open file "
  64. "request. Torque keeps track of layers of dialogs. The dialog with the highest "
  65. "layer is on top and will get all the input, unless the dialog is "
  66. "modeless, which is a profile option.\n\n"
  67. "@see GuiControlProfile\n\n"
  68. "@section GuiCanvas_dirty Dirty Rectangles\n\n"
  69. "The GuiCanvas is based on dirty regions. "
  70. "Every frame the canvas paints only the areas of the canvas that are 'dirty' "
  71. "or need updating. In most cases, this only is the area under the mouse cursor. "
  72. "This is why if you look in guiCanvas.cc the call to glClear is commented out. "
  73. "What you will see is a black screen, except in the dirty regions, where the "
  74. "screen will be painted normally. If you are making an animated GuiControl "
  75. "you need to add your control to the dirty areas of the canvas.\n\n"
  76. "@see GuiControl\n\n"
  77. "@ingroup GuiCore\n");
  78. ColorI gCanvasClearColor( 255, 0, 255 ); ///< For GFX->clear
  79. extern InputModifiers convertModifierBits(const U32 in);
  80. //-----------------------------------------------------------------------------
  81. GuiCanvas::GuiCanvas(): GuiControl(),
  82. mCurUpdateRect(0, 0, 0, 0),
  83. mCursorEnabled(true),
  84. mForceMouseToGUI(false),
  85. mAlwaysHandleMouseButtons(false),
  86. mShowCursor(true),
  87. mClampTorqueCursor(true),
  88. mCursorChanged(0),
  89. mLastCursorEnabled(false),
  90. mMouseCapturedControl(NULL),
  91. mMouseControl(NULL),
  92. mMouseControlClicked(false),
  93. mMouseButtonDown(false),
  94. mMouseRightButtonDown(false),
  95. mDefaultCursor(NULL),
  96. mMouseMiddleButtonDown(false),
  97. mCursorPt(0,0),
  98. mLastCursorPt(0,0),
  99. mLastCursor(NULL),
  100. mLastMouseClickCount(0),
  101. mRenderFront(false),
  102. mPrevMouseTime(0),
  103. mLastMouseDownTime(0),
  104. mHoverControl(NULL),
  105. mHoverPositionSet(false),
  106. mLeftMouseLast(false),
  107. mHoverLeftControlTime(0),
  108. mMiddleMouseLast(false),
  109. mRightMouseLast(false),
  110. mMouseDownPoint(0.0f,0.0f),
  111. mLastRenderMs(0),
  112. mPlatformWindow(NULL),
  113. mDisplayWindow(true),
  114. mMenuBarCtrl(nullptr),
  115. mMenuBackground(nullptr)
  116. {
  117. setBounds(0, 0, 640, 480);
  118. mAwake = true;
  119. mHoverControlStart = Platform::getRealMilliseconds();
  120. mHoverPosition = getCursorPos();
  121. mFences = NULL;
  122. mNextFenceIdx = -1;
  123. #ifndef _XBOX
  124. mNumFences = Con::getIntVariable( "$pref::Video::defaultFenceCount", 0 );
  125. #else
  126. mNumFences = 0;
  127. #endif
  128. mConsumeLastInputEvent = false;
  129. }
  130. GuiCanvas::~GuiCanvas()
  131. {
  132. SAFE_DELETE(mPlatformWindow);
  133. SAFE_DELETE_ARRAY( mFences );
  134. }
  135. //------------------------------------------------------------------------------
  136. bool GuiCanvas::setProtectedNumFences( void *object, const char *index, const char *data)
  137. {
  138. GuiCanvas *canvas = reinterpret_cast<GuiCanvas *>( object );
  139. canvas->mNumFences = dAtoi( data );
  140. canvas->setupFences();
  141. return false;
  142. }
  143. void GuiCanvas::initPersistFields()
  144. {
  145. addGroup("Mouse Handling");
  146. addField("alwaysHandleMouseButtons", TypeBool, Offset(mAlwaysHandleMouseButtons, GuiCanvas),
  147. "Deal with mouse buttons, even if the cursor is hidden." );
  148. endGroup("Mouse Handling");
  149. addGroup("Canvas Rendering");
  150. addProtectedField( "numFences", TypeS32, Offset( mNumFences, GuiCanvas ), &setProtectedNumFences, &defaultProtectedGetFn, "The number of GFX fences to use." );
  151. addField("displayWindow", TypeBool, Offset(mDisplayWindow, GuiCanvas), "Controls if the canvas window is rendered or not." );
  152. endGroup("Canvas Rendering");
  153. Parent::initPersistFields();
  154. }
  155. //------------------------------------------------------------------------------
  156. bool GuiCanvas::onAdd()
  157. {
  158. // ensure that we have a cursor
  159. setCursor(dynamic_cast<GuiCursor*>(Sim::findObject("DefaultCursor")));
  160. // Enumerate things for GFX before we have an active device.
  161. GFXInit::enumerateAdapters();
  162. // Create a device.
  163. GFXAdapter *a = GFXInit::getBestAdapterChoice();
  164. // Do we have a global device already? (This is the site if you want
  165. // to start rendering to multiple devices simultaneously)
  166. GFXDevice *newDevice = GFX;
  167. if(newDevice == NULL)
  168. newDevice = GFXInit::createDevice(a);
  169. newDevice->setAllowRender( false );
  170. // Disable starting a new journal recording or playback from here on
  171. Journal::Disable();
  172. // Initialize the window...
  173. GFXVideoMode vm = GFXInit::getInitialVideoMode();
  174. //If we're recording, store the intial video resolution
  175. if (Journal::IsRecording())
  176. {
  177. Journal::Write(vm.resolution.x);
  178. Journal::Write(vm.resolution.y);
  179. Journal::Write(vm.fullScreen);
  180. }
  181. //If we're playing, read the intial video resolution from the journal
  182. if (Journal::IsPlaying())
  183. {
  184. Journal::Read(&vm.resolution.x);
  185. Journal::Read(&vm.resolution.y);
  186. Journal::Read(&vm.fullScreen);
  187. }
  188. if (a && a->mType != NullDevice)
  189. {
  190. mPlatformWindow = WindowManager->createWindow(newDevice, vm);
  191. //Disable window resizing if recording ir playing a journal
  192. if (Journal::IsRecording() || Journal::IsPlaying())
  193. mPlatformWindow->lockSize(true);
  194. // Set a minimum on the window size so people can't break us by resizing tiny.
  195. mPlatformWindow->setMinimumWindowSize(Point2I(Con::getIntVariable("$Video::minimumXResolution", 1024),
  196. Con::getIntVariable("$Video::minimumYResolution", 720)));
  197. // Now, we have to hook in our event callbacks so we'll get
  198. // appropriate events from the window.
  199. mPlatformWindow->resizeEvent .notify(this, &GuiCanvas::handleResize);
  200. mPlatformWindow->appEvent .notify(this, &GuiCanvas::handleAppEvent);
  201. mPlatformWindow->displayEvent.notify(this, &GuiCanvas::handlePaintEvent);
  202. mPlatformWindow->setInputController( dynamic_cast<IProcessInput*>(this) );
  203. }
  204. // Need to get painted, too! :)
  205. Process::notify(this, &GuiCanvas::paint, PROCESS_RENDER_ORDER);
  206. // Set up the fences
  207. setupFences();
  208. // Make sure we're able to render.
  209. newDevice->setAllowRender( true );
  210. if(mDisplayWindow)
  211. {
  212. getPlatformWindow()->show();
  213. WindowManager->setDisplayWindow(true);
  214. getPlatformWindow()->setDisplayWindow(true);
  215. }
  216. else
  217. {
  218. getPlatformWindow()->hide();
  219. WindowManager->setDisplayWindow(false);
  220. getPlatformWindow()->setDisplayWindow(false);
  221. }
  222. // Propagate add to parents.
  223. // CodeReview - if GuiCanvas fails to add for whatever reason, what happens to
  224. // all the event registration above?
  225. bool parentRet = Parent::onAdd();
  226. // Define the menu bar for this canvas (if any)
  227. Con::executef(this, "onCreateMenu");
  228. return parentRet;
  229. }
  230. void GuiCanvas::onRemove()
  231. {
  232. // And the process list
  233. Process::remove(this, &GuiCanvas::paint);
  234. // Destroy the menu bar for this canvas (if any)
  235. Con::executef(this, "onDestroyMenu");
  236. Parent::onRemove();
  237. }
  238. void GuiCanvas::setMenuBar(SimObject *obj)
  239. {
  240. GuiControl *oldMenuBar = mMenuBarCtrl;
  241. mMenuBarCtrl = dynamic_cast<GuiControl*>(obj);
  242. //remove old menubar
  243. if (oldMenuBar)
  244. {
  245. Parent::removeObject(oldMenuBar);
  246. Parent::removeObject(mMenuBackground); //also remove the modeless wrapper
  247. }
  248. // set new menubar
  249. if (mMenuBarCtrl)
  250. {
  251. //Add a wrapper control so that the menubar sizes correctly
  252. GuiControlProfile* profile;
  253. Sim::findObject("GuiModelessDialogProfile", profile);
  254. if (!profile)
  255. {
  256. Con::errorf("GuiCanvas::setMenuBar: Unable to find the GuiModelessDialogProfile profile!");
  257. return;
  258. }
  259. if (mMenuBackground == nullptr)
  260. {
  261. mMenuBackground = new GuiControl();
  262. mMenuBackground->registerObject();
  263. mMenuBackground->setControlProfile(profile);
  264. }
  265. mMenuBackground->addObject(mMenuBarCtrl);
  266. Parent::addObject(mMenuBackground);
  267. }
  268. // update window accelerator keys
  269. if( oldMenuBar != mMenuBarCtrl )
  270. {
  271. GuiMenuBar* oldMenu = dynamic_cast<GuiMenuBar*>(oldMenuBar);
  272. GuiMenuBar* newMenu = dynamic_cast<GuiMenuBar*>(mMenuBarCtrl);
  273. if(oldMenu)
  274. oldMenu->removeWindowAcceleratorMap(*getPlatformWindow()->getInputGenerator());
  275. if(newMenu)
  276. newMenu->buildWindowAcceleratorMap(*getPlatformWindow()->getInputGenerator());
  277. }
  278. }
  279. void GuiCanvas::setWindowTitle(const char *newTitle)
  280. {
  281. if (mPlatformWindow)
  282. mPlatformWindow->setCaption(newTitle);
  283. }
  284. CanvasSizeChangeSignal GuiCanvas::smCanvasSizeChangeSignal;
  285. void GuiCanvas::handleResize( WindowId did, S32 width, S32 height )
  286. {
  287. getCanvasSizeChangeSignal().trigger(this);
  288. if (Journal::IsPlaying() && mPlatformWindow)
  289. {
  290. mPlatformWindow->lockSize(false);
  291. mPlatformWindow->setSize(Point2I(width, height));
  292. mPlatformWindow->lockSize(true);
  293. }
  294. // Notify the scripts
  295. if ( isMethod( "onResize" ) )
  296. Con::executef( this, "onResize", Con::getIntArg( width ), Con::getIntArg( height ) );
  297. }
  298. void GuiCanvas::handlePaintEvent(WindowId did)
  299. {
  300. bool canRender = mPlatformWindow->isVisible() && GFX->allowRender() && !GFX->canCurrentlyRender();
  301. // Do the screenshot first.
  302. if ( gScreenShot != NULL && gScreenShot->isPending() && canRender )
  303. gScreenShot->capture( this );
  304. // If the video capture is waiting for a canvas, start the capture
  305. if ( VIDCAP->isWaitingForCanvas() && canRender )
  306. VIDCAP->begin( this );
  307. // Now capture the video
  308. if ( VIDCAP->isRecording() && canRender )
  309. VIDCAP->capture();
  310. renderFrame(false);
  311. }
  312. void GuiCanvas::handleAppEvent( WindowId did, S32 event )
  313. {
  314. // Notify script if we gain or lose focus.
  315. if(event == LoseFocus)
  316. {
  317. if(isMethod("onLoseFocus"))
  318. Con::executef(this, "onLoseFocus");
  319. }
  320. if(event == GainFocus)
  321. {
  322. if(isMethod("onGainFocus"))
  323. Con::executef(this, "onGainFocus");
  324. }
  325. if(event == WindowClose || event == WindowDestroy)
  326. {
  327. if(isMethod("onWindowClose"))
  328. {
  329. // First see if there is a method on this window to handle
  330. // it's closure
  331. Con::executef(this,"onWindowClose");
  332. }
  333. else if(Con::isFunction("onWindowClose"))
  334. {
  335. // otherwise check to see if there is a global function handling it
  336. Con::executef("onWindowClose", getIdString());
  337. }
  338. else
  339. {
  340. // Else just shutdown
  341. Process::requestShutdown();
  342. }
  343. }
  344. }
  345. Point2I GuiCanvas::getWindowSize()
  346. {
  347. // CodeReview Asserting on this breaks previous logic
  348. // and code assumptions. It seems logical that we would
  349. // handle this and return an error value rather than implementing
  350. // if(!mPlatformWindow) whenever we need to call getWindowSize.
  351. // This should help keep our API error free and easy to use, while
  352. // cutting down on code duplication for sanity checking. [5/5/2007 justind]
  353. if( !mPlatformWindow )
  354. return Point2I(-1,-1);
  355. return mPlatformWindow->getClientExtent();
  356. }
  357. void GuiCanvas::enableKeyboardTranslation()
  358. {
  359. AssertISV(mPlatformWindow, "GuiCanvas::enableKeyboardTranslation - no window present!");
  360. mPlatformWindow->setKeyboardTranslation(true);
  361. }
  362. void GuiCanvas::disableKeyboardTranslation()
  363. {
  364. AssertISV(mPlatformWindow, "GuiCanvas::disableKeyboardTranslation - no window present!");
  365. mPlatformWindow->setKeyboardTranslation(false);
  366. }
  367. void GuiCanvas::setNativeAcceleratorsEnabled( bool enabled )
  368. {
  369. AssertISV(mPlatformWindow, "GuiCanvas::setNativeAcceleratorsEnabled - no window present!");
  370. mPlatformWindow->setAcceleratorsEnabled( enabled );
  371. }
  372. void GuiCanvas::setForceMouseToGUI(bool onOff)
  373. {
  374. mForceMouseToGUI = onOff;
  375. }
  376. void GuiCanvas::setClampTorqueCursor(bool onOff)
  377. {
  378. mClampTorqueCursor = onOff;
  379. }
  380. void GuiCanvas::setCursor(GuiCursor *curs)
  381. {
  382. mDefaultCursor = curs;
  383. }
  384. void GuiCanvas::setCursorON(bool onOff)
  385. {
  386. mCursorEnabled = onOff;
  387. if(!mCursorEnabled)
  388. mMouseControl = NULL;
  389. }
  390. Point2I GuiCanvas::getCursorPos()
  391. {
  392. Point2I p( 0, 0 );
  393. if( mPlatformWindow )
  394. mPlatformWindow->getCursorPosition( p );
  395. return p;
  396. }
  397. void GuiCanvas::setCursorPos(const Point2I &pt)
  398. {
  399. AssertISV(mPlatformWindow, "GuiCanvas::setCursorPos - no window present!");
  400. if ( mPlatformWindow->isMouseLocked() )
  401. {
  402. mCursorPt.x = F32( pt.x );
  403. mCursorPt.y = F32( pt.y );
  404. }
  405. else
  406. {
  407. Point2I screenPt( mPlatformWindow->clientToScreen( pt ) );
  408. mPlatformWindow->setCursorPosition( screenPt.x, screenPt.y );
  409. }
  410. }
  411. void GuiCanvas::showCursor(bool state)
  412. {
  413. mShowCursor = state;
  414. mPlatformWindow->setCursorVisible( state );
  415. }
  416. bool GuiCanvas::isCursorShown()
  417. {
  418. if ( !mPlatformWindow->getCursorController() )
  419. {
  420. return mShowCursor;
  421. }
  422. return mPlatformWindow->isCursorVisible();
  423. }
  424. void GuiCanvas::cursorClick(S32 buttonId, bool isDown)
  425. {
  426. InputEventInfo inputEvent;
  427. inputEvent.deviceType = MouseDeviceType;
  428. inputEvent.deviceInst = 0;
  429. inputEvent.objType = SI_BUTTON;
  430. inputEvent.objInst = (InputObjectInstances)(KEY_BUTTON0 + buttonId);
  431. inputEvent.modifier = (InputModifiers)0;
  432. inputEvent.ascii = 0;
  433. inputEvent.action = isDown ? SI_MAKE : SI_BREAK;
  434. inputEvent.fValue = isDown ? 1.0 : 0.0;
  435. processMouseEvent(inputEvent);
  436. }
  437. void GuiCanvas::cursorNudge(F32 x, F32 y)
  438. {
  439. // Generate a base Movement along and Axis event
  440. InputEventInfo inputEvent;
  441. inputEvent.deviceType = MouseDeviceType;
  442. inputEvent.deviceInst = 0;
  443. inputEvent.objType = SI_AXIS;
  444. inputEvent.modifier = (InputModifiers)0;
  445. inputEvent.ascii = 0;
  446. // Generate delta movement along each axis
  447. Point2F cursDelta(x, y);
  448. // If X axis changed, generate a relative event
  449. if(mFabs(cursDelta.x) > 0.1)
  450. {
  451. inputEvent.objInst = SI_XAXIS;
  452. inputEvent.action = SI_MOVE;
  453. inputEvent.fValue = cursDelta.x;
  454. processMouseEvent(inputEvent);
  455. }
  456. // If Y axis changed, generate a relative event
  457. if(mFabs(cursDelta.y) > 0.1)
  458. {
  459. inputEvent.objInst = SI_YAXIS;
  460. inputEvent.action = SI_MOVE;
  461. inputEvent.fValue = cursDelta.y;
  462. processMouseEvent(inputEvent);
  463. }
  464. processMouseEvent(inputEvent);
  465. }
  466. void GuiCanvas::addAcceleratorKey(GuiControl *ctrl, U32 index, U32 keyCode, U32 modifier)
  467. {
  468. if (keyCode > 0 && ctrl)
  469. {
  470. AccKeyMap newMap;
  471. newMap.ctrl = ctrl;
  472. newMap.index = index;
  473. newMap.keyCode = keyCode;
  474. newMap.modifier = modifier;
  475. mAcceleratorMap.push_back(newMap);
  476. }
  477. }
  478. bool GuiCanvas::tabNext(void)
  479. {
  480. GuiControl *ctrl = static_cast<GuiControl *>(last());
  481. if (ctrl)
  482. {
  483. //save the old
  484. GuiControl *oldResponder = mFirstResponder;
  485. GuiControl* newResponder = ctrl->findNextTabable(mFirstResponder);
  486. if ( !newResponder )
  487. newResponder = ctrl->findFirstTabable();
  488. if ( newResponder && newResponder != oldResponder )
  489. {
  490. newResponder->setFirstResponder();
  491. // CodeReview Can this get killed? Note tabPrev code. BJG - 3/25/07
  492. // if ( oldResponder )
  493. // oldResponder->onLoseFirstResponder();
  494. return true;
  495. }
  496. }
  497. return false;
  498. }
  499. bool GuiCanvas::tabPrev(void)
  500. {
  501. GuiControl *ctrl = static_cast<GuiControl *>(last());
  502. if (ctrl)
  503. {
  504. //save the old
  505. GuiControl *oldResponder = mFirstResponder;
  506. GuiControl* newResponder = ctrl->findPrevTabable(mFirstResponder);
  507. if ( !newResponder )
  508. newResponder = ctrl->findLastTabable();
  509. if ( newResponder && newResponder != oldResponder )
  510. {
  511. newResponder->setFirstResponder();
  512. // CodeReview As with tabNext() above, looks like this can now go. DAW - 7/05/09
  513. //if ( oldResponder )
  514. // oldResponder->onLoseFirstResponder();
  515. return true;
  516. }
  517. }
  518. return false;
  519. }
  520. bool GuiCanvas::processInputEvent(InputEventInfo &inputEvent)
  521. {
  522. mConsumeLastInputEvent = true;
  523. // First call the general input handler (on the extremely off-chance that it will be handled):
  524. if (mFirstResponder && mFirstResponder->onInputEvent(inputEvent))
  525. {
  526. return mConsumeLastInputEvent;
  527. }
  528. switch (inputEvent.deviceType)
  529. {
  530. case KeyboardDeviceType:
  531. return processKeyboardEvent(inputEvent);
  532. break;
  533. case GamepadDeviceType:
  534. return processGamepadEvent(inputEvent);
  535. break;
  536. case MouseDeviceType:
  537. if (mCursorEnabled || mForceMouseToGUI ||
  538. (mAlwaysHandleMouseButtons && inputEvent.objType == SI_BUTTON) )
  539. {
  540. return processMouseEvent(inputEvent);
  541. }
  542. break;
  543. default:
  544. break;
  545. }
  546. return false;
  547. }
  548. bool GuiCanvas::processKeyboardEvent(InputEventInfo &inputEvent)
  549. {
  550. mLastEvent.ascii = inputEvent.ascii;
  551. mLastEvent.modifier = inputEvent.modifier;
  552. mLastEvent.keyCode = inputEvent.objInst;
  553. // Combine left/right shift bits - if one shift modifier key
  554. // bit is set, then set the other one. This way we can simplify
  555. // our processing logic by treating the keys identically.
  556. U32 eventModifier = inputEvent.modifier;
  557. if(eventModifier & SI_SHIFT)
  558. {
  559. eventModifier |= SI_SHIFT;
  560. }
  561. if(eventModifier & SI_CTRL)
  562. {
  563. eventModifier |= SI_CTRL;
  564. }
  565. if(eventModifier & SI_ALT)
  566. {
  567. eventModifier |= SI_ALT;
  568. }
  569. if (inputEvent.action == SI_MAKE)
  570. {
  571. //see if we should now pass the event to the first responder
  572. if (mFirstResponder)
  573. {
  574. if(mFirstResponder->onKeyDown(mLastEvent))
  575. return mConsumeLastInputEvent;
  576. }
  577. //see if we should tab next/prev
  578. if ( isCursorON() && ( inputEvent.objInst == KEY_TAB ) )
  579. {
  580. if (size() > 0)
  581. {
  582. if (inputEvent.modifier & SI_SHIFT)
  583. {
  584. if(tabPrev())
  585. return mConsumeLastInputEvent;
  586. }
  587. else if (inputEvent.modifier == 0)
  588. {
  589. if(tabNext())
  590. return mConsumeLastInputEvent;
  591. }
  592. }
  593. }
  594. //if not handled, search for an accelerator
  595. for (U32 i = 0; i < mAcceleratorMap.size(); i++)
  596. {
  597. if ((U32)mAcceleratorMap[i].keyCode == (U32)inputEvent.objInst && (U32)mAcceleratorMap[i].modifier == eventModifier)
  598. {
  599. mAcceleratorMap[i].ctrl->acceleratorKeyPress(mAcceleratorMap[i].index);
  600. return mConsumeLastInputEvent;
  601. }
  602. }
  603. }
  604. else if(inputEvent.action == SI_BREAK)
  605. {
  606. if(mFirstResponder && mFirstResponder->onKeyUp(mLastEvent))
  607. return mConsumeLastInputEvent;
  608. //see if there's an accelerator
  609. for (U32 i = 0; i < mAcceleratorMap.size(); i++)
  610. {
  611. if ((U32)mAcceleratorMap[i].keyCode == (U32)inputEvent.objInst && (U32)mAcceleratorMap[i].modifier == eventModifier)
  612. {
  613. mAcceleratorMap[i].ctrl->acceleratorKeyRelease(mAcceleratorMap[i].index);
  614. return mConsumeLastInputEvent;
  615. }
  616. }
  617. }
  618. else if(inputEvent.action == SI_REPEAT)
  619. {
  620. //if not handled, search for an accelerator
  621. for (U32 i = 0; i < mAcceleratorMap.size(); i++)
  622. {
  623. if ((U32)mAcceleratorMap[i].keyCode == (U32)inputEvent.objInst && (U32)mAcceleratorMap[i].modifier == eventModifier)
  624. {
  625. mAcceleratorMap[i].ctrl->acceleratorKeyPress(mAcceleratorMap[i].index);
  626. return mConsumeLastInputEvent;
  627. }
  628. }
  629. if(mFirstResponder)
  630. {
  631. bool ret = mFirstResponder->onKeyRepeat(mLastEvent);
  632. return ret && mConsumeLastInputEvent;
  633. }
  634. }
  635. return false;
  636. }
  637. bool GuiCanvas::processMouseEvent(InputEventInfo &inputEvent)
  638. {
  639. // [rene 09/09/10] This custom mouse cursor tracking that is happening here is bad. It will frequently
  640. // get ouf of step with where the cursor actually is. We really should *not* track the cursor; it's
  641. // just another thing that can/will go wrong. Let the input system pass us absolute screen coordinates
  642. // for every mouse event instead and work off that.
  643. //
  644. // 'mCursorPt' basically is an accumulation of errors and the number of bugs that have cropped up with
  645. // the GUI clicking stuff where it is not supposed to are probably all to blame on this.
  646. S32 mouseDoubleClickWidth = 12;
  647. S32 mouseDoubleClickHeight = 12;
  648. U32 mouseDoubleClickTime = 500;
  649. // Query platform for mouse info if its available
  650. PlatformCursorController *pController = mPlatformWindow ? mPlatformWindow->getCursorController() : NULL;
  651. if (pController)
  652. {
  653. mouseDoubleClickWidth = pController->getDoubleClickWidth();
  654. mouseDoubleClickHeight = pController->getDoubleClickHeight();
  655. mouseDoubleClickTime = pController->getDoubleClickTime();
  656. }
  657. //copy the modifier into the new event
  658. mLastEvent.modifier = inputEvent.modifier;
  659. if(inputEvent.objType == SI_AXIS &&
  660. (inputEvent.objInst == SI_XAXIS || inputEvent.objInst == SI_YAXIS))
  661. {
  662. // Set the absolute position if we get an SI_MAKE on an axis
  663. if( inputEvent.objInst == SI_XAXIS )
  664. {
  665. if( inputEvent.action == SI_MAKE )
  666. mCursorPt.x = (S32)inputEvent.fValue;
  667. else if( inputEvent.action == SI_MOVE )
  668. mCursorPt.x += (S32)inputEvent.fValue;
  669. mCursorPt.x = getMax(0, getMin((S32)mCursorPt.x, getBounds().extent.x - 1));
  670. }
  671. else if( inputEvent.objInst == SI_YAXIS )
  672. {
  673. if( inputEvent.action == SI_MAKE )
  674. mCursorPt.y = (S32)inputEvent.fValue;
  675. else if( inputEvent.action == SI_MOVE )
  676. mCursorPt.y += (S32)inputEvent.fValue;
  677. mCursorPt.y = getMax(0, getMin((S32)mCursorPt.y, getBounds().extent.y - 1));
  678. }
  679. // Store new cursor position.
  680. mLastEvent.mousePoint.x = S32(mCursorPt.x);
  681. mLastEvent.mousePoint.y = S32(mCursorPt.y);
  682. // See if we need to invalidate a possible dbl click due to the cursor
  683. // moving too much.
  684. Point2F movement = mMouseDownPoint - mCursorPt;
  685. if ((mAbs((S32)movement.x) > mouseDoubleClickWidth) || (mAbs((S32)movement.y) > mouseDoubleClickHeight ) )
  686. {
  687. mLeftMouseLast = false;
  688. mMiddleMouseLast = false;
  689. mRightMouseLast = false;
  690. }
  691. if (mMouseButtonDown)
  692. rootMouseDragged(mLastEvent);
  693. else if (mMouseRightButtonDown)
  694. rootRightMouseDragged(mLastEvent);
  695. else if(mMouseMiddleButtonDown)
  696. rootMiddleMouseDragged(mLastEvent);
  697. else
  698. rootMouseMove(mLastEvent);
  699. return mConsumeLastInputEvent;
  700. }
  701. else if ( inputEvent.objInst == SI_ZAXIS
  702. || inputEvent.objInst == SI_RZAXIS )
  703. {
  704. mLastEvent.mousePoint.x = S32( mCursorPt.x );
  705. mLastEvent.mousePoint.y = S32( mCursorPt.y );
  706. mLastEvent.fval = inputEvent.fValue;
  707. if( inputEvent.objInst == SI_ZAXIS )
  708. mLastEvent.mouseAxis = 1;
  709. else
  710. mLastEvent.mouseAxis = 0;
  711. if ( inputEvent.fValue < 0.0f )
  712. return rootMouseWheelDown( mLastEvent );
  713. else
  714. return rootMouseWheelUp( mLastEvent );
  715. }
  716. else if(inputEvent.objType == SI_BUTTON)
  717. {
  718. //copy the cursor point into the event
  719. mLastEvent.mousePoint.x = S32(mCursorPt.x);
  720. mLastEvent.mousePoint.y = S32(mCursorPt.y);
  721. mMouseDownPoint = mCursorPt;
  722. if(inputEvent.objInst == KEY_BUTTON0) // left button
  723. {
  724. //see if button was pressed
  725. if (inputEvent.action == SI_MAKE)
  726. {
  727. U32 curTime = Platform::getVirtualMilliseconds();
  728. //if the last button pressed was the left...
  729. if (mLeftMouseLast)
  730. {
  731. //if it was within the double click time count the clicks
  732. if (curTime - mLastMouseDownTime <= mouseDoubleClickTime)
  733. mLastMouseClickCount++;
  734. else
  735. mLastMouseClickCount = 1;
  736. }
  737. else
  738. {
  739. mLeftMouseLast = true;
  740. mLastMouseClickCount = 1;
  741. }
  742. mLastMouseDownTime = curTime;
  743. mLastEvent.mouseClickCount = mLastMouseClickCount;
  744. rootMouseDown(mLastEvent);
  745. }
  746. //else button was released
  747. else
  748. {
  749. rootMouseUp(mLastEvent);
  750. }
  751. return mConsumeLastInputEvent;
  752. }
  753. else if(inputEvent.objInst == KEY_BUTTON1) // right button
  754. {
  755. if(inputEvent.action == SI_MAKE)
  756. {
  757. U32 curTime = Platform::getVirtualMilliseconds();
  758. //if the last button pressed was the right...
  759. if (mRightMouseLast)
  760. {
  761. //if it was within the double click time count the clicks
  762. if (curTime - mLastMouseDownTime <= mouseDoubleClickTime)
  763. mLastMouseClickCount++;
  764. else
  765. mLastMouseClickCount = 1;
  766. }
  767. else
  768. {
  769. mRightMouseLast = true;
  770. mLastMouseClickCount = 1;
  771. }
  772. mLastMouseDownTime = curTime;
  773. mLastEvent.mouseClickCount = mLastMouseClickCount;
  774. rootRightMouseDown(mLastEvent);
  775. }
  776. else // it was a mouse up
  777. rootRightMouseUp(mLastEvent);
  778. return mConsumeLastInputEvent;
  779. }
  780. else if(inputEvent.objInst == KEY_BUTTON2) // middle button
  781. {
  782. if(inputEvent.action == SI_MAKE)
  783. {
  784. U32 curTime = Platform::getVirtualMilliseconds();
  785. //if the last button pressed was the right...
  786. if (mMiddleMouseLast)
  787. {
  788. //if it was within the double click time count the clicks
  789. if (curTime - mLastMouseDownTime <= mouseDoubleClickTime)
  790. mLastMouseClickCount++;
  791. else
  792. mLastMouseClickCount = 1;
  793. }
  794. else
  795. {
  796. mMiddleMouseLast = true;
  797. mLastMouseClickCount = 1;
  798. }
  799. mLastMouseDownTime = curTime;
  800. mLastEvent.mouseClickCount = mLastMouseClickCount;
  801. rootMiddleMouseDown(mLastEvent);
  802. }
  803. else // it was a mouse up
  804. rootMiddleMouseUp(mLastEvent);
  805. return mConsumeLastInputEvent;
  806. }
  807. }
  808. return false;
  809. }
  810. bool GuiCanvas::processGamepadEvent(InputEventInfo &inputEvent)
  811. {
  812. if (! mFirstResponder)
  813. {
  814. // early out, no first responder to receive gamepad input
  815. return false;
  816. }
  817. if (inputEvent.deviceInst >= MAX_GAMEPADS)
  818. {
  819. // early out, we only support the first MAX_GAMEPADS gamepads
  820. return false;
  821. }
  822. mLastEvent.keyCode = inputEvent.objInst;
  823. if (inputEvent.objType == SI_BUTTON)
  824. {
  825. switch (inputEvent.action)
  826. {
  827. case SI_MAKE:
  828. switch (inputEvent.objInst)
  829. {
  830. case SI_UPOV:
  831. return mFirstResponder->onGamepadAxisUp(mLastEvent);
  832. case SI_DPOV:
  833. return mFirstResponder->onGamepadAxisDown(mLastEvent);
  834. case SI_LPOV:
  835. return mFirstResponder->onGamepadAxisLeft(mLastEvent);
  836. case SI_RPOV:
  837. return mFirstResponder->onGamepadAxisRight(mLastEvent);
  838. default:
  839. return mFirstResponder->onGamepadButtonDown(mLastEvent);
  840. }
  841. break;
  842. case SI_BREAK:
  843. return mFirstResponder->onGamepadButtonUp(mLastEvent);
  844. default:
  845. return false;
  846. }
  847. }
  848. else if (inputEvent.objType == SI_AXIS)
  849. {
  850. F32 incomingValue = mFabs(inputEvent.fValue);
  851. static const F32 DEAD_ZONE = 0.5f;
  852. static const F32 MIN_CLICK_TIME = 500.0f;
  853. static const F32 MAX_CLICK_TIME = 1000.0f;
  854. static F32 xDecay [] = {1.0f, 1.0f, 1.0f, 1.0f};
  855. static F32 yDecay [] = {1.0f, 1.0f, 1.0f, 1.0f};
  856. static F32 zDecay [] = {1.0f, 1.0f, 1.0f, 1.0f};
  857. static U32 xLastClickTime [] = {0, 0, 0, 0};
  858. static U32 yLastClickTime [] = {0, 0, 0, 0};
  859. static U32 zLastClickTime [] = {0, 0, 0, 0};
  860. U32 curTime = Platform::getRealMilliseconds();
  861. F32 *decay;
  862. U32 *lastClickTime;
  863. switch (inputEvent.objInst)
  864. {
  865. case SI_ZAXIS:
  866. case XI_LEFT_TRIGGER:
  867. case XI_RIGHT_TRIGGER:
  868. decay = &zDecay[inputEvent.deviceInst];
  869. lastClickTime = &zLastClickTime[inputEvent.deviceInst];
  870. break;
  871. case SI_YAXIS:
  872. case XI_THUMBLY:
  873. case XI_THUMBRY:
  874. decay = &yDecay[inputEvent.deviceInst];
  875. lastClickTime = &yLastClickTime[inputEvent.deviceInst];
  876. break;
  877. case SI_XAXIS:
  878. case XI_THUMBLX:
  879. case XI_THUMBRX:
  880. default:
  881. decay = &xDecay[inputEvent.deviceInst];
  882. lastClickTime = &xLastClickTime[inputEvent.deviceInst];
  883. break;
  884. }
  885. if (incomingValue < DEAD_ZONE)
  886. {
  887. // early out, control movement is within the deadzone
  888. *decay = 1.0f;
  889. *lastClickTime = 0;
  890. return false;
  891. }
  892. // Rescales the input between 0.0 and 1.0
  893. incomingValue = (incomingValue - DEAD_ZONE) * (1.0f / (1.0f - DEAD_ZONE));
  894. F32 clickTime = MIN_CLICK_TIME + (MAX_CLICK_TIME - MIN_CLICK_TIME) * (1.0f - incomingValue);
  895. clickTime *= *decay;
  896. if (clickTime < (curTime - *lastClickTime))
  897. {
  898. *decay *= 0.9f;
  899. if (*decay < 0.2f)
  900. {
  901. *decay = 0.2f;
  902. }
  903. *lastClickTime = curTime;
  904. bool negative = (inputEvent.fValue < 0.0f);
  905. switch (inputEvent.objInst)
  906. {
  907. case SI_ZAXIS:
  908. case SI_RZAXIS:
  909. return mFirstResponder->onGamepadTrigger(mLastEvent);
  910. case SI_YAXIS:
  911. case SI_RYAXIS:
  912. if (!negative)
  913. {
  914. return mFirstResponder->onGamepadAxisDown(mLastEvent);
  915. }
  916. else
  917. {
  918. return mFirstResponder->onGamepadAxisUp(mLastEvent);
  919. }
  920. case SI_XAXIS:
  921. case SI_RXAXIS:
  922. default:
  923. if (negative)
  924. {
  925. return mFirstResponder->onGamepadAxisLeft(mLastEvent);
  926. }
  927. else
  928. {
  929. return mFirstResponder->onGamepadAxisRight(mLastEvent);
  930. }
  931. }
  932. }
  933. }
  934. return false;
  935. }
  936. void GuiCanvas::rootMouseDown(const GuiEvent &event)
  937. {
  938. mPrevMouseTime = Platform::getVirtualMilliseconds();
  939. mMouseButtonDown = true;
  940. //pass the event to the mouse locked control
  941. if (bool(mMouseCapturedControl))
  942. mMouseCapturedControl->onMouseDown(event);
  943. else
  944. {
  945. //else pass it to whoever is underneath the cursor
  946. iterator i;
  947. i = end();
  948. while (i != begin())
  949. {
  950. i--;
  951. GuiControl *ctrl = static_cast<GuiControl *>(*i);
  952. GuiControl *controlHit = ctrl->findHitControl( event.mousePoint - ctrl->getPosition() );
  953. //see if the controlHit is a modeless dialog...
  954. if( !controlHit->getControlProfile()->mModal )
  955. continue;
  956. else
  957. {
  958. controlHit->onMouseDown(event);
  959. break;
  960. }
  961. }
  962. }
  963. if (bool(mMouseControl))
  964. mMouseControlClicked = true;
  965. }
  966. void GuiCanvas::findMouseControl(const GuiEvent &event)
  967. {
  968. // Any children at all?
  969. if(size() == 0)
  970. {
  971. mMouseControl = NULL;
  972. return;
  973. }
  974. // Otherwise, check the point and find the overlapped control.
  975. GuiControl *controlHit = findHitControl(event.mousePoint);
  976. if(controlHit != static_cast<GuiControl*>(mMouseControl))
  977. {
  978. if(bool(mMouseControl))
  979. mMouseControl->onMouseLeave(event);
  980. mMouseControl = controlHit;
  981. mMouseControl->onMouseEnter(event);
  982. }
  983. }
  984. void GuiCanvas::refreshMouseControl()
  985. {
  986. GuiEvent evt;
  987. evt.mousePoint.x = S32(mCursorPt.x);
  988. evt.mousePoint.y = S32(mCursorPt.y);
  989. findMouseControl(evt);
  990. }
  991. void GuiCanvas::checkLockMouseMove( const GuiEvent& event )
  992. {
  993. GuiControl* controlHit = findHitControl( event.mousePoint );
  994. if( controlHit != mMouseControl )
  995. {
  996. if( mMouseControl == mMouseCapturedControl )
  997. mMouseCapturedControl->onMouseLeave( event );
  998. else if( controlHit == mMouseCapturedControl )
  999. mMouseCapturedControl->onMouseEnter( event );
  1000. mMouseControl = controlHit;
  1001. }
  1002. }
  1003. void GuiCanvas::rootMouseUp(const GuiEvent &event)
  1004. {
  1005. mPrevMouseTime = Platform::getVirtualMilliseconds();
  1006. mMouseButtonDown = false;
  1007. // pass the event to the mouse locked control
  1008. if (bool(mMouseCapturedControl))
  1009. {
  1010. checkLockMouseMove( event );
  1011. mMouseCapturedControl->onMouseUp(event);
  1012. }
  1013. else
  1014. {
  1015. findMouseControl(event);
  1016. if(bool(mMouseControl))
  1017. mMouseControl->onMouseUp(event);
  1018. }
  1019. }
  1020. void GuiCanvas::rootMouseDragged(const GuiEvent &event)
  1021. {
  1022. //pass the event to the mouse locked control
  1023. if (bool(mMouseCapturedControl))
  1024. {
  1025. checkLockMouseMove( event );
  1026. mMouseCapturedControl->onMouseDragged(event);
  1027. }
  1028. else
  1029. {
  1030. findMouseControl(event);
  1031. if(bool(mMouseControl))
  1032. mMouseControl->onMouseDragged(event);
  1033. }
  1034. }
  1035. void GuiCanvas::rootMouseMove(const GuiEvent &event)
  1036. {
  1037. if (bool(mMouseCapturedControl))
  1038. {
  1039. mMouseCapturedControl->onMouseMove(event);
  1040. }
  1041. else
  1042. {
  1043. findMouseControl(event);
  1044. if(bool(mMouseControl))
  1045. mMouseControl->onMouseMove(event);
  1046. }
  1047. }
  1048. void GuiCanvas::rootRightMouseDown(const GuiEvent &event)
  1049. {
  1050. mPrevMouseTime = Platform::getVirtualMilliseconds();
  1051. mMouseRightButtonDown = true;
  1052. if (bool(mMouseCapturedControl))
  1053. {
  1054. checkLockMouseMove( event );
  1055. mMouseCapturedControl->onRightMouseDown(event);
  1056. }
  1057. else
  1058. {
  1059. findMouseControl(event);
  1060. if(bool(mMouseControl))
  1061. {
  1062. mMouseControl->onRightMouseDown(event);
  1063. }
  1064. }
  1065. }
  1066. void GuiCanvas::rootRightMouseUp(const GuiEvent &event)
  1067. {
  1068. mPrevMouseTime = Platform::getVirtualMilliseconds();
  1069. mMouseRightButtonDown = false;
  1070. if (bool(mMouseCapturedControl))
  1071. mMouseCapturedControl->onRightMouseUp(event);
  1072. else
  1073. {
  1074. findMouseControl(event);
  1075. if(bool(mMouseControl))
  1076. mMouseControl->onRightMouseUp(event);
  1077. }
  1078. }
  1079. void GuiCanvas::rootRightMouseDragged(const GuiEvent &event)
  1080. {
  1081. mPrevMouseTime = Platform::getVirtualMilliseconds();
  1082. if (bool(mMouseCapturedControl))
  1083. {
  1084. mMouseCapturedControl->onRightMouseDragged(event);
  1085. }
  1086. else
  1087. {
  1088. findMouseControl(event);
  1089. if(bool(mMouseControl))
  1090. mMouseControl->onRightMouseDragged(event);
  1091. }
  1092. }
  1093. void GuiCanvas::rootMiddleMouseDown(const GuiEvent &event)
  1094. {
  1095. mPrevMouseTime = Platform::getVirtualMilliseconds();
  1096. mMouseMiddleButtonDown = true;
  1097. if (bool(mMouseCapturedControl))
  1098. mMouseCapturedControl->onMiddleMouseDown(event);
  1099. else
  1100. {
  1101. findMouseControl(event);
  1102. if(bool(mMouseControl))
  1103. {
  1104. mMouseControl->onMiddleMouseDown(event);
  1105. }
  1106. }
  1107. }
  1108. void GuiCanvas::rootMiddleMouseUp(const GuiEvent &event)
  1109. {
  1110. mPrevMouseTime = Platform::getVirtualMilliseconds();
  1111. mMouseMiddleButtonDown = false;
  1112. if (bool(mMouseCapturedControl))
  1113. mMouseCapturedControl->onMiddleMouseUp(event);
  1114. else
  1115. {
  1116. findMouseControl(event);
  1117. if(bool(mMouseControl))
  1118. mMouseControl->onMiddleMouseUp(event);
  1119. }
  1120. }
  1121. void GuiCanvas::rootMiddleMouseDragged(const GuiEvent &event)
  1122. {
  1123. mPrevMouseTime = Platform::getVirtualMilliseconds();
  1124. if (bool(mMouseCapturedControl))
  1125. {
  1126. checkLockMouseMove( event );
  1127. mMouseCapturedControl->onMiddleMouseDragged(event);
  1128. }
  1129. else
  1130. {
  1131. findMouseControl(event);
  1132. if(bool(mMouseControl))
  1133. mMouseControl->onMiddleMouseDragged(event);
  1134. }
  1135. }
  1136. bool GuiCanvas::rootMouseWheelUp(const GuiEvent &event)
  1137. {
  1138. if (bool(mMouseCapturedControl))
  1139. return mMouseCapturedControl->onMouseWheelUp(event);
  1140. else
  1141. {
  1142. findMouseControl(event);
  1143. if (bool(mMouseControl))
  1144. return mMouseControl->onMouseWheelUp(event);
  1145. }
  1146. return false;
  1147. }
  1148. bool GuiCanvas::rootMouseWheelDown(const GuiEvent &event)
  1149. {
  1150. if (bool(mMouseCapturedControl))
  1151. return mMouseCapturedControl->onMouseWheelDown(event);
  1152. else
  1153. {
  1154. findMouseControl(event);
  1155. if (bool(mMouseControl))
  1156. return mMouseControl->onMouseWheelDown(event);
  1157. }
  1158. return false;
  1159. }
  1160. void GuiCanvas::setContentControl(GuiControl *gui)
  1161. {
  1162. // Skip out if we got passed NULL (why would that happen?)
  1163. if(!gui)
  1164. return;
  1165. GuiControl *oldContent = getContentControl();
  1166. if(oldContent)
  1167. Con::executef(oldContent, "onUnsetContent", Con::getIntArg(gui->getId()));
  1168. //remove all dialogs on layer 0
  1169. U32 index = 0;
  1170. while (size() > index)
  1171. {
  1172. GuiControl *ctrl = static_cast<GuiControl*>((*this)[index]);
  1173. if (ctrl == gui || ctrl->mLayer != 0)
  1174. index++;
  1175. Sim::getGuiGroup()->addObject( ctrl );
  1176. }
  1177. // set current menu bar
  1178. setMenuBar( mMenuBarCtrl );
  1179. // lose the first responder from the old GUI
  1180. GuiControl* responder = gui->findFirstTabable();
  1181. if(responder)
  1182. responder->setFirstResponder();
  1183. //add the gui to the front
  1184. if(!size() || gui != (*this)[0])
  1185. {
  1186. // automatically wakes objects in GuiControl::onWake
  1187. addObject(gui);
  1188. if (size() >= 2)
  1189. reOrder(gui, *begin());
  1190. }
  1191. //refresh the entire gui
  1192. resetUpdateRegions();
  1193. //rebuild the accelerator map
  1194. mAcceleratorMap.clear();
  1195. for(iterator i = end(); i != begin() ; )
  1196. {
  1197. i--;
  1198. GuiControl *ctrl = static_cast<GuiControl *>(*i);
  1199. ctrl->buildAcceleratorMap();
  1200. if (ctrl->getControlProfile()->mModal)
  1201. break;
  1202. }
  1203. refreshMouseControl();
  1204. // Force the canvas to update the sizing of the new content control
  1205. maintainSizing();
  1206. // Do this last so onWake gets called first
  1207. Con::executef(gui, "onSetContent", Con::getIntArg(oldContent ? oldContent->getId() : 0));
  1208. }
  1209. GuiControl *GuiCanvas::getContentControl()
  1210. {
  1211. if(size() > 0)
  1212. return (GuiControl *) first();
  1213. return NULL;
  1214. }
  1215. void GuiCanvas::pushDialogControl(GuiControl *gui, S32 layer, bool center)
  1216. {
  1217. if( center )
  1218. gui->setPosition( getExtent().x / 2 - gui->getExtent().x / 2,
  1219. getExtent().y / 2 - gui->getExtent().y / 2 );
  1220. //add the gui
  1221. gui->mLayer = layer;
  1222. // GuiControl::addObject wakes the object
  1223. addObject(gui);
  1224. //reorder it to the correct layer
  1225. iterator i;
  1226. for (i = begin(); i != end(); i++)
  1227. {
  1228. GuiControl *ctrl = static_cast<GuiControl*>(*i);
  1229. if (ctrl->mLayer > gui->mLayer)
  1230. {
  1231. reOrder(gui, ctrl);
  1232. break;
  1233. }
  1234. }
  1235. //call the dialog push method
  1236. gui->onDialogPush();
  1237. //find the first responder
  1238. GuiControl* responder = gui->findFirstTabable();
  1239. if(responder)
  1240. responder->setFirstResponder();
  1241. // call the 'onWake' method?
  1242. //if(wakedGui)
  1243. // Con::executef(gui, 1, "onWake");
  1244. //refresh the entire gui
  1245. resetUpdateRegions();
  1246. //rebuild the accelerator map
  1247. mAcceleratorMap.clear();
  1248. if (size() > 0)
  1249. {
  1250. GuiControl *ctrl = static_cast<GuiControl*>(last());
  1251. ctrl->buildAcceleratorMap();
  1252. }
  1253. refreshMouseControl();
  1254. // I don't see the purpose of this, and it's causing issues when showing, for instance the
  1255. // metrics dialog while in a 3d scene, causing the cursor to be shown even when the mouse
  1256. // is locked [4/25/2007 justind]
  1257. //if(gui->mProfile && gui->mProfile->mModal)
  1258. // mPlatformWindow->getCursorController()->pushCursor(PlatformCursorController::curArrow);
  1259. }
  1260. void GuiCanvas::popDialogControl(GuiControl *gui)
  1261. {
  1262. if (size() < 1)
  1263. return;
  1264. //first, find the dialog, and call the "onDialogPop()" method
  1265. GuiControl *ctrl = NULL;
  1266. if (gui)
  1267. {
  1268. //make sure the gui really exists on the stack
  1269. iterator i;
  1270. bool found = false;
  1271. for(i = begin(); i != end(); i++)
  1272. {
  1273. GuiControl *check = static_cast<GuiControl *>(*i);
  1274. if (check == gui)
  1275. {
  1276. ctrl = check;
  1277. found = true;
  1278. }
  1279. }
  1280. if (!found)
  1281. return;
  1282. }
  1283. else
  1284. ctrl = static_cast<GuiControl*>(last());
  1285. //call the "on pop" function
  1286. ctrl->onDialogPop();
  1287. //now pop the last child (will sleep if awake)
  1288. Sim::getGuiGroup()->addObject(ctrl);
  1289. if (size() > 0)
  1290. {
  1291. GuiControl *lastCtrl = static_cast<GuiControl *>(last());
  1292. if(lastCtrl->getFirstResponder() )
  1293. lastCtrl->getFirstResponder()->setFirstResponder();
  1294. }
  1295. else
  1296. {
  1297. setFirstResponder(NULL);
  1298. }
  1299. //refresh the entire gui
  1300. resetUpdateRegions();
  1301. //rebuild the accelerator map
  1302. mAcceleratorMap.clear();
  1303. if (size() > 0)
  1304. {
  1305. GuiControl *lastCtrl = static_cast<GuiControl*>(last());
  1306. lastCtrl->buildAcceleratorMap();
  1307. }
  1308. refreshMouseControl();
  1309. }
  1310. void GuiCanvas::popDialogControl(S32 layer)
  1311. {
  1312. if (size() < 1)
  1313. return;
  1314. GuiControl *ctrl = NULL;
  1315. iterator i = end(); // find in z order (last to first)
  1316. while (i != begin())
  1317. {
  1318. i--;
  1319. ctrl = static_cast<GuiControl*>(*i);
  1320. if (ctrl->mLayer == layer)
  1321. break;
  1322. }
  1323. if (ctrl)
  1324. popDialogControl(ctrl);
  1325. }
  1326. void GuiCanvas::mouseLock(GuiControl *lockingControl)
  1327. {
  1328. if (bool(mMouseCapturedControl))
  1329. return;
  1330. mMouseCapturedControl = lockingControl;
  1331. if(mMouseControl && mMouseControl != mMouseCapturedControl)
  1332. {
  1333. GuiEvent evt;
  1334. evt.mousePoint.x = S32(mCursorPt.x);
  1335. evt.mousePoint.y = S32(mCursorPt.y);
  1336. mMouseControl->onMouseLeave(evt);
  1337. }
  1338. }
  1339. void GuiCanvas::mouseUnlock(GuiControl *lockingControl)
  1340. {
  1341. if (static_cast<GuiControl*>(mMouseCapturedControl) != lockingControl)
  1342. return;
  1343. GuiEvent evt;
  1344. evt.mousePoint.x = S32(mCursorPt.x);
  1345. evt.mousePoint.y = S32(mCursorPt.y);
  1346. GuiControl * controlHit = findHitControl(evt.mousePoint);
  1347. if(controlHit != mMouseCapturedControl)
  1348. {
  1349. mMouseControl = controlHit;
  1350. mMouseControlClicked = false;
  1351. if(bool(mMouseControl))
  1352. mMouseControl->onMouseEnter(evt);
  1353. }
  1354. mMouseCapturedControl = NULL;
  1355. }
  1356. void GuiCanvas::paint()
  1357. {
  1358. resetUpdateRegions();
  1359. // inhibit explicit refreshes in the case we're swapped out
  1360. if( mPlatformWindow && mPlatformWindow->isVisible() && GFX->allowRender())
  1361. mPlatformWindow->displayEvent.trigger(mPlatformWindow->getWindowId());
  1362. }
  1363. void GuiCanvas::repaint(U32 elapsedMS)
  1364. {
  1365. // Make sure we have a window.
  1366. if ( !mPlatformWindow )
  1367. return;
  1368. // Has enough time elapsed?
  1369. U32 elapsed = Platform::getRealMilliseconds() - mLastRenderMs;
  1370. if (elapsed < elapsedMS)
  1371. return;
  1372. // Do the render.
  1373. resetUpdateRegions();
  1374. handlePaintEvent(mPlatformWindow->getWindowId());
  1375. }
  1376. void GuiCanvas::maintainSizing()
  1377. {
  1378. Point2I size = getWindowSize();
  1379. if(size.x == -1 || size.y == -1)
  1380. return;
  1381. RectI screenRect(0, 0, size.x, size.y);
  1382. setBounds(screenRect);
  1383. // all bottom level controls should be the same dimensions as the canvas
  1384. // this is necessary for passing mouse events accurately
  1385. iterator i;
  1386. for (i = begin(); i != end(); i++)
  1387. {
  1388. AssertFatal(static_cast<GuiControl*>((*i))->isAwake(), "GuiCanvas::maintainSizing - ctrl is not awake");
  1389. GuiControl *ctrl = static_cast<GuiControl*>(*i);
  1390. Point2I ext = ctrl->getExtent();
  1391. Point2I pos = ctrl->getPosition();
  1392. Point2I newExt = screenRect.extent;
  1393. Point2I newPos = screenRect.point;
  1394. // if menubar is active displace content gui control
  1395. if (mMenuBarCtrl && (ctrl == getContentControl()))
  1396. {
  1397. /*const SimObject *menu = mMenuBarCtrl->findObjectByInternalName( StringTable->insert("menubar"), true);
  1398. if( !menu )
  1399. continue;
  1400. AssertFatal( dynamic_cast<const GuiControl*>(menu), "");*/
  1401. const U32 yOffset = static_cast<const GuiMenuBar*>(mMenuBarCtrl)->mMenubarHeight;
  1402. newPos.y += yOffset;
  1403. newExt.y -= yOffset;
  1404. }
  1405. if (pos != newPos || ext != newExt)
  1406. {
  1407. ctrl->resize(newPos, newExt);
  1408. resetUpdateRegions();
  1409. }
  1410. }
  1411. }
  1412. void GuiCanvas::setupFences()
  1413. {
  1414. // Destroy old fences
  1415. SAFE_DELETE_ARRAY( mFences );
  1416. // Now create the new ones
  1417. if( mNumFences > 0 )
  1418. {
  1419. mFences = new GFXFence*[mNumFences];
  1420. // Allocate the new fences
  1421. for( S32 i = 0; i < mNumFences; i++ )
  1422. mFences[i] = GFX->createFence();
  1423. }
  1424. // Reset state
  1425. mNextFenceIdx = 0;
  1426. }
  1427. void GuiCanvas::renderFrame(bool preRenderOnly, bool bufferSwap /* = true */)
  1428. {
  1429. AssertISV(mPlatformWindow, "GuiCanvas::renderFrame - no window present!");
  1430. if(!mPlatformWindow->isVisible() || !GFX->allowRender() || GFX->canCurrentlyRender())
  1431. return;
  1432. PROFILE_START(CanvasPreRender);
  1433. // Set our window as the current render target so we can see outputs.
  1434. GFX->setActiveRenderTarget(mPlatformWindow->getGFXTarget());
  1435. if (!GFX->getActiveRenderTarget())
  1436. {
  1437. PROFILE_END();
  1438. return;
  1439. }
  1440. #ifdef TORQUE_GFX_STATE_DEBUG
  1441. GFX->getDebugStateManager()->startFrame();
  1442. #endif
  1443. GFXTarget* renderTarget = GFX->getActiveRenderTarget();
  1444. if (renderTarget == NULL)
  1445. {
  1446. PROFILE_END();
  1447. return;
  1448. }
  1449. // Make sure the root control is the size of the canvas.
  1450. Point2I size = renderTarget->getSize();
  1451. if(size.x == 0 || size.y == 0)
  1452. {
  1453. PROFILE_END();
  1454. return;
  1455. }
  1456. RectI screenRect(0, 0, size.x, size.y);
  1457. maintainSizing();
  1458. //preRender (recursive) all controls
  1459. preRender();
  1460. PROFILE_END();
  1461. // Are we just doing pre-render?
  1462. if(preRenderOnly)
  1463. return;
  1464. // Signal the interested parties.
  1465. GuiCanvas::getGuiCanvasFrameSignal().trigger(true);
  1466. // Gross hack to make sure we don't end up with advanced lighting and msaa
  1467. // at the same time, which causes artifacts. At the same time we don't
  1468. // want to just throw the settings the user has chosen if the light manager
  1469. // changes at a later time.
  1470. GFXVideoMode mode = mPlatformWindow->getVideoMode();
  1471. if ( dStricmp( LIGHTMGR->getId(), "ADVLM" ) == 0 && mode.antialiasLevel > 0 )
  1472. {
  1473. const char *pref = Con::getVariable( "$pref::Video::mode" );
  1474. mode.parseFromString( pref );
  1475. mode.antialiasLevel = 0;
  1476. Point2I winPos = mPlatformWindow->getPosition(); // Save position so we can put window back.
  1477. mPlatformWindow->setVideoMode(mode);
  1478. mPlatformWindow->setPosition(winPos);
  1479. Con::printf( "AntiAliasing has been disabled; it is not compatible with AdvancedLighting." );
  1480. }
  1481. else if ( dStricmp( LIGHTMGR->getId(), "BLM" ) == 0)
  1482. {
  1483. const char *pref = Con::getVariable( "$pref::Video::mode" );
  1484. U32 prefAA = dAtoi( StringUnit::getUnit(pref, 5, " ") );
  1485. if ( prefAA != mode.antialiasLevel )
  1486. {
  1487. mode.parseFromString( pref );
  1488. Point2I winPos = mPlatformWindow->getPosition(); // Save position so we can put window back.
  1489. mPlatformWindow->setVideoMode(mode);
  1490. mPlatformWindow->setPosition(winPos);
  1491. Con::printf( "AntiAliasing has been enabled while running BasicLighting." );
  1492. }
  1493. }
  1494. // for now, just always reset the update regions - this is a
  1495. // fix for FSAA on ATI cards
  1496. resetUpdateRegions();
  1497. PROFILE_START(CanvasRenderControls);
  1498. // Draw the mouse
  1499. GuiCursor *mouseCursor = NULL;
  1500. bool cursorVisible = true;
  1501. if(bool(mMouseCapturedControl))
  1502. mMouseCapturedControl->getCursor(mouseCursor, cursorVisible, mLastEvent);
  1503. else if(bool(mMouseControl))
  1504. mMouseControl->getCursor(mouseCursor, cursorVisible, mLastEvent);
  1505. Point2I cursorPos((S32)mCursorPt.x, (S32)mCursorPt.y);
  1506. if(!mouseCursor)
  1507. mouseCursor = mDefaultCursor;
  1508. if(mLastCursorEnabled && mLastCursor)
  1509. {
  1510. Point2I spot = mLastCursor->getHotSpot();
  1511. Point2I cext = mLastCursor->getExtent();
  1512. Point2I pos = mLastCursorPt - spot;
  1513. addUpdateRegion(pos - Point2I(2, 2), Point2I(cext.x + 4, cext.y + 4));
  1514. }
  1515. if(cursorVisible && mouseCursor)
  1516. {
  1517. Point2I spot = mouseCursor->getHotSpot();
  1518. Point2I cext = mouseCursor->getExtent();
  1519. Point2I pos = cursorPos - spot;
  1520. addUpdateRegion(pos - Point2I(2, 2), Point2I(cext.x + 4, cext.y + 4));
  1521. }
  1522. mLastCursorEnabled = cursorVisible;
  1523. mLastCursor = mouseCursor;
  1524. mLastCursorPt = cursorPos;
  1525. // Begin GFX
  1526. PROFILE_START(GFXBeginScene);
  1527. bool beginSceneRes = GFX->beginScene();
  1528. PROFILE_END();
  1529. // Render all offscreen canvas objects here since we may need them in the render loop
  1530. if (GuiOffscreenCanvas::sList.size() != 0)
  1531. {
  1532. // Reset the entire state since oculus shit will have barfed it.
  1533. GFX->updateStates(true);
  1534. for (Vector<GuiOffscreenCanvas*>::iterator itr = GuiOffscreenCanvas::sList.begin(); itr != GuiOffscreenCanvas::sList.end(); itr++)
  1535. {
  1536. (*itr)->renderFrame(false, false);
  1537. }
  1538. GFX->setActiveRenderTarget(renderTarget);
  1539. }
  1540. // Can't render if waiting for device to reset.
  1541. if ( !beginSceneRes )
  1542. {
  1543. PROFILE_END(); // CanvasRenderControls
  1544. // Since we already triggered the signal once for begin-of-frame,
  1545. // we should be consistent and trigger it again for end-of-frame.
  1546. GuiCanvas::getGuiCanvasFrameSignal().trigger(false);
  1547. return;
  1548. }
  1549. // Clear the current viewport area
  1550. GFX->setViewport( screenRect );
  1551. GFX->clear( GFXClearZBuffer | GFXClearStencil | GFXClearTarget, gCanvasClearColor, 1.0f, 0 );
  1552. resetUpdateRegions();
  1553. // Make sure we have a clean matrix state
  1554. // before we start rendering anything!
  1555. GFX->setWorldMatrix( MatrixF::Identity );
  1556. GFX->setViewMatrix( MatrixF::Identity );
  1557. GFX->setProjectionMatrix( MatrixF::Identity );
  1558. // If we're taking a screenshot then let it have
  1559. // a chance at altering the view matrix.
  1560. if ( gScreenShot && gScreenShot->isPending() )
  1561. gScreenShot->tileGui( size );
  1562. RectI updateUnion;
  1563. buildUpdateUnion(&updateUnion);
  1564. if (updateUnion.intersect(screenRect))
  1565. {
  1566. // Render active GUI Dialogs
  1567. for(iterator i = begin(); i != end(); i++)
  1568. {
  1569. // Get the control
  1570. GuiControl *contentCtrl = static_cast<GuiControl*>(*i);
  1571. GFX->setClipRect( updateUnion );
  1572. GFX->setStateBlock(mDefaultGuiSB);
  1573. contentCtrl->onRender(contentCtrl->getPosition(), updateUnion);
  1574. }
  1575. // Fill Black if no Dialogs
  1576. if(this->size() == 0)
  1577. GFX->clear( GFXClearTarget, ColorI(0,0,0,0), 1.0f, 0 );
  1578. // Tooltip resource
  1579. if(bool(mMouseControl))
  1580. {
  1581. U32 curTime = Platform::getRealMilliseconds();
  1582. if(mHoverControl == mMouseControl)
  1583. {
  1584. if(mHoverPositionSet || (curTime - mHoverControlStart) >= mHoverControl->mTipHoverTime || (curTime - mHoverLeftControlTime) <= mHoverControl->mTipHoverTime)
  1585. {
  1586. if(!mHoverPositionSet)
  1587. {
  1588. mHoverPosition = cursorPos;
  1589. }
  1590. mHoverPositionSet = mMouseControl->mRenderTooltipDelegate( mHoverPosition, cursorPos, NULL );
  1591. }
  1592. }
  1593. else
  1594. {
  1595. if(mHoverPositionSet)
  1596. {
  1597. mHoverLeftControlTime = curTime;
  1598. mHoverPositionSet = false;
  1599. }
  1600. mHoverControl = mMouseControl;
  1601. mHoverControlStart = curTime;
  1602. }
  1603. }
  1604. GFX->setClipRect( updateUnion );
  1605. // Draw an ugly box if we don't have a cursor available...
  1606. //if (mCursorEnabled && mShowCursor && !mouseCursor)
  1607. //{
  1608. // GFX->drawRectFill( RectI( mCursorPt.x, mCursorPt.y, mCursorPt.x + 2, mCursorPt.y + 2 ), ColorI( 255, 0, 0 ) );
  1609. //}
  1610. // CodeReview - Make sure our bitmap modulation is clear or else there's a black modulation
  1611. // that ruins rendering of textures at startup.. This was done in mouseCursor
  1612. // onRender and so at startup when it wasn't called the modulation was black, ruining
  1613. // the loading screen display. This fixes the issue, but is it only masking a deeper issue
  1614. // in GFX with regard to gui rendering? [5/3/2007 justind]
  1615. GFX->getDrawUtil()->clearBitmapModulation();
  1616. // Really draw the cursor. :)
  1617. // Only if the platform cursor controller is missing or the platform cursor
  1618. // isn't visible.
  1619. if (!mPlatformWindow->getCursorController() || (mCursorEnabled && mouseCursor && mShowCursor &&
  1620. !mPlatformWindow->getCursorController()->isCursorVisible()))
  1621. {
  1622. Point2I pos((S32)mCursorPt.x, (S32)mCursorPt.y);
  1623. Point2I spot = mouseCursor->getHotSpot();
  1624. pos -= spot;
  1625. mouseCursor->render(pos);
  1626. }
  1627. }
  1628. // Render all RTT end of frame updates HERE
  1629. //DynamicTexture::updateScreenTextures();
  1630. //DynamicTexture::updateEndOfFrameTextures();
  1631. // mPending is set when the console function "screenShot()" is called
  1632. // this situation is necessary because it needs to take the screenshot
  1633. // before the buffers swap
  1634. PROFILE_END();
  1635. // Fence logic here, because this is where endScene is called.
  1636. if( mNumFences > 0 )
  1637. {
  1638. // Issue next fence
  1639. mFences[mNextFenceIdx]->issue();
  1640. mNextFenceIdx++;
  1641. // Wrap the next fence around to first if we're maxxed
  1642. if( mNextFenceIdx >= mNumFences )
  1643. mNextFenceIdx = 0;
  1644. // Block on previous fence
  1645. mFences[mNextFenceIdx]->block();
  1646. }
  1647. PROFILE_START(GFXEndScene);
  1648. GFX->endScene();
  1649. PROFILE_END();
  1650. GFX->getDeviceEventSignal().trigger( GFXDevice::dePostFrame );
  1651. swapBuffers();
  1652. GuiCanvas::getGuiCanvasFrameSignal().trigger(false);
  1653. #ifdef TORQUE_GFX_STATE_DEBUG
  1654. GFX->getDebugStateManager()->endFrame();
  1655. #endif
  1656. // Keep track of the last time we rendered.
  1657. mLastRenderMs = Platform::getRealMilliseconds();
  1658. }
  1659. GuiCanvas::GuiCanvasFrameSignal& GuiCanvas::getGuiCanvasFrameSignal()
  1660. {
  1661. static GuiCanvasFrameSignal theSignal;
  1662. return theSignal;
  1663. }
  1664. void GuiCanvas::swapBuffers()
  1665. {
  1666. AssertISV(mPlatformWindow, "GuiCanvas::swapBuffers - no window present!");
  1667. if(!mPlatformWindow->isVisible())
  1668. return;
  1669. PROFILE_START(SwapBuffers);
  1670. mPlatformWindow->getGFXTarget()->present();
  1671. PROFILE_END();
  1672. }
  1673. void GuiCanvas::buildUpdateUnion(RectI *updateUnion)
  1674. {
  1675. *updateUnion = mOldUpdateRects[0];
  1676. //the update region should encompass the oldUpdateRects, and the curUpdateRect
  1677. Point2I upperL;
  1678. Point2I lowerR;
  1679. upperL.x = getMin(mOldUpdateRects[0].point.x, mOldUpdateRects[1].point.x);
  1680. upperL.x = getMin(upperL.x, mCurUpdateRect.point.x);
  1681. upperL.y = getMin(mOldUpdateRects[0].point.y, mOldUpdateRects[1].point.y);
  1682. upperL.y = getMin(upperL.y, mCurUpdateRect.point.y);
  1683. lowerR.x = getMax(mOldUpdateRects[0].point.x + mOldUpdateRects[0].extent.x, mOldUpdateRects[1].point.x + mOldUpdateRects[1].extent.x);
  1684. lowerR.x = getMax(lowerR.x, mCurUpdateRect.point.x + mCurUpdateRect.extent.x);
  1685. lowerR.y = getMax(mOldUpdateRects[0].point.y + mOldUpdateRects[0].extent.y, mOldUpdateRects[1].point.y + mOldUpdateRects[1].extent.y);
  1686. lowerR.y = getMax(lowerR.y, mCurUpdateRect.point.y + mCurUpdateRect.extent.y);
  1687. updateUnion->point = upperL;
  1688. updateUnion->extent = lowerR - upperL;
  1689. //shift the oldUpdateRects
  1690. mOldUpdateRects[0] = mOldUpdateRects[1];
  1691. mOldUpdateRects[1] = mCurUpdateRect;
  1692. mCurUpdateRect.point.set(0,0);
  1693. mCurUpdateRect.extent.set(0,0);
  1694. }
  1695. void GuiCanvas::addUpdateRegion(Point2I pos, Point2I ext)
  1696. {
  1697. if(mCurUpdateRect.extent.x == 0)
  1698. {
  1699. mCurUpdateRect.point = pos;
  1700. mCurUpdateRect.extent = ext;
  1701. }
  1702. else
  1703. {
  1704. Point2I upperL;
  1705. upperL.x = getMin(mCurUpdateRect.point.x, pos.x);
  1706. upperL.y = getMin(mCurUpdateRect.point.y, pos.y);
  1707. Point2I lowerR;
  1708. lowerR.x = getMax(mCurUpdateRect.point.x + mCurUpdateRect.extent.x, pos.x + ext.x);
  1709. lowerR.y = getMax(mCurUpdateRect.point.y + mCurUpdateRect.extent.y, pos.y + ext.y);
  1710. mCurUpdateRect.point = upperL;
  1711. mCurUpdateRect.extent = lowerR - upperL;
  1712. }
  1713. }
  1714. void GuiCanvas::resetUpdateRegions()
  1715. {
  1716. //DEBUG - get surface width and height
  1717. mOldUpdateRects[0] = getBounds();
  1718. mOldUpdateRects[1] = mOldUpdateRects[0];
  1719. mCurUpdateRect = mOldUpdateRects[0];
  1720. }
  1721. void GuiCanvas::setFirstResponder( GuiControl* newResponder )
  1722. {
  1723. GuiControl* oldResponder = mFirstResponder;
  1724. Parent::setFirstResponder( newResponder );
  1725. if( oldResponder == mFirstResponder )
  1726. return;
  1727. if( oldResponder && ( oldResponder != newResponder ) )
  1728. oldResponder->onLoseFirstResponder();
  1729. if( newResponder && ( newResponder != oldResponder ) )
  1730. newResponder->onGainFirstResponder();
  1731. }
  1732. DefineEngineMethod( GuiCanvas, getContent, S32, (),,
  1733. "@brief Get the GuiControl which is being used as the content.\n\n"
  1734. "@tsexample\n"
  1735. "Canvas.getContent();\n"
  1736. "@endtsexample\n\n"
  1737. "@return ID of current content control")
  1738. {
  1739. GuiControl *ctrl = object->getContentControl();
  1740. if(ctrl)
  1741. return ctrl->getId();
  1742. return -1;
  1743. }
  1744. DefineEngineMethod( GuiCanvas, setContent, void, (GuiControl* ctrl),,
  1745. "@brief Set the content of the canvas to a specified control.\n\n"
  1746. "@param ctrl ID or name of GuiControl to set content to\n\n"
  1747. "@tsexample\n"
  1748. "Canvas.setContent(PlayGui);\n"
  1749. "@endtsexample\n\n")
  1750. {
  1751. // Not using old error reporting until we modify the engineAPI - mperry
  1752. //GuiControl *gui = NULL;
  1753. // if(argv[2][0])
  1754. // {
  1755. // if (!Sim::findObject(argv[2], gui))
  1756. // {
  1757. // Con::printf("%s(): Invalid control: %s", argv[0], argv[2]);
  1758. // return;
  1759. // }
  1760. // }
  1761. if(!ctrl)
  1762. {
  1763. Con::errorf("GuiCanvas::setContent - Invalid control specified')");
  1764. return;
  1765. }
  1766. //set the new content control
  1767. object->setContentControl(ctrl);
  1768. }
  1769. ConsoleDocFragment _pushDialog(
  1770. "@brief Adds a dialog control onto the stack of dialogs\n\n"
  1771. "@param ctrl Dialog to add\n"
  1772. "@param layer Layer to put dialog on (optional)\n"
  1773. "@param center True to center dialog on canvas (optional)\n\n"
  1774. "@tsexample\n"
  1775. "Canvas.pushDialog(RecordingsDlg);\n"
  1776. "@endtsexample\n\n",
  1777. "GuiCanvas",
  1778. "void pushDialog( GuiControl ctrl, int layer=0, bool center=false);"
  1779. );
  1780. DefineEngineMethod( GuiCanvas, pushDialog, void, (const char * ctrlName, S32 layer, bool center), ( 0, false), "(GuiControl ctrl, int layer=0, bool center=false)"
  1781. "@hide")
  1782. {
  1783. GuiControl *gui;
  1784. if (! Sim::findObject(ctrlName, gui))
  1785. {
  1786. Con::printf("pushDialog(): Invalid control: %s", ctrlName);
  1787. return;
  1788. }
  1789. //find the layer
  1790. //set the new content control
  1791. object->pushDialogControl(gui, layer, center);
  1792. }
  1793. ConsoleDocFragment _popDialog1(
  1794. "@brief Removes a specific dialog control\n\n"
  1795. "@param ctrl Dialog to pop\n"
  1796. "@tsexample\n"
  1797. "Canvas.popDialog(RecordingsDlg);\n"
  1798. "@endtsexample\n\n",
  1799. "GuiCanvas",
  1800. "void popDialog( GuiControl ctrl);"
  1801. );
  1802. ConsoleDocFragment _popDialog2(
  1803. "@brief Removes a dialog at the front most layer\n\n"
  1804. "@tsexample\n"
  1805. "// Pops whatever is on layer 0\n"
  1806. "Canvas.popDialog();\n"
  1807. "@endtsexample\n\n",
  1808. "GuiCanvas",
  1809. "void popDialog();"
  1810. );
  1811. DefineEngineMethod( GuiCanvas, popDialog, void, (GuiControl * gui), (nullAsType<GuiControl*>()), "(GuiControl ctrl=NULL)"
  1812. "@hide")
  1813. {
  1814. if (gui)
  1815. object->popDialogControl(gui);
  1816. else
  1817. object->popDialogControl();
  1818. }
  1819. ConsoleDocFragment _popLayer1(
  1820. "@brief Removes the top most layer of dialogs\n\n"
  1821. "@tsexample\n"
  1822. "Canvas.popLayer();\n"
  1823. "@endtsexample\n\n",
  1824. "GuiCanvas",
  1825. "void popLayer();"
  1826. );
  1827. ConsoleDocFragment _popLayer2(
  1828. "@brief Removes a specified layer of dialogs\n\n"
  1829. "@param layer Number of the layer to pop\n\n"
  1830. "@tsexample\n"
  1831. "Canvas.popLayer(1);\n"
  1832. "@endtsexample\n\n",
  1833. "GuiCanvas",
  1834. "void popLayer(S32 layer);"
  1835. );
  1836. DefineEngineMethod( GuiCanvas, popLayer, void, (S32 layer), (0), "(int layer)"
  1837. "@hide")
  1838. {
  1839. object->popDialogControl(layer);
  1840. }
  1841. DefineEngineMethod( GuiCanvas, cursorOn, void, (),,
  1842. "@brief Turns on the mouse cursor.\n\n"
  1843. "@tsexample\n"
  1844. "Canvas.cursorOn();\n"
  1845. "@endtsexample\n\n")
  1846. {
  1847. object->setCursorON(true);
  1848. }
  1849. DefineEngineMethod( GuiCanvas, cursorOff, void, (),,
  1850. "@brief Turns on the mouse off.\n\n"
  1851. "@tsexample\n"
  1852. "Canvas.cursorOff();\n"
  1853. "@endtsexample\n\n")
  1854. {
  1855. object->setCursorON(false);
  1856. }
  1857. DefineEngineMethod( GuiCanvas, setCursor, void, (GuiCursor* cursor),,
  1858. "@brief Sets the cursor for the canvas.\n\n"
  1859. "@param cursor Name of the GuiCursor to use\n\n"
  1860. "@tsexample\n"
  1861. "Canvas.setCursor(\"DefaultCursor\");\n"
  1862. "@endtsexample\n\n")
  1863. {
  1864. if(!cursor)
  1865. {
  1866. Con::errorf("GuiCanvas::setCursor - Invalid GuiCursor name or ID");
  1867. return;
  1868. }
  1869. object->setCursor(cursor);
  1870. }
  1871. DefineEngineMethod( GuiCanvas, renderFront, void, ( bool enable ),,
  1872. "@brief This turns on/off front-buffer rendering.\n\n"
  1873. "@param enable True if all rendering should be done to the front buffer\n\n"
  1874. "@tsexample\n"
  1875. "Canvas.renderFront(false);\n"
  1876. "@endtsexample\n\n")
  1877. {
  1878. object->setRenderFront(enable);
  1879. }
  1880. DefineEngineMethod( GuiCanvas, showCursor, void, (),,
  1881. "@brief Enable rendering of the cursor.\n\n"
  1882. "@tsexample\n"
  1883. "Canvas.showCursor();\n"
  1884. "@endtsexample\n\n")
  1885. {
  1886. object->showCursor(true);
  1887. }
  1888. DefineEngineMethod( GuiCanvas, hideCursor, void, (),,
  1889. "@brief Disable rendering of the cursor.\n\n"
  1890. "@tsexample\n"
  1891. "Canvas.hideCursor();\n"
  1892. "@endtsexample\n\n")
  1893. {
  1894. object->showCursor(false);
  1895. }
  1896. DefineEngineMethod( GuiCanvas, isCursorOn, bool, (),,
  1897. "@brief Determines if mouse cursor is enabled.\n\n"
  1898. "@tsexample\n"
  1899. "// Is cursor on?\n"
  1900. "if(Canvas.isCursorOn())\n"
  1901. " echo(\"Canvas cursor is on\");\n"
  1902. "@endtsexample\n\n"
  1903. "@return Returns true if the cursor is on.\n\n")
  1904. {
  1905. return object->isCursorON();
  1906. }
  1907. DefineEngineMethod( GuiCanvas, isCursorShown, bool, (),,
  1908. "@brief Determines if mouse cursor is rendering.\n\n"
  1909. "@tsexample\n"
  1910. "// Is cursor rendering?\n"
  1911. "if(Canvas.isCursorShown())\n"
  1912. " echo(\"Canvas cursor is rendering\");\n"
  1913. "@endtsexample\n\n"
  1914. "@return Returns true if the cursor is rendering.\n\n")
  1915. {
  1916. return object->isCursorShown();
  1917. }
  1918. DefineEngineMethod( GuiCanvas, repaint, void, ( S32 elapsedMS ), (0),
  1919. "@brief Force canvas to redraw.\n"
  1920. "If the elapsed time is greater than the time since the last paint "
  1921. "then the repaint will be skipped.\n"
  1922. "@param elapsedMS The optional elapsed time in milliseconds.\n\n"
  1923. "@tsexample\n"
  1924. "Canvas.repaint();\n"
  1925. "@endtsexample\n\n")
  1926. {
  1927. object->repaint(elapsedMS < 0 ? 0 : elapsedMS);
  1928. }
  1929. DefineEngineMethod( GuiCanvas, reset, void, (),,
  1930. "@brief Reset the update regions for the canvas.\n\n"
  1931. "@tsexample\n"
  1932. "Canvas.reset();\n"
  1933. "@endtsexample\n\n")
  1934. {
  1935. object->resetUpdateRegions();
  1936. }
  1937. DefineEngineMethod( GuiCanvas, getCursorPos, Point2I, (),,
  1938. "@brief Get the current position of the cursor in screen-space. Note that this position"
  1939. " might be outside the Torque window. If you want to get the position within the Canvas,"
  1940. " call screenToClient on the result.\n\n"
  1941. "@see Canvas::screenToClient()\n\n"
  1942. "@param param Description\n\n"
  1943. "@tsexample\n"
  1944. "%cursorPos = Canvas.getCursorPos();\n"
  1945. "@endtsexample\n\n"
  1946. "@return Screen coordinates of mouse cursor, in format \"X Y\"")
  1947. {
  1948. return object->getCursorPos();
  1949. }
  1950. ConsoleDocFragment _setCursorPos1(
  1951. "@brief Sets the position of the cursor\n\n"
  1952. "@param pos Point, in screenspace for the cursor. Formatted as (\"x y\")\n\n"
  1953. "@tsexample\n"
  1954. "Canvas.setCursorPos(\"0 0\");\n"
  1955. "@endtsexample\n\n",
  1956. "GuiCanvas",
  1957. "bool setCursorPos( Point2I pos );"
  1958. );
  1959. ConsoleDocFragment _setCursorPos2(
  1960. "@brief Sets the position of the cursor\n\n"
  1961. "@param posX X-coordinate, in screenspace for the cursor.\n"
  1962. "@param posY Y-coordinate, in screenspace for the cursor.\n\n"
  1963. "@tsexample\n"
  1964. "Canvas.setCursorPos(0,0);\n"
  1965. "@endtsexample\n\n",
  1966. "GuiCanvas",
  1967. "bool setCursorPos( F32 posX, F32 posY);"
  1968. );
  1969. DefineEngineMethod( GuiCanvas, setCursorPos, void, (Point2I pos), , "(Point2I pos)"
  1970. "@hide")
  1971. {
  1972. object->setCursorPos(pos);
  1973. }
  1974. DefineEngineMethod( GuiCanvas, getMouseControl, S32, (),,
  1975. "@brief Gets the gui control under the mouse.\n\n"
  1976. "@tsexample\n"
  1977. "%underMouse = Canvas.getMouseControl();\n"
  1978. "@endtsexample\n\n"
  1979. "@return ID of the gui control, if one was found. NULL otherwise")
  1980. {
  1981. GuiControl* control = object->getMouseControl();
  1982. if (control)
  1983. return control->getId();
  1984. return NULL;
  1985. }
  1986. DefineEngineFunction(excludeOtherInstance, bool, (const char* appIdentifer),,
  1987. "@brief Used to exclude/prevent all other instances using the same identifier specified\n\n"
  1988. "@note Not used on OSX, Xbox, or in Win debug builds\n\n"
  1989. "@param appIdentifier Name of the app set up for exclusive use.\n"
  1990. "@return False if another app is running that specified the same appIdentifier\n\n"
  1991. "@ingroup Platform\n"
  1992. "@ingroup GuiCore")
  1993. {
  1994. // mac can only run one instance in general.
  1995. #if !defined(TORQUE_OS_MAC) && !defined(TORQUE_DEBUG) && !defined(TORQUE_OS_LINUX)
  1996. return Platform::excludeOtherInstances(appIdentifer);
  1997. #else
  1998. // We can just return true if we get here.
  1999. return true;
  2000. #endif
  2001. }
  2002. DefineEngineMethod( GuiCanvas, getExtent, Point2I, (),,
  2003. "@brief Returns the dimensions of the canvas\n\n"
  2004. "@tsexample\n"
  2005. "%extent = Canvas.getExtent();\n"
  2006. "@endtsexample\n\n"
  2007. "@return Width and height of canvas. Formatted as numerical values in a single string \"# #\"")
  2008. {
  2009. return object->getExtent();
  2010. }
  2011. DefineEngineMethod( GuiCanvas, setWindowTitle, void, ( const char* newTitle),,
  2012. "@brief Change the title of the OS window.\n\n"
  2013. "@param newTitle String containing the new name\n\n"
  2014. "@tsexample\n"
  2015. "Canvas.setWindowTitle(\"Documentation Rocks!\");\n"
  2016. "@endtsexample\n\n")
  2017. {
  2018. object->setWindowTitle(newTitle);
  2019. }
  2020. DefineEngineMethod( GuiCanvas, findFirstMatchingMonitor, S32, (const char* name),,
  2021. "@brief Find the first monitor index that matches the given name.\n\n"
  2022. "The actual match algorithm depends on the implementation.\n"
  2023. "@param name The name to search for.\n\n"
  2024. "@return The number of monitors attached to the system, including the default monoitor.")
  2025. {
  2026. return PlatformWindowManager::get()->findFirstMatchingMonitor(name);
  2027. }
  2028. DefineEngineMethod( GuiCanvas, getMonitorCount, S32, (),,
  2029. "@brief Gets the number of monitors attached to the system.\n\n"
  2030. "@return The number of monitors attached to the system, including the default monoitor.")
  2031. {
  2032. return PlatformWindowManager::get()->getMonitorCount();
  2033. }
  2034. DefineEngineMethod( GuiCanvas, getMonitorName, const char*, (S32 index),,
  2035. "@brief Gets the name of the requested monitor.\n\n"
  2036. "@param index The monitor index.\n\n"
  2037. "@return The name of the requested monitor.")
  2038. {
  2039. return PlatformWindowManager::get()->getMonitorName(index);
  2040. }
  2041. DefineEngineMethod( GuiCanvas, getMonitorRect, RectI, (S32 index),,
  2042. "@brief Gets the region of the requested monitor.\n\n"
  2043. "@param index The monitor index.\n\n"
  2044. "@return The rectangular region of the requested monitor.")
  2045. {
  2046. return PlatformWindowManager::get()->getMonitorRect(index);
  2047. }
  2048. DefineEngineMethod( GuiCanvas, getMonitorUsableRect, RectI, (S32 index),,
  2049. "@brief Use this function to get the usable desktop area represented by a display, with the primary display located at 0,0.\n\n"
  2050. "This is the same area as Canvas.getMonitorRect() reports, but with portions reserved by the system removed. "
  2051. "For example, on Apple Mac OS X, this subtracts the area occupied by the menu bar and dock.\n"
  2052. "Setting a window to be fullscreen generally bypasses these unusable areas, so these are good guidelines for "
  2053. "the maximum space available to a non - fullscreen window."
  2054. "@param index The monitor index.\n\n"
  2055. "@return The rectangular region of the requested monitor.")
  2056. {
  2057. return PlatformWindowManager::get()->getMonitorUsableRect(index);
  2058. }
  2059. DefineEngineMethod(GuiCanvas, getMonitorModeCount, S32, (S32 monitorIndex), (0),
  2060. "Gets the number of video modes available on the selected monitor.\n\n")
  2061. {
  2062. return PlatformWindowManager::get()->getMonitorModeCount(monitorIndex);
  2063. }
  2064. DefineEngineMethod(GuiCanvas, getMonitorMode, const char*, (S32 monitorIndex, S32 modeIndex), (0),
  2065. "Gets a video mode string from the selected monitor.\n\n")
  2066. {
  2067. char* buf = Con::getReturnBuffer(PlatformWindowManager::get()->getMonitorMode(monitorIndex, modeIndex));
  2068. return buf;
  2069. }
  2070. DefineEngineMethod(GuiCanvas, getMonitorDesktopMode, const char*, (S32 monitorIndex), (0),
  2071. "Gets the current desktop mode for the selected monitor.\n\n")
  2072. {
  2073. char* buf = Con::getReturnBuffer(PlatformWindowManager::get()->getMonitorDesktopMode(monitorIndex));
  2074. return buf;
  2075. }
  2076. DefineEngineMethod( GuiCanvas, getVideoMode, const char*, (),,
  2077. "@brief Gets the current screen mode as a string.\n\n"
  2078. "The return string will contain 5 values (width, height, fullscreen, bitdepth, refreshRate). "
  2079. "You will need to parse out each one for individual use.\n\n"
  2080. "@tsexample\n"
  2081. "%screenWidth = getWord(Canvas.getVideoMode(), 0);\n"
  2082. "%screenHeight = getWord(Canvas.getVideoMode(), 1);\n"
  2083. "%isFullscreen = getWord(Canvas.getVideoMode(), 2);\n"
  2084. "%bitdepth = getWord(Canvas.getVideoMode(), 3);\n"
  2085. "%refreshRate = getWord(Canvas.getVideoMode(), 4);\n"
  2086. "@endtsexample\n\n"
  2087. "@return String formatted with screen width, screen height, screen mode, bit depth, and refresh rate.")
  2088. {
  2089. // Grab the video mode.
  2090. if (!object->getPlatformWindow())
  2091. return "";
  2092. GFXVideoMode vm = object->getPlatformWindow()->getVideoMode();
  2093. char* buf = Con::getReturnBuffer(vm.toString());
  2094. return buf;
  2095. }
  2096. DefineEngineMethod( GuiCanvas, getModeCount, S32, (),,
  2097. "@brief Gets the number of modes available on this device.\n\n"
  2098. "@param param Description\n\n"
  2099. "@tsexample\n"
  2100. "%modeCount = Canvas.getModeCount()\n"
  2101. "@endtsexample\n\n"
  2102. "@return The number of video modes supported by the device")
  2103. {
  2104. if (!object->getPlatformWindow())
  2105. return 0;
  2106. // Grab the available mode list from the device.
  2107. const Vector<GFXVideoMode>* const modeList =
  2108. object->getPlatformWindow()->getGFXDevice()->getVideoModeList();
  2109. // Return the number of resolutions.
  2110. return modeList->size();
  2111. }
  2112. DefineEngineMethod( GuiCanvas, getMode, const char*, (S32 modeId),,
  2113. "@brief Gets information on the specified mode of this device.\n\n"
  2114. "@param modeId Index of the mode to get data from.\n"
  2115. "@return A video mode string given an adapter and mode index.\n\n"
  2116. "@see GuiCanvas::getVideoMode()")
  2117. {
  2118. if (!object->getPlatformWindow())
  2119. return 0;
  2120. // Grab the available mode list from the device.
  2121. const Vector<GFXVideoMode>* const modeList =
  2122. object->getPlatformWindow()->getGFXDevice()->getVideoModeList();
  2123. // Get the desired index and confirm it's valid.
  2124. S32 idx = modeId;
  2125. if((idx < 0) || (idx >= modeList->size()))
  2126. {
  2127. Con::errorf("GuiCanvas::getResolution - You requested an out of range index of %d. Please specify an index in the range [0, %d).", idx, modeList->size());
  2128. return "";
  2129. }
  2130. // Great - we got something valid, so convert the videomode into a
  2131. // string and return to the user.
  2132. GFXVideoMode vm = (*modeList)[idx];
  2133. char *retString = Con::getReturnBuffer(vm.toString());
  2134. return retString;
  2135. }
  2136. DefineEngineMethod( GuiCanvas, toggleFullscreen, void, (),,
  2137. "@brief toggle canvas from fullscreen to windowed mode or back.\n\n"
  2138. "@tsexample\n"
  2139. "// If we are in windowed mode, the following will put is in fullscreen\n"
  2140. "Canvas.toggleFullscreen();"
  2141. "@endtsexample\n\n")
  2142. {
  2143. if (Platform::getWebDeployment())
  2144. return;
  2145. if (!object->getPlatformWindow())
  2146. return;
  2147. if (Journal::IsRecording() || Journal::IsPlaying())
  2148. return;
  2149. // Get the window's video mode.
  2150. GFXVideoMode origMode = object->getPlatformWindow()->getVideoMode();
  2151. // And grab the device its using.
  2152. GFXDevice *device = object->getPlatformWindow()->getGFXDevice();
  2153. // Toggle the fullscreen bit.
  2154. GFXVideoMode newMode = origMode;
  2155. newMode.fullScreen = !origMode.fullScreen;
  2156. // CodeReview Toggling might be better served by reading the fullscreen
  2157. // or windowed video mode pref and setting that instead [bjg 5/2/07]
  2158. if(newMode.fullScreen == true)
  2159. {
  2160. // Are we going to fullscreen? If so find the first matching resolution that
  2161. // is equal to or bigger in size, and has same BPP - windows
  2162. // are often strangely sized and will need to be adjusted to a viable
  2163. // fullscreen res.
  2164. for(S32 i=0; i<device->getVideoModeList()->size(); i++)
  2165. {
  2166. const GFXVideoMode &newVm = (*(device->getVideoModeList()))[i];
  2167. if(newMode.resolution.x > newVm.resolution.x)
  2168. continue;
  2169. if(newMode.resolution.y > newVm.resolution.y)
  2170. continue;
  2171. if(newMode.bitDepth != newVm.bitDepth)
  2172. continue;
  2173. // Great - got a match.
  2174. newMode = newVm;
  2175. newMode.fullScreen = true;
  2176. break;
  2177. }
  2178. }
  2179. // Ok, we have new video mode. Set it!
  2180. object->getPlatformWindow()->setVideoMode(newMode);
  2181. }
  2182. DefineEngineMethod( GuiCanvas, clientToScreen, Point2I, ( Point2I coordinate ),,
  2183. "Translate a coordinate from canvas window-space to screen-space.\n"
  2184. "@param coordinate The coordinate in window-space.\n"
  2185. "@return The given coordinate translated to screen-space." )
  2186. {
  2187. if( !object->getPlatformWindow() )
  2188. return coordinate;
  2189. return object->getPlatformWindow()->clientToScreen( coordinate );
  2190. }
  2191. DefineEngineMethod( GuiCanvas, screenToClient, Point2I, ( Point2I coordinate ),,
  2192. "Translate a coordinate from screen-space to canvas window-space.\n"
  2193. "@param coordinate The coordinate in screen-space.\n"
  2194. "@return The given coordinate translated to window-space." )
  2195. {
  2196. if( !object->getPlatformWindow() )
  2197. return coordinate;
  2198. return object->getPlatformWindow()->screenToClient( coordinate );
  2199. }
  2200. DefineEngineMethod( GuiCanvas, getWindowPosition, Point2I, (),,
  2201. "Get the current position of the platform window associated with the canvas.\n"
  2202. "@return The window position of the canvas in screen-space." )
  2203. {
  2204. if( !object->getPlatformWindow() )
  2205. return Point2I( 0, 0 );
  2206. return object->getPlatformWindow()->getPosition();
  2207. }
  2208. DefineEngineMethod( GuiCanvas, setWindowPosition, void, ( Point2I position ),,
  2209. "Set the position of the platform window associated with the canvas.\n"
  2210. "@param position The new position of the window in screen-space." )
  2211. {
  2212. if( !object->getPlatformWindow() )
  2213. return;
  2214. object->getPlatformWindow()->setPosition( position );
  2215. }
  2216. DefineEngineMethod( GuiCanvas, isFullscreen, bool, (), , "() - Is this canvas currently fullscreen?" )
  2217. {
  2218. if (Platform::getWebDeployment())
  2219. return false;
  2220. if (!object->getPlatformWindow())
  2221. return false;
  2222. return object->getPlatformWindow()->getVideoMode().fullScreen;
  2223. }
  2224. DefineEngineMethod( GuiCanvas, minimizeWindow, void, (), , "() - minimize this canvas' window." )
  2225. {
  2226. PlatformWindow* window = object->getPlatformWindow();
  2227. if ( window )
  2228. window->minimize();
  2229. }
  2230. DefineEngineMethod( GuiCanvas, isMinimized, bool, (), , "()" )
  2231. {
  2232. PlatformWindow* window = object->getPlatformWindow();
  2233. if ( window )
  2234. return window->isMinimized();
  2235. return false;
  2236. }
  2237. DefineEngineMethod( GuiCanvas, isMaximized, bool, (), , "()" )
  2238. {
  2239. PlatformWindow* window = object->getPlatformWindow();
  2240. if ( window )
  2241. return window->isMaximized();
  2242. return false;
  2243. }
  2244. DefineEngineMethod( GuiCanvas, maximizeWindow, void, (), , "() - maximize this canvas' window." )
  2245. {
  2246. PlatformWindow* window = object->getPlatformWindow();
  2247. if ( window )
  2248. window->maximize();
  2249. }
  2250. DefineEngineMethod( GuiCanvas, restoreWindow, void, (), , "() - restore this canvas' window." )
  2251. {
  2252. PlatformWindow* window = object->getPlatformWindow();
  2253. if( window )
  2254. window->restore();
  2255. }
  2256. DefineEngineMethod( GuiCanvas, setFocus, void, (), , "() - Claim OS input focus for this canvas' window.")
  2257. {
  2258. PlatformWindow* window = object->getPlatformWindow();
  2259. if (window)
  2260. {
  2261. window->setFocus();
  2262. window->appEvent.trigger(window->getWindowId(), GainFocus);
  2263. }
  2264. }
  2265. DefineEngineMethod( GuiCanvas, setMenuBar, void, ( GuiControl* menu ),,
  2266. "Translate a coordinate from canvas window-space to screen-space.\n"
  2267. "@param coordinate The coordinate in window-space.\n"
  2268. "@return The given coordinate translated to screen-space." )
  2269. {
  2270. return object->setMenuBar( menu );
  2271. }
  2272. DefineEngineMethod( GuiCanvas, setVideoMode, void,
  2273. (U32 width, U32 height, bool fullscreen, U32 bitDepth, U32 refreshRate, U32 antialiasLevel),
  2274. ( false, 0, 0, 0),
  2275. "(int width, int height, bool fullscreen, [int bitDepth], [int refreshRate], [int antialiasLevel] )\n"
  2276. "Change the video mode of this canvas. This method has the side effect of setting the $pref::Video::mode to the new values.\n\n"
  2277. "\\param width The screen width to set.\n"
  2278. "\\param height The screen height to set.\n"
  2279. "\\param fullscreen Specify true to run fullscreen or false to run in a window\n"
  2280. "\\param bitDepth [optional] The desired bit-depth. Defaults to the current setting. This parameter is ignored if you are running in a window.\n"
  2281. "\\param refreshRate [optional] The desired refresh rate. Defaults to the current setting. This parameter is ignored if you are running in a window"
  2282. "\\param antialiasLevel [optional] The level of anti-aliasing to apply 0 = none" )
  2283. {
  2284. if (!object->getPlatformWindow())
  2285. return;
  2286. if (Journal::IsRecording() || Journal::IsPlaying())
  2287. return;
  2288. // Update the video mode and tell the window to reset.
  2289. GFXVideoMode vm = object->getPlatformWindow()->getVideoMode();
  2290. bool changed = false;
  2291. if (width == 0 && height > 0)
  2292. {
  2293. // Our width is 0 but our height isn't...
  2294. // Try to find a matching width
  2295. for(S32 i=0; i<object->getPlatformWindow()->getGFXDevice()->getVideoModeList()->size(); i++)
  2296. {
  2297. const GFXVideoMode &newVm = (*(object->getPlatformWindow()->getGFXDevice()->getVideoModeList()))[i];
  2298. if(newVm.resolution.y == height)
  2299. {
  2300. width = newVm.resolution.x;
  2301. changed = true;
  2302. break;
  2303. }
  2304. }
  2305. }
  2306. else if (height == 0 && width > 0)
  2307. {
  2308. // Our height is 0 but our width isn't...
  2309. // Try to find a matching height
  2310. for(S32 i=0; i<object->getPlatformWindow()->getGFXDevice()->getVideoModeList()->size(); i++)
  2311. {
  2312. const GFXVideoMode &newVm = (*(object->getPlatformWindow()->getGFXDevice()->getVideoModeList()))[i];
  2313. if(newVm.resolution.x == width)
  2314. {
  2315. height = newVm.resolution.y;
  2316. changed = true;
  2317. break;
  2318. }
  2319. }
  2320. }
  2321. if (width == 0 || height == 0)
  2322. {
  2323. // Got a bad size for both of our dimensions or one of our dimensions and
  2324. // didn't get a match for the other default back to our current resolution
  2325. width = vm.resolution.x;
  2326. height = vm.resolution.y;
  2327. changed = true;
  2328. }
  2329. if (changed)
  2330. {
  2331. Con::errorf("GuiCanvas::setVideoMode(): Error - Invalid resolution of (%d, %d) - attempting (%d, %d)", width, height, width, height);
  2332. }
  2333. vm.resolution = Point2I(width, height);
  2334. vm.fullScreen = fullscreen;
  2335. if (Platform::getWebDeployment())
  2336. vm.fullScreen = false;
  2337. // These optional params are set to default at construction of vm. If they
  2338. // aren't specified, just leave them at whatever they were set to.
  2339. if (bitDepth > 0)
  2340. {
  2341. vm.bitDepth = bitDepth;
  2342. }
  2343. if (refreshRate > 0)
  2344. {
  2345. vm.refreshRate = refreshRate;
  2346. }
  2347. if (antialiasLevel > 0)
  2348. {
  2349. vm.antialiasLevel = antialiasLevel;
  2350. }
  2351. object->getPlatformWindow()->setVideoMode(vm);
  2352. // Store the new mode into a pref.
  2353. Con::setVariable( "$pref::Video::mode", vm.toString() );
  2354. }
  2355. DefineEngineMethod(GuiCanvas, showWindow, void, (),, "")
  2356. {
  2357. if (!object->getPlatformWindow())
  2358. return;
  2359. object->getPlatformWindow()->show();
  2360. WindowManager->setDisplayWindow(true);
  2361. object->getPlatformWindow()->setDisplayWindow(true);
  2362. }
  2363. DefineEngineMethod(GuiCanvas, hideWindow, void, (),, "")
  2364. {
  2365. if (!object->getPlatformWindow())
  2366. return;
  2367. object->getPlatformWindow()->hide();
  2368. WindowManager->setDisplayWindow(false);
  2369. object->getPlatformWindow()->setDisplayWindow(false);
  2370. }
  2371. DefineEngineMethod(GuiCanvas, cursorClick, void, (S32 buttonId, bool isDown), , "")
  2372. {
  2373. object->cursorClick(buttonId, isDown);
  2374. }
  2375. DefineEngineMethod(GuiCanvas, cursorNudge, void, (F32 x, F32 y), , "")
  2376. {
  2377. object->cursorNudge(x, y);
  2378. }
  2379. // This function allows resetting of the video-mode from script. It was motivated by
  2380. // the need to temporarily disable vsync during datablock cache load to avoid a
  2381. // significant slowdown.
  2382. bool AFX_forceVideoReset = false;
  2383. DefineEngineMethod(GuiCanvas, resetVideoMode, void, (), , "")
  2384. {
  2385. PlatformWindow* window = object->getPlatformWindow();
  2386. if (window)
  2387. {
  2388. GFXWindowTarget* gfx_target = window->getGFXTarget();
  2389. if (gfx_target)
  2390. {
  2391. AFX_forceVideoReset = true;
  2392. gfx_target->resetMode();
  2393. AFX_forceVideoReset = false;
  2394. }
  2395. }
  2396. }