node_3d_editor_plugin.cpp 340 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182
  1. /**************************************************************************/
  2. /* node_3d_editor_plugin.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "node_3d_editor_plugin.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/input/input.h"
  33. #include "core/input/input_map.h"
  34. #include "core/math/math_funcs.h"
  35. #include "core/math/projection.h"
  36. #include "core/os/keyboard.h"
  37. #include "editor/debugger/editor_debugger_node.h"
  38. #include "editor/editor_node.h"
  39. #include "editor/editor_settings.h"
  40. #include "editor/editor_string_names.h"
  41. #include "editor/editor_undo_redo_manager.h"
  42. #include "editor/gui/editor_run_bar.h"
  43. #include "editor/gui/editor_spin_slider.h"
  44. #include "editor/plugins/animation_player_editor_plugin.h"
  45. #include "editor/plugins/gizmos/audio_listener_3d_gizmo_plugin.h"
  46. #include "editor/plugins/gizmos/audio_stream_player_3d_gizmo_plugin.h"
  47. #include "editor/plugins/gizmos/camera_3d_gizmo_plugin.h"
  48. #include "editor/plugins/gizmos/collision_object_3d_gizmo_plugin.h"
  49. #include "editor/plugins/gizmos/collision_polygon_3d_gizmo_plugin.h"
  50. #include "editor/plugins/gizmos/collision_shape_3d_gizmo_plugin.h"
  51. #include "editor/plugins/gizmos/cpu_particles_3d_gizmo_plugin.h"
  52. #include "editor/plugins/gizmos/decal_gizmo_plugin.h"
  53. #include "editor/plugins/gizmos/fog_volume_gizmo_plugin.h"
  54. #include "editor/plugins/gizmos/geometry_instance_3d_gizmo_plugin.h"
  55. #include "editor/plugins/gizmos/gpu_particles_3d_gizmo_plugin.h"
  56. #include "editor/plugins/gizmos/gpu_particles_collision_3d_gizmo_plugin.h"
  57. #include "editor/plugins/gizmos/joint_3d_gizmo_plugin.h"
  58. #include "editor/plugins/gizmos/label_3d_gizmo_plugin.h"
  59. #include "editor/plugins/gizmos/light_3d_gizmo_plugin.h"
  60. #include "editor/plugins/gizmos/lightmap_gi_gizmo_plugin.h"
  61. #include "editor/plugins/gizmos/lightmap_probe_gizmo_plugin.h"
  62. #include "editor/plugins/gizmos/marker_3d_gizmo_plugin.h"
  63. #include "editor/plugins/gizmos/mesh_instance_3d_gizmo_plugin.h"
  64. #include "editor/plugins/gizmos/navigation_link_3d_gizmo_plugin.h"
  65. #include "editor/plugins/gizmos/navigation_region_3d_gizmo_plugin.h"
  66. #include "editor/plugins/gizmos/occluder_instance_3d_gizmo_plugin.h"
  67. #include "editor/plugins/gizmos/physics_bone_3d_gizmo_plugin.h"
  68. #include "editor/plugins/gizmos/ray_cast_3d_gizmo_plugin.h"
  69. #include "editor/plugins/gizmos/reflection_probe_gizmo_plugin.h"
  70. #include "editor/plugins/gizmos/shape_cast_3d_gizmo_plugin.h"
  71. #include "editor/plugins/gizmos/soft_body_3d_gizmo_plugin.h"
  72. #include "editor/plugins/gizmos/spring_arm_3d_gizmo_plugin.h"
  73. #include "editor/plugins/gizmos/sprite_base_3d_gizmo_plugin.h"
  74. #include "editor/plugins/gizmos/vehicle_body_3d_gizmo_plugin.h"
  75. #include "editor/plugins/gizmos/visible_on_screen_notifier_3d_gizmo_plugin.h"
  76. #include "editor/plugins/gizmos/voxel_gi_gizmo_plugin.h"
  77. #include "editor/plugins/node_3d_editor_gizmos.h"
  78. #include "editor/scene_tree_dock.h"
  79. #include "scene/3d/audio_stream_player_3d.h"
  80. #include "scene/3d/camera_3d.h"
  81. #include "scene/3d/decal.h"
  82. #include "scene/3d/light_3d.h"
  83. #include "scene/3d/mesh_instance_3d.h"
  84. #include "scene/3d/physics/collision_shape_3d.h"
  85. #include "scene/3d/physics/physics_body_3d.h"
  86. #include "scene/3d/sprite_3d.h"
  87. #include "scene/3d/visual_instance_3d.h"
  88. #include "scene/3d/world_environment.h"
  89. #include "scene/gui/center_container.h"
  90. #include "scene/gui/color_picker.h"
  91. #include "scene/gui/flow_container.h"
  92. #include "scene/gui/split_container.h"
  93. #include "scene/gui/subviewport_container.h"
  94. #include "scene/resources/3d/sky_material.h"
  95. #include "scene/resources/packed_scene.h"
  96. #include "scene/resources/surface_tool.h"
  97. constexpr real_t DISTANCE_DEFAULT = 4;
  98. constexpr real_t GIZMO_ARROW_SIZE = 0.35;
  99. constexpr real_t GIZMO_RING_HALF_WIDTH = 0.1;
  100. constexpr real_t GIZMO_PLANE_SIZE = 0.2;
  101. constexpr real_t GIZMO_PLANE_DST = 0.3;
  102. constexpr real_t GIZMO_CIRCLE_SIZE = 1.1;
  103. constexpr real_t GIZMO_SCALE_OFFSET = GIZMO_CIRCLE_SIZE + 0.3;
  104. constexpr real_t GIZMO_ARROW_OFFSET = GIZMO_CIRCLE_SIZE + 0.3;
  105. constexpr real_t ZOOM_FREELOOK_MIN = 0.01;
  106. constexpr real_t ZOOM_FREELOOK_MULTIPLIER = 1.08;
  107. constexpr real_t ZOOM_FREELOOK_INDICATOR_DELAY_S = 1.5;
  108. #ifdef REAL_T_IS_DOUBLE
  109. constexpr double ZOOM_FREELOOK_MAX = 1'000'000'000'000;
  110. #else
  111. constexpr float ZOOM_FREELOOK_MAX = 10'000;
  112. #endif
  113. constexpr real_t MIN_Z = 0.01;
  114. constexpr real_t MAX_Z = 1000000.0;
  115. constexpr real_t MIN_FOV = 0.01;
  116. constexpr real_t MAX_FOV = 179;
  117. void ViewportNavigationControl::_notification(int p_what) {
  118. switch (p_what) {
  119. case NOTIFICATION_ENTER_TREE: {
  120. if (!is_connected(SceneStringName(mouse_exited), callable_mp(this, &ViewportNavigationControl::_on_mouse_exited))) {
  121. connect(SceneStringName(mouse_exited), callable_mp(this, &ViewportNavigationControl::_on_mouse_exited));
  122. }
  123. if (!is_connected(SceneStringName(mouse_entered), callable_mp(this, &ViewportNavigationControl::_on_mouse_entered))) {
  124. connect(SceneStringName(mouse_entered), callable_mp(this, &ViewportNavigationControl::_on_mouse_entered));
  125. }
  126. } break;
  127. case NOTIFICATION_DRAW: {
  128. if (viewport != nullptr) {
  129. _draw();
  130. _update_navigation();
  131. }
  132. } break;
  133. }
  134. }
  135. void ViewportNavigationControl::_draw() {
  136. if (nav_mode == Node3DEditorViewport::NAVIGATION_NONE) {
  137. return;
  138. }
  139. Vector2 center = get_size() / 2.0;
  140. float radius = get_size().x / 2.0;
  141. const bool focused = focused_index != -1;
  142. draw_circle(center, radius, Color(0.5, 0.5, 0.5, focused || hovered ? 0.35 : 0.15));
  143. const Color c = focused ? Color(0.9, 0.9, 0.9, 0.9) : Color(0.5, 0.5, 0.5, 0.25);
  144. Vector2 circle_pos = focused ? center.move_toward(focused_pos, radius) : center;
  145. draw_circle(circle_pos, AXIS_CIRCLE_RADIUS, c);
  146. draw_circle(circle_pos, AXIS_CIRCLE_RADIUS * 0.8, c.darkened(0.4));
  147. }
  148. void ViewportNavigationControl::_process_click(int p_index, Vector2 p_position, bool p_pressed) {
  149. hovered = false;
  150. queue_redraw();
  151. if (focused_index != -1 && focused_index != p_index) {
  152. return;
  153. }
  154. if (p_pressed) {
  155. if (p_position.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
  156. focused_pos = p_position;
  157. focused_index = p_index;
  158. queue_redraw();
  159. }
  160. } else {
  161. focused_index = -1;
  162. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
  163. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  164. Input::get_singleton()->warp_mouse(focused_mouse_start);
  165. }
  166. }
  167. }
  168. void ViewportNavigationControl::_process_drag(int p_index, Vector2 p_position, Vector2 p_relative_position) {
  169. if (focused_index == p_index) {
  170. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_VISIBLE) {
  171. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
  172. focused_mouse_start = p_position;
  173. }
  174. focused_pos += p_relative_position;
  175. queue_redraw();
  176. }
  177. }
  178. void ViewportNavigationControl::gui_input(const Ref<InputEvent> &p_event) {
  179. // Mouse events
  180. const Ref<InputEventMouseButton> mouse_button = p_event;
  181. if (mouse_button.is_valid() && mouse_button->get_button_index() == MouseButton::LEFT) {
  182. _process_click(100, mouse_button->get_position(), mouse_button->is_pressed());
  183. }
  184. const Ref<InputEventMouseMotion> mouse_motion = p_event;
  185. if (mouse_motion.is_valid()) {
  186. _process_drag(100, mouse_motion->get_global_position(), viewport->_get_warped_mouse_motion(mouse_motion));
  187. }
  188. // Touch events
  189. const Ref<InputEventScreenTouch> screen_touch = p_event;
  190. if (screen_touch.is_valid()) {
  191. _process_click(screen_touch->get_index(), screen_touch->get_position(), screen_touch->is_pressed());
  192. }
  193. const Ref<InputEventScreenDrag> screen_drag = p_event;
  194. if (screen_drag.is_valid()) {
  195. _process_drag(screen_drag->get_index(), screen_drag->get_position(), screen_drag->get_relative());
  196. }
  197. }
  198. void ViewportNavigationControl::_update_navigation() {
  199. if (focused_index == -1) {
  200. return;
  201. }
  202. Vector2 delta = focused_pos - (get_size() / 2.0);
  203. Vector2 delta_normalized = delta.normalized();
  204. switch (nav_mode) {
  205. case Node3DEditorViewport::NavigationMode::NAVIGATION_MOVE: {
  206. real_t speed_multiplier = MIN(delta.length() / (get_size().x * 100.0), 3.0);
  207. real_t speed = viewport->freelook_speed * speed_multiplier;
  208. const Node3DEditorViewport::FreelookNavigationScheme navigation_scheme = (Node3DEditorViewport::FreelookNavigationScheme)EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_navigation_scheme").operator int();
  209. Vector3 forward;
  210. if (navigation_scheme == Node3DEditorViewport::FreelookNavigationScheme::FREELOOK_FULLY_AXIS_LOCKED) {
  211. // Forward/backward keys will always go straight forward/backward, never moving on the Y axis.
  212. forward = Vector3(0, 0, delta_normalized.y).rotated(Vector3(0, 1, 0), viewport->camera->get_rotation().y);
  213. } else {
  214. // Forward/backward keys will be relative to the camera pitch.
  215. forward = viewport->camera->get_transform().basis.xform(Vector3(0, 0, delta_normalized.y));
  216. }
  217. const Vector3 right = viewport->camera->get_transform().basis.xform(Vector3(delta_normalized.x, 0, 0));
  218. const Vector3 direction = forward + right;
  219. const Vector3 motion = direction * speed;
  220. viewport->cursor.pos += motion;
  221. viewport->cursor.eye_pos += motion;
  222. } break;
  223. case Node3DEditorViewport::NavigationMode::NAVIGATION_LOOK: {
  224. real_t speed_multiplier = MIN(delta.length() / (get_size().x * 2.5), 3.0);
  225. real_t speed = viewport->freelook_speed * speed_multiplier;
  226. viewport->_nav_look(nullptr, delta_normalized * speed);
  227. } break;
  228. case Node3DEditorViewport::NAVIGATION_PAN: {
  229. real_t speed_multiplier = MIN(delta.length() / (get_size().x), 3.0);
  230. real_t speed = viewport->freelook_speed * speed_multiplier;
  231. viewport->_nav_pan(nullptr, -delta_normalized * speed);
  232. } break;
  233. case Node3DEditorViewport::NAVIGATION_ZOOM: {
  234. real_t speed_multiplier = MIN(delta.length() / (get_size().x), 3.0);
  235. real_t speed = viewport->freelook_speed * speed_multiplier;
  236. viewport->_nav_zoom(nullptr, delta_normalized * speed);
  237. } break;
  238. case Node3DEditorViewport::NAVIGATION_ORBIT: {
  239. real_t speed_multiplier = MIN(delta.length() / (get_size().x), 3.0);
  240. real_t speed = viewport->freelook_speed * speed_multiplier;
  241. viewport->_nav_orbit(nullptr, delta_normalized * speed);
  242. } break;
  243. case Node3DEditorViewport::NAVIGATION_NONE: {
  244. } break;
  245. }
  246. }
  247. void ViewportNavigationControl::_on_mouse_entered() {
  248. hovered = true;
  249. queue_redraw();
  250. }
  251. void ViewportNavigationControl::_on_mouse_exited() {
  252. hovered = false;
  253. queue_redraw();
  254. }
  255. void ViewportNavigationControl::set_navigation_mode(Node3DEditorViewport::NavigationMode p_nav_mode) {
  256. nav_mode = p_nav_mode;
  257. }
  258. void ViewportNavigationControl::set_viewport(Node3DEditorViewport *p_viewport) {
  259. viewport = p_viewport;
  260. }
  261. void ViewportRotationControl::_notification(int p_what) {
  262. switch (p_what) {
  263. case NOTIFICATION_ENTER_TREE: {
  264. axis_menu_options.clear();
  265. axis_menu_options.push_back(Node3DEditorViewport::VIEW_RIGHT);
  266. axis_menu_options.push_back(Node3DEditorViewport::VIEW_TOP);
  267. axis_menu_options.push_back(Node3DEditorViewport::VIEW_FRONT);
  268. axis_menu_options.push_back(Node3DEditorViewport::VIEW_LEFT);
  269. axis_menu_options.push_back(Node3DEditorViewport::VIEW_BOTTOM);
  270. axis_menu_options.push_back(Node3DEditorViewport::VIEW_REAR);
  271. axis_colors.clear();
  272. axis_colors.push_back(get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor)));
  273. axis_colors.push_back(get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor)));
  274. axis_colors.push_back(get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor)));
  275. queue_redraw();
  276. if (!is_connected(SceneStringName(mouse_exited), callable_mp(this, &ViewportRotationControl::_on_mouse_exited))) {
  277. connect(SceneStringName(mouse_exited), callable_mp(this, &ViewportRotationControl::_on_mouse_exited));
  278. }
  279. } break;
  280. case NOTIFICATION_DRAW: {
  281. if (viewport != nullptr) {
  282. _draw();
  283. }
  284. } break;
  285. }
  286. }
  287. void ViewportRotationControl::_draw() {
  288. const Vector2i center = get_size() / 2.0;
  289. const real_t radius = get_size().x / 2.0;
  290. if (focused_axis > -2 || orbiting_index != -1) {
  291. draw_circle(center, radius, Color(0.5, 0.5, 0.5, 0.25));
  292. }
  293. Vector<Axis2D> axis_to_draw;
  294. _get_sorted_axis(axis_to_draw);
  295. for (int i = 0; i < axis_to_draw.size(); ++i) {
  296. _draw_axis(axis_to_draw[i]);
  297. }
  298. }
  299. void ViewportRotationControl::_draw_axis(const Axis2D &p_axis) {
  300. const bool focused = focused_axis == p_axis.axis;
  301. const bool positive = p_axis.axis < 3;
  302. const int direction = p_axis.axis % 3;
  303. const Color axis_color = axis_colors[direction];
  304. const double alpha = focused ? 1.0 : ((p_axis.z_axis + 1.0) / 2.0) * 0.5 + 0.5;
  305. const Color c = focused ? Color(0.9, 0.9, 0.9) : Color(axis_color, alpha);
  306. if (positive) {
  307. // Draw axis lines for the positive axes.
  308. const Vector2i center = get_size() / 2.0;
  309. draw_line(center, p_axis.screen_point, c, 1.5 * EDSCALE);
  310. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS, c);
  311. // Draw the axis letter for the positive axes.
  312. const String axis_name = direction == 0 ? "X" : (direction == 1 ? "Y" : "Z");
  313. draw_char(get_theme_font(SNAME("rotation_control"), EditorStringName(EditorFonts)), p_axis.screen_point + Vector2i(Math::round(-4.0 * EDSCALE), Math::round(5.0 * EDSCALE)), axis_name, get_theme_font_size(SNAME("rotation_control_size"), EditorStringName(EditorFonts)), Color(0.0, 0.0, 0.0, alpha));
  314. } else {
  315. // Draw an outline around the negative axes.
  316. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS, c);
  317. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS * 0.8, c.darkened(0.4));
  318. }
  319. }
  320. void ViewportRotationControl::_get_sorted_axis(Vector<Axis2D> &r_axis) {
  321. const Vector2i center = get_size() / 2.0;
  322. const real_t radius = get_size().x / 2.0 - AXIS_CIRCLE_RADIUS - 2.0 * EDSCALE;
  323. const Basis camera_basis = viewport->to_camera_transform(viewport->cursor).get_basis().inverse();
  324. for (int i = 0; i < 3; ++i) {
  325. Vector3 axis_3d = camera_basis.get_column(i);
  326. Vector2i axis_vector = Vector2(axis_3d.x, -axis_3d.y) * radius;
  327. if (Math::abs(axis_3d.z) <= 1.0) {
  328. Axis2D pos_axis;
  329. pos_axis.axis = i;
  330. pos_axis.screen_point = center + axis_vector;
  331. pos_axis.z_axis = axis_3d.z;
  332. r_axis.push_back(pos_axis);
  333. Axis2D neg_axis;
  334. neg_axis.axis = i + 3;
  335. neg_axis.screen_point = center - axis_vector;
  336. neg_axis.z_axis = -axis_3d.z;
  337. r_axis.push_back(neg_axis);
  338. } else {
  339. // Special case when the camera is aligned with one axis
  340. Axis2D axis;
  341. axis.axis = i + (axis_3d.z <= 0 ? 0 : 3);
  342. axis.screen_point = center;
  343. axis.z_axis = 1.0;
  344. r_axis.push_back(axis);
  345. }
  346. }
  347. r_axis.sort_custom<Axis2DCompare>();
  348. }
  349. void ViewportRotationControl::_process_click(int p_index, Vector2 p_position, bool p_pressed) {
  350. if (orbiting_index != -1 && orbiting_index != p_index) {
  351. return;
  352. }
  353. if (p_pressed) {
  354. if (p_position.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
  355. orbiting_index = p_index;
  356. }
  357. } else {
  358. if (focused_axis > -1) {
  359. viewport->_menu_option(axis_menu_options[focused_axis]);
  360. _update_focus();
  361. }
  362. orbiting_index = -1;
  363. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
  364. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  365. Input::get_singleton()->warp_mouse(orbiting_mouse_start);
  366. }
  367. }
  368. }
  369. void ViewportRotationControl::_process_drag(Ref<InputEventWithModifiers> p_event, int p_index, Vector2 p_position, Vector2 p_relative_position) {
  370. if (orbiting_index == p_index) {
  371. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_VISIBLE) {
  372. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
  373. orbiting_mouse_start = p_position;
  374. }
  375. viewport->_nav_orbit(p_event, p_relative_position);
  376. focused_axis = -1;
  377. } else {
  378. _update_focus();
  379. }
  380. }
  381. void ViewportRotationControl::gui_input(const Ref<InputEvent> &p_event) {
  382. ERR_FAIL_COND(p_event.is_null());
  383. // Mouse events
  384. const Ref<InputEventMouseButton> mb = p_event;
  385. if (mb.is_valid() && mb->get_button_index() == MouseButton::LEFT) {
  386. _process_click(100, mb->get_position(), mb->is_pressed());
  387. }
  388. const Ref<InputEventMouseMotion> mm = p_event;
  389. if (mm.is_valid()) {
  390. _process_drag(mm, 100, mm->get_global_position(), viewport->_get_warped_mouse_motion(mm));
  391. }
  392. // Touch events
  393. const Ref<InputEventScreenTouch> screen_touch = p_event;
  394. if (screen_touch.is_valid()) {
  395. _process_click(screen_touch->get_index(), screen_touch->get_position(), screen_touch->is_pressed());
  396. }
  397. const Ref<InputEventScreenDrag> screen_drag = p_event;
  398. if (screen_drag.is_valid()) {
  399. _process_drag(screen_drag, screen_drag->get_index(), screen_drag->get_position(), screen_drag->get_relative());
  400. }
  401. }
  402. void ViewportRotationControl::_update_focus() {
  403. int original_focus = focused_axis;
  404. focused_axis = -2;
  405. Vector2 mouse_pos = get_local_mouse_position();
  406. if (mouse_pos.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
  407. focused_axis = -1;
  408. }
  409. Vector<Axis2D> axes;
  410. _get_sorted_axis(axes);
  411. for (int i = 0; i < axes.size(); i++) {
  412. const Axis2D &axis = axes[i];
  413. if (mouse_pos.distance_to(axis.screen_point) < AXIS_CIRCLE_RADIUS) {
  414. focused_axis = axis.axis;
  415. }
  416. }
  417. if (focused_axis != original_focus) {
  418. queue_redraw();
  419. }
  420. }
  421. void ViewportRotationControl::_on_mouse_exited() {
  422. focused_axis = -2;
  423. queue_redraw();
  424. }
  425. void ViewportRotationControl::set_viewport(Node3DEditorViewport *p_viewport) {
  426. viewport = p_viewport;
  427. }
  428. void Node3DEditorViewport::_view_settings_confirmed(real_t p_interp_delta) {
  429. // Set FOV override multiplier back to the default, so that the FOV
  430. // setting specified in the View menu is correctly applied.
  431. cursor.fov_scale = 1.0;
  432. _update_camera(p_interp_delta);
  433. }
  434. void Node3DEditorViewport::_update_navigation_controls_visibility() {
  435. bool show_viewport_rotation_gizmo = EDITOR_GET("editors/3d/navigation/show_viewport_rotation_gizmo") && (!previewing_cinema && !previewing_camera);
  436. rotation_control->set_visible(show_viewport_rotation_gizmo);
  437. bool show_viewport_navigation_gizmo = EDITOR_GET("editors/3d/navigation/show_viewport_navigation_gizmo") && (!previewing_cinema && !previewing_camera);
  438. position_control->set_visible(show_viewport_navigation_gizmo);
  439. look_control->set_visible(show_viewport_navigation_gizmo);
  440. }
  441. void Node3DEditorViewport::_update_camera(real_t p_interp_delta) {
  442. bool is_orthogonal = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
  443. Cursor old_camera_cursor = camera_cursor;
  444. camera_cursor = cursor;
  445. if (p_interp_delta > 0) {
  446. //-------
  447. // Perform smoothing
  448. if (is_freelook_active()) {
  449. // Higher inertia should increase "lag" (lerp with factor between 0 and 1)
  450. // 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.
  451. const real_t inertia = EDITOR_GET("editors/3d/freelook/freelook_inertia");
  452. real_t factor = (1.0 / inertia) * p_interp_delta;
  453. // We interpolate a different point here, because in freelook mode the focus point (cursor.pos) orbits around eye_pos
  454. camera_cursor.eye_pos = old_camera_cursor.eye_pos.lerp(cursor.eye_pos, CLAMP(factor, 0, 1));
  455. const real_t orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/orbit_inertia");
  456. camera_cursor.x_rot = Math::lerp(old_camera_cursor.x_rot, cursor.x_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  457. camera_cursor.y_rot = Math::lerp(old_camera_cursor.y_rot, cursor.y_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  458. if (Math::abs(camera_cursor.x_rot - cursor.x_rot) < 0.1) {
  459. camera_cursor.x_rot = cursor.x_rot;
  460. }
  461. if (Math::abs(camera_cursor.y_rot - cursor.y_rot) < 0.1) {
  462. camera_cursor.y_rot = cursor.y_rot;
  463. }
  464. Vector3 forward = to_camera_transform(camera_cursor).basis.xform(Vector3(0, 0, -1));
  465. camera_cursor.pos = camera_cursor.eye_pos + forward * camera_cursor.distance;
  466. } else {
  467. const real_t orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/orbit_inertia");
  468. const real_t translation_inertia = EDITOR_GET("editors/3d/navigation_feel/translation_inertia");
  469. const real_t zoom_inertia = EDITOR_GET("editors/3d/navigation_feel/zoom_inertia");
  470. camera_cursor.x_rot = Math::lerp(old_camera_cursor.x_rot, cursor.x_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  471. camera_cursor.y_rot = Math::lerp(old_camera_cursor.y_rot, cursor.y_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  472. if (Math::abs(camera_cursor.x_rot - cursor.x_rot) < 0.1) {
  473. camera_cursor.x_rot = cursor.x_rot;
  474. }
  475. if (Math::abs(camera_cursor.y_rot - cursor.y_rot) < 0.1) {
  476. camera_cursor.y_rot = cursor.y_rot;
  477. }
  478. camera_cursor.pos = old_camera_cursor.pos.lerp(cursor.pos, MIN(1.f, p_interp_delta * (1 / translation_inertia)));
  479. camera_cursor.distance = Math::lerp(old_camera_cursor.distance, cursor.distance, MIN((real_t)1.0, p_interp_delta * (1 / zoom_inertia)));
  480. }
  481. }
  482. //-------
  483. // Apply camera transform
  484. real_t tolerance = 0.001;
  485. bool equal = true;
  486. 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)) {
  487. equal = false;
  488. } else if (!old_camera_cursor.pos.is_equal_approx(camera_cursor.pos)) {
  489. equal = false;
  490. } else if (!Math::is_equal_approx(old_camera_cursor.distance, camera_cursor.distance, tolerance)) {
  491. equal = false;
  492. } else if (!Math::is_equal_approx(old_camera_cursor.fov_scale, camera_cursor.fov_scale, tolerance)) {
  493. equal = false;
  494. }
  495. if (!equal || p_interp_delta == 0 || is_orthogonal != orthogonal) {
  496. camera->set_global_transform(to_camera_transform(camera_cursor));
  497. if (orthogonal) {
  498. float half_fov = Math::deg_to_rad(get_fov()) / 2.0;
  499. float height = 2.0 * cursor.distance * Math::tan(half_fov);
  500. camera->set_orthogonal(height, get_znear(), get_zfar());
  501. } else {
  502. camera->set_perspective(get_fov(), get_znear(), get_zfar());
  503. }
  504. update_transform_gizmo_view();
  505. rotation_control->queue_redraw();
  506. position_control->queue_redraw();
  507. look_control->queue_redraw();
  508. spatial_editor->update_grid();
  509. }
  510. }
  511. Transform3D Node3DEditorViewport::to_camera_transform(const Cursor &p_cursor) const {
  512. Transform3D camera_transform;
  513. camera_transform.translate_local(p_cursor.pos);
  514. camera_transform.basis.rotate(Vector3(1, 0, 0), -p_cursor.x_rot);
  515. camera_transform.basis.rotate(Vector3(0, 1, 0), -p_cursor.y_rot);
  516. if (orthogonal) {
  517. camera_transform.translate_local(0, 0, (get_zfar() - get_znear()) / 2.0);
  518. } else {
  519. camera_transform.translate_local(0, 0, p_cursor.distance);
  520. }
  521. return camera_transform;
  522. }
  523. int Node3DEditorViewport::get_selected_count() const {
  524. const HashMap<Node *, Object *> &selection = editor_selection->get_selection();
  525. int count = 0;
  526. for (const KeyValue<Node *, Object *> &E : selection) {
  527. Node3D *sp = Object::cast_to<Node3D>(E.key);
  528. if (!sp) {
  529. continue;
  530. }
  531. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  532. if (!se) {
  533. continue;
  534. }
  535. count++;
  536. }
  537. return count;
  538. }
  539. void Node3DEditorViewport::cancel_transform() {
  540. List<Node *> &selection = editor_selection->get_selected_node_list();
  541. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  542. Node3D *sp = Object::cast_to<Node3D>(E->get());
  543. if (!sp) {
  544. continue;
  545. }
  546. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  547. if (!se) {
  548. continue;
  549. }
  550. if (se && se->gizmo.is_valid()) {
  551. Vector<int> ids;
  552. Vector<Transform3D> restore;
  553. for (const KeyValue<int, Transform3D> &GE : se->subgizmos) {
  554. ids.push_back(GE.key);
  555. restore.push_back(GE.value);
  556. }
  557. se->gizmo->commit_subgizmos(ids, restore, true);
  558. }
  559. sp->set_global_transform(se->original);
  560. }
  561. finish_transform();
  562. set_message(TTR("Transform Aborted."), 3);
  563. }
  564. void Node3DEditorViewport::_update_shrink() {
  565. bool shrink = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION));
  566. subviewport_container->set_stretch_shrink(shrink ? 2 : 1);
  567. subviewport_container->set_texture_filter(shrink ? TEXTURE_FILTER_NEAREST : TEXTURE_FILTER_PARENT_NODE);
  568. }
  569. float Node3DEditorViewport::get_znear() const {
  570. return CLAMP(spatial_editor->get_znear(), MIN_Z, MAX_Z);
  571. }
  572. float Node3DEditorViewport::get_zfar() const {
  573. return CLAMP(spatial_editor->get_zfar(), MIN_Z, MAX_Z);
  574. }
  575. float Node3DEditorViewport::get_fov() const {
  576. return CLAMP(spatial_editor->get_fov() * cursor.fov_scale, MIN_FOV, MAX_FOV);
  577. }
  578. Transform3D Node3DEditorViewport::_get_camera_transform() const {
  579. return camera->get_global_transform();
  580. }
  581. Vector3 Node3DEditorViewport::_get_camera_position() const {
  582. return _get_camera_transform().origin;
  583. }
  584. Point2 Node3DEditorViewport::point_to_screen(const Vector3 &p_point) {
  585. return camera->unproject_position(p_point) * subviewport_container->get_stretch_shrink();
  586. }
  587. Vector3 Node3DEditorViewport::get_ray_pos(const Vector2 &p_pos) const {
  588. return camera->project_ray_origin(p_pos / subviewport_container->get_stretch_shrink());
  589. }
  590. Vector3 Node3DEditorViewport::_get_camera_normal() const {
  591. return -_get_camera_transform().basis.get_column(2);
  592. }
  593. Vector3 Node3DEditorViewport::get_ray(const Vector2 &p_pos) const {
  594. return camera->project_ray_normal(p_pos / subviewport_container->get_stretch_shrink());
  595. }
  596. void Node3DEditorViewport::_clear_selected() {
  597. _edit.gizmo = Ref<EditorNode3DGizmo>();
  598. _edit.gizmo_handle = -1;
  599. _edit.gizmo_handle_secondary = false;
  600. _edit.gizmo_initial_value = Variant();
  601. Node3D *selected = spatial_editor->get_single_selected_node();
  602. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  603. if (se && se->gizmo.is_valid()) {
  604. se->subgizmos.clear();
  605. se->gizmo->redraw();
  606. se->gizmo.unref();
  607. spatial_editor->update_transform_gizmo();
  608. } else {
  609. editor_selection->clear();
  610. Node3DEditor::get_singleton()->edit(nullptr);
  611. }
  612. }
  613. void Node3DEditorViewport::_select_clicked(bool p_allow_locked) {
  614. Node *node = Object::cast_to<Node3D>(ObjectDB::get_instance(clicked));
  615. Node3D *selected = Object::cast_to<Node3D>(node);
  616. clicked = ObjectID();
  617. if (!selected) {
  618. return;
  619. }
  620. Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
  621. // Prevent selection of nodes not owned by the edited scene.
  622. while (node && node != edited_scene->get_parent()) {
  623. Node *node_owner = node->get_owner();
  624. if (node_owner == edited_scene || node == edited_scene || (node_owner != nullptr && edited_scene->is_editable_instance(node_owner))) {
  625. break;
  626. }
  627. node = node->get_parent();
  628. selected = Object::cast_to<Node3D>(node);
  629. }
  630. if (!p_allow_locked) {
  631. // Replace the node by the group if grouped
  632. while (node && node != edited_scene->get_parent()) {
  633. Node3D *selected_tmp = Object::cast_to<Node3D>(node);
  634. if (selected_tmp && node->has_meta("_edit_group_")) {
  635. selected = selected_tmp;
  636. }
  637. node = node->get_parent();
  638. }
  639. }
  640. if (p_allow_locked || !_is_node_locked(selected)) {
  641. if (clicked_wants_append) {
  642. if (editor_selection->is_selected(selected)) {
  643. editor_selection->remove_node(selected);
  644. } else {
  645. editor_selection->add_node(selected);
  646. }
  647. } else {
  648. if (!editor_selection->is_selected(selected)) {
  649. editor_selection->clear();
  650. editor_selection->add_node(selected);
  651. EditorNode::get_singleton()->edit_node(selected);
  652. }
  653. }
  654. if (editor_selection->get_selected_node_list().size() == 1) {
  655. EditorNode::get_singleton()->edit_node(editor_selection->get_selected_node_list().front()->get());
  656. }
  657. }
  658. }
  659. ObjectID Node3DEditorViewport::_select_ray(const Point2 &p_pos) const {
  660. Vector3 ray = get_ray(p_pos);
  661. Vector3 pos = get_ray_pos(p_pos);
  662. Vector2 shrinked_pos = p_pos / subviewport_container->get_stretch_shrink();
  663. if (viewport->get_debug_draw() == Viewport::DEBUG_DRAW_SDFGI_PROBES) {
  664. RS::get_singleton()->sdfgi_set_debug_probe_select(pos, ray);
  665. }
  666. Vector<ObjectID> instances = RenderingServer::get_singleton()->instances_cull_ray(pos, pos + ray * camera->get_far(), get_tree()->get_root()->get_world_3d()->get_scenario());
  667. HashSet<Ref<EditorNode3DGizmo>> found_gizmos;
  668. Node *edited_scene = get_tree()->get_edited_scene_root();
  669. ObjectID closest;
  670. Node *item = nullptr;
  671. float closest_dist = 1e20;
  672. for (int i = 0; i < instances.size(); i++) {
  673. Node3D *spat = Object::cast_to<Node3D>(ObjectDB::get_instance(instances[i]));
  674. if (!spat) {
  675. continue;
  676. }
  677. Vector<Ref<Node3DGizmo>> gizmos = spat->get_gizmos();
  678. for (int j = 0; j < gizmos.size(); j++) {
  679. Ref<EditorNode3DGizmo> seg = gizmos[j];
  680. if ((!seg.is_valid()) || found_gizmos.has(seg)) {
  681. continue;
  682. }
  683. found_gizmos.insert(seg);
  684. Vector3 point;
  685. Vector3 normal;
  686. bool inters = seg->intersect_ray(camera, shrinked_pos, point, normal);
  687. if (!inters) {
  688. continue;
  689. }
  690. const real_t dist = pos.distance_to(point);
  691. if (dist < 0) {
  692. continue;
  693. }
  694. if (dist < closest_dist) {
  695. item = Object::cast_to<Node>(spat);
  696. if (item != edited_scene) {
  697. item = edited_scene->get_deepest_editable_node(item);
  698. }
  699. closest = item->get_instance_id();
  700. closest_dist = dist;
  701. }
  702. }
  703. }
  704. if (!item) {
  705. return ObjectID();
  706. }
  707. return closest;
  708. }
  709. void Node3DEditorViewport::_find_items_at_pos(const Point2 &p_pos, Vector<_RayResult> &r_results, bool p_include_locked_nodes) {
  710. Vector3 ray = get_ray(p_pos);
  711. Vector3 pos = get_ray_pos(p_pos);
  712. Vector<ObjectID> instances = RenderingServer::get_singleton()->instances_cull_ray(pos, pos + ray * camera->get_far(), get_tree()->get_root()->get_world_3d()->get_scenario());
  713. HashSet<Node3D *> found_nodes;
  714. for (int i = 0; i < instances.size(); i++) {
  715. Node3D *spat = Object::cast_to<Node3D>(ObjectDB::get_instance(instances[i]));
  716. if (!spat) {
  717. continue;
  718. }
  719. if (found_nodes.has(spat)) {
  720. continue;
  721. }
  722. if (!p_include_locked_nodes && _is_node_locked(spat)) {
  723. continue;
  724. }
  725. Vector<Ref<Node3DGizmo>> gizmos = spat->get_gizmos();
  726. for (int j = 0; j < gizmos.size(); j++) {
  727. Ref<EditorNode3DGizmo> seg = gizmos[j];
  728. if (!seg.is_valid()) {
  729. continue;
  730. }
  731. Vector3 point;
  732. Vector3 normal;
  733. bool inters = seg->intersect_ray(camera, p_pos, point, normal);
  734. if (!inters) {
  735. continue;
  736. }
  737. const real_t dist = pos.distance_to(point);
  738. if (dist < 0) {
  739. continue;
  740. }
  741. found_nodes.insert(spat);
  742. _RayResult res;
  743. res.item = spat;
  744. res.depth = dist;
  745. r_results.push_back(res);
  746. break;
  747. }
  748. }
  749. r_results.sort();
  750. }
  751. Vector3 Node3DEditorViewport::_get_screen_to_space(const Vector3 &p_vector3) {
  752. Projection cm;
  753. if (orthogonal) {
  754. cm.set_orthogonal(camera->get_size(), get_size().aspect(), get_znear() + p_vector3.z, get_zfar());
  755. } else {
  756. cm.set_perspective(get_fov(), get_size().aspect(), get_znear() + p_vector3.z, get_zfar());
  757. }
  758. Vector2 screen_he = cm.get_viewport_half_extents();
  759. Transform3D camera_transform;
  760. camera_transform.translate_local(cursor.pos);
  761. camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
  762. camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
  763. camera_transform.translate_local(0, 0, cursor.distance);
  764. 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)));
  765. }
  766. void Node3DEditorViewport::_select_region() {
  767. if (cursor.region_begin == cursor.region_end) {
  768. if (!clicked_wants_append) {
  769. _clear_selected();
  770. }
  771. return; //nothing really
  772. }
  773. const real_t z_offset = MAX(0.0, 5.0 - get_znear());
  774. Vector3 box[4] = {
  775. Vector3(
  776. MIN(cursor.region_begin.x, cursor.region_end.x),
  777. MIN(cursor.region_begin.y, cursor.region_end.y),
  778. z_offset),
  779. Vector3(
  780. MAX(cursor.region_begin.x, cursor.region_end.x),
  781. MIN(cursor.region_begin.y, cursor.region_end.y),
  782. z_offset),
  783. Vector3(
  784. MAX(cursor.region_begin.x, cursor.region_end.x),
  785. MAX(cursor.region_begin.y, cursor.region_end.y),
  786. z_offset),
  787. Vector3(
  788. MIN(cursor.region_begin.x, cursor.region_end.x),
  789. MAX(cursor.region_begin.y, cursor.region_end.y),
  790. z_offset)
  791. };
  792. Vector<Plane> frustum;
  793. Vector3 cam_pos = _get_camera_position();
  794. for (int i = 0; i < 4; i++) {
  795. Vector3 a = _get_screen_to_space(box[i]);
  796. Vector3 b = _get_screen_to_space(box[(i + 1) % 4]);
  797. if (orthogonal) {
  798. frustum.push_back(Plane((a - b).normalized(), a));
  799. } else {
  800. frustum.push_back(Plane(a, b, cam_pos));
  801. }
  802. }
  803. Plane near_plane = Plane(-_get_camera_normal(), cam_pos);
  804. near_plane.d -= get_znear();
  805. frustum.push_back(near_plane);
  806. Plane far_plane = -near_plane;
  807. far_plane.d += get_zfar();
  808. frustum.push_back(far_plane);
  809. if (spatial_editor->get_single_selected_node()) {
  810. Node3D *single_selected = spatial_editor->get_single_selected_node();
  811. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(single_selected);
  812. if (se) {
  813. Ref<EditorNode3DGizmo> old_gizmo;
  814. if (!clicked_wants_append) {
  815. se->subgizmos.clear();
  816. old_gizmo = se->gizmo;
  817. se->gizmo.unref();
  818. }
  819. bool found_subgizmos = false;
  820. Vector<Ref<Node3DGizmo>> gizmos = single_selected->get_gizmos();
  821. for (int j = 0; j < gizmos.size(); j++) {
  822. Ref<EditorNode3DGizmo> seg = gizmos[j];
  823. if (!seg.is_valid()) {
  824. continue;
  825. }
  826. if (se->gizmo.is_valid() && se->gizmo != seg) {
  827. continue;
  828. }
  829. Vector<int> subgizmos = seg->subgizmos_intersect_frustum(camera, frustum);
  830. if (!subgizmos.is_empty()) {
  831. se->gizmo = seg;
  832. for (int i = 0; i < subgizmos.size(); i++) {
  833. int subgizmo_id = subgizmos[i];
  834. if (!se->subgizmos.has(subgizmo_id)) {
  835. se->subgizmos.insert(subgizmo_id, se->gizmo->get_subgizmo_transform(subgizmo_id));
  836. }
  837. }
  838. found_subgizmos = true;
  839. break;
  840. }
  841. }
  842. if (!clicked_wants_append || found_subgizmos) {
  843. if (se->gizmo.is_valid()) {
  844. se->gizmo->redraw();
  845. }
  846. if (old_gizmo != se->gizmo && old_gizmo.is_valid()) {
  847. old_gizmo->redraw();
  848. }
  849. spatial_editor->update_transform_gizmo();
  850. }
  851. if (found_subgizmos) {
  852. return;
  853. }
  854. }
  855. }
  856. if (!clicked_wants_append) {
  857. _clear_selected();
  858. }
  859. Vector<ObjectID> instances = RenderingServer::get_singleton()->instances_cull_convex(frustum, get_tree()->get_root()->get_world_3d()->get_scenario());
  860. HashSet<Node3D *> found_nodes;
  861. Vector<Node *> selected;
  862. Node *edited_scene = get_tree()->get_edited_scene_root();
  863. for (int i = 0; i < instances.size(); i++) {
  864. Node3D *sp = Object::cast_to<Node3D>(ObjectDB::get_instance(instances[i]));
  865. if (!sp || _is_node_locked(sp)) {
  866. continue;
  867. }
  868. if (found_nodes.has(sp)) {
  869. continue;
  870. }
  871. found_nodes.insert(sp);
  872. Node *node = Object::cast_to<Node>(sp);
  873. if (node != edited_scene) {
  874. node = edited_scene->get_deepest_editable_node(node);
  875. }
  876. // Prevent selection of nodes not owned by the edited scene.
  877. while (node && node != edited_scene->get_parent()) {
  878. Node *node_owner = node->get_owner();
  879. if (node_owner == edited_scene || node == edited_scene || (node_owner != nullptr && edited_scene->is_editable_instance(node_owner))) {
  880. break;
  881. }
  882. node = node->get_parent();
  883. }
  884. // Replace the node by the group if grouped
  885. if (node->is_class("Node3D")) {
  886. Node3D *sel = Object::cast_to<Node3D>(node);
  887. while (node && node != EditorNode::get_singleton()->get_edited_scene()->get_parent()) {
  888. Node3D *selected_tmp = Object::cast_to<Node3D>(node);
  889. if (selected_tmp && node->has_meta("_edit_group_")) {
  890. sel = selected_tmp;
  891. }
  892. node = node->get_parent();
  893. }
  894. node = sel;
  895. }
  896. if (_is_node_locked(node)) {
  897. continue;
  898. }
  899. Vector<Ref<Node3DGizmo>> gizmos = sp->get_gizmos();
  900. for (int j = 0; j < gizmos.size(); j++) {
  901. Ref<EditorNode3DGizmo> seg = gizmos[j];
  902. if (!seg.is_valid()) {
  903. continue;
  904. }
  905. if (seg->intersect_frustum(camera, frustum)) {
  906. selected.push_back(node);
  907. }
  908. }
  909. }
  910. for (int i = 0; i < selected.size(); i++) {
  911. if (!editor_selection->is_selected(selected[i])) {
  912. editor_selection->add_node(selected[i]);
  913. }
  914. }
  915. if (editor_selection->get_selected_node_list().size() == 1) {
  916. EditorNode::get_singleton()->edit_node(editor_selection->get_selected_node_list().front()->get());
  917. }
  918. }
  919. void Node3DEditorViewport::_update_name() {
  920. String name;
  921. switch (view_type) {
  922. case VIEW_TYPE_USER: {
  923. if (orthogonal) {
  924. name = TTR("Orthogonal");
  925. } else {
  926. name = TTR("Perspective");
  927. }
  928. } break;
  929. case VIEW_TYPE_TOP: {
  930. if (orthogonal) {
  931. name = TTR("Top Orthogonal");
  932. } else {
  933. name = TTR("Top Perspective");
  934. }
  935. } break;
  936. case VIEW_TYPE_BOTTOM: {
  937. if (orthogonal) {
  938. name = TTR("Bottom Orthogonal");
  939. } else {
  940. name = TTR("Bottom Perspective");
  941. }
  942. } break;
  943. case VIEW_TYPE_LEFT: {
  944. if (orthogonal) {
  945. name = TTR("Left Orthogonal");
  946. } else {
  947. name = TTR("Left Perspective");
  948. }
  949. } break;
  950. case VIEW_TYPE_RIGHT: {
  951. if (orthogonal) {
  952. name = TTR("Right Orthogonal");
  953. } else {
  954. name = TTR("Right Perspective");
  955. }
  956. } break;
  957. case VIEW_TYPE_FRONT: {
  958. if (orthogonal) {
  959. name = TTR("Front Orthogonal");
  960. } else {
  961. name = TTR("Front Perspective");
  962. }
  963. } break;
  964. case VIEW_TYPE_REAR: {
  965. if (orthogonal) {
  966. name = TTR("Rear Orthogonal");
  967. } else {
  968. name = TTR("Rear Perspective");
  969. }
  970. } break;
  971. }
  972. if (auto_orthogonal) {
  973. // TRANSLATORS: This will be appended to the view name when Auto Orthogonal is enabled.
  974. name += TTR(" [auto]");
  975. }
  976. view_menu->set_text(name);
  977. view_menu->reset_size();
  978. }
  979. void Node3DEditorViewport::_compute_edit(const Point2 &p_point) {
  980. _edit.original_local = spatial_editor->are_local_coords_enabled();
  981. _edit.click_ray = get_ray(p_point);
  982. _edit.click_ray_pos = get_ray_pos(p_point);
  983. _edit.plane = TRANSFORM_VIEW;
  984. spatial_editor->update_transform_gizmo();
  985. _edit.center = spatial_editor->get_gizmo_transform().origin;
  986. Node3D *selected = spatial_editor->get_single_selected_node();
  987. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  988. if (se && se->gizmo.is_valid()) {
  989. for (const KeyValue<int, Transform3D> &E : se->subgizmos) {
  990. int subgizmo_id = E.key;
  991. se->subgizmos[subgizmo_id] = se->gizmo->get_subgizmo_transform(subgizmo_id);
  992. }
  993. se->original_local = selected->get_transform();
  994. se->original = selected->get_global_transform();
  995. } else {
  996. List<Node *> &selection = editor_selection->get_selected_node_list();
  997. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  998. Node3D *sp = Object::cast_to<Node3D>(E->get());
  999. if (!sp) {
  1000. continue;
  1001. }
  1002. Node3DEditorSelectedItem *sel_item = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  1003. if (!sel_item) {
  1004. continue;
  1005. }
  1006. sel_item->original_local = sel_item->sp->get_local_gizmo_transform();
  1007. sel_item->original = sel_item->sp->get_global_gizmo_transform();
  1008. }
  1009. }
  1010. }
  1011. static Key _get_key_modifier_setting(const String &p_property) {
  1012. switch (EDITOR_GET(p_property).operator int()) {
  1013. case 0:
  1014. return Key::NONE;
  1015. case 1:
  1016. return Key::SHIFT;
  1017. case 2:
  1018. return Key::ALT;
  1019. case 3:
  1020. return Key::META;
  1021. case 4:
  1022. return Key::CTRL;
  1023. }
  1024. return Key::NONE;
  1025. }
  1026. static Key _get_key_modifier(Ref<InputEventWithModifiers> e) {
  1027. if (e->is_shift_pressed()) {
  1028. return Key::SHIFT;
  1029. }
  1030. if (e->is_alt_pressed()) {
  1031. return Key::ALT;
  1032. }
  1033. if (e->is_ctrl_pressed()) {
  1034. return Key::CTRL;
  1035. }
  1036. if (e->is_meta_pressed()) {
  1037. return Key::META;
  1038. }
  1039. return Key::NONE;
  1040. }
  1041. bool Node3DEditorViewport::_transform_gizmo_select(const Vector2 &p_screenpos, bool p_highlight_only) {
  1042. if (!spatial_editor->is_gizmo_visible()) {
  1043. return false;
  1044. }
  1045. if (get_selected_count() == 0) {
  1046. if (p_highlight_only) {
  1047. spatial_editor->select_gizmo_highlight_axis(-1);
  1048. }
  1049. return false;
  1050. }
  1051. Vector3 ray_pos = get_ray_pos(p_screenpos);
  1052. Vector3 ray = get_ray(p_screenpos);
  1053. Transform3D gt = spatial_editor->get_gizmo_transform();
  1054. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE) {
  1055. int col_axis = -1;
  1056. real_t col_d = 1e20;
  1057. for (int i = 0; i < 3; i++) {
  1058. const Vector3 grabber_pos = gt.origin + gt.basis.get_column(i).normalized() * gizmo_scale * (GIZMO_ARROW_OFFSET + (GIZMO_ARROW_SIZE * 0.5));
  1059. const real_t grabber_radius = gizmo_scale * GIZMO_ARROW_SIZE;
  1060. Vector3 r;
  1061. if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) {
  1062. const real_t d = r.distance_to(ray_pos);
  1063. if (d < col_d) {
  1064. col_d = d;
  1065. col_axis = i;
  1066. }
  1067. }
  1068. }
  1069. bool is_plane_translate = false;
  1070. // plane select
  1071. if (col_axis == -1) {
  1072. col_d = 1e20;
  1073. for (int i = 0; i < 3; i++) {
  1074. Vector3 ivec2 = gt.basis.get_column((i + 1) % 3).normalized();
  1075. Vector3 ivec3 = gt.basis.get_column((i + 2) % 3).normalized();
  1076. // Allow some tolerance to make the plane easier to click,
  1077. // even if the click is actually slightly outside the plane.
  1078. const Vector3 grabber_pos = gt.origin + (ivec2 + ivec3) * gizmo_scale * (GIZMO_PLANE_SIZE + GIZMO_PLANE_DST * 0.6667);
  1079. Vector3 r;
  1080. Plane plane(gt.basis.get_column(i).normalized(), gt.origin);
  1081. if (plane.intersects_ray(ray_pos, ray, &r)) {
  1082. const real_t dist = r.distance_to(grabber_pos);
  1083. // Allow some tolerance to make the plane easier to click,
  1084. // even if the click is actually slightly outside the plane.
  1085. if (dist < (gizmo_scale * GIZMO_PLANE_SIZE * 1.5)) {
  1086. const real_t d = ray_pos.distance_to(r);
  1087. if (d < col_d) {
  1088. col_d = d;
  1089. col_axis = i;
  1090. is_plane_translate = true;
  1091. }
  1092. }
  1093. }
  1094. }
  1095. }
  1096. if (col_axis != -1) {
  1097. if (p_highlight_only) {
  1098. spatial_editor->select_gizmo_highlight_axis(col_axis + (is_plane_translate ? 6 : 0));
  1099. } else {
  1100. //handle plane translate
  1101. _edit.mode = TRANSFORM_TRANSLATE;
  1102. _compute_edit(p_screenpos);
  1103. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis + (is_plane_translate ? 3 : 0));
  1104. }
  1105. return true;
  1106. }
  1107. }
  1108. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE) {
  1109. int col_axis = -1;
  1110. Vector3 hit_position;
  1111. Vector3 hit_normal;
  1112. real_t ray_length = gt.origin.distance_to(ray_pos) + (GIZMO_CIRCLE_SIZE * gizmo_scale) * 4.0f;
  1113. if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * ray_length, gt.origin, gizmo_scale * (GIZMO_CIRCLE_SIZE), &hit_position, &hit_normal)) {
  1114. if (hit_normal.dot(_get_camera_normal()) < 0.05) {
  1115. hit_position = gt.xform_inv(hit_position).abs();
  1116. int min_axis = hit_position.min_axis_index();
  1117. if (hit_position[min_axis] < gizmo_scale * GIZMO_RING_HALF_WIDTH) {
  1118. col_axis = min_axis;
  1119. }
  1120. }
  1121. }
  1122. if (col_axis == -1) {
  1123. float col_d = 1e20;
  1124. for (int i = 0; i < 3; i++) {
  1125. Plane plane(gt.basis.get_column(i).normalized(), gt.origin);
  1126. Vector3 r;
  1127. if (!plane.intersects_ray(ray_pos, ray, &r)) {
  1128. continue;
  1129. }
  1130. const real_t dist = r.distance_to(gt.origin);
  1131. const Vector3 r_dir = (r - gt.origin).normalized();
  1132. if (_get_camera_normal().dot(r_dir) <= 0.005) {
  1133. if (dist > gizmo_scale * (GIZMO_CIRCLE_SIZE - GIZMO_RING_HALF_WIDTH) && dist < gizmo_scale * (GIZMO_CIRCLE_SIZE + GIZMO_RING_HALF_WIDTH)) {
  1134. const real_t d = ray_pos.distance_to(r);
  1135. if (d < col_d) {
  1136. col_d = d;
  1137. col_axis = i;
  1138. }
  1139. }
  1140. }
  1141. }
  1142. }
  1143. if (col_axis != -1) {
  1144. if (p_highlight_only) {
  1145. spatial_editor->select_gizmo_highlight_axis(col_axis + 3);
  1146. } else {
  1147. //handle rotate
  1148. _edit.mode = TRANSFORM_ROTATE;
  1149. _compute_edit(p_screenpos);
  1150. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis);
  1151. }
  1152. return true;
  1153. }
  1154. }
  1155. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE) {
  1156. int col_axis = -1;
  1157. float col_d = 1e20;
  1158. for (int i = 0; i < 3; i++) {
  1159. const Vector3 grabber_pos = gt.origin + gt.basis.get_column(i).normalized() * gizmo_scale * GIZMO_SCALE_OFFSET;
  1160. const real_t grabber_radius = gizmo_scale * GIZMO_ARROW_SIZE;
  1161. Vector3 r;
  1162. if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) {
  1163. const real_t d = r.distance_to(ray_pos);
  1164. if (d < col_d) {
  1165. col_d = d;
  1166. col_axis = i;
  1167. }
  1168. }
  1169. }
  1170. bool is_plane_scale = false;
  1171. // plane select
  1172. if (col_axis == -1) {
  1173. col_d = 1e20;
  1174. for (int i = 0; i < 3; i++) {
  1175. const Vector3 ivec2 = gt.basis.get_column((i + 1) % 3).normalized();
  1176. const Vector3 ivec3 = gt.basis.get_column((i + 2) % 3).normalized();
  1177. // Allow some tolerance to make the plane easier to click,
  1178. // even if the click is actually slightly outside the plane.
  1179. const Vector3 grabber_pos = gt.origin + (ivec2 + ivec3) * gizmo_scale * (GIZMO_PLANE_SIZE + GIZMO_PLANE_DST * 0.6667);
  1180. Vector3 r;
  1181. Plane plane(gt.basis.get_column(i).normalized(), gt.origin);
  1182. if (plane.intersects_ray(ray_pos, ray, &r)) {
  1183. const real_t dist = r.distance_to(grabber_pos);
  1184. // Allow some tolerance to make the plane easier to click,
  1185. // even if the click is actually slightly outside the plane.
  1186. if (dist < (gizmo_scale * GIZMO_PLANE_SIZE * 1.5)) {
  1187. const real_t d = ray_pos.distance_to(r);
  1188. if (d < col_d) {
  1189. col_d = d;
  1190. col_axis = i;
  1191. is_plane_scale = true;
  1192. }
  1193. }
  1194. }
  1195. }
  1196. }
  1197. if (col_axis != -1) {
  1198. if (p_highlight_only) {
  1199. spatial_editor->select_gizmo_highlight_axis(col_axis + (is_plane_scale ? 12 : 9));
  1200. } else {
  1201. //handle scale
  1202. _edit.mode = TRANSFORM_SCALE;
  1203. _compute_edit(p_screenpos);
  1204. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis + (is_plane_scale ? 3 : 0));
  1205. }
  1206. return true;
  1207. }
  1208. }
  1209. if (p_highlight_only) {
  1210. spatial_editor->select_gizmo_highlight_axis(-1);
  1211. }
  1212. return false;
  1213. }
  1214. void Node3DEditorViewport::_transform_gizmo_apply(Node3D *p_node, const Transform3D &p_transform, bool p_local) {
  1215. if (p_transform.basis.determinant() == 0) {
  1216. return;
  1217. }
  1218. if (p_local) {
  1219. p_node->set_transform(p_transform);
  1220. } else {
  1221. p_node->set_global_transform(p_transform);
  1222. }
  1223. }
  1224. Transform3D Node3DEditorViewport::_compute_transform(TransformMode p_mode, const Transform3D &p_original, const Transform3D &p_original_local, Vector3 p_motion, double p_extra, bool p_local, bool p_orthogonal) {
  1225. switch (p_mode) {
  1226. case TRANSFORM_SCALE: {
  1227. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1228. p_motion.snapf(p_extra);
  1229. }
  1230. Transform3D s;
  1231. if (p_local) {
  1232. s.basis = p_original_local.basis.scaled_local(p_motion + Vector3(1, 1, 1));
  1233. s.origin = p_original_local.origin;
  1234. } else {
  1235. s.basis.scale(p_motion + Vector3(1, 1, 1));
  1236. Transform3D base = Transform3D(Basis(), _edit.center);
  1237. s = base * (s * (base.inverse() * p_original));
  1238. // Recalculate orthogonalized scale without moving origin.
  1239. if (p_orthogonal) {
  1240. s.basis = p_original.basis.scaled_orthogonal(p_motion + Vector3(1, 1, 1));
  1241. }
  1242. }
  1243. return s;
  1244. }
  1245. case TRANSFORM_TRANSLATE: {
  1246. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1247. p_motion.snapf(p_extra);
  1248. }
  1249. if (p_local) {
  1250. return p_original_local.translated_local(p_motion);
  1251. }
  1252. return p_original.translated(p_motion);
  1253. }
  1254. case TRANSFORM_ROTATE: {
  1255. Transform3D r;
  1256. if (p_local) {
  1257. Vector3 axis = p_original_local.basis.xform(p_motion);
  1258. r.basis = Basis(axis.normalized(), p_extra) * p_original_local.basis;
  1259. r.origin = p_original_local.origin;
  1260. } else {
  1261. Basis local = p_original.basis * p_original_local.basis.inverse();
  1262. Vector3 axis = local.xform_inv(p_motion);
  1263. r.basis = local * Basis(axis.normalized(), p_extra) * p_original_local.basis;
  1264. r.origin = Basis(p_motion, p_extra).xform(p_original.origin - _edit.center) + _edit.center;
  1265. }
  1266. return r;
  1267. }
  1268. default: {
  1269. ERR_FAIL_V_MSG(Transform3D(), "Invalid mode in '_compute_transform'");
  1270. }
  1271. }
  1272. }
  1273. void Node3DEditorViewport::_surface_mouse_enter() {
  1274. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
  1275. return;
  1276. }
  1277. if (!surface->has_focus() && (!get_viewport()->gui_get_focus_owner() || !get_viewport()->gui_get_focus_owner()->is_text_field())) {
  1278. surface->grab_focus();
  1279. }
  1280. }
  1281. void Node3DEditorViewport::_surface_mouse_exit() {
  1282. _remove_preview_node();
  1283. _reset_preview_material();
  1284. _remove_preview_material();
  1285. }
  1286. void Node3DEditorViewport::_surface_focus_enter() {
  1287. view_menu->set_disable_shortcuts(false);
  1288. }
  1289. void Node3DEditorViewport::_surface_focus_exit() {
  1290. view_menu->set_disable_shortcuts(true);
  1291. }
  1292. bool Node3DEditorViewport ::_is_node_locked(const Node *p_node) {
  1293. return p_node->get_meta("_edit_lock_", false);
  1294. }
  1295. void Node3DEditorViewport::_list_select(Ref<InputEventMouseButton> b) {
  1296. Vector<_RayResult> potential_selection_results;
  1297. _find_items_at_pos(b->get_position(), potential_selection_results, spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT);
  1298. Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
  1299. // Filter to a list of nodes which include either the edited scene or nodes directly owned by the edited scene.
  1300. // If a node has an invalid owner, recursively check their parents until a valid node is found.
  1301. for (int i = 0; i < potential_selection_results.size(); i++) {
  1302. Node3D *node = potential_selection_results[i].item;
  1303. while (true) {
  1304. if (node == nullptr || node == edited_scene->get_parent()) {
  1305. break;
  1306. } else {
  1307. Node *node_owner = node->get_owner();
  1308. if (node == edited_scene || node_owner == edited_scene || (node_owner != nullptr && edited_scene->is_editable_instance(node_owner))) {
  1309. if (selection_results.has(node)) {
  1310. selection_results.append(node);
  1311. }
  1312. break;
  1313. }
  1314. }
  1315. node = Object::cast_to<Node3D>(node->get_parent());
  1316. }
  1317. }
  1318. clicked_wants_append = b->is_shift_pressed();
  1319. if (selection_results.size() == 1) {
  1320. clicked = selection_results[0]->get_instance_id();
  1321. selection_results.clear();
  1322. if (clicked.is_valid()) {
  1323. _select_clicked(spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT);
  1324. }
  1325. } else if (!selection_results.is_empty()) {
  1326. NodePath root_path = get_tree()->get_edited_scene_root()->get_path();
  1327. StringName root_name = root_path.get_name(root_path.get_name_count() - 1);
  1328. for (int i = 0; i < selection_results.size(); i++) {
  1329. Node3D *spat = selection_results[i];
  1330. Ref<Texture2D> icon = EditorNode::get_singleton()->get_object_icon(spat, "Node");
  1331. String node_path = "/" + root_name + "/" + root_path.rel_path_to(spat->get_path());
  1332. int locked = 0;
  1333. if (_is_node_locked(spat)) {
  1334. locked = 1;
  1335. } else {
  1336. Node *ed_scene = EditorNode::get_singleton()->get_edited_scene();
  1337. Node *node = spat;
  1338. while (node && node != ed_scene->get_parent()) {
  1339. Node3D *selected_tmp = Object::cast_to<Node3D>(node);
  1340. if (selected_tmp && node->has_meta("_edit_group_")) {
  1341. locked = 2;
  1342. }
  1343. node = node->get_parent();
  1344. }
  1345. }
  1346. String suffix;
  1347. if (locked == 1) {
  1348. suffix = " (" + TTR("Locked") + ")";
  1349. } else if (locked == 2) {
  1350. suffix = " (" + TTR("Grouped") + ")";
  1351. }
  1352. selection_menu->add_item((String)spat->get_name() + suffix);
  1353. selection_menu->set_item_icon(i, icon);
  1354. selection_menu->set_item_metadata(i, node_path);
  1355. selection_menu->set_item_tooltip(i, String(spat->get_name()) + "\nType: " + spat->get_class() + "\nPath: " + node_path);
  1356. }
  1357. selection_results_menu = selection_results;
  1358. selection_menu->set_position(get_screen_position() + b->get_position());
  1359. selection_menu->reset_size();
  1360. selection_menu->popup();
  1361. }
  1362. }
  1363. // This is only active during instant transforms,
  1364. // to capture and wrap mouse events outside the control.
  1365. void Node3DEditorViewport::input(const Ref<InputEvent> &p_event) {
  1366. ERR_FAIL_COND(!_edit.instant);
  1367. Ref<InputEventMouseMotion> m = p_event;
  1368. if (m.is_valid()) {
  1369. if (_edit.mode == TRANSFORM_ROTATE) {
  1370. _edit.mouse_pos = m->get_position(); // rotate should not wrap
  1371. } else {
  1372. _edit.mouse_pos += _get_warped_mouse_motion(p_event);
  1373. }
  1374. update_transform(_get_key_modifier(m) == Key::SHIFT);
  1375. }
  1376. }
  1377. void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
  1378. if (previewing) {
  1379. return; //do NONE
  1380. }
  1381. EditorPlugin::AfterGUIInput after = EditorPlugin::AFTER_GUI_INPUT_PASS;
  1382. {
  1383. EditorNode *en = EditorNode::get_singleton();
  1384. EditorPluginList *force_input_forwarding_list = en->get_editor_plugins_force_input_forwarding();
  1385. if (!force_input_forwarding_list->is_empty()) {
  1386. EditorPlugin::AfterGUIInput discard = force_input_forwarding_list->forward_3d_gui_input(camera, p_event, true);
  1387. if (discard == EditorPlugin::AFTER_GUI_INPUT_STOP) {
  1388. return;
  1389. }
  1390. if (discard == EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
  1391. after = EditorPlugin::AFTER_GUI_INPUT_CUSTOM;
  1392. }
  1393. }
  1394. }
  1395. {
  1396. EditorNode *en = EditorNode::get_singleton();
  1397. EditorPluginList *over_plugin_list = en->get_editor_plugins_over();
  1398. if (!over_plugin_list->is_empty()) {
  1399. EditorPlugin::AfterGUIInput discard = over_plugin_list->forward_3d_gui_input(camera, p_event, false);
  1400. if (discard == EditorPlugin::AFTER_GUI_INPUT_STOP) {
  1401. return;
  1402. }
  1403. if (discard == EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
  1404. after = EditorPlugin::AFTER_GUI_INPUT_CUSTOM;
  1405. }
  1406. }
  1407. }
  1408. Ref<InputEventMouseButton> b = p_event;
  1409. if (b.is_valid()) {
  1410. emit_signal(SNAME("clicked"), this);
  1411. const real_t zoom_factor = 1 + (ZOOM_FREELOOK_MULTIPLIER - 1) * b->get_factor();
  1412. switch (b->get_button_index()) {
  1413. case MouseButton::WHEEL_UP: {
  1414. if (is_freelook_active()) {
  1415. scale_freelook_speed(zoom_factor);
  1416. } else {
  1417. scale_cursor_distance(1.0 / zoom_factor);
  1418. }
  1419. } break;
  1420. case MouseButton::WHEEL_DOWN: {
  1421. if (is_freelook_active()) {
  1422. scale_freelook_speed(1.0 / zoom_factor);
  1423. } else {
  1424. scale_cursor_distance(zoom_factor);
  1425. }
  1426. } break;
  1427. case MouseButton::RIGHT: {
  1428. NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
  1429. if (b->is_pressed() && _edit.gizmo.is_valid()) {
  1430. //restore
  1431. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, _edit.gizmo_initial_value, true);
  1432. _edit.gizmo = Ref<EditorNode3DGizmo>();
  1433. }
  1434. if (_edit.mode == TRANSFORM_NONE && b->is_pressed()) {
  1435. if (b->is_alt_pressed()) {
  1436. if (nav_scheme == NAVIGATION_MAYA) {
  1437. break;
  1438. }
  1439. _list_select(b);
  1440. return;
  1441. }
  1442. }
  1443. if (_edit.mode != TRANSFORM_NONE && b->is_pressed()) {
  1444. cancel_transform();
  1445. break;
  1446. }
  1447. if (b->is_pressed()) {
  1448. const Key mod = _get_key_modifier(b);
  1449. if (!orthogonal) {
  1450. if (mod == _get_key_modifier_setting("editors/3d/freelook/freelook_activation_modifier")) {
  1451. set_freelook_active(true);
  1452. }
  1453. }
  1454. } else {
  1455. set_freelook_active(false);
  1456. }
  1457. if (freelook_active && !surface->has_focus()) {
  1458. // Focus usually doesn't trigger on right-click, but in case of freelook it should,
  1459. // otherwise using keyboard navigation would misbehave
  1460. surface->grab_focus();
  1461. }
  1462. } break;
  1463. case MouseButton::MIDDLE: {
  1464. if (b->is_pressed() && _edit.mode != TRANSFORM_NONE) {
  1465. switch (_edit.plane) {
  1466. case TRANSFORM_VIEW: {
  1467. _edit.plane = TRANSFORM_X_AXIS;
  1468. set_message(TTR("X-Axis Transform."), 2);
  1469. view_type = VIEW_TYPE_USER;
  1470. _update_name();
  1471. } break;
  1472. case TRANSFORM_X_AXIS: {
  1473. _edit.plane = TRANSFORM_Y_AXIS;
  1474. set_message(TTR("Y-Axis Transform."), 2);
  1475. } break;
  1476. case TRANSFORM_Y_AXIS: {
  1477. _edit.plane = TRANSFORM_Z_AXIS;
  1478. set_message(TTR("Z-Axis Transform."), 2);
  1479. } break;
  1480. case TRANSFORM_Z_AXIS: {
  1481. _edit.plane = TRANSFORM_VIEW;
  1482. // TRANSLATORS: This refers to the transform of the view plane.
  1483. set_message(TTR("View Plane Transform."), 2);
  1484. } break;
  1485. case TRANSFORM_YZ:
  1486. case TRANSFORM_XZ:
  1487. case TRANSFORM_XY: {
  1488. } break;
  1489. }
  1490. }
  1491. } break;
  1492. case MouseButton::LEFT: {
  1493. if (b->is_pressed()) {
  1494. clicked_wants_append = b->is_shift_pressed();
  1495. if (_edit.mode != TRANSFORM_NONE && _edit.instant) {
  1496. commit_transform();
  1497. break; // just commit the edit, stop processing the event so we don't deselect the object
  1498. }
  1499. NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
  1500. if ((nav_scheme == NAVIGATION_MAYA || nav_scheme == NAVIGATION_MODO) && b->is_alt_pressed()) {
  1501. break;
  1502. }
  1503. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_LIST_SELECT) {
  1504. _list_select(b);
  1505. break;
  1506. }
  1507. _edit.mouse_pos = b->get_position();
  1508. _edit.original_mouse_pos = b->get_position();
  1509. _edit.snap = spatial_editor->is_snap_enabled();
  1510. _edit.mode = TRANSFORM_NONE;
  1511. _edit.original = spatial_editor->get_gizmo_transform(); // To prevent to break when flipping with scale.
  1512. bool can_select_gizmos = spatial_editor->get_single_selected_node();
  1513. {
  1514. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  1515. can_select_gizmos = can_select_gizmos && view_menu->get_popup()->is_item_checked(idx);
  1516. }
  1517. // Gizmo handles
  1518. if (can_select_gizmos) {
  1519. Vector<Ref<Node3DGizmo>> gizmos = spatial_editor->get_single_selected_node()->get_gizmos();
  1520. bool intersected_handle = false;
  1521. for (int i = 0; i < gizmos.size(); i++) {
  1522. Ref<EditorNode3DGizmo> seg = gizmos[i];
  1523. if ((!seg.is_valid())) {
  1524. continue;
  1525. }
  1526. int gizmo_handle = -1;
  1527. bool gizmo_secondary = false;
  1528. seg->handles_intersect_ray(camera, _edit.mouse_pos, b->is_shift_pressed(), gizmo_handle, gizmo_secondary);
  1529. if (gizmo_handle != -1) {
  1530. _edit.gizmo = seg;
  1531. seg->begin_handle_action(gizmo_handle, gizmo_secondary);
  1532. _edit.gizmo_handle = gizmo_handle;
  1533. _edit.gizmo_handle_secondary = gizmo_secondary;
  1534. _edit.gizmo_initial_value = seg->get_handle_value(gizmo_handle, gizmo_secondary);
  1535. intersected_handle = true;
  1536. break;
  1537. }
  1538. }
  1539. if (intersected_handle) {
  1540. break;
  1541. }
  1542. }
  1543. // Transform gizmo
  1544. if (_transform_gizmo_select(_edit.mouse_pos)) {
  1545. break;
  1546. }
  1547. // Subgizmos
  1548. if (can_select_gizmos) {
  1549. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(spatial_editor->get_single_selected_node());
  1550. Vector<Ref<Node3DGizmo>> gizmos = spatial_editor->get_single_selected_node()->get_gizmos();
  1551. bool intersected_subgizmo = false;
  1552. for (int i = 0; i < gizmos.size(); i++) {
  1553. Ref<EditorNode3DGizmo> seg = gizmos[i];
  1554. if ((!seg.is_valid())) {
  1555. continue;
  1556. }
  1557. int subgizmo_id = seg->subgizmos_intersect_ray(camera, _edit.mouse_pos);
  1558. if (subgizmo_id != -1) {
  1559. ERR_CONTINUE(!se);
  1560. if (b->is_shift_pressed()) {
  1561. if (se->subgizmos.has(subgizmo_id)) {
  1562. se->subgizmos.erase(subgizmo_id);
  1563. } else {
  1564. se->subgizmos.insert(subgizmo_id, seg->get_subgizmo_transform(subgizmo_id));
  1565. }
  1566. } else {
  1567. se->subgizmos.clear();
  1568. se->subgizmos.insert(subgizmo_id, seg->get_subgizmo_transform(subgizmo_id));
  1569. }
  1570. if (se->subgizmos.is_empty()) {
  1571. se->gizmo = Ref<EditorNode3DGizmo>();
  1572. } else {
  1573. se->gizmo = seg;
  1574. }
  1575. seg->redraw();
  1576. spatial_editor->update_transform_gizmo();
  1577. intersected_subgizmo = true;
  1578. break;
  1579. }
  1580. }
  1581. if (intersected_subgizmo) {
  1582. break;
  1583. }
  1584. }
  1585. clicked = ObjectID();
  1586. bool node_selected = get_selected_count() > 0;
  1587. if (node_selected && ((spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT && b->is_command_or_control_pressed()) || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE)) {
  1588. begin_transform(TRANSFORM_ROTATE, false);
  1589. break;
  1590. }
  1591. if (node_selected && spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE) {
  1592. begin_transform(TRANSFORM_TRANSLATE, false);
  1593. break;
  1594. }
  1595. if (node_selected && spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE) {
  1596. begin_transform(TRANSFORM_SCALE, false);
  1597. break;
  1598. }
  1599. if (after != EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
  1600. //clicking is always deferred to either move or release
  1601. clicked = _select_ray(b->get_position());
  1602. selection_in_progress = true;
  1603. if (clicked.is_null()) {
  1604. //default to regionselect
  1605. cursor.region_select = true;
  1606. cursor.region_begin = b->get_position();
  1607. cursor.region_end = b->get_position();
  1608. }
  1609. }
  1610. surface->queue_redraw();
  1611. } else {
  1612. if (_edit.gizmo.is_valid()) {
  1613. if (_edit.original_mouse_pos != _edit.mouse_pos) {
  1614. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, _edit.gizmo_initial_value, false);
  1615. }
  1616. _edit.gizmo = Ref<EditorNode3DGizmo>();
  1617. break;
  1618. }
  1619. if (after != EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
  1620. selection_in_progress = false;
  1621. if (clicked.is_valid()) {
  1622. _select_clicked(false);
  1623. }
  1624. if (cursor.region_select) {
  1625. _select_region();
  1626. cursor.region_select = false;
  1627. surface->queue_redraw();
  1628. }
  1629. }
  1630. if (_edit.mode != TRANSFORM_NONE) {
  1631. Node3D *selected = spatial_editor->get_single_selected_node();
  1632. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  1633. if (se && se->gizmo.is_valid()) {
  1634. Vector<int> ids;
  1635. Vector<Transform3D> restore;
  1636. for (const KeyValue<int, Transform3D> &GE : se->subgizmos) {
  1637. ids.push_back(GE.key);
  1638. restore.push_back(GE.value);
  1639. }
  1640. se->gizmo->commit_subgizmos(ids, restore, false);
  1641. } else {
  1642. if (_edit.original_mouse_pos != _edit.mouse_pos) {
  1643. commit_transform();
  1644. }
  1645. }
  1646. _edit.mode = TRANSFORM_NONE;
  1647. set_message("");
  1648. spatial_editor->update_transform_gizmo();
  1649. }
  1650. surface->queue_redraw();
  1651. }
  1652. } break;
  1653. default:
  1654. break;
  1655. }
  1656. }
  1657. Ref<InputEventMouseMotion> m = p_event;
  1658. // Instant transforms process mouse motion in input() to handle wrapping.
  1659. if (m.is_valid() && !_edit.instant) {
  1660. _edit.mouse_pos = m->get_position();
  1661. if (spatial_editor->get_single_selected_node()) {
  1662. Vector<Ref<Node3DGizmo>> gizmos = spatial_editor->get_single_selected_node()->get_gizmos();
  1663. Ref<EditorNode3DGizmo> found_gizmo;
  1664. int found_handle = -1;
  1665. bool found_handle_secondary = false;
  1666. for (int i = 0; i < gizmos.size(); i++) {
  1667. Ref<EditorNode3DGizmo> seg = gizmos[i];
  1668. if (!seg.is_valid()) {
  1669. continue;
  1670. }
  1671. seg->handles_intersect_ray(camera, _edit.mouse_pos, false, found_handle, found_handle_secondary);
  1672. if (found_handle != -1) {
  1673. found_gizmo = seg;
  1674. break;
  1675. }
  1676. }
  1677. if (found_gizmo.is_valid()) {
  1678. spatial_editor->select_gizmo_highlight_axis(-1);
  1679. }
  1680. bool current_hover_handle_secondary = false;
  1681. int curreny_hover_handle = spatial_editor->get_current_hover_gizmo_handle(current_hover_handle_secondary);
  1682. if (found_gizmo != spatial_editor->get_current_hover_gizmo() || found_handle != curreny_hover_handle || found_handle_secondary != current_hover_handle_secondary) {
  1683. spatial_editor->set_current_hover_gizmo(found_gizmo);
  1684. spatial_editor->set_current_hover_gizmo_handle(found_handle, found_handle_secondary);
  1685. spatial_editor->get_single_selected_node()->update_gizmos();
  1686. }
  1687. }
  1688. if (spatial_editor->get_current_hover_gizmo().is_null() && !m->get_button_mask().has_flag(MouseButtonMask::LEFT) && !_edit.gizmo.is_valid()) {
  1689. _transform_gizmo_select(_edit.mouse_pos, true);
  1690. }
  1691. NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
  1692. NavigationMode nav_mode = NAVIGATION_NONE;
  1693. if (_edit.gizmo.is_valid()) {
  1694. _edit.gizmo->set_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, camera, m->get_position());
  1695. Variant v = _edit.gizmo->get_handle_value(_edit.gizmo_handle, _edit.gizmo_handle_secondary);
  1696. String n = _edit.gizmo->get_handle_name(_edit.gizmo_handle, _edit.gizmo_handle_secondary);
  1697. set_message(n + ": " + String(v));
  1698. } else if (m->get_button_mask().has_flag(MouseButtonMask::LEFT)) {
  1699. if (nav_scheme == NAVIGATION_MAYA && m->is_alt_pressed()) {
  1700. nav_mode = NAVIGATION_ORBIT;
  1701. } else if (nav_scheme == NAVIGATION_MODO && m->is_alt_pressed() && m->is_shift_pressed()) {
  1702. nav_mode = NAVIGATION_PAN;
  1703. } else if (nav_scheme == NAVIGATION_MODO && m->is_alt_pressed() && m->is_command_or_control_pressed()) {
  1704. nav_mode = NAVIGATION_ZOOM;
  1705. } else if (nav_scheme == NAVIGATION_MODO && m->is_alt_pressed()) {
  1706. nav_mode = NAVIGATION_ORBIT;
  1707. } else {
  1708. const bool movement_threshold_passed = _edit.original_mouse_pos.distance_to(_edit.mouse_pos) > 8 * EDSCALE;
  1709. if (selection_in_progress && movement_threshold_passed && clicked.is_valid()) {
  1710. if (clicked_wants_append || !editor_selection->is_selected(Object::cast_to<Node>(ObjectDB::get_instance(clicked)))) {
  1711. cursor.region_select = true;
  1712. cursor.region_begin = _edit.original_mouse_pos;
  1713. clicked = ObjectID();
  1714. }
  1715. }
  1716. if (cursor.region_select) {
  1717. cursor.region_end = m->get_position();
  1718. surface->queue_redraw();
  1719. return;
  1720. }
  1721. if (clicked.is_valid() && movement_threshold_passed) {
  1722. _compute_edit(_edit.original_mouse_pos);
  1723. clicked = ObjectID();
  1724. _edit.mode = TRANSFORM_TRANSLATE;
  1725. }
  1726. if (_edit.mode == TRANSFORM_NONE || _edit.numeric_input != 0 || _edit.numeric_next_decimal != 0) {
  1727. return;
  1728. }
  1729. update_transform(_get_key_modifier(m) == Key::SHIFT);
  1730. }
  1731. } else if (m->get_button_mask().has_flag(MouseButtonMask::RIGHT) || freelook_active) {
  1732. if (nav_scheme == NAVIGATION_MAYA && m->is_alt_pressed()) {
  1733. nav_mode = NAVIGATION_ZOOM;
  1734. } else if (freelook_active) {
  1735. nav_mode = NAVIGATION_LOOK;
  1736. } else if (orthogonal) {
  1737. nav_mode = NAVIGATION_PAN;
  1738. }
  1739. } else if (m->get_button_mask().has_flag(MouseButtonMask::MIDDLE)) {
  1740. const Key mod = _get_key_modifier(m);
  1741. if (nav_scheme == NAVIGATION_GODOT) {
  1742. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1743. nav_mode = NAVIGATION_PAN;
  1744. } else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier")) {
  1745. nav_mode = NAVIGATION_ZOOM;
  1746. } else if (mod == Key::ALT || mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier")) {
  1747. // Always allow Alt as a modifier to better support graphic tablets.
  1748. nav_mode = NAVIGATION_ORBIT;
  1749. }
  1750. } else if (nav_scheme == NAVIGATION_MAYA) {
  1751. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1752. nav_mode = NAVIGATION_PAN;
  1753. }
  1754. }
  1755. } else if (EDITOR_GET("editors/3d/navigation/emulate_3_button_mouse")) {
  1756. // Handle trackpad (no external mouse) use case
  1757. const Key mod = _get_key_modifier(m);
  1758. if (mod != Key::NONE) {
  1759. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1760. nav_mode = NAVIGATION_PAN;
  1761. } else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier")) {
  1762. nav_mode = NAVIGATION_ZOOM;
  1763. } else if (mod == Key::ALT || mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier")) {
  1764. // Always allow Alt as a modifier to better support graphic tablets.
  1765. nav_mode = NAVIGATION_ORBIT;
  1766. }
  1767. }
  1768. }
  1769. switch (nav_mode) {
  1770. case NAVIGATION_PAN: {
  1771. _nav_pan(m, _get_warped_mouse_motion(m));
  1772. } break;
  1773. case NAVIGATION_ZOOM: {
  1774. _nav_zoom(m, m->get_relative());
  1775. } break;
  1776. case NAVIGATION_ORBIT: {
  1777. _nav_orbit(m, _get_warped_mouse_motion(m));
  1778. } break;
  1779. case NAVIGATION_LOOK: {
  1780. _nav_look(m, _get_warped_mouse_motion(m));
  1781. } break;
  1782. default: {
  1783. }
  1784. }
  1785. }
  1786. Ref<InputEventMagnifyGesture> magnify_gesture = p_event;
  1787. if (magnify_gesture.is_valid()) {
  1788. if (is_freelook_active()) {
  1789. scale_freelook_speed(magnify_gesture->get_factor());
  1790. } else {
  1791. scale_cursor_distance(1.0 / magnify_gesture->get_factor());
  1792. }
  1793. }
  1794. Ref<InputEventPanGesture> pan_gesture = p_event;
  1795. if (pan_gesture.is_valid()) {
  1796. NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
  1797. NavigationMode nav_mode = NAVIGATION_NONE;
  1798. if (nav_scheme == NAVIGATION_GODOT) {
  1799. const Key mod = _get_key_modifier(pan_gesture);
  1800. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1801. nav_mode = NAVIGATION_PAN;
  1802. } else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier")) {
  1803. nav_mode = NAVIGATION_ZOOM;
  1804. } else if (mod == Key::ALT || mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier")) {
  1805. // Always allow Alt as a modifier to better support graphic tablets.
  1806. nav_mode = NAVIGATION_ORBIT;
  1807. }
  1808. } else if (nav_scheme == NAVIGATION_MAYA) {
  1809. if (pan_gesture->is_alt_pressed()) {
  1810. nav_mode = NAVIGATION_PAN;
  1811. }
  1812. }
  1813. switch (nav_mode) {
  1814. case NAVIGATION_PAN: {
  1815. _nav_pan(pan_gesture, -pan_gesture->get_delta());
  1816. } break;
  1817. case NAVIGATION_ZOOM: {
  1818. _nav_zoom(pan_gesture, pan_gesture->get_delta());
  1819. } break;
  1820. case NAVIGATION_ORBIT: {
  1821. _nav_orbit(pan_gesture, -pan_gesture->get_delta());
  1822. } break;
  1823. case NAVIGATION_LOOK: {
  1824. _nav_look(pan_gesture, pan_gesture->get_delta());
  1825. } break;
  1826. default: {
  1827. }
  1828. }
  1829. }
  1830. Ref<InputEventKey> k = p_event;
  1831. if (k.is_valid()) {
  1832. if (!k->is_pressed()) {
  1833. return;
  1834. }
  1835. if (_edit.instant) {
  1836. // In a Blender-style transform, numbers set the magnitude of the transform.
  1837. // E.g. pressing g4.5x means "translate 4.5 units along the X axis".
  1838. // Use the Unicode value because we care about the text, not the actual keycode.
  1839. // This ensures numbers work consistently across different keyboard language layouts.
  1840. bool processed = true;
  1841. Key key = k->get_physical_keycode();
  1842. char32_t unicode = k->get_unicode();
  1843. if (unicode >= '0' && unicode <= '9') {
  1844. uint32_t value = uint32_t(unicode - Key::KEY_0);
  1845. if (_edit.numeric_next_decimal < 0) {
  1846. _edit.numeric_input = _edit.numeric_input + value * Math::pow(10.0, _edit.numeric_next_decimal--);
  1847. } else {
  1848. _edit.numeric_input = _edit.numeric_input * 10 + value;
  1849. }
  1850. update_transform_numeric();
  1851. } else if (unicode == '-') {
  1852. _edit.numeric_negate = !_edit.numeric_negate;
  1853. update_transform_numeric();
  1854. } else if (unicode == '.') {
  1855. if (_edit.numeric_next_decimal == 0) {
  1856. _edit.numeric_next_decimal = -1;
  1857. }
  1858. } else if (key == Key::ENTER || key == Key::KP_ENTER || key == Key::SPACE) {
  1859. commit_transform();
  1860. } else {
  1861. processed = false;
  1862. }
  1863. if (processed) {
  1864. // Ignore mouse inputs once we receive a numeric input.
  1865. set_process_input(false);
  1866. accept_event();
  1867. return;
  1868. }
  1869. }
  1870. if (EDITOR_GET("editors/3d/navigation/emulate_numpad")) {
  1871. const Key code = k->get_physical_keycode();
  1872. if (code >= Key::KEY_0 && code <= Key::KEY_9) {
  1873. k->set_keycode(code - Key::KEY_0 + Key::KP_0);
  1874. }
  1875. }
  1876. if (_edit.mode == TRANSFORM_NONE) {
  1877. if (_edit.gizmo.is_valid() && (k->get_keycode() == Key::ESCAPE || k->get_keycode() == Key::BACKSPACE)) {
  1878. // Restore.
  1879. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, _edit.gizmo_initial_value, true);
  1880. _edit.gizmo = Ref<EditorNode3DGizmo>();
  1881. }
  1882. if (k->get_keycode() == Key::ESCAPE && !cursor.region_select) {
  1883. _clear_selected();
  1884. return;
  1885. }
  1886. } else {
  1887. // We're actively transforming, handle keys specially
  1888. TransformPlane new_plane = TRANSFORM_VIEW;
  1889. if (ED_IS_SHORTCUT("spatial_editor/lock_transform_x", p_event)) {
  1890. new_plane = TRANSFORM_X_AXIS;
  1891. } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_y", p_event)) {
  1892. new_plane = TRANSFORM_Y_AXIS;
  1893. } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_z", p_event)) {
  1894. new_plane = TRANSFORM_Z_AXIS;
  1895. } else if (_edit.mode != TRANSFORM_ROTATE) { // rotating on a plane doesn't make sense
  1896. if (ED_IS_SHORTCUT("spatial_editor/lock_transform_yz", p_event)) {
  1897. new_plane = TRANSFORM_YZ;
  1898. } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_xz", p_event)) {
  1899. new_plane = TRANSFORM_XZ;
  1900. } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_xy", p_event)) {
  1901. new_plane = TRANSFORM_XY;
  1902. }
  1903. }
  1904. if (new_plane != TRANSFORM_VIEW) {
  1905. if (new_plane != _edit.plane) {
  1906. // lock me once and get a global constraint
  1907. _edit.plane = new_plane;
  1908. spatial_editor->set_local_coords_enabled(false);
  1909. } else if (!spatial_editor->are_local_coords_enabled()) {
  1910. // lock me twice and get a local constraint
  1911. spatial_editor->set_local_coords_enabled(true);
  1912. } else {
  1913. // lock me thrice and we're back where we started
  1914. _edit.plane = TRANSFORM_VIEW;
  1915. spatial_editor->set_local_coords_enabled(false);
  1916. }
  1917. if (_edit.numeric_input != 0 || _edit.numeric_next_decimal != 0) {
  1918. update_transform_numeric();
  1919. } else {
  1920. update_transform(Input::get_singleton()->is_key_pressed(Key::SHIFT));
  1921. }
  1922. accept_event();
  1923. return;
  1924. }
  1925. }
  1926. if (ED_IS_SHORTCUT("spatial_editor/snap", p_event)) {
  1927. if (_edit.mode != TRANSFORM_NONE) {
  1928. _edit.snap = !_edit.snap;
  1929. }
  1930. }
  1931. if (ED_IS_SHORTCUT("spatial_editor/bottom_view", p_event)) {
  1932. _menu_option(VIEW_BOTTOM);
  1933. }
  1934. if (ED_IS_SHORTCUT("spatial_editor/top_view", p_event)) {
  1935. _menu_option(VIEW_TOP);
  1936. }
  1937. if (ED_IS_SHORTCUT("spatial_editor/rear_view", p_event)) {
  1938. _menu_option(VIEW_REAR);
  1939. }
  1940. if (ED_IS_SHORTCUT("spatial_editor/front_view", p_event)) {
  1941. _menu_option(VIEW_FRONT);
  1942. }
  1943. if (ED_IS_SHORTCUT("spatial_editor/left_view", p_event)) {
  1944. _menu_option(VIEW_LEFT);
  1945. }
  1946. if (ED_IS_SHORTCUT("spatial_editor/right_view", p_event)) {
  1947. _menu_option(VIEW_RIGHT);
  1948. }
  1949. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_down", p_event)) {
  1950. // Clamp rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  1951. cursor.x_rot = CLAMP(cursor.x_rot - Math_PI / 12.0, -1.57, 1.57);
  1952. view_type = VIEW_TYPE_USER;
  1953. _update_name();
  1954. }
  1955. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_up", p_event)) {
  1956. // Clamp rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  1957. cursor.x_rot = CLAMP(cursor.x_rot + Math_PI / 12.0, -1.57, 1.57);
  1958. view_type = VIEW_TYPE_USER;
  1959. _update_name();
  1960. }
  1961. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_right", p_event)) {
  1962. cursor.y_rot -= Math_PI / 12.0;
  1963. view_type = VIEW_TYPE_USER;
  1964. _update_name();
  1965. }
  1966. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_left", p_event)) {
  1967. cursor.y_rot += Math_PI / 12.0;
  1968. view_type = VIEW_TYPE_USER;
  1969. _update_name();
  1970. }
  1971. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_180", p_event)) {
  1972. cursor.y_rot += Math_PI;
  1973. view_type = VIEW_TYPE_USER;
  1974. _update_name();
  1975. }
  1976. if (ED_IS_SHORTCUT("spatial_editor/focus_origin", p_event)) {
  1977. _menu_option(VIEW_CENTER_TO_ORIGIN);
  1978. }
  1979. if (ED_IS_SHORTCUT("spatial_editor/focus_selection", p_event)) {
  1980. _menu_option(VIEW_CENTER_TO_SELECTION);
  1981. }
  1982. if (ED_IS_SHORTCUT("spatial_editor/align_transform_with_view", p_event)) {
  1983. _menu_option(VIEW_ALIGN_TRANSFORM_WITH_VIEW);
  1984. }
  1985. if (ED_IS_SHORTCUT("spatial_editor/align_rotation_with_view", p_event)) {
  1986. _menu_option(VIEW_ALIGN_ROTATION_WITH_VIEW);
  1987. }
  1988. if (ED_IS_SHORTCUT("spatial_editor/insert_anim_key", p_event)) {
  1989. if (!get_selected_count() || _edit.mode != TRANSFORM_NONE) {
  1990. return;
  1991. }
  1992. if (!AnimationPlayerEditor::get_singleton()->get_track_editor()->has_keying()) {
  1993. set_message(TTR("Keying is disabled (no key inserted)."));
  1994. return;
  1995. }
  1996. List<Node *> &selection = editor_selection->get_selected_node_list();
  1997. for (Node *E : selection) {
  1998. Node3D *sp = Object::cast_to<Node3D>(E);
  1999. if (!sp) {
  2000. continue;
  2001. }
  2002. spatial_editor->emit_signal(SNAME("transform_key_request"), sp, "", sp->get_transform());
  2003. }
  2004. set_message(TTR("Animation Key Inserted."));
  2005. }
  2006. if (ED_IS_SHORTCUT("spatial_editor/cancel_transform", p_event) && _edit.mode != TRANSFORM_NONE) {
  2007. cancel_transform();
  2008. }
  2009. if (!is_freelook_active()) {
  2010. if (ED_IS_SHORTCUT("spatial_editor/instant_translate", p_event)) {
  2011. begin_transform(TRANSFORM_TRANSLATE, true);
  2012. }
  2013. if (ED_IS_SHORTCUT("spatial_editor/instant_rotate", p_event)) {
  2014. begin_transform(TRANSFORM_ROTATE, true);
  2015. }
  2016. if (ED_IS_SHORTCUT("spatial_editor/instant_scale", p_event)) {
  2017. begin_transform(TRANSFORM_SCALE, true);
  2018. }
  2019. }
  2020. // Freelook doesn't work in orthogonal mode.
  2021. if (!orthogonal && ED_IS_SHORTCUT("spatial_editor/freelook_toggle", p_event)) {
  2022. set_freelook_active(!is_freelook_active());
  2023. } else if (k->get_keycode() == Key::ESCAPE) {
  2024. set_freelook_active(false);
  2025. }
  2026. if (k->get_keycode() == Key::SPACE) {
  2027. if (!k->is_pressed()) {
  2028. emit_signal(SNAME("toggle_maximize_view"), this);
  2029. }
  2030. }
  2031. if (ED_IS_SHORTCUT("spatial_editor/decrease_fov", p_event)) {
  2032. scale_fov(-0.05);
  2033. }
  2034. if (ED_IS_SHORTCUT("spatial_editor/increase_fov", p_event)) {
  2035. scale_fov(0.05);
  2036. }
  2037. if (ED_IS_SHORTCUT("spatial_editor/reset_fov", p_event)) {
  2038. reset_fov();
  2039. }
  2040. }
  2041. // freelook uses most of the useful shortcuts, like save, so its ok
  2042. // to consider freelook active as end of the line for future events.
  2043. if (freelook_active) {
  2044. accept_event();
  2045. }
  2046. }
  2047. void Node3DEditorViewport::_nav_pan(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  2048. const NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
  2049. real_t pan_speed = 1 / 150.0;
  2050. if (p_event.is_valid() && nav_scheme == NAVIGATION_MAYA && p_event->is_shift_pressed()) {
  2051. pan_speed *= 10;
  2052. }
  2053. Transform3D camera_transform;
  2054. camera_transform.translate_local(cursor.pos);
  2055. camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
  2056. camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
  2057. const bool invert_x_axis = EDITOR_GET("editors/3d/navigation/invert_x_axis");
  2058. const bool invert_y_axis = EDITOR_GET("editors/3d/navigation/invert_y_axis");
  2059. Vector3 translation(
  2060. (invert_x_axis ? -1 : 1) * -p_relative.x * pan_speed,
  2061. (invert_y_axis ? -1 : 1) * p_relative.y * pan_speed,
  2062. 0);
  2063. translation *= cursor.distance / DISTANCE_DEFAULT;
  2064. camera_transform.translate_local(translation);
  2065. cursor.pos = camera_transform.origin;
  2066. }
  2067. void Node3DEditorViewport::_nav_zoom(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  2068. const NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
  2069. real_t zoom_speed = 1 / 80.0;
  2070. if (p_event.is_valid() && nav_scheme == NAVIGATION_MAYA && p_event->is_shift_pressed()) {
  2071. zoom_speed *= 10;
  2072. }
  2073. NavigationZoomStyle zoom_style = (NavigationZoomStyle)EDITOR_GET("editors/3d/navigation/zoom_style").operator int();
  2074. if (zoom_style == NAVIGATION_ZOOM_HORIZONTAL) {
  2075. if (p_relative.x > 0) {
  2076. scale_cursor_distance(1 - p_relative.x * zoom_speed);
  2077. } else if (p_relative.x < 0) {
  2078. scale_cursor_distance(1.0 / (1 + p_relative.x * zoom_speed));
  2079. }
  2080. } else {
  2081. if (p_relative.y > 0) {
  2082. scale_cursor_distance(1 + p_relative.y * zoom_speed);
  2083. } else if (p_relative.y < 0) {
  2084. scale_cursor_distance(1.0 / (1 - p_relative.y * zoom_speed));
  2085. }
  2086. }
  2087. }
  2088. void Node3DEditorViewport::_nav_orbit(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  2089. if (lock_rotation) {
  2090. _nav_pan(p_event, p_relative);
  2091. return;
  2092. }
  2093. if (orthogonal && auto_orthogonal) {
  2094. _menu_option(VIEW_PERSPECTIVE);
  2095. }
  2096. const real_t degrees_per_pixel = EDITOR_GET("editors/3d/navigation_feel/orbit_sensitivity");
  2097. const real_t radians_per_pixel = Math::deg_to_rad(degrees_per_pixel);
  2098. const bool invert_y_axis = EDITOR_GET("editors/3d/navigation/invert_y_axis");
  2099. const bool invert_x_axis = EDITOR_GET("editors/3d/navigation/invert_x_axis");
  2100. if (invert_y_axis) {
  2101. cursor.x_rot -= p_relative.y * radians_per_pixel;
  2102. } else {
  2103. cursor.x_rot += p_relative.y * radians_per_pixel;
  2104. }
  2105. // Clamp the Y rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  2106. cursor.x_rot = CLAMP(cursor.x_rot, -1.57, 1.57);
  2107. if (invert_x_axis) {
  2108. cursor.y_rot -= p_relative.x * radians_per_pixel;
  2109. } else {
  2110. cursor.y_rot += p_relative.x * radians_per_pixel;
  2111. }
  2112. view_type = VIEW_TYPE_USER;
  2113. _update_name();
  2114. }
  2115. void Node3DEditorViewport::_nav_look(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  2116. if (orthogonal) {
  2117. _nav_pan(p_event, p_relative);
  2118. return;
  2119. }
  2120. if (orthogonal && auto_orthogonal) {
  2121. _menu_option(VIEW_PERSPECTIVE);
  2122. }
  2123. // Scale mouse sensitivity with camera FOV scale when zoomed in to make it easier to point at things.
  2124. const real_t degrees_per_pixel = real_t(EDITOR_GET("editors/3d/freelook/freelook_sensitivity")) * MIN(1.0, cursor.fov_scale);
  2125. const real_t radians_per_pixel = Math::deg_to_rad(degrees_per_pixel);
  2126. const bool invert_y_axis = EDITOR_GET("editors/3d/navigation/invert_y_axis");
  2127. // Note: do NOT assume the camera has the "current" transform, because it is interpolated and may have "lag".
  2128. const Transform3D prev_camera_transform = to_camera_transform(cursor);
  2129. if (invert_y_axis) {
  2130. cursor.x_rot -= p_relative.y * radians_per_pixel;
  2131. } else {
  2132. cursor.x_rot += p_relative.y * radians_per_pixel;
  2133. }
  2134. // Clamp the Y rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  2135. cursor.x_rot = CLAMP(cursor.x_rot, -1.57, 1.57);
  2136. cursor.y_rot += p_relative.x * radians_per_pixel;
  2137. // Look is like the opposite of Orbit: the focus point rotates around the camera
  2138. Transform3D camera_transform = to_camera_transform(cursor);
  2139. Vector3 pos = camera_transform.xform(Vector3(0, 0, 0));
  2140. Vector3 prev_pos = prev_camera_transform.xform(Vector3(0, 0, 0));
  2141. Vector3 diff = prev_pos - pos;
  2142. cursor.pos += diff;
  2143. view_type = VIEW_TYPE_USER;
  2144. _update_name();
  2145. }
  2146. void Node3DEditorViewport::set_freelook_active(bool active_now) {
  2147. if (!freelook_active && active_now) {
  2148. // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
  2149. cursor = camera_cursor;
  2150. // Make sure eye_pos is synced, because freelook referential is eye pos rather than orbit pos
  2151. Vector3 forward = to_camera_transform(cursor).basis.xform(Vector3(0, 0, -1));
  2152. cursor.eye_pos = cursor.pos - cursor.distance * forward;
  2153. // Also sync the camera cursor, otherwise switching to freelook will be trippy if inertia is active
  2154. camera_cursor.eye_pos = cursor.eye_pos;
  2155. if (EDITOR_GET("editors/3d/freelook/freelook_speed_zoom_link")) {
  2156. // Re-adjust freelook speed from the current zoom level
  2157. real_t base_speed = EDITOR_GET("editors/3d/freelook/freelook_base_speed");
  2158. freelook_speed = base_speed * cursor.distance;
  2159. }
  2160. previous_mouse_position = get_local_mouse_position();
  2161. // Hide mouse like in an FPS (warping doesn't work)
  2162. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
  2163. } else if (freelook_active && !active_now) {
  2164. // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
  2165. cursor = camera_cursor;
  2166. // Restore mouse
  2167. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  2168. // Restore the previous mouse position when leaving freelook mode.
  2169. // This is done because leaving `Input.MOUSE_MODE_CAPTURED` will center the cursor
  2170. // due to OS limitations.
  2171. warp_mouse(previous_mouse_position);
  2172. }
  2173. freelook_active = active_now;
  2174. }
  2175. void Node3DEditorViewport::scale_fov(real_t p_fov_offset) {
  2176. cursor.fov_scale = CLAMP(cursor.fov_scale + p_fov_offset, 0.1, 2.5);
  2177. surface->queue_redraw();
  2178. }
  2179. void Node3DEditorViewport::reset_fov() {
  2180. cursor.fov_scale = 1.0;
  2181. surface->queue_redraw();
  2182. }
  2183. void Node3DEditorViewport::scale_cursor_distance(real_t scale) {
  2184. real_t min_distance = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
  2185. real_t max_distance = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
  2186. if (unlikely(min_distance > max_distance)) {
  2187. cursor.distance = (min_distance + max_distance) / 2;
  2188. } else {
  2189. cursor.distance = CLAMP(cursor.distance * scale, min_distance, max_distance);
  2190. }
  2191. if (cursor.distance == max_distance || cursor.distance == min_distance) {
  2192. zoom_failed_attempts_count++;
  2193. } else {
  2194. zoom_failed_attempts_count = 0;
  2195. }
  2196. zoom_indicator_delay = ZOOM_FREELOOK_INDICATOR_DELAY_S;
  2197. surface->queue_redraw();
  2198. }
  2199. void Node3DEditorViewport::scale_freelook_speed(real_t scale) {
  2200. real_t min_speed = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
  2201. real_t max_speed = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
  2202. if (unlikely(min_speed > max_speed)) {
  2203. freelook_speed = (min_speed + max_speed) / 2;
  2204. } else {
  2205. freelook_speed = CLAMP(freelook_speed * scale, min_speed, max_speed);
  2206. }
  2207. zoom_indicator_delay = ZOOM_FREELOOK_INDICATOR_DELAY_S;
  2208. surface->queue_redraw();
  2209. }
  2210. Point2 Node3DEditorViewport::_get_warped_mouse_motion(const Ref<InputEventMouseMotion> &p_ev_mouse_motion) const {
  2211. Point2 relative;
  2212. if (bool(EDITOR_GET("editors/3d/navigation/warped_mouse_panning"))) {
  2213. relative = Input::get_singleton()->warp_mouse_motion(p_ev_mouse_motion, surface->get_global_rect());
  2214. } else {
  2215. relative = p_ev_mouse_motion->get_relative();
  2216. }
  2217. return relative;
  2218. }
  2219. void Node3DEditorViewport::_update_freelook(real_t delta) {
  2220. if (!is_freelook_active()) {
  2221. return;
  2222. }
  2223. const FreelookNavigationScheme navigation_scheme = (FreelookNavigationScheme)EDITOR_GET("editors/3d/freelook/freelook_navigation_scheme").operator int();
  2224. Vector3 forward;
  2225. if (navigation_scheme == FREELOOK_FULLY_AXIS_LOCKED) {
  2226. // Forward/backward keys will always go straight forward/backward, never moving on the Y axis.
  2227. forward = Vector3(0, 0, -1).rotated(Vector3(0, 1, 0), camera->get_rotation().y);
  2228. } else {
  2229. // Forward/backward keys will be relative to the camera pitch.
  2230. forward = camera->get_transform().basis.xform(Vector3(0, 0, -1));
  2231. }
  2232. const Vector3 right = camera->get_transform().basis.xform(Vector3(1, 0, 0));
  2233. Vector3 up;
  2234. if (navigation_scheme == FREELOOK_PARTIALLY_AXIS_LOCKED || navigation_scheme == FREELOOK_FULLY_AXIS_LOCKED) {
  2235. // Up/down keys will always go up/down regardless of camera pitch.
  2236. up = Vector3(0, 1, 0);
  2237. } else {
  2238. // Up/down keys will be relative to the camera pitch.
  2239. up = camera->get_transform().basis.xform(Vector3(0, 1, 0));
  2240. }
  2241. Vector3 direction;
  2242. // Use actions from the inputmap, as this is the only way to reliably detect input in this method.
  2243. // See #54469 for more discussion and explanation.
  2244. Input *inp = Input::get_singleton();
  2245. if (inp->is_action_pressed("spatial_editor/freelook_left")) {
  2246. direction -= right;
  2247. }
  2248. if (inp->is_action_pressed("spatial_editor/freelook_right")) {
  2249. direction += right;
  2250. }
  2251. if (inp->is_action_pressed("spatial_editor/freelook_forward")) {
  2252. direction += forward;
  2253. }
  2254. if (inp->is_action_pressed("spatial_editor/freelook_backwards")) {
  2255. direction -= forward;
  2256. }
  2257. if (inp->is_action_pressed("spatial_editor/freelook_up")) {
  2258. direction += up;
  2259. }
  2260. if (inp->is_action_pressed("spatial_editor/freelook_down")) {
  2261. direction -= up;
  2262. }
  2263. real_t speed = freelook_speed;
  2264. if (inp->is_action_pressed("spatial_editor/freelook_speed_modifier")) {
  2265. speed *= 3.0;
  2266. }
  2267. if (inp->is_action_pressed("spatial_editor/freelook_slow_modifier")) {
  2268. speed *= 0.333333;
  2269. }
  2270. const Vector3 motion = direction * speed * delta;
  2271. cursor.pos += motion;
  2272. cursor.eye_pos += motion;
  2273. }
  2274. void Node3DEditorViewport::set_message(const String &p_message, float p_time) {
  2275. message = p_message;
  2276. message_time = p_time;
  2277. }
  2278. void Node3DEditorPlugin::edited_scene_changed() {
  2279. for (uint32_t i = 0; i < Node3DEditor::VIEWPORTS_COUNT; i++) {
  2280. Node3DEditorViewport *viewport = Node3DEditor::get_singleton()->get_editor_viewport(i);
  2281. if (viewport->is_visible()) {
  2282. viewport->notification(Control::NOTIFICATION_VISIBILITY_CHANGED);
  2283. }
  2284. }
  2285. }
  2286. void Node3DEditorViewport::_project_settings_changed() {
  2287. // Update shadow atlas if changed.
  2288. int shadowmap_size = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_size");
  2289. bool shadowmap_16_bits = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_16_bits");
  2290. int atlas_q0 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_0_subdiv");
  2291. int atlas_q1 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_1_subdiv");
  2292. int atlas_q2 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_2_subdiv");
  2293. int atlas_q3 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_3_subdiv");
  2294. viewport->set_positional_shadow_atlas_size(shadowmap_size);
  2295. viewport->set_positional_shadow_atlas_16_bits(shadowmap_16_bits);
  2296. viewport->set_positional_shadow_atlas_quadrant_subdiv(0, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q0));
  2297. viewport->set_positional_shadow_atlas_quadrant_subdiv(1, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q1));
  2298. viewport->set_positional_shadow_atlas_quadrant_subdiv(2, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q2));
  2299. viewport->set_positional_shadow_atlas_quadrant_subdiv(3, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q3));
  2300. _update_shrink();
  2301. // Update MSAA, screen-space AA and debanding if changed
  2302. const int msaa_mode = GLOBAL_GET("rendering/anti_aliasing/quality/msaa_3d");
  2303. viewport->set_msaa_3d(Viewport::MSAA(msaa_mode));
  2304. const int ssaa_mode = GLOBAL_GET("rendering/anti_aliasing/quality/screen_space_aa");
  2305. viewport->set_screen_space_aa(Viewport::ScreenSpaceAA(ssaa_mode));
  2306. const bool use_taa = GLOBAL_GET("rendering/anti_aliasing/quality/use_taa");
  2307. viewport->set_use_taa(use_taa);
  2308. const bool transparent_background = GLOBAL_GET("rendering/viewport/transparent_background");
  2309. viewport->set_transparent_background(transparent_background);
  2310. const bool use_hdr_2d = GLOBAL_GET("rendering/viewport/hdr_2d");
  2311. viewport->set_use_hdr_2d(use_hdr_2d);
  2312. const bool use_debanding = GLOBAL_GET("rendering/anti_aliasing/quality/use_debanding");
  2313. viewport->set_use_debanding(use_debanding);
  2314. const bool use_occlusion_culling = GLOBAL_GET("rendering/occlusion_culling/use_occlusion_culling");
  2315. viewport->set_use_occlusion_culling(use_occlusion_culling);
  2316. const float mesh_lod_threshold = GLOBAL_GET("rendering/mesh_lod/lod_change/threshold_pixels");
  2317. viewport->set_mesh_lod_threshold(mesh_lod_threshold);
  2318. const Viewport::Scaling3DMode scaling_3d_mode = Viewport::Scaling3DMode(int(GLOBAL_GET("rendering/scaling_3d/mode")));
  2319. viewport->set_scaling_3d_mode(scaling_3d_mode);
  2320. const float scaling_3d_scale = GLOBAL_GET("rendering/scaling_3d/scale");
  2321. viewport->set_scaling_3d_scale(scaling_3d_scale);
  2322. const float fsr_sharpness = GLOBAL_GET("rendering/scaling_3d/fsr_sharpness");
  2323. viewport->set_fsr_sharpness(fsr_sharpness);
  2324. const float texture_mipmap_bias = GLOBAL_GET("rendering/textures/default_filters/texture_mipmap_bias");
  2325. viewport->set_texture_mipmap_bias(texture_mipmap_bias);
  2326. }
  2327. void Node3DEditorViewport::_notification(int p_what) {
  2328. switch (p_what) {
  2329. case NOTIFICATION_READY: {
  2330. ProjectSettings::get_singleton()->connect("settings_changed", callable_mp(this, &Node3DEditorViewport::_project_settings_changed));
  2331. } break;
  2332. case NOTIFICATION_VISIBILITY_CHANGED: {
  2333. bool vp_visible = is_visible_in_tree();
  2334. set_process(vp_visible);
  2335. set_physics_process(vp_visible);
  2336. if (vp_visible) {
  2337. orthogonal = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL));
  2338. _update_name();
  2339. _update_camera(0);
  2340. } else {
  2341. set_freelook_active(false);
  2342. }
  2343. callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view).call_deferred();
  2344. } break;
  2345. case NOTIFICATION_RESIZED: {
  2346. callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view).call_deferred();
  2347. } break;
  2348. case NOTIFICATION_PROCESS: {
  2349. real_t delta = get_process_delta_time();
  2350. if (zoom_indicator_delay > 0) {
  2351. zoom_indicator_delay -= delta;
  2352. if (zoom_indicator_delay <= 0) {
  2353. surface->queue_redraw();
  2354. zoom_limit_label->hide();
  2355. }
  2356. }
  2357. _update_navigation_controls_visibility();
  2358. _update_freelook(delta);
  2359. Node *scene_root = SceneTreeDock::get_singleton()->get_editor_data()->get_edited_scene_root();
  2360. if (previewing_cinema && scene_root != nullptr) {
  2361. Camera3D *cam = scene_root->get_viewport()->get_camera_3d();
  2362. if (cam != nullptr && cam != previewing) {
  2363. //then switch the viewport's camera to the scene's viewport camera
  2364. if (previewing != nullptr) {
  2365. previewing->disconnect(SceneStringName(tree_exited), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  2366. }
  2367. previewing = cam;
  2368. previewing->connect(SceneStringName(tree_exited), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  2369. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), cam->get_camera());
  2370. surface->queue_redraw();
  2371. }
  2372. }
  2373. _update_camera(delta);
  2374. const HashMap<Node *, Object *> &selection = editor_selection->get_selection();
  2375. bool changed = false;
  2376. bool exist = false;
  2377. for (const KeyValue<Node *, Object *> &E : selection) {
  2378. Node3D *sp = Object::cast_to<Node3D>(E.key);
  2379. if (!sp) {
  2380. continue;
  2381. }
  2382. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  2383. if (!se) {
  2384. continue;
  2385. }
  2386. Transform3D t = sp->get_global_gizmo_transform();
  2387. AABB new_aabb = _calculate_spatial_bounds(sp);
  2388. exist = true;
  2389. if (se->last_xform == t && se->aabb == new_aabb && !se->last_xform_dirty) {
  2390. continue;
  2391. }
  2392. changed = true;
  2393. se->last_xform_dirty = false;
  2394. se->last_xform = t;
  2395. se->aabb = new_aabb;
  2396. Transform3D t_offset = t;
  2397. // apply AABB scaling before item's global transform
  2398. {
  2399. const Vector3 offset(0.005, 0.005, 0.005);
  2400. Basis aabb_s;
  2401. aabb_s.scale(se->aabb.size + offset);
  2402. t.translate_local(se->aabb.position - offset / 2);
  2403. t.basis = t.basis * aabb_s;
  2404. }
  2405. {
  2406. const Vector3 offset(0.01, 0.01, 0.01);
  2407. Basis aabb_s;
  2408. aabb_s.scale(se->aabb.size + offset);
  2409. t_offset.translate_local(se->aabb.position - offset / 2);
  2410. t_offset.basis = t_offset.basis * aabb_s;
  2411. }
  2412. RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance, t);
  2413. RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_offset, t_offset);
  2414. RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_xray, t);
  2415. RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_xray_offset, t_offset);
  2416. }
  2417. if (changed || (spatial_editor->is_gizmo_visible() && !exist)) {
  2418. spatial_editor->update_transform_gizmo();
  2419. }
  2420. if (message_time > 0) {
  2421. if (message != last_message) {
  2422. surface->queue_redraw();
  2423. last_message = message;
  2424. }
  2425. message_time -= get_process_delta_time();
  2426. if (message_time < 0) {
  2427. surface->queue_redraw();
  2428. }
  2429. }
  2430. bool show_info = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_INFORMATION));
  2431. if (show_info != info_label->is_visible()) {
  2432. info_label->set_visible(show_info);
  2433. }
  2434. Camera3D *current_camera;
  2435. if (previewing) {
  2436. current_camera = previewing;
  2437. } else {
  2438. current_camera = camera;
  2439. }
  2440. if (show_info) {
  2441. const String viewport_size = vformat(U"%d × %d", viewport->get_size().x, viewport->get_size().y);
  2442. String text;
  2443. text += vformat(TTR("X: %s\n"), rtos(current_camera->get_position().x).pad_decimals(1));
  2444. text += vformat(TTR("Y: %s\n"), rtos(current_camera->get_position().y).pad_decimals(1));
  2445. text += vformat(TTR("Z: %s\n"), rtos(current_camera->get_position().z).pad_decimals(1));
  2446. text += "\n";
  2447. text += vformat(
  2448. TTR("Size: %s (%.1fMP)\n"),
  2449. viewport_size,
  2450. viewport->get_size().x * viewport->get_size().y * 0.000001);
  2451. text += "\n";
  2452. text += vformat(TTR("Objects: %d\n"), viewport->get_render_info(Viewport::RENDER_INFO_TYPE_VISIBLE, Viewport::RENDER_INFO_OBJECTS_IN_FRAME));
  2453. text += vformat(TTR("Primitives: %d\n"), viewport->get_render_info(Viewport::RENDER_INFO_TYPE_VISIBLE, Viewport::RENDER_INFO_PRIMITIVES_IN_FRAME));
  2454. text += vformat(TTR("Draw Calls: %d"), viewport->get_render_info(Viewport::RENDER_INFO_TYPE_VISIBLE, Viewport::RENDER_INFO_DRAW_CALLS_IN_FRAME));
  2455. info_label->set_text(text);
  2456. }
  2457. // FPS Counter.
  2458. bool show_fps = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_FRAME_TIME));
  2459. if (show_fps != frame_time_panel->is_visible()) {
  2460. frame_time_panel->set_visible(show_fps);
  2461. RS::get_singleton()->viewport_set_measure_render_time(viewport->get_viewport_rid(), show_fps);
  2462. for (int i = 0; i < FRAME_TIME_HISTORY; i++) {
  2463. // Initialize to 120 FPS, so that the initial estimation until we get enough data is always reasonable.
  2464. cpu_time_history[i] = 8.333333;
  2465. gpu_time_history[i] = 8.333333;
  2466. }
  2467. cpu_time_history_index = 0;
  2468. gpu_time_history_index = 0;
  2469. }
  2470. if (show_fps) {
  2471. cpu_time_history[cpu_time_history_index] = RS::get_singleton()->viewport_get_measured_render_time_cpu(viewport->get_viewport_rid());
  2472. cpu_time_history_index = (cpu_time_history_index + 1) % FRAME_TIME_HISTORY;
  2473. double cpu_time = 0.0;
  2474. for (int i = 0; i < FRAME_TIME_HISTORY; i++) {
  2475. cpu_time += cpu_time_history[i];
  2476. }
  2477. cpu_time /= FRAME_TIME_HISTORY;
  2478. // Prevent unrealistically low values.
  2479. cpu_time = MAX(0.01, cpu_time);
  2480. gpu_time_history[gpu_time_history_index] = RS::get_singleton()->viewport_get_measured_render_time_gpu(viewport->get_viewport_rid());
  2481. gpu_time_history_index = (gpu_time_history_index + 1) % FRAME_TIME_HISTORY;
  2482. double gpu_time = 0.0;
  2483. for (int i = 0; i < FRAME_TIME_HISTORY; i++) {
  2484. gpu_time += gpu_time_history[i];
  2485. }
  2486. gpu_time /= FRAME_TIME_HISTORY;
  2487. // Prevent division by zero for the FPS counter (and unrealistically low values).
  2488. // This limits the reported FPS to 100000.
  2489. gpu_time = MAX(0.01, gpu_time);
  2490. // Color labels depending on performance level ("good" = green, "OK" = yellow, "bad" = red).
  2491. // Middle point is at 15 ms.
  2492. cpu_time_label->set_text(vformat(TTR("CPU Time: %s ms"), rtos(cpu_time).pad_decimals(2)));
  2493. cpu_time_label->add_theme_color_override(
  2494. "font_color",
  2495. frame_time_gradient->get_color_at_offset(
  2496. Math::remap(cpu_time, 0, 30, 0, 1)));
  2497. gpu_time_label->set_text(vformat(TTR("GPU Time: %s ms"), rtos(gpu_time).pad_decimals(2)));
  2498. // Middle point is at 15 ms.
  2499. gpu_time_label->add_theme_color_override(
  2500. "font_color",
  2501. frame_time_gradient->get_color_at_offset(
  2502. Math::remap(gpu_time, 0, 30, 0, 1)));
  2503. const double fps = 1000.0 / gpu_time;
  2504. fps_label->set_text(vformat(TTR("FPS: %d"), fps));
  2505. // Middle point is at 60 FPS.
  2506. fps_label->add_theme_color_override(
  2507. "font_color",
  2508. frame_time_gradient->get_color_at_offset(
  2509. Math::remap(fps, 110, 10, 0, 1)));
  2510. }
  2511. bool show_cinema = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
  2512. cinema_label->set_visible(show_cinema);
  2513. if (show_cinema) {
  2514. float cinema_half_width = cinema_label->get_size().width / 2.0f;
  2515. cinema_label->set_anchor_and_offset(SIDE_LEFT, 0.5f, -cinema_half_width);
  2516. }
  2517. if (lock_rotation) {
  2518. float locked_half_width = locked_label->get_size().width / 2.0f;
  2519. locked_label->set_anchor_and_offset(SIDE_LEFT, 0.5f, -locked_half_width);
  2520. }
  2521. } break;
  2522. case NOTIFICATION_PHYSICS_PROCESS: {
  2523. if (!update_preview_node) {
  2524. return;
  2525. }
  2526. if (preview_node->is_inside_tree()) {
  2527. preview_node_pos = spatial_editor->snap_point(_get_instance_position(preview_node_viewport_pos));
  2528. double snap = EDITOR_GET("interface/inspector/default_float_step");
  2529. int snap_step_decimals = Math::range_step_decimals(snap);
  2530. set_message(TTR("Instantiating:") + " (" + String::num(preview_node_pos.x, snap_step_decimals) + ", " +
  2531. String::num(preview_node_pos.y, snap_step_decimals) + ", " + String::num(preview_node_pos.z, snap_step_decimals) + ")");
  2532. Transform3D preview_gl_transform = Transform3D(Basis(), preview_node_pos);
  2533. preview_node->set_global_transform(preview_gl_transform);
  2534. if (!preview_node->is_visible()) {
  2535. preview_node->show();
  2536. }
  2537. }
  2538. update_preview_node = false;
  2539. } break;
  2540. case NOTIFICATION_ENTER_TREE: {
  2541. surface->connect(SceneStringName(draw), callable_mp(this, &Node3DEditorViewport::_draw));
  2542. surface->connect(SceneStringName(gui_input), callable_mp(this, &Node3DEditorViewport::_sinput));
  2543. surface->connect(SceneStringName(mouse_entered), callable_mp(this, &Node3DEditorViewport::_surface_mouse_enter));
  2544. surface->connect(SceneStringName(mouse_exited), callable_mp(this, &Node3DEditorViewport::_surface_mouse_exit));
  2545. surface->connect(SceneStringName(focus_entered), callable_mp(this, &Node3DEditorViewport::_surface_focus_enter));
  2546. surface->connect(SceneStringName(focus_exited), callable_mp(this, &Node3DEditorViewport::_surface_focus_exit));
  2547. _init_gizmo_instance(index);
  2548. } break;
  2549. case NOTIFICATION_EXIT_TREE: {
  2550. _finish_gizmo_instances();
  2551. } break;
  2552. case NOTIFICATION_THEME_CHANGED: {
  2553. view_menu->set_icon(get_editor_theme_icon(SNAME("GuiTabMenuHl")));
  2554. preview_camera->set_icon(get_editor_theme_icon(SNAME("Camera3D")));
  2555. Control *gui_base = EditorNode::get_singleton()->get_gui_base();
  2556. view_menu->begin_bulk_theme_override();
  2557. view_menu->add_theme_style_override("normal", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2558. view_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2559. view_menu->add_theme_style_override(SceneStringName(pressed), gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2560. view_menu->add_theme_style_override("focus", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2561. view_menu->add_theme_style_override("disabled", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2562. view_menu->end_bulk_theme_override();
  2563. preview_camera->begin_bulk_theme_override();
  2564. preview_camera->add_theme_style_override("normal", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2565. preview_camera->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2566. preview_camera->add_theme_style_override(SceneStringName(pressed), gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2567. preview_camera->add_theme_style_override("focus", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2568. preview_camera->add_theme_style_override("disabled", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2569. preview_camera->end_bulk_theme_override();
  2570. frame_time_gradient->set_color(0, get_theme_color(SNAME("success_color"), EditorStringName(Editor)));
  2571. frame_time_gradient->set_color(1, get_theme_color(SNAME("warning_color"), EditorStringName(Editor)));
  2572. frame_time_gradient->set_color(2, get_theme_color(SNAME("error_color"), EditorStringName(Editor)));
  2573. info_label->add_theme_style_override("normal", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2574. frame_time_panel->add_theme_style_override("panel", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2575. // Set a minimum width to prevent the width from changing all the time
  2576. // when numbers vary rapidly. This minimum width is set based on a
  2577. // GPU time of 999.99 ms in the current editor language.
  2578. const float min_width = get_theme_font(SNAME("main"), EditorStringName(EditorFonts))->get_string_size(vformat(TTR("GPU Time: %s ms"), 999.99)).x;
  2579. frame_time_panel->set_custom_minimum_size(Size2(min_width, 0) * EDSCALE);
  2580. frame_time_vbox->add_theme_constant_override("separation", Math::round(-1 * EDSCALE));
  2581. cinema_label->add_theme_style_override("normal", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2582. locked_label->add_theme_style_override("normal", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2583. } break;
  2584. case NOTIFICATION_DRAG_END: {
  2585. // Clear preview material when dropped outside applicable object.
  2586. if (spatial_editor->get_preview_material().is_valid() && !is_drag_successful()) {
  2587. _remove_preview_material();
  2588. } else {
  2589. _remove_preview_node();
  2590. }
  2591. } break;
  2592. }
  2593. }
  2594. static void draw_indicator_bar(Control &p_surface, real_t p_fill, const Ref<Texture2D> p_icon, const Ref<Font> p_font, int p_font_size, const String &p_text, const Color &p_color) {
  2595. // Adjust bar size from control height
  2596. const Vector2 surface_size = p_surface.get_size();
  2597. const real_t h = surface_size.y / 2.0;
  2598. const real_t y = (surface_size.y - h) / 2.0;
  2599. const Rect2 r(10 * EDSCALE, y, 6 * EDSCALE, h);
  2600. const real_t sy = r.size.y * p_fill;
  2601. // Note: because this bar appears over the viewport, it has to stay readable for any background color
  2602. // Draw both neutral dark and bright colors to account this
  2603. p_surface.draw_rect(r, p_color * Color(1, 1, 1, 0.2));
  2604. p_surface.draw_rect(Rect2(r.position.x, r.position.y + r.size.y - sy, r.size.x, sy), p_color * Color(1, 1, 1, 0.6));
  2605. p_surface.draw_rect(r.grow(1), Color(0, 0, 0, 0.7), false, Math::round(EDSCALE));
  2606. const Vector2 icon_size = p_icon->get_size();
  2607. const Vector2 icon_pos = Vector2(r.position.x - (icon_size.x - r.size.x) / 2, r.position.y + r.size.y + 2 * EDSCALE);
  2608. p_surface.draw_texture(p_icon, icon_pos, p_color);
  2609. // Draw text below the bar (for speed/zoom information).
  2610. p_surface.draw_string_outline(p_font, Vector2(icon_pos.x, icon_pos.y + icon_size.y + 16 * EDSCALE), p_text, HORIZONTAL_ALIGNMENT_LEFT, -1.f, p_font_size, Math::round(2 * EDSCALE), Color(0, 0, 0));
  2611. p_surface.draw_string(p_font, Vector2(icon_pos.x, icon_pos.y + icon_size.y + 16 * EDSCALE), p_text, HORIZONTAL_ALIGNMENT_LEFT, -1.f, p_font_size, p_color);
  2612. }
  2613. void Node3DEditorViewport::_draw() {
  2614. EditorPluginList *over_plugin_list = EditorNode::get_singleton()->get_editor_plugins_over();
  2615. if (!over_plugin_list->is_empty()) {
  2616. over_plugin_list->forward_3d_draw_over_viewport(surface);
  2617. }
  2618. EditorPluginList *force_over_plugin_list = EditorNode::get_singleton()->get_editor_plugins_force_over();
  2619. if (!force_over_plugin_list->is_empty()) {
  2620. force_over_plugin_list->forward_3d_force_draw_over_viewport(surface);
  2621. }
  2622. if (surface->has_focus()) {
  2623. Size2 size = surface->get_size();
  2624. Rect2 r = Rect2(Point2(), size);
  2625. get_theme_stylebox(SNAME("FocusViewport"), EditorStringName(EditorStyles))->draw(surface->get_canvas_item(), r);
  2626. }
  2627. if (cursor.region_select) {
  2628. const Rect2 selection_rect = Rect2(cursor.region_begin, cursor.region_end - cursor.region_begin);
  2629. surface->draw_rect(
  2630. selection_rect,
  2631. get_theme_color(SNAME("box_selection_fill_color"), EditorStringName(Editor)));
  2632. surface->draw_rect(
  2633. selection_rect,
  2634. get_theme_color(SNAME("box_selection_stroke_color"), EditorStringName(Editor)),
  2635. false,
  2636. Math::round(EDSCALE));
  2637. }
  2638. RID ci = surface->get_canvas_item();
  2639. if (message_time > 0) {
  2640. Ref<Font> font = get_theme_font(SNAME("font"), SNAME("Label"));
  2641. int font_size = get_theme_font_size(SNAME("font_size"), SNAME("Label"));
  2642. Point2 msgpos = Point2(5, get_size().y - 20);
  2643. font->draw_string(ci, msgpos + Point2(1, 1), message, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, Color(0, 0, 0, 0.8));
  2644. font->draw_string(ci, msgpos + Point2(-1, -1), message, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, Color(0, 0, 0, 0.8));
  2645. font->draw_string(ci, msgpos, message, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, Color(1, 1, 1, 1));
  2646. }
  2647. if (_edit.mode == TRANSFORM_ROTATE && _edit.show_rotation_line) {
  2648. Point2 center = point_to_screen(_edit.center);
  2649. Color handle_color;
  2650. switch (_edit.plane) {
  2651. case TRANSFORM_X_AXIS:
  2652. handle_color = get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor));
  2653. break;
  2654. case TRANSFORM_Y_AXIS:
  2655. handle_color = get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor));
  2656. break;
  2657. case TRANSFORM_Z_AXIS:
  2658. handle_color = get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor));
  2659. break;
  2660. default:
  2661. handle_color = get_theme_color(SNAME("accent_color"), EditorStringName(Editor));
  2662. break;
  2663. }
  2664. handle_color = handle_color.from_hsv(handle_color.get_h(), 0.25, 1.0, 1);
  2665. RenderingServer::get_singleton()->canvas_item_add_line(
  2666. ci,
  2667. _edit.mouse_pos,
  2668. center,
  2669. handle_color,
  2670. Math::round(2 * EDSCALE));
  2671. }
  2672. if (previewing) {
  2673. Size2 ss = Size2(GLOBAL_GET("display/window/size/viewport_width"), GLOBAL_GET("display/window/size/viewport_height"));
  2674. float aspect = ss.aspect();
  2675. Size2 s = get_size();
  2676. Rect2 draw_rect;
  2677. switch (previewing->get_keep_aspect_mode()) {
  2678. case Camera3D::KEEP_WIDTH: {
  2679. draw_rect.size = Size2(s.width, s.width / aspect);
  2680. draw_rect.position.x = 0;
  2681. draw_rect.position.y = (s.height - draw_rect.size.y) * 0.5;
  2682. } break;
  2683. case Camera3D::KEEP_HEIGHT: {
  2684. draw_rect.size = Size2(s.height * aspect, s.height);
  2685. draw_rect.position.y = 0;
  2686. draw_rect.position.x = (s.width - draw_rect.size.x) * 0.5;
  2687. } break;
  2688. }
  2689. draw_rect = Rect2(Vector2(), s).intersection(draw_rect);
  2690. surface->draw_rect(draw_rect, Color(0.6, 0.6, 0.1, 0.5), false, Math::round(2 * EDSCALE));
  2691. } else {
  2692. if (zoom_indicator_delay > 0.0) {
  2693. if (is_freelook_active()) {
  2694. // Show speed
  2695. real_t min_speed = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
  2696. real_t max_speed = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
  2697. real_t scale_length = (max_speed - min_speed);
  2698. if (!Math::is_zero_approx(scale_length)) {
  2699. real_t logscale_t = 1.0 - Math::log1p(freelook_speed - min_speed) / Math::log1p(scale_length);
  2700. // Display the freelook speed to help the user get a better sense of scale.
  2701. const int precision = freelook_speed < 1.0 ? 2 : 1;
  2702. draw_indicator_bar(
  2703. *surface,
  2704. 1.0 - logscale_t,
  2705. get_editor_theme_icon(SNAME("ViewportSpeed")),
  2706. get_theme_font(SNAME("font"), SNAME("Label")),
  2707. get_theme_font_size(SNAME("font_size"), SNAME("Label")),
  2708. vformat("%s m/s", String::num(freelook_speed).pad_decimals(precision)),
  2709. Color(1.0, 0.95, 0.7));
  2710. }
  2711. } else {
  2712. // Show zoom
  2713. zoom_limit_label->set_visible(zoom_failed_attempts_count > 15);
  2714. real_t min_distance = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
  2715. real_t max_distance = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
  2716. real_t scale_length = (max_distance - min_distance);
  2717. if (!Math::is_zero_approx(scale_length)) {
  2718. real_t logscale_t = 1.0 - Math::log1p(cursor.distance - min_distance) / Math::log1p(scale_length);
  2719. // Display the zoom center distance to help the user get a better sense of scale.
  2720. const int precision = cursor.distance < 1.0 ? 2 : 1;
  2721. draw_indicator_bar(
  2722. *surface,
  2723. logscale_t,
  2724. get_editor_theme_icon(SNAME("ViewportZoom")),
  2725. get_theme_font(SNAME("font"), SNAME("Label")),
  2726. get_theme_font_size(SNAME("font_size"), SNAME("Label")),
  2727. vformat("%s m", String::num(cursor.distance).pad_decimals(precision)),
  2728. Color(0.7, 0.95, 1.0));
  2729. }
  2730. }
  2731. }
  2732. }
  2733. }
  2734. void Node3DEditorViewport::_menu_option(int p_option) {
  2735. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  2736. switch (p_option) {
  2737. case VIEW_TOP: {
  2738. cursor.y_rot = 0;
  2739. cursor.x_rot = Math_PI / 2.0;
  2740. set_message(TTR("Top View."), 2);
  2741. view_type = VIEW_TYPE_TOP;
  2742. _set_auto_orthogonal();
  2743. _update_name();
  2744. } break;
  2745. case VIEW_BOTTOM: {
  2746. cursor.y_rot = 0;
  2747. cursor.x_rot = -Math_PI / 2.0;
  2748. set_message(TTR("Bottom View."), 2);
  2749. view_type = VIEW_TYPE_BOTTOM;
  2750. _set_auto_orthogonal();
  2751. _update_name();
  2752. } break;
  2753. case VIEW_LEFT: {
  2754. cursor.x_rot = 0;
  2755. cursor.y_rot = Math_PI / 2.0;
  2756. set_message(TTR("Left View."), 2);
  2757. view_type = VIEW_TYPE_LEFT;
  2758. _set_auto_orthogonal();
  2759. _update_name();
  2760. } break;
  2761. case VIEW_RIGHT: {
  2762. cursor.x_rot = 0;
  2763. cursor.y_rot = -Math_PI / 2.0;
  2764. set_message(TTR("Right View."), 2);
  2765. view_type = VIEW_TYPE_RIGHT;
  2766. _set_auto_orthogonal();
  2767. _update_name();
  2768. } break;
  2769. case VIEW_FRONT: {
  2770. cursor.x_rot = 0;
  2771. cursor.y_rot = 0;
  2772. set_message(TTR("Front View."), 2);
  2773. view_type = VIEW_TYPE_FRONT;
  2774. _set_auto_orthogonal();
  2775. _update_name();
  2776. } break;
  2777. case VIEW_REAR: {
  2778. cursor.x_rot = 0;
  2779. cursor.y_rot = Math_PI;
  2780. set_message(TTR("Rear View."), 2);
  2781. view_type = VIEW_TYPE_REAR;
  2782. _set_auto_orthogonal();
  2783. _update_name();
  2784. } break;
  2785. case VIEW_CENTER_TO_ORIGIN: {
  2786. cursor.pos = Vector3(0, 0, 0);
  2787. } break;
  2788. case VIEW_CENTER_TO_SELECTION: {
  2789. focus_selection();
  2790. } break;
  2791. case VIEW_ALIGN_TRANSFORM_WITH_VIEW: {
  2792. if (!get_selected_count()) {
  2793. break;
  2794. }
  2795. Transform3D camera_transform = camera->get_global_transform();
  2796. List<Node *> &selection = editor_selection->get_selected_node_list();
  2797. undo_redo->create_action(TTR("Align Transform with View"));
  2798. for (Node *E : selection) {
  2799. Node3D *sp = Object::cast_to<Node3D>(E);
  2800. if (!sp) {
  2801. continue;
  2802. }
  2803. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  2804. if (!se) {
  2805. continue;
  2806. }
  2807. Transform3D xform;
  2808. if (orthogonal) {
  2809. xform = sp->get_global_transform();
  2810. xform.basis = Basis::from_euler(camera_transform.basis.get_euler());
  2811. } else {
  2812. xform = camera_transform;
  2813. xform.scale_basis(sp->get_scale());
  2814. }
  2815. if (Object::cast_to<Decal>(E)) {
  2816. // Adjust rotation to match Decal's default orientation.
  2817. // This makes the decal "look" in the same direction as the camera,
  2818. // rather than pointing down relative to the camera orientation.
  2819. xform.basis.rotate_local(Vector3(1, 0, 0), Math_TAU * 0.25);
  2820. }
  2821. Node3D *parent = sp->get_parent_node_3d();
  2822. Transform3D local_xform = parent ? parent->get_global_transform().affine_inverse() * xform : xform;
  2823. undo_redo->add_do_method(sp, "set_transform", local_xform);
  2824. undo_redo->add_undo_method(sp, "set_transform", sp->get_local_gizmo_transform());
  2825. }
  2826. undo_redo->commit_action();
  2827. } break;
  2828. case VIEW_ALIGN_ROTATION_WITH_VIEW: {
  2829. if (!get_selected_count()) {
  2830. break;
  2831. }
  2832. Transform3D camera_transform = camera->get_global_transform();
  2833. List<Node *> &selection = editor_selection->get_selected_node_list();
  2834. undo_redo->create_action(TTR("Align Rotation with View"));
  2835. for (Node *E : selection) {
  2836. Node3D *sp = Object::cast_to<Node3D>(E);
  2837. if (!sp) {
  2838. continue;
  2839. }
  2840. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  2841. if (!se) {
  2842. continue;
  2843. }
  2844. Basis basis = camera_transform.basis;
  2845. if (Object::cast_to<Decal>(E)) {
  2846. // Adjust rotation to match Decal's default orientation.
  2847. // This makes the decal "look" in the same direction as the camera,
  2848. // rather than pointing down relative to the camera orientation.
  2849. basis.rotate_local(Vector3(1, 0, 0), Math_TAU * 0.25);
  2850. }
  2851. undo_redo->add_do_method(sp, "set_rotation", basis.get_euler_normalized());
  2852. undo_redo->add_undo_method(sp, "set_rotation", sp->get_rotation());
  2853. }
  2854. undo_redo->commit_action();
  2855. } break;
  2856. case VIEW_ENVIRONMENT: {
  2857. int idx = view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT);
  2858. bool current = view_menu->get_popup()->is_item_checked(idx);
  2859. current = !current;
  2860. if (current) {
  2861. camera->set_environment(Ref<Resource>());
  2862. } else {
  2863. camera->set_environment(Node3DEditor::get_singleton()->get_viewport_environment());
  2864. }
  2865. view_menu->get_popup()->set_item_checked(idx, current);
  2866. } break;
  2867. case VIEW_PERSPECTIVE: {
  2868. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
  2869. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), false);
  2870. orthogonal = false;
  2871. auto_orthogonal = false;
  2872. callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view).call_deferred();
  2873. _update_camera(0);
  2874. _update_name();
  2875. } break;
  2876. case VIEW_ORTHOGONAL: {
  2877. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), false);
  2878. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), true);
  2879. orthogonal = true;
  2880. auto_orthogonal = false;
  2881. callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view).call_deferred();
  2882. _update_camera(0);
  2883. _update_name();
  2884. } break;
  2885. case VIEW_SWITCH_PERSPECTIVE_ORTHOGONAL: {
  2886. _menu_option(orthogonal ? VIEW_PERSPECTIVE : VIEW_ORTHOGONAL);
  2887. } break;
  2888. case VIEW_AUTO_ORTHOGONAL: {
  2889. int idx = view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL);
  2890. bool current = view_menu->get_popup()->is_item_checked(idx);
  2891. current = !current;
  2892. view_menu->get_popup()->set_item_checked(idx, current);
  2893. if (auto_orthogonal) {
  2894. auto_orthogonal = false;
  2895. _update_name();
  2896. }
  2897. } break;
  2898. case VIEW_LOCK_ROTATION: {
  2899. int idx = view_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
  2900. bool current = view_menu->get_popup()->is_item_checked(idx);
  2901. _set_lock_view_rotation(!current);
  2902. } break;
  2903. case VIEW_AUDIO_LISTENER: {
  2904. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
  2905. bool current = view_menu->get_popup()->is_item_checked(idx);
  2906. current = !current;
  2907. viewport->set_as_audio_listener_3d(current);
  2908. view_menu->get_popup()->set_item_checked(idx, current);
  2909. } break;
  2910. case VIEW_AUDIO_DOPPLER: {
  2911. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
  2912. bool current = view_menu->get_popup()->is_item_checked(idx);
  2913. current = !current;
  2914. camera->set_doppler_tracking(current ? Camera3D::DOPPLER_TRACKING_IDLE_STEP : Camera3D::DOPPLER_TRACKING_DISABLED);
  2915. view_menu->get_popup()->set_item_checked(idx, current);
  2916. } break;
  2917. case VIEW_CINEMATIC_PREVIEW: {
  2918. int idx = view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
  2919. bool current = view_menu->get_popup()->is_item_checked(idx);
  2920. current = !current;
  2921. view_menu->get_popup()->set_item_checked(idx, current);
  2922. previewing_cinema = true;
  2923. _toggle_cinema_preview(current);
  2924. if (current) {
  2925. preview_camera->hide();
  2926. } else {
  2927. if (previewing != nullptr) {
  2928. preview_camera->show();
  2929. }
  2930. }
  2931. } break;
  2932. case VIEW_GIZMOS: {
  2933. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  2934. bool current = view_menu->get_popup()->is_item_checked(idx);
  2935. current = !current;
  2936. uint32_t layers = camera->get_cull_mask();
  2937. layers &= ~(1 << GIZMO_EDIT_LAYER);
  2938. if (current) {
  2939. layers |= (1 << GIZMO_EDIT_LAYER);
  2940. }
  2941. camera->set_cull_mask(layers);
  2942. view_menu->get_popup()->set_item_checked(idx, current);
  2943. } break;
  2944. case VIEW_HALF_RESOLUTION: {
  2945. int idx = view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
  2946. bool current = view_menu->get_popup()->is_item_checked(idx);
  2947. view_menu->get_popup()->set_item_checked(idx, !current);
  2948. _update_shrink();
  2949. } break;
  2950. case VIEW_INFORMATION: {
  2951. int idx = view_menu->get_popup()->get_item_index(VIEW_INFORMATION);
  2952. bool current = view_menu->get_popup()->is_item_checked(idx);
  2953. view_menu->get_popup()->set_item_checked(idx, !current);
  2954. } break;
  2955. case VIEW_FRAME_TIME: {
  2956. int idx = view_menu->get_popup()->get_item_index(VIEW_FRAME_TIME);
  2957. bool current = view_menu->get_popup()->is_item_checked(idx);
  2958. view_menu->get_popup()->set_item_checked(idx, !current);
  2959. } break;
  2960. case VIEW_GRID: {
  2961. int idx = view_menu->get_popup()->get_item_index(VIEW_GRID);
  2962. bool current = view_menu->get_popup()->is_item_checked(idx);
  2963. current = !current;
  2964. uint32_t layers = camera->get_cull_mask();
  2965. layers &= ~(1 << GIZMO_GRID_LAYER);
  2966. if (current) {
  2967. layers |= (1 << GIZMO_GRID_LAYER);
  2968. }
  2969. camera->set_cull_mask(layers);
  2970. view_menu->get_popup()->set_item_checked(idx, current);
  2971. } break;
  2972. case VIEW_DISPLAY_NORMAL:
  2973. case VIEW_DISPLAY_WIREFRAME:
  2974. case VIEW_DISPLAY_OVERDRAW:
  2975. case VIEW_DISPLAY_UNSHADED:
  2976. case VIEW_DISPLAY_LIGHTING:
  2977. case VIEW_DISPLAY_NORMAL_BUFFER:
  2978. case VIEW_DISPLAY_DEBUG_SHADOW_ATLAS:
  2979. case VIEW_DISPLAY_DEBUG_DIRECTIONAL_SHADOW_ATLAS:
  2980. case VIEW_DISPLAY_DEBUG_VOXEL_GI_ALBEDO:
  2981. case VIEW_DISPLAY_DEBUG_VOXEL_GI_LIGHTING:
  2982. case VIEW_DISPLAY_DEBUG_VOXEL_GI_EMISSION:
  2983. case VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE:
  2984. case VIEW_DISPLAY_DEBUG_SSAO:
  2985. case VIEW_DISPLAY_DEBUG_SSIL:
  2986. case VIEW_DISPLAY_DEBUG_PSSM_SPLITS:
  2987. case VIEW_DISPLAY_DEBUG_DECAL_ATLAS:
  2988. case VIEW_DISPLAY_DEBUG_SDFGI:
  2989. case VIEW_DISPLAY_DEBUG_SDFGI_PROBES:
  2990. case VIEW_DISPLAY_DEBUG_GI_BUFFER:
  2991. case VIEW_DISPLAY_DEBUG_DISABLE_LOD:
  2992. case VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS:
  2993. case VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS:
  2994. case VIEW_DISPLAY_DEBUG_CLUSTER_DECALS:
  2995. case VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES:
  2996. case VIEW_DISPLAY_DEBUG_OCCLUDERS:
  2997. case VIEW_DISPLAY_MOTION_VECTORS:
  2998. case VIEW_DISPLAY_INTERNAL_BUFFER: {
  2999. static const int display_options[] = {
  3000. VIEW_DISPLAY_NORMAL,
  3001. VIEW_DISPLAY_WIREFRAME,
  3002. VIEW_DISPLAY_OVERDRAW,
  3003. VIEW_DISPLAY_UNSHADED,
  3004. VIEW_DISPLAY_LIGHTING,
  3005. VIEW_DISPLAY_NORMAL_BUFFER,
  3006. VIEW_DISPLAY_DEBUG_SHADOW_ATLAS,
  3007. VIEW_DISPLAY_DEBUG_DIRECTIONAL_SHADOW_ATLAS,
  3008. VIEW_DISPLAY_DEBUG_VOXEL_GI_ALBEDO,
  3009. VIEW_DISPLAY_DEBUG_VOXEL_GI_LIGHTING,
  3010. VIEW_DISPLAY_DEBUG_VOXEL_GI_EMISSION,
  3011. VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE,
  3012. VIEW_DISPLAY_DEBUG_SSAO,
  3013. VIEW_DISPLAY_DEBUG_SSIL,
  3014. VIEW_DISPLAY_DEBUG_GI_BUFFER,
  3015. VIEW_DISPLAY_DEBUG_DISABLE_LOD,
  3016. VIEW_DISPLAY_DEBUG_PSSM_SPLITS,
  3017. VIEW_DISPLAY_DEBUG_DECAL_ATLAS,
  3018. VIEW_DISPLAY_DEBUG_SDFGI,
  3019. VIEW_DISPLAY_DEBUG_SDFGI_PROBES,
  3020. VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS,
  3021. VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS,
  3022. VIEW_DISPLAY_DEBUG_CLUSTER_DECALS,
  3023. VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES,
  3024. VIEW_DISPLAY_DEBUG_OCCLUDERS,
  3025. VIEW_DISPLAY_MOTION_VECTORS,
  3026. VIEW_DISPLAY_INTERNAL_BUFFER,
  3027. VIEW_MAX
  3028. };
  3029. static const Viewport::DebugDraw debug_draw_modes[] = {
  3030. Viewport::DEBUG_DRAW_DISABLED,
  3031. Viewport::DEBUG_DRAW_WIREFRAME,
  3032. Viewport::DEBUG_DRAW_OVERDRAW,
  3033. Viewport::DEBUG_DRAW_UNSHADED,
  3034. Viewport::DEBUG_DRAW_LIGHTING,
  3035. Viewport::DEBUG_DRAW_NORMAL_BUFFER,
  3036. Viewport::DEBUG_DRAW_SHADOW_ATLAS,
  3037. Viewport::DEBUG_DRAW_DIRECTIONAL_SHADOW_ATLAS,
  3038. Viewport::DEBUG_DRAW_VOXEL_GI_ALBEDO,
  3039. Viewport::DEBUG_DRAW_VOXEL_GI_LIGHTING,
  3040. Viewport::DEBUG_DRAW_VOXEL_GI_EMISSION,
  3041. Viewport::DEBUG_DRAW_SCENE_LUMINANCE,
  3042. Viewport::DEBUG_DRAW_SSAO,
  3043. Viewport::DEBUG_DRAW_SSIL,
  3044. Viewport::DEBUG_DRAW_GI_BUFFER,
  3045. Viewport::DEBUG_DRAW_DISABLE_LOD,
  3046. Viewport::DEBUG_DRAW_PSSM_SPLITS,
  3047. Viewport::DEBUG_DRAW_DECAL_ATLAS,
  3048. Viewport::DEBUG_DRAW_SDFGI,
  3049. Viewport::DEBUG_DRAW_SDFGI_PROBES,
  3050. Viewport::DEBUG_DRAW_CLUSTER_OMNI_LIGHTS,
  3051. Viewport::DEBUG_DRAW_CLUSTER_SPOT_LIGHTS,
  3052. Viewport::DEBUG_DRAW_CLUSTER_DECALS,
  3053. Viewport::DEBUG_DRAW_CLUSTER_REFLECTION_PROBES,
  3054. Viewport::DEBUG_DRAW_OCCLUDERS,
  3055. Viewport::DEBUG_DRAW_MOTION_VECTORS,
  3056. Viewport::DEBUG_DRAW_INTERNAL_BUFFER,
  3057. };
  3058. for (int idx = 0; display_options[idx] != VIEW_MAX; idx++) {
  3059. int id = display_options[idx];
  3060. int item_idx = view_menu->get_popup()->get_item_index(id);
  3061. if (item_idx != -1) {
  3062. view_menu->get_popup()->set_item_checked(item_idx, id == p_option);
  3063. }
  3064. item_idx = display_submenu->get_item_index(id);
  3065. if (item_idx != -1) {
  3066. display_submenu->set_item_checked(item_idx, id == p_option);
  3067. }
  3068. if (id == p_option) {
  3069. viewport->set_debug_draw(debug_draw_modes[idx]);
  3070. }
  3071. }
  3072. } break;
  3073. }
  3074. }
  3075. void Node3DEditorViewport::_set_auto_orthogonal() {
  3076. if (!orthogonal && view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL))) {
  3077. _menu_option(VIEW_ORTHOGONAL);
  3078. auto_orthogonal = true;
  3079. }
  3080. }
  3081. void Node3DEditorViewport::_preview_exited_scene() {
  3082. preview_camera->disconnect("toggled", callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  3083. preview_camera->set_pressed(false);
  3084. _toggle_camera_preview(false);
  3085. preview_camera->connect("toggled", callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  3086. view_menu->show();
  3087. }
  3088. void Node3DEditorViewport::_init_gizmo_instance(int p_idx) {
  3089. uint32_t layer = 1 << (GIZMO_BASE_LAYER + p_idx);
  3090. for (int i = 0; i < 3; i++) {
  3091. move_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3092. RS::get_singleton()->instance_set_base(move_gizmo_instance[i], spatial_editor->get_move_gizmo(i)->get_rid());
  3093. RS::get_singleton()->instance_set_scenario(move_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3094. RS::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  3095. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3096. RS::get_singleton()->instance_set_layer_mask(move_gizmo_instance[i], layer);
  3097. RS::get_singleton()->instance_geometry_set_flag(move_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3098. RS::get_singleton()->instance_geometry_set_flag(move_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3099. move_plane_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3100. RS::get_singleton()->instance_set_base(move_plane_gizmo_instance[i], spatial_editor->get_move_plane_gizmo(i)->get_rid());
  3101. RS::get_singleton()->instance_set_scenario(move_plane_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3102. RS::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  3103. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_plane_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3104. RS::get_singleton()->instance_set_layer_mask(move_plane_gizmo_instance[i], layer);
  3105. RS::get_singleton()->instance_geometry_set_flag(move_plane_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3106. RS::get_singleton()->instance_geometry_set_flag(move_plane_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3107. rotate_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3108. RS::get_singleton()->instance_set_base(rotate_gizmo_instance[i], spatial_editor->get_rotate_gizmo(i)->get_rid());
  3109. RS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3110. RS::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  3111. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3112. RS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[i], layer);
  3113. RS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3114. RS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3115. scale_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3116. RS::get_singleton()->instance_set_base(scale_gizmo_instance[i], spatial_editor->get_scale_gizmo(i)->get_rid());
  3117. RS::get_singleton()->instance_set_scenario(scale_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3118. RS::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  3119. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3120. RS::get_singleton()->instance_set_layer_mask(scale_gizmo_instance[i], layer);
  3121. RS::get_singleton()->instance_geometry_set_flag(scale_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3122. RS::get_singleton()->instance_geometry_set_flag(scale_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3123. scale_plane_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3124. RS::get_singleton()->instance_set_base(scale_plane_gizmo_instance[i], spatial_editor->get_scale_plane_gizmo(i)->get_rid());
  3125. RS::get_singleton()->instance_set_scenario(scale_plane_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3126. RS::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  3127. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_plane_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3128. RS::get_singleton()->instance_set_layer_mask(scale_plane_gizmo_instance[i], layer);
  3129. RS::get_singleton()->instance_geometry_set_flag(scale_plane_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3130. RS::get_singleton()->instance_geometry_set_flag(scale_plane_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3131. axis_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3132. RS::get_singleton()->instance_set_base(axis_gizmo_instance[i], spatial_editor->get_axis_gizmo(i)->get_rid());
  3133. RS::get_singleton()->instance_set_scenario(axis_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3134. RS::get_singleton()->instance_set_visible(axis_gizmo_instance[i], true);
  3135. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(axis_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3136. RS::get_singleton()->instance_set_layer_mask(axis_gizmo_instance[i], layer);
  3137. RS::get_singleton()->instance_geometry_set_flag(axis_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3138. RS::get_singleton()->instance_geometry_set_flag(axis_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3139. }
  3140. // Rotation white outline
  3141. rotate_gizmo_instance[3] = RS::get_singleton()->instance_create();
  3142. RS::get_singleton()->instance_set_base(rotate_gizmo_instance[3], spatial_editor->get_rotate_gizmo(3)->get_rid());
  3143. RS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[3], get_tree()->get_root()->get_world_3d()->get_scenario());
  3144. RS::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
  3145. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[3], RS::SHADOW_CASTING_SETTING_OFF);
  3146. RS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[3], layer);
  3147. RS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[3], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3148. RS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[3], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3149. }
  3150. void Node3DEditorViewport::_finish_gizmo_instances() {
  3151. ERR_FAIL_NULL(RenderingServer::get_singleton());
  3152. for (int i = 0; i < 3; i++) {
  3153. RS::get_singleton()->free(move_gizmo_instance[i]);
  3154. RS::get_singleton()->free(move_plane_gizmo_instance[i]);
  3155. RS::get_singleton()->free(rotate_gizmo_instance[i]);
  3156. RS::get_singleton()->free(scale_gizmo_instance[i]);
  3157. RS::get_singleton()->free(scale_plane_gizmo_instance[i]);
  3158. RS::get_singleton()->free(axis_gizmo_instance[i]);
  3159. }
  3160. // Rotation white outline
  3161. RS::get_singleton()->free(rotate_gizmo_instance[3]);
  3162. }
  3163. void Node3DEditorViewport::_toggle_camera_preview(bool p_activate) {
  3164. ERR_FAIL_COND(p_activate && !preview);
  3165. ERR_FAIL_COND(!p_activate && !previewing);
  3166. previewing_camera = p_activate;
  3167. _update_navigation_controls_visibility();
  3168. if (!p_activate) {
  3169. previewing->disconnect(SceneStringName(tree_exiting), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  3170. previewing = nullptr;
  3171. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
  3172. if (!preview) {
  3173. preview_camera->hide();
  3174. }
  3175. surface->queue_redraw();
  3176. } else {
  3177. previewing = preview;
  3178. previewing->connect(SceneStringName(tree_exiting), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  3179. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), preview->get_camera()); //replace
  3180. surface->queue_redraw();
  3181. }
  3182. }
  3183. void Node3DEditorViewport::_toggle_cinema_preview(bool p_activate) {
  3184. previewing_cinema = p_activate;
  3185. _update_navigation_controls_visibility();
  3186. if (!previewing_cinema) {
  3187. if (previewing != nullptr) {
  3188. previewing->disconnect(SceneStringName(tree_exited), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  3189. }
  3190. previewing = nullptr;
  3191. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
  3192. preview_camera->set_pressed(false);
  3193. if (!preview) {
  3194. preview_camera->hide();
  3195. } else {
  3196. preview_camera->show();
  3197. }
  3198. view_menu->show();
  3199. surface->queue_redraw();
  3200. }
  3201. }
  3202. void Node3DEditorViewport::_selection_result_pressed(int p_result) {
  3203. if (selection_results_menu.size() <= p_result) {
  3204. return;
  3205. }
  3206. clicked = selection_results_menu[p_result]->get_instance_id();
  3207. if (clicked.is_valid()) {
  3208. _select_clicked(spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT);
  3209. }
  3210. selection_results_menu.clear();
  3211. }
  3212. void Node3DEditorViewport::_selection_menu_hide() {
  3213. selection_results.clear();
  3214. selection_menu->clear();
  3215. selection_menu->reset_size();
  3216. }
  3217. void Node3DEditorViewport::set_can_preview(Camera3D *p_preview) {
  3218. preview = p_preview;
  3219. if (!preview_camera->is_pressed() && !previewing_cinema) {
  3220. preview_camera->set_visible(p_preview);
  3221. }
  3222. }
  3223. void Node3DEditorViewport::update_transform_gizmo_view() {
  3224. if (!is_visible_in_tree()) {
  3225. return;
  3226. }
  3227. Transform3D xform = spatial_editor->get_gizmo_transform();
  3228. Transform3D camera_xform = camera->get_transform();
  3229. if (xform.origin.is_equal_approx(camera_xform.origin)) {
  3230. for (int i = 0; i < 3; i++) {
  3231. RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  3232. RenderingServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  3233. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  3234. RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  3235. RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  3236. RenderingServer::get_singleton()->instance_set_visible(axis_gizmo_instance[i], false);
  3237. }
  3238. // Rotation white outline
  3239. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
  3240. return;
  3241. }
  3242. const Vector3 camz = -camera_xform.get_basis().get_column(2).normalized();
  3243. const Vector3 camy = -camera_xform.get_basis().get_column(1).normalized();
  3244. const Plane p = Plane(camz, camera_xform.origin);
  3245. const real_t gizmo_d = MAX(Math::abs(p.distance_to(xform.origin)), CMP_EPSILON);
  3246. const real_t d0 = camera->unproject_position(camera_xform.origin + camz * gizmo_d).y;
  3247. const real_t d1 = camera->unproject_position(camera_xform.origin + camz * gizmo_d + camy).y;
  3248. const real_t dd = MAX(Math::abs(d0 - d1), CMP_EPSILON);
  3249. const real_t gizmo_size = EDITOR_GET("editors/3d/manipulator_gizmo_size");
  3250. // At low viewport heights, multiply the gizmo scale based on the viewport height.
  3251. // This prevents the gizmo from growing very large and going outside the viewport.
  3252. const int viewport_base_height = 400 * MAX(1, EDSCALE);
  3253. gizmo_scale =
  3254. (gizmo_size / Math::abs(dd)) * MAX(1, EDSCALE) *
  3255. MIN(viewport_base_height, subviewport_container->get_size().height) / viewport_base_height /
  3256. subviewport_container->get_stretch_shrink();
  3257. Vector3 scale = Vector3(1, 1, 1) * gizmo_scale;
  3258. // if the determinant is zero, we should disable the gizmo from being rendered
  3259. // this prevents supplying bad values to the renderer and then having to filter it out again
  3260. if (xform.basis.determinant() == 0) {
  3261. for (int i = 0; i < 3; i++) {
  3262. RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  3263. RenderingServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  3264. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  3265. RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  3266. RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  3267. }
  3268. // Rotation white outline
  3269. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
  3270. return;
  3271. }
  3272. bool show_gizmo = spatial_editor->is_gizmo_visible() && !_edit.instant;
  3273. for (int i = 0; i < 3; i++) {
  3274. Transform3D axis_angle;
  3275. if (xform.basis.get_column(i).normalized().dot(xform.basis.get_column((i + 1) % 3).normalized()) < 1.0) {
  3276. axis_angle = axis_angle.looking_at(xform.basis.get_column(i).normalized(), xform.basis.get_column((i + 1) % 3).normalized());
  3277. }
  3278. axis_angle.basis.scale(scale);
  3279. axis_angle.origin = xform.origin;
  3280. RenderingServer::get_singleton()->instance_set_transform(move_gizmo_instance[i], axis_angle);
  3281. RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE));
  3282. RenderingServer::get_singleton()->instance_set_transform(move_plane_gizmo_instance[i], axis_angle);
  3283. RenderingServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE));
  3284. RenderingServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[i], axis_angle);
  3285. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE));
  3286. RenderingServer::get_singleton()->instance_set_transform(scale_gizmo_instance[i], axis_angle);
  3287. RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE));
  3288. RenderingServer::get_singleton()->instance_set_transform(scale_plane_gizmo_instance[i], axis_angle);
  3289. RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE));
  3290. RenderingServer::get_singleton()->instance_set_transform(axis_gizmo_instance[i], xform);
  3291. }
  3292. bool show_axes = spatial_editor->is_gizmo_visible() && _edit.mode != TRANSFORM_NONE;
  3293. RenderingServer *rs = RenderingServer::get_singleton();
  3294. rs->instance_set_visible(axis_gizmo_instance[0], show_axes && (_edit.plane == TRANSFORM_X_AXIS || _edit.plane == TRANSFORM_XY || _edit.plane == TRANSFORM_XZ));
  3295. rs->instance_set_visible(axis_gizmo_instance[1], show_axes && (_edit.plane == TRANSFORM_Y_AXIS || _edit.plane == TRANSFORM_XY || _edit.plane == TRANSFORM_YZ));
  3296. rs->instance_set_visible(axis_gizmo_instance[2], show_axes && (_edit.plane == TRANSFORM_Z_AXIS || _edit.plane == TRANSFORM_XZ || _edit.plane == TRANSFORM_YZ));
  3297. // Rotation white outline
  3298. xform.orthonormalize();
  3299. xform.basis.scale(scale);
  3300. RenderingServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[3], xform);
  3301. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE));
  3302. }
  3303. void Node3DEditorViewport::set_state(const Dictionary &p_state) {
  3304. if (p_state.has("position")) {
  3305. cursor.pos = p_state["position"];
  3306. }
  3307. if (p_state.has("x_rotation")) {
  3308. cursor.x_rot = p_state["x_rotation"];
  3309. }
  3310. if (p_state.has("y_rotation")) {
  3311. cursor.y_rot = p_state["y_rotation"];
  3312. }
  3313. if (p_state.has("distance")) {
  3314. cursor.distance = p_state["distance"];
  3315. }
  3316. if (p_state.has("orthogonal")) {
  3317. bool orth = p_state["orthogonal"];
  3318. _menu_option(orth ? VIEW_ORTHOGONAL : VIEW_PERSPECTIVE);
  3319. }
  3320. if (p_state.has("view_type")) {
  3321. view_type = ViewType(p_state["view_type"].operator int());
  3322. _update_name();
  3323. }
  3324. if (p_state.has("auto_orthogonal")) {
  3325. auto_orthogonal = p_state["auto_orthogonal"];
  3326. _update_name();
  3327. }
  3328. if (p_state.has("auto_orthogonal_enabled")) {
  3329. bool enabled = p_state["auto_orthogonal_enabled"];
  3330. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL), enabled);
  3331. }
  3332. if (p_state.has("display_mode")) {
  3333. int display = p_state["display_mode"];
  3334. int idx = view_menu->get_popup()->get_item_index(display);
  3335. if (idx != -1 && !view_menu->get_popup()->is_item_checked(idx)) {
  3336. _menu_option(display);
  3337. } else {
  3338. idx = display_submenu->get_item_index(display);
  3339. if (idx != -1 && !display_submenu->is_item_checked(idx)) {
  3340. _menu_option(display);
  3341. }
  3342. }
  3343. }
  3344. if (p_state.has("lock_rotation")) {
  3345. _set_lock_view_rotation(p_state["lock_rotation"]);
  3346. }
  3347. if (p_state.has("use_environment")) {
  3348. bool env = p_state["use_environment"];
  3349. if (env != camera->get_environment().is_valid()) {
  3350. _menu_option(VIEW_ENVIRONMENT);
  3351. }
  3352. }
  3353. if (p_state.has("listener")) {
  3354. bool listener = p_state["listener"];
  3355. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
  3356. viewport->set_as_audio_listener_3d(listener);
  3357. view_menu->get_popup()->set_item_checked(idx, listener);
  3358. }
  3359. if (p_state.has("doppler")) {
  3360. bool doppler = p_state["doppler"];
  3361. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
  3362. camera->set_doppler_tracking(doppler ? Camera3D::DOPPLER_TRACKING_IDLE_STEP : Camera3D::DOPPLER_TRACKING_DISABLED);
  3363. view_menu->get_popup()->set_item_checked(idx, doppler);
  3364. }
  3365. if (p_state.has("gizmos")) {
  3366. bool gizmos = p_state["gizmos"];
  3367. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  3368. if (view_menu->get_popup()->is_item_checked(idx) != gizmos) {
  3369. _menu_option(VIEW_GIZMOS);
  3370. }
  3371. }
  3372. if (p_state.has("information")) {
  3373. bool information = p_state["information"];
  3374. int idx = view_menu->get_popup()->get_item_index(VIEW_INFORMATION);
  3375. if (view_menu->get_popup()->is_item_checked(idx) != information) {
  3376. _menu_option(VIEW_INFORMATION);
  3377. }
  3378. }
  3379. if (p_state.has("frame_time")) {
  3380. bool fps = p_state["frame_time"];
  3381. int idx = view_menu->get_popup()->get_item_index(VIEW_FRAME_TIME);
  3382. if (view_menu->get_popup()->is_item_checked(idx) != fps) {
  3383. _menu_option(VIEW_FRAME_TIME);
  3384. }
  3385. }
  3386. if (p_state.has("half_res")) {
  3387. bool half_res = p_state["half_res"];
  3388. int idx = view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
  3389. view_menu->get_popup()->set_item_checked(idx, half_res);
  3390. _update_shrink();
  3391. }
  3392. if (p_state.has("cinematic_preview")) {
  3393. previewing_cinema = p_state["cinematic_preview"];
  3394. int idx = view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
  3395. view_menu->get_popup()->set_item_checked(idx, previewing_cinema);
  3396. }
  3397. if (preview_camera->is_connected("toggled", callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview))) {
  3398. preview_camera->disconnect("toggled", callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  3399. }
  3400. if (p_state.has("previewing")) {
  3401. Node *pv = EditorNode::get_singleton()->get_edited_scene()->get_node(p_state["previewing"]);
  3402. if (Object::cast_to<Camera3D>(pv)) {
  3403. previewing = Object::cast_to<Camera3D>(pv);
  3404. previewing->connect(SceneStringName(tree_exiting), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  3405. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), previewing->get_camera()); //replace
  3406. surface->queue_redraw();
  3407. preview_camera->set_pressed(true);
  3408. preview_camera->show();
  3409. }
  3410. }
  3411. preview_camera->connect("toggled", callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  3412. }
  3413. Dictionary Node3DEditorViewport::get_state() const {
  3414. Dictionary d;
  3415. d["position"] = cursor.pos;
  3416. d["x_rotation"] = cursor.x_rot;
  3417. d["y_rotation"] = cursor.y_rot;
  3418. d["distance"] = cursor.distance;
  3419. d["use_environment"] = camera->get_environment().is_valid();
  3420. d["orthogonal"] = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
  3421. d["view_type"] = view_type;
  3422. d["auto_orthogonal"] = auto_orthogonal;
  3423. d["auto_orthogonal_enabled"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL));
  3424. // Find selected display mode.
  3425. int display_mode = VIEW_DISPLAY_NORMAL;
  3426. for (int i = VIEW_DISPLAY_NORMAL; i < VIEW_DISPLAY_ADVANCED; i++) {
  3427. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(i))) {
  3428. display_mode = i;
  3429. break;
  3430. }
  3431. }
  3432. for (int i = VIEW_DISPLAY_ADVANCED + 1; i < VIEW_DISPLAY_MAX; i++) {
  3433. if (display_submenu->is_item_checked(display_submenu->get_item_index(i))) {
  3434. display_mode = i;
  3435. break;
  3436. }
  3437. }
  3438. d["display_mode"] = display_mode;
  3439. d["listener"] = viewport->is_audio_listener_3d();
  3440. d["doppler"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER));
  3441. d["gizmos"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_GIZMOS));
  3442. d["information"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_INFORMATION));
  3443. d["frame_time"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_FRAME_TIME));
  3444. d["half_res"] = subviewport_container->get_stretch_shrink() > 1;
  3445. d["cinematic_preview"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
  3446. if (previewing) {
  3447. d["previewing"] = EditorNode::get_singleton()->get_edited_scene()->get_path_to(previewing);
  3448. }
  3449. d["lock_rotation"] = lock_rotation;
  3450. return d;
  3451. }
  3452. void Node3DEditorViewport::_bind_methods() {
  3453. ADD_SIGNAL(MethodInfo("toggle_maximize_view", PropertyInfo(Variant::OBJECT, "viewport")));
  3454. ADD_SIGNAL(MethodInfo("clicked", PropertyInfo(Variant::OBJECT, "viewport")));
  3455. }
  3456. void Node3DEditorViewport::reset() {
  3457. orthogonal = false;
  3458. auto_orthogonal = false;
  3459. lock_rotation = false;
  3460. message_time = 0;
  3461. message = "";
  3462. last_message = "";
  3463. view_type = VIEW_TYPE_USER;
  3464. cursor = Cursor();
  3465. _update_name();
  3466. }
  3467. void Node3DEditorViewport::focus_selection() {
  3468. Vector3 center;
  3469. int count = 0;
  3470. const List<Node *> &selection = editor_selection->get_selected_node_list();
  3471. for (Node *E : selection) {
  3472. Node3D *sp = Object::cast_to<Node3D>(E);
  3473. if (!sp) {
  3474. continue;
  3475. }
  3476. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  3477. if (!se) {
  3478. continue;
  3479. }
  3480. if (se->gizmo.is_valid()) {
  3481. for (const KeyValue<int, Transform3D> &GE : se->subgizmos) {
  3482. center += se->gizmo->get_subgizmo_transform(GE.key).origin;
  3483. count++;
  3484. }
  3485. }
  3486. center += sp->get_global_gizmo_transform().origin;
  3487. count++;
  3488. }
  3489. if (count != 0) {
  3490. center /= count;
  3491. }
  3492. cursor.pos = center;
  3493. }
  3494. void Node3DEditorViewport::assign_pending_data_pointers(Node3D *p_preview_node, AABB *p_preview_bounds, AcceptDialog *p_accept) {
  3495. preview_node = p_preview_node;
  3496. preview_bounds = p_preview_bounds;
  3497. accept = p_accept;
  3498. }
  3499. Vector3 Node3DEditorViewport::_get_instance_position(const Point2 &p_pos) const {
  3500. const float MAX_DISTANCE = 50.0;
  3501. const float FALLBACK_DISTANCE = 5.0;
  3502. Vector3 world_ray = get_ray(p_pos);
  3503. Vector3 world_pos = get_ray_pos(p_pos);
  3504. PhysicsDirectSpaceState3D *ss = get_tree()->get_root()->get_world_3d()->get_direct_space_state();
  3505. PhysicsDirectSpaceState3D::RayParameters ray_params;
  3506. ray_params.from = world_pos;
  3507. ray_params.to = world_pos + world_ray * camera->get_far();
  3508. PhysicsDirectSpaceState3D::RayResult result;
  3509. if (ss->intersect_ray(ray_params, result)) {
  3510. return result.position;
  3511. }
  3512. const bool is_orthogonal = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
  3513. // The XZ plane.
  3514. Vector3 intersection;
  3515. Plane plane(Vector3(0, 1, 0));
  3516. if (plane.intersects_ray(world_pos, world_ray, &intersection)) {
  3517. if (is_orthogonal || world_pos.distance_to(intersection) <= MAX_DISTANCE) {
  3518. return intersection;
  3519. }
  3520. }
  3521. // Plane facing the camera using fallback distance.
  3522. if (is_orthogonal) {
  3523. plane = Plane(world_ray, cursor.pos - world_ray * (cursor.distance - FALLBACK_DISTANCE));
  3524. } else {
  3525. plane = Plane(world_ray, world_pos + world_ray * FALLBACK_DISTANCE);
  3526. }
  3527. if (plane.intersects_ray(world_pos, world_ray, &intersection)) {
  3528. return intersection;
  3529. }
  3530. // Not likely, but just in case...
  3531. return world_pos + world_ray * FALLBACK_DISTANCE;
  3532. }
  3533. AABB Node3DEditorViewport::_calculate_spatial_bounds(const Node3D *p_parent, const Node3D *p_top_level_parent) {
  3534. AABB bounds;
  3535. if (!p_top_level_parent) {
  3536. p_top_level_parent = p_parent;
  3537. }
  3538. if (!p_parent) {
  3539. return AABB(Vector3(-0.2, -0.2, -0.2), Vector3(0.4, 0.4, 0.4));
  3540. }
  3541. Transform3D xform_to_top_level_parent_space = p_top_level_parent->get_global_transform().affine_inverse() * p_parent->get_global_transform();
  3542. const VisualInstance3D *visual_instance = Object::cast_to<VisualInstance3D>(p_parent);
  3543. if (visual_instance) {
  3544. bounds = visual_instance->get_aabb();
  3545. } else {
  3546. bounds = AABB();
  3547. }
  3548. bounds = xform_to_top_level_parent_space.xform(bounds);
  3549. for (int i = 0; i < p_parent->get_child_count(); i++) {
  3550. Node3D *child = Object::cast_to<Node3D>(p_parent->get_child(i));
  3551. if (child) {
  3552. AABB child_bounds = _calculate_spatial_bounds(child, p_top_level_parent);
  3553. bounds.merge_with(child_bounds);
  3554. }
  3555. }
  3556. return bounds;
  3557. }
  3558. Node *Node3DEditorViewport::_sanitize_preview_node(Node *p_node) const {
  3559. Node3D *node_3d = Object::cast_to<Node3D>(p_node);
  3560. if (node_3d == nullptr) {
  3561. Node3D *replacement_node = memnew(Node3D);
  3562. replacement_node->set_name(p_node->get_name());
  3563. p_node->replace_by(replacement_node);
  3564. memdelete(p_node);
  3565. p_node = replacement_node;
  3566. } else {
  3567. VisualInstance3D *visual_instance = Object::cast_to<VisualInstance3D>(node_3d);
  3568. if (visual_instance == nullptr) {
  3569. Node3D *replacement_node = memnew(Node3D);
  3570. replacement_node->set_name(node_3d->get_name());
  3571. replacement_node->set_visible(node_3d->is_visible());
  3572. replacement_node->set_transform(node_3d->get_transform());
  3573. replacement_node->set_rotation_edit_mode(node_3d->get_rotation_edit_mode());
  3574. replacement_node->set_rotation_order(node_3d->get_rotation_order());
  3575. replacement_node->set_as_top_level(node_3d->is_set_as_top_level());
  3576. p_node->replace_by(replacement_node);
  3577. memdelete(p_node);
  3578. p_node = replacement_node;
  3579. }
  3580. }
  3581. for (int i = 0; i < p_node->get_child_count(); i++) {
  3582. _sanitize_preview_node(p_node->get_child(i));
  3583. }
  3584. return p_node;
  3585. }
  3586. void Node3DEditorViewport::_create_preview_node(const Vector<String> &files) const {
  3587. bool add_preview = false;
  3588. for (const String &path : files) {
  3589. Ref<Resource> res = ResourceLoader::load(path);
  3590. ERR_CONTINUE(res.is_null());
  3591. Ref<PackedScene> scene = res;
  3592. if (scene.is_valid()) {
  3593. Node *instance = scene->instantiate();
  3594. if (instance) {
  3595. instance = _sanitize_preview_node(instance);
  3596. preview_node->add_child(instance);
  3597. }
  3598. add_preview = true;
  3599. }
  3600. Ref<Mesh> mesh = res;
  3601. if (mesh.is_valid()) {
  3602. MeshInstance3D *mesh_instance = memnew(MeshInstance3D);
  3603. mesh_instance->set_mesh(mesh);
  3604. preview_node->add_child(mesh_instance);
  3605. add_preview = true;
  3606. }
  3607. Ref<AudioStream> audio = res;
  3608. if (audio.is_valid()) {
  3609. Sprite3D *sprite = memnew(Sprite3D);
  3610. sprite->set_texture(get_editor_theme_icon(SNAME("Gizmo3DSamplePlayer")));
  3611. sprite->set_billboard_mode(StandardMaterial3D::BILLBOARD_ENABLED);
  3612. sprite->set_pixel_size(0.005);
  3613. preview_node->add_child(sprite);
  3614. add_preview = true;
  3615. }
  3616. }
  3617. if (add_preview) {
  3618. EditorNode::get_singleton()->get_scene_root()->add_child(preview_node);
  3619. }
  3620. *preview_bounds = _calculate_spatial_bounds(preview_node);
  3621. }
  3622. void Node3DEditorViewport::_remove_preview_node() {
  3623. set_message("");
  3624. if (preview_node->get_parent()) {
  3625. for (int i = preview_node->get_child_count() - 1; i >= 0; i--) {
  3626. Node *node = preview_node->get_child(i);
  3627. node->queue_free();
  3628. preview_node->remove_child(node);
  3629. }
  3630. EditorNode::get_singleton()->get_scene_root()->remove_child(preview_node);
  3631. }
  3632. }
  3633. bool Node3DEditorViewport::_apply_preview_material(ObjectID p_target, const Point2 &p_point) const {
  3634. _reset_preview_material();
  3635. if (p_target.is_null()) {
  3636. return false;
  3637. }
  3638. spatial_editor->set_preview_material_target(p_target);
  3639. Object *target_inst = ObjectDB::get_instance(p_target);
  3640. bool is_ctrl = Input::get_singleton()->is_key_pressed(Key::CTRL);
  3641. MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(target_inst);
  3642. if (is_ctrl && mesh_instance) {
  3643. Ref<Mesh> mesh = mesh_instance->get_mesh();
  3644. int surface_count = mesh->get_surface_count();
  3645. Vector3 world_ray = get_ray(p_point);
  3646. Vector3 world_pos = get_ray_pos(p_point);
  3647. int closest_surface = -1;
  3648. float closest_dist = 1e20;
  3649. Transform3D gt = mesh_instance->get_global_transform();
  3650. Transform3D ai = gt.affine_inverse();
  3651. Vector3 xform_ray = ai.basis.xform(world_ray).normalized();
  3652. Vector3 xform_pos = ai.xform(world_pos);
  3653. for (int surface_idx = 0; surface_idx < surface_count; surface_idx++) {
  3654. Ref<TriangleMesh> surface_mesh = mesh->generate_surface_triangle_mesh(surface_idx);
  3655. Vector3 rpos, rnorm;
  3656. if (surface_mesh->intersect_ray(xform_pos, xform_ray, rpos, rnorm)) {
  3657. Vector3 hitpos = gt.xform(rpos);
  3658. const real_t dist = world_pos.distance_to(hitpos);
  3659. if (dist < 0) {
  3660. continue;
  3661. }
  3662. if (dist < closest_dist) {
  3663. closest_surface = surface_idx;
  3664. closest_dist = dist;
  3665. }
  3666. }
  3667. }
  3668. if (closest_surface == -1) {
  3669. return false;
  3670. }
  3671. spatial_editor->set_preview_material_surface(closest_surface);
  3672. spatial_editor->set_preview_reset_material(mesh_instance->get_surface_override_material(closest_surface));
  3673. mesh_instance->set_surface_override_material(closest_surface, spatial_editor->get_preview_material());
  3674. return true;
  3675. }
  3676. GeometryInstance3D *geometry_instance = Object::cast_to<GeometryInstance3D>(target_inst);
  3677. if (geometry_instance) {
  3678. spatial_editor->set_preview_material_surface(-1);
  3679. spatial_editor->set_preview_reset_material(geometry_instance->get_material_override());
  3680. geometry_instance->set_material_override(spatial_editor->get_preview_material());
  3681. return true;
  3682. }
  3683. return false;
  3684. }
  3685. void Node3DEditorViewport::_reset_preview_material() const {
  3686. ObjectID last_target = spatial_editor->get_preview_material_target();
  3687. if (last_target.is_null()) {
  3688. return;
  3689. }
  3690. Object *last_target_inst = ObjectDB::get_instance(last_target);
  3691. MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(last_target_inst);
  3692. GeometryInstance3D *geometry_instance = Object::cast_to<GeometryInstance3D>(last_target_inst);
  3693. if (mesh_instance && spatial_editor->get_preview_material_surface() != -1) {
  3694. mesh_instance->set_surface_override_material(spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_reset_material());
  3695. } else if (geometry_instance) {
  3696. geometry_instance->set_material_override(spatial_editor->get_preview_reset_material());
  3697. }
  3698. }
  3699. void Node3DEditorViewport::_remove_preview_material() {
  3700. preview_material_label->hide();
  3701. preview_material_label_desc->hide();
  3702. spatial_editor->set_preview_material(Ref<Material>());
  3703. spatial_editor->set_preview_reset_material(Ref<Material>());
  3704. spatial_editor->set_preview_material_target(ObjectID());
  3705. spatial_editor->set_preview_material_surface(-1);
  3706. }
  3707. bool Node3DEditorViewport::_cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node) const {
  3708. if (p_desired_node->get_scene_file_path() == p_target_scene_path) {
  3709. return true;
  3710. }
  3711. int childCount = p_desired_node->get_child_count();
  3712. for (int i = 0; i < childCount; i++) {
  3713. Node *child = p_desired_node->get_child(i);
  3714. if (_cyclical_dependency_exists(p_target_scene_path, child)) {
  3715. return true;
  3716. }
  3717. }
  3718. return false;
  3719. }
  3720. bool Node3DEditorViewport::_create_instance(Node *p_parent, const String &p_path, const Point2 &p_point) {
  3721. Ref<Resource> res = ResourceLoader::load(p_path);
  3722. ERR_FAIL_COND_V(res.is_null(), false);
  3723. Ref<PackedScene> scene = res;
  3724. Ref<Mesh> mesh = res;
  3725. Node *instantiated_scene = nullptr;
  3726. if (mesh != nullptr || scene != nullptr) {
  3727. if (mesh != nullptr) {
  3728. MeshInstance3D *mesh_instance = memnew(MeshInstance3D);
  3729. mesh_instance->set_mesh(mesh);
  3730. // Adjust casing according to project setting. The file name is expected to be in snake_case, but will work for others.
  3731. const String &node_name = Node::adjust_name_casing(p_path.get_file().get_basename());
  3732. if (!node_name.is_empty()) {
  3733. mesh_instance->set_name(node_name);
  3734. }
  3735. instantiated_scene = mesh_instance;
  3736. } else {
  3737. if (!scene.is_valid()) { // invalid scene
  3738. return false;
  3739. } else {
  3740. instantiated_scene = scene->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
  3741. }
  3742. }
  3743. }
  3744. if (instantiated_scene == nullptr) {
  3745. return false;
  3746. }
  3747. if (!EditorNode::get_singleton()->get_edited_scene()->get_scene_file_path().is_empty()) { // Cyclic instantiation.
  3748. if (_cyclical_dependency_exists(EditorNode::get_singleton()->get_edited_scene()->get_scene_file_path(), instantiated_scene)) {
  3749. memdelete(instantiated_scene);
  3750. return false;
  3751. }
  3752. }
  3753. if (scene != nullptr) {
  3754. instantiated_scene->set_scene_file_path(ProjectSettings::get_singleton()->localize_path(p_path));
  3755. }
  3756. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  3757. undo_redo->add_do_method(p_parent, "add_child", instantiated_scene, true);
  3758. undo_redo->add_do_method(instantiated_scene, "set_owner", EditorNode::get_singleton()->get_edited_scene());
  3759. undo_redo->add_do_reference(instantiated_scene);
  3760. undo_redo->add_undo_method(p_parent, "remove_child", instantiated_scene);
  3761. undo_redo->add_do_method(editor_selection, "add_node", instantiated_scene);
  3762. String new_name = p_parent->validate_child_name(instantiated_scene);
  3763. EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
  3764. undo_redo->add_do_method(ed, "live_debug_instantiate_node", EditorNode::get_singleton()->get_edited_scene()->get_path_to(p_parent), p_path, new_name);
  3765. undo_redo->add_undo_method(ed, "live_debug_remove_node", NodePath(String(EditorNode::get_singleton()->get_edited_scene()->get_path_to(p_parent)) + "/" + new_name));
  3766. Node3D *node3d = Object::cast_to<Node3D>(instantiated_scene);
  3767. if (node3d) {
  3768. Transform3D parent_tf;
  3769. Node3D *parent_node3d = Object::cast_to<Node3D>(p_parent);
  3770. if (parent_node3d) {
  3771. parent_tf = parent_node3d->get_global_gizmo_transform();
  3772. }
  3773. Transform3D new_tf = node3d->get_transform();
  3774. new_tf.origin = parent_tf.affine_inverse().xform(preview_node_pos + node3d->get_position());
  3775. new_tf.basis = parent_tf.affine_inverse().basis * new_tf.basis;
  3776. undo_redo->add_do_method(instantiated_scene, "set_transform", new_tf);
  3777. }
  3778. return true;
  3779. }
  3780. bool Node3DEditorViewport::_create_audio_node(Node *p_parent, const String &p_path, const Point2 &p_point) {
  3781. Ref<AudioStream> audio = ResourceLoader::load(p_path);
  3782. ERR_FAIL_COND_V(audio.is_null(), false);
  3783. AudioStreamPlayer3D *audio_player = memnew(AudioStreamPlayer3D);
  3784. audio_player->set_stream(audio);
  3785. // Adjust casing according to project setting. The file name is expected to be in snake_case, but will work for others.
  3786. const String &node_name = Node::adjust_name_casing(p_path.get_file().get_basename());
  3787. if (!node_name.is_empty()) {
  3788. audio_player->set_name(node_name);
  3789. }
  3790. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  3791. undo_redo->add_do_method(p_parent, "add_child", audio_player, true);
  3792. undo_redo->add_do_method(audio_player, "set_owner", EditorNode::get_singleton()->get_edited_scene());
  3793. undo_redo->add_do_reference(audio_player);
  3794. undo_redo->add_undo_method(p_parent, "remove_child", audio_player);
  3795. undo_redo->add_do_method(editor_selection, "add_node", audio_player);
  3796. const String new_name = p_parent->validate_child_name(audio_player);
  3797. EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
  3798. undo_redo->add_do_method(ed, "live_debug_create_node", EditorNode::get_singleton()->get_edited_scene()->get_path_to(p_parent), audio_player->get_class(), new_name);
  3799. undo_redo->add_undo_method(ed, "live_debug_remove_node", NodePath(String(EditorNode::get_singleton()->get_edited_scene()->get_path_to(p_parent)) + "/" + new_name));
  3800. Transform3D parent_tf;
  3801. Node3D *parent_node3d = Object::cast_to<Node3D>(p_parent);
  3802. if (parent_node3d) {
  3803. parent_tf = parent_node3d->get_global_gizmo_transform();
  3804. }
  3805. Transform3D new_tf = audio_player->get_transform();
  3806. new_tf.origin = parent_tf.affine_inverse().xform(preview_node_pos + audio_player->get_position());
  3807. new_tf.basis = parent_tf.affine_inverse().basis * new_tf.basis;
  3808. undo_redo->add_do_method(audio_player, "set_transform", new_tf);
  3809. return true;
  3810. }
  3811. void Node3DEditorViewport::_perform_drop_data() {
  3812. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  3813. if (spatial_editor->get_preview_material_target().is_valid()) {
  3814. GeometryInstance3D *geometry_instance = Object::cast_to<GeometryInstance3D>(ObjectDB::get_instance(spatial_editor->get_preview_material_target()));
  3815. MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(ObjectDB::get_instance(spatial_editor->get_preview_material_target()));
  3816. if (mesh_instance && spatial_editor->get_preview_material_surface() != -1) {
  3817. undo_redo->create_action(vformat(TTR("Set Surface %d Override Material"), spatial_editor->get_preview_material_surface()));
  3818. undo_redo->add_do_method(geometry_instance, "set_surface_override_material", spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_material());
  3819. undo_redo->add_undo_method(geometry_instance, "set_surface_override_material", spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_reset_material());
  3820. undo_redo->commit_action();
  3821. } else if (geometry_instance) {
  3822. undo_redo->create_action(TTR("Set Material Override"));
  3823. undo_redo->add_do_method(geometry_instance, "set_material_override", spatial_editor->get_preview_material());
  3824. undo_redo->add_undo_method(geometry_instance, "set_material_override", spatial_editor->get_preview_reset_material());
  3825. undo_redo->commit_action();
  3826. }
  3827. _remove_preview_material();
  3828. return;
  3829. }
  3830. _remove_preview_node();
  3831. PackedStringArray error_files;
  3832. undo_redo->create_action(TTR("Create Node"), UndoRedo::MERGE_DISABLE, target_node);
  3833. undo_redo->add_do_method(editor_selection, "clear");
  3834. for (int i = 0; i < selected_files.size(); i++) {
  3835. String path = selected_files[i];
  3836. Ref<Resource> res = ResourceLoader::load(path);
  3837. if (res.is_null()) {
  3838. continue;
  3839. }
  3840. Ref<PackedScene> scene = res;
  3841. Ref<Mesh> mesh = res;
  3842. if (mesh.is_valid() || scene.is_valid()) {
  3843. if (!_create_instance(target_node, path, drop_pos)) {
  3844. error_files.push_back(path.get_file());
  3845. }
  3846. }
  3847. Ref<AudioStream> audio = res;
  3848. if (audio.is_valid()) {
  3849. if (!_create_audio_node(target_node, path, drop_pos)) {
  3850. error_files.push_back(path.get_file());
  3851. }
  3852. }
  3853. }
  3854. undo_redo->commit_action();
  3855. if (error_files.size() > 0) {
  3856. accept->set_text(vformat(TTR("Error instantiating scene from %s."), String(", ").join(error_files)));
  3857. accept->popup_centered();
  3858. }
  3859. }
  3860. bool Node3DEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
  3861. preview_node_viewport_pos = p_point;
  3862. bool can_instantiate = false;
  3863. bool is_cyclical_dep = false;
  3864. String error_file;
  3865. if (!preview_node->is_inside_tree() && spatial_editor->get_preview_material().is_null()) {
  3866. Dictionary d = p_data;
  3867. if (d.has("type") && (String(d["type"]) == "files")) {
  3868. Vector<String> files = d["files"];
  3869. // Track whether a type other than PackedScene is valid to stop checking them and only
  3870. // continue to check if the rest of the scenes are valid (don't have cyclic dependencies).
  3871. bool is_other_valid = false;
  3872. // Check if at least one of the dragged files is a mesh, material, texture or scene.
  3873. for (int i = 0; i < files.size(); i++) {
  3874. const String &res_type = ResourceLoader::get_resource_type(files[i]);
  3875. bool is_scene = ClassDB::is_parent_class(res_type, "PackedScene");
  3876. bool is_mesh = ClassDB::is_parent_class(res_type, "Mesh");
  3877. bool is_material = ClassDB::is_parent_class(res_type, "Material");
  3878. bool is_texture = ClassDB::is_parent_class(res_type, "Texture");
  3879. bool is_audio = ClassDB::is_parent_class(res_type, "AudioStream");
  3880. if (is_mesh || is_scene || is_material || is_texture || is_audio) {
  3881. Ref<Resource> res = ResourceLoader::load(files[i]);
  3882. if (res.is_null()) {
  3883. continue;
  3884. }
  3885. Ref<PackedScene> scn = res;
  3886. Ref<Mesh> mesh = res;
  3887. Ref<Material> mat = res;
  3888. Ref<Texture2D> tex = res;
  3889. Ref<AudioStream> audio = res;
  3890. if (scn.is_valid()) {
  3891. Node *instantiated_scene = scn->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
  3892. if (!instantiated_scene) {
  3893. continue;
  3894. }
  3895. Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
  3896. if (edited_scene && !edited_scene->get_scene_file_path().is_empty() && _cyclical_dependency_exists(edited_scene->get_scene_file_path(), instantiated_scene)) {
  3897. memdelete(instantiated_scene);
  3898. can_instantiate = false;
  3899. is_cyclical_dep = true;
  3900. error_file = files[i].get_file();
  3901. break;
  3902. }
  3903. memdelete(instantiated_scene);
  3904. } else if (!is_other_valid && mat.is_valid()) {
  3905. Ref<BaseMaterial3D> base_mat = res;
  3906. Ref<ShaderMaterial> shader_mat = res;
  3907. if (base_mat.is_null() && shader_mat.is_null()) {
  3908. continue;
  3909. }
  3910. spatial_editor->set_preview_material(mat);
  3911. is_other_valid = true;
  3912. continue;
  3913. } else if (!is_other_valid && mesh.is_valid()) {
  3914. // Let the mesh pass.
  3915. is_other_valid = true;
  3916. } else if (!is_other_valid && tex.is_valid()) {
  3917. Ref<StandardMaterial3D> new_mat = memnew(StandardMaterial3D);
  3918. new_mat->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, tex);
  3919. spatial_editor->set_preview_material(new_mat);
  3920. is_other_valid = true;
  3921. continue;
  3922. } else if (!is_other_valid && audio.is_valid()) {
  3923. is_other_valid = true;
  3924. } else {
  3925. continue;
  3926. }
  3927. can_instantiate = true;
  3928. }
  3929. }
  3930. if (can_instantiate) {
  3931. _create_preview_node(files);
  3932. preview_node->hide();
  3933. }
  3934. }
  3935. } else {
  3936. if (preview_node->is_inside_tree()) {
  3937. can_instantiate = true;
  3938. }
  3939. }
  3940. if (is_cyclical_dep) {
  3941. set_message(vformat(TTR("Can't instantiate: %s."), vformat(TTR("Circular dependency found at %s"), error_file)));
  3942. return false;
  3943. }
  3944. if (can_instantiate) {
  3945. update_preview_node = true;
  3946. return true;
  3947. }
  3948. if (spatial_editor->get_preview_material().is_valid()) {
  3949. preview_material_label->show();
  3950. preview_material_label_desc->show();
  3951. ObjectID new_preview_material_target = _select_ray(p_point);
  3952. return _apply_preview_material(new_preview_material_target, p_point);
  3953. }
  3954. return false;
  3955. }
  3956. void Node3DEditorViewport::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
  3957. if (!can_drop_data_fw(p_point, p_data, p_from)) {
  3958. return;
  3959. }
  3960. bool is_shift = Input::get_singleton()->is_key_pressed(Key::SHIFT);
  3961. bool is_alt = Input::get_singleton()->is_key_pressed(Key::ALT);
  3962. selected_files.clear();
  3963. Dictionary d = p_data;
  3964. if (d.has("type") && String(d["type"]) == "files") {
  3965. selected_files = d["files"];
  3966. }
  3967. List<Node *> selected_nodes = EditorNode::get_singleton()->get_editor_selection()->get_selected_node_list();
  3968. Node *root_node = EditorNode::get_singleton()->get_edited_scene();
  3969. if (selected_nodes.size() > 0) {
  3970. Node *selected_node = selected_nodes.front()->get();
  3971. if (is_alt) {
  3972. target_node = root_node;
  3973. } else if (is_shift) {
  3974. target_node = selected_node;
  3975. } else { // Default behavior.
  3976. target_node = (selected_node != root_node) ? selected_node->get_parent() : root_node;
  3977. }
  3978. } else {
  3979. if (root_node) {
  3980. target_node = root_node;
  3981. } else {
  3982. // Create a root node so we can add child nodes to it.
  3983. SceneTreeDock::get_singleton()->add_root_node(memnew(Node3D));
  3984. target_node = get_tree()->get_edited_scene_root();
  3985. }
  3986. }
  3987. drop_pos = p_point;
  3988. _perform_drop_data();
  3989. }
  3990. void Node3DEditorViewport::begin_transform(TransformMode p_mode, bool instant) {
  3991. if (get_selected_count() > 0) {
  3992. _edit.mode = p_mode;
  3993. _compute_edit(_edit.mouse_pos);
  3994. _edit.instant = instant;
  3995. _edit.snap = spatial_editor->is_snap_enabled();
  3996. update_transform_gizmo_view();
  3997. set_process_input(instant);
  3998. }
  3999. }
  4000. // Apply the current transform operation.
  4001. void Node3DEditorViewport::commit_transform() {
  4002. ERR_FAIL_COND(_edit.mode == TRANSFORM_NONE);
  4003. static const char *_transform_name[4] = {
  4004. TTRC("None"),
  4005. TTRC("Rotate"),
  4006. // TRANSLATORS: This refers to the movement that changes the position of an object.
  4007. TTRC("Translate"),
  4008. TTRC("Scale"),
  4009. };
  4010. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  4011. undo_redo->create_action(_transform_name[_edit.mode]);
  4012. List<Node *> &selection = editor_selection->get_selected_node_list();
  4013. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4014. Node3D *sp = Object::cast_to<Node3D>(E->get());
  4015. if (!sp) {
  4016. continue;
  4017. }
  4018. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  4019. if (!se) {
  4020. continue;
  4021. }
  4022. undo_redo->add_do_method(sp, "set_transform", sp->get_local_gizmo_transform());
  4023. undo_redo->add_undo_method(sp, "set_transform", se->original_local);
  4024. }
  4025. undo_redo->commit_action();
  4026. finish_transform();
  4027. set_message("");
  4028. }
  4029. void Node3DEditorViewport::apply_transform(Vector3 p_motion, double p_snap) {
  4030. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  4031. List<Node *> &selection = editor_selection->get_selected_node_list();
  4032. for (Node *E : selection) {
  4033. Node3D *sp = Object::cast_to<Node3D>(E);
  4034. if (!sp) {
  4035. continue;
  4036. }
  4037. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  4038. if (!se) {
  4039. continue;
  4040. }
  4041. if (sp->has_meta("_edit_lock_")) {
  4042. continue;
  4043. }
  4044. if (se->gizmo.is_valid()) {
  4045. for (KeyValue<int, Transform3D> &GE : se->subgizmos) {
  4046. Transform3D xform = GE.value;
  4047. Transform3D new_xform = _compute_transform(_edit.mode, se->original * xform, xform, p_motion, p_snap, local_coords, _edit.plane != TRANSFORM_VIEW); // Force orthogonal with subgizmo.
  4048. if (!local_coords) {
  4049. new_xform = se->original.affine_inverse() * new_xform;
  4050. }
  4051. se->gizmo->set_subgizmo_transform(GE.key, new_xform);
  4052. }
  4053. } else {
  4054. Transform3D new_xform = _compute_transform(_edit.mode, se->original, se->original_local, p_motion, p_snap, local_coords, sp->get_rotation_edit_mode() != Node3D::ROTATION_EDIT_MODE_BASIS && _edit.plane != TRANSFORM_VIEW);
  4055. _transform_gizmo_apply(se->sp, new_xform, local_coords);
  4056. }
  4057. }
  4058. spatial_editor->update_transform_gizmo();
  4059. surface->queue_redraw();
  4060. }
  4061. // Update the current transform operation in response to an input.
  4062. void Node3DEditorViewport::update_transform(bool p_shift) {
  4063. Vector3 ray_pos = get_ray_pos(_edit.mouse_pos);
  4064. Vector3 ray = get_ray(_edit.mouse_pos);
  4065. double snap = EDITOR_GET("interface/inspector/default_float_step");
  4066. int snap_step_decimals = Math::range_step_decimals(snap);
  4067. switch (_edit.mode) {
  4068. case TRANSFORM_SCALE: {
  4069. Vector3 motion_mask;
  4070. Plane plane;
  4071. bool plane_mv = false;
  4072. switch (_edit.plane) {
  4073. case TRANSFORM_VIEW:
  4074. motion_mask = Vector3(0, 0, 0);
  4075. plane = Plane(_get_camera_normal(), _edit.center);
  4076. break;
  4077. case TRANSFORM_X_AXIS:
  4078. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(0).normalized();
  4079. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4080. break;
  4081. case TRANSFORM_Y_AXIS:
  4082. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
  4083. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4084. break;
  4085. case TRANSFORM_Z_AXIS:
  4086. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized();
  4087. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4088. break;
  4089. case TRANSFORM_YZ:
  4090. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized() + spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
  4091. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(0).normalized(), _edit.center);
  4092. plane_mv = true;
  4093. break;
  4094. case TRANSFORM_XZ:
  4095. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized() + spatial_editor->get_gizmo_transform().basis.get_column(0).normalized();
  4096. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(1).normalized(), _edit.center);
  4097. plane_mv = true;
  4098. break;
  4099. case TRANSFORM_XY:
  4100. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(0).normalized() + spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
  4101. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(2).normalized(), _edit.center);
  4102. plane_mv = true;
  4103. break;
  4104. }
  4105. Vector3 intersection;
  4106. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  4107. break;
  4108. }
  4109. Vector3 click;
  4110. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  4111. break;
  4112. }
  4113. Vector3 motion = intersection - click;
  4114. if (_edit.plane != TRANSFORM_VIEW) {
  4115. if (!plane_mv) {
  4116. motion = motion_mask.dot(motion) * motion_mask;
  4117. } else {
  4118. // Alternative planar scaling mode
  4119. if (p_shift) {
  4120. motion = motion_mask.dot(motion) * motion_mask;
  4121. }
  4122. }
  4123. } else {
  4124. const real_t center_click_dist = click.distance_to(_edit.center);
  4125. const real_t center_inters_dist = intersection.distance_to(_edit.center);
  4126. if (center_click_dist == 0) {
  4127. break;
  4128. }
  4129. const real_t scale = center_inters_dist - center_click_dist;
  4130. motion = Vector3(scale, scale, scale);
  4131. }
  4132. motion /= click.distance_to(_edit.center);
  4133. // Disable local transformation for TRANSFORM_VIEW
  4134. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  4135. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  4136. snap = spatial_editor->get_scale_snap() / 100;
  4137. }
  4138. Vector3 motion_snapped = motion;
  4139. motion_snapped.snapf(snap);
  4140. // This might not be necessary anymore after issue #288 is solved (in 4.0?).
  4141. // TRANSLATORS: Refers to changing the scale of a node in the 3D editor.
  4142. set_message(TTR("Scaling:") + " (" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
  4143. String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
  4144. if (local_coords) {
  4145. // TODO: needed?
  4146. motion = _edit.original.basis.inverse().xform(motion);
  4147. }
  4148. apply_transform(motion, snap);
  4149. } break;
  4150. case TRANSFORM_TRANSLATE: {
  4151. Vector3 motion_mask;
  4152. Plane plane;
  4153. bool plane_mv = false;
  4154. switch (_edit.plane) {
  4155. case TRANSFORM_VIEW:
  4156. plane = Plane(_get_camera_normal(), _edit.center);
  4157. break;
  4158. case TRANSFORM_X_AXIS:
  4159. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(0).normalized();
  4160. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4161. break;
  4162. case TRANSFORM_Y_AXIS:
  4163. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
  4164. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4165. break;
  4166. case TRANSFORM_Z_AXIS:
  4167. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized();
  4168. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4169. break;
  4170. case TRANSFORM_YZ:
  4171. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(0).normalized(), _edit.center);
  4172. plane_mv = true;
  4173. break;
  4174. case TRANSFORM_XZ:
  4175. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(1).normalized(), _edit.center);
  4176. plane_mv = true;
  4177. break;
  4178. case TRANSFORM_XY:
  4179. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(2).normalized(), _edit.center);
  4180. plane_mv = true;
  4181. break;
  4182. }
  4183. Vector3 intersection;
  4184. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  4185. break;
  4186. }
  4187. Vector3 click;
  4188. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  4189. break;
  4190. }
  4191. Vector3 motion = intersection - click;
  4192. if (_edit.plane != TRANSFORM_VIEW) {
  4193. if (!plane_mv) {
  4194. motion = motion_mask.dot(motion) * motion_mask;
  4195. }
  4196. }
  4197. // Disable local transformation for TRANSFORM_VIEW
  4198. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  4199. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  4200. snap = spatial_editor->get_translate_snap();
  4201. }
  4202. Vector3 motion_snapped = motion;
  4203. motion_snapped.snapf(snap);
  4204. // TRANSLATORS: Refers to changing the position of a node in the 3D editor.
  4205. set_message(TTR("Translating:") + " (" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
  4206. String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
  4207. if (local_coords) {
  4208. motion = spatial_editor->get_gizmo_transform().basis.inverse().xform(motion);
  4209. }
  4210. apply_transform(motion, snap);
  4211. } break;
  4212. case TRANSFORM_ROTATE: {
  4213. Plane plane = Plane(_get_camera_normal(), _edit.center);
  4214. Vector3 local_axis;
  4215. Vector3 global_axis;
  4216. switch (_edit.plane) {
  4217. case TRANSFORM_VIEW:
  4218. // local_axis unused
  4219. global_axis = _get_camera_normal();
  4220. break;
  4221. case TRANSFORM_X_AXIS:
  4222. local_axis = Vector3(1, 0, 0);
  4223. break;
  4224. case TRANSFORM_Y_AXIS:
  4225. local_axis = Vector3(0, 1, 0);
  4226. break;
  4227. case TRANSFORM_Z_AXIS:
  4228. local_axis = Vector3(0, 0, 1);
  4229. break;
  4230. case TRANSFORM_YZ:
  4231. case TRANSFORM_XZ:
  4232. case TRANSFORM_XY:
  4233. break;
  4234. }
  4235. if (_edit.plane != TRANSFORM_VIEW) {
  4236. global_axis = spatial_editor->get_gizmo_transform().basis.xform(local_axis).normalized();
  4237. }
  4238. Vector3 intersection;
  4239. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  4240. break;
  4241. }
  4242. Vector3 click;
  4243. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  4244. break;
  4245. }
  4246. static const float orthogonal_threshold = Math::cos(Math::deg_to_rad(87.0f));
  4247. bool axis_is_orthogonal = ABS(plane.normal.dot(global_axis)) < orthogonal_threshold;
  4248. double angle = 0.0f;
  4249. if (axis_is_orthogonal) {
  4250. _edit.show_rotation_line = false;
  4251. Vector3 projection_axis = plane.normal.cross(global_axis);
  4252. Vector3 delta = intersection - click;
  4253. float projection = delta.dot(projection_axis);
  4254. angle = (projection * (Math_PI / 2.0f)) / (gizmo_scale * GIZMO_CIRCLE_SIZE);
  4255. } else {
  4256. _edit.show_rotation_line = true;
  4257. Vector3 click_axis = (click - _edit.center).normalized();
  4258. Vector3 current_axis = (intersection - _edit.center).normalized();
  4259. angle = click_axis.signed_angle_to(current_axis, global_axis);
  4260. }
  4261. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  4262. snap = spatial_editor->get_rotate_snap();
  4263. }
  4264. angle = Math::snapped(Math::rad_to_deg(angle), snap);
  4265. set_message(vformat(TTR("Rotating %s degrees."), String::num(angle, snap_step_decimals)));
  4266. angle = Math::deg_to_rad(angle);
  4267. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW); // Disable local transformation for TRANSFORM_VIEW
  4268. Vector3 compute_axis = local_coords ? local_axis : global_axis;
  4269. apply_transform(compute_axis, angle);
  4270. } break;
  4271. default: {
  4272. }
  4273. }
  4274. }
  4275. void Node3DEditorViewport::update_transform_numeric() {
  4276. Vector3 motion;
  4277. switch (_edit.plane) {
  4278. case TRANSFORM_VIEW: {
  4279. switch (_edit.mode) {
  4280. case TRANSFORM_TRANSLATE:
  4281. motion = Vector3(1, 0, 0);
  4282. break;
  4283. case TRANSFORM_ROTATE:
  4284. motion = spatial_editor->get_gizmo_transform().basis.xform_inv(_get_camera_normal()).normalized();
  4285. break;
  4286. case TRANSFORM_SCALE:
  4287. motion = Vector3(1, 1, 1);
  4288. break;
  4289. case TRANSFORM_NONE:
  4290. ERR_FAIL_MSG("_edit.mode cannot be TRANSFORM_NONE in update_transform_numeric.");
  4291. }
  4292. break;
  4293. }
  4294. case TRANSFORM_X_AXIS:
  4295. motion = Vector3(1, 0, 0);
  4296. break;
  4297. case TRANSFORM_Y_AXIS:
  4298. motion = Vector3(0, 1, 0);
  4299. break;
  4300. case TRANSFORM_Z_AXIS:
  4301. motion = Vector3(0, 0, 1);
  4302. break;
  4303. case TRANSFORM_XY:
  4304. motion = Vector3(1, 1, 0);
  4305. break;
  4306. case TRANSFORM_XZ:
  4307. motion = Vector3(1, 0, 1);
  4308. break;
  4309. case TRANSFORM_YZ:
  4310. motion = Vector3(0, 1, 1);
  4311. break;
  4312. }
  4313. double value = _edit.numeric_input * (_edit.numeric_negate ? -1 : 1);
  4314. double extra = 0.0;
  4315. switch (_edit.mode) {
  4316. case TRANSFORM_TRANSLATE:
  4317. motion *= value;
  4318. set_message(vformat(TTR("Translating %s."), motion));
  4319. break;
  4320. case TRANSFORM_ROTATE:
  4321. extra = Math::deg_to_rad(value);
  4322. set_message(vformat(TTR("Rotating %f degrees."), value));
  4323. break;
  4324. case TRANSFORM_SCALE:
  4325. // To halve the size of an object in Blender, you scale it by 0.5.
  4326. // Doing the same in Godot is considered scaling it by -0.5.
  4327. motion *= (value - 1.0);
  4328. set_message(vformat(TTR("Scaling %s."), motion));
  4329. break;
  4330. case TRANSFORM_NONE:
  4331. ERR_FAIL_MSG("_edit.mode cannot be TRANSFORM_NONE in update_transform_numeric.");
  4332. }
  4333. apply_transform(motion, extra);
  4334. }
  4335. // Perform cleanup after a transform operation is committed or canceled.
  4336. void Node3DEditorViewport::finish_transform() {
  4337. _edit.mode = TRANSFORM_NONE;
  4338. _edit.instant = false;
  4339. _edit.numeric_input = 0;
  4340. _edit.numeric_next_decimal = 0;
  4341. _edit.numeric_negate = false;
  4342. spatial_editor->set_local_coords_enabled(_edit.original_local);
  4343. spatial_editor->update_transform_gizmo();
  4344. surface->queue_redraw();
  4345. set_process_input(false);
  4346. }
  4347. // Register a shortcut and also add it as an input action with the same events.
  4348. void Node3DEditorViewport::register_shortcut_action(const String &p_path, const String &p_name, Key p_keycode, bool p_physical) {
  4349. Ref<Shortcut> sc = ED_SHORTCUT(p_path, p_name, p_keycode, p_physical);
  4350. shortcut_changed_callback(sc, p_path);
  4351. // Connect to the change event on the shortcut so the input binding can be updated.
  4352. sc->connect_changed(callable_mp(this, &Node3DEditorViewport::shortcut_changed_callback).bind(sc, p_path));
  4353. }
  4354. // Update the action in the InputMap to the provided shortcut events.
  4355. void Node3DEditorViewport::shortcut_changed_callback(const Ref<Shortcut> p_shortcut, const String &p_shortcut_path) {
  4356. InputMap *im = InputMap::get_singleton();
  4357. if (im->has_action(p_shortcut_path)) {
  4358. im->action_erase_events(p_shortcut_path);
  4359. } else {
  4360. im->add_action(p_shortcut_path);
  4361. }
  4362. for (int i = 0; i < p_shortcut->get_events().size(); i++) {
  4363. im->action_add_event(p_shortcut_path, p_shortcut->get_events()[i]);
  4364. }
  4365. }
  4366. void Node3DEditorViewport::_set_lock_view_rotation(bool p_lock_rotation) {
  4367. lock_rotation = p_lock_rotation;
  4368. int idx = view_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
  4369. view_menu->get_popup()->set_item_checked(idx, p_lock_rotation);
  4370. if (p_lock_rotation) {
  4371. locked_label->show();
  4372. } else {
  4373. locked_label->hide();
  4374. }
  4375. }
  4376. Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, int p_index) {
  4377. cpu_time_history_index = 0;
  4378. gpu_time_history_index = 0;
  4379. _edit.mode = TRANSFORM_NONE;
  4380. _edit.plane = TRANSFORM_VIEW;
  4381. _edit.snap = true;
  4382. _edit.show_rotation_line = true;
  4383. _edit.instant = false;
  4384. _edit.gizmo_handle = -1;
  4385. _edit.gizmo_handle_secondary = false;
  4386. index = p_index;
  4387. editor_selection = EditorNode::get_singleton()->get_editor_selection();
  4388. orthogonal = false;
  4389. auto_orthogonal = false;
  4390. lock_rotation = false;
  4391. message_time = 0;
  4392. zoom_indicator_delay = 0.0;
  4393. spatial_editor = p_spatial_editor;
  4394. SubViewportContainer *c = memnew(SubViewportContainer);
  4395. subviewport_container = c;
  4396. c->set_stretch(true);
  4397. add_child(c);
  4398. c->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  4399. viewport = memnew(SubViewport);
  4400. viewport->set_disable_input(true);
  4401. c->add_child(viewport);
  4402. surface = memnew(Control);
  4403. SET_DRAG_FORWARDING_CD(surface, Node3DEditorViewport);
  4404. add_child(surface);
  4405. surface->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  4406. surface->set_clip_contents(true);
  4407. camera = memnew(Camera3D);
  4408. camera->set_disable_gizmos(true);
  4409. 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));
  4410. viewport->add_child(camera);
  4411. camera->make_current();
  4412. surface->set_focus_mode(FOCUS_ALL);
  4413. VBoxContainer *vbox = memnew(VBoxContainer);
  4414. surface->add_child(vbox);
  4415. vbox->set_offset(SIDE_LEFT, 10 * EDSCALE);
  4416. vbox->set_offset(SIDE_TOP, 10 * EDSCALE);
  4417. view_menu = memnew(MenuButton);
  4418. view_menu->set_flat(false);
  4419. view_menu->set_h_size_flags(0);
  4420. view_menu->set_shortcut_context(this);
  4421. vbox->add_child(view_menu);
  4422. view_menu->get_popup()->set_hide_on_checkable_item_selection(false);
  4423. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/top_view"), VIEW_TOP);
  4424. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/bottom_view"), VIEW_BOTTOM);
  4425. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/left_view"), VIEW_LEFT);
  4426. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/right_view"), VIEW_RIGHT);
  4427. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/front_view"), VIEW_FRONT);
  4428. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/rear_view"), VIEW_REAR);
  4429. view_menu->get_popup()->add_separator();
  4430. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/switch_perspective_orthogonal"), VIEW_SWITCH_PERSPECTIVE_ORTHOGONAL);
  4431. view_menu->get_popup()->add_radio_check_item(TTR("Perspective"), VIEW_PERSPECTIVE);
  4432. view_menu->get_popup()->add_radio_check_item(TTR("Orthogonal"), VIEW_ORTHOGONAL);
  4433. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
  4434. view_menu->get_popup()->add_check_item(TTR("Auto Orthogonal Enabled"), VIEW_AUTO_ORTHOGONAL);
  4435. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL), true);
  4436. view_menu->get_popup()->add_separator();
  4437. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_lock_rotation", TTR("Lock View Rotation")), VIEW_LOCK_ROTATION);
  4438. view_menu->get_popup()->add_separator();
  4439. // TRANSLATORS: "Normal" as in "normal life", not "normal vector".
  4440. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_normal", TTR("Display Normal")), VIEW_DISPLAY_NORMAL);
  4441. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_wireframe", TTR("Display Wireframe")), VIEW_DISPLAY_WIREFRAME);
  4442. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_overdraw", TTR("Display Overdraw")), VIEW_DISPLAY_OVERDRAW);
  4443. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_lighting", TTR("Display Lighting")), VIEW_DISPLAY_LIGHTING);
  4444. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_unshaded", TTR("Display Unshaded")), VIEW_DISPLAY_UNSHADED);
  4445. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), true);
  4446. display_submenu = memnew(PopupMenu);
  4447. display_submenu->set_hide_on_checkable_item_selection(false);
  4448. display_submenu->add_radio_check_item(TTR("Directional Shadow Splits"), VIEW_DISPLAY_DEBUG_PSSM_SPLITS);
  4449. display_submenu->add_separator();
  4450. display_submenu->add_radio_check_item(TTR("Normal Buffer"), VIEW_DISPLAY_NORMAL_BUFFER);
  4451. display_submenu->add_separator();
  4452. display_submenu->add_radio_check_item(TTR("Shadow Atlas"), VIEW_DISPLAY_DEBUG_SHADOW_ATLAS);
  4453. display_submenu->add_radio_check_item(TTR("Directional Shadow Map"), VIEW_DISPLAY_DEBUG_DIRECTIONAL_SHADOW_ATLAS);
  4454. display_submenu->add_separator();
  4455. display_submenu->add_radio_check_item(TTR("Decal Atlas"), VIEW_DISPLAY_DEBUG_DECAL_ATLAS);
  4456. display_submenu->add_separator();
  4457. display_submenu->add_radio_check_item(TTR("VoxelGI Lighting"), VIEW_DISPLAY_DEBUG_VOXEL_GI_LIGHTING);
  4458. display_submenu->add_radio_check_item(TTR("VoxelGI Albedo"), VIEW_DISPLAY_DEBUG_VOXEL_GI_ALBEDO);
  4459. display_submenu->add_radio_check_item(TTR("VoxelGI Emission"), VIEW_DISPLAY_DEBUG_VOXEL_GI_EMISSION);
  4460. display_submenu->add_separator();
  4461. display_submenu->add_radio_check_item(TTR("SDFGI Cascades"), VIEW_DISPLAY_DEBUG_SDFGI);
  4462. display_submenu->add_radio_check_item(TTR("SDFGI Probes"), VIEW_DISPLAY_DEBUG_SDFGI_PROBES);
  4463. display_submenu->add_separator();
  4464. display_submenu->add_radio_check_item(TTR("Scene Luminance"), VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE);
  4465. display_submenu->add_separator();
  4466. display_submenu->add_radio_check_item(TTR("SSAO"), VIEW_DISPLAY_DEBUG_SSAO);
  4467. display_submenu->add_radio_check_item(TTR("SSIL"), VIEW_DISPLAY_DEBUG_SSIL);
  4468. display_submenu->add_separator();
  4469. display_submenu->add_radio_check_item(TTR("VoxelGI/SDFGI Buffer"), VIEW_DISPLAY_DEBUG_GI_BUFFER);
  4470. display_submenu->add_separator();
  4471. display_submenu->add_radio_check_item(TTR("Disable Mesh LOD"), VIEW_DISPLAY_DEBUG_DISABLE_LOD);
  4472. display_submenu->add_separator();
  4473. display_submenu->add_radio_check_item(TTR("OmniLight3D Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS);
  4474. display_submenu->add_radio_check_item(TTR("SpotLight3D Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS);
  4475. display_submenu->add_radio_check_item(TTR("Decal Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_DECALS);
  4476. display_submenu->add_radio_check_item(TTR("ReflectionProbe Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES);
  4477. display_submenu->add_radio_check_item(TTR("Occlusion Culling Buffer"), VIEW_DISPLAY_DEBUG_OCCLUDERS);
  4478. display_submenu->add_radio_check_item(TTR("Motion Vectors"), VIEW_DISPLAY_MOTION_VECTORS);
  4479. display_submenu->add_radio_check_item(TTR("Internal Buffer"), VIEW_DISPLAY_INTERNAL_BUFFER);
  4480. view_menu->get_popup()->add_submenu_node_item(TTR("Display Advanced..."), display_submenu, VIEW_DISPLAY_ADVANCED);
  4481. view_menu->get_popup()->add_separator();
  4482. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_environment", TTR("View Environment")), VIEW_ENVIRONMENT);
  4483. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_gizmos", TTR("View Gizmos")), VIEW_GIZMOS);
  4484. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_grid_lines", TTR("View Grid")), VIEW_GRID);
  4485. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_information", TTR("View Information")), VIEW_INFORMATION);
  4486. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_fps", TTR("View Frame Time")), VIEW_FRAME_TIME);
  4487. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT), true);
  4488. view_menu->get_popup()->add_separator();
  4489. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_half_resolution", TTR("Half Resolution")), VIEW_HALF_RESOLUTION);
  4490. view_menu->get_popup()->add_separator();
  4491. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_listener", TTR("Audio Listener")), VIEW_AUDIO_LISTENER);
  4492. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_doppler", TTR("Enable Doppler")), VIEW_AUDIO_DOPPLER);
  4493. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_GIZMOS), true);
  4494. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_GRID), true);
  4495. view_menu->get_popup()->add_separator();
  4496. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_cinematic_preview", TTR("Cinematic Preview")), VIEW_CINEMATIC_PREVIEW);
  4497. view_menu->get_popup()->add_separator();
  4498. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_origin"), VIEW_CENTER_TO_ORIGIN);
  4499. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_selection"), VIEW_CENTER_TO_SELECTION);
  4500. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_transform_with_view"), VIEW_ALIGN_TRANSFORM_WITH_VIEW);
  4501. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_rotation_with_view"), VIEW_ALIGN_ROTATION_WITH_VIEW);
  4502. view_menu->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditorViewport::_menu_option));
  4503. display_submenu->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditorViewport::_menu_option));
  4504. view_menu->set_disable_shortcuts(true);
  4505. // TODO: Re-evaluate with new OpenGL3 renderer, and implement.
  4506. //if (OS::get_singleton()->get_current_video_driver() == OS::RENDERING_DRIVER_OPENGL3) {
  4507. if (false) {
  4508. // Alternate display modes only work when using the Vulkan renderer; make this explicit.
  4509. const int normal_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL);
  4510. const int wireframe_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME);
  4511. const int overdraw_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW);
  4512. const int shadeless_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_UNSHADED);
  4513. const String unsupported_tooltip = TTR("Not available when using the OpenGL renderer.");
  4514. view_menu->get_popup()->set_item_disabled(normal_idx, true);
  4515. view_menu->get_popup()->set_item_tooltip(normal_idx, unsupported_tooltip);
  4516. view_menu->get_popup()->set_item_disabled(wireframe_idx, true);
  4517. view_menu->get_popup()->set_item_tooltip(wireframe_idx, unsupported_tooltip);
  4518. view_menu->get_popup()->set_item_disabled(overdraw_idx, true);
  4519. view_menu->get_popup()->set_item_tooltip(overdraw_idx, unsupported_tooltip);
  4520. view_menu->get_popup()->set_item_disabled(shadeless_idx, true);
  4521. view_menu->get_popup()->set_item_tooltip(shadeless_idx, unsupported_tooltip);
  4522. }
  4523. register_shortcut_action("spatial_editor/freelook_left", TTR("Freelook Left"), Key::A, true);
  4524. register_shortcut_action("spatial_editor/freelook_right", TTR("Freelook Right"), Key::D, true);
  4525. register_shortcut_action("spatial_editor/freelook_forward", TTR("Freelook Forward"), Key::W, true);
  4526. register_shortcut_action("spatial_editor/freelook_backwards", TTR("Freelook Backwards"), Key::S, true);
  4527. register_shortcut_action("spatial_editor/freelook_up", TTR("Freelook Up"), Key::E, true);
  4528. register_shortcut_action("spatial_editor/freelook_down", TTR("Freelook Down"), Key::Q, true);
  4529. register_shortcut_action("spatial_editor/freelook_speed_modifier", TTR("Freelook Speed Modifier"), Key::SHIFT);
  4530. register_shortcut_action("spatial_editor/freelook_slow_modifier", TTR("Freelook Slow Modifier"), Key::ALT);
  4531. ED_SHORTCUT("spatial_editor/lock_transform_x", TTR("Lock Transformation to X axis"), Key::X);
  4532. ED_SHORTCUT("spatial_editor/lock_transform_y", TTR("Lock Transformation to Y axis"), Key::Y);
  4533. ED_SHORTCUT("spatial_editor/lock_transform_z", TTR("Lock Transformation to Z axis"), Key::Z);
  4534. ED_SHORTCUT("spatial_editor/lock_transform_yz", TTR("Lock Transformation to YZ plane"), KeyModifierMask::SHIFT | Key::X);
  4535. ED_SHORTCUT("spatial_editor/lock_transform_xz", TTR("Lock Transformation to XZ plane"), KeyModifierMask::SHIFT | Key::Y);
  4536. ED_SHORTCUT("spatial_editor/lock_transform_xy", TTR("Lock Transformation to XY plane"), KeyModifierMask::SHIFT | Key::Z);
  4537. ED_SHORTCUT("spatial_editor/cancel_transform", TTR("Cancel Transformation"), Key::ESCAPE);
  4538. ED_SHORTCUT("spatial_editor/instant_translate", TTR("Begin Translate Transformation"));
  4539. ED_SHORTCUT("spatial_editor/instant_rotate", TTR("Begin Rotate Transformation"));
  4540. ED_SHORTCUT("spatial_editor/instant_scale", TTR("Begin Scale Transformation"));
  4541. preview_camera = memnew(CheckBox);
  4542. preview_camera->set_text(TTR("Preview"));
  4543. preview_camera->set_shortcut(ED_SHORTCUT("spatial_editor/toggle_camera_preview", TTR("Toggle Camera Preview"), KeyModifierMask::CMD_OR_CTRL | Key::P));
  4544. vbox->add_child(preview_camera);
  4545. preview_camera->set_h_size_flags(0);
  4546. preview_camera->hide();
  4547. preview_camera->connect("toggled", callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  4548. previewing = nullptr;
  4549. gizmo_scale = 1.0;
  4550. preview_node = nullptr;
  4551. bottom_center_vbox = memnew(VBoxContainer);
  4552. bottom_center_vbox->set_anchors_preset(LayoutPreset::PRESET_CENTER);
  4553. bottom_center_vbox->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -20 * EDSCALE);
  4554. bottom_center_vbox->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, -10 * EDSCALE);
  4555. bottom_center_vbox->set_h_grow_direction(GROW_DIRECTION_BOTH);
  4556. bottom_center_vbox->set_v_grow_direction(GROW_DIRECTION_BEGIN);
  4557. surface->add_child(bottom_center_vbox);
  4558. info_label = memnew(Label);
  4559. info_label->set_anchor_and_offset(SIDE_LEFT, ANCHOR_END, -90 * EDSCALE);
  4560. info_label->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -90 * EDSCALE);
  4561. info_label->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, -10 * EDSCALE);
  4562. info_label->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, -10 * EDSCALE);
  4563. info_label->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  4564. info_label->set_v_grow_direction(GROW_DIRECTION_BEGIN);
  4565. surface->add_child(info_label);
  4566. info_label->hide();
  4567. cinema_label = memnew(Label);
  4568. cinema_label->set_anchor_and_offset(SIDE_TOP, ANCHOR_BEGIN, 10 * EDSCALE);
  4569. cinema_label->set_h_grow_direction(GROW_DIRECTION_END);
  4570. cinema_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  4571. surface->add_child(cinema_label);
  4572. cinema_label->set_text(TTR("Cinematic Preview"));
  4573. cinema_label->hide();
  4574. previewing_cinema = false;
  4575. locked_label = memnew(Label);
  4576. locked_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  4577. locked_label->set_h_size_flags(SIZE_SHRINK_CENTER);
  4578. bottom_center_vbox->add_child(locked_label);
  4579. locked_label->set_text(TTR("View Rotation Locked"));
  4580. locked_label->hide();
  4581. zoom_limit_label = memnew(Label);
  4582. zoom_limit_label->set_text(TTR("To zoom further, change the camera's clipping planes (View -> Settings...)"));
  4583. zoom_limit_label->set_name("ZoomLimitMessageLabel");
  4584. zoom_limit_label->add_theme_color_override("font_color", Color(1, 1, 1, 1));
  4585. zoom_limit_label->hide();
  4586. bottom_center_vbox->add_child(zoom_limit_label);
  4587. preview_material_label = memnew(Label);
  4588. preview_material_label->set_anchors_and_offsets_preset(LayoutPreset::PRESET_BOTTOM_LEFT);
  4589. preview_material_label->set_offset(Side::SIDE_TOP, -70 * EDSCALE);
  4590. preview_material_label->set_text(TTR("Overriding material..."));
  4591. preview_material_label->add_theme_color_override("font_color", Color(1, 1, 1, 1));
  4592. preview_material_label->hide();
  4593. surface->add_child(preview_material_label);
  4594. preview_material_label_desc = memnew(Label);
  4595. preview_material_label_desc->set_anchors_and_offsets_preset(LayoutPreset::PRESET_BOTTOM_LEFT);
  4596. preview_material_label_desc->set_offset(Side::SIDE_TOP, -50 * EDSCALE);
  4597. Key key = (OS::get_singleton()->has_feature("macos") || OS::get_singleton()->has_feature("web_macos") || OS::get_singleton()->has_feature("web_ios")) ? Key::META : Key::CTRL;
  4598. preview_material_label_desc->set_text(vformat(TTR("Drag and drop to override the material of any geometry node.\nHold %s when dropping to override a specific surface."), find_keycode_name(key)));
  4599. preview_material_label_desc->add_theme_color_override("font_color", Color(0.8, 0.8, 0.8, 1));
  4600. preview_material_label_desc->add_theme_constant_override("line_spacing", 0);
  4601. preview_material_label_desc->hide();
  4602. surface->add_child(preview_material_label_desc);
  4603. frame_time_gradient = memnew(Gradient);
  4604. // The color is set when the theme changes.
  4605. frame_time_gradient->add_point(0.5, Color());
  4606. top_right_vbox = memnew(VBoxContainer);
  4607. top_right_vbox->set_anchors_and_offsets_preset(PRESET_TOP_RIGHT, PRESET_MODE_MINSIZE, 10.0 * EDSCALE);
  4608. top_right_vbox->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  4609. const int navigation_control_size = 150;
  4610. position_control = memnew(ViewportNavigationControl);
  4611. position_control->set_navigation_mode(Node3DEditorViewport::NAVIGATION_MOVE);
  4612. position_control->set_custom_minimum_size(Size2(navigation_control_size, navigation_control_size) * EDSCALE);
  4613. position_control->set_h_size_flags(SIZE_SHRINK_END);
  4614. position_control->set_anchor_and_offset(SIDE_LEFT, ANCHOR_BEGIN, 0);
  4615. position_control->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -navigation_control_size * EDSCALE);
  4616. position_control->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_BEGIN, navigation_control_size * EDSCALE);
  4617. position_control->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
  4618. position_control->set_viewport(this);
  4619. surface->add_child(position_control);
  4620. look_control = memnew(ViewportNavigationControl);
  4621. look_control->set_navigation_mode(Node3DEditorViewport::NAVIGATION_LOOK);
  4622. look_control->set_custom_minimum_size(Size2(navigation_control_size, navigation_control_size) * EDSCALE);
  4623. look_control->set_h_size_flags(SIZE_SHRINK_END);
  4624. look_control->set_anchor_and_offset(SIDE_LEFT, ANCHOR_END, -navigation_control_size * EDSCALE);
  4625. look_control->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -navigation_control_size * EDSCALE);
  4626. look_control->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, 0);
  4627. look_control->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
  4628. look_control->set_viewport(this);
  4629. surface->add_child(look_control);
  4630. rotation_control = memnew(ViewportRotationControl);
  4631. rotation_control->set_custom_minimum_size(Size2(80, 80) * EDSCALE);
  4632. rotation_control->set_h_size_flags(SIZE_SHRINK_END);
  4633. rotation_control->set_viewport(this);
  4634. top_right_vbox->add_child(rotation_control);
  4635. frame_time_panel = memnew(PanelContainer);
  4636. top_right_vbox->add_child(frame_time_panel);
  4637. frame_time_panel->hide();
  4638. frame_time_vbox = memnew(VBoxContainer);
  4639. frame_time_panel->add_child(frame_time_vbox);
  4640. // Individual Labels are used to allow coloring each label with its own color.
  4641. cpu_time_label = memnew(Label);
  4642. frame_time_vbox->add_child(cpu_time_label);
  4643. gpu_time_label = memnew(Label);
  4644. frame_time_vbox->add_child(gpu_time_label);
  4645. fps_label = memnew(Label);
  4646. frame_time_vbox->add_child(fps_label);
  4647. surface->add_child(top_right_vbox);
  4648. accept = nullptr;
  4649. freelook_active = false;
  4650. freelook_speed = EDITOR_GET("editors/3d/freelook/freelook_base_speed");
  4651. selection_menu = memnew(PopupMenu);
  4652. add_child(selection_menu);
  4653. selection_menu->set_min_size(Size2(100, 0) * EDSCALE);
  4654. selection_menu->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditorViewport::_selection_result_pressed));
  4655. selection_menu->connect("popup_hide", callable_mp(this, &Node3DEditorViewport::_selection_menu_hide));
  4656. if (p_index == 0) {
  4657. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER), true);
  4658. viewport->set_as_audio_listener_3d(true);
  4659. }
  4660. view_type = VIEW_TYPE_USER;
  4661. _update_name();
  4662. EditorSettings::get_singleton()->connect("settings_changed", callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view));
  4663. }
  4664. Node3DEditorViewport::~Node3DEditorViewport() {
  4665. memdelete(frame_time_gradient);
  4666. }
  4667. //////////////////////////////////////////////////////////////
  4668. void Node3DEditorViewportContainer::gui_input(const Ref<InputEvent> &p_event) {
  4669. ERR_FAIL_COND(p_event.is_null());
  4670. Ref<InputEventMouseButton> mb = p_event;
  4671. if (mb.is_valid() && mb->get_button_index() == MouseButton::LEFT) {
  4672. if (mb->is_pressed()) {
  4673. Vector2 size = get_size();
  4674. int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
  4675. int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
  4676. int mid_w = size.width * ratio_h;
  4677. int mid_h = size.height * ratio_v;
  4678. dragging_h = mb->get_position().x > (mid_w - h_sep / 2) && mb->get_position().x < (mid_w + h_sep / 2);
  4679. dragging_v = mb->get_position().y > (mid_h - v_sep / 2) && mb->get_position().y < (mid_h + v_sep / 2);
  4680. drag_begin_pos = mb->get_position();
  4681. drag_begin_ratio.x = ratio_h;
  4682. drag_begin_ratio.y = ratio_v;
  4683. switch (view) {
  4684. case VIEW_USE_1_VIEWPORT: {
  4685. dragging_h = false;
  4686. dragging_v = false;
  4687. } break;
  4688. case VIEW_USE_2_VIEWPORTS: {
  4689. dragging_h = false;
  4690. } break;
  4691. case VIEW_USE_2_VIEWPORTS_ALT: {
  4692. dragging_v = false;
  4693. } break;
  4694. case VIEW_USE_3_VIEWPORTS:
  4695. case VIEW_USE_3_VIEWPORTS_ALT:
  4696. case VIEW_USE_4_VIEWPORTS: {
  4697. // Do nothing.
  4698. } break;
  4699. }
  4700. } else {
  4701. dragging_h = false;
  4702. dragging_v = false;
  4703. }
  4704. }
  4705. Ref<InputEventMouseMotion> mm = p_event;
  4706. if (mm.is_valid()) {
  4707. if (view == VIEW_USE_3_VIEWPORTS || view == VIEW_USE_3_VIEWPORTS_ALT || view == VIEW_USE_4_VIEWPORTS) {
  4708. Vector2 size = get_size();
  4709. int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
  4710. int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
  4711. int mid_w = size.width * ratio_h;
  4712. int mid_h = size.height * ratio_v;
  4713. bool was_hovering_h = hovering_h;
  4714. bool was_hovering_v = hovering_v;
  4715. hovering_h = mm->get_position().x > (mid_w - h_sep / 2) && mm->get_position().x < (mid_w + h_sep / 2);
  4716. hovering_v = mm->get_position().y > (mid_h - v_sep / 2) && mm->get_position().y < (mid_h + v_sep / 2);
  4717. if (was_hovering_h != hovering_h || was_hovering_v != hovering_v) {
  4718. queue_redraw();
  4719. }
  4720. }
  4721. if (dragging_h) {
  4722. real_t new_ratio = drag_begin_ratio.x + (mm->get_position().x - drag_begin_pos.x) / get_size().width;
  4723. new_ratio = CLAMP(new_ratio, 40 / get_size().width, (get_size().width - 40) / get_size().width);
  4724. ratio_h = new_ratio;
  4725. queue_sort();
  4726. queue_redraw();
  4727. }
  4728. if (dragging_v) {
  4729. real_t new_ratio = drag_begin_ratio.y + (mm->get_position().y - drag_begin_pos.y) / get_size().height;
  4730. new_ratio = CLAMP(new_ratio, 40 / get_size().height, (get_size().height - 40) / get_size().height);
  4731. ratio_v = new_ratio;
  4732. queue_sort();
  4733. queue_redraw();
  4734. }
  4735. }
  4736. }
  4737. void Node3DEditorViewportContainer::_notification(int p_what) {
  4738. switch (p_what) {
  4739. case NOTIFICATION_MOUSE_ENTER:
  4740. case NOTIFICATION_MOUSE_EXIT: {
  4741. mouseover = (p_what == NOTIFICATION_MOUSE_ENTER);
  4742. queue_redraw();
  4743. } break;
  4744. case NOTIFICATION_DRAW: {
  4745. if (mouseover) {
  4746. Ref<Texture2D> h_grabber = get_theme_icon(SNAME("grabber"), SNAME("HSplitContainer"));
  4747. Ref<Texture2D> v_grabber = get_theme_icon(SNAME("grabber"), SNAME("VSplitContainer"));
  4748. Ref<Texture2D> hdiag_grabber = get_editor_theme_icon(SNAME("GuiViewportHdiagsplitter"));
  4749. Ref<Texture2D> vdiag_grabber = get_editor_theme_icon(SNAME("GuiViewportVdiagsplitter"));
  4750. Ref<Texture2D> vh_grabber = get_editor_theme_icon(SNAME("GuiViewportVhsplitter"));
  4751. Vector2 size = get_size();
  4752. int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
  4753. int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
  4754. int mid_w = size.width * ratio_h;
  4755. int mid_h = size.height * ratio_v;
  4756. int size_left = mid_w - h_sep / 2;
  4757. int size_bottom = size.height - mid_h - v_sep / 2;
  4758. switch (view) {
  4759. case VIEW_USE_1_VIEWPORT: {
  4760. // Nothing to show.
  4761. } break;
  4762. case VIEW_USE_2_VIEWPORTS: {
  4763. draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  4764. set_default_cursor_shape(CURSOR_VSPLIT);
  4765. } break;
  4766. case VIEW_USE_2_VIEWPORTS_ALT: {
  4767. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
  4768. set_default_cursor_shape(CURSOR_HSPLIT);
  4769. } break;
  4770. case VIEW_USE_3_VIEWPORTS: {
  4771. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  4772. draw_texture(hdiag_grabber, Vector2(mid_w - hdiag_grabber->get_width() / 2, mid_h - v_grabber->get_height() / 4));
  4773. set_default_cursor_shape(CURSOR_DRAG);
  4774. } else if ((hovering_v && !dragging_h) || dragging_v) {
  4775. draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  4776. set_default_cursor_shape(CURSOR_VSPLIT);
  4777. } else if (hovering_h || dragging_h) {
  4778. 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));
  4779. set_default_cursor_shape(CURSOR_HSPLIT);
  4780. }
  4781. } break;
  4782. case VIEW_USE_3_VIEWPORTS_ALT: {
  4783. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  4784. draw_texture(vdiag_grabber, Vector2(mid_w - vdiag_grabber->get_width() + v_grabber->get_height() / 4, mid_h - vdiag_grabber->get_height() / 2));
  4785. set_default_cursor_shape(CURSOR_DRAG);
  4786. } else if ((hovering_v && !dragging_h) || dragging_v) {
  4787. draw_texture(v_grabber, Vector2((size_left - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  4788. set_default_cursor_shape(CURSOR_VSPLIT);
  4789. } else if (hovering_h || dragging_h) {
  4790. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
  4791. set_default_cursor_shape(CURSOR_HSPLIT);
  4792. }
  4793. } break;
  4794. case VIEW_USE_4_VIEWPORTS: {
  4795. Vector2 half(mid_w, mid_h);
  4796. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  4797. draw_texture(vh_grabber, half - vh_grabber->get_size() / 2.0);
  4798. set_default_cursor_shape(CURSOR_DRAG);
  4799. } else if ((hovering_v && !dragging_h) || dragging_v) {
  4800. draw_texture(v_grabber, half - v_grabber->get_size() / 2.0);
  4801. set_default_cursor_shape(CURSOR_VSPLIT);
  4802. } else if (hovering_h || dragging_h) {
  4803. draw_texture(h_grabber, half - h_grabber->get_size() / 2.0);
  4804. set_default_cursor_shape(CURSOR_HSPLIT);
  4805. }
  4806. } break;
  4807. }
  4808. }
  4809. } break;
  4810. case NOTIFICATION_SORT_CHILDREN: {
  4811. Node3DEditorViewport *viewports[4];
  4812. int vc = 0;
  4813. for (int i = 0; i < get_child_count(); i++) {
  4814. viewports[vc] = Object::cast_to<Node3DEditorViewport>(get_child(i));
  4815. if (viewports[vc]) {
  4816. vc++;
  4817. }
  4818. }
  4819. ERR_FAIL_COND(vc != 4);
  4820. Size2 size = get_size();
  4821. if (size.x < 10 || size.y < 10) {
  4822. for (int i = 0; i < 4; i++) {
  4823. viewports[i]->hide();
  4824. }
  4825. return;
  4826. }
  4827. int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
  4828. int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
  4829. int mid_w = size.width * ratio_h;
  4830. int mid_h = size.height * ratio_v;
  4831. int size_left = mid_w - h_sep / 2;
  4832. int size_right = size.width - mid_w - h_sep / 2;
  4833. int size_top = mid_h - v_sep / 2;
  4834. int size_bottom = size.height - mid_h - v_sep / 2;
  4835. switch (view) {
  4836. case VIEW_USE_1_VIEWPORT: {
  4837. viewports[0]->show();
  4838. for (int i = 1; i < 4; i++) {
  4839. viewports[i]->hide();
  4840. }
  4841. fit_child_in_rect(viewports[0], Rect2(Vector2(), size));
  4842. } break;
  4843. case VIEW_USE_2_VIEWPORTS: {
  4844. for (int i = 0; i < 4; i++) {
  4845. if (i == 1 || i == 3) {
  4846. viewports[i]->hide();
  4847. } else {
  4848. viewports[i]->show();
  4849. }
  4850. }
  4851. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
  4852. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size.width, size_bottom)));
  4853. } break;
  4854. case VIEW_USE_2_VIEWPORTS_ALT: {
  4855. for (int i = 0; i < 4; i++) {
  4856. if (i == 1 || i == 3) {
  4857. viewports[i]->hide();
  4858. } else {
  4859. viewports[i]->show();
  4860. }
  4861. }
  4862. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size.height)));
  4863. fit_child_in_rect(viewports[2], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
  4864. } break;
  4865. case VIEW_USE_3_VIEWPORTS: {
  4866. for (int i = 0; i < 4; i++) {
  4867. if (i == 1) {
  4868. viewports[i]->hide();
  4869. } else {
  4870. viewports[i]->show();
  4871. }
  4872. }
  4873. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
  4874. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  4875. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
  4876. } break;
  4877. case VIEW_USE_3_VIEWPORTS_ALT: {
  4878. for (int i = 0; i < 4; i++) {
  4879. if (i == 1) {
  4880. viewports[i]->hide();
  4881. } else {
  4882. viewports[i]->show();
  4883. }
  4884. }
  4885. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
  4886. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  4887. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
  4888. } break;
  4889. case VIEW_USE_4_VIEWPORTS: {
  4890. for (int i = 0; i < 4; i++) {
  4891. viewports[i]->show();
  4892. }
  4893. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
  4894. fit_child_in_rect(viewports[1], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size_top)));
  4895. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  4896. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
  4897. } break;
  4898. }
  4899. } break;
  4900. }
  4901. }
  4902. void Node3DEditorViewportContainer::set_view(View p_view) {
  4903. view = p_view;
  4904. queue_sort();
  4905. }
  4906. Node3DEditorViewportContainer::View Node3DEditorViewportContainer::get_view() {
  4907. return view;
  4908. }
  4909. Node3DEditorViewportContainer::Node3DEditorViewportContainer() {
  4910. set_clip_contents(true);
  4911. view = VIEW_USE_1_VIEWPORT;
  4912. mouseover = false;
  4913. ratio_h = 0.5;
  4914. ratio_v = 0.5;
  4915. hovering_v = false;
  4916. hovering_h = false;
  4917. dragging_v = false;
  4918. dragging_h = false;
  4919. }
  4920. ///////////////////////////////////////////////////////////////////
  4921. Node3DEditor *Node3DEditor::singleton = nullptr;
  4922. Node3DEditorSelectedItem::~Node3DEditorSelectedItem() {
  4923. ERR_FAIL_NULL(RenderingServer::get_singleton());
  4924. if (sbox_instance.is_valid()) {
  4925. RenderingServer::get_singleton()->free(sbox_instance);
  4926. }
  4927. if (sbox_instance_offset.is_valid()) {
  4928. RenderingServer::get_singleton()->free(sbox_instance_offset);
  4929. }
  4930. if (sbox_instance_xray.is_valid()) {
  4931. RenderingServer::get_singleton()->free(sbox_instance_xray);
  4932. }
  4933. if (sbox_instance_xray_offset.is_valid()) {
  4934. RenderingServer::get_singleton()->free(sbox_instance_xray_offset);
  4935. }
  4936. }
  4937. void Node3DEditor::select_gizmo_highlight_axis(int p_axis) {
  4938. for (int i = 0; i < 3; i++) {
  4939. move_gizmo[i]->surface_set_material(0, i == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  4940. move_plane_gizmo[i]->surface_set_material(0, (i + 6) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
  4941. rotate_gizmo[i]->surface_set_material(0, (i + 3) == p_axis ? rotate_gizmo_color_hl[i] : rotate_gizmo_color[i]);
  4942. scale_gizmo[i]->surface_set_material(0, (i + 9) == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  4943. scale_plane_gizmo[i]->surface_set_material(0, (i + 12) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
  4944. }
  4945. }
  4946. void Node3DEditor::update_transform_gizmo() {
  4947. int count = 0;
  4948. bool local_gizmo_coords = are_local_coords_enabled();
  4949. Vector3 gizmo_center;
  4950. Basis gizmo_basis;
  4951. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  4952. if (se && se->gizmo.is_valid()) {
  4953. for (const KeyValue<int, Transform3D> &E : se->subgizmos) {
  4954. Transform3D xf = se->sp->get_global_transform() * se->gizmo->get_subgizmo_transform(E.key);
  4955. gizmo_center += xf.origin;
  4956. if (count == 0 && local_gizmo_coords) {
  4957. gizmo_basis = xf.basis;
  4958. }
  4959. count++;
  4960. }
  4961. } else {
  4962. List<Node *> &selection = editor_selection->get_selected_node_list();
  4963. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4964. Node3D *sp = Object::cast_to<Node3D>(E->get());
  4965. if (!sp) {
  4966. continue;
  4967. }
  4968. if (sp->has_meta("_edit_lock_")) {
  4969. continue;
  4970. }
  4971. Node3DEditorSelectedItem *sel_item = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  4972. if (!sel_item) {
  4973. continue;
  4974. }
  4975. Transform3D xf = sel_item->sp->get_global_transform();
  4976. gizmo_center += xf.origin;
  4977. if (count == 0 && local_gizmo_coords) {
  4978. gizmo_basis = xf.basis;
  4979. }
  4980. count++;
  4981. }
  4982. }
  4983. gizmo.visible = count > 0;
  4984. gizmo.transform.origin = (count > 0) ? gizmo_center / count : Vector3();
  4985. gizmo.transform.basis = (count == 1) ? gizmo_basis : Basis();
  4986. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  4987. viewports[i]->update_transform_gizmo_view();
  4988. }
  4989. }
  4990. void _update_all_gizmos(Node *p_node) {
  4991. for (int i = p_node->get_child_count() - 1; 0 <= i; --i) {
  4992. Node3D *spatial_node = Object::cast_to<Node3D>(p_node->get_child(i));
  4993. if (spatial_node) {
  4994. spatial_node->update_gizmos();
  4995. }
  4996. _update_all_gizmos(p_node->get_child(i));
  4997. }
  4998. }
  4999. void Node3DEditor::update_all_gizmos(Node *p_node) {
  5000. if (!p_node && is_inside_tree()) {
  5001. p_node = get_tree()->get_edited_scene_root();
  5002. }
  5003. if (!p_node) {
  5004. // No edited scene, so nothing to update.
  5005. return;
  5006. }
  5007. _update_all_gizmos(p_node);
  5008. }
  5009. Object *Node3DEditor::_get_editor_data(Object *p_what) {
  5010. Node3D *sp = Object::cast_to<Node3D>(p_what);
  5011. if (!sp) {
  5012. return nullptr;
  5013. }
  5014. Node3DEditorSelectedItem *si = memnew(Node3DEditorSelectedItem);
  5015. si->sp = sp;
  5016. si->sbox_instance = RenderingServer::get_singleton()->instance_create2(
  5017. selection_box->get_rid(),
  5018. sp->get_world_3d()->get_scenario());
  5019. si->sbox_instance_offset = RenderingServer::get_singleton()->instance_create2(
  5020. selection_box->get_rid(),
  5021. sp->get_world_3d()->get_scenario());
  5022. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  5023. si->sbox_instance,
  5024. RS::SHADOW_CASTING_SETTING_OFF);
  5025. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  5026. si->sbox_instance_offset,
  5027. RS::SHADOW_CASTING_SETTING_OFF);
  5028. // Use the Edit layer to hide the selection box when View Gizmos is disabled, since it is a bit distracting.
  5029. // It's still possible to approximately guess what is selected by looking at the manipulation gizmo position.
  5030. RS::get_singleton()->instance_set_layer_mask(si->sbox_instance, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
  5031. RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_offset, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
  5032. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  5033. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  5034. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_offset, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  5035. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_offset, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  5036. si->sbox_instance_xray = RenderingServer::get_singleton()->instance_create2(
  5037. selection_box_xray->get_rid(),
  5038. sp->get_world_3d()->get_scenario());
  5039. si->sbox_instance_xray_offset = RenderingServer::get_singleton()->instance_create2(
  5040. selection_box_xray->get_rid(),
  5041. sp->get_world_3d()->get_scenario());
  5042. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  5043. si->sbox_instance_xray,
  5044. RS::SHADOW_CASTING_SETTING_OFF);
  5045. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  5046. si->sbox_instance_xray_offset,
  5047. RS::SHADOW_CASTING_SETTING_OFF);
  5048. // Use the Edit layer to hide the selection box when View Gizmos is disabled, since it is a bit distracting.
  5049. // It's still possible to approximately guess what is selected by looking at the manipulation gizmo position.
  5050. RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
  5051. RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray_offset, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
  5052. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  5053. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  5054. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray_offset, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  5055. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray_offset, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  5056. return si;
  5057. }
  5058. void Node3DEditor::_generate_selection_boxes() {
  5059. // Use two AABBs to create the illusion of a slightly thicker line.
  5060. AABB aabb(Vector3(), Vector3(1, 1, 1));
  5061. // Create a x-ray (visible through solid surfaces) and standard version of the selection box.
  5062. // Both will be drawn at the same position, but with different opacity.
  5063. // This lets the user see where the selection is while still having a sense of depth.
  5064. Ref<SurfaceTool> st = memnew(SurfaceTool);
  5065. Ref<SurfaceTool> st_xray = memnew(SurfaceTool);
  5066. st->begin(Mesh::PRIMITIVE_LINES);
  5067. st_xray->begin(Mesh::PRIMITIVE_LINES);
  5068. for (int i = 0; i < 12; i++) {
  5069. Vector3 a, b;
  5070. aabb.get_edge(i, a, b);
  5071. st->add_vertex(a);
  5072. st->add_vertex(b);
  5073. st_xray->add_vertex(a);
  5074. st_xray->add_vertex(b);
  5075. }
  5076. Ref<StandardMaterial3D> mat = memnew(StandardMaterial3D);
  5077. mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  5078. mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  5079. const Color selection_box_color = EDITOR_GET("editors/3d/selection_box_color");
  5080. mat->set_albedo(selection_box_color);
  5081. mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  5082. st->set_material(mat);
  5083. selection_box = st->commit();
  5084. Ref<StandardMaterial3D> mat_xray = memnew(StandardMaterial3D);
  5085. mat_xray->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  5086. mat_xray->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  5087. mat_xray->set_flag(StandardMaterial3D::FLAG_DISABLE_DEPTH_TEST, true);
  5088. mat_xray->set_albedo(selection_box_color * Color(1, 1, 1, 0.15));
  5089. mat_xray->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  5090. st_xray->set_material(mat_xray);
  5091. selection_box_xray = st_xray->commit();
  5092. }
  5093. Dictionary Node3DEditor::get_state() const {
  5094. Dictionary d;
  5095. d["snap_enabled"] = snap_enabled;
  5096. d["translate_snap"] = snap_translate_value;
  5097. d["rotate_snap"] = snap_rotate_value;
  5098. d["scale_snap"] = snap_scale_value;
  5099. d["local_coords"] = tool_option_button[TOOL_OPT_LOCAL_COORDS]->is_pressed();
  5100. int vc = 0;
  5101. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT))) {
  5102. vc = 1;
  5103. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS))) {
  5104. vc = 2;
  5105. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS))) {
  5106. vc = 3;
  5107. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS))) {
  5108. vc = 4;
  5109. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT))) {
  5110. vc = 5;
  5111. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT))) {
  5112. vc = 6;
  5113. }
  5114. d["viewport_mode"] = vc;
  5115. Array vpdata;
  5116. for (int i = 0; i < 4; i++) {
  5117. vpdata.push_back(viewports[i]->get_state());
  5118. }
  5119. d["viewports"] = vpdata;
  5120. d["show_grid"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID));
  5121. d["show_origin"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN));
  5122. d["fov"] = get_fov();
  5123. d["znear"] = get_znear();
  5124. d["zfar"] = get_zfar();
  5125. Dictionary gizmos_status;
  5126. for (int i = 0; i < gizmo_plugins_by_name.size(); i++) {
  5127. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  5128. continue;
  5129. }
  5130. int state = gizmos_menu->get_item_state(gizmos_menu->get_item_index(i));
  5131. String name = gizmo_plugins_by_name[i]->get_gizmo_name();
  5132. gizmos_status[name] = state;
  5133. }
  5134. d["gizmos_status"] = gizmos_status;
  5135. {
  5136. Dictionary pd;
  5137. pd["sun_rotation"] = sun_rotation;
  5138. pd["environ_sky_color"] = environ_sky_color->get_pick_color();
  5139. pd["environ_ground_color"] = environ_ground_color->get_pick_color();
  5140. pd["environ_energy"] = environ_energy->get_value();
  5141. pd["environ_glow_enabled"] = environ_glow_button->is_pressed();
  5142. pd["environ_tonemap_enabled"] = environ_tonemap_button->is_pressed();
  5143. pd["environ_ao_enabled"] = environ_ao_button->is_pressed();
  5144. pd["environ_gi_enabled"] = environ_gi_button->is_pressed();
  5145. pd["sun_max_distance"] = sun_max_distance->get_value();
  5146. pd["sun_color"] = sun_color->get_pick_color();
  5147. pd["sun_energy"] = sun_energy->get_value();
  5148. pd["sun_enabled"] = sun_button->is_pressed();
  5149. pd["environ_enabled"] = environ_button->is_pressed();
  5150. d["preview_sun_env"] = pd;
  5151. }
  5152. return d;
  5153. }
  5154. void Node3DEditor::set_state(const Dictionary &p_state) {
  5155. Dictionary d = p_state;
  5156. if (d.has("snap_enabled")) {
  5157. snap_enabled = d["snap_enabled"];
  5158. tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(d["snap_enabled"]);
  5159. }
  5160. if (d.has("translate_snap")) {
  5161. snap_translate_value = d["translate_snap"];
  5162. }
  5163. if (d.has("rotate_snap")) {
  5164. snap_rotate_value = d["rotate_snap"];
  5165. }
  5166. if (d.has("scale_snap")) {
  5167. snap_scale_value = d["scale_snap"];
  5168. }
  5169. _snap_update();
  5170. if (d.has("local_coords")) {
  5171. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(d["local_coords"]);
  5172. update_transform_gizmo();
  5173. }
  5174. if (d.has("viewport_mode")) {
  5175. int vc = d["viewport_mode"];
  5176. if (vc == 1) {
  5177. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  5178. } else if (vc == 2) {
  5179. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
  5180. } else if (vc == 3) {
  5181. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
  5182. } else if (vc == 4) {
  5183. _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
  5184. } else if (vc == 5) {
  5185. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
  5186. } else if (vc == 6) {
  5187. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
  5188. }
  5189. }
  5190. if (d.has("viewports")) {
  5191. Array vp = d["viewports"];
  5192. uint32_t vp_size = static_cast<uint32_t>(vp.size());
  5193. if (vp_size > VIEWPORTS_COUNT) {
  5194. WARN_PRINT("Ignoring superfluous viewport settings from spatial editor state.");
  5195. vp_size = VIEWPORTS_COUNT;
  5196. }
  5197. for (uint32_t i = 0; i < vp_size; i++) {
  5198. viewports[i]->set_state(vp[i]);
  5199. }
  5200. }
  5201. if (d.has("zfar")) {
  5202. settings_zfar->set_value(double(d["zfar"]));
  5203. }
  5204. if (d.has("znear")) {
  5205. settings_znear->set_value(double(d["znear"]));
  5206. }
  5207. if (d.has("fov")) {
  5208. settings_fov->set_value(double(d["fov"]));
  5209. }
  5210. if (d.has("show_grid")) {
  5211. bool use = d["show_grid"];
  5212. if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID))) {
  5213. _menu_item_pressed(MENU_VIEW_GRID);
  5214. }
  5215. }
  5216. if (d.has("show_origin")) {
  5217. bool use = d["show_origin"];
  5218. if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN))) {
  5219. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), use);
  5220. RenderingServer::get_singleton()->instance_set_visible(origin_instance, use);
  5221. }
  5222. }
  5223. if (d.has("gizmos_status")) {
  5224. Dictionary gizmos_status = d["gizmos_status"];
  5225. List<Variant> keys;
  5226. gizmos_status.get_key_list(&keys);
  5227. for (int j = 0; j < gizmo_plugins_by_name.size(); ++j) {
  5228. if (!gizmo_plugins_by_name[j]->can_be_hidden()) {
  5229. continue;
  5230. }
  5231. int state = EditorNode3DGizmoPlugin::VISIBLE;
  5232. for (const Variant &key : keys) {
  5233. if (gizmo_plugins_by_name.write[j]->get_gizmo_name() == String(key)) {
  5234. state = gizmos_status[key];
  5235. break;
  5236. }
  5237. }
  5238. gizmo_plugins_by_name.write[j]->set_state(state);
  5239. }
  5240. _update_gizmos_menu();
  5241. }
  5242. if (d.has("preview_sun_env")) {
  5243. sun_environ_updating = true;
  5244. Dictionary pd = d["preview_sun_env"];
  5245. sun_rotation = pd["sun_rotation"];
  5246. environ_sky_color->set_pick_color(pd["environ_sky_color"]);
  5247. environ_ground_color->set_pick_color(pd["environ_ground_color"]);
  5248. environ_energy->set_value(pd["environ_energy"]);
  5249. environ_glow_button->set_pressed(pd["environ_glow_enabled"]);
  5250. environ_tonemap_button->set_pressed(pd["environ_tonemap_enabled"]);
  5251. environ_ao_button->set_pressed(pd["environ_ao_enabled"]);
  5252. environ_gi_button->set_pressed(pd["environ_gi_enabled"]);
  5253. sun_max_distance->set_value(pd["sun_max_distance"]);
  5254. sun_color->set_pick_color(pd["sun_color"]);
  5255. sun_energy->set_value(pd["sun_energy"]);
  5256. sun_button->set_pressed(pd["sun_enabled"]);
  5257. environ_button->set_pressed(pd["environ_enabled"]);
  5258. sun_environ_updating = false;
  5259. _preview_settings_changed();
  5260. _update_preview_environment();
  5261. } else {
  5262. _load_default_preview_settings();
  5263. sun_button->set_pressed(true);
  5264. environ_button->set_pressed(true);
  5265. _preview_settings_changed();
  5266. _update_preview_environment();
  5267. }
  5268. }
  5269. void Node3DEditor::edit(Node3D *p_spatial) {
  5270. if (p_spatial != selected) {
  5271. if (selected) {
  5272. Vector<Ref<Node3DGizmo>> gizmos = selected->get_gizmos();
  5273. for (int i = 0; i < gizmos.size(); i++) {
  5274. Ref<EditorNode3DGizmo> seg = gizmos[i];
  5275. if (!seg.is_valid()) {
  5276. continue;
  5277. }
  5278. seg->set_selected(false);
  5279. }
  5280. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected);
  5281. if (se) {
  5282. se->gizmo.unref();
  5283. se->subgizmos.clear();
  5284. }
  5285. selected->update_gizmos();
  5286. }
  5287. selected = p_spatial;
  5288. current_hover_gizmo = Ref<EditorNode3DGizmo>();
  5289. current_hover_gizmo_handle = -1;
  5290. current_hover_gizmo_handle_secondary = false;
  5291. if (selected) {
  5292. Vector<Ref<Node3DGizmo>> gizmos = selected->get_gizmos();
  5293. for (int i = 0; i < gizmos.size(); i++) {
  5294. Ref<EditorNode3DGizmo> seg = gizmos[i];
  5295. if (!seg.is_valid()) {
  5296. continue;
  5297. }
  5298. seg->set_selected(true);
  5299. }
  5300. selected->update_gizmos();
  5301. }
  5302. }
  5303. }
  5304. void Node3DEditor::_snap_changed() {
  5305. snap_translate_value = snap_translate->get_text().to_float();
  5306. snap_rotate_value = snap_rotate->get_text().to_float();
  5307. snap_scale_value = snap_scale->get_text().to_float();
  5308. EditorSettings::get_singleton()->set_project_metadata("3d_editor", "snap_translate_value", snap_translate_value);
  5309. EditorSettings::get_singleton()->set_project_metadata("3d_editor", "snap_rotate_value", snap_rotate_value);
  5310. EditorSettings::get_singleton()->set_project_metadata("3d_editor", "snap_scale_value", snap_scale_value);
  5311. }
  5312. void Node3DEditor::_snap_update() {
  5313. snap_translate->set_text(String::num(snap_translate_value));
  5314. snap_rotate->set_text(String::num(snap_rotate_value));
  5315. snap_scale->set_text(String::num(snap_scale_value));
  5316. }
  5317. void Node3DEditor::_xform_dialog_action() {
  5318. Transform3D t;
  5319. //translation
  5320. Vector3 scale;
  5321. Vector3 rotate;
  5322. Vector3 translate;
  5323. for (int i = 0; i < 3; i++) {
  5324. translate[i] = xform_translate[i]->get_text().to_float();
  5325. rotate[i] = Math::deg_to_rad(xform_rotate[i]->get_text().to_float());
  5326. scale[i] = xform_scale[i]->get_text().to_float();
  5327. }
  5328. t.basis.scale(scale);
  5329. t.basis.rotate(rotate);
  5330. t.origin = translate;
  5331. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  5332. undo_redo->create_action(TTR("XForm Dialog"));
  5333. const List<Node *> &selection = editor_selection->get_selected_node_list();
  5334. for (Node *E : selection) {
  5335. Node3D *sp = Object::cast_to<Node3D>(E);
  5336. if (!sp) {
  5337. continue;
  5338. }
  5339. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  5340. if (!se) {
  5341. continue;
  5342. }
  5343. bool post = xform_type->get_selected() > 0;
  5344. Transform3D tr = sp->get_global_gizmo_transform();
  5345. if (post) {
  5346. tr = tr * t;
  5347. } else {
  5348. tr.basis = t.basis * tr.basis;
  5349. tr.origin += t.origin;
  5350. }
  5351. Node3D *parent = sp->get_parent_node_3d();
  5352. Transform3D local_tr = parent ? parent->get_global_transform().affine_inverse() * tr : tr;
  5353. undo_redo->add_do_method(sp, "set_transform", local_tr);
  5354. undo_redo->add_undo_method(sp, "set_transform", sp->get_transform());
  5355. }
  5356. undo_redo->commit_action();
  5357. }
  5358. void Node3DEditor::_menu_item_toggled(bool pressed, int p_option) {
  5359. switch (p_option) {
  5360. case MENU_TOOL_LOCAL_COORDS: {
  5361. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(pressed);
  5362. update_transform_gizmo();
  5363. } break;
  5364. case MENU_TOOL_USE_SNAP: {
  5365. tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(pressed);
  5366. snap_enabled = pressed;
  5367. } break;
  5368. case MENU_TOOL_OVERRIDE_CAMERA: {
  5369. EditorDebuggerNode *const debugger = EditorDebuggerNode::get_singleton();
  5370. using Override = EditorDebuggerNode::CameraOverride;
  5371. if (pressed) {
  5372. debugger->set_camera_override((Override)(Override::OVERRIDE_3D_1 + camera_override_viewport_id));
  5373. } else {
  5374. debugger->set_camera_override(Override::OVERRIDE_NONE);
  5375. }
  5376. } break;
  5377. }
  5378. }
  5379. void Node3DEditor::_menu_gizmo_toggled(int p_option) {
  5380. const int idx = gizmos_menu->get_item_index(p_option);
  5381. gizmos_menu->toggle_item_multistate(idx);
  5382. // Change icon
  5383. const int state = gizmos_menu->get_item_state(idx);
  5384. switch (state) {
  5385. case EditorNode3DGizmoPlugin::VISIBLE:
  5386. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_theme_icon(SNAME("visibility_visible")));
  5387. break;
  5388. case EditorNode3DGizmoPlugin::ON_TOP:
  5389. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_theme_icon(SNAME("visibility_xray")));
  5390. break;
  5391. case EditorNode3DGizmoPlugin::HIDDEN:
  5392. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_theme_icon(SNAME("visibility_hidden")));
  5393. break;
  5394. }
  5395. gizmo_plugins_by_name.write[p_option]->set_state(state);
  5396. update_all_gizmos();
  5397. }
  5398. void Node3DEditor::_update_camera_override_button(bool p_game_running) {
  5399. Button *const button = tool_option_button[TOOL_OPT_OVERRIDE_CAMERA];
  5400. if (p_game_running) {
  5401. button->set_disabled(false);
  5402. button->set_tooltip_text(TTR("Project Camera Override\nOverrides the running project's camera with the editor viewport camera."));
  5403. } else {
  5404. button->set_disabled(true);
  5405. button->set_pressed(false);
  5406. button->set_tooltip_text(TTR("Project Camera Override\nNo project instance running. Run the project from the editor to use this feature."));
  5407. }
  5408. }
  5409. void Node3DEditor::_update_camera_override_viewport(Object *p_viewport) {
  5410. Node3DEditorViewport *current_viewport = Object::cast_to<Node3DEditorViewport>(p_viewport);
  5411. if (!current_viewport) {
  5412. return;
  5413. }
  5414. EditorDebuggerNode *const debugger = EditorDebuggerNode::get_singleton();
  5415. camera_override_viewport_id = current_viewport->index;
  5416. if (debugger->get_camera_override() >= EditorDebuggerNode::OVERRIDE_3D_1) {
  5417. using Override = EditorDebuggerNode::CameraOverride;
  5418. debugger->set_camera_override((Override)(Override::OVERRIDE_3D_1 + camera_override_viewport_id));
  5419. }
  5420. }
  5421. void Node3DEditor::_menu_item_pressed(int p_option) {
  5422. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  5423. switch (p_option) {
  5424. case MENU_TOOL_SELECT:
  5425. case MENU_TOOL_MOVE:
  5426. case MENU_TOOL_ROTATE:
  5427. case MENU_TOOL_SCALE:
  5428. case MENU_TOOL_LIST_SELECT: {
  5429. for (int i = 0; i < TOOL_MAX; i++) {
  5430. tool_button[i]->set_pressed(i == p_option);
  5431. }
  5432. tool_mode = (ToolMode)p_option;
  5433. update_transform_gizmo();
  5434. } break;
  5435. case MENU_TRANSFORM_CONFIGURE_SNAP: {
  5436. snap_dialog->popup_centered(Size2(200, 180));
  5437. } break;
  5438. case MENU_TRANSFORM_DIALOG: {
  5439. for (int i = 0; i < 3; i++) {
  5440. xform_translate[i]->set_text("0");
  5441. xform_rotate[i]->set_text("0");
  5442. xform_scale[i]->set_text("1");
  5443. }
  5444. xform_dialog->popup_centered(Size2(320, 240) * EDSCALE);
  5445. } break;
  5446. case MENU_VIEW_USE_1_VIEWPORT: {
  5447. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_1_VIEWPORT);
  5448. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), true);
  5449. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5450. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5451. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5452. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5453. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5454. } break;
  5455. case MENU_VIEW_USE_2_VIEWPORTS: {
  5456. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_2_VIEWPORTS);
  5457. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5458. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), true);
  5459. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5460. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5461. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5462. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5463. } break;
  5464. case MENU_VIEW_USE_2_VIEWPORTS_ALT: {
  5465. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_2_VIEWPORTS_ALT);
  5466. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5467. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5468. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5469. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5470. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), true);
  5471. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5472. } break;
  5473. case MENU_VIEW_USE_3_VIEWPORTS: {
  5474. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_3_VIEWPORTS);
  5475. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5476. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5477. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), true);
  5478. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5479. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5480. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5481. } break;
  5482. case MENU_VIEW_USE_3_VIEWPORTS_ALT: {
  5483. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_3_VIEWPORTS_ALT);
  5484. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5485. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5486. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5487. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5488. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5489. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), true);
  5490. } break;
  5491. case MENU_VIEW_USE_4_VIEWPORTS: {
  5492. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_4_VIEWPORTS);
  5493. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5494. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5495. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5496. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), true);
  5497. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5498. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5499. } break;
  5500. case MENU_VIEW_ORIGIN: {
  5501. bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
  5502. origin_enabled = !is_checked;
  5503. RenderingServer::get_singleton()->instance_set_visible(origin_instance, origin_enabled);
  5504. // Update the grid since its appearance depends on whether the origin is enabled
  5505. _finish_grid();
  5506. _init_grid();
  5507. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), origin_enabled);
  5508. } break;
  5509. case MENU_VIEW_GRID: {
  5510. bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
  5511. grid_enabled = !is_checked;
  5512. for (int i = 0; i < 3; ++i) {
  5513. if (grid_enable[i]) {
  5514. grid_visible[i] = grid_enabled;
  5515. }
  5516. }
  5517. _finish_grid();
  5518. _init_grid();
  5519. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), grid_enabled);
  5520. } break;
  5521. case MENU_VIEW_CAMERA_SETTINGS: {
  5522. settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size() + Size2(50, 50));
  5523. } break;
  5524. case MENU_SNAP_TO_FLOOR: {
  5525. snap_selected_nodes_to_floor();
  5526. } break;
  5527. case MENU_LOCK_SELECTED: {
  5528. undo_redo->create_action(TTR("Lock Selected"));
  5529. List<Node *> &selection = editor_selection->get_selected_node_list();
  5530. for (Node *E : selection) {
  5531. Node3D *spatial = Object::cast_to<Node3D>(E);
  5532. if (!spatial || !spatial->is_inside_tree()) {
  5533. continue;
  5534. }
  5535. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  5536. continue;
  5537. }
  5538. undo_redo->add_do_method(spatial, "set_meta", "_edit_lock_", true);
  5539. undo_redo->add_undo_method(spatial, "remove_meta", "_edit_lock_");
  5540. undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
  5541. undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
  5542. }
  5543. undo_redo->add_do_method(this, "_refresh_menu_icons");
  5544. undo_redo->add_undo_method(this, "_refresh_menu_icons");
  5545. undo_redo->commit_action();
  5546. } break;
  5547. case MENU_UNLOCK_SELECTED: {
  5548. undo_redo->create_action(TTR("Unlock Selected"));
  5549. List<Node *> &selection = editor_selection->get_selected_node_list();
  5550. for (Node *E : selection) {
  5551. Node3D *spatial = Object::cast_to<Node3D>(E);
  5552. if (!spatial || !spatial->is_inside_tree()) {
  5553. continue;
  5554. }
  5555. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  5556. continue;
  5557. }
  5558. undo_redo->add_do_method(spatial, "remove_meta", "_edit_lock_");
  5559. undo_redo->add_undo_method(spatial, "set_meta", "_edit_lock_", true);
  5560. undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
  5561. undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
  5562. }
  5563. undo_redo->add_do_method(this, "_refresh_menu_icons");
  5564. undo_redo->add_undo_method(this, "_refresh_menu_icons");
  5565. undo_redo->commit_action();
  5566. } break;
  5567. case MENU_GROUP_SELECTED: {
  5568. undo_redo->create_action(TTR("Group Selected"));
  5569. List<Node *> &selection = editor_selection->get_selected_node_list();
  5570. for (Node *E : selection) {
  5571. Node3D *spatial = Object::cast_to<Node3D>(E);
  5572. if (!spatial || !spatial->is_inside_tree()) {
  5573. continue;
  5574. }
  5575. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  5576. continue;
  5577. }
  5578. undo_redo->add_do_method(spatial, "set_meta", "_edit_group_", true);
  5579. undo_redo->add_undo_method(spatial, "remove_meta", "_edit_group_");
  5580. undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
  5581. undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
  5582. }
  5583. undo_redo->add_do_method(this, "_refresh_menu_icons");
  5584. undo_redo->add_undo_method(this, "_refresh_menu_icons");
  5585. undo_redo->commit_action();
  5586. } break;
  5587. case MENU_UNGROUP_SELECTED: {
  5588. undo_redo->create_action(TTR("Ungroup Selected"));
  5589. List<Node *> &selection = editor_selection->get_selected_node_list();
  5590. for (Node *E : selection) {
  5591. Node3D *spatial = Object::cast_to<Node3D>(E);
  5592. if (!spatial || !spatial->is_inside_tree()) {
  5593. continue;
  5594. }
  5595. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  5596. continue;
  5597. }
  5598. undo_redo->add_do_method(spatial, "remove_meta", "_edit_group_");
  5599. undo_redo->add_undo_method(spatial, "set_meta", "_edit_group_", true);
  5600. undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
  5601. undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
  5602. }
  5603. undo_redo->add_do_method(this, "_refresh_menu_icons");
  5604. undo_redo->add_undo_method(this, "_refresh_menu_icons");
  5605. undo_redo->commit_action();
  5606. } break;
  5607. }
  5608. }
  5609. void Node3DEditor::_init_indicators() {
  5610. {
  5611. origin_enabled = true;
  5612. grid_enabled = true;
  5613. Ref<Shader> origin_shader = memnew(Shader);
  5614. origin_shader->set_code(R"(
  5615. // 3D editor origin line shader.
  5616. shader_type spatial;
  5617. render_mode blend_mix, cull_disabled, unshaded, fog_disabled;
  5618. void vertex() {
  5619. vec3 point_a = MODEL_MATRIX[3].xyz;
  5620. // Encoded in scale.
  5621. vec3 point_b = vec3(MODEL_MATRIX[0].x, MODEL_MATRIX[1].y, MODEL_MATRIX[2].z);
  5622. // Points are already in world space, so no need for MODEL_MATRIX anymore.
  5623. vec4 clip_a = PROJECTION_MATRIX * (VIEW_MATRIX * vec4(point_a, 1.0));
  5624. vec4 clip_b = PROJECTION_MATRIX * (VIEW_MATRIX * vec4(point_b, 1.0));
  5625. vec2 screen_a = VIEWPORT_SIZE * (0.5 * clip_a.xy / clip_a.w + 0.5);
  5626. vec2 screen_b = VIEWPORT_SIZE * (0.5 * clip_b.xy / clip_b.w + 0.5);
  5627. vec2 x_basis = normalize(screen_b - screen_a);
  5628. vec2 y_basis = vec2(-x_basis.y, x_basis.x);
  5629. float width = 3.0;
  5630. vec2 screen_point_a = screen_a + width * (VERTEX.x * x_basis + VERTEX.y * y_basis);
  5631. vec2 screen_point_b = screen_b + width * (VERTEX.x * x_basis + VERTEX.y * y_basis);
  5632. vec2 screen_point_final = mix(screen_point_a, screen_point_b, VERTEX.z);
  5633. vec4 clip_final = mix(clip_a, clip_b, VERTEX.z);
  5634. POSITION = vec4(clip_final.w * ((2.0 * screen_point_final) / VIEWPORT_SIZE - 1.0), clip_final.z, clip_final.w);
  5635. UV = VERTEX.yz * clip_final.w;
  5636. if (!OUTPUT_IS_SRGB) {
  5637. 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)));
  5638. }
  5639. }
  5640. void fragment() {
  5641. // Multiply by 0.5 since UV is actually UV is [-1, 1].
  5642. float line_width = fwidth(UV.x * 0.5);
  5643. float line_uv = abs(UV.x * 0.5);
  5644. float line = smoothstep(line_width * 1.0, line_width * 0.25, line_uv);
  5645. ALBEDO = COLOR.rgb;
  5646. ALPHA *= COLOR.a * line;
  5647. }
  5648. )");
  5649. origin_mat.instantiate();
  5650. origin_mat->set_shader(origin_shader);
  5651. Vector<Vector3> origin_points;
  5652. origin_points.resize(6);
  5653. origin_points.set(0, Vector3(0.0, -0.5, 0.0));
  5654. origin_points.set(1, Vector3(0.0, -0.5, 1.0));
  5655. origin_points.set(2, Vector3(0.0, 0.5, 1.0));
  5656. origin_points.set(3, Vector3(0.0, -0.5, 0.0));
  5657. origin_points.set(4, Vector3(0.0, 0.5, 1.0));
  5658. origin_points.set(5, Vector3(0.0, 0.5, 0.0));
  5659. Array d;
  5660. d.resize(RS::ARRAY_MAX);
  5661. d[RenderingServer::ARRAY_VERTEX] = origin_points;
  5662. origin_mesh = RenderingServer::get_singleton()->mesh_create();
  5663. RenderingServer::get_singleton()->mesh_add_surface_from_arrays(origin_mesh, RenderingServer::PRIMITIVE_TRIANGLES, d);
  5664. RenderingServer::get_singleton()->mesh_surface_set_material(origin_mesh, 0, origin_mat->get_rid());
  5665. origin_multimesh = RenderingServer::get_singleton()->multimesh_create();
  5666. RenderingServer::get_singleton()->multimesh_set_mesh(origin_multimesh, origin_mesh);
  5667. RenderingServer::get_singleton()->multimesh_allocate_data(origin_multimesh, 12, RS::MultimeshTransformFormat::MULTIMESH_TRANSFORM_3D, true, false);
  5668. RenderingServer::get_singleton()->multimesh_set_visible_instances(origin_multimesh, -1);
  5669. LocalVector<float> distances;
  5670. distances.resize(5);
  5671. distances[0] = -1000000.0;
  5672. distances[1] = -1000.0;
  5673. distances[2] = 0.0;
  5674. distances[3] = 1000.0;
  5675. distances[4] = 1000000.0;
  5676. for (int i = 0; i < 3; i++) {
  5677. Color origin_color;
  5678. switch (i) {
  5679. case 0:
  5680. origin_color = get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor));
  5681. break;
  5682. case 1:
  5683. origin_color = get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor));
  5684. break;
  5685. case 2:
  5686. origin_color = get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor));
  5687. break;
  5688. default:
  5689. origin_color = Color();
  5690. break;
  5691. }
  5692. Vector3 axis;
  5693. axis[i] = 1;
  5694. for (int j = 0; j < 4; j++) {
  5695. Transform3D t = Transform3D();
  5696. if (distances[j] > 0.0) {
  5697. t = t.scaled(axis * distances[j + 1]);
  5698. t = t.translated(axis * distances[j]);
  5699. } else {
  5700. t = t.scaled(axis * distances[j]);
  5701. t = t.translated(axis * distances[j + 1]);
  5702. }
  5703. RenderingServer::get_singleton()->multimesh_instance_set_transform(origin_multimesh, i * 4 + j, t);
  5704. RenderingServer::get_singleton()->multimesh_instance_set_color(origin_multimesh, i * 4 + j, origin_color);
  5705. }
  5706. }
  5707. origin_instance = RenderingServer::get_singleton()->instance_create2(origin_multimesh, get_tree()->get_root()->get_world_3d()->get_scenario());
  5708. RS::get_singleton()->instance_set_layer_mask(origin_instance, 1 << Node3DEditorViewport::GIZMO_GRID_LAYER);
  5709. RS::get_singleton()->instance_geometry_set_flag(origin_instance, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  5710. RS::get_singleton()->instance_geometry_set_flag(origin_instance, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  5711. RenderingServer::get_singleton()->instance_geometry_set_cast_shadows_setting(origin_instance, RS::SHADOW_CASTING_SETTING_OFF);
  5712. Ref<Shader> grid_shader = memnew(Shader);
  5713. grid_shader->set_code(R"(
  5714. // 3D editor grid shader.
  5715. shader_type spatial;
  5716. render_mode unshaded, fog_disabled;
  5717. uniform bool orthogonal;
  5718. uniform float grid_size;
  5719. void vertex() {
  5720. // From FLAG_SRGB_VERTEX_COLOR.
  5721. if (!OUTPUT_IS_SRGB) {
  5722. 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)));
  5723. }
  5724. }
  5725. void fragment() {
  5726. ALBEDO = COLOR.rgb;
  5727. vec3 dir = orthogonal ? -vec3(0, 0, 1) : VIEW;
  5728. float angle_fade = abs(dot(dir, NORMAL));
  5729. angle_fade = smoothstep(0.05, 0.2, angle_fade);
  5730. vec3 world_pos = (INV_VIEW_MATRIX * vec4(VERTEX, 1.0)).xyz;
  5731. vec3 world_normal = (INV_VIEW_MATRIX * vec4(NORMAL, 0.0)).xyz;
  5732. vec3 camera_world_pos = INV_VIEW_MATRIX[3].xyz;
  5733. vec3 camera_world_pos_on_plane = camera_world_pos * (1.0 - world_normal);
  5734. float dist_fade = 1.0 - (distance(world_pos, camera_world_pos_on_plane) / grid_size);
  5735. dist_fade = smoothstep(0.02, 0.3, dist_fade);
  5736. ALPHA = COLOR.a * dist_fade * angle_fade;
  5737. }
  5738. )");
  5739. for (int i = 0; i < 3; i++) {
  5740. grid_mat[i].instantiate();
  5741. grid_mat[i]->set_shader(grid_shader);
  5742. }
  5743. grid_enable[0] = EDITOR_GET("editors/3d/grid_xy_plane");
  5744. grid_enable[1] = EDITOR_GET("editors/3d/grid_yz_plane");
  5745. grid_enable[2] = EDITOR_GET("editors/3d/grid_xz_plane");
  5746. grid_visible[0] = grid_enable[0];
  5747. grid_visible[1] = grid_enable[1];
  5748. grid_visible[2] = grid_enable[2];
  5749. _init_grid();
  5750. }
  5751. {
  5752. //move gizmo
  5753. // Inverted zxy.
  5754. Vector3 ivec = Vector3(0, 0, -1);
  5755. Vector3 nivec = Vector3(-1, -1, 0);
  5756. Vector3 ivec2 = Vector3(-1, 0, 0);
  5757. Vector3 ivec3 = Vector3(0, -1, 0);
  5758. for (int i = 0; i < 3; i++) {
  5759. Color col;
  5760. switch (i) {
  5761. case 0:
  5762. col = get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor));
  5763. break;
  5764. case 1:
  5765. col = get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor));
  5766. break;
  5767. case 2:
  5768. col = get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor));
  5769. break;
  5770. default:
  5771. col = Color();
  5772. break;
  5773. }
  5774. col.a = EDITOR_GET("editors/3d/manipulator_gizmo_opacity");
  5775. move_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  5776. move_plane_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  5777. rotate_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  5778. scale_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  5779. scale_plane_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  5780. axis_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  5781. Ref<StandardMaterial3D> mat = memnew(StandardMaterial3D);
  5782. mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  5783. mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  5784. mat->set_on_top_of_alpha();
  5785. mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  5786. mat->set_albedo(col);
  5787. gizmo_color[i] = mat;
  5788. Ref<StandardMaterial3D> mat_hl = mat->duplicate();
  5789. const Color albedo = col.from_hsv(col.get_h(), 0.25, 1.0, 1);
  5790. mat_hl->set_albedo(albedo);
  5791. gizmo_color_hl[i] = mat_hl;
  5792. //translate
  5793. {
  5794. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  5795. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  5796. // Arrow profile
  5797. const int arrow_points = 5;
  5798. Vector3 arrow[5] = {
  5799. nivec * 0.0 + ivec * 0.0,
  5800. nivec * 0.01 + ivec * 0.0,
  5801. nivec * 0.01 + ivec * GIZMO_ARROW_OFFSET,
  5802. nivec * 0.065 + ivec * GIZMO_ARROW_OFFSET,
  5803. nivec * 0.0 + ivec * (GIZMO_ARROW_OFFSET + GIZMO_ARROW_SIZE),
  5804. };
  5805. int arrow_sides = 16;
  5806. const real_t arrow_sides_step = Math_TAU / arrow_sides;
  5807. for (int k = 0; k < arrow_sides; k++) {
  5808. Basis ma(ivec, k * arrow_sides_step);
  5809. Basis mb(ivec, (k + 1) * arrow_sides_step);
  5810. for (int j = 0; j < arrow_points - 1; j++) {
  5811. Vector3 points[4] = {
  5812. ma.xform(arrow[j]),
  5813. mb.xform(arrow[j]),
  5814. mb.xform(arrow[j + 1]),
  5815. ma.xform(arrow[j + 1]),
  5816. };
  5817. surftool->add_vertex(points[0]);
  5818. surftool->add_vertex(points[1]);
  5819. surftool->add_vertex(points[2]);
  5820. surftool->add_vertex(points[0]);
  5821. surftool->add_vertex(points[2]);
  5822. surftool->add_vertex(points[3]);
  5823. }
  5824. }
  5825. surftool->set_material(mat);
  5826. surftool->commit(move_gizmo[i]);
  5827. }
  5828. // Plane Translation
  5829. {
  5830. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  5831. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  5832. Vector3 vec = ivec2 - ivec3;
  5833. Vector3 plane[4] = {
  5834. vec * GIZMO_PLANE_DST,
  5835. vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
  5836. vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
  5837. vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
  5838. };
  5839. Basis ma(ivec, Math_PI / 2);
  5840. Vector3 points[4] = {
  5841. ma.xform(plane[0]),
  5842. ma.xform(plane[1]),
  5843. ma.xform(plane[2]),
  5844. ma.xform(plane[3]),
  5845. };
  5846. surftool->add_vertex(points[0]);
  5847. surftool->add_vertex(points[1]);
  5848. surftool->add_vertex(points[2]);
  5849. surftool->add_vertex(points[0]);
  5850. surftool->add_vertex(points[2]);
  5851. surftool->add_vertex(points[3]);
  5852. Ref<StandardMaterial3D> plane_mat = memnew(StandardMaterial3D);
  5853. plane_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  5854. plane_mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  5855. plane_mat->set_on_top_of_alpha();
  5856. plane_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  5857. plane_mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED);
  5858. plane_mat->set_albedo(col);
  5859. plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides
  5860. surftool->set_material(plane_mat);
  5861. surftool->commit(move_plane_gizmo[i]);
  5862. Ref<StandardMaterial3D> plane_mat_hl = plane_mat->duplicate();
  5863. plane_mat_hl->set_albedo(albedo);
  5864. plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
  5865. }
  5866. // Rotate
  5867. {
  5868. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  5869. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  5870. int n = 128; // number of circle segments
  5871. int m = 3; // number of thickness segments
  5872. real_t step = Math_TAU / n;
  5873. for (int j = 0; j < n; ++j) {
  5874. Basis basis = Basis(ivec, j * step);
  5875. Vector3 vertex = basis.xform(ivec2 * GIZMO_CIRCLE_SIZE);
  5876. for (int k = 0; k < m; ++k) {
  5877. Vector2 ofs = Vector2(Math::cos((Math_TAU * k) / m), Math::sin((Math_TAU * k) / m));
  5878. Vector3 normal = ivec * ofs.x + ivec2 * ofs.y;
  5879. surftool->set_normal(basis.xform(normal));
  5880. surftool->add_vertex(vertex);
  5881. }
  5882. }
  5883. for (int j = 0; j < n; ++j) {
  5884. for (int k = 0; k < m; ++k) {
  5885. int current_ring = j * m;
  5886. int next_ring = ((j + 1) % n) * m;
  5887. int current_segment = k;
  5888. int next_segment = (k + 1) % m;
  5889. surftool->add_index(current_ring + next_segment);
  5890. surftool->add_index(current_ring + current_segment);
  5891. surftool->add_index(next_ring + current_segment);
  5892. surftool->add_index(next_ring + current_segment);
  5893. surftool->add_index(next_ring + next_segment);
  5894. surftool->add_index(current_ring + next_segment);
  5895. }
  5896. }
  5897. Ref<Shader> rotate_shader = memnew(Shader);
  5898. rotate_shader->set_code(R"(
  5899. // 3D editor rotation manipulator gizmo shader.
  5900. shader_type spatial;
  5901. render_mode unshaded, depth_test_disabled, fog_disabled;
  5902. uniform vec4 albedo;
  5903. mat3 orthonormalize(mat3 m) {
  5904. vec3 x = normalize(m[0]);
  5905. vec3 y = normalize(m[1] - x * dot(x, m[1]));
  5906. vec3 z = m[2] - x * dot(x, m[2]);
  5907. z = normalize(z - y * (dot(y, m[2])));
  5908. return mat3(x,y,z);
  5909. }
  5910. void vertex() {
  5911. mat3 mv = orthonormalize(mat3(MODELVIEW_MATRIX));
  5912. vec3 n = mv * VERTEX;
  5913. float orientation = dot(vec3(0.0, 0.0, -1.0), n);
  5914. if (orientation <= 0.005) {
  5915. VERTEX += NORMAL * 0.02;
  5916. }
  5917. }
  5918. void fragment() {
  5919. ALBEDO = albedo.rgb;
  5920. ALPHA = albedo.a;
  5921. }
  5922. )");
  5923. Ref<ShaderMaterial> rotate_mat = memnew(ShaderMaterial);
  5924. rotate_mat->set_render_priority(Material::RENDER_PRIORITY_MAX);
  5925. rotate_mat->set_shader(rotate_shader);
  5926. rotate_mat->set_shader_parameter("albedo", col);
  5927. rotate_gizmo_color[i] = rotate_mat;
  5928. Array arrays = surftool->commit_to_arrays();
  5929. rotate_gizmo[i]->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);
  5930. rotate_gizmo[i]->surface_set_material(0, rotate_mat);
  5931. Ref<ShaderMaterial> rotate_mat_hl = rotate_mat->duplicate();
  5932. rotate_mat_hl->set_shader_parameter("albedo", albedo);
  5933. rotate_gizmo_color_hl[i] = rotate_mat_hl;
  5934. if (i == 2) { // Rotation white outline
  5935. Ref<ShaderMaterial> border_mat = rotate_mat->duplicate();
  5936. Ref<Shader> border_shader = memnew(Shader);
  5937. border_shader->set_code(R"(
  5938. // 3D editor rotation manipulator gizmo shader (white outline).
  5939. shader_type spatial;
  5940. render_mode unshaded, depth_test_disabled, fog_disabled;
  5941. uniform vec4 albedo;
  5942. mat3 orthonormalize(mat3 m) {
  5943. vec3 x = normalize(m[0]);
  5944. vec3 y = normalize(m[1] - x * dot(x, m[1]));
  5945. vec3 z = m[2] - x * dot(x, m[2]);
  5946. z = normalize(z - y * (dot(y, m[2])));
  5947. return mat3(x, y, z);
  5948. }
  5949. void vertex() {
  5950. mat3 mv = orthonormalize(mat3(MODELVIEW_MATRIX));
  5951. mv = inverse(mv);
  5952. VERTEX += NORMAL * 0.008;
  5953. vec3 camera_dir_local = mv * vec3(0.0, 0.0, 1.0);
  5954. vec3 camera_up_local = mv * vec3(0.0, 1.0, 0.0);
  5955. mat3 rotation_matrix = mat3(cross(camera_dir_local, camera_up_local), camera_up_local, camera_dir_local);
  5956. VERTEX = rotation_matrix * VERTEX;
  5957. }
  5958. void fragment() {
  5959. ALBEDO = albedo.rgb;
  5960. ALPHA = albedo.a;
  5961. }
  5962. )");
  5963. border_mat->set_shader(border_shader);
  5964. border_mat->set_shader_parameter("albedo", Color(0.75, 0.75, 0.75, col.a / 3.0));
  5965. rotate_gizmo[3] = Ref<ArrayMesh>(memnew(ArrayMesh));
  5966. rotate_gizmo[3]->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);
  5967. rotate_gizmo[3]->surface_set_material(0, border_mat);
  5968. }
  5969. }
  5970. // Scale
  5971. {
  5972. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  5973. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  5974. // Cube arrow profile
  5975. const int arrow_points = 6;
  5976. Vector3 arrow[6] = {
  5977. nivec * 0.0 + ivec * 0.0,
  5978. nivec * 0.01 + ivec * 0.0,
  5979. nivec * 0.01 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
  5980. nivec * 0.07 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
  5981. nivec * 0.07 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
  5982. nivec * 0.0 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
  5983. };
  5984. int arrow_sides = 4;
  5985. const real_t arrow_sides_step = Math_TAU / arrow_sides;
  5986. for (int k = 0; k < 4; k++) {
  5987. Basis ma(ivec, k * arrow_sides_step);
  5988. Basis mb(ivec, (k + 1) * arrow_sides_step);
  5989. for (int j = 0; j < arrow_points - 1; j++) {
  5990. Vector3 points[4] = {
  5991. ma.xform(arrow[j]),
  5992. mb.xform(arrow[j]),
  5993. mb.xform(arrow[j + 1]),
  5994. ma.xform(arrow[j + 1]),
  5995. };
  5996. surftool->add_vertex(points[0]);
  5997. surftool->add_vertex(points[1]);
  5998. surftool->add_vertex(points[2]);
  5999. surftool->add_vertex(points[0]);
  6000. surftool->add_vertex(points[2]);
  6001. surftool->add_vertex(points[3]);
  6002. }
  6003. }
  6004. surftool->set_material(mat);
  6005. surftool->commit(scale_gizmo[i]);
  6006. }
  6007. // Plane Scale
  6008. {
  6009. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  6010. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  6011. Vector3 vec = ivec2 - ivec3;
  6012. Vector3 plane[4] = {
  6013. vec * GIZMO_PLANE_DST,
  6014. vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
  6015. vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
  6016. vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
  6017. };
  6018. Basis ma(ivec, Math_PI / 2);
  6019. Vector3 points[4] = {
  6020. ma.xform(plane[0]),
  6021. ma.xform(plane[1]),
  6022. ma.xform(plane[2]),
  6023. ma.xform(plane[3]),
  6024. };
  6025. surftool->add_vertex(points[0]);
  6026. surftool->add_vertex(points[1]);
  6027. surftool->add_vertex(points[2]);
  6028. surftool->add_vertex(points[0]);
  6029. surftool->add_vertex(points[2]);
  6030. surftool->add_vertex(points[3]);
  6031. Ref<StandardMaterial3D> plane_mat = memnew(StandardMaterial3D);
  6032. plane_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  6033. plane_mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  6034. plane_mat->set_on_top_of_alpha();
  6035. plane_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  6036. plane_mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED);
  6037. plane_mat->set_albedo(col);
  6038. plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides
  6039. surftool->set_material(plane_mat);
  6040. surftool->commit(scale_plane_gizmo[i]);
  6041. Ref<StandardMaterial3D> plane_mat_hl = plane_mat->duplicate();
  6042. plane_mat_hl->set_albedo(col.from_hsv(col.get_h(), 0.25, 1.0, 1));
  6043. plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
  6044. }
  6045. // Lines to visualize transforms locked to an axis/plane
  6046. {
  6047. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  6048. surftool->begin(Mesh::PRIMITIVE_LINE_STRIP);
  6049. Vector3 vec;
  6050. vec[i] = 1;
  6051. // line extending through infinity(ish)
  6052. surftool->add_vertex(vec * -1048576);
  6053. surftool->add_vertex(Vector3());
  6054. surftool->add_vertex(vec * 1048576);
  6055. surftool->set_material(mat_hl);
  6056. surftool->commit(axis_gizmo[i]);
  6057. }
  6058. }
  6059. }
  6060. _generate_selection_boxes();
  6061. }
  6062. void Node3DEditor::_update_gizmos_menu() {
  6063. gizmos_menu->clear();
  6064. for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
  6065. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  6066. continue;
  6067. }
  6068. String plugin_name = gizmo_plugins_by_name[i]->get_gizmo_name();
  6069. const int plugin_state = gizmo_plugins_by_name[i]->get_state();
  6070. gizmos_menu->add_multistate_item(plugin_name, 3, plugin_state, i);
  6071. const int idx = gizmos_menu->get_item_index(i);
  6072. gizmos_menu->set_item_tooltip(
  6073. idx,
  6074. 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\")."));
  6075. switch (plugin_state) {
  6076. case EditorNode3DGizmoPlugin::VISIBLE:
  6077. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_visible")));
  6078. break;
  6079. case EditorNode3DGizmoPlugin::ON_TOP:
  6080. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_xray")));
  6081. break;
  6082. case EditorNode3DGizmoPlugin::HIDDEN:
  6083. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_hidden")));
  6084. break;
  6085. }
  6086. }
  6087. }
  6088. void Node3DEditor::_update_gizmos_menu_theme() {
  6089. for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
  6090. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  6091. continue;
  6092. }
  6093. const int plugin_state = gizmo_plugins_by_name[i]->get_state();
  6094. const int idx = gizmos_menu->get_item_index(i);
  6095. switch (plugin_state) {
  6096. case EditorNode3DGizmoPlugin::VISIBLE:
  6097. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_visible")));
  6098. break;
  6099. case EditorNode3DGizmoPlugin::ON_TOP:
  6100. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_xray")));
  6101. break;
  6102. case EditorNode3DGizmoPlugin::HIDDEN:
  6103. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_hidden")));
  6104. break;
  6105. }
  6106. }
  6107. }
  6108. void Node3DEditor::_init_grid() {
  6109. if (!grid_enabled) {
  6110. return;
  6111. }
  6112. Camera3D *camera = get_editor_viewport(0)->camera;
  6113. Vector3 camera_position = camera->get_position();
  6114. if (camera_position == Vector3()) {
  6115. return; // Camera3D is invalid, don't draw the grid.
  6116. }
  6117. bool orthogonal = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
  6118. Vector<Color> grid_colors[3];
  6119. Vector<Vector3> grid_points[3];
  6120. Vector<Vector3> grid_normals[3];
  6121. Color primary_grid_color = EDITOR_GET("editors/3d/primary_grid_color");
  6122. Color secondary_grid_color = EDITOR_GET("editors/3d/secondary_grid_color");
  6123. int grid_size = EDITOR_GET("editors/3d/grid_size");
  6124. int primary_grid_steps = EDITOR_GET("editors/3d/primary_grid_steps");
  6125. // Which grid planes are enabled? Which should we generate?
  6126. grid_enable[0] = grid_visible[0] = EDITOR_GET("editors/3d/grid_xy_plane");
  6127. grid_enable[1] = grid_visible[1] = EDITOR_GET("editors/3d/grid_yz_plane");
  6128. grid_enable[2] = grid_visible[2] = EDITOR_GET("editors/3d/grid_xz_plane");
  6129. // Offsets division_level for bigger or smaller grids.
  6130. // Default value is -0.2. -1.0 gives Blender-like behavior, 0.5 gives huge grids.
  6131. real_t division_level_bias = EDITOR_GET("editors/3d/grid_division_level_bias");
  6132. // Default largest grid size is 8^2 (default value is 2) when primary_grid_steps is 8 (64m apart, so primary grid lines are 512m apart).
  6133. int division_level_max = EDITOR_GET("editors/3d/grid_division_level_max");
  6134. // Default smallest grid size is 8^0 (default value is 0) when primary_grid_steps is 8.
  6135. int division_level_min = EDITOR_GET("editors/3d/grid_division_level_min");
  6136. 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.");
  6137. if (primary_grid_steps != 10) { // Log10 of 10 is 1.
  6138. // Change of base rule, divide by ln(10).
  6139. real_t div = Math::log((real_t)primary_grid_steps) / (real_t)2.302585092994045901094;
  6140. // Truncation (towards zero) is intentional.
  6141. division_level_max = (int)(division_level_max / div);
  6142. division_level_min = (int)(division_level_min / div);
  6143. }
  6144. for (int a = 0; a < 3; a++) {
  6145. if (!grid_enable[a]) {
  6146. continue; // If this grid plane is disabled, skip generation.
  6147. }
  6148. int b = (a + 1) % 3;
  6149. int c = (a + 2) % 3;
  6150. Vector3 normal;
  6151. normal[c] = 1.0;
  6152. real_t camera_distance = Math::abs(camera_position[c]);
  6153. if (orthogonal) {
  6154. camera_distance = camera->get_size() / 2.0;
  6155. Vector3 camera_direction = -camera->get_global_transform().get_basis().get_column(2);
  6156. Plane grid_plane = Plane(normal);
  6157. Vector3 intersection;
  6158. if (grid_plane.intersects_ray(camera_position, camera_direction, &intersection)) {
  6159. camera_position = intersection;
  6160. }
  6161. }
  6162. real_t division_level = Math::log(Math::abs(camera_distance)) / Math::log((double)primary_grid_steps) + division_level_bias;
  6163. real_t clamped_division_level = CLAMP(division_level, division_level_min, division_level_max);
  6164. real_t division_level_floored = Math::floor(clamped_division_level);
  6165. real_t division_level_decimals = clamped_division_level - division_level_floored;
  6166. real_t small_step_size = Math::pow(primary_grid_steps, division_level_floored);
  6167. real_t large_step_size = small_step_size * primary_grid_steps;
  6168. real_t center_a = large_step_size * (int)(camera_position[a] / large_step_size);
  6169. real_t center_b = large_step_size * (int)(camera_position[b] / large_step_size);
  6170. real_t bgn_a = center_a - grid_size * small_step_size;
  6171. real_t end_a = center_a + grid_size * small_step_size;
  6172. real_t bgn_b = center_b - grid_size * small_step_size;
  6173. real_t end_b = center_b + grid_size * small_step_size;
  6174. real_t fade_size = Math::pow(primary_grid_steps, division_level - 1.0);
  6175. real_t min_fade_size = Math::pow(primary_grid_steps, float(division_level_min));
  6176. real_t max_fade_size = Math::pow(primary_grid_steps, float(division_level_max));
  6177. fade_size = CLAMP(fade_size, min_fade_size, max_fade_size);
  6178. real_t grid_fade_size = (grid_size - primary_grid_steps) * fade_size;
  6179. grid_mat[c]->set_shader_parameter("grid_size", grid_fade_size);
  6180. grid_mat[c]->set_shader_parameter("orthogonal", orthogonal);
  6181. // Cache these so we don't have to re-access memory.
  6182. Vector<Vector3> &ref_grid = grid_points[c];
  6183. Vector<Vector3> &ref_grid_normals = grid_normals[c];
  6184. Vector<Color> &ref_grid_colors = grid_colors[c];
  6185. // Count our elements same as code below it.
  6186. int expected_size = 0;
  6187. for (int i = -grid_size; i <= grid_size; i++) {
  6188. const real_t position_a = center_a + i * small_step_size;
  6189. const real_t position_b = center_b + i * small_step_size;
  6190. // Don't draw lines over the origin if it's enabled.
  6191. if (!(origin_enabled && Math::is_zero_approx(position_a))) {
  6192. expected_size += 2;
  6193. }
  6194. if (!(origin_enabled && Math::is_zero_approx(position_b))) {
  6195. expected_size += 2;
  6196. }
  6197. }
  6198. int idx = 0;
  6199. ref_grid.resize(expected_size);
  6200. ref_grid_normals.resize(expected_size);
  6201. ref_grid_colors.resize(expected_size);
  6202. // In each iteration of this loop, draw one line in each direction (so two lines per loop, in each if statement).
  6203. for (int i = -grid_size; i <= grid_size; i++) {
  6204. Color line_color;
  6205. // Is this a primary line? Set the appropriate color.
  6206. if (i % primary_grid_steps == 0) {
  6207. line_color = primary_grid_color.lerp(secondary_grid_color, division_level_decimals);
  6208. } else {
  6209. line_color = secondary_grid_color;
  6210. line_color.a = line_color.a * (1 - division_level_decimals);
  6211. }
  6212. real_t position_a = center_a + i * small_step_size;
  6213. real_t position_b = center_b + i * small_step_size;
  6214. // Don't draw lines over the origin if it's enabled.
  6215. if (!(origin_enabled && Math::is_zero_approx(position_a))) {
  6216. Vector3 line_bgn;
  6217. Vector3 line_end;
  6218. line_bgn[a] = position_a;
  6219. line_end[a] = position_a;
  6220. line_bgn[b] = bgn_b;
  6221. line_end[b] = end_b;
  6222. ref_grid.set(idx, line_bgn);
  6223. ref_grid.set(idx + 1, line_end);
  6224. ref_grid_colors.set(idx, line_color);
  6225. ref_grid_colors.set(idx + 1, line_color);
  6226. ref_grid_normals.set(idx, normal);
  6227. ref_grid_normals.set(idx + 1, normal);
  6228. idx += 2;
  6229. }
  6230. if (!(origin_enabled && Math::is_zero_approx(position_b))) {
  6231. Vector3 line_bgn;
  6232. Vector3 line_end;
  6233. line_bgn[b] = position_b;
  6234. line_end[b] = position_b;
  6235. line_bgn[a] = bgn_a;
  6236. line_end[a] = end_a;
  6237. ref_grid.set(idx, line_bgn);
  6238. ref_grid.set(idx + 1, line_end);
  6239. ref_grid_colors.set(idx, line_color);
  6240. ref_grid_colors.set(idx + 1, line_color);
  6241. ref_grid_normals.set(idx, normal);
  6242. ref_grid_normals.set(idx + 1, normal);
  6243. idx += 2;
  6244. }
  6245. }
  6246. // Create a mesh from the pushed vector points and colors.
  6247. grid[c] = RenderingServer::get_singleton()->mesh_create();
  6248. Array d;
  6249. d.resize(RS::ARRAY_MAX);
  6250. d[RenderingServer::ARRAY_VERTEX] = grid_points[c];
  6251. d[RenderingServer::ARRAY_COLOR] = grid_colors[c];
  6252. d[RenderingServer::ARRAY_NORMAL] = grid_normals[c];
  6253. RenderingServer::get_singleton()->mesh_add_surface_from_arrays(grid[c], RenderingServer::PRIMITIVE_LINES, d);
  6254. RenderingServer::get_singleton()->mesh_surface_set_material(grid[c], 0, grid_mat[c]->get_rid());
  6255. grid_instance[c] = RenderingServer::get_singleton()->instance_create2(grid[c], get_tree()->get_root()->get_world_3d()->get_scenario());
  6256. // Yes, the end of this line is supposed to be a.
  6257. RenderingServer::get_singleton()->instance_set_visible(grid_instance[c], grid_visible[a]);
  6258. RenderingServer::get_singleton()->instance_geometry_set_cast_shadows_setting(grid_instance[c], RS::SHADOW_CASTING_SETTING_OFF);
  6259. RS::get_singleton()->instance_set_layer_mask(grid_instance[c], 1 << Node3DEditorViewport::GIZMO_GRID_LAYER);
  6260. RS::get_singleton()->instance_geometry_set_flag(grid_instance[c], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  6261. RS::get_singleton()->instance_geometry_set_flag(grid_instance[c], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  6262. }
  6263. }
  6264. void Node3DEditor::_finish_indicators() {
  6265. RenderingServer::get_singleton()->free(origin_instance);
  6266. RenderingServer::get_singleton()->free(origin_multimesh);
  6267. RenderingServer::get_singleton()->free(origin_mesh);
  6268. _finish_grid();
  6269. }
  6270. void Node3DEditor::_finish_grid() {
  6271. for (int i = 0; i < 3; i++) {
  6272. RenderingServer::get_singleton()->free(grid_instance[i]);
  6273. RenderingServer::get_singleton()->free(grid[i]);
  6274. }
  6275. }
  6276. void Node3DEditor::update_grid() {
  6277. const Camera3D::ProjectionType current_projection = viewports[0]->camera->get_projection();
  6278. if (current_projection != grid_camera_last_update_perspective) {
  6279. grid_init_draw = false; // redraw
  6280. grid_camera_last_update_perspective = current_projection;
  6281. }
  6282. // Gets a orthogonal or perspective position correctly (for the grid comparison)
  6283. const Vector3 camera_position = get_editor_viewport(0)->camera->get_position();
  6284. if (!grid_init_draw || grid_camera_last_update_position.distance_squared_to(camera_position) >= 100.0f) {
  6285. _finish_grid();
  6286. _init_grid();
  6287. grid_init_draw = true;
  6288. grid_camera_last_update_position = camera_position;
  6289. }
  6290. }
  6291. void Node3DEditor::_selection_changed() {
  6292. _refresh_menu_icons();
  6293. if (selected && editor_selection->get_selected_node_list().size() != 1) {
  6294. Vector<Ref<Node3DGizmo>> gizmos = selected->get_gizmos();
  6295. for (int i = 0; i < gizmos.size(); i++) {
  6296. Ref<EditorNode3DGizmo> seg = gizmos[i];
  6297. if (!seg.is_valid()) {
  6298. continue;
  6299. }
  6300. seg->set_selected(false);
  6301. }
  6302. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected);
  6303. if (se) {
  6304. se->gizmo.unref();
  6305. se->subgizmos.clear();
  6306. }
  6307. selected->update_gizmos();
  6308. selected = nullptr;
  6309. }
  6310. update_transform_gizmo();
  6311. }
  6312. void Node3DEditor::_refresh_menu_icons() {
  6313. bool all_locked = true;
  6314. bool all_grouped = true;
  6315. bool has_node3d_item = false;
  6316. List<Node *> &selection = editor_selection->get_selected_node_list();
  6317. if (selection.is_empty()) {
  6318. all_locked = false;
  6319. all_grouped = false;
  6320. } else {
  6321. for (Node *E : selection) {
  6322. Node3D *node = Object::cast_to<Node3D>(E);
  6323. if (node) {
  6324. if (all_locked && !node->has_meta("_edit_lock_")) {
  6325. all_locked = false;
  6326. }
  6327. if (all_grouped && !node->has_meta("_edit_group_")) {
  6328. all_grouped = false;
  6329. }
  6330. has_node3d_item = true;
  6331. }
  6332. if (!all_locked && !all_grouped) {
  6333. break;
  6334. }
  6335. }
  6336. }
  6337. all_locked = all_locked && has_node3d_item;
  6338. all_grouped = all_grouped && has_node3d_item;
  6339. tool_button[TOOL_LOCK_SELECTED]->set_visible(!all_locked);
  6340. tool_button[TOOL_LOCK_SELECTED]->set_disabled(!has_node3d_item);
  6341. tool_button[TOOL_UNLOCK_SELECTED]->set_visible(all_locked);
  6342. tool_button[TOOL_UNLOCK_SELECTED]->set_disabled(!has_node3d_item);
  6343. tool_button[TOOL_GROUP_SELECTED]->set_visible(!all_grouped);
  6344. tool_button[TOOL_GROUP_SELECTED]->set_disabled(!has_node3d_item);
  6345. tool_button[TOOL_UNGROUP_SELECTED]->set_visible(all_grouped);
  6346. tool_button[TOOL_UNGROUP_SELECTED]->set_disabled(!has_node3d_item);
  6347. }
  6348. template <typename T>
  6349. HashSet<T *> _get_child_nodes(Node *parent_node) {
  6350. HashSet<T *> nodes = HashSet<T *>();
  6351. T *node = Node::cast_to<T>(parent_node);
  6352. if (node) {
  6353. nodes.insert(node);
  6354. }
  6355. for (int i = 0; i < parent_node->get_child_count(); i++) {
  6356. Node *child_node = parent_node->get_child(i);
  6357. HashSet<T *> child_nodes = _get_child_nodes<T>(child_node);
  6358. for (T *I : child_nodes) {
  6359. nodes.insert(I);
  6360. }
  6361. }
  6362. return nodes;
  6363. }
  6364. HashSet<RID> _get_physics_bodies_rid(Node *node) {
  6365. HashSet<RID> rids = HashSet<RID>();
  6366. PhysicsBody3D *pb = Node::cast_to<PhysicsBody3D>(node);
  6367. if (pb) {
  6368. rids.insert(pb->get_rid());
  6369. }
  6370. HashSet<PhysicsBody3D *> child_nodes = _get_child_nodes<PhysicsBody3D>(node);
  6371. for (const PhysicsBody3D *I : child_nodes) {
  6372. rids.insert(I->get_rid());
  6373. }
  6374. return rids;
  6375. }
  6376. void Node3DEditor::snap_selected_nodes_to_floor() {
  6377. do_snap_selected_nodes_to_floor = true;
  6378. }
  6379. void Node3DEditor::_snap_selected_nodes_to_floor() {
  6380. const List<Node *> &selection = editor_selection->get_selected_node_list();
  6381. Dictionary snap_data;
  6382. for (Node *E : selection) {
  6383. Node3D *sp = Object::cast_to<Node3D>(E);
  6384. if (sp) {
  6385. Vector3 from;
  6386. Vector3 position_offset;
  6387. // Priorities for snapping to floor are CollisionShapes, VisualInstances and then origin
  6388. HashSet<VisualInstance3D *> vi = _get_child_nodes<VisualInstance3D>(sp);
  6389. HashSet<CollisionShape3D *> cs = _get_child_nodes<CollisionShape3D>(sp);
  6390. bool found_valid_shape = false;
  6391. if (cs.size()) {
  6392. AABB aabb;
  6393. HashSet<CollisionShape3D *>::Iterator I = cs.begin();
  6394. if ((*I)->get_shape().is_valid()) {
  6395. CollisionShape3D *collision_shape = *cs.begin();
  6396. aabb = collision_shape->get_global_transform().xform(collision_shape->get_shape()->get_debug_mesh()->get_aabb());
  6397. found_valid_shape = true;
  6398. }
  6399. for (++I; I; ++I) {
  6400. CollisionShape3D *col_shape = *I;
  6401. if (col_shape->get_shape().is_valid()) {
  6402. aabb.merge_with(col_shape->get_global_transform().xform(col_shape->get_shape()->get_debug_mesh()->get_aabb()));
  6403. found_valid_shape = true;
  6404. }
  6405. }
  6406. if (found_valid_shape) {
  6407. Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
  6408. from = aabb.position + size;
  6409. position_offset.y = from.y - sp->get_global_transform().origin.y;
  6410. }
  6411. }
  6412. if (!found_valid_shape && vi.size()) {
  6413. VisualInstance3D *begin = *vi.begin();
  6414. AABB aabb = begin->get_global_transform().xform(begin->get_aabb());
  6415. for (const VisualInstance3D *I : vi) {
  6416. aabb.merge_with(I->get_global_transform().xform(I->get_aabb()));
  6417. }
  6418. Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
  6419. from = aabb.position + size;
  6420. position_offset.y = from.y - sp->get_global_transform().origin.y;
  6421. } else if (!found_valid_shape) {
  6422. from = sp->get_global_transform().origin;
  6423. }
  6424. // We add a bit of margin to the from position to avoid it from snapping
  6425. // when the spatial is already on a floor and there's another floor under
  6426. // it
  6427. from = from + Vector3(0.0, 1, 0.0);
  6428. Dictionary d;
  6429. d["from"] = from;
  6430. d["position_offset"] = position_offset;
  6431. snap_data[sp] = d;
  6432. }
  6433. }
  6434. PhysicsDirectSpaceState3D *ss = get_tree()->get_root()->get_world_3d()->get_direct_space_state();
  6435. PhysicsDirectSpaceState3D::RayResult result;
  6436. Array keys = snap_data.keys();
  6437. // The maximum height an object can travel to be snapped
  6438. const float max_snap_height = 500.0;
  6439. // Will be set to `true` if at least one node from the selection was successfully snapped
  6440. bool snapped_to_floor = false;
  6441. if (keys.size()) {
  6442. // For snapping to be performed, there must be solid geometry under at least one of the selected nodes.
  6443. // We need to check this before snapping to register the undo/redo action only if needed.
  6444. for (int i = 0; i < keys.size(); i++) {
  6445. Node *node = Object::cast_to<Node>(keys[i]);
  6446. Node3D *sp = Object::cast_to<Node3D>(node);
  6447. Dictionary d = snap_data[node];
  6448. Vector3 from = d["from"];
  6449. Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
  6450. HashSet<RID> excluded = _get_physics_bodies_rid(sp);
  6451. PhysicsDirectSpaceState3D::RayParameters ray_params;
  6452. ray_params.from = from;
  6453. ray_params.to = to;
  6454. ray_params.exclude = excluded;
  6455. if (ss->intersect_ray(ray_params, result)) {
  6456. snapped_to_floor = true;
  6457. }
  6458. }
  6459. if (snapped_to_floor) {
  6460. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  6461. undo_redo->create_action(TTR("Snap Nodes to Floor"));
  6462. // Perform snapping if at least one node can be snapped
  6463. for (int i = 0; i < keys.size(); i++) {
  6464. Node *node = Object::cast_to<Node>(keys[i]);
  6465. Node3D *sp = Object::cast_to<Node3D>(node);
  6466. Dictionary d = snap_data[node];
  6467. Vector3 from = d["from"];
  6468. Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
  6469. HashSet<RID> excluded = _get_physics_bodies_rid(sp);
  6470. PhysicsDirectSpaceState3D::RayParameters ray_params;
  6471. ray_params.from = from;
  6472. ray_params.to = to;
  6473. ray_params.exclude = excluded;
  6474. if (ss->intersect_ray(ray_params, result)) {
  6475. Vector3 position_offset = d["position_offset"];
  6476. Transform3D new_transform = sp->get_global_transform();
  6477. new_transform.origin.y = result.position.y;
  6478. new_transform.origin = new_transform.origin - position_offset;
  6479. Node3D *parent = sp->get_parent_node_3d();
  6480. Transform3D new_local_xform = parent ? parent->get_global_transform().affine_inverse() * new_transform : new_transform;
  6481. undo_redo->add_do_method(sp, "set_transform", new_local_xform);
  6482. undo_redo->add_undo_method(sp, "set_transform", sp->get_transform());
  6483. }
  6484. }
  6485. undo_redo->commit_action();
  6486. } else {
  6487. EditorNode::get_singleton()->show_warning(TTR("Couldn't find a solid floor to snap the selection to."));
  6488. }
  6489. }
  6490. }
  6491. void Node3DEditor::shortcut_input(const Ref<InputEvent> &p_event) {
  6492. ERR_FAIL_COND(p_event.is_null());
  6493. if (!is_visible_in_tree()) {
  6494. return;
  6495. }
  6496. snap_key_enabled = Input::get_singleton()->is_key_pressed(Key::CTRL);
  6497. }
  6498. void Node3DEditor::_sun_environ_settings_pressed() {
  6499. Vector2 pos = sun_environ_settings->get_screen_position() + sun_environ_settings->get_size();
  6500. sun_environ_popup->set_position(pos - Vector2(sun_environ_popup->get_contents_minimum_size().width / 2, 0));
  6501. sun_environ_popup->reset_size();
  6502. sun_environ_popup->popup();
  6503. }
  6504. void Node3DEditor::_add_sun_to_scene(bool p_already_added_environment) {
  6505. sun_environ_popup->hide();
  6506. if (!p_already_added_environment && world_env_count == 0 && Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  6507. // Prevent infinite feedback loop between the sun and environment methods.
  6508. _add_environment_to_scene(true);
  6509. }
  6510. Node *base = get_tree()->get_edited_scene_root();
  6511. if (!base) {
  6512. // Create a root node so we can add child nodes to it.
  6513. SceneTreeDock::get_singleton()->add_root_node(memnew(Node3D));
  6514. base = get_tree()->get_edited_scene_root();
  6515. }
  6516. ERR_FAIL_NULL(base);
  6517. Node *new_sun = preview_sun->duplicate();
  6518. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  6519. undo_redo->create_action(TTR("Add Preview Sun to Scene"));
  6520. undo_redo->add_do_method(base, "add_child", new_sun, true);
  6521. // Move to the beginning of the scene tree since more "global" nodes
  6522. // generally look better when placed at the top.
  6523. undo_redo->add_do_method(base, "move_child", new_sun, 0);
  6524. undo_redo->add_do_method(new_sun, "set_owner", base);
  6525. undo_redo->add_undo_method(base, "remove_child", new_sun);
  6526. undo_redo->add_do_reference(new_sun);
  6527. undo_redo->commit_action();
  6528. }
  6529. void Node3DEditor::_add_environment_to_scene(bool p_already_added_sun) {
  6530. sun_environ_popup->hide();
  6531. if (!p_already_added_sun && directional_light_count == 0 && Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  6532. // Prevent infinite feedback loop between the sun and environment methods.
  6533. _add_sun_to_scene(true);
  6534. }
  6535. Node *base = get_tree()->get_edited_scene_root();
  6536. if (!base) {
  6537. // Create a root node so we can add child nodes to it.
  6538. SceneTreeDock::get_singleton()->add_root_node(memnew(Node3D));
  6539. base = get_tree()->get_edited_scene_root();
  6540. }
  6541. ERR_FAIL_NULL(base);
  6542. WorldEnvironment *new_env = memnew(WorldEnvironment);
  6543. new_env->set_environment(preview_environment->get_environment()->duplicate(true));
  6544. if (GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units")) {
  6545. new_env->set_camera_attributes(preview_environment->get_camera_attributes()->duplicate(true));
  6546. }
  6547. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  6548. undo_redo->create_action(TTR("Add Preview Environment to Scene"));
  6549. undo_redo->add_do_method(base, "add_child", new_env, true);
  6550. // Move to the beginning of the scene tree since more "global" nodes
  6551. // generally look better when placed at the top.
  6552. undo_redo->add_do_method(base, "move_child", new_env, 0);
  6553. undo_redo->add_do_method(new_env, "set_owner", base);
  6554. undo_redo->add_undo_method(base, "remove_child", new_env);
  6555. undo_redo->add_do_reference(new_env);
  6556. undo_redo->commit_action();
  6557. }
  6558. void Node3DEditor::_update_theme() {
  6559. tool_button[TOOL_MODE_SELECT]->set_icon(get_editor_theme_icon(SNAME("ToolSelect")));
  6560. tool_button[TOOL_MODE_MOVE]->set_icon(get_editor_theme_icon(SNAME("ToolMove")));
  6561. tool_button[TOOL_MODE_ROTATE]->set_icon(get_editor_theme_icon(SNAME("ToolRotate")));
  6562. tool_button[TOOL_MODE_SCALE]->set_icon(get_editor_theme_icon(SNAME("ToolScale")));
  6563. tool_button[TOOL_MODE_LIST_SELECT]->set_icon(get_editor_theme_icon(SNAME("ListSelect")));
  6564. tool_button[TOOL_LOCK_SELECTED]->set_icon(get_editor_theme_icon(SNAME("Lock")));
  6565. tool_button[TOOL_UNLOCK_SELECTED]->set_icon(get_editor_theme_icon(SNAME("Unlock")));
  6566. tool_button[TOOL_GROUP_SELECTED]->set_icon(get_editor_theme_icon(SNAME("Group")));
  6567. tool_button[TOOL_UNGROUP_SELECTED]->set_icon(get_editor_theme_icon(SNAME("Ungroup")));
  6568. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_icon(get_editor_theme_icon(SNAME("Object")));
  6569. tool_option_button[TOOL_OPT_USE_SNAP]->set_icon(get_editor_theme_icon(SNAME("Snap")));
  6570. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_icon(get_editor_theme_icon(SNAME("Camera3D")));
  6571. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), get_editor_theme_icon(SNAME("Panels1")));
  6572. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), get_editor_theme_icon(SNAME("Panels2")));
  6573. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), get_editor_theme_icon(SNAME("Panels2Alt")));
  6574. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), get_editor_theme_icon(SNAME("Panels3")));
  6575. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), get_editor_theme_icon(SNAME("Panels3Alt")));
  6576. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), get_editor_theme_icon(SNAME("Panels4")));
  6577. sun_button->set_icon(get_editor_theme_icon(SNAME("PreviewSun")));
  6578. environ_button->set_icon(get_editor_theme_icon(SNAME("PreviewEnvironment")));
  6579. sun_environ_settings->set_icon(get_editor_theme_icon(SNAME("GuiTabMenuHl")));
  6580. sun_title->add_theme_font_override("font", get_theme_font(SNAME("title_font"), SNAME("Window")));
  6581. environ_title->add_theme_font_override("font", get_theme_font(SNAME("title_font"), SNAME("Window")));
  6582. sun_color->set_custom_minimum_size(Size2(0, get_theme_constant(SNAME("color_picker_button_height"), EditorStringName(Editor))));
  6583. environ_sky_color->set_custom_minimum_size(Size2(0, get_theme_constant(SNAME("color_picker_button_height"), EditorStringName(Editor))));
  6584. environ_ground_color->set_custom_minimum_size(Size2(0, get_theme_constant(SNAME("color_picker_button_height"), EditorStringName(Editor))));
  6585. context_toolbar_panel->add_theme_style_override("panel", get_theme_stylebox(SNAME("ContextualToolbar"), EditorStringName(EditorStyles)));
  6586. }
  6587. void Node3DEditor::_notification(int p_what) {
  6588. switch (p_what) {
  6589. case NOTIFICATION_READY: {
  6590. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  6591. _refresh_menu_icons();
  6592. get_tree()->connect("node_removed", callable_mp(this, &Node3DEditor::_node_removed));
  6593. get_tree()->connect("node_added", callable_mp(this, &Node3DEditor::_node_added));
  6594. SceneTreeDock::get_singleton()->get_tree_editor()->connect("node_changed", callable_mp(this, &Node3DEditor::_refresh_menu_icons));
  6595. editor_selection->connect("selection_changed", callable_mp(this, &Node3DEditor::_selection_changed));
  6596. EditorRunBar::get_singleton()->connect("stop_pressed", callable_mp(this, &Node3DEditor::_update_camera_override_button).bind(false));
  6597. EditorRunBar::get_singleton()->connect("play_pressed", callable_mp(this, &Node3DEditor::_update_camera_override_button).bind(true));
  6598. _update_preview_environment();
  6599. sun_state->set_custom_minimum_size(sun_vb->get_combined_minimum_size());
  6600. environ_state->set_custom_minimum_size(environ_vb->get_combined_minimum_size());
  6601. ProjectSettings::get_singleton()->connect("settings_changed", callable_mp(this, &Node3DEditor::update_all_gizmos).bind(Variant()));
  6602. } break;
  6603. case NOTIFICATION_ENTER_TREE: {
  6604. _update_theme();
  6605. _register_all_gizmos();
  6606. _update_gizmos_menu();
  6607. _init_indicators();
  6608. update_all_gizmos();
  6609. } break;
  6610. case NOTIFICATION_EXIT_TREE: {
  6611. _finish_indicators();
  6612. } break;
  6613. case NOTIFICATION_THEME_CHANGED: {
  6614. _update_theme();
  6615. _update_gizmos_menu_theme();
  6616. sun_title->add_theme_font_override("font", get_theme_font(SNAME("title_font"), SNAME("Window")));
  6617. environ_title->add_theme_font_override("font", get_theme_font(SNAME("title_font"), SNAME("Window")));
  6618. } break;
  6619. case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
  6620. // Update grid color by rebuilding grid.
  6621. if (EditorSettings::get_singleton()->check_changed_settings_in_group("editors/3d")) {
  6622. _finish_grid();
  6623. _init_grid();
  6624. }
  6625. } break;
  6626. case NOTIFICATION_VISIBILITY_CHANGED: {
  6627. if (!is_visible() && tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->is_pressed()) {
  6628. EditorDebuggerNode *debugger = EditorDebuggerNode::get_singleton();
  6629. debugger->set_camera_override(EditorDebuggerNode::OVERRIDE_NONE);
  6630. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_pressed(false);
  6631. }
  6632. } break;
  6633. case NOTIFICATION_PHYSICS_PROCESS: {
  6634. if (do_snap_selected_nodes_to_floor) {
  6635. _snap_selected_nodes_to_floor();
  6636. do_snap_selected_nodes_to_floor = false;
  6637. }
  6638. }
  6639. }
  6640. }
  6641. bool Node3DEditor::is_subgizmo_selected(int p_id) {
  6642. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  6643. if (se) {
  6644. return se->subgizmos.has(p_id);
  6645. }
  6646. return false;
  6647. }
  6648. bool Node3DEditor::is_current_selected_gizmo(const EditorNode3DGizmo *p_gizmo) {
  6649. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  6650. if (se) {
  6651. return se->gizmo == p_gizmo;
  6652. }
  6653. return false;
  6654. }
  6655. Vector<int> Node3DEditor::get_subgizmo_selection() {
  6656. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  6657. Vector<int> ret;
  6658. if (se) {
  6659. for (const KeyValue<int, Transform3D> &E : se->subgizmos) {
  6660. ret.push_back(E.key);
  6661. }
  6662. }
  6663. return ret;
  6664. }
  6665. void Node3DEditor::clear_subgizmo_selection(Object *p_obj) {
  6666. _clear_subgizmo_selection(p_obj);
  6667. }
  6668. void Node3DEditor::add_control_to_menu_panel(Control *p_control) {
  6669. ERR_FAIL_NULL(p_control);
  6670. ERR_FAIL_COND(p_control->get_parent());
  6671. VSeparator *sep = memnew(VSeparator);
  6672. context_toolbar_hbox->add_child(sep);
  6673. context_toolbar_hbox->add_child(p_control);
  6674. context_toolbar_separators[p_control] = sep;
  6675. p_control->connect(SceneStringName(visibility_changed), callable_mp(this, &Node3DEditor::_update_context_toolbar));
  6676. _update_context_toolbar();
  6677. }
  6678. void Node3DEditor::remove_control_from_menu_panel(Control *p_control) {
  6679. ERR_FAIL_NULL(p_control);
  6680. ERR_FAIL_COND(p_control->get_parent() != context_toolbar_hbox);
  6681. p_control->disconnect(SceneStringName(visibility_changed), callable_mp(this, &Node3DEditor::_update_context_toolbar));
  6682. VSeparator *sep = context_toolbar_separators[p_control];
  6683. context_toolbar_hbox->remove_child(sep);
  6684. context_toolbar_hbox->remove_child(p_control);
  6685. context_toolbar_separators.erase(p_control);
  6686. memdelete(sep);
  6687. _update_context_toolbar();
  6688. }
  6689. void Node3DEditor::_update_context_toolbar() {
  6690. bool has_visible = false;
  6691. bool first_visible = false;
  6692. for (int i = 0; i < context_toolbar_hbox->get_child_count(); i++) {
  6693. Control *child = Object::cast_to<Control>(context_toolbar_hbox->get_child(i));
  6694. if (!child || !context_toolbar_separators.has(child)) {
  6695. continue;
  6696. }
  6697. if (child->is_visible()) {
  6698. first_visible = !has_visible;
  6699. has_visible = true;
  6700. }
  6701. VSeparator *sep = context_toolbar_separators[child];
  6702. sep->set_visible(!first_visible && child->is_visible());
  6703. }
  6704. context_toolbar_panel->set_visible(has_visible);
  6705. }
  6706. void Node3DEditor::set_can_preview(Camera3D *p_preview) {
  6707. for (int i = 0; i < 4; i++) {
  6708. viewports[i]->set_can_preview(p_preview);
  6709. }
  6710. }
  6711. VSplitContainer *Node3DEditor::get_shader_split() {
  6712. return shader_split;
  6713. }
  6714. void Node3DEditor::add_control_to_left_panel(Control *p_control) {
  6715. left_panel_split->add_child(p_control);
  6716. left_panel_split->move_child(p_control, 0);
  6717. }
  6718. void Node3DEditor::add_control_to_right_panel(Control *p_control) {
  6719. right_panel_split->add_child(p_control);
  6720. right_panel_split->move_child(p_control, 1);
  6721. }
  6722. void Node3DEditor::remove_control_from_left_panel(Control *p_control) {
  6723. left_panel_split->remove_child(p_control);
  6724. }
  6725. void Node3DEditor::remove_control_from_right_panel(Control *p_control) {
  6726. right_panel_split->remove_child(p_control);
  6727. }
  6728. void Node3DEditor::move_control_to_left_panel(Control *p_control) {
  6729. ERR_FAIL_NULL(p_control);
  6730. if (p_control->get_parent() == left_panel_split) {
  6731. return;
  6732. }
  6733. ERR_FAIL_COND(p_control->get_parent() != right_panel_split);
  6734. right_panel_split->remove_child(p_control);
  6735. add_control_to_left_panel(p_control);
  6736. }
  6737. void Node3DEditor::move_control_to_right_panel(Control *p_control) {
  6738. ERR_FAIL_NULL(p_control);
  6739. if (p_control->get_parent() == right_panel_split) {
  6740. return;
  6741. }
  6742. ERR_FAIL_COND(p_control->get_parent() != left_panel_split);
  6743. left_panel_split->remove_child(p_control);
  6744. add_control_to_right_panel(p_control);
  6745. }
  6746. void Node3DEditor::_request_gizmo(Object *p_obj) {
  6747. Node3D *sp = Object::cast_to<Node3D>(p_obj);
  6748. if (!sp) {
  6749. return;
  6750. }
  6751. bool is_selected = (sp == selected);
  6752. Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
  6753. if (edited_scene && (sp == edited_scene || (sp->get_owner() && edited_scene->is_ancestor_of(sp)))) {
  6754. for (int i = 0; i < gizmo_plugins_by_priority.size(); ++i) {
  6755. Ref<EditorNode3DGizmo> seg = gizmo_plugins_by_priority.write[i]->get_gizmo(sp);
  6756. if (seg.is_valid()) {
  6757. sp->add_gizmo(seg);
  6758. if (is_selected != seg->is_selected()) {
  6759. seg->set_selected(is_selected);
  6760. }
  6761. }
  6762. }
  6763. if (!sp->get_gizmos().is_empty()) {
  6764. sp->update_gizmos();
  6765. }
  6766. }
  6767. }
  6768. void Node3DEditor::_request_gizmo_for_id(ObjectID p_id) {
  6769. Node3D *node = Object::cast_to<Node3D>(ObjectDB::get_instance(p_id));
  6770. if (node) {
  6771. _request_gizmo(node);
  6772. }
  6773. }
  6774. void Node3DEditor::_set_subgizmo_selection(Object *p_obj, Ref<Node3DGizmo> p_gizmo, int p_id, Transform3D p_transform) {
  6775. if (p_id == -1) {
  6776. _clear_subgizmo_selection(p_obj);
  6777. return;
  6778. }
  6779. Node3D *sp = nullptr;
  6780. if (p_obj) {
  6781. sp = Object::cast_to<Node3D>(p_obj);
  6782. } else {
  6783. sp = selected;
  6784. }
  6785. if (!sp) {
  6786. return;
  6787. }
  6788. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  6789. if (se) {
  6790. se->subgizmos.clear();
  6791. se->subgizmos.insert(p_id, p_transform);
  6792. se->gizmo = p_gizmo;
  6793. sp->update_gizmos();
  6794. update_transform_gizmo();
  6795. }
  6796. }
  6797. void Node3DEditor::_clear_subgizmo_selection(Object *p_obj) {
  6798. Node3D *sp = nullptr;
  6799. if (p_obj) {
  6800. sp = Object::cast_to<Node3D>(p_obj);
  6801. } else {
  6802. sp = selected;
  6803. }
  6804. if (!sp) {
  6805. return;
  6806. }
  6807. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  6808. if (se) {
  6809. se->subgizmos.clear();
  6810. se->gizmo.unref();
  6811. sp->update_gizmos();
  6812. update_transform_gizmo();
  6813. }
  6814. }
  6815. void Node3DEditor::_toggle_maximize_view(Object *p_viewport) {
  6816. if (!p_viewport) {
  6817. return;
  6818. }
  6819. Node3DEditorViewport *current_viewport = Object::cast_to<Node3DEditorViewport>(p_viewport);
  6820. if (!current_viewport) {
  6821. return;
  6822. }
  6823. int index = -1;
  6824. bool maximized = false;
  6825. for (int i = 0; i < 4; i++) {
  6826. if (viewports[i] == current_viewport) {
  6827. index = i;
  6828. if (current_viewport->get_global_rect() == viewport_base->get_global_rect()) {
  6829. maximized = true;
  6830. }
  6831. break;
  6832. }
  6833. }
  6834. if (index == -1) {
  6835. return;
  6836. }
  6837. if (!maximized) {
  6838. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  6839. if (i == (uint32_t)index) {
  6840. viewports[i]->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  6841. } else {
  6842. viewports[i]->hide();
  6843. }
  6844. }
  6845. } else {
  6846. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  6847. viewports[i]->show();
  6848. }
  6849. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT))) {
  6850. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  6851. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS))) {
  6852. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
  6853. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT))) {
  6854. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
  6855. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS))) {
  6856. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
  6857. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT))) {
  6858. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
  6859. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS))) {
  6860. _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
  6861. }
  6862. }
  6863. }
  6864. void Node3DEditor::_node_added(Node *p_node) {
  6865. if (EditorNode::get_singleton()->get_scene_root()->is_ancestor_of(p_node)) {
  6866. if (Object::cast_to<WorldEnvironment>(p_node)) {
  6867. world_env_count++;
  6868. if (world_env_count == 1) {
  6869. _update_preview_environment();
  6870. }
  6871. } else if (Object::cast_to<DirectionalLight3D>(p_node)) {
  6872. directional_light_count++;
  6873. if (directional_light_count == 1) {
  6874. _update_preview_environment();
  6875. }
  6876. }
  6877. }
  6878. }
  6879. void Node3DEditor::_node_removed(Node *p_node) {
  6880. if (EditorNode::get_singleton()->get_scene_root()->is_ancestor_of(p_node)) {
  6881. if (Object::cast_to<WorldEnvironment>(p_node)) {
  6882. world_env_count--;
  6883. if (world_env_count == 0) {
  6884. _update_preview_environment();
  6885. }
  6886. } else if (Object::cast_to<DirectionalLight3D>(p_node)) {
  6887. directional_light_count--;
  6888. if (directional_light_count == 0) {
  6889. _update_preview_environment();
  6890. }
  6891. }
  6892. }
  6893. if (p_node == selected) {
  6894. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected);
  6895. if (se) {
  6896. se->gizmo.unref();
  6897. se->subgizmos.clear();
  6898. }
  6899. selected = nullptr;
  6900. update_transform_gizmo();
  6901. }
  6902. }
  6903. void Node3DEditor::_register_all_gizmos() {
  6904. add_gizmo_plugin(Ref<Camera3DGizmoPlugin>(memnew(Camera3DGizmoPlugin)));
  6905. add_gizmo_plugin(Ref<Light3DGizmoPlugin>(memnew(Light3DGizmoPlugin)));
  6906. add_gizmo_plugin(Ref<AudioStreamPlayer3DGizmoPlugin>(memnew(AudioStreamPlayer3DGizmoPlugin)));
  6907. add_gizmo_plugin(Ref<AudioListener3DGizmoPlugin>(memnew(AudioListener3DGizmoPlugin)));
  6908. add_gizmo_plugin(Ref<MeshInstance3DGizmoPlugin>(memnew(MeshInstance3DGizmoPlugin)));
  6909. add_gizmo_plugin(Ref<OccluderInstance3DGizmoPlugin>(memnew(OccluderInstance3DGizmoPlugin)));
  6910. add_gizmo_plugin(Ref<SoftBody3DGizmoPlugin>(memnew(SoftBody3DGizmoPlugin)));
  6911. add_gizmo_plugin(Ref<SpriteBase3DGizmoPlugin>(memnew(SpriteBase3DGizmoPlugin)));
  6912. add_gizmo_plugin(Ref<Label3DGizmoPlugin>(memnew(Label3DGizmoPlugin)));
  6913. add_gizmo_plugin(Ref<GeometryInstance3DGizmoPlugin>(memnew(GeometryInstance3DGizmoPlugin)));
  6914. add_gizmo_plugin(Ref<Marker3DGizmoPlugin>(memnew(Marker3DGizmoPlugin)));
  6915. add_gizmo_plugin(Ref<RayCast3DGizmoPlugin>(memnew(RayCast3DGizmoPlugin)));
  6916. add_gizmo_plugin(Ref<ShapeCast3DGizmoPlugin>(memnew(ShapeCast3DGizmoPlugin)));
  6917. add_gizmo_plugin(Ref<SpringArm3DGizmoPlugin>(memnew(SpringArm3DGizmoPlugin)));
  6918. add_gizmo_plugin(Ref<VehicleWheel3DGizmoPlugin>(memnew(VehicleWheel3DGizmoPlugin)));
  6919. add_gizmo_plugin(Ref<VisibleOnScreenNotifier3DGizmoPlugin>(memnew(VisibleOnScreenNotifier3DGizmoPlugin)));
  6920. add_gizmo_plugin(Ref<GPUParticles3DGizmoPlugin>(memnew(GPUParticles3DGizmoPlugin)));
  6921. add_gizmo_plugin(Ref<GPUParticlesCollision3DGizmoPlugin>(memnew(GPUParticlesCollision3DGizmoPlugin)));
  6922. add_gizmo_plugin(Ref<CPUParticles3DGizmoPlugin>(memnew(CPUParticles3DGizmoPlugin)));
  6923. add_gizmo_plugin(Ref<ReflectionProbeGizmoPlugin>(memnew(ReflectionProbeGizmoPlugin)));
  6924. add_gizmo_plugin(Ref<DecalGizmoPlugin>(memnew(DecalGizmoPlugin)));
  6925. add_gizmo_plugin(Ref<VoxelGIGizmoPlugin>(memnew(VoxelGIGizmoPlugin)));
  6926. add_gizmo_plugin(Ref<LightmapGIGizmoPlugin>(memnew(LightmapGIGizmoPlugin)));
  6927. add_gizmo_plugin(Ref<LightmapProbeGizmoPlugin>(memnew(LightmapProbeGizmoPlugin)));
  6928. add_gizmo_plugin(Ref<CollisionObject3DGizmoPlugin>(memnew(CollisionObject3DGizmoPlugin)));
  6929. add_gizmo_plugin(Ref<CollisionShape3DGizmoPlugin>(memnew(CollisionShape3DGizmoPlugin)));
  6930. add_gizmo_plugin(Ref<CollisionPolygon3DGizmoPlugin>(memnew(CollisionPolygon3DGizmoPlugin)));
  6931. add_gizmo_plugin(Ref<NavigationLink3DGizmoPlugin>(memnew(NavigationLink3DGizmoPlugin)));
  6932. add_gizmo_plugin(Ref<NavigationRegion3DGizmoPlugin>(memnew(NavigationRegion3DGizmoPlugin)));
  6933. add_gizmo_plugin(Ref<Joint3DGizmoPlugin>(memnew(Joint3DGizmoPlugin)));
  6934. add_gizmo_plugin(Ref<PhysicalBone3DGizmoPlugin>(memnew(PhysicalBone3DGizmoPlugin)));
  6935. add_gizmo_plugin(Ref<FogVolumeGizmoPlugin>(memnew(FogVolumeGizmoPlugin)));
  6936. }
  6937. void Node3DEditor::_bind_methods() {
  6938. ClassDB::bind_method("_get_editor_data", &Node3DEditor::_get_editor_data);
  6939. ClassDB::bind_method("_request_gizmo", &Node3DEditor::_request_gizmo);
  6940. ClassDB::bind_method("_request_gizmo_for_id", &Node3DEditor::_request_gizmo_for_id);
  6941. ClassDB::bind_method("_set_subgizmo_selection", &Node3DEditor::_set_subgizmo_selection);
  6942. ClassDB::bind_method("_clear_subgizmo_selection", &Node3DEditor::_clear_subgizmo_selection);
  6943. ClassDB::bind_method("_refresh_menu_icons", &Node3DEditor::_refresh_menu_icons);
  6944. ClassDB::bind_method("update_all_gizmos", &Node3DEditor::update_all_gizmos);
  6945. ClassDB::bind_method("update_transform_gizmo", &Node3DEditor::update_transform_gizmo);
  6946. ADD_SIGNAL(MethodInfo("transform_key_request"));
  6947. ADD_SIGNAL(MethodInfo("item_lock_status_changed"));
  6948. ADD_SIGNAL(MethodInfo("item_group_status_changed"));
  6949. }
  6950. void Node3DEditor::clear() {
  6951. settings_fov->set_value(EDITOR_GET("editors/3d/default_fov"));
  6952. settings_znear->set_value(EDITOR_GET("editors/3d/default_z_near"));
  6953. settings_zfar->set_value(EDITOR_GET("editors/3d/default_z_far"));
  6954. snap_translate_value = EditorSettings::get_singleton()->get_project_metadata("3d_editor", "snap_translate_value", 1);
  6955. snap_rotate_value = EditorSettings::get_singleton()->get_project_metadata("3d_editor", "snap_rotate_value", 15);
  6956. snap_scale_value = EditorSettings::get_singleton()->get_project_metadata("3d_editor", "snap_scale_value", 10);
  6957. _snap_update();
  6958. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  6959. viewports[i]->reset();
  6960. }
  6961. if (origin_instance.is_valid()) {
  6962. RenderingServer::get_singleton()->instance_set_visible(origin_instance, true);
  6963. }
  6964. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), true);
  6965. for (int i = 0; i < 3; ++i) {
  6966. if (grid_enable[i]) {
  6967. grid_visible[i] = true;
  6968. }
  6969. }
  6970. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  6971. viewports[i]->view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(Node3DEditorViewport::VIEW_AUDIO_LISTENER), i == 0);
  6972. viewports[i]->viewport->set_as_audio_listener_3d(i == 0);
  6973. }
  6974. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID), true);
  6975. grid_enabled = true;
  6976. grid_init_draw = false;
  6977. }
  6978. void Node3DEditor::_sun_direction_draw() {
  6979. sun_direction->draw_rect(Rect2(Vector2(), sun_direction->get_size()), Color(1, 1, 1, 1));
  6980. Vector3 z_axis = preview_sun->get_transform().basis.get_column(Vector3::AXIS_Z);
  6981. z_axis = get_editor_viewport(0)->camera->get_camera_transform().basis.xform_inv(z_axis);
  6982. sun_direction_material->set_shader_parameter("sun_direction", Vector3(z_axis.x, -z_axis.y, z_axis.z));
  6983. Color color = sun_color->get_pick_color() * sun_energy->get_value();
  6984. sun_direction_material->set_shader_parameter("sun_color", Vector3(color.r, color.g, color.b));
  6985. }
  6986. void Node3DEditor::_preview_settings_changed() {
  6987. if (sun_environ_updating) {
  6988. return;
  6989. }
  6990. { // preview sun
  6991. Transform3D t;
  6992. t.basis = Basis::from_euler(Vector3(sun_rotation.x, sun_rotation.y, 0));
  6993. preview_sun->set_transform(t);
  6994. sun_direction->queue_redraw();
  6995. preview_sun->set_param(Light3D::PARAM_ENERGY, sun_energy->get_value());
  6996. preview_sun->set_param(Light3D::PARAM_SHADOW_MAX_DISTANCE, sun_max_distance->get_value());
  6997. preview_sun->set_color(sun_color->get_pick_color());
  6998. }
  6999. { //preview env
  7000. sky_material->set_sky_energy_multiplier(environ_energy->get_value());
  7001. Color hz_color = environ_sky_color->get_pick_color().lerp(environ_ground_color->get_pick_color(), 0.5).lerp(Color(1, 1, 1), 0.5);
  7002. sky_material->set_sky_top_color(environ_sky_color->get_pick_color());
  7003. sky_material->set_sky_horizon_color(hz_color);
  7004. sky_material->set_ground_bottom_color(environ_ground_color->get_pick_color());
  7005. sky_material->set_ground_horizon_color(hz_color);
  7006. environment->set_ssao_enabled(environ_ao_button->is_pressed());
  7007. environment->set_glow_enabled(environ_glow_button->is_pressed());
  7008. environment->set_sdfgi_enabled(environ_gi_button->is_pressed());
  7009. environment->set_tonemapper(environ_tonemap_button->is_pressed() ? Environment::TONE_MAPPER_FILMIC : Environment::TONE_MAPPER_LINEAR);
  7010. }
  7011. }
  7012. void Node3DEditor::_load_default_preview_settings() {
  7013. sun_environ_updating = true;
  7014. // These default rotations place the preview sun at an angular altitude
  7015. // of 60 degrees (must be negative) and an azimuth of 30 degrees clockwise
  7016. // from north (or 150 CCW from south), from north east, facing south west.
  7017. // On any not-tidally-locked planet, a sun would have an angular altitude
  7018. // of 60 degrees as the average of all points on the sphere at noon.
  7019. // The azimuth choice is arbitrary, but ideally shouldn't be on an axis.
  7020. sun_rotation = Vector2(-Math::deg_to_rad(60.0), Math::deg_to_rad(150.0));
  7021. sun_angle_altitude->set_value(-Math::rad_to_deg(sun_rotation.x));
  7022. sun_angle_azimuth->set_value(180.0 - Math::rad_to_deg(sun_rotation.y));
  7023. sun_direction->queue_redraw();
  7024. environ_sky_color->set_pick_color(Color(0.385, 0.454, 0.55));
  7025. environ_ground_color->set_pick_color(Color(0.2, 0.169, 0.133));
  7026. environ_energy->set_value(1.0);
  7027. if (OS::get_singleton()->get_current_rendering_method() != "gl_compatibility") {
  7028. environ_glow_button->set_pressed(true);
  7029. }
  7030. environ_tonemap_button->set_pressed(true);
  7031. environ_ao_button->set_pressed(false);
  7032. environ_gi_button->set_pressed(false);
  7033. sun_max_distance->set_value(100);
  7034. sun_color->set_pick_color(Color(1, 1, 1));
  7035. sun_energy->set_value(1.0);
  7036. sun_environ_updating = false;
  7037. }
  7038. void Node3DEditor::_update_preview_environment() {
  7039. bool disable_light = directional_light_count > 0 || !sun_button->is_pressed();
  7040. sun_button->set_disabled(directional_light_count > 0);
  7041. if (disable_light) {
  7042. if (preview_sun->get_parent()) {
  7043. preview_sun->get_parent()->remove_child(preview_sun);
  7044. sun_state->show();
  7045. sun_vb->hide();
  7046. preview_sun_dangling = true;
  7047. }
  7048. if (directional_light_count > 0) {
  7049. sun_state->set_text(TTR("Scene contains\nDirectionalLight3D.\nPreview disabled."));
  7050. } else {
  7051. sun_state->set_text(TTR("Preview disabled."));
  7052. }
  7053. } else {
  7054. if (!preview_sun->get_parent()) {
  7055. add_child(preview_sun, true);
  7056. sun_state->hide();
  7057. sun_vb->show();
  7058. preview_sun_dangling = false;
  7059. }
  7060. }
  7061. sun_angle_altitude->set_value(-Math::rad_to_deg(sun_rotation.x));
  7062. sun_angle_azimuth->set_value(180.0 - Math::rad_to_deg(sun_rotation.y));
  7063. bool disable_env = world_env_count > 0 || !environ_button->is_pressed();
  7064. environ_button->set_disabled(world_env_count > 0);
  7065. if (disable_env) {
  7066. if (preview_environment->get_parent()) {
  7067. preview_environment->get_parent()->remove_child(preview_environment);
  7068. environ_state->show();
  7069. environ_vb->hide();
  7070. preview_env_dangling = true;
  7071. }
  7072. if (world_env_count > 0) {
  7073. environ_state->set_text(TTR("Scene contains\nWorldEnvironment.\nPreview disabled."));
  7074. } else {
  7075. environ_state->set_text(TTR("Preview disabled."));
  7076. }
  7077. } else {
  7078. if (!preview_environment->get_parent()) {
  7079. add_child(preview_environment);
  7080. environ_state->hide();
  7081. environ_vb->show();
  7082. preview_env_dangling = false;
  7083. }
  7084. }
  7085. }
  7086. void Node3DEditor::_sun_direction_input(const Ref<InputEvent> &p_event) {
  7087. Ref<InputEventMouseMotion> mm = p_event;
  7088. if (mm.is_valid() && (mm->get_button_mask().has_flag(MouseButtonMask::LEFT))) {
  7089. sun_rotation.x += mm->get_relative().y * (0.02 * EDSCALE);
  7090. sun_rotation.y -= mm->get_relative().x * (0.02 * EDSCALE);
  7091. sun_rotation.x = CLAMP(sun_rotation.x, -Math_TAU / 4, Math_TAU / 4);
  7092. sun_angle_altitude->set_value(-Math::rad_to_deg(sun_rotation.x));
  7093. sun_angle_azimuth->set_value(180.0 - Math::rad_to_deg(sun_rotation.y));
  7094. _preview_settings_changed();
  7095. }
  7096. }
  7097. void Node3DEditor::_sun_direction_angle_set() {
  7098. sun_rotation.x = Math::deg_to_rad(-sun_angle_altitude->get_value());
  7099. sun_rotation.y = Math::deg_to_rad(180.0 - sun_angle_azimuth->get_value());
  7100. _preview_settings_changed();
  7101. }
  7102. Node3DEditor::Node3DEditor() {
  7103. gizmo.visible = true;
  7104. gizmo.scale = 1.0;
  7105. viewport_environment = Ref<Environment>(memnew(Environment));
  7106. VBoxContainer *vbc = this;
  7107. custom_camera = nullptr;
  7108. singleton = this;
  7109. editor_selection = EditorNode::get_singleton()->get_editor_selection();
  7110. editor_selection->add_editor_plugin(this);
  7111. snap_enabled = false;
  7112. snap_key_enabled = false;
  7113. tool_mode = TOOL_MODE_SELECT;
  7114. camera_override_viewport_id = 0;
  7115. // Add some margin to the sides for better esthetics.
  7116. // This prevents the first button's hover/pressed effect from "touching" the panel's border,
  7117. // which looks ugly.
  7118. MarginContainer *toolbar_margin = memnew(MarginContainer);
  7119. toolbar_margin->add_theme_constant_override("margin_left", 4 * EDSCALE);
  7120. toolbar_margin->add_theme_constant_override("margin_right", 4 * EDSCALE);
  7121. vbc->add_child(toolbar_margin);
  7122. // A fluid container for all toolbars.
  7123. HFlowContainer *main_flow = memnew(HFlowContainer);
  7124. toolbar_margin->add_child(main_flow);
  7125. // Main toolbars.
  7126. HBoxContainer *main_menu_hbox = memnew(HBoxContainer);
  7127. main_flow->add_child(main_menu_hbox);
  7128. String sct;
  7129. tool_button[TOOL_MODE_SELECT] = memnew(Button);
  7130. main_menu_hbox->add_child(tool_button[TOOL_MODE_SELECT]);
  7131. tool_button[TOOL_MODE_SELECT]->set_toggle_mode(true);
  7132. tool_button[TOOL_MODE_SELECT]->set_theme_type_variation("FlatButton");
  7133. tool_button[TOOL_MODE_SELECT]->set_pressed(true);
  7134. tool_button[TOOL_MODE_SELECT]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_SELECT));
  7135. tool_button[TOOL_MODE_SELECT]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_select", TTR("Select Mode"), Key::Q));
  7136. tool_button[TOOL_MODE_SELECT]->set_shortcut_context(this);
  7137. tool_button[TOOL_MODE_SELECT]->set_tooltip_text(keycode_get_string((Key)KeyModifierMask::CMD_OR_CTRL) + TTR("Drag: Rotate selected node around pivot.") + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked."));
  7138. main_menu_hbox->add_child(memnew(VSeparator));
  7139. tool_button[TOOL_MODE_MOVE] = memnew(Button);
  7140. main_menu_hbox->add_child(tool_button[TOOL_MODE_MOVE]);
  7141. tool_button[TOOL_MODE_MOVE]->set_toggle_mode(true);
  7142. tool_button[TOOL_MODE_MOVE]->set_theme_type_variation("FlatButton");
  7143. tool_button[TOOL_MODE_MOVE]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_MOVE));
  7144. tool_button[TOOL_MODE_MOVE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_move", TTR("Move Mode"), Key::W));
  7145. tool_button[TOOL_MODE_MOVE]->set_shortcut_context(this);
  7146. tool_button[TOOL_MODE_MOVE]->set_tooltip_text(keycode_get_string((Key)KeyModifierMask::CMD_OR_CTRL) + TTR("Drag: Use snap.") + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked."));
  7147. tool_button[TOOL_MODE_ROTATE] = memnew(Button);
  7148. main_menu_hbox->add_child(tool_button[TOOL_MODE_ROTATE]);
  7149. tool_button[TOOL_MODE_ROTATE]->set_toggle_mode(true);
  7150. tool_button[TOOL_MODE_ROTATE]->set_theme_type_variation("FlatButton");
  7151. tool_button[TOOL_MODE_ROTATE]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_ROTATE));
  7152. tool_button[TOOL_MODE_ROTATE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_rotate", TTR("Rotate Mode"), Key::E));
  7153. tool_button[TOOL_MODE_ROTATE]->set_shortcut_context(this);
  7154. tool_button[TOOL_MODE_ROTATE]->set_tooltip_text(keycode_get_string((Key)KeyModifierMask::CMD_OR_CTRL) + TTR("Drag: Use snap.") + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked."));
  7155. tool_button[TOOL_MODE_SCALE] = memnew(Button);
  7156. main_menu_hbox->add_child(tool_button[TOOL_MODE_SCALE]);
  7157. tool_button[TOOL_MODE_SCALE]->set_toggle_mode(true);
  7158. tool_button[TOOL_MODE_SCALE]->set_theme_type_variation("FlatButton");
  7159. tool_button[TOOL_MODE_SCALE]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_SCALE));
  7160. tool_button[TOOL_MODE_SCALE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_scale", TTR("Scale Mode"), Key::R));
  7161. tool_button[TOOL_MODE_SCALE]->set_shortcut_context(this);
  7162. tool_button[TOOL_MODE_SCALE]->set_tooltip_text(keycode_get_string((Key)KeyModifierMask::CMD_OR_CTRL) + TTR("Drag: Use snap.") + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked."));
  7163. main_menu_hbox->add_child(memnew(VSeparator));
  7164. tool_button[TOOL_MODE_LIST_SELECT] = memnew(Button);
  7165. main_menu_hbox->add_child(tool_button[TOOL_MODE_LIST_SELECT]);
  7166. tool_button[TOOL_MODE_LIST_SELECT]->set_toggle_mode(true);
  7167. tool_button[TOOL_MODE_LIST_SELECT]->set_theme_type_variation("FlatButton");
  7168. tool_button[TOOL_MODE_LIST_SELECT]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_LIST_SELECT));
  7169. tool_button[TOOL_MODE_LIST_SELECT]->set_tooltip_text(TTR("Show list of selectable nodes at position clicked."));
  7170. tool_button[TOOL_LOCK_SELECTED] = memnew(Button);
  7171. main_menu_hbox->add_child(tool_button[TOOL_LOCK_SELECTED]);
  7172. tool_button[TOOL_LOCK_SELECTED]->set_theme_type_variation("FlatButton");
  7173. tool_button[TOOL_LOCK_SELECTED]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_LOCK_SELECTED));
  7174. tool_button[TOOL_LOCK_SELECTED]->set_tooltip_text(TTR("Lock selected node, preventing selection and movement."));
  7175. // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
  7176. tool_button[TOOL_LOCK_SELECTED]->set_shortcut(ED_GET_SHORTCUT("editor/lock_selected_nodes"));
  7177. tool_button[TOOL_UNLOCK_SELECTED] = memnew(Button);
  7178. main_menu_hbox->add_child(tool_button[TOOL_UNLOCK_SELECTED]);
  7179. tool_button[TOOL_UNLOCK_SELECTED]->set_theme_type_variation("FlatButton");
  7180. tool_button[TOOL_UNLOCK_SELECTED]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_UNLOCK_SELECTED));
  7181. tool_button[TOOL_UNLOCK_SELECTED]->set_tooltip_text(TTR("Unlock selected node, allowing selection and movement."));
  7182. // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
  7183. tool_button[TOOL_UNLOCK_SELECTED]->set_shortcut(ED_GET_SHORTCUT("editor/unlock_selected_nodes"));
  7184. tool_button[TOOL_GROUP_SELECTED] = memnew(Button);
  7185. main_menu_hbox->add_child(tool_button[TOOL_GROUP_SELECTED]);
  7186. tool_button[TOOL_GROUP_SELECTED]->set_theme_type_variation("FlatButton");
  7187. tool_button[TOOL_GROUP_SELECTED]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_GROUP_SELECTED));
  7188. tool_button[TOOL_GROUP_SELECTED]->set_tooltip_text(TTR("Groups the selected node with its children. This selects the parent when any child node is clicked in 2D and 3D view."));
  7189. // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
  7190. tool_button[TOOL_GROUP_SELECTED]->set_shortcut(ED_GET_SHORTCUT("editor/group_selected_nodes"));
  7191. tool_button[TOOL_UNGROUP_SELECTED] = memnew(Button);
  7192. main_menu_hbox->add_child(tool_button[TOOL_UNGROUP_SELECTED]);
  7193. tool_button[TOOL_UNGROUP_SELECTED]->set_theme_type_variation("FlatButton");
  7194. tool_button[TOOL_UNGROUP_SELECTED]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_UNGROUP_SELECTED));
  7195. tool_button[TOOL_UNGROUP_SELECTED]->set_tooltip_text(TTR("Ungroups the selected node from its children. Child nodes will be individual items in 2D and 3D view."));
  7196. // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
  7197. tool_button[TOOL_UNGROUP_SELECTED]->set_shortcut(ED_GET_SHORTCUT("editor/ungroup_selected_nodes"));
  7198. main_menu_hbox->add_child(memnew(VSeparator));
  7199. tool_option_button[TOOL_OPT_LOCAL_COORDS] = memnew(Button);
  7200. main_menu_hbox->add_child(tool_option_button[TOOL_OPT_LOCAL_COORDS]);
  7201. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_toggle_mode(true);
  7202. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_theme_type_variation("FlatButton");
  7203. tool_option_button[TOOL_OPT_LOCAL_COORDS]->connect("toggled", callable_mp(this, &Node3DEditor::_menu_item_toggled).bind(MENU_TOOL_LOCAL_COORDS));
  7204. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut(ED_SHORTCUT("spatial_editor/local_coords", TTR("Use Local Space"), Key::T));
  7205. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut_context(this);
  7206. tool_option_button[TOOL_OPT_USE_SNAP] = memnew(Button);
  7207. main_menu_hbox->add_child(tool_option_button[TOOL_OPT_USE_SNAP]);
  7208. tool_option_button[TOOL_OPT_USE_SNAP]->set_toggle_mode(true);
  7209. tool_option_button[TOOL_OPT_USE_SNAP]->set_theme_type_variation("FlatButton");
  7210. tool_option_button[TOOL_OPT_USE_SNAP]->connect("toggled", callable_mp(this, &Node3DEditor::_menu_item_toggled).bind(MENU_TOOL_USE_SNAP));
  7211. tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut(ED_SHORTCUT("spatial_editor/snap", TTR("Use Snap"), Key::Y));
  7212. tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut_context(this);
  7213. main_menu_hbox->add_child(memnew(VSeparator));
  7214. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA] = memnew(Button);
  7215. main_menu_hbox->add_child(tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]);
  7216. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_toggle_mode(true);
  7217. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_theme_type_variation("FlatButton");
  7218. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_disabled(true);
  7219. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->connect("toggled", callable_mp(this, &Node3DEditor::_menu_item_toggled).bind(MENU_TOOL_OVERRIDE_CAMERA));
  7220. _update_camera_override_button(false);
  7221. main_menu_hbox->add_child(memnew(VSeparator));
  7222. sun_button = memnew(Button);
  7223. sun_button->set_tooltip_text(TTR("Toggle preview sunlight.\nIf a DirectionalLight3D node is added to the scene, preview sunlight is disabled."));
  7224. sun_button->set_toggle_mode(true);
  7225. sun_button->set_theme_type_variation("FlatButton");
  7226. sun_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_update_preview_environment), CONNECT_DEFERRED);
  7227. // Preview is enabled by default - ensure this applies on editor startup when there is no state yet.
  7228. sun_button->set_pressed(true);
  7229. main_menu_hbox->add_child(sun_button);
  7230. environ_button = memnew(Button);
  7231. environ_button->set_tooltip_text(TTR("Toggle preview environment.\nIf a WorldEnvironment node is added to the scene, preview environment is disabled."));
  7232. environ_button->set_toggle_mode(true);
  7233. environ_button->set_theme_type_variation("FlatButton");
  7234. environ_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_update_preview_environment), CONNECT_DEFERRED);
  7235. // Preview is enabled by default - ensure this applies on editor startup when there is no state yet.
  7236. environ_button->set_pressed(true);
  7237. main_menu_hbox->add_child(environ_button);
  7238. sun_environ_settings = memnew(Button);
  7239. sun_environ_settings->set_tooltip_text(TTR("Edit Sun and Environment settings."));
  7240. sun_environ_settings->set_theme_type_variation("FlatButton");
  7241. sun_environ_settings->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_sun_environ_settings_pressed));
  7242. main_menu_hbox->add_child(sun_environ_settings);
  7243. main_menu_hbox->add_child(memnew(VSeparator));
  7244. // Drag and drop support;
  7245. preview_node = memnew(Node3D);
  7246. preview_bounds = AABB();
  7247. ED_SHORTCUT("spatial_editor/bottom_view", TTR("Bottom View"), KeyModifierMask::ALT + Key::KP_7);
  7248. ED_SHORTCUT("spatial_editor/top_view", TTR("Top View"), Key::KP_7);
  7249. ED_SHORTCUT("spatial_editor/rear_view", TTR("Rear View"), KeyModifierMask::ALT + Key::KP_1);
  7250. ED_SHORTCUT("spatial_editor/front_view", TTR("Front View"), Key::KP_1);
  7251. ED_SHORTCUT("spatial_editor/left_view", TTR("Left View"), KeyModifierMask::ALT + Key::KP_3);
  7252. ED_SHORTCUT("spatial_editor/right_view", TTR("Right View"), Key::KP_3);
  7253. ED_SHORTCUT("spatial_editor/orbit_view_down", TTR("Orbit View Down"), Key::KP_2);
  7254. ED_SHORTCUT("spatial_editor/orbit_view_left", TTR("Orbit View Left"), Key::KP_4);
  7255. ED_SHORTCUT("spatial_editor/orbit_view_right", TTR("Orbit View Right"), Key::KP_6);
  7256. ED_SHORTCUT("spatial_editor/orbit_view_up", TTR("Orbit View Up"), Key::KP_8);
  7257. ED_SHORTCUT("spatial_editor/orbit_view_180", TTR("Orbit View 180"), Key::KP_9);
  7258. ED_SHORTCUT("spatial_editor/switch_perspective_orthogonal", TTR("Switch Perspective/Orthogonal View"), Key::KP_5);
  7259. ED_SHORTCUT("spatial_editor/insert_anim_key", TTR("Insert Animation Key"), Key::K);
  7260. ED_SHORTCUT("spatial_editor/focus_origin", TTR("Focus Origin"), Key::O);
  7261. ED_SHORTCUT("spatial_editor/focus_selection", TTR("Focus Selection"), Key::F);
  7262. ED_SHORTCUT("spatial_editor/align_transform_with_view", TTR("Align Transform with View"), KeyModifierMask::ALT + KeyModifierMask::CMD_OR_CTRL + Key::M);
  7263. ED_SHORTCUT("spatial_editor/align_rotation_with_view", TTR("Align Rotation with View"), KeyModifierMask::ALT + KeyModifierMask::CMD_OR_CTRL + Key::F);
  7264. ED_SHORTCUT("spatial_editor/freelook_toggle", TTR("Toggle Freelook"), KeyModifierMask::SHIFT + Key::F);
  7265. ED_SHORTCUT("spatial_editor/decrease_fov", TTR("Decrease Field of View"), KeyModifierMask::CMD_OR_CTRL + Key::EQUAL); // Usually direct access key for `KEY_PLUS`.
  7266. ED_SHORTCUT("spatial_editor/increase_fov", TTR("Increase Field of View"), KeyModifierMask::CMD_OR_CTRL + Key::MINUS);
  7267. ED_SHORTCUT("spatial_editor/reset_fov", TTR("Reset Field of View to Default"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_0);
  7268. PopupMenu *p;
  7269. transform_menu = memnew(MenuButton);
  7270. transform_menu->set_flat(false);
  7271. transform_menu->set_theme_type_variation("FlatMenuButton");
  7272. transform_menu->set_text(TTR("Transform"));
  7273. transform_menu->set_switch_on_hover(true);
  7274. transform_menu->set_shortcut_context(this);
  7275. main_menu_hbox->add_child(transform_menu);
  7276. p = transform_menu->get_popup();
  7277. p->add_shortcut(ED_SHORTCUT("spatial_editor/snap_to_floor", TTR("Snap Object to Floor"), Key::PAGEDOWN), MENU_SNAP_TO_FLOOR);
  7278. p->add_shortcut(ED_SHORTCUT("spatial_editor/transform_dialog", TTR("Transform Dialog...")), MENU_TRANSFORM_DIALOG);
  7279. p->add_separator();
  7280. p->add_shortcut(ED_SHORTCUT("spatial_editor/configure_snap", TTR("Configure Snap...")), MENU_TRANSFORM_CONFIGURE_SNAP);
  7281. p->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed));
  7282. view_menu = memnew(MenuButton);
  7283. view_menu->set_flat(false);
  7284. view_menu->set_theme_type_variation("FlatMenuButton");
  7285. // TRANSLATORS: Noun, name of the 2D/3D View menus.
  7286. view_menu->set_text(TTR("View"));
  7287. view_menu->set_switch_on_hover(true);
  7288. view_menu->set_shortcut_context(this);
  7289. main_menu_hbox->add_child(view_menu);
  7290. main_menu_hbox->add_child(memnew(VSeparator));
  7291. context_toolbar_panel = memnew(PanelContainer);
  7292. context_toolbar_hbox = memnew(HBoxContainer);
  7293. context_toolbar_panel->add_child(context_toolbar_hbox);
  7294. main_flow->add_child(context_toolbar_panel);
  7295. // Get the view menu popup and have it stay open when a checkable item is selected
  7296. p = view_menu->get_popup();
  7297. p->set_hide_on_checkable_item_selection(false);
  7298. accept = memnew(AcceptDialog);
  7299. EditorNode::get_singleton()->get_gui_base()->add_child(accept);
  7300. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/1_viewport", TTR("1 Viewport"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_1), MENU_VIEW_USE_1_VIEWPORT);
  7301. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports", TTR("2 Viewports"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_2), MENU_VIEW_USE_2_VIEWPORTS);
  7302. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports_alt", TTR("2 Viewports (Alt)"), KeyModifierMask::ALT + KeyModifierMask::CMD_OR_CTRL + Key::KEY_2), MENU_VIEW_USE_2_VIEWPORTS_ALT);
  7303. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports", TTR("3 Viewports"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_3), MENU_VIEW_USE_3_VIEWPORTS);
  7304. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports_alt", TTR("3 Viewports (Alt)"), KeyModifierMask::ALT + KeyModifierMask::CMD_OR_CTRL + Key::KEY_3), MENU_VIEW_USE_3_VIEWPORTS_ALT);
  7305. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/4_viewports", TTR("4 Viewports"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_4), MENU_VIEW_USE_4_VIEWPORTS);
  7306. p->add_separator();
  7307. gizmos_menu = memnew(PopupMenu);
  7308. gizmos_menu->set_hide_on_checkable_item_selection(false);
  7309. p->add_submenu_node_item(TTR("Gizmos"), gizmos_menu);
  7310. gizmos_menu->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditor::_menu_gizmo_toggled));
  7311. p->add_separator();
  7312. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_origin", TTR("View Origin")), MENU_VIEW_ORIGIN);
  7313. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_grid", TTR("View Grid"), Key::NUMBERSIGN), MENU_VIEW_GRID);
  7314. p->add_separator();
  7315. p->add_shortcut(ED_SHORTCUT("spatial_editor/settings", TTR("Settings...")), MENU_VIEW_CAMERA_SETTINGS);
  7316. p->set_item_checked(p->get_item_index(MENU_VIEW_ORIGIN), true);
  7317. p->set_item_checked(p->get_item_index(MENU_VIEW_GRID), true);
  7318. p->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed));
  7319. /* REST OF MENU */
  7320. left_panel_split = memnew(HSplitContainer);
  7321. left_panel_split->set_v_size_flags(SIZE_EXPAND_FILL);
  7322. vbc->add_child(left_panel_split);
  7323. right_panel_split = memnew(HSplitContainer);
  7324. right_panel_split->set_v_size_flags(SIZE_EXPAND_FILL);
  7325. left_panel_split->add_child(right_panel_split);
  7326. shader_split = memnew(VSplitContainer);
  7327. shader_split->set_h_size_flags(SIZE_EXPAND_FILL);
  7328. right_panel_split->add_child(shader_split);
  7329. viewport_base = memnew(Node3DEditorViewportContainer);
  7330. shader_split->add_child(viewport_base);
  7331. viewport_base->set_v_size_flags(SIZE_EXPAND_FILL);
  7332. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  7333. viewports[i] = memnew(Node3DEditorViewport(this, i));
  7334. viewports[i]->connect("toggle_maximize_view", callable_mp(this, &Node3DEditor::_toggle_maximize_view));
  7335. viewports[i]->connect("clicked", callable_mp(this, &Node3DEditor::_update_camera_override_viewport));
  7336. viewports[i]->assign_pending_data_pointers(preview_node, &preview_bounds, accept);
  7337. viewport_base->add_child(viewports[i]);
  7338. }
  7339. /* SNAP DIALOG */
  7340. snap_dialog = memnew(ConfirmationDialog);
  7341. snap_dialog->set_title(TTR("Snap Settings"));
  7342. add_child(snap_dialog);
  7343. snap_dialog->connect("confirmed", callable_mp(this, &Node3DEditor::_snap_changed));
  7344. snap_dialog->get_cancel_button()->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_snap_update));
  7345. VBoxContainer *snap_dialog_vbc = memnew(VBoxContainer);
  7346. snap_dialog->add_child(snap_dialog_vbc);
  7347. snap_translate = memnew(LineEdit);
  7348. snap_translate->set_select_all_on_focus(true);
  7349. snap_dialog_vbc->add_margin_child(TTR("Translate Snap:"), snap_translate);
  7350. snap_rotate = memnew(LineEdit);
  7351. snap_rotate->set_select_all_on_focus(true);
  7352. snap_dialog_vbc->add_margin_child(TTR("Rotate Snap (deg.):"), snap_rotate);
  7353. snap_scale = memnew(LineEdit);
  7354. snap_scale->set_select_all_on_focus(true);
  7355. snap_dialog_vbc->add_margin_child(TTR("Scale Snap (%):"), snap_scale);
  7356. /* SETTINGS DIALOG */
  7357. settings_dialog = memnew(ConfirmationDialog);
  7358. settings_dialog->set_title(TTR("Viewport Settings"));
  7359. add_child(settings_dialog);
  7360. settings_vbc = memnew(VBoxContainer);
  7361. settings_vbc->set_custom_minimum_size(Size2(200, 0) * EDSCALE);
  7362. settings_dialog->add_child(settings_vbc);
  7363. settings_fov = memnew(SpinBox);
  7364. settings_fov->set_max(MAX_FOV);
  7365. settings_fov->set_min(MIN_FOV);
  7366. settings_fov->set_step(0.1);
  7367. settings_fov->set_value(EDITOR_GET("editors/3d/default_fov"));
  7368. settings_fov->set_select_all_on_focus(true);
  7369. settings_fov->set_tooltip_text(TTR("FOV is defined as a vertical value, as the editor camera always uses the Keep Height aspect mode."));
  7370. settings_vbc->add_margin_child(TTR("Perspective VFOV (deg.):"), settings_fov);
  7371. settings_znear = memnew(SpinBox);
  7372. settings_znear->set_max(MAX_Z);
  7373. settings_znear->set_min(MIN_Z);
  7374. settings_znear->set_step(0.01);
  7375. settings_znear->set_value(EDITOR_GET("editors/3d/default_z_near"));
  7376. settings_znear->set_select_all_on_focus(true);
  7377. settings_vbc->add_margin_child(TTR("View Z-Near:"), settings_znear);
  7378. settings_zfar = memnew(SpinBox);
  7379. settings_zfar->set_max(MAX_Z);
  7380. settings_zfar->set_min(MIN_Z);
  7381. settings_zfar->set_step(0.1);
  7382. settings_zfar->set_value(EDITOR_GET("editors/3d/default_z_far"));
  7383. settings_zfar->set_select_all_on_focus(true);
  7384. settings_vbc->add_margin_child(TTR("View Z-Far:"), settings_zfar);
  7385. for (uint32_t i = 0; i < VIEWPORTS_COUNT; ++i) {
  7386. settings_dialog->connect("confirmed", callable_mp(viewports[i], &Node3DEditorViewport::_view_settings_confirmed).bind(0.0));
  7387. }
  7388. /* XFORM DIALOG */
  7389. xform_dialog = memnew(ConfirmationDialog);
  7390. xform_dialog->set_title(TTR("Transform Change"));
  7391. add_child(xform_dialog);
  7392. VBoxContainer *xform_vbc = memnew(VBoxContainer);
  7393. xform_dialog->add_child(xform_vbc);
  7394. Label *l = memnew(Label);
  7395. l->set_text(TTR("Translate:"));
  7396. xform_vbc->add_child(l);
  7397. HBoxContainer *xform_hbc = memnew(HBoxContainer);
  7398. xform_vbc->add_child(xform_hbc);
  7399. for (int i = 0; i < 3; i++) {
  7400. xform_translate[i] = memnew(LineEdit);
  7401. xform_translate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  7402. xform_translate[i]->set_select_all_on_focus(true);
  7403. xform_hbc->add_child(xform_translate[i]);
  7404. }
  7405. l = memnew(Label);
  7406. l->set_text(TTR("Rotate (deg.):"));
  7407. xform_vbc->add_child(l);
  7408. xform_hbc = memnew(HBoxContainer);
  7409. xform_vbc->add_child(xform_hbc);
  7410. for (int i = 0; i < 3; i++) {
  7411. xform_rotate[i] = memnew(LineEdit);
  7412. xform_rotate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  7413. xform_rotate[i]->set_select_all_on_focus(true);
  7414. xform_hbc->add_child(xform_rotate[i]);
  7415. }
  7416. l = memnew(Label);
  7417. l->set_text(TTR("Scale (ratio):"));
  7418. xform_vbc->add_child(l);
  7419. xform_hbc = memnew(HBoxContainer);
  7420. xform_vbc->add_child(xform_hbc);
  7421. for (int i = 0; i < 3; i++) {
  7422. xform_scale[i] = memnew(LineEdit);
  7423. xform_scale[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  7424. xform_scale[i]->set_select_all_on_focus(true);
  7425. xform_hbc->add_child(xform_scale[i]);
  7426. }
  7427. l = memnew(Label);
  7428. l->set_text(TTR("Transform Type"));
  7429. xform_vbc->add_child(l);
  7430. xform_type = memnew(OptionButton);
  7431. xform_type->set_h_size_flags(SIZE_EXPAND_FILL);
  7432. xform_type->add_item(TTR("Pre"));
  7433. xform_type->add_item(TTR("Post"));
  7434. xform_vbc->add_child(xform_type);
  7435. xform_dialog->connect("confirmed", callable_mp(this, &Node3DEditor::_xform_dialog_action));
  7436. selected = nullptr;
  7437. set_process_shortcut_input(true);
  7438. add_to_group(SceneStringName(_spatial_editor_group));
  7439. EDITOR_DEF("editors/3d/manipulator_gizmo_size", 80);
  7440. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "editors/3d/manipulator_gizmo_size", PROPERTY_HINT_RANGE, "16,160,1"));
  7441. EDITOR_DEF("editors/3d/manipulator_gizmo_opacity", 0.9);
  7442. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::FLOAT, "editors/3d/manipulator_gizmo_opacity", PROPERTY_HINT_RANGE, "0,1,0.01"));
  7443. EDITOR_DEF("editors/3d/navigation/show_viewport_rotation_gizmo", true);
  7444. EDITOR_DEF("editors/3d/navigation/show_viewport_navigation_gizmo", DisplayServer::get_singleton()->is_touchscreen_available());
  7445. current_hover_gizmo_handle = -1;
  7446. current_hover_gizmo_handle_secondary = false;
  7447. {
  7448. //sun popup
  7449. sun_environ_popup = memnew(PopupPanel);
  7450. add_child(sun_environ_popup);
  7451. HBoxContainer *sun_environ_hb = memnew(HBoxContainer);
  7452. sun_environ_popup->add_child(sun_environ_hb);
  7453. sun_vb = memnew(VBoxContainer);
  7454. sun_environ_hb->add_child(sun_vb);
  7455. sun_vb->set_custom_minimum_size(Size2(200 * EDSCALE, 0));
  7456. sun_vb->hide();
  7457. sun_title = memnew(Label);
  7458. sun_title->set_theme_type_variation("HeaderSmall");
  7459. sun_vb->add_child(sun_title);
  7460. sun_title->set_text(TTR("Preview Sun"));
  7461. sun_title->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  7462. CenterContainer *sun_direction_center = memnew(CenterContainer);
  7463. sun_direction = memnew(Control);
  7464. sun_direction->set_custom_minimum_size(Size2(128, 128) * EDSCALE);
  7465. sun_direction_center->add_child(sun_direction);
  7466. sun_vb->add_margin_child(TTR("Sun Direction"), sun_direction_center);
  7467. sun_direction->connect(SceneStringName(gui_input), callable_mp(this, &Node3DEditor::_sun_direction_input));
  7468. sun_direction->connect(SceneStringName(draw), callable_mp(this, &Node3DEditor::_sun_direction_draw));
  7469. sun_direction->set_default_cursor_shape(CURSOR_MOVE);
  7470. sun_direction_shader.instantiate();
  7471. sun_direction_shader->set_code(R"(
  7472. // 3D editor Preview Sun direction shader.
  7473. shader_type canvas_item;
  7474. uniform vec3 sun_direction;
  7475. uniform vec3 sun_color;
  7476. void fragment() {
  7477. vec3 n;
  7478. n.xy = UV * 2.0 - 1.0;
  7479. n.z = sqrt(max(0.0, 1.0 - dot(n.xy, n.xy)));
  7480. COLOR.rgb = dot(n, sun_direction) * sun_color;
  7481. COLOR.a = 1.0 - smoothstep(0.99, 1.0, length(n.xy));
  7482. }
  7483. )");
  7484. sun_direction_material.instantiate();
  7485. sun_direction_material->set_shader(sun_direction_shader);
  7486. sun_direction_material->set_shader_parameter("sun_direction", Vector3(0, 0, 1));
  7487. sun_direction_material->set_shader_parameter("sun_color", Vector3(1, 1, 1));
  7488. sun_direction->set_material(sun_direction_material);
  7489. HBoxContainer *sun_angle_hbox = memnew(HBoxContainer);
  7490. VBoxContainer *sun_angle_altitude_vbox = memnew(VBoxContainer);
  7491. Label *sun_angle_altitude_label = memnew(Label);
  7492. sun_angle_altitude_label->set_text(TTR("Angular Altitude"));
  7493. sun_angle_altitude_vbox->add_child(sun_angle_altitude_label);
  7494. sun_angle_altitude = memnew(EditorSpinSlider);
  7495. sun_angle_altitude->set_max(90);
  7496. sun_angle_altitude->set_min(-90);
  7497. sun_angle_altitude->set_step(0.1);
  7498. sun_angle_altitude->connect("value_changed", callable_mp(this, &Node3DEditor::_sun_direction_angle_set).unbind(1));
  7499. sun_angle_altitude_vbox->add_child(sun_angle_altitude);
  7500. sun_angle_hbox->add_child(sun_angle_altitude_vbox);
  7501. VBoxContainer *sun_angle_azimuth_vbox = memnew(VBoxContainer);
  7502. sun_angle_azimuth_vbox->set_custom_minimum_size(Vector2(100, 0));
  7503. Label *sun_angle_azimuth_label = memnew(Label);
  7504. sun_angle_azimuth_label->set_text(TTR("Azimuth"));
  7505. sun_angle_azimuth_vbox->add_child(sun_angle_azimuth_label);
  7506. sun_angle_azimuth = memnew(EditorSpinSlider);
  7507. sun_angle_azimuth->set_max(180);
  7508. sun_angle_azimuth->set_min(-180);
  7509. sun_angle_azimuth->set_step(0.1);
  7510. sun_angle_azimuth->set_allow_greater(true);
  7511. sun_angle_azimuth->set_allow_lesser(true);
  7512. sun_angle_azimuth->connect("value_changed", callable_mp(this, &Node3DEditor::_sun_direction_angle_set).unbind(1));
  7513. sun_angle_azimuth_vbox->add_child(sun_angle_azimuth);
  7514. sun_angle_hbox->add_child(sun_angle_azimuth_vbox);
  7515. sun_angle_hbox->add_theme_constant_override("separation", 10);
  7516. sun_vb->add_child(sun_angle_hbox);
  7517. sun_color = memnew(ColorPickerButton);
  7518. sun_color->set_edit_alpha(false);
  7519. sun_vb->add_margin_child(TTR("Sun Color"), sun_color);
  7520. sun_color->connect("color_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7521. sun_color->get_popup()->connect("about_to_popup", callable_mp(EditorNode::get_singleton(), &EditorNode::setup_color_picker).bind(sun_color->get_picker()));
  7522. sun_energy = memnew(EditorSpinSlider);
  7523. sun_energy->set_max(64.0);
  7524. sun_energy->set_min(0);
  7525. sun_energy->set_step(0.05);
  7526. sun_vb->add_margin_child(TTR("Sun Energy"), sun_energy);
  7527. sun_energy->connect("value_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7528. sun_max_distance = memnew(EditorSpinSlider);
  7529. sun_vb->add_margin_child(TTR("Shadow Max Distance"), sun_max_distance);
  7530. sun_max_distance->connect("value_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7531. sun_max_distance->set_min(1);
  7532. sun_max_distance->set_max(4096);
  7533. sun_add_to_scene = memnew(Button);
  7534. sun_add_to_scene->set_text(TTR("Add Sun to Scene"));
  7535. sun_add_to_scene->set_tooltip_text(TTR("Adds a DirectionalLight3D node matching the preview sun settings to the current scene.\nHold Shift while clicking to also add the preview environment to the current scene."));
  7536. sun_add_to_scene->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_add_sun_to_scene).bind(false));
  7537. sun_vb->add_spacer();
  7538. sun_vb->add_child(sun_add_to_scene);
  7539. sun_state = memnew(Label);
  7540. sun_environ_hb->add_child(sun_state);
  7541. sun_state->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  7542. sun_state->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
  7543. sun_state->set_h_size_flags(SIZE_EXPAND_FILL);
  7544. VSeparator *sc = memnew(VSeparator);
  7545. sc->set_custom_minimum_size(Size2(50 * EDSCALE, 0));
  7546. sc->set_v_size_flags(SIZE_EXPAND_FILL);
  7547. sun_environ_hb->add_child(sc);
  7548. environ_vb = memnew(VBoxContainer);
  7549. sun_environ_hb->add_child(environ_vb);
  7550. environ_vb->set_custom_minimum_size(Size2(200 * EDSCALE, 0));
  7551. environ_vb->hide();
  7552. environ_title = memnew(Label);
  7553. environ_title->set_theme_type_variation("HeaderSmall");
  7554. environ_vb->add_child(environ_title);
  7555. environ_title->set_text(TTR("Preview Environment"));
  7556. environ_title->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  7557. environ_sky_color = memnew(ColorPickerButton);
  7558. environ_sky_color->set_edit_alpha(false);
  7559. environ_sky_color->connect("color_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7560. environ_sky_color->get_popup()->connect("about_to_popup", callable_mp(EditorNode::get_singleton(), &EditorNode::setup_color_picker).bind(environ_sky_color->get_picker()));
  7561. environ_vb->add_margin_child(TTR("Sky Color"), environ_sky_color);
  7562. environ_ground_color = memnew(ColorPickerButton);
  7563. environ_ground_color->connect("color_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7564. environ_ground_color->set_edit_alpha(false);
  7565. environ_ground_color->get_popup()->connect("about_to_popup", callable_mp(EditorNode::get_singleton(), &EditorNode::setup_color_picker).bind(environ_ground_color->get_picker()));
  7566. environ_vb->add_margin_child(TTR("Ground Color"), environ_ground_color);
  7567. environ_energy = memnew(EditorSpinSlider);
  7568. environ_energy->set_max(8.0);
  7569. environ_energy->set_min(0);
  7570. environ_energy->set_step(0.05);
  7571. environ_energy->connect("value_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7572. environ_vb->add_margin_child(TTR("Sky Energy"), environ_energy);
  7573. HBoxContainer *fx_vb = memnew(HBoxContainer);
  7574. fx_vb->set_h_size_flags(SIZE_EXPAND_FILL);
  7575. environ_ao_button = memnew(Button);
  7576. environ_ao_button->set_text(TTR("AO"));
  7577. environ_ao_button->set_toggle_mode(true);
  7578. environ_ao_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_preview_settings_changed), CONNECT_DEFERRED);
  7579. fx_vb->add_child(environ_ao_button);
  7580. environ_glow_button = memnew(Button);
  7581. environ_glow_button->set_text(TTR("Glow"));
  7582. environ_glow_button->set_toggle_mode(true);
  7583. environ_glow_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_preview_settings_changed), CONNECT_DEFERRED);
  7584. fx_vb->add_child(environ_glow_button);
  7585. environ_tonemap_button = memnew(Button);
  7586. environ_tonemap_button->set_text(TTR("Tonemap"));
  7587. environ_tonemap_button->set_toggle_mode(true);
  7588. environ_tonemap_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_preview_settings_changed), CONNECT_DEFERRED);
  7589. fx_vb->add_child(environ_tonemap_button);
  7590. environ_gi_button = memnew(Button);
  7591. environ_gi_button->set_text(TTR("GI"));
  7592. environ_gi_button->set_toggle_mode(true);
  7593. environ_gi_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_preview_settings_changed), CONNECT_DEFERRED);
  7594. fx_vb->add_child(environ_gi_button);
  7595. environ_vb->add_margin_child(TTR("Post Process"), fx_vb);
  7596. environ_add_to_scene = memnew(Button);
  7597. environ_add_to_scene->set_text(TTR("Add Environment to Scene"));
  7598. environ_add_to_scene->set_tooltip_text(TTR("Adds a WorldEnvironment node matching the preview environment settings to the current scene.\nHold Shift while clicking to also add the preview sun to the current scene."));
  7599. environ_add_to_scene->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_add_environment_to_scene).bind(false));
  7600. environ_vb->add_spacer();
  7601. environ_vb->add_child(environ_add_to_scene);
  7602. environ_state = memnew(Label);
  7603. sun_environ_hb->add_child(environ_state);
  7604. environ_state->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  7605. environ_state->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
  7606. environ_state->set_h_size_flags(SIZE_EXPAND_FILL);
  7607. preview_sun = memnew(DirectionalLight3D);
  7608. preview_sun->set_shadow(true);
  7609. preview_sun->set_shadow_mode(DirectionalLight3D::SHADOW_PARALLEL_4_SPLITS);
  7610. preview_environment = memnew(WorldEnvironment);
  7611. environment.instantiate();
  7612. preview_environment->set_environment(environment);
  7613. if (GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units")) {
  7614. camera_attributes.instantiate();
  7615. preview_environment->set_camera_attributes(camera_attributes);
  7616. }
  7617. Ref<Sky> sky;
  7618. sky.instantiate();
  7619. sky_material.instantiate();
  7620. sky->set_material(sky_material);
  7621. environment->set_sky(sky);
  7622. environment->set_background(Environment::BG_SKY);
  7623. _load_default_preview_settings();
  7624. _preview_settings_changed();
  7625. }
  7626. clear(); // Make sure values are initialized. Will call _snap_update() for us.
  7627. }
  7628. Node3DEditor::~Node3DEditor() {
  7629. memdelete(preview_node);
  7630. if (preview_sun_dangling && preview_sun) {
  7631. memdelete(preview_sun);
  7632. }
  7633. if (preview_env_dangling && preview_environment) {
  7634. memdelete(preview_environment);
  7635. }
  7636. }
  7637. void Node3DEditorPlugin::make_visible(bool p_visible) {
  7638. if (p_visible) {
  7639. spatial_editor->show();
  7640. spatial_editor->set_process(true);
  7641. spatial_editor->set_physics_process(true);
  7642. } else {
  7643. spatial_editor->hide();
  7644. spatial_editor->set_process(false);
  7645. spatial_editor->set_physics_process(false);
  7646. }
  7647. }
  7648. void Node3DEditorPlugin::edit(Object *p_object) {
  7649. spatial_editor->edit(Object::cast_to<Node3D>(p_object));
  7650. }
  7651. bool Node3DEditorPlugin::handles(Object *p_object) const {
  7652. return p_object->is_class("Node3D");
  7653. }
  7654. Dictionary Node3DEditorPlugin::get_state() const {
  7655. return spatial_editor->get_state();
  7656. }
  7657. void Node3DEditorPlugin::set_state(const Dictionary &p_state) {
  7658. spatial_editor->set_state(p_state);
  7659. }
  7660. Vector3 Node3DEditor::snap_point(Vector3 p_target, Vector3 p_start) const {
  7661. if (is_snap_enabled()) {
  7662. real_t snap = get_translate_snap();
  7663. p_target.snapf(snap);
  7664. }
  7665. return p_target;
  7666. }
  7667. bool Node3DEditor::is_gizmo_visible() const {
  7668. if (selected) {
  7669. return gizmo.visible && selected->is_transform_gizmo_visible();
  7670. }
  7671. return gizmo.visible;
  7672. }
  7673. real_t Node3DEditor::get_translate_snap() const {
  7674. real_t snap_value = snap_translate_value;
  7675. if (Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  7676. snap_value /= 10.0f;
  7677. }
  7678. return snap_value;
  7679. }
  7680. real_t Node3DEditor::get_rotate_snap() const {
  7681. real_t snap_value = snap_rotate_value;
  7682. if (Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  7683. snap_value /= 3.0f;
  7684. }
  7685. return snap_value;
  7686. }
  7687. real_t Node3DEditor::get_scale_snap() const {
  7688. real_t snap_value = snap_scale_value;
  7689. if (Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  7690. snap_value /= 2.0f;
  7691. }
  7692. return snap_value;
  7693. }
  7694. struct _GizmoPluginPriorityComparator {
  7695. bool operator()(const Ref<EditorNode3DGizmoPlugin> &p_a, const Ref<EditorNode3DGizmoPlugin> &p_b) const {
  7696. if (p_a->get_priority() == p_b->get_priority()) {
  7697. return p_a->get_gizmo_name() < p_b->get_gizmo_name();
  7698. }
  7699. return p_a->get_priority() > p_b->get_priority();
  7700. }
  7701. };
  7702. struct _GizmoPluginNameComparator {
  7703. bool operator()(const Ref<EditorNode3DGizmoPlugin> &p_a, const Ref<EditorNode3DGizmoPlugin> &p_b) const {
  7704. return p_a->get_gizmo_name() < p_b->get_gizmo_name();
  7705. }
  7706. };
  7707. void Node3DEditor::add_gizmo_plugin(Ref<EditorNode3DGizmoPlugin> p_plugin) {
  7708. ERR_FAIL_NULL(p_plugin.ptr());
  7709. gizmo_plugins_by_priority.push_back(p_plugin);
  7710. gizmo_plugins_by_priority.sort_custom<_GizmoPluginPriorityComparator>();
  7711. gizmo_plugins_by_name.push_back(p_plugin);
  7712. gizmo_plugins_by_name.sort_custom<_GizmoPluginNameComparator>();
  7713. _update_gizmos_menu();
  7714. }
  7715. void Node3DEditor::remove_gizmo_plugin(Ref<EditorNode3DGizmoPlugin> p_plugin) {
  7716. gizmo_plugins_by_priority.erase(p_plugin);
  7717. gizmo_plugins_by_name.erase(p_plugin);
  7718. _update_gizmos_menu();
  7719. }
  7720. Node3DEditorPlugin::Node3DEditorPlugin() {
  7721. spatial_editor = memnew(Node3DEditor);
  7722. spatial_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  7723. EditorNode::get_singleton()->get_main_screen_control()->add_child(spatial_editor);
  7724. spatial_editor->hide();
  7725. }
  7726. Node3DEditorPlugin::~Node3DEditorPlugin() {
  7727. }