*/}}

la_tns_kernel.c 205 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321
  1. /*
  2. * LaGUI: A graphical application framework.
  3. * Copyright (C) 2022-2023 Wu Yiming
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #define _GNU_SOURCE 1
  19. #include "la_5.h"
  20. #include <math.h>
  21. #include "freetype/ftadvanc.h"
  22. #ifdef LA_WITH_PNG
  23. #include <png.h>
  24. #endif
  25. #define HF 0.5
  26. #ifdef LA_USE_GLES
  27. void la_glUniform1f(int location, float v0){
  28. glUniform1fv(location,1,&v0);
  29. }
  30. #endif
  31. void tnsGet2DTextureSubImage(tnsTexture* t, int xoffset, int yoffset, uint32_t width, uint32_t height, int format, int type, size_t bufSize, void *pixels){
  32. int texture=t->GLTexHandle;
  33. #ifdef LA_USE_GLES
  34. int offscreen_framebuffer;
  35. glGenFramebuffers(1, &offscreen_framebuffer);
  36. glBindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer);
  37. glBindTexture(GL_TEXTURE_2D, texture);
  38. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
  39. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  40. if(status != GL_FRAMEBUFFER_COMPLETE) {
  41. logPrint("Failed to make complete framebuffer object in la_glGetTextureSubImage()", status);
  42. }
  43. glBindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer);
  44. glViewport(0, 0, t->Width, t->Height);
  45. glReadPixels(xoffset, yoffset, width, height, format, type, pixels);
  46. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  47. glDeleteFramebuffers(1, &offscreen_framebuffer);
  48. #else
  49. glGetTextureSubImage(texture,0,xoffset,yoffset,0,width,height,1,format,type,bufSize,pixels);
  50. #endif
  51. }
  52. void tnsClearTextureImage(tnsTexture* t, int tex_format, int tex_bits_type){
  53. int texture=t->GLTexHandle;
  54. #ifdef LA_USE_GLES
  55. int offscreen_framebuffer;
  56. glGenFramebuffers(1, &offscreen_framebuffer);
  57. glBindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer);
  58. glBindTexture(GL_TEXTURE_2D, texture);
  59. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
  60. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  61. if(status != GL_FRAMEBUFFER_COMPLETE) {
  62. logPrint("Failed to make complete framebuffer object in la_glGetTextureSubImage()", status);
  63. }
  64. glBindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer);
  65. glViewport(0, 0, t->Width, t->Height);
  66. glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT);
  67. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  68. glDeleteFramebuffers(1, &offscreen_framebuffer);
  69. #else
  70. glClearTexImage(t->GLTexHandle,0,tex_format,tex_bits_type,0);
  71. #endif
  72. }
  73. // 1 2
  74. // 7 9 11 13 14
  75. // 3 4
  76. // 8 10 12 15 16
  77. // 5 6
  78. real TNS_LCD_SEG_16[16][4]={
  79. {0,0,HF,0},{HF,0,1,0},{0,0.5,HF,0.5},{HF,0.5,1,0.5},{0,1,HF,1},{HF,1,1,1},
  80. {0,0,0,HF},{0,HF,0,1},{0.5,0,0.5,HF},{0.5,HF,0.5,1},{1,0,1,HF},{1,HF,1,1},
  81. {0,0,HF,HF},{1,0,HF,HF},{0,1,HF,HF},{1,1,HF,HF},
  82. };
  83. char TNS_LCD_MAP_16[][16]={
  84. {1,1,0,0,1,1,1,1,0,0,1,1,0,1,1,0},{0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0},//0-9
  85. {1,1,1,1,1,1,0,1,0,0,1,0,0,0,0,0},{1,1,1,1,1,1,0,0,0,0,1,1,0,0,0,0},
  86. {0,0,1,1,0,0,1,0,1,1,0,0,0,0,0,0},{1,1,1,1,1,1,1,0,0,0,0,1,0,0,0,0},
  87. {1,1,1,1,1,1,1,1,0,0,0,1,0,0,0,0},{1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,0},
  88. {1,1,1,1,1,1,1,1,0,0,1,1,0,0,0,0},{1,1,1,1,1,1,1,0,0,0,1,1,0,0,0,0},
  89. {1,1,1,1,0,0,1,1,0,0,1,1,0,0,0,0},{1,1,0,1,1,1,0,0,1,1,1,1,0,0,0,0},//A
  90. {1,1,0,0,1,1,1,1,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,1,1,1,1,0,0,0,0},
  91. {1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0},{1,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0},
  92. {1,1,0,1,1,1,1,1,0,0,0,1,0,0,0,0},{0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,0},
  93. {1,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0},{1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0},
  94. {0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,1},{0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0},
  95. {0,0,0,0,0,0,1,1,0,0,1,1,1,1,0,0},{0,0,0,0,0,0,1,1,0,0,1,1,1,0,0,1},
  96. {1,1,0,0,1,1,1,1,0,0,1,1,0,0,0,0},{1,1,1,1,0,0,1,1,0,0,1,0,0,0,0,0},
  97. {1,1,0,0,1,1,1,1,0,0,1,1,0,0,0,1},{1,1,1,1,0,0,1,1,0,0,1,0,0,0,0,1},
  98. {1,1,0,1,1,1,0,0,0,0,0,1,1,0,0,0},{1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0},
  99. {0,0,0,0,1,1,1,1,0,0,1,1,0,0,0,0},{0,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0},
  100. {0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1},{0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1},
  101. {0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,1,1,0},
  102. {0,0,1,0,1,1,0,1,0,1,0,0,0,0,0,0},{0,0,0,1,1,1,0,0,1,1,0,1,0,0,0,0},//a
  103. {0,0,1,1,1,1,0,1,0,0,0,0,0,0,0,0},{0,0,1,0,1,1,0,1,1,1,0,0,0,0,0,0},
  104. {0,0,1,0,1,1,0,1,0,0,0,0,0,0,1,0},{0,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0},
  105. {0,1,0,1,1,1,0,1,1,0,1,1,0,0,0,0},{0,0,1,0,0,1,1,1,0,1,0,0,0,0,0,0},
  106. {1,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0},{0,1,0,1,1,1,0,0,0,0,0,1,0,0,0,0},
  107. {0,0,1,1,0,0,0,1,1,0,0,0,0,0,0,1},{1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,0},
  108. {0,0,1,1,0,0,0,1,0,1,0,1,0,0,0,0},{0,0,1,0,0,1,0,1,0,1,0,0,0,0,0,0},
  109. {0,0,1,1,1,1,0,1,0,0,0,1,0,0,0,0},{1,1,0,1,0,0,0,0,1,1,1,0,0,0,0,0},
  110. {1,1,0,0,0,0,1,0,1,1,0,0,0,0,0,0},{0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0},
  111. {0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1},{0,0,1,1,0,1,0,0,1,1,0,0,0,0,0,0},
  112. {0,0,0,0,1,1,0,1,0,1,0,0,0,0,0,0},{0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0},
  113. {0,0,0,0,0,0,0,1,0,0,0,1,0,0,1,1},{0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1},
  114. {0,0,0,1,1,1,0,0,1,0,1,1,0,0,0,0},{0,0,1,0,1,1,0,0,0,0,0,0,0,0,1,0},
  115. };
  116. // 1
  117. // 4 6
  118. // 2
  119. // 5 7
  120. // 3
  121. real TNS_LCD_SEG_7[7][4]={ {0,0,1,0},{0,0.5,1,0.5},{0,1,1,1},
  122. {0,0,0,HF},{0,HF,0,1},{1,0,1,HF},{1,HF,1,1},
  123. };
  124. char TNS_LCD_MAP_7[][7]={
  125. {1,0,1,1,1,1,1},{0,0,0,0,0,1,1},{1,1,1,0,1,1,0},{1,1,1,0,0,1,1},{0,1,0,1,0,1,1},// 0-4
  126. {1,1,1,1,0,0,1},{1,1,1,1,1,0,1},{1,0,0,0,0,1,1},{1,1,1,1,1,1,1},{1,1,1,1,0,1,1},// 6-9
  127. };
  128. #undef HF
  129. int tKnlAttatchShader(tnsShader *tns);
  130. tnsShader *tKnlFindShader1i(int CustomIndex);
  131. void tKnlPushMatrix();
  132. void tKnlPopMatrix();
  133. laListHandle *tKnlGetTextureList();
  134. void tnsLoadIdentity44d(tnsMatrix44d m);
  135. void tnsMakeOrthoMatrix44d(tnsMatrix44d mProjection, real xMin, real xMax, real yMin, real yMax, real zMin, real zMax);
  136. void tnsMakePerspectiveMatrix44d(tnsMatrix44d mProjection, real fFov_rad, real fAspect, real zMin, real zMax);
  137. void tnsMakeTranslationMatrix44d(tnsMatrix44d mTrans, real x, real y, real z);
  138. void tnsMakeRotationMatrix44d(tnsMatrix44d m, real angle_rad, real x, real y, real z);
  139. void tnsMakeScaleMatrix44d(tnsMatrix44d m, real x, real y, real z);
  140. void tnsMultiply44d(tnsMatrix44d result, tnsMatrix44d l, tnsMatrix44d r);
  141. void tnsInitFirstLevel(tnsMatrixStack *tms);
  142. tnsMatrixStackItem *tKnlGetCurrentMatStackItem();
  143. void tnsAttach2DOffscreenBuffer(tnsOffscreen *target, GLuint attatchment, tnsTexture *use);
  144. void tnsDetach2DOffscreenBuffer(tnsOffscreen *target, GLuint which_attach_point);
  145. //=========================================================================================
  146. tnsMain *T;
  147. real DefaultZRange[2] = {0.1, 1000};
  148. //=======================================[SYS]
  149. extern LA MAIN;
  150. void InitGLRenderEnviornment(){
  151. glEnable(GL_SCISSOR_TEST);
  152. };
  153. #ifdef __linux__
  154. void tnsContextMakeCurrent(SYSGLCONTEXT context, SYSWINDOW win, void* gles_surf){
  155. #ifdef LA_USE_GLES
  156. eglMakeCurrent(MAIN.egl_dpy,gles_surf,gles_surf,context);
  157. if(gles_surf){ EGLSurface* surf=gles_surf; T->CurrentSurface=(*surf); }else{ T->CurrentSurface=0; }
  158. #else
  159. glXMakeContextCurrent(MAIN.dpy, win, win, context);
  160. #endif
  161. T->CurrentContext=context; T->CurrentWindow=win; tnsUnbindTexture(); tnsUseNoTexture();
  162. };
  163. #endif
  164. #ifdef _WIN32
  165. void tnsContextMakeCurrent(SYSGLCONTEXT context, SYSTEMDC hdc,void* unused){
  166. wglMakeCurrent(hdc, context); T->CurrentContext=context; T->CurrentDC=hdc;
  167. tnsUnbindTexture(); tnsUseNoTexture();
  168. };
  169. #endif
  170. #ifdef LA_USE_GLES
  171. void tnsContextMakeFBOCurrent(tnsOffscreen* off){
  172. tnsContextMakeCurrent(off->FboContext,off->FboWindow,off->FboSurface);
  173. }
  174. void tnsContextMakeWindowCurrent(laWindow* w){
  175. #ifdef LAGUI_ANDROID
  176. T->CurrentContext=MAIN.glc; T->CurrentSurface=MAIN.egl_surf;
  177. if (eglMakeCurrent(MAIN.egl_dpy, MAIN.egl_surf, MAIN.egl_surf, MAIN.glc) == EGL_FALSE) { logPrint("Android can't make current"); return; }
  178. return;
  179. #else
  180. tnsContextMakeCurrent(w->glc,w->win,w->egl_surf);
  181. #endif
  182. }
  183. #else
  184. void tnsContextMakeFBOCurrent(tnsOffscreen* off){
  185. #ifdef _WIN32
  186. tnsContextMakeCurrent(off->FboContext,off->FboDC,0);
  187. #else
  188. tnsContextMakeCurrent(off->FboContext,off->FboWindow,0);
  189. #endif
  190. }
  191. void tnsContextMakeWindowCurrent(laWindow* w){
  192. #ifdef _WIN32
  193. tnsContextMakeCurrent(w->glc,w->hdc,0);
  194. #else
  195. tnsContextMakeCurrent(w->glc,w->win,0);
  196. #endif
  197. }
  198. #endif
  199. void tnsSwitchToCurrentWindowContext(laWindow* w){
  200. tnsContextMakeWindowCurrent(w);
  201. };
  202. void tnsDeleteContext(SYSGLCONTEXT glc){
  203. #ifdef __linux__
  204. #ifdef LA_USE_GLES
  205. eglDestroyContext(MAIN.egl_dpy,glc);
  206. #else
  207. glXDestroyContext(MAIN.dpy,glc);
  208. #endif
  209. #endif
  210. #ifdef _WIN32
  211. wglDeleteContext(glc);
  212. #endif
  213. for(tnsOffscreen* o=T->Offscreens.pFirst;o;o=o->Item.pNext){
  214. if(o->FboContext==glc){ o->FboContext=0; }
  215. }
  216. }
  217. void tnsBindVertexArray(GLuint vao){
  218. T->CurrentVAO=vao; glBindVertexArray(vao);
  219. }
  220. void tnsViewportWithScissor(int x, int y, int w, int h){
  221. tnsShader *current_shader = 0;
  222. glEnable(GL_SCISSOR_TEST);
  223. glViewport(x, y, w, h); glScissor(x, y, w, h);
  224. T->vsx=x;T->vsy=y;T->vsw=w;T->vsh=h;
  225. if ((current_shader = T->CurrentShader)){
  226. tnsResetViewMatrix();
  227. tnsShaderApplyView(current_shader, tnsGetViewMatrix());
  228. tnsResetModelMatrix();
  229. tnsShaderApplyModel(current_shader, tnsGetModelMatrix());
  230. }
  231. }
  232. void tnsViewport(int x, int y, int w, int h){
  233. glViewport(x, y, w, h);
  234. }
  235. //Must At Origion!
  236. //void UseWindowMatrix_WithScissor(laWndPlacement* wp){
  237. // tnsViewportWithScissor(0, 0, VAL2_CLIENT_W_H(*wp));
  238. // SetMatrix2Di(0, VAL2_CLIENT_W_H(*wp), 0);
  239. //};
  240. //void UseBlockMatrix_WithScissor(laBlockPlacement* bp){
  241. // tnsViewportWithScissor(bp->UpperLeftX,
  242. // bp->ClientHeight - bp->LowerRightY,
  243. // bp->LowerRightX - bp->UpperLeftX,
  244. // bp->LowerRightY - bp->UpperLeftY);
  245. // SetMatrix2Di(0, bp->LowerRightX - bp->UpperLeftX,
  246. // 0, bp->UpperLeftY - bp->LowerRightY);
  247. //};
  248. void DrawWireRect2dp(real x, real y, real x2, real y2){
  249. real Verts[8];
  250. tnsMakeQuad2d(Verts, x, y, x2, y, x2, y2, x, y2);
  251. tnsVertexArray2d(Verts, 4);
  252. tnsPackAs(GL_LINE_LOOP);
  253. };
  254. void DrawWireRect4ds(real x, real y, real w, real h){
  255. real Verts[8];
  256. tnsMakeQuad2d(Verts, x, y, x + w, y, x + w, y + h, x, y + h);
  257. tnsVertexArray2d(Verts, 4);
  258. tnsPackAs(GL_LINE_LOOP);
  259. };
  260. void DrawWireRect4drs(real x, real y, real w, real h){
  261. real Verts[8];
  262. tnsMakeQuad2d(Verts, x, y, x + w, y, x + w, y - h, x, y - h);
  263. tnsVertexArray2d(Verts, 4);
  264. tnsPackAs(GL_LINE_LOOP);
  265. };
  266. void DrawSoildRect4drs(real x, real y, real w, real h){
  267. real Verts[8];
  268. tnsMakeQuad2d(Verts, x, y, x + w, y, x + w, y - h, x, y - h);
  269. tnsVertexArray2d(Verts, 4);
  270. tnsPackAs(GL_TRIANGLE_FAN);
  271. }
  272. void DrawWireCross4ds(real x, real y, real w, real h){
  273. real Verts[8];
  274. tnsMakeQuad2d(Verts, x, y, x + w, y + h, x + w, y, x, y + h);
  275. tnsVertexArray2d(Verts, 4);
  276. tnsPackAs(GL_LINES);
  277. };
  278. void DrawWireCross4drs(real x, real y, real w, real h){
  279. real Verts[8];
  280. tnsMakeQuad2d(Verts, x, y, x + w, y - h, x + w, y, x, y - h);
  281. tnsVertexArray2d(Verts, 4);
  282. tnsPackAs(GL_LINES);
  283. };
  284. void DrawGrid6f(real L, real R, real U, real B, real stepX, real stepY){
  285. //do nothing;
  286. }
  287. //=======================================[Shader]
  288. int tnsNextPowOf2(int i){
  289. int result = 2;
  290. while (result < i){
  291. result *= 2;
  292. }
  293. return result;
  294. }
  295. void tnsShaderMakeIndex(tnsShader *tns){
  296. int program;
  297. if (!tns) return;
  298. program = tns->glProgramID;
  299. tns->iModel = glGetUniformLocation(program, "mModel");
  300. tns->iProjection = glGetUniformLocation(program, "mProjection");
  301. tns->iProjectionInverse = glGetUniformLocation(program, "mProjectionInverse");
  302. tns->iView = glGetUniformLocation(program, "mView");
  303. //tns->iNormal = glGetUniformLocation(program, "mNormalScaler");
  304. tns->iShadow = glGetUniformLocation(program, "mShadow");
  305. tns->iVertex = glGetAttribLocation(program, "vVertex");
  306. tns->iNormal = glGetAttribLocation(program, "vNormal");
  307. tns->iColor = glGetAttribLocation(program, "vColor");
  308. tns->iUV = glGetAttribLocation(program, "vUV");
  309. tns->iTexColor = glGetUniformLocation(program, "TexColor");
  310. tns->iTexColorU = glGetUniformLocation(program, "TexColorUI");
  311. tns->iTexColorMS = glGetUniformLocation(program, "TexColorMS");
  312. if(tns->iTexColor>=0){glUniform1i(tns->iTexColor, 0);}
  313. if(tns->iTexColorMS>=0){glUniform1i(tns->iTexColorMS, 1);}
  314. if(tns->iTexColorU>=0){glUniform1i(tns->iTexColorU, 2);}
  315. tns->iTexNormal = glGetUniformLocation(program, "TexNormal");
  316. tns->iTexGPos = glGetUniformLocation(program, "TexGPos");
  317. tns->iMultiplyColor = glGetUniformLocation(program, "MultiplyColor");
  318. tns->iTextureMode = glGetUniformLocation(program, "TextureMode");
  319. tns->iColorMode = glGetUniformLocation(program, "ColorMode");
  320. tns->iHCYGamma = glGetUniformLocation(program, "HCYGamma");
  321. tns->iSampleAmount = glGetUniformLocation(program, "SampleAmount");
  322. tns->iUseNormal = glGetUniformLocation(program, "UseNormal");
  323. tns->iOutputColorSpace=glGetUniformLocation(program, "OutputColorSpace");
  324. tns->iInputColorSpace=glGetUniformLocation(program, "InputColorSpace");
  325. tns->iShowStripes=glGetUniformLocation(program, "ShowStripes");
  326. tns->iComposing=glGetUniformLocation(program, "Composing");
  327. tns->iComposingGamma=glGetUniformLocation(program, "ComposingGamma");
  328. tns->iComposingBlackpoint=glGetUniformLocation(program, "ComposingBlackpoint");
  329. tns->iDoOffset = glGetUniformLocation(program, "DoOffset");
  330. tns->iUseHalftone = glGetUniformLocation(program, "UseHalftone");
  331. tns->iHalftoneSize = glGetUniformLocation(program, "HalftoneSize");
  332. tns->uViewDir = glGetUniformLocation(program, "uViewDir");
  333. tns->uViewPos = glGetUniformLocation(program, "uViewPos");
  334. tns->uNear = glGetUniformLocation(program, "uNear");
  335. tns->uFar = glGetUniformLocation(program, "uFar");
  336. tns->uFOV = glGetUniformLocation(program, "uFOV");
  337. }
  338. void tnsShaderApplyProjection(tnsShader *tns, tnsMatrix44d m){
  339. tnsMatrix44f mf;
  340. if (T->BindedShader != tns){ glUseProgram(tns->glProgramID); T->BindedShader = tns; }
  341. tnsConvert44df(m, mf);
  342. if(tns->iProjection>-1) glUniformMatrix4fv(tns->iProjection, 1, 0, mf);
  343. }
  344. void tnsShaderApplyProjectionInverse(tnsShader *tns, tnsMatrix44d m){
  345. tnsMatrix44f mf;
  346. tnsMatrix44d i;
  347. if (T->BindedShader != tns){ glUseProgram(tns->glProgramID); T->BindedShader = tns; }
  348. tnsInverse44d(i, m);
  349. tnsConvert44df(i, mf);
  350. if(tns->iProjectionInverse>-1) glUniformMatrix4fv(tns->iProjectionInverse, 1, 0, mf);
  351. }
  352. void tnsShaderApplyModel(tnsShader *tns, tnsMatrix44d m){
  353. tnsMatrix44f mf;
  354. if (T->BindedShader != tns){ glUseProgram(tns->glProgramID); T->BindedShader = tns; }
  355. tnsConvert44df(m, mf);
  356. if(tns->iModel>-1) glUniformMatrix4fv(tns->iModel, 1, 0, mf);
  357. }
  358. void tnsShaderApplyView(tnsShader *tns, tnsMatrix44d m){
  359. tnsMatrix44f mf;
  360. if (T->BindedShader != tns){ glUseProgram(tns->glProgramID); T->BindedShader = tns; }
  361. tnsConvert44df(m, mf);
  362. if(tns->iView>-1) glUniformMatrix4fv(tns->iView, 1, 0, mf);
  363. }
  364. void tnsShaderApplyNormalScaler(tnsShader *tns, tnsMatrix44d m){
  365. tnsMatrix44f mf;
  366. if (tns->iNormal == -1) return;
  367. if (T->BindedShader != tns){ glUseProgram(tns->glProgramID); T->BindedShader = tns; }
  368. tnsConvert44df(m, mf);
  369. glUniformMatrix4fv(tns->iNormal, 1, 0, mf);
  370. }
  371. void tnsShaderApplyShadowMatrix(tnsShader *tns, tnsMatrix44d m){
  372. tnsMatrix44f mf;
  373. if (tns->iShadow == -1) return;
  374. if (T->BindedShader != tns){ glUseProgram(tns->glProgramID); T->BindedShader = tns; }
  375. tnsConvert44df(m, mf);
  376. glUniformMatrix4fv(tns->iShadow, 1, 0, mf);
  377. }
  378. char* tnsEnsureShaderCommoms(char* Content, char* Library, char* Material){
  379. char* c=0,*c1=0;
  380. c1=strSub(Content,"#with TNS_SHADER_COLOR_COMMON",TNS_SHADER_COLOR_COMMON);
  381. c=strSub(c1,"#with LA_SHADER_LIB_FXAA",LA_SHADER_LIB_FXAA); free(c1);
  382. c1=strSub(c,"#with TNS_SHADER_MATERIAL",Material?Material:""); free(c);
  383. c=strSub(c1,"#with TNS_SHADER_LIBRARY",Library?Library:""); free(c1);
  384. #ifdef LA_USE_GLES
  385. const char uint_texture_selection[] = "#define GLES_UINT_TEXTURE";
  386. #else
  387. const char uint_texture_selection[] = "";
  388. #endif
  389. c1=strSub(c,"#with TNS_GLES_UINT_TEXTURE",uint_texture_selection); free(c);
  390. return c1;
  391. }
  392. int tnsNewVertexShader(char *Content){
  393. int status = 0;
  394. char error[8192]={0};
  395. GLuint VertexShaderObject;
  396. tnsShader *s = 0;
  397. if (!Content) return -1;
  398. VertexShaderObject = glCreateShader(GL_VERTEX_SHADER);
  399. char* UseContent=tnsEnsureShaderCommoms(Content,0,0);
  400. glShaderSource(VertexShaderObject, 1, &UseContent, 0);
  401. glCompileShader(VertexShaderObject);
  402. glGetShaderiv(VertexShaderObject, GL_COMPILE_STATUS, &status);
  403. if (status == GL_FALSE){
  404. glGetShaderInfoLog(VertexShaderObject, sizeof(error), 0, error); logPrint("Vertex shader error:\n%s", error);
  405. glDeleteShader(VertexShaderObject); free(UseContent);
  406. return -1;
  407. } else {
  408. glGetShaderInfoLog(VertexShaderObject, sizeof(error), 0, error); if(error[0]) logPrint("Vertex shader info:\n%s", error);
  409. }
  410. free(UseContent);
  411. return VertexShaderObject;
  412. }
  413. int tnsNewFragmentShaderMaterial(char *Content, char* Library, char* Material){
  414. int status = 0;
  415. char error[8192]={0};
  416. GLuint FragmentShaderObject;
  417. tnsShader *s = 0;
  418. if (!Content) return -1;
  419. FragmentShaderObject = glCreateShader(GL_FRAGMENT_SHADER);
  420. char* UseContent=tnsEnsureShaderCommoms(Content,Library,Material);
  421. glShaderSource(FragmentShaderObject, 1, &UseContent, 0);
  422. glCompileShader(FragmentShaderObject);
  423. glGetShaderiv(FragmentShaderObject, GL_COMPILE_STATUS, &status);
  424. if (status == GL_FALSE){
  425. glGetShaderInfoLog(FragmentShaderObject, sizeof(error), 0, error); logPrint("Fragment shader error:\n%s", error);
  426. glDeleteShader(FragmentShaderObject); free(UseContent);
  427. return -1;
  428. } else {
  429. glGetShaderInfoLog(FragmentShaderObject, sizeof(error), 0, error); if (error[0]) logPrint("Fragment shader info:\n%s", error);
  430. }
  431. free(UseContent);
  432. return FragmentShaderObject;
  433. }
  434. int tnsNewFragmentShader(char *Content){
  435. return tnsNewFragmentShaderMaterial(Content,0,0);
  436. }
  437. int tnsNewGeometryShader(char *Content){
  438. #ifndef LAGUI_ANDROID
  439. int status = 0;
  440. char error[8192]={0};
  441. GLuint GeometryShaderObject;
  442. tnsShader *s = 0;
  443. if (!Content) return -1;
  444. GeometryShaderObject = glCreateShader(GL_GEOMETRY_SHADER);
  445. char* UseContent=tnsEnsureShaderCommoms(Content,0,0);
  446. glShaderSource(GeometryShaderObject, 1, &UseContent, 0);
  447. glCompileShader(GeometryShaderObject);
  448. glGetShaderiv(GeometryShaderObject, GL_COMPILE_STATUS, &status);
  449. if (status == GL_FALSE){
  450. glGetShaderInfoLog(GeometryShaderObject, sizeof(error), 0, error); logPrint("Geometry shader error:\n%s", error);
  451. glDeleteShader(GeometryShaderObject); free(UseContent);
  452. return -1;
  453. } else {
  454. glGetShaderInfoLog(GeometryShaderObject, sizeof(error), 0, error); if(error[0]) logPrint("Geometry shader info:\n%s", error);
  455. }
  456. free(UseContent);
  457. return GeometryShaderObject;
  458. #endif
  459. return 0;
  460. }
  461. tnsShader *tnsNewShaderProgram(int VertexShaderID, int FragmentShaderID, int GeometryShaderID){
  462. int vso = VertexShaderID;
  463. int fso = FragmentShaderID;
  464. int gso = GeometryShaderID;
  465. tnsShader *tns = 0;
  466. int status = 0;
  467. char error[8192];
  468. if (!vso || !fso) return 0;
  469. tns = CreateNew(tnsShader);
  470. tns->vtShaderID = vso;
  471. tns->fgShaderID = fso;
  472. tns->glProgramID = glCreateProgram();
  473. glAttachShader(tns->glProgramID, vso);
  474. glAttachShader(tns->glProgramID, fso);
  475. if (GeometryShaderID > -1){ glAttachShader(tns->glProgramID, gso); tns->gsShaderID=gso; }
  476. glLinkProgram(tns->glProgramID);
  477. glGetProgramiv(tns->glProgramID, GL_LINK_STATUS, &status);
  478. if (status == GL_FALSE){
  479. glGetProgramInfoLog(tns->glProgramID, sizeof(error), 0, error);
  480. printf("Shader Linking error:\n%s", error);
  481. glDetachShader(tns->glProgramID, vso);
  482. glDetachShader(tns->glProgramID, fso);
  483. glDeleteShader(vso);
  484. glDeleteShader(fso);
  485. glDeleteProgram(tns->glProgramID);
  486. FreeMem(tns);
  487. return 0;
  488. }
  489. glUseProgram(tns->glProgramID);
  490. tnsShaderMakeIndex(tns);
  491. return tns;
  492. }
  493. int tnsEnableShader(int index){
  494. tnsMatrixStackItem *tmsi;
  495. tnsShader *tns = tKnlFindShader1i(index);
  496. if (!tns){
  497. glUseProgram(0);
  498. T->CurrentShader = 0;
  499. T->BindedShader = 0;
  500. return 0;
  501. }
  502. glUseProgram(tns->glProgramID);
  503. T->CurrentShader = tns;
  504. T->BindedShader = tns;
  505. tmsi = tKnlGetCurrentMatStackItem();
  506. tnsShaderApplyProjection(tns, tmsi->projection);
  507. tnsShaderApplyView(tns, tmsi->view);
  508. tnsShaderApplyModel(tns, tmsi->model); tnsUseShader(tns);
  509. return 1;
  510. }
  511. int tnsEnableShaderv(tnsShader *shader){
  512. tnsMatrixStackItem *tmsi;
  513. tnsShader *s = shader;
  514. if (!s){ glUseProgram(0); T->CurrentShader = 0;T->BindedShader = 0; return 0; }
  515. glUseProgram(s->glProgramID);
  516. T->CurrentShader = s;
  517. T->BindedShader = s;
  518. tmsi = tKnlGetCurrentMatStackItem();
  519. tnsShaderApplyProjection(s, tmsi->projection);
  520. tnsShaderApplyProjectionInverse(s, tmsi->projection);
  521. tnsShaderApplyView(s, tmsi->view);
  522. tnsShaderApplyModel(s, tmsi->model); tnsUseShader(s);
  523. if(s->iUseNormal>-1) glUniform1i(s->iUseNormal,T->SetUseNormal);
  524. if(s->uViewPos>-1) glUniform3fv(s->uViewPos,1,T->SetViewPos);
  525. if(s->uViewDir>-1) glUniform3fv(s->uViewDir,1,T->SetViewDir);
  526. if(s->iUseHalftone>-1) glUniform1f(s->iUseHalftone,T->SetUseHalftone);
  527. if(s->iHalftoneSize>-1) glUniform1f(s->iHalftoneSize,T->SetHalftoneSize);
  528. //if(s->iTextureMode) glUniform1i(s->iTextureMode,T->StateTextureMode);
  529. //if(cs->iSampleAmount) glUniform1i(cs->iSampleAmount);
  530. return 1;
  531. }
  532. int tnsUseShader(tnsShader *shader){
  533. T->StateShader = shader;
  534. }
  535. void tnsDeleteShaderProgram(tnsShader* s){
  536. tnsUseShader(0); tnsEnableShaderv(0);
  537. if(s->vtShaderID>-1) glDeleteShader(s->vtShaderID);
  538. if(s->fgShaderID>-1) glDeleteShader(s->fgShaderID);
  539. if(s->gsShaderID>-1) glDeleteShader(s->gsShaderID);
  540. glDeleteProgram(s->glProgramID);
  541. free(s);
  542. }
  543. void tnsUseImmShader(){
  544. T->StateShader = T->immShader;
  545. }
  546. void tnsUseTransparentGridShader(){
  547. T->StateShader = T->TransparentGridShader;
  548. }
  549. void tnsUseExtraBufferShader(){
  550. T->StateShader = T->ExtraBuffersShader;
  551. }
  552. void tnsUseRayShader(){
  553. T->StateShader = T->RayShader;
  554. }
  555. void tnsUseShadowShader(){
  556. T->StateShader = T->ShadowShader;
  557. }
  558. void tnsUseSceneShader(){
  559. T->StateShader = T->SceneShader;
  560. }
  561. //=======================================[MAT]
  562. int tnsLineIntersectTest2d(tnsVector2d a1, tnsVector2d a2, tnsVector2d b1, tnsVector2d b2, double *aRatio){
  563. double k1, k2;
  564. double x;
  565. double y;
  566. double Ratio;
  567. double xDiff = (a2[0] - a1[0]); // +DBL_EPSILON;
  568. double xDiff2 = (b2[0] - b1[0]);
  569. if (xDiff == 0){
  570. if (xDiff2 == 0){
  571. *aRatio = 0;
  572. return 0;
  573. }
  574. double r2 = tnsGetRatiod(b1[0], b2[0], a1[0]);
  575. y = tnsLinearItp(b1[1], b2[1], r2);
  576. *aRatio = Ratio = tnsGetRatiod(a1[1], a2[1], y);
  577. }else{
  578. if (xDiff2 == 0){
  579. Ratio = tnsGetRatiod(a1[0], a2[0], b1[0]);
  580. //y = tnsLinearItp(a1[1], a2[1], r2);
  581. *aRatio = Ratio;
  582. }else{
  583. k1 = (a2[1] - a1[1]) / xDiff;
  584. k2 = (b2[1] - b1[1]) / xDiff2;
  585. if ((k1 == k2)) return 0;
  586. x = (a1[1] - b1[1] - k1 * a1[0] + k2 * b1[0]) / (k2 - k1);
  587. Ratio = (x - a1[0]) / xDiff;
  588. *aRatio = Ratio;
  589. }
  590. }
  591. if (b1[0] == b2[0]){
  592. y = tnsLinearItp(a1[1], a2[1], Ratio);
  593. if (y > TNS_MAX2(b1[1], b2[1]) || y < TNS_MIN2(b1[1], b2[1])) return 0;
  594. }else if (Ratio <= 0 || Ratio > 1 ||
  595. (b1[0] > b2[0] && x > b1[0]) ||
  596. (b1[0] < b2[0] && x < b1[0]) ||
  597. (b2[0] > b1[0] && x > b2[0]) ||
  598. (b2[0] < b1[0] && x < b2[0]))
  599. return 0;
  600. return 1;
  601. }
  602. double tnsGetLineZ(tnsVector3d L, tnsVector3d R, real Ratio){
  603. //double z = 1 / tnsLinearItp(1 / L[2], 1 / R[2], Ratio);
  604. double z = tnsLinearItp(L[2], R[2], Ratio);
  605. return z;
  606. }
  607. double tnsGetLineZPoint(tnsVector3d L, tnsVector3d R, tnsVector3d FromL){
  608. double r = (FromL[0] - L[0]) / (R[0] - L[0]);
  609. return tnsLinearItp(L[2], R[2], r);
  610. //return 1 / tnsLinearItp(1 / L[2], 1 / R[2], r);
  611. }
  612. double tnsGetRatio3d(tnsVector3d L, tnsVector3d R, tnsVector3d FromL){
  613. double r = (FromL[0] - L[0]) / (R[0] - L[0]);
  614. return r;
  615. }
  616. double tnsGetRatiod(real L, real R, real FromL){
  617. double r = (FromL - L) / (R - L);
  618. return r;
  619. }
  620. real tnsInterpolate(real L, real R, real T){
  621. return tnsLinearItp(L, R, T);
  622. }
  623. void tnsInterpolate2dv(real *L, real *R, real T, real *Result){
  624. Result[0] = tnsLinearItp(L[0], R[0], T);
  625. Result[1] = tnsLinearItp(L[1], R[1], T);
  626. }
  627. void tnsInterpolate3dv(real *L, real *R, real T, real *Result){
  628. Result[0] = tnsLinearItp(L[0], R[0], T);
  629. Result[1] = tnsLinearItp(L[1], R[1], T);
  630. Result[2] = tnsLinearItp(L[2], R[2], T);
  631. }
  632. void tnsInterpolateTripple2d(tnsVector2d v1, tnsVector2d v2, tnsVector2d v3, real ratio, tnsVector2d result){
  633. tnsVector2d i1,i2;
  634. tnsInterpolate2dv(v1,v2,ratio,i1);
  635. tnsInterpolate2dv(v2,v3,ratio,i2);
  636. tnsInterpolate2dv(i1,i2,ratio,result);
  637. }
  638. void tnsVectorMinus2d(tnsVector2d result, tnsVector2d l, tnsVector2d r){
  639. result[0] = l[0] - r[0];
  640. result[1] = l[1] - r[1];
  641. }
  642. void tnsVectorMinus3d(tnsVector3d result, tnsVector3d l, tnsVector3d r){
  643. result[0] = l[0] - r[0];
  644. result[1] = l[1] - r[1];
  645. result[2] = l[2] - r[2];
  646. }
  647. void tnsVectorSubtract3d(tnsVector3d l, tnsVector3d r){
  648. l[0] = l[0] - r[0];
  649. l[1] = l[1] - r[1];
  650. l[2] = l[2] - r[2];
  651. }
  652. void tnsVectorPlus3d(tnsVector3d result, tnsVector3d l, tnsVector3d r){
  653. result[0] = l[0] + r[0];
  654. result[1] = l[1] + r[1];
  655. result[2] = l[2] + r[2];
  656. }
  657. void tnsVectorAccum3d(tnsVector3d l, tnsVector3d r){
  658. l[0] = l[0] + r[0];
  659. l[1] = l[1] + r[1];
  660. l[2] = l[2] + r[2];
  661. }
  662. void tnsVectorAccum2d(tnsVector2d l, tnsVector2d r){
  663. l[0] = l[0] + r[0];
  664. l[1] = l[1] + r[1];
  665. }
  666. void tnsVectorNegate3d(tnsVector3d result, tnsVector3d l){
  667. result[0] = -l[0];
  668. result[1] = -l[1];
  669. result[2] = -l[2];
  670. }
  671. void tnsVectorNegateSelf3d(tnsVector3d l){
  672. l[0] = -l[0];
  673. l[1] = -l[1];
  674. l[2] = -l[2];
  675. }
  676. void tnsVectorCopy2d(tnsVector2d from, tnsVector2d to){
  677. to[0] = from[0];
  678. to[1] = from[1];
  679. }
  680. void tnsVectorCopy3d(tnsVector3d from, tnsVector3d to){
  681. to[0] = from[0];
  682. to[1] = from[1];
  683. to[2] = from[2];
  684. }
  685. void tnsVectorCopy4d(tnsVector4d from, tnsVector4d to){
  686. to[0] = from[0];
  687. to[1] = from[1];
  688. to[2] = from[2];
  689. to[3] = from[3];
  690. }
  691. void tnsVectorMultiSelf4d(tnsVector4d from, real num){
  692. from[0] *= num;
  693. from[1] *= num;
  694. from[2] *= num;
  695. from[3] *= num;
  696. }
  697. void tnsVectorMultiSelf3d(tnsVector3d from, real num){
  698. from[0] *= num;
  699. from[1] *= num;
  700. from[2] *= num;
  701. }
  702. void tnsVectorMultiSelf2d(tnsVector2d from, real num){
  703. from[0] *= num;
  704. from[1] *= num;
  705. }
  706. void tnsVectorMulti4d(tnsVector4d to, tnsVector4d from, real num){
  707. to[0]=from[0]*num;
  708. to[1]=from[1]*num;
  709. to[2]=from[2]*num;
  710. to[3]=from[3]*num;
  711. }
  712. void tnsVectorMulti3d(tnsVector3d to, tnsVector3d from, real num){
  713. to[0]=from[0]*num;
  714. to[1]=from[1]*num;
  715. to[2]=from[2]*num;
  716. }
  717. void tnsVectorMulti2d(tnsVector2d to, tnsVector2d from, real num){
  718. to[0]=from[0]*num;
  719. to[1]=from[1]*num;
  720. }
  721. real tnsDirectionToRad(tnsVector2d Dir){
  722. real arcc = acos(Dir[0]);
  723. real arcs = asin(Dir[1]);
  724. if (Dir[0] >= 0){
  725. if (Dir[1] >= 0) return arcc;
  726. else
  727. return TNS_PI * 2 - arcc;
  728. }else{
  729. if (Dir[1] >= 0) return arcs + TNS_PI / 2;
  730. else
  731. return TNS_PI + arcs;
  732. }
  733. }
  734. void tnsConvert44df(tnsMatrix44d from, tnsMatrix44f to){
  735. to[0] = from[0];
  736. to[1] = from[1];
  737. to[2] = from[2];
  738. to[3] = from[3];
  739. to[4] = from[4];
  740. to[5] = from[5];
  741. to[6] = from[6];
  742. to[7] = from[7];
  743. to[8] = from[8];
  744. to[9] = from[9];
  745. to[10] = from[10];
  746. to[11] = from[11];
  747. to[12] = from[12];
  748. to[13] = from[13];
  749. to[14] = from[14];
  750. to[15] = from[15];
  751. }
  752. void tnsLoadIdentity44d(tnsMatrix44d m){
  753. memset(m, 0, sizeof(tnsMatrix44d));
  754. m[0] = 1.0f;
  755. m[5] = 1.0f;
  756. m[10] = 1.0f;
  757. m[15] = 1.0f;
  758. };
  759. real tnsDistIdv2(real x1, real y1, real x2, real y2){
  760. real x = x2 - x1, y = y2 - y1;
  761. return sqrt((x * x + y * y));
  762. }
  763. real tnsDist3dv(tnsVector3d l, tnsVector3d r){
  764. real x = r[0] - l[0];
  765. real y = r[1] - l[1];
  766. real z = r[2] - l[2];
  767. return sqrt(x * x + y * y + z * z);
  768. }
  769. real tnsDist2dv(tnsVector2d l, tnsVector2d r){
  770. real x = r[0] - l[0];
  771. real y = r[1] - l[1];
  772. return sqrt(x * x + y * y);
  773. }
  774. real tnsLength3d(tnsVector3d l){
  775. return (sqrt(l[0] * l[0] + l[1] * l[1] + l[2] * l[2]));
  776. }
  777. real tnsLength2d(tnsVector3d l){
  778. return (sqrt(l[0] * l[0] + l[1] * l[1]));
  779. }
  780. void tnsNormalize3d(tnsVector3d result, tnsVector3d l){
  781. real r = sqrt(l[0] * l[0] + l[1] * l[1] + l[2] * l[2]);
  782. result[0] = l[0] / r;
  783. result[1] = l[1] / r;
  784. result[2] = l[2] / r;
  785. }
  786. void tnsNormalize2d(tnsVector2d result, tnsVector2d l){
  787. real r = sqrt(l[0] * l[0] + l[1] * l[1]);
  788. result[0] = l[0] / r;
  789. result[1] = l[1] / r;
  790. }
  791. void tnsNormalizeSelf2d(tnsVector3d result){
  792. real r = sqrt(result[0] * result[0] + result[1] * result[1]);
  793. result[0] /= r;
  794. result[1] /= r;
  795. }
  796. void tnsNormalizeSelf3d(tnsVector3d result){
  797. real r = sqrt(result[0] * result[0] + result[1] * result[1] + result[2] * result[2]);
  798. result[0] /= r;
  799. result[1] /= r;
  800. result[2] /= r;
  801. }
  802. real tnsDot3d(tnsVector3d l, tnsVector3d r, int normalize){
  803. tnsVector3d ln, rn;
  804. if (normalize){
  805. tnsNormalize3d(ln, l);
  806. tnsNormalize3d(rn, r);
  807. return (ln[0] * rn[0] + ln[1] * rn[1] + ln[2] * rn[2]);
  808. }
  809. return (l[0] * r[0] + l[1] * r[1] + l[2] * r[2]);
  810. }
  811. real tnsDot2d(tnsVector2d l, tnsVector2d r, int normalize){
  812. tnsVector3d ln, rn;
  813. if (normalize){
  814. tnsNormalize2d(ln, l);
  815. tnsNormalize2d(rn, r);
  816. return (ln[0] * rn[0] + ln[1] * rn[1]);
  817. }
  818. return (l[0] * r[0] + l[1] * r[1]);
  819. }
  820. real tnsVectorCross3d(tnsVector3d result, tnsVector3d l, tnsVector3d r){
  821. result[0] = l[1] * r[2] - l[2] * r[1];
  822. result[1] = l[2] * r[0] - l[0] * r[2];
  823. result[2] = l[0] * r[1] - l[1] * r[0];
  824. return tnsLength3d(result);
  825. }
  826. void tnsVectorCrossOnly3d(tnsVector3d result, tnsVector3d l, tnsVector3d r){
  827. result[0] = l[1] * r[2] - l[2] * r[1];
  828. result[1] = l[2] * r[0] - l[0] * r[2];
  829. result[2] = l[0] * r[1] - l[1] * r[0];
  830. }
  831. real tnsAngleRad3d(tnsVector3d from, tnsVector3d to, tnsVector3d PositiveReference){
  832. if (PositiveReference){
  833. tnsVector3d res;
  834. tnsVectorCross3d(res, from, to);
  835. if (tnsDot3d(res, PositiveReference, 1) > 0) return acosf(tnsDot3d(from, to, 1));
  836. else
  837. return -acosf(tnsDot3d(from, to, 1));
  838. }
  839. return acosf(tnsDot3d(from, to, 1));
  840. }
  841. void tnsApplyRotation33d(tnsVector3d result, tnsMatrix44d mat, tnsVector3d v){
  842. result[0] = mat[0] * v[0] + mat[1] * v[1] + mat[2] * v[2];
  843. result[1] = mat[3] * v[0] + mat[4] * v[1] + mat[5] * v[2];
  844. result[2] = mat[6] * v[0] + mat[7] * v[1] + mat[8] * v[2];
  845. }
  846. void tnsApplyRotation43d(tnsVector3d result, tnsMatrix44d mat, tnsVector3d v){
  847. result[0] = mat[0] * v[0] + mat[1] * v[1] + mat[2] * v[2];
  848. result[1] = mat[4] * v[0] + mat[5] * v[1] + mat[6] * v[2];
  849. result[2] = mat[8] * v[0] + mat[9] * v[1] + mat[10] * v[2];
  850. }
  851. void tnsApplyTransform43d(tnsVector3d result, tnsMatrix44d mat, tnsVector3d v){
  852. real w;
  853. result[0] = mat[0] * v[0] + mat[4] * v[1] + mat[8] * v[2] + mat[12] * 1;
  854. result[1] = mat[1] * v[0] + mat[5] * v[1] + mat[9] * v[2] + mat[13] * 1;
  855. result[2] = mat[2] * v[0] + mat[6] * v[1] + mat[10] * v[2] + mat[14] * 1;
  856. w = mat[3] * v[0] + mat[7] * v[1] + mat[11] * v[2] + mat[15] * 1;
  857. //result[0] /= w;
  858. //result[1] /= w;
  859. //result[2] /= w;
  860. }
  861. void tnsApplyNormalTransform43d(tnsVector3d result, tnsMatrix44d mat, tnsVector3d v){
  862. real w;
  863. result[0] = mat[0] * v[0] + mat[4] * v[1] + mat[8] * v[2] + mat[12] * 1;
  864. result[1] = mat[1] * v[0] + mat[5] * v[1] + mat[9] * v[2] + mat[13] * 1;
  865. result[2] = mat[2] * v[0] + mat[6] * v[1] + mat[10] * v[2] + mat[14] * 1;
  866. }
  867. void tnsApplyTransform44d(tnsVector4d result, tnsMatrix44d mat, tnsVector4d v){
  868. result[0] = mat[0] * v[0] + mat[4] * v[1] + mat[8] * v[2] + mat[12] * 1;
  869. result[1] = mat[1] * v[0] + mat[5] * v[1] + mat[9] * v[2] + mat[13] * 1;
  870. result[2] = mat[2] * v[0] + mat[6] * v[1] + mat[10] * v[2] + mat[14] * 1;
  871. result[3] = mat[3] * v[0] + mat[7] * v[1] + mat[11] * v[2] + mat[15] * 1;
  872. }
  873. void tnsApplyTransform44dTrue(tnsVector4d result, tnsMatrix44d mat, tnsVector4d v){
  874. result[0] = mat[0] * v[0] + mat[4] * v[1] + mat[8] * v[2] + mat[12] * v[3];
  875. result[1] = mat[1] * v[0] + mat[5] * v[1] + mat[9] * v[2] + mat[13] * v[3];
  876. result[2] = mat[2] * v[0] + mat[6] * v[1] + mat[10] * v[2] + mat[14] * v[3];
  877. result[3] = mat[3] * v[0] + mat[7] * v[1] + mat[11] * v[2] + mat[15] * v[3];
  878. }
  879. void tnsRemoveTranslation44d(tnsMatrix44d result, tnsMatrix44d mat){
  880. tnsLoadIdentity44d(result);
  881. result[0] = mat[0];
  882. result[1] = mat[1];
  883. result[2] = mat[2];
  884. result[4] = mat[4];
  885. result[5] = mat[5];
  886. result[6] = mat[6];
  887. result[8] = mat[8];
  888. result[9] = mat[9];
  889. result[10] = mat[10];
  890. }
  891. void tnsClearTranslation44d(tnsMatrix44d mat){
  892. mat[3] = 0;
  893. mat[7] = 0;
  894. mat[11] = 0;
  895. }
  896. void tnsCopyMatrix44d(tnsMatrix44d from, tnsMatrix44d to);
  897. void tnsExtractXYZEuler44d(tnsMatrix44d _mat, real *xyz_result){
  898. real xRot, yRot, zRot;
  899. tnsMatrix44d mat; tnsCopyMatrix44d(_mat,mat);
  900. tnsNormalizeSelf3d(&mat[0]);
  901. tnsNormalizeSelf3d(&mat[4]);
  902. tnsNormalizeSelf3d(&mat[8]);
  903. if (mat[2] < 1){
  904. if (mat[2] > -1){
  905. yRot = asin(mat[2]);
  906. xRot = atan2(-mat[6], mat[10]);
  907. zRot = atan2(-mat[1], mat[0]);
  908. }else{
  909. yRot = -TNS_PI / 2;
  910. xRot = -atan2(-mat[4], mat[5]);
  911. zRot = 0;
  912. }
  913. }else{
  914. yRot = TNS_PI / 2;
  915. xRot = atan2(-mat[4], mat[5]);
  916. zRot = 0;
  917. }
  918. xyz_result[0] = -xRot;
  919. xyz_result[1] = -yRot;
  920. xyz_result[2] = -zRot;
  921. }
  922. void tnsExtractLocation44d(tnsMatrix44d mat, real *xyz_result){
  923. xyz_result[0] = mat[12];
  924. xyz_result[1] = mat[13];
  925. xyz_result[2] = mat[14];
  926. }
  927. void tnsExtractScale44d(tnsMatrix44d mat, real *xyz_result){
  928. xyz_result[0] = tnsLength3d(&mat[0]);
  929. xyz_result[1] = tnsLength3d(&mat[4]);
  930. xyz_result[2] = tnsLength3d(&mat[8]);
  931. }
  932. #define L(row, col) l[(col << 2) + row]
  933. #define R(row, col) r[(col << 2) + row]
  934. #define P(row, col) result[(col << 2) + row]
  935. void tnsPrintMatrix44d(tnsMatrix44d l){
  936. int i, j;
  937. for (i = 0; i < 4; i++){
  938. for (j = 0; j < 4; j++){
  939. printf("%.5f ", L(i, j));
  940. }
  941. printf("\n");
  942. }
  943. }
  944. void tnsCopyMatrix44d(tnsMatrix44d from, tnsMatrix44d to){
  945. memcpy(to, from, sizeof(tnsMatrix44d));
  946. }
  947. void tnsMultiply44d(tnsMatrix44d result, tnsMatrix44d l, tnsMatrix44d r){
  948. int i;
  949. for (i = 0; i < 4; i++){
  950. real ai0 = L(i, 0), ai1 = L(i, 1), ai2 = L(i, 2), ai3 = L(i, 3);
  951. P(i, 0) = ai0 * R(0, 0) + ai1 * R(1, 0) + ai2 * R(2, 0) + ai3 * R(3, 0);
  952. P(i, 1) = ai0 * R(0, 1) + ai1 * R(1, 1) + ai2 * R(2, 1) + ai3 * R(3, 1);
  953. P(i, 2) = ai0 * R(0, 2) + ai1 * R(1, 2) + ai2 * R(2, 2) + ai3 * R(3, 2);
  954. P(i, 3) = ai0 * R(0, 3) + ai1 * R(1, 3) + ai2 * R(2, 3) + ai3 * R(3, 3);
  955. }
  956. };
  957. void tnsInverse44d(tnsMatrix44d inverse, tnsMatrix44d mat){
  958. int i, j, k;
  959. double temp;
  960. tnsMatrix44d tempmat;
  961. real max;
  962. int maxj;
  963. tnsLoadIdentity44d(inverse);
  964. tnsCopyMatrix44d(mat, tempmat);
  965. for (i = 0; i < 4; i++){
  966. /* Look for row with max pivot */
  967. max = fabsf(tempmat[i * 5]);
  968. maxj = i;
  969. for (j = i + 1; j < 4; j++){
  970. if (fabsf(tempmat[j * 4 + i]) > max){
  971. max = fabsf(tempmat[j * 4 + i]);
  972. maxj = j;
  973. }
  974. }
  975. /* Swap rows if necessary */
  976. if (maxj != i){
  977. for (k = 0; k < 4; k++){
  978. real t;
  979. t = tempmat[i * 4 + k];
  980. tempmat[i * 4 + k] = tempmat[maxj * 4 + k];
  981. tempmat[maxj * 4 + k] = t;
  982. t = inverse[i * 4 + k];
  983. inverse[i * 4 + k] = inverse[maxj * 4 + k];
  984. inverse[maxj * 4 + k] = t;
  985. }
  986. }
  987. //if (UNLIKELY(tempmat[i][i] == 0.0f)) {
  988. // return false; /* No non-zero pivot */
  989. //}
  990. temp = (double)tempmat[i * 5];
  991. for (k = 0; k < 4; k++){
  992. tempmat[i * 4 + k] = (real)((double)tempmat[i * 4 + k] / temp);
  993. inverse[i * 4 + k] = (real)((double)inverse[i * 4 + k] / temp);
  994. }
  995. for (j = 0; j < 4; j++){
  996. if (j != i){
  997. temp = tempmat[j * 4 + i];
  998. for (k = 0; k < 4; k++){
  999. tempmat[j * 4 + k] -= (real)((double)tempmat[i * 4 + k] * temp);
  1000. inverse[j * 4 + k] -= (real)((double)inverse[i * 4 + k] * temp);
  1001. }
  1002. }
  1003. }
  1004. }
  1005. }
  1006. void tnsMakeTranslationMatrix44d(tnsMatrix44d mTrans, real x, real y, real z){
  1007. tnsLoadIdentity44d(mTrans);
  1008. mTrans[12] = x;
  1009. mTrans[13] = y;
  1010. mTrans[14] = z;
  1011. }
  1012. void tnsMakePerspectiveMatrix44d(tnsMatrix44d mProjection, real fFov_rad, real fAspect, real zMin, real zMax){
  1013. real yMax = zMin * tanf(fFov_rad * 0.5f);
  1014. real yMin = -yMax;
  1015. real xMin = yMin * fAspect;
  1016. real xMax = -xMin;
  1017. tnsLoadIdentity44d(mProjection);
  1018. mProjection[0] = (2.0f * zMin) / (xMax - xMin);
  1019. mProjection[5] = (2.0f * zMin) / (yMax - yMin);
  1020. mProjection[8] = (xMax + xMin) / (xMax - xMin);
  1021. mProjection[9] = (yMax + yMin) / (yMax - yMin);
  1022. mProjection[10] = -((zMax + zMin) / (zMax - zMin));
  1023. mProjection[11] = -1.0f;
  1024. mProjection[14] = -((2.0f * (zMax * zMin)) / (zMax - zMin));
  1025. mProjection[15] = 0.0f;
  1026. }
  1027. void tnsMakeZTrackingMatrix44d(tnsMatrix44d mat, tnsVector3d this, tnsVector3d that, tnsVector3d up){
  1028. tnsVector4d fwd, l, t, rt;
  1029. fwd[3] = l[3] = t[3] = rt[3] = 1;
  1030. t[0] = up[0];
  1031. t[1] = up[1];
  1032. t[2] = up[2];
  1033. fwd[0] = that[0] - this[0];
  1034. fwd[1] = that[1] - this[1];
  1035. fwd[2] = that[2] - this[2];
  1036. tnsNormalizeSelf3d(fwd);
  1037. tnsVectorCross3d(l, fwd, t);
  1038. tnsNormalizeSelf3d(l);
  1039. tnsVectorCross3d(rt, l, fwd);
  1040. tnsNormalizeSelf3d(rt);
  1041. tnsLoadIdentity44d(mat);
  1042. mat[0] = l[0];
  1043. mat[1] = l[1];
  1044. mat[2] = l[2];
  1045. mat[4] = rt[0];
  1046. mat[5] = rt[1];
  1047. mat[6] = rt[2];
  1048. mat[8] = -fwd[0];
  1049. mat[9] = -fwd[1];
  1050. mat[10] = -fwd[2];
  1051. }
  1052. void tnsMakeZTrackingMatrixDelta44d(tnsMatrix44d mat, tnsVector3d delta, tnsVector3d up){
  1053. tnsVector4d fwd, l, t, rt;
  1054. fwd[3] = l[3] = t[3] = rt[3] = 1;
  1055. t[0] = up[0];
  1056. t[1] = up[1];
  1057. t[2] = up[2];
  1058. fwd[0] = delta[0];
  1059. fwd[1] = delta[1];
  1060. fwd[2] = delta[2];
  1061. tnsLoadIdentity44d(mat);
  1062. tnsVectorCross3d(l, t, fwd);
  1063. tnsVectorCross3d(rt, fwd, l);
  1064. tnsNormalizeSelf3d(l);
  1065. tnsNormalizeSelf3d(rt);
  1066. tnsNormalizeSelf3d(fwd);
  1067. mat[0] = l[0];
  1068. mat[1] = l[1];
  1069. mat[2] = l[2];
  1070. mat[4] = rt[0];
  1071. mat[5] = rt[1];
  1072. mat[6] = rt[2];
  1073. mat[8] = fwd[0];
  1074. mat[9] = fwd[1];
  1075. mat[10] = fwd[2];
  1076. }
  1077. void tnsMakeOrthoMatrix44d(tnsMatrix44d mProjection, real xMin, real xMax, real yMin, real yMax, real zMin, real zMax){
  1078. tnsLoadIdentity44d(mProjection);
  1079. mProjection[0] = 2.0f / (xMax - xMin);
  1080. mProjection[5] = 2.0f / (yMax - yMin);
  1081. mProjection[10] = -2.0f / (zMax - zMin);
  1082. mProjection[12] = -((xMax + xMin) / (xMax - xMin));
  1083. mProjection[13] = -((yMax + yMin) / (yMax - yMin));
  1084. mProjection[14] = -((zMax + zMin) / (zMax - zMin));
  1085. mProjection[15] = 1.0f;
  1086. }
  1087. void tnsMakeRotationMatrix44d(tnsMatrix44d m, real angle_rad, real x_, real y_, real z_){
  1088. float x = x_;
  1089. float y = y_;
  1090. float z = z_;
  1091. float c = cos(angle_rad);
  1092. float s = sin(angle_rad);
  1093. tnsMatrix44d d={
  1094. x*x*(1.0f-c)+c, x*y*(1.0f-c)-z*s, x*z*(1.0f-c)+y*s, 0.0f,
  1095. y*x*(1.0f-c)+z*s, y*y*(1.0f-c)+c, y*z*(1.0f-c)-x*s, 0.0f,
  1096. z*x*(1.0f-c)-y*s, z*y*(1.0f-c)+x*s, z*z*(1.0f-c)+c, 0.0f,
  1097. 0.0f, 0.0f, 0.0f, 1.0f };
  1098. memcpy(m,d,sizeof(tnsMatrix44d));
  1099. }
  1100. void tnsMakeRotationXMatrix44d(tnsMatrix44d m, real angle_rad){
  1101. tnsLoadIdentity44d(m);
  1102. m[5] = cos(angle_rad);
  1103. m[6] = sin(angle_rad);
  1104. m[9] = -sin(angle_rad);
  1105. m[10] = cos(angle_rad);
  1106. }
  1107. void tnsMakeRotationYMatrix44d(tnsMatrix44d m, real angle_rad){
  1108. tnsLoadIdentity44d(m);
  1109. m[0] = cos(angle_rad);
  1110. m[2] = -sin(angle_rad);
  1111. m[8] = sin(angle_rad);
  1112. m[10] = cos(angle_rad);
  1113. }
  1114. void tnsMakeRotationZMatrix44d(tnsMatrix44d m, real angle_rad){
  1115. tnsLoadIdentity44d(m);
  1116. m[0] = cos(angle_rad);
  1117. m[1] = sin(angle_rad);
  1118. m[4] = -sin(angle_rad);
  1119. m[5] = cos(angle_rad);
  1120. }
  1121. void tnsMakeScaleMatrix44d(tnsMatrix44d m, real x, real y, real z){
  1122. tnsLoadIdentity44d(m);
  1123. m[0] = x; m[5] = y; m[10] = z;
  1124. }
  1125. void tnsMakeViewportMatrix44d(tnsMatrix44d m, real w, real h, real Far, real Near){
  1126. tnsLoadIdentity44d(m);
  1127. m[0] = w / 2;
  1128. m[5] = h / 2;
  1129. m[10] = (Far - Near) / 2;
  1130. m[12] = w / 2;
  1131. m[13] = h / 2;
  1132. m[14] = (Far + Near) / 2;
  1133. m[15] = 1;
  1134. //m[0] = 2/w;
  1135. //m[5] = 2/h;
  1136. //m[10] = 1;
  1137. //m[12] = 2/w;
  1138. //m[13] = 2/h;
  1139. //m[14] = 1;
  1140. //m[15] = 1;
  1141. }
  1142. int tnsIntersectPlaneRay(tnsVector3d n, tnsVector3d p0, tnsVector3d l0, tnsVector3d l, real* t){
  1143. float denom = tnsDot3d(n, l, 0);
  1144. if (denom > 1e-6){
  1145. tnsVector3d p0l0; tnsVectorMinus3d(p0l0,p0 ,l0);
  1146. (*t) = tnsDot3d(p0l0, n, 0) / denom;
  1147. return ((*t) >= 0);
  1148. }
  1149. return 0;
  1150. }
  1151. void tnsInitFirstLevel(tnsMatrixStack *tms){
  1152. tnsLoadIdentity44d(tms->level[0].model);
  1153. tnsLoadIdentity44d(tms->level[0].projection);
  1154. tnsLoadIdentity44d(tms->level[0].view);
  1155. }
  1156. //-------------------Export
  1157. void tnsOrtho(real xMin, real xMax, real yMin, real yMax, real zMin, real zMax){
  1158. tnsShader *current_shader = 0;
  1159. real *mat = tnsGetProjectionMatrix();
  1160. T->vol=xMin; T->vor=xMax; T->vou=yMax; T->vob=yMin;
  1161. tnsMakeOrthoMatrix44d(mat, xMin, xMax, yMin, yMax, zMin, zMax);
  1162. if (current_shader = T->CurrentShader){
  1163. tnsShaderApplyProjection(current_shader, mat);
  1164. }
  1165. }
  1166. void tnsPerspective(real fFov_rad, real fAspect, real zMin, real zMax){
  1167. tnsShader *current_shader = 0;
  1168. real *mat = tnsGetProjectionMatrix();
  1169. tnsMakePerspectiveMatrix44d(mat, fFov_rad, fAspect, zMin, zMax);
  1170. if (current_shader = T->CurrentShader){
  1171. tnsShaderApplyProjection(current_shader, mat);
  1172. }
  1173. }
  1174. void tnsTranslate3d(real x, real y, real z){
  1175. tnsShader *current_shader = 0;
  1176. real *mat = tnsGetModelMatrix();
  1177. tnsMatrix44d transmat, result;
  1178. tnsMakeTranslationMatrix44d(transmat, x, y, z);
  1179. tnsMultiply44d(result, mat, transmat);
  1180. memcpy(mat, result, sizeof(tnsMatrix44d));
  1181. if (current_shader = T->CurrentShader){
  1182. tnsShaderApplyModel(current_shader, result);
  1183. }
  1184. }
  1185. void tnsPreTranslate3d(real x, real y, real z){
  1186. tnsShader *current_shader = 0;
  1187. real *mat = tnsGetModelMatrix();
  1188. tnsMatrix44d transmat, result;
  1189. tnsMakeTranslationMatrix44d(transmat, x, y, z);
  1190. tnsMultiply44d(result, mat, transmat);
  1191. memcpy(mat, result, sizeof(tnsMatrix44d));
  1192. }
  1193. void tnsRotate4d(real degrees, real x, real y, real z){
  1194. tnsShader *current_shader = 0;
  1195. real *mat = tnsGetModelMatrix();
  1196. tnsMatrix44d rotmat, result;
  1197. tnsMakeRotationMatrix44d(rotmat, rad(degrees), x, y, z);
  1198. tnsMultiply44d(result, mat, rotmat);
  1199. memcpy(mat, result, sizeof(tnsMatrix44d));
  1200. if (current_shader = T->CurrentShader){
  1201. tnsShaderApplyModel(current_shader, result);
  1202. }
  1203. }
  1204. void tnsPreRotate4d(real degrees, real x, real y, real z){
  1205. tnsShader *current_shader = 0;
  1206. real *mat = tnsGetModelMatrix();
  1207. tnsMatrix44d rotmat, result;
  1208. tnsMakeRotationMatrix44d(rotmat, rad(degrees), x, y, z);
  1209. tnsMultiply44d(result, mat, rotmat);
  1210. memcpy(mat, result, sizeof(tnsMatrix44d));
  1211. }
  1212. void tnsScale3d(real x, real y, real z){
  1213. tnsShader *current_shader = 0;
  1214. real *mat = tnsGetModelMatrix();
  1215. tnsMatrix44d scalemat, normal_scaler, result;
  1216. tnsMakeScaleMatrix44d(scalemat, x, y, z);
  1217. tnsMultiply44d(result, mat, scalemat);
  1218. memcpy(mat, result, sizeof(tnsMatrix44d));
  1219. if (current_shader = T->CurrentShader){
  1220. tnsShaderApplyModel(current_shader, result);
  1221. }
  1222. }
  1223. void tnsPreScale3d(real x, real y, real z){
  1224. tnsShader *current_shader = 0;
  1225. real *mat = tnsGetModelMatrix();
  1226. tnsMatrix44d scalemat, normal_scaler, result;
  1227. tnsMakeScaleMatrix44d(scalemat, x, y, z);
  1228. tnsMultiply44d(result, mat, scalemat);
  1229. memcpy(mat, result, sizeof(tnsMatrix44d));
  1230. }
  1231. void tKnlPopMatrix();
  1232. void tKnlPushMatrix();
  1233. void tnsPushMatrix(){
  1234. tKnlPushMatrix();
  1235. };
  1236. void tnsPopMatrix(){
  1237. tKnlPopMatrix();
  1238. }
  1239. //========================================[KNL]
  1240. void tnsSetRayShaderUniformTextures(tnsOffscreen* doff){
  1241. if(!doff)return;
  1242. tnsActiveTexture(GL_TEXTURE0); glBindTexture(doff->pColor[0]->GLTexType, doff->pColor[0]->GLTexHandle);
  1243. tnsActiveTexture(GL_TEXTURE1); glBindTexture(doff->pColor[1]->GLTexType, doff->pColor[1]->GLTexHandle);
  1244. tnsActiveTexture(GL_TEXTURE2); glBindTexture(doff->pColor[2]->GLTexType, doff->pColor[2]->GLTexHandle);
  1245. glUniform1i(T->RayShader->iTexColor, 0); glUniform1i(T->RayShader->iTexNormal, 1); glUniform1i(T->RayShader->iTexGPos, 2);
  1246. }
  1247. void tnsInit(){
  1248. T = memAcquire(sizeof(tnsMain));
  1249. T->World=memAcquire(sizeof(tnsWorld));
  1250. }
  1251. void tnsInitRenderKernel(int matrixStackLevel){
  1252. tnsCommand *c;
  1253. GLuint m_nQuadVAO;
  1254. T->GLVersionStr = glGetString(GL_VERSION);
  1255. T->GLVendorStr = glGetString(GL_VENDOR);
  1256. T->GLRendererStr = glGetString(GL_RENDERER);
  1257. T->GLSLVersionStr = glGetString(GL_SHADING_LANGUAGE_VERSION);
  1258. T->stack.max_level = matrixStackLevel;
  1259. T->stack.level = CreateNewBuffer(tnsMatrixStackItem, matrixStackLevel);
  1260. T->NextShaderIndex = 1;
  1261. T->BindedShader = -1;
  1262. tnsInitFirstLevel(&T->stack);
  1263. T->StateLineWidth=T->SetLineWidth=1; T->StatePointSize=T->SetPointSize=1;
  1264. arrEnsureLength(&T->Vert, T->NextVert, &T->MaxVert, sizeof(GLfloat));
  1265. glGenBuffers(1, &T->VertBufObject);
  1266. glBindBuffer(GL_ARRAY_BUFFER, T->VertBufObject);
  1267. glBufferData(GL_ARRAY_BUFFER, T->MaxVert * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1268. arrEnsureLength(&T->Color, T->NextColor, &T->MaxColor, sizeof(GLfloat));
  1269. glGenBuffers(1, &T->ColorBufObject);
  1270. glBindBuffer(GL_ARRAY_BUFFER, T->ColorBufObject);
  1271. glBufferData(GL_ARRAY_BUFFER, T->MaxColor * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1272. arrEnsureLength(&T->Normal, T->NextNormal, &T->MaxNormal, sizeof(GLfloat));
  1273. glGenBuffers(1, &T->NormalBufObject);
  1274. glBindBuffer(GL_ARRAY_BUFFER, T->NormalBufObject);
  1275. glBufferData(GL_ARRAY_BUFFER, T->MaxNormal * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1276. arrEnsureLength(&T->TexCoord, T->NextTexCoord, &T->MaxTexCoord, sizeof(GLfloat));
  1277. glGenBuffers(1, &T->TexCoordBufObject);
  1278. glBindBuffer(GL_ARRAY_BUFFER, T->TexCoordBufObject);
  1279. glBufferData(GL_ARRAY_BUFFER, T->MaxTexCoord * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1280. arrEnsureLength(&T->Index, T->NextIndex, &T->MaxIndex, sizeof(GLuint));
  1281. glGenBuffers(1, &T->IndexBufObject);
  1282. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, T->IndexBufObject);
  1283. glBufferData(GL_ELEMENT_ARRAY_BUFFER, T->MaxIndex * sizeof(GLuint), 0, GL_DYNAMIC_DRAW);
  1284. arrEnsureLength(&T->DrawingCommand, T->NextCommand, &T->MaxCommand, sizeof(tnsCommand));
  1285. }
  1286. void tnsInitBuiltinShaders(){
  1287. T->immShader = tnsNewShaderProgram(
  1288. tnsNewVertexShader(LA_IMM_VERTEX_SHADER),tnsNewFragmentShader(LA_IMM_FRAGMENT_SHADER),-1);
  1289. T->TEST_MatcapShader = tnsNewShaderProgram(
  1290. tnsNewVertexShader(TNS_VERTEX_SIMPLE_MATCAP),
  1291. tnsNewFragmentShader(TNS_FRAGMENT_SIMPLE_MATCAP), -1);
  1292. T->TransparentGridShader = tnsNewShaderProgram(
  1293. tnsNewVertexShader(TNS_VERTEX_GRID),
  1294. tnsNewFragmentShader(TNS_FRAGMENT_TRANSPARNT_GRID), -1);
  1295. T->RayShader = tnsNewShaderProgram(
  1296. tnsNewVertexShader(LA_RAY_VERTEX_SHADER),
  1297. tnsNewFragmentShader(LA_RAY_FRAGMENT_SHADER), -1);
  1298. T->ShadowShader = tnsNewShaderProgram(
  1299. tnsNewVertexShader(LA_CASCADE_SHADOW_VERTEX_SHADER),
  1300. tnsNewFragmentShader(LA_CASCADE_SHADOW_FRAGMENT_SHADER), -1);
  1301. T->SceneShader = tnsNewShaderProgram(
  1302. tnsNewVertexShader(LA_SCENE_VERTEX_SHADER),
  1303. tnsNewFragmentShader(LA_SCENE_FRAGMENT_SHADER), -1);
  1304. T->SelectionShader = tnsNewShaderProgram(
  1305. tnsNewVertexShader(LA_SELECTION_VERTEX_SHADER),
  1306. tnsNewFragmentShader(LA_SELECTION_FRAGMENT_SHADER), -1);
  1307. T->FloorShader = tnsNewShaderProgram(
  1308. tnsNewVertexShader(LA_FLOOR_VERTEX_SHADER),
  1309. tnsNewFragmentShader(LA_FLOOR_FRAGMENT_SHADER), -1);
  1310. tnsUseShader(T->immShader);
  1311. tnsEnableShaderv(T->immShader);
  1312. }
  1313. void tnsInitWindowDefaultRenderConfig(){
  1314. tnsInitBuiltinShaders();
  1315. };
  1316. void tnsDeleteBuiltinShaders(){
  1317. tnsDeleteShaderProgram(T->immShader); T->immShader=0;
  1318. tnsDeleteShaderProgram(T->TEST_MatcapShader); T->TEST_MatcapShader=0;
  1319. tnsDeleteShaderProgram(T->TransparentGridShader); T->TransparentGridShader=0;
  1320. tnsDeleteShaderProgram(T->SelectionShader); T->SelectionShader=0;
  1321. tnsDeleteShaderProgram(T->FloorShader); T->FloorShader=0;
  1322. tnsDeleteShaderProgram(T->SceneShader); T->SceneShader=0;
  1323. tnsDeleteShaderProgram(T->ShadowShader); T->ShadowShader=0;
  1324. tnsDeleteShaderProgram(T->RayShader); T->RayShader=0;
  1325. }
  1326. void tnsQuitFontManager();
  1327. void tnsQuit(){
  1328. tnsQuitFontManager();
  1329. tnsObject*o;
  1330. while(o=lstPopItem(&T->World->AllObjects)){ tnsDestroyObject(o); }
  1331. while(o=lstPopItem(&T->World->RootObjects)){ tnsDestroyRootObject(o); }
  1332. //memFreeRemainingLeftNodes();
  1333. tnsDeleteBuiltinShaders();
  1334. tnsOffscreen* off; while(off=T->Offscreens.pFirst){ tnsDelete2DOffscreen(off); }
  1335. tnsTexture* t; while(t=T->Textures.pFirst){ tnsDeleteTexture(t); }
  1336. arrFree(&T->Vert, &T->MaxVert);
  1337. arrFree(&T->Color, &T->MaxColor);
  1338. arrFree(&T->Normal, &T->MaxNormal);
  1339. arrFree(&T->TexCoord, &T->MaxTexCoord);
  1340. arrFree(&T->Index, &T->MaxIndex);
  1341. arrFree(&T->DrawingCommand, &T->DrawingCommand);
  1342. glDeleteBuffers(1, &T->VertBufObject);
  1343. glDeleteBuffers(1, &T->ColorBufObject);
  1344. glDeleteBuffers(1, &T->NormalBufObject);
  1345. glDeleteBuffers(1, &T->TexCoordBufObject);
  1346. glDeleteBuffers(1, &T->IndexBufObject);
  1347. FreeMem(T->stack.level);
  1348. memFree(T->World);
  1349. memFree(T);
  1350. }
  1351. void tnsRestoreFromNanoVG(){
  1352. glBindVertexArray(T->CurrentVAO);
  1353. tnsUseImmShader(); tnsEnableShaderv(T->immShader);
  1354. glActiveTexture(GL_TEXTURE0); tnsActiveTexture(GL_TEXTURE0);
  1355. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA,GL_ONE,GL_ONE_MINUS_SRC_ALPHA);
  1356. }
  1357. tnsMatrixStackItem *tKnlGetCurrentMatStackItem(){
  1358. return &T->stack.level[T->stack.current_level];
  1359. }
  1360. real *tnsGetModelMatrix(){
  1361. return tKnlGetCurrentMatStackItem()->model;
  1362. }
  1363. real *tnsGetViewMatrix(){
  1364. return tKnlGetCurrentMatStackItem()->view;
  1365. }
  1366. real *tnsGetProjectionMatrix(){
  1367. return tKnlGetCurrentMatStackItem()->projection;
  1368. }
  1369. void tnsGetMVMatrix(tnsMatrix44d r){
  1370. tnsMatrixStackItem *tmsi=tKnlGetCurrentMatStackItem();
  1371. tnsMatrix44d tmp;
  1372. tnsMultiply44d(r, tmsi->model, tmsi->view);
  1373. }
  1374. void tnsGetMVPMatrix(tnsMatrix44d r){
  1375. tnsMatrixStackItem *tmsi=tKnlGetCurrentMatStackItem();
  1376. tnsMatrix44d tmp;
  1377. tnsMultiply44d(tmp, tmsi->model, tmsi->view);
  1378. tnsMultiply44d(r, tmp, tmsi->projection);
  1379. }
  1380. void tnsResetModelMatrix(){
  1381. tnsLoadIdentity44d(tnsGetModelMatrix());
  1382. }
  1383. void tnsResetViewMatrix(){
  1384. tnsLoadIdentity44d(tnsGetViewMatrix());
  1385. }
  1386. void tnsResetProjectionMatrix(){
  1387. tnsLoadIdentity44d(tnsGetProjectionMatrix());
  1388. }
  1389. int tKnlAttatchShader(tnsShader *tns){
  1390. lstAppendItem(&T->Shaders, tns);
  1391. tns->CustomID = T->NextShaderIndex;
  1392. T->NextShaderIndex++;
  1393. return tns->CustomID;
  1394. };
  1395. int CMP_NUM_IsThisShader(tnsShader *tns, int *index){
  1396. return (tns->CustomID == *index);
  1397. }
  1398. tnsShader *tKnlFindShader1i(int CustomIndex){
  1399. return lstFindItem(&CustomIndex, CMP_NUM_IsThisShader, &T->Shaders);
  1400. }
  1401. void tKnlPushMatrix(){
  1402. tnsMatrixStack *tms = &T->stack;
  1403. tnsShader *current_shader = T->CurrentShader;
  1404. if (tms->current_level == tms->max_level || !current_shader) return;
  1405. memcpy(&tms->level[tms->current_level + 1], &tms->level[tms->current_level], sizeof(tnsMatrixStackItem));
  1406. tms->current_level++;
  1407. //tnsShaderApplyModel(current_shader,tms->level[tms->current_level].model);
  1408. //tnsShaderApplyView(current_shader,tms->level[tms->current_level].view);
  1409. //tnsShaderApplyProjection(current_shader,tms->level[tms->current_level].projection);
  1410. };
  1411. void tKnlPopMatrix(){
  1412. tnsMatrixStack *tms = &T->stack;
  1413. tnsShader *current_shader = T->CurrentShader;
  1414. if (tms->current_level == 0 || !current_shader) return;
  1415. tms->current_level--;
  1416. tnsShaderApplyModel(current_shader, tms->level[tms->current_level].model);
  1417. tnsShaderApplyView(current_shader, tms->level[tms->current_level].view);
  1418. tnsShaderApplyProjection(current_shader, tms->level[tms->current_level].projection);
  1419. }
  1420. laListHandle *tKnlGetTextureList(){
  1421. return &T->Textures;
  1422. }
  1423. tnsBatch *tnsCreateBatch(u32bit NumVert, int Dimension, float *Data, int NormalDimension, float *Normal, int ColorDimension, float *Colors){
  1424. tnsBatch *b = CreateNew(tnsBatch);
  1425. b->Dimension = Dimension;
  1426. b->NormalDimension=NormalDimension;
  1427. b->ColorDimension=ColorDimension;
  1428. b->NumVert = NumVert;
  1429. glGenBuffers(1, &b->VBO);
  1430. glBindBuffer(GL_ARRAY_BUFFER, b->VBO);
  1431. glBufferData(GL_ARRAY_BUFFER, NumVert * Dimension * sizeof(GLfloat), Data, GL_DYNAMIC_DRAW);
  1432. if (Normal){
  1433. glGenBuffers(1, &b->NBO); glBindBuffer(GL_ARRAY_BUFFER, b->NBO);
  1434. glBufferData(GL_ARRAY_BUFFER, NumVert * NormalDimension * sizeof(GLfloat), Normal, GL_DYNAMIC_DRAW);
  1435. b->HasNormal=1;
  1436. }
  1437. if (Colors){
  1438. glGenBuffers(1, &b->CBO); glBindBuffer(GL_ARRAY_BUFFER, b->CBO);
  1439. glBufferData(GL_ARRAY_BUFFER, NumVert * ColorDimension * sizeof(GLfloat), Colors, GL_DYNAMIC_DRAW);
  1440. b->HasColor=1;
  1441. }
  1442. return b;
  1443. }
  1444. tnsBatch *tnsCreateBatchi(u32bit NumVert, int Dimension, int *Data){
  1445. tnsBatch *b = CreateNew(tnsBatch);
  1446. b->Dimension = Dimension;
  1447. b->NumVert = NumVert;
  1448. glGenBuffers(1, &b->VBO);
  1449. glBindBuffer(GL_ARRAY_BUFFER, b->VBO);
  1450. glBufferData(GL_ARRAY_BUFFER, NumVert * Dimension * sizeof(GLuint), Data, GL_DYNAMIC_DRAW);
  1451. return b;
  1452. }
  1453. void tnsCommandUseUniformColor(tnsBatchCommand*c, real* color){
  1454. tnsVectorCopy4d(color, c->UniformColor);
  1455. c->UseUniformColor=1;
  1456. }
  1457. void tnsCommandUseMaterial(tnsBatchCommand*c, tnsMaterial* material){
  1458. c->Material=material;
  1459. }
  1460. void tnsCommandUseWidth(tnsBatchCommand*c, real width){
  1461. c->Width=width;
  1462. }
  1463. void tnsCommandOverrideColorArray(tnsBatchCommand*c, int VertCount, int ColorDimension, float* colors){
  1464. if(!colors) return;
  1465. c->OverrideColorArray=1;
  1466. glGenBuffers(1, &c->CBO); glBindBuffer(GL_ARRAY_BUFFER, c->CBO);
  1467. glBufferData(GL_ARRAY_BUFFER, VertCount* ColorDimension * sizeof(GLfloat), colors, GL_DYNAMIC_DRAW);
  1468. c->ColorDimension = ColorDimension;
  1469. }
  1470. tnsBatchCommand *tnsCreateCommand(tnsBatch *b, const char* name, u32bit ElementCount, int Dimension, GLenum DrawAs, u32bit *Elements, int HiddenByDefault){
  1471. tnsBatchCommand *bc = CreateNew(tnsBatchCommand);
  1472. bc->ElementCount = ElementCount;
  1473. bc->DrawAs = DrawAs;
  1474. bc->Dimension = Dimension;
  1475. bc->name=name;
  1476. bc->HiddenByDefault = HiddenByDefault;
  1477. if(Elements){
  1478. glGenBuffers(1, &bc->EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bc->EBO);
  1479. glBufferData(GL_ELEMENT_ARRAY_BUFFER, ElementCount * Dimension * sizeof(GLuint), Elements, GL_DYNAMIC_DRAW);
  1480. bc->DrawElements=1;
  1481. }else{ bc->EBO=-1; }
  1482. //int a = GetLastError();
  1483. lstAppendItem(&b->Branches, bc);
  1484. return bc;
  1485. }
  1486. void tnsDeleteBatch(tnsBatch *b){
  1487. tnsBatchCommand *bc, *NextBc;
  1488. glDeleteBuffers(1, &b->VBO);
  1489. if (b->NBO > -1) glDeleteBuffers(1, &b->NBO);
  1490. if (b->CBO > -1) glDeleteBuffers(1, &b->CBO);
  1491. for (bc = b->Branches.pFirst; bc; bc = NextBc){
  1492. NextBc = bc->Item.pNext;
  1493. lstRemoveItem(&b->Branches, bc);
  1494. if (bc->EBO > -1) glDeleteBuffers(1, &bc->EBO);
  1495. if (bc->CBO > -1) glDeleteBuffers(1, &bc->CBO);
  1496. FreeMem(bc);
  1497. }
  1498. FreeMem(b);
  1499. }
  1500. void tnsDrawBatchInitArrayStates(tnsBatch* batch){
  1501. tnsShader* cs=T->BindedShader;
  1502. glBindBuffer(GL_ARRAY_BUFFER, batch->VBO);
  1503. glEnableVertexAttribArray(cs->iVertex);
  1504. glVertexAttribPointer(cs->iVertex, batch->Dimension, GL_FLOAT, 0, 0, 0);
  1505. if(cs->iNormal>=0){
  1506. if(batch->HasNormal){
  1507. glBindBuffer(GL_ARRAY_BUFFER, batch->NBO); glEnableVertexAttribArray(cs->iNormal);
  1508. glVertexAttribPointer(cs->iNormal, batch->NormalDimension, GL_FLOAT, 0, 0, 0); tnsUniformUseNormal(cs,T->StateUseNormal);
  1509. }else{ glDisableVertexAttribArray(cs->iNormal); glVertexAttrib3f(cs->iNormal,0,0,1); tnsUniformUseNormal(cs,0); }
  1510. }
  1511. if(cs->iColor>=0){
  1512. if(batch->HasColor){
  1513. glBindBuffer(GL_ARRAY_BUFFER, batch->CBO); glEnableVertexAttribArray(cs->iColor);
  1514. glVertexAttribPointer(cs->iColor, batch->ColorDimension, GL_FLOAT, 0, 0, 0);
  1515. }
  1516. }
  1517. if(cs->iUV>=0){ glDisableVertexAttribArray(cs->iUV); }
  1518. tnsUniformUseTexture(cs, 0, 0);
  1519. }
  1520. int tnsDrawBatch(tnsBatch* batch, const char* OverrideCommand, real* OverrideUniformColor, int OverrideAsArray) {
  1521. if (!batch) return 0;
  1522. int Drawn=0; tnsShader *LastShader=T->BindedShader,*SaveShader=T->BindedShader; int NeedInit=1;
  1523. int IsOverrideColor=0; int PointSizeChanged=0,LineWidthChanged=0;
  1524. for (tnsBatchCommand* bc = batch->Branches.pFirst; bc; bc = bc->Item.pNext) {
  1525. if(OverrideCommand && !strSame(OverrideCommand, bc->name)){ continue; }
  1526. if(!OverrideCommand && bc->HiddenByDefault){ continue; }
  1527. if(NeedInit || (bc->Material && LastShader!=bc->Material->Shader) || ((!bc->Material)&&LastShader!=SaveShader)){
  1528. if(bc->Material && bc->Material->Shader){ LastShader=bc->Material->Shader;
  1529. tnsUseShader(LastShader); tnsEnableShaderv(LastShader);
  1530. }else{
  1531. tnsUseShader(SaveShader); tnsEnableShaderv(SaveShader);
  1532. }
  1533. tnsDrawBatchInitArrayStates(batch); NeedInit=0;
  1534. }
  1535. tnsShader* cs=T->BindedShader;
  1536. if(cs->iColor>-1){
  1537. if(bc->OverrideColorArray){
  1538. glBindBuffer(GL_ARRAY_BUFFER, bc->CBO); glEnableVertexAttribArray(cs->iColor);
  1539. glVertexAttribPointer(cs->iColor, bc->ColorDimension, GL_FLOAT, 0, 0, 0); IsOverrideColor=1;
  1540. }else{
  1541. if(batch->HasColor){ if(IsOverrideColor){ glBindBuffer(GL_ARRAY_BUFFER, batch->CBO); glEnableVertexAttribArray(cs->iColor);
  1542. glVertexAttribPointer(cs->iColor, batch->ColorDimension, GL_FLOAT, 0, 0, 0); }
  1543. }else{ glDisableVertexAttribArray(cs->iColor); glVertexAttrib4fv(cs->iColor,T->StateColor); }
  1544. }
  1545. if(bc->UseUniformColor || OverrideUniformColor){ glDisableVertexAttribArray(cs->iColor); IsOverrideColor=1;
  1546. if(OverrideUniformColor){ glVertexAttrib4f(cs->iColor,LA_COLOR4(OverrideUniformColor)); }
  1547. else glVertexAttrib4f(cs->iColor,LA_COLOR4(bc->UniformColor));
  1548. }
  1549. }
  1550. if(bc->DrawAs == GL_POINTS && bc->Width>1e-5){ glPointSize(bc->Width); PointSizeChanged=1; }
  1551. if((bc->DrawAs == GL_LINE_STRIP||bc->DrawAs == GL_LINES||bc->DrawAs == GL_LINE_LOOP) && bc->Width>1e-5){
  1552. glLineWidth(bc->Width); LineWidthChanged=1;
  1553. }
  1554. int DrawElements=OverrideAsArray?0:bc->DrawElements;
  1555. if(DrawElements){
  1556. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bc->EBO);
  1557. glDrawElements(bc->DrawAs, bc->ElementCount*bc->Dimension, GL_UNSIGNED_INT, 0);
  1558. }else{ glDrawArrays(bc->DrawAs,0,bc->ElementCount); }
  1559. Drawn++;
  1560. if(PointSizeChanged){ glPointSize(1); } if(LineWidthChanged){ glLineWidth(1); }
  1561. }
  1562. if(SaveShader!=LastShader){ tnsUseShader(SaveShader); tnsEnableShaderv(SaveShader); }
  1563. //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  1564. return Drawn;
  1565. }
  1566. //==========================*=======================[Texture]
  1567. int tnsGetTextureMemoryComponetCount(tnsTexture *t){
  1568. int Comp = 0;
  1569. int CompSize;
  1570. switch (t->GLTexBitsType){
  1571. case GL_RGB:
  1572. Comp = 3;
  1573. break;
  1574. case GL_RGBA:
  1575. Comp = 4;
  1576. break;
  1577. }
  1578. return t->Width * t->Height * Comp;
  1579. }
  1580. int tnsInit2DTexture(tnsTexture *t, GLint glInternalFormat, int w, int h, int Multisample){
  1581. if (!t) return 0;
  1582. if(0/*glInternalFormat==GL_DEPTH_COMPONENT32F*/){
  1583. t->Width = w;
  1584. t->Height = h;
  1585. t->GLTexBitsType = GL_DEPTH_COMPONENT32F;
  1586. t->GLTexType = GL_RENDERBUFFER;
  1587. t->Multisample = Multisample;
  1588. glGenRenderbuffers(1, &t->GLTexHandle);
  1589. tnsConfigure2DTexture(t);
  1590. }else{
  1591. t->Width = w;
  1592. t->Height = h;
  1593. t->GLTexBitsType = glInternalFormat;
  1594. #ifdef LAGUI_ANDROID
  1595. t->GLTexType = GL_TEXTURE_2D;
  1596. #else
  1597. t->GLTexType = Multisample?GL_TEXTURE_2D_MULTISAMPLE:GL_TEXTURE_2D;
  1598. t->Multisample = Multisample;
  1599. #endif
  1600. glGenTextures(1, &t->GLTexHandle);
  1601. tnsConfigure2DTexture(t);
  1602. }
  1603. return 1;
  1604. }
  1605. int tnsInit3DTexture(tnsTexture *t, GLint glInternalFormat, int w, int h, int slices){
  1606. if (!t) return 0;
  1607. t->Width = w;
  1608. t->Height = h;
  1609. t->GLTexBitsType = glInternalFormat;
  1610. t->GLTexType = GL_TEXTURE_3D;
  1611. glGenTextures(1, &t->GLTexHandle);
  1612. tnsConfigure3DTexture(t);
  1613. return 1;
  1614. }
  1615. void tnsConfigure2DTexture(tnsTexture *t){
  1616. tnsBindTexture(t);
  1617. if(t->GLTexType==GL_RENDERBUFFER){
  1618. if(t->Multisample){ glRenderbufferStorageMultisample(GL_RENDERBUFFER, t->Multisample, t->GLTexBitsType, t->Width, t->Height); }
  1619. else { glRenderbufferStorage(GL_RENDERBUFFER, t->GLTexBitsType, t->Width, t->Height); }
  1620. }else{
  1621. int isDepth=t->GLTexBitsType==GL_DEPTH_COMPONENT||t->GLTexBitsType==GL_DEPTH_COMPONENT16||
  1622. t->GLTexBitsType==GL_DEPTH_COMPONENT24||t->GLTexBitsType==GL_DEPTH_COMPONENT32F;
  1623. int format=isDepth?GL_DEPTH_COMPONENT:(t->GLTexBitsType==GL_R8?GL_RED:(t->GLTexBitsType==GL_RG8?GL_RG:(t->GLTexBitsType==GL_RGB8?GL_RGB:GL_RGBA)));
  1624. int type=isDepth?GL_UNSIGNED_INT:GL_UNSIGNED_BYTE;
  1625. //if(t->GLTexBitsType==GL_RGBA4){ format=GL_RGB; type=GL_UNSIGNED_SHORT_4_4_4_4; printf("ye\n"); }
  1626. if(t->GLTexBitsType==GL_RGBA16UI){ format=GL_RGBA_INTEGER; type=GL_UNSIGNED_SHORT; t->IsUIntTexture=1; }
  1627. elif(t->GLTexBitsType==GL_RGBA32UI){ format=GL_RGBA_INTEGER; type=GL_UNSIGNED_INT; t->IsUIntTexture=1; }
  1628. elif(t->GLTexBitsType==GL_R32UI){ format=GL_RED_INTEGER; type=GL_UNSIGNED_INT; t->IsUIntTexture=1; }
  1629. elif(t->GLTexBitsType==GL_RGBA16F){ format=GL_RGBA; type=GL_FLOAT; }
  1630. elif(t->GLTexBitsType==GL_DEPTH_STENCIL){ format=GL_DEPTH_STENCIL; type=GL_UNSIGNED_INT_24_8; t->GLTexBitsType=GL_DEPTH24_STENCIL8; }
  1631. #ifndef LAGUI_ANDROID
  1632. if(isDepth){t->GLTexBitsType=GL_DEPTH_COMPONENT24; type=GL_UNSIGNED_INT;}
  1633. t->Multisample=0;
  1634. #endif
  1635. if(t->Multisample){
  1636. #ifndef LAGUI_ANDROID
  1637. glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, t->Multisample, t->GLTexBitsType, t->Width, t->Height, GL_TRUE);
  1638. #endif
  1639. }else{ glTexImage2D(GL_TEXTURE_2D, 0, t->GLTexBitsType, t->Width, t->Height, 0, format, type, 0);
  1640. if(t->IsUIntTexture){
  1641. glTexStorage2D(GL_TEXTURE_2D, 1,t->GLTexBitsType,t->Width, t->Height);
  1642. }
  1643. //if(t->GLTexBitsType==GL_RGBA4){ glTexStorage2D(GL_TEXTURE_2D,0,GL_RGBA4,t->Width,t->Height); }
  1644. int a=glGetError();
  1645. int clamp = GL_CLAMP_TO_EDGE;
  1646. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, clamp);
  1647. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, clamp);
  1648. int filter = GL_LINEAR; if (t->IsUIntTexture) { filter = GL_NEAREST; }
  1649. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter);
  1650. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);
  1651. //glTexEnvi(GL_TEXTURE_2D, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  1652. }
  1653. }
  1654. tnsUnbindTexture();
  1655. }
  1656. void tnsConfigure3DTexture(tnsTexture *t){
  1657. tnsBindTexture(t);
  1658. glTexImage3D(GL_TEXTURE_3D, 0, t->GLTexBitsType, t->Width, t->Height, t->Slices, 0, GL_RGBA, GL_FLOAT, 0);
  1659. glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  1660. glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  1661. glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
  1662. glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  1663. glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1664. //glTexEnvi(GL_TEXTURE_2D, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  1665. tnsUnbindTexture();
  1666. }
  1667. void tnsReconfigureTextureParameters(int Multisample){
  1668. laListHandle* l = tKnlGetTextureList();
  1669. for(tnsOffscreen* o=T->Offscreens.pFirst;o;o=o->Item.pNext){ tnsTexture* t;
  1670. for(int i=0;i<4;i++){
  1671. t=o->pColor[i];
  1672. if(t){
  1673. int recreate=0;
  1674. #ifndef LAGUI_ANDROID
  1675. t->Multisample = Multisample;
  1676. if(t->Multisample){ if(t->GLTexType==GL_TEXTURE_2D){t->GLTexType=GL_TEXTURE_2D_MULTISAMPLE; recreate=1;}}
  1677. else { if(t->GLTexType==GL_TEXTURE_2D_MULTISAMPLE){t->GLTexType=GL_TEXTURE_2D; recreate=1;}}
  1678. #endif
  1679. if(recreate){
  1680. glDeleteTextures(1, &t->GLTexHandle);
  1681. glGenTextures(1, &t->GLTexHandle);
  1682. }
  1683. T->TexColor=0;
  1684. tnsConfigure2DTexture(t);
  1685. tnsAttach2DOffscreenBuffer(o, GL_COLOR_ATTACHMENT0+i, t);
  1686. }
  1687. }
  1688. t=o->pDepth;
  1689. if(t){
  1690. int recreate=0;
  1691. #ifndef LAGUI_ANDROID
  1692. if((!t->Multisample && Multisample)||(t->Multisample && !Multisample)){ recreate=1; }
  1693. if(Multisample){ t->GLTexType=GL_TEXTURE_2D_MULTISAMPLE; }else{ t->GLTexType=GL_TEXTURE_2D; }
  1694. t->Multisample = Multisample;
  1695. #endif
  1696. if(recreate){
  1697. glDeleteTextures(1, &t->GLTexHandle);
  1698. glGenTextures(1, &t->GLTexHandle);
  1699. } T->TexColor=0;
  1700. tnsConfigure2DTexture(t);
  1701. tnsAttach2DOffscreenBuffer(o, GL_DEPTH_ATTACHMENT, t);
  1702. }
  1703. }
  1704. }
  1705. tnsTexture *tnsCreate2DTexture(GLint glInternalFormat, int w, int h, int Multisample){
  1706. tnsTexture *tex = memAcquire(sizeof(tnsTexture));
  1707. tnsInit2DTexture(tex, glInternalFormat, w, h, Multisample);
  1708. laNotifyUsers("tns.texture_list");
  1709. lstAppendItem(tKnlGetTextureList(), tex);
  1710. return tex;
  1711. };
  1712. tnsTexture *tnsCreate3DTexture(GLint glInternalFormat, int w, int h, int slices){
  1713. tnsTexture *tex = memAcquire(sizeof(tnsTexture));
  1714. tnsInit3DTexture(tex, glInternalFormat, w, h, slices);
  1715. laNotifyUsers("tns.texture_list");
  1716. lstAppendItem(tKnlGetTextureList(), tex);
  1717. return tex;
  1718. };
  1719. void tnsCopyScreenTo2DTexture(tnsTexture *target, int x_lower_left, int y_lower_left, int w, int h){
  1720. if(target->GLTexType!=GL_TEXTURE_2D) return;
  1721. tnsBindTexture(target);
  1722. glReadBuffer(GL_BACK);
  1723. glCopyTexSubImage2D(target->GLTexType, 0, 0, 0, x_lower_left, y_lower_left, w, h);
  1724. tnsUnbindTexture();
  1725. }
  1726. void tnsUniformUseOffset(tnsShader* s, int use){
  1727. glUniform1i(s->iDoOffset,use);
  1728. }
  1729. void tnsUseMaskTexture(tnsTexture *t){
  1730. if(!t){T->StateTextureMode=0; return;}
  1731. T->StateTexColor = t; T->StateTextureMode=1;
  1732. }
  1733. void tnsUseTexture(tnsTexture *t){
  1734. if(!t){T->StateTextureMode=0; return;}
  1735. if(t->IsUIntTexture){ T->StateTexColor = t; T->StateTextureMode=4; return; }
  1736. if(t->GLTexType == GL_TEXTURE_2D){
  1737. T->StateTexColor = t;
  1738. switch(t->ChromaCompression){
  1739. case TNS_CHROMA_COMPRESSION_YUYV: T->StateTextureMode = 101; break;
  1740. case TNS_CHROMA_COMPRESSION_UYVY: T->StateTextureMode = 102; break;
  1741. default: T->StateTextureMode = 2;
  1742. }
  1743. }
  1744. #ifndef LAGUI_ANDROID
  1745. else if(t->GLTexType == GL_TEXTURE_2D_MULTISAMPLE){ T->StateTexColor = t; T->StateTextureMode=3; }
  1746. #endif
  1747. }
  1748. void tnsUseNoTexture(){
  1749. tnsUseTexture(0);
  1750. }
  1751. void tnsUseMultiplyColor(int enable){
  1752. T->StateMultiplyColor=enable?1:0;
  1753. }
  1754. void tnsUniformUseNormal(tnsShader* s, int Use){
  1755. if(T->SetUseNormal!=Use){ T->SetUseNormal=Use; glUniform1i(s->iUseNormal,Use); }
  1756. }
  1757. void tnsUseNormal(int Use){ T->StateUseNormal=Use; }
  1758. void tnsUniformUseHalftone(tnsShader* s, real Use){
  1759. if(T->SetUseHalftone!=Use){ T->SetUseHalftone=Use; glUniform1f(s->iUseHalftone,Use); }
  1760. }
  1761. void tnsUniformHalftoneSize(tnsShader* s, real Use){
  1762. if(T->SetHalftoneSize!=Use){ T->SetHalftoneSize=Use; glUniform1f(s->iHalftoneSize,Use); }
  1763. }
  1764. void tnsUseHalftone(real Factor){ T->StateUseHalftone=Factor; }
  1765. void tnsActiveTexture(GLenum tex){
  1766. if (T->GlTextureSets != tex) glActiveTexture(tex);
  1767. T->GlTextureSets = tex;
  1768. }
  1769. void tnsBindTexture(tnsTexture *t){
  1770. if ((!t) || T->TexColor==t) return;
  1771. if(t->IsUIntTexture){ tnsActiveTexture(GL_TEXTURE2); glBindTexture(t->GLTexType, t->GLTexHandle); T->TexColor=t; return; }
  1772. if(t->GLTexType == GL_TEXTURE_2D){ tnsActiveTexture(GL_TEXTURE0); glBindTexture(t->GLTexType, t->GLTexHandle); T->TexColor=t;}
  1773. #ifndef LAGUI_ANDROID
  1774. elif(t->GLTexType == GL_TEXTURE_2D_MULTISAMPLE){ tnsActiveTexture(GL_TEXTURE1); glBindTexture(t->GLTexType, t->GLTexHandle); T->TexColor=t;}
  1775. #endif
  1776. #ifndef LA_USE_GLES
  1777. elif(t->GLTexType == GL_RENDERBUFFER){ glBindRenderbufferEXT(GL_RENDERBUFFER, t->GLTexHandle); T->TexRenderbuffer = t;}
  1778. #endif
  1779. elif(t->GLTexType == GL_TEXTURE_3D){ tnsActiveTexture(GL_TEXTURE0); glBindTexture(t->GLTexType, t->GLTexHandle); T->TexColor=t;}
  1780. }
  1781. void tnsUnbindTexture(){
  1782. #ifndef LA_USE_GLES
  1783. if(T->TexRenderbuffer){ if(T->TexRenderbuffer->GLTexType == GL_RENDERBUFFER){ glBindRenderbufferEXT(GL_RENDERBUFFER, 0); T->TexRenderbuffer=0;}}
  1784. #endif
  1785. if(T->TexColor){
  1786. if(T->TexColor->IsUIntTexture){ tnsActiveTexture(GL_TEXTURE2); glBindTexture(T->TexColor->GLTexType, 0); T->TexColor=0; return; }
  1787. if(T->TexColor->GLTexType == GL_TEXTURE_2D){tnsActiveTexture(GL_TEXTURE0);}
  1788. #ifndef LAGUI_ANDROID
  1789. else if(T->TexColor->GLTexType == GL_TEXTURE_2D_MULTISAMPLE){tnsActiveTexture(GL_TEXTURE1);}
  1790. #endif
  1791. else if(T->TexColor->GLTexType == GL_TEXTURE_3D){tnsActiveTexture(GL_TEXTURE0);}
  1792. glBindTexture(T->TexColor->GLTexType, 0); T->TexColor=0;
  1793. }
  1794. }
  1795. void tnsUniformUseTexture(tnsShader* s, int mode, int sample){
  1796. if(s->StateTextureMode != mode){ s->StateTextureMode=mode; glUniform1i(s->iTextureMode,mode); }
  1797. if(mode==3 && s->StateSampleAmount != sample){ s->StateSampleAmount=sample, glUniform1i(s->iSampleAmount,sample); }
  1798. }
  1799. void tnsUniformUseMultiplyColor(tnsShader* s, int enable){
  1800. int mode=enable?1:0;
  1801. if(s->StateMultiplyColor != mode){ s->StateMultiplyColor=mode; glUniform1i(s->iMultiplyColor,mode); }
  1802. }
  1803. void tnsUniformColorMode(tnsShader* s, int mode){
  1804. glUniform1i(s->iColorMode,mode);
  1805. }
  1806. void tnsUniformHCYGamma(tnsShader* s, float Gamma){
  1807. glUniform1f(s->iHCYGamma,Gamma);
  1808. }
  1809. void tnsUniformInputColorSpace(tnsShader* s, int ColorSpace){
  1810. glUniform1i(s->iInputColorSpace,ColorSpace);
  1811. }
  1812. void tnsUniformOutputColorSpace(tnsShader* s, int ColorSpace){
  1813. glUniform1i(s->iOutputColorSpace,ColorSpace);
  1814. }
  1815. void tnsUniformShowColorOverflowStripes(tnsShader* s, int Show){
  1816. glUniform1i(s->iShowStripes,Show);
  1817. }
  1818. void tnsUniformColorComposing(tnsShader* s, int Composing, real gamma, real blackpoint){
  1819. glUniform1i(s->iComposing,Composing); glUniform1f(s->iComposingGamma,gamma);
  1820. glUniform1f(s->iComposingBlackpoint,blackpoint);
  1821. }
  1822. void tnsDraw2DTextureDirectly(tnsTexture *t, real x, real y, real w, real h){
  1823. real Verts[8];
  1824. real UV[8] = {
  1825. 0.0f, 1.0f,
  1826. 1.0f, 1.0f,
  1827. 1.0f, 0.0f,
  1828. 0.0f, 0.0f};
  1829. tnsMakeQuad2d(Verts, x, y, x + w, y, x + w, y + h, x, y + h);
  1830. tnsUseTexture(t);
  1831. tnsVertexArray2d(Verts, 4);
  1832. tnsTexCoordArray2d(UV, 4);
  1833. tnsPackAs(GL_TRIANGLE_FAN);
  1834. }
  1835. void tnsDraw2DTextureArg(tnsTexture *t,
  1836. real x_upper_right, real y_upper_right, int w, int h,
  1837. real *MultiplyColor,
  1838. real LPadding, real RPadding, real TPadding, real BPadding){
  1839. real Verts[8];
  1840. real UV[8] = {
  1841. 0.0f + LPadding, 1.0f - TPadding,
  1842. 1.0f - RPadding, 1.0f - TPadding,
  1843. 1.0f - RPadding, 0.0f + BPadding,
  1844. 0.0f + LPadding, 0.0f + BPadding};
  1845. tnsMakeQuad2d(Verts,
  1846. x_upper_right, y_upper_right,
  1847. x_upper_right + w, y_upper_right,
  1848. x_upper_right + w, y_upper_right + h,
  1849. x_upper_right, y_upper_right + h);
  1850. if (MultiplyColor){ tnsColor4dv(MultiplyColor); tnsUseMultiplyColor(1); }
  1851. tnsUseTexture(t);
  1852. tnsVertexArray2d(Verts, 4);
  1853. tnsTexCoordArray2d(UV, 4);
  1854. tnsPackAs(GL_TRIANGLE_FAN);
  1855. tnsUseMultiplyColor(0);
  1856. }
  1857. void tnsDeleteTexture(tnsTexture *t){
  1858. laListHandle *lst = tKnlGetTextureList();
  1859. tnsUnbindTexture();
  1860. if (!t) return;
  1861. if (t->GLTexType == GL_RENDERBUFFER){
  1862. #ifndef LA_USE_GLES
  1863. glBindRenderbufferEXT(GL_RENDERBUFFER, t->GLTexHandle);
  1864. glDeleteRenderbuffersEXT(1, &t->GLTexHandle);
  1865. #endif
  1866. }else{
  1867. //glBindTexture(t->GLTexType, 0);
  1868. glDeleteTextures(1, &t->GLTexHandle);
  1869. }
  1870. laNotifyUsers("tns.texture_list");
  1871. lstRemoveItem(lst, t);
  1872. if (t->DrawData) FreeMem(t->DrawData);
  1873. memFree(t);
  1874. }
  1875. int tnsTextureMemorySize(tnsTexture *t, int Mem){
  1876. int ElemSize;
  1877. if (Mem) return t->Width * t->Height * sizeof(void *);
  1878. switch (t->GLTexBitsType){
  1879. default:
  1880. case GL_R8:
  1881. ElemSize = sizeof(char) * 1;
  1882. break;
  1883. case GL_RG8:
  1884. ElemSize = sizeof(char) * 2;
  1885. break;
  1886. case GL_RGB8:
  1887. ElemSize = sizeof(char) * 3;
  1888. break;
  1889. case GL_RGBA8:
  1890. ElemSize = sizeof(char) * 4;
  1891. break;
  1892. case GL_RGBA32F:
  1893. ElemSize = sizeof(float) * 4;
  1894. break;
  1895. case GL_DEPTH_COMPONENT32F:
  1896. ElemSize = sizeof(float);
  1897. break;
  1898. }
  1899. t->ElemSize = ElemSize;
  1900. return t->Width * t->Height * ElemSize;
  1901. }
  1902. #ifdef LA_WITH_PNG
  1903. tnsImage* tnsNewImage(void* MemPNG){
  1904. tnsImage* im=memAcquire(sizeof(tnsImage));
  1905. lstAppendItem(&T->Images,im);
  1906. im->MemPNG=MemPNG; return im;
  1907. }
  1908. STRUCTURE(tnsPNGRead){
  1909. unsigned char* data;
  1910. size_t NextData;
  1911. };
  1912. static void _tns_png_read(png_struct *ps, png_byte *data, png_size_t length){
  1913. tnsPNGRead *PNGRead = (tnsPNGRead*)png_get_io_ptr(ps);
  1914. memcpy(data,&PNGRead->data[PNGRead->NextData],length);
  1915. PNGRead->NextData+=length;
  1916. }
  1917. void tns_ImageToTexture(tnsImage* im){
  1918. if(!im->MemPNG) return;
  1919. png_structp png_ptr=0;
  1920. png_infop info_ptr=0;
  1921. tnsPNGRead PNGRead={0};
  1922. png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,0,0,0); if (!png_ptr) { goto cleanup_png_read; }
  1923. info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { goto cleanup_png_read; }
  1924. if (setjmp(png_jmpbuf(png_ptr))) { goto cleanup_png_read; }
  1925. PNGRead.data=im->MemPNG; png_set_read_fn(png_ptr, &PNGRead, _tns_png_read);
  1926. png_read_info(png_ptr, info_ptr);
  1927. png_set_swap(png_ptr);
  1928. if (png_get_interlace_type (png_ptr, info_ptr) != PNG_INTERLACE_NONE){ goto cleanup_png_read; }
  1929. png_byte ColorType = png_get_color_type(png_ptr, info_ptr);
  1930. png_byte BitDepth = png_get_bit_depth(png_ptr, info_ptr);
  1931. int HasAlpha = ColorType & PNG_COLOR_MASK_ALPHA;
  1932. if (ColorType == PNG_COLOR_TYPE_PALETTE) { png_set_palette_to_rgb(png_ptr); }
  1933. //if (ColorType == PNG_COLOR_TYPE_GRAY && BitDepth < 8) { png_set_expand_gray_1_2_4_to_8(png_ptr); }
  1934. if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(png_ptr); HasAlpha = 1; }
  1935. if (BitDepth>8) {png_set_strip_16(png_ptr);} if (BitDepth<8) { png_set_expand(png_ptr); }
  1936. if (!HasAlpha) { png_set_add_alpha(png_ptr, 0xFFFF, PNG_FILLER_AFTER); }
  1937. if (ColorType == PNG_COLOR_TYPE_GRAY || ColorType == PNG_COLOR_TYPE_GRAY_ALPHA) { png_set_gray_to_rgb(png_ptr); }
  1938. png_read_update_info(png_ptr, info_ptr);
  1939. if (png_get_bit_depth(png_ptr, info_ptr)!=8) { goto cleanup_png_read; }
  1940. if (png_get_color_type(png_ptr, info_ptr) != PNG_COLOR_TYPE_RGB_ALPHA){ goto cleanup_png_read; }
  1941. if (png_get_channels(png_ptr, info_ptr) != 4) { goto cleanup_png_read; }
  1942. int W = png_get_image_width(png_ptr, info_ptr);
  1943. int H = png_get_image_height(png_ptr, info_ptr);
  1944. unsigned char* buf=calloc(W*4,H*sizeof(unsigned char));
  1945. for(int i=0;i<H;i++){ png_read_row(png_ptr, &buf[((H-i-1)*W)*4], NULL); }
  1946. im->Texture=tnsCreate2DTexture(GL_RGBA8,W,H,0);
  1947. tnsBindTexture(im->Texture); glTexSubImage2D(GL_TEXTURE_2D,0,0,0,W,H,GL_RGBA,GL_UNSIGNED_BYTE,buf);
  1948. tnsUnbindTexture();
  1949. free(buf);
  1950. cleanup_png_read:
  1951. if(png_ptr && info_ptr) png_destroy_read_struct(&png_ptr,&info_ptr,0);
  1952. }
  1953. void tnsUseImage(tnsImage* im){
  1954. if(im->UserCount==0 || !im->Texture){
  1955. if(!im->MemPNG){
  1956. if(im->Texture){ tnsDeleteTexture(im->Texture); im->Texture=0; }
  1957. }else{
  1958. tns_ImageToTexture(im);
  1959. }
  1960. }
  1961. im->UserCount++;
  1962. }
  1963. void tnsRefreshImage(tnsImage* im,void* data){
  1964. if(im->MemPNG){free(im->MemPNG);}
  1965. im->MemPNG=data; tnsDeleteTexture(im->Texture); im->Texture=0;
  1966. }
  1967. void tnsStopUsingImage(tnsImage* im){
  1968. im->UserCount--;
  1969. if(im->UserCount<=0){ im->UserCount=0; tnsDeleteTexture(im->Texture); im->Texture=0; }
  1970. }
  1971. void tnsRemoveImage(tnsImage* im){
  1972. while(im->UserCount) tnsStopUsingImage(im);
  1973. if(im->MemPNG) free(im->MemPNG);
  1974. lstRemoveItem(&T->Images,im); memFree(im);
  1975. }
  1976. #endif //png
  1977. //====================================================[NEW RENDER KERNEL]
  1978. //=================[Immediate-style api]
  1979. void tnsColor4d(real r, real g, real b, real a){ tnsVectorSet4(T->StateColor,r,g,b,a); }
  1980. void tnsColor4dv(real *rgba){ tnsVectorSet4v(T->StateColor,rgba); }
  1981. void tnsLineWidth(real Width){ if(TNS_FLOAT_CLOSE_ENOUGH_WIDER(Width,T->StateLineWidth)) return;
  1982. T->StateLineWidth=Width;
  1983. }
  1984. void tnsPointSize(real PointSize){ if(TNS_FLOAT_CLOSE_ENOUGH_WIDER(PointSize,T->StatePointSize)) return;
  1985. T->StatePointSize=PointSize;
  1986. }
  1987. void tnsVertex3d(real x, real y, real z){
  1988. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  1989. int vend = c->VertEnd;
  1990. c->UseVert = 1;
  1991. if (!c->Dimensions) c->Dimensions = 3;
  1992. if(arrEnsureLength(&T->Vert, T->NextVert+c->Dimensions, &T->MaxVert, sizeof(GLfloat))){
  1993. glBindBuffer(GL_ARRAY_BUFFER, T->VertBufObject);
  1994. glBufferData(GL_ARRAY_BUFFER, T->MaxVert * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1995. }
  1996. GLfloat *varr = T->Vert;
  1997. if (c->Dimensions == 3){
  1998. varr[vend] = x;
  1999. varr[vend + 1] = y;
  2000. varr[vend + 2] = z;
  2001. c->NumVert++;
  2002. T->NextVert += 3;
  2003. c->VertEnd += 3;
  2004. }else{
  2005. varr[vend] = x;
  2006. varr[vend + 1] = y;
  2007. c->NumVert++;
  2008. T->NextVert += 2;
  2009. c->VertEnd += 2;
  2010. }
  2011. }
  2012. void tnsVertex2d(real x, real y){
  2013. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  2014. int vend = c->VertEnd;
  2015. c->UseVert = 1;
  2016. if (!c->Dimensions) c->Dimensions = 2;
  2017. if(arrEnsureLength(&T->Vert, T->NextVert+c->Dimensions, &T->MaxVert, sizeof(GLfloat))){
  2018. glBindBuffer(GL_ARRAY_BUFFER, T->VertBufObject);
  2019. glBufferData(GL_ARRAY_BUFFER, T->MaxVert * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  2020. }
  2021. GLfloat *varr = T->Vert;
  2022. if (c->Dimensions == 2){
  2023. varr[vend] = x;
  2024. varr[vend + 1] = y;
  2025. c->NumVert++;
  2026. T->NextVert += 2;
  2027. c->VertEnd += 2;
  2028. }else{
  2029. tnsVertex3d(x, y, 0.0f);
  2030. }
  2031. }
  2032. void tnsVertexArray2d(real *verts, int amount){
  2033. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  2034. int trans = 2 * amount;
  2035. int vend = c->VertEnd;
  2036. c->UseVert = 1;
  2037. if (!c->Dimensions) c->Dimensions = 2;
  2038. if(arrEnsureLength(&T->Vert, T->NextVert+c->Dimensions*amount, &T->MaxVert, sizeof(GLfloat))){
  2039. glBindBuffer(GL_ARRAY_BUFFER, T->VertBufObject);
  2040. glBufferData(GL_ARRAY_BUFFER, T->MaxVert * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  2041. }
  2042. GLfloat *varr = T->Vert;
  2043. if (c->Dimensions == 2){
  2044. int i;
  2045. for (i = 0; i < trans; i++){
  2046. varr[vend] = verts[i];
  2047. vend++;
  2048. }
  2049. //memcpy(&varr[vend], verts, trans*sizeof(real));
  2050. c->VertEnd += trans;
  2051. c->NumVert += amount;
  2052. T->NextVert += trans;
  2053. }
  2054. }
  2055. void tnsVertexArray3d(real *verts, int amount){
  2056. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  2057. int trans = 3 * amount;
  2058. int vend = c->VertEnd;
  2059. c->UseVert = 1;
  2060. if (!c->Dimensions) c->Dimensions = 3;
  2061. if(arrEnsureLength(&T->Vert, T->NextVert+c->Dimensions*amount, &T->MaxVert, sizeof(GLfloat))){
  2062. glBindBuffer(GL_ARRAY_BUFFER, T->VertBufObject);
  2063. glBufferData(GL_ARRAY_BUFFER, T->MaxVert * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  2064. }
  2065. GLfloat *varr = T->Vert;
  2066. if (c->Dimensions == 3){
  2067. int i;
  2068. for (i = 0; i < trans; i++){
  2069. varr[vend] = verts[i];
  2070. vend++;
  2071. }
  2072. //memcpy(&varr[vend], verts, trans*sizeof(real));
  2073. c->VertEnd += trans;
  2074. c->NumVert += amount;
  2075. T->NextVert += trans;
  2076. }
  2077. }
  2078. void tnsColorArray4d(real *colors, int amount){
  2079. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  2080. int trans = 4 * amount;
  2081. int ofst = c->ColorEnd;
  2082. c->UseColor = 1;
  2083. if(arrEnsureLength(&T->Color, T->NextColor+4*amount, &T->MaxColor, sizeof(GLfloat))){
  2084. glBindBuffer(GL_ARRAY_BUFFER, T->ColorBufObject);
  2085. glBufferData(GL_ARRAY_BUFFER, T->MaxColor * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  2086. }
  2087. GLfloat *carr = T->Color;
  2088. int i;
  2089. for (i = 0; i < trans; i++){
  2090. carr[ofst] = colors[i];
  2091. ofst++;
  2092. }
  2093. //memcpy(&T->Color[c->ColorEnd], colors, trans*sizeof(real));
  2094. c->ColorEnd += trans;
  2095. T->NextColor += trans;
  2096. }
  2097. void tnsNormalArray3d(real *normals, int amount){
  2098. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  2099. int trans = 3 * amount;
  2100. int ofst = c->NormalEnd;
  2101. c->UseNormal = 1;
  2102. if(arrEnsureLength(&T->Normal, T->NextNormal+3*amount, &T->MaxNormal, sizeof(GLfloat))){
  2103. glBindBuffer(GL_ARRAY_BUFFER, T->NormalBufObject);
  2104. glBufferData(GL_ARRAY_BUFFER, T->MaxNormal * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  2105. }
  2106. GLfloat *narr = T->Normal;
  2107. int i;
  2108. for (i = 0; i < trans; i++){
  2109. narr[ofst] = normals[i];
  2110. ofst++;
  2111. }
  2112. //memcpy(&T->Normal[c->NormalEnd], normals, trans*sizeof(real));
  2113. c->NormalEnd += trans;
  2114. T->NextNormal += trans;
  2115. }
  2116. void tnsTexCoordArray2d(real *coords, int amount){
  2117. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  2118. int trans = 2 * amount;
  2119. int ofst = c->TexCoordEnd;
  2120. c->UseTexCoord = 1;
  2121. c->UVDimensions = 2;
  2122. if(arrEnsureLength(&T->TexCoord, T->NextTexCoord+2*amount, &T->MaxTexCoord, sizeof(GLfloat))){
  2123. glBindBuffer(GL_ARRAY_BUFFER, T->TexCoordBufObject);
  2124. glBufferData(GL_ARRAY_BUFFER, T->MaxTexCoord * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  2125. }
  2126. GLfloat *carr = T->TexCoord;
  2127. int i;
  2128. for (i = 0; i < trans; i++){
  2129. carr[ofst] = coords[i];
  2130. ofst++;
  2131. }
  2132. //memcpy(&T->TexCoord[c->TexCoordEnd], coords, trans*sizeof(real));
  2133. c->TexCoordEnd += trans;
  2134. T->NextTexCoord += trans;
  2135. }
  2136. void tnsTexCoordArray3d(real *coords, int amount){
  2137. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  2138. int trans = 3 * amount;
  2139. int ofst = c->TexCoordEnd;
  2140. c->UseTexCoord = 1;
  2141. c->UVDimensions = 3;
  2142. if(arrEnsureLength(&T->TexCoord, T->NextTexCoord+3*amount, &T->MaxTexCoord, sizeof(GLfloat))){
  2143. glBindBuffer(GL_ARRAY_BUFFER, T->TexCoordBufObject);
  2144. glBufferData(GL_ARRAY_BUFFER, T->MaxTexCoord * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  2145. }
  2146. GLfloat *carr = T->TexCoord;
  2147. int i;
  2148. for (i = 0; i < trans; i++){ carr[ofst] = coords[i]; ofst++; }
  2149. c->TexCoordEnd += trans;
  2150. T->NextTexCoord += trans;
  2151. }
  2152. void tnsIndexArray(GLuint *index, short amount){
  2153. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  2154. //if (c->UseIndex) return;
  2155. c->UseIndex = 1;
  2156. if(arrEnsureLength(&T->Index, T->NextIndex+amount, &T->MaxIndex, sizeof(GLuint))){
  2157. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, T->IndexBufObject);
  2158. glBufferData(GL_ELEMENT_ARRAY_BUFFER, T->MaxIndex * sizeof(GLuint), 0, GL_DYNAMIC_DRAW);
  2159. }
  2160. memcpy(&T->Index[c->IndexEnd], index, amount * sizeof(GLuint));
  2161. c->IndexEnd += amount;
  2162. c->NumIndex += amount;
  2163. T->NextIndex += amount;
  2164. }
  2165. void tnsPackAs(GLenum Mode){
  2166. arrEnsureLength(&T->DrawingCommand, T->NextCommand+1, &T->MaxCommand, sizeof(tnsCommand));
  2167. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  2168. tnsCommand *nc;
  2169. T->NextCommand++;
  2170. nc = &T->DrawingCommand[T->NextCommand];
  2171. memcpy(c->UniformColor, T->StateColor, sizeof(GLfloat) * 4);
  2172. #ifndef LAGUI_ANDROID
  2173. if (Mode == GL_QUAD_STRIP || Mode == GL_QUADS) Mode=GL_TRIANGLE_STRIP;
  2174. #endif
  2175. //if (Mode == GL_QUADS) Mode=GL_TRIANGLE_STRIP;
  2176. c->Mode = Mode;
  2177. c->ReplaceShader = T->StateShader;
  2178. c->ColorTexture = T->StateTexColor;
  2179. c->TextureMode = T->StateTextureMode;
  2180. c->MultiplyColor = T->StateMultiplyColor;
  2181. c->LineWidth=T->StateLineWidth;
  2182. c->PointSize=T->StatePointSize;
  2183. c->UseHalftone = T->StateUseHalftone;
  2184. memset(nc, 0, sizeof(tnsCommand));
  2185. nc->VertBegin = nc->VertEnd = c->VertEnd;
  2186. nc->NormalBegin = nc->NormalEnd = c->NormalEnd;
  2187. nc->ColorBegin = nc->ColorEnd = c->ColorEnd;
  2188. nc->TexCoordBegin = nc->TexCoordEnd = c->TexCoordEnd;
  2189. nc->IndexBegin = nc->IndexEnd = c->IndexEnd;
  2190. }
  2191. void tnsFlush(){
  2192. tnsShader *cs = T->CurrentShader;
  2193. tnsCommand *tc = &T->DrawingCommand[0];
  2194. tnsCommand *c = tc;
  2195. int PrevDimensions = 0;
  2196. int LastVertBegin = 0;
  2197. if (!c || !cs) return;
  2198. if (T->NextVert){ glBindBuffer(GL_ARRAY_BUFFER, T->VertBufObject);
  2199. glBufferSubData(GL_ARRAY_BUFFER, 0, T->NextVert * sizeof(GLfloat), T->Vert);
  2200. }
  2201. if (T->NextColor){ glBindBuffer(GL_ARRAY_BUFFER, T->ColorBufObject);
  2202. glBufferSubData(GL_ARRAY_BUFFER, 0, T->NextColor * sizeof(GLfloat), T->Color);
  2203. }
  2204. if (T->NextNormal){ glBindBuffer(GL_ARRAY_BUFFER, T->NormalBufObject);
  2205. glBufferSubData(GL_ARRAY_BUFFER, 0, T->NextNormal * sizeof(GLfloat), T->Normal);
  2206. }
  2207. if (T->NextTexCoord){ glBindBuffer(GL_ARRAY_BUFFER, T->TexCoordBufObject);
  2208. glBufferSubData(GL_ARRAY_BUFFER, 0, T->NextTexCoord * sizeof(GLfloat), T->TexCoord);
  2209. }
  2210. for (int i=0;i<T->NextCommand;i++){ c=&T->DrawingCommand[i];
  2211. if (c->LineWidth!=T->SetLineWidth){ glLineWidth(c->LineWidth); T->SetLineWidth=c->LineWidth; }
  2212. if (c->PointSize!=T->SetPointSize){
  2213. glPointSize(c->PointSize); T->SetPointSize=c->PointSize;
  2214. }
  2215. if (c->ReplaceShader && c->ReplaceShader != T->CurrentShader){
  2216. tnsEnableShaderv(c->ReplaceShader); cs = c->ReplaceShader;
  2217. if (!cs) continue;
  2218. }
  2219. glBindBuffer(GL_ARRAY_BUFFER, T->VertBufObject);
  2220. if (c->UseVert){
  2221. glEnableVertexAttribArray(cs->iVertex);
  2222. glVertexAttribPointer(cs->iVertex, (c->Dimensions ? c->Dimensions : PrevDimensions),
  2223. GL_FLOAT, 0, 0, c->VertBegin * sizeof(GLfloat));
  2224. LastVertBegin = c->VertBegin;
  2225. }else{
  2226. glEnableVertexAttribArray(cs->iVertex);
  2227. glVertexAttribPointer(cs->iVertex, (c->Dimensions ? c->Dimensions : PrevDimensions),
  2228. GL_FLOAT, 0, 0, LastVertBegin * sizeof(GLfloat));
  2229. }
  2230. PrevDimensions = (c->Dimensions ? c->Dimensions : PrevDimensions);
  2231. if (c->UseIndex){
  2232. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, T->IndexBufObject);
  2233. glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, c->NumIndex * sizeof(GLuint), &T->Index[c->IndexBegin]);
  2234. }
  2235. if (cs->iNormal != -1){
  2236. glBindBuffer(GL_ARRAY_BUFFER, T->NormalBufObject);
  2237. if (c->UseNormal){
  2238. glEnableVertexAttribArray(cs->iNormal); tnsUniformUseNormal(cs,1);
  2239. }
  2240. glVertexAttribPointer(cs->iNormal, 3, GL_FLOAT, 0, 0, c->NormalBegin * sizeof(GLfloat));
  2241. if (!c->UseNormal || c->Dimensions == 2){
  2242. glDisableVertexAttribArray(cs->iNormal); tnsUniformUseNormal(cs,0);
  2243. glVertexAttrib3f(cs->iNormal, 0, 0, -1);
  2244. }
  2245. }
  2246. if (cs->iColor != -1){
  2247. glBindBuffer(GL_ARRAY_BUFFER, T->ColorBufObject);
  2248. if (c->UseColor){
  2249. glEnableVertexAttribArray(cs->iColor);
  2250. glVertexAttribPointer(cs->iColor, 4, GL_FLOAT, 0, 0, c->ColorBegin * sizeof(GLfloat));
  2251. }else{
  2252. glDisableVertexAttribArray(cs->iColor);
  2253. glVertexAttrib4fv(cs->iColor, c->UniformColor);
  2254. }
  2255. }
  2256. if (cs->iUV != -1){
  2257. if (c->UseTexCoord){
  2258. glBindBuffer(GL_ARRAY_BUFFER, T->TexCoordBufObject);
  2259. if (c->UseTexCoord){ glEnableVertexAttribArray(cs->iUV);
  2260. glVertexAttribPointer(cs->iUV, c->UVDimensions, GL_FLOAT, 0, 0, c->TexCoordBegin * sizeof(GLfloat)); }
  2261. else{ glDisableVertexAttribArray(cs->iUV); }
  2262. }
  2263. }
  2264. if (c->TextureMode && c->ColorTexture && cs->iTexColor != -1){
  2265. tnsBindTexture(c->ColorTexture); tnsUniformUseTexture(cs, c->TextureMode, c->ColorTexture->Multisample);
  2266. }else{
  2267. tnsUniformUseTexture(cs, 0, 0); //tnsUnbindTexture();
  2268. }
  2269. if(cs->iMultiplyColor != -1){ tnsUniformUseMultiplyColor(cs, c->MultiplyColor); }
  2270. if(cs->iUseHalftone != -1){
  2271. tnsUniformUseHalftone(cs, c->UseHalftone);
  2272. tnsUniformHalftoneSize(cs, MAIN.ViewportHalftoneSize);
  2273. }
  2274. if (c->UseIndex){
  2275. glDrawElements(c->Mode, c->NumIndex, GL_UNSIGNED_INT, 0);
  2276. }else{
  2277. glDrawArrays(c->Mode, 0, c->NumVert);
  2278. }
  2279. }
  2280. T->NextCommand=0;
  2281. c = &T->DrawingCommand[0];
  2282. memset(c, 0, sizeof(tnsCommand));
  2283. c->ColorBegin = c->ColorEnd = T->NextColor = 0;
  2284. c->NormalBegin = c->NormalEnd = T->NextNormal = 0;
  2285. c->TexCoordBegin = c->TexCoordEnd = T->NextTexCoord = 0;
  2286. c->VertBegin = c->VertEnd = T->NextVert = 0;
  2287. c->IndexBegin = c->IndexEnd = T->NextIndex = 0;
  2288. //must --why?
  2289. //T->BindedShader = 0;
  2290. };
  2291. //============================================================================================[offscr]
  2292. const GLuint TNS_ATTACHMENT_ARRAY_NONE[] = {GL_NONE};
  2293. const GLuint TNS_ATTACHMENT_ARRAY[] = {GL_COLOR_ATTACHMENT0};
  2294. const GLuint TNS_ATTACHMENT_ARRAY_1[] = {GL_COLOR_ATTACHMENT1};
  2295. const GLuint TNS_ATTACHMENT_ARRAY_2[] = {GL_COLOR_ATTACHMENT2};
  2296. const GLuint TNS_ATTACHMENT_ARRAY_1_2[] = {GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
  2297. const GLuint TNS_ATTACHMENT_ARRAY_0_1_2[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
  2298. const GLenum TNS_WINDOW_DRAWBUFFER_ARRAY[] = {GL_BACK};
  2299. tnsOffscreen *tnsCreateOffscreenHandle(){
  2300. if(!T->CurrentContext){ logPrintNew("tnsCreateOffscreenHandle() called without GL Context. Exiting"); exit(0); }
  2301. tnsOffscreen *toff = CreateNew(tnsOffscreen); toff->FboContext=T->CurrentContext;
  2302. #ifdef LA_USE_GLES
  2303. toff->FboSurface=T->CurrentSurface;
  2304. #endif
  2305. #ifdef _WIN32
  2306. toff->FboDC=T->CurrentDC;
  2307. #endif
  2308. #ifdef __linux__
  2309. toff->FboWindow=T->CurrentWindow;
  2310. #endif
  2311. glGenFramebuffers(1, &toff->FboHandle);
  2312. lstAppendItem(&T->Offscreens, toff);
  2313. return toff;
  2314. }
  2315. void tnsAttach2DOffscreenBuffer(tnsOffscreen *target, GLuint attatchment, tnsTexture *use){
  2316. if (!target || !use || target->FboHandle == -1 || use->GLTexHandle == -1) return;
  2317. if (attatchment >= GL_COLOR_ATTACHMENT0 && attatchment <= GL_COLOR_ATTACHMENT15){
  2318. //if (target->pColor[attatchment - GL_COLOR_ATTACHMENT0]) return;
  2319. glBindFramebuffer(GL_FRAMEBUFFER, target->FboHandle);
  2320. tnsBindTexture(use);
  2321. glFramebufferTexture2D(GL_FRAMEBUFFER, attatchment, use->GLTexType, use->GLTexHandle, 0);
  2322. target->pColor[attatchment - GL_COLOR_ATTACHMENT0] = use;
  2323. tnsUnbindTexture();
  2324. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  2325. }elif (attatchment == GL_DEPTH_ATTACHMENT || attatchment==GL_STENCIL_ATTACHMENT){
  2326. //if (target->pDepth) return;
  2327. glBindFramebuffer(GL_FRAMEBUFFER, target->FboHandle);
  2328. tnsBindTexture(use);
  2329. glFramebufferTexture2D(GL_FRAMEBUFFER, attatchment, use->GLTexType, use->GLTexHandle, 0);
  2330. //glBindRenderbufferEXT(GL_RENDERBUFFER, use->GLTexHandle);
  2331. //glBindFramebuffer(GL_FRAMEBUFFER, target->FboHandle);
  2332. //glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, use->GLTexHandle);
  2333. target->pDepth = use;
  2334. tnsUnbindTexture();
  2335. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  2336. //glBindRenderbufferEXT(GL_RENDERBUFFER, 0);
  2337. //glBindFramebuffer(GL_FRAMEBUFFER, 0);
  2338. }
  2339. GLenum result = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  2340. //if (result == GL_FRAMEBUFFER_COMPLETE) { printf("Framebuffer complete!\n"); }
  2341. //else { printf("Framebuffer incomplete!\n"); }
  2342. }
  2343. void tnsDetach2DOffscreenBuffer(tnsOffscreen *target, GLuint which_attach_point){
  2344. if (which_attach_point >= GL_COLOR_ATTACHMENT0 && which_attach_point <= GL_COLOR_ATTACHMENT15){
  2345. if (target->pColor[which_attach_point - GL_COLOR_ATTACHMENT0] == 0) return;
  2346. glBindFramebuffer(GL_FRAMEBUFFER, target->FboHandle);
  2347. glFramebufferTexture2D(GL_FRAMEBUFFER, which_attach_point, GL_TEXTURE_2D, 0, 0);
  2348. tnsDeleteTexture(target->pColor[which_attach_point - GL_COLOR_ATTACHMENT0]);
  2349. target->pColor[which_attach_point - GL_COLOR_ATTACHMENT0] = 0;
  2350. }elif (which_attach_point == GL_DEPTH_ATTACHMENT || which_attach_point==GL_STENCIL_ATTACHMENT){
  2351. if (target->pDepth) return;
  2352. glBindFramebuffer(GL_FRAMEBUFFER, target->FboHandle);
  2353. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
  2354. tnsDeleteTexture(target->pDepth);
  2355. target->pDepth = 0;
  2356. }
  2357. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  2358. tnsUnbindTexture();
  2359. }
  2360. tnsOffscreen *tnsCreate2DOffscreen(int glInternalFormat, int w, int h, int Multisample, int WithDepth, int WithStencil){
  2361. tnsOffscreen *toff = tnsCreateOffscreenHandle();
  2362. tnsTexture *color; tnsTexture *depth;
  2363. if(glInternalFormat){
  2364. color = tnsCreate2DTexture(glInternalFormat, w, h, Multisample);
  2365. tnsAttach2DOffscreenBuffer(toff, GL_COLOR_ATTACHMENT0, color);
  2366. }
  2367. if(WithDepth || WithStencil){
  2368. int format=GL_DEPTH_COMPONENT;
  2369. if(WithStencil){ format=GL_DEPTH_STENCIL; }
  2370. depth = tnsCreate2DTexture(format, w, h, Multisample);
  2371. tnsAttach2DOffscreenBuffer(toff, GL_DEPTH_ATTACHMENT, depth);
  2372. if(WithStencil){ tnsAttach2DOffscreenBuffer(toff, GL_STENCIL_ATTACHMENT, depth); }
  2373. }
  2374. return toff;
  2375. }
  2376. tnsOffscreen *tnsCreateDeferredOffscreen(int w, int h, int Multisample){
  2377. tnsOffscreen *toff = tnsCreateOffscreenHandle();
  2378. tnsTexture *color,*normal,*gpos; tnsTexture *depth;
  2379. color = tnsCreate2DTexture(GL_RGBA8, w, h, Multisample); tnsAttach2DOffscreenBuffer(toff, GL_COLOR_ATTACHMENT0, color);
  2380. normal = tnsCreate2DTexture(GL_RGB8, w, h, Multisample); tnsAttach2DOffscreenBuffer(toff, GL_COLOR_ATTACHMENT1, normal);
  2381. gpos = tnsCreate2DTexture(GL_RGB32F, w, h, Multisample); tnsAttach2DOffscreenBuffer(toff, GL_COLOR_ATTACHMENT2, gpos);
  2382. depth = tnsCreate2DTexture(GL_DEPTH_COMPONENT, w, h, Multisample); tnsAttach2DOffscreenBuffer(toff, GL_DEPTH_ATTACHMENT, depth);
  2383. return toff;
  2384. }
  2385. void tnsRecreateFBO(tnsOffscreen *off){
  2386. if(off->FboContext){
  2387. #ifdef __linux__
  2388. SYSWINDOW sw=T->CurrentWindow; SYSGLCONTEXT sc=T->CurrentContext; void* gls=0;
  2389. #ifdef LA_USE_GLES
  2390. gls=&T->CurrentSurface;
  2391. #endif
  2392. tnsContextMakeFBOCurrent(off);
  2393. glDeleteFramebuffers(1, &off->FboHandle);
  2394. tnsContextMakeCurrent(sc,sw,gls);
  2395. off->FboContext=sc; off->FboWindow=sw;
  2396. #endif
  2397. #ifdef _WIN32
  2398. SYSTEMDC sd=T->CurrentDC; SYSGLCONTEXT sc=T->CurrentContext;
  2399. tnsContextMakeFBOCurrent(off);
  2400. glDeleteFramebuffers(1, &off->FboHandle);
  2401. tnsContextMakeCurrent(sc,sd,0);
  2402. off->FboContext=sc; off->FboDC=sd;
  2403. #endif
  2404. }
  2405. glGenFramebuffers(1, &off->FboHandle);
  2406. if(off->pColor[0]) tnsAttach2DOffscreenBuffer(off, GL_COLOR_ATTACHMENT0, off->pColor[0]);
  2407. if(off->pColor[1]) tnsAttach2DOffscreenBuffer(off, GL_COLOR_ATTACHMENT1, off->pColor[1]);
  2408. if(off->pColor[2]) tnsAttach2DOffscreenBuffer(off, GL_COLOR_ATTACHMENT2, off->pColor[2]);
  2409. if(off->pColor[3]) tnsAttach2DOffscreenBuffer(off, GL_COLOR_ATTACHMENT3, off->pColor[3]);
  2410. if(off->pDepth){ tnsAttach2DOffscreenBuffer(off, GL_DEPTH_ATTACHMENT, off->pDepth);
  2411. if(off->pDepth->GLTexBitsType==GL_DEPTH_STENCIL) tnsAttach2DOffscreenBuffer(off, GL_STENCIL_ATTACHMENT, off->pDepth);
  2412. }
  2413. }
  2414. void tnsEnsureOffscreenContext(tnsOffscreen *off){
  2415. if(off->FboContext!=T->CurrentContext){ tnsRecreateFBO(off); }
  2416. }
  2417. void tnsEnsureOffscreenStatus(tnsOffscreen *off, int w, int h){
  2418. tnsTexture* t=off->pColor[0];
  2419. tnsEnsureOffscreenContext(off);
  2420. if(t->Width==w && t->Height==h) return;
  2421. t->Width = w; t->Height = h; tnsConfigure2DTexture(t);
  2422. if((t=off->pColor[1])){ t->Width = w; t->Height = h; tnsConfigure2DTexture(t); }
  2423. if((t=off->pColor[2])){ t->Width = w; t->Height = h; tnsConfigure2DTexture(t); }
  2424. if((t=off->pColor[3])){ t->Width = w; t->Height = h; tnsConfigure2DTexture(t); }
  2425. if((t=off->pDepth)){ t->Width = w; t->Height = h; tnsConfigure2DTexture(t); }
  2426. }
  2427. void tnsDelete2DOffscreen(tnsOffscreen *o){
  2428. if (!o) return;
  2429. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  2430. tnsEnsureOffscreenContext(o);
  2431. for(int i=0;i<16;i++){
  2432. if(o->pColor[i]){
  2433. tnsDetach2DOffscreenBuffer(o, GL_COLOR_ATTACHMENT0+i);
  2434. tnsDeleteTexture(o->pColor[0]);
  2435. }
  2436. }
  2437. if(o->pDepth){
  2438. tnsDetach2DOffscreenBuffer(o, GL_DEPTH_ATTACHMENT);
  2439. tnsDeleteTexture(o->pDepth);
  2440. }
  2441. glDeleteFramebuffers(1, &o->FboHandle);
  2442. lstRemoveItem(&T->Offscreens, o);
  2443. FreeMem(o);
  2444. }
  2445. void tnsDrawToOffscreen(tnsOffscreen *toff, int HowMany, GLuint *AttachmentArray){
  2446. if (!toff) return;
  2447. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, toff->FboHandle); glClear(0);
  2448. if(AttachmentArray==TNS_ATTACHMENT_ARRAY_NONE){glDrawBuffer(GL_NONE);}
  2449. else glDrawBuffers((HowMany ? HowMany : 1), (AttachmentArray ? AttachmentArray : TNS_ATTACHMENT_ARRAY));
  2450. glClear(0);
  2451. T->IsOffscreen = 1;
  2452. T->BindedShader = 0;
  2453. }
  2454. void tnsDrawToOffscreenOnlyBind(tnsOffscreen *toff, int HowMany, GLuint *AttachmentArray){
  2455. if (!toff) return;
  2456. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, toff->FboHandle);
  2457. }
  2458. void tnsReadFromOffscreen(tnsOffscreen *toff){
  2459. if (!toff) return;
  2460. glBindFramebuffer(GL_READ_FRAMEBUFFER, toff->FboHandle);
  2461. }
  2462. void tnsDrawToScreen(){
  2463. glBindFramebuffer(GL_FRAMEBUFFER, 0); glClear(0);
  2464. //glDrawBuffer(GL_BACK); printf("%d\n", glGetError());
  2465. T->IsOffscreen = 0;
  2466. T->BindedShader = 0;
  2467. }
  2468. //===========================================================================[FONT]
  2469. tnsFontManager *FM;
  2470. void tnsSetuptnsFontManager(){
  2471. FM = CreateNew(tnsFontManager);
  2472. FM->BufferWidth = TNS_FONT_BUFFER_W_DEFAULT;
  2473. FM->L = INT_MIN; FM->R = INT_MAX; FM->B = INT_MAX; FM->U = INT_MIN;
  2474. };
  2475. void tnsQuitFontManager(){
  2476. tnsInvalidateFontCache();
  2477. tnsFont*f=FM->UsingFont;
  2478. for(int i=0;i<f->NumFaces;i++){
  2479. FT_Done_Face(f->ftface[i]);
  2480. }
  2481. if(f->ftfacemono) FT_Done_Face(f->ftfacemono);
  2482. FT_Done_FreeType(f->ftlib);
  2483. free(f->characters);
  2484. free(f->monocharacters);
  2485. free(f);
  2486. FreeMem(FM);
  2487. }
  2488. int next_p2(int a){
  2489. int rval = 1;
  2490. while (rval < a)
  2491. rval <<= 1;
  2492. return rval;
  2493. }
  2494. real tnsGetMonoFontAdvance(){
  2495. return FM->UsingFont->MonoAdvance;
  2496. }
  2497. int tnsInvalidateFontCache(){
  2498. tnsFont*f=FM->UsingFont;
  2499. for(int i=0;i<TNS_UNICODE_COUNT;i++){ if(f->characters[i]){ free(f->characters[i]); f->characters[i]=0; } }
  2500. for(int i=0;i<TNS_MONO_COUNT;i++){ if(f->monocharacters[i]){ free(f->monocharacters[i]); f->monocharacters[i]=0; } }
  2501. f->CurrentX=f->CurrentY=0;
  2502. f->height = LA_RH*(MAIN.FontSize/2.0f+0.5f);
  2503. int GenHeight=LA_RH*MAIN.FontSize;
  2504. for(int i=0;i<f->NumFaces;i++){
  2505. FT_Set_Char_Size(f->ftface[i], 0, GenHeight << 6, 96, 96);
  2506. FT_Glyph glyph; FT_Fixed half_adv=0;
  2507. if(!FT_Get_Advance(f->ftface[i],'a',FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, &half_adv)){
  2508. if (FT_Load_Char(f->ftface[i], 'a', FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP)||
  2509. FT_Get_Glyph(f->ftface[i]->glyph, &glyph)){ SEND_PANIC_ERROR("Monospace font doesn't contain character 'a'"); }
  2510. f->MonoAdvance=(real)f->ftface[i]->glyph->advance.x/64.0;
  2511. if(glyph) FT_Done_Glyph(glyph);
  2512. }
  2513. }
  2514. if(f->ftfacemono){
  2515. FT_Set_Char_Size(f->ftfacemono, 0, (GenHeight << 6)*f->MonoScale, 96, 96); FT_Glyph glyph;
  2516. if (FT_Load_Char(f->ftfacemono, 'a', FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP)||
  2517. FT_Get_Glyph(f->ftfacemono->glyph, &glyph)){ SEND_PANIC_ERROR("Monospace font doesn't contain character 'a'"); }
  2518. f->MonoAdvance=(real)f->ftfacemono->glyph->advance.x/64.0;
  2519. if(glyph) FT_Done_Glyph(glyph);
  2520. }
  2521. #ifndef LA_USE_GLES
  2522. if(glClearTexImage) glClearTexImage(f->TexBuffer.GLTexHandle, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  2523. #endif
  2524. }
  2525. tnsFontSingleCharacter *tfntFetchCharTextureIDW(uint32_t ch, int UseMono);
  2526. #ifndef LAGUI_FONT_CUSTOM_PATH
  2527. #define LAGUI_FONT_CUSTOM_PATH "/usr/share/fonts/opentype/noto/"
  2528. #endif
  2529. const char* TNS_FONT_CUSTOM=LAGUI_FONT_CUSTOM_PATH;
  2530. const char* TNS_FONT_LOAD_OPTIONS[9]={"","fonts/","lagui/fonts/","../","../fonts/","../lagui/fonts/","../../","../../fonts/","../../lagui/fonts/"};
  2531. const char* TNS_FONT_LOAD_OPTIONS_FROM_HOME[2]={".local/share/fonts/lagui/",".local/share/fonts/"};
  2532. int tnsLoadSystemFontMono(char* from, char* mono){
  2533. char buf[8192]; if(!FM->UsingFont || !mono || !mono[0]) return 0;
  2534. tnsFont *f=FM->UsingFont;
  2535. int GenHeight=LA_RH*MAIN.FontSize;
  2536. FT_Fixed full_adv=0,half_adv=0;
  2537. for(int i=0;i<f->NumFaces;i++){
  2538. if(!FT_Get_Advance(f->ftface[i],U'我',FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, &full_adv)) break;
  2539. }
  2540. for(int i=-2;i<11;i++){
  2541. char* option;
  2542. if(i==-2){ sprintf(buf,"%s%s%s",TNS_FONT_CUSTOM,TNS_FONT_CUSTOM[strlen(TNS_FONT_CUSTOM)-1]=='/'?"":"/",mono); }
  2543. elif(i<9){ option=(i==-1)?from:TNS_FONT_LOAD_OPTIONS[i]; sprintf(buf,"%s%s%s",SSTR(MAIN.WorkingDirectory),option,mono); }
  2544. else{ option=TNS_FONT_LOAD_OPTIONS_FROM_HOME[i-9]; sprintf(buf,"%s/%s%s",getenv("HOME"),option,mono); }
  2545. FILE* fontfile=fopen(buf,"rb"); if(!fontfile) continue;
  2546. fseek(fontfile,0,SEEK_END); int filesize=ftell(fontfile);
  2547. void*fontdata=CreateNewBuffer(char,filesize);
  2548. fseek(fontfile,0,SEEK_SET); fread(fontdata,filesize,1,fontfile);
  2549. FT_Face face; FT_Long i,num_faces; FT_Open_Args args; args.flags=FT_OPEN_MEMORY;
  2550. args.memory_base=fontdata; args.memory_size=filesize;
  2551. if(FT_Open_Face(f->ftlib, &args, 0, &f->ftfacemono)) continue;
  2552. FT_Select_Charmap(f->ftfacemono, FT_ENCODING_UNICODE);
  2553. FT_Set_Char_Size(f->ftfacemono, 0, GenHeight << 6, 96, 96);
  2554. logPrint("Loaded monospace font: %s\n",buf);
  2555. if(!FT_Get_Advance(f->ftfacemono,'a',FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, &half_adv)){
  2556. f->MonoScale=(real)full_adv/(half_adv*2);
  2557. FT_Set_Char_Size(f->ftfacemono, 0, (GenHeight << 6)*f->MonoScale, 96, 96);
  2558. logPrintNew("Monospace font scale: %.2f\n",f->MonoScale); FT_Glyph glyph;
  2559. if (FT_Load_Char(f->ftfacemono, 'a', FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP)||
  2560. FT_Get_Glyph(f->ftfacemono->glyph, &glyph)){ SEND_PANIC_ERROR("Monospace font doesn't contain character 'a'"); }
  2561. f->MonoAdvance=(real)f->ftfacemono->glyph->advance.x/64.0;
  2562. if(glyph) FT_Done_Glyph(glyph);
  2563. }
  2564. return 1;
  2565. }
  2566. return 0;
  2567. };
  2568. int tnsLoadSystemFont(char* from, char* name){
  2569. char buf[8192];
  2570. tnsFont *f=FM->UsingFont; if(!f){
  2571. f = CreateNew(tnsFont);
  2572. f->characters=calloc(1, sizeof(tnsFontSingleCharacter*)*TNS_UNICODE_COUNT);
  2573. f->monocharacters=calloc(1, sizeof(tnsFontSingleCharacter*)*TNS_MONO_COUNT);
  2574. f->height = LA_RH*(MAIN.FontSize/2.0f+0.5f);
  2575. tnsInit2DTexture(&f->TexBuffer, GL_R8, FM->BufferWidth, FM->BufferWidth, 0);
  2576. lstAppendItem(&FM->Fonts, f); FM->UsingFont=f;
  2577. if (FT_Init_FreeType(&f->ftlib)) SEND_PANIC_ERROR("Freetype Init Failed!");
  2578. logPrintNew("Loading fonts...\n");
  2579. }
  2580. int GenHeight=LA_RH*MAIN.FontSize;
  2581. for(int i=-2;i<11;i++){
  2582. char* option;
  2583. if(i==-2){ sprintf(buf,"%s%s%s",TNS_FONT_CUSTOM,TNS_FONT_CUSTOM[strlen(TNS_FONT_CUSTOM)-1]=='/'?"":"/",name); }
  2584. elif(i<9){ option=(i==-1)?from:TNS_FONT_LOAD_OPTIONS[i]; sprintf(buf,"%s%s%s",SSTR(MAIN.WorkingDirectory),option,name); }
  2585. else{ option=TNS_FONT_LOAD_OPTIONS_FROM_HOME[i-9]; sprintf(buf,"%s/%s%s",getenv("HOME"),option,name); }
  2586. FILE* fontfile=fopen(buf,"rb"); if(!fontfile) continue;
  2587. fseek(fontfile,0,SEEK_END); int filesize=ftell(fontfile);
  2588. void*fontdata=CreateNewBuffer(char,filesize);
  2589. fseek(fontfile,0,SEEK_SET); fread(fontdata,filesize,1,fontfile);
  2590. FT_Face face; FT_Long i,num_faces; FT_Open_Args args; args.flags=FT_OPEN_MEMORY;
  2591. args.memory_base=fontdata; args.memory_size=filesize;
  2592. if(FT_Open_Face(f->ftlib, &args, -1, &face )) continue;
  2593. num_faces = face->num_faces; FT_Done_Face(face); int found=0;
  2594. //for(int fa=0;fa<num_faces;fa++){
  2595. // if(FT_Open_Face(f->ftlib,&args,fa,&face)){ continue; }
  2596. // if(strstr(face->family_name,"SC")){ found=1; break; }
  2597. // FT_Done_Face(face);
  2598. //}
  2599. if(found){ f->ftface[f->NumFaces]=face; }else{ if (FT_Open_Face(f->ftlib, &args, 0, &f->ftface[f->NumFaces])) continue; }
  2600. FT_Select_Charmap(f->ftface[f->NumFaces], FT_ENCODING_UNICODE);
  2601. FT_Set_Char_Size(f->ftface[f->NumFaces], 0, GenHeight << 6, 96, 96);
  2602. f->NumFaces++; FT_Glyph glyph; FT_Fixed half_adv=0;
  2603. if(!f->MonoAdvance && !FT_Get_Advance(f->ftface[f->NumFaces],'a',FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, &half_adv)){
  2604. FT_Set_Char_Size(f->ftface[f->NumFaces], 0, (GenHeight << 6)*f->MonoScale, 96, 96);
  2605. if (FT_Load_Char(f->ftface[f->NumFaces], 'a', FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP)||
  2606. FT_Get_Glyph(f->ftface[f->NumFaces]->glyph, &glyph)){ SEND_PANIC_ERROR("Monospace font doesn't contain character 'a'"); }
  2607. f->MonoAdvance=(real)f->ftface[f->NumFaces]->glyph->advance.x/64.0;
  2608. if(glyph) FT_Done_Glyph(glyph);
  2609. }
  2610. logPrint("Loaded font: %s\n",buf);
  2611. return 1;
  2612. }
  2613. return 0;
  2614. };
  2615. int tfntBufferWidthEnough(int total_width, int current_width, int this_width){
  2616. return (current_width + this_width +1 < total_width);
  2617. }
  2618. void tfntResizeFontTexture(tnsFont* f, int size){
  2619. FM->BufferWidth=size;
  2620. f->TexBuffer.Width=f->TexBuffer.Height=FM->BufferWidth;
  2621. tnsConfigure2DTexture(&f->TexBuffer);
  2622. }
  2623. void tfntApplyCharacterBufferOffset(tnsFont *f, tnsFontSingleCharacter *fsc){
  2624. if (!tfntBufferWidthEnough(FM->BufferWidth, f->CurrentX, fsc->width)){
  2625. f->CurrentY += (f->height+1);
  2626. f->CurrentX = 0;
  2627. }
  2628. fsc->bufferx = f->CurrentX;
  2629. fsc->buffery = f->CurrentY;
  2630. f->CurrentX += (fsc->width+1);
  2631. }
  2632. tnsFontSingleCharacter *tfntFetchCharTextureIDW(uint32_t ch, int UseMono){
  2633. GLuint revel = 0;
  2634. tnsFont *f = FM->UsingFont;
  2635. tnsFontSingleCharacter **use_fsc=UseMono?f->monocharacters:f->characters, *fsc = 0;
  2636. FT_Glyph glyph = 0;
  2637. FT_BitmapGlyph bitmap_glyph;
  2638. FT_Bitmap bm;
  2639. FT_Face face;
  2640. int w, h, i, j;
  2641. GLubyte *buf = 0;
  2642. if (!f) return 0;
  2643. if(ch>TNS_MONO_COUNT){ UseMono=0; use_fsc=f->characters; }
  2644. if(ch>TNS_UNICODE_COUNT){ return 0; }
  2645. fsc = use_fsc[ch];
  2646. if(!fsc){ fsc=use_fsc[ch]=calloc(1,sizeof(tnsFontSingleCharacter)); }
  2647. if (revel = fsc->Generated) return fsc;
  2648. if(UseMono && f->ftfacemono){
  2649. face = f->ftfacemono;
  2650. if(!FT_Get_Char_Index(face,ch)){return 0;}
  2651. if (FT_Load_Char(face, ch, FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP)){ return 0; }
  2652. if (FT_Get_Glyph(face->glyph, &glyph)){ return 0; }
  2653. }else{
  2654. for(int i=0;i<f->NumFaces;i++){
  2655. if(!f->ftface[i]){continue;}
  2656. face = f->ftface[i];
  2657. if(!FT_Get_Char_Index(face,ch)){continue;}
  2658. if (FT_Load_Char(face, ch, FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP)){ continue; }
  2659. if (FT_Get_Glyph(face->glyph, &glyph)){ continue; }
  2660. break;
  2661. }
  2662. if(!glyph){ return 0; }
  2663. }
  2664. FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);
  2665. FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1);
  2666. bitmap_glyph = glyph;
  2667. bm = bitmap_glyph->bitmap;
  2668. w = bm.width;
  2669. h = bm.rows;
  2670. fsc->width = w;
  2671. fsc->height = h;
  2672. fsc->advx = (real)face->glyph->advance.x / 64.0f;
  2673. fsc->advy = face->size->metrics.y_ppem;
  2674. fsc->deltax = bitmap_glyph->left;
  2675. fsc->deltay = bitmap_glyph->top - h;
  2676. tfntApplyCharacterBufferOffset(f, fsc);
  2677. if(fsc->buffery+h>=FM->BufferWidth){
  2678. tfntResizeFontTexture(f,FM->BufferWidth*2); tnsInvalidateFontCache();
  2679. FreeMem(buf); FT_Done_Glyph(glyph);
  2680. return tfntFetchCharTextureIDW(ch,UseMono);
  2681. }
  2682. tnsBindTexture(&f->TexBuffer);
  2683. //glBindTexture(GL_TEXTURE_2D, f->TexBuffer.GLTexHandle);
  2684. buf = CreateNewBuffer(GLubyte, w * h);
  2685. for (j = 0; j < h; j++){
  2686. for (i = 0; i < w; i++){
  2687. char _vl = bm.buffer[i + w * j];
  2688. buf[i + (h - j - 1) * w] = _vl;
  2689. }
  2690. }
  2691. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  2692. glTexSubImage2D(GL_TEXTURE_2D, 0, fsc->bufferx, fsc->buffery, w, h, GL_RED, GL_UNSIGNED_BYTE, buf);
  2693. FreeMem(buf);
  2694. FT_Done_Glyph(glyph);
  2695. fsc->Generated = 1;
  2696. return fsc;
  2697. }
  2698. tnsFontSingleCharacter *tfntFetchCharacterW(uint32_t ch, int UseMono){
  2699. tnsFontSingleCharacter* fsc = tfntFetchCharTextureIDW(ch, UseMono);
  2700. if(fsc) return fsc;
  2701. return tfntFetchCharTextureIDW('?', UseMono);
  2702. }
  2703. int CMP_NAME_IsThisFont(tnsFont *enumed, char *name){
  2704. return (!strcmp(enumed->fontName, name));
  2705. };
  2706. void tnsPushStringClip(int L, int R, int U, int B){
  2707. tnsStringClip *sc=memAcquire(sizeof(tnsStringClip)); lstPushItem(&FM->StringClips, sc);
  2708. sc->L=FM->L; sc->R=FM->R; sc->U=FM->U; sc->B=FM->B;
  2709. FM->L=L; FM->R=R; FM->U=U; FM->B=B;
  2710. }
  2711. void tnsPopStringClip(){
  2712. tnsStringClip *sc=lstPopItem(&FM->StringClips);
  2713. if(!sc){ FM->L = INT_MIN; FM->R = INT_MAX; FM->B = INT_MAX; FM->U = INT_MIN; }
  2714. FM->L=sc->L; FM->R=sc->R; FM->U=sc->U; FM->B=sc->B;
  2715. };
  2716. int tnsStringGetDimension(char* content, uint32_t* contentU, int Count, int WLimit, int* Rows, int UseMono){
  2717. if((!MAIN.CurrentWindow)||(!MAIN.CurrentWindow->win)||(!FM->UsingFont)) return 0;
  2718. real sx = 0; int sy = FM->UsingFont->height; real MA=FM->UsingFont->MonoAdvance;
  2719. int i, rows=1, advance=1;
  2720. int C = 0;
  2721. int len = contentU?strlenU(contentU):(content?strlen(content):0);
  2722. char hb;
  2723. int RestoreI;
  2724. int MaxSX=0;
  2725. if(!WLimit){WLimit=INT_MAX;}
  2726. int UC=1;
  2727. for (i = 0; i < len && UC; i+=advance){
  2728. UC = contentU?contentU[i]:laToUnicode(&content[i], &advance);
  2729. tnsFontSingleCharacter *fsc;
  2730. if (UC == U'\n'){
  2731. if(sx>MaxSX) MaxSX=sx;
  2732. sx = 0; sy += LA_RH; rows++;
  2733. continue;
  2734. }else{
  2735. fsc = tfntFetchCharacterW(UC, UseMono);
  2736. if(!fsc){continue;};
  2737. real dx=fsc->advx; if(UseMono){ dx/=MA; if(dx<1.01) dx=1; if(dx>1.01)dx=2; dx*=MA; }
  2738. if(sx+dx > WLimit){ sx = 0; sy += LA_RH; rows++; }
  2739. sx += dx;
  2740. C += 1;
  2741. if (Count && C == Count) break;
  2742. }
  2743. }
  2744. if(sx==0 && rows>1){rows--;}
  2745. if(sx>MaxSX) MaxSX=sx;
  2746. if(Rows) (*Rows)=rows;
  2747. return MaxSX+1;
  2748. }
  2749. int tnsStringGetWidth(char *content, int Count, int UseMono){
  2750. return tnsStringGetDimension(content, 0, Count, 0, 0, UseMono);
  2751. }
  2752. int tnsStringGetWidthU(uint32_t *contentU, int Count, int UseMono){
  2753. return tnsStringGetDimension(0, contentU, Count, 0, 0, UseMono);
  2754. }
  2755. int tnsDrawLCD7_ProgressSystem(real x, real y, real Percent){
  2756. real hgap=LA_RH/15; real vgap=LA_RH/5;
  2757. real MA=FM->UsingFont->MonoAdvance;
  2758. real w=MA-hgap*2, h=LA_RH-vgap*2; y+=vgap; x+=hgap-MA; real shear=h/12;
  2759. TNS_CLAMP(Percent,0,1);
  2760. char str[10]; sprintf(str,"%d",(int)(Percent*100)); int len=strlen(str);
  2761. for(int i=len-1;i>=0;i--){
  2762. int uc=str[i];
  2763. if(uc>='0' && uc<='9'){ uc-='0'; }
  2764. else { continue; }
  2765. for(int i=0;i<7;i++){
  2766. if(TNS_LCD_MAP_7[uc][i]){
  2767. real* seg=TNS_LCD_SEG_7[i];
  2768. real s1=tnsInterpolate(shear,-shear,seg[1]); real s2=tnsInterpolate(shear,-shear,seg[3]);
  2769. #ifdef LA_LINUX
  2770. XDrawLine(MAIN.dpy,MAIN.Progress.w,MAIN.Progress.gc,
  2771. tnsInterpolate(x+s1,x+w+s1,seg[0]),tnsInterpolate(y,y+h,seg[1]),
  2772. tnsInterpolate(x+s2,x+w+s2,seg[2]),tnsInterpolate(y,y+h,seg[3]));
  2773. #endif
  2774. #ifdef _WIN32
  2775. MoveToEx(MAIN.Progress.hdc,tnsInterpolate(x+s1,x+w+s1,seg[0]),tnsInterpolate(y,y+h,seg[1]),0);
  2776. LineTo(MAIN.Progress.hdc,tnsInterpolate(x+s2,x+w+s2,seg[2]),tnsInterpolate(y,y+h,seg[3]));
  2777. #endif
  2778. }
  2779. }
  2780. x-=MA;
  2781. }
  2782. return 1;
  2783. return 0;
  2784. }
  2785. int tnsMakeLCD7(real x, real y, real w, real h, real shear, int ch){
  2786. int uc=ch;
  2787. if(ch>='0' && ch<='9'){ uc-='0'; }
  2788. else {return 0;}
  2789. for(int i=0;i<7;i++){
  2790. if(TNS_LCD_MAP_7[uc][i]){
  2791. real* seg=TNS_LCD_SEG_7[i];
  2792. real s1=tnsInterpolate(shear,-shear,seg[1]); real s2=tnsInterpolate(shear,-shear,seg[3]);
  2793. tnsVertex2d(tnsInterpolate(x+s1,x+w+s1,seg[0]),tnsInterpolate(y,y+h,seg[1]));
  2794. tnsVertex2d(tnsInterpolate(x+s2,x+w+s2,seg[2]),tnsInterpolate(y,y+h,seg[3]));
  2795. }
  2796. }
  2797. return 1;
  2798. }
  2799. int tnsMakeLCD16(real x, real y, real w, real h, real shear, int ch){
  2800. int uc=ch;
  2801. if(ch>='0' && ch<='9'){ uc-='0'; }
  2802. elif(ch>='A' && ch<='Z'){ uc-='A'; uc+=10; }
  2803. elif(ch>='a' && ch<='z'){ uc-='a'; uc+=(10+26); }
  2804. else {return 0;}
  2805. for(int i=0;i<16;i++){
  2806. if(TNS_LCD_MAP_16[uc][i]){
  2807. real* seg=TNS_LCD_SEG_16[i];
  2808. real s1=tnsInterpolate(shear,-shear,seg[1]); real s2=tnsInterpolate(shear,-shear,seg[3]);
  2809. tnsVertex2d(tnsInterpolate(x+s1,x+w+s1,seg[0]),tnsInterpolate(y,y+h,seg[1]));
  2810. tnsVertex2d(tnsInterpolate(x+s2,x+w+s2,seg[2]),tnsInterpolate(y,y+h,seg[3]));
  2811. }
  2812. }
  2813. return 1;
  2814. }
  2815. void tnsDrawStringLCD(char *content, uint32_t* contentU, real Color[4], int L, int R, int T, int Flags, real Scale){
  2816. if(Scale<1e-5) return;
  2817. real MA=FM->UsingFont->MonoAdvance;
  2818. real sx = L; int sy = T; real dx=MA; real hgap=LA_RH/15; real vgap=LA_RH/5;
  2819. int i,advance=1;
  2820. int len = contentU?strlenU(contentU):strlen(content);
  2821. int RevY=(Flags&LA_TEXT_REVERT_Y); int TH=LA_RH-vgap*2; real shear=TH/12;
  2822. if(RevY){ TH*=-1; vgap*=-1; } TH*=Scale;dx*=Scale;hgap*=Scale;vgap*=Scale;shear*=Scale;
  2823. int OneLine=(Flags&LA_TEXT_ONE_LINE);
  2824. int Use16=(Flags&LA_TEXT_LCD_16);
  2825. tnsFlush();
  2826. tnsUseNoTexture();
  2827. int any=0, UC=1; int BreakNow=0;
  2828. for (i = 0; i < len && UC; i+=advance){
  2829. UC = contentU?contentU[i]:laToUnicode(&content[i], &advance);
  2830. if (UC == U'\n'){ if(!OneLine){sx = L; sy += LA_RH; continue;}else{ UC=' '; } }
  2831. if (sx + dx > R+1){
  2832. if(Flags&LA_TEXT_LINE_WRAP){ sx=L; sy+=LA_RH; }else{ break; }
  2833. }
  2834. if(Use16){
  2835. if(tnsMakeLCD16(sx+hgap, sy+vgap, dx-hgap*2, TH, shear, UC)) any=1;
  2836. }else{
  2837. if(tnsMakeLCD7(sx+hgap, sy+vgap, dx-hgap*2, TH, shear, UC)) any=1;
  2838. }
  2839. sx += dx;
  2840. if(BreakNow){ break; }
  2841. }
  2842. if(any){ tnsColor4dv(Color); tnsPackAs(GL_LINES); }
  2843. }
  2844. //arr[0] = x1;
  2845. //arr[1] = y1;
  2846. //arr[2] = x2;
  2847. //arr[3] = y2;
  2848. //arr[4] = x3;
  2849. //arr[5] = y3;
  2850. //arr[6] = x2;
  2851. //arr[7] = y2;
  2852. //arr[8] = x3;
  2853. //arr[9] = y3;
  2854. //arr[10] = x4;
  2855. //arr[11] = y4;
  2856. int tns_ClipCharacterT2D(real* v, real* t){
  2857. real l=v[0]; if(l>FM->R) return 0; real r=v[4]; if(r<FM->L) return 0;
  2858. real u=v[1]; if(u>FM->B) return 0; real b=v[3]; if(b<FM->U) return 0;
  2859. real tl=t[0],tr=t[4],tu=t[1],tb=t[3];
  2860. if(l<FM->L){ real p=((real)FM->L-l)/(r-l); t[0]+=p*(tr-tl); t[6]=t[2]=t[0]; v[6]=v[2]=v[0]=FM->L; }
  2861. if(r>FM->R){ real p=(r-(real)FM->R)/(r-l); t[4]-=p*(tr-tl); t[8]=t[10]=t[4]; v[8]=v[10]=v[4]=FM->R; }
  2862. if(u<FM->U){ real p=((real)FM->U-u)/(b-u); t[1]+=p*(tb-tu); t[5]=t[9]=t[1]; v[5]=v[9]=v[1]=FM->U; }
  2863. if(b>FM->B){ real p=(b-(real)FM->B)/(b-u); t[3]-=p*(tb-tu); t[7]=t[11]=t[3]; v[7]=v[11]=v[3]=FM->B; }
  2864. return 1;
  2865. }
  2866. void tnsDrawStringM(char *content, uint32_t* contentU, real Color[4], int L, int R, int T, int Flags){
  2867. if(Flags&LA_TEXT_SHADOW){
  2868. int offset = LA_RH/16;
  2869. tnsDrawStringM(content, contentU, laAccentColor(LA_BT_SHADOW), L+offset, R+offset, T+offset, Flags&(~LA_TEXT_SHADOW));
  2870. }
  2871. if(!FM->UsingFont){return;} if(Flags&(LA_TEXT_LCD_16|LA_TEXT_LCD_7)){
  2872. tnsDrawStringLCD(content,contentU,Color,L,R,T,Flags,1.0); return;
  2873. }
  2874. real sx = L; int sy = (LA_RH!=LA_RH0)?(((((real)FM->UsingFont->height/LA_RH0-0.5)/MAIN.UiScale)+0.5)*LA_RH + T):(FM->UsingFont->height+T);
  2875. real MA=FM->UsingFont->MonoAdvance;
  2876. int i,advance=1;
  2877. int len = contentU?strlenU(contentU):(content?strlen(content):0); if(!len) return;
  2878. real xo, yo, xl, yl;
  2879. real TexCoord[12];
  2880. real VertArr[12];
  2881. int total_width = 0;
  2882. tnsFont *f = FM->UsingFont;
  2883. int FscHeight, RestoreI;
  2884. int RevY=(Flags&LA_TEXT_REVERT_Y);
  2885. int UseMono=(Flags&LA_TEXT_MONO);
  2886. int OneLine=(Flags&LA_TEXT_ONE_LINE);
  2887. if(Color) tnsColor4dv(Color);
  2888. int any=0, UC=1; int BreakNow=0;
  2889. for (i = 0; i < len && UC; i+=advance){
  2890. UC = contentU?contentU[i]:laToUnicode(&content[i], &advance);
  2891. tnsFontSingleCharacter *fsc;
  2892. real cx, cy;
  2893. if (UC == U'\n'){ if(!OneLine){sx = L; sy += LA_RH; continue;}else{ UC=' '; } }
  2894. fsc = tfntFetchCharacterW(UC, Flags&LA_TEXT_MONO); if(!fsc){continue;}
  2895. real dx=fsc->advx; if(UseMono){ dx/=MA; if(dx<1.01) dx=1; if(dx>1.01)dx=2; dx*=MA; }
  2896. if (sx + dx > R+1){
  2897. if(Flags&LA_TEXT_LINE_WRAP){
  2898. sx=L; sy+=LA_RH;
  2899. }else{
  2900. if(Flags&LA_TEXT_OVERFLOW_ARROW){ fsc = tfntFetchCharacterW(U'▷', 0); if(!fsc){continue;} sx=R-fsc->advx; BreakNow=1; }
  2901. else break;
  2902. }
  2903. }
  2904. cx = sx + fsc->deltax;
  2905. cy = sy - fsc->deltay;
  2906. xo = (real)fsc->bufferx / (real)FM->BufferWidth;
  2907. yo = (real)fsc->buffery / (real)FM->BufferWidth;
  2908. xl = (real)(fsc->bufferx + fsc->width) / (real)FM->BufferWidth;
  2909. yl = (real)(fsc->buffery + fsc->height) / (real)FM->BufferWidth;
  2910. tnsMakeQuadT2d(TexCoord, xo, yl, xo, yo, xl, yl, xl, yo);
  2911. if (RevY) tnsMakeQuadT2d(VertArr,
  2912. cx, 2 * T - cy + fsc->height,
  2913. cx, 2 * T - cy,
  2914. cx + fsc->width, 2 * T - cy + fsc->height,
  2915. cx + fsc->width, 2 * T - cy);
  2916. else tnsMakeQuadT2d(VertArr,
  2917. cx, +cy - fsc->height,
  2918. cx, +cy,
  2919. cx + fsc->width, +cy - fsc->height,
  2920. cx + fsc->width, +cy);
  2921. if(tns_ClipCharacterT2D(VertArr,TexCoord)){
  2922. tnsUseMaskTexture(&f->TexBuffer);
  2923. tnsVertexArray2d(VertArr, 6);
  2924. tnsTexCoordArray2d(TexCoord, 6);
  2925. any=1;
  2926. }
  2927. sx += dx;
  2928. if(BreakNow){ break; }
  2929. }
  2930. if(any) tnsPackAs(GL_TRIANGLES);
  2931. }
  2932. void tnsDrawStringAutoM(char *content, uint32_t* contentU, real Color[4], int L, int R, int T, int Flags){
  2933. int LL;
  2934. int al = Flags&LA_TEXT_ALIGN;
  2935. if (!content && !contentU) return;
  2936. switch (al){
  2937. case LA_TEXT_ALIGN_AUTO:
  2938. case LA_TEXT_ALIGN_CENTER: LL = L+(R-L-tnsStringGetDimension(content, contentU, 0, 0, 0, Flags&LA_TEXT_MONO)) / 2; if(LL<L) LL=L; break;
  2939. default:
  2940. case LA_TEXT_ALIGN_LEFT: LL = L; break;
  2941. case LA_TEXT_ALIGN_RIGHT: LL = R-(tnsStringGetDimension(content, contentU, 0, 0, 0, Flags&LA_TEXT_MONO)); if(LL<L) LL=L; break;
  2942. }
  2943. tnsDrawStringM(content, contentU, Color, LL, R, T, Flags);
  2944. }
  2945. void tnsDrawStringAuto(char *content, real Color[4], int L, int R, int T, int Flags){
  2946. tnsDrawStringAutoM(content,0,Color,L,R,T,Flags);
  2947. }
  2948. void tnsDrawStringWithPriority(char *Label, char *MajorContent, real Color[4], int TextAlign, int L, int R, int T, int Flags){
  2949. int W = R - L;
  2950. int Str1W = tnsStringGetWidth(Label, 0, Flags&LA_TEXT_MONO);
  2951. int Str2W = tnsStringGetWidth(MajorContent, 0, Flags&LA_TEXT_MONO);
  2952. if (Str1W + Str2W > W){
  2953. if (Str2W < W){
  2954. tnsDrawStringM(MajorContent, 0, Color, R - Str2W, R, T, Flags);
  2955. tnsDrawStringM(Label, 0, Color, L, R - Str2W, T, Flags);
  2956. }else
  2957. tnsDrawStringM(MajorContent, 0, Color, L, R, T, Flags);
  2958. }else{
  2959. int LL = L, ML;
  2960. switch (Flags&LA_TEXT_ALIGN){
  2961. case LA_TEXT_ALIGN_CENTER:
  2962. ML = L + Str1W + (W - (Str1W + Str2W)) / 2;
  2963. break;
  2964. case LA_TEXT_ALIGN_LEFT:
  2965. ML = L + Str1W;
  2966. break;
  2967. default:
  2968. case LA_TEXT_ALIGN_AUTO:
  2969. case LA_TEXT_ALIGN_RIGHT:
  2970. ML = R - Str2W;
  2971. break;
  2972. }
  2973. tnsDrawStringM(Label, 0, Color, LL, R, T, Flags);
  2974. tnsDrawStringM(MajorContent, 0, Color, ML, R, T, Flags);
  2975. }
  2976. }
  2977. void tnsDrawIcon(uint32_t ID, real Color[4], int L,int R, int T, int Flags){
  2978. char buf[5]={0}; char* next; laToUTF8(ID,buf,&next);
  2979. tnsDrawStringAuto(buf, Color, L,R,T,Flags);
  2980. }
  2981. //=====================================================================================[Object]
  2982. tnsObject *tnsFindObject(char *Name, tnsObject *FromObj){
  2983. tnsObject *io; tnsObject *ro;
  2984. laListHandle* l=FromObj?(&FromObj->ChildObjects):(&T->World->AllObjects);
  2985. for (laListItemPointer*lip=l->pFirst;lip;lip=lip->pNext){
  2986. io=((l==&T->World->AllObjects)?lip:lip->p); if (strSame(io->Name->Ptr, Name)){ return io; }
  2987. if (ro = tnsFindObject(Name, io)) return ro;
  2988. }
  2989. return 0;
  2990. }
  2991. void tnsExtractDeltaTransformValue(tnsObject *o){
  2992. if (!o) return;
  2993. tnsExtractLocation44d(o->DeltaTransform, o->DLocation);
  2994. tnsExtractXYZEuler44d(o->DeltaTransform, o->DRotation);
  2995. tnsExtractScale44d(o->DeltaTransform, o->DScale);
  2996. }
  2997. void tnsExtractSelfTransformValue(tnsObject *o){
  2998. if (!o) return;
  2999. tnsExtractLocation44d(o->SelfTransform, o->Location);
  3000. tnsExtractXYZEuler44d(o->SelfTransform, o->Rotation);
  3001. tnsExtractScale44d(o->SelfTransform, o->Scale);
  3002. }
  3003. void tnsExtractGlobalTransformValue(tnsObject *o){
  3004. if (!o) return;
  3005. tnsExtractLocation44d(o->GlobalTransform, o->GLocation);
  3006. tnsExtractXYZEuler44d(o->GlobalTransform, o->GRotation);
  3007. tnsExtractScale44d(o->GlobalTransform, o->GScale);
  3008. }
  3009. void tnsCopyGlobalTransform(tnsObject *to, tnsObject *from){
  3010. memcpy(to->GlobalTransform, from->GlobalTransform, sizeof(tnsMatrix44d));
  3011. memcpy(to->GLocation, from->GLocation, sizeof(tnsVector3d));
  3012. memcpy(to->GRotation, from->GRotation, sizeof(tnsVector3d));
  3013. memcpy(to->GScale, from->GScale, sizeof(tnsVector3d));
  3014. tnsGlobalTransformValueChanged(to);
  3015. }
  3016. void tnsSelfMatrixChanged(tnsObject* o, int ApplyToChild){
  3017. tnsMatrix44d mix;
  3018. if (!o->ParentObject){
  3019. tnsMultiply44d(mix, o->SelfTransform, o->DeltaTransform);
  3020. memcpy(o->GlobalTransform, mix, sizeof(tnsMatrix44d));
  3021. }
  3022. else{
  3023. tnsMultiply44d(mix, o->ParentObject->GlobalTransform, o->SelfTransform);
  3024. tnsMultiply44d(o->GlobalTransform, mix, o->DeltaTransform);
  3025. }
  3026. tnsExtractDeltaTransformValue(o);
  3027. tnsExtractSelfTransformValue(o);
  3028. tnsExtractGlobalTransformValue(o); tnsInvalidateEvaluation(o);
  3029. if(ApplyToChild) for (laListItemPointer* li=o->ChildObjects.pFirst;li;li=li->pNext){ tnsSelfMatrixChanged(li->p,1); }
  3030. }
  3031. void tnsGlobalMatrixChanged(tnsObject* o, int ApplyToChild){
  3032. tnsMatrix44d self,invd;
  3033. if (!o->ParentObject){ memcpy(self, o->GlobalTransform, sizeof(tnsMatrix44d)); }
  3034. else{ tnsMatrix44d inv;
  3035. tnsInverse44d(inv, o->ParentObject->GlobalTransform);
  3036. tnsMultiply44d(self, inv, o->GlobalTransform); }
  3037. tnsInverse44d(invd, o->DeltaTransform);
  3038. tnsMultiply44d(o->SelfTransform, self, invd);
  3039. tnsExtractSelfTransformValue(o);
  3040. tnsExtractGlobalTransformValue(o); tnsInvalidateEvaluation(o);
  3041. if(ApplyToChild) for (laListItemPointer* li=o->ChildObjects.pFirst;li;li=li->pNext){ tnsSelfMatrixChanged(li->p,1); }
  3042. }
  3043. void tnsGlobalMatrixChangedForDelta(tnsObject* o, int ApplyToChild){
  3044. tnsMatrix44d invs, invp, tmp;
  3045. if (!o->ParentObject){ tnsLoadIdentity44d(invp); }
  3046. else{ tnsInverse44d(invp, o->ParentObject->GlobalTransform); }
  3047. tnsInverse44d(invs, o->SelfTransform);
  3048. tnsMultiply44d(tmp, invs, invp);
  3049. tnsMultiply44d(o->DeltaTransform, tmp, o->GlobalTransform);
  3050. tnsExtractDeltaTransformValue(o);
  3051. //tnsExtractSelfTransformValue(o);
  3052. tnsExtractGlobalTransformValue(o); tnsInvalidateEvaluation(o);
  3053. if(ApplyToChild) for (laListItemPointer* li=o->ChildObjects.pFirst;li;li=li->pNext){ tnsSelfMatrixChanged(li->p,1); }
  3054. }
  3055. void tnsSelfTransformValueChanged(tnsObject* o){
  3056. tnsMatrix44d Trans, Rot1, Rot2, Rot3, Scale, Res1, Res2;
  3057. tnsLoadIdentity44d(o->SelfTransform);
  3058. tnsMakeTranslationMatrix44d(Trans, LA_COLOR3(o->Location));
  3059. if(o->Scale[0]<1e-5){ o->Scale[0]=1e-5; }
  3060. if(o->Scale[1]<1e-5){ o->Scale[1]=1e-5; }
  3061. if(o->Scale[2]<1e-5){ o->Scale[2]=1e-5; }
  3062. tnsMakeScaleMatrix44d(Scale, LA_COLOR3(o->Scale));
  3063. tnsMakeRotationXMatrix44d(Rot1, o->Rotation[0]);
  3064. tnsMakeRotationYMatrix44d(Rot2, o->Rotation[1]);
  3065. tnsMakeRotationZMatrix44d(Rot3, o->Rotation[2]);
  3066. switch (o->RotationMode){
  3067. case TNS_ROTATION_ZYX_EULER: tnsMultiply44d(Res1, Trans, Rot1); tnsMultiply44d(Res2, Res1, Rot2); tnsMultiply44d(Res1, Res2, Rot3); break;
  3068. case TNS_ROTATION_XZY_EULER: tnsMultiply44d(Res1, Trans, Rot1); tnsMultiply44d(Res2, Res1, Rot3); tnsMultiply44d(Res1, Res2, Rot2); break;
  3069. case TNS_ROTATION_YXZ_EULER: tnsMultiply44d(Res1, Trans, Rot2); tnsMultiply44d(Res2, Res1, Rot1); tnsMultiply44d(Res1, Res2, Rot3); break;
  3070. case TNS_ROTATION_YZX_EULER: tnsMultiply44d(Res1, Trans, Rot2); tnsMultiply44d(Res2, Res1, Rot3); tnsMultiply44d(Res1, Res2, Rot1); break;
  3071. case TNS_ROTATION_ZXY_EULER: tnsMultiply44d(Res1, Trans, Rot3); tnsMultiply44d(Res2, Res1, Rot1); tnsMultiply44d(Res1, Res2, Rot2); break;
  3072. case TNS_ROTATION_XYZ_EULER: tnsMultiply44d(Res1, Trans, Rot3); tnsMultiply44d(Res2, Res1, Rot2); tnsMultiply44d(Res1, Res2, Rot1); break;
  3073. }
  3074. tnsMultiply44d(o->SelfTransform, Res1, Scale);
  3075. tnsSelfMatrixChanged(o,1);
  3076. }
  3077. void tnsDeltaTransformValueChanged(tnsObject* o){
  3078. tnsMatrix44d Trans, Rot1, Rot2, Rot3, Scale, Res1, Res2;
  3079. tnsLoadIdentity44d(o->DeltaTransform);
  3080. tnsMakeTranslationMatrix44d(Trans, LA_COLOR3(o->DLocation));
  3081. tnsMakeScaleMatrix44d(Scale, LA_COLOR3(o->DScale));
  3082. tnsMakeRotationXMatrix44d(Rot1, o->DRotation[0]);
  3083. tnsMakeRotationYMatrix44d(Rot2, o->DRotation[1]);
  3084. tnsMakeRotationZMatrix44d(Rot3, o->DRotation[2]);
  3085. switch (o->RotationMode){
  3086. case TNS_ROTATION_ZYX_EULER: tnsMultiply44d(Res1, Trans, Rot1); tnsMultiply44d(Res2, Res1, Rot2); tnsMultiply44d(Res1, Res2, Rot3); break;
  3087. case TNS_ROTATION_XZY_EULER: tnsMultiply44d(Res1, Trans, Rot1); tnsMultiply44d(Res2, Res1, Rot3); tnsMultiply44d(Res1, Res2, Rot2); break;
  3088. case TNS_ROTATION_YXZ_EULER: tnsMultiply44d(Res1, Trans, Rot2); tnsMultiply44d(Res2, Res1, Rot1); tnsMultiply44d(Res1, Res2, Rot3); break;
  3089. case TNS_ROTATION_YZX_EULER: tnsMultiply44d(Res1, Trans, Rot2); tnsMultiply44d(Res2, Res1, Rot3); tnsMultiply44d(Res1, Res2, Rot1); break;
  3090. case TNS_ROTATION_ZXY_EULER: tnsMultiply44d(Res1, Trans, Rot3); tnsMultiply44d(Res2, Res1, Rot1); tnsMultiply44d(Res1, Res2, Rot2); break;
  3091. case TNS_ROTATION_XYZ_EULER: tnsMultiply44d(Res1, Trans, Rot3); tnsMultiply44d(Res2, Res1, Rot2); tnsMultiply44d(Res1, Res2, Rot1); break;
  3092. }
  3093. tnsMultiply44d(o->DeltaTransform, Res1, Scale);
  3094. tnsSelfMatrixChanged(o,1);
  3095. }
  3096. void tnsGlobalTransformValueChanged(tnsObject* o){
  3097. tnsMatrix44d Trans, Rot1, Rot2, Rot3, Scale, Res1, Res2;
  3098. tnsLoadIdentity44d(o->GlobalTransform);
  3099. tnsMakeTranslationMatrix44d(Trans, LA_COLOR3(o->GLocation));
  3100. tnsMakeScaleMatrix44d(Scale, LA_COLOR3(o->GScale));
  3101. tnsMakeRotationXMatrix44d(Rot1, o->GRotation[0]);
  3102. tnsMakeRotationYMatrix44d(Rot2, o->GRotation[1]);
  3103. tnsMakeRotationZMatrix44d(Rot3, o->GRotation[2]);
  3104. switch (o->RotationMode){
  3105. case TNS_ROTATION_ZYX_EULER: tnsMultiply44d(Res1, Trans, Rot1); tnsMultiply44d(Res2, Res1, Rot2); tnsMultiply44d(Res1, Res2, Rot3); break;
  3106. case TNS_ROTATION_XZY_EULER: tnsMultiply44d(Res1, Trans, Rot1); tnsMultiply44d(Res2, Res1, Rot3); tnsMultiply44d(Res1, Res2, Rot2); break;
  3107. case TNS_ROTATION_YXZ_EULER: tnsMultiply44d(Res1, Trans, Rot2); tnsMultiply44d(Res2, Res1, Rot1); tnsMultiply44d(Res1, Res2, Rot3); break;
  3108. case TNS_ROTATION_YZX_EULER: tnsMultiply44d(Res1, Trans, Rot2); tnsMultiply44d(Res2, Res1, Rot3); tnsMultiply44d(Res1, Res2, Rot1); break;
  3109. case TNS_ROTATION_ZXY_EULER: tnsMultiply44d(Res1, Trans, Rot3); tnsMultiply44d(Res2, Res1, Rot1); tnsMultiply44d(Res1, Res2, Rot2); break;
  3110. case TNS_ROTATION_XYZ_EULER: tnsMultiply44d(Res1, Trans, Rot3); tnsMultiply44d(Res2, Res1, Rot2); tnsMultiply44d(Res1, Res2, Rot1); break;
  3111. }
  3112. tnsMultiply44d(o->GlobalTransform, Res1, Scale);
  3113. tnsGlobalMatrixChanged(o,1);
  3114. }
  3115. void tnsSetCurrentRoot(tnsObject *o){
  3116. if(o->Type!=TNS_OBJECT_ROOT) return;
  3117. memAssignRef(T->World, &T->World->ActiveRoot, o);
  3118. }
  3119. void tnsInitObjectBase(tnsObject *o, tnsObject *under, char *Name, int Type,
  3120. real AtX, real AtY, real AtZ,
  3121. real RotX, real RotY, real RotZ, real RotW, u8bit RotationMode,
  3122. real Scale){
  3123. if (!o) return;
  3124. strSafeSet(&o->Name, Name);
  3125. o->Type = Type;
  3126. tnsVectorSet3(o->Location,AtX,AtY,AtZ);
  3127. tnsVectorSet4(o->Rotation,RotX,RotY,RotZ,RotW); o->RotationMode = RotationMode;
  3128. tnsVectorSet3(o->Scale,Scale,Scale,Scale);
  3129. o->Show = 1;
  3130. o->DrawMode = GL_LINE_LOOP;
  3131. tnsLoadIdentity44d(o->DeltaTransform);
  3132. tnsSelfTransformValueChanged(o);
  3133. lstAppendItem(&T->World->AllObjects, o);
  3134. if (under){ lstAppendPointer(&under->ChildObjects, o); int isroot=(under->Type==TNS_OBJECT_ROOT);
  3135. tnsObject* root=isroot?under:under->InRoot; memAssignRef(o, &o->InRoot, root);
  3136. if(!isroot){ o->ParentObject=under; }
  3137. }
  3138. }
  3139. int tnsCheckParentable(tnsObject* child, tnsObject* parent){
  3140. if(child==parent||parent->ParentObject==child)return 0; tnsObject* o=parent; while(o=o->ParentObject){ if(o==parent) return 0; } return 1;
  3141. }
  3142. void tnsParentObject(tnsObject *child, tnsObject *parent, int KeepTransform){
  3143. if (!child || !parent || child->ParentObject==parent || parent->ParentObject==child || parent==child) return;
  3144. if (child->ParentObject) lstRemovePointerLeave(&child->ParentObject->ChildObjects, child);
  3145. else lstRemovePointerLeave(&child->InRoot->ChildObjects, child);
  3146. lstAppendPointer(&parent->ChildObjects, child);
  3147. memAssignRef(child, &child->ParentObject, parent);
  3148. if(KeepTransform) tnsGlobalMatrixChanged(child, 1);
  3149. else tnsSelfMatrixChanged(child, 1);
  3150. }
  3151. void tnsUnparentObject(tnsObject *o, int KeepTransform){
  3152. if (!o || !o->ParentObject) return;
  3153. lstRemovePointerLeave(&o->ParentObject->ChildObjects, o);
  3154. lstAppendPointer(&o->InRoot->ChildObjects, o);
  3155. memAssignRef(o, &o->ParentObject, 0);
  3156. if(KeepTransform) tnsGlobalMatrixChanged(o,1);
  3157. else tnsSelfMatrixChanged(o,1);
  3158. }
  3159. void tnsCopyObjectTransformationsLocal(tnsObject* to, tnsObject* from){
  3160. tnsVectorCopy3d(from->Location, to->Location);
  3161. tnsVectorCopy3d(from->Rotation, to->Rotation); to->RotationMode=from->RotationMode;
  3162. tnsVectorCopy3d(from->Scale, to->Scale);
  3163. tnsSelfTransformValueChanged(to);
  3164. }
  3165. void tnsCopyObjectTransformationsGlobal(tnsObject* to, tnsObject* from){
  3166. tnsVectorCopy3d(from->GLocation, to->GLocation);
  3167. tnsVectorCopy3d(from->GRotation, to->GRotation); to->RotationMode=from->RotationMode;
  3168. tnsVectorCopy3d(from->GScale, to->GScale);
  3169. tnsGlobalTransformValueChanged(to);
  3170. }
  3171. void tnsRotateObjectLocalValues(tnsObject *o, real x, real y, real z){
  3172. o->Rotation[0] += x; o->Rotation[1] += y; o->Rotation[2] += z;
  3173. tnsSelfTransformValueChanged(o);
  3174. }
  3175. void tnsSetObjectPositionLocal(tnsObject*o, real x, real y, real z){
  3176. tnsVectorSet3(o->Location,x,y,z); tnsSelfTransformValueChanged(o);
  3177. }
  3178. void tnsResetObjectTransformations(tnsObject* o, int reset_loc,int reset_rot,int reset_sca){
  3179. if(reset_loc){ tnsVectorSet3(o->Location,0,0,0); }
  3180. if(reset_rot){ tnsVectorSet4(o->Rotation,0,0,0,0); }
  3181. if(reset_sca){ tnsVectorSet3(o->Rotation,1,1,1); }
  3182. tnsSelfTransformValueChanged(o);
  3183. }
  3184. void tnsMoveObjectLocal(tnsObject *o, real x, real y, real z){
  3185. tnsMatrix44d mat, res1, res2, res3;
  3186. tnsMakeTranslationMatrix44d(res2, x, y, z);
  3187. tnsMultiply44d(res1, o->SelfTransform, res2);
  3188. memcpy(o->SelfTransform, res1, sizeof(tnsMatrix44d));
  3189. tnsSelfMatrixChanged(o,1);
  3190. }
  3191. void tnsMoveObjectDelta(tnsObject *o, real x, real y, real z){
  3192. tnsMatrix44d mat, res1, res2, res3;
  3193. tnsMakeTranslationMatrix44d(res2, x, y, z);
  3194. tnsMultiply44d(res1, o->DeltaTransform, res2);
  3195. memcpy(o->DeltaTransform, res1, sizeof(tnsMatrix44d));
  3196. tnsExtractDeltaTransformValue(o);
  3197. tnsSelfMatrixChanged(o,1);
  3198. }
  3199. void tnsMoveObjectGlobal(tnsObject *o, real x, real y, real z){
  3200. tnsMatrix44d mat, res1, res2, res3;
  3201. tnsMakeTranslationMatrix44d(res2, x, y, z);
  3202. tnsMultiply44d(res1, res2, o->GlobalTransform); //if reverse then local
  3203. memcpy(o->GlobalTransform, res1, sizeof(tnsMatrix44d));
  3204. tnsGlobalMatrixChanged(o,1);
  3205. }
  3206. void tnsMoveObjectGlobalForDelta(tnsObject *o, real x, real y, real z){
  3207. tnsMatrix44d mat, res1, res2, res3;
  3208. tnsMakeTranslationMatrix44d(res2, x, y, z);
  3209. tnsMultiply44d(res1, res2, o->GlobalTransform); //if reverse then local
  3210. memcpy(o->GlobalTransform, res1, sizeof(tnsMatrix44d));
  3211. tnsGlobalMatrixChangedForDelta(o,1);
  3212. }
  3213. void tnsRotateObjectGlobal(tnsObject *o, real x, real y, real z, real angle, real cx,real cy,real cz){
  3214. tnsMatrix44d tback,tfwd,rot,rot2,res1,res2;
  3215. real xs, ys, zs;
  3216. tnsMakeRotationMatrix44d(rot,angle,x,y,z);
  3217. tnsMakeRotationMatrix44d(rot2,-angle,x,y,z);//why?
  3218. tnsMakeTranslationMatrix44d(tfwd, o->GLocation[0],o->GLocation[1],o->GLocation[2]);
  3219. tnsInverse44d(tback,tfwd);
  3220. tnsMultiply44d(res1,o->GlobalTransform,tback);
  3221. tnsMultiply44d(res2,rot,res1);
  3222. tnsMultiply44d(o->GlobalTransform,res2,tfwd);
  3223. tnsVector3d delta; delta[0]=o->GLocation[0]-cx; delta[1]=o->GLocation[1]-cy; delta[2]=o->GLocation[2]-cz;
  3224. tnsVector3d c; c[0]=cx; c[1]=cy; c[2]=cz; tnsVector3d r;
  3225. tnsApplyRotation43d(r,rot2,delta);
  3226. tnsVectorPlus3d(&o->GlobalTransform[12],c,r);
  3227. //memcpy(o->GlobalTransform, res1, sizeof(tnsMatrix44d));
  3228. tnsGlobalMatrixChanged(o,1);
  3229. }
  3230. void tnsRotateObjectLocal(tnsObject *o, real x, real y, real z, real angle){
  3231. tnsMatrix44d tback,tfwd,rot,res1,res2;
  3232. //tnsVector3d gp,gpt; gp[0]=gcx; gp[1]=gcy; gp[2]=gcz;
  3233. //tnsMakeTranslationMatrix44d(tfwd, gcx, gcy, gcz);
  3234. //tnsInverse44d(tback,tfwd);
  3235. tnsMakeRotationMatrix44d(rot,angle,x,y,z);
  3236. //tnsMultiply44d(res1,o->SelfTransform,tback);
  3237. //tnsMultiply44d(res2,res1,rot);
  3238. //tnsMultiply44d(o->SelfTransform,res2,tfwd);
  3239. tnsMultiply44d(res1,o->SelfTransform,rot);
  3240. tnsCopyMatrix44d(res1,o->SelfTransform);
  3241. tnsSelfMatrixChanged(o,1);
  3242. }
  3243. void tnsRotateObjectDelta(tnsObject *o, real x, real y, real z, real angle){
  3244. tnsMatrix44d tback,tfwd,rot,res1,res2;
  3245. //tnsVector3d gp,gpt; gp[0]=gcx; gp[1]=gcy; gp[2]=gcz;
  3246. //tnsApplyTransform43d(gpt,o->DeltaTransform,gp);
  3247. //tnsMakeTranslationMatrix44d(tfwd, gpt[0]-gcx, gpt[0]-gcy, gpt[0]-gcz);
  3248. //tnsInverse44d(tback,tfwd);
  3249. //tnsMakeRotationMatrix44d(rot,angle,x,y,z);
  3250. //tnsMultiply44d(res1,o->SelfTransform,tback);
  3251. //tnsMultiply44d(res2,res1,rot);
  3252. //tnsMultiply44d(o->SelfTransform,res2,tfwd);
  3253. tnsMakeRotationMatrix44d(rot,angle,x,y,z);
  3254. tnsMultiply44d(res1,o->DeltaTransform,rot);
  3255. tnsCopyMatrix44d(res1,o->DeltaTransform);
  3256. tnsExtractDeltaTransformValue(o);
  3257. tnsSelfMatrixChanged(o,1);
  3258. }
  3259. void tnsRotateObjectGlobalForDelta(tnsObject *o, real x, real y, real z, real angle, real cx,real cy,real cz){
  3260. tnsMatrix44d tback,tfwd,rot,rot2,res1,res2;
  3261. real xs, ys, zs;
  3262. tnsMakeRotationMatrix44d(rot,angle,x,y,z);
  3263. tnsMakeRotationMatrix44d(rot2,-angle,x,y,z);//why?
  3264. tnsMakeTranslationMatrix44d(tfwd, o->GLocation[0],o->GLocation[1],o->GLocation[2]);
  3265. tnsInverse44d(tback,tfwd);
  3266. tnsMultiply44d(res1,o->GlobalTransform,tback);
  3267. tnsMultiply44d(res2,rot,res1);
  3268. tnsMultiply44d(o->GlobalTransform,res2,tfwd);
  3269. tnsVector3d delta; delta[0]=o->GLocation[0]-cx; delta[1]=o->GLocation[1]-cy; delta[2]=o->GLocation[2]-cz;
  3270. tnsVector3d c; c[0]=cx; c[1]=cy; c[2]=cz; tnsVector3d r;
  3271. tnsApplyRotation43d(r,rot2,delta);
  3272. tnsVectorPlus3d(&o->GlobalTransform[12],c,r);
  3273. //memcpy(o->GlobalTransform, res1, sizeof(tnsMatrix44d));
  3274. tnsGlobalMatrixChangedForDelta(o,1);
  3275. }
  3276. void tnsScaleObject(tnsObject *o, real x,real y,real z, real cx,real cy,real cz){
  3277. tnsMatrix44d sca,res1,res2;
  3278. tnsMakeScaleMatrix44d(sca,x,y,z);
  3279. tnsMultiply44d(res1,o->GlobalTransform,sca);
  3280. tnsVector3d delta; delta[0]=res1[12]-cx; delta[1]=res1[13]-cy; delta[2]=res1[14]-cz;
  3281. tnsVector3d c; c[0]=cx; c[1]=cy; c[2]=cz;
  3282. delta[0]*=x; delta[1]*=y; delta[2]*=z;
  3283. tnsVectorPlus3d(&res1[12],c,delta);
  3284. memcpy(o->GlobalTransform, res1, sizeof(tnsMatrix44d));
  3285. tnsGlobalMatrixChanged(o,1);
  3286. }
  3287. void tnsScaleObjectDelta(tnsObject *o, real x,real y,real z, real cx,real cy,real cz){
  3288. tnsMatrix44d sca,res1,res2;
  3289. tnsMakeScaleMatrix44d(sca,x,y,z);
  3290. tnsMultiply44d(res1,o->GlobalTransform,sca);
  3291. tnsVector3d delta; delta[0]=res1[12]-cx; delta[1]=res1[13]-cy; delta[2]=res1[14]-cz;
  3292. tnsVector3d c; c[0]=cx; c[1]=cy; c[2]=cz;
  3293. delta[0]*=x; delta[1]*=y; delta[2]*=z;
  3294. tnsVectorPlus3d(&res1[12],c,delta);
  3295. memcpy(o->GlobalTransform, res1, sizeof(tnsMatrix44d));
  3296. tnsGlobalMatrixChangedForDelta(o,1);
  3297. }
  3298. void tnsZoomViewingCamera(tnsCamera *c, real Ratio){
  3299. if (c->FocusDistance < 0.1 && Ratio > 0) return;
  3300. tnsMoveObjectLocal(c, 0, 0, -c->FocusDistance * Ratio);
  3301. c->FocusDistance *= (1 - Ratio);
  3302. }
  3303. void tnsRotateViewingCamera(tnsCamera *c, real x, real z){
  3304. tnsMoveObjectLocal(c, 0, 0, -c->FocusDistance);
  3305. tnsRotateObjectLocalValues(c, x, 0, z);
  3306. tnsMoveObjectLocal(c, 0, 0, c->FocusDistance);
  3307. }
  3308. void tnsGetCameraMovingDeltas(tnsCamera *c, int ViewportW, int ViewportH, real x, real y, tnsVector4d p){
  3309. memset(p, 0, sizeof(tnsVector4d));
  3310. tnsVector4d tp = {0};
  3311. tnsMatrix44d combine, projection, projinv, vpinv, vp;
  3312. tnsLoadIdentity44d(projection);
  3313. tnsMakePerspectiveMatrix44d(projection, c->FOV, (real)ViewportW / (real)ViewportH, c->ZMin, c->ZMax);
  3314. tnsMakeViewportMatrix44d(vp, ViewportW, ViewportH, c->ZMax, c->ZMin);
  3315. tnsInverse44d(projinv, projection);
  3316. tnsInverse44d(vpinv, vp);
  3317. p[2] = -c->FocusDistance;
  3318. p[3] = 1;
  3319. tnsApplyTransform44d(tp, projection, p);
  3320. tnsVectorMultiSelf3d(tp, 1 / tp[3]);
  3321. tnsApplyTransform43d(p, vp, tp);
  3322. p[0] += x;
  3323. p[1] += y;
  3324. tnsApplyTransform43d(tp, vpinv, p);
  3325. tnsVectorMultiSelf3d(tp, tp[3]);
  3326. tnsApplyTransform44d(p, projinv, tp);
  3327. }
  3328. void tnsTranslateViewingCamera(tnsCamera *c, int ViewportW, int ViewportH, real x, real y){
  3329. tnsVector4d p={0};
  3330. tnsGetCameraMovingDeltas(c,ViewportW, ViewportH, x,y,p);
  3331. tnsMoveObjectLocal(c, p[0], p[1], 0);
  3332. }
  3333. tnsObject *tnsCreateRootObject(char *name, int Use2D){
  3334. tnsWorld *w = T->World;
  3335. tnsRootObject *o = memAcquireHyper(sizeof(tnsRootObject));
  3336. o->Base.Type==TNS_OBJECT_ROOT;
  3337. strSafeSet(&o->Base.Name, name);
  3338. lstAppendItem(&w->RootObjects, o);
  3339. memAssignRef(w,&w->ActiveRoot,o);
  3340. o->Base.Drivers=memAcquire(sizeof(laRackPageCollection));
  3341. o->Is2D=Use2D;
  3342. laAnimationUpdateHolderList();
  3343. return o;
  3344. }
  3345. void tnsDestroyRootObject(tnsObject *root){
  3346. tnsWorld *w = T->World;
  3347. memAssignRef(w,&w->ActiveRoot,root->Item.pPrev ? root->Item.pPrev : root->Item.pNext ? root->Item.pNext : 0);
  3348. root->Evaluated.Done=root->EvaluatedPlay.Done=0;
  3349. tnsFreeEvaluatedArray(&root->Evaluated);
  3350. tnsClearPlayDuplicate(root);
  3351. if(root->EvaluatedPlay.Commands) tnsFreeEvaluatedArray(&root->EvaluatedPlay);
  3352. tnsFreeEvaluatedScene(&root->EvaluatedPlay);
  3353. //destroy rack page; and then release memory;
  3354. laRackPage*rp;
  3355. while(rp=lstPopItem(&root->Drivers->Pages)){
  3356. laNodeRack* rr; while(rr=lstPopItem(&rp->Racks)){ laDestroyRack(rr); }
  3357. memLeave(rp);
  3358. }
  3359. memLeave(root->Drivers); // root->Drivers=0; never reset address for single, see la_GiveDiffCommand()
  3360. tnsRootObject* ro=root; laAction* aa; laActionProp* ap;
  3361. while(aa=ro->Actions.pFirst){ laAnimationRemoveAction(aa); }
  3362. while(ap=lstPopItem(&ro->ActionProps)){ strSafeDestroy(&ap->CachedName); memLeave(ap); }
  3363. lstRemoveItem(&w->RootObjects, root);
  3364. tnsObject*co;
  3365. while(co=lstPopPointerLeave(&root->ChildObjects)){ tnsDestroyObject(co); }
  3366. strSafeDestroy(&root->Name);
  3367. memLeave(root);
  3368. laAnimationUpdateHolderList();
  3369. }
  3370. void tnsDestroyObject(tnsObject *o){
  3371. if(o->Type==TNS_OBJECT_ROOT){ tnsDestroyRootObject(o); return; }
  3372. tnsFreeEvaluatedArray(&o->Evaluated);
  3373. tnsClearPlayDuplicate(o);
  3374. if(o->EvaluatedPlay.Commands) tnsFreeEvaluatedArray(&o->EvaluatedPlay);
  3375. tnsFreeEvaluatedScene(&o->EvaluatedPlay);
  3376. tnsUnparentObject(o,1);
  3377. while(o->ChildObjects.pFirst){ tnsUnparentObject(((laListItemPointer*)o->ChildObjects.pFirst)->p, 1); }
  3378. lstRemoveItem(&T->World->AllObjects, o);
  3379. if(o->InRoot){ lstRemovePointerLeave(&o->InRoot->ChildObjects, o);
  3380. tnsInvalidateEvaluation(o);
  3381. if(o->InRoot->Active==o){ memAssignRef(o->InRoot,&o->InRoot->Active,0); }
  3382. }
  3383. if(o->Type==TNS_OBJECT_MESH){ tnsMeshObject* mo=o;
  3384. if(mo->v) arrFree(&mo->v, &mo->maxv); if(mo->e) arrFree(&mo->e, &mo->maxe);
  3385. if(mo->f){ for(int i=0;i<mo->totf;i++){ free(mo->f[i].loop); mo->f[i].loop=0; } arrFree(&mo->f, &mo->maxf); }
  3386. mo->totv=mo->tote=mo->totf=0;
  3387. tnsInvalidateMeshBatch(o);
  3388. tnsMaterialSlot* ms; while(ms=lstPopItem(&mo->Materials)){ memLeave(ms); } memAssignRef(mo,&mo->CurrentMaterial,0);
  3389. }
  3390. if(o->Type==TNS_OBJECT_SHAPE){ tnsShapeObject* so=o;
  3391. tnsShape* s; while(s=lstPopItem(&so->Shapes)){ tnsSPoint* sp; while(sp=lstPopItem(&s->Points)){ memLeave(sp); } memLeave(s); }
  3392. tnsMaterialSlot* ms; while(ms=lstPopItem(&so->Materials)){ memLeave(ms); } memAssignRef(so,&so->CurrentMaterial,0);
  3393. }
  3394. strSafeDestroy(&o->Name);
  3395. memLeave(o);
  3396. }
  3397. tnsCamera *tnsCreateCamera(tnsObject *under, char *Name, real FOV,
  3398. real AtX, real AtY, real AtZ,
  3399. real RotX, real RotY, real RotZ,
  3400. real FocusDistance){
  3401. tnsCamera *c; tnsWorld *w = T->World;
  3402. c = memAcquireHyper(sizeof(tnsCamera));
  3403. tnsInitObjectBase(&c->Base, under, Name, TNS_OBJECT_CAMERA, AtX, AtY, AtZ, RotX, RotY, RotZ, 1.0f, TNS_ROTATION_XYZ_EULER, 1.0f);
  3404. c->FOV = FOV;
  3405. c->CameraType = TNS_CAMERA_PERSP;
  3406. c->ZMin = 0.1f;
  3407. c->ZMax = 200.0f;
  3408. c->FocusDistance = FocusDistance;
  3409. c->OrthScale = 1.0f;
  3410. if(under && under->Type==TNS_OBJECT_ROOT){ memAssignRef(under,&((tnsRootObject*)under)->ActiveCamera,c); }
  3411. return c;
  3412. }
  3413. tnsObject *tnsCreateInstancer(tnsObject *under, char *Name, real AtX, real AtY, real AtZ){
  3414. tnsObject *o; tnsWorld *w = T->World; if (!under) return 0;
  3415. o = memAcquireHyper(sizeof(tnsInstancer));
  3416. tnsInitObjectBase(o, under, Name, TNS_OBJECT_INSTANCER, AtX, AtY, AtZ, 0, 0, 0, 1.0f, TNS_ROTATION_XYZ_EULER, 1.0f);
  3417. return o;
  3418. }
  3419. tnsLight *tnsCreateLight(tnsObject *under, char *Name, real AtX, real AtY, real AtZ, real Strength, int UniDirectional){
  3420. tnsLight *l; tnsWorld *w = T->World; if (!under) return 0;
  3421. tnsObject* root=under->Type==TNS_OBJECT_ROOT?under:under->InRoot;
  3422. if (UniDirectional&&under){
  3423. if(root){ if(root->ParentObject) return root->ParentObject; }
  3424. }
  3425. l = memAcquireHyper(sizeof(tnsLight));
  3426. tnsInitObjectBase(&l->Base, under, Name, TNS_OBJECT_LIGHT, AtX, AtY, AtZ, 0, 0, 0, 1.0f, TNS_ROTATION_XYZ_EULER, 1.0f);
  3427. l->Strength = Strength;
  3428. l->UniDirectional = UniDirectional;
  3429. // ?????????? WTF
  3430. //if (root && UniDirectional && !root->ParentObject) memAssignRef(root, &root->ParentObject,l);
  3431. return l;
  3432. }
  3433. tnsInstancer* tnsDuplicateInstancer(tnsInstancer* from){
  3434. if(from->Base.Type!=TNS_OBJECT_INSTANCER) return 0; tnsInstancer* to = memAcquireHyper(sizeof(tnsInstancer));
  3435. tnsInitObjectBase(to, from->Base.ParentObject?from->Base.ParentObject:from->Base.InRoot, from->Base.Name->Ptr, TNS_OBJECT_INSTANCER,0,0,0,0,0,0,0,0,1);
  3436. tnsCopyObjectTransformationsLocal(to,from);
  3437. to->Instance=from->Instance;
  3438. return to;
  3439. }
  3440. int tnsSizeOfObject(tnsObject* o){
  3441. switch(o->Type){
  3442. case TNS_OBJECT_ROOT: return sizeof(tnsRootObject);
  3443. case TNS_OBJECT_INSTANCER: return sizeof(tnsInstancer);
  3444. case TNS_OBJECT_MESH: return sizeof(tnsMeshObject);
  3445. case TNS_OBJECT_CAMERA: return sizeof(tnsCamera);
  3446. case TNS_OBJECT_LIGHT: return sizeof(tnsLight);
  3447. case TNS_OBJECT_SHAPE: return sizeof(tnsShapeObject);
  3448. default: return sizeof(tnsObject);
  3449. }
  3450. }
  3451. tnsObject* tnsDuplicateObject(tnsObject* o){
  3452. tnsMeshObject* to = memAcquireHyper(tnsSizeOfObject(o));
  3453. tnsInitObjectBase(to, o->ParentObject?o->ParentObject:o->InRoot, o->Name->Ptr, TNS_OBJECT_MESH,0,0,0,0,0,0,0,0,1);
  3454. tnsCopyObjectTransformationsLocal(to,o);
  3455. }
  3456. int tnsAnyObjectsSelected(tnsObject *root){
  3457. for(laListItemPointer* lip=root->ChildObjects.pFirst;lip;lip=lip->pNext){ tnsObject* o=lip->p; if(o->Flags&TNS_OBJECT_FLAGS_SELECTED) return 1;
  3458. if(o->ChildObjects.pFirst && tnsAnyObjectsSelected(o)) return 1;
  3459. } return 0;
  3460. }
  3461. void tnsDeselectAllObjects(tnsObject *root){
  3462. for(laListItemPointer* lip=root->ChildObjects.pFirst;lip;lip=lip->pNext){ tnsObject* o=lip->p; o->Flags&=(~TNS_OBJECT_FLAGS_SELECTED);
  3463. if(o->ChildObjects.pFirst)tnsDeselectAllObjects(o);
  3464. }
  3465. memAssignRef(root,&root->Active,0);
  3466. tnsInvalidateEvaluation(root);
  3467. }
  3468. void tnsSelectAllObjects(tnsObject *root){
  3469. for(laListItemPointer* lip=root->ChildObjects.pFirst;lip;lip=lip->pNext){ tnsObject* o=lip->p; o->Flags|=TNS_OBJECT_FLAGS_SELECTED;
  3470. if(o->ChildObjects.pFirst)tnsSelectAllObjects(o);
  3471. }
  3472. tnsInvalidateEvaluation(root);
  3473. }
  3474. void tnsSelectObject(tnsObject* o, int Select, int Toggle){
  3475. if(!o) return;
  3476. if(Toggle) tnsSelectObject(o,(o->Flags&TNS_OBJECT_FLAGS_SELECTED?0:1),0);
  3477. elif(Select) o->Flags|=TNS_OBJECT_FLAGS_SELECTED; else o->Flags&=(~TNS_OBJECT_FLAGS_SELECTED);
  3478. tnsInvalidateEvaluation(o);
  3479. }
  3480. void tnsGetCameraProjection(tnsMatrix44d* mat, int w, int h, tnsCamera* Camera){
  3481. tnsMatrix44d inv, result;
  3482. tnsMakePerspectiveMatrix44d(mat, Camera->FOV, (real)w / (real)h, Camera->ZMin, Camera->ZMax);
  3483. }
  3484. void tnsGetCameraViewProjection(tnsMatrix44d* mat, int w, int h, tnsCamera* Camera){
  3485. tnsMatrix44d inv, result;
  3486. tnsMakePerspectiveMatrix44d(mat, Camera->FOV, (real)w / (real)h, Camera->ZMin, Camera->ZMax);
  3487. tnsInverse44d(inv, Camera->Base.GlobalTransform);
  3488. tnsMultiply44d(result, mat, inv);
  3489. memcpy(mat, result, sizeof(tnsMatrix44d));
  3490. }
  3491. void tnsApplyCameraView(int W, int H, tnsCamera *Camera, tnsMatrix44d out_optional_view, tnsMatrix44d out_optional_projection){
  3492. tnsMatrixStackItem *tmsi = tKnlGetCurrentMatStackItem();
  3493. tnsShader *current_shader = 0;
  3494. real *mat;
  3495. tnsMatrix44d result, inv;
  3496. if (!Camera) return;
  3497. mat = tnsGetProjectionMatrix();
  3498. tnsMakePerspectiveMatrix44d(mat, Camera->FOV, (real)W / (real)H, Camera->ZMin, Camera->ZMax);
  3499. if (current_shader = T->CurrentShader){
  3500. tnsShaderApplyProjection(current_shader, mat);
  3501. tnsShaderApplyProjectionInverse(current_shader, mat);
  3502. if(out_optional_projection){ tnsCopyMatrix44d(mat,out_optional_projection); }
  3503. }
  3504. tnsResetViewMatrix();
  3505. mat = tnsGetViewMatrix();
  3506. tnsInverse44d(inv, Camera->Base.GlobalTransform);
  3507. tnsMultiply44d(result, mat, inv);
  3508. memcpy(mat, result, sizeof(tnsMatrix44d));
  3509. tnsVector3d dir={0,0,0}; tnsSetCameraViewDir(dir);
  3510. if (current_shader = T->CurrentShader){
  3511. tnsShaderApplyView(current_shader, result);
  3512. if(out_optional_view){ tnsCopyMatrix44d(mat,out_optional_view); }
  3513. if(current_shader->uViewPos>-1) glUniform3f(current_shader->uViewPos,LA_COLOR3(Camera->Base.GLocation));
  3514. tnsVectorSet3v(T->SetViewPos,Camera->Base.GLocation);
  3515. }
  3516. }
  3517. void tnsApplyShadowCameraView(tnsLight *Light){
  3518. tnsMatrixStackItem *tmsi = tKnlGetCurrentMatStackItem();
  3519. tnsShader *current_shader = 0;
  3520. tnsMatrix44d mat;
  3521. tnsMatrix44d result, inv;
  3522. if (!Light || !Light->UniDirectional) return;
  3523. //mat = tnsGetProjectionMatrix();
  3524. tnsMakeOrthoMatrix44d(mat, -1000,1000,-1000,1000,-1000,1000);
  3525. tnsInverse44d(inv, Light->Base.GlobalTransform);
  3526. tnsMultiply44d(result, mat, inv);
  3527. memcpy(mat, result, sizeof(tnsMatrix44d));
  3528. if (current_shader = T->CurrentShader){
  3529. tnsShaderApplyShadowMatrix(current_shader,mat);
  3530. }
  3531. }
  3532. void tnsSetCameraViewDir(tnsVector3d dir){
  3533. tnsVectorSet3v(T->SetViewDir, dir);
  3534. if(T->BindedShader && T->BindedShader->uViewDir>-1){ glUniform3f(T->BindedShader->uViewDir,LA_COLOR3(dir)); }
  3535. }
  3536. void tnsApplyModelMatrix(tnsMatrix44d m){
  3537. tnsShader *current_shader = 0; real *mat;
  3538. if (!m) return;
  3539. mat = tnsGetModelMatrix();
  3540. memcpy(mat, m, sizeof(tnsMatrix44d));
  3541. if (current_shader = T->CurrentShader){ tnsShaderApplyModel(current_shader, mat); }
  3542. }
  3543. void tnsLookAt(tnsObject *o, tnsVector3d Target, tnsVector3d Up){
  3544. tnsVector4d target = {0};
  3545. tnsMatrix44d mat, res, res2;
  3546. real *d;
  3547. tnsShader *current_shader = 0;
  3548. d = tnsGetModelMatrix();
  3549. tnsMakeZTrackingMatrix44d(mat, o->GLocation, target, Up);
  3550. tnsLoadIdentity44d(res);
  3551. tnsMakeTranslationMatrix44d(res,o->GLocation[0],o->GLocation[1],o->GLocation[2]);
  3552. tnsMultiply44d(res2, res, mat);
  3553. memcpy(o->SelfTransform, res2, sizeof(tnsMatrix44d));
  3554. tnsSelfMatrixChanged(o,1);
  3555. if (current_shader = T->CurrentShader){
  3556. tnsShaderApplyModel(current_shader, d);
  3557. }
  3558. }
  3559. void tnsDrawCamera(tnsObject *o){
  3560. tnsCamera *c = o;
  3561. real fov_2 = c->FOV / 2; real len=1;
  3562. real ex, ey, ez; ey = len * sin(fov_2); ex = ey; ez = len * cos(fov_2);
  3563. tnsVertex3d(ex, ey, -ez); tnsVertex3d(ex, -ey, -ez); tnsVertex3d(0.0, 0.0, 0.0);
  3564. tnsVertex3d(ex, ey, -ez); tnsVertex3d(-ex, ey, -ez); tnsVertex3d(0.0, 0.0, 0.0);
  3565. tnsVertex3d(-ex, -ey, -ez); tnsVertex3d(-ex, ey, -ez);
  3566. tnsPackAs(GL_LINE_STRIP);
  3567. tnsVertex3d(ex,ey*1.25,-ez); tnsVertex3d(0,ey*2,-ez); tnsVertex3d(-ex,ey*1.25,-ez);
  3568. tnsPackAs(GL_LINE_LOOP);
  3569. tnsVertex3d(-ex, -ey, -ez); tnsVertex3d(ex, -ey, -ez);
  3570. tnsPackAs(GL_LINES);
  3571. }
  3572. void tnsDrawCross(real x,real y,real z,real x1,real x2,real y1,real y2,real z1,real z2){
  3573. tnsVertex3d(x+x1, y+0.0, z+0.0); tnsVertex3d(x+x2, y+0.0, z+0.0);
  3574. tnsVertex3d(x+0.0,y+ y1, z+0.0); tnsVertex3d(x+0.0,y+ y2, z+0.0);
  3575. tnsVertex3d(x+0.0,y+ 0.0,z+ z1); tnsVertex3d(x+0.0,y+ 0.0,z+ z2);
  3576. }
  3577. void tnsDrawEmptySelectionID(tnsEvaluatedInstance* ei, void* unused){
  3578. int i=ei->InstanceSelectionID; real color[4]={0,0,0,1}; TNS_ID_TO_COLOR(color,i); tnsColor4dv(color);
  3579. tnsDrawCross(0,0,0,-0.2,1,-0.2,1,-0.2,1); tnsPackAs(GL_LINES); tnsFlush();
  3580. }
  3581. void tnsDrawEmptyOutline(tnsEvaluatedInstance* ei, void* unused){
  3582. real* color=(ei->IsActive)?laAccentColor(LA_BT_TEXT):laAccentColor(LA_BT_NORMAL); tnsColor4dv(color);
  3583. tnsDrawCross(0,0,0,-0.2,1,-0.2,1,-0.2,1); tnsLineWidth(3);tnsPackAs(GL_LINES); tnsLineWidth(1); tnsFlush();
  3584. }
  3585. void tnsDrawEmptyObject(tnsEvaluatedInstance* ei, void* unused){
  3586. tnsColor4dv(laThemeColor(_LA_THEME_3D_VIEW,LA_BT_BORDER));
  3587. tnsDrawCross(0,0,0,-0.2,1,-0.2,1,-0.2,1);tnsLineWidth(3); tnsPackAs(GL_LINES); tnsLineWidth(1); tnsFlush();
  3588. }
  3589. void tnsEvaluateEmptyObject(tnsObject* o, tnsEvaluateData* ed){
  3590. if(ed->SceneEvaluateMode){ return; }
  3591. tnsAddEvaluatedInstance(ed,o,tnsDrawEmptyObject,TNS_EVAL_LAYER_SOLID,0,0,0);
  3592. if(ed->FillOutline && o->Flags&TNS_OBJECT_FLAGS_SELECTED){
  3593. tnsAddEvaluatedInstance(ed,o,tnsDrawEmptyOutline,TNS_EVAL_LAYER_OUTLINE,ed->Active==o,0,0);
  3594. }
  3595. if(ed->FillSelectionID){
  3596. tnsAddEvaluatedInstance(ed,o,tnsDrawEmptySelectionID,TNS_EVAL_LAYER_SELECTION,0,1,o->SelectID);
  3597. }
  3598. }
  3599. void tnsPushEvaluateMatrixWith(tnsEvaluateData* ed, tnsMatrix44d mat){
  3600. arrEnsureLength(&ed->MatArr,ed->NextMat,&ed->MaxMat,sizeof(tnsMatrix44d)); if(ed->NextMat<1) return;
  3601. real* new=ed->MatArr[ed->NextMat];
  3602. tnsMultiply44d(new, ed->MatArr[ed->NextMat-1], mat);
  3603. ed->NextMat++;
  3604. }
  3605. void tnsPushEvaluate2DMatrixWith(tnsEvaluateData* ed,tnsInstancer* o){
  3606. real* mat=o->Base.GlobalTransform; tnsMatrix44d tmat; int Hook=o->Hook;
  3607. if(Hook){ real X=0,Y=0;
  3608. if(Hook==TNS_INSTANCER_HOOK_TL||Hook==TNS_INSTANCER_HOOK_CL||Hook==TNS_INSTANCER_HOOK_BL){ X=-(real)ed->W/2/LA_RH; }
  3609. if(Hook==TNS_INSTANCER_HOOK_TR||Hook==TNS_INSTANCER_HOOK_CR||Hook==TNS_INSTANCER_HOOK_BR){ X=(real)ed->W/2/LA_RH; }
  3610. if(Hook==TNS_INSTANCER_HOOK_TL||Hook==TNS_INSTANCER_HOOK_TC||Hook==TNS_INSTANCER_HOOK_TR){ Y=(real)ed->H/2/LA_RH; }
  3611. if(Hook==TNS_INSTANCER_HOOK_BL||Hook==TNS_INSTANCER_HOOK_BC||Hook==TNS_INSTANCER_HOOK_BR){ Y=-(real)ed->H/2/LA_RH; }
  3612. X+=o->HookOffset[0]; Y+=o->HookOffset[1];
  3613. tnsMakeTranslationMatrix44d(tmat,X,Y,0); mat=tmat;
  3614. }
  3615. arrEnsureLength(&ed->MatArr,ed->NextMat,&ed->MaxMat,sizeof(tnsMatrix44d)); if(ed->NextMat<1) return;
  3616. real* new=ed->MatArr[ed->NextMat]; tnsCopyMatrix44d(mat,new); ed->NextMat++;
  3617. }
  3618. void tnsPopEvaluateMatrix(tnsEvaluateData* ed){ ed->NextMat--; }
  3619. void tnsEvaluateInstancerObject(tnsInstancer* o, tnsEvaluateData* ed){
  3620. int origid=ed->OverrideID; ed->OverrideID = o->Base.SelectID;
  3621. tnsEvaluateEmptyObject(o,ed);
  3622. int origoutline=ed->FillOutline; ed->FillOutline=0;
  3623. if(o->Instance){ int PrevState2D=ed->State2D;
  3624. tnsRootObject* inst=o->Instance; if(inst->Base.Type==TNS_OBJECT_ROOT&&inst->Is2D){ ed->State2D=1; }
  3625. if(ed->SceneEvaluateMode){ inst=tnsEnsurePlayDuplicate(inst); }
  3626. for(laListItemPointer* lip=ed->ParentStack.pFirst;lip;lip=lip->pNext){
  3627. if(lip->p == inst || lip->p==o->Instance){ goto eval_inst_cleanup; }
  3628. }
  3629. if(ed->State2D){ tnsPushEvaluate2DMatrixWith(ed,o); }
  3630. else{ tnsPushEvaluateMatrixWith(ed,o->Base.GlobalTransform); }
  3631. tnsEvaluateObjectTree(inst, ed, ed->SceneEvaluateMode);
  3632. tnsPopEvaluateMatrix(ed);
  3633. ed->State2D=PrevState2D;
  3634. }
  3635. eval_inst_cleanup:
  3636. ed->OverrideID=origid; ed->FillOutline=origoutline;
  3637. }
  3638. void tnsDrawCameraSelectionID(tnsEvaluatedInstance* ei, void* unused){
  3639. int i=ei->InstanceSelectionID; real color[4]={0,0,0,1}; TNS_ID_TO_COLOR(color,i); tnsColor4dv(color);
  3640. tnsDrawCamera(ei->Object); tnsFlush();
  3641. }
  3642. void tnsDrawCameraOutline(tnsEvaluatedInstance* ei, void* unused){
  3643. real* color=(ei->IsActive)?laAccentColor(LA_BT_TEXT):laAccentColor(LA_BT_NORMAL); tnsColor4dv(color); tnsLineWidth(3);
  3644. tnsDrawCamera(ei->Object); tnsLineWidth(1); tnsFlush();
  3645. }
  3646. void tnsDrawCameraObject(tnsEvaluatedInstance* ei, void* unused){
  3647. tnsColor4dv(laThemeColor(_LA_THEME_3D_VIEW,LA_BT_BORDER)); tnsLineWidth(3);
  3648. tnsDrawCamera(ei->Object); tnsLineWidth(1); tnsFlush();
  3649. }
  3650. void tnsEvaluateCameraObject(tnsObject* o, tnsEvaluateData* ed){
  3651. if(ed->SceneEvaluateMode){ return; }
  3652. tnsAddEvaluatedInstance(ed,o,tnsDrawCameraObject,TNS_EVAL_LAYER_SOLID,0,0,0);
  3653. if(ed->FillOutline && o->Flags&TNS_OBJECT_FLAGS_SELECTED){
  3654. tnsAddEvaluatedInstance(ed,o,tnsDrawCameraOutline,TNS_EVAL_LAYER_OUTLINE,ed->Active==o,0,0);
  3655. }
  3656. if(ed->FillSelectionID){
  3657. tnsAddEvaluatedInstance(ed,o,tnsDrawCameraSelectionID,TNS_EVAL_LAYER_SELECTION,0,1,o->SelectID);
  3658. }
  3659. }
  3660. void tnsRunNode(tnsEvaluatedNode* en, int func, tnsObject* root){
  3661. T->Runtime.CurrentEN = en;
  3662. tnsObject* ob=root; // should be the same as en->Target.
  3663. for(laRackPage* rp=ob->Drivers->Pages.pFirst;rp;rp=rp->Item.pNext){
  3664. if(!rp->Eval.pFirst || rp->TriggerMode!=func) continue;
  3665. laRunPage(rp, 1);
  3666. }
  3667. }
  3668. #ifdef LA_WITH_LUAJIT
  3669. void tnsLuaEnsureNode(lua_State* L,int index,tnsObject* o);
  3670. void tnsLuaRunNode(lua_State* L, tnsEvaluatedNode* en, char* func, tnsObject* root);
  3671. #endif
  3672. void tnsEvaluateThisObject(tnsObject *o, tnsEvaluateData* ed){
  3673. tnsEvaluatedNode* CP,*CC;
  3674. if(ed->SceneEvaluateMode){
  3675. tnsEvaluateSyncNode(ed,o);
  3676. if(o->Type==TNS_OBJECT_INSTANCER){
  3677. CP=ed->Scene->CurrentParent; CC=ed->Scene->CurrentChild;
  3678. ed->Scene->CurrentParent=ed->Scene->CurrentChild; ed->Scene->CurrentChild=ed->Scene->CurrentParent->Children.pFirst;
  3679. }elif(o->Type==TNS_OBJECT_ROOT){ tnsEvaluatedNode* en=ed->Scene->CurrentChild;
  3680. tnsRunNode(en,TNS_PAGE_TRIGGER_PROCESS,o);
  3681. #ifdef LA_WITH_LUAJIT
  3682. tnsLuaEnsureNode(ed->L,en->LuaID,o);
  3683. tnsLuaRunNode(ed->L,en,"run",o);
  3684. #endif
  3685. if(en->ActionRetarget){
  3686. laActionRetarget* ar;
  3687. if(en->ActionRetarget->DetachedInNode){ ar = en->ActionRetarget; }
  3688. else{ ar = ((tnsRootObject*)en->Target)->ActionRetarget; }
  3689. laAnimationSyncRetarget(ar, MAIN.Animation->RunPlayHead);
  3690. laAnimationEvaluateRetargetedActions(ar);
  3691. }
  3692. }
  3693. }
  3694. if (!o->Show) return;
  3695. switch (o->Type){
  3696. case TNS_OBJECT_MESH: tnsEvaluateMeshObject(o, ed); break;
  3697. case TNS_OBJECT_INSTANCER:
  3698. tnsEvaluateInstancerObject(o,ed);
  3699. if(ed->SceneEvaluateMode){ ed->Scene->CurrentParent=CP; ed->Scene->CurrentChild=CC;}
  3700. break;
  3701. case TNS_OBJECT_CAMERA: tnsEvaluateCameraObject(o,ed); break;
  3702. case TNS_OBJECT_SHAPE: tnsEvaluateShapeObject(o,ed); break;
  3703. default: tnsEvaluateEmptyObject(o,ed); break;
  3704. }
  3705. }
  3706. void tnsClearDriversEval(tnsObject* o){
  3707. if(!o->Drivers) return;
  3708. for(laRackPage* rp=o->Drivers->Pages.pFirst;rp;rp=rp->Item.pNext){
  3709. while(lstPopPointer(&rp->Eval)); while(lstPopPointer(&rp->AlwaysBranchers));
  3710. }
  3711. }
  3712. void tnsClearPlayDuplicate(tnsObject* o){
  3713. if(!o || !o->PlayDuplicate) return;
  3714. tnsClearDriversEval(o);
  3715. while(lstPopPointer(&o->PlayDuplicate->ChildObjects));
  3716. for(laListItemPointer* lip=o->ChildObjects.pFirst;lip;lip=lip->pNext){
  3717. tnsObject*co=lip->p; tnsClearPlayDuplicate(co);
  3718. }
  3719. if(o->Type==TNS_OBJECT_ROOT){ tnsRootObject* ro=o; laAnimationClearRetarget(&ro->ActionRetarget); }
  3720. elif(o->Type==TNS_OBJECT_INSTANCER){ tnsInstancer* oi=o; tnsClearPlayDuplicate(oi->Instance); }
  3721. memFree(o->PlayDuplicate); o->PlayDuplicate=0;
  3722. }
  3723. void tnsFreeEvaluatedNode(tnsEvaluatedNode* n){
  3724. tnsEvaluatedNode* en;
  3725. while(en=lstPopItem(&n->Children)){ tnsFreeEvaluatedNode(en); }
  3726. n->Target->LuaCacheID=0; laAnimationClearRetarget(&n->ActionRetarget);
  3727. memFree(n);
  3728. }
  3729. void tnsFreeEvaluatedScene(tnsEvaluateData* ed){
  3730. if(!ed->Scene) return;
  3731. if(ed->Scene->Root) tnsFreeEvaluatedNode(ed->Scene->Root);
  3732. #ifdef LA_WITH_LUAJIT
  3733. logPrintNew("Shutting down Lua for the evaluated scene.\n");
  3734. lua_close(ed->L);
  3735. #endif
  3736. memFree(ed->Scene); ed->Scene=0;
  3737. }
  3738. void tnsClearPlayState(tnsObject* o){
  3739. tnsClearPlayDuplicate(o);
  3740. if(o->EvaluatedPlay.Commands) tnsFreeEvaluatedArray(&o->EvaluatedPlay);
  3741. tnsFreeEvaluatedScene(&o->EvaluatedPlay);
  3742. }
  3743. void tnsEnsureDriversEval(tnsObject* o){
  3744. if(!o->Drivers) return;
  3745. for(laRackPage* rp=o->Drivers->Pages.pFirst;rp;rp=rp->Item.pNext){
  3746. laRebuildPageEval(rp);
  3747. }
  3748. }
  3749. tnsObject* tnsEnsurePlayDuplicate(tnsObject* o){
  3750. tnsEnsureDriversEval(o);
  3751. if(o->Flags&TNS_OBJECT_FLAGS_PLAY_DUPLICATE) return o;
  3752. if(o->PlayDuplicate) return o->PlayDuplicate;
  3753. int obsize=tnsSizeOfObject(o);
  3754. tnsObject* dup=memAcquireHyper(obsize);
  3755. memcpy(dup,o,obsize); o->PlayDuplicate=dup;
  3756. dup->ChildObjects.pFirst=dup->ChildObjects.pLast=0;
  3757. for(laListItemPointer* lip=o->ChildObjects.pFirst;lip;lip=lip->pNext){
  3758. tnsObject*co=lip->p; tnsEnsurePlayDuplicate(co);
  3759. lstAppendPointer(&dup->ChildObjects,co->PlayDuplicate);
  3760. co->PlayDuplicate->ParentObject=o->ParentObject?dup:0; //objects directly under root doesn't have parent object
  3761. }
  3762. if(o->Type==TNS_OBJECT_ROOT){ tnsRootObject* ro=o; laAnimationEnsureRetarget(o,&ro->Actions,&ro->ActionRetarget);
  3763. ((tnsRootObject*)o->PlayDuplicate)->ActionRetarget=ro->ActionRetarget;
  3764. }elif(o->Type==TNS_OBJECT_INSTANCER){ tnsInstancer* oi=o; tnsEnsurePlayDuplicate(oi->Instance); }
  3765. dup->Flags|=TNS_OBJECT_FLAGS_PLAY_DUPLICATE;
  3766. return o->PlayDuplicate;
  3767. }
  3768. #ifdef LA_WITH_LUAJIT
  3769. void tnsLuaPushTypedPointer(lua_State* L, char* ct, void* data){
  3770. lua_getglobal(L,"ffi"); lua_getfield(L,-1,"cast"); lua_pushstring(L,ct); lua_pushlightuserdata(L,data);
  3771. lua_call(L,2,1); lua_remove(L,-2);
  3772. }
  3773. void tnsLuaSetObject(lua_State* L, tnsObject*o){
  3774. tnsLuaPushTypedPointer(L,"struct tnsObject *",o); lua_setfield(L,-2,"object");
  3775. }
  3776. void tnsLuaInit(lua_State* L){
  3777. if(luaL_loadstring(L, LA_TNS_LIB_COMMON) || lua_pcall(L, 0, 0, 0)){ logPrint(" Error loading tns lua libs\n");
  3778. lua_getglobal(L,"log"); lua_insert(L,-2); if(lua_pcall(L,1,0,0)){ lua_pop(L,1); }
  3779. };
  3780. lua_settop(L,0);
  3781. lua_newtable(L); lua_setglobal(L,"scene");
  3782. lua_getglobal(L,"scene"); lua_pushstring(L,"nodes"); lua_newtable(L); lua_settable(L,1);
  3783. lua_pushnil(L); lua_setfield(L,1,"node"); lua_pop(L,1);
  3784. }
  3785. void tnsLuaEnsureNode(lua_State* L,int index,tnsObject* o){ lua_settop(L,0);
  3786. lua_getglobal(L,"scene"); lua_getfield(L,1,"nodes");
  3787. lua_pushinteger(L,index); lua_gettable(L,2); if(lua_isnil(L,3) || (!lua_istable(L,3))){
  3788. lua_pushinteger(L,index); lua_newtable(L); lua_settable(L,2); lua_pop(L,1);
  3789. lua_pushinteger(L,index); lua_gettable(L,2);
  3790. lua_pushlightuserdata(L,0); lua_setfield(L,3,"object");
  3791. }
  3792. lua_settop(L,0);
  3793. }
  3794. void tnsLuaRemoveNode(lua_State* L,int index){ lua_settop(L,0);
  3795. lua_getglobal(L,"scene"); lua_pushstring(L,"nodes"); lua_gettable(L,1);
  3796. lua_pushinteger(L,index); lua_pushnil(L); lua_settable(L,2); lua_pop(L,2);
  3797. }
  3798. void tnsLuaRunNode(lua_State* L, tnsEvaluatedNode* en, char* func, tnsObject* root){ lua_settop(L,0); int index=en->LuaID;
  3799. lua_getglobal(L,"scene"); lua_getfield(L,1,"nodes");
  3800. lua_pushinteger(L,index); lua_gettable(L,-2); lua_setfield(L,1,"node");
  3801. lua_getfield(L,1,"node"); tnsLuaSetObject(L,root);
  3802. lua_getfield(L,-1,"scripts");
  3803. if(lua_isnil(L,-1) || (!lua_istable(L,-1))){
  3804. lua_pop(L,1); lua_newtable(L); lua_setfield(L,-2,"scripts"); lua_getfield(L,-1,"scripts");
  3805. }
  3806. if(!en->LuaLoaded){
  3807. if(root->Drivers){
  3808. if(root->LuaCacheID){
  3809. int scrtable=lua_gettop(L);
  3810. lua_pushinteger(L,root->LuaCacheID); lua_gettable(L,2); lua_getfield(L,-1,"scripts");
  3811. lua_pushnil(L); while(lua_next(L,-2)){
  3812. lua_pushvalue(L,-2); lua_pushvalue(L,-2); lua_settable(L,scrtable);
  3813. lua_pop(L,1);
  3814. }
  3815. lua_pop(L,2);
  3816. }else{
  3817. for(laRackPage*rp=root->Drivers->Pages.pFirst;rp;rp=rp->Item.pNext){
  3818. if(!(rp->UseScript&&rp->Script&&rp->Script->Ptr)){ continue; }
  3819. char* debug_name=rp->Name&&rp->Name->Ptr?rp->Name->Ptr:"unamed_driver_page";
  3820. lua_pushinteger(L,lua_objlen(L,-1)+1);
  3821. if(!luaL_loadbuffer(L,rp->Script->Ptr,strlen(rp->Script->Ptr),debug_name)){
  3822. if(lua_pcall(L,0,1,0)){ lua_getglobal(L,"log"); lua_insert(L,-2); if(lua_pcall(L,1,0,0)){ lua_pop(L,1); } }
  3823. else{ lua_settable(L,-3); }
  3824. }else{ lua_getglobal(L,"log"); lua_insert(L,-2); if(lua_pcall(L,1,0,0)){ lua_pop(L,1); } lua_pop(L,1); /* pop index */ }
  3825. }
  3826. root->LuaCacheID=en->LuaID;
  3827. }
  3828. }
  3829. en->LuaLoaded=1;
  3830. }
  3831. //lua_getglobal(L,"ddump"); lua_getglobal(L,"scene"); lua_call(L,1,0);
  3832. lua_pushnil(L); while(lua_next(L,-2)){
  3833. lua_getfield(L,-1,func); if((!lua_isnil(L,-1))&&lua_isfunction(L,-1)){
  3834. lua_pushvalue(L,-2); if(lua_pcall(L,1,0,0)){ lua_getglobal(L,"log"); lua_insert(L,-2); if(lua_pcall(L,1,0,0)){ lua_pop(L,1); } }
  3835. }else{ lua_pop(L,1); }
  3836. lua_pop(L,1);
  3837. }
  3838. lua_pop(L,3);
  3839. }
  3840. int tnsLuaRunNodeEvent(lua_State* L, tnsEvaluatedNode* en, tnsObject* object, laEvent* e){ lua_settop(L,0); int index=en->LuaID;
  3841. if(!en->LuaLoaded){ return 0; }
  3842. lua_getglobal(L,"scene"); lua_getfield(L,1,"nodes");
  3843. lua_pushinteger(L,index); lua_gettable(L,-2); lua_setfield(L,1,"node");
  3844. lua_getfield(L,1,"node"); tnsLuaSetObject(L,object);
  3845. lua_getfield(L,-1,"scripts");
  3846. if(lua_isnil(L,-1) || (!lua_istable(L,-1))){ return 0; }
  3847. lua_pushnil(L); while(lua_next(L,-2)){
  3848. lua_getfield(L,-1,"input"); if((!lua_isnil(L,-1))&&lua_isfunction(L,-1)){
  3849. lua_pushvalue(L,-2); tnsLuaPushTypedPointer(L,"laEvent*",e);
  3850. if(lua_pcall(L,2,1,0)){ lua_getglobal(L,"log"); lua_insert(L,-2); if(lua_pcall(L,1,0,0)){ lua_pop(L,1); } lua_pop(L,1); continue; }
  3851. int result = lua_tonumber(L,-1); lua_pop(L,1);
  3852. if (result!=0){ lua_settop(L,0); return 1; }
  3853. }else{ lua_pop(L,1); }
  3854. lua_pop(L,1);
  3855. }
  3856. lua_pop(L,3);
  3857. }
  3858. #endif //luajit
  3859. void tnsAddEvaluatedInstance(tnsEvaluateData* ed, tnsObject* ob, tnsDrawEvaluatedInstanceF Draw, int Layer,
  3860. int IsActive, int MeshSelectionType, int InstanceSelectionID){
  3861. tnsEvaluatedInstance* ei;
  3862. if(Layer==TNS_EVAL_LAYER_SOLID){
  3863. arrEnsureLength(&ed->Commands,ed->NextCommand,&ed->MaxCommand,sizeof(tnsEvaluatedInstance));
  3864. ei=&ed->Commands[ed->NextCommand]; ed->NextCommand++;
  3865. }elif(Layer==TNS_EVAL_LAYER_BACKDROP){
  3866. arrEnsureLength(&ed->Backdrop,ed->NextBackdrop,&ed->MaxBackdrop,sizeof(tnsEvaluatedInstance));
  3867. ei=&ed->Backdrop[ed->NextBackdrop]; ed->NextBackdrop++;
  3868. }elif(Layer==TNS_EVAL_LAYER_OUTLINE){
  3869. arrEnsureLength(&ed->Outlines,ed->NextOutline,&ed->MaxOutline,sizeof(tnsEvaluatedInstance));
  3870. ei=&ed->Outlines[ed->NextOutline]; ed->NextOutline++;
  3871. }elif(Layer==TNS_EVAL_LAYER_OVERLAY){
  3872. arrEnsureLength(&ed->Overlays,ed->NextOverlay,&ed->MaxOverlay,sizeof(tnsEvaluatedInstance));
  3873. ei=&ed->Overlays[ed->NextOverlay]; ed->NextOverlay++;
  3874. }elif(Layer==TNS_EVAL_LAYER_SELECTION){
  3875. arrEnsureLength(&ed->Selections,ed->NextSelection,&ed->MaxSelection,sizeof(tnsEvaluatedInstance));
  3876. ei=&ed->Selections[ed->NextSelection]; ed->NextSelection++;
  3877. }else{ return; }
  3878. ei->IsActive=IsActive; ei->MeshSelectionType=MeshSelectionType;
  3879. ei->InstanceSelectionID=ed->OverrideID?ed->OverrideID:InstanceSelectionID;
  3880. ei->Draw=Draw; ei->Object=ob; ei->DrawnIn2D=ed->State2D; if(ed->State2D){ ed->Has2D=1; }
  3881. tnsMultiply44d(ei->Mat,ed->MatArr[ed->NextMat-1],ob->GlobalTransform);
  3882. }
  3883. void tnsFreeEvaluatedArray(tnsEvaluateData* ed){
  3884. ed->Done=0;
  3885. arrFree(&ed->Backdrop,&ed->MaxBackdrop);
  3886. arrFree(&ed->Commands,&ed->MaxCommand);
  3887. arrFree(&ed->Outlines,&ed->MaxOutline);
  3888. arrFree(&ed->Overlays,&ed->MaxOverlay);
  3889. arrFree(&ed->Selections,&ed->MaxSelection);
  3890. }
  3891. void tnsInvalidateEvaluation(tnsObject* o){ if(!o) return;
  3892. if(o->InRoot) o->InRoot->Evaluated.Done=0; else o->Evaluated.Done=0;
  3893. }
  3894. void tnsInvalidatePlayEvaluation(tnsObject* o){
  3895. if(o->InRoot) o->InRoot->EvaluatedPlay.Done=0; else o->EvaluatedPlay.Done=0;
  3896. }
  3897. void tnsSetObjectTreeEvaluationArgs(tnsObject* from, tnsObject* Active, int FillOutline, int FillSelectionID, int W, int H){
  3898. tnsEvaluateData* ed=&from->Evaluated; int set=0;
  3899. #define SETARG(a)\
  3900. if(ed->a==0 && a!=0){ set=1; } ed->a=a;
  3901. SETARG(Active); SETARG(FillOutline); SETARG(FillSelectionID); SETARG(W); SETARG(H);
  3902. if(set) ed->Done=0;
  3903. }
  3904. tnsEvaluatedNode* tnsAcquireEvaluateNode(tnsEvaluateData* ed){
  3905. if(!ed->Scene->WastedEvaluateNodes.pFirst){ tnsEvaluatedNode* en=memAcquire(sizeof(tnsEvaluatedNode));
  3906. ed->Scene->NextLuaID++; en->LuaID=ed->Scene->NextLuaID; return en; }
  3907. else{ return lstPopItem(&ed->Scene->WastedEvaluateNodes); }
  3908. }
  3909. void tnsEvaluateNewNode(tnsEvaluateData* ed, tnsObject* ob){
  3910. tnsEvaluatedScene* s=ed->Scene;
  3911. tnsEvaluatedNode* en=tnsAcquireEvaluateNode(ed); en->Target=ob;
  3912. if(ob->Type==TNS_OBJECT_ROOT){ tnsRootObject* ro=ob;
  3913. en->ActionRetarget=laAnimationCopyRetargetFrom(ro->ActionRetarget); en->ActionRetarget->DetachedInNode = 1;
  3914. }
  3915. tnsMultiply44d(en->Mat,ed->MatArr[ed->NextMat-1],ob->GlobalTransform);
  3916. if(s->CurrentChild) lstInsertItemBefore(&s->CurrentParent->Children,en,s->CurrentChild);
  3917. else lstAppendItem(&s->CurrentParent->Children,en);
  3918. s->CurrentChild = en;
  3919. }
  3920. int tnsEvaluateTryRelinkExistingNode(tnsEvaluateData* ed, tnsObject* ob){
  3921. tnsEvaluatedScene* s=ed->Scene;
  3922. if(!s->CurrentChild) return 0;
  3923. int done=0; for(tnsEvaluatedNode* en=s->CurrentChild->Item.pNext;en;en=en->Item.pNext){
  3924. if(ob==en->Target){ done=1; lstRemoveItem(&s->CurrentParent->Children,en);
  3925. lstInsertItemBefore(&s->CurrentParent->Children,en,s->CurrentChild); break; }
  3926. }
  3927. return done;
  3928. }
  3929. void tnsEvaluateEndNode(tnsEvaluateData* ed, tnsEvaluatedNode* en){
  3930. tnsEvaluatedNode* sen;
  3931. while(sen=lstPopItem(&en->Children)){ tnsEvaluateEndNode(ed,sen); }
  3932. if(en->Target->Type==TNS_OBJECT_ROOT){ tnsRootObject* ro=en->Target;
  3933. laAnimationClearRetarget(&en->ActionRetarget);
  3934. }
  3935. int luaid=en->LuaID; memset(en,0,sizeof(tnsEvaluatedNode)); //memFree(sen);
  3936. en->LuaID=luaid;
  3937. #ifdef LA_WITH_LUAJIT
  3938. if(en->LuaID!=0) tnsLuaRemoveNode(ed->L,en->LuaID);
  3939. #endif
  3940. lstAppendItem(&ed->Scene->WastedEvaluateNodes,en);
  3941. }
  3942. void tnsEvaluateSyncNode(tnsEvaluateData* ed, tnsObject* ob){
  3943. tnsEvaluatedScene* s=ed->Scene;
  3944. if(ob && ((!s->CurrentChild) || (s->CurrentChild->Target!=ob))){
  3945. if(!tnsEvaluateTryRelinkExistingNode(ed,ob)) tnsEvaluateNewNode(ed,ob);
  3946. }
  3947. if((!ob) && s->CurrentChild){ tnsEvaluatedNode* en=s->CurrentChild->Item.pPrev;
  3948. if(en) while(en->Item.pNext){ tnsEvaluatedNode* den=en->Item.pNext;
  3949. lstRemoveItem(&s->CurrentParent->Children,den); tnsEvaluateEndNode(ed,den); }
  3950. s->CurrentChild=0;
  3951. }
  3952. }
  3953. void tnsEnsureEvaluatedScene(tnsEvaluateData* ed, tnsObject* root){
  3954. if(!ed->Scene){
  3955. ed->Scene=memAcquire(sizeof(tnsEvaluatedScene));
  3956. #ifdef LA_WITH_LUAJIT
  3957. logPrintNew("Starting Lua for evaluated scene.\n");
  3958. ed->L = lua_open(); la_luaLoadLibs(ed->L);
  3959. la_luaPrintStatus(ed->L); tnsLuaInit(ed->L);
  3960. #else
  3961. logPrintNew("Starting evaluated scene without lua.\n");
  3962. #endif
  3963. }
  3964. if(!ed->Scene->Root){
  3965. ed->Scene->Root=tnsAcquireEvaluateNode(ed);
  3966. ed->Scene->NextLuaID++; ed->Scene->Root->LuaID=ed->Scene->NextLuaID;
  3967. if(root->Type==TNS_OBJECT_ROOT){ tnsRootObject* ro=root;
  3968. ed->Scene->Root->ActionRetarget=laAnimationCopyRetargetFrom(ro->ActionRetarget);
  3969. }
  3970. }
  3971. ed->Scene->CurrentChild=ed->Scene->Root;
  3972. ed->Scene->CurrentChild->Target=root; tnsLoadIdentity44d(ed->Scene->CurrentChild->Mat);
  3973. }
  3974. void tnsPrintEvaluatedNode(tnsEvaluatedNode* en,int level){
  3975. for(int i=0;i<level;i++){ printf(" "); }
  3976. printf("%s\n",en->Target->Name?en->Target->Name->Ptr:"?");
  3977. for(tnsEvaluatedNode* sen=en->Children.pFirst;sen;sen=sen->Item.pNext){
  3978. tnsPrintEvaluatedNode(sen,level+1);
  3979. }
  3980. if(level==0){printf("\n");}
  3981. }
  3982. void tnsEvaluateObjectTree(tnsObject* from, tnsEvaluateData* UseED, int EvaluatePlay){
  3983. if(!from) return;
  3984. tnsObject* UseRoot=from->InRoot?from->InRoot:from;
  3985. tnsEvaluateData* ed=UseED?UseED:(EvaluatePlay?&UseRoot->EvaluatedPlay:&UseRoot->Evaluated);
  3986. ed->SceneEvaluateMode=EvaluatePlay;
  3987. if(ed->Done) return;
  3988. elif(!UseED){ ed->NextCommand=ed->NextOverlay=ed->NextSelection=ed->NextOutline=ed->NextMat=0;
  3989. if(!ed->Backdrop) arrInitLength(&ed->Backdrop,16,&ed->MaxBackdrop,sizeof(tnsEvaluatedInstance));
  3990. if(!ed->Commands) arrInitLength(&ed->Commands,16,&ed->MaxCommand,sizeof(tnsEvaluatedInstance));
  3991. if(!ed->Outlines) arrInitLength(&ed->Outlines,16,&ed->MaxOutline,sizeof(tnsEvaluatedInstance));
  3992. if(!ed->Overlays) arrInitLength(&ed->Overlays,16,&ed->MaxOverlay,sizeof(tnsEvaluatedInstance));
  3993. if(!ed->Selections) arrInitLength(&ed->Selections,16,&ed->MaxSelection,sizeof(tnsEvaluatedInstance));
  3994. if(!ed->MatArr) arrInitLength(&ed->MatArr,8,&ed->MaxMat,sizeof(tnsMatrix44d));
  3995. tnsLoadIdentity44d(ed->MatArr[0]); ed->NextMat=1; ed->Has2D=0;
  3996. }
  3997. tnsEvaluatedNode* CP,*CC;
  3998. if(ed->SceneEvaluateMode){
  3999. from=tnsEnsurePlayDuplicate(from);
  4000. if(!UseED){ tnsEnsureEvaluatedScene(ed,from); }
  4001. CP=ed->Scene->CurrentParent; CC=ed->Scene->CurrentChild;
  4002. }
  4003. lstPushPointer(&ed->ParentStack,from);
  4004. tnsEvaluateThisObject(from, ed);
  4005. if(ed->SceneEvaluateMode){ ed->Scene->CurrentParent=ed->Scene->CurrentChild; ed->Scene->CurrentChild=ed->Scene->CurrentParent->Children.pFirst; }
  4006. for (laListItemPointer* lip=from->ChildObjects.pFirst;lip;lip=lip->pNext){
  4007. tnsObject *o=lip->p; if (o){ tnsEvaluateObjectTree(o,ed,EvaluatePlay); }
  4008. if(ed->SceneEvaluateMode){ ed->Scene->CurrentChild=ed->Scene->CurrentChild?ed->Scene->CurrentChild->Item.pNext:0; }
  4009. }
  4010. lstPopPointer(&ed->ParentStack);
  4011. if(ed->SceneEvaluateMode){ ed->Scene->CurrentParent=CP; ed->Scene->CurrentChild=CC; }
  4012. if(!UseED){ ed->Done=1;
  4013. //if(ed->Scene){ tnsPrintEvaluatedNode(ed->Scene->Root,0);}
  4014. }
  4015. }
  4016. int tnsEvaluateObjectTreeEvent(tnsEvaluateData* ed_play, tnsEvaluatedNode* en, laEvent* e){
  4017. int stop=0;
  4018. for(tnsEvaluatedNode* lip=en->Children.pFirst;lip;lip=lip->Item.pNext){
  4019. if(tnsEvaluateObjectTreeEvent(ed_play, lip, e)){ stop=1; }
  4020. }
  4021. if(en->Target->Type==TNS_OBJECT_ROOT){
  4022. if(e->type&LA_KEYBOARD_EVENT){
  4023. tnsRunNode(en,TNS_PAGE_TRIGGER_KEYBOARD,en->Target);
  4024. }elif(e->type&LA_MOUSE_EVENT){
  4025. tnsRunNode(en,TNS_PAGE_TRIGGER_MOUSE,en->Target);
  4026. }
  4027. #ifdef LA_WITH_LUAJIT
  4028. if(!stop){ return tnsLuaRunNodeEvent(ed_play->L,en,en->Target,e); }
  4029. #endif
  4030. }
  4031. }
  4032. void tnsDrawLayer(tnsEvaluateData* ed,int Layer,void* CustomData){
  4033. tnsEvaluatedInstance* ei; int next=0;
  4034. int No2D=Layer&TNS_EVAL_LAYER_NO_2D; int Do2D=Layer&TNS_EVAL_LAYER_SHOW_2D;
  4035. Layer&=(~(TNS_EVAL_LAYER_SHOW_2D|TNS_EVAL_LAYER_NO_2D));
  4036. if(Layer==TNS_EVAL_LAYER_SOLID){ ei=ed->Commands; next=ed->NextCommand; }
  4037. elif(Layer==TNS_EVAL_LAYER_BACKDROP){ ei=ed->Backdrop; next=ed->NextBackdrop; }
  4038. elif(Layer==TNS_EVAL_LAYER_OUTLINE){ ei=ed->Outlines; next=ed->NextOutline; }
  4039. elif(Layer==TNS_EVAL_LAYER_OVERLAY){ ei=ed->Overlays; next=ed->NextOverlay; }
  4040. elif(Layer==TNS_EVAL_LAYER_SELECTION){ ei=ed->Selections; next=ed->NextSelection; }
  4041. else{ return; } if(!next){ return; }
  4042. for(int i=0;i<next;i++){
  4043. if(No2D && ei->Object->Type==TNS_OBJECT_SHAPE){ ei++; continue; }
  4044. if((Do2D && (!ei->DrawnIn2D)) || ((!Do2D) && ei->DrawnIn2D)){ ei++; continue; }
  4045. tnsPushMatrix(); tnsApplyModelMatrix(ei->Mat);
  4046. ei->Draw(ei,CustomData);
  4047. tnsPopMatrix();
  4048. ei++;
  4049. }
  4050. }
  4051. void tnsDrawObjectTree(tnsObject* from, int Layers,void* CustomData, int DrawRuntime){
  4052. if(!from) return;
  4053. tnsEvaluateData* ed=DrawRuntime?&from->EvaluatedPlay:&from->Evaluated;
  4054. if(!ed->Done) return; int Do2D=Layers&TNS_EVAL_LAYER_SHOW_2D;
  4055. if(Layers&TNS_EVAL_LAYER_BACKDROP){ tnsDrawLayer(ed,TNS_EVAL_LAYER_BACKDROP|Do2D,CustomData); }
  4056. if(Layers&TNS_EVAL_LAYER_SOLID){ tnsDrawLayer(ed,TNS_EVAL_LAYER_SOLID|Do2D,CustomData); }
  4057. if(Layers&TNS_EVAL_LAYER_OUTLINE){ tnsDrawLayer(ed,TNS_EVAL_LAYER_OUTLINE|Do2D,CustomData);}
  4058. if(Layers&TNS_EVAL_LAYER_OVERLAY){ tnsDrawLayer(ed,TNS_EVAL_LAYER_OVERLAY|Do2D,CustomData);}
  4059. if(Layers&TNS_EVAL_LAYER_SELECTION){ tnsDrawLayer(ed,TNS_EVAL_LAYER_SELECTION|Do2D,CustomData); }
  4060. }
  4061. void tnsDrawSingleObjectOrigin(tnsObject* o){
  4062. real* c=laThemeColor(_LA_THEME_3D_VIEW,LA_BT_BORDER); tnsColor4d(LA_COLOR3(c),0.5);
  4063. tnsPointSize(8); tnsVertex3d(0,0,0); tnsPackAs(GL_POINTS);
  4064. tnsFlush(); tnsPointSize(1);
  4065. }
  4066. void tnsDrawObjectOrigins(tnsObject *from, tnsObject *active, int AllOrigins){
  4067. tnsObject *o; if(!from) return;
  4068. tnsVector4d pos;
  4069. for (laListItemPointer* lip=from->ChildObjects.pFirst;lip;lip=lip->pNext){
  4070. o=lip->p; if((!AllOrigins)){
  4071. if((o!=active) && (!(o->Flags&TNS_OBJECT_FLAGS_SELECTED))) continue;
  4072. if(o->Type==TNS_OBJECT_MESH && ((tnsMeshObject*)o)->Mode==TNS_MESH_EDIT_MODE){ continue; }
  4073. }
  4074. if(T->BindedShader==T->SelectionShader){ int i=o->SelectID; real color[4]={0,0,0,1}; TNS_ID_TO_COLOR(color,i); tnsColor4dv(color); }
  4075. else{
  4076. if(o==active){ tnsColor4dv(laAccentColor(LA_BT_TEXT_ACTIVE)); }
  4077. elif(o->Flags&TNS_OBJECT_FLAGS_SELECTED){ tnsColor4dv(laAccentColor(LA_BT_NORMAL)); }
  4078. else{ real* c=laThemeColor(_LA_THEME_3D_VIEW,LA_BT_BORDER); tnsColor4d(LA_COLOR3(c),0.5); }
  4079. }
  4080. tnsVertex3d(LA_COLOR3(o->GLocation)); tnsPackAs(GL_POINTS);
  4081. }
  4082. }
  4083. void tnsDrawCursor(tnsObject* root){
  4084. if(!root || root->Type!=TNS_OBJECT_ROOT) return;
  4085. tnsMatrix44d vp; tnsVector4d t; tnsVector4d t1={0,0,0,1};
  4086. tnsMultiply44d(vp,tnsGetProjectionMatrix(),tnsGetViewMatrix());
  4087. tnsApplyTransform44d(t,vp,root->GLocation); real w=t[3]*0.05;
  4088. tnsDrawCross(LA_COLOR3(root->GLocation),-w,w,-w,w,-w,w); tnsColor4d(0,0,0,0.5);
  4089. tnsPackAs(GL_LINES); glLineWidth(5);
  4090. tnsFlush(); w*=0.9;
  4091. tnsDrawCross(LA_COLOR3(root->GLocation),-w,w,-w,w,-w,w); tnsColor4dv(laThemeColor(_LA_THEME_3D_VIEW,LA_BT_BORDER));
  4092. tnsPackAs(GL_LINES); glLineWidth(2);
  4093. tnsFlush(); glLineWidth(1);
  4094. }
  4095. //===================================================================[Material]
  4096. tnsMaterial *tnsCreateMaterial(char *Name){
  4097. tnsMaterial *m; if(!Name || !Name[0]) return 0;
  4098. m = memAcquireHyper(sizeof(tnsMaterial));
  4099. strSafeSet(&m->Name, Name); tnsVectorSet4(m->Color,0.8,0.8,0.8,1); tnsVectorSet4(m->Color2,0.8,0.8,0.8,1);
  4100. m->Page=memAcquire(sizeof(laRackPage));
  4101. lstAppendItem(&T->World->Materials, m);
  4102. return m;
  4103. }
  4104. tnsMaterial *tnsFindMaterial(char *name){
  4105. tnsMaterial *m;
  4106. for (m = T->World->Materials.pFirst; m; m = m->Item.pNext){ if(strSame(m->Name->Ptr, name)) return m; }
  4107. return 0;
  4108. }
  4109. void tnsRemoveMaterial(tnsMaterial* mat){
  4110. lstRemoveItem(&T->World->Materials,mat);
  4111. laNodeRack* rr; while(rr=lstPopItem(&mat->Page->Racks)){ laDestroyRack(rr); }
  4112. strSafeDestroy(&mat->Page->Name); memLeave(mat->Page);
  4113. for(tnsObject* o=T->World->AllObjects.pFirst;o;o=o->Item.pNext){
  4114. if(o->Type==TNS_OBJECT_MESH){ tnsMeshObject* mo=o;
  4115. for(tnsMaterialSlot* msi=mo->Materials.pFirst;msi;msi=msi->Item.pNext){
  4116. if(msi->Material==mat){ memAssignRef(msi,&msi->Material,0); }
  4117. }
  4118. }elif(o->Type==TNS_OBJECT_SHAPE){ tnsShapeObject* so=o;
  4119. for(tnsMaterialSlot* msi=so->Materials.pFirst;msi;msi=msi->Item.pNext){
  4120. if(msi->Material==mat){ memAssignRef(msi,&msi->Material,0); }
  4121. }
  4122. }
  4123. }
  4124. tnsRefreshMaterialLibraries();
  4125. memLeave(mat);
  4126. }
  4127. tnsMaterialSlot* tnsNewMaterialSlot(tnsObject* o){
  4128. if(o->Type==TNS_OBJECT_MESH){ tnsMeshObject* mo=o; short nextid=0,found=1;
  4129. while(found){ found=0;
  4130. for(tnsMaterialSlot* msi=mo->Materials.pFirst;msi;msi=msi->Item.pNext){
  4131. if(nextid==msi->Index){ found=1; nextid++; continue; }
  4132. }
  4133. }
  4134. tnsMaterialSlot* ms=memAcquire(sizeof(tnsMaterialSlot)); lstAppendItem(&mo->Materials,ms);
  4135. ms->Index=nextid; memAssignRef(ms,&ms->Parent,mo); memAssignRef(mo,&mo->CurrentMaterial,ms);
  4136. return ms;
  4137. }elif(o->Type==TNS_OBJECT_SHAPE){ tnsShapeObject* so=o; short nextid=0,found=1;
  4138. while(found){ found=0;
  4139. for(tnsMaterialSlot* msi=so->Materials.pFirst;msi;msi=msi->Item.pNext){
  4140. if(nextid==msi->Index){ found=1; nextid++; continue; }
  4141. }
  4142. }
  4143. tnsMaterialSlot* ms=memAcquire(sizeof(tnsMaterialSlot)); lstAppendItem(&so->Materials,ms);
  4144. ms->Index=nextid; memAssignRef(ms,&ms->Parent,so); memAssignRef(so,&so->CurrentMaterial,ms);
  4145. return ms;
  4146. }
  4147. }
  4148. void tnsRemoveMaterialSlot(tnsObject* o, tnsMaterialSlot* ms){
  4149. if(o->Type==TNS_OBJECT_MESH){ tnsMeshObject* mo=o;
  4150. memAssignRef(mo,&mo->CurrentMaterial,ms->Item.pNext?ms->Item.pNext:ms->Item.pPrev);
  4151. lstRemoveItem(&mo->Materials,ms); memLeave(ms);
  4152. }elif(o->Type==TNS_OBJECT_SHAPE){ tnsShapeObject* so=o;
  4153. memAssignRef(so,&so->CurrentMaterial,ms->Item.pNext?ms->Item.pNext:ms->Item.pPrev);
  4154. lstRemoveItem(&so->Materials,ms); memLeave(ms);
  4155. }
  4156. }
  4157. void tnsAssignMaterialSlot(tnsObject* o, tnsMaterialSlot* ms){
  4158. if(o->Type==TNS_OBJECT_MESH){ tnsMeshObject* mo=o;
  4159. if(mo->Mode==TNS_MESH_OBJECT_MODE){
  4160. for(int i=0;i<mo->totf;i++){ mo->f[i].mat=ms->Index; }
  4161. }elif(mo->Mode==TNS_MESH_EDIT_MODE){
  4162. for(tnsMFace* f=mo->mf.pFirst;f;f=f->Item.pNext){ if(f->flags&TNS_MESH_FLAG_SELECTED) f->mat=ms->Index; }
  4163. }
  4164. }elif(o->Type==TNS_OBJECT_SHAPE){ tnsShapeObject* so=o;
  4165. if(so->Mode==TNS_MESH_OBJECT_MODE){
  4166. for(tnsShape*s=so->Shapes.pFirst;s;s=s->Item.pNext){ s->mat=ms->Index; }
  4167. }elif(so->Mode==TNS_MESH_EDIT_MODE){
  4168. for(tnsShape*s=so->Shapes.pFirst;s;s=s->Item.pNext){ if(tnsShapePointAnySelected(s)) s->mat=ms->Index; }
  4169. }
  4170. }
  4171. }
  4172. void tns_InvalidateMeshWithMaterial(tnsMaterial* m);
  4173. void tnsRefreshMaterialLibraries(){
  4174. strSafeDestroy(&T->World->MaterialLibraries);
  4175. for(tnsMaterial* mat=T->World->Materials.pFirst;mat;mat=mat->Item.pNext){
  4176. if(!mat->AsLibrary || !mat->Page->UseScript) continue;
  4177. if(mat->Page->Script) strSafeAppend(&T->World->MaterialLibraries,mat->Page->Script->Ptr);
  4178. tnsEnsureMaterialShader(mat,1);
  4179. }
  4180. for(tnsMaterial* mat=T->World->Materials.pFirst;mat;mat=mat->Item.pNext){
  4181. if(mat->AsLibrary || !mat->Page->UseScript) continue;
  4182. tnsEnsureMaterialShader(mat,1); tns_InvalidateMeshWithMaterial(mat);
  4183. }
  4184. laNotifyUsers("tns.world");
  4185. }
  4186. void tnsEnsureMaterialShader(tnsMaterial* mat, int Refresh){
  4187. if(Refresh){
  4188. if(mat->Shader && mat->Shader!=T->immShader){ tnsDeleteShaderProgram(mat->Shader); mat->Shader=0; }
  4189. }
  4190. if((!(mat->Page->Script&&mat->Page->Script->Ptr))||mat->AsLibrary){ mat->Shader=T->immShader; return; }
  4191. char* str=mat->Page->Script->Ptr;
  4192. char* lib=T->World->MaterialLibraries?T->World->MaterialLibraries->Ptr:0;
  4193. mat->Shader = tnsNewShaderProgram(
  4194. tnsNewVertexShader(LA_IMM_VERTEX_SHADER),tnsNewFragmentShaderMaterial(LA_OBJECT_FRAGMENT_SHADER,lib,str),-1);
  4195. if(!mat->Shader){ mat->Shader=T->immShader; }
  4196. }
  4197. void tnsPrintMaterials(){
  4198. for(tnsMaterial* m=T->World->Materials.pFirst;m;m=m->Item.pNext){
  4199. printf("%s %d %d\n",(m->Name&&m->Name->Ptr?m->Name->Ptr:""),m,m->Page->Racks.pFirst);
  4200. }
  4201. }
  4202. //==================================================================[Util]
  4203. #define MAX3(a, b, c) \
  4204. a > b ? (a > c ? a : c) : (b > c ? b : c)
  4205. #define MIN3(a, b, c) \
  4206. a < b ? (a < c ? a : c) : (b < c ? b : c)
  4207. extern LA MAIN;
  4208. void tnssRGB2XYZ(tnsVector3d rgb,tnsVector3d xyz){
  4209. tnsMatrix44d mat={0.4124564,0.3575761,0.1804375,0,
  4210. 0.2126729,0.7151522,0.0721750,0,
  4211. 0.0193339,0.1191920,0.9503041,0,0,0,0,0};
  4212. tnsApplyRotation33d(xyz,mat,rgb);
  4213. }
  4214. void tnsClay2XYZ(tnsVector3d rgb,tnsVector3d xyz){
  4215. tnsMatrix44d mat={0.5767309,0.1855540,0.1881852,0,
  4216. 0.2973769,0.6273491,0.0752741,0,
  4217. 0.0270343,0.0706872,0.9911085,0,0,0,0,0};
  4218. tnsApplyRotation33d(xyz,mat,rgb);
  4219. }
  4220. void tnsXYZ2sRGB(tnsVector3d xyz,tnsVector3d rgb){
  4221. tnsMatrix44d mat={3.2404542,-1.5371385,-0.4985314,0,
  4222. -0.9692660,1.8760108,0.0415560,0,
  4223. 0.0556434,-0.2040259,1.0572252,0,0,0,0,0};
  4224. tnsApplyRotation33d(rgb,mat,xyz);
  4225. }
  4226. void tnsXYZ2Clay(tnsVector3d xyz,tnsVector3d rgb){
  4227. tnsMatrix44d mat={2.0413690,-0.5649464,-0.3446944,0,
  4228. -0.9692660,1.8760108,0.0415560,0,
  4229. 0.0134474,-0.1183897,1.0154096,0,0,0,0,0};
  4230. tnsApplyRotation33d(rgb,mat,xyz);
  4231. }
  4232. void tnsRGB2Clay(tnsVector3d rgb, tnsVector3d clay){
  4233. tnsVector3d xyz; tnssRGB2XYZ(rgb,xyz);
  4234. tnsXYZ2Clay(xyz,clay);
  4235. }
  4236. void tnsClay2RGB(tnsVector3d clay, tnsVector3d rgb){
  4237. tnsVector3d xyz; tnsClay2XYZ(clay,xyz);
  4238. tnsXYZ2sRGB(xyz,rgb);
  4239. }
  4240. static real _srgb_transfer_function(real a){
  4241. return .0031308f >= a ? 12.92f * a : 1.055f * powf(a, .4166666666666667f) - .055f;
  4242. }
  4243. static real _srgb_transfer_function_inv(real a){
  4244. return .04045f < a ? powf((a + .055f) / 1.055f, 2.4f) : a / 12.92f;
  4245. }
  4246. void tns2LogsRGBSingle(real* a){
  4247. *a=_srgb_transfer_function(*a);
  4248. }
  4249. void tns2LinearsRGBSingle(real* a){
  4250. *a=_srgb_transfer_function_inv(*a);
  4251. }
  4252. void tns2LogsRGB(real* srgb){
  4253. srgb[0]=_srgb_transfer_function(srgb[0]);
  4254. srgb[1]=_srgb_transfer_function(srgb[1]);
  4255. srgb[2]=_srgb_transfer_function(srgb[2]);
  4256. }
  4257. void tns2LinearsRGB(real* srgb){
  4258. srgb[0]=_srgb_transfer_function_inv(srgb[0]);
  4259. srgb[1]=_srgb_transfer_function_inv(srgb[1]);
  4260. srgb[2]=_srgb_transfer_function_inv(srgb[2]);
  4261. }
  4262. void tnsRGB2OKLAB(real* rgb, real* oklab){
  4263. real l = 0.4122214708f * rgb[0] + 0.5363325363f * rgb[1] + 0.0514459929f * rgb[2];
  4264. real m = 0.2119034982f * rgb[0] + 0.6806995451f * rgb[1] + 0.1073969566f * rgb[2];
  4265. real s = 0.0883024619f * rgb[0] + 0.2817188376f * rgb[1] + 0.6299787005f * rgb[2];
  4266. real l_ = cbrt(l); real m_ = cbrt(m); real s_ = cbrt(s);
  4267. oklab[0]=0.2104542553f*l_ + 0.7936177850f*m_ - 0.0040720468f*s_;
  4268. oklab[1]=1.9779984951f*l_ - 2.4285922050f*m_ + 0.4505937099f*s_;
  4269. oklab[2]=0.0259040371f*l_ + 0.7827717662f*m_ - 0.8086757660f*s_;
  4270. }
  4271. void tnsOKLAB2RGB(real* oklab, real* rgb){
  4272. real l_ = oklab[0] + 0.3963377774f * oklab[1] + 0.2158037573f * oklab[2];
  4273. real m_ = oklab[0] - 0.1055613458f * oklab[1] - 0.0638541728f * oklab[2];
  4274. real s_ = oklab[0] - 0.0894841775f * oklab[1] - 1.2914855480f * oklab[2];
  4275. real l = l_*l_*l_; real m = m_*m_*m_; real s = s_*s_*s_;
  4276. rgb[0]=+4.0767416621f * l - 3.3077115913f * m + 0.2309699292f * s;
  4277. rgb[1]=-1.2684380046f * l + 2.6097574011f * m - 0.3413193965f * s;
  4278. rgb[2]=-0.0041960863f * l - 0.7034186147f * m + 1.7076147010f * s;
  4279. }
  4280. static real _compute_max_saturation(real a, real b){
  4281. real k0, k1, k2, k3, k4, wl, wm, ws;
  4282. if (-1.88170328f * a - 0.80936493f * b > 1){
  4283. k0 = +1.19086277f; k1 = +1.76576728f; k2 = +0.59662641f; k3 = +0.75515197f; k4 = +0.56771245f;
  4284. wl = +4.0767416621f; wm = -3.3077115913f; ws = +0.2309699292f;
  4285. }
  4286. else if (1.81444104f * a - 1.19445276f * b > 1){
  4287. k0 = +0.73956515f; k1 = -0.45954404f; k2 = +0.08285427f; k3 = +0.12541070f; k4 = +0.14503204f;
  4288. wl = -1.2684380046f; wm = +2.6097574011f; ws = -0.3413193965f;
  4289. }
  4290. else{
  4291. k0 = +1.35733652f; k1 = -0.00915799f; k2 = -1.15130210f; k3 = -0.50559606f; k4 = +0.00692167f;
  4292. wl = -0.0041960863f; wm = -0.7034186147f; ws = +1.7076147010f;
  4293. }
  4294. real S = k0 + k1 * a + k2 * b + k3 * a * a + k4 * a * b;
  4295. real k_l = +0.3963377774f * a + 0.2158037573f * b;
  4296. real k_m = -0.1055613458f * a - 0.0638541728f * b;
  4297. real k_s = -0.0894841775f * a - 1.2914855480f * b;
  4298. {
  4299. real l_ = 1.f + S * k_l;
  4300. real m_ = 1.f + S * k_m;
  4301. real s_ = 1.f + S * k_s;
  4302. real l = l_ * l_ * l_;
  4303. real m = m_ * m_ * m_;
  4304. real s = s_ * s_ * s_;
  4305. real l_dS = 3.f * k_l * l_ * l_;
  4306. real m_dS = 3.f * k_m * m_ * m_;
  4307. real s_dS = 3.f * k_s * s_ * s_;
  4308. real l_dS2 = 6.f * k_l * k_l * l_;
  4309. real m_dS2 = 6.f * k_m * k_m * m_;
  4310. real s_dS2 = 6.f * k_s * k_s * s_;
  4311. real f = wl * l + wm * m + ws * s;
  4312. real f1 = wl * l_dS + wm * m_dS + ws * s_dS;
  4313. real f2 = wl * l_dS2 + wm * m_dS2 + ws * s_dS2;
  4314. S = S - f * f1 / (f1 * f1 - 0.5f * f * f2);
  4315. }
  4316. return S;
  4317. }
  4318. static void _find_cusp(real a, real b, real *l, real *c)
  4319. {
  4320. real S_cusp = _compute_max_saturation(a, b);
  4321. real oklab[3]={1, S_cusp * a, S_cusp * b}; real rgb_at_max[3];
  4322. tnsOKLAB2RGB(oklab,rgb_at_max);
  4323. real L_cusp = cbrt(1.f / TNS_MAX3(rgb_at_max[0], rgb_at_max[1], rgb_at_max[2]));
  4324. real C_cusp = L_cusp * S_cusp;
  4325. *l=L_cusp; *c=C_cusp;
  4326. }
  4327. static real _find_gamut_intersection(real a, real b, real L1, real C1, real L0, real cusp_L, real cusp_C)
  4328. {
  4329. real t;
  4330. if (((L1 - L0) * cusp_C - (cusp_L - L0) * C1) <= 0.f) {
  4331. t = cusp_C * L0 / (C1 * cusp_L + cusp_C * (L0 - L1));
  4332. }else{
  4333. t = cusp_C * (L0 - 1.f) / (C1 * (cusp_L - 1.f) + cusp_C * (L0 - L1));
  4334. {
  4335. real dL = L1 - L0; real dC = C1;
  4336. real k_l = +0.3963377774f * a + 0.2158037573f * b;
  4337. real k_m = -0.1055613458f * a - 0.0638541728f * b;
  4338. real k_s = -0.0894841775f * a - 1.2914855480f * b;
  4339. real l_dt = dL + dC * k_l;
  4340. real m_dt = dL + dC * k_m;
  4341. real s_dt = dL + dC * k_s;
  4342. {
  4343. real L = L0 * (1.f - t) + t * L1;
  4344. real C = t * C1;
  4345. real l_ = L + C * k_l;
  4346. real m_ = L + C * k_m;
  4347. real s_ = L + C * k_s;
  4348. real l = l_ * l_ * l_;
  4349. real m = m_ * m_ * m_;
  4350. real s = s_ * s_ * s_;
  4351. real ldt = 3 * l_dt * l_ * l_;
  4352. real mdt = 3 * m_dt * m_ * m_;
  4353. real sdt = 3 * s_dt * s_ * s_;
  4354. real ldt2 = 6 * l_dt * l_dt * l_;
  4355. real mdt2 = 6 * m_dt * m_dt * m_;
  4356. real sdt2 = 6 * s_dt * s_dt * s_;
  4357. real r = 4.0767416621f * l - 3.3077115913f * m + 0.2309699292f * s - 1;
  4358. real r1 = 4.0767416621f * ldt - 3.3077115913f * mdt + 0.2309699292f * sdt;
  4359. real r2 = 4.0767416621f * ldt2 - 3.3077115913f * mdt2 + 0.2309699292f * sdt2;
  4360. real u_r = r1 / (r1 * r1 - 0.5f * r * r2);
  4361. real t_r = -r * u_r;
  4362. real g = -1.2684380046f * l + 2.6097574011f * m - 0.3413193965f * s - 1;
  4363. real g1 = -1.2684380046f * ldt + 2.6097574011f * mdt - 0.3413193965f * sdt;
  4364. real g2 = -1.2684380046f * ldt2 + 2.6097574011f * mdt2 - 0.3413193965f * sdt2;
  4365. real u_g = g1 / (g1 * g1 - 0.5f * g * g2);
  4366. real t_g = -g * u_g;
  4367. real b = -0.0041960863f * l - 0.7034186147f * m + 1.7076147010f * s - 1;
  4368. real b1 = -0.0041960863f * ldt - 0.7034186147f * mdt + 1.7076147010f * sdt;
  4369. real b2 = -0.0041960863f * ldt2 - 0.7034186147f * mdt2 + 1.7076147010f * sdt2;
  4370. real u_b = b1 / (b1 * b1 - 0.5f * b * b2);
  4371. real t_b = -b * u_b;
  4372. t_r = u_r >= 0.f ? t_r : FLT_MAX;
  4373. t_g = u_g >= 0.f ? t_g : FLT_MAX;
  4374. t_b = u_b >= 0.f ? t_b : FLT_MAX;
  4375. t += fmin(t_r, fmin(t_g, t_b));
  4376. }
  4377. }
  4378. }
  4379. return t;
  4380. }
  4381. static real _toe(real x) {
  4382. const real k_1 = 0.206f; const real k_2 = 0.03f; const real k_3 = (1.f + k_1) / (1.f + k_2);
  4383. return 0.5f * (k_3 * x - k_1 + sqrt((k_3 * x - k_1) * (k_3 * x - k_1) + 4 * k_2 * k_3 * x));
  4384. }
  4385. static real _toe_inv(real x) {
  4386. const real k_1 = 0.206f; const real k_2 = 0.03f; const real k_3 = (1.f + k_1) / (1.f + k_2);
  4387. return (x * x + k_1 * x) / (k_3 * (x + k_2));
  4388. }
  4389. static void _to_ST(real cusp_L, real cusp_C, real* _s, real* _t) {
  4390. real L = cusp_L; real C = cusp_C;
  4391. *_s=C / L; *_t=C / (1 - L);
  4392. }
  4393. static void _get_ST_mid(real a_, real b_, real *s,real *t){
  4394. *s = 0.11516993f + 1.f / (
  4395. +7.44778970f + 4.15901240f * b_
  4396. + a_ * (-2.19557347f + 1.75198401f * b_
  4397. + a_ * (-2.13704948f - 10.02301043f * b_
  4398. + a_ * (-4.24894561f + 5.38770819f * b_ + 4.69891013f * a_
  4399. )))
  4400. );
  4401. *t = 0.11239642f + 1.f / (
  4402. +1.61320320f - 0.68124379f * b_
  4403. + a_ * (+0.40370612f + 0.90148123f * b_
  4404. + a_ * (-0.27087943f + 0.61223990f * b_
  4405. + a_ * (+0.00299215f - 0.45399568f * b_ - 0.14661872f * a_
  4406. )))
  4407. );
  4408. }
  4409. static void _get_Cs(real L, real a_, real b_,real *rC_0, real *rC_mid, real *rC_max){
  4410. real cusp_L,cusp_C; _find_cusp(a_, b_,&cusp_L,&cusp_C);
  4411. real C_max = _find_gamut_intersection(a_, b_, L, 1, L,cusp_L,cusp_C);
  4412. real _S,_T; _to_ST(cusp_L,cusp_C,&_S, &_T);
  4413. real k = C_max / fmin((L * _S), (1 - L) * _T);
  4414. real C_mid;{
  4415. real _s, _t; _get_ST_mid(a_, b_,&_s,&_t);
  4416. real C_a = L * _s; real C_b = (1.f - L) * _t;
  4417. C_mid = 0.9f * k * sqrt(sqrt(1.f / (1.f / (C_a * C_a * C_a * C_a) + 1.f / (C_b * C_b * C_b * C_b))));
  4418. }
  4419. real C_0;{
  4420. real C_a = L * 0.4f;
  4421. real C_b = (1.f - L) * 0.8f;
  4422. C_0 = sqrt(1.f / (1.f / (C_a * C_a) + 1.f / (C_b * C_b)));
  4423. }
  4424. *rC_0=C_0; *rC_mid=C_mid; *rC_max=C_max;
  4425. }
  4426. void tnsHCY2RGBLinear(real *hcy, real *rgb){
  4427. real h = hcy[0]; real s = hcy[1]; real l = hcy[2];
  4428. if (l >= 1.0f){ tnsVectorSet3(rgb,1,1,1); return; }
  4429. else if (l <= 0.0f){ tnsVectorSet3(rgb,0,0,0); return; }
  4430. real a_ = cos(2.f * TNS_PI * h);
  4431. real b_ = sin(2.f * TNS_PI * h);
  4432. real L = _toe_inv(l);
  4433. real C_0, C_mid, C_max;
  4434. _get_Cs(L, a_, b_,&C_0,&C_mid,&C_max);
  4435. real mid = 0.8f; real mid_inv = 1.25f;
  4436. real C, t, k_0, k_1, k_2;
  4437. if (s < mid){
  4438. t = mid_inv * s;
  4439. k_1 = mid * C_0;
  4440. k_2 = (1.f - k_1 / C_mid);
  4441. C = t * k_1 / (1.f - k_2 * t);
  4442. }else{
  4443. t = (s - mid)/ (1 - mid);
  4444. k_0 = C_mid;
  4445. k_1 = (1.f - mid) * C_mid * C_mid * mid_inv * mid_inv / C_0;
  4446. k_2 = (1.f - (k_1) / (C_max - C_mid));
  4447. C = k_0 + t * k_1 / (1.f - k_2 * t);
  4448. }
  4449. real okl[3]={L, C * a_, C * b_};
  4450. tnsOKLAB2RGB(okl, rgb);
  4451. }
  4452. void tnsRGB2HCYLinear(real *rgb, real *hcy){
  4453. real lab[3]; real lrgb[3];
  4454. lrgb[0]=rgb[0]; lrgb[1]=rgb[1]; lrgb[2]=rgb[2];
  4455. tnsRGB2OKLAB(lrgb,lab);
  4456. if(lab[0]>=1.0f-1e-4){ tnsVectorSet3(hcy,0,0,1); return; }
  4457. if(lab[0]<=1e-4){ tnsVectorSet3(hcy,0,0,0); return; }
  4458. real C = sqrt(lab[1]*lab[1] + lab[2]*lab[2]);
  4459. real a_ = (!C)?0:(lab[1] / C);
  4460. real b_ = (!C)?0:(lab[2] / C);
  4461. real L = lab[0];
  4462. real h = 0.5f + 0.5f * atan2(-lab[2], -lab[1]) / TNS_PI;
  4463. real C_0, C_mid, C_max;
  4464. _get_Cs(L, a_, b_,&C_0,&C_mid,&C_max);
  4465. real mid = 0.8f; real mid_inv = 1.25f;
  4466. real s;
  4467. if (C < C_mid){
  4468. real k_1 = mid * C_0;
  4469. real k_2 = (1.f - k_1 / C_mid);
  4470. real t = C / (k_1 + k_2 * C);
  4471. s = t * mid;
  4472. }else{
  4473. real k_0 = C_mid;
  4474. real k_1 = (1.f - mid) * C_mid * C_mid * mid_inv * mid_inv / C_0;
  4475. real k_2 = (1.f - (k_1) / (C_max - C_mid));
  4476. real t = (C - k_0) / (k_1 + k_2 * (C - k_0));
  4477. s = mid + (1.f - mid) * t;
  4478. }
  4479. real l = _toe(L);
  4480. hcy[0]=h; hcy[1]=s; hcy[2]=l;
  4481. }
  4482. void tnsHCY2RGB(real *hcy, real *rgb){
  4483. tnsHCY2RGBLinear(hcy,rgb);
  4484. rgb[0]=_srgb_transfer_function(rgb[0]);
  4485. rgb[1]=_srgb_transfer_function(rgb[1]);
  4486. rgb[2]=_srgb_transfer_function(rgb[2]);
  4487. }
  4488. void tnsRGB2HCY(real *rgb, real *hcy){
  4489. real lrgb[3];
  4490. lrgb[0]=_srgb_transfer_function_inv(rgb[0]);
  4491. lrgb[1]=_srgb_transfer_function_inv(rgb[1]);
  4492. lrgb[2]=_srgb_transfer_function_inv(rgb[2]);
  4493. tnsRGB2HCYLinear(lrgb,hcy);
  4494. }
  4495. static float hue2rgb(float p, float q, float t) {
  4496. if (t < 0) t += 1; if (t > 1) t -= 1;
  4497. if (t < 1./6) return p + (q - p) * 6 * t;
  4498. if (t < 1./2) return q;
  4499. if (t < 2./3) return p + (q - p) * (2./3 - t) * 6;
  4500. return p;
  4501. }
  4502. void tnsRGB2HSL(real *rgb, real *hsl) {
  4503. float max = TNS_MAX3(rgb[0],rgb[1],rgb[2]);
  4504. float min = TNS_MIN3(rgb[0],rgb[1],rgb[2]);
  4505. hsl[0]=hsl[1]=hsl[2]=(max+min) / 2;
  4506. if (max == min) { hsl[0]=hsl[1]=0; }
  4507. else {
  4508. float d = max - min;
  4509. hsl[1] = (hsl[2] > 0.5) ? d / (2 - max - min) : d / (max + min);
  4510. if (max == rgb[0]) { hsl[0] = (rgb[1] - rgb[2]) / d + (rgb[1] < rgb[2] ? 6 : 0); }
  4511. else if (max == rgb[1]) { hsl[0] = (rgb[2] - rgb[0]) / d + 2; }
  4512. else if (max == rgb[2]) { hsl[0] = (rgb[0] - rgb[1]) / d + 4; }
  4513. hsl[0] /= 6;
  4514. }
  4515. }
  4516. void tnsHSL2RGB(real *hsl, real *rgb) {
  4517. if(hsl[1]==0) {rgb[0]=rgb[1]=rgb[2]=hsl[2];}
  4518. else {
  4519. float q = hsl[2] < 0.5 ? hsl[2] * (1 + hsl[1]) : hsl[2] + hsl[1] - hsl[2] * hsl[1];
  4520. float p = 2 * hsl[2] - q;
  4521. rgb[0] = hue2rgb(p, q, hsl[0] + 1./3);
  4522. rgb[1] = hue2rgb(p, q, hsl[0]);
  4523. rgb[2] = hue2rgb(p, q, hsl[0] - 1./3);
  4524. }
  4525. }
  4526. // https://web.archive.org/web/20180423091842/http://www.equasys.de/colorconversion.html
  4527. void tnsYUV2RGB(real* yuv,real* rgb){
  4528. yuv[0]=1.1643*(yuv[0]-0.0625);
  4529. yuv[1]-=0.5; yuv[2]-=0.5;
  4530. rgb[0] = (yuv[0] + 1.793 * yuv[2]);
  4531. rgb[1] = (yuv[0] - 0.213 * yuv[1] - 0.533 * yuv[2]);
  4532. rgb[2] = (yuv[0] + 2.112 * yuv[1]);
  4533. }
  4534. void tnsClearAll(){
  4535. glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);
  4536. }
  4537. void tnsClearColorv(real *rgba){
  4538. glClearColor(rgba[0], rgba[1], rgba[2], rgba[3]);
  4539. }
  4540. void tnsClearColor(real r, real g, real b, real a){
  4541. glClearColor(r, g, b, a);
  4542. }
  4543. //Assuming *result is long enough
  4544. void tnsMakeIndexUInt(unsigned int *result, int num, ...){
  4545. int i;
  4546. va_list list;
  4547. va_start(list, num);
  4548. for (i = 0; i < num; i++){
  4549. result[i] = va_arg(list, unsigned int);
  4550. }
  4551. va_end(list);
  4552. }
  4553. void tnsMakeTriangle(real *arr, real x1, real y1, real x2, real y2, real x3, real y3){
  4554. arr[0] = x1;
  4555. arr[1] = y1;
  4556. arr[2] = x2;
  4557. arr[3] = y2;
  4558. arr[4] = x3;
  4559. arr[5] = y3;
  4560. }
  4561. void tnsMakeQuad2d(real *arr, real x1, real y1, real x2, real y2, real x3, real y3, real x4, real y4){
  4562. arr[0] = x1;
  4563. arr[1] = y1;
  4564. arr[2] = x2;
  4565. arr[3] = y2;
  4566. arr[4] = x3;
  4567. arr[5] = y3;
  4568. arr[6] = x4;
  4569. arr[7] = y4;
  4570. }
  4571. void tnsMakeQuadT2d(real *arr, real x1, real y1, real x2, real y2, real x3, real y3, real x4, real y4){
  4572. arr[0] = x1;
  4573. arr[1] = y1;
  4574. arr[2] = x2;
  4575. arr[3] = y2;
  4576. arr[4] = x3;
  4577. arr[5] = y3;
  4578. arr[6] = x2;
  4579. arr[7] = y2;
  4580. arr[8] = x3;
  4581. arr[9] = y3;
  4582. arr[10] = x4;
  4583. arr[11] = y4;
  4584. }
  4585. void tnsMakeQuad3d(real *arr, real x1, real y1, real z1, real x2, real y2, real z2, real x3, real y3, real z3, real x4, real y4, real z4){
  4586. arr[0] = x1;
  4587. arr[1] = y1;
  4588. arr[2] = z1;
  4589. arr[3] = x2;
  4590. arr[4] = y2;
  4591. arr[5] = z2;
  4592. arr[6] = x3;
  4593. arr[7] = y3;
  4594. arr[8] = z3;
  4595. arr[9] = x4;
  4596. arr[10] = y4;
  4597. arr[11] = z4;
  4598. }
  4599. void tnsMakeQuad4d(real *arr, real x1, real y1, real z1, real w1, real x2, real y2, real z2, real w2, real x3, real y3, real z3, real w3, real x4, real y4, real z4, real w4){
  4600. arr[0] = x1;
  4601. arr[1] = y1;
  4602. arr[2] = z1;
  4603. arr[3] = w1;
  4604. arr[4] = x2;
  4605. arr[5] = y2;
  4606. arr[6] = z2;
  4607. arr[7] = w2;
  4608. arr[8] = x3;
  4609. arr[9] = y3;
  4610. arr[10] = z3;
  4611. arr[11] = w3;
  4612. arr[12] = x4;
  4613. arr[13] = y4;
  4614. arr[14] = z4;
  4615. arr[15] = w4;
  4616. }
  4617. void tnsMakeCircle2d(real *arr, int slices, real ctrX, real ctrY, real r, int jump){
  4618. int i;
  4619. real radstep = 2 * TNS_PI / (real)slices;
  4620. real rd = 0;
  4621. real x, y;
  4622. for (i = 0; i < slices; i++){
  4623. x = ctrX + cos(rd) * r;
  4624. y = ctrY + sin(rd) * r;
  4625. int idx=2 * i * (1+jump);
  4626. arr[idx] = x;
  4627. arr[idx+1] = y;
  4628. rd += radstep;
  4629. }
  4630. }
  4631. void tnsMakeArc2d(real *arr, int slices, real ctrX, real ctrY, real r, real rad_begin, real rad_end){
  4632. int i;
  4633. real radstep = (rad_end - rad_begin) / (real)slices;
  4634. real rd = rad_begin + TNS_PI * 2;
  4635. real x, y;
  4636. for (i = 0; i <= slices; i++){
  4637. x = ctrX + cos(rd) * r;
  4638. y = ctrY + sin(rd) * r;
  4639. arr[2 * i] = x;
  4640. arr[2 * i + 1] = y;
  4641. rd += radstep;
  4642. }
  4643. }
  4644. void tnsMakeBridgedIndex(unsigned int *result, int num, int revert, int begin){
  4645. int i;
  4646. if (!revert){
  4647. for (i = 0; i < num; i++){
  4648. result[i * 2] = begin + i;
  4649. result[i * 2 + 1] = begin + i + num;
  4650. }
  4651. }else{
  4652. for (i = 0; i < num; i++){
  4653. result[i * 2] = begin + i;
  4654. result[i * 2 + 1] = begin - i + num * 2;
  4655. }
  4656. }
  4657. }
  4658. void tnsMakeRing2d(real *arr, int *index, int slices, real ctrX, real ctrY, real r1, real r2){
  4659. tnsMakeCircle2d(arr, slices, ctrX, ctrY, r1,0);
  4660. tnsMakeCircle2d(&arr[slices*2], slices, ctrX, ctrY, r2,0);
  4661. tnsMakeBridgedIndex(index, slices, 0, 0);
  4662. index[slices*2]=0; index[slices*2+1]=slices;
  4663. }
  4664. void tnsMakeLinerGradient3d(real *arr, int num_points, real r0, real g0, real b0, real r1, real g1, real b1){
  4665. int i = 0;
  4666. real sr = (r1 - r0) / (real)num_points, sg = (g1 - g0) / (real)num_points, sb = (b1 - b0) / (real)num_points;
  4667. for (i; i < num_points; i++){
  4668. int a = 3 * i;
  4669. arr[a] = r0 + sr * i;
  4670. arr[a + 1] = g0 + sg * i;
  4671. arr[a + 2] = b0 + sb * i;
  4672. }
  4673. }
  4674. void tnsMakeLinerGradient4d(real *arr, int num_points, real r0, real g0, real b0, real a0, real r1, real g1, real b1, real a1){
  4675. int i = 0;
  4676. real sr = (r1 - r0) / (real)num_points, sg = (g1 - g0) / (real)num_points, sb = (b1 - b0) / (real)num_points, sa = (a1 - a0) / (real)num_points;
  4677. for (i; i < num_points; i++){
  4678. int a = 4 * i;
  4679. arr[a] = r0 + sr * i;
  4680. arr[a + 1] = g0 + sg * i;
  4681. arr[a + 2] = b0 + sb * i;
  4682. arr[a + 3] = a0 + sa * i;
  4683. }
  4684. }
  4685. void tnsMakeLinerGradient3dv(real *arr, int num_points, real *rgb0, real *rgb1){
  4686. int i = 0;
  4687. real sr = (rgb1[0] - rgb0[0]) / (real)num_points, sg = (rgb1[1] - rgb0[1]) / (real)num_points, sb = (rgb1[2] - rgb0[2]) / (real)num_points;
  4688. for (i; i < num_points; i++){
  4689. int a = 3 * i;
  4690. arr[a] = rgb0[0] + sr * i;
  4691. arr[a + 1] = rgb0[1] + sg * i;
  4692. arr[a + 2] = rgb0[2] + sb * i;
  4693. }
  4694. }
  4695. void tnsMakeLinerGradient4dv(real *arr, int num_points, real *rgb0, real *rgb1){
  4696. int i = 0;
  4697. real sr = (rgb1[0] - rgb0[0]) / (real)(num_points - 1), sg = (rgb1[1] - rgb0[1]) / (real)(num_points - 1), sb = (rgb1[2] - rgb0[2]) / (real)(num_points - 1), sa = (rgb1[3] - rgb0[3]) / (real)(num_points - 1);
  4698. for (i; i < num_points; i++){
  4699. int a = 4 * i;
  4700. arr[a] = rgb0[0] + sr * i;
  4701. arr[a + 1] = rgb0[1] + sg * i;
  4702. arr[a + 2] = rgb0[2] + sb * i;
  4703. arr[a + 3] = rgb0[3] + sa * i;
  4704. }
  4705. }
  4706. void tnsMakeFoucsSquare(int L, int R, int U, int B, int W){
  4707. int w = W;
  4708. //int al = Len + w;
  4709. real v[16];
  4710. //v[0] = L - w; v[1] = U - l;
  4711. //v[2] = L - w; v[3] = U + w;
  4712. //v[4] = L + l; v[4] = U + w;
  4713. //v[6] = L + l; v[7] = U - w;
  4714. //v[8] = L + w; v[9] = U - w;
  4715. //v[10] = L + w; v[11] = U - l;
  4716. //v[12] = R - l; v[13] = U + w;
  4717. //v[14] = R + w; v[15] = U + w;
  4718. //v[16] = R + w; v[17] = U - l;
  4719. //v[18] = R - w; v[19] = U - l;
  4720. //v[20] = R - w; v[21] = U - w;
  4721. //v[22] = R - l; v[23] = U - w;
  4722. tnsMakeQuad2d(v, L, U, R, U, R, B, L, B);
  4723. tnsVertexArray2d(v, 4);
  4724. tnsPackAs(GL_LINE_LOOP);
  4725. tnsMakeQuad2d(&v[8], L + W, U - W, R - W, U - W, R - W, B + W, L + W, B + W);
  4726. tnsVertexArray2d(&v[8], 4);
  4727. tnsPackAs(GL_LINE_LOOP);
  4728. }
  4729. void tnsDrawFloor(real* CamPosition, real Far, int *ShowAxis){
  4730. real OrigFar=Far;
  4731. real height=CamPosition[2];
  4732. real dist=sqrt(fabs(Far*Far-height*height));
  4733. real spanstart=Far/10000;
  4734. real spanl=1e-3,spanh=1e-3;
  4735. while((spanl*10)<spanstart){ spanl*=10; } spanh=spanl;
  4736. while((spanh*10)<Far){ spanh*=10; }
  4737. float usefar=Far;
  4738. tnsFlush();
  4739. glEnable(GL_BLEND); glDepthMask(GL_FALSE); glEnable(GL_DEPTH_TEST);
  4740. tnsUseShader(T->FloorShader);
  4741. tnsEnableShaderv(T->FloorShader);
  4742. //glUniform3f(T->FloorShader->uViewPos,1,1,1);
  4743. usefar=Far; glUniform1fv(T->FloorShader->uFar,1,&usefar);
  4744. real sp=spanh;
  4745. while(sp>=spanl){
  4746. real xmin=((int)((CamPosition[0]-dist-sp)/sp))*sp,xmax=((int)((CamPosition[0]+dist+sp)/sp))*sp;
  4747. real ymin=((int)((CamPosition[1]-dist-sp)/sp))*sp,ymax=((int)((CamPosition[1]+dist+sp)/sp))*sp;
  4748. real ux=xmin; while(ux<xmax){ tnsVertex2d(ux,ymin),tnsVertex2d(ux,ymax); ux+=sp; }
  4749. real uy=ymin; while(uy<ymax){ tnsVertex2d(xmin,uy),tnsVertex2d(xmax,uy); uy+=sp; }
  4750. tnsPackAs(GL_LINES);
  4751. tnsFlush();
  4752. Far/=3; if(Far<height) break;
  4753. dist=sqrt(fabs(Far*Far-height*height)); sp/=10;
  4754. usefar=Far; glUniform1fv(T->FloorShader->uFar,1,&usefar);
  4755. }
  4756. //for (i; i < Lim; i++){
  4757. // if (i == Span && ShowAxis[0]) continue;
  4758. // tnsVertex3d(-Dist, i * Size - Dist, 0);
  4759. // tnsVertex3d(Dist, i * Size - Dist, 0);
  4760. //}
  4761. //
  4762. //for (i = 0; i < Lim; i++){
  4763. // if (i == Span && ShowAxis[1]) continue;
  4764. // tnsVertex3d(i * Size - Dist, -Dist, 0);
  4765. // tnsVertex3d(i * Size - Dist, Dist, 0);
  4766. //}
  4767. //tnsPackAs(GL_LINES);
  4768. usefar=OrigFar; glUniform1fv(T->FloorShader->uFar,1,&usefar);
  4769. if (ShowAxis[0]){ tnsColor4d(1, 0, 0, 1);
  4770. tnsVertex3d(-OrigFar, 0, 0); tnsVertex3d(OrigFar, 0, 0);
  4771. tnsPackAs(GL_LINES);
  4772. }
  4773. if (ShowAxis[1]){ tnsColor4d(0, 1, 0, 1);
  4774. tnsVertex3d(0, -OrigFar, 0); tnsVertex3d(0, OrigFar, 0);
  4775. tnsPackAs(GL_LINES);
  4776. }
  4777. if (ShowAxis[2]){ tnsColor4d(0, 0, 1, 1);
  4778. tnsVertex3d(0, 0, -OrigFar); tnsVertex3d(0, 0, OrigFar);
  4779. tnsPackAs(GL_LINES);
  4780. }
  4781. tnsFlush();
  4782. tnsUseShader(T->immShader);
  4783. tnsEnableShaderv(T->immShader);
  4784. glDepthMask(GL_TRUE);
  4785. }
  4786. void tnsDraw2DGrid10(real L, real R, real U, real B, real xmin, real xmax, real ymin, real ymax, real MostDenseW, real MostDenseH,
  4787. real* color4, real AlphaFactor, int ShowGrid, int TextAlign){
  4788. real span; real W=R-L, H=B-U, rangeX=xmax-xmin, rangeY=ymax-ymin, dW=rangeX/W, dH=rangeY/H;
  4789. real MinSpanW=fabs(MostDenseW*dW), MinSpanH=fabs(MostDenseH*dH);
  4790. for(int i=0;i<20;i++){ span=1e-5*pow(10,i); if(span>MinSpanW) break; }
  4791. real startx=((real)((int)(xmin/span)))*span; real x=startx;
  4792. while(x<xmax){
  4793. real lx=tnsInterpolate(L,R,tnsGetRatiod(xmin,xmax,x));
  4794. tnsVertex2d(lx,U);tnsVertex2d(lx,B); x+=span;
  4795. } tnsColor4d(LA_COLOR3(color4),color4[3]*AlphaFactor*AlphaFactor*AlphaFactor); tnsPackAs(GL_LINES);
  4796. x=startx; while(x<xmax){ if((((int)round(x/span))%5)){ x+=span; continue; }
  4797. real lx=tnsInterpolate(L,R,tnsGetRatiod(xmin,xmax,x));
  4798. tnsVertex2d(lx,U);tnsVertex2d(lx,B); x+=span;
  4799. } tnsColor4d(LA_COLOR3(color4),color4[3]*AlphaFactor*AlphaFactor); tnsPackAs(GL_LINES);
  4800. x=startx; while(x<xmax){ if((((int)round(x/span))%10)){ x+=span; continue; }
  4801. real lx=tnsInterpolate(L,R,tnsGetRatiod(xmin,xmax,x));
  4802. tnsVertex2d(lx,U);tnsVertex2d(lx,B); x+=span;
  4803. } tnsColor4d(LA_COLOR3(color4),color4[3]*AlphaFactor); tnsPackAs(GL_LINES);
  4804. for(int i=0;i<20;i++){ span=1e-5*pow(10,i); if(span>MinSpanH) break; }
  4805. real starty=((real)((int)(ymin/span)))*span; real y=starty;
  4806. while(y<ymax){
  4807. real ly=tnsInterpolate(B,U,tnsGetRatiod(ymin,ymax,y));
  4808. tnsVertex2d(L,ly);tnsVertex2d(R,ly); y+=span;
  4809. } tnsColor4d(LA_COLOR3(color4),color4[3]*AlphaFactor*AlphaFactor*AlphaFactor); tnsPackAs(GL_LINES);
  4810. y=starty; while(y<ymax){ if((((int)round(y/span))%5)){ y+=span; continue; }
  4811. real ly=tnsInterpolate(B,U,tnsGetRatiod(ymin,ymax,y));
  4812. tnsVertex2d(L,ly);tnsVertex2d(R,ly); y+=span;
  4813. } tnsColor4d(LA_COLOR3(color4),color4[3]*AlphaFactor*AlphaFactor); tnsPackAs(GL_LINES);
  4814. y=starty; while(y<ymax){ if((((int)round(y/span))%10)){ y+=span; continue; }
  4815. real ly=tnsInterpolate(B,U,tnsGetRatiod(ymin,ymax,y));
  4816. tnsVertex2d(L,ly);tnsVertex2d(R,ly); y+=span;
  4817. } tnsColor4d(LA_COLOR3(color4),color4[3]*AlphaFactor); tnsPackAs(GL_LINES);
  4818. }