spatial_editor_plugin.cpp 228 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727
  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. if (cursor.x_rot > Math_PI / 2.0)
  1620. cursor.x_rot = Math_PI / 2.0;
  1621. if (cursor.x_rot < -Math_PI / 2.0)
  1622. cursor.x_rot = -Math_PI / 2.0;
  1623. name = "";
  1624. _update_name();
  1625. }
  1626. void SpatialEditorViewport::_nav_look(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  1627. if (orthogonal) {
  1628. _nav_pan(p_event, p_relative);
  1629. return;
  1630. }
  1631. if (orthogonal && auto_orthogonal) {
  1632. _menu_option(VIEW_PERSPECTIVE);
  1633. }
  1634. real_t degrees_per_pixel = EditorSettings::get_singleton()->get("editors/3d/navigation_feel/orbit_sensitivity");
  1635. real_t radians_per_pixel = Math::deg2rad(degrees_per_pixel);
  1636. bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y_axis");
  1637. // Note: do NOT assume the camera has the "current" transform, because it is interpolated and may have "lag".
  1638. Transform prev_camera_transform = to_camera_transform(cursor);
  1639. if (invert_y_axis) {
  1640. cursor.x_rot -= p_relative.y * radians_per_pixel;
  1641. } else {
  1642. cursor.x_rot += p_relative.y * radians_per_pixel;
  1643. }
  1644. cursor.y_rot += p_relative.x * radians_per_pixel;
  1645. if (cursor.x_rot > Math_PI / 2.0)
  1646. cursor.x_rot = Math_PI / 2.0;
  1647. if (cursor.x_rot < -Math_PI / 2.0)
  1648. cursor.x_rot = -Math_PI / 2.0;
  1649. // Look is like the opposite of Orbit: the focus point rotates around the camera
  1650. Transform camera_transform = to_camera_transform(cursor);
  1651. Vector3 pos = camera_transform.xform(Vector3(0, 0, 0));
  1652. Vector3 prev_pos = prev_camera_transform.xform(Vector3(0, 0, 0));
  1653. Vector3 diff = prev_pos - pos;
  1654. cursor.pos += diff;
  1655. name = "";
  1656. _update_name();
  1657. }
  1658. void SpatialEditorViewport::set_freelook_active(bool active_now) {
  1659. if (!freelook_active && active_now) {
  1660. // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
  1661. cursor = camera_cursor;
  1662. // Make sure eye_pos is synced, because freelook referential is eye pos rather than orbit pos
  1663. Vector3 forward = to_camera_transform(cursor).basis.xform(Vector3(0, 0, -1));
  1664. cursor.eye_pos = cursor.pos - cursor.distance * forward;
  1665. // Also sync the camera cursor, otherwise switching to freelook will be trippy if inertia is active
  1666. camera_cursor.eye_pos = cursor.eye_pos;
  1667. if (EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_speed_zoom_link")) {
  1668. // Re-adjust freelook speed from the current zoom level
  1669. real_t base_speed = EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_base_speed");
  1670. freelook_speed = base_speed * cursor.distance;
  1671. }
  1672. // Hide mouse like in an FPS (warping doesn't work)
  1673. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
  1674. } else if (freelook_active && !active_now) {
  1675. // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
  1676. cursor = camera_cursor;
  1677. // Restore mouse
  1678. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  1679. }
  1680. freelook_active = active_now;
  1681. }
  1682. void SpatialEditorViewport::scale_cursor_distance(real_t scale) {
  1683. // Prevents zero distance which would short-circuit any scaling
  1684. if (cursor.distance < ZOOM_MIN_DISTANCE)
  1685. cursor.distance = ZOOM_MIN_DISTANCE;
  1686. cursor.distance *= scale;
  1687. if (cursor.distance < ZOOM_MIN_DISTANCE)
  1688. cursor.distance = ZOOM_MIN_DISTANCE;
  1689. zoom_indicator_delay = ZOOM_INDICATOR_DELAY_S;
  1690. surface->update();
  1691. }
  1692. void SpatialEditorViewport::scale_freelook_speed(real_t scale) {
  1693. // Prevents zero distance which would short-circuit any scaling
  1694. if (freelook_speed < FREELOOK_MIN_SPEED)
  1695. freelook_speed = FREELOOK_MIN_SPEED;
  1696. freelook_speed *= scale;
  1697. if (freelook_speed < FREELOOK_MIN_SPEED)
  1698. freelook_speed = FREELOOK_MIN_SPEED;
  1699. zoom_indicator_delay = ZOOM_INDICATOR_DELAY_S;
  1700. surface->update();
  1701. }
  1702. Point2i SpatialEditorViewport::_get_warped_mouse_motion(const Ref<InputEventMouseMotion> &p_ev_mouse_motion) const {
  1703. Point2i relative;
  1704. if (bool(EDITOR_DEF("editors/3d/navigation/warped_mouse_panning", false))) {
  1705. relative = Input::get_singleton()->warp_mouse_motion(p_ev_mouse_motion, surface->get_global_rect());
  1706. } else {
  1707. relative = p_ev_mouse_motion->get_relative();
  1708. }
  1709. return relative;
  1710. }
  1711. static bool is_shortcut_pressed(const String &p_path) {
  1712. Ref<ShortCut> shortcut = ED_GET_SHORTCUT(p_path);
  1713. if (shortcut.is_null()) {
  1714. return false;
  1715. }
  1716. InputEventKey *k = Object::cast_to<InputEventKey>(shortcut->get_shortcut().ptr());
  1717. if (k == NULL) {
  1718. return false;
  1719. }
  1720. const Input &input = *Input::get_singleton();
  1721. int scancode = k->get_scancode();
  1722. return input.is_key_pressed(scancode);
  1723. }
  1724. void SpatialEditorViewport::_update_freelook(real_t delta) {
  1725. if (!is_freelook_active()) {
  1726. return;
  1727. }
  1728. const FreelookNavigationScheme navigation_scheme = (FreelookNavigationScheme)EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_navigation_scheme").operator int();
  1729. Vector3 forward;
  1730. if (navigation_scheme == FREELOOK_FULLY_AXIS_LOCKED) {
  1731. // Forward/backward keys will always go straight forward/backward, never moving on the Y axis.
  1732. forward = Vector3(0, 0, -1).rotated(Vector3(0, 1, 0), camera->get_rotation().y);
  1733. } else {
  1734. // Forward/backward keys will be relative to the camera pitch.
  1735. forward = camera->get_transform().basis.xform(Vector3(0, 0, -1));
  1736. }
  1737. const Vector3 right = camera->get_transform().basis.xform(Vector3(1, 0, 0));
  1738. Vector3 up;
  1739. if (navigation_scheme == FREELOOK_PARTIALLY_AXIS_LOCKED || navigation_scheme == FREELOOK_FULLY_AXIS_LOCKED) {
  1740. // Up/down keys will always go up/down regardless of camera pitch.
  1741. up = Vector3(0, 1, 0);
  1742. } else {
  1743. // Up/down keys will be relative to the camera pitch.
  1744. up = camera->get_transform().basis.xform(Vector3(0, 1, 0));
  1745. }
  1746. Vector3 direction;
  1747. if (is_shortcut_pressed("spatial_editor/freelook_left")) {
  1748. direction -= right;
  1749. }
  1750. if (is_shortcut_pressed("spatial_editor/freelook_right")) {
  1751. direction += right;
  1752. }
  1753. if (is_shortcut_pressed("spatial_editor/freelook_forward")) {
  1754. direction += forward;
  1755. }
  1756. if (is_shortcut_pressed("spatial_editor/freelook_backwards")) {
  1757. direction -= forward;
  1758. }
  1759. if (is_shortcut_pressed("spatial_editor/freelook_up")) {
  1760. direction += up;
  1761. }
  1762. if (is_shortcut_pressed("spatial_editor/freelook_down")) {
  1763. direction -= up;
  1764. }
  1765. real_t speed = freelook_speed;
  1766. if (is_shortcut_pressed("spatial_editor/freelook_speed_modifier")) {
  1767. speed *= 3.0;
  1768. }
  1769. if (is_shortcut_pressed("spatial_editor/freelook_slow_modifier")) {
  1770. speed *= 0.333333;
  1771. }
  1772. const Vector3 motion = direction * speed * delta;
  1773. cursor.pos += motion;
  1774. cursor.eye_pos += motion;
  1775. }
  1776. void SpatialEditorViewport::set_message(String p_message, float p_time) {
  1777. message = p_message;
  1778. message_time = p_time;
  1779. }
  1780. void SpatialEditorPlugin::edited_scene_changed() {
  1781. for (uint32_t i = 0; i < SpatialEditor::VIEWPORTS_COUNT; i++) {
  1782. SpatialEditorViewport *viewport = SpatialEditor::get_singleton()->get_editor_viewport(i);
  1783. if (viewport->is_visible()) {
  1784. viewport->notification(Control::NOTIFICATION_VISIBILITY_CHANGED);
  1785. }
  1786. }
  1787. }
  1788. void SpatialEditorViewport::_notification(int p_what) {
  1789. if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
  1790. bool visible = is_visible_in_tree();
  1791. set_process(visible);
  1792. if (visible) {
  1793. orthogonal = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL));
  1794. _update_name();
  1795. _update_camera(0);
  1796. } else {
  1797. set_freelook_active(false);
  1798. }
  1799. call_deferred("update_transform_gizmo_view");
  1800. rotation_control->set_visible(EditorSettings::get_singleton()->get("editors/3d/navigation/show_viewport_rotation_gizmo"));
  1801. }
  1802. if (p_what == NOTIFICATION_RESIZED) {
  1803. call_deferred("update_transform_gizmo_view");
  1804. }
  1805. if (p_what == NOTIFICATION_READY) {
  1806. // The crosshair icon doesn't depend on the editor theme.
  1807. crosshair->set_texture(get_icon("Crosshair", "EditorIcons"));
  1808. // Set the anchors and margins after changing the icon to ensure it's centered correctly.
  1809. crosshair->set_anchors_and_margins_preset(PRESET_CENTER);
  1810. }
  1811. if (p_what == NOTIFICATION_PROCESS) {
  1812. real_t delta = get_process_delta_time();
  1813. if (zoom_indicator_delay > 0) {
  1814. zoom_indicator_delay -= delta;
  1815. if (zoom_indicator_delay <= 0) {
  1816. surface->update();
  1817. }
  1818. }
  1819. _update_freelook(delta);
  1820. Node *scene_root = editor->get_scene_tree_dock()->get_editor_data()->get_edited_scene_root();
  1821. if (previewing_cinema && scene_root != NULL) {
  1822. Camera *cam = scene_root->get_viewport()->get_camera();
  1823. if (cam != NULL && cam != previewing) {
  1824. //then switch the viewport's camera to the scene's viewport camera
  1825. if (previewing != NULL) {
  1826. previewing->disconnect("tree_exited", this, "_preview_exited_scene");
  1827. }
  1828. previewing = cam;
  1829. previewing->connect("tree_exited", this, "_preview_exited_scene");
  1830. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), cam->get_camera());
  1831. surface->update();
  1832. }
  1833. }
  1834. _update_camera(delta);
  1835. Map<Node *, Object *> &selection = editor_selection->get_selection();
  1836. bool changed = false;
  1837. bool exist = false;
  1838. for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
  1839. Spatial *sp = Object::cast_to<Spatial>(E->key());
  1840. if (!sp)
  1841. continue;
  1842. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1843. if (!se)
  1844. continue;
  1845. Transform t = sp->get_global_gizmo_transform();
  1846. exist = true;
  1847. if (se->last_xform == t && !se->last_xform_dirty)
  1848. continue;
  1849. changed = true;
  1850. se->last_xform_dirty = false;
  1851. se->last_xform = t;
  1852. VisualInstance *vi = Object::cast_to<VisualInstance>(sp);
  1853. se->aabb = vi ? vi->get_aabb() : _calculate_spatial_bounds(sp);
  1854. t.translate(se->aabb.position);
  1855. // apply AABB scaling before item's global transform
  1856. Basis aabb_s;
  1857. aabb_s.scale(se->aabb.size);
  1858. t.basis = t.basis * aabb_s;
  1859. VisualServer::get_singleton()->instance_set_transform(se->sbox_instance, t);
  1860. }
  1861. if (changed || (spatial_editor->is_gizmo_visible() && !exist)) {
  1862. spatial_editor->update_transform_gizmo();
  1863. }
  1864. if (message_time > 0) {
  1865. if (message != last_message) {
  1866. surface->update();
  1867. last_message = message;
  1868. }
  1869. message_time -= get_physics_process_delta_time();
  1870. if (message_time < 0)
  1871. surface->update();
  1872. }
  1873. //update shadow atlas if changed
  1874. int shadowmap_size = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/size");
  1875. int atlas_q0 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_0_subdiv");
  1876. int atlas_q1 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_1_subdiv");
  1877. int atlas_q2 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_2_subdiv");
  1878. int atlas_q3 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_3_subdiv");
  1879. viewport->set_shadow_atlas_size(shadowmap_size);
  1880. viewport->set_shadow_atlas_quadrant_subdiv(0, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q0));
  1881. viewport->set_shadow_atlas_quadrant_subdiv(1, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q1));
  1882. viewport->set_shadow_atlas_quadrant_subdiv(2, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q2));
  1883. viewport->set_shadow_atlas_quadrant_subdiv(3, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q3));
  1884. bool shrink = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION));
  1885. if (shrink != (viewport_container->get_stretch_shrink() > 1)) {
  1886. viewport_container->set_stretch_shrink(shrink ? 2 : 1);
  1887. }
  1888. //update msaa if changed
  1889. int msaa_mode = ProjectSettings::get_singleton()->get("rendering/quality/filters/msaa");
  1890. viewport->set_msaa(Viewport::MSAA(msaa_mode));
  1891. bool hdr = ProjectSettings::get_singleton()->get("rendering/quality/depth/hdr");
  1892. viewport->set_hdr(hdr);
  1893. bool show_info = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_INFORMATION));
  1894. info_label->set_visible(show_info);
  1895. Camera *current_camera;
  1896. if (previewing) {
  1897. current_camera = previewing;
  1898. } else {
  1899. current_camera = camera;
  1900. }
  1901. // Display the crosshair only while freelooking. Hide it otherwise,
  1902. // as the crosshair can be distracting.
  1903. crosshair->set_visible(freelook_active);
  1904. if (show_info) {
  1905. String text;
  1906. text += "X: " + rtos(current_camera->get_translation().x).pad_decimals(1) + "\n";
  1907. text += "Y: " + rtos(current_camera->get_translation().y).pad_decimals(1) + "\n";
  1908. text += "Z: " + rtos(current_camera->get_translation().z).pad_decimals(1) + "\n";
  1909. text += TTR("Pitch") + ": " + itos(Math::round(current_camera->get_rotation_degrees().x)) + "\n";
  1910. text += TTR("Yaw") + ": " + itos(Math::round(current_camera->get_rotation_degrees().y)) + "\n\n";
  1911. text += TTR("Objects Drawn") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_OBJECTS_IN_FRAME)) + "\n";
  1912. text += TTR("Material Changes") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_MATERIAL_CHANGES_IN_FRAME)) + "\n";
  1913. text += TTR("Shader Changes") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_SHADER_CHANGES_IN_FRAME)) + "\n";
  1914. text += TTR("Surface Changes") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_SURFACE_CHANGES_IN_FRAME)) + "\n";
  1915. text += TTR("Draw Calls") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_DRAW_CALLS_IN_FRAME)) + "\n";
  1916. text += TTR("Vertices") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_VERTICES_IN_FRAME));
  1917. info_label->set_text(text);
  1918. }
  1919. // FPS Counter.
  1920. bool show_fps = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_FPS));
  1921. fps_label->set_visible(show_fps);
  1922. if (show_fps) {
  1923. String text;
  1924. const float temp_fps = Engine::get_singleton()->get_frames_per_second();
  1925. text += TTR(vformat("FPS: %d (%s ms)", temp_fps, String::num(1000.0f / temp_fps, 2)));
  1926. fps_label->set_text(text);
  1927. }
  1928. bool show_cinema = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
  1929. cinema_label->set_visible(show_cinema);
  1930. if (show_cinema) {
  1931. float cinema_half_width = cinema_label->get_size().width / 2.0f;
  1932. cinema_label->set_anchor_and_margin(MARGIN_LEFT, 0.5f, -cinema_half_width);
  1933. }
  1934. if (lock_rotation) {
  1935. float locked_half_width = locked_label->get_size().width / 2.0f;
  1936. locked_label->set_anchor_and_margin(MARGIN_LEFT, 0.5f, -locked_half_width);
  1937. }
  1938. }
  1939. if (p_what == NOTIFICATION_ENTER_TREE) {
  1940. surface->connect("draw", this, "_draw");
  1941. surface->connect("gui_input", this, "_sinput");
  1942. surface->connect("mouse_entered", this, "_surface_mouse_enter");
  1943. surface->connect("mouse_exited", this, "_surface_mouse_exit");
  1944. surface->connect("focus_entered", this, "_surface_focus_enter");
  1945. surface->connect("focus_exited", this, "_surface_focus_exit");
  1946. _init_gizmo_instance(index);
  1947. }
  1948. if (p_what == NOTIFICATION_EXIT_TREE) {
  1949. _finish_gizmo_instances();
  1950. }
  1951. if (p_what == NOTIFICATION_THEME_CHANGED) {
  1952. view_menu->set_icon(get_icon("GuiTabMenu", "EditorIcons"));
  1953. preview_camera->set_icon(get_icon("Camera", "EditorIcons"));
  1954. view_menu->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1955. view_menu->add_style_override("hover", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1956. view_menu->add_style_override("pressed", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1957. view_menu->add_style_override("focus", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1958. view_menu->add_style_override("disabled", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1959. preview_camera->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1960. preview_camera->add_style_override("hover", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1961. preview_camera->add_style_override("pressed", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1962. preview_camera->add_style_override("focus", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1963. preview_camera->add_style_override("disabled", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1964. info_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1965. fps_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1966. cinema_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1967. locked_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  1968. }
  1969. }
  1970. static void draw_indicator_bar(Control &surface, real_t fill, Ref<Texture> icon) {
  1971. // Adjust bar size from control height
  1972. Vector2 surface_size = surface.get_size();
  1973. real_t h = surface_size.y / 2.0;
  1974. real_t y = (surface_size.y - h) / 2.0;
  1975. Rect2 r(10, y, 6, h);
  1976. real_t sy = r.size.y * fill;
  1977. // Note: because this bar appears over the viewport, it has to stay readable for any background color
  1978. // Draw both neutral dark and bright colors to account this
  1979. surface.draw_rect(r, Color(1, 1, 1, 0.2));
  1980. surface.draw_rect(Rect2(r.position.x, r.position.y + r.size.y - sy, r.size.x, sy), Color(1, 1, 1, 0.6));
  1981. surface.draw_rect(r.grow(1), Color(0, 0, 0, 0.7), false, Math::round(EDSCALE));
  1982. Vector2 icon_size = icon->get_size();
  1983. Vector2 icon_pos = Vector2(r.position.x - (icon_size.x - r.size.x) / 2, r.position.y + r.size.y + 2);
  1984. surface.draw_texture(icon, icon_pos);
  1985. }
  1986. void SpatialEditorViewport::_draw() {
  1987. EditorPluginList *over_plugin_list = EditorNode::get_singleton()->get_editor_plugins_over();
  1988. if (!over_plugin_list->empty()) {
  1989. over_plugin_list->forward_spatial_draw_over_viewport(surface);
  1990. }
  1991. EditorPluginList *force_over_plugin_list = editor->get_editor_plugins_force_over();
  1992. if (!force_over_plugin_list->empty()) {
  1993. force_over_plugin_list->forward_spatial_force_draw_over_viewport(surface);
  1994. }
  1995. if (surface->has_focus()) {
  1996. Size2 size = surface->get_size();
  1997. Rect2 r = Rect2(Point2(), size);
  1998. get_stylebox("Focus", "EditorStyles")->draw(surface->get_canvas_item(), r);
  1999. }
  2000. if (cursor.region_select) {
  2001. const Rect2 selection_rect = Rect2(cursor.region_begin, cursor.region_end - cursor.region_begin);
  2002. surface->draw_rect(
  2003. selection_rect,
  2004. get_color("box_selection_fill_color", "Editor"));
  2005. surface->draw_rect(
  2006. selection_rect,
  2007. get_color("box_selection_stroke_color", "Editor"),
  2008. false,
  2009. Math::round(EDSCALE));
  2010. }
  2011. RID ci = surface->get_canvas_item();
  2012. if (message_time > 0) {
  2013. Ref<Font> font = get_font("font", "Label");
  2014. Point2 msgpos = Point2(5, get_size().y - 20);
  2015. font->draw(ci, msgpos + Point2(1, 1), message, Color(0, 0, 0, 0.8));
  2016. font->draw(ci, msgpos + Point2(-1, -1), message, Color(0, 0, 0, 0.8));
  2017. font->draw(ci, msgpos, message, Color(1, 1, 1, 1));
  2018. }
  2019. if (_edit.mode == TRANSFORM_ROTATE) {
  2020. Point2 center = _point_to_screen(_edit.center);
  2021. VisualServer::get_singleton()->canvas_item_add_line(
  2022. ci,
  2023. _edit.mouse_pos,
  2024. center,
  2025. get_color("accent_color", "Editor") * Color(1, 1, 1, 0.6),
  2026. Math::round(2 * EDSCALE),
  2027. true);
  2028. }
  2029. if (previewing) {
  2030. Size2 ss = Size2(ProjectSettings::get_singleton()->get("display/window/size/width"), ProjectSettings::get_singleton()->get("display/window/size/height"));
  2031. float aspect = ss.aspect();
  2032. Size2 s = get_size();
  2033. Rect2 draw_rect;
  2034. switch (previewing->get_keep_aspect_mode()) {
  2035. case Camera::KEEP_WIDTH: {
  2036. draw_rect.size = Size2(s.width, s.width / aspect);
  2037. draw_rect.position.x = 0;
  2038. draw_rect.position.y = (s.height - draw_rect.size.y) * 0.5;
  2039. } break;
  2040. case Camera::KEEP_HEIGHT: {
  2041. draw_rect.size = Size2(s.height * aspect, s.height);
  2042. draw_rect.position.y = 0;
  2043. draw_rect.position.x = (s.width - draw_rect.size.x) * 0.5;
  2044. } break;
  2045. }
  2046. draw_rect = Rect2(Vector2(), s).clip(draw_rect);
  2047. surface->draw_rect(draw_rect, Color(0.6, 0.6, 0.1, 0.5), false, Math::round(2 * EDSCALE));
  2048. } else {
  2049. if (zoom_indicator_delay > 0.0) {
  2050. if (is_freelook_active()) {
  2051. // Show speed
  2052. real_t min_speed = FREELOOK_MIN_SPEED;
  2053. real_t max_speed = camera->get_zfar();
  2054. real_t scale_length = (max_speed - min_speed);
  2055. if (!Math::is_zero_approx(scale_length)) {
  2056. real_t logscale_t = 1.0 - Math::log(1 + freelook_speed - min_speed) / Math::log(1 + scale_length);
  2057. // There is no real maximum speed so that factor can become negative,
  2058. // Let's make it look asymptotic instead (will decrease slower and slower).
  2059. if (logscale_t < 0.25)
  2060. logscale_t = 0.25 * Math::exp(4.0 * logscale_t - 1.0);
  2061. draw_indicator_bar(*surface, 1.0 - logscale_t, get_icon("ViewportSpeed", "EditorIcons"));
  2062. }
  2063. } else {
  2064. // Show zoom
  2065. real_t min_distance = ZOOM_MIN_DISTANCE; // TODO Why not pick znear to limit zoom?
  2066. real_t max_distance = camera->get_zfar();
  2067. real_t scale_length = (max_distance - min_distance);
  2068. if (!Math::is_zero_approx(scale_length)) {
  2069. real_t logscale_t = 1.0 - Math::log(1 + cursor.distance - min_distance) / Math::log(1 + scale_length);
  2070. // There is no real maximum distance so that factor can become negative,
  2071. // Let's make it look asymptotic instead (will decrease slower and slower).
  2072. if (logscale_t < 0.25)
  2073. logscale_t = 0.25 * Math::exp(4.0 * logscale_t - 1.0);
  2074. draw_indicator_bar(*surface, logscale_t, get_icon("ViewportZoom", "EditorIcons"));
  2075. }
  2076. }
  2077. }
  2078. }
  2079. }
  2080. void SpatialEditorViewport::_menu_option(int p_option) {
  2081. switch (p_option) {
  2082. case VIEW_TOP: {
  2083. cursor.y_rot = 0;
  2084. cursor.x_rot = Math_PI / 2.0;
  2085. set_message(TTR("Top View."), 2);
  2086. name = TTR("Top");
  2087. _set_auto_orthogonal();
  2088. _update_name();
  2089. } break;
  2090. case VIEW_BOTTOM: {
  2091. cursor.y_rot = 0;
  2092. cursor.x_rot = -Math_PI / 2.0;
  2093. set_message(TTR("Bottom View."), 2);
  2094. name = TTR("Bottom");
  2095. _set_auto_orthogonal();
  2096. _update_name();
  2097. } break;
  2098. case VIEW_LEFT: {
  2099. cursor.x_rot = 0;
  2100. cursor.y_rot = Math_PI / 2.0;
  2101. set_message(TTR("Left View."), 2);
  2102. name = TTR("Left");
  2103. _set_auto_orthogonal();
  2104. _update_name();
  2105. } break;
  2106. case VIEW_RIGHT: {
  2107. cursor.x_rot = 0;
  2108. cursor.y_rot = -Math_PI / 2.0;
  2109. set_message(TTR("Right View."), 2);
  2110. name = TTR("Right");
  2111. _set_auto_orthogonal();
  2112. _update_name();
  2113. } break;
  2114. case VIEW_FRONT: {
  2115. cursor.x_rot = 0;
  2116. cursor.y_rot = 0;
  2117. set_message(TTR("Front View."), 2);
  2118. name = TTR("Front");
  2119. _set_auto_orthogonal();
  2120. _update_name();
  2121. } break;
  2122. case VIEW_REAR: {
  2123. cursor.x_rot = 0;
  2124. cursor.y_rot = Math_PI;
  2125. set_message(TTR("Rear View."), 2);
  2126. name = TTR("Rear");
  2127. _set_auto_orthogonal();
  2128. _update_name();
  2129. } break;
  2130. case VIEW_CENTER_TO_ORIGIN: {
  2131. cursor.pos = Vector3(0, 0, 0);
  2132. } break;
  2133. case VIEW_CENTER_TO_SELECTION: {
  2134. focus_selection();
  2135. } break;
  2136. case VIEW_ALIGN_TRANSFORM_WITH_VIEW: {
  2137. if (!get_selected_count())
  2138. break;
  2139. Transform camera_transform = camera->get_global_transform();
  2140. List<Node *> &selection = editor_selection->get_selected_node_list();
  2141. undo_redo->create_action(TTR("Align Transform with View"));
  2142. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  2143. Spatial *sp = Object::cast_to<Spatial>(E->get());
  2144. if (!sp)
  2145. continue;
  2146. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  2147. if (!se)
  2148. continue;
  2149. Transform xform;
  2150. if (orthogonal) {
  2151. xform = sp->get_global_transform();
  2152. xform.basis.set_euler(camera_transform.basis.get_euler());
  2153. } else {
  2154. xform = camera_transform;
  2155. xform.scale_basis(sp->get_scale());
  2156. }
  2157. undo_redo->add_do_method(sp, "set_global_transform", xform);
  2158. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
  2159. }
  2160. undo_redo->commit_action();
  2161. } break;
  2162. case VIEW_ALIGN_ROTATION_WITH_VIEW: {
  2163. if (!get_selected_count())
  2164. break;
  2165. Transform camera_transform = camera->get_global_transform();
  2166. List<Node *> &selection = editor_selection->get_selected_node_list();
  2167. undo_redo->create_action(TTR("Align Rotation with View"));
  2168. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  2169. Spatial *sp = Object::cast_to<Spatial>(E->get());
  2170. if (!sp)
  2171. continue;
  2172. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  2173. if (!se)
  2174. continue;
  2175. undo_redo->add_do_method(sp, "set_rotation", camera_transform.basis.get_rotation());
  2176. undo_redo->add_undo_method(sp, "set_rotation", sp->get_rotation());
  2177. }
  2178. undo_redo->commit_action();
  2179. } break;
  2180. case VIEW_ENVIRONMENT: {
  2181. int idx = view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT);
  2182. bool current = view_menu->get_popup()->is_item_checked(idx);
  2183. current = !current;
  2184. if (current) {
  2185. camera->set_environment(RES());
  2186. } else {
  2187. camera->set_environment(SpatialEditor::get_singleton()->get_viewport_environment());
  2188. }
  2189. view_menu->get_popup()->set_item_checked(idx, current);
  2190. } break;
  2191. case VIEW_PERSPECTIVE: {
  2192. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
  2193. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), false);
  2194. orthogonal = false;
  2195. auto_orthogonal = false;
  2196. call_deferred("update_transform_gizmo_view");
  2197. _update_name();
  2198. } break;
  2199. case VIEW_ORTHOGONAL: {
  2200. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), false);
  2201. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), true);
  2202. orthogonal = true;
  2203. auto_orthogonal = false;
  2204. call_deferred("update_transform_gizmo_view");
  2205. _update_name();
  2206. } break;
  2207. case VIEW_AUTO_ORTHOGONAL: {
  2208. int idx = view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL);
  2209. bool current = view_menu->get_popup()->is_item_checked(idx);
  2210. current = !current;
  2211. view_menu->get_popup()->set_item_checked(idx, current);
  2212. if (auto_orthogonal) {
  2213. auto_orthogonal = false;
  2214. _update_name();
  2215. }
  2216. } break;
  2217. case VIEW_LOCK_ROTATION: {
  2218. int idx = view_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
  2219. bool current = view_menu->get_popup()->is_item_checked(idx);
  2220. lock_rotation = !current;
  2221. view_menu->get_popup()->set_item_checked(idx, !current);
  2222. if (lock_rotation) {
  2223. locked_label->show();
  2224. } else {
  2225. locked_label->hide();
  2226. }
  2227. } break;
  2228. case VIEW_AUDIO_LISTENER: {
  2229. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
  2230. bool current = view_menu->get_popup()->is_item_checked(idx);
  2231. current = !current;
  2232. viewport->set_as_audio_listener(current);
  2233. view_menu->get_popup()->set_item_checked(idx, current);
  2234. } break;
  2235. case VIEW_AUDIO_DOPPLER: {
  2236. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
  2237. bool current = view_menu->get_popup()->is_item_checked(idx);
  2238. current = !current;
  2239. camera->set_doppler_tracking(current ? Camera::DOPPLER_TRACKING_IDLE_STEP : Camera::DOPPLER_TRACKING_DISABLED);
  2240. view_menu->get_popup()->set_item_checked(idx, current);
  2241. } break;
  2242. case VIEW_CINEMATIC_PREVIEW: {
  2243. int idx = view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
  2244. bool current = view_menu->get_popup()->is_item_checked(idx);
  2245. current = !current;
  2246. view_menu->get_popup()->set_item_checked(idx, current);
  2247. previewing_cinema = true;
  2248. _toggle_cinema_preview(current);
  2249. if (current) {
  2250. preview_camera->hide();
  2251. } else {
  2252. if (previewing != NULL)
  2253. preview_camera->show();
  2254. }
  2255. } break;
  2256. case VIEW_GIZMOS: {
  2257. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  2258. bool current = view_menu->get_popup()->is_item_checked(idx);
  2259. current = !current;
  2260. if (current)
  2261. camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + index)) | (1 << GIZMO_EDIT_LAYER) | (1 << GIZMO_GRID_LAYER));
  2262. else
  2263. camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + index)) | (1 << GIZMO_GRID_LAYER));
  2264. view_menu->get_popup()->set_item_checked(idx, current);
  2265. } break;
  2266. case VIEW_HALF_RESOLUTION: {
  2267. int idx = view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
  2268. bool current = view_menu->get_popup()->is_item_checked(idx);
  2269. current = !current;
  2270. view_menu->get_popup()->set_item_checked(idx, current);
  2271. } break;
  2272. case VIEW_INFORMATION: {
  2273. int idx = view_menu->get_popup()->get_item_index(VIEW_INFORMATION);
  2274. bool current = view_menu->get_popup()->is_item_checked(idx);
  2275. view_menu->get_popup()->set_item_checked(idx, !current);
  2276. } break;
  2277. case VIEW_FPS: {
  2278. int idx = view_menu->get_popup()->get_item_index(VIEW_FPS);
  2279. bool current = view_menu->get_popup()->is_item_checked(idx);
  2280. view_menu->get_popup()->set_item_checked(idx, !current);
  2281. } break;
  2282. case VIEW_DISPLAY_NORMAL: {
  2283. viewport->set_debug_draw(Viewport::DEBUG_DRAW_DISABLED);
  2284. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), true);
  2285. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), false);
  2286. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), false);
  2287. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), false);
  2288. } break;
  2289. case VIEW_DISPLAY_WIREFRAME: {
  2290. viewport->set_debug_draw(Viewport::DEBUG_DRAW_WIREFRAME);
  2291. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), false);
  2292. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), true);
  2293. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), false);
  2294. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), false);
  2295. } break;
  2296. case VIEW_DISPLAY_OVERDRAW: {
  2297. viewport->set_debug_draw(Viewport::DEBUG_DRAW_OVERDRAW);
  2298. VisualServer::get_singleton()->scenario_set_debug(get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_OVERDRAW);
  2299. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), false);
  2300. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), false);
  2301. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), true);
  2302. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), false);
  2303. } break;
  2304. case VIEW_DISPLAY_SHADELESS: {
  2305. viewport->set_debug_draw(Viewport::DEBUG_DRAW_UNSHADED);
  2306. VisualServer::get_singleton()->scenario_set_debug(get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_SHADELESS);
  2307. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), false);
  2308. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), false);
  2309. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), false);
  2310. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), true);
  2311. } break;
  2312. }
  2313. }
  2314. void SpatialEditorViewport::_set_auto_orthogonal() {
  2315. if (!orthogonal && view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL))) {
  2316. _menu_option(VIEW_ORTHOGONAL);
  2317. auto_orthogonal = true;
  2318. }
  2319. }
  2320. void SpatialEditorViewport::_preview_exited_scene() {
  2321. preview_camera->disconnect("toggled", this, "_toggle_camera_preview");
  2322. preview_camera->set_pressed(false);
  2323. _toggle_camera_preview(false);
  2324. preview_camera->connect("toggled", this, "_toggle_camera_preview");
  2325. view_menu->show();
  2326. }
  2327. void SpatialEditorViewport::_init_gizmo_instance(int p_idx) {
  2328. uint32_t layer = 1 << (GIZMO_BASE_LAYER + p_idx);
  2329. for (int i = 0; i < 3; i++) {
  2330. move_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2331. VS::get_singleton()->instance_set_base(move_gizmo_instance[i], spatial_editor->get_move_gizmo(i)->get_rid());
  2332. VS::get_singleton()->instance_set_scenario(move_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2333. VS::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  2334. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2335. VS::get_singleton()->instance_set_layer_mask(move_gizmo_instance[i], layer);
  2336. move_plane_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2337. VS::get_singleton()->instance_set_base(move_plane_gizmo_instance[i], spatial_editor->get_move_plane_gizmo(i)->get_rid());
  2338. VS::get_singleton()->instance_set_scenario(move_plane_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2339. VS::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  2340. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_plane_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2341. VS::get_singleton()->instance_set_layer_mask(move_plane_gizmo_instance[i], layer);
  2342. rotate_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2343. VS::get_singleton()->instance_set_base(rotate_gizmo_instance[i], spatial_editor->get_rotate_gizmo(i)->get_rid());
  2344. VS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2345. VS::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  2346. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2347. VS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[i], layer);
  2348. scale_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2349. VS::get_singleton()->instance_set_base(scale_gizmo_instance[i], spatial_editor->get_scale_gizmo(i)->get_rid());
  2350. VS::get_singleton()->instance_set_scenario(scale_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2351. VS::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  2352. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2353. VS::get_singleton()->instance_set_layer_mask(scale_gizmo_instance[i], layer);
  2354. scale_plane_gizmo_instance[i] = VS::get_singleton()->instance_create();
  2355. VS::get_singleton()->instance_set_base(scale_plane_gizmo_instance[i], spatial_editor->get_scale_plane_gizmo(i)->get_rid());
  2356. VS::get_singleton()->instance_set_scenario(scale_plane_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2357. VS::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  2358. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_plane_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2359. VS::get_singleton()->instance_set_layer_mask(scale_plane_gizmo_instance[i], layer);
  2360. }
  2361. }
  2362. void SpatialEditorViewport::_finish_gizmo_instances() {
  2363. for (int i = 0; i < 3; i++) {
  2364. VS::get_singleton()->free(move_gizmo_instance[i]);
  2365. VS::get_singleton()->free(move_plane_gizmo_instance[i]);
  2366. VS::get_singleton()->free(rotate_gizmo_instance[i]);
  2367. VS::get_singleton()->free(scale_gizmo_instance[i]);
  2368. VS::get_singleton()->free(scale_plane_gizmo_instance[i]);
  2369. }
  2370. }
  2371. void SpatialEditorViewport::_toggle_camera_preview(bool p_activate) {
  2372. ERR_FAIL_COND(p_activate && !preview);
  2373. ERR_FAIL_COND(!p_activate && !previewing);
  2374. rotation_control->set_visible(!p_activate);
  2375. if (!p_activate) {
  2376. previewing->disconnect("tree_exiting", this, "_preview_exited_scene");
  2377. previewing = NULL;
  2378. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
  2379. if (!preview)
  2380. preview_camera->hide();
  2381. view_menu->set_disabled(false);
  2382. surface->update();
  2383. } else {
  2384. previewing = preview;
  2385. previewing->connect("tree_exiting", this, "_preview_exited_scene");
  2386. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), preview->get_camera()); //replace
  2387. view_menu->set_disabled(true);
  2388. surface->update();
  2389. }
  2390. }
  2391. void SpatialEditorViewport::_toggle_cinema_preview(bool p_activate) {
  2392. previewing_cinema = p_activate;
  2393. if (!previewing_cinema) {
  2394. if (previewing != NULL)
  2395. previewing->disconnect("tree_exited", this, "_preview_exited_scene");
  2396. previewing = NULL;
  2397. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
  2398. preview_camera->set_pressed(false);
  2399. if (!preview) {
  2400. preview_camera->hide();
  2401. } else {
  2402. preview_camera->show();
  2403. }
  2404. view_menu->show();
  2405. surface->update();
  2406. }
  2407. }
  2408. void SpatialEditorViewport::_selection_result_pressed(int p_result) {
  2409. if (selection_results.size() <= p_result)
  2410. return;
  2411. clicked = selection_results[p_result].item->get_instance_id();
  2412. if (clicked) {
  2413. _select_clicked(clicked_wants_append, true);
  2414. clicked = 0;
  2415. }
  2416. }
  2417. void SpatialEditorViewport::_selection_menu_hide() {
  2418. selection_results.clear();
  2419. selection_menu->clear();
  2420. selection_menu->set_size(Vector2(0, 0));
  2421. }
  2422. void SpatialEditorViewport::set_can_preview(Camera *p_preview) {
  2423. preview = p_preview;
  2424. if (!preview_camera->is_pressed() && !previewing_cinema)
  2425. preview_camera->set_visible(p_preview);
  2426. }
  2427. void SpatialEditorViewport::update_transform_gizmo_view() {
  2428. if (!is_visible_in_tree())
  2429. return;
  2430. Transform xform = spatial_editor->get_gizmo_transform();
  2431. Transform camera_xform = camera->get_transform();
  2432. if (xform.origin.distance_squared_to(camera_xform.origin) < 0.01) {
  2433. for (int i = 0; i < 3; i++) {
  2434. VisualServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  2435. VisualServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  2436. VisualServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  2437. VisualServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  2438. VisualServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  2439. }
  2440. return;
  2441. }
  2442. Vector3 camz = -camera_xform.get_basis().get_axis(2).normalized();
  2443. Vector3 camy = -camera_xform.get_basis().get_axis(1).normalized();
  2444. Plane p(camera_xform.origin, camz);
  2445. float gizmo_d = Math::abs(p.distance_to(xform.origin));
  2446. float d0 = camera->unproject_position(camera_xform.origin + camz * gizmo_d).y;
  2447. float d1 = camera->unproject_position(camera_xform.origin + camz * gizmo_d + camy).y;
  2448. float dd = Math::abs(d0 - d1);
  2449. if (dd == 0)
  2450. dd = 0.0001;
  2451. float gizmo_size = EditorSettings::get_singleton()->get("editors/3d/manipulator_gizmo_size");
  2452. // At low viewport heights, multiply the gizmo scale based on the viewport height.
  2453. // This prevents the gizmo from growing very large and going outside the viewport.
  2454. const int viewport_base_height = 400 * MAX(1, EDSCALE);
  2455. gizmo_scale =
  2456. (gizmo_size / Math::abs(dd)) * MAX(1, EDSCALE) *
  2457. MIN(viewport_base_height, viewport_container->get_size().height) / viewport_base_height /
  2458. viewport_container->get_stretch_shrink();
  2459. Vector3 scale = Vector3(1, 1, 1) * gizmo_scale;
  2460. xform.basis.scale(scale);
  2461. for (int i = 0; i < 3; i++) {
  2462. VisualServer::get_singleton()->instance_set_transform(move_gizmo_instance[i], xform);
  2463. 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));
  2464. VisualServer::get_singleton()->instance_set_transform(move_plane_gizmo_instance[i], xform);
  2465. 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));
  2466. VisualServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[i], xform);
  2467. 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));
  2468. VisualServer::get_singleton()->instance_set_transform(scale_gizmo_instance[i], xform);
  2469. VisualServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SCALE));
  2470. VisualServer::get_singleton()->instance_set_transform(scale_plane_gizmo_instance[i], xform);
  2471. 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));
  2472. }
  2473. }
  2474. void SpatialEditorViewport::set_state(const Dictionary &p_state) {
  2475. if (p_state.has("position"))
  2476. cursor.pos = p_state["position"];
  2477. if (p_state.has("x_rotation"))
  2478. cursor.x_rot = p_state["x_rotation"];
  2479. if (p_state.has("y_rotation"))
  2480. cursor.y_rot = p_state["y_rotation"];
  2481. if (p_state.has("distance"))
  2482. cursor.distance = p_state["distance"];
  2483. if (p_state.has("use_orthogonal")) {
  2484. bool orth = p_state["use_orthogonal"];
  2485. if (orth)
  2486. _menu_option(VIEW_ORTHOGONAL);
  2487. else
  2488. _menu_option(VIEW_PERSPECTIVE);
  2489. }
  2490. if (p_state.has("view_name")) {
  2491. name = p_state["view_name"];
  2492. _update_name();
  2493. }
  2494. if (p_state.has("auto_orthogonal")) {
  2495. auto_orthogonal = p_state["auto_orthogonal"];
  2496. _update_name();
  2497. }
  2498. if (p_state.has("auto_orthogonal_enabled")) {
  2499. bool enabled = p_state["auto_orthogonal_enabled"];
  2500. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL), enabled);
  2501. }
  2502. if (p_state.has("display_mode")) {
  2503. int display = p_state["display_mode"];
  2504. int idx = view_menu->get_popup()->get_item_index(display);
  2505. if (!view_menu->get_popup()->is_item_checked(idx))
  2506. _menu_option(display);
  2507. }
  2508. if (p_state.has("lock_rotation")) {
  2509. lock_rotation = p_state["lock_rotation"];
  2510. int idx = view_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
  2511. view_menu->get_popup()->set_item_checked(idx, lock_rotation);
  2512. }
  2513. if (p_state.has("use_environment")) {
  2514. bool env = p_state["use_environment"];
  2515. if (env != camera->get_environment().is_valid())
  2516. _menu_option(VIEW_ENVIRONMENT);
  2517. }
  2518. if (p_state.has("listener")) {
  2519. bool listener = p_state["listener"];
  2520. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
  2521. viewport->set_as_audio_listener(listener);
  2522. view_menu->get_popup()->set_item_checked(idx, listener);
  2523. }
  2524. if (p_state.has("doppler")) {
  2525. bool doppler = p_state["doppler"];
  2526. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
  2527. camera->set_doppler_tracking(doppler ? Camera::DOPPLER_TRACKING_IDLE_STEP : Camera::DOPPLER_TRACKING_DISABLED);
  2528. view_menu->get_popup()->set_item_checked(idx, doppler);
  2529. }
  2530. if (p_state.has("gizmos")) {
  2531. bool gizmos = p_state["gizmos"];
  2532. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  2533. if (view_menu->get_popup()->is_item_checked(idx) != gizmos)
  2534. _menu_option(VIEW_GIZMOS);
  2535. }
  2536. if (p_state.has("information")) {
  2537. bool information = p_state["information"];
  2538. int idx = view_menu->get_popup()->get_item_index(VIEW_INFORMATION);
  2539. if (view_menu->get_popup()->is_item_checked(idx) != information)
  2540. _menu_option(VIEW_INFORMATION);
  2541. }
  2542. if (p_state.has("fps")) {
  2543. bool fps = p_state["fps"];
  2544. int idx = view_menu->get_popup()->get_item_index(VIEW_FPS);
  2545. if (view_menu->get_popup()->is_item_checked(idx) != fps)
  2546. _menu_option(VIEW_FPS);
  2547. }
  2548. if (p_state.has("half_res")) {
  2549. bool half_res = p_state["half_res"];
  2550. int idx = view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
  2551. view_menu->get_popup()->set_item_checked(idx, half_res);
  2552. }
  2553. if (p_state.has("cinematic_preview")) {
  2554. previewing_cinema = p_state["cinematic_preview"];
  2555. int idx = view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
  2556. view_menu->get_popup()->set_item_checked(idx, previewing_cinema);
  2557. }
  2558. if (preview_camera->is_connected("toggled", this, "_toggle_camera_preview")) {
  2559. preview_camera->disconnect("toggled", this, "_toggle_camera_preview");
  2560. }
  2561. if (p_state.has("previewing")) {
  2562. Node *pv = EditorNode::get_singleton()->get_edited_scene()->get_node(p_state["previewing"]);
  2563. if (Object::cast_to<Camera>(pv)) {
  2564. previewing = Object::cast_to<Camera>(pv);
  2565. previewing->connect("tree_exiting", this, "_preview_exited_scene");
  2566. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), previewing->get_camera()); //replace
  2567. view_menu->set_disabled(true);
  2568. surface->update();
  2569. preview_camera->set_pressed(true);
  2570. preview_camera->show();
  2571. }
  2572. }
  2573. preview_camera->connect("toggled", this, "_toggle_camera_preview");
  2574. }
  2575. Dictionary SpatialEditorViewport::get_state() const {
  2576. Dictionary d;
  2577. d["position"] = cursor.pos;
  2578. d["x_rotation"] = cursor.x_rot;
  2579. d["y_rotation"] = cursor.y_rot;
  2580. d["distance"] = cursor.distance;
  2581. d["use_environment"] = camera->get_environment().is_valid();
  2582. d["use_orthogonal"] = camera->get_projection() == Camera::PROJECTION_ORTHOGONAL;
  2583. d["view_name"] = name;
  2584. d["auto_orthogonal"] = auto_orthogonal;
  2585. d["auto_orthogonal_enabled"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL));
  2586. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL)))
  2587. d["display_mode"] = VIEW_DISPLAY_NORMAL;
  2588. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME)))
  2589. d["display_mode"] = VIEW_DISPLAY_WIREFRAME;
  2590. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW)))
  2591. d["display_mode"] = VIEW_DISPLAY_OVERDRAW;
  2592. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS)))
  2593. d["display_mode"] = VIEW_DISPLAY_SHADELESS;
  2594. d["listener"] = viewport->is_audio_listener();
  2595. d["doppler"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER));
  2596. d["gizmos"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_GIZMOS));
  2597. d["information"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_INFORMATION));
  2598. d["fps"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_FPS));
  2599. d["half_res"] = viewport_container->get_stretch_shrink() > 1;
  2600. d["cinematic_preview"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
  2601. if (previewing)
  2602. d["previewing"] = EditorNode::get_singleton()->get_edited_scene()->get_path_to(previewing);
  2603. if (lock_rotation)
  2604. d["lock_rotation"] = lock_rotation;
  2605. return d;
  2606. }
  2607. void SpatialEditorViewport::_bind_methods() {
  2608. ClassDB::bind_method(D_METHOD("_draw"), &SpatialEditorViewport::_draw);
  2609. ClassDB::bind_method(D_METHOD("_surface_mouse_enter"), &SpatialEditorViewport::_surface_mouse_enter);
  2610. ClassDB::bind_method(D_METHOD("_surface_mouse_exit"), &SpatialEditorViewport::_surface_mouse_exit);
  2611. ClassDB::bind_method(D_METHOD("_surface_focus_enter"), &SpatialEditorViewport::_surface_focus_enter);
  2612. ClassDB::bind_method(D_METHOD("_surface_focus_exit"), &SpatialEditorViewport::_surface_focus_exit);
  2613. ClassDB::bind_method(D_METHOD("_sinput"), &SpatialEditorViewport::_sinput);
  2614. ClassDB::bind_method(D_METHOD("_menu_option"), &SpatialEditorViewport::_menu_option);
  2615. ClassDB::bind_method(D_METHOD("_toggle_camera_preview"), &SpatialEditorViewport::_toggle_camera_preview);
  2616. ClassDB::bind_method(D_METHOD("_preview_exited_scene"), &SpatialEditorViewport::_preview_exited_scene);
  2617. ClassDB::bind_method(D_METHOD("_update_camera"), &SpatialEditorViewport::_update_camera);
  2618. ClassDB::bind_method(D_METHOD("update_transform_gizmo_view"), &SpatialEditorViewport::update_transform_gizmo_view);
  2619. ClassDB::bind_method(D_METHOD("_selection_result_pressed"), &SpatialEditorViewport::_selection_result_pressed);
  2620. ClassDB::bind_method(D_METHOD("_selection_menu_hide"), &SpatialEditorViewport::_selection_menu_hide);
  2621. ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &SpatialEditorViewport::can_drop_data_fw);
  2622. ClassDB::bind_method(D_METHOD("drop_data_fw"), &SpatialEditorViewport::drop_data_fw);
  2623. ADD_SIGNAL(MethodInfo("toggle_maximize_view", PropertyInfo(Variant::OBJECT, "viewport")));
  2624. ADD_SIGNAL(MethodInfo("clicked", PropertyInfo(Variant::OBJECT, "viewport")));
  2625. }
  2626. void SpatialEditorViewport::reset() {
  2627. orthogonal = false;
  2628. auto_orthogonal = false;
  2629. lock_rotation = false;
  2630. message_time = 0;
  2631. message = "";
  2632. last_message = "";
  2633. name = "";
  2634. cursor.x_rot = 0.5;
  2635. cursor.y_rot = 0.5;
  2636. cursor.distance = 4;
  2637. cursor.region_select = false;
  2638. cursor.pos = Vector3();
  2639. _update_name();
  2640. }
  2641. void SpatialEditorViewport::focus_selection() {
  2642. if (!get_selected_count())
  2643. return;
  2644. Vector3 center;
  2645. int count = 0;
  2646. List<Node *> &selection = editor_selection->get_selected_node_list();
  2647. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  2648. Spatial *sp = Object::cast_to<Spatial>(E->get());
  2649. if (!sp)
  2650. continue;
  2651. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  2652. if (!se)
  2653. continue;
  2654. center += sp->get_global_gizmo_transform().origin;
  2655. count++;
  2656. }
  2657. if (count != 0) {
  2658. center /= float(count);
  2659. }
  2660. cursor.pos = center;
  2661. }
  2662. void SpatialEditorViewport::assign_pending_data_pointers(Spatial *p_preview_node, AABB *p_preview_bounds, AcceptDialog *p_accept) {
  2663. preview_node = p_preview_node;
  2664. preview_bounds = p_preview_bounds;
  2665. accept = p_accept;
  2666. }
  2667. Vector3 SpatialEditorViewport::_get_instance_position(const Point2 &p_pos) const {
  2668. const float MAX_DISTANCE = 10;
  2669. Vector3 world_ray = _get_ray(p_pos);
  2670. Vector3 world_pos = _get_ray_pos(p_pos);
  2671. Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_ray(world_pos, world_ray, get_tree()->get_root()->get_world()->get_scenario());
  2672. Set<Ref<EditorSpatialGizmo> > found_gizmos;
  2673. float closest_dist = MAX_DISTANCE;
  2674. Vector3 point = world_pos + world_ray * MAX_DISTANCE;
  2675. Vector3 normal = Vector3(0.0, 0.0, 0.0);
  2676. for (int i = 0; i < instances.size(); i++) {
  2677. MeshInstance *mesh_instance = Object::cast_to<MeshInstance>(ObjectDB::get_instance(instances[i]));
  2678. if (!mesh_instance)
  2679. continue;
  2680. Ref<EditorSpatialGizmo> seg = mesh_instance->get_gizmo();
  2681. if ((!seg.is_valid()) || found_gizmos.has(seg)) {
  2682. continue;
  2683. }
  2684. found_gizmos.insert(seg);
  2685. Vector3 hit_point;
  2686. Vector3 hit_normal;
  2687. bool inters = seg->intersect_ray(camera, p_pos, hit_point, hit_normal, NULL, false);
  2688. if (!inters)
  2689. continue;
  2690. float dist = world_pos.distance_to(hit_point);
  2691. if (dist < 0)
  2692. continue;
  2693. if (dist < closest_dist) {
  2694. closest_dist = dist;
  2695. point = hit_point;
  2696. normal = hit_normal;
  2697. }
  2698. }
  2699. Vector3 offset = Vector3();
  2700. for (int i = 0; i < 3; i++) {
  2701. if (normal[i] > 0.0)
  2702. offset[i] = (preview_bounds->get_size()[i] - (preview_bounds->get_size()[i] + preview_bounds->get_position()[i]));
  2703. else if (normal[i] < 0.0)
  2704. offset[i] = -(preview_bounds->get_size()[i] + preview_bounds->get_position()[i]);
  2705. }
  2706. return point + offset;
  2707. }
  2708. AABB SpatialEditorViewport::_calculate_spatial_bounds(const Spatial *p_parent, bool p_exclude_toplevel_transform) {
  2709. AABB bounds;
  2710. const MeshInstance *mesh_instance = Object::cast_to<MeshInstance>(p_parent);
  2711. if (mesh_instance) {
  2712. bounds = mesh_instance->get_aabb();
  2713. }
  2714. for (int i = 0; i < p_parent->get_child_count(); i++) {
  2715. Spatial *child = Object::cast_to<Spatial>(p_parent->get_child(i));
  2716. if (child) {
  2717. AABB child_bounds = _calculate_spatial_bounds(child, false);
  2718. if (bounds.size == Vector3() && p_parent->get_class_name() == StringName("Spatial")) {
  2719. bounds = child_bounds;
  2720. } else {
  2721. bounds.merge_with(child_bounds);
  2722. }
  2723. }
  2724. }
  2725. if (bounds.size == Vector3() && p_parent->get_class_name() != StringName("Spatial")) {
  2726. bounds = AABB(Vector3(-0.2, -0.2, -0.2), Vector3(0.4, 0.4, 0.4));
  2727. }
  2728. if (!p_exclude_toplevel_transform) {
  2729. bounds = p_parent->get_transform().xform(bounds);
  2730. }
  2731. return bounds;
  2732. }
  2733. void SpatialEditorViewport::_create_preview(const Vector<String> &files) const {
  2734. for (int i = 0; i < files.size(); i++) {
  2735. String path = files[i];
  2736. RES res = ResourceLoader::load(path);
  2737. ERR_CONTINUE(res.is_null());
  2738. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  2739. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  2740. if (mesh != NULL || scene != NULL) {
  2741. if (mesh != NULL) {
  2742. MeshInstance *mesh_instance = memnew(MeshInstance);
  2743. mesh_instance->set_mesh(mesh);
  2744. preview_node->add_child(mesh_instance);
  2745. } else {
  2746. if (scene.is_valid()) {
  2747. Node *instance = scene->instance();
  2748. if (instance) {
  2749. preview_node->add_child(instance);
  2750. }
  2751. }
  2752. }
  2753. editor->get_scene_root()->add_child(preview_node);
  2754. }
  2755. }
  2756. *preview_bounds = _calculate_spatial_bounds(preview_node);
  2757. }
  2758. void SpatialEditorViewport::_remove_preview() {
  2759. if (preview_node->get_parent()) {
  2760. for (int i = preview_node->get_child_count() - 1; i >= 0; i--) {
  2761. Node *node = preview_node->get_child(i);
  2762. node->queue_delete();
  2763. preview_node->remove_child(node);
  2764. }
  2765. editor->get_scene_root()->remove_child(preview_node);
  2766. }
  2767. }
  2768. bool SpatialEditorViewport::_cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node) {
  2769. if (p_desired_node->get_filename() == p_target_scene_path) {
  2770. return true;
  2771. }
  2772. int childCount = p_desired_node->get_child_count();
  2773. for (int i = 0; i < childCount; i++) {
  2774. Node *child = p_desired_node->get_child(i);
  2775. if (_cyclical_dependency_exists(p_target_scene_path, child)) {
  2776. return true;
  2777. }
  2778. }
  2779. return false;
  2780. }
  2781. bool SpatialEditorViewport::_create_instance(Node *parent, String &path, const Point2 &p_point) {
  2782. RES res = ResourceLoader::load(path);
  2783. ERR_FAIL_COND_V(res.is_null(), false);
  2784. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  2785. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  2786. Node *instanced_scene = NULL;
  2787. if (mesh != NULL || scene != NULL) {
  2788. if (mesh != NULL) {
  2789. MeshInstance *mesh_instance = memnew(MeshInstance);
  2790. mesh_instance->set_mesh(mesh);
  2791. mesh_instance->set_name(path.get_file().get_basename());
  2792. instanced_scene = mesh_instance;
  2793. } else {
  2794. if (!scene.is_valid()) { // invalid scene
  2795. return false;
  2796. } else {
  2797. instanced_scene = scene->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
  2798. }
  2799. }
  2800. }
  2801. if (instanced_scene == NULL) {
  2802. return false;
  2803. }
  2804. if (editor->get_edited_scene()->get_filename() != "") { // cyclical instancing
  2805. if (_cyclical_dependency_exists(editor->get_edited_scene()->get_filename(), instanced_scene)) {
  2806. memdelete(instanced_scene);
  2807. return false;
  2808. }
  2809. }
  2810. if (scene != NULL) {
  2811. instanced_scene->set_filename(ProjectSettings::get_singleton()->localize_path(path));
  2812. }
  2813. editor_data->get_undo_redo().add_do_method(parent, "add_child", instanced_scene);
  2814. editor_data->get_undo_redo().add_do_method(instanced_scene, "set_owner", editor->get_edited_scene());
  2815. editor_data->get_undo_redo().add_do_reference(instanced_scene);
  2816. editor_data->get_undo_redo().add_undo_method(parent, "remove_child", instanced_scene);
  2817. String new_name = parent->validate_child_name(instanced_scene);
  2818. ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger();
  2819. editor_data->get_undo_redo().add_do_method(sed, "live_debug_instance_node", editor->get_edited_scene()->get_path_to(parent), path, new_name);
  2820. 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));
  2821. Transform global_transform;
  2822. Spatial *parent_spatial = Object::cast_to<Spatial>(parent);
  2823. if (parent_spatial)
  2824. global_transform = parent_spatial->get_global_gizmo_transform();
  2825. global_transform.origin = spatial_editor->snap_point(_get_instance_position(p_point));
  2826. editor_data->get_undo_redo().add_do_method(instanced_scene, "set_global_transform", global_transform);
  2827. return true;
  2828. }
  2829. void SpatialEditorViewport::_perform_drop_data() {
  2830. _remove_preview();
  2831. Vector<String> error_files;
  2832. editor_data->get_undo_redo().create_action(TTR("Create Node"));
  2833. for (int i = 0; i < selected_files.size(); i++) {
  2834. String path = selected_files[i];
  2835. RES res = ResourceLoader::load(path);
  2836. if (res.is_null()) {
  2837. continue;
  2838. }
  2839. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  2840. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  2841. if (mesh != NULL || scene != NULL) {
  2842. bool success = _create_instance(target_node, path, drop_pos);
  2843. if (!success) {
  2844. error_files.push_back(path);
  2845. }
  2846. }
  2847. }
  2848. editor_data->get_undo_redo().commit_action();
  2849. if (error_files.size() > 0) {
  2850. String files_str;
  2851. for (int i = 0; i < error_files.size(); i++) {
  2852. files_str += error_files[i].get_file().get_basename() + ",";
  2853. }
  2854. files_str = files_str.substr(0, files_str.length() - 1);
  2855. accept->set_text(vformat(TTR("Error instancing scene from %s"), files_str.c_str()));
  2856. accept->popup_centered_minsize();
  2857. }
  2858. }
  2859. bool SpatialEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
  2860. bool can_instance = false;
  2861. if (!preview_node->is_inside_tree()) {
  2862. Dictionary d = p_data;
  2863. if (d.has("type") && (String(d["type"]) == "files")) {
  2864. Vector<String> files = d["files"];
  2865. List<String> scene_extensions;
  2866. ResourceLoader::get_recognized_extensions_for_type("PackedScene", &scene_extensions);
  2867. List<String> mesh_extensions;
  2868. ResourceLoader::get_recognized_extensions_for_type("Mesh", &mesh_extensions);
  2869. for (int i = 0; i < files.size(); i++) {
  2870. if (mesh_extensions.find(files[i].get_extension()) || scene_extensions.find(files[i].get_extension())) {
  2871. RES res = ResourceLoader::load(files[i]);
  2872. if (res.is_null()) {
  2873. continue;
  2874. }
  2875. String type = res->get_class();
  2876. if (type == "PackedScene") {
  2877. Ref<PackedScene> sdata = ResourceLoader::load(files[i]);
  2878. Node *instanced_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
  2879. if (!instanced_scene) {
  2880. continue;
  2881. }
  2882. memdelete(instanced_scene);
  2883. } else if (type == "Mesh" || type == "ArrayMesh" || type == "PrimitiveMesh") {
  2884. Ref<Mesh> mesh = ResourceLoader::load(files[i]);
  2885. if (!mesh.is_valid()) {
  2886. continue;
  2887. }
  2888. } else {
  2889. continue;
  2890. }
  2891. can_instance = true;
  2892. break;
  2893. }
  2894. }
  2895. if (can_instance) {
  2896. _create_preview(files);
  2897. }
  2898. }
  2899. } else {
  2900. can_instance = true;
  2901. }
  2902. if (can_instance) {
  2903. Transform global_transform = Transform(Basis(), _get_instance_position(p_point));
  2904. preview_node->set_global_transform(global_transform);
  2905. }
  2906. return can_instance;
  2907. }
  2908. void SpatialEditorViewport::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
  2909. if (!can_drop_data_fw(p_point, p_data, p_from))
  2910. return;
  2911. bool is_shift = Input::get_singleton()->is_key_pressed(KEY_SHIFT);
  2912. selected_files.clear();
  2913. Dictionary d = p_data;
  2914. if (d.has("type") && String(d["type"]) == "files") {
  2915. selected_files = d["files"];
  2916. }
  2917. List<Node *> list = editor->get_editor_selection()->get_selected_node_list();
  2918. if (list.size() == 0) {
  2919. Node *root_node = editor->get_edited_scene();
  2920. if (root_node) {
  2921. list.push_back(root_node);
  2922. } else {
  2923. accept->set_text(TTR("No parent to instance a child at."));
  2924. accept->popup_centered_minsize();
  2925. _remove_preview();
  2926. return;
  2927. }
  2928. }
  2929. if (list.size() != 1) {
  2930. accept->set_text(TTR("This operation requires a single selected node."));
  2931. accept->popup_centered_minsize();
  2932. _remove_preview();
  2933. return;
  2934. }
  2935. target_node = list[0];
  2936. if (is_shift && target_node != editor->get_edited_scene()) {
  2937. target_node = target_node->get_parent();
  2938. }
  2939. drop_pos = p_point;
  2940. _perform_drop_data();
  2941. }
  2942. SpatialEditorViewport::SpatialEditorViewport(SpatialEditor *p_spatial_editor, EditorNode *p_editor, int p_index) {
  2943. _edit.mode = TRANSFORM_NONE;
  2944. _edit.plane = TRANSFORM_VIEW;
  2945. _edit.edited_gizmo = 0;
  2946. _edit.snap = 1;
  2947. _edit.gizmo_handle = 0;
  2948. index = p_index;
  2949. editor = p_editor;
  2950. editor_data = editor->get_scene_tree_dock()->get_editor_data();
  2951. editor_selection = editor->get_editor_selection();
  2952. undo_redo = editor->get_undo_redo();
  2953. clicked = 0;
  2954. clicked_includes_current = false;
  2955. orthogonal = false;
  2956. auto_orthogonal = false;
  2957. lock_rotation = false;
  2958. message_time = 0;
  2959. zoom_indicator_delay = 0.0;
  2960. spatial_editor = p_spatial_editor;
  2961. ViewportContainer *c = memnew(ViewportContainer);
  2962. viewport_container = c;
  2963. c->set_stretch(true);
  2964. add_child(c);
  2965. c->set_anchors_and_margins_preset(Control::PRESET_WIDE);
  2966. viewport = memnew(Viewport);
  2967. viewport->set_disable_input(true);
  2968. c->add_child(viewport);
  2969. surface = memnew(Control);
  2970. surface->set_drag_forwarding(this);
  2971. add_child(surface);
  2972. surface->set_anchors_and_margins_preset(Control::PRESET_WIDE);
  2973. surface->set_clip_contents(true);
  2974. camera = memnew(Camera);
  2975. camera->set_disable_gizmo(true);
  2976. camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + p_index)) | (1 << GIZMO_EDIT_LAYER) | (1 << GIZMO_GRID_LAYER));
  2977. viewport->add_child(camera);
  2978. camera->make_current();
  2979. surface->set_focus_mode(FOCUS_ALL);
  2980. crosshair = memnew(TextureRect);
  2981. crosshair->set_mouse_filter(MOUSE_FILTER_IGNORE);
  2982. surface->add_child(crosshair);
  2983. VBoxContainer *vbox = memnew(VBoxContainer);
  2984. surface->add_child(vbox);
  2985. vbox->set_position(Point2(10, 10) * EDSCALE);
  2986. view_menu = memnew(MenuButton);
  2987. view_menu->set_flat(false);
  2988. vbox->add_child(view_menu);
  2989. view_menu->set_h_size_flags(0);
  2990. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/top_view"), VIEW_TOP);
  2991. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/bottom_view"), VIEW_BOTTOM);
  2992. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/left_view"), VIEW_LEFT);
  2993. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/right_view"), VIEW_RIGHT);
  2994. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/front_view"), VIEW_FRONT);
  2995. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/rear_view"), VIEW_REAR);
  2996. view_menu->get_popup()->add_separator();
  2997. view_menu->get_popup()->add_radio_check_item(TTR("Perspective") + " (" + ED_GET_SHORTCUT("spatial_editor/switch_perspective_orthogonal")->get_as_text() + ")", VIEW_PERSPECTIVE);
  2998. view_menu->get_popup()->add_radio_check_item(TTR("Orthogonal") + " (" + ED_GET_SHORTCUT("spatial_editor/switch_perspective_orthogonal")->get_as_text() + ")", VIEW_ORTHOGONAL);
  2999. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
  3000. view_menu->get_popup()->add_check_item(TTR("Auto Orthogonal Enabled"), VIEW_AUTO_ORTHOGONAL);
  3001. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL), true);
  3002. view_menu->get_popup()->add_separator();
  3003. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_lock_rotation", TTR("Lock View Rotation")), VIEW_LOCK_ROTATION);
  3004. view_menu->get_popup()->add_separator();
  3005. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_normal", TTR("Display Normal")), VIEW_DISPLAY_NORMAL);
  3006. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_wireframe", TTR("Display Wireframe")), VIEW_DISPLAY_WIREFRAME);
  3007. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_overdraw", TTR("Display Overdraw")), VIEW_DISPLAY_OVERDRAW);
  3008. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_unshaded", TTR("Display Unshaded")), VIEW_DISPLAY_SHADELESS);
  3009. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), true);
  3010. view_menu->get_popup()->add_separator();
  3011. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_environment", TTR("View Environment")), VIEW_ENVIRONMENT);
  3012. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_gizmos", TTR("View Gizmos")), VIEW_GIZMOS);
  3013. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_information", TTR("View Information")), VIEW_INFORMATION);
  3014. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_fps", TTR("View FPS")), VIEW_FPS);
  3015. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT), true);
  3016. view_menu->get_popup()->add_separator();
  3017. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_half_resolution", TTR("Half Resolution")), VIEW_HALF_RESOLUTION);
  3018. view_menu->get_popup()->add_separator();
  3019. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_listener", TTR("Audio Listener")), VIEW_AUDIO_LISTENER);
  3020. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_doppler", TTR("Enable Doppler")), VIEW_AUDIO_DOPPLER);
  3021. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_GIZMOS), true);
  3022. view_menu->get_popup()->add_separator();
  3023. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_cinematic_preview", TTR("Cinematic Preview")), VIEW_CINEMATIC_PREVIEW);
  3024. view_menu->get_popup()->add_separator();
  3025. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_origin"), VIEW_CENTER_TO_ORIGIN);
  3026. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_selection"), VIEW_CENTER_TO_SELECTION);
  3027. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_transform_with_view"), VIEW_ALIGN_TRANSFORM_WITH_VIEW);
  3028. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_rotation_with_view"), VIEW_ALIGN_ROTATION_WITH_VIEW);
  3029. view_menu->get_popup()->connect("id_pressed", this, "_menu_option");
  3030. view_menu->set_disable_shortcuts(true);
  3031. if (OS::get_singleton()->get_current_video_driver() == OS::VIDEO_DRIVER_GLES2) {
  3032. // Alternate display modes only work when using the GLES3 renderer; make this explicit.
  3033. const int normal_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL);
  3034. const int wireframe_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME);
  3035. const int overdraw_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW);
  3036. const int shadeless_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS);
  3037. const String unsupported_tooltip = TTR("Not available when using the GLES2 renderer.");
  3038. view_menu->get_popup()->set_item_disabled(normal_idx, true);
  3039. view_menu->get_popup()->set_item_tooltip(normal_idx, unsupported_tooltip);
  3040. view_menu->get_popup()->set_item_disabled(wireframe_idx, true);
  3041. view_menu->get_popup()->set_item_tooltip(wireframe_idx, unsupported_tooltip);
  3042. view_menu->get_popup()->set_item_disabled(overdraw_idx, true);
  3043. view_menu->get_popup()->set_item_tooltip(overdraw_idx, unsupported_tooltip);
  3044. view_menu->get_popup()->set_item_disabled(shadeless_idx, true);
  3045. view_menu->get_popup()->set_item_tooltip(shadeless_idx, unsupported_tooltip);
  3046. }
  3047. ED_SHORTCUT("spatial_editor/freelook_left", TTR("Freelook Left"), KEY_A);
  3048. ED_SHORTCUT("spatial_editor/freelook_right", TTR("Freelook Right"), KEY_D);
  3049. ED_SHORTCUT("spatial_editor/freelook_forward", TTR("Freelook Forward"), KEY_W);
  3050. ED_SHORTCUT("spatial_editor/freelook_backwards", TTR("Freelook Backwards"), KEY_S);
  3051. ED_SHORTCUT("spatial_editor/freelook_up", TTR("Freelook Up"), KEY_E);
  3052. ED_SHORTCUT("spatial_editor/freelook_down", TTR("Freelook Down"), KEY_Q);
  3053. ED_SHORTCUT("spatial_editor/freelook_speed_modifier", TTR("Freelook Speed Modifier"), KEY_SHIFT);
  3054. ED_SHORTCUT("spatial_editor/freelook_slow_modifier", TTR("Freelook Slow Modifier"), KEY_ALT);
  3055. preview_camera = memnew(CheckBox);
  3056. preview_camera->set_text(TTR("Preview"));
  3057. vbox->add_child(preview_camera);
  3058. preview_camera->set_h_size_flags(0);
  3059. preview_camera->hide();
  3060. preview_camera->connect("toggled", this, "_toggle_camera_preview");
  3061. previewing = NULL;
  3062. gizmo_scale = 1.0;
  3063. preview_node = NULL;
  3064. info_label = memnew(Label);
  3065. info_label->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, -90 * EDSCALE);
  3066. info_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_END, -90 * EDSCALE);
  3067. info_label->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -10 * EDSCALE);
  3068. info_label->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, -10 * EDSCALE);
  3069. info_label->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  3070. info_label->set_v_grow_direction(GROW_DIRECTION_BEGIN);
  3071. surface->add_child(info_label);
  3072. info_label->hide();
  3073. cinema_label = memnew(Label);
  3074. cinema_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 10 * EDSCALE);
  3075. cinema_label->set_h_grow_direction(GROW_DIRECTION_END);
  3076. cinema_label->set_align(Label::ALIGN_CENTER);
  3077. surface->add_child(cinema_label);
  3078. cinema_label->set_text(TTR("Cinematic Preview"));
  3079. cinema_label->hide();
  3080. previewing_cinema = false;
  3081. locked_label = memnew(Label);
  3082. locked_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_END, -20 * EDSCALE);
  3083. locked_label->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, -10 * EDSCALE);
  3084. locked_label->set_h_grow_direction(GROW_DIRECTION_END);
  3085. locked_label->set_v_grow_direction(GROW_DIRECTION_BEGIN);
  3086. locked_label->set_align(Label::ALIGN_CENTER);
  3087. surface->add_child(locked_label);
  3088. locked_label->set_text(TTR("View Rotation Locked"));
  3089. locked_label->hide();
  3090. top_right_vbox = memnew(VBoxContainer);
  3091. top_right_vbox->set_anchors_and_margins_preset(PRESET_TOP_RIGHT, PRESET_MODE_MINSIZE, 2.0 * EDSCALE);
  3092. top_right_vbox->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  3093. rotation_control = memnew(ViewportRotationControl);
  3094. rotation_control->set_custom_minimum_size(Size2(80, 80) * EDSCALE);
  3095. rotation_control->set_h_size_flags(SIZE_SHRINK_END);
  3096. rotation_control->set_viewport(this);
  3097. top_right_vbox->add_child(rotation_control);
  3098. fps_label = memnew(Label);
  3099. fps_label->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, -90 * EDSCALE);
  3100. fps_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 10 * EDSCALE);
  3101. fps_label->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -10 * EDSCALE);
  3102. fps_label->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  3103. 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."));
  3104. fps_label->set_mouse_filter(MOUSE_FILTER_PASS); // Otherwise tooltip doesn't show.
  3105. top_right_vbox->add_child(fps_label);
  3106. fps_label->hide();
  3107. surface->add_child(top_right_vbox);
  3108. accept = NULL;
  3109. freelook_active = false;
  3110. freelook_speed = EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_base_speed");
  3111. selection_menu = memnew(PopupMenu);
  3112. add_child(selection_menu);
  3113. selection_menu->set_custom_minimum_size(Size2(100, 0) * EDSCALE);
  3114. selection_menu->connect("id_pressed", this, "_selection_result_pressed");
  3115. selection_menu->connect("popup_hide", this, "_selection_menu_hide");
  3116. if (p_index == 0) {
  3117. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER), true);
  3118. viewport->set_as_audio_listener(true);
  3119. }
  3120. name = "";
  3121. _update_name();
  3122. EditorSettings::get_singleton()->connect("settings_changed", this, "update_transform_gizmo_view");
  3123. }
  3124. //////////////////////////////////////////////////////////////
  3125. void SpatialEditorViewportContainer::_gui_input(const Ref<InputEvent> &p_event) {
  3126. Ref<InputEventMouseButton> mb = p_event;
  3127. if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT) {
  3128. if (mb->is_pressed()) {
  3129. Vector2 size = get_size();
  3130. int h_sep = get_constant("separation", "HSplitContainer");
  3131. int v_sep = get_constant("separation", "VSplitContainer");
  3132. int mid_w = size.width * ratio_h;
  3133. int mid_h = size.height * ratio_v;
  3134. dragging_h = mb->get_position().x > (mid_w - h_sep / 2) && mb->get_position().x < (mid_w + h_sep / 2);
  3135. dragging_v = mb->get_position().y > (mid_h - v_sep / 2) && mb->get_position().y < (mid_h + v_sep / 2);
  3136. drag_begin_pos = mb->get_position();
  3137. drag_begin_ratio.x = ratio_h;
  3138. drag_begin_ratio.y = ratio_v;
  3139. switch (view) {
  3140. case VIEW_USE_1_VIEWPORT: {
  3141. dragging_h = false;
  3142. dragging_v = false;
  3143. } break;
  3144. case VIEW_USE_2_VIEWPORTS: {
  3145. dragging_h = false;
  3146. } break;
  3147. case VIEW_USE_2_VIEWPORTS_ALT: {
  3148. dragging_v = false;
  3149. } break;
  3150. case VIEW_USE_3_VIEWPORTS:
  3151. case VIEW_USE_3_VIEWPORTS_ALT:
  3152. case VIEW_USE_4_VIEWPORTS: {
  3153. // Do nothing.
  3154. } break;
  3155. }
  3156. } else {
  3157. dragging_h = false;
  3158. dragging_v = false;
  3159. }
  3160. }
  3161. Ref<InputEventMouseMotion> mm = p_event;
  3162. if (mm.is_valid()) {
  3163. if (view == VIEW_USE_3_VIEWPORTS || view == VIEW_USE_3_VIEWPORTS_ALT || view == VIEW_USE_4_VIEWPORTS) {
  3164. Vector2 size = get_size();
  3165. int h_sep = get_constant("separation", "HSplitContainer");
  3166. int v_sep = get_constant("separation", "VSplitContainer");
  3167. int mid_w = size.width * ratio_h;
  3168. int mid_h = size.height * ratio_v;
  3169. bool was_hovering_h = hovering_h;
  3170. bool was_hovering_v = hovering_v;
  3171. hovering_h = mm->get_position().x > (mid_w - h_sep / 2) && mm->get_position().x < (mid_w + h_sep / 2);
  3172. hovering_v = mm->get_position().y > (mid_h - v_sep / 2) && mm->get_position().y < (mid_h + v_sep / 2);
  3173. if (was_hovering_h != hovering_h || was_hovering_v != hovering_v) {
  3174. update();
  3175. }
  3176. }
  3177. if (dragging_h) {
  3178. float new_ratio = drag_begin_ratio.x + (mm->get_position().x - drag_begin_pos.x) / get_size().width;
  3179. new_ratio = CLAMP(new_ratio, 40 / get_size().width, (get_size().width - 40) / get_size().width);
  3180. ratio_h = new_ratio;
  3181. queue_sort();
  3182. update();
  3183. }
  3184. if (dragging_v) {
  3185. float new_ratio = drag_begin_ratio.y + (mm->get_position().y - drag_begin_pos.y) / get_size().height;
  3186. new_ratio = CLAMP(new_ratio, 40 / get_size().height, (get_size().height - 40) / get_size().height);
  3187. ratio_v = new_ratio;
  3188. queue_sort();
  3189. update();
  3190. }
  3191. }
  3192. }
  3193. void SpatialEditorViewportContainer::_notification(int p_what) {
  3194. if (p_what == NOTIFICATION_MOUSE_ENTER || p_what == NOTIFICATION_MOUSE_EXIT) {
  3195. mouseover = (p_what == NOTIFICATION_MOUSE_ENTER);
  3196. update();
  3197. }
  3198. if (p_what == NOTIFICATION_DRAW && mouseover) {
  3199. Ref<Texture> h_grabber = get_icon("grabber", "HSplitContainer");
  3200. Ref<Texture> v_grabber = get_icon("grabber", "VSplitContainer");
  3201. Ref<Texture> hdiag_grabber = get_icon("GuiViewportHdiagsplitter", "EditorIcons");
  3202. Ref<Texture> vdiag_grabber = get_icon("GuiViewportVdiagsplitter", "EditorIcons");
  3203. Ref<Texture> vh_grabber = get_icon("GuiViewportVhsplitter", "EditorIcons");
  3204. Vector2 size = get_size();
  3205. int h_sep = get_constant("separation", "HSplitContainer");
  3206. int v_sep = get_constant("separation", "VSplitContainer");
  3207. int mid_w = size.width * ratio_h;
  3208. int mid_h = size.height * ratio_v;
  3209. int size_left = mid_w - h_sep / 2;
  3210. int size_bottom = size.height - mid_h - v_sep / 2;
  3211. switch (view) {
  3212. case VIEW_USE_1_VIEWPORT: {
  3213. // Nothing to show.
  3214. } break;
  3215. case VIEW_USE_2_VIEWPORTS: {
  3216. draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  3217. set_default_cursor_shape(CURSOR_VSPLIT);
  3218. } break;
  3219. case VIEW_USE_2_VIEWPORTS_ALT: {
  3220. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
  3221. set_default_cursor_shape(CURSOR_HSPLIT);
  3222. } break;
  3223. case VIEW_USE_3_VIEWPORTS: {
  3224. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  3225. draw_texture(hdiag_grabber, Vector2(mid_w - hdiag_grabber->get_width() / 2, mid_h - v_grabber->get_height() / 4));
  3226. set_default_cursor_shape(CURSOR_DRAG);
  3227. } else if ((hovering_v && !dragging_h) || dragging_v) {
  3228. draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  3229. set_default_cursor_shape(CURSOR_VSPLIT);
  3230. } else if (hovering_h || dragging_h) {
  3231. 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));
  3232. set_default_cursor_shape(CURSOR_HSPLIT);
  3233. }
  3234. } break;
  3235. case VIEW_USE_3_VIEWPORTS_ALT: {
  3236. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  3237. draw_texture(vdiag_grabber, Vector2(mid_w - vdiag_grabber->get_width() + v_grabber->get_height() / 4, mid_h - vdiag_grabber->get_height() / 2));
  3238. set_default_cursor_shape(CURSOR_DRAG);
  3239. } else if ((hovering_v && !dragging_h) || dragging_v) {
  3240. draw_texture(v_grabber, Vector2((size_left - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  3241. set_default_cursor_shape(CURSOR_VSPLIT);
  3242. } else if (hovering_h || dragging_h) {
  3243. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
  3244. set_default_cursor_shape(CURSOR_HSPLIT);
  3245. }
  3246. } break;
  3247. case VIEW_USE_4_VIEWPORTS: {
  3248. Vector2 half(mid_w, mid_h);
  3249. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  3250. draw_texture(vh_grabber, half - vh_grabber->get_size() / 2.0);
  3251. set_default_cursor_shape(CURSOR_DRAG);
  3252. } else if ((hovering_v && !dragging_h) || dragging_v) {
  3253. draw_texture(v_grabber, half - v_grabber->get_size() / 2.0);
  3254. set_default_cursor_shape(CURSOR_VSPLIT);
  3255. } else if (hovering_h || dragging_h) {
  3256. draw_texture(h_grabber, half - h_grabber->get_size() / 2.0);
  3257. set_default_cursor_shape(CURSOR_HSPLIT);
  3258. }
  3259. } break;
  3260. }
  3261. }
  3262. if (p_what == NOTIFICATION_SORT_CHILDREN) {
  3263. SpatialEditorViewport *viewports[4];
  3264. int vc = 0;
  3265. for (int i = 0; i < get_child_count(); i++) {
  3266. viewports[vc] = Object::cast_to<SpatialEditorViewport>(get_child(i));
  3267. if (viewports[vc]) {
  3268. vc++;
  3269. }
  3270. }
  3271. ERR_FAIL_COND(vc != 4);
  3272. Size2 size = get_size();
  3273. if (size.x < 10 || size.y < 10) {
  3274. for (int i = 0; i < 4; i++) {
  3275. viewports[i]->hide();
  3276. }
  3277. return;
  3278. }
  3279. int h_sep = get_constant("separation", "HSplitContainer");
  3280. int v_sep = get_constant("separation", "VSplitContainer");
  3281. int mid_w = size.width * ratio_h;
  3282. int mid_h = size.height * ratio_v;
  3283. int size_left = mid_w - h_sep / 2;
  3284. int size_right = size.width - mid_w - h_sep / 2;
  3285. int size_top = mid_h - v_sep / 2;
  3286. int size_bottom = size.height - mid_h - v_sep / 2;
  3287. switch (view) {
  3288. case VIEW_USE_1_VIEWPORT: {
  3289. viewports[0]->show();
  3290. for (int i = 1; i < 4; i++) {
  3291. viewports[i]->hide();
  3292. }
  3293. fit_child_in_rect(viewports[0], Rect2(Vector2(), size));
  3294. } break;
  3295. case VIEW_USE_2_VIEWPORTS: {
  3296. for (int i = 0; i < 4; i++) {
  3297. if (i == 1 || i == 3)
  3298. viewports[i]->hide();
  3299. else
  3300. viewports[i]->show();
  3301. }
  3302. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
  3303. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size.width, size_bottom)));
  3304. } break;
  3305. case VIEW_USE_2_VIEWPORTS_ALT: {
  3306. for (int i = 0; i < 4; i++) {
  3307. if (i == 1 || i == 3)
  3308. viewports[i]->hide();
  3309. else
  3310. viewports[i]->show();
  3311. }
  3312. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size.height)));
  3313. fit_child_in_rect(viewports[2], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
  3314. } break;
  3315. case VIEW_USE_3_VIEWPORTS: {
  3316. for (int i = 0; i < 4; i++) {
  3317. if (i == 1)
  3318. viewports[i]->hide();
  3319. else
  3320. viewports[i]->show();
  3321. }
  3322. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
  3323. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  3324. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
  3325. } break;
  3326. case VIEW_USE_3_VIEWPORTS_ALT: {
  3327. for (int i = 0; i < 4; i++) {
  3328. if (i == 1)
  3329. viewports[i]->hide();
  3330. else
  3331. viewports[i]->show();
  3332. }
  3333. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
  3334. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  3335. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
  3336. } break;
  3337. case VIEW_USE_4_VIEWPORTS: {
  3338. for (int i = 0; i < 4; i++) {
  3339. viewports[i]->show();
  3340. }
  3341. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
  3342. fit_child_in_rect(viewports[1], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size_top)));
  3343. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  3344. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
  3345. } break;
  3346. }
  3347. }
  3348. }
  3349. void SpatialEditorViewportContainer::set_view(View p_view) {
  3350. view = p_view;
  3351. queue_sort();
  3352. }
  3353. SpatialEditorViewportContainer::View SpatialEditorViewportContainer::get_view() {
  3354. return view;
  3355. }
  3356. void SpatialEditorViewportContainer::_bind_methods() {
  3357. ClassDB::bind_method("_gui_input", &SpatialEditorViewportContainer::_gui_input);
  3358. }
  3359. SpatialEditorViewportContainer::SpatialEditorViewportContainer() {
  3360. set_clip_contents(true);
  3361. view = VIEW_USE_1_VIEWPORT;
  3362. mouseover = false;
  3363. ratio_h = 0.5;
  3364. ratio_v = 0.5;
  3365. hovering_v = false;
  3366. hovering_h = false;
  3367. dragging_v = false;
  3368. dragging_h = false;
  3369. }
  3370. ///////////////////////////////////////////////////////////////////
  3371. SpatialEditor *SpatialEditor::singleton = NULL;
  3372. SpatialEditorSelectedItem::~SpatialEditorSelectedItem() {
  3373. if (sbox_instance.is_valid())
  3374. VisualServer::get_singleton()->free(sbox_instance);
  3375. }
  3376. void SpatialEditor::select_gizmo_highlight_axis(int p_axis) {
  3377. for (int i = 0; i < 3; i++) {
  3378. move_gizmo[i]->surface_set_material(0, i == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  3379. move_plane_gizmo[i]->surface_set_material(0, (i + 6) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
  3380. rotate_gizmo[i]->surface_set_material(0, (i + 3) == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  3381. scale_gizmo[i]->surface_set_material(0, (i + 9) == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  3382. scale_plane_gizmo[i]->surface_set_material(0, (i + 12) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
  3383. }
  3384. }
  3385. void SpatialEditor::update_transform_gizmo() {
  3386. List<Node *> &selection = editor_selection->get_selected_node_list();
  3387. AABB center;
  3388. bool first = true;
  3389. Basis gizmo_basis;
  3390. bool local_gizmo_coords = are_local_coords_enabled();
  3391. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3392. Spatial *sp = Object::cast_to<Spatial>(E->get());
  3393. if (!sp)
  3394. continue;
  3395. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  3396. if (!se)
  3397. continue;
  3398. Transform xf = se->sp->get_global_gizmo_transform();
  3399. if (first) {
  3400. center.position = xf.origin;
  3401. first = false;
  3402. if (local_gizmo_coords) {
  3403. gizmo_basis = xf.basis;
  3404. gizmo_basis.orthonormalize();
  3405. }
  3406. } else {
  3407. center.expand_to(xf.origin);
  3408. gizmo_basis = Basis();
  3409. }
  3410. }
  3411. Vector3 pcenter = center.position + center.size * 0.5;
  3412. gizmo.visible = !first;
  3413. gizmo.transform.origin = pcenter;
  3414. gizmo.transform.basis = gizmo_basis;
  3415. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  3416. viewports[i]->update_transform_gizmo_view();
  3417. }
  3418. }
  3419. void _update_all_gizmos(Node *p_node) {
  3420. for (int i = p_node->get_child_count() - 1; 0 <= i; --i) {
  3421. Spatial *spatial_node = Object::cast_to<Spatial>(p_node->get_child(i));
  3422. if (spatial_node) {
  3423. spatial_node->update_gizmo();
  3424. }
  3425. _update_all_gizmos(p_node->get_child(i));
  3426. }
  3427. }
  3428. void SpatialEditor::update_all_gizmos(Node *p_node) {
  3429. if (!p_node) {
  3430. p_node = SceneTree::get_singleton()->get_root();
  3431. }
  3432. _update_all_gizmos(p_node);
  3433. }
  3434. Object *SpatialEditor::_get_editor_data(Object *p_what) {
  3435. Spatial *sp = Object::cast_to<Spatial>(p_what);
  3436. if (!sp)
  3437. return NULL;
  3438. SpatialEditorSelectedItem *si = memnew(SpatialEditorSelectedItem);
  3439. si->sp = sp;
  3440. si->sbox_instance = VisualServer::get_singleton()->instance_create2(selection_box->get_rid(), sp->get_world()->get_scenario());
  3441. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(si->sbox_instance, VS::SHADOW_CASTING_SETTING_OFF);
  3442. return si;
  3443. }
  3444. void SpatialEditor::_generate_selection_box() {
  3445. AABB aabb(Vector3(), Vector3(1, 1, 1));
  3446. aabb.grow_by(aabb.get_longest_axis_size() / 20.0);
  3447. Ref<SurfaceTool> st = memnew(SurfaceTool);
  3448. st->begin(Mesh::PRIMITIVE_LINES);
  3449. for (int i = 0; i < 12; i++) {
  3450. Vector3 a, b;
  3451. aabb.get_edge(i, a, b);
  3452. st->add_color(Color(1.0, 1.0, 0.8, 0.8));
  3453. st->add_vertex(a);
  3454. st->add_color(Color(1.0, 1.0, 0.8, 0.4));
  3455. st->add_vertex(a.linear_interpolate(b, 0.2));
  3456. st->add_color(Color(1.0, 1.0, 0.8, 0.4));
  3457. st->add_vertex(a.linear_interpolate(b, 0.8));
  3458. st->add_color(Color(1.0, 1.0, 0.8, 0.8));
  3459. st->add_vertex(b);
  3460. }
  3461. Ref<SpatialMaterial> mat = memnew(SpatialMaterial);
  3462. mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  3463. mat->set_albedo(Color(1, 1, 1));
  3464. mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  3465. mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  3466. mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  3467. st->set_material(mat);
  3468. selection_box = st->commit();
  3469. }
  3470. Dictionary SpatialEditor::get_state() const {
  3471. Dictionary d;
  3472. d["snap_enabled"] = snap_enabled;
  3473. d["translate_snap"] = get_translate_snap();
  3474. d["rotate_snap"] = get_rotate_snap();
  3475. d["scale_snap"] = get_scale_snap();
  3476. d["local_coords"] = tool_option_button[TOOL_OPT_LOCAL_COORDS]->is_pressed();
  3477. int vc = 0;
  3478. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT)))
  3479. vc = 1;
  3480. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS)))
  3481. vc = 2;
  3482. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS)))
  3483. vc = 3;
  3484. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS)))
  3485. vc = 4;
  3486. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT)))
  3487. vc = 5;
  3488. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT)))
  3489. vc = 6;
  3490. d["viewport_mode"] = vc;
  3491. Array vpdata;
  3492. for (int i = 0; i < 4; i++) {
  3493. vpdata.push_back(viewports[i]->get_state());
  3494. }
  3495. d["viewports"] = vpdata;
  3496. d["show_grid"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID));
  3497. d["show_origin"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN));
  3498. d["fov"] = get_fov();
  3499. d["znear"] = get_znear();
  3500. d["zfar"] = get_zfar();
  3501. Dictionary gizmos_status;
  3502. for (int i = 0; i < gizmo_plugins_by_name.size(); i++) {
  3503. if (!gizmo_plugins_by_name[i]->can_be_hidden()) continue;
  3504. int state = gizmos_menu->get_item_state(gizmos_menu->get_item_index(i));
  3505. String name = gizmo_plugins_by_name[i]->get_name();
  3506. gizmos_status[name] = state;
  3507. }
  3508. d["gizmos_status"] = gizmos_status;
  3509. return d;
  3510. }
  3511. void SpatialEditor::set_state(const Dictionary &p_state) {
  3512. Dictionary d = p_state;
  3513. if (d.has("snap_enabled")) {
  3514. snap_enabled = d["snap_enabled"];
  3515. tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(d["snap_enabled"]);
  3516. }
  3517. if (d.has("translate_snap"))
  3518. snap_translate_value = d["translate_snap"];
  3519. if (d.has("rotate_snap"))
  3520. snap_rotate_value = d["rotate_snap"];
  3521. if (d.has("scale_snap"))
  3522. snap_scale_value = d["scale_snap"];
  3523. _snap_update();
  3524. if (d.has("local_coords")) {
  3525. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(d["local_coords"]);
  3526. update_transform_gizmo();
  3527. }
  3528. if (d.has("viewport_mode")) {
  3529. int vc = d["viewport_mode"];
  3530. if (vc == 1)
  3531. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  3532. else if (vc == 2)
  3533. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
  3534. else if (vc == 3)
  3535. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
  3536. else if (vc == 4)
  3537. _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
  3538. else if (vc == 5)
  3539. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
  3540. else if (vc == 6)
  3541. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
  3542. }
  3543. if (d.has("viewports")) {
  3544. Array vp = d["viewports"];
  3545. uint32_t vp_size = static_cast<uint32_t>(vp.size());
  3546. if (vp_size > VIEWPORTS_COUNT) {
  3547. WARN_PRINT("Ignoring superfluous viewport settings from spatial editor state.");
  3548. vp_size = VIEWPORTS_COUNT;
  3549. }
  3550. for (uint32_t i = 0; i < vp_size; i++) {
  3551. viewports[i]->set_state(vp[i]);
  3552. }
  3553. }
  3554. if (d.has("zfar"))
  3555. settings_zfar->set_value(float(d["zfar"]));
  3556. if (d.has("znear"))
  3557. settings_znear->set_value(float(d["znear"]));
  3558. if (d.has("fov"))
  3559. settings_fov->set_value(float(d["fov"]));
  3560. if (d.has("show_grid")) {
  3561. bool use = d["show_grid"];
  3562. if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID))) {
  3563. _menu_item_pressed(MENU_VIEW_GRID);
  3564. }
  3565. }
  3566. if (d.has("show_origin")) {
  3567. bool use = d["show_origin"];
  3568. if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN))) {
  3569. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), use);
  3570. VisualServer::get_singleton()->instance_set_visible(origin_instance, use);
  3571. }
  3572. }
  3573. if (d.has("gizmos_status")) {
  3574. Dictionary gizmos_status = d["gizmos_status"];
  3575. List<Variant> keys;
  3576. gizmos_status.get_key_list(&keys);
  3577. for (int j = 0; j < gizmo_plugins_by_name.size(); ++j) {
  3578. if (!gizmo_plugins_by_name[j]->can_be_hidden()) continue;
  3579. int state = EditorSpatialGizmoPlugin::VISIBLE;
  3580. for (int i = 0; i < keys.size(); i++) {
  3581. if (gizmo_plugins_by_name.write[j]->get_name() == keys[i]) {
  3582. state = gizmos_status[keys[i]];
  3583. break;
  3584. }
  3585. }
  3586. gizmo_plugins_by_name.write[j]->set_state(state);
  3587. }
  3588. _update_gizmos_menu();
  3589. }
  3590. }
  3591. void SpatialEditor::edit(Spatial *p_spatial) {
  3592. if (p_spatial != selected) {
  3593. if (selected) {
  3594. Ref<EditorSpatialGizmo> seg = selected->get_gizmo();
  3595. if (seg.is_valid()) {
  3596. seg->set_selected(false);
  3597. selected->update_gizmo();
  3598. }
  3599. }
  3600. selected = p_spatial;
  3601. over_gizmo_handle = -1;
  3602. if (selected) {
  3603. Ref<EditorSpatialGizmo> seg = selected->get_gizmo();
  3604. if (seg.is_valid()) {
  3605. seg->set_selected(true);
  3606. selected->update_gizmo();
  3607. }
  3608. }
  3609. }
  3610. }
  3611. void SpatialEditor::_snap_changed() {
  3612. snap_translate_value = snap_translate->get_text().to_double();
  3613. snap_rotate_value = snap_rotate->get_text().to_double();
  3614. snap_scale_value = snap_scale->get_text().to_double();
  3615. }
  3616. void SpatialEditor::_snap_update() {
  3617. snap_translate->set_text(String::num(snap_translate_value));
  3618. snap_rotate->set_text(String::num(snap_rotate_value));
  3619. snap_scale->set_text(String::num(snap_scale_value));
  3620. }
  3621. void SpatialEditor::_xform_dialog_action() {
  3622. Transform t;
  3623. //translation
  3624. Vector3 scale;
  3625. Vector3 rotate;
  3626. Vector3 translate;
  3627. for (int i = 0; i < 3; i++) {
  3628. translate[i] = xform_translate[i]->get_text().to_double();
  3629. rotate[i] = Math::deg2rad(xform_rotate[i]->get_text().to_double());
  3630. scale[i] = xform_scale[i]->get_text().to_double();
  3631. }
  3632. t.basis.scale(scale);
  3633. t.basis.rotate(rotate);
  3634. t.origin = translate;
  3635. undo_redo->create_action(TTR("XForm Dialog"));
  3636. List<Node *> &selection = editor_selection->get_selected_node_list();
  3637. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3638. Spatial *sp = Object::cast_to<Spatial>(E->get());
  3639. if (!sp)
  3640. continue;
  3641. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  3642. if (!se)
  3643. continue;
  3644. bool post = xform_type->get_selected() > 0;
  3645. Transform tr = sp->get_global_gizmo_transform();
  3646. if (post)
  3647. tr = tr * t;
  3648. else {
  3649. tr.basis = t.basis * tr.basis;
  3650. tr.origin += t.origin;
  3651. }
  3652. undo_redo->add_do_method(sp, "set_global_transform", tr);
  3653. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
  3654. }
  3655. undo_redo->commit_action();
  3656. }
  3657. void SpatialEditor::_menu_item_toggled(bool pressed, int p_option) {
  3658. switch (p_option) {
  3659. case MENU_TOOL_LOCAL_COORDS: {
  3660. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(pressed);
  3661. update_transform_gizmo();
  3662. } break;
  3663. case MENU_TOOL_USE_SNAP: {
  3664. tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(pressed);
  3665. snap_enabled = pressed;
  3666. } break;
  3667. case MENU_TOOL_OVERRIDE_CAMERA: {
  3668. ScriptEditorDebugger *const debugger = ScriptEditor::get_singleton()->get_debugger();
  3669. if (pressed) {
  3670. using Override = ScriptEditorDebugger::CameraOverride;
  3671. debugger->set_camera_override((Override)(Override::OVERRIDE_3D_1 + camera_override_viewport_id));
  3672. } else {
  3673. debugger->set_camera_override(ScriptEditorDebugger::OVERRIDE_NONE);
  3674. }
  3675. } break;
  3676. }
  3677. }
  3678. void SpatialEditor::_menu_gizmo_toggled(int p_option) {
  3679. const int idx = gizmos_menu->get_item_index(p_option);
  3680. gizmos_menu->toggle_item_multistate(idx);
  3681. // Change icon
  3682. const int state = gizmos_menu->get_item_state(idx);
  3683. switch (state) {
  3684. case EditorSpatialGizmoPlugin::VISIBLE:
  3685. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_icon("visibility_visible"));
  3686. break;
  3687. case EditorSpatialGizmoPlugin::ON_TOP:
  3688. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_icon("visibility_xray"));
  3689. break;
  3690. case EditorSpatialGizmoPlugin::HIDDEN:
  3691. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_icon("visibility_hidden"));
  3692. break;
  3693. }
  3694. gizmo_plugins_by_name.write[p_option]->set_state(state);
  3695. update_all_gizmos();
  3696. }
  3697. void SpatialEditor::_update_camera_override_button(bool p_game_running) {
  3698. Button *const button = tool_option_button[TOOL_OPT_OVERRIDE_CAMERA];
  3699. if (p_game_running) {
  3700. button->set_disabled(false);
  3701. button->set_tooltip(TTR("Game Camera Override\nNo game instance running."));
  3702. } else {
  3703. button->set_disabled(true);
  3704. button->set_pressed(false);
  3705. button->set_tooltip(TTR("Game Camera Override\nOverrides game camera with editor viewport camera."));
  3706. }
  3707. }
  3708. void SpatialEditor::_update_camera_override_viewport(Object *p_viewport) {
  3709. SpatialEditorViewport *current_viewport = Object::cast_to<SpatialEditorViewport>(p_viewport);
  3710. if (!current_viewport)
  3711. return;
  3712. ScriptEditorDebugger *const debugger = ScriptEditor::get_singleton()->get_debugger();
  3713. camera_override_viewport_id = current_viewport->index;
  3714. if (debugger->get_camera_override() >= ScriptEditorDebugger::OVERRIDE_3D_1) {
  3715. using Override = ScriptEditorDebugger::CameraOverride;
  3716. debugger->set_camera_override((Override)(Override::OVERRIDE_3D_1 + camera_override_viewport_id));
  3717. }
  3718. }
  3719. void SpatialEditor::_menu_item_pressed(int p_option) {
  3720. switch (p_option) {
  3721. case MENU_TOOL_SELECT:
  3722. case MENU_TOOL_MOVE:
  3723. case MENU_TOOL_ROTATE:
  3724. case MENU_TOOL_SCALE:
  3725. case MENU_TOOL_LIST_SELECT: {
  3726. for (int i = 0; i < TOOL_MAX; i++)
  3727. tool_button[i]->set_pressed(i == p_option);
  3728. tool_mode = (ToolMode)p_option;
  3729. update_transform_gizmo();
  3730. } break;
  3731. case MENU_TRANSFORM_CONFIGURE_SNAP: {
  3732. snap_dialog->popup_centered(Size2(200, 180));
  3733. } break;
  3734. case MENU_TRANSFORM_DIALOG: {
  3735. for (int i = 0; i < 3; i++) {
  3736. xform_translate[i]->set_text("0");
  3737. xform_rotate[i]->set_text("0");
  3738. xform_scale[i]->set_text("1");
  3739. }
  3740. xform_dialog->popup_centered(Size2(320, 240) * EDSCALE);
  3741. } break;
  3742. case MENU_VIEW_USE_1_VIEWPORT: {
  3743. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_1_VIEWPORT);
  3744. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), true);
  3745. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  3746. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  3747. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  3748. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  3749. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  3750. } break;
  3751. case MENU_VIEW_USE_2_VIEWPORTS: {
  3752. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_2_VIEWPORTS);
  3753. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  3754. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), true);
  3755. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  3756. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  3757. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  3758. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  3759. } break;
  3760. case MENU_VIEW_USE_2_VIEWPORTS_ALT: {
  3761. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_2_VIEWPORTS_ALT);
  3762. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  3763. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  3764. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  3765. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  3766. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), true);
  3767. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  3768. } break;
  3769. case MENU_VIEW_USE_3_VIEWPORTS: {
  3770. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_3_VIEWPORTS);
  3771. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  3772. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  3773. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), true);
  3774. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  3775. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  3776. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  3777. } break;
  3778. case MENU_VIEW_USE_3_VIEWPORTS_ALT: {
  3779. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_3_VIEWPORTS_ALT);
  3780. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  3781. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  3782. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  3783. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  3784. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  3785. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), true);
  3786. } break;
  3787. case MENU_VIEW_USE_4_VIEWPORTS: {
  3788. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_4_VIEWPORTS);
  3789. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  3790. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  3791. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  3792. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), true);
  3793. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  3794. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  3795. } break;
  3796. case MENU_VIEW_ORIGIN: {
  3797. bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
  3798. origin_enabled = !is_checked;
  3799. VisualServer::get_singleton()->instance_set_visible(origin_instance, origin_enabled);
  3800. // Update the grid since its appearance depends on whether the origin is enabled
  3801. _finish_grid();
  3802. _init_grid();
  3803. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), origin_enabled);
  3804. } break;
  3805. case MENU_VIEW_GRID: {
  3806. bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
  3807. grid_enabled = !is_checked;
  3808. for (int i = 0; i < 3; ++i) {
  3809. if (grid_enable[i]) {
  3810. VisualServer::get_singleton()->instance_set_visible(grid_instance[i], grid_enabled);
  3811. grid_visible[i] = grid_enabled;
  3812. }
  3813. }
  3814. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), grid_enabled);
  3815. } break;
  3816. case MENU_VIEW_CAMERA_SETTINGS: {
  3817. settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size() + Size2(50, 50));
  3818. } break;
  3819. case MENU_SNAP_TO_FLOOR: {
  3820. snap_selected_nodes_to_floor();
  3821. } break;
  3822. case MENU_LOCK_SELECTED: {
  3823. undo_redo->create_action(TTR("Lock Selected"));
  3824. List<Node *> &selection = editor_selection->get_selected_node_list();
  3825. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3826. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  3827. if (!spatial || !spatial->is_visible_in_tree())
  3828. continue;
  3829. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root())
  3830. continue;
  3831. undo_redo->add_do_method(spatial, "set_meta", "_edit_lock_", true);
  3832. undo_redo->add_undo_method(spatial, "remove_meta", "_edit_lock_");
  3833. undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
  3834. undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
  3835. }
  3836. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  3837. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  3838. undo_redo->commit_action();
  3839. } break;
  3840. case MENU_UNLOCK_SELECTED: {
  3841. undo_redo->create_action(TTR("Unlock Selected"));
  3842. List<Node *> &selection = editor_selection->get_selected_node_list();
  3843. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3844. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  3845. if (!spatial || !spatial->is_visible_in_tree())
  3846. continue;
  3847. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root())
  3848. continue;
  3849. undo_redo->add_do_method(spatial, "remove_meta", "_edit_lock_");
  3850. undo_redo->add_undo_method(spatial, "set_meta", "_edit_lock_", true);
  3851. undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
  3852. undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
  3853. }
  3854. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  3855. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  3856. undo_redo->commit_action();
  3857. } break;
  3858. case MENU_GROUP_SELECTED: {
  3859. undo_redo->create_action(TTR("Group Selected"));
  3860. List<Node *> &selection = editor_selection->get_selected_node_list();
  3861. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3862. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  3863. if (!spatial || !spatial->is_visible_in_tree())
  3864. continue;
  3865. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root())
  3866. continue;
  3867. undo_redo->add_do_method(spatial, "set_meta", "_edit_group_", true);
  3868. undo_redo->add_undo_method(spatial, "remove_meta", "_edit_group_");
  3869. undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
  3870. undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
  3871. }
  3872. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  3873. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  3874. undo_redo->commit_action();
  3875. } break;
  3876. case MENU_UNGROUP_SELECTED: {
  3877. undo_redo->create_action(TTR("Ungroup Selected"));
  3878. List<Node *> &selection = editor_selection->get_selected_node_list();
  3879. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3880. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  3881. if (!spatial || !spatial->is_visible_in_tree())
  3882. continue;
  3883. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root())
  3884. continue;
  3885. undo_redo->add_do_method(spatial, "remove_meta", "_edit_group_");
  3886. undo_redo->add_undo_method(spatial, "set_meta", "_edit_group_", true);
  3887. undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
  3888. undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
  3889. }
  3890. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  3891. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  3892. undo_redo->commit_action();
  3893. } break;
  3894. }
  3895. }
  3896. void SpatialEditor::_init_indicators() {
  3897. {
  3898. origin_enabled = true;
  3899. grid_enabled = true;
  3900. indicator_mat.instance();
  3901. indicator_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  3902. indicator_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  3903. indicator_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  3904. Vector<Color> origin_colors;
  3905. Vector<Vector3> origin_points;
  3906. for (int i = 0; i < 3; i++) {
  3907. Vector3 axis;
  3908. axis[i] = 1;
  3909. Color origin_color;
  3910. switch (i) {
  3911. case 0:
  3912. origin_color = get_color("axis_x_color", "Editor");
  3913. break;
  3914. case 1:
  3915. origin_color = get_color("axis_y_color", "Editor");
  3916. break;
  3917. case 2:
  3918. origin_color = get_color("axis_z_color", "Editor");
  3919. break;
  3920. default:
  3921. origin_color = Color();
  3922. break;
  3923. }
  3924. grid_enable[i] = false;
  3925. grid_visible[i] = false;
  3926. origin_colors.push_back(origin_color);
  3927. origin_colors.push_back(origin_color);
  3928. origin_points.push_back(axis * 4096);
  3929. origin_points.push_back(axis * -4096);
  3930. }
  3931. grid_enable[1] = true;
  3932. grid_visible[1] = true;
  3933. _init_grid();
  3934. origin = VisualServer::get_singleton()->mesh_create();
  3935. Array d;
  3936. d.resize(VS::ARRAY_MAX);
  3937. d[VisualServer::ARRAY_VERTEX] = origin_points;
  3938. d[VisualServer::ARRAY_COLOR] = origin_colors;
  3939. VisualServer::get_singleton()->mesh_add_surface_from_arrays(origin, VisualServer::PRIMITIVE_LINES, d);
  3940. VisualServer::get_singleton()->mesh_surface_set_material(origin, 0, indicator_mat->get_rid());
  3941. origin_instance = VisualServer::get_singleton()->instance_create2(origin, get_tree()->get_root()->get_world()->get_scenario());
  3942. VS::get_singleton()->instance_set_layer_mask(origin_instance, 1 << SpatialEditorViewport::GIZMO_GRID_LAYER);
  3943. VisualServer::get_singleton()->instance_geometry_set_cast_shadows_setting(origin_instance, VS::SHADOW_CASTING_SETTING_OFF);
  3944. }
  3945. {
  3946. //move gizmo
  3947. for (int i = 0; i < 3; i++) {
  3948. Color col;
  3949. switch (i) {
  3950. case 0:
  3951. col = get_color("axis_x_color", "Editor");
  3952. break;
  3953. case 1:
  3954. col = get_color("axis_y_color", "Editor");
  3955. break;
  3956. case 2:
  3957. col = get_color("axis_z_color", "Editor");
  3958. break;
  3959. default:
  3960. col = Color();
  3961. break;
  3962. }
  3963. col.a = EditorSettings::get_singleton()->get("editors/3d/manipulator_gizmo_opacity");
  3964. move_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  3965. move_plane_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  3966. rotate_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  3967. scale_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  3968. scale_plane_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  3969. Ref<SpatialMaterial> mat = memnew(SpatialMaterial);
  3970. mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  3971. mat->set_on_top_of_alpha();
  3972. mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  3973. mat->set_albedo(col);
  3974. gizmo_color[i] = mat;
  3975. Ref<SpatialMaterial> mat_hl = mat->duplicate();
  3976. mat_hl->set_albedo(Color(col.r, col.g, col.b, 1.0));
  3977. gizmo_color_hl[i] = mat_hl;
  3978. Vector3 ivec;
  3979. ivec[i] = 1;
  3980. Vector3 nivec;
  3981. nivec[(i + 1) % 3] = 1;
  3982. nivec[(i + 2) % 3] = 1;
  3983. Vector3 ivec2;
  3984. ivec2[(i + 1) % 3] = 1;
  3985. Vector3 ivec3;
  3986. ivec3[(i + 2) % 3] = 1;
  3987. //translate
  3988. {
  3989. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  3990. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  3991. // Arrow profile
  3992. const int arrow_points = 5;
  3993. Vector3 arrow[5] = {
  3994. nivec * 0.0 + ivec * 0.0,
  3995. nivec * 0.01 + ivec * 0.0,
  3996. nivec * 0.01 + ivec * GIZMO_ARROW_OFFSET,
  3997. nivec * 0.065 + ivec * GIZMO_ARROW_OFFSET,
  3998. nivec * 0.0 + ivec * (GIZMO_ARROW_OFFSET + GIZMO_ARROW_SIZE),
  3999. };
  4000. int arrow_sides = 16;
  4001. for (int k = 0; k < arrow_sides; k++) {
  4002. Basis ma(ivec, Math_PI * 2 * float(k) / arrow_sides);
  4003. Basis mb(ivec, Math_PI * 2 * float(k + 1) / arrow_sides);
  4004. for (int j = 0; j < arrow_points - 1; j++) {
  4005. Vector3 points[4] = {
  4006. ma.xform(arrow[j]),
  4007. mb.xform(arrow[j]),
  4008. mb.xform(arrow[j + 1]),
  4009. ma.xform(arrow[j + 1]),
  4010. };
  4011. surftool->add_vertex(points[0]);
  4012. surftool->add_vertex(points[1]);
  4013. surftool->add_vertex(points[2]);
  4014. surftool->add_vertex(points[0]);
  4015. surftool->add_vertex(points[2]);
  4016. surftool->add_vertex(points[3]);
  4017. }
  4018. }
  4019. surftool->set_material(mat);
  4020. surftool->commit(move_gizmo[i]);
  4021. }
  4022. // Plane Translation
  4023. {
  4024. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  4025. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  4026. Vector3 vec = ivec2 - ivec3;
  4027. Vector3 plane[4] = {
  4028. vec * GIZMO_PLANE_DST,
  4029. vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
  4030. vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
  4031. vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
  4032. };
  4033. Basis ma(ivec, Math_PI / 2);
  4034. Vector3 points[4] = {
  4035. ma.xform(plane[0]),
  4036. ma.xform(plane[1]),
  4037. ma.xform(plane[2]),
  4038. ma.xform(plane[3]),
  4039. };
  4040. surftool->add_vertex(points[0]);
  4041. surftool->add_vertex(points[1]);
  4042. surftool->add_vertex(points[2]);
  4043. surftool->add_vertex(points[0]);
  4044. surftool->add_vertex(points[2]);
  4045. surftool->add_vertex(points[3]);
  4046. Ref<SpatialMaterial> plane_mat = memnew(SpatialMaterial);
  4047. plane_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  4048. plane_mat->set_on_top_of_alpha();
  4049. plane_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  4050. plane_mat->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  4051. plane_mat->set_albedo(col);
  4052. plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides
  4053. surftool->set_material(plane_mat);
  4054. surftool->commit(move_plane_gizmo[i]);
  4055. Ref<SpatialMaterial> plane_mat_hl = plane_mat->duplicate();
  4056. plane_mat_hl->set_albedo(Color(col.r, col.g, col.b, 1.0));
  4057. plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
  4058. }
  4059. // Rotate
  4060. {
  4061. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  4062. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  4063. Vector3 circle[5] = {
  4064. ivec * 0.02 + ivec2 * 0.02 + ivec2 * GIZMO_CIRCLE_SIZE,
  4065. ivec * -0.02 + ivec2 * 0.02 + ivec2 * GIZMO_CIRCLE_SIZE,
  4066. ivec * -0.02 + ivec2 * -0.02 + ivec2 * GIZMO_CIRCLE_SIZE,
  4067. ivec * 0.02 + ivec2 * -0.02 + ivec2 * GIZMO_CIRCLE_SIZE,
  4068. ivec * 0.02 + ivec2 * 0.02 + ivec2 * GIZMO_CIRCLE_SIZE,
  4069. };
  4070. for (int k = 0; k < 64; k++) {
  4071. Basis ma(ivec, Math_PI * 2 * float(k) / 64);
  4072. Basis mb(ivec, Math_PI * 2 * float(k + 1) / 64);
  4073. for (int j = 0; j < 4; j++) {
  4074. Vector3 points[4] = {
  4075. ma.xform(circle[j]),
  4076. mb.xform(circle[j]),
  4077. mb.xform(circle[j + 1]),
  4078. ma.xform(circle[j + 1]),
  4079. };
  4080. surftool->add_vertex(points[0]);
  4081. surftool->add_vertex(points[1]);
  4082. surftool->add_vertex(points[2]);
  4083. surftool->add_vertex(points[0]);
  4084. surftool->add_vertex(points[2]);
  4085. surftool->add_vertex(points[3]);
  4086. }
  4087. }
  4088. surftool->set_material(mat);
  4089. surftool->commit(rotate_gizmo[i]);
  4090. }
  4091. // Scale
  4092. {
  4093. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  4094. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  4095. // Cube arrow profile
  4096. const int arrow_points = 6;
  4097. Vector3 arrow[6] = {
  4098. nivec * 0.0 + ivec * 0.0,
  4099. nivec * 0.01 + ivec * 0.0,
  4100. nivec * 0.01 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
  4101. nivec * 0.07 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
  4102. nivec * 0.07 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
  4103. nivec * 0.0 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
  4104. };
  4105. int arrow_sides = 4;
  4106. for (int k = 0; k < 4; k++) {
  4107. Basis ma(ivec, Math_PI * 2 * float(k) / arrow_sides);
  4108. Basis mb(ivec, Math_PI * 2 * float(k + 1) / arrow_sides);
  4109. for (int j = 0; j < arrow_points - 1; j++) {
  4110. Vector3 points[4] = {
  4111. ma.xform(arrow[j]),
  4112. mb.xform(arrow[j]),
  4113. mb.xform(arrow[j + 1]),
  4114. ma.xform(arrow[j + 1]),
  4115. };
  4116. surftool->add_vertex(points[0]);
  4117. surftool->add_vertex(points[1]);
  4118. surftool->add_vertex(points[2]);
  4119. surftool->add_vertex(points[0]);
  4120. surftool->add_vertex(points[2]);
  4121. surftool->add_vertex(points[3]);
  4122. }
  4123. }
  4124. surftool->set_material(mat);
  4125. surftool->commit(scale_gizmo[i]);
  4126. }
  4127. // Plane Scale
  4128. {
  4129. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  4130. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  4131. Vector3 vec = ivec2 - ivec3;
  4132. Vector3 plane[4] = {
  4133. vec * GIZMO_PLANE_DST,
  4134. vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
  4135. vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
  4136. vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
  4137. };
  4138. Basis ma(ivec, Math_PI / 2);
  4139. Vector3 points[4] = {
  4140. ma.xform(plane[0]),
  4141. ma.xform(plane[1]),
  4142. ma.xform(plane[2]),
  4143. ma.xform(plane[3]),
  4144. };
  4145. surftool->add_vertex(points[0]);
  4146. surftool->add_vertex(points[1]);
  4147. surftool->add_vertex(points[2]);
  4148. surftool->add_vertex(points[0]);
  4149. surftool->add_vertex(points[2]);
  4150. surftool->add_vertex(points[3]);
  4151. Ref<SpatialMaterial> plane_mat = memnew(SpatialMaterial);
  4152. plane_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  4153. plane_mat->set_on_top_of_alpha();
  4154. plane_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  4155. plane_mat->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  4156. plane_mat->set_albedo(col);
  4157. plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides
  4158. surftool->set_material(plane_mat);
  4159. surftool->commit(scale_plane_gizmo[i]);
  4160. Ref<SpatialMaterial> plane_mat_hl = plane_mat->duplicate();
  4161. plane_mat_hl->set_albedo(Color(col.r, col.g, col.b, 1.0));
  4162. plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
  4163. }
  4164. }
  4165. }
  4166. _generate_selection_box();
  4167. }
  4168. void SpatialEditor::_update_gizmos_menu() {
  4169. gizmos_menu->clear();
  4170. for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
  4171. if (!gizmo_plugins_by_name[i]->can_be_hidden()) continue;
  4172. String plugin_name = gizmo_plugins_by_name[i]->get_name();
  4173. const int plugin_state = gizmo_plugins_by_name[i]->get_state();
  4174. gizmos_menu->add_multistate_item(TTR(plugin_name), 3, plugin_state, i);
  4175. const int idx = gizmos_menu->get_item_index(i);
  4176. switch (plugin_state) {
  4177. case EditorSpatialGizmoPlugin::VISIBLE:
  4178. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_visible"));
  4179. break;
  4180. case EditorSpatialGizmoPlugin::ON_TOP:
  4181. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_xray"));
  4182. break;
  4183. case EditorSpatialGizmoPlugin::HIDDEN:
  4184. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_hidden"));
  4185. break;
  4186. }
  4187. }
  4188. }
  4189. void SpatialEditor::_update_gizmos_menu_theme() {
  4190. for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
  4191. if (!gizmo_plugins_by_name[i]->can_be_hidden()) continue;
  4192. const int plugin_state = gizmo_plugins_by_name[i]->get_state();
  4193. const int idx = gizmos_menu->get_item_index(i);
  4194. switch (plugin_state) {
  4195. case EditorSpatialGizmoPlugin::VISIBLE:
  4196. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_visible"));
  4197. break;
  4198. case EditorSpatialGizmoPlugin::ON_TOP:
  4199. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_xray"));
  4200. break;
  4201. case EditorSpatialGizmoPlugin::HIDDEN:
  4202. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_hidden"));
  4203. break;
  4204. }
  4205. }
  4206. }
  4207. void SpatialEditor::_init_grid() {
  4208. PoolVector<Color> grid_colors[3];
  4209. PoolVector<Vector3> grid_points[3];
  4210. Color primary_grid_color = EditorSettings::get_singleton()->get("editors/3d/primary_grid_color");
  4211. Color secondary_grid_color = EditorSettings::get_singleton()->get("editors/3d/secondary_grid_color");
  4212. int grid_size = EditorSettings::get_singleton()->get("editors/3d/grid_size");
  4213. int primary_grid_steps = EditorSettings::get_singleton()->get("editors/3d/primary_grid_steps");
  4214. for (int i = 0; i < 3; i++) {
  4215. Vector3 axis;
  4216. axis[i] = 1;
  4217. Vector3 axis_n1;
  4218. axis_n1[(i + 1) % 3] = 1;
  4219. Vector3 axis_n2;
  4220. axis_n2[(i + 2) % 3] = 1;
  4221. for (int j = -grid_size; j <= grid_size; j++) {
  4222. Vector3 p1 = axis_n1 * j + axis_n2 * -grid_size;
  4223. Vector3 p1_dest = p1 * (-axis_n2 + axis_n1);
  4224. Vector3 p2 = axis_n2 * j + axis_n1 * -grid_size;
  4225. Vector3 p2_dest = p2 * (-axis_n1 + axis_n2);
  4226. Color line_color = secondary_grid_color;
  4227. if (origin_enabled && j == 0) {
  4228. // Don't draw the center lines of the grid if the origin is enabled
  4229. // The origin would overlap the grid lines in this case, causing flickering
  4230. continue;
  4231. } else if (j % primary_grid_steps == 0) {
  4232. line_color = primary_grid_color;
  4233. }
  4234. grid_points[i].push_back(p1);
  4235. grid_points[i].push_back(p1_dest);
  4236. grid_colors[i].push_back(line_color);
  4237. grid_colors[i].push_back(line_color);
  4238. grid_points[i].push_back(p2);
  4239. grid_points[i].push_back(p2_dest);
  4240. grid_colors[i].push_back(line_color);
  4241. grid_colors[i].push_back(line_color);
  4242. }
  4243. grid[i] = VisualServer::get_singleton()->mesh_create();
  4244. Array d;
  4245. d.resize(VS::ARRAY_MAX);
  4246. d[VisualServer::ARRAY_VERTEX] = grid_points[i];
  4247. d[VisualServer::ARRAY_COLOR] = grid_colors[i];
  4248. VisualServer::get_singleton()->mesh_add_surface_from_arrays(grid[i], VisualServer::PRIMITIVE_LINES, d);
  4249. VisualServer::get_singleton()->mesh_surface_set_material(grid[i], 0, indicator_mat->get_rid());
  4250. grid_instance[i] = VisualServer::get_singleton()->instance_create2(grid[i], get_tree()->get_root()->get_world()->get_scenario());
  4251. VisualServer::get_singleton()->instance_set_visible(grid_instance[i], grid_visible[i]);
  4252. VisualServer::get_singleton()->instance_geometry_set_cast_shadows_setting(grid_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  4253. VS::get_singleton()->instance_set_layer_mask(grid_instance[i], 1 << SpatialEditorViewport::GIZMO_GRID_LAYER);
  4254. }
  4255. }
  4256. void SpatialEditor::_finish_indicators() {
  4257. VisualServer::get_singleton()->free(origin_instance);
  4258. VisualServer::get_singleton()->free(origin);
  4259. _finish_grid();
  4260. }
  4261. void SpatialEditor::_finish_grid() {
  4262. for (int i = 0; i < 3; i++) {
  4263. VisualServer::get_singleton()->free(grid_instance[i]);
  4264. VisualServer::get_singleton()->free(grid[i]);
  4265. }
  4266. }
  4267. bool SpatialEditor::is_any_freelook_active() const {
  4268. for (unsigned int i = 0; i < VIEWPORTS_COUNT; ++i) {
  4269. if (viewports[i]->is_freelook_active())
  4270. return true;
  4271. }
  4272. return false;
  4273. }
  4274. void SpatialEditor::_refresh_menu_icons() {
  4275. bool all_locked = true;
  4276. bool all_grouped = true;
  4277. List<Node *> &selection = editor_selection->get_selected_node_list();
  4278. if (selection.empty()) {
  4279. all_locked = false;
  4280. all_grouped = false;
  4281. } else {
  4282. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4283. if (Object::cast_to<Spatial>(E->get()) && !Object::cast_to<Spatial>(E->get())->has_meta("_edit_lock_")) {
  4284. all_locked = false;
  4285. break;
  4286. }
  4287. }
  4288. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4289. if (Object::cast_to<Spatial>(E->get()) && !Object::cast_to<Spatial>(E->get())->has_meta("_edit_group_")) {
  4290. all_grouped = false;
  4291. break;
  4292. }
  4293. }
  4294. }
  4295. tool_button[TOOL_LOCK_SELECTED]->set_visible(!all_locked);
  4296. tool_button[TOOL_LOCK_SELECTED]->set_disabled(selection.empty());
  4297. tool_button[TOOL_UNLOCK_SELECTED]->set_visible(all_locked);
  4298. tool_button[TOOL_GROUP_SELECTED]->set_visible(!all_grouped);
  4299. tool_button[TOOL_GROUP_SELECTED]->set_disabled(selection.empty());
  4300. tool_button[TOOL_UNGROUP_SELECTED]->set_visible(all_grouped);
  4301. }
  4302. template <typename T>
  4303. Set<T *> _get_child_nodes(Node *parent_node) {
  4304. Set<T *> nodes = Set<T *>();
  4305. T *node = Node::cast_to<T>(parent_node);
  4306. if (node) {
  4307. nodes.insert(node);
  4308. }
  4309. for (int i = 0; i < parent_node->get_child_count(); i++) {
  4310. Node *child_node = parent_node->get_child(i);
  4311. Set<T *> child_nodes = _get_child_nodes<T>(child_node);
  4312. for (typename Set<T *>::Element *I = child_nodes.front(); I; I = I->next()) {
  4313. nodes.insert(I->get());
  4314. }
  4315. }
  4316. return nodes;
  4317. }
  4318. Set<RID> _get_physics_bodies_rid(Node *node) {
  4319. Set<RID> rids = Set<RID>();
  4320. PhysicsBody *pb = Node::cast_to<PhysicsBody>(node);
  4321. if (pb) {
  4322. rids.insert(pb->get_rid());
  4323. }
  4324. Set<PhysicsBody *> child_nodes = _get_child_nodes<PhysicsBody>(node);
  4325. for (Set<PhysicsBody *>::Element *I = child_nodes.front(); I; I = I->next()) {
  4326. rids.insert(I->get()->get_rid());
  4327. }
  4328. return rids;
  4329. }
  4330. void SpatialEditor::snap_selected_nodes_to_floor() {
  4331. List<Node *> &selection = editor_selection->get_selected_node_list();
  4332. Dictionary snap_data;
  4333. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4334. Spatial *sp = Object::cast_to<Spatial>(E->get());
  4335. if (sp) {
  4336. Vector3 from = Vector3();
  4337. Vector3 position_offset = Vector3();
  4338. // Priorities for snapping to floor are CollisionShapes, VisualInstances and then origin
  4339. Set<VisualInstance *> vi = _get_child_nodes<VisualInstance>(sp);
  4340. Set<CollisionShape *> cs = _get_child_nodes<CollisionShape>(sp);
  4341. if (cs.size()) {
  4342. AABB aabb = sp->get_global_transform().xform(cs.front()->get()->get_shape()->get_debug_mesh()->get_aabb());
  4343. for (Set<CollisionShape *>::Element *I = cs.front(); I; I = I->next()) {
  4344. aabb.merge_with(sp->get_global_transform().xform(I->get()->get_shape()->get_debug_mesh()->get_aabb()));
  4345. }
  4346. Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
  4347. from = aabb.position + size;
  4348. position_offset.y = from.y - sp->get_global_transform().origin.y;
  4349. } else if (vi.size()) {
  4350. AABB aabb = vi.front()->get()->get_transformed_aabb();
  4351. for (Set<VisualInstance *>::Element *I = vi.front(); I; I = I->next()) {
  4352. aabb.merge_with(I->get()->get_transformed_aabb());
  4353. }
  4354. Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
  4355. from = aabb.position + size;
  4356. position_offset.y = from.y - sp->get_global_transform().origin.y;
  4357. } else {
  4358. from = sp->get_global_transform().origin;
  4359. }
  4360. // We add a bit of margin to the from position to avoid it from snapping
  4361. // when the spatial is already on a floor and there's another floor under
  4362. // it
  4363. from = from + Vector3(0.0, 0.2, 0.0);
  4364. Dictionary d;
  4365. d["from"] = from;
  4366. d["position_offset"] = position_offset;
  4367. snap_data[sp] = d;
  4368. }
  4369. }
  4370. PhysicsDirectSpaceState *ss = get_tree()->get_root()->get_world()->get_direct_space_state();
  4371. PhysicsDirectSpaceState::RayResult result;
  4372. Array keys = snap_data.keys();
  4373. // The maximum height an object can travel to be snapped
  4374. const float max_snap_height = 20.0;
  4375. // Will be set to `true` if at least one node from the selection was successfully snapped
  4376. bool snapped_to_floor = false;
  4377. if (keys.size()) {
  4378. // For snapping to be performed, there must be solid geometry under at least one of the selected nodes.
  4379. // We need to check this before snapping to register the undo/redo action only if needed.
  4380. for (int i = 0; i < keys.size(); i++) {
  4381. Node *node = keys[i];
  4382. Spatial *sp = Object::cast_to<Spatial>(node);
  4383. Dictionary d = snap_data[node];
  4384. Vector3 from = d["from"];
  4385. Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
  4386. Set<RID> excluded = _get_physics_bodies_rid(sp);
  4387. if (ss->intersect_ray(from, to, result, excluded)) {
  4388. snapped_to_floor = true;
  4389. }
  4390. }
  4391. if (snapped_to_floor) {
  4392. undo_redo->create_action(TTR("Snap Nodes To Floor"));
  4393. // Perform snapping if at least one node can be snapped
  4394. for (int i = 0; i < keys.size(); i++) {
  4395. Node *node = keys[i];
  4396. Spatial *sp = Object::cast_to<Spatial>(node);
  4397. Dictionary d = snap_data[node];
  4398. Vector3 from = d["from"];
  4399. Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
  4400. Set<RID> excluded = _get_physics_bodies_rid(sp);
  4401. if (ss->intersect_ray(from, to, result, excluded)) {
  4402. Vector3 position_offset = d["position_offset"];
  4403. Transform new_transform = sp->get_global_transform();
  4404. new_transform.origin.y = result.position.y;
  4405. new_transform.origin = new_transform.origin - position_offset;
  4406. undo_redo->add_do_method(sp, "set_global_transform", new_transform);
  4407. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_transform());
  4408. }
  4409. }
  4410. undo_redo->commit_action();
  4411. } else {
  4412. EditorNode::get_singleton()->show_warning(TTR("Couldn't find a solid floor to snap the selection to."));
  4413. }
  4414. }
  4415. }
  4416. void SpatialEditor::_unhandled_key_input(Ref<InputEvent> p_event) {
  4417. if (!is_visible_in_tree() || get_viewport()->gui_has_modal_stack())
  4418. return;
  4419. snap_key_enabled = Input::get_singleton()->is_key_pressed(KEY_CONTROL);
  4420. }
  4421. void SpatialEditor::_notification(int p_what) {
  4422. if (p_what == NOTIFICATION_READY) {
  4423. tool_button[SpatialEditor::TOOL_MODE_SELECT]->set_icon(get_icon("ToolSelect", "EditorIcons"));
  4424. tool_button[SpatialEditor::TOOL_MODE_MOVE]->set_icon(get_icon("ToolMove", "EditorIcons"));
  4425. tool_button[SpatialEditor::TOOL_MODE_ROTATE]->set_icon(get_icon("ToolRotate", "EditorIcons"));
  4426. tool_button[SpatialEditor::TOOL_MODE_SCALE]->set_icon(get_icon("ToolScale", "EditorIcons"));
  4427. tool_button[SpatialEditor::TOOL_MODE_LIST_SELECT]->set_icon(get_icon("ListSelect", "EditorIcons"));
  4428. tool_button[SpatialEditor::TOOL_LOCK_SELECTED]->set_icon(get_icon("Lock", "EditorIcons"));
  4429. tool_button[SpatialEditor::TOOL_UNLOCK_SELECTED]->set_icon(get_icon("Unlock", "EditorIcons"));
  4430. tool_button[SpatialEditor::TOOL_GROUP_SELECTED]->set_icon(get_icon("Group", "EditorIcons"));
  4431. tool_button[SpatialEditor::TOOL_UNGROUP_SELECTED]->set_icon(get_icon("Ungroup", "EditorIcons"));
  4432. tool_option_button[SpatialEditor::TOOL_OPT_LOCAL_COORDS]->set_icon(get_icon("Object", "EditorIcons"));
  4433. tool_option_button[SpatialEditor::TOOL_OPT_USE_SNAP]->set_icon(get_icon("Snap", "EditorIcons"));
  4434. tool_option_button[SpatialEditor::TOOL_OPT_OVERRIDE_CAMERA]->set_icon(get_icon("Camera", "EditorIcons"));
  4435. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), get_icon("Panels1", "EditorIcons"));
  4436. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), get_icon("Panels2", "EditorIcons"));
  4437. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), get_icon("Panels2Alt", "EditorIcons"));
  4438. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), get_icon("Panels3", "EditorIcons"));
  4439. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), get_icon("Panels3Alt", "EditorIcons"));
  4440. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), get_icon("Panels4", "EditorIcons"));
  4441. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  4442. _refresh_menu_icons();
  4443. get_tree()->connect("node_removed", this, "_node_removed");
  4444. EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor()->connect("node_changed", this, "_refresh_menu_icons");
  4445. editor_selection->connect("selection_changed", this, "_refresh_menu_icons");
  4446. editor->connect("stop_pressed", this, "_update_camera_override_button", make_binds(false));
  4447. editor->connect("play_pressed", this, "_update_camera_override_button", make_binds(true));
  4448. } else if (p_what == NOTIFICATION_ENTER_TREE) {
  4449. _register_all_gizmos();
  4450. _update_gizmos_menu();
  4451. _init_indicators();
  4452. } else if (p_what == NOTIFICATION_THEME_CHANGED) {
  4453. _update_gizmos_menu_theme();
  4454. } else if (p_what == NOTIFICATION_EXIT_TREE) {
  4455. _finish_indicators();
  4456. } else if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) {
  4457. tool_button[SpatialEditor::TOOL_MODE_SELECT]->set_icon(get_icon("ToolSelect", "EditorIcons"));
  4458. tool_button[SpatialEditor::TOOL_MODE_MOVE]->set_icon(get_icon("ToolMove", "EditorIcons"));
  4459. tool_button[SpatialEditor::TOOL_MODE_ROTATE]->set_icon(get_icon("ToolRotate", "EditorIcons"));
  4460. tool_button[SpatialEditor::TOOL_MODE_SCALE]->set_icon(get_icon("ToolScale", "EditorIcons"));
  4461. tool_button[SpatialEditor::TOOL_MODE_LIST_SELECT]->set_icon(get_icon("ListSelect", "EditorIcons"));
  4462. tool_button[SpatialEditor::TOOL_LOCK_SELECTED]->set_icon(get_icon("Lock", "EditorIcons"));
  4463. tool_button[SpatialEditor::TOOL_UNLOCK_SELECTED]->set_icon(get_icon("Unlock", "EditorIcons"));
  4464. tool_button[SpatialEditor::TOOL_GROUP_SELECTED]->set_icon(get_icon("Group", "EditorIcons"));
  4465. tool_button[SpatialEditor::TOOL_UNGROUP_SELECTED]->set_icon(get_icon("Ungroup", "EditorIcons"));
  4466. tool_option_button[SpatialEditor::TOOL_OPT_LOCAL_COORDS]->set_icon(get_icon("Object", "EditorIcons"));
  4467. tool_option_button[SpatialEditor::TOOL_OPT_USE_SNAP]->set_icon(get_icon("Snap", "EditorIcons"));
  4468. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), get_icon("Panels1", "EditorIcons"));
  4469. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), get_icon("Panels2", "EditorIcons"));
  4470. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), get_icon("Panels2Alt", "EditorIcons"));
  4471. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), get_icon("Panels3", "EditorIcons"));
  4472. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), get_icon("Panels3Alt", "EditorIcons"));
  4473. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), get_icon("Panels4", "EditorIcons"));
  4474. // Update grid color by rebuilding grid.
  4475. _finish_grid();
  4476. _init_grid();
  4477. } else if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
  4478. if (!is_visible() && tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->is_pressed()) {
  4479. ScriptEditorDebugger *debugger = ScriptEditor::get_singleton()->get_debugger();
  4480. debugger->set_camera_override(ScriptEditorDebugger::OVERRIDE_NONE);
  4481. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_pressed(false);
  4482. }
  4483. }
  4484. }
  4485. void SpatialEditor::add_control_to_menu_panel(Control *p_control) {
  4486. hbc_menu->add_child(p_control);
  4487. }
  4488. void SpatialEditor::remove_control_from_menu_panel(Control *p_control) {
  4489. hbc_menu->remove_child(p_control);
  4490. }
  4491. void SpatialEditor::set_can_preview(Camera *p_preview) {
  4492. for (int i = 0; i < 4; i++) {
  4493. viewports[i]->set_can_preview(p_preview);
  4494. }
  4495. }
  4496. VSplitContainer *SpatialEditor::get_shader_split() {
  4497. return shader_split;
  4498. }
  4499. HSplitContainer *SpatialEditor::get_palette_split() {
  4500. return palette_split;
  4501. }
  4502. void SpatialEditor::_request_gizmo(Object *p_obj) {
  4503. Spatial *sp = Object::cast_to<Spatial>(p_obj);
  4504. if (!sp)
  4505. return;
  4506. if (editor->get_edited_scene() && (sp == editor->get_edited_scene() || (sp->get_owner() && editor->get_edited_scene()->is_a_parent_of(sp)))) {
  4507. Ref<EditorSpatialGizmo> seg;
  4508. for (int i = 0; i < gizmo_plugins_by_priority.size(); ++i) {
  4509. seg = gizmo_plugins_by_priority.write[i]->get_gizmo(sp);
  4510. if (seg.is_valid()) {
  4511. sp->set_gizmo(seg);
  4512. if (sp == selected) {
  4513. seg->set_selected(true);
  4514. selected->update_gizmo();
  4515. }
  4516. break;
  4517. }
  4518. }
  4519. }
  4520. }
  4521. void SpatialEditor::_toggle_maximize_view(Object *p_viewport) {
  4522. if (!p_viewport) return;
  4523. SpatialEditorViewport *current_viewport = Object::cast_to<SpatialEditorViewport>(p_viewport);
  4524. if (!current_viewport) return;
  4525. int index = -1;
  4526. bool maximized = false;
  4527. for (int i = 0; i < 4; i++) {
  4528. if (viewports[i] == current_viewport) {
  4529. index = i;
  4530. if (current_viewport->get_global_rect() == viewport_base->get_global_rect())
  4531. maximized = true;
  4532. break;
  4533. }
  4534. }
  4535. if (index == -1) return;
  4536. if (!maximized) {
  4537. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  4538. if (i == (uint32_t)index)
  4539. viewports[i]->set_anchors_and_margins_preset(Control::PRESET_WIDE);
  4540. else
  4541. viewports[i]->hide();
  4542. }
  4543. } else {
  4544. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++)
  4545. viewports[i]->show();
  4546. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT)))
  4547. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  4548. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS)))
  4549. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
  4550. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT)))
  4551. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
  4552. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS)))
  4553. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
  4554. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT)))
  4555. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
  4556. else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS)))
  4557. _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
  4558. }
  4559. }
  4560. void SpatialEditor::_node_removed(Node *p_node) {
  4561. if (p_node == selected)
  4562. selected = NULL;
  4563. }
  4564. void SpatialEditor::_register_all_gizmos() {
  4565. add_gizmo_plugin(Ref<CameraSpatialGizmoPlugin>(memnew(CameraSpatialGizmoPlugin)));
  4566. add_gizmo_plugin(Ref<LightSpatialGizmoPlugin>(memnew(LightSpatialGizmoPlugin)));
  4567. add_gizmo_plugin(Ref<AudioStreamPlayer3DSpatialGizmoPlugin>(memnew(AudioStreamPlayer3DSpatialGizmoPlugin)));
  4568. add_gizmo_plugin(Ref<MeshInstanceSpatialGizmoPlugin>(memnew(MeshInstanceSpatialGizmoPlugin)));
  4569. add_gizmo_plugin(Ref<SoftBodySpatialGizmoPlugin>(memnew(SoftBodySpatialGizmoPlugin)));
  4570. add_gizmo_plugin(Ref<Sprite3DSpatialGizmoPlugin>(memnew(Sprite3DSpatialGizmoPlugin)));
  4571. add_gizmo_plugin(Ref<SkeletonSpatialGizmoPlugin>(memnew(SkeletonSpatialGizmoPlugin)));
  4572. add_gizmo_plugin(Ref<Position3DSpatialGizmoPlugin>(memnew(Position3DSpatialGizmoPlugin)));
  4573. add_gizmo_plugin(Ref<RayCastSpatialGizmoPlugin>(memnew(RayCastSpatialGizmoPlugin)));
  4574. add_gizmo_plugin(Ref<SpringArmSpatialGizmoPlugin>(memnew(SpringArmSpatialGizmoPlugin)));
  4575. add_gizmo_plugin(Ref<VehicleWheelSpatialGizmoPlugin>(memnew(VehicleWheelSpatialGizmoPlugin)));
  4576. add_gizmo_plugin(Ref<VisibilityNotifierGizmoPlugin>(memnew(VisibilityNotifierGizmoPlugin)));
  4577. add_gizmo_plugin(Ref<ParticlesGizmoPlugin>(memnew(ParticlesGizmoPlugin)));
  4578. add_gizmo_plugin(Ref<CPUParticlesGizmoPlugin>(memnew(CPUParticlesGizmoPlugin)));
  4579. add_gizmo_plugin(Ref<ReflectionProbeGizmoPlugin>(memnew(ReflectionProbeGizmoPlugin)));
  4580. add_gizmo_plugin(Ref<GIProbeGizmoPlugin>(memnew(GIProbeGizmoPlugin)));
  4581. add_gizmo_plugin(Ref<BakedIndirectLightGizmoPlugin>(memnew(BakedIndirectLightGizmoPlugin)));
  4582. add_gizmo_plugin(Ref<CollisionShapeSpatialGizmoPlugin>(memnew(CollisionShapeSpatialGizmoPlugin)));
  4583. add_gizmo_plugin(Ref<CollisionPolygonSpatialGizmoPlugin>(memnew(CollisionPolygonSpatialGizmoPlugin)));
  4584. add_gizmo_plugin(Ref<NavigationMeshSpatialGizmoPlugin>(memnew(NavigationMeshSpatialGizmoPlugin)));
  4585. add_gizmo_plugin(Ref<JointSpatialGizmoPlugin>(memnew(JointSpatialGizmoPlugin)));
  4586. add_gizmo_plugin(Ref<PhysicalBoneSpatialGizmoPlugin>(memnew(PhysicalBoneSpatialGizmoPlugin)));
  4587. }
  4588. void SpatialEditor::_bind_methods() {
  4589. ClassDB::bind_method("_unhandled_key_input", &SpatialEditor::_unhandled_key_input);
  4590. ClassDB::bind_method("_node_removed", &SpatialEditor::_node_removed);
  4591. ClassDB::bind_method("_menu_item_pressed", &SpatialEditor::_menu_item_pressed);
  4592. ClassDB::bind_method("_menu_gizmo_toggled", &SpatialEditor::_menu_gizmo_toggled);
  4593. ClassDB::bind_method("_menu_item_toggled", &SpatialEditor::_menu_item_toggled);
  4594. ClassDB::bind_method("_xform_dialog_action", &SpatialEditor::_xform_dialog_action);
  4595. ClassDB::bind_method("_get_editor_data", &SpatialEditor::_get_editor_data);
  4596. ClassDB::bind_method("_request_gizmo", &SpatialEditor::_request_gizmo);
  4597. ClassDB::bind_method("_toggle_maximize_view", &SpatialEditor::_toggle_maximize_view);
  4598. ClassDB::bind_method("_refresh_menu_icons", &SpatialEditor::_refresh_menu_icons);
  4599. ClassDB::bind_method("_update_camera_override_button", &SpatialEditor::_update_camera_override_button);
  4600. ClassDB::bind_method("_update_camera_override_viewport", &SpatialEditor::_update_camera_override_viewport);
  4601. ClassDB::bind_method("_snap_changed", &SpatialEditor::_snap_changed);
  4602. ClassDB::bind_method("_snap_update", &SpatialEditor::_snap_update);
  4603. ADD_SIGNAL(MethodInfo("transform_key_request"));
  4604. ADD_SIGNAL(MethodInfo("item_lock_status_changed"));
  4605. ADD_SIGNAL(MethodInfo("item_group_status_changed"));
  4606. }
  4607. void SpatialEditor::clear() {
  4608. settings_fov->set_value(EDITOR_DEF("editors/3d/default_fov", 70.0));
  4609. settings_znear->set_value(EDITOR_DEF("editors/3d/default_z_near", 0.05));
  4610. settings_zfar->set_value(EDITOR_DEF("editors/3d/default_z_far", 1500.0));
  4611. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  4612. viewports[i]->reset();
  4613. }
  4614. VisualServer::get_singleton()->instance_set_visible(origin_instance, true);
  4615. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), true);
  4616. for (int i = 0; i < 3; ++i) {
  4617. if (grid_enable[i]) {
  4618. VisualServer::get_singleton()->instance_set_visible(grid_instance[i], true);
  4619. grid_visible[i] = true;
  4620. }
  4621. }
  4622. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  4623. viewports[i]->view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(SpatialEditorViewport::VIEW_AUDIO_LISTENER), i == 0);
  4624. viewports[i]->viewport->set_as_audio_listener(i == 0);
  4625. }
  4626. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID), true);
  4627. }
  4628. SpatialEditor::SpatialEditor(EditorNode *p_editor) {
  4629. gizmo.visible = true;
  4630. gizmo.scale = 1.0;
  4631. viewport_environment = Ref<Environment>(memnew(Environment));
  4632. undo_redo = p_editor->get_undo_redo();
  4633. VBoxContainer *vbc = this;
  4634. custom_camera = NULL;
  4635. singleton = this;
  4636. editor = p_editor;
  4637. editor_selection = editor->get_editor_selection();
  4638. editor_selection->add_editor_plugin(this);
  4639. snap_enabled = false;
  4640. snap_key_enabled = false;
  4641. tool_mode = TOOL_MODE_SELECT;
  4642. camera_override_viewport_id = 0;
  4643. hbc_menu = memnew(HBoxContainer);
  4644. vbc->add_child(hbc_menu);
  4645. Vector<Variant> button_binds;
  4646. button_binds.resize(1);
  4647. String sct;
  4648. tool_button[TOOL_MODE_SELECT] = memnew(ToolButton);
  4649. hbc_menu->add_child(tool_button[TOOL_MODE_SELECT]);
  4650. tool_button[TOOL_MODE_SELECT]->set_toggle_mode(true);
  4651. tool_button[TOOL_MODE_SELECT]->set_flat(true);
  4652. tool_button[TOOL_MODE_SELECT]->set_pressed(true);
  4653. button_binds.write[0] = MENU_TOOL_SELECT;
  4654. tool_button[TOOL_MODE_SELECT]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4655. tool_button[TOOL_MODE_SELECT]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_select", TTR("Select Mode"), KEY_Q));
  4656. tool_button[TOOL_MODE_SELECT]->set_tooltip(keycode_get_string(KEY_MASK_CMD) + TTR("Drag: Rotate\nAlt+Drag: Move\nAlt+RMB: Depth list selection"));
  4657. hbc_menu->add_child(memnew(VSeparator));
  4658. tool_button[TOOL_MODE_MOVE] = memnew(ToolButton);
  4659. hbc_menu->add_child(tool_button[TOOL_MODE_MOVE]);
  4660. tool_button[TOOL_MODE_MOVE]->set_toggle_mode(true);
  4661. tool_button[TOOL_MODE_MOVE]->set_flat(true);
  4662. button_binds.write[0] = MENU_TOOL_MOVE;
  4663. tool_button[TOOL_MODE_MOVE]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4664. tool_button[TOOL_MODE_MOVE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_move", TTR("Move Mode"), KEY_W));
  4665. tool_button[TOOL_MODE_ROTATE] = memnew(ToolButton);
  4666. hbc_menu->add_child(tool_button[TOOL_MODE_ROTATE]);
  4667. tool_button[TOOL_MODE_ROTATE]->set_toggle_mode(true);
  4668. tool_button[TOOL_MODE_ROTATE]->set_flat(true);
  4669. button_binds.write[0] = MENU_TOOL_ROTATE;
  4670. tool_button[TOOL_MODE_ROTATE]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4671. tool_button[TOOL_MODE_ROTATE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_rotate", TTR("Rotate Mode"), KEY_E));
  4672. tool_button[TOOL_MODE_SCALE] = memnew(ToolButton);
  4673. hbc_menu->add_child(tool_button[TOOL_MODE_SCALE]);
  4674. tool_button[TOOL_MODE_SCALE]->set_toggle_mode(true);
  4675. tool_button[TOOL_MODE_SCALE]->set_flat(true);
  4676. button_binds.write[0] = MENU_TOOL_SCALE;
  4677. tool_button[TOOL_MODE_SCALE]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4678. tool_button[TOOL_MODE_SCALE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_scale", TTR("Scale Mode"), KEY_R));
  4679. hbc_menu->add_child(memnew(VSeparator));
  4680. tool_button[TOOL_MODE_LIST_SELECT] = memnew(ToolButton);
  4681. hbc_menu->add_child(tool_button[TOOL_MODE_LIST_SELECT]);
  4682. tool_button[TOOL_MODE_LIST_SELECT]->set_toggle_mode(true);
  4683. tool_button[TOOL_MODE_LIST_SELECT]->set_flat(true);
  4684. button_binds.write[0] = MENU_TOOL_LIST_SELECT;
  4685. tool_button[TOOL_MODE_LIST_SELECT]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4686. 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)."));
  4687. tool_button[TOOL_LOCK_SELECTED] = memnew(ToolButton);
  4688. hbc_menu->add_child(tool_button[TOOL_LOCK_SELECTED]);
  4689. button_binds.write[0] = MENU_LOCK_SELECTED;
  4690. tool_button[TOOL_LOCK_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4691. tool_button[TOOL_LOCK_SELECTED]->set_tooltip(TTR("Lock the selected object in place (can't be moved)."));
  4692. tool_button[TOOL_UNLOCK_SELECTED] = memnew(ToolButton);
  4693. hbc_menu->add_child(tool_button[TOOL_UNLOCK_SELECTED]);
  4694. button_binds.write[0] = MENU_UNLOCK_SELECTED;
  4695. tool_button[TOOL_UNLOCK_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4696. tool_button[TOOL_UNLOCK_SELECTED]->set_tooltip(TTR("Unlock the selected object (can be moved)."));
  4697. tool_button[TOOL_GROUP_SELECTED] = memnew(ToolButton);
  4698. hbc_menu->add_child(tool_button[TOOL_GROUP_SELECTED]);
  4699. button_binds.write[0] = MENU_GROUP_SELECTED;
  4700. tool_button[TOOL_GROUP_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4701. tool_button[TOOL_GROUP_SELECTED]->set_tooltip(TTR("Makes sure the object's children are not selectable."));
  4702. tool_button[TOOL_UNGROUP_SELECTED] = memnew(ToolButton);
  4703. hbc_menu->add_child(tool_button[TOOL_UNGROUP_SELECTED]);
  4704. button_binds.write[0] = MENU_UNGROUP_SELECTED;
  4705. tool_button[TOOL_UNGROUP_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  4706. tool_button[TOOL_UNGROUP_SELECTED]->set_tooltip(TTR("Restores the object's children's ability to be selected."));
  4707. hbc_menu->add_child(memnew(VSeparator));
  4708. tool_option_button[TOOL_OPT_LOCAL_COORDS] = memnew(ToolButton);
  4709. hbc_menu->add_child(tool_option_button[TOOL_OPT_LOCAL_COORDS]);
  4710. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_toggle_mode(true);
  4711. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_flat(true);
  4712. button_binds.write[0] = MENU_TOOL_LOCAL_COORDS;
  4713. tool_option_button[TOOL_OPT_LOCAL_COORDS]->connect("toggled", this, "_menu_item_toggled", button_binds);
  4714. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut(ED_SHORTCUT("spatial_editor/local_coords", TTR("Use Local Space"), KEY_T));
  4715. tool_option_button[TOOL_OPT_USE_SNAP] = memnew(ToolButton);
  4716. hbc_menu->add_child(tool_option_button[TOOL_OPT_USE_SNAP]);
  4717. tool_option_button[TOOL_OPT_USE_SNAP]->set_toggle_mode(true);
  4718. tool_option_button[TOOL_OPT_USE_SNAP]->set_flat(true);
  4719. button_binds.write[0] = MENU_TOOL_USE_SNAP;
  4720. tool_option_button[TOOL_OPT_USE_SNAP]->connect("toggled", this, "_menu_item_toggled", button_binds);
  4721. tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut(ED_SHORTCUT("spatial_editor/snap", TTR("Use Snap"), KEY_Y));
  4722. hbc_menu->add_child(memnew(VSeparator));
  4723. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA] = memnew(ToolButton);
  4724. hbc_menu->add_child(tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]);
  4725. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_toggle_mode(true);
  4726. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_flat(true);
  4727. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_disabled(true);
  4728. button_binds.write[0] = MENU_TOOL_OVERRIDE_CAMERA;
  4729. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->connect("toggled", this, "_menu_item_toggled", button_binds);
  4730. _update_camera_override_button(false);
  4731. hbc_menu->add_child(memnew(VSeparator));
  4732. // Drag and drop support;
  4733. preview_node = memnew(Spatial);
  4734. preview_bounds = AABB();
  4735. ED_SHORTCUT("spatial_editor/bottom_view", TTR("Bottom View"), KEY_MASK_ALT + KEY_KP_7);
  4736. ED_SHORTCUT("spatial_editor/top_view", TTR("Top View"), KEY_KP_7);
  4737. ED_SHORTCUT("spatial_editor/rear_view", TTR("Rear View"), KEY_MASK_ALT + KEY_KP_1);
  4738. ED_SHORTCUT("spatial_editor/front_view", TTR("Front View"), KEY_KP_1);
  4739. ED_SHORTCUT("spatial_editor/left_view", TTR("Left View"), KEY_MASK_ALT + KEY_KP_3);
  4740. ED_SHORTCUT("spatial_editor/right_view", TTR("Right View"), KEY_KP_3);
  4741. ED_SHORTCUT("spatial_editor/switch_perspective_orthogonal", TTR("Switch Perspective/Orthogonal View"), KEY_KP_5);
  4742. ED_SHORTCUT("spatial_editor/insert_anim_key", TTR("Insert Animation Key"), KEY_K);
  4743. ED_SHORTCUT("spatial_editor/focus_origin", TTR("Focus Origin"), KEY_O);
  4744. ED_SHORTCUT("spatial_editor/focus_selection", TTR("Focus Selection"), KEY_F);
  4745. ED_SHORTCUT("spatial_editor/align_transform_with_view", TTR("Align Transform with View"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_M);
  4746. ED_SHORTCUT("spatial_editor/align_rotation_with_view", TTR("Align Rotation with View"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_F);
  4747. ED_SHORTCUT("spatial_editor/freelook_toggle", TTR("Toggle Freelook"), KEY_MASK_SHIFT + KEY_F);
  4748. PopupMenu *p;
  4749. transform_menu = memnew(MenuButton);
  4750. transform_menu->set_text(TTR("Transform"));
  4751. transform_menu->set_switch_on_hover(true);
  4752. hbc_menu->add_child(transform_menu);
  4753. p = transform_menu->get_popup();
  4754. p->add_shortcut(ED_SHORTCUT("spatial_editor/snap_to_floor", TTR("Snap Object to Floor"), KEY_PAGEDOWN), MENU_SNAP_TO_FLOOR);
  4755. p->add_shortcut(ED_SHORTCUT("spatial_editor/transform_dialog", TTR("Transform Dialog...")), MENU_TRANSFORM_DIALOG);
  4756. p->add_separator();
  4757. p->add_shortcut(ED_SHORTCUT("spatial_editor/configure_snap", TTR("Configure Snap...")), MENU_TRANSFORM_CONFIGURE_SNAP);
  4758. p->connect("id_pressed", this, "_menu_item_pressed");
  4759. view_menu = memnew(MenuButton);
  4760. view_menu->set_text(TTR("View"));
  4761. view_menu->set_switch_on_hover(true);
  4762. hbc_menu->add_child(view_menu);
  4763. p = view_menu->get_popup();
  4764. accept = memnew(AcceptDialog);
  4765. editor->get_gui_base()->add_child(accept);
  4766. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/1_viewport", TTR("1 Viewport"), KEY_MASK_CMD + KEY_1), MENU_VIEW_USE_1_VIEWPORT);
  4767. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports", TTR("2 Viewports"), KEY_MASK_CMD + KEY_2), MENU_VIEW_USE_2_VIEWPORTS);
  4768. 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);
  4769. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports", TTR("3 Viewports"), KEY_MASK_CMD + KEY_3), MENU_VIEW_USE_3_VIEWPORTS);
  4770. 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);
  4771. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/4_viewports", TTR("4 Viewports"), KEY_MASK_CMD + KEY_4), MENU_VIEW_USE_4_VIEWPORTS);
  4772. p->add_separator();
  4773. p->add_submenu_item(TTR("Gizmos"), "GizmosMenu");
  4774. p->add_separator();
  4775. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_origin", TTR("View Origin")), MENU_VIEW_ORIGIN);
  4776. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_grid", TTR("View Grid")), MENU_VIEW_GRID);
  4777. p->add_separator();
  4778. p->add_shortcut(ED_SHORTCUT("spatial_editor/settings", TTR("Settings...")), MENU_VIEW_CAMERA_SETTINGS);
  4779. p->set_item_checked(p->get_item_index(MENU_VIEW_ORIGIN), true);
  4780. p->set_item_checked(p->get_item_index(MENU_VIEW_GRID), true);
  4781. p->connect("id_pressed", this, "_menu_item_pressed");
  4782. gizmos_menu = memnew(PopupMenu);
  4783. p->add_child(gizmos_menu);
  4784. gizmos_menu->set_name("GizmosMenu");
  4785. gizmos_menu->set_hide_on_checkable_item_selection(false);
  4786. gizmos_menu->connect("id_pressed", this, "_menu_gizmo_toggled");
  4787. /* REST OF MENU */
  4788. palette_split = memnew(HSplitContainer);
  4789. palette_split->set_v_size_flags(SIZE_EXPAND_FILL);
  4790. vbc->add_child(palette_split);
  4791. shader_split = memnew(VSplitContainer);
  4792. shader_split->set_h_size_flags(SIZE_EXPAND_FILL);
  4793. palette_split->add_child(shader_split);
  4794. viewport_base = memnew(SpatialEditorViewportContainer);
  4795. shader_split->add_child(viewport_base);
  4796. viewport_base->set_v_size_flags(SIZE_EXPAND_FILL);
  4797. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  4798. viewports[i] = memnew(SpatialEditorViewport(this, editor, i));
  4799. viewports[i]->connect("toggle_maximize_view", this, "_toggle_maximize_view");
  4800. viewports[i]->connect("clicked", this, "_update_camera_override_viewport");
  4801. viewports[i]->assign_pending_data_pointers(preview_node, &preview_bounds, accept);
  4802. viewport_base->add_child(viewports[i]);
  4803. }
  4804. /* SNAP DIALOG */
  4805. snap_translate_value = 1;
  4806. snap_rotate_value = 15;
  4807. snap_scale_value = 10;
  4808. snap_dialog = memnew(ConfirmationDialog);
  4809. snap_dialog->set_title(TTR("Snap Settings"));
  4810. add_child(snap_dialog);
  4811. snap_dialog->connect("confirmed", this, "_snap_changed");
  4812. snap_dialog->get_cancel()->connect("pressed", this, "_snap_update");
  4813. VBoxContainer *snap_dialog_vbc = memnew(VBoxContainer);
  4814. snap_dialog->add_child(snap_dialog_vbc);
  4815. snap_translate = memnew(LineEdit);
  4816. snap_dialog_vbc->add_margin_child(TTR("Translate Snap:"), snap_translate);
  4817. snap_rotate = memnew(LineEdit);
  4818. snap_dialog_vbc->add_margin_child(TTR("Rotate Snap (deg.):"), snap_rotate);
  4819. snap_scale = memnew(LineEdit);
  4820. snap_dialog_vbc->add_margin_child(TTR("Scale Snap (%):"), snap_scale);
  4821. _snap_update();
  4822. /* SETTINGS DIALOG */
  4823. settings_dialog = memnew(ConfirmationDialog);
  4824. settings_dialog->set_title(TTR("Viewport Settings"));
  4825. add_child(settings_dialog);
  4826. settings_vbc = memnew(VBoxContainer);
  4827. settings_vbc->set_custom_minimum_size(Size2(200, 0) * EDSCALE);
  4828. settings_dialog->add_child(settings_vbc);
  4829. settings_fov = memnew(SpinBox);
  4830. settings_fov->set_max(MAX_FOV);
  4831. settings_fov->set_min(MIN_FOV);
  4832. settings_fov->set_step(0.01);
  4833. settings_fov->set_value(EDITOR_DEF("editors/3d/default_fov", 70.0));
  4834. settings_vbc->add_margin_child(TTR("Perspective FOV (deg.):"), settings_fov);
  4835. settings_znear = memnew(SpinBox);
  4836. settings_znear->set_max(MAX_Z);
  4837. settings_znear->set_min(MIN_Z);
  4838. settings_znear->set_step(0.01);
  4839. settings_znear->set_value(EDITOR_DEF("editors/3d/default_z_near", 0.05));
  4840. settings_vbc->add_margin_child(TTR("View Z-Near:"), settings_znear);
  4841. settings_zfar = memnew(SpinBox);
  4842. settings_zfar->set_max(MAX_Z);
  4843. settings_zfar->set_min(MIN_Z);
  4844. settings_zfar->set_step(0.01);
  4845. settings_zfar->set_value(EDITOR_DEF("editors/3d/default_z_far", 1500));
  4846. settings_vbc->add_margin_child(TTR("View Z-Far:"), settings_zfar);
  4847. for (uint32_t i = 0; i < VIEWPORTS_COUNT; ++i) {
  4848. settings_dialog->connect("confirmed", viewports[i], "_update_camera", varray(0.0));
  4849. }
  4850. /* XFORM DIALOG */
  4851. xform_dialog = memnew(ConfirmationDialog);
  4852. xform_dialog->set_title(TTR("Transform Change"));
  4853. add_child(xform_dialog);
  4854. VBoxContainer *xform_vbc = memnew(VBoxContainer);
  4855. xform_dialog->add_child(xform_vbc);
  4856. Label *l = memnew(Label);
  4857. l->set_text(TTR("Translate:"));
  4858. xform_vbc->add_child(l);
  4859. HBoxContainer *xform_hbc = memnew(HBoxContainer);
  4860. xform_vbc->add_child(xform_hbc);
  4861. for (int i = 0; i < 3; i++) {
  4862. xform_translate[i] = memnew(LineEdit);
  4863. xform_translate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  4864. xform_hbc->add_child(xform_translate[i]);
  4865. }
  4866. l = memnew(Label);
  4867. l->set_text(TTR("Rotate (deg.):"));
  4868. xform_vbc->add_child(l);
  4869. xform_hbc = memnew(HBoxContainer);
  4870. xform_vbc->add_child(xform_hbc);
  4871. for (int i = 0; i < 3; i++) {
  4872. xform_rotate[i] = memnew(LineEdit);
  4873. xform_rotate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  4874. xform_hbc->add_child(xform_rotate[i]);
  4875. }
  4876. l = memnew(Label);
  4877. l->set_text(TTR("Scale (ratio):"));
  4878. xform_vbc->add_child(l);
  4879. xform_hbc = memnew(HBoxContainer);
  4880. xform_vbc->add_child(xform_hbc);
  4881. for (int i = 0; i < 3; i++) {
  4882. xform_scale[i] = memnew(LineEdit);
  4883. xform_scale[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  4884. xform_hbc->add_child(xform_scale[i]);
  4885. }
  4886. l = memnew(Label);
  4887. l->set_text(TTR("Transform Type"));
  4888. xform_vbc->add_child(l);
  4889. xform_type = memnew(OptionButton);
  4890. xform_type->set_h_size_flags(SIZE_EXPAND_FILL);
  4891. xform_type->add_item(TTR("Pre"));
  4892. xform_type->add_item(TTR("Post"));
  4893. xform_vbc->add_child(xform_type);
  4894. xform_dialog->connect("confirmed", this, "_xform_dialog_action");
  4895. scenario_debug = VisualServer::SCENARIO_DEBUG_DISABLED;
  4896. selected = NULL;
  4897. set_process_unhandled_key_input(true);
  4898. add_to_group("_spatial_editor_group");
  4899. EDITOR_DEF("editors/3d/manipulator_gizmo_size", 80);
  4900. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "editors/3d/manipulator_gizmo_size", PROPERTY_HINT_RANGE, "16,1024,1"));
  4901. EDITOR_DEF("editors/3d/manipulator_gizmo_opacity", 0.4);
  4902. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::REAL, "editors/3d/manipulator_gizmo_opacity", PROPERTY_HINT_RANGE, "0,1,0.01"));
  4903. EDITOR_DEF("editors/3d/navigation/show_viewport_rotation_gizmo", true);
  4904. over_gizmo_handle = -1;
  4905. }
  4906. SpatialEditor::~SpatialEditor() {
  4907. memdelete(preview_node);
  4908. }
  4909. void SpatialEditorPlugin::make_visible(bool p_visible) {
  4910. if (p_visible) {
  4911. spatial_editor->show();
  4912. spatial_editor->set_process(true);
  4913. } else {
  4914. spatial_editor->hide();
  4915. spatial_editor->set_process(false);
  4916. }
  4917. }
  4918. void SpatialEditorPlugin::edit(Object *p_object) {
  4919. spatial_editor->edit(Object::cast_to<Spatial>(p_object));
  4920. }
  4921. bool SpatialEditorPlugin::handles(Object *p_object) const {
  4922. return p_object->is_class("Spatial");
  4923. }
  4924. Dictionary SpatialEditorPlugin::get_state() const {
  4925. return spatial_editor->get_state();
  4926. }
  4927. void SpatialEditorPlugin::set_state(const Dictionary &p_state) {
  4928. spatial_editor->set_state(p_state);
  4929. }
  4930. void SpatialEditor::snap_cursor_to_plane(const Plane &p_plane) {
  4931. //cursor.pos=p_plane.project(cursor.pos);
  4932. }
  4933. Vector3 SpatialEditor::snap_point(Vector3 p_target, Vector3 p_start) const {
  4934. if (is_snap_enabled()) {
  4935. p_target.x = Math::snap_scalar(0.0, get_translate_snap(), p_target.x);
  4936. p_target.y = Math::snap_scalar(0.0, get_translate_snap(), p_target.y);
  4937. p_target.z = Math::snap_scalar(0.0, get_translate_snap(), p_target.z);
  4938. }
  4939. return p_target;
  4940. }
  4941. float SpatialEditor::get_translate_snap() const {
  4942. float snap_value;
  4943. if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
  4944. snap_value = snap_translate->get_text().to_double() / 10.0;
  4945. } else {
  4946. snap_value = snap_translate->get_text().to_double();
  4947. }
  4948. return snap_value;
  4949. }
  4950. float SpatialEditor::get_rotate_snap() const {
  4951. float snap_value;
  4952. if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
  4953. snap_value = snap_rotate->get_text().to_double() / 3.0;
  4954. } else {
  4955. snap_value = snap_rotate->get_text().to_double();
  4956. }
  4957. return snap_value;
  4958. }
  4959. float SpatialEditor::get_scale_snap() const {
  4960. float snap_value;
  4961. if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
  4962. snap_value = snap_scale->get_text().to_double() / 2.0;
  4963. } else {
  4964. snap_value = snap_scale->get_text().to_double();
  4965. }
  4966. return snap_value;
  4967. }
  4968. void SpatialEditorPlugin::_bind_methods() {
  4969. ClassDB::bind_method("snap_cursor_to_plane", &SpatialEditorPlugin::snap_cursor_to_plane);
  4970. }
  4971. void SpatialEditorPlugin::snap_cursor_to_plane(const Plane &p_plane) {
  4972. spatial_editor->snap_cursor_to_plane(p_plane);
  4973. }
  4974. struct _GizmoPluginPriorityComparator {
  4975. bool operator()(const Ref<EditorSpatialGizmoPlugin> &p_a, const Ref<EditorSpatialGizmoPlugin> &p_b) const {
  4976. if (p_a->get_priority() == p_b->get_priority()) {
  4977. return p_a->get_name() < p_b->get_name();
  4978. }
  4979. return p_a->get_priority() > p_b->get_priority();
  4980. }
  4981. };
  4982. struct _GizmoPluginNameComparator {
  4983. bool operator()(const Ref<EditorSpatialGizmoPlugin> &p_a, const Ref<EditorSpatialGizmoPlugin> &p_b) const {
  4984. return p_a->get_name() < p_b->get_name();
  4985. }
  4986. };
  4987. void SpatialEditor::add_gizmo_plugin(Ref<EditorSpatialGizmoPlugin> p_plugin) {
  4988. ERR_FAIL_NULL(p_plugin.ptr());
  4989. gizmo_plugins_by_priority.push_back(p_plugin);
  4990. gizmo_plugins_by_priority.sort_custom<_GizmoPluginPriorityComparator>();
  4991. gizmo_plugins_by_name.push_back(p_plugin);
  4992. gizmo_plugins_by_name.sort_custom<_GizmoPluginNameComparator>();
  4993. _update_gizmos_menu();
  4994. SpatialEditor::get_singleton()->update_all_gizmos();
  4995. }
  4996. void SpatialEditor::remove_gizmo_plugin(Ref<EditorSpatialGizmoPlugin> p_plugin) {
  4997. gizmo_plugins_by_priority.erase(p_plugin);
  4998. gizmo_plugins_by_name.erase(p_plugin);
  4999. _update_gizmos_menu();
  5000. }
  5001. SpatialEditorPlugin::SpatialEditorPlugin(EditorNode *p_node) {
  5002. editor = p_node;
  5003. spatial_editor = memnew(SpatialEditor(p_node));
  5004. spatial_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  5005. editor->get_viewport()->add_child(spatial_editor);
  5006. spatial_editor->hide();
  5007. spatial_editor->connect("transform_key_request", editor->get_inspector_dock(), "_transform_keyed");
  5008. }
  5009. SpatialEditorPlugin::~SpatialEditorPlugin() {
  5010. }
  5011. void EditorSpatialGizmoPlugin::create_material(const String &p_name, const Color &p_color, bool p_billboard, bool p_on_top, bool p_use_vertex_color) {
  5012. Color instanced_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/instanced", Color(0.7, 0.7, 0.7, 0.6));
  5013. Vector<Ref<SpatialMaterial> > mats;
  5014. for (int i = 0; i < 4; i++) {
  5015. bool selected = i % 2 == 1;
  5016. bool instanced = i < 2;
  5017. Ref<SpatialMaterial> material = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  5018. Color color = instanced ? instanced_color : p_color;
  5019. if (!selected) {
  5020. color.a *= 0.3;
  5021. }
  5022. material->set_albedo(color);
  5023. material->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  5024. material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  5025. material->set_render_priority(SpatialMaterial::RENDER_PRIORITY_MIN + 1);
  5026. if (p_use_vertex_color) {
  5027. material->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  5028. material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  5029. }
  5030. if (p_billboard) {
  5031. material->set_billboard_mode(SpatialMaterial::BILLBOARD_ENABLED);
  5032. }
  5033. if (p_on_top && selected) {
  5034. material->set_on_top_of_alpha();
  5035. }
  5036. mats.push_back(material);
  5037. }
  5038. materials[p_name] = mats;
  5039. }
  5040. void EditorSpatialGizmoPlugin::create_icon_material(const String &p_name, const Ref<Texture> &p_texture, bool p_on_top, const Color &p_albedo) {
  5041. Color instanced_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/instanced", Color(0.7, 0.7, 0.7, 0.6));
  5042. Vector<Ref<SpatialMaterial> > icons;
  5043. for (int i = 0; i < 4; i++) {
  5044. bool selected = i % 2 == 1;
  5045. bool instanced = i < 2;
  5046. Ref<SpatialMaterial> icon = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  5047. Color color = instanced ? instanced_color : p_albedo;
  5048. if (!selected) {
  5049. color.a *= 0.85;
  5050. }
  5051. icon->set_albedo(color);
  5052. icon->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  5053. icon->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  5054. icon->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  5055. icon->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  5056. icon->set_depth_draw_mode(SpatialMaterial::DEPTH_DRAW_DISABLED);
  5057. icon->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  5058. icon->set_texture(SpatialMaterial::TEXTURE_ALBEDO, p_texture);
  5059. icon->set_flag(SpatialMaterial::FLAG_FIXED_SIZE, true);
  5060. icon->set_billboard_mode(SpatialMaterial::BILLBOARD_ENABLED);
  5061. icon->set_render_priority(SpatialMaterial::RENDER_PRIORITY_MIN);
  5062. if (p_on_top && selected) {
  5063. icon->set_on_top_of_alpha();
  5064. }
  5065. icons.push_back(icon);
  5066. }
  5067. materials[p_name] = icons;
  5068. }
  5069. void EditorSpatialGizmoPlugin::create_handle_material(const String &p_name, bool p_billboard) {
  5070. Ref<SpatialMaterial> handle_material = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  5071. handle_material->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  5072. handle_material->set_flag(SpatialMaterial::FLAG_USE_POINT_SIZE, true);
  5073. Ref<Texture> handle_t = SpatialEditor::get_singleton()->get_icon("Editor3DHandle", "EditorIcons");
  5074. handle_material->set_point_size(handle_t->get_width());
  5075. handle_material->set_texture(SpatialMaterial::TEXTURE_ALBEDO, handle_t);
  5076. handle_material->set_albedo(Color(1, 1, 1));
  5077. handle_material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  5078. handle_material->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  5079. handle_material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  5080. handle_material->set_on_top_of_alpha();
  5081. if (p_billboard) {
  5082. handle_material->set_billboard_mode(SpatialMaterial::BILLBOARD_ENABLED);
  5083. handle_material->set_on_top_of_alpha();
  5084. }
  5085. materials[p_name] = Vector<Ref<SpatialMaterial> >();
  5086. materials[p_name].push_back(handle_material);
  5087. }
  5088. void EditorSpatialGizmoPlugin::add_material(const String &p_name, Ref<SpatialMaterial> p_material) {
  5089. materials[p_name] = Vector<Ref<SpatialMaterial> >();
  5090. materials[p_name].push_back(p_material);
  5091. }
  5092. Ref<SpatialMaterial> EditorSpatialGizmoPlugin::get_material(const String &p_name, const Ref<EditorSpatialGizmo> &p_gizmo) {
  5093. ERR_FAIL_COND_V(!materials.has(p_name), Ref<SpatialMaterial>());
  5094. ERR_FAIL_COND_V(materials[p_name].size() == 0, Ref<SpatialMaterial>());
  5095. if (p_gizmo.is_null() || materials[p_name].size() == 1) return materials[p_name][0];
  5096. int index = (p_gizmo->is_selected() ? 1 : 0) + (p_gizmo->is_editable() ? 2 : 0);
  5097. Ref<SpatialMaterial> mat = materials[p_name][index];
  5098. if (current_state == ON_TOP && p_gizmo->is_selected()) {
  5099. mat->set_flag(SpatialMaterial::FLAG_DISABLE_DEPTH_TEST, true);
  5100. } else {
  5101. mat->set_flag(SpatialMaterial::FLAG_DISABLE_DEPTH_TEST, false);
  5102. }
  5103. return mat;
  5104. }
  5105. String EditorSpatialGizmoPlugin::get_name() const {
  5106. if (get_script_instance() && get_script_instance()->has_method("get_name")) {
  5107. return get_script_instance()->call("get_name");
  5108. }
  5109. return TTR("Nameless gizmo");
  5110. }
  5111. int EditorSpatialGizmoPlugin::get_priority() const {
  5112. if (get_script_instance() && get_script_instance()->has_method("get_priority")) {
  5113. return get_script_instance()->call("get_priority");
  5114. }
  5115. return 0;
  5116. }
  5117. Ref<EditorSpatialGizmo> EditorSpatialGizmoPlugin::get_gizmo(Spatial *p_spatial) {
  5118. if (get_script_instance() && get_script_instance()->has_method("get_gizmo")) {
  5119. return get_script_instance()->call("get_gizmo", p_spatial);
  5120. }
  5121. Ref<EditorSpatialGizmo> ref = create_gizmo(p_spatial);
  5122. if (ref.is_null()) return ref;
  5123. ref->set_plugin(this);
  5124. ref->set_spatial_node(p_spatial);
  5125. ref->set_hidden(current_state == HIDDEN);
  5126. current_gizmos.push_back(ref.ptr());
  5127. return ref;
  5128. }
  5129. void EditorSpatialGizmoPlugin::_bind_methods() {
  5130. #define GIZMO_REF PropertyInfo(Variant::OBJECT, "gizmo", PROPERTY_HINT_RESOURCE_TYPE, "EditorSpatialGizmo")
  5131. BIND_VMETHOD(MethodInfo(Variant::BOOL, "has_gizmo", PropertyInfo(Variant::OBJECT, "spatial", PROPERTY_HINT_RESOURCE_TYPE, "Spatial")));
  5132. BIND_VMETHOD(MethodInfo(GIZMO_REF, "create_gizmo", PropertyInfo(Variant::OBJECT, "spatial", PROPERTY_HINT_RESOURCE_TYPE, "Spatial")));
  5133. ClassDB::bind_method(D_METHOD("create_material", "name", "color", "billboard", "on_top", "use_vertex_color"), &EditorSpatialGizmoPlugin::create_material, DEFVAL(false), DEFVAL(false), DEFVAL(false));
  5134. 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)));
  5135. ClassDB::bind_method(D_METHOD("create_handle_material", "name", "billboard"), &EditorSpatialGizmoPlugin::create_handle_material, DEFVAL(false));
  5136. ClassDB::bind_method(D_METHOD("add_material", "name", "material"), &EditorSpatialGizmoPlugin::add_material);
  5137. ClassDB::bind_method(D_METHOD("get_material", "name", "gizmo"), &EditorSpatialGizmoPlugin::get_material); //, DEFVAL(Ref<EditorSpatialGizmo>()));
  5138. BIND_VMETHOD(MethodInfo(Variant::STRING, "get_name"));
  5139. BIND_VMETHOD(MethodInfo(Variant::STRING, "get_priority"));
  5140. BIND_VMETHOD(MethodInfo(Variant::BOOL, "can_be_hidden"));
  5141. BIND_VMETHOD(MethodInfo(Variant::BOOL, "is_selectable_when_hidden"));
  5142. BIND_VMETHOD(MethodInfo("redraw", GIZMO_REF));
  5143. BIND_VMETHOD(MethodInfo(Variant::STRING, "get_handle_name", GIZMO_REF, PropertyInfo(Variant::INT, "index")));
  5144. MethodInfo hvget(Variant::NIL, "get_handle_value", GIZMO_REF, PropertyInfo(Variant::INT, "index"));
  5145. hvget.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  5146. BIND_VMETHOD(hvget);
  5147. BIND_VMETHOD(MethodInfo("set_handle", GIZMO_REF, PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::OBJECT, "camera", PROPERTY_HINT_RESOURCE_TYPE, "Camera"), PropertyInfo(Variant::VECTOR2, "point")));
  5148. MethodInfo cm = MethodInfo("commit_handle", GIZMO_REF, PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::NIL, "restore"), PropertyInfo(Variant::BOOL, "cancel"));
  5149. cm.default_arguments.push_back(false);
  5150. BIND_VMETHOD(cm);
  5151. BIND_VMETHOD(MethodInfo(Variant::BOOL, "is_handle_highlighted", GIZMO_REF, PropertyInfo(Variant::INT, "index")));
  5152. #undef GIZMO_REF
  5153. }
  5154. bool EditorSpatialGizmoPlugin::has_gizmo(Spatial *p_spatial) {
  5155. if (get_script_instance() && get_script_instance()->has_method("has_gizmo")) {
  5156. return get_script_instance()->call("has_gizmo", p_spatial);
  5157. }
  5158. return false;
  5159. }
  5160. Ref<EditorSpatialGizmo> EditorSpatialGizmoPlugin::create_gizmo(Spatial *p_spatial) {
  5161. if (get_script_instance() && get_script_instance()->has_method("create_gizmo")) {
  5162. return get_script_instance()->call("create_gizmo", p_spatial);
  5163. }
  5164. Ref<EditorSpatialGizmo> ref;
  5165. if (has_gizmo(p_spatial)) ref.instance();
  5166. return ref;
  5167. }
  5168. bool EditorSpatialGizmoPlugin::can_be_hidden() const {
  5169. if (get_script_instance() && get_script_instance()->has_method("can_be_hidden")) {
  5170. return get_script_instance()->call("can_be_hidden");
  5171. }
  5172. return true;
  5173. }
  5174. bool EditorSpatialGizmoPlugin::is_selectable_when_hidden() const {
  5175. if (get_script_instance() && get_script_instance()->has_method("is_selectable_when_hidden")) {
  5176. return get_script_instance()->call("is_selectable_when_hidden");
  5177. }
  5178. return false;
  5179. }
  5180. void EditorSpatialGizmoPlugin::redraw(EditorSpatialGizmo *p_gizmo) {
  5181. if (get_script_instance() && get_script_instance()->has_method("redraw")) {
  5182. Ref<EditorSpatialGizmo> ref(p_gizmo);
  5183. get_script_instance()->call("redraw", ref);
  5184. }
  5185. }
  5186. String EditorSpatialGizmoPlugin::get_handle_name(const EditorSpatialGizmo *p_gizmo, int p_idx) const {
  5187. if (get_script_instance() && get_script_instance()->has_method("get_handle_name")) {
  5188. return get_script_instance()->call("get_handle_name", p_gizmo, p_idx);
  5189. }
  5190. return "";
  5191. }
  5192. Variant EditorSpatialGizmoPlugin::get_handle_value(EditorSpatialGizmo *p_gizmo, int p_idx) const {
  5193. if (get_script_instance() && get_script_instance()->has_method("get_handle_value")) {
  5194. return get_script_instance()->call("get_handle_value", p_gizmo, p_idx);
  5195. }
  5196. return Variant();
  5197. }
  5198. void EditorSpatialGizmoPlugin::set_handle(EditorSpatialGizmo *p_gizmo, int p_idx, Camera *p_camera, const Point2 &p_point) {
  5199. if (get_script_instance() && get_script_instance()->has_method("set_handle")) {
  5200. get_script_instance()->call("set_handle", p_gizmo, p_idx, p_camera, p_point);
  5201. }
  5202. }
  5203. void EditorSpatialGizmoPlugin::commit_handle(EditorSpatialGizmo *p_gizmo, int p_idx, const Variant &p_restore, bool p_cancel) {
  5204. if (get_script_instance() && get_script_instance()->has_method("commit_handle")) {
  5205. get_script_instance()->call("commit_handle", p_gizmo, p_idx, p_restore, p_cancel);
  5206. }
  5207. }
  5208. bool EditorSpatialGizmoPlugin::is_handle_highlighted(const EditorSpatialGizmo *p_gizmo, int p_idx) const {
  5209. if (get_script_instance() && get_script_instance()->has_method("is_handle_highlighted")) {
  5210. return get_script_instance()->call("is_handle_highlighted", p_gizmo, p_idx);
  5211. }
  5212. return false;
  5213. }
  5214. void EditorSpatialGizmoPlugin::set_state(int p_state) {
  5215. current_state = p_state;
  5216. for (int i = 0; i < current_gizmos.size(); ++i) {
  5217. current_gizmos[i]->set_hidden(current_state == HIDDEN);
  5218. }
  5219. }
  5220. int EditorSpatialGizmoPlugin::get_state() const {
  5221. return current_state;
  5222. }
  5223. void EditorSpatialGizmoPlugin::unregister_gizmo(EditorSpatialGizmo *p_gizmo) {
  5224. current_gizmos.erase(p_gizmo);
  5225. }
  5226. EditorSpatialGizmoPlugin::EditorSpatialGizmoPlugin() {
  5227. current_state = VISIBLE;
  5228. }
  5229. EditorSpatialGizmoPlugin::~EditorSpatialGizmoPlugin() {
  5230. for (int i = 0; i < current_gizmos.size(); ++i) {
  5231. current_gizmos[i]->set_plugin(NULL);
  5232. current_gizmos[i]->get_spatial_node()->set_gizmo(NULL);
  5233. }
  5234. if (SpatialEditor::get_singleton()) {
  5235. SpatialEditor::get_singleton()->update_all_gizmos();
  5236. }
  5237. }