spatial_editor_plugin.cpp 245 KB

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