spatial_editor_plugin.cpp 282 KB

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