spatial_editor_plugin.cpp 264 KB

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