spatial_editor_plugin.cpp 212 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270
  1. /*************************************************************************/
  2. /* spatial_editor_plugin.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "spatial_editor_plugin.h"
  31. #include "core/math/camera_matrix.h"
  32. #include "core/os/input.h"
  33. #include "core/os/keyboard.h"
  34. #include "core/print_string.h"
  35. #include "core/project_settings.h"
  36. #include "core/sort_array.h"
  37. #include "editor/editor_node.h"
  38. #include "editor/editor_settings.h"
  39. #include "editor/plugins/animation_player_editor_plugin.h"
  40. #include "editor/plugins/script_editor_plugin.h"
  41. #include "editor/script_editor_debugger.h"
  42. #include "editor/spatial_editor_gizmos.h"
  43. #include "scene/3d/camera.h"
  44. #include "scene/3d/collision_shape.h"
  45. #include "scene/3d/mesh_instance.h"
  46. #include "scene/3d/physics_body.h"
  47. #include "scene/3d/visual_instance.h"
  48. #include "scene/resources/packed_scene.h"
  49. #include "scene/resources/surface_tool.h"
  50. #define DISTANCE_DEFAULT 4
  51. #define GIZMO_ARROW_SIZE 0.35
  52. #define GIZMO_RING_HALF_WIDTH 0.1
  53. #define GIZMO_SCALE_DEFAULT 0.15
  54. #define GIZMO_PLANE_SIZE 0.2
  55. #define GIZMO_PLANE_DST 0.3
  56. #define GIZMO_CIRCLE_SIZE 1.1
  57. #define GIZMO_SCALE_OFFSET (GIZMO_CIRCLE_SIZE + 0.3)
  58. #define GIZMO_ARROW_OFFSET (GIZMO_CIRCLE_SIZE + 0.3)
  59. #define ZOOM_MIN_DISTANCE 0.001
  60. #define ZOOM_MULTIPLIER 1.08
  61. #define ZOOM_INDICATOR_DELAY_S 1.5
  62. #define FREELOOK_MIN_SPEED 0.01
  63. #define FREELOOK_SPEED_MULTIPLIER 1.08
  64. #define MIN_Z 0.01
  65. #define MAX_Z 1000000.0
  66. #define MIN_FOV 0.01
  67. #define MAX_FOV 179
  68. void SpatialEditorViewport::_update_camera(float p_interp_delta) {
  69. bool is_orthogonal = camera->get_projection() == Camera::PROJECTION_ORTHOGONAL;
  70. Cursor old_camera_cursor = camera_cursor;
  71. camera_cursor = cursor;
  72. if (p_interp_delta > 0) {
  73. //-------
  74. // Perform smoothing
  75. if (is_freelook_active()) {
  76. // Higher inertia should increase "lag" (lerp with factor between 0 and 1)
  77. // Inertia of zero should produce instant movement (lerp with factor of 1) in this case it returns a really high value and gets clamped to 1.
  78. real_t inertia = EDITOR_GET("editors/3d/freelook/freelook_inertia");
  79. inertia = MAX(0.001, inertia);
  80. real_t factor = (1.0 / inertia) * p_interp_delta;
  81. // We interpolate a different point here, because in freelook mode the focus point (cursor.pos) orbits around eye_pos
  82. camera_cursor.eye_pos = old_camera_cursor.eye_pos.linear_interpolate(cursor.eye_pos, CLAMP(factor, 0, 1));
  83. float orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/orbit_inertia");
  84. orbit_inertia = MAX(0.0001, orbit_inertia);
  85. camera_cursor.x_rot = Math::lerp(old_camera_cursor.x_rot, cursor.x_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  86. camera_cursor.y_rot = Math::lerp(old_camera_cursor.y_rot, cursor.y_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  87. Vector3 forward = to_camera_transform(camera_cursor).basis.xform(Vector3(0, 0, -1));
  88. camera_cursor.pos = camera_cursor.eye_pos + forward * camera_cursor.distance;
  89. } else {
  90. //when not being manipulated, move softly
  91. float free_orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/orbit_inertia");
  92. float free_translation_inertia = EDITOR_GET("editors/3d/navigation_feel/translation_inertia");
  93. //when being manipulated, move more quickly
  94. float manip_orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/manipulation_orbit_inertia");
  95. float manip_translation_inertia = EDITOR_GET("editors/3d/navigation_feel/manipulation_translation_inertia");
  96. float zoom_inertia = EDITOR_GET("editors/3d/navigation_feel/zoom_inertia");
  97. //determine if being manipulated
  98. bool manipulated = Input::get_singleton()->get_mouse_button_mask() & (2 | 4);
  99. manipulated |= Input::get_singleton()->is_key_pressed(KEY_SHIFT);
  100. manipulated |= Input::get_singleton()->is_key_pressed(KEY_ALT);
  101. manipulated |= Input::get_singleton()->is_key_pressed(KEY_CONTROL);
  102. float orbit_inertia = MAX(0.00001, manipulated ? manip_orbit_inertia : free_orbit_inertia);
  103. float translation_inertia = MAX(0.0001, manipulated ? manip_translation_inertia : free_translation_inertia);
  104. zoom_inertia = MAX(0.0001, zoom_inertia);
  105. camera_cursor.x_rot = Math::lerp(old_camera_cursor.x_rot, cursor.x_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  106. camera_cursor.y_rot = Math::lerp(old_camera_cursor.y_rot, cursor.y_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  107. camera_cursor.pos = old_camera_cursor.pos.linear_interpolate(cursor.pos, MIN(1.f, p_interp_delta * (1 / translation_inertia)));
  108. camera_cursor.distance = Math::lerp(old_camera_cursor.distance, cursor.distance, MIN(1.f, p_interp_delta * (1 / zoom_inertia)));
  109. }
  110. }
  111. //-------
  112. // Apply camera transform
  113. float tolerance = 0.001;
  114. bool equal = true;
  115. if (Math::abs(old_camera_cursor.x_rot - camera_cursor.x_rot) > tolerance || Math::abs(old_camera_cursor.y_rot - camera_cursor.y_rot) > tolerance) {
  116. equal = false;
  117. }
  118. if (equal && old_camera_cursor.pos.distance_squared_to(camera_cursor.pos) > tolerance * tolerance) {
  119. equal = false;
  120. }
  121. if (equal && Math::abs(old_camera_cursor.distance - camera_cursor.distance) > tolerance) {
  122. equal = false;
  123. }
  124. if (!equal || p_interp_delta == 0 || is_freelook_active() || is_orthogonal != orthogonal) {
  125. camera->set_global_transform(to_camera_transform(camera_cursor));
  126. if (orthogonal)
  127. camera->set_orthogonal(2 * cursor.distance, 0.1, 8192);
  128. else
  129. camera->set_perspective(get_fov(), get_znear(), get_zfar());
  130. update_transform_gizmo_view();
  131. }
  132. }
  133. Transform SpatialEditorViewport::to_camera_transform(const Cursor &p_cursor) const {
  134. Transform camera_transform;
  135. camera_transform.translate(p_cursor.pos);
  136. camera_transform.basis.rotate(Vector3(1, 0, 0), -p_cursor.x_rot);
  137. camera_transform.basis.rotate(Vector3(0, 1, 0), -p_cursor.y_rot);
  138. if (orthogonal)
  139. camera_transform.translate(0, 0, 4096);
  140. else
  141. camera_transform.translate(0, 0, p_cursor.distance);
  142. return camera_transform;
  143. }
  144. int SpatialEditorViewport::get_selected_count() const {
  145. Map<Node *, Object *> &selection = editor_selection->get_selection();
  146. int count = 0;
  147. for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
  148. Spatial *sp = Object::cast_to<Spatial>(E->key());
  149. if (!sp)
  150. continue;
  151. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  152. if (!se)
  153. continue;
  154. count++;
  155. }
  156. return count;
  157. }
  158. float SpatialEditorViewport::get_znear() const {
  159. return CLAMP(spatial_editor->get_znear(), MIN_Z, MAX_Z);
  160. }
  161. float SpatialEditorViewport::get_zfar() const {
  162. return CLAMP(spatial_editor->get_zfar(), MIN_Z, MAX_Z);
  163. }
  164. float SpatialEditorViewport::get_fov() const {
  165. return CLAMP(spatial_editor->get_fov(), MIN_FOV, MAX_FOV);
  166. }
  167. Transform SpatialEditorViewport::_get_camera_transform() const {
  168. return camera->get_global_transform();
  169. }
  170. Vector3 SpatialEditorViewport::_get_camera_position() const {
  171. return _get_camera_transform().origin;
  172. }
  173. Point2 SpatialEditorViewport::_point_to_screen(const Vector3 &p_point) {
  174. return camera->unproject_position(p_point) * viewport_container->get_stretch_shrink();
  175. }
  176. Vector3 SpatialEditorViewport::_get_ray_pos(const Vector2 &p_pos) const {
  177. return camera->project_ray_origin(p_pos / viewport_container->get_stretch_shrink());
  178. }
  179. Vector3 SpatialEditorViewport::_get_camera_normal() const {
  180. return -_get_camera_transform().basis.get_axis(2);
  181. }
  182. Vector3 SpatialEditorViewport::_get_ray(const Vector2 &p_pos) const {
  183. return camera->project_ray_normal(p_pos / viewport_container->get_stretch_shrink());
  184. }
  185. void SpatialEditorViewport::_clear_selected() {
  186. editor_selection->clear();
  187. }
  188. void SpatialEditorViewport::_select_clicked(bool p_append, bool p_single) {
  189. if (!clicked)
  190. return;
  191. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(clicked));
  192. Spatial *selected = Object::cast_to<Spatial>(node);
  193. if (!selected)
  194. return;
  195. // Replace the node by the group if grouped
  196. while (node && node != editor->get_edited_scene()->get_parent()) {
  197. Spatial *selected_tmp = Object::cast_to<Spatial>(node);
  198. if (selected_tmp && node->has_meta("_edit_group_")) {
  199. selected = selected_tmp;
  200. }
  201. node = node->get_parent();
  202. }
  203. if (!_is_node_locked(selected))
  204. _select(selected, clicked_wants_append, true);
  205. }
  206. void SpatialEditorViewport::_select(Node *p_node, bool p_append, bool p_single) {
  207. if (!p_append) {
  208. editor_selection->clear();
  209. }
  210. if (editor_selection->is_selected(p_node)) {
  211. //erase
  212. editor_selection->remove_node(p_node);
  213. } else {
  214. editor_selection->add_node(p_node);
  215. }
  216. if (p_single) {
  217. if (Engine::get_singleton()->is_editor_hint())
  218. editor->call("edit_node", p_node);
  219. }
  220. }
  221. ObjectID SpatialEditorViewport::_select_ray(const Point2 &p_pos, bool p_append, bool &r_includes_current, int *r_gizmo_handle, bool p_alt_select) {
  222. if (r_gizmo_handle)
  223. *r_gizmo_handle = -1;
  224. Vector3 ray = _get_ray(p_pos);
  225. Vector3 pos = _get_ray_pos(p_pos);
  226. Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_ray(pos, ray, get_tree()->get_root()->get_world()->get_scenario());
  227. Set<Ref<EditorSpatialGizmo> > found_gizmos;
  228. Node *edited_scene = get_tree()->get_edited_scene_root();
  229. ObjectID closest = 0;
  230. Node *item = NULL;
  231. float closest_dist = 1e20;
  232. int selected_handle = -1;
  233. for (int i = 0; i < instances.size(); i++) {
  234. Spatial *spat = Object::cast_to<Spatial>(ObjectDB::get_instance(instances[i]));
  235. if (!spat)
  236. continue;
  237. Ref<EditorSpatialGizmo> seg = spat->get_gizmo();
  238. if ((!seg.is_valid()) || found_gizmos.has(seg)) {
  239. continue;
  240. }
  241. found_gizmos.insert(seg);
  242. Vector3 point;
  243. Vector3 normal;
  244. int handle = -1;
  245. bool inters = seg->intersect_ray(camera, p_pos, point, normal, &handle, p_alt_select);
  246. if (!inters)
  247. continue;
  248. float dist = pos.distance_to(point);
  249. if (dist < 0)
  250. continue;
  251. if (dist < closest_dist) {
  252. item = Object::cast_to<Node>(spat);
  253. while (item->get_owner() && item->get_owner() != edited_scene && !edited_scene->is_editable_instance(item->get_owner())) {
  254. item = item->get_owner();
  255. }
  256. closest = item->get_instance_id();
  257. closest_dist = dist;
  258. selected_handle = handle;
  259. }
  260. }
  261. if (!item)
  262. return 0;
  263. if (!editor_selection->is_selected(item) || (r_gizmo_handle && selected_handle >= 0)) {
  264. if (r_gizmo_handle)
  265. *r_gizmo_handle = selected_handle;
  266. }
  267. return closest;
  268. }
  269. void SpatialEditorViewport::_find_items_at_pos(const Point2 &p_pos, bool &r_includes_current, Vector<_RayResult> &results, bool p_alt_select) {
  270. Vector3 ray = _get_ray(p_pos);
  271. Vector3 pos = _get_ray_pos(p_pos);
  272. Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_ray(pos, ray, get_tree()->get_root()->get_world()->get_scenario());
  273. Set<Ref<EditorSpatialGizmo> > found_gizmos;
  274. r_includes_current = false;
  275. for (int i = 0; i < instances.size(); i++) {
  276. Spatial *spat = Object::cast_to<Spatial>(ObjectDB::get_instance(instances[i]));
  277. if (!spat)
  278. continue;
  279. Ref<EditorSpatialGizmo> seg = spat->get_gizmo();
  280. if (!seg.is_valid())
  281. continue;
  282. if (found_gizmos.has(seg))
  283. continue;
  284. found_gizmos.insert(seg);
  285. Vector3 point;
  286. Vector3 normal;
  287. int handle = -1;
  288. bool inters = seg->intersect_ray(camera, p_pos, point, normal, NULL, p_alt_select);
  289. if (!inters)
  290. continue;
  291. float dist = pos.distance_to(point);
  292. if (dist < 0)
  293. continue;
  294. if (editor_selection->is_selected(spat))
  295. r_includes_current = true;
  296. _RayResult res;
  297. res.item = spat;
  298. res.depth = dist;
  299. res.handle = handle;
  300. results.push_back(res);
  301. }
  302. if (results.empty())
  303. return;
  304. results.sort();
  305. }
  306. Vector3 SpatialEditorViewport::_get_screen_to_space(const Vector3 &p_vector3) {
  307. CameraMatrix cm;
  308. if (orthogonal) {
  309. cm.set_orthogonal(camera->get_size(), get_size().aspect(), get_znear() + p_vector3.z, get_zfar());
  310. } else {
  311. cm.set_perspective(get_fov(), get_size().aspect(), get_znear() + p_vector3.z, get_zfar());
  312. }
  313. float screen_w, screen_h;
  314. cm.get_viewport_size(screen_w, screen_h);
  315. Transform camera_transform;
  316. camera_transform.translate(cursor.pos);
  317. camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
  318. camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
  319. camera_transform.translate(0, 0, cursor.distance);
  320. return camera_transform.xform(Vector3(((p_vector3.x / get_size().width) * 2.0 - 1.0) * screen_w, ((1.0 - (p_vector3.y / get_size().height)) * 2.0 - 1.0) * screen_h, -(get_znear() + p_vector3.z)));
  321. }
  322. void SpatialEditorViewport::_select_region() {
  323. if (cursor.region_begin == cursor.region_end)
  324. return; //nothing really
  325. float z_offset = MAX(0.0, 5.0 - get_znear());
  326. Vector3 box[4] = {
  327. Vector3(
  328. MIN(cursor.region_begin.x, cursor.region_end.x),
  329. MIN(cursor.region_begin.y, cursor.region_end.y),
  330. z_offset),
  331. Vector3(
  332. MAX(cursor.region_begin.x, cursor.region_end.x),
  333. MIN(cursor.region_begin.y, cursor.region_end.y),
  334. z_offset),
  335. Vector3(
  336. MAX(cursor.region_begin.x, cursor.region_end.x),
  337. MAX(cursor.region_begin.y, cursor.region_end.y),
  338. z_offset),
  339. Vector3(
  340. MIN(cursor.region_begin.x, cursor.region_end.x),
  341. MAX(cursor.region_begin.y, cursor.region_end.y),
  342. z_offset)
  343. };
  344. Vector<Plane> frustum;
  345. Vector3 cam_pos = _get_camera_position();
  346. for (int i = 0; i < 4; i++) {
  347. Vector3 a = _get_screen_to_space(box[i]);
  348. Vector3 b = _get_screen_to_space(box[(i + 1) % 4]);
  349. if (orthogonal) {
  350. frustum.push_back(Plane(a, (a - b).normalized()));
  351. } else {
  352. frustum.push_back(Plane(a, b, cam_pos));
  353. }
  354. }
  355. if (!orthogonal) {
  356. Plane near(cam_pos, -_get_camera_normal());
  357. near.d -= get_znear();
  358. frustum.push_back(near);
  359. Plane far = -near;
  360. far.d += get_zfar();
  361. frustum.push_back(far);
  362. }
  363. Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_convex(frustum, get_tree()->get_root()->get_world()->get_scenario());
  364. Vector<Node *> selected;
  365. Node *edited_scene = get_tree()->get_edited_scene_root();
  366. for (int i = 0; i < instances.size(); i++) {
  367. Spatial *sp = Object::cast_to<Spatial>(ObjectDB::get_instance(instances[i]));
  368. if (!sp || _is_node_locked(sp))
  369. continue;
  370. Node *item = Object::cast_to<Node>(sp);
  371. while (item->get_owner() && item->get_owner() != edited_scene && !edited_scene->is_editable_instance(item->get_owner())) {
  372. item = item->get_owner();
  373. }
  374. // Replace the node by the group if grouped
  375. if (item->is_class("Spatial")) {
  376. Spatial *sel = Object::cast_to<Spatial>(item);
  377. while (item && item != editor->get_edited_scene()->get_parent()) {
  378. Spatial *selected_tmp = Object::cast_to<Spatial>(item);
  379. if (selected_tmp && item->has_meta("_edit_group_")) {
  380. sel = selected_tmp;
  381. }
  382. item = item->get_parent();
  383. }
  384. item = sel;
  385. }
  386. if (selected.find(item) != -1) continue;
  387. if (_is_node_locked(Object::cast_to<Spatial>(item))) continue;
  388. Ref<EditorSpatialGizmo> seg = sp->get_gizmo();
  389. if (!seg.is_valid())
  390. continue;
  391. if (seg->intersect_frustum(camera, frustum)) {
  392. selected.push_back(item);
  393. }
  394. }
  395. bool single = selected.size() == 1;
  396. for (int i = 0; i < selected.size(); i++) {
  397. _select(selected[i], true, single);
  398. }
  399. }
  400. void SpatialEditorViewport::_update_name() {
  401. String view_mode = orthogonal ? TTR("Orthogonal") : TTR("Perspective");
  402. if (name != "")
  403. view_menu->set_text(name + " " + view_mode);
  404. else
  405. view_menu->set_text(view_mode);
  406. view_menu->set_size(Vector2(0, 0)); // resets the button size
  407. }
  408. void SpatialEditorViewport::_compute_edit(const Point2 &p_point) {
  409. _edit.click_ray = _get_ray(Vector2(p_point.x, p_point.y));
  410. _edit.click_ray_pos = _get_ray_pos(Vector2(p_point.x, p_point.y));
  411. _edit.plane = TRANSFORM_VIEW;
  412. spatial_editor->update_transform_gizmo();
  413. _edit.center = spatial_editor->get_gizmo_transform().origin;
  414. List<Node *> &selection = editor_selection->get_selected_node_list();
  415. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  416. Spatial *sp = Object::cast_to<Spatial>(E->get());
  417. if (!sp)
  418. continue;
  419. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  420. if (!se)
  421. continue;
  422. se->original = se->sp->get_global_gizmo_transform();
  423. se->original_local = se->sp->get_local_gizmo_transform();
  424. }
  425. }
  426. static int _get_key_modifier_setting(const String &p_property) {
  427. switch (EditorSettings::get_singleton()->get(p_property).operator int()) {
  428. case 0: return 0;
  429. case 1: return KEY_SHIFT;
  430. case 2: return KEY_ALT;
  431. case 3: return KEY_META;
  432. case 4: return KEY_CONTROL;
  433. }
  434. return 0;
  435. }
  436. static int _get_key_modifier(Ref<InputEventWithModifiers> e) {
  437. if (e->get_shift())
  438. return KEY_SHIFT;
  439. if (e->get_alt())
  440. return KEY_ALT;
  441. if (e->get_control())
  442. return KEY_CONTROL;
  443. if (e->get_metakey())
  444. return KEY_META;
  445. return 0;
  446. }
  447. bool SpatialEditorViewport::_gizmo_select(const Vector2 &p_screenpos, bool p_highlight_only) {
  448. if (!spatial_editor->is_gizmo_visible())
  449. return false;
  450. if (get_selected_count() == 0) {
  451. if (p_highlight_only)
  452. spatial_editor->select_gizmo_highlight_axis(-1);
  453. return false;
  454. }
  455. Vector3 ray_pos = _get_ray_pos(Vector2(p_screenpos.x, p_screenpos.y));
  456. Vector3 ray = _get_ray(Vector2(p_screenpos.x, p_screenpos.y));
  457. Transform gt = spatial_editor->get_gizmo_transform();
  458. float gs = gizmo_scale;
  459. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_MOVE) {
  460. int col_axis = -1;
  461. float col_d = 1e20;
  462. for (int i = 0; i < 3; i++) {
  463. Vector3 grabber_pos = gt.origin + gt.basis.get_axis(i) * gs * (GIZMO_ARROW_OFFSET + (GIZMO_ARROW_SIZE * 0.5));
  464. float grabber_radius = gs * GIZMO_ARROW_SIZE;
  465. Vector3 r;
  466. if (Geometry::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) {
  467. float d = r.distance_to(ray_pos);
  468. if (d < col_d) {
  469. col_d = d;
  470. col_axis = i;
  471. }
  472. }
  473. }
  474. bool is_plane_translate = false;
  475. // plane select
  476. if (col_axis == -1) {
  477. col_d = 1e20;
  478. for (int i = 0; i < 3; i++) {
  479. Vector3 ivec2 = gt.basis.get_axis((i + 1) % 3).normalized();
  480. Vector3 ivec3 = gt.basis.get_axis((i + 2) % 3).normalized();
  481. Vector3 grabber_pos = gt.origin + (ivec2 + ivec3) * gs * (GIZMO_PLANE_SIZE + GIZMO_PLANE_DST);
  482. Vector3 r;
  483. Plane plane(gt.origin, gt.basis.get_axis(i).normalized());
  484. if (plane.intersects_ray(ray_pos, ray, &r)) {
  485. float dist = r.distance_to(grabber_pos);
  486. if (dist < (gs * GIZMO_PLANE_SIZE)) {
  487. float d = ray_pos.distance_to(r);
  488. if (d < col_d) {
  489. col_d = d;
  490. col_axis = i;
  491. is_plane_translate = true;
  492. }
  493. }
  494. }
  495. }
  496. }
  497. if (col_axis != -1) {
  498. if (p_highlight_only) {
  499. spatial_editor->select_gizmo_highlight_axis(col_axis + (is_plane_translate ? 6 : 0));
  500. } else {
  501. //handle plane translate
  502. _edit.mode = TRANSFORM_TRANSLATE;
  503. _compute_edit(Point2(p_screenpos.x, p_screenpos.y));
  504. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis + (is_plane_translate ? 3 : 0));
  505. }
  506. return true;
  507. }
  508. }
  509. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_ROTATE) {
  510. int col_axis = -1;
  511. float col_d = 1e20;
  512. for (int i = 0; i < 3; i++) {
  513. Plane plane(gt.origin, gt.basis.get_axis(i).normalized());
  514. Vector3 r;
  515. if (!plane.intersects_ray(ray_pos, ray, &r))
  516. continue;
  517. float dist = r.distance_to(gt.origin);
  518. if (dist > gs * (GIZMO_CIRCLE_SIZE - GIZMO_RING_HALF_WIDTH) && dist < gs * (GIZMO_CIRCLE_SIZE + GIZMO_RING_HALF_WIDTH)) {
  519. float d = ray_pos.distance_to(r);
  520. if (d < col_d) {
  521. col_d = d;
  522. col_axis = i;
  523. }
  524. }
  525. }
  526. if (col_axis != -1) {
  527. if (p_highlight_only) {
  528. spatial_editor->select_gizmo_highlight_axis(col_axis + 3);
  529. } else {
  530. //handle rotate
  531. _edit.mode = TRANSFORM_ROTATE;
  532. _compute_edit(Point2(p_screenpos.x, p_screenpos.y));
  533. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis);
  534. }
  535. return true;
  536. }
  537. }
  538. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SCALE) {
  539. int col_axis = -1;
  540. float col_d = 1e20;
  541. for (int i = 0; i < 3; i++) {
  542. Vector3 grabber_pos = gt.origin + gt.basis.get_axis(i) * gs * GIZMO_SCALE_OFFSET;
  543. float grabber_radius = gs * GIZMO_ARROW_SIZE;
  544. Vector3 r;
  545. if (Geometry::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) {
  546. float d = r.distance_to(ray_pos);
  547. if (d < col_d) {
  548. col_d = d;
  549. col_axis = i;
  550. }
  551. }
  552. }
  553. bool is_plane_scale = false;
  554. // plane select
  555. if (col_axis == -1) {
  556. col_d = 1e20;
  557. for (int i = 0; i < 3; i++) {
  558. Vector3 ivec2 = gt.basis.get_axis((i + 1) % 3).normalized();
  559. Vector3 ivec3 = gt.basis.get_axis((i + 2) % 3).normalized();
  560. Vector3 grabber_pos = gt.origin + (ivec2 + ivec3) * gs * (GIZMO_PLANE_SIZE + GIZMO_PLANE_DST);
  561. Vector3 r;
  562. Plane plane(gt.origin, gt.basis.get_axis(i).normalized());
  563. if (plane.intersects_ray(ray_pos, ray, &r)) {
  564. float dist = r.distance_to(grabber_pos);
  565. if (dist < (gs * GIZMO_PLANE_SIZE)) {
  566. float d = ray_pos.distance_to(r);
  567. if (d < col_d) {
  568. col_d = d;
  569. col_axis = i;
  570. is_plane_scale = true;
  571. }
  572. }
  573. }
  574. }
  575. }
  576. if (col_axis != -1) {
  577. if (p_highlight_only) {
  578. spatial_editor->select_gizmo_highlight_axis(col_axis + (is_plane_scale ? 12 : 9));
  579. } else {
  580. //handle scale
  581. _edit.mode = TRANSFORM_SCALE;
  582. _compute_edit(Point2(p_screenpos.x, p_screenpos.y));
  583. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis + (is_plane_scale ? 3 : 0));
  584. }
  585. return true;
  586. }
  587. }
  588. if (p_highlight_only)
  589. spatial_editor->select_gizmo_highlight_axis(-1);
  590. return false;
  591. }
  592. void SpatialEditorViewport::_surface_mouse_enter() {
  593. if (!surface->has_focus() && (!get_focus_owner() || !get_focus_owner()->is_text_field()))
  594. surface->grab_focus();
  595. }
  596. void SpatialEditorViewport::_surface_mouse_exit() {
  597. _remove_preview();
  598. }
  599. void SpatialEditorViewport::_surface_focus_enter() {
  600. view_menu->set_disable_shortcuts(false);
  601. }
  602. void SpatialEditorViewport::_surface_focus_exit() {
  603. view_menu->set_disable_shortcuts(true);
  604. }
  605. bool SpatialEditorViewport ::_is_node_locked(const Node *p_node) {
  606. return p_node->has_meta("_edit_lock_") && p_node->get_meta("_edit_lock_");
  607. }
  608. void SpatialEditorViewport::_list_select(Ref<InputEventMouseButton> b) {
  609. _find_items_at_pos(b->get_position(), clicked_includes_current, selection_results, b->get_shift());
  610. Node *scene = editor->get_edited_scene();
  611. for (int i = 0; i < selection_results.size(); i++) {
  612. Spatial *item = selection_results[i].item;
  613. if (item != scene && item->get_owner() != scene && !scene->is_editable_instance(item->get_owner())) {
  614. //invalid result
  615. selection_results.remove(i);
  616. i--;
  617. }
  618. }
  619. clicked_wants_append = b->get_shift();
  620. if (selection_results.size() == 1) {
  621. clicked = selection_results[0].item->get_instance_id();
  622. selection_results.clear();
  623. if (clicked) {
  624. _select_clicked(clicked_wants_append, true);
  625. clicked = 0;
  626. }
  627. } else if (!selection_results.empty()) {
  628. NodePath root_path = get_tree()->get_edited_scene_root()->get_path();
  629. StringName root_name = root_path.get_name(root_path.get_name_count() - 1);
  630. for (int i = 0; i < selection_results.size(); i++) {
  631. Spatial *spat = selection_results[i].item;
  632. Ref<Texture> icon = EditorNode::get_singleton()->get_object_icon(spat, "Node");
  633. String node_path = "/" + root_name + "/" + root_path.rel_path_to(spat->get_path());
  634. selection_menu->add_item(spat->get_name());
  635. selection_menu->set_item_icon(i, icon);
  636. selection_menu->set_item_metadata(i, node_path);
  637. selection_menu->set_item_tooltip(i, String(spat->get_name()) + "\nType: " + spat->get_class() + "\nPath: " + node_path);
  638. }
  639. selection_menu->set_global_position(b->get_global_position());
  640. selection_menu->popup();
  641. }
  642. }
  643. void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
  644. if (previewing)
  645. return; //do NONE
  646. {
  647. EditorNode *en = editor;
  648. EditorPluginList *force_input_forwarding_list = en->get_editor_plugins_force_input_forwarding();
  649. if (!force_input_forwarding_list->empty()) {
  650. bool discard = force_input_forwarding_list->forward_spatial_gui_input(camera, p_event, true);
  651. if (discard)
  652. return;
  653. }
  654. }
  655. {
  656. EditorNode *en = editor;
  657. EditorPluginList *over_plugin_list = en->get_editor_plugins_over();
  658. if (!over_plugin_list->empty()) {
  659. bool discard = over_plugin_list->forward_spatial_gui_input(camera, p_event, false);
  660. if (discard)
  661. return;
  662. }
  663. }
  664. Ref<InputEventMouseButton> b = p_event;
  665. if (b.is_valid()) {
  666. float zoom_factor = 1 + (ZOOM_MULTIPLIER - 1) * b->get_factor();
  667. switch (b->get_button_index()) {
  668. case BUTTON_WHEEL_UP: {
  669. if (is_freelook_active())
  670. scale_freelook_speed(zoom_factor);
  671. else
  672. scale_cursor_distance(1.0 / zoom_factor);
  673. } break;
  674. case BUTTON_WHEEL_DOWN: {
  675. if (is_freelook_active())
  676. scale_freelook_speed(1.0 / zoom_factor);
  677. else
  678. scale_cursor_distance(zoom_factor);
  679. } break;
  680. case BUTTON_RIGHT: {
  681. NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  682. if (b->is_pressed() && _edit.gizmo.is_valid()) {
  683. //restore
  684. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_initial_value, true);
  685. _edit.gizmo = Ref<EditorSpatialGizmo>();
  686. }
  687. if (_edit.mode == TRANSFORM_NONE && b->is_pressed()) {
  688. if (b->get_alt()) {
  689. if (nav_scheme == NAVIGATION_MAYA)
  690. break;
  691. _list_select(b);
  692. return;
  693. }
  694. }
  695. if (_edit.mode != TRANSFORM_NONE && b->is_pressed()) {
  696. //cancel motion
  697. _edit.mode = TRANSFORM_NONE;
  698. List<Node *> &selection = editor_selection->get_selected_node_list();
  699. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  700. Spatial *sp = Object::cast_to<Spatial>(E->get());
  701. if (!sp)
  702. continue;
  703. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  704. if (!se)
  705. continue;
  706. sp->set_global_transform(se->original);
  707. }
  708. surface->update();
  709. set_message(TTR("Transform Aborted."), 3);
  710. }
  711. if (b->is_pressed()) {
  712. int mod = _get_key_modifier(b);
  713. if (!orthogonal) {
  714. if (mod == _get_key_modifier_setting("editors/3d/freelook/freelook_activation_modifier")) {
  715. set_freelook_active(true);
  716. }
  717. }
  718. } else {
  719. set_freelook_active(false);
  720. }
  721. if (freelook_active && !surface->has_focus()) {
  722. // Focus usually doesn't trigger on right-click, but in case of freelook it should,
  723. // otherwise using keyboard navigation would misbehave
  724. surface->grab_focus();
  725. }
  726. } break;
  727. case BUTTON_MIDDLE: {
  728. if (b->is_pressed() && _edit.mode != TRANSFORM_NONE) {
  729. switch (_edit.plane) {
  730. case TRANSFORM_VIEW: {
  731. _edit.plane = TRANSFORM_X_AXIS;
  732. set_message(TTR("X-Axis Transform."), 2);
  733. name = "";
  734. _update_name();
  735. } break;
  736. case TRANSFORM_X_AXIS: {
  737. _edit.plane = TRANSFORM_Y_AXIS;
  738. set_message(TTR("Y-Axis Transform."), 2);
  739. } break;
  740. case TRANSFORM_Y_AXIS: {
  741. _edit.plane = TRANSFORM_Z_AXIS;
  742. set_message(TTR("Z-Axis Transform."), 2);
  743. } break;
  744. case TRANSFORM_Z_AXIS: {
  745. _edit.plane = TRANSFORM_VIEW;
  746. set_message(TTR("View Plane Transform."), 2);
  747. } break;
  748. case TRANSFORM_YZ:
  749. case TRANSFORM_XZ:
  750. case TRANSFORM_XY: {
  751. } break;
  752. }
  753. }
  754. } break;
  755. case BUTTON_LEFT: {
  756. if (b->is_pressed()) {
  757. NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  758. if ((nav_scheme == NAVIGATION_MAYA || nav_scheme == NAVIGATION_MODO) && b->get_alt()) {
  759. break;
  760. }
  761. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_LIST_SELECT) {
  762. _list_select(b);
  763. break;
  764. }
  765. _edit.mouse_pos = b->get_position();
  766. _edit.snap = spatial_editor->is_snap_enabled();
  767. _edit.mode = TRANSFORM_NONE;
  768. //gizmo has priority over everything
  769. bool can_select_gizmos = true;
  770. {
  771. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  772. can_select_gizmos = view_menu->get_popup()->is_item_checked(idx);
  773. }
  774. if (can_select_gizmos && spatial_editor->get_selected()) {
  775. Ref<EditorSpatialGizmo> seg = spatial_editor->get_selected()->get_gizmo();
  776. if (seg.is_valid()) {
  777. int handle = -1;
  778. Vector3 point;
  779. Vector3 normal;
  780. bool inters = seg->intersect_ray(camera, _edit.mouse_pos, point, normal, &handle, b->get_shift());
  781. if (inters && handle != -1) {
  782. _edit.gizmo = seg;
  783. _edit.gizmo_handle = handle;
  784. _edit.gizmo_initial_value = seg->get_handle_value(handle);
  785. break;
  786. }
  787. }
  788. }
  789. if (_gizmo_select(_edit.mouse_pos))
  790. break;
  791. clicked = 0;
  792. clicked_includes_current = false;
  793. if ((spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT && b->get_control()) || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_ROTATE) {
  794. /* HANDLE ROTATION */
  795. if (get_selected_count() == 0)
  796. break; //bye
  797. //handle rotate
  798. _edit.mode = TRANSFORM_ROTATE;
  799. _compute_edit(b->get_position());
  800. break;
  801. }
  802. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_MOVE) {
  803. if (get_selected_count() == 0)
  804. break; //bye
  805. //handle translate
  806. _edit.mode = TRANSFORM_TRANSLATE;
  807. _compute_edit(b->get_position());
  808. break;
  809. }
  810. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SCALE) {
  811. if (get_selected_count() == 0)
  812. break; //bye
  813. //handle scale
  814. _edit.mode = TRANSFORM_SCALE;
  815. _compute_edit(b->get_position());
  816. break;
  817. }
  818. // todo scale
  819. int gizmo_handle = -1;
  820. clicked = _select_ray(b->get_position(), b->get_shift(), clicked_includes_current, &gizmo_handle, b->get_shift());
  821. //clicking is always deferred to either move or release
  822. clicked_wants_append = b->get_shift();
  823. if (!clicked) {
  824. if (!clicked_wants_append)
  825. _clear_selected();
  826. //default to regionselect
  827. cursor.region_select = true;
  828. cursor.region_begin = b->get_position();
  829. cursor.region_end = b->get_position();
  830. }
  831. if (clicked && gizmo_handle >= 0) {
  832. Spatial *spa = Object::cast_to<Spatial>(ObjectDB::get_instance(clicked));
  833. if (spa) {
  834. Ref<EditorSpatialGizmo> seg = spa->get_gizmo();
  835. if (seg.is_valid()) {
  836. _edit.gizmo = seg;
  837. _edit.gizmo_handle = gizmo_handle;
  838. _edit.gizmo_initial_value = seg->get_handle_value(gizmo_handle);
  839. break;
  840. }
  841. }
  842. }
  843. surface->update();
  844. } else {
  845. if (_edit.gizmo.is_valid()) {
  846. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_initial_value, false);
  847. _edit.gizmo = Ref<EditorSpatialGizmo>();
  848. break;
  849. }
  850. if (clicked) {
  851. _select_clicked(clicked_wants_append, true);
  852. // Processing was deferred.
  853. clicked = 0;
  854. }
  855. if (cursor.region_select) {
  856. if (!clicked_wants_append) _clear_selected();
  857. _select_region();
  858. cursor.region_select = false;
  859. surface->update();
  860. }
  861. if (_edit.mode != TRANSFORM_NONE) {
  862. static const char *_transform_name[4] = { "None", "Rotate", "Translate", "Scale" };
  863. undo_redo->create_action(_transform_name[_edit.mode]);
  864. List<Node *> &selection = editor_selection->get_selected_node_list();
  865. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  866. Spatial *sp = Object::cast_to<Spatial>(E->get());
  867. if (!sp)
  868. continue;
  869. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  870. if (!se)
  871. continue;
  872. undo_redo->add_do_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
  873. undo_redo->add_undo_method(sp, "set_global_transform", se->original);
  874. }
  875. undo_redo->commit_action();
  876. _edit.mode = TRANSFORM_NONE;
  877. set_message("");
  878. }
  879. surface->update();
  880. }
  881. } break;
  882. }
  883. }
  884. Ref<InputEventMouseMotion> m = p_event;
  885. if (m.is_valid()) {
  886. _edit.mouse_pos = m->get_position();
  887. if (spatial_editor->get_selected()) {
  888. Ref<EditorSpatialGizmo> seg = spatial_editor->get_selected()->get_gizmo();
  889. if (seg.is_valid()) {
  890. int selected_handle = -1;
  891. int handle = -1;
  892. Vector3 point;
  893. Vector3 normal;
  894. bool inters = seg->intersect_ray(camera, _edit.mouse_pos, point, normal, &handle, false);
  895. if (inters && handle != -1) {
  896. selected_handle = handle;
  897. }
  898. if (selected_handle != spatial_editor->get_over_gizmo_handle()) {
  899. spatial_editor->set_over_gizmo_handle(selected_handle);
  900. spatial_editor->get_selected()->update_gizmo();
  901. if (selected_handle != -1)
  902. spatial_editor->select_gizmo_highlight_axis(-1);
  903. }
  904. }
  905. }
  906. if (spatial_editor->get_over_gizmo_handle() == -1 && !(m->get_button_mask() & 1) && !_edit.gizmo.is_valid()) {
  907. _gizmo_select(_edit.mouse_pos, true);
  908. }
  909. NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  910. NavigationMode nav_mode = NAVIGATION_NONE;
  911. if (_edit.gizmo.is_valid()) {
  912. _edit.gizmo->set_handle(_edit.gizmo_handle, camera, m->get_position());
  913. Variant v = _edit.gizmo->get_handle_value(_edit.gizmo_handle);
  914. String n = _edit.gizmo->get_handle_name(_edit.gizmo_handle);
  915. set_message(n + ": " + String(v));
  916. } else if (m->get_button_mask() & BUTTON_MASK_LEFT) {
  917. if (nav_scheme == NAVIGATION_MAYA && m->get_alt()) {
  918. nav_mode = NAVIGATION_ORBIT;
  919. } else if (nav_scheme == NAVIGATION_MODO && m->get_alt() && m->get_shift()) {
  920. nav_mode = NAVIGATION_PAN;
  921. } else if (nav_scheme == NAVIGATION_MODO && m->get_alt() && m->get_control()) {
  922. nav_mode = NAVIGATION_ZOOM;
  923. } else if (nav_scheme == NAVIGATION_MODO && m->get_alt()) {
  924. nav_mode = NAVIGATION_ORBIT;
  925. } else {
  926. if (clicked) {
  927. if (!clicked_includes_current) {
  928. _select_clicked(clicked_wants_append, true);
  929. // Processing was deferred.
  930. }
  931. _compute_edit(_edit.mouse_pos);
  932. clicked = 0;
  933. _edit.mode = TRANSFORM_TRANSLATE;
  934. }
  935. if (cursor.region_select) {
  936. cursor.region_end = m->get_position();
  937. surface->update();
  938. return;
  939. }
  940. if (_edit.mode == TRANSFORM_NONE)
  941. return;
  942. Vector3 ray_pos = _get_ray_pos(m->get_position());
  943. Vector3 ray = _get_ray(m->get_position());
  944. float snap = EDITOR_GET("interface/inspector/default_float_step");
  945. int snap_step_decimals = Math::range_step_decimals(snap);
  946. switch (_edit.mode) {
  947. case TRANSFORM_SCALE: {
  948. Vector3 motion_mask;
  949. Plane plane;
  950. bool plane_mv = false;
  951. switch (_edit.plane) {
  952. case TRANSFORM_VIEW:
  953. motion_mask = Vector3(0, 0, 0);
  954. plane = Plane(_edit.center, _get_camera_normal());
  955. break;
  956. case TRANSFORM_X_AXIS:
  957. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0);
  958. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  959. break;
  960. case TRANSFORM_Y_AXIS:
  961. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(1);
  962. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  963. break;
  964. case TRANSFORM_Z_AXIS:
  965. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2);
  966. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  967. break;
  968. case TRANSFORM_YZ:
  969. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2) + spatial_editor->get_gizmo_transform().basis.get_axis(1);
  970. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(0));
  971. plane_mv = true;
  972. break;
  973. case TRANSFORM_XZ:
  974. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2) + spatial_editor->get_gizmo_transform().basis.get_axis(0);
  975. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(1));
  976. plane_mv = true;
  977. break;
  978. case TRANSFORM_XY:
  979. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0) + spatial_editor->get_gizmo_transform().basis.get_axis(1);
  980. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(2));
  981. plane_mv = true;
  982. break;
  983. }
  984. Vector3 intersection;
  985. if (!plane.intersects_ray(ray_pos, ray, &intersection))
  986. break;
  987. Vector3 click;
  988. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click))
  989. break;
  990. Vector3 motion = intersection - click;
  991. if (_edit.plane != TRANSFORM_VIEW) {
  992. if (!plane_mv) {
  993. motion = motion_mask.dot(motion) * motion_mask;
  994. } else {
  995. // Alternative planar scaling mode
  996. if (_get_key_modifier(m) != KEY_SHIFT) {
  997. motion = motion_mask.dot(motion) * motion_mask;
  998. }
  999. }
  1000. } else {
  1001. float center_click_dist = click.distance_to(_edit.center);
  1002. float center_inters_dist = intersection.distance_to(_edit.center);
  1003. if (center_click_dist == 0)
  1004. break;
  1005. float scale = center_inters_dist - center_click_dist;
  1006. motion = Vector3(scale, scale, scale);
  1007. }
  1008. List<Node *> &selection = editor_selection->get_selected_node_list();
  1009. // Disable local transformation for TRANSFORM_VIEW
  1010. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  1011. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1012. snap = spatial_editor->get_scale_snap() / 100;
  1013. }
  1014. Vector3 motion_snapped = motion;
  1015. motion_snapped.snap(Vector3(snap, snap, snap));
  1016. // This might not be necessary anymore after issue #288 is solved (in 4.0?).
  1017. set_message(TTR("Scaling: ") + "(" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
  1018. String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
  1019. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1020. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1021. if (!sp) {
  1022. continue;
  1023. }
  1024. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1025. if (!se) {
  1026. continue;
  1027. }
  1028. if (sp->has_meta("_edit_lock_")) {
  1029. continue;
  1030. }
  1031. Transform original = se->original;
  1032. Transform original_local = se->original_local;
  1033. Transform base = Transform(Basis(), _edit.center);
  1034. Transform t;
  1035. Vector3 local_scale;
  1036. if (local_coords) {
  1037. Basis g = original.basis.orthonormalized();
  1038. Vector3 local_motion = g.inverse().xform(motion);
  1039. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1040. local_motion.snap(Vector3(snap, snap, snap));
  1041. }
  1042. local_scale = original_local.basis.get_scale() * (local_motion + Vector3(1, 1, 1));
  1043. // Prevent scaling to 0 it would break the gizmo
  1044. Basis check = original_local.basis;
  1045. check.scale(local_scale);
  1046. if (check.determinant() != 0) {
  1047. // Apply scale
  1048. sp->set_scale(local_scale);
  1049. }
  1050. } else {
  1051. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1052. motion.snap(Vector3(snap, snap, snap));
  1053. }
  1054. Transform r;
  1055. r.basis.scale(motion + Vector3(1, 1, 1));
  1056. t = base * (r * (base.inverse() * original));
  1057. // Apply scale
  1058. sp->set_global_transform(t);
  1059. }
  1060. }
  1061. surface->update();
  1062. } break;
  1063. case TRANSFORM_TRANSLATE: {
  1064. Vector3 motion_mask;
  1065. Plane plane;
  1066. bool plane_mv = false;
  1067. switch (_edit.plane) {
  1068. case TRANSFORM_VIEW:
  1069. plane = Plane(_edit.center, _get_camera_normal());
  1070. break;
  1071. case TRANSFORM_X_AXIS:
  1072. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0);
  1073. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1074. break;
  1075. case TRANSFORM_Y_AXIS:
  1076. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(1);
  1077. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1078. break;
  1079. case TRANSFORM_Z_AXIS:
  1080. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2);
  1081. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1082. break;
  1083. case TRANSFORM_YZ:
  1084. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(0));
  1085. plane_mv = true;
  1086. break;
  1087. case TRANSFORM_XZ:
  1088. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(1));
  1089. plane_mv = true;
  1090. break;
  1091. case TRANSFORM_XY:
  1092. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(2));
  1093. plane_mv = true;
  1094. break;
  1095. }
  1096. Vector3 intersection;
  1097. if (!plane.intersects_ray(ray_pos, ray, &intersection))
  1098. break;
  1099. Vector3 click;
  1100. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click))
  1101. break;
  1102. Vector3 motion = intersection - click;
  1103. if (_edit.plane != TRANSFORM_VIEW) {
  1104. if (!plane_mv) {
  1105. motion = motion_mask.dot(motion) * motion_mask;
  1106. }
  1107. }
  1108. List<Node *> &selection = editor_selection->get_selected_node_list();
  1109. // Disable local transformation for TRANSFORM_VIEW
  1110. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  1111. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1112. snap = spatial_editor->get_translate_snap();
  1113. }
  1114. Vector3 motion_snapped = motion;
  1115. motion_snapped.snap(Vector3(snap, snap, snap));
  1116. set_message(TTR("Translating: ") + "(" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
  1117. String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
  1118. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1119. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1120. if (!sp) {
  1121. continue;
  1122. }
  1123. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1124. if (!se) {
  1125. continue;
  1126. }
  1127. if (sp->has_meta("_edit_lock_")) {
  1128. continue;
  1129. }
  1130. Transform original = se->original;
  1131. Transform t;
  1132. if (local_coords) {
  1133. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1134. Basis g = original.basis.orthonormalized();
  1135. Vector3 local_motion = g.inverse().xform(motion);
  1136. local_motion.snap(Vector3(snap, snap, snap));
  1137. motion = g.xform(local_motion);
  1138. }
  1139. } else {
  1140. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1141. motion.snap(Vector3(snap, snap, snap));
  1142. }
  1143. }
  1144. // Apply translation
  1145. t = original;
  1146. t.origin += motion;
  1147. sp->set_global_transform(t);
  1148. }
  1149. surface->update();
  1150. } break;
  1151. case TRANSFORM_ROTATE: {
  1152. Plane plane;
  1153. Vector3 axis;
  1154. switch (_edit.plane) {
  1155. case TRANSFORM_VIEW:
  1156. plane = Plane(_edit.center, _get_camera_normal());
  1157. break;
  1158. case TRANSFORM_X_AXIS:
  1159. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(0));
  1160. axis = Vector3(1, 0, 0);
  1161. break;
  1162. case TRANSFORM_Y_AXIS:
  1163. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(1));
  1164. axis = Vector3(0, 1, 0);
  1165. break;
  1166. case TRANSFORM_Z_AXIS:
  1167. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(2));
  1168. axis = Vector3(0, 0, 1);
  1169. break;
  1170. case TRANSFORM_YZ:
  1171. case TRANSFORM_XZ:
  1172. case TRANSFORM_XY:
  1173. break;
  1174. }
  1175. Vector3 intersection;
  1176. if (!plane.intersects_ray(ray_pos, ray, &intersection))
  1177. break;
  1178. Vector3 click;
  1179. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click))
  1180. break;
  1181. Vector3 y_axis = (click - _edit.center).normalized();
  1182. Vector3 x_axis = plane.normal.cross(y_axis).normalized();
  1183. float angle = Math::atan2(x_axis.dot(intersection - _edit.center), y_axis.dot(intersection - _edit.center));
  1184. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1185. snap = spatial_editor->get_rotate_snap();
  1186. }
  1187. angle = Math::rad2deg(angle) + snap * 0.5; //else it won't reach +180
  1188. angle -= Math::fmod(angle, snap);
  1189. set_message(vformat(TTR("Rotating %s degrees."), String::num(angle, snap_step_decimals)));
  1190. angle = Math::deg2rad(angle);
  1191. List<Node *> &selection = editor_selection->get_selected_node_list();
  1192. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW); // Disable local transformation for TRANSFORM_VIEW
  1193. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1194. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1195. if (!sp)
  1196. continue;
  1197. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1198. if (!se)
  1199. continue;
  1200. if (sp->has_meta("_edit_lock_")) {
  1201. continue;
  1202. }
  1203. Transform t;
  1204. if (local_coords) {
  1205. Transform original_local = se->original_local;
  1206. Basis rot = Basis(axis, angle);
  1207. t.basis = original_local.get_basis().orthonormalized() * rot;
  1208. t.origin = original_local.origin;
  1209. // Apply rotation
  1210. sp->set_transform(t);
  1211. sp->set_scale(original_local.basis.get_scale()); // re-apply original scale
  1212. } else {
  1213. Transform original = se->original;
  1214. Transform r;
  1215. Transform base = Transform(Basis(), _edit.center);
  1216. r.basis.rotate(plane.normal, angle);
  1217. t = base * r * base.inverse() * original;
  1218. // Apply rotation
  1219. sp->set_global_transform(t);
  1220. }
  1221. }
  1222. surface->update();
  1223. } break;
  1224. default: {
  1225. }
  1226. }
  1227. }
  1228. } else if ((m->get_button_mask() & BUTTON_MASK_RIGHT) || freelook_active) {
  1229. if (nav_scheme == NAVIGATION_MAYA && m->get_alt()) {
  1230. nav_mode = NAVIGATION_ZOOM;
  1231. } else if (freelook_active) {
  1232. nav_mode = NAVIGATION_LOOK;
  1233. } else if (orthogonal) {
  1234. nav_mode = NAVIGATION_PAN;
  1235. }
  1236. } else if (m->get_button_mask() & BUTTON_MASK_MIDDLE) {
  1237. if (nav_scheme == NAVIGATION_GODOT) {
  1238. int mod = _get_key_modifier(m);
  1239. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier"))
  1240. nav_mode = NAVIGATION_PAN;
  1241. else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier"))
  1242. nav_mode = NAVIGATION_ZOOM;
  1243. else if (mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier"))
  1244. nav_mode = NAVIGATION_ORBIT;
  1245. } else if (nav_scheme == NAVIGATION_MAYA) {
  1246. if (m->get_alt())
  1247. nav_mode = NAVIGATION_PAN;
  1248. }
  1249. } else if (EditorSettings::get_singleton()->get("editors/3d/navigation/emulate_3_button_mouse")) {
  1250. // Handle trackpad (no external mouse) use case
  1251. int mod = _get_key_modifier(m);
  1252. if (mod) {
  1253. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier"))
  1254. nav_mode = NAVIGATION_PAN;
  1255. else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier"))
  1256. nav_mode = NAVIGATION_ZOOM;
  1257. else if (mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier"))
  1258. nav_mode = NAVIGATION_ORBIT;
  1259. }
  1260. }
  1261. switch (nav_mode) {
  1262. case NAVIGATION_PAN: {
  1263. _nav_pan(m, _get_warped_mouse_motion(m));
  1264. } break;
  1265. case NAVIGATION_ZOOM: {
  1266. _nav_zoom(m, m->get_relative());
  1267. } break;
  1268. case NAVIGATION_ORBIT: {
  1269. _nav_orbit(m, _get_warped_mouse_motion(m));
  1270. } break;
  1271. case NAVIGATION_LOOK: {
  1272. _nav_look(m, _get_warped_mouse_motion(m));
  1273. } break;
  1274. default: {
  1275. }
  1276. }
  1277. }
  1278. Ref<InputEventMagnifyGesture> magnify_gesture = p_event;
  1279. if (magnify_gesture.is_valid()) {
  1280. if (is_freelook_active())
  1281. scale_freelook_speed(magnify_gesture->get_factor());
  1282. else
  1283. scale_cursor_distance(1.0 / magnify_gesture->get_factor());
  1284. }
  1285. Ref<InputEventPanGesture> pan_gesture = p_event;
  1286. if (pan_gesture.is_valid()) {
  1287. NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  1288. NavigationMode nav_mode = NAVIGATION_NONE;
  1289. if (nav_scheme == NAVIGATION_GODOT) {
  1290. int mod = _get_key_modifier(pan_gesture);
  1291. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier"))
  1292. nav_mode = NAVIGATION_PAN;
  1293. else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier"))
  1294. nav_mode = NAVIGATION_ZOOM;
  1295. else if (mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier"))
  1296. nav_mode = NAVIGATION_ORBIT;
  1297. } else if (nav_scheme == NAVIGATION_MAYA) {
  1298. if (pan_gesture->get_alt())
  1299. nav_mode = NAVIGATION_PAN;
  1300. }
  1301. switch (nav_mode) {
  1302. case NAVIGATION_PAN: {
  1303. _nav_pan(m, pan_gesture->get_delta());
  1304. } break;
  1305. case NAVIGATION_ZOOM: {
  1306. _nav_zoom(m, pan_gesture->get_delta());
  1307. } break;
  1308. case NAVIGATION_ORBIT: {
  1309. _nav_orbit(m, pan_gesture->get_delta());
  1310. } break;
  1311. case NAVIGATION_LOOK: {
  1312. _nav_look(m, pan_gesture->get_delta());
  1313. } break;
  1314. default: {
  1315. }
  1316. }
  1317. }
  1318. Ref<InputEventKey> k = p_event;
  1319. if (k.is_valid()) {
  1320. if (!k->is_pressed())
  1321. return;
  1322. if (ED_IS_SHORTCUT("spatial_editor/snap", p_event)) {
  1323. if (_edit.mode != TRANSFORM_NONE) {
  1324. _edit.snap = !_edit.snap;
  1325. }
  1326. }
  1327. if (ED_IS_SHORTCUT("spatial_editor/bottom_view", p_event)) {
  1328. _menu_option(VIEW_BOTTOM);
  1329. }
  1330. if (ED_IS_SHORTCUT("spatial_editor/top_view", p_event)) {
  1331. _menu_option(VIEW_TOP);
  1332. }
  1333. if (ED_IS_SHORTCUT("spatial_editor/rear_view", p_event)) {
  1334. _menu_option(VIEW_REAR);
  1335. }
  1336. if (ED_IS_SHORTCUT("spatial_editor/front_view", p_event)) {
  1337. _menu_option(VIEW_FRONT);
  1338. }
  1339. if (ED_IS_SHORTCUT("spatial_editor/left_view", p_event)) {
  1340. _menu_option(VIEW_LEFT);
  1341. }
  1342. if (ED_IS_SHORTCUT("spatial_editor/right_view", p_event)) {
  1343. _menu_option(VIEW_RIGHT);
  1344. }
  1345. if (ED_IS_SHORTCUT("spatial_editor/focus_origin", p_event)) {
  1346. _menu_option(VIEW_CENTER_TO_ORIGIN);
  1347. }
  1348. if (ED_IS_SHORTCUT("spatial_editor/focus_selection", p_event)) {
  1349. _menu_option(VIEW_CENTER_TO_SELECTION);
  1350. }
  1351. // Orthgonal mode doesn't work in freelook.
  1352. if (!freelook_active && ED_IS_SHORTCUT("spatial_editor/switch_perspective_orthogonal", p_event)) {
  1353. _menu_option(orthogonal ? VIEW_PERSPECTIVE : VIEW_ORTHOGONAL);
  1354. _update_name();
  1355. }
  1356. if (ED_IS_SHORTCUT("spatial_editor/align_transform_with_view", p_event)) {
  1357. _menu_option(VIEW_ALIGN_TRANSFORM_WITH_VIEW);
  1358. }
  1359. if (ED_IS_SHORTCUT("spatial_editor/align_rotation_with_view", p_event)) {
  1360. _menu_option(VIEW_ALIGN_ROTATION_WITH_VIEW);
  1361. }
  1362. if (ED_IS_SHORTCUT("spatial_editor/insert_anim_key", p_event)) {
  1363. if (!get_selected_count() || _edit.mode != TRANSFORM_NONE)
  1364. return;
  1365. if (!AnimationPlayerEditor::singleton->get_track_editor()->has_keying()) {
  1366. set_message(TTR("Keying is disabled (no key inserted)."));
  1367. return;
  1368. }
  1369. List<Node *> &selection = editor_selection->get_selected_node_list();
  1370. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1371. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1372. if (!sp)
  1373. continue;
  1374. spatial_editor->emit_signal("transform_key_request", sp, "", sp->get_transform());
  1375. }
  1376. set_message(TTR("Animation Key Inserted."));
  1377. }
  1378. // Freelook doesn't work in orthogonal mode.
  1379. if (!orthogonal && ED_IS_SHORTCUT("spatial_editor/freelook_toggle", p_event)) {
  1380. set_freelook_active(!is_freelook_active());
  1381. } else if (k->get_scancode() == KEY_ESCAPE) {
  1382. set_freelook_active(false);
  1383. }
  1384. if (k->get_scancode() == KEY_SPACE) {
  1385. if (!k->is_pressed()) emit_signal("toggle_maximize_view", this);
  1386. }
  1387. }
  1388. // freelook uses most of the useful shortcuts, like save, so its ok
  1389. // to consider freelook active as end of the line for future events.
  1390. if (freelook_active)
  1391. accept_event();
  1392. }
  1393. void SpatialEditorViewport::_nav_pan(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  1394. const NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  1395. real_t pan_speed = 1 / 150.0;
  1396. int pan_speed_modifier = 10;
  1397. if (nav_scheme == NAVIGATION_MAYA && p_event->get_shift())
  1398. pan_speed *= pan_speed_modifier;
  1399. Transform camera_transform;
  1400. camera_transform.translate(cursor.pos);
  1401. camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
  1402. camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
  1403. Vector3 translation(-p_relative.x * pan_speed, p_relative.y * pan_speed, 0);
  1404. translation *= cursor.distance / DISTANCE_DEFAULT;
  1405. camera_transform.translate(translation);
  1406. cursor.pos = camera_transform.origin;
  1407. }
  1408. void SpatialEditorViewport::_nav_zoom(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  1409. const NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  1410. real_t zoom_speed = 1 / 80.0;
  1411. int zoom_speed_modifier = 10;
  1412. if (nav_scheme == NAVIGATION_MAYA && p_event->get_shift())
  1413. zoom_speed *= zoom_speed_modifier;
  1414. NavigationZoomStyle zoom_style = (NavigationZoomStyle)EditorSettings::get_singleton()->get("editors/3d/navigation/zoom_style").operator int();
  1415. if (zoom_style == NAVIGATION_ZOOM_HORIZONTAL) {
  1416. if (p_relative.x > 0)
  1417. scale_cursor_distance(1 - p_relative.x * zoom_speed);
  1418. else if (p_relative.x < 0)
  1419. scale_cursor_distance(1.0 / (1 + p_relative.x * zoom_speed));
  1420. } else {
  1421. if (p_relative.y > 0)
  1422. scale_cursor_distance(1 + p_relative.y * zoom_speed);
  1423. else if (p_relative.y < 0)
  1424. scale_cursor_distance(1.0 / (1 - p_relative.y * zoom_speed));
  1425. }
  1426. }
  1427. void SpatialEditorViewport::_nav_orbit(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  1428. if (lock_rotation) {
  1429. _nav_pan(p_event, p_relative);
  1430. return;
  1431. }
  1432. real_t degrees_per_pixel = EditorSettings::get_singleton()->get("editors/3d/navigation_feel/orbit_sensitivity");
  1433. real_t radians_per_pixel = Math::deg2rad(degrees_per_pixel);
  1434. bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y_axis");
  1435. if (invert_y_axis) {
  1436. cursor.x_rot -= p_relative.y * radians_per_pixel;
  1437. } else {
  1438. cursor.x_rot += p_relative.y * radians_per_pixel;
  1439. }
  1440. cursor.y_rot += p_relative.x * radians_per_pixel;
  1441. if (cursor.x_rot > Math_PI / 2.0)
  1442. cursor.x_rot = Math_PI / 2.0;
  1443. if (cursor.x_rot < -Math_PI / 2.0)
  1444. cursor.x_rot = -Math_PI / 2.0;
  1445. name = "";
  1446. _update_name();
  1447. }
  1448. void SpatialEditorViewport::_nav_look(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  1449. if (orthogonal) {
  1450. _nav_pan(p_event, p_relative);
  1451. return;
  1452. }
  1453. real_t degrees_per_pixel = EditorSettings::get_singleton()->get("editors/3d/navigation_feel/orbit_sensitivity");
  1454. real_t radians_per_pixel = Math::deg2rad(degrees_per_pixel);
  1455. bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y_axis");
  1456. // Note: do NOT assume the camera has the "current" transform, because it is interpolated and may have "lag".
  1457. Transform prev_camera_transform = to_camera_transform(cursor);
  1458. if (invert_y_axis) {
  1459. cursor.x_rot -= p_relative.y * radians_per_pixel;
  1460. } else {
  1461. cursor.x_rot += p_relative.y * radians_per_pixel;
  1462. }
  1463. cursor.y_rot += p_relative.x * radians_per_pixel;
  1464. if (cursor.x_rot > Math_PI / 2.0)
  1465. cursor.x_rot = Math_PI / 2.0;
  1466. if (cursor.x_rot < -Math_PI / 2.0)
  1467. cursor.x_rot = -Math_PI / 2.0;
  1468. // Look is like the opposite of Orbit: the focus point rotates around the camera
  1469. Transform camera_transform = to_camera_transform(cursor);
  1470. Vector3 pos = camera_transform.xform(Vector3(0, 0, 0));
  1471. Vector3 prev_pos = prev_camera_transform.xform(Vector3(0, 0, 0));
  1472. Vector3 diff = prev_pos - pos;
  1473. cursor.pos += diff;
  1474. name = "";
  1475. _update_name();
  1476. }
  1477. void SpatialEditorViewport::set_freelook_active(bool active_now) {
  1478. if (!freelook_active && active_now) {
  1479. // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
  1480. cursor = camera_cursor;
  1481. // Make sure eye_pos is synced, because freelook referential is eye pos rather than orbit pos
  1482. Vector3 forward = to_camera_transform(cursor).basis.xform(Vector3(0, 0, -1));
  1483. cursor.eye_pos = cursor.pos - cursor.distance * forward;
  1484. // Also sync the camera cursor, otherwise switching to freelook will be trippy if inertia is active
  1485. camera_cursor.eye_pos = cursor.eye_pos;
  1486. if (EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_speed_zoom_link")) {
  1487. // Re-adjust freelook speed from the current zoom level
  1488. real_t base_speed = EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_base_speed");
  1489. freelook_speed = base_speed * cursor.distance;
  1490. }
  1491. // Hide mouse like in an FPS (warping doesn't work)
  1492. OS::get_singleton()->set_mouse_mode(OS::MOUSE_MODE_CAPTURED);
  1493. } else if (freelook_active && !active_now) {
  1494. // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
  1495. cursor = camera_cursor;
  1496. // Restore mouse
  1497. OS::get_singleton()->set_mouse_mode(OS::MOUSE_MODE_VISIBLE);
  1498. }
  1499. freelook_active = active_now;
  1500. }
  1501. void SpatialEditorViewport::scale_cursor_distance(real_t scale) {
  1502. // Prevents zero distance which would short-circuit any scaling
  1503. if (cursor.distance < ZOOM_MIN_DISTANCE)
  1504. cursor.distance = ZOOM_MIN_DISTANCE;
  1505. cursor.distance *= scale;
  1506. if (cursor.distance < ZOOM_MIN_DISTANCE)
  1507. cursor.distance = ZOOM_MIN_DISTANCE;
  1508. zoom_indicator_delay = ZOOM_INDICATOR_DELAY_S;
  1509. surface->update();
  1510. }
  1511. void SpatialEditorViewport::scale_freelook_speed(real_t scale) {
  1512. // Prevents zero distance which would short-circuit any scaling
  1513. if (freelook_speed < FREELOOK_MIN_SPEED)
  1514. freelook_speed = FREELOOK_MIN_SPEED;
  1515. freelook_speed *= scale;
  1516. if (freelook_speed < FREELOOK_MIN_SPEED)
  1517. freelook_speed = FREELOOK_MIN_SPEED;
  1518. zoom_indicator_delay = ZOOM_INDICATOR_DELAY_S;
  1519. surface->update();
  1520. }
  1521. Point2i SpatialEditorViewport::_get_warped_mouse_motion(const Ref<InputEventMouseMotion> &p_ev_mouse_motion) const {
  1522. Point2i relative;
  1523. if (bool(EDITOR_DEF("editors/3d/navigation/warped_mouse_panning", false))) {
  1524. relative = Input::get_singleton()->warp_mouse_motion(p_ev_mouse_motion, surface->get_global_rect());
  1525. } else {
  1526. relative = p_ev_mouse_motion->get_relative();
  1527. }
  1528. return relative;
  1529. }
  1530. static bool is_shortcut_pressed(const String &p_path) {
  1531. Ref<ShortCut> shortcut = ED_GET_SHORTCUT(p_path);
  1532. if (shortcut.is_null()) {
  1533. return false;
  1534. }
  1535. InputEventKey *k = Object::cast_to<InputEventKey>(shortcut->get_shortcut().ptr());
  1536. if (k == NULL) {
  1537. return false;
  1538. }
  1539. const Input &input = *Input::get_singleton();
  1540. int scancode = k->get_scancode();
  1541. return input.is_key_pressed(scancode);
  1542. }
  1543. void SpatialEditorViewport::_update_freelook(real_t delta) {
  1544. if (!is_freelook_active()) {
  1545. return;
  1546. }
  1547. Vector3 forward = camera->get_transform().basis.xform(Vector3(0, 0, -1));
  1548. Vector3 right = camera->get_transform().basis.xform(Vector3(1, 0, 0));
  1549. Vector3 up = camera->get_transform().basis.xform(Vector3(0, 1, 0));
  1550. Vector3 direction;
  1551. bool speed_modifier = false;
  1552. if (is_shortcut_pressed("spatial_editor/freelook_left")) {
  1553. direction -= right;
  1554. }
  1555. if (is_shortcut_pressed("spatial_editor/freelook_right")) {
  1556. direction += right;
  1557. }
  1558. if (is_shortcut_pressed("spatial_editor/freelook_forward")) {
  1559. direction += forward;
  1560. }
  1561. if (is_shortcut_pressed("spatial_editor/freelook_backwards")) {
  1562. direction -= forward;
  1563. }
  1564. if (is_shortcut_pressed("spatial_editor/freelook_up")) {
  1565. direction += up;
  1566. }
  1567. if (is_shortcut_pressed("spatial_editor/freelook_down")) {
  1568. direction -= up;
  1569. }
  1570. if (is_shortcut_pressed("spatial_editor/freelook_speed_modifier")) {
  1571. speed_modifier = true;
  1572. }
  1573. real_t speed = freelook_speed;
  1574. if (speed_modifier) {
  1575. real_t modifier_speed_factor = EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_modifier_speed_factor");
  1576. speed *= modifier_speed_factor;
  1577. }
  1578. Vector3 motion = direction * speed * delta;
  1579. cursor.pos += motion;
  1580. cursor.eye_pos += motion;
  1581. }
  1582. void SpatialEditorViewport::set_message(String p_message, float p_time) {
  1583. message = p_message;
  1584. message_time = p_time;
  1585. }
  1586. void SpatialEditorPlugin::edited_scene_changed() {
  1587. for (uint32_t i = 0; i < SpatialEditor::VIEWPORTS_COUNT; i++) {
  1588. SpatialEditorViewport *viewport = SpatialEditor::get_singleton()->get_editor_viewport(i);
  1589. if (viewport->is_visible()) {
  1590. viewport->notification(Control::NOTIFICATION_VISIBILITY_CHANGED);
  1591. }
  1592. }
  1593. }
  1594. void SpatialEditorViewport::_notification(int p_what) {
  1595. if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
  1596. bool visible = is_visible_in_tree();
  1597. set_process(visible);
  1598. if (visible) {
  1599. _update_camera(0);
  1600. } else {
  1601. set_freelook_active(false);
  1602. }
  1603. call_deferred("update_transform_gizmo_view");
  1604. }
  1605. if (p_what == NOTIFICATION_RESIZED) {
  1606. call_deferred("update_transform_gizmo_view");
  1607. }
  1608. if (p_what == NOTIFICATION_PROCESS) {
  1609. real_t delta = get_process_delta_time();
  1610. if (zoom_indicator_delay > 0) {
  1611. zoom_indicator_delay -= delta;
  1612. if (zoom_indicator_delay <= 0) {
  1613. surface->update();
  1614. }
  1615. }
  1616. _update_freelook(delta);
  1617. Node *scene_root = editor->get_scene_tree_dock()->get_editor_data()->get_edited_scene_root();
  1618. if (previewing_cinema && scene_root != NULL) {
  1619. Camera *cam = scene_root->get_viewport()->get_camera();
  1620. if (cam != NULL && cam != previewing) {
  1621. //then switch the viewport's camera to the scene's viewport camera
  1622. if (previewing != NULL) {
  1623. previewing->disconnect("tree_exited", this, "_preview_exited_scene");
  1624. }
  1625. previewing = cam;
  1626. previewing->connect("tree_exited", this, "_preview_exited_scene");
  1627. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), cam->get_camera());
  1628. surface->update();
  1629. }
  1630. }
  1631. _update_camera(delta);
  1632. Map<Node *, Object *> &selection = editor_selection->get_selection();
  1633. bool changed = false;
  1634. bool exist = false;
  1635. for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
  1636. Spatial *sp = Object::cast_to<Spatial>(E->key());
  1637. if (!sp)
  1638. continue;
  1639. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1640. if (!se)
  1641. continue;
  1642. VisualInstance *vi = Object::cast_to<VisualInstance>(sp);
  1643. se->aabb = vi ? vi->get_aabb() : AABB(Vector3(-0.2, -0.2, -0.2), Vector3(0.4, 0.4, 0.4));
  1644. Transform t = sp->get_global_gizmo_transform();
  1645. t.translate(se->aabb.position);
  1646. // apply AABB scaling before item's global transform
  1647. Basis aabb_s;
  1648. aabb_s.scale(se->aabb.size);
  1649. t.basis = t.basis * aabb_s;
  1650. exist = true;
  1651. if (se->last_xform == t)
  1652. continue;
  1653. changed = true;
  1654. se->last_xform = t;
  1655. VisualServer::get_singleton()->instance_set_transform(se->sbox_instance, t);
  1656. }
  1657. if (changed || (spatial_editor->is_gizmo_visible() && !exist)) {
  1658. spatial_editor->update_transform_gizmo();
  1659. }
  1660. if (message_time > 0) {
  1661. if (message != last_message) {
  1662. surface->update();
  1663. last_message = message;
  1664. }
  1665. message_time -= get_physics_process_delta_time();
  1666. if (message_time < 0)
  1667. surface->update();
  1668. }
  1669. //update shadow atlas if changed
  1670. int shadowmap_size = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/size");
  1671. int atlas_q0 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_0_subdiv");
  1672. int atlas_q1 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_1_subdiv");
  1673. int atlas_q2 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_2_subdiv");
  1674. int atlas_q3 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_3_subdiv");
  1675. viewport->set_shadow_atlas_size(shadowmap_size);
  1676. viewport->set_shadow_atlas_quadrant_subdiv(0, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q0));
  1677. viewport->set_shadow_atlas_quadrant_subdiv(1, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q1));
  1678. viewport->set_shadow_atlas_quadrant_subdiv(2, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q2));
  1679. viewport->set_shadow_atlas_quadrant_subdiv(3, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q3));
  1680. bool shrink = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION));
  1681. if (shrink != (viewport_container->get_stretch_shrink() > 1)) {
  1682. viewport_container->set_stretch_shrink(shrink ? 2 : 1);
  1683. }
  1684. //update msaa if changed
  1685. int msaa_mode = ProjectSettings::get_singleton()->get("rendering/quality/filters/msaa");
  1686. viewport->set_msaa(Viewport::MSAA(msaa_mode));
  1687. bool hdr = ProjectSettings::get_singleton()->get("rendering/quality/depth/hdr");
  1688. viewport->set_hdr(hdr);
  1689. bool show_info = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_INFORMATION));
  1690. info_label->set_visible(show_info);
  1691. Camera *current_camera;
  1692. if (previewing) {
  1693. current_camera = previewing;
  1694. } else {
  1695. current_camera = camera;
  1696. }
  1697. if (show_info) {
  1698. String text;
  1699. text += "X: " + rtos(current_camera->get_translation().x).pad_decimals(1) + "\n";
  1700. text += "Y: " + rtos(current_camera->get_translation().y).pad_decimals(1) + "\n";
  1701. text += "Z: " + rtos(current_camera->get_translation().z).pad_decimals(1) + "\n";
  1702. text += TTR("Pitch") + ": " + itos(Math::round(current_camera->get_rotation_degrees().x)) + "\n";
  1703. text += TTR("Yaw") + ": " + itos(Math::round(current_camera->get_rotation_degrees().y)) + "\n\n";
  1704. text += TTR("Objects Drawn") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_OBJECTS_IN_FRAME)) + "\n";
  1705. text += TTR("Material Changes") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_MATERIAL_CHANGES_IN_FRAME)) + "\n";
  1706. text += TTR("Shader Changes") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_SHADER_CHANGES_IN_FRAME)) + "\n";
  1707. text += TTR("Surface Changes") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_SURFACE_CHANGES_IN_FRAME)) + "\n";
  1708. text += TTR("Draw Calls") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_DRAW_CALLS_IN_FRAME)) + "\n";
  1709. text += TTR("Vertices") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_VERTICES_IN_FRAME));
  1710. info_label->set_text(text);
  1711. }
  1712. // FPS Counter.
  1713. bool show_fps = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_FPS));
  1714. fps_label->set_visible(show_fps);
  1715. if (show_fps) {
  1716. String text;
  1717. const float temp_fps = Engine::get_singleton()->get_frames_per_second();
  1718. text += TTR(vformat("FPS: %d (%s ms)", temp_fps, String::num(1000.0f / temp_fps, 2)));
  1719. fps_label->set_text(text);
  1720. }
  1721. bool show_cinema = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
  1722. cinema_label->set_visible(show_cinema);
  1723. if (show_cinema) {
  1724. float cinema_half_width = cinema_label->get_size().width / 2.0f;
  1725. cinema_label->set_anchor_and_margin(MARGIN_LEFT, 0.5f, -cinema_half_width);
  1726. }
  1727. if (lock_rotation) {
  1728. float locked_half_width = locked_label->get_size().width / 2.0f;
  1729. locked_label->set_anchor_and_margin(MARGIN_LEFT, 0.5f, -locked_half_width);
  1730. }
  1731. }
  1732. if (p_what == NOTIFICATION_ENTER_TREE) {
  1733. surface->connect("draw", this, "_draw");
  1734. surface->connect("gui_input", this, "_sinput");
  1735. surface->connect("mouse_entered", this, "_surface_mouse_enter");
  1736. surface->connect("mouse_exited", this, "_surface_mouse_exit");
  1737. surface->connect("focus_entered", this, "_surface_focus_enter");
  1738. surface->connect("focus_exited", this, "_surface_focus_exit");
  1739. _init_gizmo_instance(index);
  1740. }
  1741. if (p_what == NOTIFICATION_EXIT_TREE) {
  1742. _finish_gizmo_instances();
  1743. }
  1744. if (p_what == NOTIFICATION_THEME_CHANGED) {
  1745. view_menu->set_icon(get_icon("GuiMiniTabMenu", "EditorIcons"));
  1746. preview_camera->set_icon(get_icon("Camera", "EditorIcons"));
  1747. view_menu->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1748. view_menu->add_style_override("hover", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1749. view_menu->add_style_override("pressed", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1750. view_menu->add_style_override("focus", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1751. view_menu->add_style_override("disabled", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1752. preview_camera->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1753. preview_camera->add_style_override("hover", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1754. preview_camera->add_style_override("pressed", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1755. preview_camera->add_style_override("focus", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1756. preview_camera->add_style_override("disabled", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1757. info_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1758. fps_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1759. cinema_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1760. locked_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1761. }
  1762. }
  1763. static void draw_indicator_bar(Control &surface, real_t fill, Ref<Texture> icon) {
  1764. // Adjust bar size from control height
  1765. Vector2 surface_size = surface.get_size();
  1766. real_t h = surface_size.y / 2.0;
  1767. real_t y = (surface_size.y - h) / 2.0;
  1768. Rect2 r(10, y, 6, h);
  1769. real_t sy = r.size.y * fill;
  1770. // Note: because this bar appears over the viewport, it has to stay readable for any background color
  1771. // Draw both neutral dark and bright colors to account this
  1772. surface.draw_rect(r, Color(1, 1, 1, 0.2));
  1773. surface.draw_rect(Rect2(r.position.x, r.position.y + r.size.y - sy, r.size.x, sy), Color(1, 1, 1, 0.6));
  1774. surface.draw_rect(r.grow(1), Color(0, 0, 0, 0.7), false, Math::round(EDSCALE));
  1775. Vector2 icon_size = icon->get_size();
  1776. Vector2 icon_pos = Vector2(r.position.x - (icon_size.x - r.size.x) / 2, r.position.y + r.size.y + 2);
  1777. surface.draw_texture(icon, icon_pos);
  1778. }
  1779. void SpatialEditorViewport::_draw() {
  1780. EditorPluginList *over_plugin_list = EditorNode::get_singleton()->get_editor_plugins_over();
  1781. if (!over_plugin_list->empty()) {
  1782. over_plugin_list->forward_spatial_draw_over_viewport(surface);
  1783. }
  1784. EditorPluginList *force_over_plugin_list = editor->get_editor_plugins_force_over();
  1785. if (!force_over_plugin_list->empty()) {
  1786. force_over_plugin_list->forward_spatial_force_draw_over_viewport(surface);
  1787. }
  1788. if (surface->has_focus()) {
  1789. Size2 size = surface->get_size();
  1790. Rect2 r = Rect2(Point2(), size);
  1791. get_stylebox("Focus", "EditorStyles")->draw(surface->get_canvas_item(), r);
  1792. }
  1793. if (cursor.region_select) {
  1794. const Rect2 selection_rect = Rect2(cursor.region_begin, cursor.region_end - cursor.region_begin);
  1795. surface->draw_rect(
  1796. selection_rect,
  1797. get_color("box_selection_fill_color", "Editor"));
  1798. surface->draw_rect(
  1799. selection_rect,
  1800. get_color("box_selection_stroke_color", "Editor"),
  1801. false,
  1802. Math::round(EDSCALE));
  1803. }
  1804. RID ci = surface->get_canvas_item();
  1805. if (message_time > 0) {
  1806. Ref<Font> font = get_font("font", "Label");
  1807. Point2 msgpos = Point2(5, get_size().y - 20);
  1808. font->draw(ci, msgpos + Point2(1, 1), message, Color(0, 0, 0, 0.8));
  1809. font->draw(ci, msgpos + Point2(-1, -1), message, Color(0, 0, 0, 0.8));
  1810. font->draw(ci, msgpos, message, Color(1, 1, 1, 1));
  1811. }
  1812. if (_edit.mode == TRANSFORM_ROTATE) {
  1813. Point2 center = _point_to_screen(_edit.center);
  1814. VisualServer::get_singleton()->canvas_item_add_line(
  1815. ci,
  1816. _edit.mouse_pos,
  1817. center,
  1818. get_color("accent_color", "Editor") * Color(1, 1, 1, 0.6),
  1819. Math::round(2 * EDSCALE),
  1820. true);
  1821. }
  1822. if (previewing) {
  1823. Size2 ss = Size2(ProjectSettings::get_singleton()->get("display/window/size/width"), ProjectSettings::get_singleton()->get("display/window/size/height"));
  1824. float aspect = ss.aspect();
  1825. Size2 s = get_size();
  1826. Rect2 draw_rect;
  1827. switch (previewing->get_keep_aspect_mode()) {
  1828. case Camera::KEEP_WIDTH: {
  1829. draw_rect.size = Size2(s.width, s.width / aspect);
  1830. draw_rect.position.x = 0;
  1831. draw_rect.position.y = (s.height - draw_rect.size.y) * 0.5;
  1832. } break;
  1833. case Camera::KEEP_HEIGHT: {
  1834. draw_rect.size = Size2(s.height * aspect, s.height);
  1835. draw_rect.position.y = 0;
  1836. draw_rect.position.x = (s.width - draw_rect.size.x) * 0.5;
  1837. } break;
  1838. }
  1839. draw_rect = Rect2(Vector2(), s).clip(draw_rect);
  1840. surface->draw_rect(draw_rect, Color(0.6, 0.6, 0.1, 0.5), false, Math::round(2 * EDSCALE));
  1841. } else {
  1842. if (zoom_indicator_delay > 0.0) {
  1843. if (is_freelook_active()) {
  1844. // Show speed
  1845. real_t min_speed = FREELOOK_MIN_SPEED;
  1846. real_t max_speed = camera->get_zfar();
  1847. real_t scale_length = (max_speed - min_speed);
  1848. if (!Math::is_zero_approx(scale_length)) {
  1849. real_t logscale_t = 1.0 - Math::log(1 + freelook_speed - min_speed) / Math::log(1 + scale_length);
  1850. // There is no real maximum speed so that factor can become negative,
  1851. // Let's make it look asymptotic instead (will decrease slower and slower).
  1852. if (logscale_t < 0.25)
  1853. logscale_t = 0.25 * Math::exp(4.0 * logscale_t - 1.0);
  1854. draw_indicator_bar(*surface, 1.0 - logscale_t, get_icon("ViewportSpeed", "EditorIcons"));
  1855. }
  1856. } else {
  1857. // Show zoom
  1858. real_t min_distance = ZOOM_MIN_DISTANCE; // TODO Why not pick znear to limit zoom?
  1859. real_t max_distance = camera->get_zfar();
  1860. real_t scale_length = (max_distance - min_distance);
  1861. if (!Math::is_zero_approx(scale_length)) {
  1862. real_t logscale_t = 1.0 - Math::log(1 + cursor.distance - min_distance) / Math::log(1 + scale_length);
  1863. // There is no real maximum distance so that factor can become negative,
  1864. // Let's make it look asymptotic instead (will decrease slower and slower).
  1865. if (logscale_t < 0.25)
  1866. logscale_t = 0.25 * Math::exp(4.0 * logscale_t - 1.0);
  1867. draw_indicator_bar(*surface, logscale_t, get_icon("ViewportZoom", "EditorIcons"));
  1868. }
  1869. }
  1870. }
  1871. }
  1872. }
  1873. void SpatialEditorViewport::_menu_option(int p_option) {
  1874. switch (p_option) {
  1875. case VIEW_TOP: {
  1876. cursor.y_rot = 0;
  1877. cursor.x_rot = Math_PI / 2.0;
  1878. set_message(TTR("Top View."), 2);
  1879. name = TTR("Top");
  1880. _update_name();
  1881. } break;
  1882. case VIEW_BOTTOM: {
  1883. cursor.y_rot = 0;
  1884. cursor.x_rot = -Math_PI / 2.0;
  1885. set_message(TTR("Bottom View."), 2);
  1886. name = TTR("Bottom");
  1887. _update_name();
  1888. } break;
  1889. case VIEW_LEFT: {
  1890. cursor.x_rot = 0;
  1891. cursor.y_rot = Math_PI / 2.0;
  1892. set_message(TTR("Left View."), 2);
  1893. name = TTR("Left");
  1894. _update_name();
  1895. } break;
  1896. case VIEW_RIGHT: {
  1897. cursor.x_rot = 0;
  1898. cursor.y_rot = -Math_PI / 2.0;
  1899. set_message(TTR("Right View."), 2);
  1900. name = TTR("Right");
  1901. _update_name();
  1902. } break;
  1903. case VIEW_FRONT: {
  1904. cursor.x_rot = 0;
  1905. cursor.y_rot = 0;
  1906. set_message(TTR("Front View."), 2);
  1907. name = TTR("Front");
  1908. _update_name();
  1909. } break;
  1910. case VIEW_REAR: {
  1911. cursor.x_rot = 0;
  1912. cursor.y_rot = Math_PI;
  1913. set_message(TTR("Rear View."), 2);
  1914. name = TTR("Rear");
  1915. _update_name();
  1916. } break;
  1917. case VIEW_CENTER_TO_ORIGIN: {
  1918. cursor.pos = Vector3(0, 0, 0);
  1919. } break;
  1920. case VIEW_CENTER_TO_SELECTION: {
  1921. focus_selection();
  1922. } break;
  1923. case VIEW_ALIGN_TRANSFORM_WITH_VIEW: {
  1924. if (!get_selected_count())
  1925. break;
  1926. Transform camera_transform = camera->get_global_transform();
  1927. List<Node *> &selection = editor_selection->get_selected_node_list();
  1928. undo_redo->create_action(TTR("Align Transform with View"));
  1929. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1930. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1931. if (!sp)
  1932. continue;
  1933. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1934. if (!se)
  1935. continue;
  1936. Transform xform;
  1937. if (orthogonal) {
  1938. xform = sp->get_global_transform();
  1939. xform.basis.set_euler(camera_transform.basis.get_euler());
  1940. } else {
  1941. xform = camera_transform;
  1942. xform.scale_basis(sp->get_scale());
  1943. }
  1944. undo_redo->add_do_method(sp, "set_global_transform", xform);
  1945. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
  1946. }
  1947. undo_redo->commit_action();
  1948. focus_selection();
  1949. } break;
  1950. case VIEW_ALIGN_ROTATION_WITH_VIEW: {
  1951. if (!get_selected_count())
  1952. break;
  1953. Transform camera_transform = camera->get_global_transform();
  1954. List<Node *> &selection = editor_selection->get_selected_node_list();
  1955. undo_redo->create_action(TTR("Align Rotation with View"));
  1956. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1957. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1958. if (!sp)
  1959. continue;
  1960. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1961. if (!se)
  1962. continue;
  1963. undo_redo->add_do_method(sp, "set_rotation", camera_transform.basis.get_rotation());
  1964. undo_redo->add_undo_method(sp, "set_rotation", sp->get_rotation());
  1965. }
  1966. undo_redo->commit_action();
  1967. } break;
  1968. case VIEW_ENVIRONMENT: {
  1969. int idx = view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT);
  1970. bool current = view_menu->get_popup()->is_item_checked(idx);
  1971. current = !current;
  1972. if (current) {
  1973. camera->set_environment(RES());
  1974. } else {
  1975. camera->set_environment(SpatialEditor::get_singleton()->get_viewport_environment());
  1976. }
  1977. view_menu->get_popup()->set_item_checked(idx, current);
  1978. } break;
  1979. case VIEW_PERSPECTIVE: {
  1980. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
  1981. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), false);
  1982. orthogonal = false;
  1983. call_deferred("update_transform_gizmo_view");
  1984. _update_name();
  1985. } break;
  1986. case VIEW_ORTHOGONAL: {
  1987. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), false);
  1988. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), true);
  1989. orthogonal = true;
  1990. call_deferred("update_transform_gizmo_view");
  1991. _update_name();
  1992. } break;
  1993. case VIEW_LOCK_ROTATION: {
  1994. int idx = view_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
  1995. bool current = view_menu->get_popup()->is_item_checked(idx);
  1996. lock_rotation = !current;
  1997. view_menu->get_popup()->set_item_checked(idx, !current);
  1998. if (lock_rotation) {
  1999. locked_label->show();
  2000. } else {
  2001. locked_label->hide();
  2002. }
  2003. } break;
  2004. case VIEW_AUDIO_LISTENER: {
  2005. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
  2006. bool current = view_menu->get_popup()->is_item_checked(idx);
  2007. current = !current;
  2008. viewport->set_as_audio_listener(current);
  2009. view_menu->get_popup()->set_item_checked(idx, current);
  2010. } break;
  2011. case VIEW_AUDIO_DOPPLER: {
  2012. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
  2013. bool current = view_menu->get_popup()->is_item_checked(idx);
  2014. current = !current;
  2015. camera->set_doppler_tracking(current ? Camera::DOPPLER_TRACKING_IDLE_STEP : Camera::DOPPLER_TRACKING_DISABLED);
  2016. view_menu->get_popup()->set_item_checked(idx, current);
  2017. } break;
  2018. case VIEW_CINEMATIC_PREVIEW: {
  2019. int idx = view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
  2020. bool current = view_menu->get_popup()->is_item_checked(idx);
  2021. current = !current;
  2022. view_menu->get_popup()->set_item_checked(idx, current);
  2023. previewing_cinema = true;
  2024. _toggle_cinema_preview(current);
  2025. if (current) {
  2026. preview_camera->hide();
  2027. } else {
  2028. if (previewing != NULL)
  2029. preview_camera->show();
  2030. }
  2031. } break;
  2032. case VIEW_GIZMOS: {
  2033. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  2034. bool current = view_menu->get_popup()->is_item_checked(idx);
  2035. current = !current;
  2036. if (current)
  2037. camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + index)) | (1 << GIZMO_EDIT_LAYER) | (1 << GIZMO_GRID_LAYER));
  2038. else
  2039. camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + index)) | (1 << GIZMO_GRID_LAYER));
  2040. view_menu->get_popup()->set_item_checked(idx, current);
  2041. } break;
  2042. case VIEW_HALF_RESOLUTION: {
  2043. int idx = view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
  2044. bool current = view_menu->get_popup()->is_item_checked(idx);
  2045. current = !current;
  2046. view_menu->get_popup()->set_item_checked(idx, current);
  2047. } break;
  2048. case VIEW_INFORMATION: {
  2049. int idx = view_menu->get_popup()->get_item_index(VIEW_INFORMATION);
  2050. bool current = view_menu->get_popup()->is_item_checked(idx);
  2051. view_menu->get_popup()->set_item_checked(idx, !current);
  2052. } break;
  2053. case VIEW_FPS: {
  2054. int idx = view_menu->get_popup()->get_item_index(VIEW_FPS);
  2055. bool current = view_menu->get_popup()->is_item_checked(idx);
  2056. view_menu->get_popup()->set_item_checked(idx, !current);
  2057. } break;
  2058. case VIEW_DISPLAY_NORMAL: {
  2059. viewport->set_debug_draw(Viewport::DEBUG_DRAW_DISABLED);
  2060. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), true);
  2061. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), false);
  2062. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), false);
  2063. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), false);
  2064. } break;
  2065. case VIEW_DISPLAY_WIREFRAME: {
  2066. viewport->set_debug_draw(Viewport::DEBUG_DRAW_WIREFRAME);
  2067. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), false);
  2068. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), true);
  2069. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), false);
  2070. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), false);
  2071. } break;
  2072. case VIEW_DISPLAY_OVERDRAW: {
  2073. viewport->set_debug_draw(Viewport::DEBUG_DRAW_OVERDRAW);
  2074. VisualServer::get_singleton()->scenario_set_debug(get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_OVERDRAW);
  2075. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), false);
  2076. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), false);
  2077. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), true);
  2078. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), false);
  2079. } break;
  2080. case VIEW_DISPLAY_SHADELESS: {
  2081. viewport->set_debug_draw(Viewport::DEBUG_DRAW_UNSHADED);
  2082. VisualServer::get_singleton()->scenario_set_debug(get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_SHADELESS);
  2083. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), false);
  2084. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), false);
  2085. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), false);
  2086. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), true);
  2087. } break;
  2088. }
  2089. }
  2090. void SpatialEditorViewport::_preview_exited_scene() {
  2091. preview_camera->set_pressed(false);
  2092. _toggle_camera_preview(false);
  2093. view_menu->show();
  2094. }
  2095. void SpatialEditorViewport::_init_gizmo_instance(int p_idx) {
  2096. uint32_t layer = 1 << (GIZMO_BASE_LAYER + p_idx);
  2097. for (int i = 0; i < 3; i++) {
  2098. move_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2099. VS::get_singleton()->instance_set_base(move_gizmo_instance[i], spatial_editor->get_move_gizmo(i)->get_rid());
  2100. VS::get_singleton()->instance_set_scenario(move_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2101. VS::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  2102. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2103. VS::get_singleton()->instance_set_layer_mask(move_gizmo_instance[i], layer);
  2104. move_plane_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2105. VS::get_singleton()->instance_set_base(move_plane_gizmo_instance[i], spatial_editor->get_move_plane_gizmo(i)->get_rid());
  2106. VS::get_singleton()->instance_set_scenario(move_plane_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2107. VS::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  2108. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_plane_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2109. VS::get_singleton()->instance_set_layer_mask(move_plane_gizmo_instance[i], layer);
  2110. rotate_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2111. VS::get_singleton()->instance_set_base(rotate_gizmo_instance[i], spatial_editor->get_rotate_gizmo(i)->get_rid());
  2112. VS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2113. VS::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  2114. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2115. VS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[i], layer);
  2116. scale_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2117. VS::get_singleton()->instance_set_base(scale_gizmo_instance[i], spatial_editor->get_scale_gizmo(i)->get_rid());
  2118. VS::get_singleton()->instance_set_scenario(scale_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2119. VS::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  2120. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2121. VS::get_singleton()->instance_set_layer_mask(scale_gizmo_instance[i], layer);
  2122. scale_plane_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2123. VS::get_singleton()->instance_set_base(scale_plane_gizmo_instance[i], spatial_editor->get_scale_plane_gizmo(i)->get_rid());
  2124. VS::get_singleton()->instance_set_scenario(scale_plane_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2125. VS::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  2126. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_plane_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2127. VS::get_singleton()->instance_set_layer_mask(scale_plane_gizmo_instance[i], layer);
  2128. }
  2129. }
  2130. void SpatialEditorViewport::_finish_gizmo_instances() {
  2131. for (int i = 0; i < 3; i++) {
  2132. VS::get_singleton()->free(move_gizmo_instance[i]);
  2133. VS::get_singleton()->free(move_plane_gizmo_instance[i]);
  2134. VS::get_singleton()->free(rotate_gizmo_instance[i]);
  2135. VS::get_singleton()->free(scale_gizmo_instance[i]);
  2136. VS::get_singleton()->free(scale_plane_gizmo_instance[i]);
  2137. }
  2138. }
  2139. void SpatialEditorViewport::_toggle_camera_preview(bool p_activate) {
  2140. ERR_FAIL_COND(p_activate && !preview);
  2141. ERR_FAIL_COND(!p_activate && !previewing);
  2142. if (!p_activate) {
  2143. previewing->disconnect("tree_exiting", this, "_preview_exited_scene");
  2144. previewing = NULL;
  2145. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
  2146. if (!preview)
  2147. preview_camera->hide();
  2148. view_menu->set_disabled(false);
  2149. surface->update();
  2150. } else {
  2151. previewing = preview;
  2152. previewing->connect("tree_exiting", this, "_preview_exited_scene");
  2153. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), preview->get_camera()); //replace
  2154. view_menu->set_disabled(true);
  2155. surface->update();
  2156. }
  2157. }
  2158. void SpatialEditorViewport::_toggle_cinema_preview(bool p_activate) {
  2159. previewing_cinema = p_activate;
  2160. if (!previewing_cinema) {
  2161. if (previewing != NULL)
  2162. previewing->disconnect("tree_exited", this, "_preview_exited_scene");
  2163. previewing = NULL;
  2164. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
  2165. preview_camera->set_pressed(false);
  2166. if (!preview) {
  2167. preview_camera->hide();
  2168. } else {
  2169. preview_camera->show();
  2170. }
  2171. view_menu->show();
  2172. surface->update();
  2173. }
  2174. }
  2175. void SpatialEditorViewport::_selection_result_pressed(int p_result) {
  2176. if (selection_results.size() <= p_result)
  2177. return;
  2178. clicked = selection_results[p_result].item->get_instance_id();
  2179. if (clicked) {
  2180. _select_clicked(clicked_wants_append, true);
  2181. clicked = 0;
  2182. }
  2183. }
  2184. void SpatialEditorViewport::_selection_menu_hide() {
  2185. selection_results.clear();
  2186. selection_menu->clear();
  2187. selection_menu->set_size(Vector2(0, 0));
  2188. }
  2189. void SpatialEditorViewport::set_can_preview(Camera *p_preview) {
  2190. preview = p_preview;
  2191. if (!preview_camera->is_pressed() && !previewing_cinema)
  2192. preview_camera->set_visible(p_preview);
  2193. }
  2194. void SpatialEditorViewport::update_transform_gizmo_view() {
  2195. if (!is_visible_in_tree())
  2196. return;
  2197. Transform xform = spatial_editor->get_gizmo_transform();
  2198. Transform camera_xform = camera->get_transform();
  2199. if (xform.origin.distance_squared_to(camera_xform.origin) < 0.01) {
  2200. for (int i = 0; i < 3; i++) {
  2201. VisualServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  2202. VisualServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  2203. VisualServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  2204. VisualServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  2205. VisualServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  2206. }
  2207. return;
  2208. }
  2209. Vector3 camz = -camera_xform.get_basis().get_axis(2).normalized();
  2210. Vector3 camy = -camera_xform.get_basis().get_axis(1).normalized();
  2211. Plane p(camera_xform.origin, camz);
  2212. float gizmo_d = Math::abs(p.distance_to(xform.origin));
  2213. float d0 = camera->unproject_position(camera_xform.origin + camz * gizmo_d).y;
  2214. float d1 = camera->unproject_position(camera_xform.origin + camz * gizmo_d + camy).y;
  2215. float dd = Math::abs(d0 - d1);
  2216. if (dd == 0)
  2217. dd = 0.0001;
  2218. float gizmo_size = EditorSettings::get_singleton()->get("editors/3d/manipulator_gizmo_size");
  2219. // At low viewport heights, multiply the gizmo scale based on the viewport height.
  2220. // This prevents the gizmo from growing very large and going outside the viewport.
  2221. const int viewport_base_height = 400 * MAX(1, EDSCALE);
  2222. gizmo_scale =
  2223. (gizmo_size / Math::abs(dd)) * MAX(1, EDSCALE) *
  2224. MIN(viewport_base_height, viewport_container->get_size().height) / viewport_base_height /
  2225. viewport_container->get_stretch_shrink();
  2226. Vector3 scale = Vector3(1, 1, 1) * gizmo_scale;
  2227. xform.basis.scale(scale);
  2228. for (int i = 0; i < 3; i++) {
  2229. VisualServer::get_singleton()->instance_set_transform(move_gizmo_instance[i], xform);
  2230. VisualServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_MOVE));
  2231. VisualServer::get_singleton()->instance_set_transform(move_plane_gizmo_instance[i], xform);
  2232. VisualServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_MOVE));
  2233. VisualServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[i], xform);
  2234. VisualServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_ROTATE));
  2235. VisualServer::get_singleton()->instance_set_transform(scale_gizmo_instance[i], xform);
  2236. VisualServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SCALE));
  2237. VisualServer::get_singleton()->instance_set_transform(scale_plane_gizmo_instance[i], xform);
  2238. VisualServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SCALE));
  2239. }
  2240. }
  2241. void SpatialEditorViewport::set_state(const Dictionary &p_state) {
  2242. if (p_state.has("position"))
  2243. cursor.pos = p_state["position"];
  2244. if (p_state.has("x_rotation"))
  2245. cursor.x_rot = p_state["x_rotation"];
  2246. if (p_state.has("y_rotation"))
  2247. cursor.y_rot = p_state["y_rotation"];
  2248. if (p_state.has("distance"))
  2249. cursor.distance = p_state["distance"];
  2250. if (p_state.has("use_orthogonal")) {
  2251. bool orth = p_state["use_orthogonal"];
  2252. if (orth)
  2253. _menu_option(VIEW_ORTHOGONAL);
  2254. else
  2255. _menu_option(VIEW_PERSPECTIVE);
  2256. }
  2257. if (p_state.has("display_mode")) {
  2258. int display = p_state["display_mode"];
  2259. int idx = view_menu->get_popup()->get_item_index(display);
  2260. if (!view_menu->get_popup()->is_item_checked(idx))
  2261. _menu_option(display);
  2262. }
  2263. if (p_state.has("lock_rotation")) {
  2264. lock_rotation = p_state["lock_rotation"];
  2265. int idx = view_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
  2266. view_menu->get_popup()->set_item_checked(idx, lock_rotation);
  2267. }
  2268. if (p_state.has("use_environment")) {
  2269. bool env = p_state["use_environment"];
  2270. if (env != camera->get_environment().is_valid())
  2271. _menu_option(VIEW_ENVIRONMENT);
  2272. }
  2273. if (p_state.has("listener")) {
  2274. bool listener = p_state["listener"];
  2275. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
  2276. viewport->set_as_audio_listener(listener);
  2277. view_menu->get_popup()->set_item_checked(idx, listener);
  2278. }
  2279. if (p_state.has("doppler")) {
  2280. bool doppler = p_state["doppler"];
  2281. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
  2282. camera->set_doppler_tracking(doppler ? Camera::DOPPLER_TRACKING_IDLE_STEP : Camera::DOPPLER_TRACKING_DISABLED);
  2283. view_menu->get_popup()->set_item_checked(idx, doppler);
  2284. }
  2285. if (p_state.has("gizmos")) {
  2286. bool gizmos = p_state["gizmos"];
  2287. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  2288. if (view_menu->get_popup()->is_item_checked(idx) != gizmos)
  2289. _menu_option(VIEW_GIZMOS);
  2290. }
  2291. if (p_state.has("information")) {
  2292. bool information = p_state["information"];
  2293. int idx = view_menu->get_popup()->get_item_index(VIEW_INFORMATION);
  2294. if (view_menu->get_popup()->is_item_checked(idx) != information)
  2295. _menu_option(VIEW_INFORMATION);
  2296. }
  2297. if (p_state.has("fps")) {
  2298. bool fps = p_state["fps"];
  2299. int idx = view_menu->get_popup()->get_item_index(VIEW_FPS);
  2300. if (view_menu->get_popup()->is_item_checked(idx) != fps)
  2301. _menu_option(VIEW_FPS);
  2302. }
  2303. if (p_state.has("half_res")) {
  2304. bool half_res = p_state["half_res"];
  2305. int idx = view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
  2306. view_menu->get_popup()->set_item_checked(idx, half_res);
  2307. }
  2308. if (p_state.has("cinematic_preview")) {
  2309. previewing_cinema = p_state["cinematic_preview"];
  2310. int idx = view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
  2311. view_menu->get_popup()->set_item_checked(idx, previewing_cinema);
  2312. }
  2313. if (p_state.has("previewing")) {
  2314. Node *pv = EditorNode::get_singleton()->get_edited_scene()->get_node(p_state["previewing"]);
  2315. if (Object::cast_to<Camera>(pv)) {
  2316. previewing = Object::cast_to<Camera>(pv);
  2317. previewing->connect("tree_exiting", this, "_preview_exited_scene");
  2318. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), previewing->get_camera()); //replace
  2319. view_menu->set_disabled(true);
  2320. surface->update();
  2321. preview_camera->set_pressed(true);
  2322. preview_camera->show();
  2323. }
  2324. }
  2325. }
  2326. Dictionary SpatialEditorViewport::get_state() const {
  2327. Dictionary d;
  2328. d["position"] = cursor.pos;
  2329. d["x_rotation"] = cursor.x_rot;
  2330. d["y_rotation"] = cursor.y_rot;
  2331. d["distance"] = cursor.distance;
  2332. d["use_environment"] = camera->get_environment().is_valid();
  2333. d["use_orthogonal"] = camera->get_projection() == Camera::PROJECTION_ORTHOGONAL;
  2334. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL)))
  2335. d["display_mode"] = VIEW_DISPLAY_NORMAL;
  2336. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME)))
  2337. d["display_mode"] = VIEW_DISPLAY_WIREFRAME;
  2338. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW)))
  2339. d["display_mode"] = VIEW_DISPLAY_OVERDRAW;
  2340. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS)))
  2341. d["display_mode"] = VIEW_DISPLAY_SHADELESS;
  2342. d["listener"] = viewport->is_audio_listener();
  2343. d["doppler"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER));
  2344. d["gizmos"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_GIZMOS));
  2345. d["information"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_INFORMATION));
  2346. d["fps"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_FPS));
  2347. d["half_res"] = viewport_container->get_stretch_shrink() > 1;
  2348. d["cinematic_preview"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
  2349. if (previewing)
  2350. d["previewing"] = EditorNode::get_singleton()->get_edited_scene()->get_path_to(previewing);
  2351. if (lock_rotation)
  2352. d["lock_rotation"] = lock_rotation;
  2353. return d;
  2354. }
  2355. void SpatialEditorViewport::_bind_methods() {
  2356. ClassDB::bind_method(D_METHOD("_draw"), &SpatialEditorViewport::_draw);
  2357. ClassDB::bind_method(D_METHOD("_surface_mouse_enter"), &SpatialEditorViewport::_surface_mouse_enter);
  2358. ClassDB::bind_method(D_METHOD("_surface_mouse_exit"), &SpatialEditorViewport::_surface_mouse_exit);
  2359. ClassDB::bind_method(D_METHOD("_surface_focus_enter"), &SpatialEditorViewport::_surface_focus_enter);
  2360. ClassDB::bind_method(D_METHOD("_surface_focus_exit"), &SpatialEditorViewport::_surface_focus_exit);
  2361. ClassDB::bind_method(D_METHOD("_sinput"), &SpatialEditorViewport::_sinput);
  2362. ClassDB::bind_method(D_METHOD("_menu_option"), &SpatialEditorViewport::_menu_option);
  2363. ClassDB::bind_method(D_METHOD("_toggle_camera_preview"), &SpatialEditorViewport::_toggle_camera_preview);
  2364. ClassDB::bind_method(D_METHOD("_preview_exited_scene"), &SpatialEditorViewport::_preview_exited_scene);
  2365. ClassDB::bind_method(D_METHOD("update_transform_gizmo_view"), &SpatialEditorViewport::update_transform_gizmo_view);
  2366. ClassDB::bind_method(D_METHOD("_selection_result_pressed"), &SpatialEditorViewport::_selection_result_pressed);
  2367. ClassDB::bind_method(D_METHOD("_selection_menu_hide"), &SpatialEditorViewport::_selection_menu_hide);
  2368. ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &SpatialEditorViewport::can_drop_data_fw);
  2369. ClassDB::bind_method(D_METHOD("drop_data_fw"), &SpatialEditorViewport::drop_data_fw);
  2370. ADD_SIGNAL(MethodInfo("toggle_maximize_view", PropertyInfo(Variant::OBJECT, "viewport")));
  2371. }
  2372. void SpatialEditorViewport::reset() {
  2373. orthogonal = false;
  2374. lock_rotation = false;
  2375. message_time = 0;
  2376. message = "";
  2377. last_message = "";
  2378. name = "";
  2379. cursor.x_rot = 0.5;
  2380. cursor.y_rot = 0.5;
  2381. cursor.distance = 4;
  2382. cursor.region_select = false;
  2383. cursor.pos = Vector3();
  2384. _update_name();
  2385. }
  2386. void SpatialEditorViewport::focus_selection() {
  2387. if (!get_selected_count())
  2388. return;
  2389. Vector3 center;
  2390. int count = 0;
  2391. List<Node *> &selection = editor_selection->get_selected_node_list();
  2392. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  2393. Spatial *sp = Object::cast_to<Spatial>(E->get());
  2394. if (!sp)
  2395. continue;
  2396. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  2397. if (!se)
  2398. continue;
  2399. center += sp->get_global_gizmo_transform().origin;
  2400. count++;
  2401. }
  2402. if (count != 0) {
  2403. center /= float(count);
  2404. }
  2405. cursor.pos = center;
  2406. }
  2407. void SpatialEditorViewport::assign_pending_data_pointers(Spatial *p_preview_node, AABB *p_preview_bounds, AcceptDialog *p_accept) {
  2408. preview_node = p_preview_node;
  2409. preview_bounds = p_preview_bounds;
  2410. accept = p_accept;
  2411. }
  2412. Vector3 SpatialEditorViewport::_get_instance_position(const Point2 &p_pos) const {
  2413. const float MAX_DISTANCE = 10;
  2414. Vector3 world_ray = _get_ray(p_pos);
  2415. Vector3 world_pos = _get_ray_pos(p_pos);
  2416. Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_ray(world_pos, world_ray, get_tree()->get_root()->get_world()->get_scenario());
  2417. Set<Ref<EditorSpatialGizmo> > found_gizmos;
  2418. float closest_dist = MAX_DISTANCE;
  2419. Vector3 point = world_pos + world_ray * MAX_DISTANCE;
  2420. Vector3 normal = Vector3(0.0, 0.0, 0.0);
  2421. for (int i = 0; i < instances.size(); i++) {
  2422. MeshInstance *mesh_instance = Object::cast_to<MeshInstance>(ObjectDB::get_instance(instances[i]));
  2423. if (!mesh_instance)
  2424. continue;
  2425. Ref<EditorSpatialGizmo> seg = mesh_instance->get_gizmo();
  2426. if ((!seg.is_valid()) || found_gizmos.has(seg)) {
  2427. continue;
  2428. }
  2429. found_gizmos.insert(seg);
  2430. Vector3 hit_point;
  2431. Vector3 hit_normal;
  2432. bool inters = seg->intersect_ray(camera, p_pos, hit_point, hit_normal, NULL, false);
  2433. if (!inters)
  2434. continue;
  2435. float dist = world_pos.distance_to(hit_point);
  2436. if (dist < 0)
  2437. continue;
  2438. if (dist < closest_dist) {
  2439. closest_dist = dist;
  2440. point = hit_point;
  2441. normal = hit_normal;
  2442. }
  2443. }
  2444. Vector3 offset = Vector3();
  2445. for (int i = 0; i < 3; i++) {
  2446. if (normal[i] > 0.0)
  2447. offset[i] = (preview_bounds->get_size()[i] - (preview_bounds->get_size()[i] + preview_bounds->get_position()[i]));
  2448. else if (normal[i] < 0.0)
  2449. offset[i] = -(preview_bounds->get_size()[i] + preview_bounds->get_position()[i]);
  2450. }
  2451. return point + offset;
  2452. }
  2453. AABB SpatialEditorViewport::_calculate_spatial_bounds(const Spatial *p_parent, const AABB &p_bounds) {
  2454. AABB bounds = p_bounds;
  2455. for (int i = 0; i < p_parent->get_child_count(); i++) {
  2456. Spatial *child = Object::cast_to<Spatial>(p_parent->get_child(i));
  2457. if (child) {
  2458. MeshInstance *mesh_instance = Object::cast_to<MeshInstance>(child);
  2459. if (mesh_instance) {
  2460. AABB mesh_instance_bounds = mesh_instance->get_aabb();
  2461. mesh_instance_bounds.position += mesh_instance->get_global_gizmo_transform().origin - p_parent->get_global_gizmo_transform().origin;
  2462. bounds.merge_with(mesh_instance_bounds);
  2463. }
  2464. bounds = _calculate_spatial_bounds(child, bounds);
  2465. }
  2466. }
  2467. return bounds;
  2468. }
  2469. void SpatialEditorViewport::_create_preview(const Vector<String> &files) const {
  2470. for (int i = 0; i < files.size(); i++) {
  2471. String path = files[i];
  2472. RES res = ResourceLoader::load(path);
  2473. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  2474. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  2475. if (mesh != NULL || scene != NULL) {
  2476. if (mesh != NULL) {
  2477. MeshInstance *mesh_instance = memnew(MeshInstance);
  2478. mesh_instance->set_mesh(mesh);
  2479. preview_node->add_child(mesh_instance);
  2480. } else {
  2481. if (scene.is_valid()) {
  2482. Node *instance = scene->instance();
  2483. if (instance) {
  2484. preview_node->add_child(instance);
  2485. }
  2486. }
  2487. }
  2488. editor->get_scene_root()->add_child(preview_node);
  2489. }
  2490. }
  2491. *preview_bounds = _calculate_spatial_bounds(preview_node, AABB());
  2492. }
  2493. void SpatialEditorViewport::_remove_preview() {
  2494. if (preview_node->get_parent()) {
  2495. for (int i = preview_node->get_child_count() - 1; i >= 0; i--) {
  2496. Node *node = preview_node->get_child(i);
  2497. node->queue_delete();
  2498. preview_node->remove_child(node);
  2499. }
  2500. editor->get_scene_root()->remove_child(preview_node);
  2501. }
  2502. }
  2503. bool SpatialEditorViewport::_cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node) {
  2504. if (p_desired_node->get_filename() == p_target_scene_path) {
  2505. return true;
  2506. }
  2507. int childCount = p_desired_node->get_child_count();
  2508. for (int i = 0; i < childCount; i++) {
  2509. Node *child = p_desired_node->get_child(i);
  2510. if (_cyclical_dependency_exists(p_target_scene_path, child)) {
  2511. return true;
  2512. }
  2513. }
  2514. return false;
  2515. }
  2516. bool SpatialEditorViewport::_create_instance(Node *parent, String &path, const Point2 &p_point) {
  2517. RES res = ResourceLoader::load(path);
  2518. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  2519. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  2520. Node *instanced_scene = NULL;
  2521. if (mesh != NULL || scene != NULL) {
  2522. if (mesh != NULL) {
  2523. MeshInstance *mesh_instance = memnew(MeshInstance);
  2524. mesh_instance->set_mesh(mesh);
  2525. mesh_instance->set_name(path.get_file().get_basename());
  2526. instanced_scene = mesh_instance;
  2527. } else {
  2528. if (!scene.is_valid()) { // invalid scene
  2529. return false;
  2530. } else {
  2531. instanced_scene = scene->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
  2532. }
  2533. }
  2534. }
  2535. if (instanced_scene == NULL) {
  2536. return false;
  2537. }
  2538. if (editor->get_edited_scene()->get_filename() != "") { // cyclical instancing
  2539. if (_cyclical_dependency_exists(editor->get_edited_scene()->get_filename(), instanced_scene)) {
  2540. memdelete(instanced_scene);
  2541. return false;
  2542. }
  2543. }
  2544. if (scene != NULL) {
  2545. instanced_scene->set_filename(ProjectSettings::get_singleton()->localize_path(path));
  2546. }
  2547. editor_data->get_undo_redo().add_do_method(parent, "add_child", instanced_scene);
  2548. editor_data->get_undo_redo().add_do_method(instanced_scene, "set_owner", editor->get_edited_scene());
  2549. editor_data->get_undo_redo().add_do_reference(instanced_scene);
  2550. editor_data->get_undo_redo().add_undo_method(parent, "remove_child", instanced_scene);
  2551. String new_name = parent->validate_child_name(instanced_scene);
  2552. ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger();
  2553. editor_data->get_undo_redo().add_do_method(sed, "live_debug_instance_node", editor->get_edited_scene()->get_path_to(parent), path, new_name);
  2554. editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(editor->get_edited_scene()->get_path_to(parent)) + "/" + new_name));
  2555. Transform global_transform;
  2556. Spatial *parent_spatial = Object::cast_to<Spatial>(parent);
  2557. if (parent_spatial)
  2558. global_transform = parent_spatial->get_global_gizmo_transform();
  2559. global_transform.origin = spatial_editor->snap_point(_get_instance_position(p_point));
  2560. editor_data->get_undo_redo().add_do_method(instanced_scene, "set_global_transform", global_transform);
  2561. return true;
  2562. }
  2563. void SpatialEditorViewport::_perform_drop_data() {
  2564. _remove_preview();
  2565. Vector<String> error_files;
  2566. editor_data->get_undo_redo().create_action(TTR("Create Node"));
  2567. for (int i = 0; i < selected_files.size(); i++) {
  2568. String path = selected_files[i];
  2569. RES res = ResourceLoader::load(path);
  2570. if (res.is_null()) {
  2571. continue;
  2572. }
  2573. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  2574. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  2575. if (mesh != NULL || scene != NULL) {
  2576. bool success = _create_instance(target_node, path, drop_pos);
  2577. if (!success) {
  2578. error_files.push_back(path);
  2579. }
  2580. }
  2581. }
  2582. editor_data->get_undo_redo().commit_action();
  2583. if (error_files.size() > 0) {
  2584. String files_str;
  2585. for (int i = 0; i < error_files.size(); i++) {
  2586. files_str += error_files[i].get_file().get_basename() + ",";
  2587. }
  2588. files_str = files_str.substr(0, files_str.length() - 1);
  2589. accept->set_text(vformat(TTR("Error instancing scene from %s"), files_str.c_str()));
  2590. accept->popup_centered_minsize();
  2591. }
  2592. }
  2593. bool SpatialEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
  2594. bool can_instance = false;
  2595. if (!preview_node->is_inside_tree()) {
  2596. Dictionary d = p_data;
  2597. if (d.has("type") && (String(d["type"]) == "files")) {
  2598. Vector<String> files = d["files"];
  2599. List<String> scene_extensions;
  2600. ResourceLoader::get_recognized_extensions_for_type("PackedScene", &scene_extensions);
  2601. List<String> mesh_extensions;
  2602. ResourceLoader::get_recognized_extensions_for_type("Mesh", &mesh_extensions);
  2603. for (int i = 0; i < files.size(); i++) {
  2604. if (mesh_extensions.find(files[i].get_extension()) || scene_extensions.find(files[i].get_extension())) {
  2605. RES res = ResourceLoader::load(files[i]);
  2606. if (res.is_null()) {
  2607. continue;
  2608. }
  2609. String type = res->get_class();
  2610. if (type == "PackedScene") {
  2611. Ref<PackedScene> sdata = ResourceLoader::load(files[i]);
  2612. Node *instanced_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
  2613. if (!instanced_scene) {
  2614. continue;
  2615. }
  2616. memdelete(instanced_scene);
  2617. } else if (type == "Mesh" || type == "ArrayMesh" || type == "PrimitiveMesh") {
  2618. Ref<Mesh> mesh = ResourceLoader::load(files[i]);
  2619. if (!mesh.is_valid()) {
  2620. continue;
  2621. }
  2622. } else {
  2623. continue;
  2624. }
  2625. can_instance = true;
  2626. break;
  2627. }
  2628. }
  2629. if (can_instance) {
  2630. _create_preview(files);
  2631. }
  2632. }
  2633. } else {
  2634. can_instance = true;
  2635. }
  2636. if (can_instance) {
  2637. Transform global_transform = Transform(Basis(), _get_instance_position(p_point));
  2638. preview_node->set_global_transform(global_transform);
  2639. }
  2640. return can_instance;
  2641. }
  2642. void SpatialEditorViewport::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
  2643. if (!can_drop_data_fw(p_point, p_data, p_from))
  2644. return;
  2645. bool is_shift = Input::get_singleton()->is_key_pressed(KEY_SHIFT);
  2646. selected_files.clear();
  2647. Dictionary d = p_data;
  2648. if (d.has("type") && String(d["type"]) == "files") {
  2649. selected_files = d["files"];
  2650. }
  2651. List<Node *> list = editor->get_editor_selection()->get_selected_node_list();
  2652. if (list.size() == 0) {
  2653. Node *root_node = editor->get_edited_scene();
  2654. if (root_node) {
  2655. list.push_back(root_node);
  2656. } else {
  2657. accept->set_text(TTR("No parent to instance a child at."));
  2658. accept->popup_centered_minsize();
  2659. _remove_preview();
  2660. return;
  2661. }
  2662. }
  2663. if (list.size() != 1) {
  2664. accept->set_text(TTR("This operation requires a single selected node."));
  2665. accept->popup_centered_minsize();
  2666. _remove_preview();
  2667. return;
  2668. }
  2669. target_node = list[0];
  2670. if (is_shift && target_node != editor->get_edited_scene()) {
  2671. target_node = target_node->get_parent();
  2672. }
  2673. drop_pos = p_point;
  2674. _perform_drop_data();
  2675. }
  2676. SpatialEditorViewport::SpatialEditorViewport(SpatialEditor *p_spatial_editor, EditorNode *p_editor, int p_index) {
  2677. _edit.mode = TRANSFORM_NONE;
  2678. _edit.plane = TRANSFORM_VIEW;
  2679. _edit.edited_gizmo = 0;
  2680. _edit.snap = 1;
  2681. _edit.gizmo_handle = 0;
  2682. index = p_index;
  2683. editor = p_editor;
  2684. editor_data = editor->get_scene_tree_dock()->get_editor_data();
  2685. editor_selection = editor->get_editor_selection();
  2686. undo_redo = editor->get_undo_redo();
  2687. clicked = 0;
  2688. clicked_includes_current = false;
  2689. orthogonal = false;
  2690. lock_rotation = false;
  2691. message_time = 0;
  2692. zoom_indicator_delay = 0.0;
  2693. spatial_editor = p_spatial_editor;
  2694. ViewportContainer *c = memnew(ViewportContainer);
  2695. viewport_container = c;
  2696. c->set_stretch(true);
  2697. add_child(c);
  2698. c->set_anchors_and_margins_preset(Control::PRESET_WIDE);
  2699. viewport = memnew(Viewport);
  2700. viewport->set_disable_input(true);
  2701. c->add_child(viewport);
  2702. surface = memnew(Control);
  2703. surface->set_drag_forwarding(this);
  2704. add_child(surface);
  2705. surface->set_anchors_and_margins_preset(Control::PRESET_WIDE);
  2706. surface->set_clip_contents(true);
  2707. camera = memnew(Camera);
  2708. camera->set_disable_gizmo(true);
  2709. camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + p_index)) | (1 << GIZMO_EDIT_LAYER) | (1 << GIZMO_GRID_LAYER));
  2710. viewport->add_child(camera);
  2711. camera->make_current();
  2712. surface->set_focus_mode(FOCUS_ALL);
  2713. VBoxContainer *vbox = memnew(VBoxContainer);
  2714. surface->add_child(vbox);
  2715. vbox->set_position(Point2(10, 10) * EDSCALE);
  2716. view_menu = memnew(MenuButton);
  2717. view_menu->set_flat(false);
  2718. vbox->add_child(view_menu);
  2719. view_menu->set_h_size_flags(0);
  2720. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/top_view"), VIEW_TOP);
  2721. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/bottom_view"), VIEW_BOTTOM);
  2722. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/left_view"), VIEW_LEFT);
  2723. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/right_view"), VIEW_RIGHT);
  2724. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/front_view"), VIEW_FRONT);
  2725. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/rear_view"), VIEW_REAR);
  2726. view_menu->get_popup()->add_separator();
  2727. view_menu->get_popup()->add_radio_check_item(TTR("Perspective") + " (" + ED_GET_SHORTCUT("spatial_editor/switch_perspective_orthogonal")->get_as_text() + ")", VIEW_PERSPECTIVE);
  2728. view_menu->get_popup()->add_radio_check_item(TTR("Orthogonal") + " (" + ED_GET_SHORTCUT("spatial_editor/switch_perspective_orthogonal")->get_as_text() + ")", VIEW_ORTHOGONAL);
  2729. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
  2730. view_menu->get_popup()->add_separator();
  2731. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_lock_rotation", TTR("Lock View Rotation")), VIEW_LOCK_ROTATION);
  2732. view_menu->get_popup()->add_separator();
  2733. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_normal", TTR("Display Normal")), VIEW_DISPLAY_NORMAL);
  2734. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_wireframe", TTR("Display Wireframe")), VIEW_DISPLAY_WIREFRAME);
  2735. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_overdraw", TTR("Display Overdraw")), VIEW_DISPLAY_OVERDRAW);
  2736. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_unshaded", TTR("Display Unshaded")), VIEW_DISPLAY_SHADELESS);
  2737. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), true);
  2738. view_menu->get_popup()->add_separator();
  2739. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_environment", TTR("View Environment")), VIEW_ENVIRONMENT);
  2740. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_gizmos", TTR("View Gizmos")), VIEW_GIZMOS);
  2741. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_information", TTR("View Information")), VIEW_INFORMATION);
  2742. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_fps", TTR("View FPS")), VIEW_FPS);
  2743. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT), true);
  2744. view_menu->get_popup()->add_separator();
  2745. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_half_resolution", TTR("Half Resolution")), VIEW_HALF_RESOLUTION);
  2746. view_menu->get_popup()->add_separator();
  2747. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_listener", TTR("Audio Listener")), VIEW_AUDIO_LISTENER);
  2748. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_doppler", TTR("Enable Doppler")), VIEW_AUDIO_DOPPLER);
  2749. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_GIZMOS), true);
  2750. view_menu->get_popup()->add_separator();
  2751. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_cinematic_preview", TTR("Cinematic Preview")), VIEW_CINEMATIC_PREVIEW);
  2752. view_menu->get_popup()->add_separator();
  2753. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_origin"), VIEW_CENTER_TO_ORIGIN);
  2754. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_selection"), VIEW_CENTER_TO_SELECTION);
  2755. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_transform_with_view"), VIEW_ALIGN_TRANSFORM_WITH_VIEW);
  2756. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_rotation_with_view"), VIEW_ALIGN_ROTATION_WITH_VIEW);
  2757. view_menu->get_popup()->connect("id_pressed", this, "_menu_option");
  2758. view_menu->set_disable_shortcuts(true);
  2759. ED_SHORTCUT("spatial_editor/freelook_left", TTR("Freelook Left"), KEY_A);
  2760. ED_SHORTCUT("spatial_editor/freelook_right", TTR("Freelook Right"), KEY_D);
  2761. ED_SHORTCUT("spatial_editor/freelook_forward", TTR("Freelook Forward"), KEY_W);
  2762. ED_SHORTCUT("spatial_editor/freelook_backwards", TTR("Freelook Backwards"), KEY_S);
  2763. ED_SHORTCUT("spatial_editor/freelook_up", TTR("Freelook Up"), KEY_E);
  2764. ED_SHORTCUT("spatial_editor/freelook_down", TTR("Freelook Down"), KEY_Q);
  2765. ED_SHORTCUT("spatial_editor/freelook_speed_modifier", TTR("Freelook Speed Modifier"), KEY_SHIFT);
  2766. preview_camera = memnew(CheckBox);
  2767. preview_camera->set_text(TTR("Preview"));
  2768. vbox->add_child(preview_camera);
  2769. preview_camera->set_h_size_flags(0);
  2770. preview_camera->hide();
  2771. preview_camera->connect("toggled", this, "_toggle_camera_preview");
  2772. previewing = NULL;
  2773. gizmo_scale = 1.0;
  2774. preview_node = NULL;
  2775. info_label = memnew(Label);
  2776. info_label->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, -90 * EDSCALE);
  2777. info_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_END, -90 * EDSCALE);
  2778. info_label->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -10 * EDSCALE);
  2779. info_label->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, -10 * EDSCALE);
  2780. info_label->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  2781. info_label->set_v_grow_direction(GROW_DIRECTION_BEGIN);
  2782. surface->add_child(info_label);
  2783. info_label->hide();
  2784. fps_label = memnew(Label);
  2785. fps_label->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, -90 * EDSCALE);
  2786. fps_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 10 * EDSCALE);
  2787. fps_label->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -10 * EDSCALE);
  2788. fps_label->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  2789. fps_label->set_tooltip(TTR("Note: The FPS value displayed is the editor's framerate.\nIt cannot be used as a reliable indication of in-game performance."));
  2790. fps_label->set_mouse_filter(MOUSE_FILTER_PASS); // Otherwise tooltip doesn't show.
  2791. surface->add_child(fps_label);
  2792. fps_label->hide();
  2793. cinema_label = memnew(Label);
  2794. cinema_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 10 * EDSCALE);
  2795. cinema_label->set_h_grow_direction(GROW_DIRECTION_END);
  2796. cinema_label->set_align(Label::ALIGN_CENTER);
  2797. surface->add_child(cinema_label);
  2798. cinema_label->set_text(TTR("Cinematic Preview"));
  2799. cinema_label->hide();
  2800. previewing_cinema = false;
  2801. locked_label = memnew(Label);
  2802. locked_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_END, -20 * EDSCALE);
  2803. locked_label->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, -10 * EDSCALE);
  2804. locked_label->set_h_grow_direction(GROW_DIRECTION_END);
  2805. locked_label->set_v_grow_direction(GROW_DIRECTION_BEGIN);
  2806. locked_label->set_align(Label::ALIGN_CENTER);
  2807. surface->add_child(locked_label);
  2808. locked_label->set_text(TTR("View Rotation Locked"));
  2809. locked_label->hide();
  2810. accept = NULL;
  2811. freelook_active = false;
  2812. freelook_speed = EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_base_speed");
  2813. selection_menu = memnew(PopupMenu);
  2814. add_child(selection_menu);
  2815. selection_menu->set_custom_minimum_size(Size2(100, 0) * EDSCALE);
  2816. selection_menu->connect("id_pressed", this, "_selection_result_pressed");
  2817. selection_menu->connect("popup_hide", this, "_selection_menu_hide");
  2818. if (p_index == 0) {
  2819. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER), true);
  2820. viewport->set_as_audio_listener(true);
  2821. }
  2822. name = "";
  2823. _update_name();
  2824. EditorSettings::get_singleton()->connect("settings_changed", this, "update_transform_gizmo_view");
  2825. }
  2826. //////////////////////////////////////////////////////////////
  2827. void SpatialEditorViewportContainer::_gui_input(const Ref<InputEvent> &p_event) {
  2828. Ref<InputEventMouseButton> mb = p_event;
  2829. if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT) {
  2830. if (mb->is_pressed()) {
  2831. Vector2 size = get_size();
  2832. int h_sep = get_constant("separation", "HSplitContainer");
  2833. int v_sep = get_constant("separation", "VSplitContainer");
  2834. int mid_w = size.width * ratio_h;
  2835. int mid_h = size.height * ratio_v;
  2836. dragging_h = mb->get_position().x > (mid_w - h_sep / 2) && mb->get_position().x < (mid_w + h_sep / 2);
  2837. dragging_v = mb->get_position().y > (mid_h - v_sep / 2) && mb->get_position().y < (mid_h + v_sep / 2);
  2838. drag_begin_pos = mb->get_position();
  2839. drag_begin_ratio.x = ratio_h;
  2840. drag_begin_ratio.y = ratio_v;
  2841. switch (view) {
  2842. case VIEW_USE_1_VIEWPORT: {
  2843. dragging_h = false;
  2844. dragging_v = false;
  2845. } break;
  2846. case VIEW_USE_2_VIEWPORTS: {
  2847. dragging_h = false;
  2848. } break;
  2849. case VIEW_USE_2_VIEWPORTS_ALT: {
  2850. dragging_v = false;
  2851. } break;
  2852. case VIEW_USE_3_VIEWPORTS:
  2853. case VIEW_USE_3_VIEWPORTS_ALT:
  2854. case VIEW_USE_4_VIEWPORTS: {
  2855. // Do nothing.
  2856. } break;
  2857. }
  2858. } else {
  2859. dragging_h = false;
  2860. dragging_v = false;
  2861. }
  2862. }
  2863. Ref<InputEventMouseMotion> mm = p_event;
  2864. if (mm.is_valid()) {
  2865. if (view == VIEW_USE_3_VIEWPORTS || view == VIEW_USE_3_VIEWPORTS_ALT || view == VIEW_USE_4_VIEWPORTS) {
  2866. Vector2 size = get_size();
  2867. int h_sep = get_constant("separation", "HSplitContainer");
  2868. int v_sep = get_constant("separation", "VSplitContainer");
  2869. int mid_w = size.width * ratio_h;
  2870. int mid_h = size.height * ratio_v;
  2871. bool was_hovering_h = hovering_h;
  2872. bool was_hovering_v = hovering_v;
  2873. hovering_h = mm->get_position().x > (mid_w - h_sep / 2) && mm->get_position().x < (mid_w + h_sep / 2);
  2874. hovering_v = mm->get_position().y > (mid_h - v_sep / 2) && mm->get_position().y < (mid_h + v_sep / 2);
  2875. if (was_hovering_h != hovering_h || was_hovering_v != hovering_v) {
  2876. update();
  2877. }
  2878. }
  2879. if (dragging_h) {
  2880. float new_ratio = drag_begin_ratio.x + (mm->get_position().x - drag_begin_pos.x) / get_size().width;
  2881. new_ratio = CLAMP(new_ratio, 40 / get_size().width, (get_size().width - 40) / get_size().width);
  2882. ratio_h = new_ratio;
  2883. queue_sort();
  2884. update();
  2885. }
  2886. if (dragging_v) {
  2887. float new_ratio = drag_begin_ratio.y + (mm->get_position().y - drag_begin_pos.y) / get_size().height;
  2888. new_ratio = CLAMP(new_ratio, 40 / get_size().height, (get_size().height - 40) / get_size().height);
  2889. ratio_v = new_ratio;
  2890. queue_sort();
  2891. update();
  2892. }
  2893. }
  2894. }
  2895. void SpatialEditorViewportContainer::_notification(int p_what) {
  2896. if (p_what == NOTIFICATION_MOUSE_ENTER || p_what == NOTIFICATION_MOUSE_EXIT) {
  2897. mouseover = (p_what == NOTIFICATION_MOUSE_ENTER);
  2898. update();
  2899. }
  2900. if (p_what == NOTIFICATION_DRAW && mouseover) {
  2901. Ref<Texture> h_grabber = get_icon("grabber", "HSplitContainer");
  2902. Ref<Texture> v_grabber = get_icon("grabber", "VSplitContainer");
  2903. Ref<Texture> hdiag_grabber = get_icon("GuiViewportHdiagsplitter", "EditorIcons");
  2904. Ref<Texture> vdiag_grabber = get_icon("GuiViewportVdiagsplitter", "EditorIcons");
  2905. Ref<Texture> vh_grabber = get_icon("GuiViewportVhsplitter", "EditorIcons");
  2906. Vector2 size = get_size();
  2907. int h_sep = get_constant("separation", "HSplitContainer");
  2908. int v_sep = get_constant("separation", "VSplitContainer");
  2909. int mid_w = size.width * ratio_h;
  2910. int mid_h = size.height * ratio_v;
  2911. int size_left = mid_w - h_sep / 2;
  2912. int size_bottom = size.height - mid_h - v_sep / 2;
  2913. switch (view) {
  2914. case VIEW_USE_1_VIEWPORT: {
  2915. // Nothing to show.
  2916. } break;
  2917. case VIEW_USE_2_VIEWPORTS: {
  2918. draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  2919. set_default_cursor_shape(CURSOR_VSPLIT);
  2920. } break;
  2921. case VIEW_USE_2_VIEWPORTS_ALT: {
  2922. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
  2923. set_default_cursor_shape(CURSOR_HSPLIT);
  2924. } break;
  2925. case VIEW_USE_3_VIEWPORTS: {
  2926. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  2927. draw_texture(hdiag_grabber, Vector2(mid_w - hdiag_grabber->get_width() / 2, mid_h - v_grabber->get_height() / 4));
  2928. set_default_cursor_shape(CURSOR_DRAG);
  2929. } else if ((hovering_v && !dragging_h) || dragging_v) {
  2930. draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  2931. set_default_cursor_shape(CURSOR_VSPLIT);
  2932. } else if (hovering_h || dragging_h) {
  2933. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, mid_h + v_grabber->get_height() / 2 + (size_bottom - h_grabber->get_height()) / 2));
  2934. set_default_cursor_shape(CURSOR_HSPLIT);
  2935. }
  2936. } break;
  2937. case VIEW_USE_3_VIEWPORTS_ALT: {
  2938. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  2939. draw_texture(vdiag_grabber, Vector2(mid_w - vdiag_grabber->get_width() + v_grabber->get_height() / 4, mid_h - vdiag_grabber->get_height() / 2));
  2940. set_default_cursor_shape(CURSOR_DRAG);
  2941. } else if ((hovering_v && !dragging_h) || dragging_v) {
  2942. draw_texture(v_grabber, Vector2((size_left - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  2943. set_default_cursor_shape(CURSOR_VSPLIT);
  2944. } else if (hovering_h || dragging_h) {
  2945. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
  2946. set_default_cursor_shape(CURSOR_HSPLIT);
  2947. }
  2948. } break;
  2949. case VIEW_USE_4_VIEWPORTS: {
  2950. Vector2 half(mid_w, mid_h);
  2951. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  2952. draw_texture(vh_grabber, half - vh_grabber->get_size() / 2.0);
  2953. set_default_cursor_shape(CURSOR_DRAG);
  2954. } else if ((hovering_v && !dragging_h) || dragging_v) {
  2955. draw_texture(v_grabber, half - v_grabber->get_size() / 2.0);
  2956. set_default_cursor_shape(CURSOR_VSPLIT);
  2957. } else if (hovering_h || dragging_h) {
  2958. draw_texture(h_grabber, half - h_grabber->get_size() / 2.0);
  2959. set_default_cursor_shape(CURSOR_HSPLIT);
  2960. }
  2961. } break;
  2962. }
  2963. }
  2964. if (p_what == NOTIFICATION_SORT_CHILDREN) {
  2965. SpatialEditorViewport *viewports[4];
  2966. int vc = 0;
  2967. for (int i = 0; i < get_child_count(); i++) {
  2968. viewports[vc] = Object::cast_to<SpatialEditorViewport>(get_child(i));
  2969. if (viewports[vc]) {
  2970. vc++;
  2971. }
  2972. }
  2973. ERR_FAIL_COND(vc != 4);
  2974. Size2 size = get_size();
  2975. if (size.x < 10 || size.y < 10) {
  2976. for (int i = 0; i < 4; i++) {
  2977. viewports[i]->hide();
  2978. }
  2979. return;
  2980. }
  2981. int h_sep = get_constant("separation", "HSplitContainer");
  2982. int v_sep = get_constant("separation", "VSplitContainer");
  2983. int mid_w = size.width * ratio_h;
  2984. int mid_h = size.height * ratio_v;
  2985. int size_left = mid_w - h_sep / 2;
  2986. int size_right = size.width - mid_w - h_sep / 2;
  2987. int size_top = mid_h - v_sep / 2;
  2988. int size_bottom = size.height - mid_h - v_sep / 2;
  2989. switch (view) {
  2990. case VIEW_USE_1_VIEWPORT: {
  2991. viewports[0]->show();
  2992. for (int i = 1; i < 4; i++) {
  2993. viewports[i]->hide();
  2994. }
  2995. fit_child_in_rect(viewports[0], Rect2(Vector2(), size));
  2996. } break;
  2997. case VIEW_USE_2_VIEWPORTS: {
  2998. for (int i = 0; i < 4; i++) {
  2999. if (i == 1 || i == 3)
  3000. viewports[i]->hide();
  3001. else
  3002. viewports[i]->show();
  3003. }
  3004. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
  3005. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size.width, size_bottom)));
  3006. } break;
  3007. case VIEW_USE_2_VIEWPORTS_ALT: {
  3008. for (int i = 0; i < 4; i++) {
  3009. if (i == 1 || i == 3)
  3010. viewports[i]->hide();
  3011. else
  3012. viewports[i]->show();
  3013. }
  3014. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size.height)));
  3015. fit_child_in_rect(viewports[2], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
  3016. } break;
  3017. case VIEW_USE_3_VIEWPORTS: {
  3018. for (int i = 0; i < 4; i++) {
  3019. if (i == 1)
  3020. viewports[i]->hide();
  3021. else
  3022. viewports[i]->show();
  3023. }
  3024. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
  3025. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  3026. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
  3027. } break;
  3028. case VIEW_USE_3_VIEWPORTS_ALT: {
  3029. for (int i = 0; i < 4; i++) {
  3030. if (i == 1)
  3031. viewports[i]->hide();
  3032. else
  3033. viewports[i]->show();
  3034. }
  3035. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
  3036. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  3037. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
  3038. } break;
  3039. case VIEW_USE_4_VIEWPORTS: {
  3040. for (int i = 0; i < 4; i++) {
  3041. viewports[i]->show();
  3042. }
  3043. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
  3044. fit_child_in_rect(viewports[1], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size_top)));
  3045. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  3046. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
  3047. } break;
  3048. }
  3049. }
  3050. }
  3051. void SpatialEditorViewportContainer::set_view(View p_view) {
  3052. view = p_view;
  3053. queue_sort();
  3054. }
  3055. SpatialEditorViewportContainer::View SpatialEditorViewportContainer::get_view() {
  3056. return view;
  3057. }
  3058. void SpatialEditorViewportContainer::_bind_methods() {
  3059. ClassDB::bind_method("_gui_input", &SpatialEditorViewportContainer::_gui_input);
  3060. }
  3061. SpatialEditorViewportContainer::SpatialEditorViewportContainer() {
  3062. set_clip_contents(true);
  3063. view = VIEW_USE_1_VIEWPORT;
  3064. mouseover = false;
  3065. ratio_h = 0.5;
  3066. ratio_v = 0.5;
  3067. hovering_v = false;
  3068. hovering_h = false;
  3069. dragging_v = false;
  3070. dragging_h = false;
  3071. }
  3072. ///////////////////////////////////////////////////////////////////
  3073. SpatialEditor *SpatialEditor::singleton = NULL;
  3074. SpatialEditorSelectedItem::~SpatialEditorSelectedItem() {
  3075. if (sbox_instance.is_valid())
  3076. VisualServer::get_singleton()->free(sbox_instance);
  3077. }
  3078. void SpatialEditor::select_gizmo_highlight_axis(int p_axis) {
  3079. for (int i = 0; i < 3; i++) {
  3080. move_gizmo[i]->surface_set_material(0, i == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  3081. move_plane_gizmo[i]->surface_set_material(0, (i + 6) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
  3082. rotate_gizmo[i]->surface_set_material(0, (i + 3) == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  3083. scale_gizmo[i]->surface_set_material(0, (i + 9) == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  3084. scale_plane_gizmo[i]->surface_set_material(0, (i + 12) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
  3085. }
  3086. }
  3087. void SpatialEditor::update_transform_gizmo() {
  3088. List<Node *> &selection = editor_selection->get_selected_node_list();
  3089. AABB center;
  3090. bool first = true;
  3091. Basis gizmo_basis;
  3092. bool local_gizmo_coords = are_local_coords_enabled();
  3093. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3094. Spatial *sp = Object::cast_to<Spatial>(E->get());
  3095. if (!sp)
  3096. continue;
  3097. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  3098. if (!se)
  3099. continue;
  3100. Transform xf = se->sp->get_global_gizmo_transform();
  3101. if (first) {
  3102. center.position = xf.origin;
  3103. first = false;
  3104. if (local_gizmo_coords) {
  3105. gizmo_basis = xf.basis;
  3106. gizmo_basis.orthonormalize();
  3107. }
  3108. } else {
  3109. center.expand_to(xf.origin);
  3110. gizmo_basis = Basis();
  3111. }
  3112. }
  3113. Vector3 pcenter = center.position + center.size * 0.5;
  3114. gizmo.visible = !first;
  3115. gizmo.transform.origin = pcenter;
  3116. gizmo.transform.basis = gizmo_basis;
  3117. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  3118. viewports[i]->update_transform_gizmo_view();
  3119. }
  3120. }
  3121. void _update_all_gizmos(Node *p_node) {
  3122. for (int i = p_node->get_child_count() - 1; 0 <= i; --i) {
  3123. Spatial *spatial_node = Object::cast_to<Spatial>(p_node->get_child(i));
  3124. if (spatial_node) {
  3125. spatial_node->update_gizmo();
  3126. }
  3127. _update_all_gizmos(p_node->get_child(i));
  3128. }
  3129. }
  3130. void SpatialEditor::update_all_gizmos(Node *p_node) {
  3131. if (!p_node) p_node = SceneTree::get_singleton()->get_root();
  3132. _update_all_gizmos(p_node);
  3133. }
  3134. Object *SpatialEditor::_get_editor_data(Object *p_what) {
  3135. Spatial *sp = Object::cast_to<Spatial>(p_what);
  3136. if (!sp)
  3137. return NULL;
  3138. SpatialEditorSelectedItem *si = memnew(SpatialEditorSelectedItem);
  3139. si->sp = sp;
  3140. si->sbox_instance = VisualServer::get_singleton()->instance_create2(selection_box->get_rid(), sp->get_world()->get_scenario());
  3141. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(si->sbox_instance, VS::SHADOW_CASTING_SETTING_OFF);
  3142. return si;
  3143. }
  3144. void SpatialEditor::_generate_selection_box() {
  3145. AABB aabb(Vector3(), Vector3(1, 1, 1));
  3146. aabb.grow_by(aabb.get_longest_axis_size() / 20.0);
  3147. Ref<SurfaceTool> st = memnew(SurfaceTool);
  3148. st->begin(Mesh::PRIMITIVE_LINES);
  3149. for (int i = 0; i < 12; i++) {
  3150. Vector3 a, b;
  3151. aabb.get_edge(i, a, b);
  3152. st->add_color(Color(1.0, 1.0, 0.8, 0.8));
  3153. st->add_vertex(a);
  3154. st->add_color(Color(1.0, 1.0, 0.8, 0.4));
  3155. st->add_vertex(a.linear_interpolate(b, 0.2));
  3156. st->add_color(Color(1.0, 1.0, 0.8, 0.4));
  3157. st->add_vertex(a.linear_interpolate(b, 0.8));
  3158. st->add_color(Color(1.0, 1.0, 0.8, 0.8));
  3159. st->add_vertex(b);
  3160. }
  3161. Ref<SpatialMaterial> mat = memnew(SpatialMaterial);
  3162. mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  3163. mat->set_albedo(Color(1, 1, 1));
  3164. mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  3165. mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  3166. mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  3167. st->set_material(mat);
  3168. selection_box = st->commit();
  3169. }
  3170. Dictionary SpatialEditor::get_state() const {
  3171. Dictionary d;
  3172. d["snap_enabled"] = snap_enabled;
  3173. d["translate_snap"] = get_translate_snap();
  3174. d["rotate_snap"] = get_rotate_snap();
  3175. d["scale_snap"] = get_scale_snap();
  3176. d["local_coords"] = tool_option_button[TOOL_OPT_LOCAL_COORDS]->is_pressed();
  3177. int vc = 0;
  3178. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT)))
  3179. vc = 1;
  3180. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS)))
  3181. vc = 2;
  3182. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS)))
  3183. vc = 3;
  3184. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS)))
  3185. vc = 4;
  3186. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT)))
  3187. vc = 5;
  3188. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT)))
  3189. vc = 6;
  3190. d["viewport_mode"] = vc;
  3191. Array vpdata;
  3192. for (int i = 0; i < 4; i++) {
  3193. vpdata.push_back(viewports[i]->get_state());
  3194. }
  3195. d["viewports"] = vpdata;
  3196. d["show_grid"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID));
  3197. d["show_origin"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN));
  3198. d["fov"] = get_fov();
  3199. d["znear"] = get_znear();
  3200. d["zfar"] = get_zfar();
  3201. Dictionary gizmos_status;
  3202. for (int i = 0; i < gizmo_plugins_by_name.size(); i++) {
  3203. if (!gizmo_plugins_by_name[i]->can_be_hidden()) continue;
  3204. int state = gizmos_menu->get_item_state(gizmos_menu->get_item_index(i));
  3205. String name = gizmo_plugins_by_name[i]->get_name();
  3206. gizmos_status[name] = state;
  3207. }
  3208. d["gizmos_status"] = gizmos_status;
  3209. return d;
  3210. }
  3211. void SpatialEditor::set_state(const Dictionary &p_state) {
  3212. Dictionary d = p_state;
  3213. if (d.has("snap_enabled")) {
  3214. snap_enabled = d["snap_enabled"];
  3215. tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(d["snap_enabled"]);
  3216. }
  3217. if (d.has("translate_snap"))
  3218. snap_translate->set_text(d["translate_snap"]);
  3219. if (d.has("rotate_snap"))
  3220. snap_rotate->set_text(d["rotate_snap"]);
  3221. if (d.has("scale_snap"))
  3222. snap_scale->set_text(d["scale_snap"]);
  3223. if (d.has("local_coords")) {
  3224. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(d["local_coords"]);
  3225. update_transform_gizmo();
  3226. }
  3227. if (d.has("viewport_mode")) {
  3228. int vc = d["viewport_mode"];
  3229. if (vc == 1)
  3230. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  3231. else if (vc == 2)
  3232. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
  3233. else if (vc == 3)
  3234. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
  3235. else if (vc == 4)
  3236. _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
  3237. else if (vc == 5)
  3238. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
  3239. else if (vc == 6)
  3240. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
  3241. }
  3242. if (d.has("viewports")) {
  3243. Array vp = d["viewports"];
  3244. uint32_t vp_size = static_cast<uint32_t>(vp.size());
  3245. if (vp_size > VIEWPORTS_COUNT) {
  3246. WARN_PRINT("Ignoring superfluous viewport settings from spatial editor state.");
  3247. vp_size = VIEWPORTS_COUNT;
  3248. }
  3249. for (uint32_t i = 0; i < vp_size; i++) {
  3250. viewports[i]->set_state(vp[i]);
  3251. }
  3252. }
  3253. if (d.has("zfar"))
  3254. settings_zfar->set_value(float(d["zfar"]));
  3255. if (d.has("znear"))
  3256. settings_znear->set_value(float(d["znear"]));
  3257. if (d.has("fov"))
  3258. settings_fov->set_value(float(d["fov"]));
  3259. if (d.has("show_grid")) {
  3260. bool use = d["show_grid"];
  3261. if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID))) {
  3262. _menu_item_pressed(MENU_VIEW_GRID);
  3263. }
  3264. }
  3265. if (d.has("show_origin")) {
  3266. bool use = d["show_origin"];
  3267. if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN))) {
  3268. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), use);
  3269. VisualServer::get_singleton()->instance_set_visible(origin_instance, use);
  3270. }
  3271. }
  3272. if (d.has("gizmos_status")) {
  3273. Dictionary gizmos_status = d["gizmos_status"];
  3274. List<Variant> keys;
  3275. gizmos_status.get_key_list(&keys);
  3276. for (int j = 0; j < gizmo_plugins_by_name.size(); ++j) {
  3277. if (!gizmo_plugins_by_name[j]->can_be_hidden()) continue;
  3278. int state = EditorSpatialGizmoPlugin::VISIBLE;
  3279. for (int i = 0; i < keys.size(); i++) {
  3280. if (gizmo_plugins_by_name.write[j]->get_name() == keys[i]) {
  3281. state = gizmos_status[keys[i]];
  3282. break;
  3283. }
  3284. }
  3285. gizmo_plugins_by_name.write[j]->set_state(state);
  3286. }
  3287. _update_gizmos_menu();
  3288. }
  3289. }
  3290. void SpatialEditor::edit(Spatial *p_spatial) {
  3291. if (p_spatial != selected) {
  3292. if (selected) {
  3293. Ref<EditorSpatialGizmo> seg = selected->get_gizmo();
  3294. if (seg.is_valid()) {
  3295. seg->set_selected(false);
  3296. selected->update_gizmo();
  3297. }
  3298. }
  3299. selected = p_spatial;
  3300. over_gizmo_handle = -1;
  3301. if (selected) {
  3302. Ref<EditorSpatialGizmo> seg = selected->get_gizmo();
  3303. if (seg.is_valid()) {
  3304. seg->set_selected(true);
  3305. selected->update_gizmo();
  3306. }
  3307. }
  3308. }
  3309. }
  3310. void SpatialEditor::_xform_dialog_action() {
  3311. Transform t;
  3312. //translation
  3313. Vector3 scale;
  3314. Vector3 rotate;
  3315. Vector3 translate;
  3316. for (int i = 0; i < 3; i++) {
  3317. translate[i] = xform_translate[i]->get_text().to_double();
  3318. rotate[i] = Math::deg2rad(xform_rotate[i]->get_text().to_double());
  3319. scale[i] = xform_scale[i]->get_text().to_double();
  3320. }
  3321. t.basis.scale(scale);
  3322. t.basis.rotate(rotate);
  3323. t.origin = translate;
  3324. undo_redo->create_action(TTR("XForm Dialog"));
  3325. List<Node *> &selection = editor_selection->get_selected_node_list();
  3326. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3327. Spatial *sp = Object::cast_to<Spatial>(E->get());
  3328. if (!sp)
  3329. continue;
  3330. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  3331. if (!se)
  3332. continue;
  3333. bool post = xform_type->get_selected() > 0;
  3334. Transform tr = sp->get_global_gizmo_transform();
  3335. if (post)
  3336. tr = tr * t;
  3337. else {
  3338. tr.basis = t.basis * tr.basis;
  3339. tr.origin += t.origin;
  3340. }
  3341. undo_redo->add_do_method(sp, "set_global_transform", tr);
  3342. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
  3343. }
  3344. undo_redo->commit_action();
  3345. }
  3346. void SpatialEditor::_menu_item_toggled(bool pressed, int p_option) {
  3347. switch (p_option) {
  3348. case MENU_TOOL_LOCAL_COORDS: {
  3349. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(pressed);
  3350. update_transform_gizmo();
  3351. } break;
  3352. case MENU_TOOL_USE_SNAP: {
  3353. tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(pressed);
  3354. snap_enabled = pressed;
  3355. } break;
  3356. }
  3357. }
  3358. void SpatialEditor::_menu_gizmo_toggled(int p_option) {
  3359. const int idx = gizmos_menu->get_item_index(p_option);
  3360. gizmos_menu->toggle_item_multistate(idx);
  3361. // Change icon
  3362. const int state = gizmos_menu->get_item_state(idx);
  3363. switch (state) {
  3364. case EditorSpatialGizmoPlugin::VISIBLE:
  3365. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_icon("visibility_visible"));
  3366. break;
  3367. case EditorSpatialGizmoPlugin::ON_TOP:
  3368. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_icon("visibility_xray"));
  3369. break;
  3370. case EditorSpatialGizmoPlugin::HIDDEN:
  3371. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_icon("visibility_hidden"));
  3372. break;
  3373. }
  3374. gizmo_plugins_by_name.write[p_option]->set_state(state);
  3375. update_all_gizmos();
  3376. }
  3377. void SpatialEditor::_menu_item_pressed(int p_option) {
  3378. switch (p_option) {
  3379. case MENU_TOOL_SELECT:
  3380. case MENU_TOOL_MOVE:
  3381. case MENU_TOOL_ROTATE:
  3382. case MENU_TOOL_SCALE:
  3383. case MENU_TOOL_LIST_SELECT: {
  3384. for (int i = 0; i < TOOL_MAX; i++)
  3385. tool_button[i]->set_pressed(i == p_option);
  3386. tool_mode = (ToolMode)p_option;
  3387. update_transform_gizmo();
  3388. } break;
  3389. case MENU_TRANSFORM_CONFIGURE_SNAP: {
  3390. snap_dialog->popup_centered(Size2(200, 180));
  3391. } break;
  3392. case MENU_TRANSFORM_DIALOG: {
  3393. for (int i = 0; i < 3; i++) {
  3394. xform_translate[i]->set_text("0");
  3395. xform_rotate[i]->set_text("0");
  3396. xform_scale[i]->set_text("1");
  3397. }
  3398. xform_dialog->popup_centered(Size2(320, 240) * EDSCALE);
  3399. } break;
  3400. case MENU_VIEW_USE_1_VIEWPORT: {
  3401. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_1_VIEWPORT);
  3402. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), true);
  3403. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  3404. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  3405. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  3406. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  3407. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  3408. } break;
  3409. case MENU_VIEW_USE_2_VIEWPORTS: {
  3410. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_2_VIEWPORTS);
  3411. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  3412. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), true);
  3413. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  3414. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  3415. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  3416. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  3417. } break;
  3418. case MENU_VIEW_USE_2_VIEWPORTS_ALT: {
  3419. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_2_VIEWPORTS_ALT);
  3420. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  3421. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  3422. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  3423. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  3424. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), true);
  3425. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  3426. } break;
  3427. case MENU_VIEW_USE_3_VIEWPORTS: {
  3428. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_3_VIEWPORTS);
  3429. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  3430. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  3431. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), true);
  3432. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  3433. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  3434. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  3435. } break;
  3436. case MENU_VIEW_USE_3_VIEWPORTS_ALT: {
  3437. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_3_VIEWPORTS_ALT);
  3438. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  3439. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  3440. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  3441. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  3442. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  3443. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), true);
  3444. } break;
  3445. case MENU_VIEW_USE_4_VIEWPORTS: {
  3446. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_4_VIEWPORTS);
  3447. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  3448. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  3449. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  3450. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), true);
  3451. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  3452. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  3453. } break;
  3454. case MENU_VIEW_ORIGIN: {
  3455. bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
  3456. origin_enabled = !is_checked;
  3457. VisualServer::get_singleton()->instance_set_visible(origin_instance, origin_enabled);
  3458. // Update the grid since its appearance depends on whether the origin is enabled
  3459. _finish_grid();
  3460. _init_grid();
  3461. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), origin_enabled);
  3462. } break;
  3463. case MENU_VIEW_GRID: {
  3464. bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
  3465. grid_enabled = !is_checked;
  3466. for (int i = 0; i < 3; ++i) {
  3467. if (grid_enable[i]) {
  3468. VisualServer::get_singleton()->instance_set_visible(grid_instance[i], grid_enabled);
  3469. grid_visible[i] = grid_enabled;
  3470. }
  3471. }
  3472. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), grid_enabled);
  3473. } break;
  3474. case MENU_VIEW_CAMERA_SETTINGS: {
  3475. settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size() + Size2(50, 50));
  3476. } break;
  3477. case MENU_SNAP_TO_FLOOR: {
  3478. snap_selected_nodes_to_floor();
  3479. } break;
  3480. case MENU_LOCK_SELECTED: {
  3481. undo_redo->create_action(TTR("Lock Selected"));
  3482. List<Node *> &selection = editor_selection->get_selected_node_list();
  3483. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3484. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  3485. if (!spatial || !spatial->is_visible_in_tree())
  3486. continue;
  3487. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root())
  3488. continue;
  3489. undo_redo->add_do_method(spatial, "set_meta", "_edit_lock_", true);
  3490. undo_redo->add_undo_method(spatial, "remove_meta", "_edit_lock_");
  3491. undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
  3492. undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
  3493. }
  3494. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  3495. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  3496. undo_redo->commit_action();
  3497. } break;
  3498. case MENU_UNLOCK_SELECTED: {
  3499. undo_redo->create_action(TTR("Unlock Selected"));
  3500. List<Node *> &selection = editor_selection->get_selected_node_list();
  3501. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3502. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  3503. if (!spatial || !spatial->is_visible_in_tree())
  3504. continue;
  3505. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root())
  3506. continue;
  3507. undo_redo->add_do_method(spatial, "remove_meta", "_edit_lock_");
  3508. undo_redo->add_undo_method(spatial, "set_meta", "_edit_lock_", true);
  3509. undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
  3510. undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
  3511. }
  3512. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  3513. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  3514. undo_redo->commit_action();
  3515. } break;
  3516. case MENU_GROUP_SELECTED: {
  3517. undo_redo->create_action(TTR("Group Selected"));
  3518. List<Node *> &selection = editor_selection->get_selected_node_list();
  3519. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3520. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  3521. if (!spatial || !spatial->is_visible_in_tree())
  3522. continue;
  3523. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root())
  3524. continue;
  3525. undo_redo->add_do_method(spatial, "set_meta", "_edit_group_", true);
  3526. undo_redo->add_undo_method(spatial, "remove_meta", "_edit_group_");
  3527. undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
  3528. undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
  3529. }
  3530. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  3531. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  3532. undo_redo->commit_action();
  3533. } break;
  3534. case MENU_UNGROUP_SELECTED: {
  3535. undo_redo->create_action(TTR("Ungroup Selected"));
  3536. List<Node *> &selection = editor_selection->get_selected_node_list();
  3537. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3538. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  3539. if (!spatial || !spatial->is_visible_in_tree())
  3540. continue;
  3541. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root())
  3542. continue;
  3543. undo_redo->add_do_method(spatial, "remove_meta", "_edit_group_");
  3544. undo_redo->add_undo_method(spatial, "set_meta", "_edit_group_", true);
  3545. undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
  3546. undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
  3547. }
  3548. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  3549. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  3550. undo_redo->commit_action();
  3551. } break;
  3552. }
  3553. }
  3554. void SpatialEditor::_init_indicators() {
  3555. {
  3556. origin_enabled = true;
  3557. grid_enabled = true;
  3558. indicator_mat.instance();
  3559. indicator_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  3560. indicator_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  3561. indicator_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  3562. Vector<Color> origin_colors;
  3563. Vector<Vector3> origin_points;
  3564. for (int i = 0; i < 3; i++) {
  3565. Vector3 axis;
  3566. axis[i] = 1;
  3567. Color origin_color;
  3568. switch (i) {
  3569. case 0:
  3570. origin_color = get_color("axis_x_color", "Editor");
  3571. break;
  3572. case 1:
  3573. origin_color = get_color("axis_y_color", "Editor");
  3574. break;
  3575. case 2:
  3576. origin_color = get_color("axis_z_color", "Editor");
  3577. break;
  3578. default:
  3579. origin_color = Color();
  3580. break;
  3581. }
  3582. grid_enable[i] = false;
  3583. grid_visible[i] = false;
  3584. origin_colors.push_back(origin_color);
  3585. origin_colors.push_back(origin_color);
  3586. origin_points.push_back(axis * 4096);
  3587. origin_points.push_back(axis * -4096);
  3588. }
  3589. grid_enable[1] = true;
  3590. grid_visible[1] = true;
  3591. _init_grid();
  3592. origin = VisualServer::get_singleton()->mesh_create();
  3593. Array d;
  3594. d.resize(VS::ARRAY_MAX);
  3595. d[VisualServer::ARRAY_VERTEX] = origin_points;
  3596. d[VisualServer::ARRAY_COLOR] = origin_colors;
  3597. VisualServer::get_singleton()->mesh_add_surface_from_arrays(origin, VisualServer::PRIMITIVE_LINES, d);
  3598. VisualServer::get_singleton()->mesh_surface_set_material(origin, 0, indicator_mat->get_rid());
  3599. origin_instance = VisualServer::get_singleton()->instance_create2(origin, get_tree()->get_root()->get_world()->get_scenario());
  3600. VS::get_singleton()->instance_set_layer_mask(origin_instance, 1 << SpatialEditorViewport::GIZMO_GRID_LAYER);
  3601. VisualServer::get_singleton()->instance_geometry_set_cast_shadows_setting(origin_instance, VS::SHADOW_CASTING_SETTING_OFF);
  3602. }
  3603. {
  3604. //move gizmo
  3605. for (int i = 0; i < 3; i++) {
  3606. Color col;
  3607. switch (i) {
  3608. case 0:
  3609. col = get_color("axis_x_color", "Editor");
  3610. break;
  3611. case 1:
  3612. col = get_color("axis_y_color", "Editor");
  3613. break;
  3614. case 2:
  3615. col = get_color("axis_z_color", "Editor");
  3616. break;
  3617. default:
  3618. col = Color();
  3619. break;
  3620. }
  3621. col.a = EditorSettings::get_singleton()->get("editors/3d/manipulator_gizmo_opacity");
  3622. move_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  3623. move_plane_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  3624. rotate_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  3625. scale_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  3626. scale_plane_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  3627. Ref<SpatialMaterial> mat = memnew(SpatialMaterial);
  3628. mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  3629. mat->set_on_top_of_alpha();
  3630. mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  3631. mat->set_albedo(col);
  3632. gizmo_color[i] = mat;
  3633. Ref<SpatialMaterial> mat_hl = mat->duplicate();
  3634. mat_hl->set_albedo(Color(col.r, col.g, col.b, 1.0));
  3635. gizmo_color_hl[i] = mat_hl;
  3636. Vector3 ivec;
  3637. ivec[i] = 1;
  3638. Vector3 nivec;
  3639. nivec[(i + 1) % 3] = 1;
  3640. nivec[(i + 2) % 3] = 1;
  3641. Vector3 ivec2;
  3642. ivec2[(i + 1) % 3] = 1;
  3643. Vector3 ivec3;
  3644. ivec3[(i + 2) % 3] = 1;
  3645. //translate
  3646. {
  3647. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  3648. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  3649. // Arrow profile
  3650. const int arrow_points = 5;
  3651. Vector3 arrow[5] = {
  3652. nivec * 0.0 + ivec * 0.0,
  3653. nivec * 0.01 + ivec * 0.0,
  3654. nivec * 0.01 + ivec * GIZMO_ARROW_OFFSET,
  3655. nivec * 0.065 + ivec * GIZMO_ARROW_OFFSET,
  3656. nivec * 0.0 + ivec * (GIZMO_ARROW_OFFSET + GIZMO_ARROW_SIZE),
  3657. };
  3658. int arrow_sides = 16;
  3659. for (int k = 0; k < arrow_sides; k++) {
  3660. Basis ma(ivec, Math_PI * 2 * float(k) / arrow_sides);
  3661. Basis mb(ivec, Math_PI * 2 * float(k + 1) / arrow_sides);
  3662. for (int j = 0; j < arrow_points - 1; j++) {
  3663. Vector3 points[4] = {
  3664. ma.xform(arrow[j]),
  3665. mb.xform(arrow[j]),
  3666. mb.xform(arrow[j + 1]),
  3667. ma.xform(arrow[j + 1]),
  3668. };
  3669. surftool->add_vertex(points[0]);
  3670. surftool->add_vertex(points[1]);
  3671. surftool->add_vertex(points[2]);
  3672. surftool->add_vertex(points[0]);
  3673. surftool->add_vertex(points[2]);
  3674. surftool->add_vertex(points[3]);
  3675. }
  3676. }
  3677. surftool->set_material(mat);
  3678. surftool->commit(move_gizmo[i]);
  3679. }
  3680. // Plane Translation
  3681. {
  3682. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  3683. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  3684. Vector3 vec = ivec2 - ivec3;
  3685. Vector3 plane[4] = {
  3686. vec * GIZMO_PLANE_DST,
  3687. vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
  3688. vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
  3689. vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
  3690. };
  3691. Basis ma(ivec, Math_PI / 2);
  3692. Vector3 points[4] = {
  3693. ma.xform(plane[0]),
  3694. ma.xform(plane[1]),
  3695. ma.xform(plane[2]),
  3696. ma.xform(plane[3]),
  3697. };
  3698. surftool->add_vertex(points[0]);
  3699. surftool->add_vertex(points[1]);
  3700. surftool->add_vertex(points[2]);
  3701. surftool->add_vertex(points[0]);
  3702. surftool->add_vertex(points[2]);
  3703. surftool->add_vertex(points[3]);
  3704. Ref<SpatialMaterial> plane_mat = memnew(SpatialMaterial);
  3705. plane_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  3706. plane_mat->set_on_top_of_alpha();
  3707. plane_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  3708. plane_mat->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  3709. plane_mat->set_albedo(col);
  3710. plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides
  3711. surftool->set_material(plane_mat);
  3712. surftool->commit(move_plane_gizmo[i]);
  3713. Ref<SpatialMaterial> plane_mat_hl = plane_mat->duplicate();
  3714. plane_mat_hl->set_albedo(Color(col.r, col.g, col.b, 1.0));
  3715. plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
  3716. }
  3717. // Rotate
  3718. {
  3719. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  3720. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  3721. Vector3 circle[5] = {
  3722. ivec * 0.02 + ivec2 * 0.02 + ivec2 * GIZMO_CIRCLE_SIZE,
  3723. ivec * -0.02 + ivec2 * 0.02 + ivec2 * GIZMO_CIRCLE_SIZE,
  3724. ivec * -0.02 + ivec2 * -0.02 + ivec2 * GIZMO_CIRCLE_SIZE,
  3725. ivec * 0.02 + ivec2 * -0.02 + ivec2 * GIZMO_CIRCLE_SIZE,
  3726. ivec * 0.02 + ivec2 * 0.02 + ivec2 * GIZMO_CIRCLE_SIZE,
  3727. };
  3728. for (int k = 0; k < 64; k++) {
  3729. Basis ma(ivec, Math_PI * 2 * float(k) / 64);
  3730. Basis mb(ivec, Math_PI * 2 * float(k + 1) / 64);
  3731. for (int j = 0; j < 4; j++) {
  3732. Vector3 points[4] = {
  3733. ma.xform(circle[j]),
  3734. mb.xform(circle[j]),
  3735. mb.xform(circle[j + 1]),
  3736. ma.xform(circle[j + 1]),
  3737. };
  3738. surftool->add_vertex(points[0]);
  3739. surftool->add_vertex(points[1]);
  3740. surftool->add_vertex(points[2]);
  3741. surftool->add_vertex(points[0]);
  3742. surftool->add_vertex(points[2]);
  3743. surftool->add_vertex(points[3]);
  3744. }
  3745. }
  3746. surftool->set_material(mat);
  3747. surftool->commit(rotate_gizmo[i]);
  3748. }
  3749. // Scale
  3750. {
  3751. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  3752. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  3753. // Cube arrow profile
  3754. const int arrow_points = 6;
  3755. Vector3 arrow[6] = {
  3756. nivec * 0.0 + ivec * 0.0,
  3757. nivec * 0.01 + ivec * 0.0,
  3758. nivec * 0.01 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
  3759. nivec * 0.07 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
  3760. nivec * 0.07 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
  3761. nivec * 0.0 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
  3762. };
  3763. int arrow_sides = 4;
  3764. for (int k = 0; k < 4; k++) {
  3765. Basis ma(ivec, Math_PI * 2 * float(k) / arrow_sides);
  3766. Basis mb(ivec, Math_PI * 2 * float(k + 1) / arrow_sides);
  3767. for (int j = 0; j < arrow_points - 1; j++) {
  3768. Vector3 points[4] = {
  3769. ma.xform(arrow[j]),
  3770. mb.xform(arrow[j]),
  3771. mb.xform(arrow[j + 1]),
  3772. ma.xform(arrow[j + 1]),
  3773. };
  3774. surftool->add_vertex(points[0]);
  3775. surftool->add_vertex(points[1]);
  3776. surftool->add_vertex(points[2]);
  3777. surftool->add_vertex(points[0]);
  3778. surftool->add_vertex(points[2]);
  3779. surftool->add_vertex(points[3]);
  3780. }
  3781. }
  3782. surftool->set_material(mat);
  3783. surftool->commit(scale_gizmo[i]);
  3784. }
  3785. // Plane Scale
  3786. {
  3787. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  3788. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  3789. Vector3 vec = ivec2 - ivec3;
  3790. Vector3 plane[4] = {
  3791. vec * GIZMO_PLANE_DST,
  3792. vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
  3793. vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
  3794. vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
  3795. };
  3796. Basis ma(ivec, Math_PI / 2);
  3797. Vector3 points[4] = {
  3798. ma.xform(plane[0]),
  3799. ma.xform(plane[1]),
  3800. ma.xform(plane[2]),
  3801. ma.xform(plane[3]),
  3802. };
  3803. surftool->add_vertex(points[0]);
  3804. surftool->add_vertex(points[1]);
  3805. surftool->add_vertex(points[2]);
  3806. surftool->add_vertex(points[0]);
  3807. surftool->add_vertex(points[2]);
  3808. surftool->add_vertex(points[3]);
  3809. Ref<SpatialMaterial> plane_mat = memnew(SpatialMaterial);
  3810. plane_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  3811. plane_mat->set_on_top_of_alpha();
  3812. plane_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  3813. plane_mat->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  3814. plane_mat->set_albedo(col);
  3815. plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides
  3816. surftool->set_material(plane_mat);
  3817. surftool->commit(scale_plane_gizmo[i]);
  3818. Ref<SpatialMaterial> plane_mat_hl = plane_mat->duplicate();
  3819. plane_mat_hl->set_albedo(Color(col.r, col.g, col.b, 1.0));
  3820. plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
  3821. }
  3822. }
  3823. }
  3824. _generate_selection_box();
  3825. }
  3826. void SpatialEditor::_update_gizmos_menu() {
  3827. gizmos_menu->clear();
  3828. for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
  3829. if (!gizmo_plugins_by_name[i]->can_be_hidden()) continue;
  3830. String plugin_name = gizmo_plugins_by_name[i]->get_name();
  3831. const int plugin_state = gizmo_plugins_by_name[i]->get_state();
  3832. gizmos_menu->add_multistate_item(TTR(plugin_name), 3, plugin_state, i);
  3833. const int idx = gizmos_menu->get_item_index(i);
  3834. switch (plugin_state) {
  3835. case EditorSpatialGizmoPlugin::VISIBLE:
  3836. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_visible"));
  3837. break;
  3838. case EditorSpatialGizmoPlugin::ON_TOP:
  3839. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_xray"));
  3840. break;
  3841. case EditorSpatialGizmoPlugin::HIDDEN:
  3842. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_hidden"));
  3843. break;
  3844. }
  3845. }
  3846. }
  3847. void SpatialEditor::_update_gizmos_menu_theme() {
  3848. for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
  3849. if (!gizmo_plugins_by_name[i]->can_be_hidden()) continue;
  3850. const int plugin_state = gizmo_plugins_by_name[i]->get_state();
  3851. const int idx = gizmos_menu->get_item_index(i);
  3852. switch (plugin_state) {
  3853. case EditorSpatialGizmoPlugin::VISIBLE:
  3854. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_visible"));
  3855. break;
  3856. case EditorSpatialGizmoPlugin::ON_TOP:
  3857. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_xray"));
  3858. break;
  3859. case EditorSpatialGizmoPlugin::HIDDEN:
  3860. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_hidden"));
  3861. break;
  3862. }
  3863. }
  3864. }
  3865. void SpatialEditor::_init_grid() {
  3866. PoolVector<Color> grid_colors[3];
  3867. PoolVector<Vector3> grid_points[3];
  3868. Color primary_grid_color = EditorSettings::get_singleton()->get("editors/3d/primary_grid_color");
  3869. Color secondary_grid_color = EditorSettings::get_singleton()->get("editors/3d/secondary_grid_color");
  3870. int grid_size = EditorSettings::get_singleton()->get("editors/3d/grid_size");
  3871. int primary_grid_steps = EditorSettings::get_singleton()->get("editors/3d/primary_grid_steps");
  3872. for (int i = 0; i < 3; i++) {
  3873. Vector3 axis;
  3874. axis[i] = 1;
  3875. Vector3 axis_n1;
  3876. axis_n1[(i + 1) % 3] = 1;
  3877. Vector3 axis_n2;
  3878. axis_n2[(i + 2) % 3] = 1;
  3879. for (int j = -grid_size; j <= grid_size; j++) {
  3880. Vector3 p1 = axis_n1 * j + axis_n2 * -grid_size;
  3881. Vector3 p1_dest = p1 * (-axis_n2 + axis_n1);
  3882. Vector3 p2 = axis_n2 * j + axis_n1 * -grid_size;
  3883. Vector3 p2_dest = p2 * (-axis_n1 + axis_n2);
  3884. Color line_color = secondary_grid_color;
  3885. if (origin_enabled && j == 0) {
  3886. // Don't draw the center lines of the grid if the origin is enabled
  3887. // The origin would overlap the grid lines in this case, causing flickering
  3888. continue;
  3889. } else if (j % primary_grid_steps == 0) {
  3890. line_color = primary_grid_color;
  3891. }
  3892. grid_points[i].push_back(p1);
  3893. grid_points[i].push_back(p1_dest);
  3894. grid_colors[i].push_back(line_color);
  3895. grid_colors[i].push_back(line_color);
  3896. grid_points[i].push_back(p2);
  3897. grid_points[i].push_back(p2_dest);
  3898. grid_colors[i].push_back(line_color);
  3899. grid_colors[i].push_back(line_color);
  3900. }
  3901. grid[i] = VisualServer::get_singleton()->mesh_create();
  3902. Array d;
  3903. d.resize(VS::ARRAY_MAX);
  3904. d[VisualServer::ARRAY_VERTEX] = grid_points[i];
  3905. d[VisualServer::ARRAY_COLOR] = grid_colors[i];
  3906. VisualServer::get_singleton()->mesh_add_surface_from_arrays(grid[i], VisualServer::PRIMITIVE_LINES, d);
  3907. VisualServer::get_singleton()->mesh_surface_set_material(grid[i], 0, indicator_mat->get_rid());
  3908. grid_instance[i] = VisualServer::get_singleton()->instance_create2(grid[i], get_tree()->get_root()->get_world()->get_scenario());
  3909. VisualServer::get_singleton()->instance_set_visible(grid_instance[i], grid_visible[i]);
  3910. VisualServer::get_singleton()->instance_geometry_set_cast_shadows_setting(grid_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  3911. VS::get_singleton()->instance_set_layer_mask(grid_instance[i], 1 << SpatialEditorViewport::GIZMO_GRID_LAYER);
  3912. }
  3913. }
  3914. void SpatialEditor::_finish_indicators() {
  3915. VisualServer::get_singleton()->free(origin_instance);
  3916. VisualServer::get_singleton()->free(origin);
  3917. _finish_grid();
  3918. }
  3919. void SpatialEditor::_finish_grid() {
  3920. for (int i = 0; i < 3; i++) {
  3921. VisualServer::get_singleton()->free(grid_instance[i]);
  3922. VisualServer::get_singleton()->free(grid[i]);
  3923. }
  3924. }
  3925. bool SpatialEditor::is_any_freelook_active() const {
  3926. for (unsigned int i = 0; i < VIEWPORTS_COUNT; ++i) {
  3927. if (viewports[i]->is_freelook_active())
  3928. return true;
  3929. }
  3930. return false;
  3931. }
  3932. void SpatialEditor::_refresh_menu_icons() {
  3933. bool all_locked = true;
  3934. bool all_grouped = true;
  3935. List<Node *> &selection = editor_selection->get_selected_node_list();
  3936. if (selection.empty()) {
  3937. all_locked = false;
  3938. all_grouped = false;
  3939. } else {
  3940. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3941. if (Object::cast_to<Spatial>(E->get()) && !Object::cast_to<Spatial>(E->get())->has_meta("_edit_lock_")) {
  3942. all_locked = false;
  3943. break;
  3944. }
  3945. }
  3946. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3947. if (Object::cast_to<Spatial>(E->get()) && !Object::cast_to<Spatial>(E->get())->has_meta("_edit_group_")) {
  3948. all_grouped = false;
  3949. break;
  3950. }
  3951. }
  3952. }
  3953. tool_button[TOOL_LOCK_SELECTED]->set_visible(!all_locked);
  3954. tool_button[TOOL_LOCK_SELECTED]->set_disabled(selection.empty());
  3955. tool_button[TOOL_UNLOCK_SELECTED]->set_visible(all_locked);
  3956. tool_button[TOOL_GROUP_SELECTED]->set_visible(!all_grouped);
  3957. tool_button[TOOL_GROUP_SELECTED]->set_disabled(selection.empty());
  3958. tool_button[TOOL_UNGROUP_SELECTED]->set_visible(all_grouped);
  3959. }
  3960. template <typename T>
  3961. Set<T *> _get_child_nodes(Node *parent_node) {
  3962. Set<T *> nodes = Set<T *>();
  3963. T *node = Node::cast_to<T>(parent_node);
  3964. if (node) {
  3965. nodes.insert(node);
  3966. }
  3967. for (int i = 0; i < parent_node->get_child_count(); i++) {
  3968. Node *child_node = parent_node->get_child(i);
  3969. Set<T *> child_nodes = _get_child_nodes<T>(child_node);
  3970. for (typename Set<T *>::Element *I = child_nodes.front(); I; I = I->next()) {
  3971. nodes.insert(I->get());
  3972. }
  3973. }
  3974. return nodes;
  3975. }
  3976. Set<RID> _get_physics_bodies_rid(Node *node) {
  3977. Set<RID> rids = Set<RID>();
  3978. PhysicsBody *pb = Node::cast_to<PhysicsBody>(node);
  3979. if (pb) {
  3980. rids.insert(pb->get_rid());
  3981. }
  3982. Set<PhysicsBody *> child_nodes = _get_child_nodes<PhysicsBody>(node);
  3983. for (Set<PhysicsBody *>::Element *I = child_nodes.front(); I; I = I->next()) {
  3984. rids.insert(I->get()->get_rid());
  3985. }
  3986. return rids;
  3987. }
  3988. void SpatialEditor::snap_selected_nodes_to_floor() {
  3989. List<Node *> &selection = editor_selection->get_selected_node_list();
  3990. Dictionary snap_data;
  3991. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3992. Spatial *sp = Object::cast_to<Spatial>(E->get());
  3993. if (sp) {
  3994. Vector3 from = Vector3();
  3995. Vector3 position_offset = Vector3();
  3996. // Priorities for snapping to floor are CollisionShapes, VisualInstances and then origin
  3997. Set<VisualInstance *> vi = _get_child_nodes<VisualInstance>(sp);
  3998. Set<CollisionShape *> cs = _get_child_nodes<CollisionShape>(sp);
  3999. if (cs.size()) {
  4000. AABB aabb = sp->get_global_transform().xform(cs.front()->get()->get_shape()->get_debug_mesh()->get_aabb());
  4001. for (Set<CollisionShape *>::Element *I = cs.front(); I; I = I->next()) {
  4002. aabb.merge_with(sp->get_global_transform().xform(I->get()->get_shape()->get_debug_mesh()->get_aabb()));
  4003. }
  4004. Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
  4005. from = aabb.position + size;
  4006. position_offset.y = from.y - sp->get_global_transform().origin.y;
  4007. } else if (vi.size()) {
  4008. AABB aabb = vi.front()->get()->get_transformed_aabb();
  4009. for (Set<VisualInstance *>::Element *I = vi.front(); I; I = I->next()) {
  4010. aabb.merge_with(I->get()->get_transformed_aabb());
  4011. }
  4012. Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
  4013. from = aabb.position + size;
  4014. position_offset.y = from.y - sp->get_global_transform().origin.y;
  4015. } else {
  4016. from = sp->get_global_transform().origin;
  4017. }
  4018. // We add a bit of margin to the from position to avoid it from snapping
  4019. // when the spatial is already on a floor and there's another floor under
  4020. // it
  4021. from = from + Vector3(0.0, 0.2, 0.0);
  4022. Dictionary d;
  4023. d["from"] = from;
  4024. d["position_offset"] = position_offset;
  4025. snap_data[sp] = d;
  4026. }
  4027. }
  4028. PhysicsDirectSpaceState *ss = get_tree()->get_root()->get_world()->get_direct_space_state();
  4029. PhysicsDirectSpaceState::RayResult result;
  4030. Array keys = snap_data.keys();
  4031. // The maximum height an object can travel to be snapped
  4032. const float max_snap_height = 20.0;
  4033. // Will be set to `true` if at least one node from the selection was sucessfully snapped
  4034. bool snapped_to_floor = false;
  4035. if (keys.size()) {
  4036. // For snapping to be performed, there must be solid geometry under at least one of the selected nodes.
  4037. // We need to check this before snapping to register the undo/redo action only if needed.
  4038. for (int i = 0; i < keys.size(); i++) {
  4039. Node *node = keys[i];
  4040. Spatial *sp = Object::cast_to<Spatial>(node);
  4041. Dictionary d = snap_data[node];
  4042. Vector3 from = d["from"];
  4043. Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
  4044. Set<RID> excluded = _get_physics_bodies_rid(sp);
  4045. if (ss->intersect_ray(from, to, result, excluded)) {
  4046. snapped_to_floor = true;
  4047. }
  4048. }
  4049. if (snapped_to_floor) {
  4050. undo_redo->create_action(TTR("Snap Nodes To Floor"));
  4051. // Perform snapping if at least one node can be snapped
  4052. for (int i = 0; i < keys.size(); i++) {
  4053. Node *node = keys[i];
  4054. Spatial *sp = Object::cast_to<Spatial>(node);
  4055. Dictionary d = snap_data[node];
  4056. Vector3 from = d["from"];
  4057. Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
  4058. Set<RID> excluded = _get_physics_bodies_rid(sp);
  4059. if (ss->intersect_ray(from, to, result, excluded)) {
  4060. Vector3 position_offset = d["position_offset"];
  4061. Transform new_transform = sp->get_global_transform();
  4062. new_transform.origin.y = result.position.y;
  4063. new_transform.origin = new_transform.origin - position_offset;
  4064. undo_redo->add_do_method(sp, "set_global_transform", new_transform);
  4065. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_transform());
  4066. }
  4067. }
  4068. undo_redo->commit_action();
  4069. } else {
  4070. EditorNode::get_singleton()->show_warning(TTR("Couldn't find a solid floor to snap the selection to."));
  4071. }
  4072. }
  4073. }
  4074. void SpatialEditor::_unhandled_key_input(Ref<InputEvent> p_event) {
  4075. if (!is_visible_in_tree() || get_viewport()->gui_has_modal_stack())
  4076. return;
  4077. snap_key_enabled = Input::get_singleton()->is_key_pressed(KEY_CONTROL);
  4078. }
  4079. void SpatialEditor::_notification(int p_what) {
  4080. if (p_what == NOTIFICATION_READY) {
  4081. tool_button[SpatialEditor::TOOL_MODE_SELECT]->set_icon(get_icon("ToolSelect", "EditorIcons"));
  4082. tool_button[SpatialEditor::TOOL_MODE_MOVE]->set_icon(get_icon("ToolMove", "EditorIcons"));
  4083. tool_button[SpatialEditor::TOOL_MODE_ROTATE]->set_icon(get_icon("ToolRotate", "EditorIcons"));
  4084. tool_button[SpatialEditor::TOOL_MODE_SCALE]->set_icon(get_icon("ToolScale", "EditorIcons"));
  4085. tool_button[SpatialEditor::TOOL_MODE_LIST_SELECT]->set_icon(get_icon("ListSelect", "EditorIcons"));
  4086. tool_button[SpatialEditor::TOOL_LOCK_SELECTED]->set_icon(get_icon("Lock", "EditorIcons"));
  4087. tool_button[SpatialEditor::TOOL_UNLOCK_SELECTED]->set_icon(get_icon("Unlock", "EditorIcons"));
  4088. tool_button[SpatialEditor::TOOL_GROUP_SELECTED]->set_icon(get_icon("Group", "EditorIcons"));
  4089. tool_button[SpatialEditor::TOOL_UNGROUP_SELECTED]->set_icon(get_icon("Ungroup", "EditorIcons"));
  4090. tool_option_button[SpatialEditor::TOOL_OPT_LOCAL_COORDS]->set_icon(get_icon("Object", "EditorIcons"));
  4091. tool_option_button[SpatialEditor::TOOL_OPT_USE_SNAP]->set_icon(get_icon("Snap", "EditorIcons"));
  4092. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), get_icon("Panels1", "EditorIcons"));
  4093. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), get_icon("Panels2", "EditorIcons"));
  4094. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), get_icon("Panels2Alt", "EditorIcons"));
  4095. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), get_icon("Panels3", "EditorIcons"));
  4096. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), get_icon("Panels3Alt", "EditorIcons"));
  4097. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), get_icon("Panels4", "EditorIcons"));
  4098. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  4099. _refresh_menu_icons();
  4100. get_tree()->connect("node_removed", this, "_node_removed");
  4101. EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor()->connect("node_changed", this, "_refresh_menu_icons");
  4102. editor_selection->connect("selection_changed", this, "_refresh_menu_icons");
  4103. } else if (p_what == NOTIFICATION_ENTER_TREE) {
  4104. _register_all_gizmos();
  4105. _update_gizmos_menu();
  4106. _init_indicators();
  4107. } else if (p_what == NOTIFICATION_THEME_CHANGED) {
  4108. _update_gizmos_menu_theme();
  4109. } else if (p_what == NOTIFICATION_EXIT_TREE) {
  4110. _finish_indicators();
  4111. } else if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) {
  4112. tool_button[SpatialEditor::TOOL_MODE_SELECT]->set_icon(get_icon("ToolSelect", "EditorIcons"));
  4113. tool_button[SpatialEditor::TOOL_MODE_MOVE]->set_icon(get_icon("ToolMove", "EditorIcons"));
  4114. tool_button[SpatialEditor::TOOL_MODE_ROTATE]->set_icon(get_icon("ToolRotate", "EditorIcons"));
  4115. tool_button[SpatialEditor::TOOL_MODE_SCALE]->set_icon(get_icon("ToolScale", "EditorIcons"));
  4116. tool_button[SpatialEditor::TOOL_MODE_LIST_SELECT]->set_icon(get_icon("ListSelect", "EditorIcons"));
  4117. tool_button[SpatialEditor::TOOL_LOCK_SELECTED]->set_icon(get_icon("Lock", "EditorIcons"));
  4118. tool_button[SpatialEditor::TOOL_UNLOCK_SELECTED]->set_icon(get_icon("Unlock", "EditorIcons"));
  4119. tool_button[SpatialEditor::TOOL_GROUP_SELECTED]->set_icon(get_icon("Group", "EditorIcons"));
  4120. tool_button[SpatialEditor::TOOL_UNGROUP_SELECTED]->set_icon(get_icon("Ungroup", "EditorIcons"));
  4121. tool_option_button[SpatialEditor::TOOL_OPT_LOCAL_COORDS]->set_icon(get_icon("Object", "EditorIcons"));
  4122. tool_option_button[SpatialEditor::TOOL_OPT_USE_SNAP]->set_icon(get_icon("Snap", "EditorIcons"));
  4123. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), get_icon("Panels1", "EditorIcons"));
  4124. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), get_icon("Panels2", "EditorIcons"));
  4125. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), get_icon("Panels2Alt", "EditorIcons"));
  4126. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), get_icon("Panels3", "EditorIcons"));
  4127. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), get_icon("Panels3Alt", "EditorIcons"));
  4128. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), get_icon("Panels4", "EditorIcons"));
  4129. // Update grid color by rebuilding grid.
  4130. _finish_grid();
  4131. _init_grid();
  4132. }
  4133. }
  4134. void SpatialEditor::add_control_to_menu_panel(Control *p_control) {
  4135. hbc_menu->add_child(p_control);
  4136. }
  4137. void SpatialEditor::remove_control_from_menu_panel(Control *p_control) {
  4138. hbc_menu->remove_child(p_control);
  4139. }
  4140. void SpatialEditor::set_can_preview(Camera *p_preview) {
  4141. for (int i = 0; i < 4; i++) {
  4142. viewports[i]->set_can_preview(p_preview);
  4143. }
  4144. }
  4145. VSplitContainer *SpatialEditor::get_shader_split() {
  4146. return shader_split;
  4147. }
  4148. HSplitContainer *SpatialEditor::get_palette_split() {
  4149. return palette_split;
  4150. }
  4151. void SpatialEditor::_request_gizmo(Object *p_obj) {
  4152. Spatial *sp = Object::cast_to<Spatial>(p_obj);
  4153. if (!sp)
  4154. return;
  4155. if (editor->get_edited_scene() && (sp == editor->get_edited_scene() || (sp->get_owner() && editor->get_edited_scene()->is_a_parent_of(sp)))) {
  4156. Ref<EditorSpatialGizmo> seg;
  4157. for (int i = 0; i < gizmo_plugins_by_priority.size(); ++i) {
  4158. seg = gizmo_plugins_by_priority.write[i]->get_gizmo(sp);
  4159. if (seg.is_valid()) {
  4160. sp->set_gizmo(seg);
  4161. if (sp == selected) {
  4162. seg->set_selected(true);
  4163. selected->update_gizmo();
  4164. }
  4165. break;
  4166. }
  4167. }
  4168. }
  4169. }
  4170. void SpatialEditor::_toggle_maximize_view(Object *p_viewport) {
  4171. if (!p_viewport) return;
  4172. SpatialEditorViewport *current_viewport = Object::cast_to<SpatialEditorViewport>(p_viewport);
  4173. if (!current_viewport) return;
  4174. int index = -1;
  4175. bool maximized = false;
  4176. for (int i = 0; i < 4; i++) {
  4177. if (viewports[i] == current_viewport) {
  4178. index = i;
  4179. if (current_viewport->get_global_rect() == viewport_base->get_global_rect())
  4180. maximized = true;
  4181. break;
  4182. }
  4183. }
  4184. if (index == -1) return;
  4185. if (!maximized) {
  4186. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  4187. if (i == (uint32_t)index)
  4188. viewports[i]->set_anchors_and_margins_preset(Control::PRESET_WIDE);
  4189. else
  4190. viewports[i]->hide();
  4191. }
  4192. } else {
  4193. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++)
  4194. viewports[i]->show();
  4195. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT)))
  4196. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  4197. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS)))
  4198. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
  4199. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT)))
  4200. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
  4201. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS)))
  4202. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
  4203. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT)))
  4204. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
  4205. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS)))
  4206. _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
  4207. }
  4208. }
  4209. void SpatialEditor::_node_removed(Node *p_node) {
  4210. if (p_node == selected)
  4211. selected = NULL;
  4212. }
  4213. void SpatialEditor::_register_all_gizmos() {
  4214. add_gizmo_plugin(Ref<CameraSpatialGizmoPlugin>(memnew(CameraSpatialGizmoPlugin)));
  4215. add_gizmo_plugin(Ref<LightSpatialGizmoPlugin>(memnew(LightSpatialGizmoPlugin)));
  4216. add_gizmo_plugin(Ref<AudioStreamPlayer3DSpatialGizmoPlugin>(memnew(AudioStreamPlayer3DSpatialGizmoPlugin)));
  4217. add_gizmo_plugin(Ref<MeshInstanceSpatialGizmoPlugin>(memnew(MeshInstanceSpatialGizmoPlugin)));
  4218. add_gizmo_plugin(Ref<SoftBodySpatialGizmoPlugin>(memnew(SoftBodySpatialGizmoPlugin)));
  4219. add_gizmo_plugin(Ref<Sprite3DSpatialGizmoPlugin>(memnew(Sprite3DSpatialGizmoPlugin)));
  4220. add_gizmo_plugin(Ref<SkeletonSpatialGizmoPlugin>(memnew(SkeletonSpatialGizmoPlugin)));
  4221. add_gizmo_plugin(Ref<Position3DSpatialGizmoPlugin>(memnew(Position3DSpatialGizmoPlugin)));
  4222. add_gizmo_plugin(Ref<RayCastSpatialGizmoPlugin>(memnew(RayCastSpatialGizmoPlugin)));
  4223. add_gizmo_plugin(Ref<SpringArmSpatialGizmoPlugin>(memnew(SpringArmSpatialGizmoPlugin)));
  4224. add_gizmo_plugin(Ref<VehicleWheelSpatialGizmoPlugin>(memnew(VehicleWheelSpatialGizmoPlugin)));
  4225. add_gizmo_plugin(Ref<VisibilityNotifierGizmoPlugin>(memnew(VisibilityNotifierGizmoPlugin)));
  4226. add_gizmo_plugin(Ref<ParticlesGizmoPlugin>(memnew(ParticlesGizmoPlugin)));
  4227. add_gizmo_plugin(Ref<CPUParticlesGizmoPlugin>(memnew(CPUParticlesGizmoPlugin)));
  4228. add_gizmo_plugin(Ref<ReflectionProbeGizmoPlugin>(memnew(ReflectionProbeGizmoPlugin)));
  4229. add_gizmo_plugin(Ref<GIProbeGizmoPlugin>(memnew(GIProbeGizmoPlugin)));
  4230. add_gizmo_plugin(Ref<BakedIndirectLightGizmoPlugin>(memnew(BakedIndirectLightGizmoPlugin)));
  4231. add_gizmo_plugin(Ref<CollisionShapeSpatialGizmoPlugin>(memnew(CollisionShapeSpatialGizmoPlugin)));
  4232. add_gizmo_plugin(Ref<CollisionPolygonSpatialGizmoPlugin>(memnew(CollisionPolygonSpatialGizmoPlugin)));
  4233. add_gizmo_plugin(Ref<NavigationMeshSpatialGizmoPlugin>(memnew(NavigationMeshSpatialGizmoPlugin)));
  4234. add_gizmo_plugin(Ref<JointSpatialGizmoPlugin>(memnew(JointSpatialGizmoPlugin)));
  4235. add_gizmo_plugin(Ref<PhysicalBoneSpatialGizmoPlugin>(memnew(PhysicalBoneSpatialGizmoPlugin)));
  4236. }
  4237. void SpatialEditor::_bind_methods() {
  4238. ClassDB::bind_method("_unhandled_key_input", &SpatialEditor::_unhandled_key_input);
  4239. ClassDB::bind_method("_node_removed", &SpatialEditor::_node_removed);
  4240. ClassDB::bind_method("_menu_item_pressed", &SpatialEditor::_menu_item_pressed);
  4241. ClassDB::bind_method("_menu_gizmo_toggled", &SpatialEditor::_menu_gizmo_toggled);
  4242. ClassDB::bind_method("_menu_item_toggled", &SpatialEditor::_menu_item_toggled);
  4243. ClassDB::bind_method("_xform_dialog_action", &SpatialEditor::_xform_dialog_action);
  4244. ClassDB::bind_method("_get_editor_data", &SpatialEditor::_get_editor_data);
  4245. ClassDB::bind_method("_request_gizmo", &SpatialEditor::_request_gizmo);
  4246. ClassDB::bind_method("_toggle_maximize_view", &SpatialEditor::_toggle_maximize_view);
  4247. ClassDB::bind_method("_refresh_menu_icons", &SpatialEditor::_refresh_menu_icons);
  4248. ADD_SIGNAL(MethodInfo("transform_key_request"));
  4249. ADD_SIGNAL(MethodInfo("item_lock_status_changed"));
  4250. ADD_SIGNAL(MethodInfo("item_group_status_changed"));
  4251. }
  4252. void SpatialEditor::clear() {
  4253. settings_fov->set_value(EDITOR_DEF("editors/3d/default_fov", 70.0));
  4254. settings_znear->set_value(EDITOR_DEF("editors/3d/default_z_near", 0.05));
  4255. settings_zfar->set_value(EDITOR_DEF("editors/3d/default_z_far", 1500.0));
  4256. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  4257. viewports[i]->reset();
  4258. }
  4259. VisualServer::get_singleton()->instance_set_visible(origin_instance, true);
  4260. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), true);
  4261. for (int i = 0; i < 3; ++i) {
  4262. if (grid_enable[i]) {
  4263. VisualServer::get_singleton()->instance_set_visible(grid_instance[i], true);
  4264. grid_visible[i] = true;
  4265. }
  4266. }
  4267. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  4268. viewports[i]->view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(SpatialEditorViewport::VIEW_AUDIO_LISTENER), i == 0);
  4269. viewports[i]->viewport->set_as_audio_listener(i == 0);
  4270. }
  4271. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID), true);
  4272. }
  4273. SpatialEditor::SpatialEditor(EditorNode *p_editor) {
  4274. gizmo.visible = true;
  4275. gizmo.scale = 1.0;
  4276. viewport_environment = Ref<Environment>(memnew(Environment));
  4277. undo_redo = p_editor->get_undo_redo();
  4278. VBoxContainer *vbc = this;
  4279. custom_camera = NULL;
  4280. singleton = this;
  4281. editor = p_editor;
  4282. editor_selection = editor->get_editor_selection();
  4283. editor_selection->add_editor_plugin(this);
  4284. snap_enabled = false;
  4285. snap_key_enabled = false;
  4286. tool_mode = TOOL_MODE_SELECT;
  4287. hbc_menu = memnew(HBoxContainer);
  4288. vbc->add_child(hbc_menu);
  4289. Vector<Variant> button_binds;
  4290. button_binds.resize(1);
  4291. String sct;
  4292. tool_button[TOOL_MODE_SELECT] = memnew(ToolButton);
  4293. hbc_menu->add_child(tool_button[TOOL_MODE_SELECT]);
  4294. tool_button[TOOL_MODE_SELECT]->set_toggle_mode(true);
  4295. tool_button[TOOL_MODE_SELECT]->set_flat(true);
  4296. tool_button[TOOL_MODE_SELECT]->set_pressed(true);
  4297. button_binds.write[0] = MENU_TOOL_SELECT;
  4298. tool_button[TOOL_MODE_SELECT]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4299. tool_button[TOOL_MODE_SELECT]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_select", TTR("Select Mode"), KEY_Q));
  4300. tool_button[TOOL_MODE_SELECT]->set_tooltip(keycode_get_string(KEY_MASK_CMD) + TTR("Drag: Rotate\nAlt+Drag: Move\nAlt+RMB: Depth list selection"));
  4301. hbc_menu->add_child(memnew(VSeparator));
  4302. tool_button[TOOL_MODE_MOVE] = memnew(ToolButton);
  4303. hbc_menu->add_child(tool_button[TOOL_MODE_MOVE]);
  4304. tool_button[TOOL_MODE_MOVE]->set_toggle_mode(true);
  4305. tool_button[TOOL_MODE_MOVE]->set_flat(true);
  4306. button_binds.write[0] = MENU_TOOL_MOVE;
  4307. tool_button[TOOL_MODE_MOVE]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4308. tool_button[TOOL_MODE_MOVE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_move", TTR("Move Mode"), KEY_W));
  4309. tool_button[TOOL_MODE_ROTATE] = memnew(ToolButton);
  4310. hbc_menu->add_child(tool_button[TOOL_MODE_ROTATE]);
  4311. tool_button[TOOL_MODE_ROTATE]->set_toggle_mode(true);
  4312. tool_button[TOOL_MODE_ROTATE]->set_flat(true);
  4313. button_binds.write[0] = MENU_TOOL_ROTATE;
  4314. tool_button[TOOL_MODE_ROTATE]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4315. tool_button[TOOL_MODE_ROTATE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_rotate", TTR("Rotate Mode"), KEY_E));
  4316. tool_button[TOOL_MODE_SCALE] = memnew(ToolButton);
  4317. hbc_menu->add_child(tool_button[TOOL_MODE_SCALE]);
  4318. tool_button[TOOL_MODE_SCALE]->set_toggle_mode(true);
  4319. tool_button[TOOL_MODE_SCALE]->set_flat(true);
  4320. button_binds.write[0] = MENU_TOOL_SCALE;
  4321. tool_button[TOOL_MODE_SCALE]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4322. tool_button[TOOL_MODE_SCALE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_scale", TTR("Scale Mode"), KEY_R));
  4323. hbc_menu->add_child(memnew(VSeparator));
  4324. tool_button[TOOL_MODE_LIST_SELECT] = memnew(ToolButton);
  4325. hbc_menu->add_child(tool_button[TOOL_MODE_LIST_SELECT]);
  4326. tool_button[TOOL_MODE_LIST_SELECT]->set_toggle_mode(true);
  4327. tool_button[TOOL_MODE_LIST_SELECT]->set_flat(true);
  4328. button_binds.write[0] = MENU_TOOL_LIST_SELECT;
  4329. tool_button[TOOL_MODE_LIST_SELECT]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4330. tool_button[TOOL_MODE_LIST_SELECT]->set_tooltip(TTR("Show a list of all objects at the position clicked\n(same as Alt+RMB in select mode)."));
  4331. tool_button[TOOL_LOCK_SELECTED] = memnew(ToolButton);
  4332. hbc_menu->add_child(tool_button[TOOL_LOCK_SELECTED]);
  4333. button_binds.write[0] = MENU_LOCK_SELECTED;
  4334. tool_button[TOOL_LOCK_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4335. tool_button[TOOL_LOCK_SELECTED]->set_tooltip(TTR("Lock the selected object in place (can't be moved)."));
  4336. tool_button[TOOL_UNLOCK_SELECTED] = memnew(ToolButton);
  4337. hbc_menu->add_child(tool_button[TOOL_UNLOCK_SELECTED]);
  4338. button_binds.write[0] = MENU_UNLOCK_SELECTED;
  4339. tool_button[TOOL_UNLOCK_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4340. tool_button[TOOL_UNLOCK_SELECTED]->set_tooltip(TTR("Unlock the selected object (can be moved)."));
  4341. tool_button[TOOL_GROUP_SELECTED] = memnew(ToolButton);
  4342. hbc_menu->add_child(tool_button[TOOL_GROUP_SELECTED]);
  4343. button_binds.write[0] = MENU_GROUP_SELECTED;
  4344. tool_button[TOOL_GROUP_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4345. tool_button[TOOL_GROUP_SELECTED]->set_tooltip(TTR("Makes sure the object's children are not selectable."));
  4346. tool_button[TOOL_UNGROUP_SELECTED] = memnew(ToolButton);
  4347. hbc_menu->add_child(tool_button[TOOL_UNGROUP_SELECTED]);
  4348. button_binds.write[0] = MENU_UNGROUP_SELECTED;
  4349. tool_button[TOOL_UNGROUP_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4350. tool_button[TOOL_UNGROUP_SELECTED]->set_tooltip(TTR("Restores the object's children's ability to be selected."));
  4351. hbc_menu->add_child(memnew(VSeparator));
  4352. tool_option_button[TOOL_OPT_LOCAL_COORDS] = memnew(ToolButton);
  4353. hbc_menu->add_child(tool_option_button[TOOL_OPT_LOCAL_COORDS]);
  4354. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_toggle_mode(true);
  4355. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_flat(true);
  4356. button_binds.write[0] = MENU_TOOL_LOCAL_COORDS;
  4357. tool_option_button[TOOL_OPT_LOCAL_COORDS]->connect("toggled", this, "_menu_item_toggled", button_binds);
  4358. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut(ED_SHORTCUT("spatial_editor/local_coords", TTR("Use Local Space"), KEY_T));
  4359. tool_option_button[TOOL_OPT_USE_SNAP] = memnew(ToolButton);
  4360. hbc_menu->add_child(tool_option_button[TOOL_OPT_USE_SNAP]);
  4361. tool_option_button[TOOL_OPT_USE_SNAP]->set_toggle_mode(true);
  4362. tool_option_button[TOOL_OPT_USE_SNAP]->set_flat(true);
  4363. button_binds.write[0] = MENU_TOOL_USE_SNAP;
  4364. tool_option_button[TOOL_OPT_USE_SNAP]->connect("toggled", this, "_menu_item_toggled", button_binds);
  4365. tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut(ED_SHORTCUT("spatial_editor/snap", TTR("Use Snap"), KEY_Y));
  4366. hbc_menu->add_child(memnew(VSeparator));
  4367. // Drag and drop support;
  4368. preview_node = memnew(Spatial);
  4369. preview_bounds = AABB();
  4370. ED_SHORTCUT("spatial_editor/bottom_view", TTR("Bottom View"), KEY_MASK_ALT + KEY_KP_7);
  4371. ED_SHORTCUT("spatial_editor/top_view", TTR("Top View"), KEY_KP_7);
  4372. ED_SHORTCUT("spatial_editor/rear_view", TTR("Rear View"), KEY_MASK_ALT + KEY_KP_1);
  4373. ED_SHORTCUT("spatial_editor/front_view", TTR("Front View"), KEY_KP_1);
  4374. ED_SHORTCUT("spatial_editor/left_view", TTR("Left View"), KEY_MASK_ALT + KEY_KP_3);
  4375. ED_SHORTCUT("spatial_editor/right_view", TTR("Right View"), KEY_KP_3);
  4376. ED_SHORTCUT("spatial_editor/switch_perspective_orthogonal", TTR("Switch Perspective/Orthogonal View"), KEY_KP_5);
  4377. ED_SHORTCUT("spatial_editor/insert_anim_key", TTR("Insert Animation Key"), KEY_K);
  4378. ED_SHORTCUT("spatial_editor/focus_origin", TTR("Focus Origin"), KEY_O);
  4379. ED_SHORTCUT("spatial_editor/focus_selection", TTR("Focus Selection"), KEY_F);
  4380. ED_SHORTCUT("spatial_editor/align_transform_with_view", TTR("Align Transform with View"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_M);
  4381. ED_SHORTCUT("spatial_editor/align_rotation_with_view", TTR("Align Rotation with View"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_F);
  4382. ED_SHORTCUT("spatial_editor/freelook_toggle", TTR("Toggle Freelook"), KEY_MASK_SHIFT + KEY_F);
  4383. PopupMenu *p;
  4384. transform_menu = memnew(MenuButton);
  4385. transform_menu->set_text(TTR("Transform"));
  4386. transform_menu->set_switch_on_hover(true);
  4387. hbc_menu->add_child(transform_menu);
  4388. p = transform_menu->get_popup();
  4389. p->add_shortcut(ED_SHORTCUT("spatial_editor/snap_to_floor", TTR("Snap Object to Floor"), KEY_PAGEDOWN), MENU_SNAP_TO_FLOOR);
  4390. p->add_shortcut(ED_SHORTCUT("spatial_editor/transform_dialog", TTR("Transform Dialog...")), MENU_TRANSFORM_DIALOG);
  4391. p->add_separator();
  4392. p->add_shortcut(ED_SHORTCUT("spatial_editor/configure_snap", TTR("Configure Snap...")), MENU_TRANSFORM_CONFIGURE_SNAP);
  4393. p->connect("id_pressed", this, "_menu_item_pressed");
  4394. view_menu = memnew(MenuButton);
  4395. view_menu->set_text(TTR("View"));
  4396. view_menu->set_switch_on_hover(true);
  4397. hbc_menu->add_child(view_menu);
  4398. p = view_menu->get_popup();
  4399. accept = memnew(AcceptDialog);
  4400. editor->get_gui_base()->add_child(accept);
  4401. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/1_viewport", TTR("1 Viewport"), KEY_MASK_CMD + KEY_1), MENU_VIEW_USE_1_VIEWPORT);
  4402. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports", TTR("2 Viewports"), KEY_MASK_CMD + KEY_2), MENU_VIEW_USE_2_VIEWPORTS);
  4403. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports_alt", TTR("2 Viewports (Alt)"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_2), MENU_VIEW_USE_2_VIEWPORTS_ALT);
  4404. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports", TTR("3 Viewports"), KEY_MASK_CMD + KEY_3), MENU_VIEW_USE_3_VIEWPORTS);
  4405. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports_alt", TTR("3 Viewports (Alt)"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_3), MENU_VIEW_USE_3_VIEWPORTS_ALT);
  4406. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/4_viewports", TTR("4 Viewports"), KEY_MASK_CMD + KEY_4), MENU_VIEW_USE_4_VIEWPORTS);
  4407. p->add_separator();
  4408. p->add_submenu_item(TTR("Gizmos"), "GizmosMenu");
  4409. p->add_separator();
  4410. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_origin", TTR("View Origin")), MENU_VIEW_ORIGIN);
  4411. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_grid", TTR("View Grid")), MENU_VIEW_GRID);
  4412. p->add_separator();
  4413. p->add_shortcut(ED_SHORTCUT("spatial_editor/settings", TTR("Settings...")), MENU_VIEW_CAMERA_SETTINGS);
  4414. p->set_item_checked(p->get_item_index(MENU_VIEW_ORIGIN), true);
  4415. p->set_item_checked(p->get_item_index(MENU_VIEW_GRID), true);
  4416. p->connect("id_pressed", this, "_menu_item_pressed");
  4417. gizmos_menu = memnew(PopupMenu);
  4418. p->add_child(gizmos_menu);
  4419. gizmos_menu->set_name("GizmosMenu");
  4420. gizmos_menu->set_hide_on_checkable_item_selection(false);
  4421. gizmos_menu->connect("id_pressed", this, "_menu_gizmo_toggled");
  4422. /* REST OF MENU */
  4423. palette_split = memnew(HSplitContainer);
  4424. palette_split->set_v_size_flags(SIZE_EXPAND_FILL);
  4425. vbc->add_child(palette_split);
  4426. shader_split = memnew(VSplitContainer);
  4427. shader_split->set_h_size_flags(SIZE_EXPAND_FILL);
  4428. palette_split->add_child(shader_split);
  4429. viewport_base = memnew(SpatialEditorViewportContainer);
  4430. shader_split->add_child(viewport_base);
  4431. viewport_base->set_v_size_flags(SIZE_EXPAND_FILL);
  4432. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  4433. viewports[i] = memnew(SpatialEditorViewport(this, editor, i));
  4434. viewports[i]->connect("toggle_maximize_view", this, "_toggle_maximize_view");
  4435. viewports[i]->assign_pending_data_pointers(preview_node, &preview_bounds, accept);
  4436. viewport_base->add_child(viewports[i]);
  4437. }
  4438. /* SNAP DIALOG */
  4439. snap_dialog = memnew(ConfirmationDialog);
  4440. snap_dialog->set_title(TTR("Snap Settings"));
  4441. add_child(snap_dialog);
  4442. VBoxContainer *snap_dialog_vbc = memnew(VBoxContainer);
  4443. snap_dialog->add_child(snap_dialog_vbc);
  4444. snap_translate = memnew(LineEdit);
  4445. snap_translate->set_text("1");
  4446. snap_dialog_vbc->add_margin_child(TTR("Translate Snap:"), snap_translate);
  4447. snap_rotate = memnew(LineEdit);
  4448. snap_rotate->set_text("15");
  4449. snap_dialog_vbc->add_margin_child(TTR("Rotate Snap (deg.):"), snap_rotate);
  4450. snap_scale = memnew(LineEdit);
  4451. snap_scale->set_text("10");
  4452. snap_dialog_vbc->add_margin_child(TTR("Scale Snap (%):"), snap_scale);
  4453. /* SETTINGS DIALOG */
  4454. settings_dialog = memnew(ConfirmationDialog);
  4455. settings_dialog->set_title(TTR("Viewport Settings"));
  4456. add_child(settings_dialog);
  4457. settings_vbc = memnew(VBoxContainer);
  4458. settings_vbc->set_custom_minimum_size(Size2(200, 0) * EDSCALE);
  4459. settings_dialog->add_child(settings_vbc);
  4460. settings_fov = memnew(SpinBox);
  4461. settings_fov->set_max(MAX_FOV);
  4462. settings_fov->set_min(MIN_FOV);
  4463. settings_fov->set_step(0.01);
  4464. settings_fov->set_value(EDITOR_DEF("editors/3d/default_fov", 70.0));
  4465. settings_vbc->add_margin_child(TTR("Perspective FOV (deg.):"), settings_fov);
  4466. settings_znear = memnew(SpinBox);
  4467. settings_znear->set_max(MAX_Z);
  4468. settings_znear->set_min(MIN_Z);
  4469. settings_znear->set_step(0.01);
  4470. settings_znear->set_value(EDITOR_DEF("editors/3d/default_z_near", 0.05));
  4471. settings_vbc->add_margin_child(TTR("View Z-Near:"), settings_znear);
  4472. settings_zfar = memnew(SpinBox);
  4473. settings_zfar->set_max(MAX_Z);
  4474. settings_zfar->set_min(MIN_Z);
  4475. settings_zfar->set_step(0.01);
  4476. settings_zfar->set_value(EDITOR_DEF("editors/3d/default_z_far", 1500));
  4477. settings_vbc->add_margin_child(TTR("View Z-Far:"), settings_zfar);
  4478. /* XFORM DIALOG */
  4479. xform_dialog = memnew(ConfirmationDialog);
  4480. xform_dialog->set_title(TTR("Transform Change"));
  4481. add_child(xform_dialog);
  4482. VBoxContainer *xform_vbc = memnew(VBoxContainer);
  4483. xform_dialog->add_child(xform_vbc);
  4484. Label *l = memnew(Label);
  4485. l->set_text(TTR("Translate:"));
  4486. xform_vbc->add_child(l);
  4487. HBoxContainer *xform_hbc = memnew(HBoxContainer);
  4488. xform_vbc->add_child(xform_hbc);
  4489. for (int i = 0; i < 3; i++) {
  4490. xform_translate[i] = memnew(LineEdit);
  4491. xform_translate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  4492. xform_hbc->add_child(xform_translate[i]);
  4493. }
  4494. l = memnew(Label);
  4495. l->set_text(TTR("Rotate (deg.):"));
  4496. xform_vbc->add_child(l);
  4497. xform_hbc = memnew(HBoxContainer);
  4498. xform_vbc->add_child(xform_hbc);
  4499. for (int i = 0; i < 3; i++) {
  4500. xform_rotate[i] = memnew(LineEdit);
  4501. xform_rotate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  4502. xform_hbc->add_child(xform_rotate[i]);
  4503. }
  4504. l = memnew(Label);
  4505. l->set_text(TTR("Scale (ratio):"));
  4506. xform_vbc->add_child(l);
  4507. xform_hbc = memnew(HBoxContainer);
  4508. xform_vbc->add_child(xform_hbc);
  4509. for (int i = 0; i < 3; i++) {
  4510. xform_scale[i] = memnew(LineEdit);
  4511. xform_scale[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  4512. xform_hbc->add_child(xform_scale[i]);
  4513. }
  4514. l = memnew(Label);
  4515. l->set_text(TTR("Transform Type"));
  4516. xform_vbc->add_child(l);
  4517. xform_type = memnew(OptionButton);
  4518. xform_type->set_h_size_flags(SIZE_EXPAND_FILL);
  4519. xform_type->add_item(TTR("Pre"));
  4520. xform_type->add_item(TTR("Post"));
  4521. xform_vbc->add_child(xform_type);
  4522. xform_dialog->connect("confirmed", this, "_xform_dialog_action");
  4523. scenario_debug = VisualServer::SCENARIO_DEBUG_DISABLED;
  4524. selected = NULL;
  4525. set_process_unhandled_key_input(true);
  4526. add_to_group("_spatial_editor_group");
  4527. EDITOR_DEF("editors/3d/manipulator_gizmo_size", 80);
  4528. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "editors/3d/manipulator_gizmo_size", PROPERTY_HINT_RANGE, "16,1024,1"));
  4529. EDITOR_DEF("editors/3d/manipulator_gizmo_opacity", 0.4);
  4530. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::REAL, "editors/3d/manipulator_gizmo_opacity", PROPERTY_HINT_RANGE, "0,1,0.01"));
  4531. over_gizmo_handle = -1;
  4532. }
  4533. SpatialEditor::~SpatialEditor() {
  4534. memdelete(preview_node);
  4535. }
  4536. void SpatialEditorPlugin::make_visible(bool p_visible) {
  4537. if (p_visible) {
  4538. spatial_editor->show();
  4539. spatial_editor->set_process(true);
  4540. } else {
  4541. spatial_editor->hide();
  4542. spatial_editor->set_process(false);
  4543. }
  4544. }
  4545. void SpatialEditorPlugin::edit(Object *p_object) {
  4546. spatial_editor->edit(Object::cast_to<Spatial>(p_object));
  4547. }
  4548. bool SpatialEditorPlugin::handles(Object *p_object) const {
  4549. return p_object->is_class("Spatial");
  4550. }
  4551. Dictionary SpatialEditorPlugin::get_state() const {
  4552. return spatial_editor->get_state();
  4553. }
  4554. void SpatialEditorPlugin::set_state(const Dictionary &p_state) {
  4555. spatial_editor->set_state(p_state);
  4556. }
  4557. void SpatialEditor::snap_cursor_to_plane(const Plane &p_plane) {
  4558. //cursor.pos=p_plane.project(cursor.pos);
  4559. }
  4560. Vector3 SpatialEditor::snap_point(Vector3 p_target, Vector3 p_start) const {
  4561. if (is_snap_enabled()) {
  4562. p_target.x = Math::snap_scalar(0.0, get_translate_snap(), p_target.x);
  4563. p_target.y = Math::snap_scalar(0.0, get_translate_snap(), p_target.y);
  4564. p_target.z = Math::snap_scalar(0.0, get_translate_snap(), p_target.z);
  4565. }
  4566. return p_target;
  4567. }
  4568. float SpatialEditor::get_translate_snap() const {
  4569. float snap_value;
  4570. if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
  4571. snap_value = snap_translate->get_text().to_double() / 10.0;
  4572. } else {
  4573. snap_value = snap_translate->get_text().to_double();
  4574. }
  4575. return snap_value;
  4576. }
  4577. float SpatialEditor::get_rotate_snap() const {
  4578. float snap_value;
  4579. if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
  4580. snap_value = snap_rotate->get_text().to_double() / 3.0;
  4581. } else {
  4582. snap_value = snap_rotate->get_text().to_double();
  4583. }
  4584. return snap_value;
  4585. }
  4586. float SpatialEditor::get_scale_snap() const {
  4587. float snap_value;
  4588. if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
  4589. snap_value = snap_scale->get_text().to_double() / 2.0;
  4590. } else {
  4591. snap_value = snap_scale->get_text().to_double();
  4592. }
  4593. return snap_value;
  4594. }
  4595. void SpatialEditorPlugin::_bind_methods() {
  4596. ClassDB::bind_method("snap_cursor_to_plane", &SpatialEditorPlugin::snap_cursor_to_plane);
  4597. }
  4598. void SpatialEditorPlugin::snap_cursor_to_plane(const Plane &p_plane) {
  4599. spatial_editor->snap_cursor_to_plane(p_plane);
  4600. }
  4601. struct _GizmoPluginPriorityComparator {
  4602. bool operator()(const Ref<EditorSpatialGizmoPlugin> &p_a, const Ref<EditorSpatialGizmoPlugin> &p_b) const {
  4603. if (p_a->get_priority() == p_b->get_priority()) {
  4604. return p_a->get_name() < p_b->get_name();
  4605. }
  4606. return p_a->get_priority() > p_b->get_priority();
  4607. }
  4608. };
  4609. struct _GizmoPluginNameComparator {
  4610. bool operator()(const Ref<EditorSpatialGizmoPlugin> &p_a, const Ref<EditorSpatialGizmoPlugin> &p_b) const {
  4611. return p_a->get_name() < p_b->get_name();
  4612. }
  4613. };
  4614. void SpatialEditor::add_gizmo_plugin(Ref<EditorSpatialGizmoPlugin> p_plugin) {
  4615. ERR_FAIL_NULL(p_plugin.ptr());
  4616. gizmo_plugins_by_priority.push_back(p_plugin);
  4617. gizmo_plugins_by_priority.sort_custom<_GizmoPluginPriorityComparator>();
  4618. gizmo_plugins_by_name.push_back(p_plugin);
  4619. gizmo_plugins_by_name.sort_custom<_GizmoPluginNameComparator>();
  4620. _update_gizmos_menu();
  4621. SpatialEditor::get_singleton()->update_all_gizmos();
  4622. }
  4623. void SpatialEditor::remove_gizmo_plugin(Ref<EditorSpatialGizmoPlugin> p_plugin) {
  4624. gizmo_plugins_by_priority.erase(p_plugin);
  4625. gizmo_plugins_by_name.erase(p_plugin);
  4626. _update_gizmos_menu();
  4627. }
  4628. SpatialEditorPlugin::SpatialEditorPlugin(EditorNode *p_node) {
  4629. editor = p_node;
  4630. spatial_editor = memnew(SpatialEditor(p_node));
  4631. spatial_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  4632. editor->get_viewport()->add_child(spatial_editor);
  4633. spatial_editor->hide();
  4634. spatial_editor->connect("transform_key_request", editor->get_inspector_dock(), "_transform_keyed");
  4635. }
  4636. SpatialEditorPlugin::~SpatialEditorPlugin() {
  4637. }
  4638. void EditorSpatialGizmoPlugin::create_material(const String &p_name, const Color &p_color, bool p_billboard, bool p_on_top, bool p_use_vertex_color) {
  4639. Color instanced_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/instanced", Color(0.7, 0.7, 0.7, 0.6));
  4640. Vector<Ref<SpatialMaterial> > mats;
  4641. for (int i = 0; i < 4; i++) {
  4642. bool selected = i % 2 == 1;
  4643. bool instanced = i < 2;
  4644. Ref<SpatialMaterial> material = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  4645. Color color = instanced ? instanced_color : p_color;
  4646. if (!selected) {
  4647. color.a *= 0.3;
  4648. }
  4649. material->set_albedo(color);
  4650. material->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  4651. material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  4652. material->set_render_priority(SpatialMaterial::RENDER_PRIORITY_MIN + 1);
  4653. if (p_use_vertex_color) {
  4654. material->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  4655. material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  4656. }
  4657. if (p_billboard) {
  4658. material->set_billboard_mode(SpatialMaterial::BILLBOARD_ENABLED);
  4659. }
  4660. if (p_on_top && selected) {
  4661. material->set_on_top_of_alpha();
  4662. }
  4663. mats.push_back(material);
  4664. }
  4665. materials[p_name] = mats;
  4666. }
  4667. void EditorSpatialGizmoPlugin::create_icon_material(const String &p_name, const Ref<Texture> &p_texture, bool p_on_top, const Color &p_albedo) {
  4668. Color instanced_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/instanced", Color(0.7, 0.7, 0.7, 0.6));
  4669. Vector<Ref<SpatialMaterial> > icons;
  4670. for (int i = 0; i < 4; i++) {
  4671. bool selected = i % 2 == 1;
  4672. bool instanced = i < 2;
  4673. Ref<SpatialMaterial> icon = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  4674. Color color = instanced ? instanced_color : p_albedo;
  4675. if (!selected) {
  4676. color.a *= 0.85;
  4677. }
  4678. icon->set_albedo(color);
  4679. icon->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  4680. icon->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  4681. icon->set_depth_draw_mode(SpatialMaterial::DEPTH_DRAW_DISABLED);
  4682. icon->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  4683. icon->set_texture(SpatialMaterial::TEXTURE_ALBEDO, p_texture);
  4684. icon->set_flag(SpatialMaterial::FLAG_FIXED_SIZE, true);
  4685. icon->set_billboard_mode(SpatialMaterial::BILLBOARD_ENABLED);
  4686. icon->set_render_priority(SpatialMaterial::RENDER_PRIORITY_MIN);
  4687. if (p_on_top && selected) {
  4688. icon->set_on_top_of_alpha();
  4689. }
  4690. icons.push_back(icon);
  4691. }
  4692. materials[p_name] = icons;
  4693. }
  4694. void EditorSpatialGizmoPlugin::create_handle_material(const String &p_name, bool p_billboard) {
  4695. Ref<SpatialMaterial> handle_material = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  4696. handle_material->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  4697. handle_material->set_flag(SpatialMaterial::FLAG_USE_POINT_SIZE, true);
  4698. Ref<Texture> handle_t = SpatialEditor::get_singleton()->get_icon("Editor3DHandle", "EditorIcons");
  4699. handle_material->set_point_size(handle_t->get_width());
  4700. handle_material->set_texture(SpatialMaterial::TEXTURE_ALBEDO, handle_t);
  4701. handle_material->set_albedo(Color(1, 1, 1));
  4702. handle_material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  4703. handle_material->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  4704. handle_material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  4705. handle_material->set_on_top_of_alpha();
  4706. if (p_billboard) {
  4707. handle_material->set_billboard_mode(SpatialMaterial::BILLBOARD_ENABLED);
  4708. handle_material->set_on_top_of_alpha();
  4709. }
  4710. materials[p_name] = Vector<Ref<SpatialMaterial> >();
  4711. materials[p_name].push_back(handle_material);
  4712. }
  4713. void EditorSpatialGizmoPlugin::add_material(const String &p_name, Ref<SpatialMaterial> p_material) {
  4714. materials[p_name] = Vector<Ref<SpatialMaterial> >();
  4715. materials[p_name].push_back(p_material);
  4716. }
  4717. Ref<SpatialMaterial> EditorSpatialGizmoPlugin::get_material(const String &p_name, const Ref<EditorSpatialGizmo> &p_gizmo) {
  4718. ERR_FAIL_COND_V(!materials.has(p_name), Ref<SpatialMaterial>());
  4719. ERR_FAIL_COND_V(materials[p_name].size() == 0, Ref<SpatialMaterial>());
  4720. if (p_gizmo.is_null() || materials[p_name].size() == 1) return materials[p_name][0];
  4721. int index = (p_gizmo->is_selected() ? 1 : 0) + (p_gizmo->is_editable() ? 2 : 0);
  4722. Ref<SpatialMaterial> mat = materials[p_name][index];
  4723. if (current_state == ON_TOP && p_gizmo->is_selected()) {
  4724. mat->set_flag(SpatialMaterial::FLAG_DISABLE_DEPTH_TEST, true);
  4725. } else {
  4726. mat->set_flag(SpatialMaterial::FLAG_DISABLE_DEPTH_TEST, false);
  4727. }
  4728. return mat;
  4729. }
  4730. String EditorSpatialGizmoPlugin::get_name() const {
  4731. if (get_script_instance() && get_script_instance()->has_method("get_name")) {
  4732. return get_script_instance()->call("get_name");
  4733. }
  4734. return TTR("Nameless gizmo");
  4735. }
  4736. int EditorSpatialGizmoPlugin::get_priority() const {
  4737. if (get_script_instance() && get_script_instance()->has_method("get_priority")) {
  4738. return get_script_instance()->call("get_priority");
  4739. }
  4740. return 0;
  4741. }
  4742. Ref<EditorSpatialGizmo> EditorSpatialGizmoPlugin::get_gizmo(Spatial *p_spatial) {
  4743. if (get_script_instance() && get_script_instance()->has_method("get_gizmo")) {
  4744. return get_script_instance()->call("get_gizmo", p_spatial);
  4745. }
  4746. Ref<EditorSpatialGizmo> ref = create_gizmo(p_spatial);
  4747. if (ref.is_null()) return ref;
  4748. ref->set_plugin(this);
  4749. ref->set_spatial_node(p_spatial);
  4750. ref->set_hidden(current_state == HIDDEN);
  4751. current_gizmos.push_back(ref.ptr());
  4752. return ref;
  4753. }
  4754. void EditorSpatialGizmoPlugin::_bind_methods() {
  4755. #define GIZMO_REF PropertyInfo(Variant::OBJECT, "gizmo", PROPERTY_HINT_RESOURCE_TYPE, "EditorSpatialGizmo")
  4756. BIND_VMETHOD(MethodInfo(Variant::BOOL, "has_gizmo", PropertyInfo(Variant::OBJECT, "spatial", PROPERTY_HINT_RESOURCE_TYPE, "Spatial")));
  4757. BIND_VMETHOD(MethodInfo(GIZMO_REF, "create_gizmo", PropertyInfo(Variant::OBJECT, "spatial", PROPERTY_HINT_RESOURCE_TYPE, "Spatial")));
  4758. ClassDB::bind_method(D_METHOD("create_material", "name", "color", "billboard", "on_top", "use_vertex_color"), &EditorSpatialGizmoPlugin::create_material, DEFVAL(false), DEFVAL(false), DEFVAL(false));
  4759. ClassDB::bind_method(D_METHOD("create_icon_material", "name", "texture", "on_top", "color"), &EditorSpatialGizmoPlugin::create_icon_material, DEFVAL(false), DEFVAL(Color(1, 1, 1, 1)));
  4760. ClassDB::bind_method(D_METHOD("create_handle_material", "name", "billboard"), &EditorSpatialGizmoPlugin::create_handle_material, DEFVAL(false));
  4761. ClassDB::bind_method(D_METHOD("add_material", "name", "material"), &EditorSpatialGizmoPlugin::add_material);
  4762. ClassDB::bind_method(D_METHOD("get_material", "name", "gizmo"), &EditorSpatialGizmoPlugin::get_material); //, DEFVAL(Ref<EditorSpatialGizmo>()));
  4763. BIND_VMETHOD(MethodInfo(Variant::STRING, "get_name"));
  4764. BIND_VMETHOD(MethodInfo(Variant::STRING, "get_priority"));
  4765. BIND_VMETHOD(MethodInfo(Variant::BOOL, "can_be_hidden"));
  4766. BIND_VMETHOD(MethodInfo(Variant::BOOL, "is_selectable_when_hidden"));
  4767. BIND_VMETHOD(MethodInfo("redraw", GIZMO_REF));
  4768. BIND_VMETHOD(MethodInfo(Variant::STRING, "get_handle_name", GIZMO_REF, PropertyInfo(Variant::INT, "index")));
  4769. MethodInfo hvget(Variant::NIL, "get_handle_value", GIZMO_REF, PropertyInfo(Variant::INT, "index"));
  4770. hvget.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  4771. BIND_VMETHOD(hvget);
  4772. BIND_VMETHOD(MethodInfo("set_handle", GIZMO_REF, PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::OBJECT, "camera", PROPERTY_HINT_RESOURCE_TYPE, "Camera"), PropertyInfo(Variant::VECTOR2, "point")));
  4773. MethodInfo cm = MethodInfo("commit_handle", GIZMO_REF, PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::NIL, "restore"), PropertyInfo(Variant::BOOL, "cancel"));
  4774. cm.default_arguments.push_back(false);
  4775. BIND_VMETHOD(cm);
  4776. BIND_VMETHOD(MethodInfo(Variant::BOOL, "is_handle_highlighted", GIZMO_REF, PropertyInfo(Variant::INT, "index")));
  4777. #undef GIZMO_REF
  4778. }
  4779. bool EditorSpatialGizmoPlugin::has_gizmo(Spatial *p_spatial) {
  4780. if (get_script_instance() && get_script_instance()->has_method("has_gizmo")) {
  4781. return get_script_instance()->call("has_gizmo", p_spatial);
  4782. }
  4783. return false;
  4784. }
  4785. Ref<EditorSpatialGizmo> EditorSpatialGizmoPlugin::create_gizmo(Spatial *p_spatial) {
  4786. if (get_script_instance() && get_script_instance()->has_method("create_gizmo")) {
  4787. return get_script_instance()->call("create_gizmo", p_spatial);
  4788. }
  4789. Ref<EditorSpatialGizmo> ref;
  4790. if (has_gizmo(p_spatial)) ref.instance();
  4791. return ref;
  4792. }
  4793. bool EditorSpatialGizmoPlugin::can_be_hidden() const {
  4794. if (get_script_instance() && get_script_instance()->has_method("can_be_hidden")) {
  4795. return get_script_instance()->call("can_be_hidden");
  4796. }
  4797. return true;
  4798. }
  4799. bool EditorSpatialGizmoPlugin::is_selectable_when_hidden() const {
  4800. if (get_script_instance() && get_script_instance()->has_method("is_selectable_when_hidden")) {
  4801. return get_script_instance()->call("is_selectable_when_hidden");
  4802. }
  4803. return false;
  4804. }
  4805. void EditorSpatialGizmoPlugin::redraw(EditorSpatialGizmo *p_gizmo) {
  4806. if (get_script_instance() && get_script_instance()->has_method("redraw")) {
  4807. Ref<EditorSpatialGizmo> ref(p_gizmo);
  4808. get_script_instance()->call("redraw", ref);
  4809. }
  4810. }
  4811. String EditorSpatialGizmoPlugin::get_handle_name(const EditorSpatialGizmo *p_gizmo, int p_idx) const {
  4812. if (get_script_instance() && get_script_instance()->has_method("get_handle_name")) {
  4813. return get_script_instance()->call("get_handle_name", p_gizmo, p_idx);
  4814. }
  4815. return "";
  4816. }
  4817. Variant EditorSpatialGizmoPlugin::get_handle_value(EditorSpatialGizmo *p_gizmo, int p_idx) const {
  4818. if (get_script_instance() && get_script_instance()->has_method("get_handle_value")) {
  4819. return get_script_instance()->call("get_handle_value", p_gizmo, p_idx);
  4820. }
  4821. return Variant();
  4822. }
  4823. void EditorSpatialGizmoPlugin::set_handle(EditorSpatialGizmo *p_gizmo, int p_idx, Camera *p_camera, const Point2 &p_point) {
  4824. if (get_script_instance() && get_script_instance()->has_method("set_handle")) {
  4825. get_script_instance()->call("set_handle", p_gizmo, p_idx, p_camera, p_point);
  4826. }
  4827. }
  4828. void EditorSpatialGizmoPlugin::commit_handle(EditorSpatialGizmo *p_gizmo, int p_idx, const Variant &p_restore, bool p_cancel) {
  4829. if (get_script_instance() && get_script_instance()->has_method("commit_handle")) {
  4830. get_script_instance()->call("commit_handle", p_gizmo, p_idx, p_restore, p_cancel);
  4831. }
  4832. }
  4833. bool EditorSpatialGizmoPlugin::is_handle_highlighted(const EditorSpatialGizmo *p_gizmo, int p_idx) const {
  4834. if (get_script_instance() && get_script_instance()->has_method("is_handle_highlighted")) {
  4835. return get_script_instance()->call("is_handle_highlighted", p_gizmo, p_idx);
  4836. }
  4837. return false;
  4838. }
  4839. void EditorSpatialGizmoPlugin::set_state(int p_state) {
  4840. current_state = p_state;
  4841. for (int i = 0; i < current_gizmos.size(); ++i) {
  4842. current_gizmos[i]->set_hidden(current_state == HIDDEN);
  4843. }
  4844. }
  4845. int EditorSpatialGizmoPlugin::get_state() const {
  4846. return current_state;
  4847. }
  4848. void EditorSpatialGizmoPlugin::unregister_gizmo(EditorSpatialGizmo *p_gizmo) {
  4849. current_gizmos.erase(p_gizmo);
  4850. }
  4851. EditorSpatialGizmoPlugin::EditorSpatialGizmoPlugin() {
  4852. current_state = VISIBLE;
  4853. }
  4854. EditorSpatialGizmoPlugin::~EditorSpatialGizmoPlugin() {
  4855. for (int i = 0; i < current_gizmos.size(); ++i) {
  4856. current_gizmos[i]->set_plugin(NULL);
  4857. current_gizmos[i]->get_spatial_node()->set_gizmo(NULL);
  4858. }
  4859. SpatialEditor::get_singleton()->update_all_gizmos();
  4860. }