spatial_editor_plugin.cpp 245 KB

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