*/}}
1
0

la_tns_kernel.c 191 KB

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