spatial_editor_plugin.cpp 229 KB

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