AmplifyShaderEditorWindow.cs 193 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107
  1. // Amplify Shader Editor - Visual Shader Editing Tool
  2. // Copyright (c) Amplify Creations, Lda <info@amplify.pt>
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. using UnityEditor;
  8. using UnityEditor.Callbacks;
  9. using UnityEngine;
  10. using UnityEngine.Networking;
  11. namespace AmplifyShaderEditor
  12. {
  13. // Disabling Substance Deprecated warning
  14. public class AmplifyShaderEditorWindow : SearchableEditorWindow, ISerializationCallbackReceiver
  15. {
  16. public const string PreviewSizeGlobalVariable = "_ASEPreviewSize";
  17. public const double InactivitySaveTime = 1.0;
  18. public const string ASEFileList = "ASEfileList";
  19. public const string CopyCommand = "Copy";
  20. public const string PasteCommand = "Paste";
  21. public const string SelectAll = "SelectAll";
  22. public const string Duplicate = "Duplicate";
  23. public const string ObjectSelectorClosed = "ObjectSelectorClosed";
  24. public const string LiveShaderError = "Live Shader only works with an assigned Master Node on the graph";
  25. private const string OnlineSharingWarning = "Please enable \"Allow downloads over HTTP*\" in Player Settings to use the Online Sharing feature.";
  26. //public Texture2D MasterNodeOnTexture = null;
  27. //public Texture2D MasterNodeOffTexture = null;
  28. //public Texture2D GPUInstancedOnTexture = null;
  29. //public Texture2D GPUInstancedOffTexture = null;
  30. private bool m_initialized = false;
  31. private bool m_checkInvalidConnections = false;
  32. private bool m_afterDeserializeFlag = true;
  33. [SerializeField]
  34. private ParentGraph m_customGraph = null;
  35. // UI
  36. private Rect m_graphArea;
  37. private Texture2D m_graphBgTexture;
  38. private Texture2D m_graphFgTexture;
  39. private GUIStyle m_graphFontStyle;
  40. //private GUIStyle _borderStyle;
  41. private Texture2D m_wireTexture;
  42. [SerializeField]
  43. TemplatesManager m_templatesManager;
  44. [SerializeField]
  45. private InnerWindowEditorVariables m_innerEditorVariables;
  46. [SerializeField]
  47. private string m_lastpath;
  48. [SerializeField]
  49. private ASESelectionMode m_selectionMode = ASESelectionMode.Shader;
  50. [SerializeField]
  51. private DuplicatePreventionBuffer m_duplicatePreventionBuffer;
  52. [SerializeField]
  53. private double m_inactivityTime = 0;
  54. // Prevent save ops every tick when on live mode
  55. [SerializeField]
  56. private double m_lastTimeSaved = 0;
  57. [SerializeField]
  58. private bool m_cacheSaveOp = false;
  59. private const double SaveTime = 1;
  60. private bool m_markedToSave = false;
  61. // Graph logic
  62. [SerializeField]
  63. private ParentGraph m_mainGraphInstance;
  64. public ParentGraph MainGraphInstance { get { return m_mainGraphInstance; } }
  65. // Camera control
  66. [SerializeField]
  67. private Vector2 m_cameraOffset;
  68. private float m_cameraSpeed = 1;
  69. private Rect m_cameraInfo;
  70. [SerializeField]
  71. private float m_cameraZoom;
  72. [SerializeField]
  73. private Vector2 m_minNodePos;
  74. [SerializeField]
  75. private Vector2 m_maxNodePos;
  76. [SerializeField]
  77. private bool m_isDirty;
  78. [SerializeField]
  79. private bool m_saveIsDirty;
  80. [SerializeField]
  81. private bool m_repaintIsDirty;
  82. [SerializeField]
  83. private bool m_liveShaderEditing = false;
  84. [SerializeField]
  85. private bool m_shaderIsModified = false;
  86. [SerializeField]
  87. private string m_lastOpenedLocation = string.Empty;
  88. [SerializeField]
  89. private bool m_zoomChanged = true;
  90. [SerializeField]
  91. private float m_lastWindowWidth = 0;
  92. [SerializeField]
  93. private int m_graphCount = 0;
  94. [SerializeField]
  95. private double m_currentInactiveTime = 0;
  96. private bool m_ctrlSCallback = false;
  97. private bool m_altBoxSelection = false;
  98. private bool m_altDragStarted = false;
  99. private bool m_altPressDown = false;
  100. private bool m_altAvailable = true;
  101. // Events
  102. private Vector3 m_currentMousePos;
  103. private Vector2 m_keyEvtMousePos2D;
  104. private Vector2 m_currentMousePos2D;
  105. private Event m_currentEvent;
  106. private string m_currentCommandName = string.Empty;
  107. private bool m_insideEditorWindow;
  108. private bool m_lostFocus = false;
  109. // Selection box for multiple node selection
  110. private bool m_multipleSelectionActive = false;
  111. private bool m_lmbPressed = false;
  112. private Vector2 m_multipleSelectionStart;
  113. private Rect m_multipleSelectionArea = new Rect( 0, 0, 0, 0 );
  114. private bool m_autoPanDirActive = false;
  115. private bool m_forceAutoPanDir = false;
  116. private bool m_refreshOnUndo = false;
  117. private bool m_loadShaderOnSelection = false;
  118. private bool m_refreshAvailableNodes = false;
  119. private double m_time;
  120. //Context Menu
  121. private Vector2 m_rmbStartPos;
  122. private Vector2 m_altKeyStartPos;
  123. private GraphContextMenu m_contextMenu;
  124. private ShortcutsManager m_shortcutManager;
  125. [SerializeField]
  126. private NodeAvailability m_currentNodeAvailability = NodeAvailability.SurfaceShader;
  127. //Clipboard
  128. private Clipboard m_clipboard;
  129. //Node Parameters Window
  130. [SerializeField]
  131. private bool m_nodeParametersWindowMaximized = true;
  132. private NodeParametersWindow m_nodeParametersWindow;
  133. // Tools Window
  134. private ToolsWindow m_toolsWindow;
  135. private ConsoleLogWindow m_consoleLogWindow;
  136. //Editor Options
  137. private OptionsWindow m_optionsWindow;
  138. // Mode Window
  139. private ShaderEditorModeWindow m_modeWindow;
  140. // Tools Window
  141. private TipsWindow m_tipsWindow;
  142. //Palette Window
  143. [SerializeField]
  144. private bool m_paletteWindowMaximized = true;
  145. private PaletteWindow m_paletteWindow;
  146. private ContextPalette m_contextPalette;
  147. private PalettePopUp m_palettePopup;
  148. private System.Type m_paletteChosenType;
  149. private AmplifyShaderFunction m_paletteChosenFunction;
  150. // In-Editor Message System
  151. GenericMessageUI m_genericMessageUI;
  152. private GUIContent m_genericMessageContent;
  153. // Drag&Drop Tool
  154. private DragAndDropTool m_dragAndDropTool;
  155. //Custom Styles
  156. //private CustomStylesContainer m_customStyles;
  157. private AmplifyShaderFunction m_previousShaderFunction;
  158. private List<MenuParent> m_registeredMenus;
  159. private PreMadeShaders m_preMadeShaders;
  160. private AutoPanData[] m_autoPanArea;
  161. private DrawInfo m_drawInfo;
  162. private KeyCode m_lastKeyPressed = KeyCode.None;
  163. private System.Type m_commentaryTypeNode;
  164. private int m_onLoadDone = 0;
  165. private float m_copyPasteDeltaMul = 0;
  166. private Vector2 m_copyPasteInitialPos = Vector2.zero;
  167. private Vector2 m_copyPasteDeltaPos = Vector2.zero;
  168. private int m_repaintCount = 0;
  169. private bool m_forceUpdateFromMaterialFlag = false;
  170. private UnityEngine.Object m_delayedLoadObject = null;
  171. private double m_focusOnSelectionTimestamp;
  172. private double m_focusOnMasterNodeTimestamp;
  173. private double m_wiredDoubleTapTimestamp;
  174. private bool m_globalPreview = false;
  175. private bool m_globalShowInternalData = true;
  176. private const double AutoZoomTime = 0.25;
  177. private const double ToggleTime = 0.25;
  178. private const double WiredDoubleTapTime = 0.25;
  179. private const double DoubleClickTime = 0.25;
  180. private Material m_delayedMaterialSet = null;
  181. private bool m_mouseDownOnValidArea = false;
  182. private bool m_removedKeyboardFocus = false;
  183. private int m_lastHotControl = -1;
  184. [SerializeField]
  185. private bool m_isShaderFunctionWindow = false;
  186. private string m_currentTitle = string.Empty;
  187. private bool m_currentTitleMod = false;
  188. //private Material m_maskingMaterial = null;
  189. //private int m_cachedProjectInLinearId = -1;
  190. private int m_cachedEditorTimeId = -1;
  191. private int m_cachedEditorDeltaTimeId = -1;
  192. //private float m_repaintFrequency = 15;
  193. //private double m_repaintTimestamp = 0;
  194. // Smooth Zoom
  195. private bool m_smoothZoom = false;
  196. private float m_targetZoom;
  197. private double m_zoomTime;
  198. private Vector2 m_zoomPivot;
  199. private float m_targetZoomIncrement;
  200. private float m_zoomVelocity = 0;
  201. // Smooth Pan
  202. private bool m_smoothOffset = false;
  203. private double m_offsetTime;
  204. private Vector2 m_targetOffset;
  205. private Vector2 m_camVelocity = Vector2.zero;
  206. // Auto-Compile samples
  207. private bool m_forcingMaterialUpdateFlag = false;
  208. private bool m_forcingMaterialUpdateOp = false;
  209. private List<Material> m_materialsToUpdate = new List<Material>();
  210. private NodeExporterUtils m_nodeExporterUtils;
  211. private bool m_performFullUndoRegister = true;
  212. //[SerializeField]
  213. //private AmplifyShaderFunction m_openedShaderFunction;
  214. [SerializeField]
  215. private bool m_openedAssetFromNode = false;
  216. private bool m_nodesLoadedCorrectly = false;
  217. private GUIContent NodesExceptionMessage = new GUIContent( "ASE is unable to load correctly due to some faulty other classes/plugin in your project. We advise to review all your imported plugins." );
  218. private bool m_outdatedShaderFromTemplateLoaded = false;
  219. private bool m_replaceMasterNode = false;
  220. private AvailableShaderTypes m_replaceMasterNodeType;
  221. private string m_replaceMasterNodeData;
  222. private bool m_replaceMasterNodeDataFromCache;
  223. private NodeWireReferencesUtils m_wireReferenceUtils = new NodeWireReferencesUtils();
  224. private ParentNode m_nodeToFocus = null;
  225. private float m_zoomToFocus = 1.0f;
  226. private bool m_selectNodeToFocus = true;
  227. [NonSerialized]
  228. public Dictionary<string, bool> VisitedChanged = new Dictionary<string, bool>();
  229. [SerializeField]
  230. private List<Toast> m_messages = new List<Toast>();
  231. [SerializeField]
  232. private float m_maxMsgWidth = 100;
  233. [SerializeField]
  234. private bool m_maximizeMessages = false;
  235. [NonSerialized]
  236. private Dictionary<string, OutputPort> m_savedList = new Dictionary<string, OutputPort>();
  237. public int m_frameCounter = 0;
  238. public double m_fpsTime = 0;
  239. public string m_fpsDisplay = string.Empty;
  240. #if UNITY_EDITOR_WIN
  241. // ScreenShot vars
  242. IntPtr m_aseHandle;
  243. private Rect m_prevWindowRect;
  244. private Vector2 m_prevCameraOffset;
  245. private float m_prevCameraZoom;
  246. private bool m_openSavedFolder = false;
  247. private bool m_takeScreenShot = false;
  248. #endif
  249. public bool CheckFunctions = false;
  250. private static System.Diagnostics.Stopwatch m_batchTimer = new System.Diagnostics.Stopwatch();
  251. // Unity Menu item
  252. [MenuItem( "Window/Amplify Shader Editor/Open Canvas", false, 1000 )]
  253. static void OpenMainShaderGraph()
  254. {
  255. if( IOUtils.AllOpenedWindows.Count > 0 )
  256. {
  257. AmplifyShaderEditorWindow currentWindow = CreateTab( "Empty", UIUtils.ShaderIcon );
  258. UIUtils.CurrentWindow = currentWindow;
  259. currentWindow.CreateNewGraph( "Empty" );
  260. currentWindow.Show();
  261. }
  262. else
  263. {
  264. AmplifyShaderEditorWindow currentWindow = OpenWindow( "Empty", UIUtils.ShaderIcon );
  265. currentWindow.CreateNewGraph( "Empty" );
  266. //currentWindow.Show();
  267. }
  268. }
  269. public static string GenerateTabTitle( string original, bool modified = false )
  270. {
  271. GUIContent content = new GUIContent( original );
  272. GUIStyle tabStyle = new GUIStyle( (GUIStyle)"dragtabdropwindow" );// GUI.skin.FindStyle( "dragtabdropwindow" );
  273. string finalTitle = string.Empty;
  274. bool addEllipsis = false;
  275. for( int i = 1; i <= original.Length; i++ )
  276. {
  277. content.text = original.Substring( 0, i );
  278. Vector2 titleSize = tabStyle.CalcSize( content );
  279. int maxSize = modified ? 62 : 69;
  280. if( titleSize.x > maxSize )
  281. {
  282. addEllipsis = true;
  283. break;
  284. }
  285. else
  286. {
  287. finalTitle = content.text;
  288. }
  289. }
  290. if( addEllipsis )
  291. finalTitle += "..";
  292. if( modified )
  293. finalTitle += "*";
  294. return finalTitle;
  295. }
  296. public static void ConvertShaderToASE( Shader shader, bool OpenOnSeparateWindow = false )
  297. {
  298. if( UIUtils.IsUnityNativeShader( shader ) )
  299. {
  300. Debug.LogWarningFormat( "Action not allowed. Attempting to load the native {0} shader into Amplify Shader Editor", shader.name );
  301. return;
  302. }
  303. if ( IOUtils.IsASEShader( shader ) )
  304. {
  305. if ( OpenOnSeparateWindow )
  306. {
  307. AmplifyShaderEditorWindow currentWindow = CreateTab( shader.name , UIUtils.ShaderIcon );
  308. UIUtils.CurrentWindow = currentWindow;
  309. currentWindow.Show();
  310. }
  311. else
  312. {
  313. string guid = AssetDatabase.AssetPathToGUID( AssetDatabase.GetAssetPath( shader ) );
  314. if( IOUtils.AllOpenedWindows.Count > 0 )
  315. {
  316. AmplifyShaderEditorWindow openedTab = null;
  317. for( int i = 0 ; i < IOUtils.AllOpenedWindows.Count ; i++ )
  318. {
  319. //if( AssetDatabase.GetAssetPath( shader ).Equals( IOUtils.AllOpenedWindows[ i ].LastOpenedLocation ) )
  320. if( guid.Equals( IOUtils.AllOpenedWindows[ i ].GUID ) )
  321. {
  322. openedTab = IOUtils.AllOpenedWindows[ i ];
  323. break;
  324. }
  325. }
  326. if( openedTab != null )
  327. {
  328. openedTab.wantsMouseMove = true;
  329. openedTab.ShowTab();
  330. UIUtils.CurrentWindow = openedTab;
  331. }
  332. else
  333. {
  334. EditorWindow openedWindow = AmplifyShaderEditorWindow.GetWindow<AmplifyShaderEditorWindow>();
  335. AmplifyShaderEditorWindow currentWindow = CreateTab();
  336. WindowHelper.AddTab( openedWindow , currentWindow );
  337. UIUtils.CurrentWindow = currentWindow;
  338. }
  339. }
  340. else
  341. {
  342. AmplifyShaderEditorWindow currentWindow = OpenWindow( shader.name , UIUtils.ShaderIcon );
  343. UIUtils.CurrentWindow = currentWindow;
  344. }
  345. }
  346. UIUtils.CurrentWindow.LoadProjectSelected( shader );
  347. }
  348. else
  349. {
  350. Debug.LogWarning( "[AmplifyShaderEditor] Can't open shader " + shader.name + " because it was not created in ASE." );
  351. //UIUtils.CreateEmptyFromInvalid( shader );
  352. //UIUtils.ShowMessage( "Trying to open shader not created on ASE! BEWARE, old data will be lost if saving it here!", MessageSeverity.Warning );
  353. //if( UIUtils.CurrentWindow.LiveShaderEditing )
  354. //{
  355. // UIUtils.ShowMessage( "Disabling Live Shader Editing. Must manually re-enable it.", MessageSeverity.Warning );
  356. // UIUtils.CurrentWindow.LiveShaderEditing = false;
  357. //}
  358. }
  359. }
  360. public static void LoadMaterialToASE( Material material )
  361. {
  362. string guid = AssetDatabase.AssetPathToGUID( AssetDatabase.GetAssetPath( material.shader ) );
  363. if( IOUtils.AllOpenedWindows.Count > 0 )
  364. {
  365. AmplifyShaderEditorWindow openedTab = null;
  366. for( int i = 0; i < IOUtils.AllOpenedWindows.Count; i++ )
  367. {
  368. //if( AssetDatabase.GetAssetPath( material.shader ).Equals( IOUtils.AllOpenedWindows[ i ].LastOpenedLocation ) )
  369. if( guid.Equals( IOUtils.AllOpenedWindows[ i ].GUID ) )
  370. {
  371. openedTab = IOUtils.AllOpenedWindows[ i ];
  372. break;
  373. }
  374. }
  375. if( openedTab != null )
  376. {
  377. openedTab.wantsMouseMove = true;
  378. openedTab.ShowTab();
  379. UIUtils.CurrentWindow = openedTab;
  380. }
  381. else
  382. {
  383. EditorWindow openedWindow = AmplifyShaderEditorWindow.GetWindow<AmplifyShaderEditorWindow>();
  384. AmplifyShaderEditorWindow currentWindow = CreateTab();
  385. WindowHelper.AddTab( openedWindow, currentWindow );
  386. UIUtils.CurrentWindow = currentWindow;
  387. }
  388. }
  389. else
  390. {
  391. AmplifyShaderEditorWindow currentWindow = OpenWindow( material.name, UIUtils.MaterialIcon );
  392. UIUtils.CurrentWindow = currentWindow;
  393. }
  394. if( IOUtils.IsASEShader( material.shader ) )
  395. {
  396. UIUtils.CurrentWindow.LoadProjectSelected( material );
  397. }
  398. else
  399. {
  400. UIUtils.CreateEmptyFromInvalid( material.shader );
  401. UIUtils.SetDelayedMaterialMode( material );
  402. }
  403. }
  404. public static void LoadShaderFunctionToASE( AmplifyShaderFunction shaderFunction, bool openedAssetFromNode , bool OpenOnSeparateWindow = false )
  405. {
  406. string guid = AssetDatabase.AssetPathToGUID( AssetDatabase.GetAssetPath( shaderFunction ) );
  407. if( OpenOnSeparateWindow )
  408. {
  409. AmplifyShaderEditorWindow currentWindow = CreateTab( shaderFunction.FunctionName , UIUtils.ShaderFunctionIcon );
  410. UIUtils.CurrentWindow = currentWindow;
  411. currentWindow.Show();
  412. }
  413. else
  414. {
  415. if( IOUtils.AllOpenedWindows.Count > 0 )
  416. {
  417. AmplifyShaderEditorWindow openedTab = null;
  418. for( int i = 0 ; i < IOUtils.AllOpenedWindows.Count ; i++ )
  419. {
  420. //if( AssetDatabase.GetAssetPath( shaderFunction ).Equals( IOUtils.AllOpenedWindows[ i ].LastOpenedLocation ) )
  421. if( guid.Equals( IOUtils.AllOpenedWindows[ i ].GUID ) )
  422. {
  423. openedTab = IOUtils.AllOpenedWindows[ i ];
  424. break;
  425. }
  426. }
  427. if( openedTab != null )
  428. {
  429. openedTab.wantsMouseMove = true;
  430. openedTab.ShowTab();
  431. UIUtils.CurrentWindow = openedTab;
  432. }
  433. else
  434. {
  435. EditorWindow openedWindow = AmplifyShaderEditorWindow.GetWindow<AmplifyShaderEditorWindow>();
  436. AmplifyShaderEditorWindow currentWindow = CreateTab();
  437. WindowHelper.AddTab( openedWindow , currentWindow );
  438. UIUtils.CurrentWindow = currentWindow;
  439. }
  440. }
  441. else
  442. {
  443. AmplifyShaderEditorWindow currentWindow = OpenWindow( shaderFunction.FunctionName , UIUtils.ShaderFunctionIcon );
  444. UIUtils.CurrentWindow = currentWindow;
  445. }
  446. }
  447. UIUtils.CurrentWindow.OpenedAssetFromNode = openedAssetFromNode;
  448. if( IOUtils.IsShaderFunction( shaderFunction.FunctionInfo ) )
  449. {
  450. UIUtils.CurrentWindow.LoadProjectSelected( shaderFunction );
  451. }
  452. else
  453. {
  454. UIUtils.CurrentWindow.titleContent.text = GenerateTabTitle( shaderFunction.FunctionName );
  455. UIUtils.CurrentWindow.titleContent.image = UIUtils.ShaderFunctionIcon;
  456. UIUtils.CreateEmptyFunction( shaderFunction );
  457. }
  458. }
  459. public static void LoadAndSaveList( string[] assetList )
  460. {
  461. m_batchTimer.Reset();
  462. m_batchTimer.Start();
  463. EditorPrefs.SetString( ASEFileList , string.Join( ",", assetList ) );
  464. if( assetList[ 0 ].EndsWith( ".asset" ) )
  465. {
  466. var obj = AssetDatabase.LoadAssetAtPath<AmplifyShaderFunction>( assetList[ 0 ] );
  467. AmplifyShaderEditorWindow.LoadShaderFunctionToASE( obj, false , true );
  468. }
  469. else
  470. {
  471. var obj = AssetDatabase.LoadAssetAtPath<Shader>( assetList[ 0 ] );
  472. AmplifyShaderEditorWindow.ConvertShaderToASE( obj, true );
  473. }
  474. UIUtils.CurrentWindow.State = AmplifyShaderEditorWindow.OpenSaveState.OPEN;
  475. UIUtils.CurrentWindow.Repaint();
  476. }
  477. public static AmplifyShaderEditorWindow OpenWindow( string title = null, Texture icon = null )
  478. {
  479. AmplifyShaderEditorWindow currentWindow = (AmplifyShaderEditorWindow)AmplifyShaderEditorWindow.GetWindow( typeof( AmplifyShaderEditorWindow ), false );
  480. currentWindow.minSize = new Vector2( ( Constants.MINIMIZE_WINDOW_LOCK_SIZE - 150 ), 270 );
  481. currentWindow.wantsMouseMove = true;
  482. if( title != null )
  483. currentWindow.titleContent.text = GenerateTabTitle( title );
  484. if( icon != null )
  485. currentWindow.titleContent.image = icon;
  486. return currentWindow;
  487. }
  488. public static AmplifyShaderEditorWindow CreateTab( string title = null, Texture icon = null )
  489. {
  490. AmplifyShaderEditorWindow currentWindow = EditorWindow.CreateInstance<AmplifyShaderEditorWindow>();
  491. currentWindow.minSize = new Vector2( ( Constants.MINIMIZE_WINDOW_LOCK_SIZE - 150 ), 270 );
  492. currentWindow.wantsMouseMove = true;
  493. if( title != null )
  494. currentWindow.titleContent.text = GenerateTabTitle( title );
  495. if( icon != null )
  496. currentWindow.titleContent.image = icon;
  497. return currentWindow;
  498. }
  499. public double CalculateInactivityTime()
  500. {
  501. double currTime = EditorApplication.timeSinceStartup;
  502. switch( Event.current.type )
  503. {
  504. case EventType.MouseDown:
  505. case EventType.MouseUp:
  506. //case EventType.MouseMove:
  507. case EventType.MouseDrag:
  508. case EventType.KeyDown:
  509. case EventType.KeyUp:
  510. case EventType.ScrollWheel:
  511. case EventType.DragUpdated:
  512. case EventType.DragPerform:
  513. case EventType.DragExited:
  514. case EventType.ValidateCommand:
  515. case EventType.ExecuteCommand:
  516. {
  517. m_inactivityTime = currTime;
  518. return 0;
  519. }
  520. }
  521. return currTime - m_inactivityTime;
  522. }
  523. public void ActivatePreviews( bool value )
  524. {
  525. m_mainGraphInstance.ActivatePreviews( value );
  526. }
  527. // Shader Graph window
  528. public override void OnEnable()
  529. {
  530. base.OnEnable();
  531. UndoUtils.RegisterUndoRedoCallback( UndoRedoPerformed );
  532. m_nodeExporterUtils = new NodeExporterUtils( this );
  533. ASEPackageManagerHelper.RequestInfo();
  534. ASEPackageManagerHelper.Update();
  535. Shader.SetGlobalVector( PreviewSizeGlobalVariable, new Vector4( Constants.PreviewSize , Constants.PreviewSize , 0, 0 ) );
  536. if( m_templatesManager == null )
  537. {
  538. m_templatesManager = IOUtils.FirstValidTemplatesManager;
  539. if( m_templatesManager == null )
  540. {
  541. m_templatesManager = ScriptableObject.CreateInstance<TemplatesManager>();
  542. m_templatesManager.Init();
  543. if( TemplatesManager.ShowDebugMessages )
  544. Debug.Log( "Creating Manager" );
  545. }
  546. else
  547. {
  548. if( TemplatesManager.ShowDebugMessages )
  549. Debug.Log( "Assigning Manager" );
  550. }
  551. }
  552. else if( !m_templatesManager.Initialized )
  553. {
  554. if( TemplatesManager.ShowDebugMessages )
  555. Debug.Log( "Re-Initializing Manager" );
  556. m_templatesManager.Init();
  557. }
  558. TemplatePostProcessor.Destroy();
  559. if( m_innerEditorVariables == null )
  560. {
  561. m_innerEditorVariables = new InnerWindowEditorVariables();
  562. m_innerEditorVariables.Initialize();
  563. }
  564. if( m_mainGraphInstance == null )
  565. {
  566. m_mainGraphInstance = CreateInstance<ParentGraph>();
  567. m_mainGraphInstance.Init();
  568. m_mainGraphInstance.ParentWindow = this;
  569. m_mainGraphInstance.SetGraphId( 0 );
  570. }
  571. m_mainGraphInstance.ResetEvents();
  572. m_mainGraphInstance.OnNodeEvent += OnNodeStoppedMovingEvent;
  573. m_mainGraphInstance.OnMaterialUpdatedEvent += OnMaterialUpdated;
  574. m_mainGraphInstance.OnShaderUpdatedEvent += OnShaderUpdated;
  575. m_mainGraphInstance.OnEmptyGraphDetectedEvt += OnEmptyGraphDetected;
  576. m_mainGraphInstance.OnNodeRemovedEvent += m_toolsWindow.OnNodeRemovedFromGraph;
  577. GraphCount = 1;
  578. IOUtils.Init();
  579. IOUtils.AllOpenedWindows.Add( this );
  580. // Only runs once for multiple windows
  581. EditorApplication.update -= IOUtils.UpdateIO;
  582. EditorApplication.update += IOUtils.UpdateIO;
  583. //EditorApplication.update -= UpdateTime;
  584. EditorApplication.update -= UpdateNodePreviewListAndTime;
  585. //EditorApplication.update += UpdateTime;
  586. EditorApplication.update += UpdateNodePreviewListAndTime;
  587. if( CurrentSelection == ASESelectionMode.ShaderFunction )
  588. {
  589. IsShaderFunctionWindow = true;
  590. }
  591. else
  592. {
  593. IsShaderFunctionWindow = false;
  594. }
  595. m_optionsWindow = new OptionsWindow( this );
  596. m_optionsWindow.Init();
  597. m_contextMenu = new GraphContextMenu( m_mainGraphInstance );
  598. m_nodesLoadedCorrectly = m_contextMenu.CorrectlyLoaded;
  599. m_paletteWindow = new PaletteWindow( this )
  600. {
  601. Resizable = true
  602. };
  603. m_paletteWindow.OnPaletteNodeCreateEvt += OnPaletteNodeCreate;
  604. m_registeredMenus.Add( m_paletteWindow );
  605. m_contextPalette = new ContextPalette( this );
  606. m_contextPalette.OnPaletteNodeCreateEvt += OnContextPaletteNodeCreate;
  607. m_registeredMenus.Add( m_contextPalette );
  608. m_genericMessageUI = new GenericMessageUI();
  609. m_genericMessageUI.OnMessageDisplayEvent += ShowMessageImmediately;
  610. Selection.selectionChanged += OnProjectSelectionChanged;
  611. EditorApplication.projectChanged += OnProjectWindowChanged;
  612. m_focusOnSelectionTimestamp = EditorApplication.timeSinceStartup;
  613. m_focusOnMasterNodeTimestamp = EditorApplication.timeSinceStartup;
  614. m_nodeParametersWindow.IsMaximized = m_innerEditorVariables.NodeParametersMaximized;
  615. if( DebugConsoleWindow.UseShaderPanelsInfo )
  616. m_nodeParametersWindow.IsMaximized = m_nodeParametersWindowMaximized;
  617. m_paletteWindow.IsMaximized = m_innerEditorVariables.NodePaletteMaximized;
  618. if( DebugConsoleWindow.UseShaderPanelsInfo )
  619. m_paletteWindow.IsMaximized = m_paletteWindowMaximized;
  620. m_shortcutManager = new ShortcutsManager();
  621. // REGISTER NODE SHORTCUTS
  622. foreach( KeyValuePair<KeyCode, ShortcutKeyData> kvp in m_contextMenu.NodeShortcuts )
  623. {
  624. m_shortcutManager.RegisterNodesShortcuts( kvp.Key, kvp.Value.Name );
  625. }
  626. // REGISTER EDITOR SHORTCUTS
  627. m_shortcutManager.RegisterEditorShortcut( true, EventModifiers.FunctionKey, KeyCode.F1, "Open Selected Node Wiki page", () =>
  628. {
  629. List<ParentNode> selectedNodes = m_mainGraphInstance.SelectedNodes;
  630. if( selectedNodes != null && selectedNodes.Count == 1 )
  631. {
  632. FunctionNode shaderFunctionNode = selectedNodes[ 0 ] as FunctionNode;
  633. if( shaderFunctionNode != null )
  634. {
  635. string url = ( string.IsNullOrEmpty( shaderFunctionNode.Function.URL ) ) ?
  636. Constants.NodeCommonUrl + UIUtils.UrlReplaceInvalidStrings( shaderFunctionNode.Function.FunctionName ) :
  637. shaderFunctionNode.Function.URL;
  638. Application.OpenURL( url );
  639. }
  640. else
  641. {
  642. if( selectedNodes[ 0 ].Attributes != null )
  643. {
  644. Application.OpenURL( selectedNodes[ 0 ].Attributes.NodeUrl );
  645. }
  646. else
  647. {
  648. UIUtils.ShowMessage( "Selected node doesn't have valid attibutes to get URL from." );
  649. }
  650. }
  651. }
  652. } );
  653. m_shortcutManager.RegisterEditorShortcut( true, KeyCode.C, "Create Commentary", () =>
  654. {
  655. // Create commentary
  656. ParentNode[] selectedNodes = m_mainGraphInstance.SelectedNodes.ToArray();
  657. UIUtils.MarkUndoAction();
  658. UndoUtils.RegisterCompleteObjectUndo( this, "Adding Commentary Node" );
  659. CommentaryNode node = m_mainGraphInstance.CreateNode( m_commentaryTypeNode, true, -1, false ) as CommentaryNode;
  660. node.CreateFromSelectedNodes( TranformedMousePos, selectedNodes );
  661. node.Focus();
  662. m_mainGraphInstance.DeSelectAll();
  663. m_mainGraphInstance.SelectNode( node, false, false );
  664. SetSaveIsDirty();
  665. ForceRepaint();
  666. } );
  667. m_shortcutManager.RegisterEditorShortcut( true, KeyCode.F, "Focus On Selection", () =>
  668. {
  669. OnToolButtonPressed( ToolButtonType.FocusOnSelection );
  670. ForceRepaint();
  671. } );
  672. //m_shortcutManager.RegisterEditorShortcut( true, EventModifiers.None, KeyCode.B, "New Master Node", () =>
  673. //{
  674. // OnToolButtonPressed( ToolButtonType.MasterNode );
  675. // ForceRepaint();
  676. //} );
  677. m_shortcutManager.RegisterEditorShortcut( true, EventModifiers.None, KeyCode.Space, "Open Node Palette", null, () =>
  678. {
  679. m_contextPalette.Show( m_currentMousePos2D, m_cameraInfo );
  680. } );
  681. m_shortcutManager.RegisterEditorShortcut( true, KeyCode.W, "Toggle Colored Line Mode", () =>
  682. {
  683. m_optionsWindow.ColoredPorts = !m_optionsWindow.ColoredPorts;
  684. ForceRepaint();
  685. } );
  686. m_shortcutManager.RegisterEditorShortcut( true, EventModifiers.Control, KeyCode.W, "Toggle Multi-Line Mode", () =>
  687. {
  688. m_optionsWindow.MultiLinePorts = !m_optionsWindow.MultiLinePorts;
  689. ForceRepaint();
  690. } );
  691. m_shortcutManager.RegisterEditorShortcut( true, KeyCode.P, "Global Preview", () =>
  692. {
  693. GlobalPreview = !GlobalPreview;
  694. EditorPrefs.SetBool( "GlobalPreview", GlobalPreview );
  695. ForceRepaint();
  696. } );
  697. GlobalShowInternalData = EditorPrefs.GetBool( "ASEGlobalShowInternalData", true );
  698. m_shortcutManager.RegisterEditorShortcut( true, KeyCode.I, "Global Show Internal Data", () =>
  699. {
  700. GlobalShowInternalData = !GlobalShowInternalData;
  701. EditorPrefs.SetBool( "ASEGlobalShowInternalData", GlobalShowInternalData );
  702. ForceRepaint();
  703. } );
  704. m_shortcutManager.RegisterEditorShortcut( true, EventModifiers.FunctionKey, KeyCode.Delete, "Delete selected nodes", DeleteSelectedNodeWithRepaint );
  705. m_shortcutManager.RegisterEditorShortcut( true, EventModifiers.FunctionKey, KeyCode.Backspace, "Delete selected nodes", DeleteSelectedNodeWithRepaint );
  706. m_liveShaderEditing = m_innerEditorVariables.LiveMode;
  707. UpdateLiveUI();
  708. }
  709. public AmplifyShaderEditorWindow()
  710. {
  711. m_minNodePos = new Vector2( float.MaxValue, float.MaxValue );
  712. m_maxNodePos = new Vector2( float.MinValue, float.MinValue );
  713. m_duplicatePreventionBuffer = new DuplicatePreventionBuffer();
  714. m_commentaryTypeNode = typeof( CommentaryNode );
  715. titleContent = new GUIContent( "Shader Editor" );
  716. autoRepaintOnSceneChange = true;
  717. m_currentMousePos = new Vector3( 0, 0, 0 );
  718. m_keyEvtMousePos2D = new Vector2( 0, 0 );
  719. m_multipleSelectionStart = new Vector2( 0, 0 );
  720. m_initialized = false;
  721. m_graphBgTexture = null;
  722. m_graphFgTexture = null;
  723. m_cameraOffset = new Vector2( 0, 0 );
  724. CameraZoom = 1;
  725. m_registeredMenus = new List<MenuParent>();
  726. m_nodeParametersWindow = new NodeParametersWindow( this )
  727. {
  728. Resizable = true
  729. };
  730. m_registeredMenus.Add( m_nodeParametersWindow );
  731. m_modeWindow = new ShaderEditorModeWindow( this );
  732. //_registeredMenus.Add( _modeWindow );
  733. m_toolsWindow = new ToolsWindow( this );
  734. m_toolsWindow.ToolButtonPressedEvt += OnToolButtonPressed;
  735. m_consoleLogWindow = new ConsoleLogWindow( this );
  736. m_tipsWindow = new TipsWindow( this );
  737. m_registeredMenus.Add( m_toolsWindow );
  738. //m_registeredMenus.Add( m_consoleLogWindow );
  739. m_palettePopup = new PalettePopUp();
  740. m_clipboard = new Clipboard();
  741. m_genericMessageContent = new GUIContent();
  742. m_dragAndDropTool = new DragAndDropTool();
  743. m_dragAndDropTool.OnValidDropObjectEvt += OnValidObjectsDropped;
  744. //_confirmationWindow = new ConfirmationWindow( 100, 100, 300, 100 );
  745. m_saveIsDirty = false;
  746. m_preMadeShaders = new PreMadeShaders();
  747. float autoPanSpeed = 2;
  748. m_autoPanArea = new AutoPanData[ 4 ];
  749. m_autoPanArea[ 0 ] = new AutoPanData( AutoPanLocation.TOP, 25, autoPanSpeed * Vector2.up );
  750. m_autoPanArea[ 1 ] = new AutoPanData( AutoPanLocation.BOTTOM, 25, autoPanSpeed * Vector2.down );
  751. m_autoPanArea[ 2 ] = new AutoPanData( AutoPanLocation.LEFT, 25, autoPanSpeed * Vector2.right );
  752. m_autoPanArea[ 3 ] = new AutoPanData( AutoPanLocation.RIGHT, 25, autoPanSpeed * Vector2.left );
  753. m_drawInfo = new DrawInfo();
  754. UIUtils.CurrentWindow = this;
  755. m_repaintIsDirty = false;
  756. m_initialized = false;
  757. }
  758. public void SetStandardShader()
  759. {
  760. m_mainGraphInstance.ReplaceMasterNode( AvailableShaderTypes.SurfaceShader );
  761. m_mainGraphInstance.FireMasterNodeReplacedEvent();
  762. }
  763. public void SetTemplateShader( string templateName, bool writeDefaultData )
  764. {
  765. TemplateDataParent templateData = m_templatesManager.GetTemplate( ( string.IsNullOrEmpty( templateName ) ? "6e114a916ca3e4b4bb51972669d463bf" : templateName ) );
  766. m_mainGraphInstance.ReplaceMasterNode( AvailableShaderTypes.Template, writeDefaultData, templateData );
  767. }
  768. public void DeleteSelectedNodeWithRepaint()
  769. {
  770. DeleteSelectedNodes();
  771. SetSaveIsDirty();
  772. }
  773. void UndoRedoPerformed()
  774. {
  775. m_repaintIsDirty = true;
  776. m_saveIsDirty = true;
  777. m_removedKeyboardFocus = true;
  778. m_refreshOnUndo = true;
  779. }
  780. void Destroy()
  781. {
  782. UndoUtils.ClearUndo( this );
  783. m_initialized = false;
  784. m_nodeExporterUtils.Destroy();
  785. m_nodeExporterUtils = null;
  786. m_delayedMaterialSet = null;
  787. m_materialsToUpdate.Clear();
  788. m_materialsToUpdate = null;
  789. GLDraw.Destroy();
  790. UIUtils.Destroy();
  791. m_preMadeShaders.Destroy();
  792. m_preMadeShaders = null;
  793. m_registeredMenus.Clear();
  794. m_registeredMenus = null;
  795. m_mainGraphInstance.Destroy();
  796. ScriptableObject.DestroyImmediate( m_mainGraphInstance );
  797. m_mainGraphInstance = null;
  798. Resources.UnloadAsset( m_graphBgTexture );
  799. m_graphBgTexture = null;
  800. Resources.UnloadAsset( m_graphFgTexture );
  801. m_graphFgTexture = null;
  802. Resources.UnloadAsset( m_wireTexture );
  803. m_wireTexture = null;
  804. m_contextMenu.Destroy();
  805. m_contextMenu = null;
  806. m_shortcutManager.Destroy();
  807. m_shortcutManager = null;
  808. m_nodeParametersWindow.Destroy();
  809. m_nodeParametersWindow = null;
  810. m_modeWindow.Destroy();
  811. m_modeWindow = null;
  812. m_toolsWindow.Destroy();
  813. m_toolsWindow = null;
  814. m_consoleLogWindow.Destroy();
  815. m_consoleLogWindow = null;
  816. m_tipsWindow.Destroy();
  817. m_tipsWindow = null;
  818. m_optionsWindow.Destroy();
  819. m_optionsWindow = null;
  820. m_paletteWindow.Destroy();
  821. m_paletteWindow = null;
  822. m_palettePopup.Destroy();
  823. m_palettePopup = null;
  824. m_contextPalette.Destroy();
  825. m_contextPalette = null;
  826. m_clipboard.ClearClipboard();
  827. m_clipboard = null;
  828. m_genericMessageUI.Destroy();
  829. m_genericMessageUI = null;
  830. m_genericMessageContent = null;
  831. m_dragAndDropTool.Destroy();
  832. m_dragAndDropTool = null;
  833. //m_openedShaderFunction = null;
  834. UIUtils.CurrentWindow = null;
  835. m_duplicatePreventionBuffer.ReleaseAllData();
  836. m_duplicatePreventionBuffer = null;
  837. EditorApplication.projectChanged -= OnProjectWindowChanged;
  838. Selection.selectionChanged -= OnProjectSelectionChanged;
  839. IOUtils.AllOpenedWindows.Remove( this );
  840. if( IOUtils.AllOpenedWindows.Count == 0 )
  841. {
  842. m_templatesManager.Destroy();
  843. ScriptableObject.DestroyImmediate( m_templatesManager );
  844. }
  845. m_templatesManager = null;
  846. IOUtils.Destroy();
  847. Resources.UnloadUnusedAssets();
  848. GC.Collect();
  849. }
  850. void Init()
  851. {
  852. // = AssetDatabase.LoadAssetAtPath( Constants.ASEPath + "", typeof( Texture2D ) ) as Texture2D;
  853. m_graphBgTexture = AssetDatabase.LoadAssetAtPath( AssetDatabase.GUIDToAssetPath( IOUtils.GraphBgTextureGUID ), typeof( Texture2D ) ) as Texture2D;
  854. if( m_graphBgTexture != null )
  855. {
  856. m_graphFgTexture = AssetDatabase.LoadAssetAtPath( AssetDatabase.GUIDToAssetPath( IOUtils.GraphFgTextureGUID ), typeof( Texture2D ) ) as Texture2D;
  857. //Setup usable area
  858. m_cameraInfo = position;
  859. m_graphArea = new Rect( 0, 0, m_cameraInfo.width, m_cameraInfo.height );
  860. // Creating style state to show current selected object
  861. m_graphFontStyle = new GUIStyle()
  862. {
  863. fontSize = 32,
  864. alignment = TextAnchor.MiddleCenter,
  865. fixedWidth = m_cameraInfo.width,
  866. fixedHeight = 50,
  867. stretchWidth = true,
  868. stretchHeight = true
  869. };
  870. m_graphFontStyle.normal.textColor = Color.white;
  871. m_wireTexture = AssetDatabase.LoadAssetAtPath( AssetDatabase.GUIDToAssetPath( IOUtils.WireTextureGUID ), typeof( Texture2D ) ) as Texture2D;
  872. m_initialized = m_graphBgTexture != null &&
  873. m_graphFgTexture != null &&
  874. m_wireTexture != null;
  875. }
  876. }
  877. [OnOpenAsset(0)]
  878. static bool OnOpenAsset( int instanceID, int line )
  879. {
  880. // This test is needed since it is what is used when we both click the button to open generated code inside the canvas
  881. // ( in there we call AssetDatabase.OpenAsset with line set to 1 to let ASE know that we want to ignore normal shader opening )
  882. // And click on shader errors/warnings over the shader inspector
  883. // ( Line is greater than -1 focusing on where the error/warning is )
  884. if( line > -1 )
  885. {
  886. return false;
  887. }
  888. UnityEngine.Object selection = EditorUtility.InstanceIDToObject( instanceID );
  889. ASEPackageManagerHelper.RequestInfo();
  890. ASEPackageManagerHelper.Update();
  891. if( ASEPackageManagerHelper.IsProcessing )
  892. {
  893. Shader selectedShader = selection as Shader;
  894. if( selectedShader != null )
  895. {
  896. if( IOUtils.IsASEShader( selectedShader ) )
  897. {
  898. ASEPackageManagerHelper.SetupLateShader( selectedShader );
  899. return true;
  900. }
  901. }
  902. else
  903. {
  904. Material mat = selection as Material;
  905. if( mat != null )
  906. {
  907. if( !Preferences.User.DisableMaterialMode && IOUtils.IsASEShader( mat.shader ) )
  908. {
  909. ASEPackageManagerHelper.SetupLateMaterial( mat );
  910. return true;
  911. }
  912. }
  913. else
  914. {
  915. AmplifyShaderFunction shaderFunction = selection as AmplifyShaderFunction;
  916. if( shaderFunction != null )
  917. {
  918. if( IOUtils.IsShaderFunction( shaderFunction.FunctionInfo ) )
  919. {
  920. ASEPackageManagerHelper.SetupLateShaderFunction( shaderFunction );
  921. return true;
  922. }
  923. }
  924. }
  925. }
  926. }
  927. else
  928. {
  929. Shader selectedShader = selection as Shader;
  930. if( selectedShader != null )
  931. {
  932. if( IOUtils.IsASEShader( selectedShader ) )
  933. {
  934. ConvertShaderToASE( selectedShader );
  935. return true;
  936. }
  937. }
  938. else
  939. {
  940. Material mat = selection as Material;
  941. if( mat != null )
  942. {
  943. if( !Preferences.User.DisableMaterialMode && IOUtils.IsASEShader( mat.shader ) )
  944. {
  945. LoadMaterialToASE( mat );
  946. return true;
  947. }
  948. }
  949. else
  950. {
  951. AmplifyShaderFunction shaderFunction = selection as AmplifyShaderFunction;
  952. if( shaderFunction != null )
  953. {
  954. if( IOUtils.IsShaderFunction( shaderFunction.FunctionInfo ) )
  955. {
  956. LoadShaderFunctionToASE( shaderFunction, false );
  957. return true;
  958. }
  959. }
  960. }
  961. }
  962. }
  963. return false;
  964. }
  965. [MenuItem( "Assets/Create/Amplify Shader/Surface", false, 84 )]
  966. [MenuItem( "Assets/Create/Shader/Amplify Surface Shader" )]
  967. static void CreateConfirmationStandardShader()
  968. {
  969. //string path = AssetDatabase.GetAssetPath( Selection.activeObject );
  970. //if( path == "" )
  971. //{
  972. // path = "Assets";
  973. //}
  974. //else if( System.IO.Path.GetExtension( path ) != "" )
  975. //{
  976. // path = path.Replace( System.IO.Path.GetFileName( AssetDatabase.GetAssetPath( Selection.activeObject ) ), "" );
  977. //}
  978. //string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath( path + "/New Amplify Shader.shader" );
  979. var endNameEditAction = ScriptableObject.CreateInstance<DoCreateStandardShader>();
  980. ProjectWindowUtil.StartNameEditingIfProjectWindowExists( 0, endNameEditAction, "New Amplify Shader.shader"/*assetPathAndName*/, AssetPreview.GetMiniTypeThumbnail( typeof( Shader ) ), null );
  981. }
  982. //static void CreateNewShader( )
  983. //{
  984. // CreateNewShader( null, null );
  985. //}
  986. static void CreateNewShader( string customPath , string customShaderName )
  987. {
  988. string path = string.Empty;
  989. if( string.IsNullOrEmpty( customPath ) )
  990. {
  991. if( Selection.activeObject != null )
  992. {
  993. path = ( IOUtils.dataPath + AssetDatabase.GetAssetPath( Selection.activeObject ) );
  994. }
  995. else
  996. {
  997. UnityEngine.Object[] selection = Selection.GetFiltered( typeof( UnityEngine.Object ), SelectionMode.DeepAssets );
  998. if( selection.Length > 0 && selection[ 0 ] != null )
  999. {
  1000. path = ( IOUtils.dataPath + AssetDatabase.GetAssetPath( selection[ 0 ] ) );
  1001. }
  1002. else
  1003. {
  1004. path = Application.dataPath;
  1005. }
  1006. }
  1007. if( path.IndexOf( '.' ) > -1 )
  1008. {
  1009. path = path.Substring( 0, path.LastIndexOf( '/' ) );
  1010. }
  1011. path += "/";
  1012. }
  1013. else
  1014. {
  1015. path = customPath;
  1016. }
  1017. if( IOUtils.AllOpenedWindows.Count > 0 )
  1018. {
  1019. EditorWindow openedWindow = AmplifyShaderEditorWindow.GetWindow<AmplifyShaderEditorWindow>();
  1020. AmplifyShaderEditorWindow currentWindow = CreateTab();
  1021. WindowHelper.AddTab( openedWindow, currentWindow );
  1022. UIUtils.CurrentWindow = currentWindow;
  1023. Shader shader = UIUtils.CreateNewEmpty( path, customShaderName );
  1024. Selection.activeObject = shader;
  1025. }
  1026. else
  1027. {
  1028. AmplifyShaderEditorWindow currentWindow = OpenWindow();
  1029. UIUtils.CurrentWindow = currentWindow;
  1030. Shader shader = UIUtils.CreateNewEmpty( path, customShaderName );
  1031. Selection.activeObject = shader;
  1032. }
  1033. //Selection.objects = new UnityEngine.Object[] { shader };
  1034. }
  1035. public static void CreateConfirmationTemplateShader( string templateGuid )
  1036. {
  1037. UIUtils.NewTemplateGUID = templateGuid;
  1038. //string path = AssetDatabase.GetAssetPath( Selection.activeObject );
  1039. //if( path == "" )
  1040. //{
  1041. // path = "Assets";
  1042. //}
  1043. //else if( System.IO.Path.GetExtension( path ) != "" )
  1044. //{
  1045. // path = path.Replace( System.IO.Path.GetFileName( AssetDatabase.GetAssetPath( Selection.activeObject ) ), "" );
  1046. //}
  1047. //string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath( path + "/New Amplify Shader.shader" );
  1048. var endNameEditAction = ScriptableObject.CreateInstance<DoCreateTemplateShader>();
  1049. ProjectWindowUtil.StartNameEditingIfProjectWindowExists( 0, endNameEditAction, "New Amplify Shader.shader"/*assetPathAndName*/, AssetPreview.GetMiniTypeThumbnail( typeof( Shader ) ), null );
  1050. }
  1051. public static Shader CreateNewTemplateShader( string templateGUID , string customPath = null, string customShaderName = null )
  1052. {
  1053. string path = string.Empty;
  1054. if( string.IsNullOrEmpty( customPath ) )
  1055. {
  1056. path = Selection.activeObject == null ? Application.dataPath : ( IOUtils.dataPath + AssetDatabase.GetAssetPath( Selection.activeObject ) );
  1057. if( path.IndexOf( '.' ) > -1 )
  1058. {
  1059. path = path.Substring( 0, path.LastIndexOf( '/' ) );
  1060. }
  1061. path += "/";
  1062. }
  1063. else
  1064. {
  1065. path = customPath;
  1066. }
  1067. Shader shader = null;
  1068. if( IOUtils.AllOpenedWindows.Count > 0 )
  1069. {
  1070. EditorWindow openedWindow = AmplifyShaderEditorWindow.GetWindow<AmplifyShaderEditorWindow>();
  1071. AmplifyShaderEditorWindow currentWindow = CreateTab();
  1072. WindowHelper.AddTab( openedWindow, currentWindow );
  1073. UIUtils.CurrentWindow = currentWindow;
  1074. shader = UIUtils.CreateNewEmptyTemplate( templateGUID, path, customShaderName );
  1075. Selection.activeObject = shader;
  1076. }
  1077. else
  1078. {
  1079. AmplifyShaderEditorWindow currentWindow = OpenWindow();
  1080. UIUtils.CurrentWindow = currentWindow;
  1081. shader = UIUtils.CreateNewEmptyTemplate( templateGUID, path, customShaderName );
  1082. Selection.activeObject = shader;
  1083. }
  1084. //Selection.objects = new UnityEngine.Object[] { shader };
  1085. return shader;
  1086. }
  1087. [MenuItem( "Assets/Create/Amplify Shader Function", false, 84 )]
  1088. [MenuItem( "Assets/Create/Shader/Amplify Shader Function" )]
  1089. static void CreateNewShaderFunction()
  1090. {
  1091. AmplifyShaderFunction asset = ScriptableObject.CreateInstance<AmplifyShaderFunction>();
  1092. //string path = AssetDatabase.GetAssetPath( Selection.activeObject );
  1093. //if( path == "" )
  1094. //{
  1095. // path = "Assets";
  1096. //}
  1097. //else if( System.IO.Path.GetExtension( path ) != "" )
  1098. //{
  1099. // path = path.Replace( System.IO.Path.GetFileName( AssetDatabase.GetAssetPath( Selection.activeObject ) ), "" );
  1100. //}
  1101. //string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath( path + "/New ShaderFunction.asset" );
  1102. var endNameEditAction = ScriptableObject.CreateInstance<DoCreateFunction>();
  1103. ProjectWindowUtil.StartNameEditingIfProjectWindowExists( asset.GetInstanceID(), endNameEditAction, "New ShaderFunction.asset"/*assetPathAndName*/, AssetPreview.GetMiniThumbnail( asset ), null );
  1104. }
  1105. public void UpdateTabTitle( string newTitle, bool modified )
  1106. {
  1107. string[] titleArray = newTitle.Split( '/' );
  1108. newTitle = titleArray[ titleArray.Length - 1 ];
  1109. if( !( m_currentTitle.Equals( newTitle ) && m_currentTitleMod == modified ) )
  1110. {
  1111. this.titleContent.text = GenerateTabTitle( newTitle, modified );
  1112. }
  1113. m_currentTitle = newTitle;
  1114. m_currentTitleMod = modified;
  1115. }
  1116. public void OnProjectWindowChanged()
  1117. {
  1118. Shader selectedShader = Selection.activeObject as Shader;
  1119. if( selectedShader != null )
  1120. {
  1121. if( m_mainGraphInstance != null && m_mainGraphInstance.CurrentMasterNode != null && selectedShader == m_mainGraphInstance.CurrentMasterNode.CurrentShader )
  1122. {
  1123. m_lastOpenedLocation = AssetDatabase.GetAssetPath( selectedShader );
  1124. }
  1125. }
  1126. }
  1127. public void LoadProjectSelected( UnityEngine.Object selectedObject = null )
  1128. {
  1129. bool hasFocus = true;
  1130. if( EditorWindow.focusedWindow != this )
  1131. {
  1132. hasFocus = false;
  1133. }
  1134. if( hasFocus && m_mainGraphInstance != null && m_mainGraphInstance.CurrentMasterNode != null )
  1135. {
  1136. LoadObject( selectedObject ?? Selection.activeObject );
  1137. }
  1138. else
  1139. {
  1140. m_delayedLoadObject = selectedObject ?? Selection.activeObject;
  1141. }
  1142. if( !hasFocus )
  1143. Focus();
  1144. }
  1145. public void LoadObject( UnityEngine.Object objToLoad )
  1146. {
  1147. Shader selectedShader = objToLoad as Shader;
  1148. Material selectedMaterial = objToLoad as Material;
  1149. AmplifyShaderFunction selectedFunction = objToLoad as AmplifyShaderFunction;
  1150. if( selectedFunction != null )
  1151. {
  1152. IsShaderFunctionWindow = true;
  1153. m_mainGraphInstance.CurrentCanvasMode = NodeAvailability.ShaderFunction;
  1154. }
  1155. else
  1156. {
  1157. IsShaderFunctionWindow = false;
  1158. }
  1159. ASESelectionMode selectedFileType = ASESelectionMode.Shader;
  1160. if( selectedShader != null )
  1161. {
  1162. selectedFileType = ASESelectionMode.Shader;
  1163. }
  1164. else if( selectedMaterial != null )
  1165. {
  1166. selectedFileType = ASESelectionMode.Material;
  1167. }
  1168. else if( selectedFunction != null )
  1169. {
  1170. selectedFileType = ASESelectionMode.ShaderFunction;
  1171. }
  1172. switch( CurrentSelection )
  1173. {
  1174. case ASESelectionMode.Shader:
  1175. {
  1176. if( ShaderIsModified )
  1177. {
  1178. Shader currShader = m_mainGraphInstance.CurrentMasterNode.CurrentShader;
  1179. bool savePrevious = UIUtils.DisplayDialog( AssetDatabase.GetAssetPath( currShader ) );
  1180. OnSaveShader( savePrevious, currShader, null, null );
  1181. }
  1182. }
  1183. break;
  1184. case ASESelectionMode.Material:
  1185. {
  1186. if( ShaderIsModified )
  1187. {
  1188. Shader currShader = m_mainGraphInstance.CurrentMasterNode.CurrentShader;
  1189. bool savePrevious = UIUtils.DisplayDialog( AssetDatabase.GetAssetPath( currShader ) );
  1190. OnSaveShader( savePrevious, currShader, m_mainGraphInstance.CurrentMasterNode.CurrentMaterial, null );
  1191. }
  1192. }
  1193. break;
  1194. case ASESelectionMode.ShaderFunction:
  1195. {
  1196. if( ShaderIsModified )
  1197. {
  1198. bool savePrevious = UIUtils.DisplayDialog( AssetDatabase.GetAssetPath( m_mainGraphInstance.CurrentShaderFunction ) );
  1199. OnSaveShader( savePrevious, null, null, selectedFunction );
  1200. }
  1201. }
  1202. break;
  1203. }
  1204. switch( selectedFileType )
  1205. {
  1206. case ASESelectionMode.Shader:
  1207. {
  1208. LoadDroppedObject( true, selectedShader, null );
  1209. }
  1210. break;
  1211. case ASESelectionMode.Material:
  1212. {
  1213. LoadDroppedObject( true, selectedMaterial.shader, selectedMaterial );
  1214. }
  1215. break;
  1216. case ASESelectionMode.ShaderFunction:
  1217. {
  1218. LoadDroppedObject( true, null, null, selectedFunction );
  1219. }
  1220. break;
  1221. }
  1222. //m_openedShaderFunction = m_mainGraphInstance.CurrentShaderFunction;
  1223. //Need to force one graph draw because it wont call OnGui propertly since its focuses somewhere else
  1224. // Focus() doesn't fix this since it only changes keyboard focus
  1225. m_drawInfo.InvertedZoom = 1 / m_cameraZoom;
  1226. m_mainGraphInstance.IsLoading = true;
  1227. m_mainGraphInstance.Draw( m_drawInfo );
  1228. m_mainGraphInstance.IsLoading = false;
  1229. ShaderIsModified = false;
  1230. Focus();
  1231. Repaint();
  1232. }
  1233. public void OnProjectSelectionChanged()
  1234. {
  1235. if( m_loadShaderOnSelection )
  1236. {
  1237. LoadProjectSelected();
  1238. }
  1239. }
  1240. ShaderLoadResult OnSaveShader( bool value, Shader shader, Material material, AmplifyShaderFunction function )
  1241. {
  1242. if( value )
  1243. {
  1244. SaveToDisk( false );
  1245. }
  1246. return value ? ShaderLoadResult.LOADED : ShaderLoadResult.FILE_NOT_FOUND;
  1247. }
  1248. public void ResetCameraSettings()
  1249. {
  1250. m_cameraInfo = position;
  1251. m_cameraOffset = new Vector2( m_cameraInfo.width * 0.5f, m_cameraInfo.height * 0.5f );
  1252. CameraZoom = 1;
  1253. }
  1254. public void Reset()
  1255. {
  1256. if( m_mainGraphInstance == null )
  1257. {
  1258. m_mainGraphInstance = CreateInstance<ParentGraph>();
  1259. m_mainGraphInstance.Init();
  1260. m_mainGraphInstance.ParentWindow = this;
  1261. m_mainGraphInstance.SetGraphId( 0 );
  1262. }
  1263. m_mainGraphInstance.ResetEvents();
  1264. m_mainGraphInstance.OnNodeEvent += OnNodeStoppedMovingEvent;
  1265. m_mainGraphInstance.OnMaterialUpdatedEvent += OnMaterialUpdated;
  1266. m_mainGraphInstance.OnShaderUpdatedEvent += OnShaderUpdated;
  1267. m_mainGraphInstance.OnEmptyGraphDetectedEvt += OnEmptyGraphDetected;
  1268. m_mainGraphInstance.OnNodeRemovedEvent += m_toolsWindow.OnNodeRemovedFromGraph;
  1269. m_outdatedShaderFromTemplateLoaded = false;
  1270. GraphCount = 1;
  1271. FullCleanUndoStack();
  1272. m_performFullUndoRegister = true;
  1273. m_toolsWindow.BorderStyle = null;
  1274. m_selectionMode = ASESelectionMode.Shader;
  1275. ResetCameraSettings();
  1276. UIUtils.ResetMainSkin();
  1277. m_duplicatePreventionBuffer.ReleaseAllData();
  1278. if( m_genericMessageUI != null )
  1279. m_genericMessageUI.CleanUpMessageStack();
  1280. }
  1281. public Shader CreateNewGraph( string name )
  1282. {
  1283. Reset();
  1284. UIUtils.DirtyMask = false;
  1285. m_mainGraphInstance.CreateNewEmpty( name );
  1286. m_lastOpenedLocation = string.Empty;
  1287. UIUtils.DirtyMask = true;
  1288. return m_mainGraphInstance.CurrentMasterNode.CurrentShader;
  1289. }
  1290. public Shader CreateNewTemplateGraph( string templateGUID )
  1291. {
  1292. Reset();
  1293. UIUtils.DirtyMask = false;
  1294. m_mainGraphInstance.CreateNewEmptyTemplate( templateGUID );
  1295. m_lastOpenedLocation = string.Empty;
  1296. UIUtils.DirtyMask = true;
  1297. return m_mainGraphInstance.CurrentMasterNode.CurrentShader;
  1298. }
  1299. public Shader CreateNewGraph( Shader shader )
  1300. {
  1301. Reset();
  1302. UIUtils.DirtyMask = false;
  1303. m_mainGraphInstance.CreateNewEmpty( shader.name );
  1304. m_mainGraphInstance.CurrentMasterNode.CurrentShader = shader;
  1305. m_lastOpenedLocation = string.Empty;
  1306. UIUtils.DirtyMask = true;
  1307. return m_mainGraphInstance.CurrentMasterNode.CurrentShader;
  1308. }
  1309. public void CreateNewFunctionGraph( AmplifyShaderFunction shaderFunction )
  1310. {
  1311. Reset();
  1312. UIUtils.DirtyMask = false;
  1313. m_mainGraphInstance.CreateNewEmptyFunction( shaderFunction );
  1314. m_mainGraphInstance.CurrentShaderFunction = shaderFunction;
  1315. m_lastOpenedLocation = AssetDatabase.GetAssetPath( shaderFunction ); //string.Empty;
  1316. UIUtils.DirtyMask = true;
  1317. //return m_mainGraphInstance.CurrentMasterNode.CurrentShader;
  1318. }
  1319. private void FinishedShaderCompileLog( double compileTimeInSeconds )
  1320. {
  1321. string name = string.Empty;
  1322. if ( m_mainGraphInstance.CurrentShader != null )
  1323. {
  1324. name = " \"" + AssetDatabase.GetAssetPath( m_mainGraphInstance.CurrentShader ) + "\"";
  1325. }
  1326. else if ( m_mainGraphInstance.CurrentShaderFunction != null )
  1327. {
  1328. name = " \"" + AssetDatabase.GetAssetPath( m_mainGraphInstance.CurrentShaderFunction ) + "\"";
  1329. }
  1330. Debug.Log( "[AmplifyShaderEditor] Finished compiling" + name + " in " + compileTimeInSeconds.ToString( "0.00" ) + " seconds." );
  1331. }
  1332. public bool SaveToDisk( bool checkTimestamp )
  1333. {
  1334. if( checkTimestamp )
  1335. {
  1336. if( !m_cacheSaveOp )
  1337. {
  1338. m_lastTimeSaved = EditorApplication.timeSinceStartup;
  1339. m_cacheSaveOp = true;
  1340. }
  1341. return false;
  1342. }
  1343. FullCleanUndoStack();
  1344. System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
  1345. var timer = new System.Diagnostics.Stopwatch();
  1346. timer.Start();
  1347. m_customGraph = null;
  1348. m_cacheSaveOp = false;
  1349. ShaderIsModified = false;
  1350. m_mainGraphInstance.LoadedShaderVersion = VersionInfo.FullNumber;
  1351. m_lastTimeSaved = EditorApplication.timeSinceStartup;
  1352. bool succeeded = false;
  1353. if ( m_mainGraphInstance.CurrentMasterNodeId == Constants.INVALID_NODE_ID )
  1354. {
  1355. Shader currentShader = m_mainGraphInstance.CurrentMasterNode != null ? m_mainGraphInstance.CurrentMasterNode.CurrentShader : null;
  1356. string newShader;
  1357. if( !String.IsNullOrEmpty( m_lastOpenedLocation ) )
  1358. {
  1359. newShader = m_lastOpenedLocation;
  1360. }
  1361. else if( currentShader != null )
  1362. {
  1363. newShader = AssetDatabase.GetAssetPath( currentShader );
  1364. }
  1365. else
  1366. {
  1367. newShader = EditorUtility.SaveFilePanel( "Select Shader to save", Application.dataPath, "MyShader", "shader" );
  1368. }
  1369. if( !String.IsNullOrEmpty( newShader ) )
  1370. {
  1371. ShowMessage( "No Master node assigned.\nShader file will only have node info" );
  1372. IOUtils.StartSaveThread( GenerateGraphInfo(), newShader );
  1373. AssetDatabase.Refresh();
  1374. LoadFromDisk( newShader );
  1375. succeeded = true;
  1376. }
  1377. }
  1378. else if( m_mainGraphInstance.CurrentMasterNode != null )
  1379. {
  1380. //m_mainGraphInstance.CurrentStandardSurface.ForceReordering();
  1381. Shader currShader = m_mainGraphInstance.CurrentMasterNode.CurrentShader;
  1382. if( currShader != null )
  1383. {
  1384. m_mainGraphInstance.FireMasterNode( currShader );
  1385. Material material = m_mainGraphInstance.CurrentMaterial;
  1386. m_lastpath = ( material != null ) ? AssetDatabase.GetAssetPath( material ) : AssetDatabase.GetAssetPath( currShader );
  1387. EditorPrefs.SetString( IOUtils.LAST_OPENED_OBJ_ID, m_lastpath );
  1388. if( IOUtils.OnShaderSavedEvent != null )
  1389. {
  1390. string info = string.Empty;
  1391. if( !m_mainGraphInstance.IsStandardSurface )
  1392. {
  1393. TemplateMultiPassMasterNode masterNode = m_mainGraphInstance.GetMainMasterNodeOfLOD( -1 );
  1394. if( masterNode != null )
  1395. {
  1396. info = masterNode.CurrentTemplate.GUID;
  1397. }
  1398. }
  1399. IOUtils.OnShaderSavedEvent( currShader, !m_mainGraphInstance.IsStandardSurface, info );
  1400. }
  1401. succeeded = true;
  1402. }
  1403. else
  1404. {
  1405. string shaderName;
  1406. string pathName;
  1407. IOUtils.GetShaderName( out shaderName, out pathName, Constants.DefaultShaderName, UIUtils.LatestOpenedFolder );
  1408. if( !String.IsNullOrEmpty( pathName ) )
  1409. {
  1410. UIUtils.CurrentWindow.CurrentGraph.CurrentMasterNode.SetName( shaderName );
  1411. m_mainGraphInstance.FireMasterNode( pathName, true );
  1412. m_lastpath = pathName;
  1413. EditorPrefs.SetString( IOUtils.LAST_OPENED_OBJ_ID, pathName );
  1414. succeeded = true;
  1415. }
  1416. }
  1417. }
  1418. else
  1419. {
  1420. //m_nodeParametersWindow.ForceReordering();
  1421. m_mainGraphInstance.ResetNodesLocalVariables();
  1422. List<FunctionInput> functionInputNodes = UIUtils.FunctionInputList();
  1423. functionInputNodes.Sort( ( x, y ) => { return x.OrderIndex.CompareTo( y.OrderIndex ); } );
  1424. for( int i = 0; i < functionInputNodes.Count; i++ )
  1425. {
  1426. functionInputNodes[ i ].OrderIndex = i;
  1427. }
  1428. List<FunctionOutput> functionOutputNodes = UIUtils.FunctionOutputList();
  1429. functionOutputNodes.Sort( ( x, y ) => { return x.OrderIndex.CompareTo( y.OrderIndex ); } );
  1430. for( int i = 0; i < functionOutputNodes.Count; i++ )
  1431. {
  1432. functionOutputNodes[ i ].OrderIndex = i;
  1433. }
  1434. m_mainGraphInstance.CurrentShaderFunction.AdditionalDirectives.UpdateSaveItemsFromDirectives();
  1435. m_mainGraphInstance.CurrentShaderFunction.FunctionInfo = GenerateGraphInfo();
  1436. m_mainGraphInstance.CurrentShaderFunction.FunctionInfo = IOUtils.AddAdditionalInfo( m_mainGraphInstance.CurrentShaderFunction.FunctionInfo );
  1437. if( AssetDatabase.IsMainAsset( m_mainGraphInstance.CurrentShaderFunction ) )
  1438. {
  1439. EditorUtility.SetDirty( m_mainGraphInstance.CurrentShaderFunction );
  1440. }
  1441. else
  1442. {
  1443. //Debug.Log( LastOpenedLocation );
  1444. //AssetDatabase.CreateAsset( m_mainGraphInstance.CurrentShaderFunction, LastOpenedLocation );
  1445. }
  1446. AssetDatabase.SaveAssets();
  1447. AssetDatabase.Refresh();
  1448. m_mainGraphInstance.CurrentShaderFunction.AdditionalDirectives.UpdateDirectivesFromSaveItems();
  1449. IOUtils.FunctionNodeChanged = true;
  1450. m_lastpath = AssetDatabase.GetAssetPath( m_mainGraphInstance.CurrentShaderFunction );
  1451. //EditorPrefs.SetString( IOUtils.LAST_OPENED_OBJ_ID, AssetDatabase.GetAssetPath( m_mainGraphInstance.CurrentShaderFunction ) );
  1452. succeeded = true;
  1453. }
  1454. timer.Stop();
  1455. if ( Preferences.User.LogShaderCompile )
  1456. {
  1457. FinishedShaderCompileLog( timer.Elapsed.TotalSeconds );
  1458. }
  1459. System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
  1460. return succeeded;
  1461. }
  1462. public void OnToolButtonPressed( ToolButtonType type )
  1463. {
  1464. switch( type )
  1465. {
  1466. case ToolButtonType.New:
  1467. {
  1468. UIUtils.CreateNewEmpty();
  1469. }
  1470. break;
  1471. case ToolButtonType.Open:
  1472. {
  1473. UIUtils.OpenFile();
  1474. }
  1475. break;
  1476. case ToolButtonType.Save:
  1477. {
  1478. SaveToDisk( false );
  1479. }
  1480. break;
  1481. case ToolButtonType.Library:
  1482. {
  1483. ShowShaderLibrary();
  1484. }
  1485. break;
  1486. case ToolButtonType.Options: { } break;
  1487. case ToolButtonType.Update:
  1488. {
  1489. if( Preferences.User.ClearLog )
  1490. {
  1491. m_consoleLogWindow.ClearMessages();
  1492. }
  1493. SaveToDisk( false );
  1494. }
  1495. break;
  1496. case ToolButtonType.Live:
  1497. {
  1498. m_liveShaderEditing = !m_liveShaderEditing;
  1499. m_innerEditorVariables.LiveMode = m_liveShaderEditing;
  1500. // 0 off
  1501. // 1 on
  1502. // 2 pending
  1503. if( m_liveShaderEditing && m_mainGraphInstance.CurrentMasterNode != null && m_mainGraphInstance.CurrentMasterNode.CurrentShader == null )
  1504. {
  1505. m_liveShaderEditing = false;
  1506. m_innerEditorVariables.LiveMode = false;
  1507. }
  1508. UpdateLiveUI();
  1509. if( m_liveShaderEditing )
  1510. {
  1511. SaveToDisk( false );
  1512. }
  1513. }
  1514. break;
  1515. case ToolButtonType.OpenSourceCode:
  1516. {
  1517. AssetDatabase.OpenAsset( m_mainGraphInstance.CurrentMasterNode.CurrentShader, 1 );
  1518. }
  1519. break;
  1520. case ToolButtonType.MasterNode:
  1521. {
  1522. m_mainGraphInstance.AssignMasterNode();
  1523. }
  1524. break;
  1525. case ToolButtonType.FocusOnMasterNode:
  1526. {
  1527. double currTime = EditorApplication.timeSinceStartup;
  1528. bool autoZoom = ( currTime - m_focusOnMasterNodeTimestamp ) < AutoZoomTime;
  1529. m_focusOnMasterNodeTimestamp = currTime;
  1530. FocusOnNode( m_mainGraphInstance.CurrentMasterNode, autoZoom ? 1 : m_cameraZoom, true );
  1531. }
  1532. break;
  1533. case ToolButtonType.FocusOnSelection:
  1534. {
  1535. FocusZoom( false, true, true );
  1536. }
  1537. break;
  1538. case ToolButtonType.ShowInfoWindow:
  1539. {
  1540. PortLegendInfo.OpenWindow();
  1541. }
  1542. break;
  1543. case ToolButtonType.ShowTipsWindow:
  1544. {
  1545. TipsWindow.ShowWindow( true );
  1546. }
  1547. break;
  1548. case ToolButtonType.ShowConsole:
  1549. {
  1550. m_consoleLogWindow.Toggle();
  1551. }
  1552. break;
  1553. case ToolButtonType.Share:
  1554. {
  1555. List<ParentNode> selectedNodes = m_mainGraphInstance.SelectedNodes;
  1556. if ( selectedNodes.Count > 0 )
  1557. {
  1558. CopyToClipboard();
  1559. StartPasteRequest();
  1560. }
  1561. else
  1562. {
  1563. ShowMessage( "No nodes selected to share" );
  1564. }
  1565. }
  1566. break;
  1567. case ToolButtonType.TakeScreenshot:
  1568. {
  1569. #if UNITY_EDITOR_WIN
  1570. this.Focus();
  1571. m_aseHandle = WindowsUtil.GetActiveWindow();
  1572. //m_aseHandle = FindASEWindowHandle();
  1573. bool takeit = EditorUtility.DisplayDialog( "Take Screenshot", "This is a work in progress feature that will undock itself if needed, increase the window outside of your screen resolution to take the shot, if something fails (ie: graph too big) you may need to restart Unity, do you wish to continue?", "Yes", "Cancel" );
  1574. if( !takeit )
  1575. break;
  1576. if( this.IsDocked() )
  1577. {
  1578. this.Undock();
  1579. this.Focus();
  1580. m_aseHandle = WindowsUtil.GetActiveWindow();
  1581. }
  1582. int windowLong = WindowsUtil.GetWindowLong( m_aseHandle, WindowsUtil.GWL_STYLE );
  1583. List<ParentNode> selectedNodes = m_mainGraphInstance.AllNodes;
  1584. Vector2 minPos = new Vector2( float.MaxValue, float.MaxValue );
  1585. Vector2 maxPos = new Vector2( float.MinValue, float.MinValue );
  1586. Vector2 centroid = Vector2.zero;
  1587. for( int i = 0; i < selectedNodes.Count; i++ )
  1588. {
  1589. Rect currPos = selectedNodes[ i ].TruePosition;
  1590. minPos.x = ( currPos.x < minPos.x ) ? currPos.x : minPos.x;
  1591. minPos.y = ( currPos.y < minPos.y ) ? currPos.y : minPos.y;
  1592. maxPos.x = ( ( currPos.x + currPos.width ) > maxPos.x ) ? ( currPos.x + currPos.width ) : maxPos.x;
  1593. maxPos.y = ( ( currPos.y + currPos.height ) > maxPos.y ) ? ( currPos.y + currPos.height ) : maxPos.y;
  1594. }
  1595. centroid = ( maxPos - minPos );
  1596. m_prevCameraOffset = m_cameraOffset;
  1597. m_prevCameraZoom = CameraZoom;
  1598. WindowsUtil.SetWindowLong( m_aseHandle, WindowsUtil.GWL_STYLE, (int)( windowLong & ~( WindowsUtil.WS_SIZEBOX ) ) );
  1599. var rect = new WindowsUtil.Rect();
  1600. WindowsUtil.GetWindowRect( m_aseHandle, ref rect );
  1601. m_prevWindowRect = new Rect( rect.Left, rect.Top, rect.Width, rect.Height );
  1602. WindowsUtil.SetWindowPos( m_aseHandle, 0, (int)m_prevWindowRect.xMin, (int)m_prevWindowRect.yMin, (int)centroid.x, (int)centroid.y, 0x0040 );
  1603. WindowsUtil.SetWindowLong( m_aseHandle, WindowsUtil.GWL_STYLE, (int)( windowLong ) );
  1604. m_takeScreenShot = true;
  1605. #else
  1606. EditorUtility.DisplayDialog( "Take Screenshot", "This is a work in progress feature that only works in Windows environment", "Ok" );
  1607. #endif
  1608. }
  1609. break;
  1610. case ToolButtonType.CleanUnusedNodes:
  1611. {
  1612. m_mainGraphInstance.CleanUnusedNodes();
  1613. }
  1614. break;
  1615. case ToolButtonType.Help:
  1616. {
  1617. Application.OpenURL( Constants.HelpURL );
  1618. }
  1619. break;
  1620. }
  1621. }
  1622. #if UNITY_EDITOR_WIN
  1623. IntPtr FindASEWindowHandle()
  1624. {
  1625. System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
  1626. IntPtr[] winPtrs = WindowsUtil.GetProcessWindows( process.Id );
  1627. m_aseHandle = IntPtr.Zero;
  1628. bool found = false;
  1629. for( int i = 0; i < winPtrs.Length; i++ )
  1630. {
  1631. WindowsUtil.EnumChildWindows( winPtrs[ i ], delegate ( System.IntPtr hwnd, System.IntPtr param )
  1632. {
  1633. System.Text.StringBuilder Title = new System.Text.StringBuilder( 256 );
  1634. WindowsUtil.GetWindowText( hwnd, Title, Title.Capacity );
  1635. if( Title.ToString().Contains( "AmplifyShaderEditor.AmplifyShaderEditorWindow" ) )
  1636. {
  1637. if( !found )
  1638. {
  1639. m_aseHandle = winPtrs[ i ];
  1640. found = true;
  1641. }
  1642. }
  1643. return true;
  1644. }, System.IntPtr.Zero );
  1645. }
  1646. return m_aseHandle;
  1647. }
  1648. void OpenSavedFolder()
  1649. {
  1650. m_openSavedFolder = false;
  1651. var path = System.IO.Path.GetFullPath( Application.dataPath + "\\..\\ScreenshotASE.png" );
  1652. EditorUtility.RevealInFinder( path );
  1653. GUIUtility.ExitGUI();
  1654. }
  1655. void TakeScreenShot()
  1656. {
  1657. m_takeScreenShot = false;
  1658. var cacher = RenderTexture.active;
  1659. RenderTexture.active = null;
  1660. Texture2D m_screenshotTex2D = new Texture2D( (int)position.width, (int)position.height, TextureFormat.RGB24, false );
  1661. m_screenshotTex2D.ReadPixels( new Rect( 0, 0, m_screenshotTex2D.width, m_screenshotTex2D.height ), 0, 0 );
  1662. m_screenshotTex2D.Apply();
  1663. byte[] bytes = m_screenshotTex2D.EncodeToPNG();
  1664. var path = System.IO.Path.GetFullPath( Application.dataPath + "\\..\\ScreenshotASE.png" );
  1665. System.IO.File.WriteAllBytes( path, bytes );
  1666. RenderTexture.active = cacher;
  1667. ShowMessage( "[AmplifyShaderEditor] Screenshot successfully taken and saved at: " + path, consoleLog:true );
  1668. WindowsUtil.SetWindowPos( m_aseHandle, 0, (int)m_prevWindowRect.xMin, (int)m_prevWindowRect.yMin, (int)m_prevWindowRect.width, (int)m_prevWindowRect.height, 0x0040 );
  1669. m_cameraOffset = m_prevCameraOffset;
  1670. CameraZoom = m_prevCameraZoom;
  1671. m_openSavedFolder = true;
  1672. }
  1673. #endif
  1674. void UpdateLiveUI()
  1675. {
  1676. if( m_toolsWindow != null )
  1677. {
  1678. m_toolsWindow.SetStateOnButton( ToolButtonType.Live, ( m_liveShaderEditing ) ? 1 : 0 );
  1679. }
  1680. }
  1681. void FocusZoom( bool forceAllNodes, bool doubleTap, bool smooth = true, float maxZoom = float.MaxValue )
  1682. {
  1683. List<ParentNode> selectedNodes = ( m_mainGraphInstance.SelectedNodes.Count > 0 ) && !forceAllNodes ? m_mainGraphInstance.SelectedNodes : m_mainGraphInstance.AllNodes;
  1684. Vector2 minPos = new Vector2( float.MaxValue, float.MaxValue );
  1685. Vector2 maxPos = new Vector2( float.MinValue, float.MinValue );
  1686. Vector2 centroid = Vector2.zero;
  1687. for( int i = 0; i < selectedNodes.Count; i++ )
  1688. {
  1689. Rect currPos = selectedNodes[ i ].TruePosition;
  1690. minPos.x = ( currPos.x < minPos.x ) ? currPos.x : minPos.x;
  1691. minPos.y = ( currPos.y < minPos.y ) ? currPos.y : minPos.y;
  1692. maxPos.x = ( ( currPos.x + currPos.width ) > maxPos.x ) ? ( currPos.x + currPos.width ) : maxPos.x;
  1693. maxPos.y = ( ( currPos.y + currPos.height ) > maxPos.y ) ? ( currPos.y + currPos.height ) : maxPos.y;
  1694. }
  1695. centroid = ( maxPos - minPos );
  1696. double currTime = EditorApplication.timeSinceStartup;
  1697. bool autoZoom = ( currTime - m_focusOnSelectionTimestamp ) < AutoZoomTime;
  1698. if( !doubleTap )
  1699. autoZoom = true;
  1700. m_focusOnSelectionTimestamp = currTime;
  1701. float zoom = m_cameraZoom;
  1702. if( autoZoom )
  1703. {
  1704. zoom = 1f;
  1705. float canvasWidth = m_cameraInfo.width;
  1706. if( m_nodeParametersWindow.IsMaximized )
  1707. canvasWidth -= m_nodeParametersWindow.RealWidth;
  1708. if( m_paletteWindow.IsMaximized )
  1709. canvasWidth -= m_paletteWindow.RealWidth;
  1710. canvasWidth -= 40;
  1711. //float canvasWidth = AvailableCanvasWidth;// - 20;
  1712. float canvasHeight = AvailableCanvasHeight - 60;
  1713. if( centroid.x > canvasWidth ||
  1714. centroid.y > canvasHeight )
  1715. {
  1716. float hZoom = float.MinValue;
  1717. float vZoom = float.MinValue;
  1718. if( centroid.x > canvasWidth )
  1719. {
  1720. hZoom = ( centroid.x ) / canvasWidth;
  1721. }
  1722. if( centroid.y > canvasHeight )
  1723. {
  1724. vZoom = ( centroid.y ) / canvasHeight;
  1725. }
  1726. zoom = ( hZoom > vZoom ) ? hZoom : vZoom;
  1727. }
  1728. }
  1729. zoom = Mathf.Min( zoom, maxZoom );
  1730. minPos.y -= 20 * zoom;
  1731. if( m_nodeParametersWindow.IsMaximized )
  1732. minPos.x -= m_nodeParametersWindow.RealWidth * 0.5f * zoom;
  1733. if( m_paletteWindow.IsMaximized )
  1734. minPos.x += m_paletteWindow.RealWidth * 0.5f * zoom;
  1735. FocusOnPoint( minPos + centroid * 0.5f, zoom, smooth );
  1736. }
  1737. public void FocusOnNode( int nodeId, float zoom, bool selectNode, bool late = false )
  1738. {
  1739. ParentNode node = m_mainGraphInstance.GetNode( nodeId );
  1740. if( node != null )
  1741. {
  1742. FocusOnNode( node, zoom, selectNode, late );
  1743. }
  1744. }
  1745. public void FocusOnNode( ParentNode node, float zoom, bool selectNode, bool late = false )
  1746. {
  1747. if( late )
  1748. {
  1749. m_nodeToFocus = node;
  1750. m_zoomToFocus = zoom;
  1751. m_selectNodeToFocus = selectNode;
  1752. return;
  1753. }
  1754. if( selectNode )
  1755. {
  1756. m_mainGraphInstance.SelectNode( node, false, false );
  1757. }
  1758. Vector2 nodePoint = node.CenterPosition;
  1759. nodePoint.x = nodePoint.x - ( m_nodeParametersWindow.RealWidth * 0.5f + m_paletteWindow.RealWidth * 0.5f ) * ( zoom > 0.999f ? zoom : CameraZoom );
  1760. FocusOnPoint( nodePoint, zoom );
  1761. }
  1762. public void FocusOnPoint( Vector2 point, float zoom, bool smooth = true )
  1763. {
  1764. if( zoom > 0.999f )
  1765. {
  1766. if( smooth )
  1767. SmoothZoom( zoom );
  1768. else
  1769. CameraZoom = zoom;
  1770. }
  1771. if( smooth )
  1772. SmoothCameraOffset( -point + new Vector2( ( m_cameraInfo.width ) * 0.5f, m_cameraInfo.height * 0.5f ) * CameraZoom );
  1773. else
  1774. m_cameraOffset = -point + new Vector2( ( m_cameraInfo.width ) * 0.5f, m_cameraInfo.height * 0.5f ) * CameraZoom;
  1775. }
  1776. void SmoothZoom( float newZoom )
  1777. {
  1778. m_smoothZoom = true;
  1779. m_zoomTime = 0;
  1780. m_targetZoom = newZoom;
  1781. m_zoomPivot = m_graphArea.center;
  1782. }
  1783. void SmoothCameraOffset( Vector2 newOffset )
  1784. {
  1785. m_smoothOffset = true;
  1786. m_offsetTime = 0;
  1787. m_targetOffset = newOffset;
  1788. }
  1789. void PreTestLeftMouseDown()
  1790. {
  1791. if( m_currentEvent.type == EventType.MouseDown && m_currentEvent.button == ButtonClickId.LeftMouseButton )
  1792. {
  1793. ParentNode node = m_mainGraphInstance.CheckNodeAt( m_currentMousePos );
  1794. if( node != null )
  1795. {
  1796. m_mainGraphInstance.NodeClicked = node.UniqueId;
  1797. return;
  1798. }
  1799. }
  1800. m_mainGraphInstance.NodeClicked = -1;
  1801. }
  1802. void OnLeftMouseDown()
  1803. {
  1804. Focus();
  1805. if( m_lastKeyPressed == KeyCode.Q )
  1806. {
  1807. m_rmbStartPos = m_currentMousePos2D;
  1808. UseCurrentEvent();
  1809. return;
  1810. }
  1811. m_mouseDownOnValidArea = true;
  1812. m_lmbPressed = true;
  1813. if( m_currentEvent.alt )
  1814. {
  1815. m_altBoxSelection = true;
  1816. }
  1817. UIUtils.ShowContextOnPick = true;
  1818. ParentNode node = ( m_mainGraphInstance.NodeClicked < 0 ) ? m_mainGraphInstance.CheckNodeAt( m_currentMousePos ) : m_mainGraphInstance.GetClickedNode();
  1819. if( node != null )
  1820. {
  1821. m_mainGraphInstance.NodeClicked = node.UniqueId;
  1822. m_altBoxSelection = false;
  1823. if( m_contextMenu.CheckShortcutKey() )
  1824. {
  1825. if( node.ConnStatus == NodeConnectionStatus.Island )
  1826. {
  1827. if( !m_multipleSelectionActive )
  1828. {
  1829. ParentNode newNode = m_contextMenu.CreateNodeFromShortcutKey();
  1830. if( newNode != null )
  1831. {
  1832. newNode.ContainerGraph = m_mainGraphInstance;
  1833. newNode.Vec2Position = TranformedMousePos;
  1834. m_mainGraphInstance.AddNode( newNode, true );
  1835. m_mainGraphInstance.SelectNode( newNode, false, false );
  1836. ForceRepaint();
  1837. }
  1838. ( node as CommentaryNode ).AddNodeToCommentary( newNode );
  1839. }
  1840. }
  1841. }
  1842. else
  1843. {
  1844. if( node.OnClick( m_currentMousePos2D ) )
  1845. {
  1846. if( !node.Selected )
  1847. {
  1848. m_mainGraphInstance.SelectNode( node, ( m_currentEvent.modifiers == EventModifiers.Shift || m_currentEvent.modifiers == EventModifiers.Control ), true );
  1849. }
  1850. else if( m_currentEvent.modifiers == EventModifiers.Shift || m_currentEvent.modifiers == EventModifiers.Control )
  1851. {
  1852. m_mainGraphInstance.DeselectNode( node );
  1853. }
  1854. if( m_currentEvent.alt )
  1855. {
  1856. int conn = 0;
  1857. for( int i = 0; i < node.InputPorts.Count; i++ )
  1858. {
  1859. if( node.InputPorts[ i ].IsConnected )
  1860. conn++;
  1861. }
  1862. if( node.InputPorts.Count > 0 && node.OutputPorts.Count > 0 && conn > 0 && node.OutputPorts[ 0 ].IsConnected )
  1863. {
  1864. m_altDragStarted = true;
  1865. }
  1866. }
  1867. }
  1868. if( m_currentEvent.alt )
  1869. {
  1870. if( node.InputPorts.Count > 0 && node.OutputPorts.Count > 0 && node.InputPorts[ 0 ].IsConnected && node.OutputPorts[ 0 ].IsConnected )
  1871. {
  1872. m_altDragStarted = true;
  1873. }
  1874. }
  1875. return;
  1876. }
  1877. }
  1878. else if( !m_multipleSelectionActive )
  1879. {
  1880. ParentNode newNode = m_contextMenu.CreateNodeFromShortcutKey();
  1881. if( newNode != null )
  1882. {
  1883. newNode.ContainerGraph = m_mainGraphInstance;
  1884. newNode.Vec2Position = TranformedMousePos;
  1885. m_mainGraphInstance.AddNode( newNode, true );
  1886. m_mainGraphInstance.SelectNode( newNode, false, false );
  1887. SetSaveIsDirty();
  1888. ForceRepaint();
  1889. }
  1890. else
  1891. {
  1892. List<WireBezierReference> wireRefs = m_mainGraphInstance.GetWireBezierListInPos( m_currentMousePos2D );
  1893. if( wireRefs != null && wireRefs.Count > 0 )
  1894. {
  1895. for( int i = 0; i < wireRefs.Count; i++ )
  1896. {
  1897. // Place wire code here
  1898. ParentNode outNode = m_mainGraphInstance.GetNode( wireRefs[ i ].OutNodeId );
  1899. ParentNode inNode = m_mainGraphInstance.GetNode( wireRefs[ i ].InNodeId );
  1900. OutputPort outputPort = outNode.GetOutputPortByUniqueId( wireRefs[ i ].OutPortId );
  1901. InputPort inputPort = inNode.GetInputPortByUniqueId( wireRefs[ i ].InPortId );
  1902. // Calculate the 4 points for bezier taking into account wire nodes and their automatic tangents
  1903. Vector3 endPos = new Vector3( inputPort.Position.x, inputPort.Position.y );
  1904. Vector3 startPos = new Vector3( outputPort.Position.x, outputPort.Position.y );
  1905. float mag = ( endPos - startPos ).magnitude;
  1906. float resizedMag = Mathf.Min( mag, Constants.HORIZONTAL_TANGENT_SIZE * m_drawInfo.InvertedZoom );
  1907. Vector3 startTangent = new Vector3( startPos.x + resizedMag, startPos.y );
  1908. Vector3 endTangent = new Vector3( endPos.x - resizedMag, endPos.y );
  1909. if( inNode != null && inNode.GetType() == typeof( WireNode ) )
  1910. endTangent = endPos + ( ( inNode as WireNode ).TangentDirection ) * mag * 0.33f;
  1911. if( outNode != null && outNode.GetType() == typeof( WireNode ) )
  1912. startTangent = startPos - ( ( outNode as WireNode ).TangentDirection ) * mag * 0.33f;
  1913. float dist = HandleUtility.DistancePointBezier( m_currentMousePos, startPos, endPos, startTangent, endTangent );
  1914. if( dist < 10 )
  1915. {
  1916. double doubleTapTime = EditorApplication.timeSinceStartup;
  1917. bool doubleTap = ( doubleTapTime - m_wiredDoubleTapTimestamp ) < WiredDoubleTapTime;
  1918. m_wiredDoubleTapTimestamp = doubleTapTime;
  1919. if( doubleTap )
  1920. {
  1921. UndoUtils.RegisterCompleteObjectUndo( this, Constants.UndoCreateConnectionId );
  1922. UndoUtils.RegisterCompleteObjectUndo( m_mainGraphInstance, Constants.UndoCreateConnectionId );
  1923. UndoUtils.RecordObject( outNode, Constants.UndoCreateConnectionId );
  1924. UndoUtils.RecordObject( inNode, Constants.UndoCreateConnectionId );
  1925. ParentNode wireNode = m_mainGraphInstance.CreateNode( typeof( WireNode ), true );
  1926. if( wireNode != null )
  1927. {
  1928. wireNode.Vec2Position = TranformedMousePos;
  1929. m_mainGraphInstance.CreateConnection( wireNode.InputPorts[ 0 ].NodeId, wireNode.InputPorts[ 0 ].PortId, outputPort.NodeId, outputPort.PortId );
  1930. m_mainGraphInstance.CreateConnection( inputPort.NodeId, inputPort.PortId, wireNode.OutputPorts[ 0 ].NodeId, wireNode.OutputPorts[ 0 ].PortId );
  1931. SetSaveIsDirty();
  1932. ForceRepaint();
  1933. UndoUtils.IncrementCurrentGroup();
  1934. }
  1935. }
  1936. break;
  1937. }
  1938. }
  1939. }
  1940. //Reset focus from any textfield which may be selected at this time
  1941. GUIUtility.keyboardControl = 0;
  1942. }
  1943. }
  1944. if( m_currentEvent.modifiers != EventModifiers.Shift && m_currentEvent.modifiers != EventModifiers.Control && !m_altBoxSelection )
  1945. m_mainGraphInstance.DeSelectAll();
  1946. if( m_wireReferenceUtils.ValidReferences() )
  1947. {
  1948. m_wireReferenceUtils.InvalidateReferences();
  1949. return;
  1950. }
  1951. if( !m_contextMenu.CheckShortcutKey() && m_currentEvent.modifiers != EventModifiers.Shift && m_currentEvent.modifiers != EventModifiers.Control || m_altBoxSelection )
  1952. {
  1953. // Only activate multiple selection if no node is selected and shift key not pressed
  1954. m_multipleSelectionActive = true;
  1955. m_multipleSelectionStart = TranformedMousePos;
  1956. m_multipleSelectionArea.position = m_multipleSelectionStart;
  1957. m_multipleSelectionArea.size = Vector2.zero;
  1958. }
  1959. UseCurrentEvent();
  1960. }
  1961. void OnLeftMouseDrag()
  1962. {
  1963. if( m_lostFocus )
  1964. {
  1965. m_lostFocus = false;
  1966. return;
  1967. }
  1968. if( m_lastKeyPressed == KeyCode.Q )
  1969. {
  1970. if( m_currentEvent.alt )
  1971. {
  1972. ModifyZoom( Constants.ALT_CAMERA_ZOOM_SPEED * ( m_currentEvent.delta.x + m_currentEvent.delta.y ), m_altKeyStartPos );
  1973. }
  1974. else
  1975. {
  1976. m_cameraOffset += m_cameraZoom * m_currentEvent.delta;
  1977. }
  1978. UseCurrentEvent();
  1979. return;
  1980. }
  1981. if( m_altDragStarted )
  1982. {
  1983. m_altDragStarted = false;
  1984. if( m_currentEvent.modifiers == EventModifiers.Alt && CurrentGraph.SelectedNodes.Count == 1 )
  1985. {
  1986. ParentNode node = CurrentGraph.SelectedNodes[ 0 ];
  1987. int lastId = 0;
  1988. int conn = 0;
  1989. for( int i = 0; i < node.InputPorts.Count; i++ )
  1990. {
  1991. if( node.InputPorts[ i ].IsConnected )
  1992. {
  1993. conn++;
  1994. lastId = i;
  1995. }
  1996. }
  1997. if( conn > 1 )
  1998. lastId = 0;
  1999. OutputPort outputPort = node.InputPorts[ lastId ].GetOutputConnection( 0 );
  2000. ParentNode outputNode = m_mainGraphInstance.GetNode( outputPort.NodeId );
  2001. bool outputIsWireNode = outputNode is WireNode;
  2002. UndoUtils.RegisterCompleteObjectUndo( this, Constants.UndoCreateConnectionId );
  2003. node.RecordObject( Constants.UndoCreateConnectionId );
  2004. outputNode.RecordObject( Constants.UndoCreateConnectionId );
  2005. List<InputPort> inputPorts = new List<InputPort>();
  2006. for( int i = 0; i < node.OutputPorts[ 0 ].ConnectionCount; i++ )
  2007. {
  2008. InputPort inputPort = node.OutputPorts[ 0 ].GetInputConnection( i );
  2009. ParentNode inputNode = m_mainGraphInstance.GetNode( inputPort.NodeId );
  2010. inputNode.RecordObject( Constants.UndoCreateConnectionId );
  2011. inputPorts.Add( inputPort );
  2012. }
  2013. for( int i = 0; i < inputPorts.Count; i++ )
  2014. {
  2015. if( outputIsWireNode )
  2016. {
  2017. if( i == 0 )
  2018. {
  2019. m_mainGraphInstance.CreateConnection( inputPorts[ i ].NodeId, inputPorts[ i ].PortId, outputPort.NodeId, outputPort.PortId );
  2020. }
  2021. else
  2022. {
  2023. UIUtils.DeleteConnection( true, inputPorts[ i ].NodeId, inputPorts[ i ].PortId, false, true );
  2024. }
  2025. }
  2026. else
  2027. {
  2028. m_mainGraphInstance.CreateConnection( inputPorts[ i ].NodeId, inputPorts[ i ].PortId, outputPort.NodeId, outputPort.PortId );
  2029. }
  2030. }
  2031. UIUtils.DeleteConnection( true, node.UniqueId, node.InputPorts[ lastId ].PortId, false, true );
  2032. SetSaveIsDirty();
  2033. ForceRepaint();
  2034. }
  2035. }
  2036. if( !m_wireReferenceUtils.ValidReferences() && !m_altBoxSelection )
  2037. {
  2038. if( m_mouseDownOnValidArea && m_insideEditorWindow )
  2039. {
  2040. if( m_currentEvent.control || Preferences.User.AlwaysSnapToGrid )
  2041. {
  2042. m_mainGraphInstance.MoveSelectedNodes( m_cameraZoom * m_currentEvent.delta, true );
  2043. }
  2044. else
  2045. {
  2046. m_mainGraphInstance.MoveSelectedNodes( m_cameraZoom * m_currentEvent.delta );
  2047. }
  2048. //m_mainGraphInstance.MoveSelectedNodes( m_cameraZoom * m_currentEvent.delta );
  2049. m_autoPanDirActive = true;
  2050. }
  2051. }
  2052. else
  2053. {
  2054. List<ParentNode> nodes = m_mainGraphInstance.GetNodesInGrid( m_drawInfo.TransformedMousePos );
  2055. if( nodes != null && nodes.Count > 0 )
  2056. {
  2057. Vector2 currentPortPos = new Vector2();
  2058. Vector2 mousePos = TranformedMousePos;
  2059. if( m_wireReferenceUtils.InputPortReference.IsValid )
  2060. {
  2061. OutputPort currentPort = null;
  2062. float smallestDistance = float.MaxValue;
  2063. Vector2 smallestPosition = Vector2.zero;
  2064. for( int nodeIdx = 0; nodeIdx < nodes.Count; nodeIdx++ )
  2065. {
  2066. List<OutputPort> outputPorts = nodes[ nodeIdx ].OutputPorts;
  2067. if( outputPorts != null )
  2068. {
  2069. for( int o = 0; o < outputPorts.Count; o++ )
  2070. {
  2071. if( outputPorts[ o ].Available )
  2072. {
  2073. currentPortPos.x = outputPorts[ o ].Position.x;
  2074. currentPortPos.y = outputPorts[ o ].Position.y;
  2075. currentPortPos = currentPortPos * m_cameraZoom - m_cameraOffset;
  2076. float dist = ( mousePos - currentPortPos ).sqrMagnitude;
  2077. if( dist < smallestDistance )
  2078. {
  2079. smallestDistance = dist;
  2080. smallestPosition = currentPortPos;
  2081. currentPort = outputPorts[ o ];
  2082. }
  2083. }
  2084. }
  2085. }
  2086. }
  2087. if( currentPort != null && currentPort.Available && ( smallestDistance < Constants.SNAP_SQR_DIST || currentPort.InsideActiveArea( ( mousePos + m_cameraOffset ) / m_cameraZoom ) ) )
  2088. {
  2089. m_wireReferenceUtils.ActivateSnap( smallestPosition, currentPort );
  2090. }
  2091. else
  2092. {
  2093. m_wireReferenceUtils.DeactivateSnap();
  2094. }
  2095. }
  2096. if( m_wireReferenceUtils.OutputPortReference.IsValid )
  2097. {
  2098. InputPort currentPort = null;
  2099. float smallestDistance = float.MaxValue;
  2100. Vector2 smallestPosition = Vector2.zero;
  2101. for( int nodeIdx = 0; nodeIdx < nodes.Count; nodeIdx++ )
  2102. {
  2103. List<InputPort> inputPorts = nodes[ nodeIdx ].InputPorts;
  2104. if( inputPorts != null )
  2105. {
  2106. for( int i = 0; i < inputPorts.Count; i++ )
  2107. {
  2108. if( inputPorts[ i ].Available )
  2109. {
  2110. currentPortPos.x = inputPorts[ i ].Position.x;
  2111. currentPortPos.y = inputPorts[ i ].Position.y;
  2112. currentPortPos = currentPortPos * m_cameraZoom - m_cameraOffset;
  2113. float dist = ( mousePos - currentPortPos ).sqrMagnitude;
  2114. if( dist < smallestDistance )
  2115. {
  2116. smallestDistance = dist;
  2117. smallestPosition = currentPortPos;
  2118. currentPort = inputPorts[ i ];
  2119. }
  2120. }
  2121. }
  2122. }
  2123. }
  2124. if( currentPort != null && currentPort.Available && ( smallestDistance < Constants.SNAP_SQR_DIST || currentPort.InsideActiveArea( ( mousePos + m_cameraOffset ) / m_cameraZoom ) ) )
  2125. {
  2126. m_wireReferenceUtils.ActivateSnap( smallestPosition, currentPort );
  2127. }
  2128. else
  2129. {
  2130. m_wireReferenceUtils.DeactivateSnap();
  2131. }
  2132. }
  2133. }
  2134. else if( m_wireReferenceUtils.SnapEnabled )
  2135. {
  2136. m_wireReferenceUtils.DeactivateSnap();
  2137. }
  2138. }
  2139. UseCurrentEvent();
  2140. }
  2141. public void OnLeftMouseUp()
  2142. {
  2143. m_lmbPressed = false;
  2144. if( m_multipleSelectionActive )
  2145. {
  2146. //m_multipleSelectionActive = false;
  2147. UpdateSelectionArea();
  2148. //m_mainGraphInstance.MultipleSelection( m_multipleSelectionArea, ( m_currentEvent.modifiers == EventModifiers.Shift || m_currentEvent.modifiers == EventModifiers.Control ), true );
  2149. if( m_currentEvent.alt && m_altBoxSelection )
  2150. {
  2151. m_mainGraphInstance.MultipleSelection( m_multipleSelectionArea, !m_currentEvent.shift );
  2152. }
  2153. else
  2154. {
  2155. m_mainGraphInstance.DeSelectAll();
  2156. m_mainGraphInstance.MultipleSelection( m_multipleSelectionArea );
  2157. }
  2158. }
  2159. if( m_wireReferenceUtils.ValidReferences() )
  2160. {
  2161. //Check if there is some kind of port beneath the mouse ... if so connect to it
  2162. ParentNode targetNode = m_wireReferenceUtils.SnapEnabled ? m_mainGraphInstance.GetNode( m_wireReferenceUtils.SnapPort.NodeId ) : m_mainGraphInstance.CheckNodeAt( m_currentMousePos );
  2163. if( targetNode != null && targetNode.ConnStatus != NodeConnectionStatus.Island )
  2164. {
  2165. if( m_wireReferenceUtils.InputPortReference.IsValid && m_wireReferenceUtils.InputPortReference.NodeId != targetNode.UniqueId )
  2166. {
  2167. OutputPort outputPort = m_wireReferenceUtils.SnapEnabled ? targetNode.GetOutputPortByUniqueId( m_wireReferenceUtils.SnapPort.PortId ) : targetNode.CheckOutputPortAt( m_currentMousePos );
  2168. if( outputPort != null && !outputPort.Locked && ( !m_wireReferenceUtils.InputPortReference.TypeLocked ||
  2169. m_wireReferenceUtils.InputPortReference.DataType == WirePortDataType.OBJECT ||
  2170. ( m_wireReferenceUtils.InputPortReference.TypeLocked && outputPort.DataType == m_wireReferenceUtils.InputPortReference.DataType ) ) )
  2171. {
  2172. ParentNode originNode = m_mainGraphInstance.GetNode( m_wireReferenceUtils.InputPortReference.NodeId );
  2173. InputPort inputPort = originNode.GetInputPortByUniqueId( m_wireReferenceUtils.InputPortReference.PortId );
  2174. UIUtils.MarkUndoAction();
  2175. UndoUtils.RegisterCompleteObjectUndo( this, Constants.UndoCreateConnectionId );
  2176. originNode.RecordObject( Constants.UndoCreateConnectionId );
  2177. targetNode.RecordObject( Constants.UndoCreateConnectionId );
  2178. if( inputPort.NotFreeForAllTypes && outputPort.NotFreeForAllTypes )
  2179. {
  2180. if( !inputPort.CheckValidType( outputPort.DataType ) )
  2181. {
  2182. UIUtils.ShowIncompatiblePortMessage( true, originNode, inputPort, targetNode, outputPort );
  2183. m_wireReferenceUtils.InvalidateReferences();
  2184. UseCurrentEvent();
  2185. return;
  2186. }
  2187. if( !outputPort.CheckValidType( inputPort.DataType ) )
  2188. {
  2189. UIUtils.ShowIncompatiblePortMessage( false, targetNode, outputPort, originNode, inputPort );
  2190. m_wireReferenceUtils.InvalidateReferences();
  2191. UseCurrentEvent();
  2192. return;
  2193. }
  2194. }
  2195. inputPort.DummyAdd( outputPort.NodeId, outputPort.PortId );
  2196. outputPort.DummyAdd( m_wireReferenceUtils.InputPortReference.NodeId, m_wireReferenceUtils.InputPortReference.PortId );
  2197. if( UIUtils.DetectNodeLoopsFrom( originNode, new Dictionary<int, int>() ) )
  2198. {
  2199. inputPort.DummyRemove();
  2200. outputPort.DummyRemove();
  2201. m_wireReferenceUtils.InvalidateReferences();
  2202. ShowMessage( "Infinite Loop detected" );
  2203. UseCurrentEvent();
  2204. return;
  2205. }
  2206. inputPort.DummyRemove();
  2207. outputPort.DummyRemove();
  2208. if( inputPort.IsConnected )
  2209. {
  2210. DeleteConnection( true, m_wireReferenceUtils.InputPortReference.NodeId, m_wireReferenceUtils.InputPortReference.PortId, true, false );
  2211. }
  2212. //link output to input
  2213. if( outputPort.ConnectTo( m_wireReferenceUtils.InputPortReference.NodeId, m_wireReferenceUtils.InputPortReference.PortId, m_wireReferenceUtils.InputPortReference.DataType, m_wireReferenceUtils.InputPortReference.TypeLocked ) )
  2214. targetNode.OnOutputPortConnected( outputPort.PortId, m_wireReferenceUtils.InputPortReference.NodeId, m_wireReferenceUtils.InputPortReference.PortId );
  2215. //link input to output
  2216. if( inputPort.ConnectTo( outputPort.NodeId, outputPort.PortId, outputPort.DataType, m_wireReferenceUtils.InputPortReference.TypeLocked ) )
  2217. originNode.OnInputPortConnected( m_wireReferenceUtils.InputPortReference.PortId, targetNode.UniqueId, outputPort.PortId );
  2218. m_mainGraphInstance.MarkWireHighlights();
  2219. }
  2220. else if( outputPort != null && m_wireReferenceUtils.InputPortReference.TypeLocked && m_wireReferenceUtils.InputPortReference.DataType != outputPort.DataType )
  2221. {
  2222. ShowMessage( "Attempting to connect a port locked to type " + m_wireReferenceUtils.InputPortReference.DataType + " into a port of type " + outputPort.DataType );
  2223. }
  2224. ShaderIsModified = true;
  2225. SetSaveIsDirty();
  2226. }
  2227. if( m_wireReferenceUtils.OutputPortReference.IsValid && m_wireReferenceUtils.OutputPortReference.NodeId != targetNode.UniqueId )
  2228. {
  2229. InputPort inputPort = m_wireReferenceUtils.SnapEnabled ? targetNode.GetInputPortByUniqueId( m_wireReferenceUtils.SnapPort.PortId ) : targetNode.CheckInputPortAt( m_currentMousePos );
  2230. if( inputPort != null && !inputPort.Locked && ( !inputPort.TypeLocked ||
  2231. inputPort.DataType == WirePortDataType.OBJECT ||
  2232. ( inputPort.TypeLocked && inputPort.DataType == m_wireReferenceUtils.OutputPortReference.DataType ) ) )
  2233. {
  2234. ParentNode originNode = m_mainGraphInstance.GetNode( m_wireReferenceUtils.OutputPortReference.NodeId );
  2235. OutputPort outputPort = originNode.GetOutputPortByUniqueId( m_wireReferenceUtils.OutputPortReference.PortId );
  2236. UIUtils.MarkUndoAction();
  2237. UndoUtils.RegisterCompleteObjectUndo( this, Constants.UndoCreateConnectionId );
  2238. originNode.RecordObject( Constants.UndoCreateConnectionId );
  2239. targetNode.RecordObject( Constants.UndoCreateConnectionId );
  2240. if( inputPort.NotFreeForAllTypes && outputPort.NotFreeForAllTypes )
  2241. {
  2242. if( !inputPort.CheckValidType( outputPort.DataType ) )
  2243. {
  2244. UIUtils.ShowIncompatiblePortMessage( true, targetNode, inputPort, originNode, outputPort );
  2245. m_wireReferenceUtils.InvalidateReferences();
  2246. UseCurrentEvent();
  2247. return;
  2248. }
  2249. if( !outputPort.CheckValidType( inputPort.DataType ) )
  2250. {
  2251. UIUtils.ShowIncompatiblePortMessage( false, originNode, outputPort, targetNode, inputPort );
  2252. m_wireReferenceUtils.InvalidateReferences();
  2253. UseCurrentEvent();
  2254. return;
  2255. }
  2256. }
  2257. inputPort.DummyAdd( m_wireReferenceUtils.OutputPortReference.NodeId, m_wireReferenceUtils.OutputPortReference.PortId );
  2258. outputPort.DummyAdd( inputPort.NodeId, inputPort.PortId );
  2259. if( UIUtils.DetectNodeLoopsFrom( targetNode, new Dictionary<int, int>() ) )
  2260. {
  2261. inputPort.DummyRemove();
  2262. outputPort.DummyRemove();
  2263. m_wireReferenceUtils.InvalidateReferences();
  2264. ShowMessage( "Infinite Loop detected" );
  2265. UseCurrentEvent();
  2266. return;
  2267. }
  2268. inputPort.DummyRemove();
  2269. outputPort.DummyRemove();
  2270. if( inputPort.IsConnected )
  2271. {
  2272. if( m_currentEvent.control && m_wireReferenceUtils.SwitchPortReference.IsValid )
  2273. {
  2274. ParentNode oldOutputNode = UIUtils.GetNode( inputPort.GetConnection( 0 ).NodeId );
  2275. OutputPort oldOutputPort = oldOutputNode.GetOutputPortByUniqueId( inputPort.GetConnection( 0 ).PortId );
  2276. ParentNode switchNode = UIUtils.GetNode( m_wireReferenceUtils.SwitchPortReference.NodeId );
  2277. InputPort switchPort = switchNode.GetInputPortByUniqueId( m_wireReferenceUtils.SwitchPortReference.PortId );
  2278. switchPort.DummyAdd( oldOutputPort.NodeId, oldOutputPort.PortId );
  2279. oldOutputPort.DummyAdd( switchPort.NodeId, switchPort.PortId );
  2280. if( UIUtils.DetectNodeLoopsFrom( switchNode, new Dictionary<int, int>() ) )
  2281. {
  2282. switchPort.DummyRemove();
  2283. oldOutputPort.DummyRemove();
  2284. m_wireReferenceUtils.InvalidateReferences();
  2285. ShowMessage( "Infinite Loop detected" );
  2286. UseCurrentEvent();
  2287. return;
  2288. }
  2289. switchPort.DummyRemove();
  2290. oldOutputPort.DummyRemove();
  2291. DeleteConnection( true, inputPort.NodeId, inputPort.PortId, true, false );
  2292. ConnectInputToOutput( switchPort.NodeId, switchPort.PortId, oldOutputPort.NodeId, oldOutputPort.PortId );
  2293. }
  2294. else
  2295. {
  2296. DeleteConnection( true, inputPort.NodeId, inputPort.PortId, true, false );
  2297. }
  2298. }
  2299. inputPort.InvalidateAllConnections();
  2300. //link input to output
  2301. if( inputPort.ConnectTo( m_wireReferenceUtils.OutputPortReference.NodeId, m_wireReferenceUtils.OutputPortReference.PortId, m_wireReferenceUtils.OutputPortReference.DataType, inputPort.TypeLocked ) )
  2302. targetNode.OnInputPortConnected( inputPort.PortId, m_wireReferenceUtils.OutputPortReference.NodeId, m_wireReferenceUtils.OutputPortReference.PortId );
  2303. //link output to input
  2304. if( outputPort.ConnectTo( inputPort.NodeId, inputPort.PortId, inputPort.DataType, inputPort.TypeLocked ) )
  2305. originNode.OnOutputPortConnected( m_wireReferenceUtils.OutputPortReference.PortId, targetNode.UniqueId, inputPort.PortId );
  2306. m_mainGraphInstance.MarkWireHighlights();
  2307. }
  2308. else if( inputPort != null && inputPort.TypeLocked && inputPort.DataType != m_wireReferenceUtils.OutputPortReference.DataType )
  2309. {
  2310. ShowMessage( "Attempting to connect a " + m_wireReferenceUtils.OutputPortReference.DataType + " to a port locked to type " + inputPort.DataType );
  2311. }
  2312. ShaderIsModified = true;
  2313. SetSaveIsDirty();
  2314. }
  2315. m_wireReferenceUtils.InvalidateReferences();
  2316. }
  2317. else
  2318. {
  2319. if( UIUtils.ShowContextOnPick )
  2320. m_contextPalette.Show( m_currentMousePos2D, m_cameraInfo );
  2321. else
  2322. m_wireReferenceUtils.InvalidateReferences();
  2323. }
  2324. }
  2325. else if( m_currentEvent.modifiers == EventModifiers.Alt && m_altAvailable && CurrentGraph.SelectedNodes.Count == 1 && !m_altBoxSelection && !m_multipleSelectionActive )
  2326. {
  2327. List<WireBezierReference> wireRefs = m_mainGraphInstance.GetWireBezierListInPos( m_currentMousePos2D );
  2328. if( wireRefs != null && wireRefs.Count > 0 )
  2329. {
  2330. float closestDist = 50;
  2331. int closestId = 0;
  2332. for( int i = 0; i < wireRefs.Count; i++ )
  2333. {
  2334. ParentNode outNode = m_mainGraphInstance.GetNode( wireRefs[ i ].OutNodeId );
  2335. ParentNode inNode = m_mainGraphInstance.GetNode( wireRefs[ i ].InNodeId );
  2336. if( outNode == CurrentGraph.SelectedNodes[ 0 ] || inNode == CurrentGraph.SelectedNodes[ 0 ] )
  2337. continue;
  2338. OutputPort outputPort = outNode.GetOutputPortByUniqueId( wireRefs[ i ].OutPortId );
  2339. InputPort inputPort = inNode.GetInputPortByUniqueId( wireRefs[ i ].InPortId );
  2340. // Calculate the 4 points for bezier taking into account wire nodes and their automatic tangents
  2341. Vector3 endPos = new Vector3( inputPort.Position.x, inputPort.Position.y );
  2342. Vector3 startPos = new Vector3( outputPort.Position.x, outputPort.Position.y );
  2343. float mag = ( endPos - startPos ).magnitude;
  2344. float resizedMag = Mathf.Min( mag, Constants.HORIZONTAL_TANGENT_SIZE * m_drawInfo.InvertedZoom );
  2345. Vector3 startTangent = new Vector3( startPos.x + resizedMag, startPos.y );
  2346. Vector3 endTangent = new Vector3( endPos.x - resizedMag, endPos.y );
  2347. if( inNode != null && inNode.GetType() == typeof( WireNode ) )
  2348. endTangent = endPos + ( ( inNode as WireNode ).TangentDirection ) * mag * 0.33f;
  2349. if( outNode != null && outNode.GetType() == typeof( WireNode ) )
  2350. startTangent = startPos - ( ( outNode as WireNode ).TangentDirection ) * mag * 0.33f;
  2351. //Vector2 pos = ( CurrentGraph.SelectedNodes[0].CenterPosition + m_cameraOffset ) / m_cameraZoom;
  2352. float dist = HandleUtility.DistancePointBezier( /*pos*/ m_currentMousePos, startPos, endPos, startTangent, endTangent );
  2353. if( dist < 40 )
  2354. {
  2355. if( dist < closestDist )
  2356. {
  2357. closestDist = dist;
  2358. closestId = i;
  2359. }
  2360. }
  2361. }
  2362. if( closestDist < 40 )
  2363. {
  2364. ParentNode outNode = m_mainGraphInstance.GetNode( wireRefs[ closestId ].OutNodeId );
  2365. ParentNode inNode = m_mainGraphInstance.GetNode( wireRefs[ closestId ].InNodeId );
  2366. OutputPort outputPort = outNode.GetOutputPortByUniqueId( wireRefs[ closestId ].OutPortId );
  2367. InputPort inputPort = inNode.GetInputPortByUniqueId( wireRefs[ closestId ].InPortId );
  2368. ParentNode selectedNode = CurrentGraph.SelectedNodes[ 0 ];
  2369. if( selectedNode.InputPorts.Count > 0 && selectedNode.OutputPorts.Count > 0 )
  2370. {
  2371. UndoUtils.RegisterCompleteObjectUndo( this, Constants.UndoCreateConnectionId );
  2372. selectedNode.RecordObject( Constants.UndoCreateConnectionId );
  2373. inNode.RecordObject( Constants.UndoCreateConnectionId );
  2374. outNode.RecordObject( Constants.UndoCreateConnectionId );
  2375. m_mainGraphInstance.CreateConnection( selectedNode.UniqueId, selectedNode.InputPorts[ 0 ].PortId, outputPort.NodeId, outputPort.PortId );
  2376. m_mainGraphInstance.CreateConnection( inputPort.NodeId, inputPort.PortId, selectedNode.UniqueId, selectedNode.OutputPorts[ 0 ].PortId );
  2377. }
  2378. SetSaveIsDirty();
  2379. ForceRepaint();
  2380. }
  2381. }
  2382. }
  2383. UIUtils.ShowContextOnPick = true;
  2384. m_altBoxSelection = false;
  2385. m_multipleSelectionActive = false;
  2386. UseCurrentEvent();
  2387. }
  2388. public void ConnectInputToOutput( int inNodeId, int inPortId, int outNodeId, int outPortId, bool registerUndo = true )
  2389. {
  2390. ParentNode inNode = m_mainGraphInstance.GetNode( inNodeId );
  2391. ParentNode outNode = m_mainGraphInstance.GetNode( outNodeId );
  2392. if( inNode != null && outNode != null )
  2393. {
  2394. InputPort inPort = inNode.GetInputPortByUniqueId( inPortId );
  2395. OutputPort outPort = outNode.GetOutputPortByUniqueId( outPortId );
  2396. if( inPort != null && outPort != null )
  2397. {
  2398. if( registerUndo )
  2399. {
  2400. UndoUtils.RegisterCompleteObjectUndo( this, Constants.UndoCreateConnectionId );
  2401. inNode.RecordObject( Constants.UndoCreateConnectionId );
  2402. outNode.RecordObject( Constants.UndoCreateConnectionId );
  2403. }
  2404. if( inPort.ConnectTo( outNodeId, outPortId, outPort.DataType, inPort.TypeLocked ) )
  2405. {
  2406. inNode.OnInputPortConnected( inPortId, outNodeId, outPortId );
  2407. }
  2408. if( outPort.ConnectTo( inNodeId, inPortId, inPort.DataType, inPort.TypeLocked ) )
  2409. {
  2410. outNode.OnOutputPortConnected( outPortId, inNodeId, inPortId );
  2411. }
  2412. }
  2413. m_mainGraphInstance.MarkWireHighlights();
  2414. ShaderIsModified = true;
  2415. }
  2416. }
  2417. void OnRightMouseDown()
  2418. {
  2419. Focus();
  2420. m_rmbStartPos = m_currentMousePos2D;
  2421. UseCurrentEvent();
  2422. }
  2423. void OnRightMouseDrag()
  2424. {
  2425. // We look at the control to detect when user hits a tooltip ( which has a hot control of 0 )
  2426. // This needs to be checked because on this first "frame" of hitting a tooltip because it generates incorrect mouse delta values
  2427. if( GUIUtility.hotControl == 0 && m_lastHotControl != 0 )
  2428. {
  2429. m_lastHotControl = GUIUtility.hotControl;
  2430. return;
  2431. }
  2432. m_lastHotControl = GUIUtility.hotControl;
  2433. if( m_currentEvent.alt )
  2434. {
  2435. ModifyZoom( Constants.ALT_CAMERA_ZOOM_SPEED * ( m_currentEvent.delta.x + m_currentEvent.delta.y ), m_altKeyStartPos );
  2436. }
  2437. else
  2438. {
  2439. m_cameraOffset += m_cameraZoom * m_currentEvent.delta;
  2440. }
  2441. UseCurrentEvent();
  2442. }
  2443. void OnRightMouseUp()
  2444. {
  2445. //Resetting the hot control test variable so it can be used again on right mouse drag detection ( if we did not do this then m_lastHotControl could be left with a a value of 0 and wouldn't be able to be correctly used on rthe drag )
  2446. m_lastHotControl = -1;
  2447. if( ( m_rmbStartPos - m_currentMousePos2D ).sqrMagnitude < Constants.RMB_SCREEN_DIST )
  2448. {
  2449. ParentNode node = m_mainGraphInstance.CheckNodeAt( m_currentMousePos, true );
  2450. if( node == null )
  2451. {
  2452. m_contextPalette.Show( m_currentMousePos2D, m_cameraInfo );
  2453. }
  2454. }
  2455. UseCurrentEvent();
  2456. }
  2457. void UpdateSelectionArea()
  2458. {
  2459. m_multipleSelectionArea.size = TranformedMousePos - m_multipleSelectionStart;
  2460. }
  2461. public void OnValidObjectsDropped( UnityEngine.Object[] droppedObjs )
  2462. {
  2463. bool propagateDraggedObjsToNode = true;
  2464. // Only supporting single drag&drop object selection
  2465. if( droppedObjs.Length == 1 )
  2466. {
  2467. ShaderIsModified = true;
  2468. SetSaveIsDirty();
  2469. // Check if its a shader, material or game object and if so load the shader graph code from it
  2470. Shader newShader = droppedObjs[ 0 ] as Shader;
  2471. Material newMaterial = null;
  2472. if( newShader == null )
  2473. {
  2474. newMaterial = droppedObjs[ 0 ] as Material;
  2475. bool isProcedural = ( newMaterial != null );
  2476. if( newMaterial != null && !isProcedural )
  2477. {
  2478. if( UIUtils.IsUnityNativeShader( AssetDatabase.GetAssetPath( newMaterial.shader ) ) )
  2479. {
  2480. return;
  2481. }
  2482. //newShader = newMaterial.shader;
  2483. LoadMaterialToASE( newMaterial );
  2484. //m_mainGraphInstance.UpdateMaterialOnMasterNode( newMaterial );
  2485. }
  2486. else
  2487. {
  2488. GameObject go = droppedObjs[ 0 ] as GameObject;
  2489. if( go != null )
  2490. {
  2491. Renderer renderer = go.GetComponent<Renderer>();
  2492. if( renderer )
  2493. {
  2494. newMaterial = renderer.sharedMaterial;
  2495. newShader = newMaterial.shader;
  2496. }
  2497. }
  2498. }
  2499. }
  2500. if( newShader != null )
  2501. {
  2502. ConvertShaderToASE( newShader );
  2503. propagateDraggedObjsToNode = false;
  2504. }
  2505. // if not shader loading then propagate the seletion to whats below the mouse
  2506. if( propagateDraggedObjsToNode )
  2507. {
  2508. ParentNode node = m_mainGraphInstance.CheckNodeAt( m_currentMousePos );
  2509. if( node != null )
  2510. {
  2511. // if there's a node then pass the object into it to see if there's a setup with it
  2512. node.OnObjectDropped( droppedObjs[ 0 ] );
  2513. }
  2514. else
  2515. {
  2516. // If not then check if there's a node that can be created through the dropped object
  2517. ParentNode newNode = m_contextMenu.CreateNodeFromCastType( droppedObjs[ 0 ].GetType() );
  2518. if( newNode )
  2519. {
  2520. newNode.ContainerGraph = m_mainGraphInstance;
  2521. newNode.Vec2Position = TranformedMousePos;
  2522. m_mainGraphInstance.AddNode( newNode, true );
  2523. newNode.SetupFromCastObject( droppedObjs[ 0 ] );
  2524. m_mainGraphInstance.SelectNode( newNode, false, false );
  2525. ForceRepaint();
  2526. bool find = false;
  2527. if( newNode is FunctionNode && CurrentGraph.CurrentShaderFunction != null )
  2528. find = SearchFunctionNodeRecursively( CurrentGraph.CurrentShaderFunction );
  2529. if( find )
  2530. {
  2531. DestroyNode( newNode, false );
  2532. ShowMessage( "Shader Function loop detected, new node was removed to prevent errors." );
  2533. }
  2534. }
  2535. }
  2536. }
  2537. }
  2538. }
  2539. public bool SearchFunctionNodeRecursively( AmplifyShaderFunction function )
  2540. {
  2541. List<FunctionNode> graphList = UIUtils.FunctionList();
  2542. bool nodeFind = false;
  2543. for( int i = 0; i < graphList.Count; i++ )
  2544. {
  2545. ParentGraph temp = CustomGraph;
  2546. CustomGraph = graphList[ i ].FunctionGraph;
  2547. nodeFind = SearchFunctionNodeRecursively( function );
  2548. CustomGraph = temp;
  2549. //Debug.Log( "tested = " + node.Function.FunctionName + " : " + function.FunctionName );
  2550. if( graphList[ i ].Function == function )
  2551. return true;
  2552. }
  2553. return nodeFind;
  2554. }
  2555. public void SetDelayedMaterialMode( Material material )
  2556. {
  2557. if( material == null )
  2558. return;
  2559. m_delayedMaterialSet = material;
  2560. }
  2561. public ShaderLoadResult LoadDroppedObject( bool value, Shader shader, Material material, AmplifyShaderFunction shaderFunction = null )
  2562. {
  2563. UIUtils.CurrentWindow = this;
  2564. ShaderLoadResult result;
  2565. if( shaderFunction != null )
  2566. {
  2567. string assetDatapath = AssetDatabase.GetAssetPath( shaderFunction );
  2568. string latestOpenedFolder = Application.dataPath + assetDatapath.Substring( 6 );
  2569. UIUtils.LatestOpenedFolder = latestOpenedFolder.Substring( 0, latestOpenedFolder.LastIndexOf( '/' ) + 1 );
  2570. result = LoadFromDisk( assetDatapath, shaderFunction );
  2571. CurrentSelection = ASESelectionMode.ShaderFunction;
  2572. IsShaderFunctionWindow = true;
  2573. titleContent.text = GenerateTabTitle( shaderFunction.FunctionName );
  2574. titleContent.image = UIUtils.ShaderFunctionIcon;
  2575. m_lastpath = assetDatapath;
  2576. m_nodeParametersWindow.OnShaderFunctionLoad();
  2577. //EditorPrefs.SetString( IOUtils.LAST_OPENED_OBJ_ID, assetDatapath );
  2578. }
  2579. else if( value && shader != null )
  2580. {
  2581. string assetDatapath = AssetDatabase.GetAssetPath( shader );
  2582. string latestOpenedFolder = Application.dataPath + assetDatapath.Substring( 6 );
  2583. UIUtils.LatestOpenedFolder = latestOpenedFolder.Substring( 0, latestOpenedFolder.LastIndexOf( '/' ) + 1 );
  2584. result = LoadFromDisk( assetDatapath );
  2585. switch( result )
  2586. {
  2587. case ShaderLoadResult.LOADED:
  2588. {
  2589. m_mainGraphInstance.UpdateShaderOnMasterNode( shader );
  2590. }
  2591. break;
  2592. case ShaderLoadResult.ASE_INFO_NOT_FOUND:
  2593. {
  2594. ShowMessage( "Loaded shader wasn't created with ASE. Saving it will remove previous data." );
  2595. UIUtils.CreateEmptyFromInvalid( shader );
  2596. }
  2597. break;
  2598. case ShaderLoadResult.FILE_NOT_FOUND:
  2599. case ShaderLoadResult.UNITY_NATIVE_PATHS:
  2600. {
  2601. UIUtils.CreateEmptyFromInvalid( shader );
  2602. }
  2603. break;
  2604. }
  2605. m_mainGraphInstance.UpdateMaterialOnMasterNode( material );
  2606. m_mainGraphInstance.SetMaterialModeOnGraph( material );
  2607. if( material != null )
  2608. {
  2609. CurrentSelection = ASESelectionMode.Material;
  2610. IsShaderFunctionWindow = false;
  2611. titleContent.text = GenerateTabTitle( material.name );
  2612. titleContent.image = UIUtils.MaterialIcon;
  2613. if( material.HasProperty( IOUtils.DefaultASEDirtyCheckId ) )
  2614. {
  2615. material.SetInt( IOUtils.DefaultASEDirtyCheckId, 1 );
  2616. }
  2617. m_lastpath = AssetDatabase.GetAssetPath( material );
  2618. EditorPrefs.SetString( IOUtils.LAST_OPENED_OBJ_ID, m_lastpath );
  2619. }
  2620. else
  2621. {
  2622. CurrentSelection = ASESelectionMode.Shader;
  2623. IsShaderFunctionWindow = false;
  2624. titleContent.text = GenerateTabTitle( shader.name );
  2625. titleContent.image = UIUtils.ShaderIcon;
  2626. m_lastpath = AssetDatabase.GetAssetPath( shader );
  2627. EditorPrefs.SetString( IOUtils.LAST_OPENED_OBJ_ID, m_lastpath );
  2628. }
  2629. }
  2630. else
  2631. {
  2632. result = ShaderLoadResult.FILE_NOT_FOUND;
  2633. }
  2634. return result;
  2635. }
  2636. bool InsideMenus( Vector2 position )
  2637. {
  2638. for( int i = 0; i < m_registeredMenus.Count; i++ )
  2639. {
  2640. if( m_registeredMenus[ i ].IsInside( position ) )
  2641. {
  2642. return true;
  2643. }
  2644. }
  2645. return false;
  2646. }
  2647. void HandleGUIEvents()
  2648. {
  2649. if( m_currentEvent.type == EventType.KeyDown )
  2650. {
  2651. m_contextMenu.UpdateKeyPress( m_currentEvent.keyCode );
  2652. }
  2653. else if( m_currentEvent.type == EventType.KeyUp )
  2654. {
  2655. m_contextMenu.UpdateKeyReleased( m_currentEvent.keyCode );
  2656. }
  2657. if( InsideMenus( m_currentMousePos2D ) )
  2658. {
  2659. if( m_currentEvent.type == EventType.Used )
  2660. m_mouseDownOnValidArea = false;
  2661. if( m_currentEvent.type == EventType.MouseDown )
  2662. {
  2663. m_mouseDownOnValidArea = false;
  2664. UseCurrentEvent();
  2665. }
  2666. return;
  2667. }
  2668. else if( m_nodeParametersWindow.IsResizing || m_paletteWindow.IsResizing )
  2669. {
  2670. m_mouseDownOnValidArea = false;
  2671. }
  2672. int controlID = GUIUtility.GetControlID( FocusType.Passive );
  2673. switch( m_currentEvent.GetTypeForControl( controlID ) )
  2674. {
  2675. case EventType.MouseDown:
  2676. {
  2677. GUIUtility.hotControl = controlID;
  2678. switch( m_currentEvent.button )
  2679. {
  2680. case ButtonClickId.LeftMouseButton:
  2681. {
  2682. OnLeftMouseDown();
  2683. }
  2684. break;
  2685. case ButtonClickId.RightMouseButton:
  2686. case ButtonClickId.MiddleMouseButton:
  2687. {
  2688. OnRightMouseDown();
  2689. }
  2690. break;
  2691. }
  2692. }
  2693. break;
  2694. case EventType.MouseMove:
  2695. {
  2696. m_keyEvtMousePos2D = m_currentEvent.mousePosition;
  2697. }
  2698. break;
  2699. case EventType.MouseUp:
  2700. {
  2701. GUIUtility.hotControl = 0;
  2702. switch( m_currentEvent.button )
  2703. {
  2704. case ButtonClickId.LeftMouseButton:
  2705. {
  2706. OnLeftMouseUp();
  2707. }
  2708. break;
  2709. case ButtonClickId.MiddleMouseButton: break;
  2710. case ButtonClickId.RightMouseButton:
  2711. {
  2712. OnRightMouseUp();
  2713. }
  2714. break;
  2715. }
  2716. }
  2717. break;
  2718. case EventType.MouseDrag:
  2719. {
  2720. switch( m_currentEvent.button )
  2721. {
  2722. case ButtonClickId.LeftMouseButton:
  2723. {
  2724. OnLeftMouseDrag();
  2725. }
  2726. break;
  2727. case ButtonClickId.MiddleMouseButton:
  2728. case ButtonClickId.RightMouseButton:
  2729. {
  2730. OnRightMouseDrag();
  2731. }
  2732. break;
  2733. }
  2734. }
  2735. break;
  2736. case EventType.ScrollWheel:
  2737. {
  2738. OnScrollWheel();
  2739. }
  2740. break;
  2741. case EventType.KeyDown:
  2742. {
  2743. OnKeyboardDown();
  2744. }
  2745. break;
  2746. case EventType.KeyUp:
  2747. {
  2748. OnKeyboardUp();
  2749. }
  2750. break;
  2751. case EventType.ValidateCommand:
  2752. {
  2753. switch( m_currentEvent.commandName )
  2754. {
  2755. case CopyCommand:
  2756. case PasteCommand:
  2757. case SelectAll:
  2758. case Duplicate:
  2759. {
  2760. m_currentEvent.Use();
  2761. }
  2762. break;
  2763. case ObjectSelectorClosed:
  2764. {
  2765. m_mouseDownOnValidArea = false;
  2766. }
  2767. break;
  2768. }
  2769. }
  2770. break;
  2771. case EventType.ExecuteCommand:
  2772. {
  2773. m_currentEvent.Use();
  2774. switch( m_currentEvent.commandName )
  2775. {
  2776. case CopyCommand:
  2777. {
  2778. CopyToClipboard();
  2779. }
  2780. break;
  2781. case PasteCommand:
  2782. {
  2783. PasteFromClipboard( true );
  2784. }
  2785. break;
  2786. case SelectAll:
  2787. {
  2788. m_mainGraphInstance.SelectAll();
  2789. ForceRepaint();
  2790. }
  2791. break;
  2792. case Duplicate:
  2793. {
  2794. CopyToClipboard();
  2795. PasteFromClipboard( true );
  2796. }
  2797. break;
  2798. case ObjectSelectorClosed:
  2799. {
  2800. m_mouseDownOnValidArea = false;
  2801. }
  2802. break;
  2803. }
  2804. }
  2805. break;
  2806. case EventType.Repaint:
  2807. {
  2808. }
  2809. break;
  2810. }
  2811. m_dragAndDropTool.TestDragAndDrop( m_graphArea );
  2812. }
  2813. public void DeleteConnection( bool isInput, int nodeId, int portId, bool registerOnLog, bool propagateCallback )
  2814. {
  2815. m_mainGraphInstance.DeleteConnection( isInput, nodeId, portId, registerOnLog, propagateCallback );
  2816. }
  2817. void DeleteSelectedNodes()
  2818. {
  2819. if( m_mainGraphInstance.SelectedNodes.Count == 0 )
  2820. return;
  2821. UIUtils.ClearUndoHelper();
  2822. ParentNode[] selectedNodes = new ParentNode[ m_mainGraphInstance.SelectedNodes.Count ];
  2823. for( int i = 0; i < selectedNodes.Length; i++ )
  2824. {
  2825. selectedNodes[ i ] = m_mainGraphInstance.SelectedNodes[ i ];
  2826. selectedNodes[ i ].Rewire();
  2827. UIUtils.CheckUndoNode( selectedNodes[ i ] );
  2828. }
  2829. //Check nodes connected to deleted nodes to preserve connections on undo
  2830. List<ParentNode> extraNodes = new List<ParentNode>();
  2831. for( int selectedNodeIdx = 0; selectedNodeIdx < selectedNodes.Length; selectedNodeIdx++ )
  2832. {
  2833. // Check inputs
  2834. {
  2835. int inputIdxCount = selectedNodes[ selectedNodeIdx ].InputPorts.Count;
  2836. if( inputIdxCount > 0 )
  2837. {
  2838. for( int inputIdx = 0; inputIdx < inputIdxCount; inputIdx++ )
  2839. {
  2840. if( selectedNodes[ selectedNodeIdx ].InputPorts[ inputIdx ].IsConnected )
  2841. {
  2842. int nodeIdx = selectedNodes[ selectedNodeIdx ].InputPorts[ inputIdx ].ExternalReferences[ 0 ].NodeId;
  2843. if( nodeIdx > -1 )
  2844. {
  2845. ParentNode node = m_mainGraphInstance.GetNode( nodeIdx );
  2846. if( node != null && UIUtils.CheckUndoNode( node ) )
  2847. {
  2848. extraNodes.Add( node );
  2849. }
  2850. }
  2851. }
  2852. }
  2853. }
  2854. }
  2855. // Check outputs
  2856. int outputIdxCount = selectedNodes[ selectedNodeIdx ].OutputPorts.Count;
  2857. if( outputIdxCount > 0 )
  2858. {
  2859. for( int outputIdx = 0; outputIdx < outputIdxCount; outputIdx++ )
  2860. {
  2861. int inputIdxCount = selectedNodes[ selectedNodeIdx ].OutputPorts[ outputIdx ].ExternalReferences.Count;
  2862. if( inputIdxCount > 0 )
  2863. {
  2864. for( int inputIdx = 0; inputIdx < inputIdxCount; inputIdx++ )
  2865. {
  2866. int nodeIdx = selectedNodes[ selectedNodeIdx ].OutputPorts[ outputIdx ].ExternalReferences[ inputIdx ].NodeId;
  2867. if( nodeIdx > -1 )
  2868. {
  2869. ParentNode node = m_mainGraphInstance.GetNode( nodeIdx );
  2870. if( UIUtils.CheckUndoNode( node ) )
  2871. {
  2872. extraNodes.Add( node );
  2873. }
  2874. }
  2875. }
  2876. }
  2877. }
  2878. }
  2879. }
  2880. UIUtils.ClearUndoHelper();
  2881. //UndoUtils.IncrementCurrentGroup();
  2882. //Record deleted nodes
  2883. UIUtils.MarkUndoAction();
  2884. UndoUtils.RegisterCompleteObjectUndo( this, Constants.UndoDeleteNodeId );
  2885. UndoUtils.RegisterCompleteObjectUndo( m_mainGraphInstance, Constants.UndoDeleteNodeId );
  2886. UndoUtils.RecordObjects( selectedNodes, Constants.UndoDeleteNodeId );
  2887. UndoUtils.RecordObjects( extraNodes.ToArray(), Constants.UndoDeleteNodeId );
  2888. //Record deleting connections
  2889. for( int i = 0; i < selectedNodes.Length; i++ )
  2890. {
  2891. selectedNodes[ i ].Alive = false;
  2892. m_mainGraphInstance.DeleteAllConnectionFromNode( selectedNodes[ i ], false, true, true );
  2893. }
  2894. //Delete
  2895. m_mainGraphInstance.DeleteNodesOnArray( ref selectedNodes );
  2896. //UndoUtils.IncrementCurrentGroup();
  2897. extraNodes.Clear();
  2898. extraNodes = null;
  2899. EditorUtility.SetDirty( this );
  2900. ForceRepaint();
  2901. }
  2902. void OnKeyboardUp()
  2903. {
  2904. CheckKeyboardCameraUp();
  2905. if( m_altPressDown )
  2906. {
  2907. m_altPressDown = false;
  2908. }
  2909. if( m_shortcutManager.ActivateShortcut( m_currentEvent.modifiers, m_lastKeyPressed, false ) )
  2910. {
  2911. ForceRepaint();
  2912. }
  2913. m_lastKeyPressed = KeyCode.None;
  2914. }
  2915. bool OnKeyboardPress( KeyCode code )
  2916. {
  2917. return ( m_currentEvent.keyCode == code && m_lastKeyPressed == KeyCode.None );
  2918. }
  2919. void CheckKeyboardCameraDown()
  2920. {
  2921. if( m_contextPalette.IsActive )
  2922. return;
  2923. if( m_currentEvent.alt )
  2924. {
  2925. bool foundKey = false;
  2926. float dir = 0;
  2927. switch( m_currentEvent.keyCode )
  2928. {
  2929. case KeyCode.UpArrow: foundKey = true; dir = 1; break;
  2930. case KeyCode.DownArrow: foundKey = true; dir = -1; break;
  2931. case KeyCode.LeftArrow: foundKey = true; dir = 1; break;
  2932. case KeyCode.RightArrow: foundKey = true; dir = -1; break;
  2933. }
  2934. if( foundKey )
  2935. {
  2936. ModifyZoom( Constants.ALT_CAMERA_ZOOM_SPEED * dir * m_cameraSpeed, new Vector2( m_cameraInfo.width * 0.5f, m_cameraInfo.height * 0.5f ) );
  2937. if( m_cameraSpeed < 15 )
  2938. m_cameraSpeed += 0.2f;
  2939. UseCurrentEvent();
  2940. }
  2941. }
  2942. else
  2943. {
  2944. bool foundKey = false;
  2945. Vector2 dir = Vector2.zero;
  2946. switch( m_currentEvent.keyCode )
  2947. {
  2948. case KeyCode.UpArrow: foundKey = true; dir = Vector2.up; break;
  2949. case KeyCode.DownArrow: foundKey = true; dir = Vector2.down; break;
  2950. case KeyCode.LeftArrow: foundKey = true; dir = Vector2.right; break;
  2951. case KeyCode.RightArrow: foundKey = true; dir = Vector2.left; break;
  2952. }
  2953. if( foundKey )
  2954. {
  2955. m_cameraOffset += m_cameraZoom * m_cameraSpeed * dir;
  2956. if( m_cameraSpeed < 15 )
  2957. m_cameraSpeed += 0.2f;
  2958. UseCurrentEvent();
  2959. }
  2960. }
  2961. }
  2962. void CheckKeyboardCameraUp()
  2963. {
  2964. switch( m_currentEvent.keyCode )
  2965. {
  2966. case KeyCode.UpArrow:
  2967. case KeyCode.DownArrow:
  2968. case KeyCode.LeftArrow:
  2969. case KeyCode.RightArrow: m_cameraSpeed = 1; break;
  2970. }
  2971. }
  2972. void OnKeyboardDown()
  2973. {
  2974. //if( DebugConsoleWindow.DeveloperMode )
  2975. //{
  2976. // if( OnKeyboardPress( KeyCode.F8 ) )
  2977. // {
  2978. // Shader currShader = CurrentGraph.CurrentShader;
  2979. // ShaderUtilEx.OpenCompiledShader( currShader, ShaderInspectorPlatformsPopupEx.GetCurrentMode(), ShaderInspectorPlatformsPopupEx.GetCurrentPlatformMask(), ShaderInspectorPlatformsPopupEx.GetCurrentVariantStripping() == 0 );
  2980. // string filename = Application.dataPath;
  2981. // filename = filename.Replace( "Assets", "Temp/Compiled-" );
  2982. // string shaderFilename = AssetDatabase.GetAssetPath( currShader );
  2983. // int lastIndex = shaderFilename.LastIndexOf( '/' ) + 1;
  2984. // filename = filename + shaderFilename.Substring( lastIndex );
  2985. // string compiledContents = IOUtils.LoadTextFileFromDisk( filename );
  2986. // Debug.Log( compiledContents );
  2987. // }
  2988. // if( OnKeyboardPress( KeyCode.F9 ) )
  2989. // {
  2990. // m_nodeExporterUtils.CalculateShaderInstructions( CurrentGraph.CurrentShader );
  2991. // }
  2992. //}
  2993. CheckKeyboardCameraDown();
  2994. if( m_lastKeyPressed == KeyCode.None )
  2995. {
  2996. m_shortcutManager.ActivateShortcut( m_currentEvent.modifiers, m_currentEvent.keyCode, true );
  2997. }
  2998. if( m_currentEvent.control && m_currentEvent.shift && m_currentEvent.keyCode == KeyCode.V )
  2999. {
  3000. PasteFromClipboard( false );
  3001. }
  3002. if( !m_altPressDown && ( OnKeyboardPress( KeyCode.LeftAlt ) || OnKeyboardPress( KeyCode.RightAlt ) || OnKeyboardPress( KeyCode.AltGr ) ) )
  3003. {
  3004. m_altPressDown = true;
  3005. m_altAvailable = true;
  3006. m_altKeyStartPos = m_currentMousePos2D;
  3007. }
  3008. if( m_currentEvent.keyCode != KeyCode.None && m_currentEvent.modifiers == EventModifiers.None )
  3009. {
  3010. m_lastKeyPressed = m_currentEvent.keyCode;
  3011. }
  3012. }
  3013. IEnumerator m_coroutine;
  3014. private void StartPasteRequest()
  3015. {
  3016. m_coroutine = SendPostCoroutine( "https://paste.amplify.pt/api/create" );
  3017. EditorApplication.update += PasteRequest;
  3018. }
  3019. IEnumerator SendPostCoroutine( string url )
  3020. {
  3021. WWWForm form = new WWWForm();
  3022. form.AddField( "text", Clipboard.ClipboardId + ";" + EditorPrefs.GetString( Clipboard.ClipboardId, string.Empty ) );
  3023. form.AddField( "title", "ASE Copy" );
  3024. form.AddField( "name", "ASE" );
  3025. form.AddField( "private", "1" );
  3026. form.AddField( "lang", "text" );
  3027. form.AddField( "expire", "0" );
  3028. UnityWebRequest www = UnityWebRequest.Post( url, form );
  3029. www.SendWebRequest();
  3030. yield return www;
  3031. }
  3032. public void PasteRequest()
  3033. {
  3034. UnityWebRequest www = (UnityWebRequest)m_coroutine.Current;
  3035. if( !m_coroutine.MoveNext() && www != null )
  3036. {
  3037. if( !www.isDone )
  3038. {
  3039. m_coroutine.MoveNext();
  3040. }
  3041. else
  3042. {
  3043. #if UNITY_2020_1_OR_NEWER
  3044. if( www.result == UnityWebRequest.Result.ConnectionError )
  3045. #else
  3046. if( www.isNetworkError )
  3047. #endif
  3048. {
  3049. Debug.Log( "[AmplifyShaderEditor]\n" + www.error );
  3050. }
  3051. else
  3052. {
  3053. // Print Body
  3054. string finalURL = www.downloadHandler.text;
  3055. if( finalURL.IndexOf( "paste.amplify.pt/view/" ) > -1 )
  3056. {
  3057. System.Text.RegularExpressions.Regex parser = new System.Text.RegularExpressions.Regex( @".*(http:\/\/paste.amplify.pt\/view\/)([0-9a-z]*).*", System.Text.RegularExpressions.RegexOptions.Singleline );
  3058. finalURL = parser.Replace( finalURL, "$1raw/$2" );
  3059. ShowMessage( "Link copied to clipboard\n"+ finalURL, consoleLog:false );
  3060. Debug.Log( "[AmplifyShaderEditor] Link copied to clipboard\n"+ finalURL+"\n" );
  3061. // Copy Paste to clipboard
  3062. EditorGUIUtility.systemCopyBuffer = finalURL;
  3063. }
  3064. else
  3065. {
  3066. Debug.Log( "[AmplifyShaderEditor] Failed to generate paste:\n" + finalURL );
  3067. }
  3068. }
  3069. EditorApplication.update -= PasteRequest;
  3070. }
  3071. }
  3072. }
  3073. void OnScrollWheel()
  3074. {
  3075. ModifyZoomSmooth( m_currentEvent.delta.y, m_currentMousePos2D );
  3076. UseCurrentEvent();
  3077. }
  3078. void ModifyZoom( float zoomIncrement, Vector2 pivot )
  3079. {
  3080. float minCam = Mathf.Min( ( m_cameraInfo.width - ( m_nodeParametersWindow.RealWidth + m_paletteWindow.RealWidth ) ), ( m_cameraInfo.height - ( m_toolsWindow.Height ) ) );
  3081. if( minCam < 1 )
  3082. minCam = 1;
  3083. float dynamicMaxZoom = m_mainGraphInstance.MaxNodeDist / minCam;
  3084. Vector2 canvasPos = TranformPosition( pivot );
  3085. if( zoomIncrement < 0 )
  3086. CameraZoom = Mathf.Max( m_cameraZoom + zoomIncrement * Constants.CAMERA_ZOOM_SPEED, Constants.CAMERA_MIN_ZOOM );
  3087. else if( CameraZoom < Mathf.Max( Constants.CAMERA_MAX_ZOOM, dynamicMaxZoom ) )
  3088. CameraZoom = m_cameraZoom + zoomIncrement * Constants.CAMERA_ZOOM_SPEED;// Mathf.Min( m_cameraZoom + zoomIncrement * Constants.CAMERA_ZOOM_SPEED, Mathf.Max( Constants.CAMERA_MAX_ZOOM, dynamicMaxZoom ) );
  3089. m_cameraOffset.x = pivot.x * m_cameraZoom - canvasPos.x;
  3090. m_cameraOffset.y = pivot.y * m_cameraZoom - canvasPos.y;
  3091. }
  3092. void ModifyZoomSmooth( float zoomIncrement, Vector2 pivot )
  3093. {
  3094. if( m_smoothZoom && Mathf.Sign( m_targetZoomIncrement * zoomIncrement ) >= 0 )
  3095. m_targetZoomIncrement += zoomIncrement;
  3096. else
  3097. m_targetZoomIncrement = zoomIncrement;
  3098. m_smoothZoom = true;
  3099. m_zoomTime = 0;
  3100. float minCam = Mathf.Min( ( m_cameraInfo.width - ( m_nodeParametersWindow.RealWidth + m_paletteWindow.RealWidth ) ), ( m_cameraInfo.height - ( m_toolsWindow.Height ) ) );
  3101. if( minCam < 1 )
  3102. minCam = 1;
  3103. float dynamicMaxZoom = m_mainGraphInstance.MaxNodeDist / minCam;
  3104. if( m_targetZoomIncrement < 0 )
  3105. m_targetZoom = Mathf.Max( m_cameraZoom + m_targetZoomIncrement * Constants.CAMERA_ZOOM_SPEED, Constants.CAMERA_MIN_ZOOM );
  3106. else if( CameraZoom < Mathf.Max( Constants.CAMERA_MAX_ZOOM, dynamicMaxZoom ) )
  3107. m_targetZoom = m_cameraZoom + m_targetZoomIncrement * Constants.CAMERA_ZOOM_SPEED;// Mathf.Min( m_cameraZoom + zoomIncrement * Constants.CAMERA_ZOOM_SPEED, Mathf.Max( Constants.CAMERA_MAX_ZOOM, dynamicMaxZoom ) );
  3108. m_zoomPivot = pivot;
  3109. }
  3110. void OnSelectionChange()
  3111. {
  3112. ForceRepaint();
  3113. }
  3114. private void OnFocus()
  3115. {
  3116. EditorGUI.FocusTextInControl( null );
  3117. // m_fixOnFocus = true;
  3118. }
  3119. void OnLostFocus()
  3120. {
  3121. m_lostFocus = true;
  3122. m_multipleSelectionActive = false;
  3123. m_wireReferenceUtils.InvalidateReferences();
  3124. if( m_genericMessageUI != null )
  3125. m_genericMessageUI.CleanUpMessageStack();
  3126. m_nodeParametersWindow.OnLostFocus();
  3127. m_paletteWindow.OnLostFocus();
  3128. m_contextMenu.ResetShortcutKeyStates();
  3129. }
  3130. void CopyToClipboard()
  3131. {
  3132. m_copyPasteDeltaMul = 0;
  3133. m_copyPasteDeltaPos = new Vector2( float.MaxValue, float.MaxValue );
  3134. m_clipboard.ClearClipboard();
  3135. m_copyPasteInitialPos = m_mainGraphInstance.SelectedNodesCentroid;
  3136. m_clipboard.AddToClipboard( m_mainGraphInstance.SelectedNodes, m_copyPasteInitialPos, m_mainGraphInstance );
  3137. }
  3138. ParentNode CreateNodeFromClipboardData( int clipId )
  3139. {
  3140. string[] parameters = m_clipboard.CurrentClipboardStrData[ clipId ].Data.Split( IOUtils.FIELD_SEPARATOR );
  3141. System.Type nodeType = System.Type.GetType( parameters[ IOUtils.NodeTypeId ] );
  3142. NodeAttributes attributes = m_contextMenu.GetNodeAttributesForType( nodeType );
  3143. if( attributes != null && !UIUtils.GetNodeAvailabilityInBitArray( attributes.NodeAvailabilityFlags, m_mainGraphInstance.CurrentCanvasMode ) && !UIUtils.GetNodeAvailabilityInBitArray( attributes.NodeAvailabilityFlags, m_currentNodeAvailability ) )
  3144. return null;
  3145. ParentNode newNode = (ParentNode)ScriptableObject.CreateInstance( nodeType );
  3146. newNode.IsNodeBeingCopied = true;
  3147. if( newNode != null )
  3148. {
  3149. newNode.ContainerGraph = m_mainGraphInstance;
  3150. newNode.ClipboardFullReadFromString( ref parameters );
  3151. m_mainGraphInstance.AddNode( newNode, true, true, true, false );
  3152. newNode.IsNodeBeingCopied = false;
  3153. m_clipboard.CurrentClipboardStrData[ clipId ].NewNodeId = newNode.UniqueId;
  3154. return newNode;
  3155. }
  3156. return null;
  3157. }
  3158. void CreateConnectionsFromClipboardData( int clipId )
  3159. {
  3160. if( String.IsNullOrEmpty( m_clipboard.CurrentClipboardStrData[ clipId ].Connections ) )
  3161. return;
  3162. string[] lines = m_clipboard.CurrentClipboardStrData[ clipId ].Connections.Split( IOUtils.LINE_TERMINATOR );
  3163. for( int lineIdx = 0; lineIdx < lines.Length; lineIdx++ )
  3164. {
  3165. string[] parameters = lines[ lineIdx ].Split( IOUtils.FIELD_SEPARATOR );
  3166. int InNodeId = 0;
  3167. int InPortId = 0;
  3168. int OutNodeId = 0;
  3169. int OutPortId = 0;
  3170. try
  3171. {
  3172. InNodeId = Convert.ToInt32( parameters[ IOUtils.InNodeId ] );
  3173. InPortId = Convert.ToInt32( parameters[ IOUtils.InPortId ] );
  3174. OutNodeId = Convert.ToInt32( parameters[ IOUtils.OutNodeId ] );
  3175. OutPortId = Convert.ToInt32( parameters[ IOUtils.OutPortId ] );
  3176. }
  3177. catch( Exception e )
  3178. {
  3179. Debug.LogException( e );
  3180. }
  3181. int newInNodeId = m_clipboard.GeNewNodeId( InNodeId );
  3182. int newOutNodeId = m_clipboard.GeNewNodeId( OutNodeId );
  3183. if( newInNodeId > -1 && newOutNodeId > -1 )
  3184. {
  3185. ParentNode inNode = m_mainGraphInstance.GetNode( newInNodeId );
  3186. ParentNode outNode = m_mainGraphInstance.GetNode( newOutNodeId );
  3187. InputPort inputPort = null;
  3188. OutputPort outputPort = null;
  3189. if( inNode != null && outNode != null )
  3190. {
  3191. inNode.IsNodeBeingCopied = true;
  3192. outNode.IsNodeBeingCopied = true;
  3193. inputPort = inNode.GetInputPortByUniqueId( InPortId );
  3194. outputPort = outNode.GetOutputPortByUniqueId( OutPortId );
  3195. if( inputPort != null && outputPort != null )
  3196. {
  3197. inputPort.ConnectTo( newOutNodeId, OutPortId, outputPort.DataType, false );
  3198. outputPort.ConnectTo( newInNodeId, InPortId, inputPort.DataType, inputPort.TypeLocked );
  3199. inNode.OnInputPortConnected( InPortId, newOutNodeId, OutPortId );
  3200. outNode.OnOutputPortConnected( OutPortId, newInNodeId, InPortId );
  3201. }
  3202. inNode.IsNodeBeingCopied = false;
  3203. outNode.IsNodeBeingCopied = false;
  3204. }
  3205. }
  3206. }
  3207. }
  3208. private void StartGetRequest( string url )
  3209. {
  3210. m_coroutine = SendGetCoroutine( url );
  3211. EditorApplication.update += GetRequest;
  3212. }
  3213. IEnumerator SendGetCoroutine( string url )
  3214. {
  3215. UnityWebRequest www = UnityWebRequest.Get( url );
  3216. www.SendWebRequest();
  3217. yield return www;
  3218. }
  3219. public void GetRequest()
  3220. {
  3221. UnityWebRequest www = (UnityWebRequest)m_coroutine.Current;
  3222. if( !m_coroutine.MoveNext() )
  3223. {
  3224. if( !www.isDone )
  3225. {
  3226. m_coroutine.MoveNext();
  3227. }
  3228. else
  3229. {
  3230. #if UNITY_2020_1_OR_NEWER
  3231. if( www.result == UnityWebRequest.Result.ConnectionError )
  3232. #else
  3233. if( www.isNetworkError )
  3234. #endif
  3235. {
  3236. Debug.Log( "[AmplifyShaderEditor]\n" + www.error );
  3237. }
  3238. else
  3239. {
  3240. string data = www.downloadHandler.text;
  3241. if( data.IndexOf( Clipboard.ClipboardId + ";" ) > -1 )
  3242. {
  3243. data = www.downloadHandler.text.Replace( Clipboard.ClipboardId + ";", "" );
  3244. if( data.IndexOf( "<div " ) > -1 )
  3245. {
  3246. System.Text.RegularExpressions.Regex parser = new System.Text.RegularExpressions.Regex( @"(.*)<div .*", System.Text.RegularExpressions.RegexOptions.Singleline );
  3247. data = parser.Replace( data, "$1" );
  3248. }
  3249. EditorGUIUtility.systemCopyBuffer = string.Empty;
  3250. Debug.Log( "[AmplifyShaderEditor] Successfully downloaded snippet!" );
  3251. EditorPrefs.SetString( Clipboard.ClipboardId, data );
  3252. try
  3253. {
  3254. // send paste event instead to make sure it runs properly
  3255. Event e = new Event();
  3256. e.type = EventType.ExecuteCommand;
  3257. e.commandName = PasteCommand;
  3258. this.SendEvent( e );
  3259. }
  3260. catch( Exception )
  3261. {
  3262. EditorGUIUtility.systemCopyBuffer = string.Empty;
  3263. EditorApplication.update -= GetRequest;
  3264. throw;
  3265. }
  3266. }
  3267. else
  3268. {
  3269. Debug.Log( "[AmplifyShaderEditor] Error downloading, snippet might not exist anymore, clearing clipboard..." );
  3270. EditorGUIUtility.systemCopyBuffer = string.Empty;
  3271. }
  3272. }
  3273. EditorApplication.update -= GetRequest;
  3274. }
  3275. }
  3276. }
  3277. void PasteFromClipboard( bool copyConnections )
  3278. {
  3279. string result = EditorGUIUtility.systemCopyBuffer.Replace( "http://", "https://" );
  3280. if( result.IndexOf( "https://paste.amplify.pt/view/raw/" ) > -1 )
  3281. {
  3282. StartGetRequest( result );
  3283. return;
  3284. }
  3285. if( result.IndexOf( Clipboard.ClipboardId + ";" ) > -1 )
  3286. {
  3287. result = result.Replace( Clipboard.ClipboardId + ";", "" );
  3288. EditorPrefs.SetString( Clipboard.ClipboardId, result );
  3289. }
  3290. m_mainGraphInstance.IsDuplicating = true;
  3291. m_copyPasteInitialPos = m_clipboard.GetDataFromEditorPrefs();
  3292. if( m_clipboard.CurrentClipboardStrData.Count == 0 )
  3293. {
  3294. return;
  3295. }
  3296. Vector2 deltaPos = TranformedKeyEvtMousePos - m_copyPasteInitialPos;
  3297. if( ( m_copyPasteDeltaPos - deltaPos ).magnitude > 5.0f )
  3298. {
  3299. m_copyPasteDeltaMul = 0;
  3300. }
  3301. else
  3302. {
  3303. m_copyPasteDeltaMul += 1;
  3304. }
  3305. m_copyPasteDeltaPos = deltaPos;
  3306. m_mainGraphInstance.DeSelectAll();
  3307. UIUtils.InhibitMessages = true;
  3308. if( m_clipboard.CurrentClipboardStrData.Count > 0 )
  3309. {
  3310. UIUtils.MarkUndoAction();
  3311. UndoUtils.RegisterCompleteObjectUndo( this, Constants.UndoPasteNodeId );
  3312. }
  3313. List<ParentNode> createdNodes = new List<ParentNode>();
  3314. for( int i = 0; i < m_clipboard.CurrentClipboardStrData.Count; i++ )
  3315. {
  3316. ParentNode node = CreateNodeFromClipboardData( i );
  3317. if( node != null )
  3318. {
  3319. m_clipboard.CurrentClipboardStrData[ i ].NewNodeId = node.UniqueId;
  3320. Vector2 pos = node.Vec2Position;
  3321. node.Vec2Position = pos + deltaPos + m_copyPasteDeltaMul * Constants.CopyPasteDeltaPos;
  3322. //node.RefreshExternalReferences();
  3323. node.AfterDuplication();
  3324. createdNodes.Add( node );
  3325. m_mainGraphInstance.SelectNode( node, true, false );
  3326. }
  3327. }
  3328. if( copyConnections )
  3329. {
  3330. for( int i = 0; i < m_clipboard.CurrentClipboardStrData.Count; i++ )
  3331. {
  3332. CreateConnectionsFromClipboardData( i );
  3333. }
  3334. }
  3335. // Refresh external references must always be called after all nodes are created
  3336. for( int i = 0; i < createdNodes.Count; i++ )
  3337. {
  3338. createdNodes[ i ].RefreshExternalReferences();
  3339. }
  3340. createdNodes.Clear();
  3341. createdNodes = null;
  3342. //Need to force increment on Undo because if not Undo may incorrectly group consecutive pastes
  3343. UndoUtils.IncrementCurrentGroup();
  3344. UIUtils.InhibitMessages = false;
  3345. ShaderIsModified = true;
  3346. SetSaveIsDirty();
  3347. ForceRepaint();
  3348. m_mainGraphInstance.IsDuplicating = false;
  3349. }
  3350. public string GenerateGraphInfo()
  3351. {
  3352. EditorPrefs.SetString( GUID,
  3353. m_cameraInfo.x.ToString() + IOUtils.FIELD_SEPARATOR +
  3354. m_cameraInfo.y.ToString() + IOUtils.FIELD_SEPARATOR +
  3355. m_cameraInfo.width.ToString() + IOUtils.FIELD_SEPARATOR +
  3356. m_cameraInfo.height.ToString() + IOUtils.FIELD_SEPARATOR +
  3357. m_cameraOffset.x.ToString() + IOUtils.FIELD_SEPARATOR +
  3358. m_cameraOffset.y.ToString() + IOUtils.FIELD_SEPARATOR +
  3359. m_cameraZoom.ToString() + IOUtils.FIELD_SEPARATOR +
  3360. m_nodeParametersWindow.IsMaximized + IOUtils.FIELD_SEPARATOR +
  3361. m_paletteWindow.IsMaximized + '\n' );
  3362. string graphInfo = IOUtils.ShaderBodyBegin + '\n';
  3363. string nodesInfo = "";
  3364. string connectionsInfo = "";
  3365. graphInfo += VersionInfo.FullLabel + '\n';
  3366. m_mainGraphInstance.OrderNodesByGraphDepth();
  3367. m_mainGraphInstance.WriteToString( ref nodesInfo, ref connectionsInfo );
  3368. graphInfo += nodesInfo;
  3369. graphInfo += connectionsInfo;
  3370. graphInfo += IOUtils.ShaderBodyEnd + '\n';
  3371. return graphInfo;
  3372. }
  3373. // TODO: this need to be fused to the main load function somehow
  3374. public static void LoadFromMeta( ref ParentGraph graph, GraphContextMenu contextMenu, string meta )
  3375. {
  3376. graph.IsLoading = true;
  3377. graph.CleanNodes();
  3378. string[] cameraParams = new string[ 0 ];
  3379. int checksumId = meta.IndexOf( IOUtils.CHECKSUM );
  3380. if( checksumId > -1 )
  3381. {
  3382. string checkSumStoredValue = meta.Substring( checksumId );
  3383. string trimmedBuffer = meta.Remove( checksumId );
  3384. string[] typeValuePair = checkSumStoredValue.Split( IOUtils.VALUE_SEPARATOR );
  3385. if( typeValuePair != null && typeValuePair.Length == 2 )
  3386. {
  3387. // Check read checksum and compare with the actual shader body to detect external changes
  3388. string currentChecksumValue = IOUtils.CreateChecksum( trimmedBuffer );
  3389. if( DebugConsoleWindow.DeveloperMode && !currentChecksumValue.Equals( typeValuePair[ 1 ] ) )
  3390. {
  3391. //ShowMessage( "Wrong checksum" );
  3392. }
  3393. trimmedBuffer = trimmedBuffer.Replace( "\r", string.Empty );
  3394. // find node info body
  3395. int shaderBodyId = trimmedBuffer.IndexOf( IOUtils.ShaderBodyBegin );
  3396. if( shaderBodyId > -1 )
  3397. {
  3398. trimmedBuffer = trimmedBuffer.Substring( shaderBodyId );
  3399. //Find set of instructions
  3400. string[] instructions = trimmedBuffer.Split( IOUtils.LINE_TERMINATOR );
  3401. // First line is to be ignored and second line contains version
  3402. string[] versionParams = instructions[ 1 ].Split( IOUtils.VALUE_SEPARATOR );
  3403. if( versionParams.Length == 2 )
  3404. {
  3405. int version = 0;
  3406. try
  3407. {
  3408. version = Convert.ToInt32( versionParams[ 1 ] );
  3409. }
  3410. catch( Exception e )
  3411. {
  3412. Debug.LogException( e );
  3413. }
  3414. //if( version > versionInfo.FullNumber )
  3415. //{
  3416. //ShowMessage( "This shader was created on a new ASE version\nPlease install v." + version );
  3417. //}
  3418. if( DebugConsoleWindow.DeveloperMode )
  3419. {
  3420. //if( version < versionInfo.FullNumber )
  3421. //{
  3422. //ShowMessage( "This shader was created on a older ASE version\nSaving will update it to the new one." );
  3423. //}
  3424. }
  3425. graph.LoadedShaderVersion = version;
  3426. }
  3427. else
  3428. {
  3429. //ShowMessage( "Corrupted version" );
  3430. }
  3431. // valid instructions are only between the line after version and the line before the last one ( which contains ShaderBodyEnd )
  3432. for ( int instructionIdx = 0; instructionIdx < instructions.Length - 1; instructionIdx++ )
  3433. {
  3434. //TODO: After all is working, convert string parameters to ints in order to speed up reading
  3435. string[] parameters = instructions[ instructionIdx ].Split( IOUtils.FIELD_SEPARATOR );
  3436. // All nodes must be created before wiring the connections ...
  3437. // Since all nodes on the save op are written before the wires, we can safely create them
  3438. // If that order is not maintained the it's because of external editing and its the users responsability
  3439. switch( parameters[ 0 ] )
  3440. {
  3441. case IOUtils.NodeParam:
  3442. {
  3443. string typeStr = parameters[ IOUtils.NodeTypeId ];
  3444. typeStr = IOUtils.NodeTypeReplacer.ContainsKey( typeStr ) ? IOUtils.NodeTypeReplacer[ typeStr ] : typeStr;
  3445. System.Type type = System.Type.GetType( typeStr );
  3446. if( type == null )
  3447. {
  3448. try
  3449. {
  3450. var editorAssembly = System.Reflection.Assembly.Load( "Assembly-CSharp-Editor" );
  3451. if( editorAssembly != null )
  3452. {
  3453. type = editorAssembly.GetType( typeStr );
  3454. }
  3455. }
  3456. catch( Exception )
  3457. {
  3458. }
  3459. if( type == null )
  3460. {
  3461. type = IOUtils.GetAssemblyType( typeStr );
  3462. }
  3463. }
  3464. if( type != null )
  3465. {
  3466. System.Type oldType = type;
  3467. NodeAttributes attribs = contextMenu.GetNodeAttributesForType( type );
  3468. if( attribs == null )
  3469. {
  3470. attribs = contextMenu.GetDeprecatedNodeAttributesForType( type );
  3471. if( attribs != null )
  3472. {
  3473. if( attribs.Deprecated && attribs.DeprecatedAlternativeType != null )
  3474. {
  3475. type = attribs.DeprecatedAlternativeType;
  3476. //ShowMessage( string.Format( "Node {0} is deprecated and was replaced by {1} ", attribs.Name, attribs.DeprecatedAlternative ) );
  3477. }
  3478. }
  3479. }
  3480. ParentNode newNode = (ParentNode)ScriptableObject.CreateInstance( type );
  3481. if( newNode != null )
  3482. {
  3483. try
  3484. {
  3485. newNode.ContainerGraph = graph;
  3486. if( oldType != type )
  3487. {
  3488. newNode.ParentReadFromString( ref parameters );
  3489. newNode.ReadFromDeprecated( ref parameters, oldType );
  3490. newNode.WasDeprecated = true;
  3491. }
  3492. else
  3493. newNode.ReadFromString( ref parameters );
  3494. if( oldType == type )
  3495. {
  3496. newNode.ReadInputDataFromString( ref parameters );
  3497. if( UIUtils.CurrentShaderVersion() > 5107 )
  3498. {
  3499. newNode.ReadOutputDataFromString( ref parameters );
  3500. }
  3501. }
  3502. }
  3503. catch( Exception e )
  3504. {
  3505. Debug.LogException( e, newNode );
  3506. }
  3507. graph.AddNode( newNode, false, true, false );
  3508. }
  3509. }
  3510. else
  3511. {
  3512. UIUtils.ShowMessage( string.Format( "{0} is not a valid ASE node ", parameters[ IOUtils.NodeTypeId ] ), MessageSeverity.Error );
  3513. }
  3514. }
  3515. break;
  3516. case IOUtils.WireConnectionParam:
  3517. {
  3518. int InNodeId = 0;
  3519. int InPortId = 0;
  3520. int OutNodeId = 0;
  3521. int OutPortId = 0;
  3522. try
  3523. {
  3524. InNodeId = Convert.ToInt32( parameters[ IOUtils.InNodeId ] );
  3525. InPortId = Convert.ToInt32( parameters[ IOUtils.InPortId ] );
  3526. OutNodeId = Convert.ToInt32( parameters[ IOUtils.OutNodeId ] );
  3527. OutPortId = Convert.ToInt32( parameters[ IOUtils.OutPortId ] );
  3528. }
  3529. catch( Exception e )
  3530. {
  3531. Debug.LogException( e );
  3532. }
  3533. ParentNode inNode = graph.GetNode( InNodeId );
  3534. ParentNode outNode = graph.GetNode( OutNodeId );
  3535. //if ( UIUtils.CurrentShaderVersion() < 5002 )
  3536. //{
  3537. // InPortId = inNode.VersionConvertInputPortId( InPortId );
  3538. // OutPortId = outNode.VersionConvertOutputPortId( OutPortId );
  3539. //}
  3540. InputPort inputPort = null;
  3541. OutputPort outputPort = null;
  3542. if( inNode != null && outNode != null )
  3543. {
  3544. if( UIUtils.CurrentShaderVersion() < 5002 )
  3545. {
  3546. InPortId = inNode.VersionConvertInputPortId( InPortId );
  3547. OutPortId = outNode.VersionConvertOutputPortId( OutPortId );
  3548. if( inNode.WasDeprecated )
  3549. InPortId = inNode.InputIdFromDeprecated( InPortId );
  3550. if( outNode.WasDeprecated )
  3551. OutPortId = outNode.OutputIdFromDeprecated( OutPortId );
  3552. inputPort = inNode.GetInputPortByArrayId( InPortId );
  3553. outputPort = outNode.GetOutputPortByArrayId( OutPortId );
  3554. }
  3555. else
  3556. {
  3557. if( inNode.WasDeprecated )
  3558. InPortId = inNode.InputIdFromDeprecated( InPortId );
  3559. if( outNode.WasDeprecated )
  3560. OutPortId = outNode.OutputIdFromDeprecated( OutPortId );
  3561. inputPort = inNode.GetInputPortByUniqueId( InPortId );
  3562. outputPort = outNode.GetOutputPortByUniqueId( OutPortId );
  3563. }
  3564. if( inputPort != null && outputPort != null )
  3565. {
  3566. bool inputCompatible = inputPort.CheckValidType( outputPort.DataType );
  3567. bool outputCompatible = outputPort.CheckValidType( inputPort.DataType );
  3568. if( inputCompatible && outputCompatible )
  3569. {
  3570. inputPort.ConnectTo( OutNodeId, OutPortId, outputPort.DataType, false );
  3571. outputPort.ConnectTo( InNodeId, InPortId, inputPort.DataType, inputPort.TypeLocked );
  3572. inNode.OnInputPortConnected( InPortId, OutNodeId, OutPortId, false );
  3573. outNode.OnOutputPortConnected( OutPortId, InNodeId, InPortId );
  3574. }
  3575. else if( DebugConsoleWindow.DeveloperMode )
  3576. {
  3577. if( !inputCompatible )
  3578. UIUtils.ShowIncompatiblePortMessage( true, inNode, inputPort, outNode, outputPort );
  3579. if( !outputCompatible )
  3580. UIUtils.ShowIncompatiblePortMessage( true, outNode, outputPort, inNode, inputPort );
  3581. }
  3582. }
  3583. else if( DebugConsoleWindow.DeveloperMode )
  3584. {
  3585. if( inputPort == null )
  3586. {
  3587. UIUtils.ShowMessage( "Input Port " + InPortId + " doesn't exist on node " + InNodeId, MessageSeverity.Error );
  3588. }
  3589. else
  3590. {
  3591. UIUtils.ShowMessage( "Output Port " + OutPortId + " doesn't exist on node " + OutNodeId, MessageSeverity.Error );
  3592. }
  3593. }
  3594. }
  3595. else if( DebugConsoleWindow.DeveloperMode )
  3596. {
  3597. if( inNode == null )
  3598. {
  3599. UIUtils.ShowMessage( "Input node " + InNodeId + " doesn't exist", MessageSeverity.Error );
  3600. }
  3601. else
  3602. {
  3603. UIUtils.ShowMessage( "Output node " + OutNodeId + " doesn't exist", MessageSeverity.Error );
  3604. }
  3605. }
  3606. }
  3607. break;
  3608. }
  3609. }
  3610. }
  3611. }
  3612. }
  3613. graph.CheckForDuplicates();
  3614. graph.UpdateRegisters();
  3615. graph.RefreshExternalReferences();
  3616. graph.ForceSignalPropagationOnMasterNode();
  3617. graph.LoadedShaderVersion = VersionInfo.FullNumber;
  3618. //Reset();
  3619. graph.IsLoading = false;
  3620. }
  3621. public ShaderLoadResult LoadFromDisk( string pathname, AmplifyShaderFunction shaderFunction = null )
  3622. {
  3623. m_mainGraphInstance.IsLoading = true;
  3624. System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
  3625. FullCleanUndoStack();
  3626. m_performFullUndoRegister = true;
  3627. InlinePropertyTable.Initialize();
  3628. UIUtils.DirtyMask = false;
  3629. if( UIUtils.IsUnityNativeShader( pathname ) )
  3630. {
  3631. ShowMessage( "Cannot edit native unity shaders.\nReplacing by a new one." );
  3632. return ShaderLoadResult.UNITY_NATIVE_PATHS;
  3633. }
  3634. m_lastOpenedLocation = pathname;
  3635. Lastpath = pathname;
  3636. string buffer = string.Empty;
  3637. if( shaderFunction == null )
  3638. buffer = IOUtils.LoadTextFileFromDisk( pathname );
  3639. else
  3640. buffer = shaderFunction.FunctionInfo;
  3641. if( String.IsNullOrEmpty( buffer ) )
  3642. {
  3643. ShowMessage( "Could not open file " + pathname );
  3644. return ShaderLoadResult.FILE_NOT_FOUND;
  3645. }
  3646. if( !IOUtils.HasValidShaderBody( ref buffer ) )
  3647. {
  3648. return ShaderLoadResult.ASE_INFO_NOT_FOUND;
  3649. }
  3650. m_mainGraphInstance.CleanNodes();
  3651. Reset();
  3652. string[] cameraParams = new string[ 0 ];
  3653. Shader shader = null;
  3654. ShaderLoadResult loadResult = ShaderLoadResult.LOADED;
  3655. // Find checksum value on body
  3656. int checksumId = buffer.IndexOf( IOUtils.CHECKSUM );
  3657. if( checksumId > -1 )
  3658. {
  3659. string checkSumStoredValue = buffer.Substring( checksumId );
  3660. string trimmedBuffer = buffer.Remove( checksumId );
  3661. string[] typeValuePair = checkSumStoredValue.Split( IOUtils.VALUE_SEPARATOR );
  3662. if( typeValuePair != null && typeValuePair.Length == 2 )
  3663. {
  3664. // Check read checksum and compare with the actual shader body to detect external changes
  3665. string currentChecksumValue = IOUtils.CreateChecksum( trimmedBuffer );
  3666. if( DebugConsoleWindow.DeveloperMode && !currentChecksumValue.Equals( typeValuePair[ 1 ] ) )
  3667. {
  3668. ShowMessage( "Wrong checksum" );
  3669. }
  3670. trimmedBuffer = trimmedBuffer.Replace( "\r", string.Empty );
  3671. // find node info body
  3672. int shaderBodyId = trimmedBuffer.IndexOf( IOUtils.ShaderBodyBegin );
  3673. if( shaderBodyId > -1 )
  3674. {
  3675. trimmedBuffer = trimmedBuffer.Substring( shaderBodyId );
  3676. //Find set of instructions
  3677. string[] instructions = trimmedBuffer.Split( IOUtils.LINE_TERMINATOR );
  3678. // First line is to be ignored and second line contains version
  3679. string[] versionParams = instructions[ 1 ].Split( IOUtils.VALUE_SEPARATOR );
  3680. if( versionParams.Length == 2 )
  3681. {
  3682. int version = 0;
  3683. try
  3684. {
  3685. version = Convert.ToInt32( versionParams[ 1 ] );
  3686. }
  3687. catch( Exception e )
  3688. {
  3689. Debug.LogException( e );
  3690. }
  3691. if( version > VersionInfo.FullNumber )
  3692. {
  3693. ShowMessage( "This shader was created on a new ASE version\nPlease install v." + version );
  3694. }
  3695. if( DebugConsoleWindow.DeveloperMode )
  3696. {
  3697. if( version < VersionInfo.FullNumber )
  3698. {
  3699. ShowMessage( "This shader was created on a older ASE version\nSaving will update it to the new one." );
  3700. }
  3701. }
  3702. m_mainGraphInstance.LoadedShaderVersion = version;
  3703. }
  3704. else
  3705. {
  3706. ShowMessage( "Corrupted version" );
  3707. }
  3708. // @diogo: second line MAY contain camera information ( position, size, offset and zoom )
  3709. string[] split = instructions[ 2 ].Split( IOUtils.FIELD_SEPARATOR );
  3710. if ( split.Length == 9 && float.TryParse( split[ 0 ], NumberStyles.Any, CultureInfo.InvariantCulture, out float value ) )
  3711. {
  3712. // @diogo: valid camera parameter serialization
  3713. cameraParams = split;
  3714. }
  3715. // valid instructions are only between the line after version and the line before the last one ( which contains ShaderBodyEnd )
  3716. for ( int instructionIdx = 0; instructionIdx < instructions.Length - 1; instructionIdx++ )
  3717. {
  3718. //TODO: After all is working, convert string parameters to ints in order to speed up reading
  3719. string[] parameters = instructions[ instructionIdx ].Split( IOUtils.FIELD_SEPARATOR );
  3720. // All nodes must be created before wiring the connections ...
  3721. // Since all nodes on the save op are written before the wires, we can safely create them
  3722. // If that order is not maintained the it's because of external editing and its the users responsability
  3723. switch( parameters[ 0 ] )
  3724. {
  3725. case IOUtils.NodeParam:
  3726. {
  3727. string typeStr = parameters[ IOUtils.NodeTypeId ];
  3728. typeStr = IOUtils.NodeTypeReplacer.ContainsKey( typeStr ) ? IOUtils.NodeTypeReplacer[ typeStr ] : typeStr;
  3729. System.Type type = System.Type.GetType( typeStr );
  3730. if( type == null )
  3731. {
  3732. try
  3733. {
  3734. var editorAssembly = System.Reflection.Assembly.Load( "Assembly-CSharp-Editor" );
  3735. if( editorAssembly != null )
  3736. {
  3737. type = editorAssembly.GetType( typeStr );
  3738. }
  3739. }
  3740. catch( Exception )
  3741. {
  3742. }
  3743. if( type == null )
  3744. {
  3745. type = IOUtils.GetAssemblyType( typeStr );
  3746. }
  3747. }
  3748. if( type != null )
  3749. {
  3750. System.Type oldType = type;
  3751. NodeAttributes attribs = m_contextMenu.GetNodeAttributesForType( type );
  3752. if( attribs == null )
  3753. {
  3754. attribs = m_contextMenu.GetDeprecatedNodeAttributesForType( type );
  3755. if( attribs != null )
  3756. {
  3757. if( attribs.Deprecated )
  3758. {
  3759. if( attribs.DeprecatedAlternativeType != null )
  3760. {
  3761. type = attribs.DeprecatedAlternativeType;
  3762. ShowMessage( string.Format( "Node {0} is deprecated and was replaced by {1} ", attribs.Name, attribs.DeprecatedAlternative ) );
  3763. }
  3764. else
  3765. {
  3766. if( string.IsNullOrEmpty( attribs.DeprecatedAlternative ) )
  3767. ShowMessage( string.Format( Constants.DeprecatedNoAlternativeMessageStr, attribs.Name, attribs.DeprecatedAlternative ), MessageSeverity.Normal, false );
  3768. else
  3769. ShowMessage( string.Format( Constants.DeprecatedMessageStr, attribs.Name, attribs.DeprecatedAlternative ), MessageSeverity.Normal, false );
  3770. }
  3771. }
  3772. }
  3773. }
  3774. ParentNode newNode = (ParentNode)ScriptableObject.CreateInstance( type );
  3775. if( newNode != null )
  3776. {
  3777. try
  3778. {
  3779. newNode.ContainerGraph = m_mainGraphInstance;
  3780. if( oldType != type )
  3781. {
  3782. newNode.ParentReadFromString( ref parameters );
  3783. newNode.ReadFromDeprecated( ref parameters, oldType );
  3784. newNode.WasDeprecated = true;
  3785. }
  3786. else
  3787. newNode.ReadFromString( ref parameters );
  3788. if( oldType == type )
  3789. {
  3790. newNode.ReadInputDataFromString( ref parameters );
  3791. if( UIUtils.CurrentShaderVersion() > 5107 )
  3792. {
  3793. newNode.ReadOutputDataFromString( ref parameters );
  3794. }
  3795. }
  3796. }
  3797. catch( Exception e )
  3798. {
  3799. Debug.LogException( e, newNode );
  3800. }
  3801. m_mainGraphInstance.AddNode( newNode, false, true, false );
  3802. }
  3803. }
  3804. else
  3805. {
  3806. ShowMessage( string.Format( "{0} is not a valid ASE node ", parameters[ IOUtils.NodeTypeId ] ), MessageSeverity.Error );
  3807. }
  3808. }
  3809. break;
  3810. case IOUtils.WireConnectionParam:
  3811. {
  3812. int InNodeId = 0;
  3813. int InPortId = 0;
  3814. int OutNodeId = 0;
  3815. int OutPortId = 0;
  3816. try
  3817. {
  3818. InNodeId = Convert.ToInt32( parameters[ IOUtils.InNodeId ] );
  3819. InPortId = Convert.ToInt32( parameters[ IOUtils.InPortId ] );
  3820. OutNodeId = Convert.ToInt32( parameters[ IOUtils.OutNodeId ] );
  3821. OutPortId = Convert.ToInt32( parameters[ IOUtils.OutPortId ] );
  3822. }
  3823. catch( Exception e )
  3824. {
  3825. Debug.LogException( e );
  3826. }
  3827. ParentNode inNode = m_mainGraphInstance.GetNode( InNodeId );
  3828. ParentNode outNode = m_mainGraphInstance.GetNode( OutNodeId );
  3829. //if ( UIUtils.CurrentShaderVersion() < 5002 )
  3830. //{
  3831. // InPortId = inNode.VersionConvertInputPortId( InPortId );
  3832. // OutPortId = outNode.VersionConvertOutputPortId( OutPortId );
  3833. //}
  3834. InputPort inputPort = null;
  3835. OutputPort outputPort = null;
  3836. if( inNode != null && outNode != null )
  3837. {
  3838. if( UIUtils.CurrentShaderVersion() < 5002 )
  3839. {
  3840. InPortId = inNode.VersionConvertInputPortId( InPortId );
  3841. OutPortId = outNode.VersionConvertOutputPortId( OutPortId );
  3842. if( inNode.WasDeprecated )
  3843. InPortId = inNode.InputIdFromDeprecated( InPortId );
  3844. if( outNode.WasDeprecated )
  3845. OutPortId = outNode.OutputIdFromDeprecated( OutPortId );
  3846. inputPort = inNode.GetInputPortByArrayId( InPortId );
  3847. outputPort = outNode.GetOutputPortByArrayId( OutPortId );
  3848. }
  3849. else
  3850. {
  3851. if( inNode.WasDeprecated )
  3852. InPortId = inNode.InputIdFromDeprecated( InPortId );
  3853. if( outNode.WasDeprecated )
  3854. OutPortId = outNode.OutputIdFromDeprecated( OutPortId );
  3855. inputPort = inNode.GetInputPortByUniqueId( InPortId );
  3856. outputPort = outNode.GetOutputPortByUniqueId( OutPortId );
  3857. }
  3858. if( inputPort != null && outputPort != null )
  3859. {
  3860. bool inputCompatible = inputPort.CheckValidType( outputPort.DataType );
  3861. bool outputCompatible = outputPort.CheckValidType( inputPort.DataType );
  3862. if( inputCompatible && outputCompatible )
  3863. {
  3864. inputPort.ConnectTo( OutNodeId, OutPortId, outputPort.DataType, false );
  3865. outputPort.ConnectTo( InNodeId, InPortId, inputPort.DataType, inputPort.TypeLocked );
  3866. inNode.OnInputPortConnected( InPortId, OutNodeId, OutPortId, false );
  3867. outNode.OnOutputPortConnected( OutPortId, InNodeId, InPortId );
  3868. }
  3869. else if( DebugConsoleWindow.DeveloperMode )
  3870. {
  3871. if( !inputCompatible )
  3872. UIUtils.ShowIncompatiblePortMessage( true, inNode, inputPort, outNode, outputPort );
  3873. if( !outputCompatible )
  3874. UIUtils.ShowIncompatiblePortMessage( true, outNode, outputPort, inNode, inputPort );
  3875. }
  3876. }
  3877. else if( DebugConsoleWindow.DeveloperMode )
  3878. {
  3879. if( inputPort == null )
  3880. {
  3881. UIUtils.ShowMessage( "Input Port " + InPortId + " doesn't exist on node " + InNodeId, MessageSeverity.Error );
  3882. }
  3883. else
  3884. {
  3885. UIUtils.ShowMessage( "Output Port " + OutPortId + " doesn't exist on node " + OutNodeId, MessageSeverity.Error );
  3886. }
  3887. }
  3888. }
  3889. else if( DebugConsoleWindow.DeveloperMode )
  3890. {
  3891. if( inNode == null )
  3892. {
  3893. UIUtils.ShowMessage( "Input node " + InNodeId + " doesn't exist", MessageSeverity.Error );
  3894. }
  3895. else
  3896. {
  3897. UIUtils.ShowMessage( "Output node " + OutNodeId + " doesn't exist", MessageSeverity.Error );
  3898. }
  3899. }
  3900. }
  3901. break;
  3902. }
  3903. }
  3904. if ( shaderFunction != null )
  3905. {
  3906. m_onLoadDone = 2;
  3907. }
  3908. else
  3909. {
  3910. shader = AssetDatabase.LoadAssetAtPath<Shader>( pathname );
  3911. if ( shader )
  3912. {
  3913. m_onLoadDone = 2;
  3914. }
  3915. else
  3916. {
  3917. ShowMessage( "Could not load shader asset" );
  3918. }
  3919. }
  3920. }
  3921. else
  3922. {
  3923. ShowMessage( "Graph info not found" );
  3924. }
  3925. }
  3926. else
  3927. {
  3928. ShowMessage( "Corrupted checksum" );
  3929. }
  3930. }
  3931. else
  3932. {
  3933. ShowMessage( "Checksum not found" );
  3934. }
  3935. //m_mainGraphInstance.LoadedShaderVersion = m_versionInfo.FullNumber;
  3936. if( UIUtils.CurrentMasterNode() )
  3937. UIUtils.CurrentMasterNode().ForcePortType();
  3938. UIUtils.DirtyMask = true;
  3939. m_checkInvalidConnections = true;
  3940. m_mainGraphInstance.CheckForDuplicates();
  3941. m_mainGraphInstance.UpdateRegisters();
  3942. m_mainGraphInstance.RefreshExternalReferences();
  3943. m_mainGraphInstance.ForceSignalPropagationOnMasterNode();
  3944. InlinePropertyTable.ResolveDependencies();
  3945. if( shaderFunction != null )
  3946. {
  3947. //if( CurrentGraph.CurrentFunctionOutput == null )
  3948. //{
  3949. // //Fix in case a function output node is not marked as main node
  3950. // CurrentGraph.AssignMasterNode( UIUtils.FunctionOutputList()[ 0 ], false );
  3951. //}
  3952. shaderFunction.ResetDirectivesOrigin();
  3953. CurrentGraph.CurrentShaderFunction = shaderFunction;
  3954. }
  3955. else
  3956. {
  3957. if( shader != null )
  3958. {
  3959. m_mainGraphInstance.UpdateShaderOnMasterNode( shader );
  3960. if( m_mainGraphInstance.CurrentCanvasMode == NodeAvailability.TemplateShader )
  3961. {
  3962. m_mainGraphInstance.RefreshLinkedMasterNodes( false );
  3963. m_mainGraphInstance.OnRefreshLinkedPortsComplete();
  3964. //m_mainGraphInstance.SetLateOptionsRefresh();
  3965. }
  3966. }
  3967. }
  3968. // @diogo: set camera parameters
  3969. if ( shaderFunction != null || shader != null )
  3970. {
  3971. cameraParams = ( cameraParams.Length != 0 ) ? cameraParams : EditorPrefs.GetString( GUID, "" ).Split( IOUtils.FIELD_SEPARATOR );
  3972. if ( cameraParams.Length == 9 )
  3973. {
  3974. try
  3975. {
  3976. var cameraInfo = new Rect( Convert.ToSingle( cameraParams[ 0 ] ), Convert.ToSingle( cameraParams[ 1 ] ), Convert.ToSingle( cameraParams[ 2 ] ), Convert.ToSingle( cameraParams[ 3 ] ) );
  3977. var cameraOffset = new Vector2( Convert.ToSingle( cameraParams[ 4 ] ), Convert.ToSingle( cameraParams[ 5 ] ) );
  3978. float cameraZoom = Convert.ToSingle( cameraParams[ 6 ] );
  3979. float centerWidth = ( this.position.width - cameraInfo.width ) * 0.5f * cameraZoom;
  3980. float centerHeight = ( this.position.height - cameraInfo.height ) * 0.5f * cameraZoom;
  3981. cameraInfo.x += centerWidth;
  3982. cameraInfo.y += centerHeight;
  3983. cameraOffset.x += centerWidth;
  3984. cameraOffset.y += centerHeight;
  3985. bool nodeParametersWindowMaximized = Convert.ToBoolean( cameraParams[ 7 ] );
  3986. bool paletteWindowMaximized = Convert.ToBoolean( cameraParams[ 8 ] );
  3987. m_cameraInfo = cameraInfo;
  3988. m_cameraOffset = cameraOffset;
  3989. CameraZoom = cameraZoom;
  3990. if ( DebugConsoleWindow.UseShaderPanelsInfo )
  3991. {
  3992. m_nodeParametersWindowMaximized = m_nodeParametersWindow.IsMaximized = nodeParametersWindowMaximized;
  3993. m_paletteWindowMaximized = m_paletteWindow.IsMaximized = paletteWindowMaximized;
  3994. }
  3995. }
  3996. catch ( Exception )
  3997. {
  3998. FocusZoom( true, false, false );
  3999. }
  4000. }
  4001. else
  4002. {
  4003. FocusZoom( true, false, false );
  4004. }
  4005. }
  4006. m_mainGraphInstance.LoadedShaderVersion = VersionInfo.FullNumber;
  4007. System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
  4008. m_mainGraphInstance.IsLoading = false;
  4009. //Remove focus from UI elements so no UI is incorrectly selected from previous loads
  4010. //Shader Name textfield was sometimes incorrectly selected
  4011. GUI.FocusControl( null );
  4012. return loadResult;
  4013. }
  4014. public void FullCleanUndoStack()
  4015. {
  4016. UndoUtils.ClearUndo( this );
  4017. m_mainGraphInstance.FullCleanUndoStack();
  4018. }
  4019. public void FullRegisterOnUndoStack()
  4020. {
  4021. UndoUtils.RegisterCompleteObjectUndo( this, Constants.UndoRegisterFullGrapId );
  4022. m_mainGraphInstance.FullRegisterOnUndoStack();
  4023. }
  4024. public void ShowPortInfo()
  4025. {
  4026. GetWindow<PortLegendInfo>();
  4027. }
  4028. public void ShowShaderLibrary()
  4029. {
  4030. GetWindow<ShaderLibrary>();
  4031. }
  4032. public void ShowMessage( string message, MessageSeverity severity = MessageSeverity.Normal, bool registerTimestamp = true, bool consoleLog = false )
  4033. {
  4034. ShowMessage( -1, message, severity, registerTimestamp, consoleLog );
  4035. }
  4036. public void ShowMessage( int messageOwner, string message, MessageSeverity severity = MessageSeverity.Normal, bool registerTimestamp = true, bool consoleLog = false )
  4037. {
  4038. if( UIUtils.InhibitMessages || m_genericMessageUI == null )
  4039. return;
  4040. m_consoleLogWindow.AddMessage( severity, message , messageOwner);
  4041. MarkToRepaint();
  4042. if( consoleLog )
  4043. {
  4044. switch( severity )
  4045. {
  4046. case MessageSeverity.Normal:
  4047. {
  4048. Debug.Log( message );
  4049. }
  4050. break;
  4051. case MessageSeverity.Warning:
  4052. {
  4053. Debug.LogWarning( message );
  4054. }
  4055. break;
  4056. case MessageSeverity.Error:
  4057. {
  4058. Debug.LogError( message );
  4059. }
  4060. break;
  4061. }
  4062. }
  4063. }
  4064. // NOTE: this can probably be removed safely
  4065. public void ShowMessageImmediately( string message, MessageSeverity severity = MessageSeverity.Normal, bool consoleLog = true )
  4066. {
  4067. if( UIUtils.InhibitMessages )
  4068. return;
  4069. switch( severity )
  4070. {
  4071. case MessageSeverity.Normal:
  4072. {
  4073. m_genericMessageContent.text = message;
  4074. if( consoleLog )
  4075. {
  4076. Debug.Log( message );
  4077. }
  4078. }
  4079. break;
  4080. case MessageSeverity.Warning:
  4081. {
  4082. m_genericMessageContent.text = "Warning!\n" + message;
  4083. if( consoleLog )
  4084. {
  4085. Debug.LogWarning( message );
  4086. }
  4087. }
  4088. break;
  4089. case MessageSeverity.Error:
  4090. {
  4091. m_genericMessageContent.text = "Error!!!\n" + message;
  4092. if( consoleLog )
  4093. {
  4094. Debug.LogError( message );
  4095. }
  4096. }
  4097. break;
  4098. }
  4099. try
  4100. {
  4101. ShowNotification( m_genericMessageContent );
  4102. }
  4103. catch( Exception e )
  4104. {
  4105. Debug.LogException( e );
  4106. }
  4107. }
  4108. public bool MouseInteracted = false;
  4109. void OnGUI()
  4110. {
  4111. if( ASEPackageManagerHelper.CheckImporter )
  4112. return;
  4113. #if UNITY_EDITOR_WIN
  4114. if( m_openSavedFolder && Event.current.type == EventType.Repaint )
  4115. {
  4116. OpenSavedFolder();
  4117. return;
  4118. }
  4119. #endif
  4120. AmplifyShaderEditorWindow cacheWindow = UIUtils.CurrentWindow;
  4121. UIUtils.CurrentWindow = this;
  4122. if( !m_initialized || (object)UIUtils.MainSkin == null || !UIUtils.Initialized )
  4123. {
  4124. UIUtils.InitMainSkin();
  4125. Init();
  4126. }
  4127. m_currentEvent = Event.current;
  4128. if( m_currentEvent.type == EventType.ExecuteCommand || m_currentEvent.type == EventType.ValidateCommand )
  4129. m_currentCommandName = m_currentEvent.commandName;
  4130. else
  4131. m_currentCommandName = string.Empty;
  4132. System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
  4133. MouseInteracted = false;
  4134. if( m_refreshOnUndo )
  4135. {
  4136. m_refreshOnUndo = false;
  4137. m_mainGraphInstance.RefreshOnUndo();
  4138. }
  4139. if( m_refreshAvailableNodes )
  4140. {
  4141. RefreshAvaibleNodes();
  4142. }
  4143. if( m_previousShaderFunction != CurrentGraph.CurrentShaderFunction )
  4144. {
  4145. m_nodeParametersWindow.ForceUpdate = true;
  4146. m_previousShaderFunction = CurrentGraph.CurrentShaderFunction;
  4147. }
  4148. if( m_nodeToFocus != null && m_currentEvent.type == EventType.Layout )
  4149. {
  4150. FocusOnNode( m_nodeToFocus, m_zoomToFocus, m_selectNodeToFocus );
  4151. m_nodeToFocus = null;
  4152. }
  4153. m_mainGraphInstance.OnDuplicateEventWrapper();
  4154. m_currentInactiveTime = CalculateInactivityTime();
  4155. if( m_nodeParametersWindow != null && m_innerEditorVariables.NodeParametersMaximized != m_nodeParametersWindow.IsMaximized )
  4156. m_innerEditorVariables.NodeParametersMaximized = m_nodeParametersWindow.IsMaximized;
  4157. if( m_paletteWindow != null && m_innerEditorVariables.NodePaletteMaximized != m_paletteWindow.IsMaximized )
  4158. m_innerEditorVariables.NodePaletteMaximized = m_paletteWindow.IsMaximized;
  4159. if( m_checkInvalidConnections )
  4160. {
  4161. m_checkInvalidConnections = false;
  4162. m_mainGraphInstance.DeleteInvalidConnections();
  4163. }
  4164. //if ( m_repaintIsDirty )
  4165. //{
  4166. // m_repaintIsDirty = false;
  4167. // ForceRepaint();
  4168. //}
  4169. if( m_forcingMaterialUpdateFlag )
  4170. {
  4171. Focus();
  4172. if( m_materialsToUpdate.Count > 0 )
  4173. {
  4174. float percentage = 100.0f * (float)( UIUtils.TotalExampleMaterials - m_materialsToUpdate.Count ) / (float)UIUtils.TotalExampleMaterials;
  4175. if( m_forcingMaterialUpdateOp ) // Read
  4176. {
  4177. Debug.Log( percentage + "% Recompiling " + m_materialsToUpdate[ 0 ].name );
  4178. LoadDroppedObject( true, m_materialsToUpdate[ 0 ].shader, m_materialsToUpdate[ 0 ] );
  4179. }
  4180. else // Write
  4181. {
  4182. Debug.Log( percentage + "% Saving " + m_materialsToUpdate[ 0 ].name );
  4183. SaveToDisk( false );
  4184. m_materialsToUpdate.RemoveAt( 0 );
  4185. }
  4186. m_forcingMaterialUpdateOp = !m_forcingMaterialUpdateOp;
  4187. }
  4188. else
  4189. {
  4190. Debug.Log( "100% - All Materials compiled " );
  4191. m_forcingMaterialUpdateFlag = false;
  4192. }
  4193. }
  4194. if( m_removedKeyboardFocus )
  4195. {
  4196. m_removedKeyboardFocus = false;
  4197. GUIUtility.keyboardControl = 0;
  4198. }
  4199. Vector2 pos = m_currentEvent.mousePosition;
  4200. pos.x += position.x;
  4201. pos.y += position.y;
  4202. m_insideEditorWindow = position.Contains( pos );
  4203. if( m_delayedLoadObject != null && m_mainGraphInstance.CurrentMasterNode != null )
  4204. {
  4205. m_mainGraphInstance.SetLateOptionsRefresh();
  4206. LoadObject( m_delayedLoadObject );
  4207. m_delayedLoadObject = null;
  4208. }
  4209. else if( m_delayedLoadObject != null && m_mainGraphInstance.CurrentOutputNode != null )
  4210. {
  4211. m_mainGraphInstance.SetLateOptionsRefresh();
  4212. LoadObject( m_delayedLoadObject );
  4213. m_delayedLoadObject = null;
  4214. }
  4215. if( m_delayedMaterialSet != null && m_mainGraphInstance.CurrentMasterNode != null )
  4216. {
  4217. m_mainGraphInstance.UpdateMaterialOnMasterNode( m_delayedMaterialSet );
  4218. m_mainGraphInstance.SetMaterialModeOnGraph( m_delayedMaterialSet );
  4219. CurrentSelection = ASESelectionMode.Material;
  4220. IsShaderFunctionWindow = false;
  4221. m_delayedMaterialSet = null;
  4222. }
  4223. Material currentMaterial = m_mainGraphInstance.CurrentMaterial;
  4224. if( m_forceUpdateFromMaterialFlag )
  4225. {
  4226. Focus();
  4227. m_forceUpdateFromMaterialFlag = false;
  4228. if( currentMaterial != null )
  4229. {
  4230. m_mainGraphInstance.CopyValuesFromMaterial( currentMaterial );
  4231. m_repaintIsDirty = true;
  4232. }
  4233. }
  4234. m_repaintCount = 0;
  4235. m_cameraInfo = position;
  4236. //if( m_currentEvent.type == EventType.keyDown )
  4237. if( m_currentEvent.type == EventType.Repaint )
  4238. m_keyEvtMousePos2D = m_currentEvent.mousePosition;
  4239. m_currentMousePos2D = m_currentEvent.mousePosition;
  4240. m_currentMousePos.x = m_currentMousePos2D.x;
  4241. m_currentMousePos.y = m_currentMousePos2D.y;
  4242. m_graphArea.width = m_cameraInfo.width;
  4243. m_graphArea.height = m_cameraInfo.height;
  4244. m_autoPanDirActive = m_lmbPressed || m_forceAutoPanDir || m_multipleSelectionActive || m_wireReferenceUtils.ValidReferences();
  4245. // Need to use it in order to prevent Mismatched LayoutGroup on ValidateCommand when rendering nodes
  4246. //if( Event.current.type == EventType.ValidateCommand )
  4247. //{
  4248. // Event.current.Use();
  4249. //}
  4250. // Nodes Graph background area
  4251. //GUILayout.BeginArea( m_graphArea, "Nodes" );
  4252. {
  4253. // Camera movement is simulated by grabing the current camera offset, transforming it into texture space and manipulating the tiled texture uv coords
  4254. GUI.DrawTextureWithTexCoords( m_graphArea, m_graphBgTexture,
  4255. new Rect( ( -m_cameraOffset.x / m_graphBgTexture.width ),
  4256. ( m_cameraOffset.y / m_graphBgTexture.height ) - m_cameraZoom * m_cameraInfo.height / m_graphBgTexture.height,
  4257. m_cameraZoom * m_cameraInfo.width / m_graphBgTexture.width,
  4258. m_cameraZoom * m_cameraInfo.height / m_graphBgTexture.height ) );
  4259. Color col = GUI.color;
  4260. GUI.color = new Color( 1, 1, 1, 0.7f );
  4261. GUI.DrawTexture( m_graphArea, m_graphFgTexture, ScaleMode.StretchToFill, true );
  4262. GUI.color = col;
  4263. }
  4264. //GUILayout.EndArea();
  4265. if( DebugConsoleWindow.DeveloperMode && m_currentEvent.type == EventType.Repaint )
  4266. {
  4267. GUI.Label( new Rect(Screen.width - 60, 40, 60, 50), m_fpsDisplay );
  4268. }
  4269. bool restoreMouse = false;
  4270. if( InsideMenus( m_currentMousePos2D ) /*|| _confirmationWindow.IsActive*/ )
  4271. {
  4272. if( Event.current.type == EventType.MouseDown )
  4273. {
  4274. restoreMouse = true;
  4275. Event.current.type = EventType.Ignore;
  4276. }
  4277. // Must guarantee that mouse up ops on menus will reset auto pan if it is set
  4278. if( m_currentEvent.type == EventType.MouseUp && m_currentEvent.button == ButtonClickId.LeftMouseButton )
  4279. {
  4280. m_lmbPressed = false;
  4281. }
  4282. }
  4283. // Nodes
  4284. //GUILayout.BeginArea( m_graphArea );
  4285. {
  4286. m_drawInfo.CameraArea = m_cameraInfo;
  4287. m_drawInfo.TransformedCameraArea = m_graphArea;
  4288. m_drawInfo.MousePosition = m_currentMousePos2D;
  4289. m_drawInfo.CameraOffset = m_cameraOffset;
  4290. m_drawInfo.InvertedZoom = 1 / m_cameraZoom;
  4291. m_drawInfo.LeftMouseButtonPressed = m_currentEvent.button == ButtonClickId.LeftMouseButton;
  4292. m_drawInfo.CurrentEventType = m_currentEvent.type;
  4293. m_drawInfo.ZoomChanged = m_zoomChanged;
  4294. m_drawInfo.TransformedMousePos = m_currentMousePos2D * m_cameraZoom - m_cameraOffset;
  4295. if( m_drawInfo.CurrentEventType == EventType.Repaint )
  4296. UIUtils.UpdateMainSkin( m_drawInfo );
  4297. // Draw mode indicator
  4298. m_modeWindow.Draw( m_graphArea, m_currentMousePos2D, m_mainGraphInstance.CurrentShader, currentMaterial,
  4299. 0.5f * ( m_graphArea.width - m_paletteWindow.RealWidth - m_nodeParametersWindow.RealWidth ),
  4300. ( m_nodeParametersWindow.IsMaximized ? m_nodeParametersWindow.RealWidth : 0 ),
  4301. ( m_paletteWindow.IsMaximized ? m_paletteWindow.RealWidth : 0 )/*, m_openedAssetFromNode*/ );
  4302. PreTestLeftMouseDown();
  4303. //m_consoleLogWindow.Draw( m_graphArea, m_currentMousePos2D, m_currentEvent.button, false, m_paletteWindow.IsMaximized ? m_paletteWindow.RealWidth : 0 );
  4304. //m_mainGraphInstance.DrawBezierBoundingBox();
  4305. //CheckNodeReplacement();
  4306. // Main Graph Draw
  4307. m_repaintIsDirty = m_mainGraphInstance.Draw( m_drawInfo ) || m_repaintIsDirty;
  4308. m_mainGraphInstance.DrawGrid( m_drawInfo );
  4309. bool hasUnusedConnNodes = m_mainGraphInstance.HasUnConnectedNodes;
  4310. m_toolsWindow.SetStateOnButton( ToolButtonType.CleanUnusedNodes, hasUnusedConnNodes ? 1 : 0 );
  4311. m_zoomChanged = false;
  4312. MasterNode masterNode = m_mainGraphInstance.CurrentMasterNode;
  4313. if( masterNode != null )
  4314. {
  4315. m_toolsWindow.DrawShaderTitle( m_nodeParametersWindow, m_paletteWindow, AvailableCanvasWidth, m_graphArea.height, masterNode.CroppedShaderName );
  4316. }
  4317. else if( m_mainGraphInstance.CurrentOutputNode != null )
  4318. {
  4319. string functionName = string.Empty;
  4320. if( m_mainGraphInstance.CurrentShaderFunction != null )
  4321. functionName = m_mainGraphInstance.CurrentShaderFunction.FunctionName;
  4322. m_toolsWindow.DrawShaderTitle( m_nodeParametersWindow, m_paletteWindow, AvailableCanvasWidth, m_graphArea.height, functionName );
  4323. }
  4324. }
  4325. //m_consoleLogWindow.Draw( m_graphArea, m_currentMousePos2D, m_currentEvent.button, false, m_paletteWindow.IsMaximized ? m_paletteWindow.RealWidth : 0 );
  4326. //GUILayout.EndArea();
  4327. if( restoreMouse )
  4328. {
  4329. Event.current.type = EventType.MouseDown;
  4330. m_drawInfo.CurrentEventType = EventType.MouseDown;
  4331. }
  4332. m_toolsWindow.InitialX = m_nodeParametersWindow.RealWidth;
  4333. m_toolsWindow.Width = m_cameraInfo.width - ( m_nodeParametersWindow.RealWidth + m_paletteWindow.RealWidth );
  4334. m_toolsWindow.Draw( m_cameraInfo, m_currentMousePos2D, m_currentEvent.button, false );
  4335. m_tipsWindow.Draw( m_cameraInfo, m_currentMousePos2D, m_currentEvent.button, false );
  4336. bool autoMinimize = false;
  4337. if( position.width < m_lastWindowWidth && position.width < Constants.MINIMIZE_WINDOW_LOCK_SIZE )
  4338. {
  4339. autoMinimize = true;
  4340. }
  4341. if( autoMinimize )
  4342. m_nodeParametersWindow.IsMaximized = false;
  4343. ParentNode selectedNode = ( m_mainGraphInstance.SelectedNodes.Count == 1 ) ? m_mainGraphInstance.SelectedNodes[ 0 ] : m_mainGraphInstance.CurrentMasterNode;
  4344. m_repaintIsDirty = m_nodeParametersWindow.Draw( m_cameraInfo, selectedNode, m_currentMousePos2D, m_currentEvent.button, false ) || m_repaintIsDirty; //TODO: If multiple nodes from the same type are selected also show a parameters window which modifies all of them
  4345. if( m_nodeParametersWindow.IsResizing )
  4346. m_repaintIsDirty = true;
  4347. // Test to ignore mouse on main palette when inside context palette ... IsInside also takes active state into account
  4348. bool ignoreMouseForPalette = m_contextPalette.IsInside( m_currentMousePos2D );
  4349. if( ignoreMouseForPalette && Event.current.type == EventType.MouseDown )
  4350. {
  4351. Event.current.type = EventType.Ignore;
  4352. m_drawInfo.CurrentEventType = EventType.Ignore;
  4353. }
  4354. if( autoMinimize )
  4355. m_paletteWindow.IsMaximized = false;
  4356. m_paletteWindow.Draw( m_cameraInfo, m_currentMousePos2D, m_currentEvent.button, !m_contextPalette.IsActive );
  4357. if( m_paletteWindow.IsResizing )
  4358. {
  4359. m_repaintIsDirty = true;
  4360. }
  4361. if( ignoreMouseForPalette )
  4362. {
  4363. if( restoreMouse )
  4364. {
  4365. Event.current.type = EventType.MouseDown;
  4366. m_drawInfo.CurrentEventType = EventType.MouseDown;
  4367. }
  4368. }
  4369. m_consoleLogWindow.Draw( m_graphArea, m_currentMousePos2D, m_currentEvent.button, false, m_paletteWindow.IsMaximized ? m_paletteWindow.RealWidth : 0 );
  4370. if( m_contextPalette.IsActive )
  4371. {
  4372. m_contextPalette.Draw( m_cameraInfo, m_currentMousePos2D, m_currentEvent.button, m_contextPalette.IsActive );
  4373. }
  4374. if( m_palettePopup.IsActive )
  4375. {
  4376. m_palettePopup.Draw( m_currentMousePos2D );
  4377. m_repaintIsDirty = true;
  4378. int controlID = GUIUtility.GetControlID( FocusType.Passive );
  4379. if( m_currentEvent.GetTypeForControl( controlID ) == EventType.MouseUp )
  4380. {
  4381. if( m_currentEvent.button == ButtonClickId.LeftMouseButton )
  4382. {
  4383. m_palettePopup.Deactivate();
  4384. if( !InsideMenus( m_currentMousePos2D ) )
  4385. {
  4386. ParentNode newNode = CreateNode( m_paletteChosenType, TranformedMousePos, m_paletteChosenFunction );
  4387. //Debug.Log("created menu");
  4388. m_mainGraphInstance.SelectNode( newNode, false, false );
  4389. bool find = false;
  4390. if( newNode is FunctionNode && CurrentGraph.CurrentShaderFunction != null )
  4391. find = SearchFunctionNodeRecursively( CurrentGraph.CurrentShaderFunction );
  4392. if( find )
  4393. {
  4394. DestroyNode( newNode, false );
  4395. ShowMessage( "Shader Function loop detected, new node was removed to prevent errors." );
  4396. }
  4397. else
  4398. {
  4399. newNode.RefreshExternalReferences();
  4400. }
  4401. }
  4402. }
  4403. }
  4404. }
  4405. // Handle all events ( mouse interaction + others )
  4406. if( !MouseInteracted )
  4407. HandleGUIEvents();
  4408. if( m_currentEvent.type == EventType.Repaint )
  4409. {
  4410. m_mainGraphInstance.UpdateMarkForDeletion();
  4411. }
  4412. // UI Overlay
  4413. // Selection Box
  4414. if( m_multipleSelectionActive )
  4415. {
  4416. UpdateSelectionArea();
  4417. Rect transformedArea = m_multipleSelectionArea;
  4418. transformedArea.position = ( transformedArea.position + m_cameraOffset ) / m_cameraZoom;
  4419. transformedArea.size /= m_cameraZoom;
  4420. if( transformedArea.width < 0 )
  4421. {
  4422. transformedArea.width = -transformedArea.width;
  4423. transformedArea.x -= transformedArea.width;
  4424. }
  4425. if( transformedArea.height < 0 )
  4426. {
  4427. transformedArea.height = -transformedArea.height;
  4428. transformedArea.y -= transformedArea.height;
  4429. }
  4430. Color original = GUI.color;
  4431. GUI.color = Constants.BoxSelectionColor;
  4432. GUI.Label( transformedArea, "", UIUtils.Box );
  4433. GUI.color = original;
  4434. //GUI.backgroundColor = original;
  4435. }
  4436. bool isResizing = m_nodeParametersWindow.IsResizing || m_paletteWindow.IsResizing;
  4437. //Test boundaries for auto-pan
  4438. if( !isResizing && m_autoPanDirActive )
  4439. {
  4440. m_autoPanArea[ (int)AutoPanLocation.LEFT ].AdjustInitialX = m_nodeParametersWindow.IsMaximized ? m_nodeParametersWindow.RealWidth : 0;
  4441. m_autoPanArea[ (int)AutoPanLocation.RIGHT ].AdjustInitialX = m_paletteWindow.IsMaximized ? -m_paletteWindow.RealWidth : 0;
  4442. Vector2 autoPanDir = Vector2.zero;
  4443. for( int i = 0; i < m_autoPanArea.Length; i++ )
  4444. {
  4445. if( m_autoPanArea[ i ].CheckArea( m_currentMousePos2D, m_cameraInfo, false ) )
  4446. {
  4447. autoPanDir += m_autoPanArea[ i ].Velocity;
  4448. }
  4449. }
  4450. m_cameraOffset += autoPanDir;
  4451. if( !m_wireReferenceUtils.ValidReferences() && m_insideEditorWindow && !m_altBoxSelection )
  4452. {
  4453. m_mainGraphInstance.MoveSelectedNodes( -autoPanDir );
  4454. }
  4455. m_repaintIsDirty = true;
  4456. }
  4457. m_isDirty = m_isDirty || m_mainGraphInstance.IsDirty;
  4458. if( m_isDirty )
  4459. {
  4460. m_isDirty = false;
  4461. //ShaderIsModified = true;
  4462. EditorUtility.SetDirty( this );
  4463. }
  4464. m_saveIsDirty = m_saveIsDirty || m_mainGraphInstance.SaveIsDirty;
  4465. if( m_liveShaderEditing )
  4466. {
  4467. if( m_saveIsDirty )
  4468. {
  4469. if( focusedWindow == this && m_currentInactiveTime > InactivitySaveTime && !(EditorGUIUtility.editingTextField && EditorGUIUtility.keyboardControl!=0) )
  4470. {
  4471. m_saveIsDirty = false;
  4472. if( m_mainGraphInstance.CurrentMasterNodeId != Constants.INVALID_NODE_ID )
  4473. {
  4474. SaveToDisk( true );
  4475. }
  4476. else
  4477. {
  4478. ShowMessage( LiveShaderError );
  4479. }
  4480. }
  4481. }
  4482. }
  4483. else if( m_saveIsDirty )
  4484. {
  4485. ShaderIsModified = true;
  4486. m_saveIsDirty = false;
  4487. }
  4488. if( m_onLoadDone > 0 )
  4489. {
  4490. m_onLoadDone--;
  4491. if( m_onLoadDone == 0 )
  4492. {
  4493. ShaderIsModified = false;
  4494. }
  4495. }
  4496. if( m_cacheSaveOp )
  4497. {
  4498. if( ( EditorApplication.timeSinceStartup - m_lastTimeSaved ) > SaveTime )
  4499. {
  4500. SaveToDisk( false );
  4501. }
  4502. }
  4503. m_genericMessageUI.CheckForMessages();
  4504. if( m_ctrlSCallback )
  4505. {
  4506. m_ctrlSCallback = false;
  4507. OnToolButtonPressed( ToolButtonType.Update );
  4508. }
  4509. m_lastWindowWidth = position.width;
  4510. m_nodeExporterUtils.Update();
  4511. if( m_markedToSave )
  4512. {
  4513. m_markedToSave = false;
  4514. SaveToDisk( false );
  4515. }
  4516. if( m_performFullUndoRegister )
  4517. {
  4518. m_performFullUndoRegister = false;
  4519. FullRegisterOnUndoStack();
  4520. }
  4521. if( CheckFunctions )
  4522. CheckFunctions = false;
  4523. System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
  4524. UIUtils.CurrentWindow = cacheWindow;
  4525. if( !m_nodesLoadedCorrectly )
  4526. {
  4527. try
  4528. {
  4529. ShowNotification( NodesExceptionMessage );
  4530. }
  4531. catch( Exception e )
  4532. {
  4533. Debug.LogException( e );
  4534. }
  4535. }
  4536. CheckNodeReplacement();
  4537. #if UNITY_EDITOR_WIN
  4538. if( m_takeScreenShot )
  4539. FocusZoom( true, false, false );
  4540. if( m_takeScreenShot && Event.current.type == EventType.Repaint )
  4541. TakeScreenShot();
  4542. #endif
  4543. if( Event.current.type == EventType.Layout )
  4544. {
  4545. switch( State )
  4546. {
  4547. default:
  4548. case OpenSaveState.NONE:
  4549. break;
  4550. case OpenSaveState.OPEN:
  4551. {
  4552. State = OpenSaveState.WAIT;
  4553. string list = EditorPrefs.GetString( ASEFileList , "" );
  4554. m_assetPaths = new List<string>( list.Split( ',' ) );
  4555. Repaint();
  4556. }
  4557. break;
  4558. case OpenSaveState.WAIT:
  4559. {
  4560. // we wait one frame to give time for the editor to properly initialize everything
  4561. State = OpenSaveState.SAVE;
  4562. Repaint();
  4563. }
  4564. break;
  4565. case OpenSaveState.SAVE:
  4566. {
  4567. State = OpenSaveState.CLOSE;
  4568. try
  4569. {
  4570. SaveToDisk( false );
  4571. }
  4572. catch( Exception e )
  4573. {
  4574. State = OpenSaveState.NONE;
  4575. EditorPrefs.DeleteKey( ASEFileList );
  4576. throw e;
  4577. }
  4578. Repaint();
  4579. }
  4580. break;
  4581. case OpenSaveState.CLOSE:
  4582. {
  4583. State = OpenSaveState.NONE;
  4584. m_assetPaths.RemoveAt( 0 );
  4585. if( m_assetPaths.Count > 0 )
  4586. {
  4587. AmplifyShaderEditorWindow.LoadAndSaveList( m_assetPaths.ToArray() );
  4588. }
  4589. else
  4590. {
  4591. EditorPrefs.DeleteKey( ASEFileList );
  4592. m_batchTimer.Stop();
  4593. if ( Preferences.User.LogBatchCompile )
  4594. {
  4595. Debug.Log( "[AmplifyShaderEditor] Finished batch compilation in " + m_batchTimer.Elapsed.TotalSeconds.ToString( "0.00" ) + " seconds." );
  4596. }
  4597. }
  4598. this.Close();
  4599. }
  4600. break;
  4601. }
  4602. }
  4603. }
  4604. bool m_markToClose = false;
  4605. private List<string> m_assetPaths = new List<string>();
  4606. public OpenSaveState State = OpenSaveState.NONE;
  4607. public enum OpenSaveState
  4608. {
  4609. NONE,
  4610. OPEN,
  4611. WAIT,
  4612. SAVE,
  4613. CLOSE
  4614. }
  4615. void OnInspectorUpdate()
  4616. {
  4617. ASEPackageManagerHelper.Update();
  4618. if( m_afterDeserializeFlag )
  4619. {
  4620. m_afterDeserializeFlag = false;
  4621. //m_mainGraphInstance.ParentWindow = this;
  4622. }
  4623. if( (IsShaderFunctionWindow && CurrentGraph.CurrentShaderFunction == null) || m_markToClose )
  4624. {
  4625. Close();
  4626. }
  4627. }
  4628. public void SetCtrlSCallback( bool imediate )
  4629. {
  4630. //MasterNode node = _mainGraphInstance.CurrentMasterNode;
  4631. if( /*node != null && node.CurrentShader != null && */m_shaderIsModified )
  4632. {
  4633. if( imediate )
  4634. {
  4635. OnToolButtonPressed( ToolButtonType.Update );
  4636. }
  4637. else
  4638. {
  4639. m_ctrlSCallback = true;
  4640. }
  4641. }
  4642. }
  4643. public void SetSaveIsDirty()
  4644. {
  4645. m_saveIsDirty = true && UIUtils.DirtyMask;
  4646. }
  4647. public void OnPaletteNodeCreate( System.Type type, string name, AmplifyShaderFunction function )
  4648. {
  4649. m_mainGraphInstance.DeSelectAll();
  4650. m_paletteChosenType = type;
  4651. m_paletteChosenFunction = function;
  4652. m_palettePopup.Activate( name );
  4653. }
  4654. public void OnContextPaletteNodeCreate( System.Type type, string name, AmplifyShaderFunction function )
  4655. {
  4656. m_mainGraphInstance.DeSelectAll();
  4657. ParentNode newNode = CreateNode( type, m_contextPalette.StartDropPosition * m_cameraZoom - m_cameraOffset, function );
  4658. //Debug.Log( "created context" );
  4659. m_mainGraphInstance.SelectNode( newNode, false, false );
  4660. bool find = false;
  4661. if( newNode is FunctionNode && CurrentGraph.CurrentShaderFunction != null )
  4662. find = SearchFunctionNodeRecursively( CurrentGraph.CurrentShaderFunction );
  4663. if( find )
  4664. {
  4665. DestroyNode( newNode, false );
  4666. ShowMessage( "Shader Function loop detected, new node was removed to prevent errors." );
  4667. }
  4668. else
  4669. {
  4670. newNode.RefreshExternalReferences();
  4671. }
  4672. }
  4673. void OnNodeStoppedMovingEvent( ParentNode node )
  4674. {
  4675. CheckZoomBoundaries( node.Vec2Position );
  4676. //ShaderIsModified = true;
  4677. }
  4678. void OnRefreshFunctionNodeEvent( FunctionNode node )
  4679. {
  4680. Debug.Log( node );
  4681. }
  4682. private const string ShaderIsModifiedMessage = "Click to save changes.";
  4683. private const string ShaderIsNotModified = "No changes to save, up-to-date.";
  4684. void OnMaterialUpdated( MasterNode masterNode )
  4685. {
  4686. if( masterNode != null )
  4687. {
  4688. if( masterNode.CurrentMaterial )
  4689. {
  4690. m_toolsWindow.SetStateOnButton( ToolButtonType.Update, ShaderIsModified ? 0 : 2, ShaderIsModified ? ShaderIsModifiedMessage : ShaderIsNotModified);
  4691. }
  4692. else
  4693. {
  4694. m_toolsWindow.SetStateOnButton( ToolButtonType.Update, 1, "Set an active Material in the Master Node." );
  4695. }
  4696. UpdateLiveUI();
  4697. }
  4698. else
  4699. {
  4700. m_toolsWindow.SetStateOnButton( ToolButtonType.Update, 1, "Set an active Material in the Master Node." );
  4701. }
  4702. }
  4703. void OnShaderUpdated( MasterNode masterNode )
  4704. {
  4705. m_toolsWindow.SetStateOnButton( ToolButtonType.OpenSourceCode, masterNode.CurrentShader != null ? 1 : 0 );
  4706. }
  4707. public void CheckZoomBoundaries( Vector2 newPosition )
  4708. {
  4709. if( newPosition.x < m_minNodePos.x )
  4710. {
  4711. m_minNodePos.x = newPosition.x;
  4712. }
  4713. else if( newPosition.x > m_maxNodePos.x )
  4714. {
  4715. m_maxNodePos.x = newPosition.x;
  4716. }
  4717. if( newPosition.y < m_minNodePos.y )
  4718. {
  4719. m_minNodePos.y = newPosition.y;
  4720. }
  4721. else if( newPosition.y > m_maxNodePos.y )
  4722. {
  4723. m_maxNodePos.y = newPosition.y;
  4724. }
  4725. }
  4726. public void DestroyNode( ParentNode node, bool registerUndo = true ) { m_mainGraphInstance.DestroyNode( node, registerUndo ); }
  4727. public ParentNode CreateNode( System.Type type, Vector2 position, AmplifyShaderFunction function = null, bool selectNode = true )
  4728. {
  4729. ParentNode node;
  4730. if( function == null )
  4731. node = m_mainGraphInstance.CreateNode( type, true );
  4732. else
  4733. node = m_mainGraphInstance.CreateNode( function, true );
  4734. Vector2 newPosition = position;
  4735. node.Vec2Position = newPosition;
  4736. CheckZoomBoundaries( newPosition );
  4737. // Connect node if a wire is active
  4738. if( m_wireReferenceUtils.ValidReferences() )
  4739. {
  4740. if( m_wireReferenceUtils.InputPortReference.IsValid )
  4741. {
  4742. ParentNode originNode = m_mainGraphInstance.GetNode( m_wireReferenceUtils.InputPortReference.NodeId );
  4743. InputPort originPort = originNode.GetInputPortByUniqueId( m_wireReferenceUtils.InputPortReference.PortId );
  4744. OutputPort outputPort = node.GetFirstOutputPortOfType( m_wireReferenceUtils.InputPortReference.DataType, true );
  4745. if( outputPort != null && originPort.CheckValidType( outputPort.DataType ) && ( !m_wireReferenceUtils.InputPortReference.TypeLocked ||
  4746. m_wireReferenceUtils.InputPortReference.DataType == WirePortDataType.OBJECT ||
  4747. ( m_wireReferenceUtils.InputPortReference.TypeLocked && outputPort.DataType == m_wireReferenceUtils.InputPortReference.DataType ) ) )
  4748. {
  4749. //link output to input
  4750. if( outputPort.ConnectTo( m_wireReferenceUtils.InputPortReference.NodeId, m_wireReferenceUtils.InputPortReference.PortId, m_wireReferenceUtils.InputPortReference.DataType, m_wireReferenceUtils.InputPortReference.TypeLocked ) )
  4751. node.OnOutputPortConnected( outputPort.PortId, m_wireReferenceUtils.InputPortReference.NodeId, m_wireReferenceUtils.InputPortReference.PortId );
  4752. //link input to output
  4753. if( originPort.ConnectTo( outputPort.NodeId, outputPort.PortId, outputPort.DataType, m_wireReferenceUtils.InputPortReference.TypeLocked ) )
  4754. originNode.OnInputPortConnected( m_wireReferenceUtils.InputPortReference.PortId, node.UniqueId, outputPort.PortId );
  4755. }
  4756. }
  4757. if( m_wireReferenceUtils.OutputPortReference.IsValid )
  4758. {
  4759. ParentNode originNode = m_mainGraphInstance.GetNode( m_wireReferenceUtils.OutputPortReference.NodeId );
  4760. InputPort inputPort = node.GetFirstInputPortOfType( m_wireReferenceUtils.OutputPortReference.DataType, true );
  4761. if( inputPort != null && ( !inputPort.TypeLocked ||
  4762. inputPort.DataType == WirePortDataType.OBJECT ||
  4763. ( inputPort.TypeLocked && inputPort.DataType == m_wireReferenceUtils.OutputPortReference.DataType ) ) )
  4764. {
  4765. inputPort.InvalidateAllConnections();
  4766. //link input to output
  4767. if( inputPort.ConnectTo( m_wireReferenceUtils.OutputPortReference.NodeId, m_wireReferenceUtils.OutputPortReference.PortId, m_wireReferenceUtils.OutputPortReference.DataType, inputPort.TypeLocked ) )
  4768. node.OnInputPortConnected( inputPort.PortId, m_wireReferenceUtils.OutputPortReference.NodeId, m_wireReferenceUtils.OutputPortReference.PortId );
  4769. //link output to input
  4770. if( originNode.GetOutputPortByUniqueId( m_wireReferenceUtils.OutputPortReference.PortId ).ConnectTo( inputPort.NodeId, inputPort.PortId, m_wireReferenceUtils.OutputPortReference.DataType, inputPort.TypeLocked ) )
  4771. originNode.OnOutputPortConnected( m_wireReferenceUtils.OutputPortReference.PortId, node.UniqueId, inputPort.PortId );
  4772. }
  4773. }
  4774. m_wireReferenceUtils.InvalidateReferences();
  4775. //for ( int i = 0; i < m_mainGraphInstance.VisibleNodes.Count; i++ )
  4776. //{
  4777. // m_mainGraphInstance.VisibleNodes[ i ].OnNodeInteraction( node );
  4778. //}
  4779. }
  4780. if( selectNode )
  4781. m_mainGraphInstance.SelectNode( node, false, false );
  4782. //_repaintIsDirty = true
  4783. SetSaveIsDirty();
  4784. ForceRepaint();
  4785. return node;
  4786. }
  4787. public void UpdateNodePreviewListAndTime()
  4788. {
  4789. if( UIUtils.CurrentWindow != this )
  4790. return;
  4791. double deltaTime = Time.realtimeSinceStartup - m_time;
  4792. m_time = Time.realtimeSinceStartup;
  4793. if( DebugConsoleWindow.DeveloperMode )
  4794. {
  4795. m_frameCounter++;
  4796. if( m_frameCounter >= 60 )
  4797. {
  4798. m_fpsDisplay = ( 60 / ( Time.realtimeSinceStartup - m_fpsTime ) ).ToString( "N2" );
  4799. m_fpsTime = Time.realtimeSinceStartup;
  4800. m_frameCounter = 0;
  4801. }
  4802. }
  4803. if( m_smoothZoom )
  4804. {
  4805. m_repaintIsDirty = true;
  4806. if( Mathf.Abs( m_targetZoom - m_cameraZoom ) < 0.001f )
  4807. {
  4808. m_smoothZoom = false;
  4809. m_cameraZoom = m_targetZoom;
  4810. m_zoomTime = 0;
  4811. }
  4812. else
  4813. {
  4814. m_zoomTime += deltaTime;
  4815. Vector2 canvasPos = m_zoomPivot * m_cameraZoom;
  4816. m_cameraZoom = Mathf.SmoothDamp( m_cameraZoom, m_targetZoom, ref m_zoomVelocity, 0.1f, 10000, (float)deltaTime * 1.5f );
  4817. canvasPos = canvasPos - m_zoomPivot * m_cameraZoom;
  4818. m_cameraOffset = m_cameraOffset - canvasPos;
  4819. m_targetOffset = m_targetOffset - canvasPos;
  4820. }
  4821. }
  4822. if( m_smoothOffset )
  4823. {
  4824. m_repaintIsDirty = true;
  4825. if( ( m_targetOffset - m_cameraOffset ).SqrMagnitude() < 1f )
  4826. {
  4827. m_smoothOffset = false;
  4828. m_offsetTime = 0;
  4829. }
  4830. else
  4831. {
  4832. m_offsetTime += deltaTime;
  4833. m_cameraOffset = Vector2.SmoothDamp( m_cameraOffset, m_targetOffset, ref m_camVelocity, 0.1f, 100000, (float)deltaTime * 1.5f );
  4834. }
  4835. }
  4836. if( m_cachedEditorTimeId == -1 )
  4837. m_cachedEditorTimeId = Shader.PropertyToID( "_EditorTime" );
  4838. if( m_cachedEditorDeltaTimeId == -1 )
  4839. m_cachedEditorDeltaTimeId = Shader.PropertyToID( "_EditorDeltaTime" );
  4840. //Update Game View?
  4841. //Shader.SetGlobalVector( "_Time", new Vector4( Time.realtimeSinceStartup / 20, Time.realtimeSinceStartup, Time.realtimeSinceStartup * 2, Time.realtimeSinceStartup * 3 ) );
  4842. //System.Type T = System.Type.GetType( "UnityEditor.GameView,UnityEditor" );
  4843. //UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll( T );
  4844. //EditorWindow gameView = ( array.Length <= 0 ) ? null : ( ( EditorWindow ) array[ 0 ] );
  4845. //gameView.Repaint();
  4846. if( RenderSettings.sun != null )
  4847. {
  4848. Vector3 lightdir = -RenderSettings.sun.transform.forward;//.rotation.eulerAngles;
  4849. Shader.SetGlobalVector( "_EditorWorldLightPos", new Vector4( lightdir.x, lightdir.y, lightdir.z, 0 ) );
  4850. Shader.SetGlobalColor( "_EditorLightColor", RenderSettings.sun.color.linear );
  4851. }
  4852. Shader.SetGlobalFloat( "_EditorTime", (float)m_time );
  4853. Shader.SetGlobalFloat( "_EditorDeltaTime", (float)deltaTime );
  4854. /////////// UPDATE PREVIEWS //////////////
  4855. UIUtils.CheckNullMaterials();
  4856. UIUtils.SetPreviewShaderConstants();
  4857. //CurrentGraph.AllNodes.Sort( ( x, y ) => { return x.Depth.CompareTo( y.Depth ); } );
  4858. int nodeCount = CurrentGraph.AllNodes.Count;
  4859. for( int i = nodeCount - 1; i >= 0; i-- )
  4860. {
  4861. ParentNode node = CurrentGraph.AllNodes[ i ];
  4862. if( node != null && !VisitedChanged.ContainsKey( node.OutputId ) )
  4863. {
  4864. bool result = node.RecursivePreviewUpdate();
  4865. if( result )
  4866. m_repaintIsDirty = true;
  4867. }
  4868. }
  4869. VisitedChanged.Clear();
  4870. if( m_repaintIsDirty )
  4871. {
  4872. m_repaintIsDirty = false;
  4873. Repaint();
  4874. }
  4875. }
  4876. public void ForceRepaint()
  4877. {
  4878. m_repaintCount += 1;
  4879. m_repaintIsDirty = true;
  4880. //Repaint();
  4881. }
  4882. public void ForceUpdateFromMaterial() { m_forceUpdateFromMaterialFlag = true; }
  4883. void UseCurrentEvent()
  4884. {
  4885. m_currentEvent.Use();
  4886. }
  4887. public void OnBeforeSerialize()
  4888. {
  4889. //if ( !UIUtils.SerializeFromUndo() )
  4890. //{
  4891. // m_mainGraphInstance.DeSelectAll();
  4892. //}
  4893. if( DebugConsoleWindow.UseShaderPanelsInfo )
  4894. {
  4895. if( m_nodeParametersWindow != null )
  4896. m_nodeParametersWindowMaximized = m_nodeParametersWindow.IsMaximized;
  4897. if( m_paletteWindow != null )
  4898. m_paletteWindowMaximized = m_paletteWindow.IsMaximized;
  4899. }
  4900. }
  4901. public void OnAfterDeserialize()
  4902. {
  4903. m_afterDeserializeFlag = true;
  4904. //m_customGraph = null;
  4905. if( DebugConsoleWindow.UseShaderPanelsInfo )
  4906. {
  4907. if( m_nodeParametersWindow != null )
  4908. m_nodeParametersWindow.IsMaximized = m_nodeParametersWindowMaximized;
  4909. if( m_paletteWindow != null )
  4910. m_paletteWindow.IsMaximized = m_paletteWindowMaximized;
  4911. }
  4912. }
  4913. void OnDestroy()
  4914. {
  4915. m_ctrlSCallback = false;
  4916. Destroy();
  4917. }
  4918. public override void OnDisable()
  4919. {
  4920. base.OnDisable();
  4921. m_ctrlSCallback = false;
  4922. //EditorApplication.update -= UpdateTime;
  4923. EditorApplication.update -= UpdateNodePreviewListAndTime;
  4924. EditorApplication.update -= IOUtils.UpdateIO;
  4925. for( int i = 0; i < IOUtils.AllOpenedWindows.Count; i++ )
  4926. {
  4927. if( IOUtils.AllOpenedWindows[ i ] != this )
  4928. {
  4929. EditorApplication.update += IOUtils.UpdateIO;
  4930. break;
  4931. }
  4932. }
  4933. }
  4934. void OnEmptyGraphDetected( ParentGraph graph )
  4935. {
  4936. if( m_delayedLoadObject != null )
  4937. {
  4938. LoadObject( m_delayedLoadObject );
  4939. m_delayedLoadObject = null;
  4940. Repaint();
  4941. }
  4942. else
  4943. {
  4944. if( !string.IsNullOrEmpty( Lastpath ) )
  4945. {
  4946. Shader shader = AssetDatabase.LoadAssetAtPath<Shader>( Lastpath );
  4947. if( shader == null )
  4948. {
  4949. Material material = AssetDatabase.LoadAssetAtPath<Material>( Lastpath );
  4950. if( material != null )
  4951. {
  4952. LoadDroppedObject( true, material.shader, material, null );
  4953. }
  4954. else
  4955. {
  4956. AmplifyShaderFunction function = AssetDatabase.LoadAssetAtPath<AmplifyShaderFunction>( Lastpath );
  4957. if( function != null )
  4958. {
  4959. LoadDroppedObject( true, null, null, function );
  4960. }
  4961. }
  4962. }
  4963. else
  4964. {
  4965. LoadDroppedObject( true, shader, null, null );
  4966. }
  4967. Repaint();
  4968. }
  4969. }
  4970. }
  4971. public void ForceMaterialsToUpdate( ref Dictionary<string, string> availableMaterials )
  4972. {
  4973. m_forcingMaterialUpdateOp = true;
  4974. m_forcingMaterialUpdateFlag = true;
  4975. m_materialsToUpdate.Clear();
  4976. foreach( KeyValuePair<string, string> kvp in availableMaterials )
  4977. {
  4978. Material material = AssetDatabase.LoadAssetAtPath<Material>( AssetDatabase.GUIDToAssetPath( kvp.Value ) );
  4979. if( material != null )
  4980. {
  4981. m_materialsToUpdate.Add( material );
  4982. }
  4983. }
  4984. }
  4985. public void SetOutdatedShaderFromTemplate()
  4986. {
  4987. m_outdatedShaderFromTemplateLoaded = true;
  4988. }
  4989. public void ReplaceMasterNode( MasterNodeCategoriesData data, bool cacheMasterNodes )
  4990. {
  4991. // save connection list before switching
  4992. m_savedList.Clear();
  4993. int count = m_mainGraphInstance.CurrentMasterNode.InputPorts.Count;
  4994. for( int i = 0; i < count; i++ )
  4995. {
  4996. if( m_mainGraphInstance.CurrentMasterNode.InputPorts[ i ].IsConnected )
  4997. {
  4998. string name = m_mainGraphInstance.CurrentMasterNode.InputPorts[ i ].Name;
  4999. OutputPort op = m_mainGraphInstance.CurrentMasterNode.InputPorts[ i ].GetOutputConnection();
  5000. if( !m_savedList.ContainsKey( name ) )
  5001. {
  5002. m_savedList.Add( name, op );
  5003. }
  5004. }
  5005. }
  5006. m_replaceMasterNodeType = data.Category;
  5007. m_replaceMasterNode = true;
  5008. m_replaceMasterNodeData = data.Name;
  5009. m_replaceMasterNodeDataFromCache = cacheMasterNodes;
  5010. if( cacheMasterNodes )
  5011. {
  5012. m_clipboard.AddMultiPassNodesToClipboard( m_mainGraphInstance.MultiPassMasterNodes.NodesList, true, -1 );
  5013. for( int i = 0; i < m_mainGraphInstance.LodMultiPassMasternodes.Count; i++ )
  5014. {
  5015. if( m_mainGraphInstance.LodMultiPassMasternodes[ i ].Count > 0 )
  5016. m_clipboard.AddMultiPassNodesToClipboard( m_mainGraphInstance.LodMultiPassMasternodes[ i ].NodesList, false, i );
  5017. }
  5018. }
  5019. }
  5020. void CheckNodeReplacement()
  5021. {
  5022. if( m_replaceMasterNode )
  5023. {
  5024. m_replaceMasterNode = false;
  5025. switch( m_replaceMasterNodeType )
  5026. {
  5027. default:
  5028. case AvailableShaderTypes.SurfaceShader:
  5029. {
  5030. SetStandardShader();
  5031. if( IOUtils.OnShaderTypeChangedEvent != null )
  5032. {
  5033. IOUtils.OnShaderTypeChangedEvent( m_mainGraphInstance.CurrentShader, false, string.Empty );
  5034. }
  5035. }
  5036. break;
  5037. case AvailableShaderTypes.Template:
  5038. {
  5039. TemplateDataParent templateData = m_templatesManager.GetTemplate( m_replaceMasterNodeData );
  5040. if( m_replaceMasterNodeDataFromCache )
  5041. {
  5042. m_mainGraphInstance.CrossCheckTemplateNodes( templateData, m_mainGraphInstance.MultiPassMasterNodes.NodesList , -1 );
  5043. for( int i = 0; i < m_mainGraphInstance.LodMultiPassMasternodes.Count; i++ )
  5044. {
  5045. if( m_mainGraphInstance.LodMultiPassMasternodes[ i ].Count > 0 )
  5046. m_mainGraphInstance.CrossCheckTemplateNodes( templateData, m_mainGraphInstance.LodMultiPassMasternodes[ i ].NodesList, i );
  5047. }
  5048. //Getting data from clipboard must be done after cross check all lists
  5049. m_clipboard.GetMultiPassNodesFromClipboard( m_mainGraphInstance.MultiPassMasterNodes.NodesList,-1 );
  5050. for( int i = 0; i < m_mainGraphInstance.LodMultiPassMasternodes.Count; i++ )
  5051. {
  5052. if( m_mainGraphInstance.LodMultiPassMasternodes[ i ].Count > 0 )
  5053. m_clipboard.GetMultiPassNodesFromClipboard( m_mainGraphInstance.LodMultiPassMasternodes[i].NodesList, i );
  5054. }
  5055. m_clipboard.ResetMultipassNodesData();
  5056. }
  5057. else
  5058. {
  5059. SetTemplateShader( m_replaceMasterNodeData, false );
  5060. }
  5061. if( IOUtils.OnShaderTypeChangedEvent != null )
  5062. {
  5063. IOUtils.OnShaderTypeChangedEvent( m_mainGraphInstance.CurrentShader, true, templateData.GUID );
  5064. }
  5065. }
  5066. break;
  5067. }
  5068. }
  5069. else if( m_outdatedShaderFromTemplateLoaded )
  5070. {
  5071. m_outdatedShaderFromTemplateLoaded = false;
  5072. TemplateMultiPassMasterNode masterNode = m_mainGraphInstance.CurrentMasterNode as TemplateMultiPassMasterNode;
  5073. if( masterNode != null )
  5074. {
  5075. ReplaceMasterNode( masterNode.CurrentCategoriesData, true );
  5076. }
  5077. }
  5078. // restore possible connections by name
  5079. if( m_savedList.Count > 0 )
  5080. {
  5081. foreach( var item in m_savedList )
  5082. {
  5083. string name = item.Key;
  5084. OutputPort op = item.Value;
  5085. InputPort ip = m_mainGraphInstance.CurrentMasterNode.InputPorts.Find( x => x.Name == name );
  5086. if( op != null && ip != null && ip.Visible )
  5087. {
  5088. var iNode = UIUtils.GetNode( ip.NodeId );
  5089. var oNode = UIUtils.GetNode( op.NodeId );
  5090. ip.ConnectTo( oNode.UniqueId, op.PortId, op.DataType, false );
  5091. op.ConnectTo( iNode.UniqueId, ip.PortId, ip.DataType, ip.TypeLocked );
  5092. iNode.OnInputPortConnected( ip.PortId, oNode.UniqueId, op.PortId );
  5093. oNode.OnOutputPortConnected( op.PortId, iNode.UniqueId, ip.PortId );
  5094. }
  5095. }
  5096. }
  5097. m_savedList.Clear();
  5098. }
  5099. public Vector2 TranformPosition( Vector2 pos )
  5100. {
  5101. return pos * m_cameraZoom - m_cameraOffset;
  5102. }
  5103. public void UpdateTabTitle()
  5104. {
  5105. if( m_isShaderFunctionWindow )
  5106. {
  5107. AmplifyShaderFunction openedShaderFunction = m_mainGraphInstance.CurrentShaderFunction;
  5108. if( openedShaderFunction != null )
  5109. {
  5110. this.titleContent.text = GenerateTabTitle( openedShaderFunction.FunctionName );
  5111. }
  5112. }
  5113. else
  5114. {
  5115. if( m_selectionMode == ASESelectionMode.Material )
  5116. {
  5117. this.titleContent.text = GenerateTabTitle( m_mainGraphInstance.CurrentMaterial.name );
  5118. }
  5119. else
  5120. {
  5121. this.titleContent.text = GenerateTabTitle( m_mainGraphInstance.CurrentShader.name );
  5122. }
  5123. }
  5124. }
  5125. public ParentGraph CustomGraph
  5126. {
  5127. get { return m_customGraph; }
  5128. set { m_customGraph = value; }
  5129. }
  5130. public ParentGraph CurrentGraph
  5131. {
  5132. get
  5133. {
  5134. if( m_customGraph != null )
  5135. return m_customGraph;
  5136. return m_mainGraphInstance;
  5137. }
  5138. }
  5139. public void RefreshAvaibleNodes()
  5140. {
  5141. if( m_contextMenu != null && m_mainGraphInstance != null )
  5142. {
  5143. m_contextMenu.RefreshNodes( m_mainGraphInstance );
  5144. m_paletteWindow.ForceUpdate = true;
  5145. m_contextPalette.ForceUpdate = true;
  5146. m_refreshAvailableNodes = false;
  5147. }
  5148. }
  5149. public void LateRefreshAvailableNodes()
  5150. {
  5151. m_refreshAvailableNodes = true;
  5152. }
  5153. public ParentGraph OutsideGraph { get { return m_mainGraphInstance; } }
  5154. public bool ShaderIsModified
  5155. {
  5156. get { return m_shaderIsModified; }
  5157. set
  5158. {
  5159. m_shaderIsModified = value && UIUtils.DirtyMask;
  5160. m_toolsWindow.SetStateOnButton( ToolButtonType.Save, m_shaderIsModified ? 1 : 0 );
  5161. if( !IsShaderFunctionWindow )
  5162. {
  5163. MasterNode masterNode = m_mainGraphInstance.CurrentMasterNode;
  5164. if( masterNode != null && masterNode.CurrentShader != null )
  5165. {
  5166. m_toolsWindow.SetStateOnButton( ToolButtonType.Update, ShaderIsModified ? 0 : 2, ShaderIsModified ? ShaderIsModifiedMessage : ShaderIsNotModified );
  5167. UpdateTabTitle( masterNode.ShaderName, m_shaderIsModified );
  5168. }
  5169. else
  5170. {
  5171. m_toolsWindow.SetStateOnButton( ToolButtonType.Update, 1 );
  5172. }
  5173. //if( m_mainGraphInstance.CurrentStandardSurface != null )
  5174. // UpdateTabTitle( m_mainGraphInstance.CurrentStandardSurface.ShaderName, m_shaderIsModified );
  5175. }
  5176. else
  5177. {
  5178. m_toolsWindow.SetStateOnButton( ToolButtonType.Update, m_shaderIsModified ? 0 : 2 );
  5179. if( m_mainGraphInstance.CurrentShaderFunction != null )
  5180. UpdateTabTitle( m_mainGraphInstance.CurrentShaderFunction.FunctionName, m_shaderIsModified );
  5181. }
  5182. }
  5183. }
  5184. public void MarkToRepaint() { m_repaintIsDirty = true; }
  5185. public void RequestSave() { m_markedToSave = true; }
  5186. public void RequestRepaint() { m_repaintIsDirty = true; }
  5187. public OptionsWindow Options { get { return m_optionsWindow; } }
  5188. public GraphContextMenu ContextMenuInstance { get { return m_contextMenu; } set { m_contextMenu = value; } }
  5189. public ShortcutsManager ShortcutManagerInstance { get { return m_shortcutManager; } }
  5190. public bool GlobalPreview
  5191. {
  5192. get { return m_globalPreview; }
  5193. set { m_globalPreview = value; }
  5194. }
  5195. public bool GlobalShowInternalData
  5196. {
  5197. get { return m_globalShowInternalData; }
  5198. set { m_globalShowInternalData = value; }
  5199. }
  5200. public double EditorTime
  5201. {
  5202. get { return m_time; }
  5203. set { m_time = value; }
  5204. }
  5205. public ASESelectionMode CurrentSelection
  5206. {
  5207. get { return m_selectionMode; }
  5208. set
  5209. {
  5210. m_selectionMode = value;
  5211. switch( m_selectionMode )
  5212. {
  5213. default:
  5214. case ASESelectionMode.Shader:
  5215. {
  5216. m_toolsWindow.BorderStyle = UIUtils.GetCustomStyle( CustomStyle.ShaderBorder );
  5217. }
  5218. break;
  5219. case ASESelectionMode.Material:
  5220. {
  5221. m_toolsWindow.BorderStyle = UIUtils.GetCustomStyle( CustomStyle.MaterialBorder );
  5222. }
  5223. break;
  5224. case ASESelectionMode.ShaderFunction:
  5225. {
  5226. m_toolsWindow.BorderStyle = UIUtils.GetCustomStyle( CustomStyle.ShaderFunctionBorder );
  5227. }
  5228. break;
  5229. }
  5230. }
  5231. }
  5232. public bool LiveShaderEditing
  5233. {
  5234. get { return m_liveShaderEditing; }
  5235. set
  5236. {
  5237. m_liveShaderEditing = value;
  5238. m_innerEditorVariables.LiveMode = m_liveShaderEditing;
  5239. UpdateLiveUI();
  5240. }
  5241. }
  5242. public NodeAvailability CurrentNodeAvailability
  5243. {
  5244. get { return m_currentNodeAvailability; }
  5245. set
  5246. {
  5247. NodeAvailability cache = m_currentNodeAvailability;
  5248. m_currentNodeAvailability = value;
  5249. if( cache != value )
  5250. RefreshAvaibleNodes();
  5251. }
  5252. }
  5253. public string GUID
  5254. {
  5255. get
  5256. {
  5257. if( m_isShaderFunctionWindow )
  5258. {
  5259. AmplifyShaderFunction openedShaderFunction = m_mainGraphInstance.CurrentShaderFunction;
  5260. return openedShaderFunction != null ? AssetDatabase.AssetPathToGUID( AssetDatabase.GetAssetPath( openedShaderFunction ) ) : string.Empty;
  5261. }
  5262. else
  5263. {
  5264. return m_mainGraphInstance.CurrentShader != null ? AssetDatabase.AssetPathToGUID( AssetDatabase.GetAssetPath( m_mainGraphInstance.CurrentShader ) ) : string.Empty;
  5265. }
  5266. }
  5267. }
  5268. public List<Toast> Messages { get { return m_messages; } set { m_messages = value; } }
  5269. public float MaxMsgWidth { get { return m_maxMsgWidth; } set { m_maxMsgWidth = value; } }
  5270. public bool MaximizeMessages { get { return m_maximizeMessages; } set { m_maximizeMessages = value; } }
  5271. public void InvalidateAlt() { m_altAvailable = false; }
  5272. public PaletteWindow CurrentPaletteWindow { get { return m_paletteWindow; } }
  5273. public PreMadeShaders PreMadeShadersInstance { get { return m_preMadeShaders; } }
  5274. public Rect CameraInfo { get { return m_cameraInfo; } }
  5275. public Vector2 TranformedMousePos { get { return m_currentMousePos2D * m_cameraZoom - m_cameraOffset; } }
  5276. public Vector2 TranformedKeyEvtMousePos { get { return m_keyEvtMousePos2D * m_cameraZoom - m_cameraOffset; } }
  5277. public PalettePopUp PalettePopUpInstance { get { return m_palettePopup; } }
  5278. public DuplicatePreventionBuffer DuplicatePrevBufferInstance { get { return m_duplicatePreventionBuffer; } }
  5279. public NodeParametersWindow ParametersWindow { get { return m_nodeParametersWindow; } }
  5280. public NodeExporterUtils CurrentNodeExporterUtils { get { return m_nodeExporterUtils; } }
  5281. public AmplifyShaderFunction OpenedShaderFunction { get { return m_mainGraphInstance.CurrentShaderFunction; } }
  5282. public DrawInfo CameraDrawInfo { get { return m_drawInfo; } }
  5283. public string Lastpath { get { return m_lastpath; } set { m_lastpath = value; } }
  5284. public string LastOpenedLocation { get { return m_lastOpenedLocation; } set { m_lastOpenedLocation = value; } }
  5285. public float AvailableCanvasWidth { get { return ( m_cameraInfo.width - m_paletteWindow.RealWidth - m_nodeParametersWindow.RealWidth ); } }
  5286. public float AvailableCanvasHeight { get { return ( m_cameraInfo.height ); } }
  5287. public float CameraZoom { get { return m_cameraZoom; } set { m_cameraZoom = value; m_zoomChanged = true; } }
  5288. public int GraphCount { get { return m_graphCount; } set { m_graphCount = value; } }
  5289. public bool ForceAutoPanDir { get { return m_forceAutoPanDir; } set { m_forceAutoPanDir = value; } }
  5290. public bool OpenedAssetFromNode { get { return m_openedAssetFromNode; } set { m_openedAssetFromNode = value; } }
  5291. public bool IsShaderFunctionWindow { get { return m_isShaderFunctionWindow; } set { m_isShaderFunctionWindow = value; } }
  5292. public bool NodesLoadedCorrectly { get { return m_nodesLoadedCorrectly; } set { m_nodesLoadedCorrectly = value; } }
  5293. public double CurrentInactiveTime { get { return m_currentInactiveTime; } }
  5294. public string ReplaceMasterNodeData { get { return m_replaceMasterNodeData; } }
  5295. public AvailableShaderTypes ReplaceMasterNodeType { get { return m_replaceMasterNodeType; } }
  5296. public NodeWireReferencesUtils WireReferenceUtils { get { return m_wireReferenceUtils; } }
  5297. public ContextPalette WindowContextPallete { get { return m_contextPalette; } }
  5298. // This needs to go to UIUtils
  5299. public Texture2D WireTexture { get { return m_wireTexture; } }
  5300. public Event CurrentEvent { get { return m_currentEvent; } }
  5301. public string CurrentCommandName { get { return m_currentCommandName; } }
  5302. public InnerWindowEditorVariables InnerWindowVariables { get { return m_innerEditorVariables; } }
  5303. public TemplatesManager TemplatesManagerInstance { get { return m_templatesManager; } }
  5304. public Material CurrentMaterial { get { return CurrentGraph.CurrentMaterial; } }
  5305. public Shader CurrentShader { get { return CurrentGraph.CurrentShader; } }
  5306. public Clipboard ClipboardInstance { get { return m_clipboard; } }
  5307. }
  5308. }