node_3d_editor_plugin.cpp 275 KB

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