spatial_editor_plugin.cpp 255 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131
  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-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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_scale.h"
  39. #include "editor/editor_settings.h"
  40. #include "editor/plugins/animation_player_editor_plugin.h"
  41. #include "editor/plugins/script_editor_plugin.h"
  42. #include "editor/script_editor_debugger.h"
  43. #include "editor/spatial_editor_gizmos.h"
  44. #include "scene/3d/camera.h"
  45. #include "scene/3d/collision_shape.h"
  46. #include "scene/3d/mesh_instance.h"
  47. #include "scene/3d/physics_body.h"
  48. #include "scene/3d/room_manager.h"
  49. #include "scene/3d/visual_instance.h"
  50. #include "scene/gui/viewport_container.h"
  51. #include "scene/resources/packed_scene.h"
  52. #include "scene/resources/surface_tool.h"
  53. #define DISTANCE_DEFAULT 4
  54. #define GIZMO_ARROW_SIZE 0.35
  55. #define GIZMO_RING_HALF_WIDTH 0.1
  56. #define GIZMO_SCALE_DEFAULT 0.15
  57. #define GIZMO_PLANE_SIZE 0.2
  58. #define GIZMO_PLANE_DST 0.3
  59. #define GIZMO_CIRCLE_SIZE 1.1
  60. #define GIZMO_SCALE_OFFSET (GIZMO_CIRCLE_SIZE + 0.3)
  61. #define GIZMO_ARROW_OFFSET (GIZMO_CIRCLE_SIZE + 0.3)
  62. #define ZOOM_FREELOOK_MIN 0.01
  63. #define ZOOM_FREELOOK_MULTIPLIER 1.08
  64. #define ZOOM_FREELOOK_INDICATOR_DELAY_S 1.5
  65. #define ZOOM_FREELOOK_MAX 10'000
  66. #define MIN_Z 0.01
  67. #define MAX_Z 1000000.0
  68. #define MIN_FOV 0.01
  69. #define MAX_FOV 179
  70. void ViewportRotationControl::_notification(int p_what) {
  71. if (p_what == NOTIFICATION_ENTER_TREE) {
  72. axis_menu_options.clear();
  73. axis_menu_options.push_back(SpatialEditorViewport::VIEW_RIGHT);
  74. axis_menu_options.push_back(SpatialEditorViewport::VIEW_TOP);
  75. axis_menu_options.push_back(SpatialEditorViewport::VIEW_REAR);
  76. axis_menu_options.push_back(SpatialEditorViewport::VIEW_LEFT);
  77. axis_menu_options.push_back(SpatialEditorViewport::VIEW_BOTTOM);
  78. axis_menu_options.push_back(SpatialEditorViewport::VIEW_FRONT);
  79. axis_colors.clear();
  80. axis_colors.push_back(get_color("axis_x_color", "Editor"));
  81. axis_colors.push_back(get_color("axis_y_color", "Editor"));
  82. axis_colors.push_back(get_color("axis_z_color", "Editor"));
  83. update();
  84. if (!is_connected("mouse_exited", this, "_on_mouse_exited")) {
  85. connect("mouse_exited", this, "_on_mouse_exited");
  86. }
  87. }
  88. if (p_what == NOTIFICATION_DRAW && viewport != nullptr) {
  89. _draw();
  90. }
  91. }
  92. void ViewportRotationControl::_draw() {
  93. Vector2i center = get_size() / 2.0;
  94. float radius = get_size().x / 2.0;
  95. if (focused_axis > -2 || orbiting) {
  96. draw_circle(center, radius, Color(0.5, 0.5, 0.5, 0.25));
  97. }
  98. Vector<Axis2D> axis_to_draw;
  99. _get_sorted_axis(axis_to_draw);
  100. for (int i = 0; i < axis_to_draw.size(); ++i) {
  101. _draw_axis(axis_to_draw[i]);
  102. }
  103. }
  104. void ViewportRotationControl::_draw_axis(const Axis2D &p_axis) {
  105. const bool focused = focused_axis == p_axis.axis;
  106. const bool positive = p_axis.axis < 3;
  107. const int direction = p_axis.axis % 3;
  108. const Color axis_color = axis_colors[direction];
  109. const double alpha = focused ? 1.0 : ((p_axis.z_axis + 1.0) / 2.0) * 0.5 + 0.5;
  110. const Color c = focused ? Color(0.9, 0.9, 0.9) : Color(axis_color.r, axis_color.g, axis_color.b, alpha);
  111. if (positive) {
  112. // Draw axis lines for the positive axes.
  113. const Vector2i center = get_size() / 2.0;
  114. draw_line(center, p_axis.screen_point, c, 1.5 * EDSCALE, true);
  115. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS, c);
  116. // Draw the axis letter for the positive axes.
  117. const String axis_name = direction == 0 ? "X" : (direction == 1 ? "Y" : "Z");
  118. draw_char(get_font("rotation_control", "EditorFonts"), p_axis.screen_point + Vector2(-4.0, 5.0) * EDSCALE, axis_name, "", Color(0.0, 0.0, 0.0, alpha));
  119. } else {
  120. // Draw an outline around the negative axes.
  121. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS, c);
  122. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS * 0.8, c.darkened(0.4));
  123. }
  124. }
  125. void ViewportRotationControl::_get_sorted_axis(Vector<Axis2D> &r_axis) {
  126. Vector2i center = get_size() / 2.0;
  127. float radius = get_size().x / 2.0;
  128. float axis_radius = radius - AXIS_CIRCLE_RADIUS - 2.0 * EDSCALE;
  129. Basis camera_basis = viewport->to_camera_transform(viewport->cursor).get_basis().inverse();
  130. for (int i = 0; i < 3; ++i) {
  131. Vector3 axis_3d = camera_basis.get_axis(i);
  132. Vector2i axis_vector = Vector2(axis_3d.x, -axis_3d.y) * axis_radius;
  133. if (Math::abs(axis_3d.z) < 1.0) {
  134. Axis2D pos_axis;
  135. pos_axis.axis = i;
  136. pos_axis.screen_point = center + axis_vector;
  137. pos_axis.z_axis = axis_3d.z;
  138. r_axis.push_back(pos_axis);
  139. Axis2D neg_axis;
  140. neg_axis.axis = i + 3;
  141. neg_axis.screen_point = center - axis_vector;
  142. neg_axis.z_axis = -axis_3d.z;
  143. r_axis.push_back(neg_axis);
  144. } else {
  145. // Special case when the camera is aligned with one axis
  146. Axis2D axis;
  147. axis.axis = i + (axis_3d.z < 0 ? 0 : 3);
  148. axis.screen_point = center;
  149. axis.z_axis = 1.0;
  150. r_axis.push_back(axis);
  151. }
  152. }
  153. r_axis.sort_custom<Axis2DCompare>();
  154. }
  155. void ViewportRotationControl::_gui_input(Ref<InputEvent> p_event) {
  156. const Ref<InputEventMouseButton> mb = p_event;
  157. if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT) {
  158. Vector2 pos = mb->get_position();
  159. if (mb->is_pressed()) {
  160. if (pos.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
  161. orbiting = true;
  162. }
  163. } else {
  164. if (focused_axis > -1) {
  165. viewport->_menu_option(axis_menu_options[focused_axis]);
  166. _update_focus();
  167. }
  168. orbiting = false;
  169. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
  170. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  171. Input::get_singleton()->warp_mouse_position(orbiting_mouse_start);
  172. }
  173. }
  174. }
  175. const Ref<InputEventMouseMotion> mm = p_event;
  176. if (mm.is_valid()) {
  177. if (orbiting) {
  178. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_VISIBLE) {
  179. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
  180. orbiting_mouse_start = mm->get_global_position();
  181. }
  182. viewport->_nav_orbit(mm, viewport->_get_warped_mouse_motion(mm));
  183. focused_axis = -1;
  184. } else {
  185. _update_focus();
  186. }
  187. }
  188. }
  189. void ViewportRotationControl::_update_focus() {
  190. int original_focus = focused_axis;
  191. focused_axis = -2;
  192. Vector2 mouse_pos = get_local_mouse_position();
  193. if (mouse_pos.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
  194. focused_axis = -1;
  195. }
  196. Vector<Axis2D> axes;
  197. _get_sorted_axis(axes);
  198. for (int i = 0; i < axes.size(); i++) {
  199. const Axis2D &axis = axes[i];
  200. if (mouse_pos.distance_to(axis.screen_point) < AXIS_CIRCLE_RADIUS) {
  201. focused_axis = axis.axis;
  202. }
  203. }
  204. if (focused_axis != original_focus) {
  205. update();
  206. }
  207. }
  208. void ViewportRotationControl::_on_mouse_exited() {
  209. focused_axis = -2;
  210. update();
  211. }
  212. void ViewportRotationControl::set_viewport(SpatialEditorViewport *p_viewport) {
  213. viewport = p_viewport;
  214. }
  215. void ViewportRotationControl::_bind_methods() {
  216. ClassDB::bind_method(D_METHOD("_gui_input"), &ViewportRotationControl::_gui_input);
  217. ClassDB::bind_method(D_METHOD("_on_mouse_exited"), &ViewportRotationControl::_on_mouse_exited);
  218. }
  219. void SpatialEditorViewport::_update_camera(float p_interp_delta) {
  220. bool is_orthogonal = camera->get_projection() == Camera::PROJECTION_ORTHOGONAL;
  221. Cursor old_camera_cursor = camera_cursor;
  222. camera_cursor = cursor;
  223. if (p_interp_delta > 0) {
  224. //-------
  225. // Perform smoothing
  226. if (is_freelook_active()) {
  227. // Higher inertia should increase "lag" (lerp with factor between 0 and 1)
  228. // 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.
  229. const real_t inertia = EDITOR_GET("editors/3d/freelook/freelook_inertia");
  230. real_t factor = (1.0 / inertia) * p_interp_delta;
  231. // We interpolate a different point here, because in freelook mode the focus point (cursor.pos) orbits around eye_pos
  232. camera_cursor.eye_pos = old_camera_cursor.eye_pos.linear_interpolate(cursor.eye_pos, CLAMP(factor, 0, 1));
  233. const float orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/orbit_inertia");
  234. camera_cursor.x_rot = Math::lerp(old_camera_cursor.x_rot, cursor.x_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  235. camera_cursor.y_rot = Math::lerp(old_camera_cursor.y_rot, cursor.y_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  236. if (Math::abs(camera_cursor.x_rot - cursor.x_rot) < 0.1) {
  237. camera_cursor.x_rot = cursor.x_rot;
  238. }
  239. if (Math::abs(camera_cursor.y_rot - cursor.y_rot) < 0.1) {
  240. camera_cursor.y_rot = cursor.y_rot;
  241. }
  242. Vector3 forward = to_camera_transform(camera_cursor).basis.xform(Vector3(0, 0, -1));
  243. camera_cursor.pos = camera_cursor.eye_pos + forward * camera_cursor.distance;
  244. } else {
  245. const float orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/orbit_inertia");
  246. const float translation_inertia = EDITOR_GET("editors/3d/navigation_feel/translation_inertia");
  247. const float zoom_inertia = EDITOR_GET("editors/3d/navigation_feel/zoom_inertia");
  248. camera_cursor.x_rot = Math::lerp(old_camera_cursor.x_rot, cursor.x_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  249. camera_cursor.y_rot = Math::lerp(old_camera_cursor.y_rot, cursor.y_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  250. if (Math::abs(camera_cursor.x_rot - cursor.x_rot) < 0.1) {
  251. camera_cursor.x_rot = cursor.x_rot;
  252. }
  253. if (Math::abs(camera_cursor.y_rot - cursor.y_rot) < 0.1) {
  254. camera_cursor.y_rot = cursor.y_rot;
  255. }
  256. camera_cursor.pos = old_camera_cursor.pos.linear_interpolate(cursor.pos, MIN(1.f, p_interp_delta * (1 / translation_inertia)));
  257. camera_cursor.distance = Math::lerp(old_camera_cursor.distance, cursor.distance, MIN(1.f, p_interp_delta * (1 / zoom_inertia)));
  258. }
  259. }
  260. //-------
  261. // Apply camera transform
  262. real_t tolerance = 0.001;
  263. bool equal = true;
  264. if (!Math::is_equal_approx(old_camera_cursor.x_rot, camera_cursor.x_rot, tolerance) || !Math::is_equal_approx(old_camera_cursor.y_rot, camera_cursor.y_rot, tolerance)) {
  265. equal = false;
  266. } else if (!old_camera_cursor.pos.is_equal_approx(camera_cursor.pos)) {
  267. equal = false;
  268. } else if (!Math::is_equal_approx(old_camera_cursor.distance, camera_cursor.distance, tolerance)) {
  269. equal = false;
  270. }
  271. if (!equal || p_interp_delta == 0 || is_orthogonal != orthogonal) {
  272. camera->set_global_transform(to_camera_transform(camera_cursor));
  273. if (orthogonal) {
  274. float half_fov = Math::deg2rad(get_fov()) / 2.0;
  275. float height = 2.0 * cursor.distance * Math::tan(half_fov);
  276. camera->set_orthogonal(height, get_znear(), get_zfar());
  277. } else {
  278. camera->set_perspective(get_fov(), get_znear(), get_zfar());
  279. }
  280. update_transform_gizmo_view();
  281. rotation_control->update();
  282. spatial_editor->update_grid();
  283. }
  284. }
  285. Transform SpatialEditorViewport::to_camera_transform(const Cursor &p_cursor) const {
  286. Transform camera_transform;
  287. camera_transform.translate(p_cursor.pos);
  288. camera_transform.basis.rotate(Vector3(1, 0, 0), -p_cursor.x_rot);
  289. camera_transform.basis.rotate(Vector3(0, 1, 0), -p_cursor.y_rot);
  290. if (orthogonal) {
  291. camera_transform.translate(0, 0, (get_zfar() - get_znear()) / 2.0);
  292. } else {
  293. camera_transform.translate(0, 0, p_cursor.distance);
  294. }
  295. return camera_transform;
  296. }
  297. int SpatialEditorViewport::get_selected_count() const {
  298. Map<Node *, Object *> &selection = editor_selection->get_selection();
  299. int count = 0;
  300. for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
  301. Spatial *sp = Object::cast_to<Spatial>(E->key());
  302. if (!sp) {
  303. continue;
  304. }
  305. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  306. if (!se) {
  307. continue;
  308. }
  309. count++;
  310. }
  311. return count;
  312. }
  313. float SpatialEditorViewport::get_znear() const {
  314. return CLAMP(spatial_editor->get_znear(), MIN_Z, MAX_Z);
  315. }
  316. float SpatialEditorViewport::get_zfar() const {
  317. return CLAMP(spatial_editor->get_zfar(), MIN_Z, MAX_Z);
  318. }
  319. float SpatialEditorViewport::get_fov() const {
  320. return CLAMP(spatial_editor->get_fov(), MIN_FOV, MAX_FOV);
  321. }
  322. Transform SpatialEditorViewport::_get_camera_transform() const {
  323. return camera->get_global_transform();
  324. }
  325. Vector3 SpatialEditorViewport::_get_camera_position() const {
  326. return _get_camera_transform().origin;
  327. }
  328. Point2 SpatialEditorViewport::_point_to_screen(const Vector3 &p_point) {
  329. return camera->unproject_position(p_point) * viewport_container->get_stretch_shrink();
  330. }
  331. Vector3 SpatialEditorViewport::_get_ray_pos(const Vector2 &p_pos) const {
  332. return camera->project_ray_origin(p_pos / viewport_container->get_stretch_shrink());
  333. }
  334. Vector3 SpatialEditorViewport::_get_camera_normal() const {
  335. return -_get_camera_transform().basis.get_axis(2);
  336. }
  337. Vector3 SpatialEditorViewport::_get_ray(const Vector2 &p_pos) const {
  338. return camera->project_ray_normal(p_pos / viewport_container->get_stretch_shrink());
  339. }
  340. void SpatialEditorViewport::_clear_selected() {
  341. editor_selection->clear();
  342. }
  343. void SpatialEditorViewport::_select_clicked(bool p_append, bool p_single, bool p_allow_locked) {
  344. if (!clicked) {
  345. return;
  346. }
  347. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(clicked));
  348. Spatial *selected = Object::cast_to<Spatial>(node);
  349. if (!selected) {
  350. return;
  351. }
  352. if (!p_allow_locked) {
  353. // Replace the node by the group if grouped.
  354. while (node && node != editor->get_edited_scene()->get_parent()) {
  355. Spatial *selected_tmp = Object::cast_to<Spatial>(node);
  356. if (selected_tmp && node->has_meta("_edit_group_")) {
  357. selected = selected_tmp;
  358. }
  359. node = node->get_parent();
  360. }
  361. }
  362. if (p_allow_locked || !_is_node_locked(selected)) {
  363. _select(selected, clicked_wants_append, true);
  364. }
  365. }
  366. void SpatialEditorViewport::_select(Node *p_node, bool p_append, bool p_single) {
  367. if (!p_append) {
  368. editor_selection->clear();
  369. }
  370. if (editor_selection->is_selected(p_node)) {
  371. //erase
  372. editor_selection->remove_node(p_node);
  373. } else {
  374. editor_selection->add_node(p_node);
  375. }
  376. if (p_single) {
  377. if (Engine::get_singleton()->is_editor_hint()) {
  378. editor->call("edit_node", p_node);
  379. }
  380. }
  381. }
  382. ObjectID SpatialEditorViewport::_select_ray(const Point2 &p_pos, bool p_append, bool &r_includes_current, int *r_gizmo_handle, bool p_alt_select) {
  383. if (r_gizmo_handle) {
  384. *r_gizmo_handle = -1;
  385. }
  386. Vector3 ray = _get_ray(p_pos);
  387. Vector3 pos = _get_ray_pos(p_pos);
  388. Vector2 shrinked_pos = p_pos / viewport_container->get_stretch_shrink();
  389. Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_ray(pos, ray, get_tree()->get_root()->get_world()->get_scenario());
  390. Set<Ref<EditorSpatialGizmo>> found_gizmos;
  391. Node *edited_scene = get_tree()->get_edited_scene_root();
  392. ObjectID closest = 0;
  393. Node *item = nullptr;
  394. float closest_dist = 1e20;
  395. int selected_handle = -1;
  396. for (int i = 0; i < instances.size(); i++) {
  397. Spatial *spat = Object::cast_to<Spatial>(ObjectDB::get_instance(instances[i]));
  398. if (!spat) {
  399. continue;
  400. }
  401. Ref<EditorSpatialGizmo> seg = spat->get_gizmo();
  402. if ((!seg.is_valid()) || found_gizmos.has(seg)) {
  403. continue;
  404. }
  405. found_gizmos.insert(seg);
  406. Vector3 point;
  407. Vector3 normal;
  408. int handle = -1;
  409. bool inters = seg->intersect_ray(camera, shrinked_pos, point, normal, &handle, p_alt_select);
  410. if (!inters) {
  411. continue;
  412. }
  413. float dist = pos.distance_to(point);
  414. if (dist < 0) {
  415. continue;
  416. }
  417. if (dist < closest_dist) {
  418. item = Object::cast_to<Node>(spat);
  419. if (item != edited_scene) {
  420. item = edited_scene->get_deepest_editable_node(item);
  421. }
  422. closest = item->get_instance_id();
  423. closest_dist = dist;
  424. selected_handle = handle;
  425. }
  426. }
  427. if (!item) {
  428. return 0;
  429. }
  430. if (!editor_selection->is_selected(item) || (r_gizmo_handle && selected_handle >= 0)) {
  431. if (r_gizmo_handle) {
  432. *r_gizmo_handle = selected_handle;
  433. }
  434. }
  435. return closest;
  436. }
  437. void SpatialEditorViewport::_find_items_at_pos(const Point2 &p_pos, bool &r_includes_current, Vector<_RayResult> &results, bool p_alt_select) {
  438. Vector3 ray = _get_ray(p_pos);
  439. Vector3 pos = _get_ray_pos(p_pos);
  440. Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_ray(pos, ray, get_tree()->get_root()->get_world()->get_scenario());
  441. Set<Ref<EditorSpatialGizmo>> found_gizmos;
  442. r_includes_current = false;
  443. for (int i = 0; i < instances.size(); i++) {
  444. Spatial *spat = Object::cast_to<Spatial>(ObjectDB::get_instance(instances[i]));
  445. if (!spat) {
  446. continue;
  447. }
  448. Ref<EditorSpatialGizmo> seg = spat->get_gizmo();
  449. if (!seg.is_valid()) {
  450. continue;
  451. }
  452. if (found_gizmos.has(seg)) {
  453. continue;
  454. }
  455. found_gizmos.insert(seg);
  456. Vector3 point;
  457. Vector3 normal;
  458. int handle = -1;
  459. bool inters = seg->intersect_ray(camera, p_pos, point, normal, nullptr, p_alt_select);
  460. if (!inters) {
  461. continue;
  462. }
  463. float dist = pos.distance_to(point);
  464. if (dist < 0) {
  465. continue;
  466. }
  467. if (editor_selection->is_selected(spat)) {
  468. r_includes_current = true;
  469. }
  470. _RayResult res;
  471. res.item = spat;
  472. res.depth = dist;
  473. res.handle = handle;
  474. results.push_back(res);
  475. }
  476. if (results.empty()) {
  477. return;
  478. }
  479. results.sort();
  480. }
  481. Vector3 SpatialEditorViewport::_get_screen_to_space(const Vector3 &p_vector3) {
  482. CameraMatrix cm;
  483. if (orthogonal) {
  484. cm.set_orthogonal(camera->get_size(), get_size().aspect(), get_znear() + p_vector3.z, get_zfar());
  485. } else {
  486. cm.set_perspective(get_fov(), get_size().aspect(), get_znear() + p_vector3.z, get_zfar());
  487. }
  488. Vector2 screen_he = cm.get_viewport_half_extents();
  489. Transform camera_transform;
  490. camera_transform.translate(cursor.pos);
  491. camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
  492. camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
  493. camera_transform.translate(0, 0, cursor.distance);
  494. return camera_transform.xform(Vector3(((p_vector3.x / get_size().width) * 2.0 - 1.0) * screen_he.x, ((1.0 - (p_vector3.y / get_size().height)) * 2.0 - 1.0) * screen_he.y, -(get_znear() + p_vector3.z)));
  495. }
  496. void SpatialEditorViewport::_select_region() {
  497. if (cursor.region_begin == cursor.region_end) {
  498. return; //nothing really
  499. }
  500. float z_offset = MAX(0.0, 5.0 - get_znear());
  501. Vector3 box[4] = {
  502. Vector3(
  503. MIN(cursor.region_begin.x, cursor.region_end.x),
  504. MIN(cursor.region_begin.y, cursor.region_end.y),
  505. z_offset),
  506. Vector3(
  507. MAX(cursor.region_begin.x, cursor.region_end.x),
  508. MIN(cursor.region_begin.y, cursor.region_end.y),
  509. z_offset),
  510. Vector3(
  511. MAX(cursor.region_begin.x, cursor.region_end.x),
  512. MAX(cursor.region_begin.y, cursor.region_end.y),
  513. z_offset),
  514. Vector3(
  515. MIN(cursor.region_begin.x, cursor.region_end.x),
  516. MAX(cursor.region_begin.y, cursor.region_end.y),
  517. z_offset)
  518. };
  519. Vector<Plane> frustum;
  520. Vector3 cam_pos = _get_camera_position();
  521. for (int i = 0; i < 4; i++) {
  522. Vector3 a = _get_screen_to_space(box[i]);
  523. Vector3 b = _get_screen_to_space(box[(i + 1) % 4]);
  524. if (orthogonal) {
  525. frustum.push_back(Plane(a, (a - b).normalized()));
  526. } else {
  527. frustum.push_back(Plane(a, b, cam_pos));
  528. }
  529. }
  530. Plane near(cam_pos, -_get_camera_normal());
  531. near.d -= get_znear();
  532. frustum.push_back(near);
  533. Plane far = -near;
  534. far.d += get_zfar();
  535. frustum.push_back(far);
  536. Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_convex(frustum, get_tree()->get_root()->get_world()->get_scenario());
  537. Vector<Node *> selected;
  538. Node *edited_scene = get_tree()->get_edited_scene_root();
  539. for (int i = 0; i < instances.size(); i++) {
  540. Spatial *sp = Object::cast_to<Spatial>(ObjectDB::get_instance(instances[i]));
  541. if (!sp || _is_node_locked(sp)) {
  542. continue;
  543. }
  544. Node *item = Object::cast_to<Node>(sp);
  545. if (item != edited_scene) {
  546. item = edited_scene->get_deepest_editable_node(item);
  547. }
  548. // Replace the node by the group if grouped
  549. if (item->is_class("Spatial")) {
  550. Spatial *sel = Object::cast_to<Spatial>(item);
  551. while (item && item != editor->get_edited_scene()->get_parent()) {
  552. Spatial *selected_tmp = Object::cast_to<Spatial>(item);
  553. if (selected_tmp && item->has_meta("_edit_group_")) {
  554. sel = selected_tmp;
  555. }
  556. item = item->get_parent();
  557. }
  558. item = sel;
  559. }
  560. if (selected.find(item) != -1) {
  561. continue;
  562. }
  563. if (_is_node_locked(item)) {
  564. continue;
  565. }
  566. Ref<EditorSpatialGizmo> seg = sp->get_gizmo();
  567. if (!seg.is_valid()) {
  568. continue;
  569. }
  570. if (seg->intersect_frustum(camera, frustum)) {
  571. selected.push_back(item);
  572. }
  573. }
  574. bool single = selected.size() == 1;
  575. for (int i = 0; i < selected.size(); i++) {
  576. _select(selected[i], true, single);
  577. }
  578. }
  579. void SpatialEditorViewport::_update_name() {
  580. String name;
  581. switch (view_type) {
  582. case VIEW_TYPE_USER: {
  583. if (orthogonal) {
  584. name = TTR("Orthogonal");
  585. } else {
  586. name = TTR("Perspective");
  587. }
  588. } break;
  589. case VIEW_TYPE_TOP: {
  590. if (orthogonal) {
  591. name = TTR("Top Orthogonal");
  592. } else {
  593. name = TTR("Top Perspective");
  594. }
  595. } break;
  596. case VIEW_TYPE_BOTTOM: {
  597. if (orthogonal) {
  598. name = TTR("Bottom Orthogonal");
  599. } else {
  600. name = TTR("Bottom Perspective");
  601. }
  602. } break;
  603. case VIEW_TYPE_LEFT: {
  604. if (orthogonal) {
  605. name = TTR("Left Orthogonal");
  606. } else {
  607. name = TTR("Left Perspective");
  608. }
  609. } break;
  610. case VIEW_TYPE_RIGHT: {
  611. if (orthogonal) {
  612. name = TTR("Right Orthogonal");
  613. } else {
  614. name = TTR("Right Perspective");
  615. }
  616. } break;
  617. case VIEW_TYPE_FRONT: {
  618. if (orthogonal) {
  619. name = TTR("Front Orthogonal");
  620. } else {
  621. name = TTR("Front Perspective");
  622. }
  623. } break;
  624. case VIEW_TYPE_REAR: {
  625. if (orthogonal) {
  626. name = TTR("Rear Orthogonal");
  627. } else {
  628. name = TTR("Rear Perspective");
  629. }
  630. } break;
  631. }
  632. if (auto_orthogonal) {
  633. // TRANSLATORS: This will be appended to the view name when Auto Orthogonal is enabled.
  634. name += TTR(" [auto]");
  635. }
  636. if (RoomManager::static_rooms_get_active_and_loaded()) {
  637. // TRANSLATORS: This will be appended to the view name when Portal Occulusion is enabled.
  638. name += TTR(" [portals active]");
  639. }
  640. view_menu->set_text(name);
  641. view_menu->set_size(Vector2(0, 0)); // resets the button size
  642. }
  643. void SpatialEditorViewport::_compute_edit(const Point2 &p_point) {
  644. _edit.click_ray = _get_ray(Vector2(p_point.x, p_point.y));
  645. _edit.click_ray_pos = _get_ray_pos(Vector2(p_point.x, p_point.y));
  646. _edit.plane = TRANSFORM_VIEW;
  647. spatial_editor->update_transform_gizmo();
  648. _edit.center = spatial_editor->get_gizmo_transform().origin;
  649. List<Node *> &selection = editor_selection->get_selected_node_list();
  650. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  651. Spatial *sp = Object::cast_to<Spatial>(E->get());
  652. if (!sp) {
  653. continue;
  654. }
  655. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  656. if (!se) {
  657. continue;
  658. }
  659. se->original = se->sp->get_global_gizmo_transform();
  660. se->original_local = se->sp->get_local_gizmo_transform();
  661. }
  662. }
  663. static int _get_key_modifier_setting(const String &p_property) {
  664. switch (EditorSettings::get_singleton()->get(p_property).operator int()) {
  665. case 0:
  666. return 0;
  667. case 1:
  668. return KEY_SHIFT;
  669. case 2:
  670. return KEY_ALT;
  671. case 3:
  672. return KEY_META;
  673. case 4:
  674. return KEY_CONTROL;
  675. }
  676. return 0;
  677. }
  678. static int _get_key_modifier(Ref<InputEventWithModifiers> e) {
  679. if (e->get_shift()) {
  680. return KEY_SHIFT;
  681. }
  682. if (e->get_alt()) {
  683. return KEY_ALT;
  684. }
  685. if (e->get_control()) {
  686. return KEY_CONTROL;
  687. }
  688. if (e->get_metakey()) {
  689. return KEY_META;
  690. }
  691. return 0;
  692. }
  693. bool SpatialEditorViewport::_gizmo_select(const Vector2 &p_screenpos, bool p_highlight_only) {
  694. if (!spatial_editor->is_gizmo_visible()) {
  695. return false;
  696. }
  697. if (get_selected_count() == 0) {
  698. if (p_highlight_only) {
  699. spatial_editor->select_gizmo_highlight_axis(-1);
  700. }
  701. return false;
  702. }
  703. Vector3 ray_pos = _get_ray_pos(Vector2(p_screenpos.x, p_screenpos.y));
  704. Vector3 ray = _get_ray(Vector2(p_screenpos.x, p_screenpos.y));
  705. Transform gt = spatial_editor->get_gizmo_transform();
  706. float gs = gizmo_scale;
  707. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_MOVE) {
  708. int col_axis = -1;
  709. float col_d = 1e20;
  710. for (int i = 0; i < 3; i++) {
  711. Vector3 grabber_pos = gt.origin + gt.basis.get_axis(i) * gs * (GIZMO_ARROW_OFFSET + (GIZMO_ARROW_SIZE * 0.5));
  712. float grabber_radius = gs * GIZMO_ARROW_SIZE;
  713. Vector3 r;
  714. if (Geometry::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) {
  715. float d = r.distance_to(ray_pos);
  716. if (d < col_d) {
  717. col_d = d;
  718. col_axis = i;
  719. }
  720. }
  721. }
  722. bool is_plane_translate = false;
  723. // plane select
  724. if (col_axis == -1) {
  725. col_d = 1e20;
  726. for (int i = 0; i < 3; i++) {
  727. Vector3 ivec2 = gt.basis.get_axis((i + 1) % 3).normalized();
  728. Vector3 ivec3 = gt.basis.get_axis((i + 2) % 3).normalized();
  729. // Allow some tolerance to make the plane easier to click,
  730. // even if the click is actually slightly outside the plane.
  731. const Vector3 grabber_pos = gt.origin + (ivec2 + ivec3) * gs * (GIZMO_PLANE_SIZE + GIZMO_PLANE_DST * 0.6667);
  732. Vector3 r;
  733. Plane plane(gt.origin, gt.basis.get_axis(i).normalized());
  734. if (plane.intersects_ray(ray_pos, ray, &r)) {
  735. float dist = r.distance_to(grabber_pos);
  736. // Allow some tolerance to make the plane easier to click,
  737. // even if the click is actually slightly outside the plane.
  738. if (dist < (gs * GIZMO_PLANE_SIZE * 1.5)) {
  739. float d = ray_pos.distance_to(r);
  740. if (d < col_d) {
  741. col_d = d;
  742. col_axis = i;
  743. is_plane_translate = true;
  744. }
  745. }
  746. }
  747. }
  748. }
  749. if (col_axis != -1) {
  750. if (p_highlight_only) {
  751. spatial_editor->select_gizmo_highlight_axis(col_axis + (is_plane_translate ? 6 : 0));
  752. } else {
  753. //handle plane translate
  754. _edit.mode = TRANSFORM_TRANSLATE;
  755. _compute_edit(Point2(p_screenpos.x, p_screenpos.y));
  756. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis + (is_plane_translate ? 3 : 0));
  757. }
  758. return true;
  759. }
  760. }
  761. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_ROTATE) {
  762. int col_axis = -1;
  763. float col_d = 1e20;
  764. for (int i = 0; i < 3; i++) {
  765. Plane plane(gt.origin, gt.basis.get_axis(i).normalized());
  766. Vector3 r;
  767. if (!plane.intersects_ray(ray_pos, ray, &r)) {
  768. continue;
  769. }
  770. float dist = r.distance_to(gt.origin);
  771. Vector3 r_dir = (r - gt.origin).normalized();
  772. if (_get_camera_normal().dot(r_dir) <= 0.005) {
  773. if (dist > gs * (GIZMO_CIRCLE_SIZE - GIZMO_RING_HALF_WIDTH) && dist < gs * (GIZMO_CIRCLE_SIZE + GIZMO_RING_HALF_WIDTH)) {
  774. float d = ray_pos.distance_to(r);
  775. if (d < col_d) {
  776. col_d = d;
  777. col_axis = i;
  778. }
  779. }
  780. }
  781. }
  782. if (col_axis != -1) {
  783. if (p_highlight_only) {
  784. spatial_editor->select_gizmo_highlight_axis(col_axis + 3);
  785. } else {
  786. //handle rotate
  787. _edit.mode = TRANSFORM_ROTATE;
  788. _compute_edit(Point2(p_screenpos.x, p_screenpos.y));
  789. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis);
  790. }
  791. return true;
  792. }
  793. }
  794. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SCALE) {
  795. int col_axis = -1;
  796. float col_d = 1e20;
  797. for (int i = 0; i < 3; i++) {
  798. Vector3 grabber_pos = gt.origin + gt.basis.get_axis(i) * gs * GIZMO_SCALE_OFFSET;
  799. float grabber_radius = gs * GIZMO_ARROW_SIZE;
  800. Vector3 r;
  801. if (Geometry::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) {
  802. float d = r.distance_to(ray_pos);
  803. if (d < col_d) {
  804. col_d = d;
  805. col_axis = i;
  806. }
  807. }
  808. }
  809. bool is_plane_scale = false;
  810. // plane select
  811. if (col_axis == -1) {
  812. col_d = 1e20;
  813. for (int i = 0; i < 3; i++) {
  814. Vector3 ivec2 = gt.basis.get_axis((i + 1) % 3).normalized();
  815. Vector3 ivec3 = gt.basis.get_axis((i + 2) % 3).normalized();
  816. // Allow some tolerance to make the plane easier to click,
  817. // even if the click is actually slightly outside the plane.
  818. Vector3 grabber_pos = gt.origin + (ivec2 + ivec3) * gs * (GIZMO_PLANE_SIZE + GIZMO_PLANE_DST * 0.6667);
  819. Vector3 r;
  820. Plane plane(gt.origin, gt.basis.get_axis(i).normalized());
  821. if (plane.intersects_ray(ray_pos, ray, &r)) {
  822. float dist = r.distance_to(grabber_pos);
  823. // Allow some tolerance to make the plane easier to click,
  824. // even if the click is actually slightly outside the plane.
  825. if (dist < (gs * GIZMO_PLANE_SIZE * 1.5)) {
  826. float d = ray_pos.distance_to(r);
  827. if (d < col_d) {
  828. col_d = d;
  829. col_axis = i;
  830. is_plane_scale = true;
  831. }
  832. }
  833. }
  834. }
  835. }
  836. if (col_axis != -1) {
  837. if (p_highlight_only) {
  838. spatial_editor->select_gizmo_highlight_axis(col_axis + (is_plane_scale ? 12 : 9));
  839. } else {
  840. //handle scale
  841. _edit.mode = TRANSFORM_SCALE;
  842. _compute_edit(Point2(p_screenpos.x, p_screenpos.y));
  843. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis + (is_plane_scale ? 3 : 0));
  844. }
  845. return true;
  846. }
  847. }
  848. if (p_highlight_only) {
  849. spatial_editor->select_gizmo_highlight_axis(-1);
  850. }
  851. return false;
  852. }
  853. void SpatialEditorViewport::_surface_mouse_enter() {
  854. if (!surface->has_focus() && (!get_focus_owner() || !get_focus_owner()->is_text_field())) {
  855. surface->grab_focus();
  856. }
  857. }
  858. void SpatialEditorViewport::_surface_mouse_exit() {
  859. _remove_preview();
  860. }
  861. void SpatialEditorViewport::_surface_focus_enter() {
  862. view_menu->set_disable_shortcuts(false);
  863. }
  864. void SpatialEditorViewport::_surface_focus_exit() {
  865. view_menu->set_disable_shortcuts(true);
  866. }
  867. bool SpatialEditorViewport ::_is_node_locked(const Node *p_node) {
  868. return p_node->has_meta("_edit_lock_") && p_node->get_meta("_edit_lock_");
  869. }
  870. void SpatialEditorViewport::_list_select(Ref<InputEventMouseButton> b) {
  871. _find_items_at_pos(b->get_position(), clicked_includes_current, selection_results, b->get_shift());
  872. Node *scene = editor->get_edited_scene();
  873. for (int i = 0; i < selection_results.size(); i++) {
  874. Spatial *item = selection_results[i].item;
  875. if (item != scene && item->get_owner() != scene && item != scene->get_deepest_editable_node(item)) {
  876. //invalid result
  877. selection_results.remove(i);
  878. i--;
  879. }
  880. }
  881. clicked_wants_append = b->get_shift();
  882. bool allow_locked = b->get_alt() && spatial_editor->get_tool_mode() != SpatialEditor::TOOL_MODE_LIST_SELECT;
  883. if (selection_results.size() == 1) {
  884. clicked = selection_results[0].item->get_instance_id();
  885. selection_results.clear();
  886. if (clicked) {
  887. _select_clicked(clicked_wants_append, true, allow_locked);
  888. clicked = 0;
  889. }
  890. } else if (!selection_results.empty()) {
  891. NodePath root_path = get_tree()->get_edited_scene_root()->get_path();
  892. StringName root_name = root_path.get_name(root_path.get_name_count() - 1);
  893. for (int i = 0; i < selection_results.size(); i++) {
  894. Spatial *spat = selection_results[i].item;
  895. Ref<Texture> icon = EditorNode::get_singleton()->get_object_icon(spat, "Node");
  896. String node_path = "/" + root_name + "/" + root_path.rel_path_to(spat->get_path());
  897. int locked = 0;
  898. if (_is_node_locked(spat)) {
  899. locked = 1;
  900. } else {
  901. Node *ed_scene = editor->get_edited_scene();
  902. Node *node = spat;
  903. while (node && node != ed_scene->get_parent()) {
  904. Spatial *selected_tmp = Object::cast_to<Spatial>(node);
  905. if (selected_tmp && node->has_meta("_edit_group_")) {
  906. locked = 2;
  907. }
  908. node = node->get_parent();
  909. }
  910. }
  911. if (!allow_locked && locked > 0) {
  912. continue;
  913. }
  914. String suffix = String();
  915. if (locked == 1) {
  916. suffix = " (" + TTR("Locked") + ")";
  917. } else if (locked == 2) {
  918. suffix = " (" + TTR("Grouped") + ")";
  919. }
  920. selection_menu->add_item((String)spat->get_name() + suffix);
  921. selection_menu->set_item_icon(i, icon);
  922. selection_menu->set_item_metadata(i, node_path);
  923. selection_menu->set_item_tooltip(i, String(spat->get_name()) + "\nType: " + spat->get_class() + "\nPath: " + node_path);
  924. }
  925. if (selection_menu->get_item_count() > 0) {
  926. selection_menu->set_global_position(b->get_global_position());
  927. selection_menu->popup();
  928. }
  929. }
  930. }
  931. void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
  932. if (previewing) {
  933. return; //do NONE
  934. }
  935. {
  936. EditorNode *en = editor;
  937. EditorPluginList *force_input_forwarding_list = en->get_editor_plugins_force_input_forwarding();
  938. if (!force_input_forwarding_list->empty()) {
  939. bool discard = force_input_forwarding_list->forward_spatial_gui_input(camera, p_event, true);
  940. if (discard) {
  941. return;
  942. }
  943. }
  944. }
  945. {
  946. EditorNode *en = editor;
  947. EditorPluginList *over_plugin_list = en->get_editor_plugins_over();
  948. if (!over_plugin_list->empty()) {
  949. bool discard = over_plugin_list->forward_spatial_gui_input(camera, p_event, false);
  950. if (discard) {
  951. return;
  952. }
  953. }
  954. }
  955. Ref<InputEventMouseButton> b = p_event;
  956. if (b.is_valid()) {
  957. emit_signal("clicked", this);
  958. float zoom_factor = 1 + (ZOOM_FREELOOK_MULTIPLIER - 1) * b->get_factor();
  959. switch (b->get_button_index()) {
  960. case BUTTON_WHEEL_UP: {
  961. if (is_freelook_active()) {
  962. scale_freelook_speed(zoom_factor);
  963. } else {
  964. scale_cursor_distance(1.0 / zoom_factor);
  965. }
  966. } break;
  967. case BUTTON_WHEEL_DOWN: {
  968. if (is_freelook_active()) {
  969. scale_freelook_speed(1.0 / zoom_factor);
  970. } else {
  971. scale_cursor_distance(zoom_factor);
  972. }
  973. } break;
  974. case BUTTON_RIGHT: {
  975. NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  976. if (b->is_pressed() && _edit.gizmo.is_valid()) {
  977. //restore
  978. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_initial_value, true);
  979. _edit.gizmo = Ref<EditorSpatialGizmo>();
  980. }
  981. if (_edit.mode == TRANSFORM_NONE && b->is_pressed()) {
  982. if (b->get_alt()) {
  983. if (nav_scheme == NAVIGATION_MAYA) {
  984. break;
  985. }
  986. _list_select(b);
  987. return;
  988. }
  989. }
  990. if (_edit.mode != TRANSFORM_NONE && b->is_pressed()) {
  991. //cancel motion
  992. _edit.mode = TRANSFORM_NONE;
  993. List<Node *> &selection = editor_selection->get_selected_node_list();
  994. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  995. Spatial *sp = Object::cast_to<Spatial>(E->get());
  996. if (!sp) {
  997. continue;
  998. }
  999. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1000. if (!se) {
  1001. continue;
  1002. }
  1003. sp->set_global_transform(se->original);
  1004. }
  1005. surface->update();
  1006. set_message(TTR("Transform Aborted."), 3);
  1007. }
  1008. if (b->is_pressed()) {
  1009. const int mod = _get_key_modifier(b);
  1010. if (!orthogonal) {
  1011. if (mod == _get_key_modifier_setting("editors/3d/freelook/freelook_activation_modifier")) {
  1012. set_freelook_active(true);
  1013. }
  1014. }
  1015. } else {
  1016. set_freelook_active(false);
  1017. }
  1018. if (freelook_active && !surface->has_focus()) {
  1019. // Focus usually doesn't trigger on right-click, but in case of freelook it should,
  1020. // otherwise using keyboard navigation would misbehave
  1021. surface->grab_focus();
  1022. }
  1023. } break;
  1024. case BUTTON_MIDDLE: {
  1025. if (b->is_pressed() && _edit.mode != TRANSFORM_NONE) {
  1026. switch (_edit.plane) {
  1027. case TRANSFORM_VIEW: {
  1028. _edit.plane = TRANSFORM_X_AXIS;
  1029. set_message(TTR("X-Axis Transform."), 2);
  1030. view_type = VIEW_TYPE_USER;
  1031. _update_name();
  1032. } break;
  1033. case TRANSFORM_X_AXIS: {
  1034. _edit.plane = TRANSFORM_Y_AXIS;
  1035. set_message(TTR("Y-Axis Transform."), 2);
  1036. } break;
  1037. case TRANSFORM_Y_AXIS: {
  1038. _edit.plane = TRANSFORM_Z_AXIS;
  1039. set_message(TTR("Z-Axis Transform."), 2);
  1040. } break;
  1041. case TRANSFORM_Z_AXIS: {
  1042. _edit.plane = TRANSFORM_VIEW;
  1043. set_message(TTR("View Plane Transform."), 2);
  1044. } break;
  1045. case TRANSFORM_YZ:
  1046. case TRANSFORM_XZ:
  1047. case TRANSFORM_XY: {
  1048. } break;
  1049. }
  1050. }
  1051. } break;
  1052. case BUTTON_LEFT: {
  1053. if (b->is_pressed()) {
  1054. NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  1055. if ((nav_scheme == NAVIGATION_MAYA || nav_scheme == NAVIGATION_MODO) && b->get_alt()) {
  1056. break;
  1057. }
  1058. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_LIST_SELECT) {
  1059. _list_select(b);
  1060. break;
  1061. }
  1062. _edit.mouse_pos = b->get_position();
  1063. _edit.original_mouse_pos = b->get_position();
  1064. _edit.snap = spatial_editor->is_snap_enabled();
  1065. _edit.mode = TRANSFORM_NONE;
  1066. //gizmo has priority over everything
  1067. bool can_select_gizmos = true;
  1068. {
  1069. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  1070. can_select_gizmos = view_menu->get_popup()->is_item_checked(idx);
  1071. }
  1072. if (can_select_gizmos && spatial_editor->get_selected()) {
  1073. Ref<EditorSpatialGizmo> seg = spatial_editor->get_selected()->get_gizmo();
  1074. if (seg.is_valid()) {
  1075. int handle = -1;
  1076. Vector3 point;
  1077. Vector3 normal;
  1078. bool inters = seg->intersect_ray(camera, _edit.mouse_pos, point, normal, &handle, b->get_shift());
  1079. if (inters && handle != -1) {
  1080. _edit.gizmo = seg;
  1081. _edit.gizmo_handle = handle;
  1082. _edit.gizmo_initial_value = seg->get_handle_value(handle);
  1083. break;
  1084. }
  1085. }
  1086. }
  1087. if (_gizmo_select(_edit.mouse_pos)) {
  1088. break;
  1089. }
  1090. clicked = 0;
  1091. clicked_includes_current = false;
  1092. if ((spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT && b->get_command()) || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_ROTATE) {
  1093. /* HANDLE ROTATION */
  1094. if (get_selected_count() == 0) {
  1095. break; //bye
  1096. }
  1097. //handle rotate
  1098. _edit.mode = TRANSFORM_ROTATE;
  1099. _compute_edit(b->get_position());
  1100. break;
  1101. }
  1102. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_MOVE) {
  1103. if (get_selected_count() == 0) {
  1104. break; //bye
  1105. }
  1106. //handle translate
  1107. _edit.mode = TRANSFORM_TRANSLATE;
  1108. _compute_edit(b->get_position());
  1109. break;
  1110. }
  1111. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SCALE) {
  1112. if (get_selected_count() == 0) {
  1113. break; //bye
  1114. }
  1115. //handle scale
  1116. _edit.mode = TRANSFORM_SCALE;
  1117. _compute_edit(b->get_position());
  1118. break;
  1119. }
  1120. // todo scale
  1121. int gizmo_handle = -1;
  1122. clicked = _select_ray(b->get_position(), b->get_shift(), clicked_includes_current, &gizmo_handle, b->get_shift());
  1123. //clicking is always deferred to either move or release
  1124. clicked_wants_append = b->get_shift();
  1125. if (!clicked) {
  1126. if (!clicked_wants_append) {
  1127. _clear_selected();
  1128. }
  1129. //default to regionselect
  1130. cursor.region_select = true;
  1131. cursor.region_begin = b->get_position();
  1132. cursor.region_end = b->get_position();
  1133. }
  1134. if (clicked && gizmo_handle >= 0) {
  1135. Spatial *spa = Object::cast_to<Spatial>(ObjectDB::get_instance(clicked));
  1136. if (spa) {
  1137. Ref<EditorSpatialGizmo> seg = spa->get_gizmo();
  1138. if (seg.is_valid()) {
  1139. _edit.gizmo = seg;
  1140. _edit.gizmo_handle = gizmo_handle;
  1141. _edit.gizmo_initial_value = seg->get_handle_value(gizmo_handle);
  1142. break;
  1143. }
  1144. }
  1145. }
  1146. surface->update();
  1147. } else {
  1148. if (_edit.gizmo.is_valid()) {
  1149. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_initial_value, false);
  1150. _edit.gizmo = Ref<EditorSpatialGizmo>();
  1151. break;
  1152. }
  1153. if (clicked) {
  1154. _select_clicked(clicked_wants_append, true);
  1155. // Processing was deferred.
  1156. clicked = 0;
  1157. }
  1158. if (cursor.region_select) {
  1159. if (!clicked_wants_append) {
  1160. _clear_selected();
  1161. }
  1162. _select_region();
  1163. cursor.region_select = false;
  1164. surface->update();
  1165. }
  1166. if (_edit.mode != TRANSFORM_NONE) {
  1167. static const char *_transform_name[4] = {
  1168. TTRC("None"),
  1169. TTRC("Rotate"),
  1170. // TRANSLATORS: This refers to the movement that changes the position of an object.
  1171. TTRC("Translate"),
  1172. TTRC("Scale"),
  1173. };
  1174. undo_redo->create_action(TTRGET(_transform_name[_edit.mode]));
  1175. List<Node *> &selection = editor_selection->get_selected_node_list();
  1176. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1177. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1178. if (!sp) {
  1179. continue;
  1180. }
  1181. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1182. if (!se) {
  1183. continue;
  1184. }
  1185. undo_redo->add_do_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
  1186. undo_redo->add_undo_method(sp, "set_global_transform", se->original);
  1187. }
  1188. undo_redo->commit_action();
  1189. _edit.mode = TRANSFORM_NONE;
  1190. set_message("");
  1191. }
  1192. surface->update();
  1193. }
  1194. } break;
  1195. }
  1196. }
  1197. Ref<InputEventMouseMotion> m = p_event;
  1198. if (m.is_valid()) {
  1199. _edit.mouse_pos = m->get_position();
  1200. if (spatial_editor->get_selected()) {
  1201. Ref<EditorSpatialGizmo> seg = spatial_editor->get_selected()->get_gizmo();
  1202. if (seg.is_valid()) {
  1203. int selected_handle = -1;
  1204. int handle = -1;
  1205. Vector3 point;
  1206. Vector3 normal;
  1207. bool inters = seg->intersect_ray(camera, _edit.mouse_pos, point, normal, &handle, false);
  1208. if (inters && handle != -1) {
  1209. selected_handle = handle;
  1210. }
  1211. if (selected_handle != spatial_editor->get_over_gizmo_handle()) {
  1212. spatial_editor->set_over_gizmo_handle(selected_handle);
  1213. spatial_editor->get_selected()->update_gizmo();
  1214. if (selected_handle != -1) {
  1215. spatial_editor->select_gizmo_highlight_axis(-1);
  1216. }
  1217. }
  1218. }
  1219. }
  1220. if (spatial_editor->get_over_gizmo_handle() == -1 && !(m->get_button_mask() & 1) && !_edit.gizmo.is_valid()) {
  1221. _gizmo_select(_edit.mouse_pos, true);
  1222. }
  1223. NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  1224. NavigationMode nav_mode = NAVIGATION_NONE;
  1225. if (_edit.gizmo.is_valid()) {
  1226. _edit.gizmo->set_handle(_edit.gizmo_handle, camera, m->get_position());
  1227. Variant v = _edit.gizmo->get_handle_value(_edit.gizmo_handle);
  1228. String n = _edit.gizmo->get_handle_name(_edit.gizmo_handle);
  1229. set_message(n + ": " + String(v));
  1230. } else if (m->get_button_mask() & BUTTON_MASK_LEFT) {
  1231. if (nav_scheme == NAVIGATION_MAYA && m->get_alt()) {
  1232. nav_mode = NAVIGATION_ORBIT;
  1233. } else if (nav_scheme == NAVIGATION_MODO && m->get_alt() && m->get_shift()) {
  1234. nav_mode = NAVIGATION_PAN;
  1235. } else if (nav_scheme == NAVIGATION_MODO && m->get_alt() && m->get_control()) {
  1236. nav_mode = NAVIGATION_ZOOM;
  1237. } else if (nav_scheme == NAVIGATION_MODO && m->get_alt()) {
  1238. nav_mode = NAVIGATION_ORBIT;
  1239. } else {
  1240. const bool movement_threshold_passed = _edit.original_mouse_pos.distance_to(_edit.mouse_pos) > 8 * EDSCALE;
  1241. if (clicked && movement_threshold_passed) {
  1242. if (!clicked_includes_current) {
  1243. _select_clicked(clicked_wants_append, true);
  1244. // Processing was deferred.
  1245. }
  1246. _compute_edit(_edit.mouse_pos);
  1247. clicked = 0;
  1248. _edit.mode = TRANSFORM_TRANSLATE;
  1249. }
  1250. if (cursor.region_select) {
  1251. cursor.region_end = m->get_position();
  1252. surface->update();
  1253. return;
  1254. }
  1255. if (_edit.mode == TRANSFORM_NONE) {
  1256. return;
  1257. }
  1258. Vector3 ray_pos = _get_ray_pos(m->get_position());
  1259. Vector3 ray = _get_ray(m->get_position());
  1260. double snap = EDITOR_GET("interface/inspector/default_float_step");
  1261. int snap_step_decimals = Math::range_step_decimals(snap);
  1262. switch (_edit.mode) {
  1263. case TRANSFORM_SCALE: {
  1264. Vector3 motion_mask;
  1265. Plane plane;
  1266. bool plane_mv = false;
  1267. switch (_edit.plane) {
  1268. case TRANSFORM_VIEW:
  1269. motion_mask = Vector3(0, 0, 0);
  1270. plane = Plane(_edit.center, _get_camera_normal());
  1271. break;
  1272. case TRANSFORM_X_AXIS:
  1273. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0);
  1274. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1275. break;
  1276. case TRANSFORM_Y_AXIS:
  1277. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(1);
  1278. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1279. break;
  1280. case TRANSFORM_Z_AXIS:
  1281. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2);
  1282. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1283. break;
  1284. case TRANSFORM_YZ:
  1285. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2) + spatial_editor->get_gizmo_transform().basis.get_axis(1);
  1286. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(0));
  1287. plane_mv = true;
  1288. break;
  1289. case TRANSFORM_XZ:
  1290. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2) + spatial_editor->get_gizmo_transform().basis.get_axis(0);
  1291. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(1));
  1292. plane_mv = true;
  1293. break;
  1294. case TRANSFORM_XY:
  1295. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0) + spatial_editor->get_gizmo_transform().basis.get_axis(1);
  1296. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(2));
  1297. plane_mv = true;
  1298. break;
  1299. }
  1300. Vector3 intersection;
  1301. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  1302. break;
  1303. }
  1304. Vector3 click;
  1305. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  1306. break;
  1307. }
  1308. Vector3 motion = intersection - click;
  1309. if (_edit.plane != TRANSFORM_VIEW) {
  1310. if (!plane_mv) {
  1311. motion = motion_mask.dot(motion) * motion_mask;
  1312. } else {
  1313. // Alternative planar scaling mode
  1314. if (_get_key_modifier(m) != KEY_SHIFT) {
  1315. motion = motion_mask.dot(motion) * motion_mask;
  1316. }
  1317. }
  1318. } else {
  1319. float center_click_dist = click.distance_to(_edit.center);
  1320. float center_inters_dist = intersection.distance_to(_edit.center);
  1321. if (center_click_dist == 0) {
  1322. break;
  1323. }
  1324. float scale = center_inters_dist - center_click_dist;
  1325. motion = Vector3(scale, scale, scale);
  1326. }
  1327. motion /= click.distance_to(_edit.center);
  1328. List<Node *> &selection = editor_selection->get_selected_node_list();
  1329. // Disable local transformation for TRANSFORM_VIEW
  1330. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  1331. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1332. snap = spatial_editor->get_scale_snap() / 100;
  1333. }
  1334. Vector3 motion_snapped = motion;
  1335. motion_snapped.snap(Vector3(snap, snap, snap));
  1336. // This might not be necessary anymore after issue #288 is solved (in 4.0?).
  1337. set_message(TTR("Scaling: ") + "(" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
  1338. String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
  1339. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1340. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1341. if (!sp) {
  1342. continue;
  1343. }
  1344. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1345. if (!se) {
  1346. continue;
  1347. }
  1348. if (sp->has_meta("_edit_lock_")) {
  1349. continue;
  1350. }
  1351. Transform original = se->original;
  1352. Transform original_local = se->original_local;
  1353. Transform base = Transform(Basis(), _edit.center);
  1354. Transform t;
  1355. Vector3 local_scale;
  1356. if (local_coords) {
  1357. Basis g = original.basis.orthonormalized();
  1358. Vector3 local_motion = g.inverse().xform(motion);
  1359. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1360. local_motion.snap(Vector3(snap, snap, snap));
  1361. }
  1362. local_scale = original_local.basis.get_scale() * (local_motion + Vector3(1, 1, 1));
  1363. // Prevent scaling to 0 it would break the gizmo
  1364. Basis check = original_local.basis;
  1365. check.scale(local_scale);
  1366. if (check.determinant() != 0) {
  1367. // Apply scale
  1368. sp->set_scale(local_scale);
  1369. }
  1370. } else {
  1371. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1372. motion.snap(Vector3(snap, snap, snap));
  1373. }
  1374. Transform r;
  1375. r.basis.scale(motion + Vector3(1, 1, 1));
  1376. t = base * (r * (base.inverse() * original));
  1377. // Apply scale
  1378. sp->set_global_transform(t);
  1379. }
  1380. }
  1381. surface->update();
  1382. } break;
  1383. case TRANSFORM_TRANSLATE: {
  1384. Vector3 motion_mask;
  1385. Plane plane;
  1386. bool plane_mv = false;
  1387. switch (_edit.plane) {
  1388. case TRANSFORM_VIEW:
  1389. plane = Plane(_edit.center, _get_camera_normal());
  1390. break;
  1391. case TRANSFORM_X_AXIS:
  1392. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0);
  1393. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1394. break;
  1395. case TRANSFORM_Y_AXIS:
  1396. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(1);
  1397. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1398. break;
  1399. case TRANSFORM_Z_AXIS:
  1400. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2);
  1401. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1402. break;
  1403. case TRANSFORM_YZ:
  1404. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(0));
  1405. plane_mv = true;
  1406. break;
  1407. case TRANSFORM_XZ:
  1408. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(1));
  1409. plane_mv = true;
  1410. break;
  1411. case TRANSFORM_XY:
  1412. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(2));
  1413. plane_mv = true;
  1414. break;
  1415. }
  1416. Vector3 intersection;
  1417. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  1418. break;
  1419. }
  1420. Vector3 click;
  1421. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  1422. break;
  1423. }
  1424. Vector3 motion = intersection - click;
  1425. if (_edit.plane != TRANSFORM_VIEW) {
  1426. if (!plane_mv) {
  1427. motion = motion_mask.dot(motion) * motion_mask;
  1428. }
  1429. }
  1430. List<Node *> &selection = editor_selection->get_selected_node_list();
  1431. // Disable local transformation for TRANSFORM_VIEW
  1432. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  1433. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1434. snap = spatial_editor->get_translate_snap();
  1435. }
  1436. Vector3 motion_snapped = motion;
  1437. motion_snapped.snap(Vector3(snap, snap, snap));
  1438. set_message(TTR("Translating: ") + "(" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
  1439. String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
  1440. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1441. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1442. if (!sp) {
  1443. continue;
  1444. }
  1445. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1446. if (!se) {
  1447. continue;
  1448. }
  1449. if (sp->has_meta("_edit_lock_")) {
  1450. continue;
  1451. }
  1452. Transform original = se->original;
  1453. Transform t;
  1454. if (local_coords) {
  1455. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1456. Basis g = original.basis.orthonormalized();
  1457. Vector3 local_motion = g.inverse().xform(motion);
  1458. local_motion.snap(Vector3(snap, snap, snap));
  1459. motion = g.xform(local_motion);
  1460. }
  1461. } else {
  1462. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1463. motion.snap(Vector3(snap, snap, snap));
  1464. }
  1465. }
  1466. // Apply translation
  1467. t = original;
  1468. t.origin += motion;
  1469. sp->set_global_transform(t);
  1470. }
  1471. surface->update();
  1472. } break;
  1473. case TRANSFORM_ROTATE: {
  1474. Plane plane;
  1475. Vector3 axis;
  1476. switch (_edit.plane) {
  1477. case TRANSFORM_VIEW:
  1478. plane = Plane(_edit.center, _get_camera_normal());
  1479. break;
  1480. case TRANSFORM_X_AXIS:
  1481. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(0));
  1482. axis = Vector3(1, 0, 0);
  1483. break;
  1484. case TRANSFORM_Y_AXIS:
  1485. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(1));
  1486. axis = Vector3(0, 1, 0);
  1487. break;
  1488. case TRANSFORM_Z_AXIS:
  1489. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(2));
  1490. axis = Vector3(0, 0, 1);
  1491. break;
  1492. case TRANSFORM_YZ:
  1493. case TRANSFORM_XZ:
  1494. case TRANSFORM_XY:
  1495. break;
  1496. }
  1497. Vector3 intersection;
  1498. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  1499. break;
  1500. }
  1501. Vector3 click;
  1502. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  1503. break;
  1504. }
  1505. Vector3 y_axis = (click - _edit.center).normalized();
  1506. Vector3 x_axis = plane.normal.cross(y_axis).normalized();
  1507. double angle = Math::atan2(x_axis.dot(intersection - _edit.center), y_axis.dot(intersection - _edit.center));
  1508. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1509. snap = spatial_editor->get_rotate_snap();
  1510. }
  1511. angle = Math::rad2deg(angle) + snap * 0.5; //else it won't reach +180
  1512. angle -= Math::fmod(angle, snap);
  1513. set_message(vformat(TTR("Rotating %s degrees."), String::num(angle, snap_step_decimals)));
  1514. angle = Math::deg2rad(angle);
  1515. List<Node *> &selection = editor_selection->get_selected_node_list();
  1516. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW); // Disable local transformation for TRANSFORM_VIEW
  1517. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1518. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1519. if (!sp) {
  1520. continue;
  1521. }
  1522. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1523. if (!se) {
  1524. continue;
  1525. }
  1526. if (sp->has_meta("_edit_lock_")) {
  1527. continue;
  1528. }
  1529. Transform t;
  1530. if (local_coords) {
  1531. Transform original_local = se->original_local;
  1532. Basis rot = Basis(axis, angle);
  1533. t.basis = original_local.get_basis().orthonormalized() * rot;
  1534. t.origin = original_local.origin;
  1535. // Apply rotation
  1536. sp->set_transform(t);
  1537. sp->set_scale(original_local.basis.get_scale()); // re-apply original scale
  1538. } else {
  1539. Transform original = se->original;
  1540. Transform r;
  1541. Transform base = Transform(Basis(), _edit.center);
  1542. r.basis.rotate(plane.normal, angle);
  1543. t = base * r * base.inverse() * original;
  1544. // Apply rotation
  1545. sp->set_global_transform(t);
  1546. }
  1547. }
  1548. surface->update();
  1549. } break;
  1550. default: {
  1551. }
  1552. }
  1553. }
  1554. } else if ((m->get_button_mask() & BUTTON_MASK_RIGHT) || freelook_active) {
  1555. if (nav_scheme == NAVIGATION_MAYA && m->get_alt()) {
  1556. nav_mode = NAVIGATION_ZOOM;
  1557. } else if (freelook_active) {
  1558. nav_mode = NAVIGATION_LOOK;
  1559. } else if (orthogonal) {
  1560. nav_mode = NAVIGATION_PAN;
  1561. }
  1562. } else if (m->get_button_mask() & BUTTON_MASK_MIDDLE) {
  1563. const int mod = _get_key_modifier(m);
  1564. if (nav_scheme == NAVIGATION_GODOT) {
  1565. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1566. nav_mode = NAVIGATION_PAN;
  1567. } else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier")) {
  1568. nav_mode = NAVIGATION_ZOOM;
  1569. } else if (mod == KEY_ALT || mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier")) {
  1570. // Always allow Alt as a modifier to better support graphic tablets.
  1571. nav_mode = NAVIGATION_ORBIT;
  1572. }
  1573. } else if (nav_scheme == NAVIGATION_MAYA) {
  1574. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1575. nav_mode = NAVIGATION_PAN;
  1576. }
  1577. }
  1578. } else if (EditorSettings::get_singleton()->get("editors/3d/navigation/emulate_3_button_mouse")) {
  1579. // Handle trackpad (no external mouse) use case
  1580. const int mod = _get_key_modifier(m);
  1581. if (mod) {
  1582. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1583. nav_mode = NAVIGATION_PAN;
  1584. } else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier")) {
  1585. nav_mode = NAVIGATION_ZOOM;
  1586. } else if (mod == KEY_ALT || mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier")) {
  1587. // Always allow Alt as a modifier to better support graphic tablets.
  1588. nav_mode = NAVIGATION_ORBIT;
  1589. }
  1590. }
  1591. }
  1592. switch (nav_mode) {
  1593. case NAVIGATION_PAN: {
  1594. _nav_pan(m, _get_warped_mouse_motion(m));
  1595. } break;
  1596. case NAVIGATION_ZOOM: {
  1597. _nav_zoom(m, m->get_relative());
  1598. } break;
  1599. case NAVIGATION_ORBIT: {
  1600. _nav_orbit(m, _get_warped_mouse_motion(m));
  1601. } break;
  1602. case NAVIGATION_LOOK: {
  1603. _nav_look(m, _get_warped_mouse_motion(m));
  1604. } break;
  1605. default: {
  1606. }
  1607. }
  1608. }
  1609. Ref<InputEventMagnifyGesture> magnify_gesture = p_event;
  1610. if (magnify_gesture.is_valid()) {
  1611. if (is_freelook_active()) {
  1612. scale_freelook_speed(magnify_gesture->get_factor());
  1613. } else {
  1614. scale_cursor_distance(1.0 / magnify_gesture->get_factor());
  1615. }
  1616. }
  1617. Ref<InputEventPanGesture> pan_gesture = p_event;
  1618. if (pan_gesture.is_valid()) {
  1619. NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  1620. NavigationMode nav_mode = NAVIGATION_NONE;
  1621. if (nav_scheme == NAVIGATION_GODOT) {
  1622. const int mod = _get_key_modifier(pan_gesture);
  1623. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1624. nav_mode = NAVIGATION_PAN;
  1625. } else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier")) {
  1626. nav_mode = NAVIGATION_ZOOM;
  1627. } else if (mod == KEY_ALT || mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier")) {
  1628. // Always allow Alt as a modifier to better support graphic tablets.
  1629. nav_mode = NAVIGATION_ORBIT;
  1630. }
  1631. } else if (nav_scheme == NAVIGATION_MAYA) {
  1632. if (pan_gesture->get_alt()) {
  1633. nav_mode = NAVIGATION_PAN;
  1634. }
  1635. }
  1636. switch (nav_mode) {
  1637. case NAVIGATION_PAN: {
  1638. _nav_pan(pan_gesture, pan_gesture->get_delta());
  1639. } break;
  1640. case NAVIGATION_ZOOM: {
  1641. _nav_zoom(pan_gesture, pan_gesture->get_delta());
  1642. } break;
  1643. case NAVIGATION_ORBIT: {
  1644. _nav_orbit(pan_gesture, pan_gesture->get_delta());
  1645. } break;
  1646. case NAVIGATION_LOOK: {
  1647. _nav_look(pan_gesture, pan_gesture->get_delta());
  1648. } break;
  1649. default: {
  1650. }
  1651. }
  1652. }
  1653. Ref<InputEventKey> k = p_event;
  1654. if (k.is_valid()) {
  1655. if (!k->is_pressed()) {
  1656. return;
  1657. }
  1658. if (EditorSettings::get_singleton()->get("editors/3d/navigation/emulate_numpad")) {
  1659. const uint32_t code = k->get_scancode();
  1660. if (code >= KEY_0 && code <= KEY_9) {
  1661. k->set_scancode(code - KEY_0 + KEY_KP_0);
  1662. }
  1663. }
  1664. if (ED_IS_SHORTCUT("spatial_editor/snap", p_event)) {
  1665. if (_edit.mode != TRANSFORM_NONE) {
  1666. _edit.snap = !_edit.snap;
  1667. }
  1668. }
  1669. if (ED_IS_SHORTCUT("spatial_editor/bottom_view", p_event)) {
  1670. _menu_option(VIEW_BOTTOM);
  1671. }
  1672. if (ED_IS_SHORTCUT("spatial_editor/top_view", p_event)) {
  1673. _menu_option(VIEW_TOP);
  1674. }
  1675. if (ED_IS_SHORTCUT("spatial_editor/rear_view", p_event)) {
  1676. _menu_option(VIEW_REAR);
  1677. }
  1678. if (ED_IS_SHORTCUT("spatial_editor/front_view", p_event)) {
  1679. _menu_option(VIEW_FRONT);
  1680. }
  1681. if (ED_IS_SHORTCUT("spatial_editor/left_view", p_event)) {
  1682. _menu_option(VIEW_LEFT);
  1683. }
  1684. if (ED_IS_SHORTCUT("spatial_editor/right_view", p_event)) {
  1685. _menu_option(VIEW_RIGHT);
  1686. }
  1687. if (ED_IS_SHORTCUT("spatial_editor/focus_origin", p_event)) {
  1688. _menu_option(VIEW_CENTER_TO_ORIGIN);
  1689. }
  1690. if (ED_IS_SHORTCUT("spatial_editor/focus_selection", p_event)) {
  1691. _menu_option(VIEW_CENTER_TO_SELECTION);
  1692. }
  1693. // Orthgonal mode doesn't work in freelook.
  1694. if (!freelook_active && ED_IS_SHORTCUT("spatial_editor/switch_perspective_orthogonal", p_event)) {
  1695. _menu_option(orthogonal ? VIEW_PERSPECTIVE : VIEW_ORTHOGONAL);
  1696. }
  1697. if (ED_IS_SHORTCUT("spatial_editor/align_transform_with_view", p_event)) {
  1698. _menu_option(VIEW_ALIGN_TRANSFORM_WITH_VIEW);
  1699. }
  1700. if (ED_IS_SHORTCUT("spatial_editor/align_rotation_with_view", p_event)) {
  1701. _menu_option(VIEW_ALIGN_ROTATION_WITH_VIEW);
  1702. }
  1703. if (ED_IS_SHORTCUT("spatial_editor/insert_anim_key", p_event)) {
  1704. if (!get_selected_count() || _edit.mode != TRANSFORM_NONE) {
  1705. return;
  1706. }
  1707. if (!AnimationPlayerEditor::singleton->get_track_editor()->has_keying()) {
  1708. set_message(TTR("Keying is disabled (no key inserted)."));
  1709. return;
  1710. }
  1711. List<Node *> &selection = editor_selection->get_selected_node_list();
  1712. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1713. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1714. if (!sp) {
  1715. continue;
  1716. }
  1717. spatial_editor->emit_signal("transform_key_request", sp, "", sp->get_transform());
  1718. }
  1719. set_message(TTR("Animation Key Inserted."));
  1720. }
  1721. // Freelook doesn't work in orthogonal mode.
  1722. if (!orthogonal && ED_IS_SHORTCUT("spatial_editor/freelook_toggle", p_event)) {
  1723. set_freelook_active(!is_freelook_active());
  1724. } else if (k->get_scancode() == KEY_ESCAPE) {
  1725. set_freelook_active(false);
  1726. }
  1727. if (k->get_scancode() == KEY_SPACE) {
  1728. if (!k->is_pressed()) {
  1729. emit_signal("toggle_maximize_view", this);
  1730. }
  1731. }
  1732. }
  1733. // freelook uses most of the useful shortcuts, like save, so its ok
  1734. // to consider freelook active as end of the line for future events.
  1735. if (freelook_active) {
  1736. accept_event();
  1737. }
  1738. }
  1739. void SpatialEditorViewport::_nav_pan(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  1740. const NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  1741. real_t pan_speed = 1 / 150.0;
  1742. int pan_speed_modifier = 10;
  1743. if (nav_scheme == NAVIGATION_MAYA && p_event->get_shift()) {
  1744. pan_speed *= pan_speed_modifier;
  1745. }
  1746. Transform camera_transform;
  1747. camera_transform.translate(cursor.pos);
  1748. camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
  1749. camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
  1750. const bool invert_x_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_x_axis");
  1751. const bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y_axis");
  1752. Vector3 translation(
  1753. (invert_x_axis ? -1 : 1) * -p_relative.x * pan_speed,
  1754. (invert_y_axis ? -1 : 1) * p_relative.y * pan_speed,
  1755. 0);
  1756. translation *= cursor.distance / DISTANCE_DEFAULT;
  1757. camera_transform.translate(translation);
  1758. cursor.pos = camera_transform.origin;
  1759. }
  1760. void SpatialEditorViewport::_nav_zoom(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  1761. const NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  1762. real_t zoom_speed = 1 / 80.0;
  1763. int zoom_speed_modifier = 10;
  1764. if (nav_scheme == NAVIGATION_MAYA && p_event->get_shift()) {
  1765. zoom_speed *= zoom_speed_modifier;
  1766. }
  1767. NavigationZoomStyle zoom_style = (NavigationZoomStyle)EditorSettings::get_singleton()->get("editors/3d/navigation/zoom_style").operator int();
  1768. if (zoom_style == NAVIGATION_ZOOM_HORIZONTAL) {
  1769. if (p_relative.x > 0) {
  1770. scale_cursor_distance(1 - p_relative.x * zoom_speed);
  1771. } else if (p_relative.x < 0) {
  1772. scale_cursor_distance(1.0 / (1 + p_relative.x * zoom_speed));
  1773. }
  1774. } else {
  1775. if (p_relative.y > 0) {
  1776. scale_cursor_distance(1 + p_relative.y * zoom_speed);
  1777. } else if (p_relative.y < 0) {
  1778. scale_cursor_distance(1.0 / (1 - p_relative.y * zoom_speed));
  1779. }
  1780. }
  1781. }
  1782. void SpatialEditorViewport::_nav_orbit(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  1783. if (lock_rotation) {
  1784. _nav_pan(p_event, p_relative);
  1785. return;
  1786. }
  1787. if (orthogonal && auto_orthogonal) {
  1788. _menu_option(VIEW_PERSPECTIVE);
  1789. }
  1790. const real_t degrees_per_pixel = EditorSettings::get_singleton()->get("editors/3d/navigation_feel/orbit_sensitivity");
  1791. const real_t radians_per_pixel = Math::deg2rad(degrees_per_pixel);
  1792. const bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y_axis");
  1793. const bool invert_x_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_x_axis");
  1794. if (invert_y_axis) {
  1795. cursor.x_rot -= p_relative.y * radians_per_pixel;
  1796. } else {
  1797. cursor.x_rot += p_relative.y * radians_per_pixel;
  1798. }
  1799. // Clamp the Y rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  1800. cursor.x_rot = CLAMP(cursor.x_rot, -1.57, 1.57);
  1801. if (invert_x_axis) {
  1802. cursor.y_rot -= p_relative.x * radians_per_pixel;
  1803. } else {
  1804. cursor.y_rot += p_relative.x * radians_per_pixel;
  1805. }
  1806. view_type = VIEW_TYPE_USER;
  1807. _update_name();
  1808. }
  1809. void SpatialEditorViewport::_nav_look(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  1810. if (orthogonal) {
  1811. _nav_pan(p_event, p_relative);
  1812. return;
  1813. }
  1814. if (orthogonal && auto_orthogonal) {
  1815. _menu_option(VIEW_PERSPECTIVE);
  1816. }
  1817. const real_t degrees_per_pixel = EditorSettings::get_singleton()->get("editors/3d/navigation_feel/orbit_sensitivity");
  1818. const real_t radians_per_pixel = Math::deg2rad(degrees_per_pixel);
  1819. const bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y_axis");
  1820. // Note: do NOT assume the camera has the "current" transform, because it is interpolated and may have "lag".
  1821. const Transform prev_camera_transform = to_camera_transform(cursor);
  1822. if (invert_y_axis) {
  1823. cursor.x_rot -= p_relative.y * radians_per_pixel;
  1824. } else {
  1825. cursor.x_rot += p_relative.y * radians_per_pixel;
  1826. }
  1827. // Clamp the Y rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  1828. cursor.x_rot = CLAMP(cursor.x_rot, -1.57, 1.57);
  1829. cursor.y_rot += p_relative.x * radians_per_pixel;
  1830. // Look is like the opposite of Orbit: the focus point rotates around the camera
  1831. Transform camera_transform = to_camera_transform(cursor);
  1832. Vector3 pos = camera_transform.xform(Vector3(0, 0, 0));
  1833. Vector3 prev_pos = prev_camera_transform.xform(Vector3(0, 0, 0));
  1834. Vector3 diff = prev_pos - pos;
  1835. cursor.pos += diff;
  1836. view_type = VIEW_TYPE_USER;
  1837. _update_name();
  1838. }
  1839. void SpatialEditorViewport::set_freelook_active(bool active_now) {
  1840. if (!freelook_active && active_now) {
  1841. // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
  1842. cursor = camera_cursor;
  1843. // Make sure eye_pos is synced, because freelook referential is eye pos rather than orbit pos
  1844. Vector3 forward = to_camera_transform(cursor).basis.xform(Vector3(0, 0, -1));
  1845. cursor.eye_pos = cursor.pos - cursor.distance * forward;
  1846. // Also sync the camera cursor, otherwise switching to freelook will be trippy if inertia is active
  1847. camera_cursor.eye_pos = cursor.eye_pos;
  1848. if (EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_speed_zoom_link")) {
  1849. // Re-adjust freelook speed from the current zoom level
  1850. real_t base_speed = EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_base_speed");
  1851. freelook_speed = base_speed * cursor.distance;
  1852. }
  1853. previous_mouse_position = get_local_mouse_position();
  1854. // Hide mouse like in an FPS (warping doesn't work)
  1855. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
  1856. } else if (freelook_active && !active_now) {
  1857. // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
  1858. cursor = camera_cursor;
  1859. // Restore mouse
  1860. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  1861. // Restore the previous mouse position when leaving freelook mode.
  1862. // This is done because leaving `Input.MOUSE_MODE_CAPTURED` will center the cursor
  1863. // due to OS limitations.
  1864. warp_mouse(previous_mouse_position);
  1865. }
  1866. freelook_active = active_now;
  1867. }
  1868. void SpatialEditorViewport::scale_cursor_distance(real_t scale) {
  1869. real_t min_distance = MAX(camera->get_znear() * 4, ZOOM_FREELOOK_MIN);
  1870. real_t max_distance = MIN(camera->get_zfar() / 2, ZOOM_FREELOOK_MAX);
  1871. if (unlikely(min_distance > max_distance)) {
  1872. cursor.distance = (min_distance + max_distance) / 2;
  1873. } else {
  1874. cursor.distance = CLAMP(cursor.distance * scale, min_distance, max_distance);
  1875. }
  1876. if (cursor.distance == max_distance || cursor.distance == min_distance) {
  1877. zoom_failed_attempts_count++;
  1878. } else {
  1879. zoom_failed_attempts_count = 0;
  1880. }
  1881. zoom_indicator_delay = ZOOM_FREELOOK_INDICATOR_DELAY_S;
  1882. surface->update();
  1883. }
  1884. void SpatialEditorViewport::scale_freelook_speed(real_t scale) {
  1885. real_t min_speed = MAX(camera->get_znear() * 4, ZOOM_FREELOOK_MIN);
  1886. real_t max_speed = MIN(camera->get_zfar() / 2, ZOOM_FREELOOK_MAX);
  1887. if (unlikely(min_speed > max_speed)) {
  1888. freelook_speed = (min_speed + max_speed) / 2;
  1889. } else {
  1890. freelook_speed = CLAMP(freelook_speed * scale, min_speed, max_speed);
  1891. }
  1892. zoom_indicator_delay = ZOOM_FREELOOK_INDICATOR_DELAY_S;
  1893. surface->update();
  1894. }
  1895. Point2i SpatialEditorViewport::_get_warped_mouse_motion(const Ref<InputEventMouseMotion> &p_ev_mouse_motion) const {
  1896. Point2i relative;
  1897. if (bool(EDITOR_DEF("editors/3d/navigation/warped_mouse_panning", false))) {
  1898. relative = Input::get_singleton()->warp_mouse_motion(p_ev_mouse_motion, surface->get_global_rect());
  1899. } else {
  1900. relative = p_ev_mouse_motion->get_relative();
  1901. }
  1902. return relative;
  1903. }
  1904. static bool is_shortcut_pressed(const String &p_path) {
  1905. Ref<ShortCut> shortcut = ED_GET_SHORTCUT(p_path);
  1906. if (shortcut.is_null()) {
  1907. return false;
  1908. }
  1909. InputEventKey *k = Object::cast_to<InputEventKey>(shortcut->get_shortcut().ptr());
  1910. if (k == nullptr) {
  1911. return false;
  1912. }
  1913. const Input &input = *Input::get_singleton();
  1914. int scancode = k->get_scancode();
  1915. return input.is_key_pressed(scancode);
  1916. }
  1917. void SpatialEditorViewport::_update_freelook(real_t delta) {
  1918. if (!is_freelook_active()) {
  1919. return;
  1920. }
  1921. const FreelookNavigationScheme navigation_scheme = (FreelookNavigationScheme)EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_navigation_scheme").operator int();
  1922. Vector3 forward;
  1923. if (navigation_scheme == FREELOOK_FULLY_AXIS_LOCKED) {
  1924. // Forward/backward keys will always go straight forward/backward, never moving on the Y axis.
  1925. forward = Vector3(0, 0, -1).rotated(Vector3(0, 1, 0), camera->get_rotation().y);
  1926. } else {
  1927. // Forward/backward keys will be relative to the camera pitch.
  1928. forward = camera->get_transform().basis.xform(Vector3(0, 0, -1));
  1929. }
  1930. const Vector3 right = camera->get_transform().basis.xform(Vector3(1, 0, 0));
  1931. Vector3 up;
  1932. if (navigation_scheme == FREELOOK_PARTIALLY_AXIS_LOCKED || navigation_scheme == FREELOOK_FULLY_AXIS_LOCKED) {
  1933. // Up/down keys will always go up/down regardless of camera pitch.
  1934. up = Vector3(0, 1, 0);
  1935. } else {
  1936. // Up/down keys will be relative to the camera pitch.
  1937. up = camera->get_transform().basis.xform(Vector3(0, 1, 0));
  1938. }
  1939. Vector3 direction;
  1940. if (is_shortcut_pressed("spatial_editor/freelook_left")) {
  1941. direction -= right;
  1942. }
  1943. if (is_shortcut_pressed("spatial_editor/freelook_right")) {
  1944. direction += right;
  1945. }
  1946. if (is_shortcut_pressed("spatial_editor/freelook_forward")) {
  1947. direction += forward;
  1948. }
  1949. if (is_shortcut_pressed("spatial_editor/freelook_backwards")) {
  1950. direction -= forward;
  1951. }
  1952. if (is_shortcut_pressed("spatial_editor/freelook_up")) {
  1953. direction += up;
  1954. }
  1955. if (is_shortcut_pressed("spatial_editor/freelook_down")) {
  1956. direction -= up;
  1957. }
  1958. real_t speed = freelook_speed;
  1959. if (is_shortcut_pressed("spatial_editor/freelook_speed_modifier")) {
  1960. speed *= 3.0;
  1961. }
  1962. if (is_shortcut_pressed("spatial_editor/freelook_slow_modifier")) {
  1963. speed *= 0.333333;
  1964. }
  1965. const Vector3 motion = direction * speed * delta;
  1966. cursor.pos += motion;
  1967. cursor.eye_pos += motion;
  1968. }
  1969. void SpatialEditorViewport::set_message(String p_message, float p_time) {
  1970. message = p_message;
  1971. message_time = p_time;
  1972. }
  1973. void SpatialEditorPlugin::edited_scene_changed() {
  1974. for (uint32_t i = 0; i < SpatialEditor::VIEWPORTS_COUNT; i++) {
  1975. SpatialEditorViewport *viewport = SpatialEditor::get_singleton()->get_editor_viewport(i);
  1976. if (viewport->is_visible()) {
  1977. viewport->notification(Control::NOTIFICATION_VISIBILITY_CHANGED);
  1978. }
  1979. }
  1980. }
  1981. void SpatialEditorViewport::_notification(int p_what) {
  1982. if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
  1983. bool visible = is_visible_in_tree();
  1984. set_process(visible);
  1985. if (visible) {
  1986. orthogonal = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL));
  1987. _update_name();
  1988. _update_camera(0);
  1989. } else {
  1990. set_freelook_active(false);
  1991. }
  1992. call_deferred("update_transform_gizmo_view");
  1993. rotation_control->set_visible(EditorSettings::get_singleton()->get("editors/3d/navigation/show_viewport_rotation_gizmo"));
  1994. }
  1995. if (p_what == NOTIFICATION_RESIZED) {
  1996. call_deferred("update_transform_gizmo_view");
  1997. }
  1998. if (p_what == NOTIFICATION_PROCESS) {
  1999. real_t delta = get_process_delta_time();
  2000. if (zoom_indicator_delay > 0) {
  2001. zoom_indicator_delay -= delta;
  2002. if (zoom_indicator_delay <= 0) {
  2003. surface->update();
  2004. zoom_limit_label->hide();
  2005. }
  2006. }
  2007. _update_freelook(delta);
  2008. Node *scene_root = editor->get_scene_tree_dock()->get_editor_data()->get_edited_scene_root();
  2009. if (previewing_cinema && scene_root != nullptr) {
  2010. Camera *cam = scene_root->get_viewport()->get_camera();
  2011. if (cam != nullptr && cam != previewing) {
  2012. //then switch the viewport's camera to the scene's viewport camera
  2013. if (previewing != nullptr) {
  2014. previewing->disconnect("tree_exited", this, "_preview_exited_scene");
  2015. }
  2016. previewing = cam;
  2017. previewing->connect("tree_exited", this, "_preview_exited_scene");
  2018. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), cam->get_camera());
  2019. surface->update();
  2020. }
  2021. }
  2022. _update_camera(delta);
  2023. Map<Node *, Object *> &selection = editor_selection->get_selection();
  2024. bool changed = false;
  2025. bool exist = false;
  2026. for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
  2027. Spatial *sp = Object::cast_to<Spatial>(E->key());
  2028. if (!sp) {
  2029. continue;
  2030. }
  2031. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  2032. if (!se) {
  2033. continue;
  2034. }
  2035. Transform t = sp->get_global_gizmo_transform();
  2036. VisualInstance *vi = Object::cast_to<VisualInstance>(sp);
  2037. AABB new_aabb = vi ? vi->get_aabb() : _calculate_spatial_bounds(sp);
  2038. exist = true;
  2039. if (se->last_xform == t && se->aabb == new_aabb && !se->last_xform_dirty) {
  2040. continue;
  2041. }
  2042. changed = true;
  2043. se->last_xform_dirty = false;
  2044. se->last_xform = t;
  2045. se->aabb = new_aabb;
  2046. Transform t_offset = t;
  2047. // apply AABB scaling before item's global transform
  2048. {
  2049. const Vector3 offset(0.005, 0.005, 0.005);
  2050. Basis aabb_s;
  2051. aabb_s.scale(se->aabb.size + offset);
  2052. t.translate(se->aabb.position - offset / 2);
  2053. t.basis = t.basis * aabb_s;
  2054. }
  2055. {
  2056. const Vector3 offset(0.01, 0.01, 0.01);
  2057. Basis aabb_s;
  2058. aabb_s.scale(se->aabb.size + offset);
  2059. t_offset.translate(se->aabb.position - offset / 2);
  2060. t_offset.basis = t_offset.basis * aabb_s;
  2061. }
  2062. VisualServer::get_singleton()->instance_set_transform(se->sbox_instance, t);
  2063. VisualServer::get_singleton()->instance_set_transform(se->sbox_instance_offset, t_offset);
  2064. VisualServer::get_singleton()->instance_set_transform(se->sbox_instance_xray, t);
  2065. VisualServer::get_singleton()->instance_set_transform(se->sbox_instance_xray_offset, t_offset);
  2066. }
  2067. if (changed || (spatial_editor->is_gizmo_visible() && !exist)) {
  2068. spatial_editor->update_transform_gizmo();
  2069. }
  2070. if (message_time > 0) {
  2071. if (message != last_message) {
  2072. surface->update();
  2073. last_message = message;
  2074. }
  2075. message_time -= get_physics_process_delta_time();
  2076. if (message_time < 0) {
  2077. surface->update();
  2078. }
  2079. }
  2080. //update shadow atlas if changed
  2081. int shadowmap_size = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/size");
  2082. int atlas_q0 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_0_subdiv");
  2083. int atlas_q1 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_1_subdiv");
  2084. int atlas_q2 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_2_subdiv");
  2085. int atlas_q3 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_3_subdiv");
  2086. viewport->set_shadow_atlas_size(shadowmap_size);
  2087. viewport->set_shadow_atlas_quadrant_subdiv(0, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q0));
  2088. viewport->set_shadow_atlas_quadrant_subdiv(1, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q1));
  2089. viewport->set_shadow_atlas_quadrant_subdiv(2, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q2));
  2090. viewport->set_shadow_atlas_quadrant_subdiv(3, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q3));
  2091. bool shrink = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION));
  2092. if (shrink != (viewport_container->get_stretch_shrink() > 1)) {
  2093. viewport_container->set_stretch_shrink(shrink ? 2 : 1);
  2094. }
  2095. // Update MSAA, FXAA, debanding and HDR if changed.
  2096. int msaa_mode = ProjectSettings::get_singleton()->get("rendering/quality/filters/msaa");
  2097. viewport->set_msaa(Viewport::MSAA(msaa_mode));
  2098. bool use_fxaa = ProjectSettings::get_singleton()->get("rendering/quality/filters/use_fxaa");
  2099. viewport->set_use_fxaa(use_fxaa);
  2100. bool use_debanding = ProjectSettings::get_singleton()->get("rendering/quality/filters/use_debanding");
  2101. viewport->set_use_debanding(use_debanding);
  2102. float sharpen_intensity = ProjectSettings::get_singleton()->get("rendering/quality/filters/sharpen_intensity");
  2103. viewport->set_sharpen_intensity(sharpen_intensity);
  2104. bool hdr = ProjectSettings::get_singleton()->get("rendering/quality/depth/hdr");
  2105. viewport->set_hdr(hdr);
  2106. bool show_info = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_INFORMATION));
  2107. info_label->set_visible(show_info);
  2108. Camera *current_camera;
  2109. if (previewing) {
  2110. current_camera = previewing;
  2111. } else {
  2112. current_camera = camera;
  2113. }
  2114. if (show_info) {
  2115. const String viewport_size = vformat(String::utf8("%d × %d"), viewport->get_size().x, viewport->get_size().y);
  2116. String text;
  2117. text += "X: " + rtos(current_camera->get_translation().x).pad_decimals(1) + "\n";
  2118. text += "Y: " + rtos(current_camera->get_translation().y).pad_decimals(1) + "\n";
  2119. text += "Z: " + rtos(current_camera->get_translation().z).pad_decimals(1) + "\n";
  2120. text += TTR("Pitch:") + " " + itos(Math::round(current_camera->get_rotation_degrees().x)) + "\n";
  2121. text += TTR("Yaw:") + " " + itos(Math::round(current_camera->get_rotation_degrees().y)) + "\n\n";
  2122. text += TTR("Size:") +
  2123. vformat(
  2124. " %s (%.1fMP)\n",
  2125. viewport_size,
  2126. viewport->get_size().x * viewport->get_size().y * 0.000'001);
  2127. text += TTR("Objects Drawn:") + " " + itos(viewport->get_render_info(Viewport::RENDER_INFO_OBJECTS_IN_FRAME)) + "\n";
  2128. text += TTR("Material Changes:") + " " + itos(viewport->get_render_info(Viewport::RENDER_INFO_MATERIAL_CHANGES_IN_FRAME)) + "\n";
  2129. text += TTR("Shader Changes:") + " " + itos(viewport->get_render_info(Viewport::RENDER_INFO_SHADER_CHANGES_IN_FRAME)) + "\n";
  2130. text += TTR("Surface Changes:") + " " + itos(viewport->get_render_info(Viewport::RENDER_INFO_SURFACE_CHANGES_IN_FRAME)) + "\n";
  2131. text += TTR("Draw Calls:") + " " + itos(viewport->get_render_info(Viewport::RENDER_INFO_DRAW_CALLS_IN_FRAME)) + "\n";
  2132. text += TTR("Vertices:") + " " + itos(viewport->get_render_info(Viewport::RENDER_INFO_VERTICES_IN_FRAME));
  2133. info_label->set_text(text);
  2134. }
  2135. // FPS Counter.
  2136. bool show_fps = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_FPS));
  2137. fps_label->set_visible(show_fps);
  2138. if (show_fps) {
  2139. String text;
  2140. const float temp_fps = Engine::get_singleton()->get_frames_per_second();
  2141. text += vformat(TTR("FPS: %d (%s ms)"), temp_fps, String::num(1000.0f / temp_fps, 2));
  2142. fps_label->set_text(text);
  2143. }
  2144. bool show_cinema = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
  2145. cinema_label->set_visible(show_cinema);
  2146. if (show_cinema) {
  2147. float cinema_half_width = cinema_label->get_size().width / 2.0f;
  2148. cinema_label->set_anchor_and_margin(MARGIN_LEFT, 0.5f, -cinema_half_width);
  2149. }
  2150. if (lock_rotation) {
  2151. float locked_half_width = locked_label->get_size().width / 2.0f;
  2152. locked_label->set_anchor_and_margin(MARGIN_LEFT, 0.5f, -locked_half_width);
  2153. }
  2154. }
  2155. if (p_what == NOTIFICATION_ENTER_TREE) {
  2156. surface->connect("draw", this, "_draw");
  2157. surface->connect("gui_input", this, "_sinput");
  2158. surface->connect("mouse_entered", this, "_surface_mouse_enter");
  2159. surface->connect("mouse_exited", this, "_surface_mouse_exit");
  2160. surface->connect("focus_entered", this, "_surface_focus_enter");
  2161. surface->connect("focus_exited", this, "_surface_focus_exit");
  2162. _init_gizmo_instance(index);
  2163. }
  2164. if (p_what == NOTIFICATION_EXIT_TREE) {
  2165. _finish_gizmo_instances();
  2166. }
  2167. if (p_what == NOTIFICATION_THEME_CHANGED) {
  2168. view_menu->set_icon(get_icon("GuiTabMenuHl", "EditorIcons"));
  2169. preview_camera->set_icon(get_icon("Camera", "EditorIcons"));
  2170. view_menu->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2171. view_menu->add_style_override("hover", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2172. view_menu->add_style_override("pressed", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2173. view_menu->add_style_override("focus", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2174. view_menu->add_style_override("disabled", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2175. preview_camera->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2176. preview_camera->add_style_override("hover", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2177. preview_camera->add_style_override("pressed", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2178. preview_camera->add_style_override("focus", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2179. preview_camera->add_style_override("disabled", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2180. info_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2181. fps_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2182. cinema_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2183. locked_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2184. }
  2185. }
  2186. static void draw_indicator_bar(Control &surface, real_t fill, const Ref<Texture> icon, const Ref<Font> font, const String &text) {
  2187. // Adjust bar size from control height
  2188. const Vector2 surface_size = surface.get_size();
  2189. const real_t h = surface_size.y / 2.0;
  2190. const real_t y = (surface_size.y - h) / 2.0;
  2191. const Rect2 r(10 * EDSCALE, y, 6 * EDSCALE, h);
  2192. const real_t sy = r.size.y * fill;
  2193. // Note: because this bar appears over the viewport, it has to stay readable for any background color
  2194. // Draw both neutral dark and bright colors to account this
  2195. surface.draw_rect(r, Color(1, 1, 1, 0.2));
  2196. surface.draw_rect(Rect2(r.position.x, r.position.y + r.size.y - sy, r.size.x, sy), Color(1, 1, 1, 0.6));
  2197. surface.draw_rect(r.grow(1), Color(0, 0, 0, 0.7), false, Math::round(EDSCALE));
  2198. const Vector2 icon_size = icon->get_size();
  2199. const Vector2 icon_pos = Vector2(r.position.x - (icon_size.x - r.size.x) / 2, r.position.y + r.size.y + 2 * EDSCALE);
  2200. surface.draw_texture(icon, icon_pos);
  2201. // Draw text below the bar (for speed/zoom information).
  2202. surface.draw_string(font, Vector2(icon_pos.x, icon_pos.y + icon_size.y + 16 * EDSCALE), text);
  2203. }
  2204. void SpatialEditorViewport::_draw() {
  2205. EditorPluginList *over_plugin_list = EditorNode::get_singleton()->get_editor_plugins_over();
  2206. if (!over_plugin_list->empty()) {
  2207. over_plugin_list->forward_spatial_draw_over_viewport(surface);
  2208. }
  2209. EditorPluginList *force_over_plugin_list = editor->get_editor_plugins_force_over();
  2210. if (!force_over_plugin_list->empty()) {
  2211. force_over_plugin_list->forward_spatial_force_draw_over_viewport(surface);
  2212. }
  2213. if (surface->has_focus()) {
  2214. Size2 size = surface->get_size();
  2215. Rect2 r = Rect2(Point2(), size);
  2216. get_stylebox("Focus", "EditorStyles")->draw(surface->get_canvas_item(), r);
  2217. }
  2218. if (cursor.region_select) {
  2219. const Rect2 selection_rect = Rect2(cursor.region_begin, cursor.region_end - cursor.region_begin);
  2220. surface->draw_rect(
  2221. selection_rect,
  2222. get_color("box_selection_fill_color", "Editor"));
  2223. surface->draw_rect(
  2224. selection_rect,
  2225. get_color("box_selection_stroke_color", "Editor"),
  2226. false,
  2227. Math::round(EDSCALE));
  2228. }
  2229. RID ci = surface->get_canvas_item();
  2230. if (message_time > 0) {
  2231. Ref<Font> font = get_font("font", "Label");
  2232. Point2 msgpos = Point2(5, get_size().y - 20);
  2233. font->draw(ci, msgpos + Point2(1, 1), message, Color(0, 0, 0, 0.8));
  2234. font->draw(ci, msgpos + Point2(-1, -1), message, Color(0, 0, 0, 0.8));
  2235. font->draw(ci, msgpos, message, Color(1, 1, 1, 1));
  2236. }
  2237. if (_edit.mode == TRANSFORM_ROTATE) {
  2238. Point2 center = _point_to_screen(_edit.center);
  2239. Color handle_color;
  2240. switch (_edit.plane) {
  2241. case TRANSFORM_X_AXIS:
  2242. handle_color = get_color("axis_x_color", "Editor");
  2243. break;
  2244. case TRANSFORM_Y_AXIS:
  2245. handle_color = get_color("axis_y_color", "Editor");
  2246. break;
  2247. case TRANSFORM_Z_AXIS:
  2248. handle_color = get_color("axis_z_color", "Editor");
  2249. break;
  2250. default:
  2251. handle_color = get_color("accent_color", "Editor");
  2252. break;
  2253. }
  2254. handle_color = handle_color.from_hsv(handle_color.get_h(), 0.25, 1.0, 1);
  2255. VisualServer::get_singleton()->canvas_item_add_line(
  2256. ci,
  2257. _edit.mouse_pos,
  2258. center,
  2259. handle_color,
  2260. Math::round(2 * EDSCALE),
  2261. true);
  2262. }
  2263. if (previewing) {
  2264. Size2 ss = Size2(ProjectSettings::get_singleton()->get("display/window/size/width"), ProjectSettings::get_singleton()->get("display/window/size/height"));
  2265. float aspect = ss.aspect();
  2266. Size2 s = get_size();
  2267. Rect2 draw_rect;
  2268. switch (previewing->get_keep_aspect_mode()) {
  2269. case Camera::KEEP_WIDTH: {
  2270. draw_rect.size = Size2(s.width, s.width / aspect);
  2271. draw_rect.position.x = 0;
  2272. draw_rect.position.y = (s.height - draw_rect.size.y) * 0.5;
  2273. } break;
  2274. case Camera::KEEP_HEIGHT: {
  2275. draw_rect.size = Size2(s.height * aspect, s.height);
  2276. draw_rect.position.y = 0;
  2277. draw_rect.position.x = (s.width - draw_rect.size.x) * 0.5;
  2278. } break;
  2279. }
  2280. draw_rect = Rect2(Vector2(), s).clip(draw_rect);
  2281. surface->draw_rect(draw_rect, Color(0.6, 0.6, 0.1, 0.5), false, Math::round(2 * EDSCALE));
  2282. } else {
  2283. if (zoom_indicator_delay > 0.0) {
  2284. if (is_freelook_active()) {
  2285. // Show speed
  2286. real_t min_speed = MAX(camera->get_znear() * 4, ZOOM_FREELOOK_MIN);
  2287. real_t max_speed = MIN(camera->get_zfar() / 2, ZOOM_FREELOOK_MAX);
  2288. real_t scale_length = (max_speed - min_speed);
  2289. if (!Math::is_zero_approx(scale_length)) {
  2290. real_t logscale_t = 1.0 - Math::log(1 + freelook_speed - min_speed) / Math::log(1 + scale_length);
  2291. // Display the freelook speed to help the user get a better sense of scale.
  2292. const int precision = freelook_speed < 1.0 ? 2 : 1;
  2293. draw_indicator_bar(
  2294. *surface,
  2295. 1.0 - logscale_t,
  2296. get_icon("ViewportSpeed", "EditorIcons"),
  2297. get_font("font", "Label"),
  2298. vformat("%s u/s", String::num(freelook_speed).pad_decimals(precision)));
  2299. }
  2300. } else {
  2301. // Show zoom
  2302. zoom_limit_label->set_visible(zoom_failed_attempts_count > 15);
  2303. real_t min_distance = MAX(camera->get_znear() * 4, ZOOM_FREELOOK_MIN);
  2304. real_t max_distance = MIN(camera->get_zfar() / 2, ZOOM_FREELOOK_MAX);
  2305. real_t scale_length = (max_distance - min_distance);
  2306. if (!Math::is_zero_approx(scale_length)) {
  2307. real_t logscale_t = 1.0 - Math::log(1 + cursor.distance - min_distance) / Math::log(1 + scale_length);
  2308. // Display the zoom center distance to help the user get a better sense of scale.
  2309. const int precision = cursor.distance < 1.0 ? 2 : 1;
  2310. draw_indicator_bar(
  2311. *surface,
  2312. logscale_t,
  2313. get_icon("ViewportZoom", "EditorIcons"),
  2314. get_font("font", "Label"),
  2315. vformat("%s u", String::num(cursor.distance).pad_decimals(precision)));
  2316. }
  2317. }
  2318. }
  2319. }
  2320. }
  2321. void SpatialEditorViewport::_menu_option(int p_option) {
  2322. switch (p_option) {
  2323. case VIEW_TOP: {
  2324. cursor.y_rot = 0;
  2325. cursor.x_rot = Math_PI / 2.0;
  2326. set_message(TTR("Top View."), 2);
  2327. view_type = VIEW_TYPE_TOP;
  2328. _set_auto_orthogonal();
  2329. _update_name();
  2330. } break;
  2331. case VIEW_BOTTOM: {
  2332. cursor.y_rot = 0;
  2333. cursor.x_rot = -Math_PI / 2.0;
  2334. set_message(TTR("Bottom View."), 2);
  2335. view_type = VIEW_TYPE_BOTTOM;
  2336. _set_auto_orthogonal();
  2337. _update_name();
  2338. } break;
  2339. case VIEW_LEFT: {
  2340. cursor.x_rot = 0;
  2341. cursor.y_rot = Math_PI / 2.0;
  2342. set_message(TTR("Left View."), 2);
  2343. view_type = VIEW_TYPE_LEFT;
  2344. _set_auto_orthogonal();
  2345. _update_name();
  2346. } break;
  2347. case VIEW_RIGHT: {
  2348. cursor.x_rot = 0;
  2349. cursor.y_rot = -Math_PI / 2.0;
  2350. set_message(TTR("Right View."), 2);
  2351. view_type = VIEW_TYPE_RIGHT;
  2352. _set_auto_orthogonal();
  2353. _update_name();
  2354. } break;
  2355. case VIEW_FRONT: {
  2356. cursor.x_rot = 0;
  2357. cursor.y_rot = Math_PI;
  2358. set_message(TTR("Front View."), 2);
  2359. view_type = VIEW_TYPE_FRONT;
  2360. _set_auto_orthogonal();
  2361. _update_name();
  2362. } break;
  2363. case VIEW_REAR: {
  2364. cursor.x_rot = 0;
  2365. cursor.y_rot = 0;
  2366. set_message(TTR("Rear View."), 2);
  2367. view_type = VIEW_TYPE_REAR;
  2368. _set_auto_orthogonal();
  2369. _update_name();
  2370. } break;
  2371. case VIEW_CENTER_TO_ORIGIN: {
  2372. cursor.pos = Vector3(0, 0, 0);
  2373. } break;
  2374. case VIEW_CENTER_TO_SELECTION: {
  2375. focus_selection();
  2376. } break;
  2377. case VIEW_ALIGN_TRANSFORM_WITH_VIEW: {
  2378. if (!get_selected_count()) {
  2379. break;
  2380. }
  2381. Transform camera_transform = camera->get_global_transform();
  2382. List<Node *> &selection = editor_selection->get_selected_node_list();
  2383. undo_redo->create_action(TTR("Align Transform with View"));
  2384. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  2385. Spatial *sp = Object::cast_to<Spatial>(E->get());
  2386. if (!sp) {
  2387. continue;
  2388. }
  2389. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  2390. if (!se) {
  2391. continue;
  2392. }
  2393. Transform xform;
  2394. if (orthogonal) {
  2395. xform = sp->get_global_transform();
  2396. xform.basis.set_euler(camera_transform.basis.get_euler());
  2397. } else {
  2398. xform = camera_transform;
  2399. xform.scale_basis(sp->get_scale());
  2400. }
  2401. undo_redo->add_do_method(sp, "set_global_transform", xform);
  2402. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
  2403. }
  2404. undo_redo->commit_action();
  2405. } break;
  2406. case VIEW_ALIGN_ROTATION_WITH_VIEW: {
  2407. if (!get_selected_count()) {
  2408. break;
  2409. }
  2410. Transform camera_transform = camera->get_global_transform();
  2411. List<Node *> &selection = editor_selection->get_selected_node_list();
  2412. undo_redo->create_action(TTR("Align Rotation with View"));
  2413. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  2414. Spatial *sp = Object::cast_to<Spatial>(E->get());
  2415. if (!sp) {
  2416. continue;
  2417. }
  2418. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  2419. if (!se) {
  2420. continue;
  2421. }
  2422. undo_redo->add_do_method(sp, "set_rotation", camera_transform.basis.get_rotation());
  2423. undo_redo->add_undo_method(sp, "set_rotation", sp->get_rotation());
  2424. }
  2425. undo_redo->commit_action();
  2426. } break;
  2427. case VIEW_ENVIRONMENT: {
  2428. int idx = view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT);
  2429. bool current = view_menu->get_popup()->is_item_checked(idx);
  2430. current = !current;
  2431. if (current) {
  2432. camera->set_environment(RES());
  2433. } else {
  2434. camera->set_environment(SpatialEditor::get_singleton()->get_viewport_environment());
  2435. }
  2436. view_menu->get_popup()->set_item_checked(idx, current);
  2437. } break;
  2438. case VIEW_PERSPECTIVE: {
  2439. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
  2440. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), false);
  2441. orthogonal = false;
  2442. auto_orthogonal = false;
  2443. call_deferred("update_transform_gizmo_view");
  2444. _update_name();
  2445. } break;
  2446. case VIEW_ORTHOGONAL: {
  2447. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), false);
  2448. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), true);
  2449. orthogonal = true;
  2450. auto_orthogonal = false;
  2451. call_deferred("update_transform_gizmo_view");
  2452. _update_name();
  2453. } break;
  2454. case VIEW_AUTO_ORTHOGONAL: {
  2455. int idx = view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL);
  2456. bool current = view_menu->get_popup()->is_item_checked(idx);
  2457. current = !current;
  2458. view_menu->get_popup()->set_item_checked(idx, current);
  2459. if (auto_orthogonal) {
  2460. auto_orthogonal = false;
  2461. _update_name();
  2462. }
  2463. } break;
  2464. case VIEW_LOCK_ROTATION: {
  2465. int idx = view_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
  2466. bool current = view_menu->get_popup()->is_item_checked(idx);
  2467. lock_rotation = !current;
  2468. view_menu->get_popup()->set_item_checked(idx, !current);
  2469. if (lock_rotation) {
  2470. locked_label->show();
  2471. } else {
  2472. locked_label->hide();
  2473. }
  2474. } break;
  2475. case VIEW_AUDIO_LISTENER: {
  2476. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
  2477. bool current = view_menu->get_popup()->is_item_checked(idx);
  2478. current = !current;
  2479. viewport->set_as_audio_listener(current);
  2480. view_menu->get_popup()->set_item_checked(idx, current);
  2481. } break;
  2482. case VIEW_AUDIO_DOPPLER: {
  2483. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
  2484. bool current = view_menu->get_popup()->is_item_checked(idx);
  2485. current = !current;
  2486. camera->set_doppler_tracking(current ? Camera::DOPPLER_TRACKING_IDLE_STEP : Camera::DOPPLER_TRACKING_DISABLED);
  2487. view_menu->get_popup()->set_item_checked(idx, current);
  2488. } break;
  2489. case VIEW_CINEMATIC_PREVIEW: {
  2490. int idx = view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
  2491. bool current = view_menu->get_popup()->is_item_checked(idx);
  2492. current = !current;
  2493. view_menu->get_popup()->set_item_checked(idx, current);
  2494. previewing_cinema = true;
  2495. _toggle_cinema_preview(current);
  2496. if (current) {
  2497. preview_camera->hide();
  2498. } else {
  2499. if (previewing != nullptr) {
  2500. preview_camera->show();
  2501. }
  2502. }
  2503. } break;
  2504. case VIEW_GIZMOS: {
  2505. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  2506. bool current = view_menu->get_popup()->is_item_checked(idx);
  2507. current = !current;
  2508. uint32_t layers = ((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + index)) | (1 << GIZMO_GRID_LAYER) | (1 << MISC_TOOL_LAYER);
  2509. if (current) {
  2510. layers |= (1 << GIZMO_EDIT_LAYER);
  2511. }
  2512. camera->set_cull_mask(layers);
  2513. view_menu->get_popup()->set_item_checked(idx, current);
  2514. } break;
  2515. case VIEW_HALF_RESOLUTION: {
  2516. int idx = view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
  2517. bool current = view_menu->get_popup()->is_item_checked(idx);
  2518. current = !current;
  2519. view_menu->get_popup()->set_item_checked(idx, current);
  2520. } break;
  2521. case VIEW_INFORMATION: {
  2522. int idx = view_menu->get_popup()->get_item_index(VIEW_INFORMATION);
  2523. bool current = view_menu->get_popup()->is_item_checked(idx);
  2524. view_menu->get_popup()->set_item_checked(idx, !current);
  2525. } break;
  2526. case VIEW_FPS: {
  2527. int idx = view_menu->get_popup()->get_item_index(VIEW_FPS);
  2528. bool current = view_menu->get_popup()->is_item_checked(idx);
  2529. view_menu->get_popup()->set_item_checked(idx, !current);
  2530. } break;
  2531. case VIEW_DISPLAY_NORMAL: {
  2532. viewport->set_debug_draw(Viewport::DEBUG_DRAW_DISABLED);
  2533. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), true);
  2534. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), false);
  2535. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), false);
  2536. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), false);
  2537. } break;
  2538. case VIEW_DISPLAY_WIREFRAME: {
  2539. viewport->set_debug_draw(Viewport::DEBUG_DRAW_WIREFRAME);
  2540. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), false);
  2541. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), true);
  2542. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), false);
  2543. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), false);
  2544. } break;
  2545. case VIEW_DISPLAY_OVERDRAW: {
  2546. viewport->set_debug_draw(Viewport::DEBUG_DRAW_OVERDRAW);
  2547. VisualServer::get_singleton()->scenario_set_debug(get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_OVERDRAW);
  2548. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), false);
  2549. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), false);
  2550. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), true);
  2551. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), false);
  2552. } break;
  2553. case VIEW_DISPLAY_SHADELESS: {
  2554. viewport->set_debug_draw(Viewport::DEBUG_DRAW_UNSHADED);
  2555. VisualServer::get_singleton()->scenario_set_debug(get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_SHADELESS);
  2556. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), false);
  2557. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), false);
  2558. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), false);
  2559. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), true);
  2560. } break;
  2561. }
  2562. }
  2563. void SpatialEditorViewport::_set_auto_orthogonal() {
  2564. if (!orthogonal && view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL))) {
  2565. _menu_option(VIEW_ORTHOGONAL);
  2566. auto_orthogonal = true;
  2567. }
  2568. }
  2569. void SpatialEditorViewport::_preview_exited_scene() {
  2570. preview_camera->disconnect("toggled", this, "_toggle_camera_preview");
  2571. preview_camera->set_pressed(false);
  2572. _toggle_camera_preview(false);
  2573. preview_camera->connect("toggled", this, "_toggle_camera_preview");
  2574. view_menu->show();
  2575. }
  2576. void SpatialEditorViewport::_init_gizmo_instance(int p_idx) {
  2577. uint32_t layer = 1 << (GIZMO_BASE_LAYER + p_idx);
  2578. for (int i = 0; i < 3; i++) {
  2579. move_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2580. VS::get_singleton()->instance_set_base(move_gizmo_instance[i], spatial_editor->get_move_gizmo(i)->get_rid());
  2581. VS::get_singleton()->instance_set_scenario(move_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2582. VS::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  2583. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2584. VS::get_singleton()->instance_set_layer_mask(move_gizmo_instance[i], layer);
  2585. VS::get_singleton()->instance_set_portal_mode(move_gizmo_instance[i], VisualServer::INSTANCE_PORTAL_MODE_GLOBAL);
  2586. move_plane_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2587. VS::get_singleton()->instance_set_base(move_plane_gizmo_instance[i], spatial_editor->get_move_plane_gizmo(i)->get_rid());
  2588. VS::get_singleton()->instance_set_scenario(move_plane_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2589. VS::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  2590. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_plane_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2591. VS::get_singleton()->instance_set_layer_mask(move_plane_gizmo_instance[i], layer);
  2592. VS::get_singleton()->instance_set_portal_mode(move_plane_gizmo_instance[i], VisualServer::INSTANCE_PORTAL_MODE_GLOBAL);
  2593. rotate_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2594. VS::get_singleton()->instance_set_base(rotate_gizmo_instance[i], spatial_editor->get_rotate_gizmo(i)->get_rid());
  2595. VS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2596. VS::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  2597. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2598. VS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[i], layer);
  2599. VS::get_singleton()->instance_set_portal_mode(rotate_gizmo_instance[i], VisualServer::INSTANCE_PORTAL_MODE_GLOBAL);
  2600. scale_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2601. VS::get_singleton()->instance_set_base(scale_gizmo_instance[i], spatial_editor->get_scale_gizmo(i)->get_rid());
  2602. VS::get_singleton()->instance_set_scenario(scale_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2603. VS::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  2604. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2605. VS::get_singleton()->instance_set_layer_mask(scale_gizmo_instance[i], layer);
  2606. VS::get_singleton()->instance_set_portal_mode(scale_gizmo_instance[i], VisualServer::INSTANCE_PORTAL_MODE_GLOBAL);
  2607. scale_plane_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2608. VS::get_singleton()->instance_set_base(scale_plane_gizmo_instance[i], spatial_editor->get_scale_plane_gizmo(i)->get_rid());
  2609. VS::get_singleton()->instance_set_scenario(scale_plane_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2610. VS::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  2611. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_plane_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2612. VS::get_singleton()->instance_set_layer_mask(scale_plane_gizmo_instance[i], layer);
  2613. VS::get_singleton()->instance_set_portal_mode(scale_plane_gizmo_instance[i], VisualServer::INSTANCE_PORTAL_MODE_GLOBAL);
  2614. }
  2615. // Rotation white outline
  2616. rotate_gizmo_instance[3] = VS::get_singleton()->instance_create();
  2617. VS::get_singleton()->instance_set_base(rotate_gizmo_instance[3], spatial_editor->get_rotate_gizmo(3)->get_rid());
  2618. VS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[3], get_tree()->get_root()->get_world()->get_scenario());
  2619. VS::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
  2620. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[3], VS::SHADOW_CASTING_SETTING_OFF);
  2621. VS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[3], layer);
  2622. }
  2623. void SpatialEditorViewport::_finish_gizmo_instances() {
  2624. for (int i = 0; i < 3; i++) {
  2625. VS::get_singleton()->free(move_gizmo_instance[i]);
  2626. VS::get_singleton()->free(move_plane_gizmo_instance[i]);
  2627. VS::get_singleton()->free(rotate_gizmo_instance[i]);
  2628. VS::get_singleton()->free(scale_gizmo_instance[i]);
  2629. VS::get_singleton()->free(scale_plane_gizmo_instance[i]);
  2630. }
  2631. // Rotation white outline
  2632. VS::get_singleton()->free(rotate_gizmo_instance[3]);
  2633. }
  2634. void SpatialEditorViewport::_toggle_camera_preview(bool p_activate) {
  2635. ERR_FAIL_COND(p_activate && !preview);
  2636. ERR_FAIL_COND(!p_activate && !previewing);
  2637. rotation_control->set_visible(!p_activate);
  2638. if (!p_activate) {
  2639. previewing->disconnect("tree_exiting", this, "_preview_exited_scene");
  2640. previewing = nullptr;
  2641. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
  2642. if (!preview) {
  2643. preview_camera->hide();
  2644. }
  2645. surface->update();
  2646. } else {
  2647. previewing = preview;
  2648. previewing->connect("tree_exiting", this, "_preview_exited_scene");
  2649. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), preview->get_camera()); //replace
  2650. surface->update();
  2651. }
  2652. }
  2653. void SpatialEditorViewport::_toggle_cinema_preview(bool p_activate) {
  2654. previewing_cinema = p_activate;
  2655. rotation_control->set_visible(!p_activate);
  2656. if (!previewing_cinema) {
  2657. if (previewing != nullptr) {
  2658. previewing->disconnect("tree_exited", this, "_preview_exited_scene");
  2659. }
  2660. previewing = nullptr;
  2661. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
  2662. preview_camera->set_pressed(false);
  2663. if (!preview) {
  2664. preview_camera->hide();
  2665. } else {
  2666. preview_camera->show();
  2667. }
  2668. view_menu->show();
  2669. surface->update();
  2670. }
  2671. }
  2672. void SpatialEditorViewport::_selection_result_pressed(int p_result) {
  2673. if (selection_results.size() <= p_result) {
  2674. return;
  2675. }
  2676. clicked = selection_results[p_result].item->get_instance_id();
  2677. if (clicked) {
  2678. _select_clicked(clicked_wants_append, true, spatial_editor->get_tool_mode() != SpatialEditor::TOOL_MODE_LIST_SELECT);
  2679. clicked = 0;
  2680. }
  2681. }
  2682. void SpatialEditorViewport::_selection_menu_hide() {
  2683. selection_results.clear();
  2684. selection_menu->clear();
  2685. selection_menu->set_size(Vector2(0, 0));
  2686. }
  2687. void SpatialEditorViewport::set_can_preview(Camera *p_preview) {
  2688. preview = p_preview;
  2689. if (!preview_camera->is_pressed() && !previewing_cinema) {
  2690. preview_camera->set_visible(p_preview);
  2691. }
  2692. }
  2693. void SpatialEditorViewport::update_transform_gizmo_view() {
  2694. if (!is_visible_in_tree()) {
  2695. return;
  2696. }
  2697. Transform xform = spatial_editor->get_gizmo_transform();
  2698. Transform camera_xform = camera->get_transform();
  2699. if (xform.origin.distance_squared_to(camera_xform.origin) < 0.01) {
  2700. for (int i = 0; i < 3; i++) {
  2701. VisualServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  2702. VisualServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  2703. VisualServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  2704. VisualServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  2705. VisualServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  2706. }
  2707. // Rotation white outline
  2708. VisualServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
  2709. return;
  2710. }
  2711. Vector3 camz = -camera_xform.get_basis().get_axis(2).normalized();
  2712. Vector3 camy = -camera_xform.get_basis().get_axis(1).normalized();
  2713. Plane p(camera_xform.origin, camz);
  2714. float gizmo_d = MAX(Math::abs(p.distance_to(xform.origin)), CMP_EPSILON);
  2715. float d0 = camera->unproject_position(camera_xform.origin + camz * gizmo_d).y;
  2716. float d1 = camera->unproject_position(camera_xform.origin + camz * gizmo_d + camy).y;
  2717. float dd = Math::abs(d0 - d1);
  2718. if (dd == 0) {
  2719. dd = 0.0001;
  2720. }
  2721. float gizmo_size = EditorSettings::get_singleton()->get("editors/3d/manipulator_gizmo_size");
  2722. // At low viewport heights, multiply the gizmo scale based on the viewport height.
  2723. // This prevents the gizmo from growing very large and going outside the viewport.
  2724. const int viewport_base_height = 400 * MAX(1, EDSCALE);
  2725. gizmo_scale =
  2726. (gizmo_size / Math::abs(dd)) * MAX(1, EDSCALE) *
  2727. MIN(viewport_base_height, viewport_container->get_size().height) / viewport_base_height /
  2728. viewport_container->get_stretch_shrink();
  2729. Vector3 scale = Vector3(1, 1, 1) * gizmo_scale;
  2730. xform.basis.scale(scale);
  2731. for (int i = 0; i < 3; i++) {
  2732. VisualServer::get_singleton()->instance_set_transform(move_gizmo_instance[i], xform);
  2733. 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));
  2734. VisualServer::get_singleton()->instance_set_transform(move_plane_gizmo_instance[i], xform);
  2735. 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));
  2736. VisualServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[i], xform);
  2737. 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));
  2738. VisualServer::get_singleton()->instance_set_transform(scale_gizmo_instance[i], xform);
  2739. VisualServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SCALE));
  2740. VisualServer::get_singleton()->instance_set_transform(scale_plane_gizmo_instance[i], xform);
  2741. 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));
  2742. }
  2743. // Rotation white outline
  2744. VisualServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[3], xform);
  2745. VisualServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_ROTATE));
  2746. }
  2747. void SpatialEditorViewport::set_state(const Dictionary &p_state) {
  2748. if (p_state.has("position")) {
  2749. cursor.pos = p_state["position"];
  2750. }
  2751. if (p_state.has("x_rotation")) {
  2752. cursor.x_rot = p_state["x_rotation"];
  2753. }
  2754. if (p_state.has("y_rotation")) {
  2755. cursor.y_rot = p_state["y_rotation"];
  2756. }
  2757. if (p_state.has("distance")) {
  2758. cursor.distance = p_state["distance"];
  2759. }
  2760. if (p_state.has("use_orthogonal")) {
  2761. bool orth = p_state["use_orthogonal"];
  2762. if (orth) {
  2763. _menu_option(VIEW_ORTHOGONAL);
  2764. } else {
  2765. _menu_option(VIEW_PERSPECTIVE);
  2766. }
  2767. }
  2768. if (p_state.has("view_type")) {
  2769. view_type = ViewType(p_state["view_type"].operator int());
  2770. _update_name();
  2771. }
  2772. if (p_state.has("auto_orthogonal")) {
  2773. auto_orthogonal = p_state["auto_orthogonal"];
  2774. _update_name();
  2775. }
  2776. if (p_state.has("auto_orthogonal_enabled")) {
  2777. bool enabled = p_state["auto_orthogonal_enabled"];
  2778. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL), enabled);
  2779. }
  2780. if (p_state.has("display_mode")) {
  2781. int display = p_state["display_mode"];
  2782. int idx = view_menu->get_popup()->get_item_index(display);
  2783. if (!view_menu->get_popup()->is_item_checked(idx)) {
  2784. _menu_option(display);
  2785. }
  2786. }
  2787. if (p_state.has("lock_rotation")) {
  2788. lock_rotation = p_state["lock_rotation"];
  2789. int idx = view_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
  2790. view_menu->get_popup()->set_item_checked(idx, lock_rotation);
  2791. }
  2792. if (p_state.has("use_environment")) {
  2793. bool env = p_state["use_environment"];
  2794. if (env != camera->get_environment().is_valid()) {
  2795. _menu_option(VIEW_ENVIRONMENT);
  2796. }
  2797. }
  2798. if (p_state.has("listener")) {
  2799. bool listener = p_state["listener"];
  2800. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
  2801. viewport->set_as_audio_listener(listener);
  2802. view_menu->get_popup()->set_item_checked(idx, listener);
  2803. }
  2804. if (p_state.has("doppler")) {
  2805. bool doppler = p_state["doppler"];
  2806. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
  2807. camera->set_doppler_tracking(doppler ? Camera::DOPPLER_TRACKING_IDLE_STEP : Camera::DOPPLER_TRACKING_DISABLED);
  2808. view_menu->get_popup()->set_item_checked(idx, doppler);
  2809. }
  2810. if (p_state.has("gizmos")) {
  2811. bool gizmos = p_state["gizmos"];
  2812. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  2813. if (view_menu->get_popup()->is_item_checked(idx) != gizmos) {
  2814. _menu_option(VIEW_GIZMOS);
  2815. }
  2816. }
  2817. if (p_state.has("information")) {
  2818. bool information = p_state["information"];
  2819. int idx = view_menu->get_popup()->get_item_index(VIEW_INFORMATION);
  2820. if (view_menu->get_popup()->is_item_checked(idx) != information) {
  2821. _menu_option(VIEW_INFORMATION);
  2822. }
  2823. }
  2824. if (p_state.has("fps")) {
  2825. bool fps = p_state["fps"];
  2826. int idx = view_menu->get_popup()->get_item_index(VIEW_FPS);
  2827. if (view_menu->get_popup()->is_item_checked(idx) != fps) {
  2828. _menu_option(VIEW_FPS);
  2829. }
  2830. }
  2831. if (p_state.has("half_res")) {
  2832. bool half_res = p_state["half_res"];
  2833. int idx = view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
  2834. view_menu->get_popup()->set_item_checked(idx, half_res);
  2835. }
  2836. if (p_state.has("cinematic_preview")) {
  2837. previewing_cinema = p_state["cinematic_preview"];
  2838. int idx = view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
  2839. view_menu->get_popup()->set_item_checked(idx, previewing_cinema);
  2840. }
  2841. if (preview_camera->is_connected("toggled", this, "_toggle_camera_preview")) {
  2842. preview_camera->disconnect("toggled", this, "_toggle_camera_preview");
  2843. }
  2844. if (p_state.has("previewing")) {
  2845. Node *pv = EditorNode::get_singleton()->get_edited_scene()->get_node(p_state["previewing"]);
  2846. if (Object::cast_to<Camera>(pv)) {
  2847. previewing = Object::cast_to<Camera>(pv);
  2848. previewing->connect("tree_exiting", this, "_preview_exited_scene");
  2849. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), previewing->get_camera()); //replace
  2850. surface->update();
  2851. preview_camera->set_pressed(true);
  2852. preview_camera->show();
  2853. }
  2854. }
  2855. preview_camera->connect("toggled", this, "_toggle_camera_preview");
  2856. }
  2857. Dictionary SpatialEditorViewport::get_state() const {
  2858. Dictionary d;
  2859. d["position"] = cursor.pos;
  2860. d["x_rotation"] = cursor.x_rot;
  2861. d["y_rotation"] = cursor.y_rot;
  2862. d["distance"] = cursor.distance;
  2863. d["use_environment"] = camera->get_environment().is_valid();
  2864. d["use_orthogonal"] = camera->get_projection() == Camera::PROJECTION_ORTHOGONAL;
  2865. d["view_type"] = view_type;
  2866. d["auto_orthogonal"] = auto_orthogonal;
  2867. d["auto_orthogonal_enabled"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL));
  2868. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL))) {
  2869. d["display_mode"] = VIEW_DISPLAY_NORMAL;
  2870. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME))) {
  2871. d["display_mode"] = VIEW_DISPLAY_WIREFRAME;
  2872. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW))) {
  2873. d["display_mode"] = VIEW_DISPLAY_OVERDRAW;
  2874. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS))) {
  2875. d["display_mode"] = VIEW_DISPLAY_SHADELESS;
  2876. }
  2877. d["listener"] = viewport->is_audio_listener();
  2878. d["doppler"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER));
  2879. d["gizmos"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_GIZMOS));
  2880. d["information"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_INFORMATION));
  2881. d["fps"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_FPS));
  2882. d["half_res"] = viewport_container->get_stretch_shrink() > 1;
  2883. d["cinematic_preview"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
  2884. if (previewing) {
  2885. d["previewing"] = EditorNode::get_singleton()->get_edited_scene()->get_path_to(previewing);
  2886. }
  2887. if (lock_rotation) {
  2888. d["lock_rotation"] = lock_rotation;
  2889. }
  2890. return d;
  2891. }
  2892. void SpatialEditorViewport::_bind_methods() {
  2893. ClassDB::bind_method(D_METHOD("_draw"), &SpatialEditorViewport::_draw);
  2894. ClassDB::bind_method(D_METHOD("_surface_mouse_enter"), &SpatialEditorViewport::_surface_mouse_enter);
  2895. ClassDB::bind_method(D_METHOD("_surface_mouse_exit"), &SpatialEditorViewport::_surface_mouse_exit);
  2896. ClassDB::bind_method(D_METHOD("_surface_focus_enter"), &SpatialEditorViewport::_surface_focus_enter);
  2897. ClassDB::bind_method(D_METHOD("_surface_focus_exit"), &SpatialEditorViewport::_surface_focus_exit);
  2898. ClassDB::bind_method(D_METHOD("_sinput"), &SpatialEditorViewport::_sinput);
  2899. ClassDB::bind_method(D_METHOD("_menu_option"), &SpatialEditorViewport::_menu_option);
  2900. ClassDB::bind_method(D_METHOD("_toggle_camera_preview"), &SpatialEditorViewport::_toggle_camera_preview);
  2901. ClassDB::bind_method(D_METHOD("_preview_exited_scene"), &SpatialEditorViewport::_preview_exited_scene);
  2902. ClassDB::bind_method(D_METHOD("_update_camera"), &SpatialEditorViewport::_update_camera);
  2903. ClassDB::bind_method(D_METHOD("update_transform_gizmo_view"), &SpatialEditorViewport::update_transform_gizmo_view);
  2904. ClassDB::bind_method(D_METHOD("_selection_result_pressed"), &SpatialEditorViewport::_selection_result_pressed);
  2905. ClassDB::bind_method(D_METHOD("_selection_menu_hide"), &SpatialEditorViewport::_selection_menu_hide);
  2906. ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &SpatialEditorViewport::can_drop_data_fw);
  2907. ClassDB::bind_method(D_METHOD("drop_data_fw"), &SpatialEditorViewport::drop_data_fw);
  2908. ADD_SIGNAL(MethodInfo("toggle_maximize_view", PropertyInfo(Variant::OBJECT, "viewport")));
  2909. ADD_SIGNAL(MethodInfo("clicked", PropertyInfo(Variant::OBJECT, "viewport")));
  2910. }
  2911. void SpatialEditorViewport::reset() {
  2912. orthogonal = false;
  2913. auto_orthogonal = false;
  2914. lock_rotation = false;
  2915. message_time = 0;
  2916. message = "";
  2917. last_message = "";
  2918. view_type = VIEW_TYPE_USER;
  2919. cursor = Cursor();
  2920. _update_name();
  2921. }
  2922. void SpatialEditorViewport::focus_selection() {
  2923. Vector3 center;
  2924. int count = 0;
  2925. List<Node *> &selection = editor_selection->get_selected_node_list();
  2926. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  2927. Spatial *sp = Object::cast_to<Spatial>(E->get());
  2928. if (!sp) {
  2929. continue;
  2930. }
  2931. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  2932. if (!se) {
  2933. continue;
  2934. }
  2935. center += sp->get_global_gizmo_transform().origin;
  2936. count++;
  2937. }
  2938. if (count != 0) {
  2939. center /= float(count);
  2940. }
  2941. cursor.pos = center;
  2942. }
  2943. void SpatialEditorViewport::assign_pending_data_pointers(Spatial *p_preview_node, AABB *p_preview_bounds, AcceptDialog *p_accept) {
  2944. preview_node = p_preview_node;
  2945. preview_bounds = p_preview_bounds;
  2946. accept = p_accept;
  2947. }
  2948. Vector3 SpatialEditorViewport::_get_instance_position(const Point2 &p_pos) const {
  2949. const float MAX_DISTANCE = 50.0;
  2950. Vector3 world_ray = _get_ray(p_pos);
  2951. Vector3 world_pos = _get_ray_pos(p_pos);
  2952. Vector3 point = world_pos + world_ray * MAX_DISTANCE;
  2953. PhysicsDirectSpaceState *ss = get_tree()->get_root()->get_world()->get_direct_space_state();
  2954. PhysicsDirectSpaceState::RayResult result;
  2955. if (ss->intersect_ray(world_pos, world_pos + world_ray * MAX_DISTANCE, result)) {
  2956. point = result.position;
  2957. }
  2958. return point;
  2959. }
  2960. AABB SpatialEditorViewport::_calculate_spatial_bounds(const Spatial *p_parent, bool p_exclude_toplevel_transform) {
  2961. AABB bounds;
  2962. const VisualInstance *visual_instance = Object::cast_to<VisualInstance>(p_parent);
  2963. if (visual_instance) {
  2964. bounds = visual_instance->get_aabb();
  2965. }
  2966. for (int i = 0; i < p_parent->get_child_count(); i++) {
  2967. Spatial *child = Object::cast_to<Spatial>(p_parent->get_child(i));
  2968. if (child) {
  2969. AABB child_bounds = _calculate_spatial_bounds(child, false);
  2970. if (bounds.size == Vector3() && p_parent->get_class_name() == StringName("Spatial")) {
  2971. bounds = child_bounds;
  2972. } else {
  2973. bounds.merge_with(child_bounds);
  2974. }
  2975. }
  2976. }
  2977. if (bounds.size == Vector3() && p_parent->get_class_name() != StringName("Spatial")) {
  2978. bounds = AABB(Vector3(-0.2, -0.2, -0.2), Vector3(0.4, 0.4, 0.4));
  2979. }
  2980. if (!p_exclude_toplevel_transform) {
  2981. bounds = p_parent->get_transform().xform(bounds);
  2982. }
  2983. return bounds;
  2984. }
  2985. void SpatialEditorViewport::_create_preview(const Vector<String> &files) const {
  2986. for (int i = 0; i < files.size(); i++) {
  2987. String path = files[i];
  2988. RES res = ResourceLoader::load(path);
  2989. ERR_CONTINUE(res.is_null());
  2990. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  2991. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  2992. if (mesh != nullptr || scene != nullptr) {
  2993. if (mesh != nullptr) {
  2994. MeshInstance *mesh_instance = memnew(MeshInstance);
  2995. mesh_instance->set_mesh(mesh);
  2996. preview_node->add_child(mesh_instance);
  2997. } else {
  2998. if (scene.is_valid()) {
  2999. Node *instance = scene->instance();
  3000. if (instance) {
  3001. preview_node->add_child(instance);
  3002. }
  3003. }
  3004. }
  3005. editor->get_scene_root()->add_child(preview_node);
  3006. }
  3007. }
  3008. *preview_bounds = _calculate_spatial_bounds(preview_node);
  3009. }
  3010. void SpatialEditorViewport::_remove_preview() {
  3011. if (preview_node->get_parent()) {
  3012. for (int i = preview_node->get_child_count() - 1; i >= 0; i--) {
  3013. Node *node = preview_node->get_child(i);
  3014. node->queue_delete();
  3015. preview_node->remove_child(node);
  3016. }
  3017. editor->get_scene_root()->remove_child(preview_node);
  3018. }
  3019. }
  3020. bool SpatialEditorViewport::_cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node) {
  3021. if (p_desired_node->get_filename() == p_target_scene_path) {
  3022. return true;
  3023. }
  3024. int childCount = p_desired_node->get_child_count();
  3025. for (int i = 0; i < childCount; i++) {
  3026. Node *child = p_desired_node->get_child(i);
  3027. if (_cyclical_dependency_exists(p_target_scene_path, child)) {
  3028. return true;
  3029. }
  3030. }
  3031. return false;
  3032. }
  3033. bool SpatialEditorViewport::_create_instance(Node *parent, String &path, const Point2 &p_point) {
  3034. RES res = ResourceLoader::load(path);
  3035. ERR_FAIL_COND_V(res.is_null(), false);
  3036. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  3037. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  3038. Node *instanced_scene = nullptr;
  3039. if (mesh != nullptr || scene != nullptr) {
  3040. if (mesh != nullptr) {
  3041. MeshInstance *mesh_instance = memnew(MeshInstance);
  3042. mesh_instance->set_mesh(mesh);
  3043. mesh_instance->set_name(path.get_file().get_basename());
  3044. instanced_scene = mesh_instance;
  3045. } else {
  3046. if (!scene.is_valid()) { // invalid scene
  3047. return false;
  3048. } else {
  3049. instanced_scene = scene->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
  3050. }
  3051. }
  3052. }
  3053. if (instanced_scene == nullptr) {
  3054. return false;
  3055. }
  3056. if (editor->get_edited_scene()->get_filename() != "") { // cyclical instancing
  3057. if (_cyclical_dependency_exists(editor->get_edited_scene()->get_filename(), instanced_scene)) {
  3058. memdelete(instanced_scene);
  3059. return false;
  3060. }
  3061. }
  3062. if (scene != nullptr) {
  3063. instanced_scene->set_filename(ProjectSettings::get_singleton()->localize_path(path));
  3064. }
  3065. editor_data->get_undo_redo().add_do_method(parent, "add_child", instanced_scene);
  3066. editor_data->get_undo_redo().add_do_method(instanced_scene, "set_owner", editor->get_edited_scene());
  3067. editor_data->get_undo_redo().add_do_reference(instanced_scene);
  3068. editor_data->get_undo_redo().add_undo_method(parent, "remove_child", instanced_scene);
  3069. String new_name = parent->validate_child_name(instanced_scene);
  3070. ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger();
  3071. editor_data->get_undo_redo().add_do_method(sed, "live_debug_instance_node", editor->get_edited_scene()->get_path_to(parent), path, new_name);
  3072. 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));
  3073. Spatial *spatial = Object::cast_to<Spatial>(instanced_scene);
  3074. if (spatial) {
  3075. Transform global_transform;
  3076. Spatial *parent_spatial = Object::cast_to<Spatial>(parent);
  3077. if (parent_spatial) {
  3078. global_transform = parent_spatial->get_global_gizmo_transform();
  3079. }
  3080. global_transform.origin = spatial_editor->snap_point(_get_instance_position(p_point));
  3081. global_transform.basis *= spatial->get_transform().basis;
  3082. editor_data->get_undo_redo().add_do_method(instanced_scene, "set_global_transform", global_transform);
  3083. }
  3084. return true;
  3085. }
  3086. void SpatialEditorViewport::_perform_drop_data() {
  3087. _remove_preview();
  3088. Vector<String> error_files;
  3089. editor_data->get_undo_redo().create_action(TTR("Create Node"));
  3090. for (int i = 0; i < selected_files.size(); i++) {
  3091. String path = selected_files[i];
  3092. RES res = ResourceLoader::load(path);
  3093. if (res.is_null()) {
  3094. continue;
  3095. }
  3096. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  3097. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  3098. if (mesh != nullptr || scene != nullptr) {
  3099. bool success = _create_instance(target_node, path, drop_pos);
  3100. if (!success) {
  3101. error_files.push_back(path);
  3102. }
  3103. }
  3104. }
  3105. editor_data->get_undo_redo().commit_action();
  3106. if (error_files.size() > 0) {
  3107. String files_str;
  3108. for (int i = 0; i < error_files.size(); i++) {
  3109. files_str += error_files[i].get_file().get_basename() + ",";
  3110. }
  3111. files_str = files_str.substr(0, files_str.length() - 1);
  3112. accept->set_text(vformat(TTR("Error instancing scene from %s"), files_str.c_str()));
  3113. accept->popup_centered_minsize();
  3114. }
  3115. }
  3116. bool SpatialEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
  3117. bool can_instance = false;
  3118. if (!preview_node->is_inside_tree()) {
  3119. Dictionary d = p_data;
  3120. if (d.has("type") && (String(d["type"]) == "files")) {
  3121. Vector<String> files = d["files"];
  3122. List<String> scene_extensions;
  3123. ResourceLoader::get_recognized_extensions_for_type("PackedScene", &scene_extensions);
  3124. List<String> mesh_extensions;
  3125. ResourceLoader::get_recognized_extensions_for_type("Mesh", &mesh_extensions);
  3126. for (int i = 0; i < files.size(); i++) {
  3127. if (mesh_extensions.find(files[i].get_extension()) || scene_extensions.find(files[i].get_extension())) {
  3128. RES res = ResourceLoader::load(files[i]);
  3129. if (res.is_null()) {
  3130. continue;
  3131. }
  3132. String type = res->get_class();
  3133. if (type == "PackedScene") {
  3134. Ref<PackedScene> sdata = ResourceLoader::load(files[i]);
  3135. Node *instanced_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
  3136. if (!instanced_scene) {
  3137. continue;
  3138. }
  3139. memdelete(instanced_scene);
  3140. } else if (type == "Mesh" || type == "ArrayMesh" || type == "PrimitiveMesh") {
  3141. Ref<Mesh> mesh = ResourceLoader::load(files[i]);
  3142. if (!mesh.is_valid()) {
  3143. continue;
  3144. }
  3145. } else {
  3146. continue;
  3147. }
  3148. can_instance = true;
  3149. break;
  3150. }
  3151. }
  3152. if (can_instance) {
  3153. _create_preview(files);
  3154. }
  3155. }
  3156. } else {
  3157. can_instance = true;
  3158. }
  3159. if (can_instance) {
  3160. Transform global_transform = Transform(Basis(), _get_instance_position(p_point));
  3161. preview_node->set_global_transform(global_transform);
  3162. }
  3163. return can_instance;
  3164. }
  3165. void SpatialEditorViewport::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
  3166. if (!can_drop_data_fw(p_point, p_data, p_from)) {
  3167. return;
  3168. }
  3169. bool is_shift = Input::get_singleton()->is_key_pressed(KEY_SHIFT);
  3170. selected_files.clear();
  3171. Dictionary d = p_data;
  3172. if (d.has("type") && String(d["type"]) == "files") {
  3173. selected_files = d["files"];
  3174. }
  3175. List<Node *> list = editor->get_editor_selection()->get_selected_node_list();
  3176. if (list.size() == 0) {
  3177. Node *root_node = editor->get_edited_scene();
  3178. if (root_node) {
  3179. list.push_back(root_node);
  3180. } else {
  3181. accept->set_text(TTR("No parent to instance a child at."));
  3182. accept->popup_centered_minsize();
  3183. _remove_preview();
  3184. return;
  3185. }
  3186. }
  3187. if (list.size() != 1) {
  3188. accept->set_text(TTR("This operation requires a single selected node."));
  3189. accept->popup_centered_minsize();
  3190. _remove_preview();
  3191. return;
  3192. }
  3193. target_node = list[0];
  3194. if (is_shift && target_node != editor->get_edited_scene()) {
  3195. target_node = target_node->get_parent();
  3196. }
  3197. drop_pos = p_point;
  3198. _perform_drop_data();
  3199. }
  3200. SpatialEditorViewport::SpatialEditorViewport(SpatialEditor *p_spatial_editor, EditorNode *p_editor, int p_index) {
  3201. _edit.mode = TRANSFORM_NONE;
  3202. _edit.plane = TRANSFORM_VIEW;
  3203. _edit.edited_gizmo = 0;
  3204. _edit.snap = true;
  3205. _edit.gizmo_handle = 0;
  3206. index = p_index;
  3207. editor = p_editor;
  3208. editor_data = editor->get_scene_tree_dock()->get_editor_data();
  3209. editor_selection = editor->get_editor_selection();
  3210. undo_redo = editor->get_undo_redo();
  3211. clicked = 0;
  3212. clicked_includes_current = false;
  3213. orthogonal = false;
  3214. auto_orthogonal = false;
  3215. lock_rotation = false;
  3216. message_time = 0;
  3217. zoom_indicator_delay = 0.0;
  3218. spatial_editor = p_spatial_editor;
  3219. ViewportContainer *c = memnew(ViewportContainer);
  3220. viewport_container = c;
  3221. c->set_stretch(true);
  3222. add_child(c);
  3223. c->set_anchors_and_margins_preset(Control::PRESET_WIDE);
  3224. viewport = memnew(Viewport);
  3225. viewport->set_disable_input(true);
  3226. c->add_child(viewport);
  3227. surface = memnew(Control);
  3228. surface->set_drag_forwarding(this);
  3229. add_child(surface);
  3230. surface->set_anchors_and_margins_preset(Control::PRESET_WIDE);
  3231. surface->set_clip_contents(true);
  3232. camera = memnew(Camera);
  3233. camera->set_disable_gizmo(true);
  3234. camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + p_index)) | (1 << GIZMO_EDIT_LAYER) | (1 << GIZMO_GRID_LAYER) | (1 << MISC_TOOL_LAYER));
  3235. viewport->add_child(camera);
  3236. camera->make_current();
  3237. surface->set_focus_mode(FOCUS_ALL);
  3238. VBoxContainer *vbox = memnew(VBoxContainer);
  3239. surface->add_child(vbox);
  3240. vbox->set_position(Point2(10, 10) * EDSCALE);
  3241. view_menu = memnew(MenuButton);
  3242. view_menu->set_flat(false);
  3243. vbox->add_child(view_menu);
  3244. view_menu->set_h_size_flags(0);
  3245. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/top_view"), VIEW_TOP);
  3246. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/bottom_view"), VIEW_BOTTOM);
  3247. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/left_view"), VIEW_LEFT);
  3248. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/right_view"), VIEW_RIGHT);
  3249. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/front_view"), VIEW_FRONT);
  3250. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/rear_view"), VIEW_REAR);
  3251. view_menu->get_popup()->add_separator();
  3252. view_menu->get_popup()->add_radio_check_item(TTR("Perspective") + " (" + ED_GET_SHORTCUT("spatial_editor/switch_perspective_orthogonal")->get_as_text() + ")", VIEW_PERSPECTIVE);
  3253. view_menu->get_popup()->add_radio_check_item(TTR("Orthogonal") + " (" + ED_GET_SHORTCUT("spatial_editor/switch_perspective_orthogonal")->get_as_text() + ")", VIEW_ORTHOGONAL);
  3254. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
  3255. view_menu->get_popup()->add_check_item(TTR("Auto Orthogonal Enabled"), VIEW_AUTO_ORTHOGONAL);
  3256. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL), true);
  3257. view_menu->get_popup()->add_separator();
  3258. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_lock_rotation", TTR("Lock View Rotation")), VIEW_LOCK_ROTATION);
  3259. view_menu->get_popup()->add_separator();
  3260. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_normal", TTR("Display Normal")), VIEW_DISPLAY_NORMAL);
  3261. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_wireframe", TTR("Display Wireframe")), VIEW_DISPLAY_WIREFRAME);
  3262. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_overdraw", TTR("Display Overdraw")), VIEW_DISPLAY_OVERDRAW);
  3263. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_unshaded", TTR("Display Unshaded")), VIEW_DISPLAY_SHADELESS);
  3264. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), true);
  3265. view_menu->get_popup()->add_separator();
  3266. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_environment", TTR("View Environment")), VIEW_ENVIRONMENT);
  3267. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT), true);
  3268. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_gizmos", TTR("View Gizmos")), VIEW_GIZMOS);
  3269. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_GIZMOS), true);
  3270. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_information", TTR("View Information")), VIEW_INFORMATION);
  3271. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_fps", TTR("View FPS")), VIEW_FPS);
  3272. view_menu->get_popup()->add_separator();
  3273. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_half_resolution", TTR("Half Resolution")), VIEW_HALF_RESOLUTION);
  3274. view_menu->get_popup()->add_separator();
  3275. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_listener", TTR("Audio Listener")), VIEW_AUDIO_LISTENER);
  3276. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_doppler", TTR("Enable Doppler")), VIEW_AUDIO_DOPPLER);
  3277. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER), true);
  3278. view_menu->get_popup()->add_separator();
  3279. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_cinematic_preview", TTR("Cinematic Preview")), VIEW_CINEMATIC_PREVIEW);
  3280. view_menu->get_popup()->add_separator();
  3281. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_origin"), VIEW_CENTER_TO_ORIGIN);
  3282. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_selection"), VIEW_CENTER_TO_SELECTION);
  3283. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_transform_with_view"), VIEW_ALIGN_TRANSFORM_WITH_VIEW);
  3284. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_rotation_with_view"), VIEW_ALIGN_ROTATION_WITH_VIEW);
  3285. view_menu->get_popup()->connect("id_pressed", this, "_menu_option");
  3286. view_menu->set_disable_shortcuts(true);
  3287. if (OS::get_singleton()->get_current_video_driver() == OS::VIDEO_DRIVER_GLES2) {
  3288. // Alternate display modes only work when using the GLES3 renderer; make this explicit.
  3289. const int normal_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL);
  3290. const int wireframe_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME);
  3291. const int overdraw_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW);
  3292. const int shadeless_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS);
  3293. const String unsupported_tooltip = TTR("Not available when using the GLES2 renderer.");
  3294. view_menu->get_popup()->set_item_disabled(normal_idx, true);
  3295. view_menu->get_popup()->set_item_tooltip(normal_idx, unsupported_tooltip);
  3296. view_menu->get_popup()->set_item_disabled(wireframe_idx, true);
  3297. view_menu->get_popup()->set_item_tooltip(wireframe_idx, unsupported_tooltip);
  3298. view_menu->get_popup()->set_item_disabled(overdraw_idx, true);
  3299. view_menu->get_popup()->set_item_tooltip(overdraw_idx, unsupported_tooltip);
  3300. view_menu->get_popup()->set_item_disabled(shadeless_idx, true);
  3301. view_menu->get_popup()->set_item_tooltip(shadeless_idx, unsupported_tooltip);
  3302. }
  3303. ED_SHORTCUT("spatial_editor/freelook_left", TTR("Freelook Left"), KEY_A);
  3304. ED_SHORTCUT("spatial_editor/freelook_right", TTR("Freelook Right"), KEY_D);
  3305. ED_SHORTCUT("spatial_editor/freelook_forward", TTR("Freelook Forward"), KEY_W);
  3306. ED_SHORTCUT("spatial_editor/freelook_backwards", TTR("Freelook Backwards"), KEY_S);
  3307. ED_SHORTCUT("spatial_editor/freelook_up", TTR("Freelook Up"), KEY_E);
  3308. ED_SHORTCUT("spatial_editor/freelook_down", TTR("Freelook Down"), KEY_Q);
  3309. ED_SHORTCUT("spatial_editor/freelook_speed_modifier", TTR("Freelook Speed Modifier"), KEY_SHIFT);
  3310. ED_SHORTCUT("spatial_editor/freelook_slow_modifier", TTR("Freelook Slow Modifier"), KEY_ALT);
  3311. preview_camera = memnew(CheckBox);
  3312. preview_camera->set_text(TTR("Preview"));
  3313. preview_camera->set_shortcut(ED_SHORTCUT("spatial_editor/toggle_camera_preview", TTR("Toggle Camera Preview"), KEY_MASK_CMD | KEY_P));
  3314. vbox->add_child(preview_camera);
  3315. preview_camera->set_h_size_flags(0);
  3316. preview_camera->hide();
  3317. preview_camera->connect("toggled", this, "_toggle_camera_preview");
  3318. previewing = nullptr;
  3319. gizmo_scale = 1.0;
  3320. preview_node = nullptr;
  3321. info_label = memnew(Label);
  3322. info_label->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, -90 * EDSCALE);
  3323. info_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_END, -90 * EDSCALE);
  3324. info_label->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -10 * EDSCALE);
  3325. info_label->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, -10 * EDSCALE);
  3326. info_label->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  3327. info_label->set_v_grow_direction(GROW_DIRECTION_BEGIN);
  3328. surface->add_child(info_label);
  3329. info_label->hide();
  3330. cinema_label = memnew(Label);
  3331. cinema_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 10 * EDSCALE);
  3332. cinema_label->set_h_grow_direction(GROW_DIRECTION_END);
  3333. cinema_label->set_align(Label::ALIGN_CENTER);
  3334. surface->add_child(cinema_label);
  3335. cinema_label->set_text(TTR("Cinematic Preview"));
  3336. cinema_label->hide();
  3337. previewing_cinema = false;
  3338. locked_label = memnew(Label);
  3339. locked_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_END, -20 * EDSCALE);
  3340. locked_label->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, -10 * EDSCALE);
  3341. locked_label->set_h_grow_direction(GROW_DIRECTION_END);
  3342. locked_label->set_v_grow_direction(GROW_DIRECTION_BEGIN);
  3343. locked_label->set_align(Label::ALIGN_CENTER);
  3344. surface->add_child(locked_label);
  3345. locked_label->set_text(TTR("View Rotation Locked"));
  3346. locked_label->hide();
  3347. zoom_limit_label = memnew(Label);
  3348. zoom_limit_label->set_anchors_and_margins_preset(LayoutPreset::PRESET_BOTTOM_LEFT);
  3349. zoom_limit_label->set_margin(Margin::MARGIN_TOP, -28 * EDSCALE);
  3350. zoom_limit_label->set_text(TTR("To zoom further, change the camera's clipping planes (View -> Settings...)"));
  3351. zoom_limit_label->set_name("ZoomLimitMessageLabel");
  3352. zoom_limit_label->add_color_override("font_color", Color(1, 1, 1, 1));
  3353. zoom_limit_label->hide();
  3354. surface->add_child(zoom_limit_label);
  3355. top_right_vbox = memnew(VBoxContainer);
  3356. top_right_vbox->set_anchors_and_margins_preset(PRESET_TOP_RIGHT, PRESET_MODE_MINSIZE, 2.0 * EDSCALE);
  3357. top_right_vbox->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  3358. rotation_control = memnew(ViewportRotationControl);
  3359. rotation_control->set_custom_minimum_size(Size2(80, 80) * EDSCALE);
  3360. rotation_control->set_h_size_flags(SIZE_SHRINK_END);
  3361. rotation_control->set_viewport(this);
  3362. top_right_vbox->add_child(rotation_control);
  3363. fps_label = memnew(Label);
  3364. fps_label->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, -90 * EDSCALE);
  3365. fps_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 10 * EDSCALE);
  3366. fps_label->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -10 * EDSCALE);
  3367. fps_label->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  3368. 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."));
  3369. fps_label->set_mouse_filter(MOUSE_FILTER_PASS); // Otherwise tooltip doesn't show.
  3370. top_right_vbox->add_child(fps_label);
  3371. fps_label->hide();
  3372. surface->add_child(top_right_vbox);
  3373. accept = nullptr;
  3374. freelook_active = false;
  3375. freelook_speed = EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_base_speed");
  3376. selection_menu = memnew(PopupMenu);
  3377. add_child(selection_menu);
  3378. selection_menu->set_custom_minimum_size(Size2(100, 0) * EDSCALE);
  3379. selection_menu->connect("id_pressed", this, "_selection_result_pressed");
  3380. selection_menu->connect("popup_hide", this, "_selection_menu_hide");
  3381. if (p_index == 0) {
  3382. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER), true);
  3383. viewport->set_as_audio_listener(true);
  3384. }
  3385. view_type = VIEW_TYPE_USER;
  3386. _update_name();
  3387. EditorSettings::get_singleton()->connect("settings_changed", this, "update_transform_gizmo_view");
  3388. }
  3389. //////////////////////////////////////////////////////////////
  3390. void SpatialEditorViewportContainer::_gui_input(const Ref<InputEvent> &p_event) {
  3391. Ref<InputEventMouseButton> mb = p_event;
  3392. if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT) {
  3393. if (mb->is_pressed()) {
  3394. Vector2 size = get_size();
  3395. int h_sep = get_constant("separation", "HSplitContainer");
  3396. int v_sep = get_constant("separation", "VSplitContainer");
  3397. int mid_w = size.width * ratio_h;
  3398. int mid_h = size.height * ratio_v;
  3399. dragging_h = mb->get_position().x > (mid_w - h_sep / 2) && mb->get_position().x < (mid_w + h_sep / 2);
  3400. dragging_v = mb->get_position().y > (mid_h - v_sep / 2) && mb->get_position().y < (mid_h + v_sep / 2);
  3401. drag_begin_pos = mb->get_position();
  3402. drag_begin_ratio.x = ratio_h;
  3403. drag_begin_ratio.y = ratio_v;
  3404. switch (view) {
  3405. case VIEW_USE_1_VIEWPORT: {
  3406. dragging_h = false;
  3407. dragging_v = false;
  3408. } break;
  3409. case VIEW_USE_2_VIEWPORTS: {
  3410. dragging_h = false;
  3411. } break;
  3412. case VIEW_USE_2_VIEWPORTS_ALT: {
  3413. dragging_v = false;
  3414. } break;
  3415. case VIEW_USE_3_VIEWPORTS:
  3416. case VIEW_USE_3_VIEWPORTS_ALT:
  3417. case VIEW_USE_4_VIEWPORTS: {
  3418. // Do nothing.
  3419. } break;
  3420. }
  3421. } else {
  3422. dragging_h = false;
  3423. dragging_v = false;
  3424. }
  3425. }
  3426. Ref<InputEventMouseMotion> mm = p_event;
  3427. if (mm.is_valid()) {
  3428. if (view == VIEW_USE_3_VIEWPORTS || view == VIEW_USE_3_VIEWPORTS_ALT || view == VIEW_USE_4_VIEWPORTS) {
  3429. Vector2 size = get_size();
  3430. int h_sep = get_constant("separation", "HSplitContainer");
  3431. int v_sep = get_constant("separation", "VSplitContainer");
  3432. int mid_w = size.width * ratio_h;
  3433. int mid_h = size.height * ratio_v;
  3434. bool was_hovering_h = hovering_h;
  3435. bool was_hovering_v = hovering_v;
  3436. hovering_h = mm->get_position().x > (mid_w - h_sep / 2) && mm->get_position().x < (mid_w + h_sep / 2);
  3437. hovering_v = mm->get_position().y > (mid_h - v_sep / 2) && mm->get_position().y < (mid_h + v_sep / 2);
  3438. if (was_hovering_h != hovering_h || was_hovering_v != hovering_v) {
  3439. update();
  3440. }
  3441. }
  3442. if (dragging_h) {
  3443. float new_ratio = drag_begin_ratio.x + (mm->get_position().x - drag_begin_pos.x) / get_size().width;
  3444. new_ratio = CLAMP(new_ratio, 40 / get_size().width, (get_size().width - 40) / get_size().width);
  3445. ratio_h = new_ratio;
  3446. queue_sort();
  3447. update();
  3448. }
  3449. if (dragging_v) {
  3450. float new_ratio = drag_begin_ratio.y + (mm->get_position().y - drag_begin_pos.y) / get_size().height;
  3451. new_ratio = CLAMP(new_ratio, 40 / get_size().height, (get_size().height - 40) / get_size().height);
  3452. ratio_v = new_ratio;
  3453. queue_sort();
  3454. update();
  3455. }
  3456. }
  3457. }
  3458. void SpatialEditorViewportContainer::_notification(int p_what) {
  3459. if (p_what == NOTIFICATION_MOUSE_ENTER || p_what == NOTIFICATION_MOUSE_EXIT) {
  3460. mouseover = (p_what == NOTIFICATION_MOUSE_ENTER);
  3461. update();
  3462. }
  3463. if (p_what == NOTIFICATION_DRAW && mouseover) {
  3464. Ref<Texture> h_grabber = get_icon("grabber", "HSplitContainer");
  3465. Ref<Texture> v_grabber = get_icon("grabber", "VSplitContainer");
  3466. Ref<Texture> hdiag_grabber = get_icon("GuiViewportHdiagsplitter", "EditorIcons");
  3467. Ref<Texture> vdiag_grabber = get_icon("GuiViewportVdiagsplitter", "EditorIcons");
  3468. Ref<Texture> vh_grabber = get_icon("GuiViewportVhsplitter", "EditorIcons");
  3469. Vector2 size = get_size();
  3470. int h_sep = get_constant("separation", "HSplitContainer");
  3471. int v_sep = get_constant("separation", "VSplitContainer");
  3472. int mid_w = size.width * ratio_h;
  3473. int mid_h = size.height * ratio_v;
  3474. int size_left = mid_w - h_sep / 2;
  3475. int size_bottom = size.height - mid_h - v_sep / 2;
  3476. switch (view) {
  3477. case VIEW_USE_1_VIEWPORT: {
  3478. // Nothing to show.
  3479. } break;
  3480. case VIEW_USE_2_VIEWPORTS: {
  3481. draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  3482. set_default_cursor_shape(CURSOR_VSPLIT);
  3483. } break;
  3484. case VIEW_USE_2_VIEWPORTS_ALT: {
  3485. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
  3486. set_default_cursor_shape(CURSOR_HSPLIT);
  3487. } break;
  3488. case VIEW_USE_3_VIEWPORTS: {
  3489. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  3490. draw_texture(hdiag_grabber, Vector2(mid_w - hdiag_grabber->get_width() / 2, mid_h - v_grabber->get_height() / 4));
  3491. set_default_cursor_shape(CURSOR_DRAG);
  3492. } else if ((hovering_v && !dragging_h) || dragging_v) {
  3493. draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  3494. set_default_cursor_shape(CURSOR_VSPLIT);
  3495. } else if (hovering_h || dragging_h) {
  3496. 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));
  3497. set_default_cursor_shape(CURSOR_HSPLIT);
  3498. }
  3499. } break;
  3500. case VIEW_USE_3_VIEWPORTS_ALT: {
  3501. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  3502. draw_texture(vdiag_grabber, Vector2(mid_w - vdiag_grabber->get_width() + v_grabber->get_height() / 4, mid_h - vdiag_grabber->get_height() / 2));
  3503. set_default_cursor_shape(CURSOR_DRAG);
  3504. } else if ((hovering_v && !dragging_h) || dragging_v) {
  3505. draw_texture(v_grabber, Vector2((size_left - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  3506. set_default_cursor_shape(CURSOR_VSPLIT);
  3507. } else if (hovering_h || dragging_h) {
  3508. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
  3509. set_default_cursor_shape(CURSOR_HSPLIT);
  3510. }
  3511. } break;
  3512. case VIEW_USE_4_VIEWPORTS: {
  3513. Vector2 half(mid_w, mid_h);
  3514. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  3515. draw_texture(vh_grabber, half - vh_grabber->get_size() / 2.0);
  3516. set_default_cursor_shape(CURSOR_DRAG);
  3517. } else if ((hovering_v && !dragging_h) || dragging_v) {
  3518. draw_texture(v_grabber, half - v_grabber->get_size() / 2.0);
  3519. set_default_cursor_shape(CURSOR_VSPLIT);
  3520. } else if (hovering_h || dragging_h) {
  3521. draw_texture(h_grabber, half - h_grabber->get_size() / 2.0);
  3522. set_default_cursor_shape(CURSOR_HSPLIT);
  3523. }
  3524. } break;
  3525. }
  3526. }
  3527. if (p_what == NOTIFICATION_SORT_CHILDREN) {
  3528. SpatialEditorViewport *viewports[4];
  3529. int vc = 0;
  3530. for (int i = 0; i < get_child_count(); i++) {
  3531. viewports[vc] = Object::cast_to<SpatialEditorViewport>(get_child(i));
  3532. if (viewports[vc]) {
  3533. vc++;
  3534. }
  3535. }
  3536. ERR_FAIL_COND(vc != 4);
  3537. Size2 size = get_size();
  3538. if (size.x < 10 || size.y < 10) {
  3539. for (int i = 0; i < 4; i++) {
  3540. viewports[i]->hide();
  3541. }
  3542. return;
  3543. }
  3544. int h_sep = get_constant("separation", "HSplitContainer");
  3545. int v_sep = get_constant("separation", "VSplitContainer");
  3546. int mid_w = size.width * ratio_h;
  3547. int mid_h = size.height * ratio_v;
  3548. int size_left = mid_w - h_sep / 2;
  3549. int size_right = size.width - mid_w - h_sep / 2;
  3550. int size_top = mid_h - v_sep / 2;
  3551. int size_bottom = size.height - mid_h - v_sep / 2;
  3552. switch (view) {
  3553. case VIEW_USE_1_VIEWPORT: {
  3554. viewports[0]->show();
  3555. for (int i = 1; i < 4; i++) {
  3556. viewports[i]->hide();
  3557. }
  3558. fit_child_in_rect(viewports[0], Rect2(Vector2(), size));
  3559. } break;
  3560. case VIEW_USE_2_VIEWPORTS: {
  3561. for (int i = 0; i < 4; i++) {
  3562. if (i == 1 || i == 3) {
  3563. viewports[i]->hide();
  3564. } else {
  3565. viewports[i]->show();
  3566. }
  3567. }
  3568. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
  3569. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size.width, size_bottom)));
  3570. } break;
  3571. case VIEW_USE_2_VIEWPORTS_ALT: {
  3572. for (int i = 0; i < 4; i++) {
  3573. if (i == 1 || i == 3) {
  3574. viewports[i]->hide();
  3575. } else {
  3576. viewports[i]->show();
  3577. }
  3578. }
  3579. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size.height)));
  3580. fit_child_in_rect(viewports[2], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
  3581. } break;
  3582. case VIEW_USE_3_VIEWPORTS: {
  3583. for (int i = 0; i < 4; i++) {
  3584. if (i == 1) {
  3585. viewports[i]->hide();
  3586. } else {
  3587. viewports[i]->show();
  3588. }
  3589. }
  3590. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
  3591. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  3592. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
  3593. } break;
  3594. case VIEW_USE_3_VIEWPORTS_ALT: {
  3595. for (int i = 0; i < 4; i++) {
  3596. if (i == 1) {
  3597. viewports[i]->hide();
  3598. } else {
  3599. viewports[i]->show();
  3600. }
  3601. }
  3602. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
  3603. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  3604. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
  3605. } break;
  3606. case VIEW_USE_4_VIEWPORTS: {
  3607. for (int i = 0; i < 4; i++) {
  3608. viewports[i]->show();
  3609. }
  3610. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
  3611. fit_child_in_rect(viewports[1], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size_top)));
  3612. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  3613. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
  3614. } break;
  3615. }
  3616. }
  3617. }
  3618. void SpatialEditorViewportContainer::set_view(View p_view) {
  3619. view = p_view;
  3620. queue_sort();
  3621. }
  3622. SpatialEditorViewportContainer::View SpatialEditorViewportContainer::get_view() {
  3623. return view;
  3624. }
  3625. void SpatialEditorViewportContainer::_bind_methods() {
  3626. ClassDB::bind_method("_gui_input", &SpatialEditorViewportContainer::_gui_input);
  3627. }
  3628. SpatialEditorViewportContainer::SpatialEditorViewportContainer() {
  3629. set_clip_contents(true);
  3630. view = VIEW_USE_1_VIEWPORT;
  3631. mouseover = false;
  3632. ratio_h = 0.5;
  3633. ratio_v = 0.5;
  3634. hovering_v = false;
  3635. hovering_h = false;
  3636. dragging_v = false;
  3637. dragging_h = false;
  3638. }
  3639. ///////////////////////////////////////////////////////////////////
  3640. SpatialEditor *SpatialEditor::singleton = nullptr;
  3641. SpatialEditorSelectedItem::~SpatialEditorSelectedItem() {
  3642. if (sbox_instance.is_valid()) {
  3643. VisualServer::get_singleton()->free(sbox_instance);
  3644. }
  3645. if (sbox_instance_offset.is_valid()) {
  3646. VisualServer::get_singleton()->free(sbox_instance_offset);
  3647. }
  3648. if (sbox_instance_xray.is_valid()) {
  3649. VisualServer::get_singleton()->free(sbox_instance_xray);
  3650. }
  3651. if (sbox_instance_xray_offset.is_valid()) {
  3652. VisualServer::get_singleton()->free(sbox_instance_xray_offset);
  3653. }
  3654. }
  3655. void SpatialEditor::select_gizmo_highlight_axis(int p_axis) {
  3656. for (int i = 0; i < 3; i++) {
  3657. move_gizmo[i]->surface_set_material(0, i == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  3658. move_plane_gizmo[i]->surface_set_material(0, (i + 6) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
  3659. rotate_gizmo[i]->surface_set_material(0, (i + 3) == p_axis ? rotate_gizmo_color_hl[i] : rotate_gizmo_color[i]);
  3660. scale_gizmo[i]->surface_set_material(0, (i + 9) == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  3661. scale_plane_gizmo[i]->surface_set_material(0, (i + 12) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
  3662. }
  3663. }
  3664. void SpatialEditor::show_advanced_portal_tools(bool p_show) {
  3665. // toolbar button
  3666. Button *const button = tool_button[TOOL_CONVERT_ROOMS];
  3667. if (p_show) {
  3668. button->set_text(TTR("Convert Rooms"));
  3669. } else {
  3670. button->set_text("");
  3671. }
  3672. }
  3673. void SpatialEditor::update_portal_tools() {
  3674. // just some protection against calling null pointers, hopefully not needed
  3675. if (view_menu && view_menu->get_popup()) {
  3676. // the view portal culling toggle
  3677. int view_portal_item_index = view_menu->get_popup()->get_item_index(MENU_VIEW_PORTAL_CULLING);
  3678. if (RoomManager::active_room_manager) {
  3679. view_menu->get_popup()->set_item_disabled(view_portal_item_index, false);
  3680. bool active = RoomManager::static_rooms_get_active();
  3681. view_menu->get_popup()->set_item_checked(view_portal_item_index, active);
  3682. } else {
  3683. view_menu->get_popup()->set_item_disabled(view_portal_item_index, true);
  3684. }
  3685. // toolbar button
  3686. Button *const button = tool_button[TOOL_CONVERT_ROOMS];
  3687. if (RoomManager::active_room_manager) {
  3688. button->show();
  3689. } else {
  3690. button->hide();
  3691. }
  3692. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  3693. viewports[i]->_update_name();
  3694. }
  3695. }
  3696. }
  3697. void SpatialEditor::update_transform_gizmo() {
  3698. List<Node *> &selection = editor_selection->get_selected_node_list();
  3699. AABB center;
  3700. bool first = true;
  3701. Basis gizmo_basis;
  3702. bool local_gizmo_coords = are_local_coords_enabled();
  3703. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3704. Spatial *sp = Object::cast_to<Spatial>(E->get());
  3705. if (!sp) {
  3706. continue;
  3707. }
  3708. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  3709. if (!se) {
  3710. continue;
  3711. }
  3712. Transform xf = se->sp->get_global_gizmo_transform();
  3713. if (first) {
  3714. center.position = xf.origin;
  3715. first = false;
  3716. if (local_gizmo_coords) {
  3717. gizmo_basis = xf.basis;
  3718. gizmo_basis.orthonormalize();
  3719. }
  3720. } else {
  3721. center.expand_to(xf.origin);
  3722. gizmo_basis = Basis();
  3723. }
  3724. }
  3725. Vector3 pcenter = center.position + center.size * 0.5;
  3726. gizmo.visible = !first;
  3727. gizmo.transform.origin = pcenter;
  3728. gizmo.transform.basis = gizmo_basis;
  3729. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  3730. viewports[i]->update_transform_gizmo_view();
  3731. }
  3732. }
  3733. void _update_all_gizmos(Node *p_node) {
  3734. for (int i = p_node->get_child_count() - 1; 0 <= i; --i) {
  3735. Spatial *spatial_node = Object::cast_to<Spatial>(p_node->get_child(i));
  3736. if (spatial_node) {
  3737. spatial_node->update_gizmo();
  3738. }
  3739. _update_all_gizmos(p_node->get_child(i));
  3740. }
  3741. }
  3742. void SpatialEditor::update_all_gizmos(Node *p_node) {
  3743. if (!p_node) {
  3744. if (SceneTree::get_singleton()) {
  3745. p_node = SceneTree::get_singleton()->get_root();
  3746. } else {
  3747. // No scene tree, so nothing to update.
  3748. return;
  3749. }
  3750. }
  3751. _update_all_gizmos(p_node);
  3752. }
  3753. Object *SpatialEditor::_get_editor_data(Object *p_what) {
  3754. Spatial *sp = Object::cast_to<Spatial>(p_what);
  3755. if (!sp) {
  3756. return nullptr;
  3757. }
  3758. SpatialEditorSelectedItem *si = memnew(SpatialEditorSelectedItem);
  3759. si->sp = sp;
  3760. si->sbox_instance = VisualServer::get_singleton()->instance_create2(
  3761. selection_box->get_rid(),
  3762. sp->get_world()->get_scenario());
  3763. si->sbox_instance_offset = VisualServer::get_singleton()->instance_create2(
  3764. selection_box->get_rid(),
  3765. sp->get_world()->get_scenario());
  3766. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  3767. si->sbox_instance,
  3768. VS::SHADOW_CASTING_SETTING_OFF);
  3769. // Use the Edit layer to hide the selection box when View Gizmos is disabled, since it is a bit distracting.
  3770. // It's still possible to approximately guess what is selected by looking at the manipulation gizmo position.
  3771. VS::get_singleton()->instance_set_layer_mask(si->sbox_instance, 1 << SpatialEditorViewport::GIZMO_EDIT_LAYER);
  3772. VS::get_singleton()->instance_set_layer_mask(si->sbox_instance_offset, 1 << SpatialEditorViewport::GIZMO_EDIT_LAYER);
  3773. si->sbox_instance_xray = VisualServer::get_singleton()->instance_create2(
  3774. selection_box_xray->get_rid(),
  3775. sp->get_world()->get_scenario());
  3776. si->sbox_instance_xray_offset = VisualServer::get_singleton()->instance_create2(
  3777. selection_box_xray->get_rid(),
  3778. sp->get_world()->get_scenario());
  3779. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  3780. si->sbox_instance_xray,
  3781. VS::SHADOW_CASTING_SETTING_OFF);
  3782. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  3783. si->sbox_instance_xray_offset,
  3784. VS::SHADOW_CASTING_SETTING_OFF);
  3785. // Use the Edit layer to hide the selection box when View Gizmos is disabled, since it is a bit distracting.
  3786. // It's still possible to approximately guess what is selected by looking at the manipulation gizmo position.
  3787. VS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray, 1 << SpatialEditorViewport::GIZMO_EDIT_LAYER);
  3788. VS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray_offset, 1 << SpatialEditorViewport::GIZMO_EDIT_LAYER);
  3789. return si;
  3790. }
  3791. void SpatialEditor::_generate_selection_boxes() {
  3792. // Use two AABBs to create the illusion of a slightly thicker line.
  3793. AABB aabb(Vector3(), Vector3(1, 1, 1));
  3794. // Create a x-ray (visible through solid surfaces) and standard version of the selection box.
  3795. // Both will be drawn at the same position, but with different opacity.
  3796. // This lets the user see where the selection is while still having a sense of depth.
  3797. Ref<SurfaceTool> st = memnew(SurfaceTool);
  3798. Ref<SurfaceTool> st_xray = memnew(SurfaceTool);
  3799. st->begin(Mesh::PRIMITIVE_LINES);
  3800. st_xray->begin(Mesh::PRIMITIVE_LINES);
  3801. for (int i = 0; i < 12; i++) {
  3802. Vector3 a, b;
  3803. aabb.get_edge(i, a, b);
  3804. st->add_vertex(a);
  3805. st->add_vertex(b);
  3806. st_xray->add_vertex(a);
  3807. st_xray->add_vertex(b);
  3808. }
  3809. Ref<SpatialMaterial> mat = memnew(SpatialMaterial);
  3810. mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  3811. const Color selection_box_color = EDITOR_GET("editors/3d/selection_box_color");
  3812. mat->set_albedo(selection_box_color);
  3813. mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  3814. st->set_material(mat);
  3815. selection_box = st->commit();
  3816. Ref<SpatialMaterial> mat_xray = memnew(SpatialMaterial);
  3817. mat_xray->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  3818. mat_xray->set_flag(SpatialMaterial::FLAG_DISABLE_DEPTH_TEST, true);
  3819. mat_xray->set_albedo(selection_box_color * Color(1, 1, 1, 0.15));
  3820. mat_xray->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  3821. st_xray->set_material(mat_xray);
  3822. selection_box_xray = st_xray->commit();
  3823. }
  3824. Dictionary SpatialEditor::get_state() const {
  3825. Dictionary d;
  3826. d["snap_enabled"] = snap_enabled;
  3827. d["translate_snap"] = get_translate_snap();
  3828. d["rotate_snap"] = get_rotate_snap();
  3829. d["scale_snap"] = get_scale_snap();
  3830. d["local_coords"] = tool_option_button[TOOL_OPT_LOCAL_COORDS]->is_pressed();
  3831. int vc = 0;
  3832. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT))) {
  3833. vc = 1;
  3834. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS))) {
  3835. vc = 2;
  3836. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS))) {
  3837. vc = 3;
  3838. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS))) {
  3839. vc = 4;
  3840. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT))) {
  3841. vc = 5;
  3842. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT))) {
  3843. vc = 6;
  3844. }
  3845. d["viewport_mode"] = vc;
  3846. Array vpdata;
  3847. for (int i = 0; i < 4; i++) {
  3848. vpdata.push_back(viewports[i]->get_state());
  3849. }
  3850. d["viewports"] = vpdata;
  3851. d["show_grid"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID));
  3852. d["show_origin"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN));
  3853. d["fov"] = get_fov();
  3854. d["znear"] = get_znear();
  3855. d["zfar"] = get_zfar();
  3856. Dictionary gizmos_status;
  3857. for (int i = 0; i < gizmo_plugins_by_name.size(); i++) {
  3858. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  3859. continue;
  3860. }
  3861. int state = gizmos_menu->get_item_state(gizmos_menu->get_item_index(i));
  3862. String name = gizmo_plugins_by_name[i]->get_name();
  3863. gizmos_status[name] = state;
  3864. }
  3865. d["gizmos_status"] = gizmos_status;
  3866. return d;
  3867. }
  3868. void SpatialEditor::set_state(const Dictionary &p_state) {
  3869. Dictionary d = p_state;
  3870. if (d.has("snap_enabled")) {
  3871. snap_enabled = d["snap_enabled"];
  3872. tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(d["snap_enabled"]);
  3873. }
  3874. if (d.has("translate_snap")) {
  3875. snap_translate_value = d["translate_snap"];
  3876. }
  3877. if (d.has("rotate_snap")) {
  3878. snap_rotate_value = d["rotate_snap"];
  3879. }
  3880. if (d.has("scale_snap")) {
  3881. snap_scale_value = d["scale_snap"];
  3882. }
  3883. _snap_update();
  3884. if (d.has("local_coords")) {
  3885. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(d["local_coords"]);
  3886. update_transform_gizmo();
  3887. }
  3888. if (d.has("viewport_mode")) {
  3889. int vc = d["viewport_mode"];
  3890. if (vc == 1) {
  3891. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  3892. } else if (vc == 2) {
  3893. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
  3894. } else if (vc == 3) {
  3895. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
  3896. } else if (vc == 4) {
  3897. _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
  3898. } else if (vc == 5) {
  3899. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
  3900. } else if (vc == 6) {
  3901. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
  3902. }
  3903. }
  3904. if (d.has("viewports")) {
  3905. Array vp = d["viewports"];
  3906. uint32_t vp_size = static_cast<uint32_t>(vp.size());
  3907. if (vp_size > VIEWPORTS_COUNT) {
  3908. WARN_PRINT("Ignoring superfluous viewport settings from spatial editor state.");
  3909. vp_size = VIEWPORTS_COUNT;
  3910. }
  3911. for (uint32_t i = 0; i < vp_size; i++) {
  3912. viewports[i]->set_state(vp[i]);
  3913. }
  3914. }
  3915. if (d.has("zfar")) {
  3916. settings_zfar->set_value(float(d["zfar"]));
  3917. }
  3918. if (d.has("znear")) {
  3919. settings_znear->set_value(float(d["znear"]));
  3920. }
  3921. if (d.has("fov")) {
  3922. settings_fov->set_value(float(d["fov"]));
  3923. }
  3924. if (d.has("show_grid")) {
  3925. bool use = d["show_grid"];
  3926. if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID))) {
  3927. _menu_item_pressed(MENU_VIEW_GRID);
  3928. }
  3929. }
  3930. if (d.has("show_origin")) {
  3931. bool use = d["show_origin"];
  3932. if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN))) {
  3933. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), use);
  3934. VisualServer::get_singleton()->instance_set_visible(origin_instance, use);
  3935. }
  3936. }
  3937. if (d.has("gizmos_status")) {
  3938. Dictionary gizmos_status = d["gizmos_status"];
  3939. List<Variant> keys;
  3940. gizmos_status.get_key_list(&keys);
  3941. for (int j = 0; j < gizmo_plugins_by_name.size(); ++j) {
  3942. if (!gizmo_plugins_by_name[j]->can_be_hidden()) {
  3943. continue;
  3944. }
  3945. int state = EditorSpatialGizmoPlugin::VISIBLE;
  3946. for (int i = 0; i < keys.size(); i++) {
  3947. if (gizmo_plugins_by_name.write[j]->get_name() == keys[i]) {
  3948. state = gizmos_status[keys[i]];
  3949. break;
  3950. }
  3951. }
  3952. gizmo_plugins_by_name.write[j]->set_state(state);
  3953. }
  3954. _update_gizmos_menu();
  3955. }
  3956. }
  3957. void SpatialEditor::edit(Spatial *p_spatial) {
  3958. if (p_spatial != selected) {
  3959. if (selected) {
  3960. Ref<EditorSpatialGizmo> seg = selected->get_gizmo();
  3961. if (seg.is_valid()) {
  3962. seg->set_selected(false);
  3963. selected->update_gizmo();
  3964. }
  3965. }
  3966. selected = p_spatial;
  3967. over_gizmo_handle = -1;
  3968. if (selected) {
  3969. Ref<EditorSpatialGizmo> seg = selected->get_gizmo();
  3970. if (seg.is_valid()) {
  3971. seg->set_selected(true);
  3972. selected->update_gizmo();
  3973. }
  3974. }
  3975. }
  3976. }
  3977. void SpatialEditor::_snap_changed() {
  3978. snap_translate_value = snap_translate->get_text().to_double();
  3979. snap_rotate_value = snap_rotate->get_text().to_double();
  3980. snap_scale_value = snap_scale->get_text().to_double();
  3981. }
  3982. void SpatialEditor::_snap_update() {
  3983. snap_translate->set_text(String::num(snap_translate_value));
  3984. snap_rotate->set_text(String::num(snap_rotate_value));
  3985. snap_scale->set_text(String::num(snap_scale_value));
  3986. }
  3987. void SpatialEditor::_xform_dialog_action() {
  3988. Transform t;
  3989. //translation
  3990. Vector3 scale;
  3991. Vector3 rotate;
  3992. Vector3 translate;
  3993. for (int i = 0; i < 3; i++) {
  3994. translate[i] = xform_translate[i]->get_text().to_double();
  3995. rotate[i] = Math::deg2rad(xform_rotate[i]->get_text().to_double());
  3996. scale[i] = xform_scale[i]->get_text().to_double();
  3997. }
  3998. t.basis.scale(scale);
  3999. t.basis.rotate(rotate);
  4000. t.origin = translate;
  4001. undo_redo->create_action(TTR("XForm Dialog"));
  4002. List<Node *> &selection = editor_selection->get_selected_node_list();
  4003. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4004. Spatial *sp = Object::cast_to<Spatial>(E->get());
  4005. if (!sp) {
  4006. continue;
  4007. }
  4008. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  4009. if (!se) {
  4010. continue;
  4011. }
  4012. bool post = xform_type->get_selected() > 0;
  4013. Transform tr = sp->get_global_gizmo_transform();
  4014. if (post) {
  4015. tr = tr * t;
  4016. } else {
  4017. tr.basis = t.basis * tr.basis;
  4018. tr.origin += t.origin;
  4019. }
  4020. undo_redo->add_do_method(sp, "set_global_transform", tr);
  4021. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
  4022. }
  4023. undo_redo->commit_action();
  4024. }
  4025. void SpatialEditor::_menu_item_toggled(bool pressed, int p_option) {
  4026. switch (p_option) {
  4027. case MENU_TOOL_LOCAL_COORDS: {
  4028. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(pressed);
  4029. update_transform_gizmo();
  4030. } break;
  4031. case MENU_TOOL_USE_SNAP: {
  4032. tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(pressed);
  4033. snap_enabled = pressed;
  4034. } break;
  4035. case MENU_TOOL_OVERRIDE_CAMERA: {
  4036. ScriptEditorDebugger *const debugger = ScriptEditor::get_singleton()->get_debugger();
  4037. if (pressed) {
  4038. using Override = ScriptEditorDebugger::CameraOverride;
  4039. debugger->set_camera_override((Override)(Override::OVERRIDE_3D_1 + camera_override_viewport_id));
  4040. } else {
  4041. debugger->set_camera_override(ScriptEditorDebugger::OVERRIDE_NONE);
  4042. }
  4043. } break;
  4044. }
  4045. }
  4046. void SpatialEditor::_menu_gizmo_toggled(int p_option) {
  4047. const int idx = gizmos_menu->get_item_index(p_option);
  4048. gizmos_menu->toggle_item_multistate(idx);
  4049. // Change icon
  4050. const int state = gizmos_menu->get_item_state(idx);
  4051. switch (state) {
  4052. case EditorSpatialGizmoPlugin::VISIBLE:
  4053. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_icon("visibility_visible"));
  4054. break;
  4055. case EditorSpatialGizmoPlugin::ON_TOP:
  4056. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_icon("visibility_xray"));
  4057. break;
  4058. case EditorSpatialGizmoPlugin::HIDDEN:
  4059. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_icon("visibility_hidden"));
  4060. break;
  4061. }
  4062. gizmo_plugins_by_name.write[p_option]->set_state(state);
  4063. update_all_gizmos();
  4064. }
  4065. void SpatialEditor::_update_camera_override_button(bool p_game_running) {
  4066. Button *const button = tool_option_button[TOOL_OPT_OVERRIDE_CAMERA];
  4067. if (p_game_running) {
  4068. button->set_disabled(false);
  4069. button->set_tooltip(TTR("Project Camera Override\nOverrides the running project's camera with the editor viewport camera."));
  4070. } else {
  4071. button->set_disabled(true);
  4072. button->set_pressed(false);
  4073. button->set_tooltip(TTR("Project Camera Override\nNo project instance running. Run the project from the editor to use this feature."));
  4074. }
  4075. }
  4076. void SpatialEditor::_update_camera_override_viewport(Object *p_viewport) {
  4077. SpatialEditorViewport *current_viewport = Object::cast_to<SpatialEditorViewport>(p_viewport);
  4078. if (!current_viewport) {
  4079. return;
  4080. }
  4081. ScriptEditorDebugger *const debugger = ScriptEditor::get_singleton()->get_debugger();
  4082. camera_override_viewport_id = current_viewport->index;
  4083. if (debugger->get_camera_override() >= ScriptEditorDebugger::OVERRIDE_3D_1) {
  4084. using Override = ScriptEditorDebugger::CameraOverride;
  4085. debugger->set_camera_override((Override)(Override::OVERRIDE_3D_1 + camera_override_viewport_id));
  4086. }
  4087. }
  4088. void SpatialEditor::_menu_item_pressed(int p_option) {
  4089. switch (p_option) {
  4090. case MENU_TOOL_SELECT:
  4091. case MENU_TOOL_MOVE:
  4092. case MENU_TOOL_ROTATE:
  4093. case MENU_TOOL_SCALE:
  4094. case MENU_TOOL_LIST_SELECT: {
  4095. for (int i = 0; i < TOOL_MAX; i++) {
  4096. tool_button[i]->set_pressed(i == p_option);
  4097. }
  4098. tool_mode = (ToolMode)p_option;
  4099. update_transform_gizmo();
  4100. } break;
  4101. case MENU_TOOL_CONVERT_ROOMS: {
  4102. RoomManager::static_rooms_convert();
  4103. update_portal_tools();
  4104. } break;
  4105. case MENU_TRANSFORM_CONFIGURE_SNAP: {
  4106. snap_dialog->popup_centered(Size2(200, 180));
  4107. } break;
  4108. case MENU_TRANSFORM_DIALOG: {
  4109. for (int i = 0; i < 3; i++) {
  4110. xform_translate[i]->set_text("0");
  4111. xform_rotate[i]->set_text("0");
  4112. xform_scale[i]->set_text("1");
  4113. }
  4114. xform_dialog->popup_centered(Size2(320, 240) * EDSCALE);
  4115. } break;
  4116. case MENU_VIEW_USE_1_VIEWPORT: {
  4117. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_1_VIEWPORT);
  4118. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), true);
  4119. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  4120. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  4121. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  4122. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  4123. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  4124. } break;
  4125. case MENU_VIEW_USE_2_VIEWPORTS: {
  4126. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_2_VIEWPORTS);
  4127. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  4128. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), true);
  4129. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  4130. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  4131. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  4132. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  4133. } break;
  4134. case MENU_VIEW_USE_2_VIEWPORTS_ALT: {
  4135. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_2_VIEWPORTS_ALT);
  4136. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  4137. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  4138. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  4139. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  4140. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), true);
  4141. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  4142. } break;
  4143. case MENU_VIEW_USE_3_VIEWPORTS: {
  4144. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_3_VIEWPORTS);
  4145. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  4146. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  4147. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), true);
  4148. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  4149. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  4150. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  4151. } break;
  4152. case MENU_VIEW_USE_3_VIEWPORTS_ALT: {
  4153. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_3_VIEWPORTS_ALT);
  4154. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  4155. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  4156. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  4157. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  4158. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  4159. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), true);
  4160. } break;
  4161. case MENU_VIEW_USE_4_VIEWPORTS: {
  4162. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_4_VIEWPORTS);
  4163. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  4164. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  4165. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  4166. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), true);
  4167. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  4168. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  4169. } break;
  4170. case MENU_VIEW_ORIGIN: {
  4171. bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
  4172. origin_enabled = !is_checked;
  4173. VisualServer::get_singleton()->instance_set_visible(origin_instance, origin_enabled);
  4174. // Update the grid since its appearance depends on whether the origin is enabled
  4175. _finish_grid();
  4176. _init_grid();
  4177. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), origin_enabled);
  4178. } break;
  4179. case MENU_VIEW_GRID: {
  4180. bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
  4181. grid_enabled = !is_checked;
  4182. for (int i = 0; i < 3; ++i) {
  4183. if (grid_enable[i]) {
  4184. grid_visible[i] = grid_enabled;
  4185. }
  4186. }
  4187. _finish_grid();
  4188. _init_grid();
  4189. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), grid_enabled);
  4190. } break;
  4191. case MENU_VIEW_PORTAL_CULLING: {
  4192. bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
  4193. RoomManager::static_rooms_set_active(!is_checked);
  4194. update_portal_tools();
  4195. } break;
  4196. case MENU_VIEW_OCCLUSION_CULLING: {
  4197. int checkbox_id = view_menu->get_popup()->get_item_index(p_option);
  4198. bool is_checked = view_menu->get_popup()->is_item_checked(checkbox_id);
  4199. VisualServer::get_singleton()->set_use_occlusion_culling(!is_checked);
  4200. view_menu->get_popup()->set_item_checked(checkbox_id, !is_checked);
  4201. } break;
  4202. case MENU_VIEW_CAMERA_SETTINGS: {
  4203. settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size() + Size2(50, 50));
  4204. } break;
  4205. case MENU_SNAP_TO_FLOOR: {
  4206. snap_selected_nodes_to_floor();
  4207. } break;
  4208. case MENU_LOCK_SELECTED: {
  4209. undo_redo->create_action(TTR("Lock Selected"));
  4210. List<Node *> &selection = editor_selection->get_selected_node_list();
  4211. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4212. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  4213. if (!spatial || !spatial->is_visible_in_tree()) {
  4214. continue;
  4215. }
  4216. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  4217. continue;
  4218. }
  4219. undo_redo->add_do_method(spatial, "set_meta", "_edit_lock_", true);
  4220. undo_redo->add_undo_method(spatial, "remove_meta", "_edit_lock_");
  4221. undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
  4222. undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
  4223. }
  4224. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  4225. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  4226. undo_redo->commit_action();
  4227. } break;
  4228. case MENU_UNLOCK_SELECTED: {
  4229. undo_redo->create_action(TTR("Unlock Selected"));
  4230. List<Node *> &selection = editor_selection->get_selected_node_list();
  4231. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4232. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  4233. if (!spatial || !spatial->is_visible_in_tree()) {
  4234. continue;
  4235. }
  4236. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  4237. continue;
  4238. }
  4239. undo_redo->add_do_method(spatial, "remove_meta", "_edit_lock_");
  4240. undo_redo->add_undo_method(spatial, "set_meta", "_edit_lock_", true);
  4241. undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
  4242. undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
  4243. }
  4244. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  4245. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  4246. undo_redo->commit_action();
  4247. } break;
  4248. case MENU_GROUP_SELECTED: {
  4249. undo_redo->create_action(TTR("Group Selected"));
  4250. List<Node *> &selection = editor_selection->get_selected_node_list();
  4251. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4252. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  4253. if (!spatial || !spatial->is_visible_in_tree()) {
  4254. continue;
  4255. }
  4256. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  4257. continue;
  4258. }
  4259. undo_redo->add_do_method(spatial, "set_meta", "_edit_group_", true);
  4260. undo_redo->add_undo_method(spatial, "remove_meta", "_edit_group_");
  4261. undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
  4262. undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
  4263. }
  4264. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  4265. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  4266. undo_redo->commit_action();
  4267. } break;
  4268. case MENU_UNGROUP_SELECTED: {
  4269. undo_redo->create_action(TTR("Ungroup Selected"));
  4270. List<Node *> &selection = editor_selection->get_selected_node_list();
  4271. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4272. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  4273. if (!spatial || !spatial->is_visible_in_tree()) {
  4274. continue;
  4275. }
  4276. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  4277. continue;
  4278. }
  4279. undo_redo->add_do_method(spatial, "remove_meta", "_edit_group_");
  4280. undo_redo->add_undo_method(spatial, "set_meta", "_edit_group_", true);
  4281. undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
  4282. undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
  4283. }
  4284. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  4285. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  4286. undo_redo->commit_action();
  4287. } break;
  4288. }
  4289. }
  4290. void SpatialEditor::_init_indicators() {
  4291. {
  4292. origin_enabled = true;
  4293. grid_enabled = true;
  4294. indicator_mat.instance();
  4295. indicator_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  4296. indicator_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  4297. indicator_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  4298. indicator_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  4299. Vector<Color> origin_colors;
  4300. Vector<Vector3> origin_points;
  4301. for (int i = 0; i < 3; i++) {
  4302. Vector3 axis;
  4303. axis[i] = 1;
  4304. Color origin_color;
  4305. switch (i) {
  4306. case 0:
  4307. origin_color = get_color("axis_x_color", "Editor");
  4308. break;
  4309. case 1:
  4310. origin_color = get_color("axis_y_color", "Editor");
  4311. break;
  4312. case 2:
  4313. origin_color = get_color("axis_z_color", "Editor");
  4314. break;
  4315. default:
  4316. origin_color = Color();
  4317. break;
  4318. }
  4319. grid_enable[i] = false;
  4320. grid_visible[i] = false;
  4321. origin_colors.push_back(origin_color);
  4322. origin_colors.push_back(origin_color);
  4323. origin_colors.push_back(origin_color);
  4324. origin_colors.push_back(origin_color);
  4325. origin_colors.push_back(origin_color);
  4326. origin_colors.push_back(origin_color);
  4327. // To both allow having a large origin size and avoid jitter
  4328. // at small scales, we should segment the line into pieces.
  4329. // 3 pieces seems to do the trick, and let's use powers of 2.
  4330. origin_points.push_back(axis * 1048576);
  4331. origin_points.push_back(axis * 1024);
  4332. origin_points.push_back(axis * 1024);
  4333. origin_points.push_back(axis * -1024);
  4334. origin_points.push_back(axis * -1024);
  4335. origin_points.push_back(axis * -1048576);
  4336. }
  4337. Ref<Shader> grid_shader = memnew(Shader);
  4338. grid_shader->set_code(
  4339. "\n"
  4340. "shader_type spatial; \n"
  4341. "render_mode unshaded; \n"
  4342. "uniform bool orthogonal; \n"
  4343. "uniform float grid_size; \n"
  4344. "\n"
  4345. "void vertex() { \n"
  4346. " // From FLAG_SRGB_VERTEX_COLOR \n"
  4347. " if (!OUTPUT_IS_SRGB) { \n"
  4348. " COLOR.rgb = mix(pow((COLOR.rgb + vec3(0.055)) * (1.0 / (1.0 + 0.055)), vec3(2.4)), COLOR.rgb * (1.0 / 12.92), lessThan(COLOR.rgb, vec3(0.04045))); \n"
  4349. " } \n"
  4350. "} \n"
  4351. "\n"
  4352. "void fragment() { \n"
  4353. " ALBEDO = COLOR.rgb; \n"
  4354. " vec3 dir = orthogonal ? -vec3(0, 0, 1) : VIEW; \n"
  4355. " float angle_fade = abs(dot(dir, NORMAL)); \n"
  4356. " angle_fade = smoothstep(0.05, 0.2, angle_fade); \n"
  4357. " \n"
  4358. " vec3 world_pos = (CAMERA_MATRIX * vec4(VERTEX, 1.0)).xyz; \n"
  4359. " vec3 world_normal = (CAMERA_MATRIX * vec4(NORMAL, 0.0)).xyz; \n"
  4360. " vec3 camera_world_pos = CAMERA_MATRIX[3].xyz; \n"
  4361. " vec3 camera_world_pos_on_plane = camera_world_pos * (1.0 - world_normal); \n"
  4362. " float dist_fade = 1.0 - (distance(world_pos, camera_world_pos_on_plane) / grid_size); \n"
  4363. " dist_fade = smoothstep(0.02, 0.3, dist_fade); \n"
  4364. " \n"
  4365. " ALPHA = COLOR.a * dist_fade * angle_fade; \n"
  4366. "}");
  4367. for (int i = 0; i < 3; i++) {
  4368. grid_mat[i].instance();
  4369. grid_mat[i]->set_shader(grid_shader);
  4370. }
  4371. grid_enable[0] = EditorSettings::get_singleton()->get("editors/3d/grid_xy_plane");
  4372. grid_enable[1] = EditorSettings::get_singleton()->get("editors/3d/grid_yz_plane");
  4373. grid_enable[2] = EditorSettings::get_singleton()->get("editors/3d/grid_xz_plane");
  4374. grid_visible[0] = grid_enable[0];
  4375. grid_visible[1] = grid_enable[1];
  4376. grid_visible[2] = grid_enable[2];
  4377. _init_grid();
  4378. origin = VisualServer::get_singleton()->mesh_create();
  4379. Array d;
  4380. d.resize(VS::ARRAY_MAX);
  4381. d[VisualServer::ARRAY_VERTEX] = origin_points;
  4382. d[VisualServer::ARRAY_COLOR] = origin_colors;
  4383. VisualServer::get_singleton()->mesh_add_surface_from_arrays(origin, VisualServer::PRIMITIVE_LINES, d);
  4384. VisualServer::get_singleton()->mesh_surface_set_material(origin, 0, indicator_mat->get_rid());
  4385. origin_instance = VisualServer::get_singleton()->instance_create2(origin, get_tree()->get_root()->get_world()->get_scenario());
  4386. VS::get_singleton()->instance_set_layer_mask(origin_instance, 1 << SpatialEditorViewport::GIZMO_GRID_LAYER);
  4387. VisualServer::get_singleton()->instance_geometry_set_cast_shadows_setting(origin_instance, VS::SHADOW_CASTING_SETTING_OFF);
  4388. }
  4389. {
  4390. //move gizmo
  4391. for (int i = 0; i < 3; i++) {
  4392. Color col;
  4393. switch (i) {
  4394. case 0:
  4395. col = get_color("axis_x_color", "Editor");
  4396. break;
  4397. case 1:
  4398. col = get_color("axis_y_color", "Editor");
  4399. break;
  4400. case 2:
  4401. col = get_color("axis_z_color", "Editor");
  4402. break;
  4403. default:
  4404. col = Color();
  4405. break;
  4406. }
  4407. col.a = EditorSettings::get_singleton()->get("editors/3d/manipulator_gizmo_opacity");
  4408. move_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  4409. move_plane_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  4410. rotate_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  4411. scale_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  4412. scale_plane_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  4413. Ref<SpatialMaterial> mat = memnew(SpatialMaterial);
  4414. mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  4415. mat->set_on_top_of_alpha();
  4416. mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  4417. mat->set_albedo(col);
  4418. gizmo_color[i] = mat;
  4419. Ref<SpatialMaterial> mat_hl = mat->duplicate();
  4420. const Color albedo = col.from_hsv(col.get_h(), 0.25, 1.0, 1);
  4421. mat_hl->set_albedo(albedo);
  4422. gizmo_color_hl[i] = mat_hl;
  4423. Vector3 ivec;
  4424. ivec[i] = 1;
  4425. Vector3 nivec;
  4426. nivec[(i + 1) % 3] = 1;
  4427. nivec[(i + 2) % 3] = 1;
  4428. Vector3 ivec2;
  4429. ivec2[(i + 1) % 3] = 1;
  4430. Vector3 ivec3;
  4431. ivec3[(i + 2) % 3] = 1;
  4432. //translate
  4433. {
  4434. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  4435. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  4436. // Arrow profile
  4437. const int arrow_points = 5;
  4438. Vector3 arrow[5] = {
  4439. nivec * 0.0 + ivec * 0.0,
  4440. nivec * 0.01 + ivec * 0.0,
  4441. nivec * 0.01 + ivec * GIZMO_ARROW_OFFSET,
  4442. nivec * 0.065 + ivec * GIZMO_ARROW_OFFSET,
  4443. nivec * 0.0 + ivec * (GIZMO_ARROW_OFFSET + GIZMO_ARROW_SIZE),
  4444. };
  4445. int arrow_sides = 16;
  4446. for (int k = 0; k < arrow_sides; k++) {
  4447. Basis ma(ivec, Math_PI * 2 * float(k) / arrow_sides);
  4448. Basis mb(ivec, Math_PI * 2 * float(k + 1) / arrow_sides);
  4449. for (int j = 0; j < arrow_points - 1; j++) {
  4450. Vector3 points[4] = {
  4451. ma.xform(arrow[j]),
  4452. mb.xform(arrow[j]),
  4453. mb.xform(arrow[j + 1]),
  4454. ma.xform(arrow[j + 1]),
  4455. };
  4456. surftool->add_vertex(points[0]);
  4457. surftool->add_vertex(points[1]);
  4458. surftool->add_vertex(points[2]);
  4459. surftool->add_vertex(points[0]);
  4460. surftool->add_vertex(points[2]);
  4461. surftool->add_vertex(points[3]);
  4462. }
  4463. }
  4464. surftool->set_material(mat);
  4465. surftool->commit(move_gizmo[i]);
  4466. }
  4467. // Plane Translation
  4468. {
  4469. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  4470. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  4471. Vector3 vec = ivec2 - ivec3;
  4472. Vector3 plane[4] = {
  4473. vec * GIZMO_PLANE_DST,
  4474. vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
  4475. vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
  4476. vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
  4477. };
  4478. Basis ma(ivec, Math_PI / 2);
  4479. Vector3 points[4] = {
  4480. ma.xform(plane[0]),
  4481. ma.xform(plane[1]),
  4482. ma.xform(plane[2]),
  4483. ma.xform(plane[3]),
  4484. };
  4485. surftool->add_vertex(points[0]);
  4486. surftool->add_vertex(points[1]);
  4487. surftool->add_vertex(points[2]);
  4488. surftool->add_vertex(points[0]);
  4489. surftool->add_vertex(points[2]);
  4490. surftool->add_vertex(points[3]);
  4491. Ref<SpatialMaterial> plane_mat = memnew(SpatialMaterial);
  4492. plane_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  4493. plane_mat->set_on_top_of_alpha();
  4494. plane_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  4495. plane_mat->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  4496. plane_mat->set_albedo(col);
  4497. plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides
  4498. surftool->set_material(plane_mat);
  4499. surftool->commit(move_plane_gizmo[i]);
  4500. Ref<SpatialMaterial> plane_mat_hl = plane_mat->duplicate();
  4501. plane_mat_hl->set_albedo(albedo);
  4502. plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
  4503. }
  4504. // Rotate
  4505. {
  4506. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  4507. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  4508. int n = 128; // number of circle segments
  4509. int m = 3; // number of thickness segments
  4510. for (int j = 0; j < n; ++j) {
  4511. Basis basis = Basis(ivec, (Math_PI * 2.0f * j) / n);
  4512. Vector3 vertex = basis.xform(ivec2 * GIZMO_CIRCLE_SIZE);
  4513. for (int k = 0; k < m; ++k) {
  4514. Vector2 ofs = Vector2(Math::cos((Math_PI * 2.0 * k) / m), Math::sin((Math_PI * 2.0 * k) / m));
  4515. Vector3 normal = ivec * ofs.x + ivec2 * ofs.y;
  4516. surftool->add_normal(basis.xform(normal));
  4517. surftool->add_vertex(vertex);
  4518. }
  4519. }
  4520. for (int j = 0; j < n; ++j) {
  4521. for (int k = 0; k < m; ++k) {
  4522. int current_ring = j * m;
  4523. int next_ring = ((j + 1) % n) * m;
  4524. int current_segment = k;
  4525. int next_segment = (k + 1) % m;
  4526. surftool->add_index(current_ring + next_segment);
  4527. surftool->add_index(current_ring + current_segment);
  4528. surftool->add_index(next_ring + current_segment);
  4529. surftool->add_index(next_ring + current_segment);
  4530. surftool->add_index(next_ring + next_segment);
  4531. surftool->add_index(current_ring + next_segment);
  4532. }
  4533. }
  4534. Ref<Shader> rotate_shader = memnew(Shader);
  4535. rotate_shader->set_code(
  4536. "\n"
  4537. "shader_type spatial; \n"
  4538. "render_mode unshaded, depth_test_disable; \n"
  4539. "uniform vec4 albedo; \n"
  4540. "\n"
  4541. "mat3 orthonormalize(mat3 m) { \n"
  4542. " vec3 x = normalize(m[0]); \n"
  4543. " vec3 y = normalize(m[1] - x * dot(x, m[1])); \n"
  4544. " vec3 z = m[2] - x * dot(x, m[2]); \n"
  4545. " z = normalize(z - y * (dot(y,m[2]))); \n"
  4546. " return mat3(x,y,z); \n"
  4547. "} \n"
  4548. "\n"
  4549. "void vertex() { \n"
  4550. " mat3 mv = orthonormalize(mat3(MODELVIEW_MATRIX)); \n"
  4551. " vec3 n = mv * VERTEX; \n"
  4552. " float orientation = dot(vec3(0,0,-1),n); \n"
  4553. " if (orientation <= 0.005) { \n"
  4554. " VERTEX += NORMAL*0.02; \n"
  4555. " } \n"
  4556. "} \n"
  4557. "\n"
  4558. "void fragment() { \n"
  4559. " ALBEDO = albedo.rgb; \n"
  4560. " ALPHA = albedo.a; \n"
  4561. "}");
  4562. Ref<ShaderMaterial> rotate_mat = memnew(ShaderMaterial);
  4563. rotate_mat->set_render_priority(Material::RENDER_PRIORITY_MAX);
  4564. rotate_mat->set_shader(rotate_shader);
  4565. rotate_mat->set_shader_param("albedo", col);
  4566. rotate_gizmo_color[i] = rotate_mat;
  4567. Array arrays = surftool->commit_to_arrays();
  4568. rotate_gizmo[i]->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);
  4569. rotate_gizmo[i]->surface_set_material(0, rotate_mat);
  4570. Ref<ShaderMaterial> rotate_mat_hl = rotate_mat->duplicate();
  4571. rotate_mat_hl->set_shader_param("albedo", albedo);
  4572. rotate_gizmo_color_hl[i] = rotate_mat_hl;
  4573. if (i == 2) { // Rotation white outline
  4574. Ref<ShaderMaterial> border_mat = rotate_mat->duplicate();
  4575. Ref<Shader> border_shader = memnew(Shader);
  4576. border_shader->set_code(
  4577. "\n"
  4578. "shader_type spatial; \n"
  4579. "render_mode unshaded, depth_test_disable; \n"
  4580. "uniform vec4 albedo; \n"
  4581. "\n"
  4582. "mat3 orthonormalize(mat3 m) { \n"
  4583. " vec3 x = normalize(m[0]); \n"
  4584. " vec3 y = normalize(m[1] - x * dot(x, m[1])); \n"
  4585. " vec3 z = m[2] - x * dot(x, m[2]); \n"
  4586. " z = normalize(z - y * (dot(y,m[2]))); \n"
  4587. " return mat3(x,y,z); \n"
  4588. "} \n"
  4589. "\n"
  4590. "void vertex() { \n"
  4591. " mat3 mv = orthonormalize(mat3(MODELVIEW_MATRIX)); \n"
  4592. " mv = inverse(mv); \n"
  4593. " VERTEX += NORMAL*0.008; \n"
  4594. " vec3 camera_dir_local = mv * vec3(0,0,1); \n"
  4595. " vec3 camera_up_local = mv * vec3(0,1,0); \n"
  4596. " mat3 rotation_matrix = mat3(cross(camera_dir_local, camera_up_local), camera_up_local, camera_dir_local); \n"
  4597. " VERTEX = rotation_matrix * VERTEX; \n"
  4598. "} \n"
  4599. "\n"
  4600. "void fragment() { \n"
  4601. " ALBEDO = albedo.rgb; \n"
  4602. " ALPHA = albedo.a; \n"
  4603. "}");
  4604. border_mat->set_shader(border_shader);
  4605. border_mat->set_shader_param("albedo", Color(0.75, 0.75, 0.75, col.a / 3.0));
  4606. rotate_gizmo[3] = Ref<ArrayMesh>(memnew(ArrayMesh));
  4607. rotate_gizmo[3]->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);
  4608. rotate_gizmo[3]->surface_set_material(0, border_mat);
  4609. }
  4610. }
  4611. // Scale
  4612. {
  4613. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  4614. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  4615. // Cube arrow profile
  4616. const int arrow_points = 6;
  4617. Vector3 arrow[6] = {
  4618. nivec * 0.0 + ivec * 0.0,
  4619. nivec * 0.01 + ivec * 0.0,
  4620. nivec * 0.01 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
  4621. nivec * 0.07 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
  4622. nivec * 0.07 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
  4623. nivec * 0.0 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
  4624. };
  4625. int arrow_sides = 4;
  4626. for (int k = 0; k < 4; k++) {
  4627. Basis ma(ivec, Math_PI * 2 * float(k) / arrow_sides);
  4628. Basis mb(ivec, Math_PI * 2 * float(k + 1) / arrow_sides);
  4629. for (int j = 0; j < arrow_points - 1; j++) {
  4630. Vector3 points[4] = {
  4631. ma.xform(arrow[j]),
  4632. mb.xform(arrow[j]),
  4633. mb.xform(arrow[j + 1]),
  4634. ma.xform(arrow[j + 1]),
  4635. };
  4636. surftool->add_vertex(points[0]);
  4637. surftool->add_vertex(points[1]);
  4638. surftool->add_vertex(points[2]);
  4639. surftool->add_vertex(points[0]);
  4640. surftool->add_vertex(points[2]);
  4641. surftool->add_vertex(points[3]);
  4642. }
  4643. }
  4644. surftool->set_material(mat);
  4645. surftool->commit(scale_gizmo[i]);
  4646. }
  4647. // Plane Scale
  4648. {
  4649. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  4650. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  4651. Vector3 vec = ivec2 - ivec3;
  4652. Vector3 plane[4] = {
  4653. vec * GIZMO_PLANE_DST,
  4654. vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
  4655. vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
  4656. vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
  4657. };
  4658. Basis ma(ivec, Math_PI / 2);
  4659. Vector3 points[4] = {
  4660. ma.xform(plane[0]),
  4661. ma.xform(plane[1]),
  4662. ma.xform(plane[2]),
  4663. ma.xform(plane[3]),
  4664. };
  4665. surftool->add_vertex(points[0]);
  4666. surftool->add_vertex(points[1]);
  4667. surftool->add_vertex(points[2]);
  4668. surftool->add_vertex(points[0]);
  4669. surftool->add_vertex(points[2]);
  4670. surftool->add_vertex(points[3]);
  4671. Ref<SpatialMaterial> plane_mat = memnew(SpatialMaterial);
  4672. plane_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  4673. plane_mat->set_on_top_of_alpha();
  4674. plane_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  4675. plane_mat->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  4676. plane_mat->set_albedo(col);
  4677. plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides
  4678. surftool->set_material(plane_mat);
  4679. surftool->commit(scale_plane_gizmo[i]);
  4680. Ref<SpatialMaterial> plane_mat_hl = plane_mat->duplicate();
  4681. plane_mat_hl->set_albedo(col.from_hsv(col.get_h(), 0.25, 1.0, 1));
  4682. plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
  4683. }
  4684. }
  4685. }
  4686. _generate_selection_boxes();
  4687. }
  4688. void SpatialEditor::_update_context_menu_stylebox() {
  4689. // This must be called when the theme changes to follow the new accent color.
  4690. Ref<StyleBoxFlat> context_menu_stylebox = memnew(StyleBoxFlat);
  4691. const Color accent_color = EditorNode::get_singleton()->get_gui_base()->get_color("accent_color", "Editor");
  4692. context_menu_stylebox->set_bg_color(accent_color * Color(1, 1, 1, 0.1));
  4693. // Add an underline to the StyleBox, but prevent its minimum vertical size from changing.
  4694. context_menu_stylebox->set_border_color(accent_color);
  4695. context_menu_stylebox->set_border_width(MARGIN_BOTTOM, Math::round(2 * EDSCALE));
  4696. context_menu_stylebox->set_default_margin(MARGIN_BOTTOM, 0);
  4697. context_menu_container->add_style_override("panel", context_menu_stylebox);
  4698. }
  4699. void SpatialEditor::_update_gizmos_menu() {
  4700. gizmos_menu->clear();
  4701. for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
  4702. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  4703. continue;
  4704. }
  4705. String plugin_name = gizmo_plugins_by_name[i]->get_name();
  4706. const int plugin_state = gizmo_plugins_by_name[i]->get_state();
  4707. gizmos_menu->add_multistate_item(TTR(plugin_name), 3, plugin_state, i);
  4708. const int idx = gizmos_menu->get_item_index(i);
  4709. gizmos_menu->set_item_tooltip(
  4710. idx,
  4711. TTR("Click to toggle between visibility states.\n\nOpen eye: Gizmo is visible.\nClosed eye: Gizmo is hidden.\nHalf-open eye: Gizmo is also visible through opaque surfaces (\"x-ray\")."));
  4712. switch (plugin_state) {
  4713. case EditorSpatialGizmoPlugin::VISIBLE:
  4714. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_visible"));
  4715. break;
  4716. case EditorSpatialGizmoPlugin::ON_TOP:
  4717. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_xray"));
  4718. break;
  4719. case EditorSpatialGizmoPlugin::HIDDEN:
  4720. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_hidden"));
  4721. break;
  4722. }
  4723. }
  4724. }
  4725. void SpatialEditor::_update_gizmos_menu_theme() {
  4726. for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
  4727. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  4728. continue;
  4729. }
  4730. const int plugin_state = gizmo_plugins_by_name[i]->get_state();
  4731. const int idx = gizmos_menu->get_item_index(i);
  4732. switch (plugin_state) {
  4733. case EditorSpatialGizmoPlugin::VISIBLE:
  4734. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_visible"));
  4735. break;
  4736. case EditorSpatialGizmoPlugin::ON_TOP:
  4737. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_xray"));
  4738. break;
  4739. case EditorSpatialGizmoPlugin::HIDDEN:
  4740. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_hidden"));
  4741. break;
  4742. }
  4743. }
  4744. }
  4745. void SpatialEditor::_init_grid() {
  4746. if (!grid_enabled) {
  4747. return;
  4748. }
  4749. Camera *camera = get_editor_viewport(0)->camera;
  4750. Vector3 camera_position = camera->get_translation();
  4751. if (camera_position == Vector3()) {
  4752. return; // Camera is invalid, don't draw the grid.
  4753. }
  4754. bool orthogonal = camera->get_projection() == Camera::PROJECTION_ORTHOGONAL;
  4755. PoolVector<Color> grid_colors[3];
  4756. PoolVector<Vector3> grid_points[3];
  4757. PoolVector<Vector3> grid_normals[3];
  4758. Color primary_grid_color = EditorSettings::get_singleton()->get("editors/3d/primary_grid_color");
  4759. Color secondary_grid_color = EditorSettings::get_singleton()->get("editors/3d/secondary_grid_color");
  4760. int grid_size = EditorSettings::get_singleton()->get("editors/3d/grid_size");
  4761. int primary_grid_steps = EditorSettings::get_singleton()->get("editors/3d/primary_grid_steps");
  4762. // Which grid planes are enabled? Which should we generate?
  4763. grid_enable[0] = grid_visible[0] = EditorSettings::get_singleton()->get("editors/3d/grid_xy_plane");
  4764. grid_enable[1] = grid_visible[1] = EditorSettings::get_singleton()->get("editors/3d/grid_yz_plane");
  4765. grid_enable[2] = grid_visible[2] = EditorSettings::get_singleton()->get("editors/3d/grid_xz_plane");
  4766. // Offsets division_level for bigger or smaller grids.
  4767. // Default value is -0.2. -1.0 gives Blender-like behavior, 0.5 gives huge grids.
  4768. real_t division_level_bias = EditorSettings::get_singleton()->get("editors/3d/grid_division_level_bias");
  4769. // Default largest grid size is 8^2 when primary_grid_steps is 8 (64m apart, so primary grid lines are 512m apart).
  4770. int division_level_max = EditorSettings::get_singleton()->get("editors/3d/grid_division_level_max");
  4771. // Default smallest grid size is 1cm, 10^-2 (default value is -2).
  4772. int division_level_min = EditorSettings::get_singleton()->get("editors/3d/grid_division_level_min");
  4773. ERR_FAIL_COND_MSG(division_level_max < division_level_min, "The 3D grid's maximum division level cannot be lower than its minimum division level.");
  4774. if (primary_grid_steps != 10) { // Log10 of 10 is 1.
  4775. // Change of base rule, divide by ln(10).
  4776. real_t div = Math::log((real_t)primary_grid_steps) / (real_t)2.302585092994045901094;
  4777. // Trucation (towards zero) is intentional.
  4778. division_level_max = (int)(division_level_max / div);
  4779. division_level_min = (int)(division_level_min / div);
  4780. }
  4781. for (int a = 0; a < 3; a++) {
  4782. if (!grid_enable[a]) {
  4783. continue; // If this grid plane is disabled, skip generation.
  4784. }
  4785. int b = (a + 1) % 3;
  4786. int c = (a + 2) % 3;
  4787. Vector3 normal;
  4788. normal[c] = 1.0;
  4789. real_t camera_distance = Math::abs(camera_position[c]);
  4790. if (orthogonal) {
  4791. camera_distance = camera->get_size() / 2.0;
  4792. Vector3 camera_direction = -camera->get_global_transform().get_basis().get_axis(2);
  4793. Plane grid_plane = Plane(Vector3(), normal);
  4794. Vector3 intersection;
  4795. if (grid_plane.intersects_ray(camera_position, camera_direction, &intersection)) {
  4796. camera_position = intersection;
  4797. }
  4798. }
  4799. real_t division_level = Math::log(Math::abs(camera_distance)) / Math::log((double)primary_grid_steps) + division_level_bias;
  4800. real_t clamped_division_level = CLAMP(division_level, division_level_min, division_level_max);
  4801. real_t division_level_floored = Math::floor(clamped_division_level);
  4802. real_t division_level_decimals = clamped_division_level - division_level_floored;
  4803. real_t small_step_size = Math::pow(primary_grid_steps, division_level_floored);
  4804. real_t large_step_size = small_step_size * primary_grid_steps;
  4805. real_t center_a = large_step_size * (int)(camera_position[a] / large_step_size);
  4806. real_t center_b = large_step_size * (int)(camera_position[b] / large_step_size);
  4807. real_t bgn_a = center_a - grid_size * small_step_size;
  4808. real_t end_a = center_a + grid_size * small_step_size;
  4809. real_t bgn_b = center_b - grid_size * small_step_size;
  4810. real_t end_b = center_b + grid_size * small_step_size;
  4811. real_t fade_size = Math::pow(primary_grid_steps, division_level - 1.0);
  4812. real_t min_fade_size = Math::pow(primary_grid_steps, float(division_level_min));
  4813. real_t max_fade_size = Math::pow(primary_grid_steps, float(division_level_max));
  4814. fade_size = CLAMP(fade_size, min_fade_size, max_fade_size);
  4815. real_t grid_fade_size = (grid_size - primary_grid_steps) * fade_size;
  4816. grid_mat[c]->set_shader_param("grid_size", grid_fade_size);
  4817. grid_mat[c]->set_shader_param("orthogonal", orthogonal);
  4818. // In each iteration of this loop, draw one line in each direction (so two lines per loop, in each if statement).
  4819. for (int i = -grid_size; i <= grid_size; i++) {
  4820. Color line_color;
  4821. // Is this a primary line? Set the appropriate color.
  4822. if (i % primary_grid_steps == 0) {
  4823. line_color = primary_grid_color.linear_interpolate(secondary_grid_color, division_level_decimals);
  4824. } else {
  4825. line_color = secondary_grid_color;
  4826. line_color.a = line_color.a * (1 - division_level_decimals);
  4827. }
  4828. real_t position_a = center_a + i * small_step_size;
  4829. real_t position_b = center_b + i * small_step_size;
  4830. // Don't draw lines over the origin if it's enabled.
  4831. if (!(origin_enabled && Math::is_zero_approx(position_a))) {
  4832. Vector3 line_bgn = Vector3();
  4833. Vector3 line_end = Vector3();
  4834. line_bgn[a] = position_a;
  4835. line_end[a] = position_a;
  4836. line_bgn[b] = bgn_b;
  4837. line_end[b] = end_b;
  4838. grid_points[c].push_back(line_bgn);
  4839. grid_points[c].push_back(line_end);
  4840. grid_colors[c].push_back(line_color);
  4841. grid_colors[c].push_back(line_color);
  4842. grid_normals[c].push_back(normal);
  4843. grid_normals[c].push_back(normal);
  4844. }
  4845. if (!(origin_enabled && Math::is_zero_approx(position_b))) {
  4846. Vector3 line_bgn = Vector3();
  4847. Vector3 line_end = Vector3();
  4848. line_bgn[b] = position_b;
  4849. line_end[b] = position_b;
  4850. line_bgn[a] = bgn_a;
  4851. line_end[a] = end_a;
  4852. grid_points[c].push_back(line_bgn);
  4853. grid_points[c].push_back(line_end);
  4854. grid_colors[c].push_back(line_color);
  4855. grid_colors[c].push_back(line_color);
  4856. grid_normals[c].push_back(normal);
  4857. grid_normals[c].push_back(normal);
  4858. }
  4859. }
  4860. // Create a mesh from the pushed vector points and colors.
  4861. grid[c] = VisualServer::get_singleton()->mesh_create();
  4862. Array d;
  4863. d.resize(VS::ARRAY_MAX);
  4864. d[VisualServer::ARRAY_VERTEX] = grid_points[c];
  4865. d[VisualServer::ARRAY_COLOR] = grid_colors[c];
  4866. d[VisualServer::ARRAY_NORMAL] = grid_normals[c];
  4867. VisualServer::get_singleton()->mesh_add_surface_from_arrays(grid[c], VisualServer::PRIMITIVE_LINES, d);
  4868. VisualServer::get_singleton()->mesh_surface_set_material(grid[c], 0, grid_mat[c]->get_rid());
  4869. grid_instance[c] = VisualServer::get_singleton()->instance_create2(grid[c], get_tree()->get_root()->get_world()->get_scenario());
  4870. // Yes, the end of this line is supposed to be a.
  4871. VisualServer::get_singleton()->instance_set_visible(grid_instance[c], grid_visible[a]);
  4872. VisualServer::get_singleton()->instance_geometry_set_cast_shadows_setting(grid_instance[c], VS::SHADOW_CASTING_SETTING_OFF);
  4873. VS::get_singleton()->instance_set_layer_mask(grid_instance[c], 1 << SpatialEditorViewport::GIZMO_GRID_LAYER);
  4874. }
  4875. }
  4876. void SpatialEditor::_finish_indicators() {
  4877. VisualServer::get_singleton()->free(origin_instance);
  4878. VisualServer::get_singleton()->free(origin);
  4879. _finish_grid();
  4880. }
  4881. void SpatialEditor::_finish_grid() {
  4882. for (int i = 0; i < 3; i++) {
  4883. VisualServer::get_singleton()->free(grid_instance[i]);
  4884. VisualServer::get_singleton()->free(grid[i]);
  4885. }
  4886. }
  4887. void SpatialEditor::update_grid() {
  4888. _finish_grid();
  4889. _init_grid();
  4890. }
  4891. bool SpatialEditor::is_any_freelook_active() const {
  4892. for (unsigned int i = 0; i < VIEWPORTS_COUNT; ++i) {
  4893. if (viewports[i]->is_freelook_active()) {
  4894. return true;
  4895. }
  4896. }
  4897. return false;
  4898. }
  4899. void SpatialEditor::_refresh_menu_icons() {
  4900. bool all_locked = true;
  4901. bool all_grouped = true;
  4902. List<Node *> &selection = editor_selection->get_selected_node_list();
  4903. if (selection.empty()) {
  4904. all_locked = false;
  4905. all_grouped = false;
  4906. } else {
  4907. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4908. if (Object::cast_to<Spatial>(E->get()) && !Object::cast_to<Spatial>(E->get())->has_meta("_edit_lock_")) {
  4909. all_locked = false;
  4910. break;
  4911. }
  4912. }
  4913. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4914. if (Object::cast_to<Spatial>(E->get()) && !Object::cast_to<Spatial>(E->get())->has_meta("_edit_group_")) {
  4915. all_grouped = false;
  4916. break;
  4917. }
  4918. }
  4919. }
  4920. tool_button[TOOL_LOCK_SELECTED]->set_visible(!all_locked);
  4921. tool_button[TOOL_LOCK_SELECTED]->set_disabled(selection.empty());
  4922. tool_button[TOOL_UNLOCK_SELECTED]->set_visible(all_locked);
  4923. tool_button[TOOL_GROUP_SELECTED]->set_visible(!all_grouped);
  4924. tool_button[TOOL_GROUP_SELECTED]->set_disabled(selection.empty());
  4925. tool_button[TOOL_UNGROUP_SELECTED]->set_visible(all_grouped);
  4926. }
  4927. template <typename T>
  4928. Set<T *> _get_child_nodes(Node *parent_node) {
  4929. Set<T *> nodes = Set<T *>();
  4930. T *node = Node::cast_to<T>(parent_node);
  4931. if (node) {
  4932. nodes.insert(node);
  4933. }
  4934. for (int i = 0; i < parent_node->get_child_count(); i++) {
  4935. Node *child_node = parent_node->get_child(i);
  4936. Set<T *> child_nodes = _get_child_nodes<T>(child_node);
  4937. for (typename Set<T *>::Element *I = child_nodes.front(); I; I = I->next()) {
  4938. nodes.insert(I->get());
  4939. }
  4940. }
  4941. return nodes;
  4942. }
  4943. Set<RID> _get_physics_bodies_rid(Node *node) {
  4944. Set<RID> rids = Set<RID>();
  4945. PhysicsBody *pb = Node::cast_to<PhysicsBody>(node);
  4946. if (pb) {
  4947. rids.insert(pb->get_rid());
  4948. }
  4949. Set<PhysicsBody *> child_nodes = _get_child_nodes<PhysicsBody>(node);
  4950. for (Set<PhysicsBody *>::Element *I = child_nodes.front(); I; I = I->next()) {
  4951. rids.insert(I->get()->get_rid());
  4952. }
  4953. return rids;
  4954. }
  4955. void SpatialEditor::snap_selected_nodes_to_floor() {
  4956. List<Node *> &selection = editor_selection->get_selected_node_list();
  4957. Dictionary snap_data;
  4958. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4959. Spatial *sp = Object::cast_to<Spatial>(E->get());
  4960. if (sp) {
  4961. Vector3 from = Vector3();
  4962. Vector3 position_offset = Vector3();
  4963. // Priorities for snapping to floor are CollisionShapes, VisualInstances and then origin
  4964. Set<VisualInstance *> vi = _get_child_nodes<VisualInstance>(sp);
  4965. Set<CollisionShape *> cs = _get_child_nodes<CollisionShape>(sp);
  4966. bool found_valid_shape = false;
  4967. if (cs.size()) {
  4968. AABB aabb;
  4969. Set<CollisionShape *>::Element *I = cs.front();
  4970. if (I->get()->get_shape().is_valid()) {
  4971. CollisionShape *collision_shape = cs.front()->get();
  4972. aabb = collision_shape->get_global_transform().xform(collision_shape->get_shape()->get_debug_mesh()->get_aabb());
  4973. found_valid_shape = true;
  4974. }
  4975. for (I = I->next(); I; I = I->next()) {
  4976. CollisionShape *col_shape = I->get();
  4977. if (col_shape->get_shape().is_valid()) {
  4978. aabb.merge_with(col_shape->get_global_transform().xform(col_shape->get_shape()->get_debug_mesh()->get_aabb()));
  4979. found_valid_shape = true;
  4980. }
  4981. }
  4982. if (found_valid_shape) {
  4983. Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
  4984. from = aabb.position + size;
  4985. position_offset.y = from.y - sp->get_global_transform().origin.y;
  4986. }
  4987. }
  4988. if (!found_valid_shape && vi.size()) {
  4989. AABB aabb = vi.front()->get()->get_transformed_aabb();
  4990. for (Set<VisualInstance *>::Element *I = vi.front(); I; I = I->next()) {
  4991. aabb.merge_with(I->get()->get_transformed_aabb());
  4992. }
  4993. Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
  4994. from = aabb.position + size;
  4995. position_offset.y = from.y - sp->get_global_transform().origin.y;
  4996. } else if (!found_valid_shape) {
  4997. from = sp->get_global_transform().origin;
  4998. }
  4999. // We add a bit of margin to the from position to avoid it from snapping
  5000. // when the spatial is already on a floor and there's another floor under
  5001. // it
  5002. from = from + Vector3(0.0, 1, 0.0);
  5003. Dictionary d;
  5004. d["from"] = from;
  5005. d["position_offset"] = position_offset;
  5006. snap_data[sp] = d;
  5007. }
  5008. }
  5009. PhysicsDirectSpaceState *ss = get_tree()->get_root()->get_world()->get_direct_space_state();
  5010. PhysicsDirectSpaceState::RayResult result;
  5011. Array keys = snap_data.keys();
  5012. // The maximum height an object can travel to be snapped
  5013. const float max_snap_height = 500.0;
  5014. // Will be set to `true` if at least one node from the selection was successfully snapped
  5015. bool snapped_to_floor = false;
  5016. if (keys.size()) {
  5017. // For snapping to be performed, there must be solid geometry under at least one of the selected nodes.
  5018. // We need to check this before snapping to register the undo/redo action only if needed.
  5019. for (int i = 0; i < keys.size(); i++) {
  5020. Node *node = keys[i];
  5021. Spatial *sp = Object::cast_to<Spatial>(node);
  5022. Dictionary d = snap_data[node];
  5023. Vector3 from = d["from"];
  5024. Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
  5025. Set<RID> excluded = _get_physics_bodies_rid(sp);
  5026. if (ss->intersect_ray(from, to, result, excluded)) {
  5027. snapped_to_floor = true;
  5028. }
  5029. }
  5030. if (snapped_to_floor) {
  5031. undo_redo->create_action(TTR("Snap Nodes to Floor"));
  5032. // Perform snapping if at least one node can be snapped
  5033. for (int i = 0; i < keys.size(); i++) {
  5034. Node *node = keys[i];
  5035. Spatial *sp = Object::cast_to<Spatial>(node);
  5036. Dictionary d = snap_data[node];
  5037. Vector3 from = d["from"];
  5038. Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
  5039. Set<RID> excluded = _get_physics_bodies_rid(sp);
  5040. if (ss->intersect_ray(from, to, result, excluded)) {
  5041. Vector3 position_offset = d["position_offset"];
  5042. Transform new_transform = sp->get_global_transform();
  5043. new_transform.origin.y = result.position.y;
  5044. new_transform.origin = new_transform.origin - position_offset;
  5045. undo_redo->add_do_method(sp, "set_global_transform", new_transform);
  5046. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_transform());
  5047. }
  5048. }
  5049. undo_redo->commit_action();
  5050. } else {
  5051. EditorNode::get_singleton()->show_warning(TTR("Couldn't find a solid floor to snap the selection to."));
  5052. }
  5053. }
  5054. }
  5055. void SpatialEditor::_unhandled_key_input(Ref<InputEvent> p_event) {
  5056. ERR_FAIL_COND(p_event.is_null());
  5057. if (!is_visible_in_tree() || get_viewport()->gui_has_modal_stack()) {
  5058. return;
  5059. }
  5060. snap_key_enabled = Input::get_singleton()->is_key_pressed(KEY_CONTROL);
  5061. }
  5062. void SpatialEditor::_notification(int p_what) {
  5063. if (p_what == NOTIFICATION_READY) {
  5064. tool_button[SpatialEditor::TOOL_MODE_SELECT]->set_icon(get_icon("ToolSelect", "EditorIcons"));
  5065. tool_button[SpatialEditor::TOOL_MODE_MOVE]->set_icon(get_icon("ToolMove", "EditorIcons"));
  5066. tool_button[SpatialEditor::TOOL_MODE_ROTATE]->set_icon(get_icon("ToolRotate", "EditorIcons"));
  5067. tool_button[SpatialEditor::TOOL_MODE_SCALE]->set_icon(get_icon("ToolScale", "EditorIcons"));
  5068. tool_button[SpatialEditor::TOOL_MODE_LIST_SELECT]->set_icon(get_icon("ListSelect", "EditorIcons"));
  5069. tool_button[SpatialEditor::TOOL_LOCK_SELECTED]->set_icon(get_icon("Lock", "EditorIcons"));
  5070. tool_button[SpatialEditor::TOOL_UNLOCK_SELECTED]->set_icon(get_icon("Unlock", "EditorIcons"));
  5071. tool_button[SpatialEditor::TOOL_GROUP_SELECTED]->set_icon(get_icon("Group", "EditorIcons"));
  5072. tool_button[SpatialEditor::TOOL_UNGROUP_SELECTED]->set_icon(get_icon("Ungroup", "EditorIcons"));
  5073. tool_button[SpatialEditor::TOOL_CONVERT_ROOMS]->set_icon(get_icon("RoomGroup", "EditorIcons"));
  5074. tool_option_button[SpatialEditor::TOOL_OPT_LOCAL_COORDS]->set_icon(get_icon("Object", "EditorIcons"));
  5075. tool_option_button[SpatialEditor::TOOL_OPT_USE_SNAP]->set_icon(get_icon("Snap", "EditorIcons"));
  5076. tool_option_button[SpatialEditor::TOOL_OPT_OVERRIDE_CAMERA]->set_icon(get_icon("Camera", "EditorIcons"));
  5077. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), get_icon("Panels1", "EditorIcons"));
  5078. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), get_icon("Panels2", "EditorIcons"));
  5079. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), get_icon("Panels2Alt", "EditorIcons"));
  5080. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), get_icon("Panels3", "EditorIcons"));
  5081. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), get_icon("Panels3Alt", "EditorIcons"));
  5082. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), get_icon("Panels4", "EditorIcons"));
  5083. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  5084. _refresh_menu_icons();
  5085. get_tree()->connect("node_removed", this, "_node_removed");
  5086. EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor()->connect("node_changed", this, "_refresh_menu_icons");
  5087. editor_selection->connect("selection_changed", this, "_refresh_menu_icons");
  5088. editor->connect("stop_pressed", this, "_update_camera_override_button", make_binds(false));
  5089. editor->connect("play_pressed", this, "_update_camera_override_button", make_binds(true));
  5090. } else if (p_what == NOTIFICATION_ENTER_TREE) {
  5091. _register_all_gizmos();
  5092. _update_gizmos_menu();
  5093. _init_indicators();
  5094. } else if (p_what == NOTIFICATION_THEME_CHANGED) {
  5095. _update_gizmos_menu_theme();
  5096. _update_context_menu_stylebox();
  5097. } else if (p_what == NOTIFICATION_EXIT_TREE) {
  5098. _finish_indicators();
  5099. } else if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) {
  5100. tool_button[SpatialEditor::TOOL_MODE_SELECT]->set_icon(get_icon("ToolSelect", "EditorIcons"));
  5101. tool_button[SpatialEditor::TOOL_MODE_MOVE]->set_icon(get_icon("ToolMove", "EditorIcons"));
  5102. tool_button[SpatialEditor::TOOL_MODE_ROTATE]->set_icon(get_icon("ToolRotate", "EditorIcons"));
  5103. tool_button[SpatialEditor::TOOL_MODE_SCALE]->set_icon(get_icon("ToolScale", "EditorIcons"));
  5104. tool_button[SpatialEditor::TOOL_MODE_LIST_SELECT]->set_icon(get_icon("ListSelect", "EditorIcons"));
  5105. tool_button[SpatialEditor::TOOL_LOCK_SELECTED]->set_icon(get_icon("Lock", "EditorIcons"));
  5106. tool_button[SpatialEditor::TOOL_UNLOCK_SELECTED]->set_icon(get_icon("Unlock", "EditorIcons"));
  5107. tool_button[SpatialEditor::TOOL_GROUP_SELECTED]->set_icon(get_icon("Group", "EditorIcons"));
  5108. tool_button[SpatialEditor::TOOL_UNGROUP_SELECTED]->set_icon(get_icon("Ungroup", "EditorIcons"));
  5109. tool_option_button[SpatialEditor::TOOL_OPT_LOCAL_COORDS]->set_icon(get_icon("Object", "EditorIcons"));
  5110. tool_option_button[SpatialEditor::TOOL_OPT_USE_SNAP]->set_icon(get_icon("Snap", "EditorIcons"));
  5111. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), get_icon("Panels1", "EditorIcons"));
  5112. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), get_icon("Panels2", "EditorIcons"));
  5113. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), get_icon("Panels2Alt", "EditorIcons"));
  5114. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), get_icon("Panels3", "EditorIcons"));
  5115. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), get_icon("Panels3Alt", "EditorIcons"));
  5116. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), get_icon("Panels4", "EditorIcons"));
  5117. // Update grid color by rebuilding grid.
  5118. _finish_grid();
  5119. _init_grid();
  5120. } else if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
  5121. if (!is_visible() && tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->is_pressed()) {
  5122. ScriptEditorDebugger *debugger = ScriptEditor::get_singleton()->get_debugger();
  5123. debugger->set_camera_override(ScriptEditorDebugger::OVERRIDE_NONE);
  5124. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_pressed(false);
  5125. }
  5126. }
  5127. }
  5128. void SpatialEditor::add_control_to_menu_panel(Control *p_control) {
  5129. hbc_context_menu->add_child(p_control);
  5130. }
  5131. void SpatialEditor::remove_control_from_menu_panel(Control *p_control) {
  5132. hbc_context_menu->remove_child(p_control);
  5133. }
  5134. void SpatialEditor::set_can_preview(Camera *p_preview) {
  5135. for (int i = 0; i < 4; i++) {
  5136. viewports[i]->set_can_preview(p_preview);
  5137. }
  5138. }
  5139. void SpatialEditor::set_message(String p_message, float p_time) {
  5140. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  5141. SpatialEditorViewport *viewport = get_editor_viewport(i);
  5142. if (viewport->is_visible()) {
  5143. viewport->set_message(p_message, p_time);
  5144. }
  5145. }
  5146. }
  5147. VSplitContainer *SpatialEditor::get_shader_split() {
  5148. return shader_split;
  5149. }
  5150. HSplitContainer *SpatialEditor::get_palette_split() {
  5151. return palette_split;
  5152. }
  5153. void SpatialEditor::_request_gizmo(Object *p_obj) {
  5154. Spatial *sp = Object::cast_to<Spatial>(p_obj);
  5155. if (!sp) {
  5156. return;
  5157. }
  5158. if (editor->get_edited_scene() && (sp == editor->get_edited_scene() || (sp->get_owner() && editor->get_edited_scene()->is_a_parent_of(sp)))) {
  5159. Ref<EditorSpatialGizmo> seg;
  5160. for (int i = 0; i < gizmo_plugins_by_priority.size(); ++i) {
  5161. seg = gizmo_plugins_by_priority.write[i]->get_gizmo(sp);
  5162. if (seg.is_valid()) {
  5163. sp->set_gizmo(seg);
  5164. if (sp == selected) {
  5165. seg->set_selected(true);
  5166. selected->update_gizmo();
  5167. }
  5168. break;
  5169. }
  5170. }
  5171. }
  5172. }
  5173. void SpatialEditor::_toggle_maximize_view(Object *p_viewport) {
  5174. if (!p_viewport) {
  5175. return;
  5176. }
  5177. SpatialEditorViewport *current_viewport = Object::cast_to<SpatialEditorViewport>(p_viewport);
  5178. if (!current_viewport) {
  5179. return;
  5180. }
  5181. int index = -1;
  5182. bool maximized = false;
  5183. for (int i = 0; i < 4; i++) {
  5184. if (viewports[i] == current_viewport) {
  5185. index = i;
  5186. if (current_viewport->get_global_rect() == viewport_base->get_global_rect()) {
  5187. maximized = true;
  5188. }
  5189. break;
  5190. }
  5191. }
  5192. if (index == -1) {
  5193. return;
  5194. }
  5195. if (!maximized) {
  5196. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  5197. if (i == (uint32_t)index) {
  5198. viewports[i]->set_anchors_and_margins_preset(Control::PRESET_WIDE);
  5199. } else {
  5200. viewports[i]->hide();
  5201. }
  5202. }
  5203. } else {
  5204. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  5205. viewports[i]->show();
  5206. }
  5207. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT))) {
  5208. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  5209. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS))) {
  5210. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
  5211. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT))) {
  5212. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
  5213. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS))) {
  5214. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
  5215. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT))) {
  5216. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
  5217. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS))) {
  5218. _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
  5219. }
  5220. }
  5221. }
  5222. void SpatialEditor::_node_removed(Node *p_node) {
  5223. if (p_node == selected) {
  5224. selected = nullptr;
  5225. }
  5226. }
  5227. void SpatialEditor::_register_all_gizmos() {
  5228. add_gizmo_plugin(Ref<CameraSpatialGizmoPlugin>(memnew(CameraSpatialGizmoPlugin)));
  5229. add_gizmo_plugin(Ref<LightSpatialGizmoPlugin>(memnew(LightSpatialGizmoPlugin)));
  5230. add_gizmo_plugin(Ref<AudioStreamPlayer3DSpatialGizmoPlugin>(memnew(AudioStreamPlayer3DSpatialGizmoPlugin)));
  5231. add_gizmo_plugin(Ref<ListenerSpatialGizmoPlugin>(memnew(ListenerSpatialGizmoPlugin)));
  5232. add_gizmo_plugin(Ref<MeshInstanceSpatialGizmoPlugin>(memnew(MeshInstanceSpatialGizmoPlugin)));
  5233. add_gizmo_plugin(Ref<SoftBodySpatialGizmoPlugin>(memnew(SoftBodySpatialGizmoPlugin)));
  5234. add_gizmo_plugin(Ref<Sprite3DSpatialGizmoPlugin>(memnew(Sprite3DSpatialGizmoPlugin)));
  5235. add_gizmo_plugin(Ref<SkeletonSpatialGizmoPlugin>(memnew(SkeletonSpatialGizmoPlugin)));
  5236. add_gizmo_plugin(Ref<Position3DSpatialGizmoPlugin>(memnew(Position3DSpatialGizmoPlugin)));
  5237. add_gizmo_plugin(Ref<RayCastSpatialGizmoPlugin>(memnew(RayCastSpatialGizmoPlugin)));
  5238. add_gizmo_plugin(Ref<SpringArmSpatialGizmoPlugin>(memnew(SpringArmSpatialGizmoPlugin)));
  5239. add_gizmo_plugin(Ref<VehicleWheelSpatialGizmoPlugin>(memnew(VehicleWheelSpatialGizmoPlugin)));
  5240. add_gizmo_plugin(Ref<VisibilityNotifierGizmoPlugin>(memnew(VisibilityNotifierGizmoPlugin)));
  5241. add_gizmo_plugin(Ref<ParticlesGizmoPlugin>(memnew(ParticlesGizmoPlugin)));
  5242. add_gizmo_plugin(Ref<CPUParticlesGizmoPlugin>(memnew(CPUParticlesGizmoPlugin)));
  5243. add_gizmo_plugin(Ref<ReflectionProbeGizmoPlugin>(memnew(ReflectionProbeGizmoPlugin)));
  5244. add_gizmo_plugin(Ref<GIProbeGizmoPlugin>(memnew(GIProbeGizmoPlugin)));
  5245. add_gizmo_plugin(Ref<BakedIndirectLightGizmoPlugin>(memnew(BakedIndirectLightGizmoPlugin)));
  5246. add_gizmo_plugin(Ref<CollisionObjectGizmoPlugin>(memnew(CollisionObjectGizmoPlugin)));
  5247. add_gizmo_plugin(Ref<CollisionShapeSpatialGizmoPlugin>(memnew(CollisionShapeSpatialGizmoPlugin)));
  5248. add_gizmo_plugin(Ref<CollisionPolygonSpatialGizmoPlugin>(memnew(CollisionPolygonSpatialGizmoPlugin)));
  5249. add_gizmo_plugin(Ref<NavigationMeshSpatialGizmoPlugin>(memnew(NavigationMeshSpatialGizmoPlugin)));
  5250. add_gizmo_plugin(Ref<JointSpatialGizmoPlugin>(memnew(JointSpatialGizmoPlugin)));
  5251. add_gizmo_plugin(Ref<PhysicalBoneSpatialGizmoPlugin>(memnew(PhysicalBoneSpatialGizmoPlugin)));
  5252. }
  5253. void SpatialEditor::_bind_methods() {
  5254. ClassDB::bind_method("_unhandled_key_input", &SpatialEditor::_unhandled_key_input);
  5255. ClassDB::bind_method("_node_removed", &SpatialEditor::_node_removed);
  5256. ClassDB::bind_method("_menu_item_pressed", &SpatialEditor::_menu_item_pressed);
  5257. ClassDB::bind_method("_menu_gizmo_toggled", &SpatialEditor::_menu_gizmo_toggled);
  5258. ClassDB::bind_method("_menu_item_toggled", &SpatialEditor::_menu_item_toggled);
  5259. ClassDB::bind_method("_xform_dialog_action", &SpatialEditor::_xform_dialog_action);
  5260. ClassDB::bind_method("_get_editor_data", &SpatialEditor::_get_editor_data);
  5261. ClassDB::bind_method("_request_gizmo", &SpatialEditor::_request_gizmo);
  5262. ClassDB::bind_method("_toggle_maximize_view", &SpatialEditor::_toggle_maximize_view);
  5263. ClassDB::bind_method("_refresh_menu_icons", &SpatialEditor::_refresh_menu_icons);
  5264. ClassDB::bind_method("_update_camera_override_button", &SpatialEditor::_update_camera_override_button);
  5265. ClassDB::bind_method("_update_camera_override_viewport", &SpatialEditor::_update_camera_override_viewport);
  5266. ClassDB::bind_method("_snap_changed", &SpatialEditor::_snap_changed);
  5267. ClassDB::bind_method("_snap_update", &SpatialEditor::_snap_update);
  5268. ADD_SIGNAL(MethodInfo("transform_key_request"));
  5269. ADD_SIGNAL(MethodInfo("item_lock_status_changed"));
  5270. ADD_SIGNAL(MethodInfo("item_group_status_changed"));
  5271. }
  5272. void SpatialEditor::clear() {
  5273. settings_fov->set_value(EDITOR_DEF("editors/3d/default_fov", 70.0));
  5274. settings_znear->set_value(EDITOR_DEF("editors/3d/default_z_near", 0.05));
  5275. settings_zfar->set_value(EDITOR_DEF("editors/3d/default_z_far", 1500.0));
  5276. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  5277. viewports[i]->reset();
  5278. }
  5279. VisualServer::get_singleton()->instance_set_visible(origin_instance, true);
  5280. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), true);
  5281. for (int i = 0; i < 3; ++i) {
  5282. if (grid_enable[i]) {
  5283. grid_visible[i] = true;
  5284. }
  5285. }
  5286. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  5287. viewports[i]->view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(SpatialEditorViewport::VIEW_AUDIO_LISTENER), i == 0);
  5288. viewports[i]->viewport->set_as_audio_listener(i == 0);
  5289. }
  5290. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID), true);
  5291. }
  5292. SpatialEditor::SpatialEditor(EditorNode *p_editor) {
  5293. gizmo.visible = true;
  5294. gizmo.scale = 1.0;
  5295. viewport_environment = Ref<Environment>(memnew(Environment));
  5296. undo_redo = p_editor->get_undo_redo();
  5297. VBoxContainer *vbc = this;
  5298. custom_camera = nullptr;
  5299. singleton = this;
  5300. editor = p_editor;
  5301. editor_selection = editor->get_editor_selection();
  5302. editor_selection->add_editor_plugin(this);
  5303. snap_enabled = false;
  5304. snap_key_enabled = false;
  5305. tool_mode = TOOL_MODE_SELECT;
  5306. camera_override_viewport_id = 0;
  5307. hbc_menu = memnew(HBoxContainer);
  5308. vbc->add_child(hbc_menu);
  5309. Vector<Variant> button_binds;
  5310. button_binds.resize(1);
  5311. String sct;
  5312. tool_button[TOOL_MODE_SELECT] = memnew(ToolButton);
  5313. hbc_menu->add_child(tool_button[TOOL_MODE_SELECT]);
  5314. tool_button[TOOL_MODE_SELECT]->set_toggle_mode(true);
  5315. tool_button[TOOL_MODE_SELECT]->set_flat(true);
  5316. tool_button[TOOL_MODE_SELECT]->set_pressed(true);
  5317. button_binds.write[0] = MENU_TOOL_SELECT;
  5318. tool_button[TOOL_MODE_SELECT]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5319. tool_button[TOOL_MODE_SELECT]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_select", TTR("Select Mode"), KEY_Q));
  5320. tool_button[TOOL_MODE_SELECT]->set_tooltip(keycode_get_string(KEY_MASK_CMD) + TTR("Drag: Rotate selected node around pivot.") + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked."));
  5321. hbc_menu->add_child(memnew(VSeparator));
  5322. tool_button[TOOL_MODE_MOVE] = memnew(ToolButton);
  5323. hbc_menu->add_child(tool_button[TOOL_MODE_MOVE]);
  5324. tool_button[TOOL_MODE_MOVE]->set_toggle_mode(true);
  5325. tool_button[TOOL_MODE_MOVE]->set_flat(true);
  5326. button_binds.write[0] = MENU_TOOL_MOVE;
  5327. tool_button[TOOL_MODE_MOVE]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5328. tool_button[TOOL_MODE_MOVE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_move", TTR("Move Mode"), KEY_W));
  5329. tool_button[TOOL_MODE_ROTATE] = memnew(ToolButton);
  5330. hbc_menu->add_child(tool_button[TOOL_MODE_ROTATE]);
  5331. tool_button[TOOL_MODE_ROTATE]->set_toggle_mode(true);
  5332. tool_button[TOOL_MODE_ROTATE]->set_flat(true);
  5333. button_binds.write[0] = MENU_TOOL_ROTATE;
  5334. tool_button[TOOL_MODE_ROTATE]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5335. tool_button[TOOL_MODE_ROTATE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_rotate", TTR("Rotate Mode"), KEY_E));
  5336. tool_button[TOOL_MODE_SCALE] = memnew(ToolButton);
  5337. hbc_menu->add_child(tool_button[TOOL_MODE_SCALE]);
  5338. tool_button[TOOL_MODE_SCALE]->set_toggle_mode(true);
  5339. tool_button[TOOL_MODE_SCALE]->set_flat(true);
  5340. button_binds.write[0] = MENU_TOOL_SCALE;
  5341. tool_button[TOOL_MODE_SCALE]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5342. tool_button[TOOL_MODE_SCALE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_scale", TTR("Scale Mode"), KEY_R));
  5343. hbc_menu->add_child(memnew(VSeparator));
  5344. tool_button[TOOL_MODE_LIST_SELECT] = memnew(ToolButton);
  5345. hbc_menu->add_child(tool_button[TOOL_MODE_LIST_SELECT]);
  5346. tool_button[TOOL_MODE_LIST_SELECT]->set_toggle_mode(true);
  5347. tool_button[TOOL_MODE_LIST_SELECT]->set_flat(true);
  5348. button_binds.write[0] = MENU_TOOL_LIST_SELECT;
  5349. tool_button[TOOL_MODE_LIST_SELECT]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5350. 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)."));
  5351. tool_button[TOOL_LOCK_SELECTED] = memnew(ToolButton);
  5352. hbc_menu->add_child(tool_button[TOOL_LOCK_SELECTED]);
  5353. button_binds.write[0] = MENU_LOCK_SELECTED;
  5354. tool_button[TOOL_LOCK_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5355. tool_button[TOOL_LOCK_SELECTED]->set_tooltip(TTR("Lock the selected object in place (can't be moved)."));
  5356. tool_button[TOOL_UNLOCK_SELECTED] = memnew(ToolButton);
  5357. hbc_menu->add_child(tool_button[TOOL_UNLOCK_SELECTED]);
  5358. button_binds.write[0] = MENU_UNLOCK_SELECTED;
  5359. tool_button[TOOL_UNLOCK_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5360. tool_button[TOOL_UNLOCK_SELECTED]->set_tooltip(TTR("Unlock the selected object (can be moved)."));
  5361. tool_button[TOOL_GROUP_SELECTED] = memnew(ToolButton);
  5362. hbc_menu->add_child(tool_button[TOOL_GROUP_SELECTED]);
  5363. button_binds.write[0] = MENU_GROUP_SELECTED;
  5364. tool_button[TOOL_GROUP_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5365. tool_button[TOOL_GROUP_SELECTED]->set_tooltip(TTR("Makes sure the object's children are not selectable."));
  5366. tool_button[TOOL_UNGROUP_SELECTED] = memnew(ToolButton);
  5367. hbc_menu->add_child(tool_button[TOOL_UNGROUP_SELECTED]);
  5368. button_binds.write[0] = MENU_UNGROUP_SELECTED;
  5369. tool_button[TOOL_UNGROUP_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5370. tool_button[TOOL_UNGROUP_SELECTED]->set_tooltip(TTR("Restores the object's children's ability to be selected."));
  5371. hbc_menu->add_child(memnew(VSeparator));
  5372. tool_option_button[TOOL_OPT_LOCAL_COORDS] = memnew(ToolButton);
  5373. hbc_menu->add_child(tool_option_button[TOOL_OPT_LOCAL_COORDS]);
  5374. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_toggle_mode(true);
  5375. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_flat(true);
  5376. button_binds.write[0] = MENU_TOOL_LOCAL_COORDS;
  5377. tool_option_button[TOOL_OPT_LOCAL_COORDS]->connect("toggled", this, "_menu_item_toggled", button_binds);
  5378. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut(ED_SHORTCUT("spatial_editor/local_coords", TTR("Use Local Space"), KEY_T));
  5379. tool_option_button[TOOL_OPT_USE_SNAP] = memnew(ToolButton);
  5380. hbc_menu->add_child(tool_option_button[TOOL_OPT_USE_SNAP]);
  5381. tool_option_button[TOOL_OPT_USE_SNAP]->set_toggle_mode(true);
  5382. tool_option_button[TOOL_OPT_USE_SNAP]->set_flat(true);
  5383. button_binds.write[0] = MENU_TOOL_USE_SNAP;
  5384. tool_option_button[TOOL_OPT_USE_SNAP]->connect("toggled", this, "_menu_item_toggled", button_binds);
  5385. tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut(ED_SHORTCUT("spatial_editor/snap", TTR("Use Snap"), KEY_Y));
  5386. hbc_menu->add_child(memnew(VSeparator));
  5387. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA] = memnew(ToolButton);
  5388. hbc_menu->add_child(tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]);
  5389. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_toggle_mode(true);
  5390. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_flat(true);
  5391. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_disabled(true);
  5392. button_binds.write[0] = MENU_TOOL_OVERRIDE_CAMERA;
  5393. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->connect("toggled", this, "_menu_item_toggled", button_binds);
  5394. _update_camera_override_button(false);
  5395. tool_button[TOOL_CONVERT_ROOMS] = memnew(ToolButton);
  5396. hbc_menu->add_child(tool_button[TOOL_CONVERT_ROOMS]);
  5397. tool_button[TOOL_CONVERT_ROOMS]->set_toggle_mode(false);
  5398. tool_button[TOOL_CONVERT_ROOMS]->set_flat(true);
  5399. button_binds.write[0] = MENU_TOOL_CONVERT_ROOMS;
  5400. tool_button[TOOL_CONVERT_ROOMS]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5401. tool_button[TOOL_CONVERT_ROOMS]->set_shortcut(ED_SHORTCUT("spatial_editor/convert_rooms", TTR("Convert Rooms"), KEY_MASK_ALT | KEY_C));
  5402. tool_button[TOOL_CONVERT_ROOMS]->set_tooltip(TTR("Converts rooms for portal culling."));
  5403. hbc_menu->add_child(memnew(VSeparator));
  5404. // Drag and drop support;
  5405. preview_node = memnew(Spatial);
  5406. preview_bounds = AABB();
  5407. ED_SHORTCUT("spatial_editor/bottom_view", TTR("Bottom View"), KEY_MASK_ALT + KEY_KP_7);
  5408. ED_SHORTCUT("spatial_editor/top_view", TTR("Top View"), KEY_KP_7);
  5409. ED_SHORTCUT("spatial_editor/rear_view", TTR("Rear View"), KEY_MASK_ALT + KEY_KP_1);
  5410. ED_SHORTCUT("spatial_editor/front_view", TTR("Front View"), KEY_KP_1);
  5411. ED_SHORTCUT("spatial_editor/left_view", TTR("Left View"), KEY_MASK_ALT + KEY_KP_3);
  5412. ED_SHORTCUT("spatial_editor/right_view", TTR("Right View"), KEY_KP_3);
  5413. ED_SHORTCUT("spatial_editor/switch_perspective_orthogonal", TTR("Switch Perspective/Orthogonal View"), KEY_KP_5);
  5414. ED_SHORTCUT("spatial_editor/insert_anim_key", TTR("Insert Animation Key"), KEY_K);
  5415. ED_SHORTCUT("spatial_editor/focus_origin", TTR("Focus Origin"), KEY_O);
  5416. ED_SHORTCUT("spatial_editor/focus_selection", TTR("Focus Selection"), KEY_F);
  5417. ED_SHORTCUT("spatial_editor/align_transform_with_view", TTR("Align Transform with View"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_M);
  5418. ED_SHORTCUT("spatial_editor/align_rotation_with_view", TTR("Align Rotation with View"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_F);
  5419. ED_SHORTCUT("spatial_editor/freelook_toggle", TTR("Toggle Freelook"), KEY_MASK_SHIFT + KEY_F);
  5420. PopupMenu *p;
  5421. transform_menu = memnew(MenuButton);
  5422. transform_menu->set_text(TTR("Transform"));
  5423. transform_menu->set_switch_on_hover(true);
  5424. hbc_menu->add_child(transform_menu);
  5425. p = transform_menu->get_popup();
  5426. p->add_shortcut(ED_SHORTCUT("spatial_editor/snap_to_floor", TTR("Snap Object to Floor"), KEY_PAGEDOWN), MENU_SNAP_TO_FLOOR);
  5427. p->add_shortcut(ED_SHORTCUT("spatial_editor/transform_dialog", TTR("Transform Dialog...")), MENU_TRANSFORM_DIALOG);
  5428. p->add_separator();
  5429. p->add_shortcut(ED_SHORTCUT("spatial_editor/configure_snap", TTR("Configure Snap...")), MENU_TRANSFORM_CONFIGURE_SNAP);
  5430. p->connect("id_pressed", this, "_menu_item_pressed");
  5431. view_menu = memnew(MenuButton);
  5432. view_menu->set_text(TTR("View"));
  5433. view_menu->set_switch_on_hover(true);
  5434. hbc_menu->add_child(view_menu);
  5435. hbc_menu->add_child(memnew(VSeparator));
  5436. context_menu_container = memnew(PanelContainer);
  5437. hbc_context_menu = memnew(HBoxContainer);
  5438. context_menu_container->add_child(hbc_context_menu);
  5439. // Use a custom stylebox to make contextual menu items stand out from the rest.
  5440. // This helps with editor usability as contextual menu items change when selecting nodes,
  5441. // even though it may not be immediately obvious at first.
  5442. hbc_menu->add_child(context_menu_container);
  5443. _update_context_menu_stylebox();
  5444. // Get the view menu popup and have it stay open when a checkable item is selected
  5445. p = view_menu->get_popup();
  5446. p->set_hide_on_checkable_item_selection(false);
  5447. accept = memnew(AcceptDialog);
  5448. editor->get_gui_base()->add_child(accept);
  5449. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/1_viewport", TTR("1 Viewport"), KEY_MASK_CMD + KEY_1), MENU_VIEW_USE_1_VIEWPORT);
  5450. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports", TTR("2 Viewports"), KEY_MASK_CMD + KEY_2), MENU_VIEW_USE_2_VIEWPORTS);
  5451. 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);
  5452. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports", TTR("3 Viewports"), KEY_MASK_CMD + KEY_3), MENU_VIEW_USE_3_VIEWPORTS);
  5453. 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);
  5454. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/4_viewports", TTR("4 Viewports"), KEY_MASK_CMD + KEY_4), MENU_VIEW_USE_4_VIEWPORTS);
  5455. p->add_separator();
  5456. p->add_submenu_item(TTR("Gizmos"), "GizmosMenu");
  5457. p->add_separator();
  5458. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_origin", TTR("View Origin")), MENU_VIEW_ORIGIN);
  5459. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_grid", TTR("View Grid"), KEY_MASK_CMD + KEY_G), MENU_VIEW_GRID);
  5460. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_portal_culling", TTR("View Portal Culling"), KEY_MASK_ALT | KEY_P), MENU_VIEW_PORTAL_CULLING);
  5461. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_occlusion_culling", TTR("View Occlusion Culling")), MENU_VIEW_OCCLUSION_CULLING);
  5462. p->add_separator();
  5463. p->add_shortcut(ED_SHORTCUT("spatial_editor/settings", TTR("Settings...")), MENU_VIEW_CAMERA_SETTINGS);
  5464. p->set_item_checked(p->get_item_index(MENU_VIEW_ORIGIN), true);
  5465. p->set_item_checked(p->get_item_index(MENU_VIEW_GRID), true);
  5466. p->set_item_checked(p->get_item_index(MENU_VIEW_OCCLUSION_CULLING), true);
  5467. p->connect("id_pressed", this, "_menu_item_pressed");
  5468. gizmos_menu = memnew(PopupMenu);
  5469. p->add_child(gizmos_menu);
  5470. gizmos_menu->set_name("GizmosMenu");
  5471. gizmos_menu->set_hide_on_checkable_item_selection(false);
  5472. gizmos_menu->connect("id_pressed", this, "_menu_gizmo_toggled");
  5473. /* REST OF MENU */
  5474. palette_split = memnew(HSplitContainer);
  5475. palette_split->set_v_size_flags(SIZE_EXPAND_FILL);
  5476. vbc->add_child(palette_split);
  5477. shader_split = memnew(VSplitContainer);
  5478. shader_split->set_h_size_flags(SIZE_EXPAND_FILL);
  5479. palette_split->add_child(shader_split);
  5480. viewport_base = memnew(SpatialEditorViewportContainer);
  5481. shader_split->add_child(viewport_base);
  5482. viewport_base->set_v_size_flags(SIZE_EXPAND_FILL);
  5483. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  5484. viewports[i] = memnew(SpatialEditorViewport(this, editor, i));
  5485. viewports[i]->connect("toggle_maximize_view", this, "_toggle_maximize_view");
  5486. viewports[i]->connect("clicked", this, "_update_camera_override_viewport");
  5487. viewports[i]->assign_pending_data_pointers(preview_node, &preview_bounds, accept);
  5488. viewport_base->add_child(viewports[i]);
  5489. }
  5490. /* SNAP DIALOG */
  5491. snap_translate_value = 1;
  5492. snap_rotate_value = 15;
  5493. snap_scale_value = 10;
  5494. snap_dialog = memnew(ConfirmationDialog);
  5495. snap_dialog->set_title(TTR("Snap Settings"));
  5496. add_child(snap_dialog);
  5497. snap_dialog->connect("confirmed", this, "_snap_changed");
  5498. snap_dialog->get_cancel()->connect("pressed", this, "_snap_update");
  5499. VBoxContainer *snap_dialog_vbc = memnew(VBoxContainer);
  5500. snap_dialog->add_child(snap_dialog_vbc);
  5501. snap_translate = memnew(LineEdit);
  5502. snap_dialog_vbc->add_margin_child(TTR("Translate Snap:"), snap_translate);
  5503. snap_rotate = memnew(LineEdit);
  5504. snap_dialog_vbc->add_margin_child(TTR("Rotate Snap (deg.):"), snap_rotate);
  5505. snap_scale = memnew(LineEdit);
  5506. snap_dialog_vbc->add_margin_child(TTR("Scale Snap (%):"), snap_scale);
  5507. _snap_update();
  5508. /* SETTINGS DIALOG */
  5509. settings_dialog = memnew(ConfirmationDialog);
  5510. settings_dialog->set_title(TTR("Viewport Settings"));
  5511. add_child(settings_dialog);
  5512. settings_vbc = memnew(VBoxContainer);
  5513. settings_vbc->set_custom_minimum_size(Size2(200, 0) * EDSCALE);
  5514. settings_dialog->add_child(settings_vbc);
  5515. settings_fov = memnew(SpinBox);
  5516. settings_fov->set_max(MAX_FOV);
  5517. settings_fov->set_min(MIN_FOV);
  5518. settings_fov->set_step(0.01);
  5519. settings_fov->set_value(EDITOR_DEF("editors/3d/default_fov", 70.0));
  5520. settings_vbc->add_margin_child(TTR("Perspective FOV (deg.):"), settings_fov);
  5521. settings_znear = memnew(SpinBox);
  5522. settings_znear->set_max(MAX_Z);
  5523. settings_znear->set_min(MIN_Z);
  5524. settings_znear->set_step(0.01);
  5525. settings_znear->set_value(EDITOR_DEF("editors/3d/default_z_near", 0.05));
  5526. settings_vbc->add_margin_child(TTR("View Z-Near:"), settings_znear);
  5527. settings_zfar = memnew(SpinBox);
  5528. settings_zfar->set_max(MAX_Z);
  5529. settings_zfar->set_min(MIN_Z);
  5530. settings_zfar->set_step(0.01);
  5531. settings_zfar->set_value(EDITOR_DEF("editors/3d/default_z_far", 1500));
  5532. settings_vbc->add_margin_child(TTR("View Z-Far:"), settings_zfar);
  5533. for (uint32_t i = 0; i < VIEWPORTS_COUNT; ++i) {
  5534. settings_dialog->connect("confirmed", viewports[i], "_update_camera", varray(0.0));
  5535. }
  5536. /* XFORM DIALOG */
  5537. xform_dialog = memnew(ConfirmationDialog);
  5538. xform_dialog->set_title(TTR("Transform Change"));
  5539. add_child(xform_dialog);
  5540. VBoxContainer *xform_vbc = memnew(VBoxContainer);
  5541. xform_dialog->add_child(xform_vbc);
  5542. Label *l = memnew(Label);
  5543. l->set_text(TTR("Translate:"));
  5544. xform_vbc->add_child(l);
  5545. HBoxContainer *xform_hbc = memnew(HBoxContainer);
  5546. xform_vbc->add_child(xform_hbc);
  5547. for (int i = 0; i < 3; i++) {
  5548. xform_translate[i] = memnew(LineEdit);
  5549. xform_translate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  5550. xform_hbc->add_child(xform_translate[i]);
  5551. }
  5552. l = memnew(Label);
  5553. l->set_text(TTR("Rotate (deg.):"));
  5554. xform_vbc->add_child(l);
  5555. xform_hbc = memnew(HBoxContainer);
  5556. xform_vbc->add_child(xform_hbc);
  5557. for (int i = 0; i < 3; i++) {
  5558. xform_rotate[i] = memnew(LineEdit);
  5559. xform_rotate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  5560. xform_hbc->add_child(xform_rotate[i]);
  5561. }
  5562. l = memnew(Label);
  5563. l->set_text(TTR("Scale (ratio):"));
  5564. xform_vbc->add_child(l);
  5565. xform_hbc = memnew(HBoxContainer);
  5566. xform_vbc->add_child(xform_hbc);
  5567. for (int i = 0; i < 3; i++) {
  5568. xform_scale[i] = memnew(LineEdit);
  5569. xform_scale[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  5570. xform_hbc->add_child(xform_scale[i]);
  5571. }
  5572. l = memnew(Label);
  5573. l->set_text(TTR("Transform Type"));
  5574. xform_vbc->add_child(l);
  5575. xform_type = memnew(OptionButton);
  5576. xform_type->set_h_size_flags(SIZE_EXPAND_FILL);
  5577. xform_type->add_item(TTR("Pre"));
  5578. xform_type->add_item(TTR("Post"));
  5579. xform_vbc->add_child(xform_type);
  5580. xform_dialog->connect("confirmed", this, "_xform_dialog_action");
  5581. scenario_debug = VisualServer::SCENARIO_DEBUG_DISABLED;
  5582. selected = nullptr;
  5583. set_process_unhandled_key_input(true);
  5584. add_to_group("_spatial_editor_group");
  5585. EDITOR_DEF("editors/3d/manipulator_gizmo_size", 80);
  5586. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "editors/3d/manipulator_gizmo_size", PROPERTY_HINT_RANGE, "16,160,1"));
  5587. EDITOR_DEF("editors/3d/manipulator_gizmo_opacity", 0.9);
  5588. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::REAL, "editors/3d/manipulator_gizmo_opacity", PROPERTY_HINT_RANGE, "0,1,0.01"));
  5589. EDITOR_DEF("editors/3d/navigation/show_viewport_rotation_gizmo", true);
  5590. over_gizmo_handle = -1;
  5591. // make sure the portal tools are off by default
  5592. // (when no RoomManager is present)
  5593. update_portal_tools();
  5594. }
  5595. SpatialEditor::~SpatialEditor() {
  5596. memdelete(preview_node);
  5597. }
  5598. void SpatialEditorPlugin::make_visible(bool p_visible) {
  5599. if (p_visible) {
  5600. spatial_editor->show();
  5601. spatial_editor->set_process(true);
  5602. } else {
  5603. spatial_editor->hide();
  5604. spatial_editor->set_process(false);
  5605. }
  5606. }
  5607. void SpatialEditorPlugin::edit(Object *p_object) {
  5608. spatial_editor->edit(Object::cast_to<Spatial>(p_object));
  5609. }
  5610. bool SpatialEditorPlugin::handles(Object *p_object) const {
  5611. return p_object->is_class("Spatial");
  5612. }
  5613. Dictionary SpatialEditorPlugin::get_state() const {
  5614. return spatial_editor->get_state();
  5615. }
  5616. void SpatialEditorPlugin::set_state(const Dictionary &p_state) {
  5617. spatial_editor->set_state(p_state);
  5618. }
  5619. void SpatialEditor::snap_cursor_to_plane(const Plane &p_plane) {
  5620. //cursor.pos=p_plane.project(cursor.pos);
  5621. }
  5622. Vector3 SpatialEditor::snap_point(Vector3 p_target, Vector3 p_start) const {
  5623. if (is_snap_enabled()) {
  5624. p_target.x = Math::snap_scalar(0.0, get_translate_snap(), p_target.x);
  5625. p_target.y = Math::snap_scalar(0.0, get_translate_snap(), p_target.y);
  5626. p_target.z = Math::snap_scalar(0.0, get_translate_snap(), p_target.z);
  5627. }
  5628. return p_target;
  5629. }
  5630. float SpatialEditor::get_translate_snap() const {
  5631. float snap_value;
  5632. if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
  5633. snap_value = snap_translate->get_text().to_double() / 10.0;
  5634. } else {
  5635. snap_value = snap_translate->get_text().to_double();
  5636. }
  5637. return snap_value;
  5638. }
  5639. float SpatialEditor::get_rotate_snap() const {
  5640. float snap_value;
  5641. if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
  5642. snap_value = snap_rotate->get_text().to_double() / 3.0;
  5643. } else {
  5644. snap_value = snap_rotate->get_text().to_double();
  5645. }
  5646. return snap_value;
  5647. }
  5648. float SpatialEditor::get_scale_snap() const {
  5649. float snap_value;
  5650. if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
  5651. snap_value = snap_scale->get_text().to_double() / 2.0;
  5652. } else {
  5653. snap_value = snap_scale->get_text().to_double();
  5654. }
  5655. return snap_value;
  5656. }
  5657. void SpatialEditorPlugin::_bind_methods() {
  5658. ClassDB::bind_method("snap_cursor_to_plane", &SpatialEditorPlugin::snap_cursor_to_plane);
  5659. }
  5660. void SpatialEditorPlugin::snap_cursor_to_plane(const Plane &p_plane) {
  5661. spatial_editor->snap_cursor_to_plane(p_plane);
  5662. }
  5663. struct _GizmoPluginPriorityComparator {
  5664. bool operator()(const Ref<EditorSpatialGizmoPlugin> &p_a, const Ref<EditorSpatialGizmoPlugin> &p_b) const {
  5665. if (p_a->get_priority() == p_b->get_priority()) {
  5666. return p_a->get_name() < p_b->get_name();
  5667. }
  5668. return p_a->get_priority() > p_b->get_priority();
  5669. }
  5670. };
  5671. struct _GizmoPluginNameComparator {
  5672. bool operator()(const Ref<EditorSpatialGizmoPlugin> &p_a, const Ref<EditorSpatialGizmoPlugin> &p_b) const {
  5673. return p_a->get_name() < p_b->get_name();
  5674. }
  5675. };
  5676. void SpatialEditor::add_gizmo_plugin(Ref<EditorSpatialGizmoPlugin> p_plugin) {
  5677. ERR_FAIL_NULL(p_plugin.ptr());
  5678. gizmo_plugins_by_priority.push_back(p_plugin);
  5679. gizmo_plugins_by_priority.sort_custom<_GizmoPluginPriorityComparator>();
  5680. gizmo_plugins_by_name.push_back(p_plugin);
  5681. gizmo_plugins_by_name.sort_custom<_GizmoPluginNameComparator>();
  5682. _update_gizmos_menu();
  5683. SpatialEditor::get_singleton()->update_all_gizmos();
  5684. }
  5685. void SpatialEditor::remove_gizmo_plugin(Ref<EditorSpatialGizmoPlugin> p_plugin) {
  5686. gizmo_plugins_by_priority.erase(p_plugin);
  5687. gizmo_plugins_by_name.erase(p_plugin);
  5688. _update_gizmos_menu();
  5689. }
  5690. SpatialEditorPlugin::SpatialEditorPlugin(EditorNode *p_node) {
  5691. editor = p_node;
  5692. spatial_editor = memnew(SpatialEditor(p_node));
  5693. spatial_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  5694. editor->get_viewport()->add_child(spatial_editor);
  5695. spatial_editor->hide();
  5696. spatial_editor->connect("transform_key_request", editor->get_inspector_dock(), "_transform_keyed");
  5697. }
  5698. SpatialEditorPlugin::~SpatialEditorPlugin() {
  5699. }
  5700. void EditorSpatialGizmoPlugin::create_material(const String &p_name, const Color &p_color, bool p_billboard, bool p_on_top, bool p_use_vertex_color) {
  5701. Color instanced_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/instanced", Color(0.7, 0.7, 0.7, 0.6));
  5702. Vector<Ref<SpatialMaterial>> mats;
  5703. for (int i = 0; i < 4; i++) {
  5704. bool selected = i % 2 == 1;
  5705. bool instanced = i < 2;
  5706. Ref<SpatialMaterial> material = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  5707. Color color = instanced ? instanced_color : p_color;
  5708. if (!selected) {
  5709. color.a *= 0.3;
  5710. }
  5711. material->set_albedo(color);
  5712. material->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  5713. material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  5714. material->set_render_priority(SpatialMaterial::RENDER_PRIORITY_MIN + 1);
  5715. if (p_use_vertex_color) {
  5716. material->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  5717. material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  5718. }
  5719. if (p_billboard) {
  5720. material->set_billboard_mode(SpatialMaterial::BILLBOARD_ENABLED);
  5721. }
  5722. if (p_on_top && selected) {
  5723. material->set_on_top_of_alpha();
  5724. }
  5725. mats.push_back(material);
  5726. }
  5727. materials[p_name] = mats;
  5728. }
  5729. void EditorSpatialGizmoPlugin::create_icon_material(const String &p_name, const Ref<Texture> &p_texture, bool p_on_top, const Color &p_albedo) {
  5730. Color instanced_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/instanced", Color(0.7, 0.7, 0.7, 0.6));
  5731. Vector<Ref<SpatialMaterial>> icons;
  5732. for (int i = 0; i < 4; i++) {
  5733. bool selected = i % 2 == 1;
  5734. bool instanced = i < 2;
  5735. Ref<SpatialMaterial> icon = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  5736. Color color = instanced ? instanced_color : p_albedo;
  5737. if (!selected) {
  5738. color.a *= 0.85;
  5739. }
  5740. icon->set_albedo(color);
  5741. icon->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  5742. icon->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  5743. icon->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  5744. icon->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  5745. icon->set_depth_draw_mode(SpatialMaterial::DEPTH_DRAW_DISABLED);
  5746. icon->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  5747. icon->set_texture(SpatialMaterial::TEXTURE_ALBEDO, p_texture);
  5748. icon->set_flag(SpatialMaterial::FLAG_FIXED_SIZE, true);
  5749. icon->set_billboard_mode(SpatialMaterial::BILLBOARD_ENABLED);
  5750. icon->set_render_priority(SpatialMaterial::RENDER_PRIORITY_MIN);
  5751. if (p_on_top && selected) {
  5752. icon->set_on_top_of_alpha();
  5753. }
  5754. icons.push_back(icon);
  5755. }
  5756. materials[p_name] = icons;
  5757. }
  5758. void EditorSpatialGizmoPlugin::create_handle_material(const String &p_name, bool p_billboard, const Ref<Texture> &p_icon) {
  5759. Ref<SpatialMaterial> handle_material = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  5760. handle_material->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  5761. handle_material->set_flag(SpatialMaterial::FLAG_USE_POINT_SIZE, true);
  5762. Ref<Texture> handle_t = p_icon != nullptr ? p_icon : SpatialEditor::get_singleton()->get_icon("Editor3DHandle", "EditorIcons");
  5763. handle_material->set_point_size(handle_t->get_width());
  5764. handle_material->set_texture(SpatialMaterial::TEXTURE_ALBEDO, handle_t);
  5765. handle_material->set_albedo(Color(1, 1, 1));
  5766. handle_material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  5767. handle_material->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  5768. handle_material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  5769. handle_material->set_on_top_of_alpha();
  5770. if (p_billboard) {
  5771. handle_material->set_billboard_mode(SpatialMaterial::BILLBOARD_ENABLED);
  5772. handle_material->set_on_top_of_alpha();
  5773. }
  5774. materials[p_name] = Vector<Ref<SpatialMaterial>>();
  5775. materials[p_name].push_back(handle_material);
  5776. }
  5777. void EditorSpatialGizmoPlugin::add_material(const String &p_name, Ref<SpatialMaterial> p_material) {
  5778. materials[p_name] = Vector<Ref<SpatialMaterial>>();
  5779. materials[p_name].push_back(p_material);
  5780. }
  5781. Ref<SpatialMaterial> EditorSpatialGizmoPlugin::get_material(const String &p_name, const Ref<EditorSpatialGizmo> &p_gizmo) {
  5782. ERR_FAIL_COND_V(!materials.has(p_name), Ref<SpatialMaterial>());
  5783. ERR_FAIL_COND_V(materials[p_name].size() == 0, Ref<SpatialMaterial>());
  5784. if (p_gizmo.is_null() || materials[p_name].size() == 1) {
  5785. return materials[p_name][0];
  5786. }
  5787. int index = (p_gizmo->is_selected() ? 1 : 0) + (p_gizmo->is_editable() ? 2 : 0);
  5788. Ref<SpatialMaterial> mat = materials[p_name][index];
  5789. if (current_state == ON_TOP && p_gizmo->is_selected()) {
  5790. mat->set_flag(SpatialMaterial::FLAG_DISABLE_DEPTH_TEST, true);
  5791. } else {
  5792. mat->set_flag(SpatialMaterial::FLAG_DISABLE_DEPTH_TEST, false);
  5793. }
  5794. return mat;
  5795. }
  5796. String EditorSpatialGizmoPlugin::get_name() const {
  5797. if (get_script_instance() && get_script_instance()->has_method("get_name")) {
  5798. return get_script_instance()->call("get_name");
  5799. }
  5800. WARN_PRINT_ONCE("A 3D editor gizmo has no name defined (it will appear as \"Unnamed Gizmo\" in the \"View > Gizmos\" menu). To resolve this, override the `get_name()` function to return a String in the script that extends EditorSpatialGizmoPlugin.");
  5801. return TTR("Unnamed Gizmo");
  5802. }
  5803. int EditorSpatialGizmoPlugin::get_priority() const {
  5804. if (get_script_instance() && get_script_instance()->has_method("get_priority")) {
  5805. return get_script_instance()->call("get_priority");
  5806. }
  5807. return 0;
  5808. }
  5809. Ref<EditorSpatialGizmo> EditorSpatialGizmoPlugin::get_gizmo(Spatial *p_spatial) {
  5810. if (get_script_instance() && get_script_instance()->has_method("get_gizmo")) {
  5811. return get_script_instance()->call("get_gizmo", p_spatial);
  5812. }
  5813. Ref<EditorSpatialGizmo> ref = create_gizmo(p_spatial);
  5814. if (ref.is_null()) {
  5815. return ref;
  5816. }
  5817. ref->set_plugin(this);
  5818. ref->set_spatial_node(p_spatial);
  5819. ref->set_hidden(current_state == HIDDEN);
  5820. current_gizmos.push_back(ref.ptr());
  5821. return ref;
  5822. }
  5823. void EditorSpatialGizmoPlugin::_bind_methods() {
  5824. #define GIZMO_REF PropertyInfo(Variant::OBJECT, "gizmo", PROPERTY_HINT_RESOURCE_TYPE, "EditorSpatialGizmo")
  5825. BIND_VMETHOD(MethodInfo(Variant::BOOL, "has_gizmo", PropertyInfo(Variant::OBJECT, "spatial", PROPERTY_HINT_RESOURCE_TYPE, "Spatial")));
  5826. BIND_VMETHOD(MethodInfo(GIZMO_REF, "create_gizmo", PropertyInfo(Variant::OBJECT, "spatial", PROPERTY_HINT_RESOURCE_TYPE, "Spatial")));
  5827. ClassDB::bind_method(D_METHOD("create_material", "name", "color", "billboard", "on_top", "use_vertex_color"), &EditorSpatialGizmoPlugin::create_material, DEFVAL(false), DEFVAL(false), DEFVAL(false));
  5828. 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)));
  5829. ClassDB::bind_method(D_METHOD("create_handle_material", "name", "billboard", "texture"), &EditorSpatialGizmoPlugin::create_handle_material, DEFVAL(false), DEFVAL(Variant()));
  5830. ClassDB::bind_method(D_METHOD("add_material", "name", "material"), &EditorSpatialGizmoPlugin::add_material);
  5831. ClassDB::bind_method(D_METHOD("get_material", "name", "gizmo"), &EditorSpatialGizmoPlugin::get_material, DEFVAL(Ref<EditorSpatialGizmo>()));
  5832. BIND_VMETHOD(MethodInfo(Variant::STRING, "get_name"));
  5833. BIND_VMETHOD(MethodInfo(Variant::INT, "get_priority"));
  5834. BIND_VMETHOD(MethodInfo(Variant::BOOL, "can_be_hidden"));
  5835. BIND_VMETHOD(MethodInfo(Variant::BOOL, "is_selectable_when_hidden"));
  5836. BIND_VMETHOD(MethodInfo("redraw", GIZMO_REF));
  5837. BIND_VMETHOD(MethodInfo(Variant::STRING, "get_handle_name", GIZMO_REF, PropertyInfo(Variant::INT, "index")));
  5838. MethodInfo hvget(Variant::NIL, "get_handle_value", GIZMO_REF, PropertyInfo(Variant::INT, "index"));
  5839. hvget.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  5840. BIND_VMETHOD(hvget);
  5841. BIND_VMETHOD(MethodInfo("set_handle", GIZMO_REF, PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::OBJECT, "camera", PROPERTY_HINT_RESOURCE_TYPE, "Camera"), PropertyInfo(Variant::VECTOR2, "point")));
  5842. MethodInfo cm = MethodInfo("commit_handle", GIZMO_REF, PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::NIL, "restore"), PropertyInfo(Variant::BOOL, "cancel"));
  5843. cm.default_arguments.push_back(false);
  5844. BIND_VMETHOD(cm);
  5845. BIND_VMETHOD(MethodInfo(Variant::BOOL, "is_handle_highlighted", GIZMO_REF, PropertyInfo(Variant::INT, "index")));
  5846. #undef GIZMO_REF
  5847. }
  5848. bool EditorSpatialGizmoPlugin::has_gizmo(Spatial *p_spatial) {
  5849. if (get_script_instance() && get_script_instance()->has_method("has_gizmo")) {
  5850. return get_script_instance()->call("has_gizmo", p_spatial);
  5851. }
  5852. return false;
  5853. }
  5854. Ref<EditorSpatialGizmo> EditorSpatialGizmoPlugin::create_gizmo(Spatial *p_spatial) {
  5855. if (get_script_instance() && get_script_instance()->has_method("create_gizmo")) {
  5856. return get_script_instance()->call("create_gizmo", p_spatial);
  5857. }
  5858. Ref<EditorSpatialGizmo> ref;
  5859. if (has_gizmo(p_spatial)) {
  5860. ref.instance();
  5861. }
  5862. return ref;
  5863. }
  5864. bool EditorSpatialGizmoPlugin::can_be_hidden() const {
  5865. if (get_script_instance() && get_script_instance()->has_method("can_be_hidden")) {
  5866. return get_script_instance()->call("can_be_hidden");
  5867. }
  5868. return true;
  5869. }
  5870. bool EditorSpatialGizmoPlugin::is_selectable_when_hidden() const {
  5871. if (get_script_instance() && get_script_instance()->has_method("is_selectable_when_hidden")) {
  5872. return get_script_instance()->call("is_selectable_when_hidden");
  5873. }
  5874. return false;
  5875. }
  5876. void EditorSpatialGizmoPlugin::redraw(EditorSpatialGizmo *p_gizmo) {
  5877. if (get_script_instance() && get_script_instance()->has_method("redraw")) {
  5878. Ref<EditorSpatialGizmo> ref(p_gizmo);
  5879. get_script_instance()->call("redraw", ref);
  5880. }
  5881. }
  5882. String EditorSpatialGizmoPlugin::get_handle_name(const EditorSpatialGizmo *p_gizmo, int p_idx) const {
  5883. if (get_script_instance() && get_script_instance()->has_method("get_handle_name")) {
  5884. return get_script_instance()->call("get_handle_name", p_gizmo, p_idx);
  5885. }
  5886. return "";
  5887. }
  5888. Variant EditorSpatialGizmoPlugin::get_handle_value(EditorSpatialGizmo *p_gizmo, int p_idx) const {
  5889. if (get_script_instance() && get_script_instance()->has_method("get_handle_value")) {
  5890. return get_script_instance()->call("get_handle_value", p_gizmo, p_idx);
  5891. }
  5892. return Variant();
  5893. }
  5894. void EditorSpatialGizmoPlugin::set_handle(EditorSpatialGizmo *p_gizmo, int p_idx, Camera *p_camera, const Point2 &p_point) {
  5895. if (get_script_instance() && get_script_instance()->has_method("set_handle")) {
  5896. get_script_instance()->call("set_handle", p_gizmo, p_idx, p_camera, p_point);
  5897. }
  5898. }
  5899. void EditorSpatialGizmoPlugin::commit_handle(EditorSpatialGizmo *p_gizmo, int p_idx, const Variant &p_restore, bool p_cancel) {
  5900. if (get_script_instance() && get_script_instance()->has_method("commit_handle")) {
  5901. get_script_instance()->call("commit_handle", p_gizmo, p_idx, p_restore, p_cancel);
  5902. }
  5903. }
  5904. bool EditorSpatialGizmoPlugin::is_handle_highlighted(const EditorSpatialGizmo *p_gizmo, int p_idx) const {
  5905. if (get_script_instance() && get_script_instance()->has_method("is_handle_highlighted")) {
  5906. return get_script_instance()->call("is_handle_highlighted", p_gizmo, p_idx);
  5907. }
  5908. return false;
  5909. }
  5910. void EditorSpatialGizmoPlugin::set_state(int p_state) {
  5911. current_state = p_state;
  5912. for (int i = 0; i < current_gizmos.size(); ++i) {
  5913. current_gizmos[i]->set_hidden(current_state == HIDDEN);
  5914. }
  5915. }
  5916. int EditorSpatialGizmoPlugin::get_state() const {
  5917. return current_state;
  5918. }
  5919. void EditorSpatialGizmoPlugin::unregister_gizmo(EditorSpatialGizmo *p_gizmo) {
  5920. current_gizmos.erase(p_gizmo);
  5921. }
  5922. EditorSpatialGizmoPlugin::EditorSpatialGizmoPlugin() {
  5923. current_state = VISIBLE;
  5924. }
  5925. EditorSpatialGizmoPlugin::~EditorSpatialGizmoPlugin() {
  5926. for (int i = 0; i < current_gizmos.size(); ++i) {
  5927. current_gizmos[i]->set_plugin(nullptr);
  5928. current_gizmos[i]->get_spatial_node()->set_gizmo(nullptr);
  5929. }
  5930. if (SpatialEditor::get_singleton()) {
  5931. SpatialEditor::get_singleton()->update_all_gizmos();
  5932. }
  5933. }