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