small3dlib.h 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810
  1. #ifndef SMALL3DLIB_H
  2. #define SMALL3DLIB_H
  3. /*
  4. Simple realtime 3D software rasterization renderer. It is fast, focused on
  5. resource-limited computers, located in a single C header file, with no
  6. dependencies, using only 32bit integer arithmetics.
  7. author: Miloslav Ciz
  8. license: CC0 1.0 (public domain)
  9. found at https://creativecommons.org/publicdomain/zero/1.0/
  10. + additional waiver of all IP
  11. version: 0.852d
  12. Before including the library, define S3L_PIXEL_FUNCTION to the name of the
  13. function you'll be using to draw single pixels (this function will be called
  14. by the library to render the frames). Also either init S3L_resolutionX and
  15. S3L_resolutionY or define S3L_RESOLUTION_X and S3L_RESOLUTION_Y.
  16. You'll also need to decide what rendering strategy and other settings you
  17. want to use, depending on your specific usecase. You may want to use a
  18. z-buffer (full or reduced, S3L_Z_BUFFER), sorted-drawing (S3L_SORT), or even
  19. none of these. See the description of the options in this file.
  20. The rendering itself is done with S3L_drawScene, usually preceded by
  21. S3L_newFrame (for clearing zBuffer etc.).
  22. The library is meant to be used in not so huge programs that use single
  23. translation unit and so includes both declarations and implementation at once.
  24. If you for some reason use multiple translation units (which include the
  25. library), you'll have to handle this yourself (e.g. create a wrapper, manually
  26. split the library into .c and .h etc.).
  27. --------------------
  28. This work's goal is to never be encumbered by any exclusive intellectual
  29. property rights. The work is therefore provided under CC0 1.0 + additional
  30. WAIVER OF ALL INTELLECTUAL PROPERTY RIGHTS that waives the rest of
  31. intellectual property rights not already waived by CC0 1.0. The WAIVER OF ALL
  32. INTELLECTUAL PROPERTY RGHTS is as follows:
  33. Each contributor to this work agrees that they waive any exclusive rights,
  34. including but not limited to copyright, patents, trademark, trade dress,
  35. industrial design, plant varieties and trade secrets, to any and all ideas,
  36. concepts, processes, discoveries, improvements and inventions conceived,
  37. discovered, made, designed, researched or developed by the contributor either
  38. solely or jointly with others, which relate to this work or result from this
  39. work. Should any waiver of such right be judged legally invalid or
  40. ineffective under applicable law, the contributor hereby grants to each
  41. affected person a royalty-free, non transferable, non sublicensable, non
  42. exclusive, irrevocable and unconditional license to this right.
  43. --------------------
  44. CONVENTIONS:
  45. This library should never draw pixels outside the specified screen
  46. boundaries, so you don't have to check this (that would cost CPU time)!
  47. You can safely assume that triangles are rasterized one by one and from top
  48. down, left to right (so you can utilize e.g. various caches), and if sorting
  49. is disabled the order of rasterization will be that specified in the scene
  50. structure and model arrays (of course, some triangles and models may be
  51. skipped due to culling etc.).
  52. Angles are in S3L_Units, a full angle (2 pi) is S3L_FRACTIONS_PER_UNITs.
  53. We use row vectors.
  54. In 3D space, a left-handed coord. system is used. One spatial unit is split
  55. into S3L_FRACTIONS_PER_UNIT fractions (fixed point arithmetic).
  56. y ^
  57. | _
  58. | /| z
  59. | /
  60. | /
  61. [0,0,0]-------> x
  62. Untransformed camera is placed at [0,0,0], looking forward along +z axis. The
  63. projection plane is centered at [0,0,0], stretrinch from
  64. -S3L_FRACTIONS_PER_UNIT to S3L_FRACTIONS_PER_UNIT horizontally (x),
  65. vertical size (y) depends on the aspect ratio (S3L_RESOLUTION_X and
  66. S3L_RESOLUTION_Y). Camera FOV is defined by focal length in S3L_Units.
  67. y ^
  68. | _
  69. | /| z
  70. ____|_/__
  71. | |/ |
  72. -----[0,0,0]-|-----> x
  73. |____|____|
  74. |
  75. |
  76. Rotations use Euler angles and are generally in the extrinsic Euler angles in
  77. ZXY order (by Z, then by X, then by Y). Positive rotation about an axis
  78. rotates CW (clock-wise) when looking in the direction of the axis.
  79. Coordinates of pixels on the screen start at the top left, from [0,0].
  80. There is NO subpixel accuracy (screen coordinates are only integer).
  81. Triangle rasterization rules are these (mostly same as OpenGL, D3D etc.):
  82. - Let's define:
  83. - left side:
  84. - not exactly horizontal, and on the left side of triangle
  85. - exactly horizontal and above the topmost
  86. (in other words: its normal points at least a little to the left or
  87. completely up)
  88. - right side: not left side
  89. - Pixel centers are at integer coordinates and triangle for drawing are
  90. specified with integer coordinates of pixel centers.
  91. - A pixel is rasterized:
  92. - if its center is inside the triangle OR
  93. - if its center is exactly on the triangle side which is left and at the
  94. same time is not on the side that's right (case of a triangle that's on
  95. a single line) OR
  96. - if its center is exactly on the triangle corner of sides neither of which
  97. is right.
  98. These rules imply among others:
  99. - Adjacent triangles don't have any overlapping pixels, nor gaps between.
  100. - Triangles of points that lie on a single line are NOT rasterized.
  101. - A single "long" triangle CAN be rasterized as isolated islands of pixels.
  102. - Transforming (e.g. mirroring, rotating by 90 degrees etc.) a result of
  103. rasterizing triangle A is NOT generally equal to applying the same
  104. transformation to triangle A first and then rasterizing it. Even the number
  105. of rasterized pixels is usually different.
  106. - If specifying a triangle with integer coordinates (which we are), then:
  107. - The bottom-most corner (or side) of a triangle is never rasterized
  108. (because it is connected to a right side).
  109. - The top-most corner can only be rasterized on completely horizontal side
  110. (otherwise it is connected to a right side).
  111. - Vertically middle corner is rasterized if and only if it is on the left
  112. of the triangle and at the same time is also not the bottom-most corner.
  113. */
  114. #include <stdint.h>
  115. #ifdef S3L_RESOLUTION_X
  116. #ifdef S3L_RESOLUTION_Y
  117. #define S3L_MAX_PIXELS (S3L_RESOLUTION_X * S3L_RESOLUTION_Y)
  118. #endif
  119. #endif
  120. #ifndef S3L_RESOLUTION_X
  121. #ifndef S3L_MAX_PIXELS
  122. #error Dynamic resolution set (S3L_RESOLUTION_X not defined), but\
  123. S3L_MAX_PIXELS not defined!
  124. #endif
  125. uint16_t S3L_resolutionX = 512; /**< If a static resolution is not set with
  126. S3L_RESOLUTION_X, this variable can be
  127. used to change X resolution at runtime,
  128. in which case S3L_MAX_PIXELS has to be
  129. defined (to allocate zBuffer etc.)! */
  130. #define S3L_RESOLUTION_X S3L_resolutionX
  131. #endif
  132. #ifndef S3L_RESOLUTION_Y
  133. #ifndef S3L_MAX_PIXELS
  134. #error Dynamic resolution set (S3L_RESOLUTION_Y not defined), but\
  135. S3L_MAX_PIXELS not defined!
  136. #endif
  137. uint16_t S3L_resolutionY = 512; /**< Same as S3L_resolutionX, but for Y
  138. resolution. */
  139. #define S3L_RESOLUTION_Y S3L_resolutionY
  140. #endif
  141. /** Units of measurement in 3D space. There is S3L_FRACTIONS_PER_UNIT in one
  142. spatial unit. By dividing the unit into fractions we effectively achieve a
  143. fixed point arithmetic. The number of fractions is a constant that serves as
  144. 1.0 in floating point arithmetic (normalization etc.). */
  145. typedef int32_t S3L_Unit;
  146. /** How many fractions a spatial unit is split into. This is NOT SUPPOSED TO
  147. BE REDEFINED, so rather don't do it (otherwise things may overflow etc.). */
  148. #define S3L_FRACTIONS_PER_UNIT 512
  149. typedef int16_t S3L_ScreenCoord;
  150. typedef uint16_t S3L_Index;
  151. #ifndef S3L_NEAR_CROSS_STRATEGY
  152. /** Specifies how the library will handle triangles that partially cross the
  153. near plane. These are problematic and require special handling. Possible
  154. values:
  155. 0: Strictly cull any triangle crossing the near plane. This will make such
  156. triangles disappear. This is good for performance or models viewed only
  157. from at least small distance.
  158. 1: Forcefully push the vertices crossing near plane in front of it. This is
  159. a cheap technique that can be good enough for displaying simple
  160. environments on slow devices, but texturing and geometric artifacts/warps
  161. will appear.
  162. 2: Geometrically correct the triangles crossing the near plane. This may
  163. result in some triangles being subdivided into two and is a little more
  164. expensive, but the results will be geometrically correct, even though
  165. barycentric correction is not performed so texturing artifacts will
  166. appear. Can be ideal with S3L_FLAT.
  167. 3: NOT IMPLEMENTED YET
  168. Perform both geometrical and barycentric correction of triangle crossing
  169. the near plane. This is significantly more expensive but results in
  170. correct rendering.
  171. */
  172. #define S3L_NEAR_CROSS_STRATEGY 0
  173. #endif
  174. #ifndef S3L_FLAT
  175. /** If on, disables computation of per-pixel values such as barycentric
  176. coordinates and depth -- these will still be available but will be the same
  177. for the whole triangle. This can be used to create flat-shaded renders and
  178. will be a lot faster. With this option on you will probably want to use
  179. sorting instead of z-buffer. */
  180. #define S3L_FLAT 0
  181. #endif
  182. #if S3L_FLAT
  183. #define S3L_COMPUTE_DEPTH 0
  184. #define S3L_PERSPECTIVE_CORRECTION 0
  185. // don't disable z-buffer, it makes sense to use it with no sorting
  186. #endif
  187. #ifndef S3L_PERSPECTIVE_CORRECTION
  188. /** Specifies what type of perspective correction (PC) to use. Remember this
  189. is an expensive operation! Possible values:
  190. - 0: No perspective correction. Fastest, inaccurate from most angles.
  191. - 1: Per-pixel perspective correction, accurate but very expensive.
  192. - 2: Approximation (computing only at every S3L_PC_APPROX_LENGTHth pixel).
  193. Quake-style approximation is used, which only computes the PC after
  194. S3L_PC_APPROX_LENGTH pixels. This is reasonably accurate and fast. */
  195. #define S3L_PERSPECTIVE_CORRECTION 0
  196. #endif
  197. #ifndef S3L_PC_APPROX_LENGTH
  198. /** For S3L_PERSPECTIVE_CORRECTION == 2, this specifies after how many pixels
  199. PC is recomputed. Should be a power of two to keep up the performance.
  200. Smaller is nicer but slower. */
  201. #define S3L_PC_APPROX_LENGTH 32
  202. #endif
  203. #if S3L_PERSPECTIVE_CORRECTION
  204. #define S3L_COMPUTE_DEPTH 1 // PC inevitably computes depth, so enable it
  205. #endif
  206. #ifndef S3L_COMPUTE_DEPTH
  207. /** Whether to compute depth for each pixel (fragment). Some other options
  208. may turn this on automatically. If you don't need depth information, turning
  209. this off can save performance. Depth will still be accessible in
  210. S3L_PixelInfo, but will be constant -- equal to center point depth -- over
  211. the whole triangle. */
  212. #define S3L_COMPUTE_DEPTH 1
  213. #endif
  214. #ifndef S3L_Z_BUFFER
  215. /** What type of z-buffer (depth buffer) to use for visibility determination.
  216. Possible values:
  217. - 0: Don't use z-buffer. This saves a lot of memory, but visibility checking
  218. won't be pixel-accurate and has to mostly be done by other means
  219. (typically sorting).
  220. - 1: Use full z-buffer (of S3L_Units) for visibiltiy determination. This is
  221. the most accurate option (and also a fast one), but requires a big
  222. amount of memory.
  223. - 2: Use reduced-size z-buffer (of bytes). This is fast and somewhat
  224. accurate, but inaccuracies can occur and a considerable amount of memory
  225. is needed. */
  226. #define S3L_Z_BUFFER 0
  227. #endif
  228. #ifndef S3L_REDUCED_Z_BUFFER_GRANULARITY
  229. /** For S3L_Z_BUFFER == 2 this sets the reduced z-buffer granularity. */
  230. #define S3L_REDUCED_Z_BUFFER_GRANULARITY 5
  231. #endif
  232. #ifndef S3L_STENCIL_BUFFER
  233. /** Whether to use stencil buffer for drawing -- with this a pixel that would
  234. be resterized over an already rasterized pixel (within a frame) will be
  235. discarded. This is mostly for front-to-back sorted drawing. */
  236. #define S3L_STENCIL_BUFFER 0
  237. #endif
  238. #ifndef S3L_SORT
  239. /** Defines how to sort triangles before drawing a frame. This can be used to
  240. solve visibility in case z-buffer is not used, to prevent overwriting already
  241. rasterized pixels, implement transparency etc. Note that for simplicity and
  242. performance a relatively simple sorting is used which doesn't work completely
  243. correctly, so mistakes can occur (even the best sorting wouldn't be able to
  244. solve e.g. intersecting triangles). Note that sorting requires a bit of extra
  245. memory -- an array of the triangles to sort -- the size of this array limits
  246. the maximum number of triangles that can be drawn in a single frame
  247. (S3L_MAX_TRIANGES_DRAWN). Possible values:
  248. - 0: Don't sort triangles. This is fastest and doesn't use extra memory.
  249. - 1: Sort triangles from back to front. This can in most cases solve
  250. visibility without requiring almost any extra memory compared to
  251. z-buffer.
  252. - 2: Sort triangles from front to back. This can be faster than back to
  253. front, because we prevent computing pixels that will be overwritten by
  254. nearer ones, but we need a 1b stencil buffer for this (enable
  255. S3L_STENCIL_BUFFER), so a bit more memory is needed. */
  256. #define S3L_SORT 0
  257. #endif
  258. #ifndef S3L_MAX_TRIANGES_DRAWN
  259. /** Maximum number of triangles that can be drawn in sorted modes. This
  260. affects the size of the cache used for triangle sorting. */
  261. #define S3L_MAX_TRIANGES_DRAWN 128
  262. #endif
  263. #ifndef S3L_NEAR
  264. /** Distance of the near clipping plane. Points in front or EXATLY ON this
  265. plane are considered outside the frustum. This must be >= 0. */
  266. #define S3L_NEAR (S3L_FRACTIONS_PER_UNIT / 4)
  267. #endif
  268. #if S3L_NEAR <= 0
  269. #define S3L_NEAR 1 // Can't be <= 0.
  270. #endif
  271. #ifndef S3L_NORMAL_COMPUTE_MAXIMUM_AVERAGE
  272. /** Affects the S3L_computeModelNormals function. See its description for
  273. details. */
  274. #define S3L_NORMAL_COMPUTE_MAXIMUM_AVERAGE 6
  275. #endif
  276. #ifndef S3L_FAST_LERP_QUALITY
  277. /** Quality (scaling) of SOME (stepped) linear interpolations. 0 will most
  278. likely be a tiny bit faster, but artifacts can occur for bigger tris, while
  279. higher values can fix this -- in theory all higher values will have the same
  280. speed (it is a shift value), but it mustn't be too high to prevent
  281. overflow. */
  282. #define S3L_FAST_LERP_QUALITY 11
  283. #endif
  284. /** Vector that consists of four scalars and can represent homogenous
  285. coordinates, but is generally also used as Vec3 and Vec2 for various
  286. purposes. */
  287. typedef struct
  288. {
  289. S3L_Unit x;
  290. S3L_Unit y;
  291. S3L_Unit z;
  292. S3L_Unit w;
  293. } S3L_Vec4;
  294. #define S3L_logVec4(v)\
  295. printf("Vec4: %d %d %d %d\n",((v).x),((v).y),((v).z),((v).w))
  296. static inline void S3L_initVec4(S3L_Vec4 *v);
  297. static inline void S3L_setVec4(S3L_Vec4 *v, S3L_Unit x, S3L_Unit y,
  298. S3L_Unit z, S3L_Unit w);
  299. static inline void S3L_vec3Add(S3L_Vec4 *result, S3L_Vec4 added);
  300. static inline void S3L_vec3Sub(S3L_Vec4 *result, S3L_Vec4 substracted);
  301. S3L_Unit S3L_vec3Length(S3L_Vec4 v);
  302. /** Normalizes Vec3. Note that this function tries to normalize correctly
  303. rather than quickly! If you need to normalize quickly, do it yourself in a
  304. way that best fits your case. */
  305. void S3L_normalizeVec3(S3L_Vec4 *v);
  306. /** Like S3L_normalizeVec3, but doesn't perform any checks on the input vector,
  307. which is faster, but can be very innacurate or overflowing. You are supposed
  308. to provide a "nice" vector (not too big or small). */
  309. static inline void S3L_normalizeVec3Fast(S3L_Vec4 *v);
  310. S3L_Unit S3L_vec2Length(S3L_Vec4 v);
  311. void S3L_crossProduct(S3L_Vec4 a, S3L_Vec4 b, S3L_Vec4 *result);
  312. static inline S3L_Unit S3L_dotProductVec3(S3L_Vec4 a, S3L_Vec4 b);
  313. /** Computes a reflection direction (typically used e.g. for specular component
  314. in Phong illumination). The input vectors must be normalized. The result will
  315. be normalized as well. */
  316. void S3L_reflect(S3L_Vec4 toLight, S3L_Vec4 normal, S3L_Vec4 *result);
  317. /** Determines the winding of a triangle, returns 1 (CW, clockwise), -1 (CCW,
  318. counterclockwise) or 0 (points lie on a single line). */
  319. static inline int8_t S3L_triangleWinding(
  320. S3L_ScreenCoord x0,
  321. S3L_ScreenCoord y0,
  322. S3L_ScreenCoord x1,
  323. S3L_ScreenCoord y1,
  324. S3L_ScreenCoord x2,
  325. S3L_ScreenCoord y2);
  326. typedef struct
  327. {
  328. S3L_Vec4 translation;
  329. S3L_Vec4 rotation; /**< Euler angles. Rortation is applied in this order:
  330. 1. z = by z (roll) CW looking along z+
  331. 2. x = by x (pitch) CW looking along x+
  332. 3. y = by y (yaw) CW looking along y+ */
  333. S3L_Vec4 scale;
  334. } S3L_Transform3D;
  335. #define S3L_logTransform3D(t)\
  336. printf("Transform3D: T = [%d %d %d], R = [%d %d %d], S = [%d %d %d]\n",\
  337. (t).translation.x,(t).translation.y,(t).translation.z,\
  338. (t).rotation.x,(t).rotation.y,(t).rotation.z,\
  339. (t).scale.x,(t).scale.y,(t).scale.z)
  340. static inline void S3L_initTransform3D(S3L_Transform3D *t);
  341. void S3L_lookAt(S3L_Vec4 pointTo, S3L_Transform3D *t);
  342. void S3L_setTransform3D(
  343. S3L_Unit tx,
  344. S3L_Unit ty,
  345. S3L_Unit tz,
  346. S3L_Unit rx,
  347. S3L_Unit ry,
  348. S3L_Unit rz,
  349. S3L_Unit sx,
  350. S3L_Unit sy,
  351. S3L_Unit sz,
  352. S3L_Transform3D *t);
  353. /** Converts rotation transformation to three direction vectors of given length
  354. (any one can be NULL, in which case it won't be computed). */
  355. void S3L_rotationToDirections(
  356. S3L_Vec4 rotation,
  357. S3L_Unit length,
  358. S3L_Vec4 *forw,
  359. S3L_Vec4 *right,
  360. S3L_Vec4 *up);
  361. /** 4x4 matrix, used mostly for 3D transforms. The indexing is this:
  362. matrix[column][row]. */
  363. typedef S3L_Unit S3L_Mat4[4][4];
  364. #define S3L_logMat4(m)\
  365. printf("Mat4:\n %d %d %d %d\n %d %d %d %d\n %d %d %d %d\n %d %d %d %d\n"\
  366. ,(m)[0][0],(m)[1][0],(m)[2][0],(m)[3][0],\
  367. (m)[0][1],(m)[1][1],(m)[2][1],(m)[3][1],\
  368. (m)[0][2],(m)[1][2],(m)[2][2],(m)[3][2],\
  369. (m)[0][3],(m)[1][3],(m)[2][3],(m)[3][3])
  370. /** Initializes a 4x4 matrix to identity. */
  371. static inline void S3L_initMat4(S3L_Mat4 *m);
  372. void S3L_transposeMat4(S3L_Mat4 *m);
  373. void S3L_makeTranslationMat(
  374. S3L_Unit offsetX,
  375. S3L_Unit offsetY,
  376. S3L_Unit offsetZ,
  377. S3L_Mat4 *m);
  378. /** Makes a scaling matrix. DON'T FORGET: scale of 1.0 is set with
  379. S3L_FRACTIONS_PER_UNIT! */
  380. void S3L_makeScaleMatrix(
  381. S3L_Unit scaleX,
  382. S3L_Unit scaleY,
  383. S3L_Unit scaleZ,
  384. S3L_Mat4 *m);
  385. /** Makes a matrix for rotation in the ZXY order. */
  386. void S3L_makeRotationMatrixZXY(
  387. S3L_Unit byX,
  388. S3L_Unit byY,
  389. S3L_Unit byZ,
  390. S3L_Mat4 *m);
  391. void S3L_makeWorldMatrix(S3L_Transform3D worldTransform, S3L_Mat4 *m);
  392. void S3L_makeCameraMatrix(S3L_Transform3D cameraTransform, S3L_Mat4 *m);
  393. /** Multiplies a vector by a matrix with normalization by
  394. S3L_FRACTIONS_PER_UNIT. Result is stored in the input vector. */
  395. void S3L_vec4Xmat4(S3L_Vec4 *v, S3L_Mat4 *m);
  396. /** Same as S3L_vec4Xmat4 but faster, because this version doesn't compute the
  397. W component of the result, which is usually not needed. */
  398. void S3L_vec3Xmat4(S3L_Vec4 *v, S3L_Mat4 *m);
  399. /** Multiplies two matrices with normalization by S3L_FRACTIONS_PER_UNIT.
  400. Result is stored in the first matrix. The result represents a transformation
  401. that has the same effect as applying the transformation represented by m1 and
  402. then m2 (in that order). */
  403. void S3L_mat4Xmat4(S3L_Mat4 *m1, S3L_Mat4 *m2);
  404. typedef struct
  405. {
  406. S3L_Unit focalLength; ///< Defines the field of view (FOV).
  407. S3L_Transform3D transform;
  408. } S3L_Camera;
  409. void S3L_initCamera(S3L_Camera *camera);
  410. typedef struct
  411. {
  412. uint8_t backfaceCulling; /**< What backface culling to use. Possible
  413. values:
  414. - 0 none
  415. - 1 clock-wise
  416. - 2 counter clock-wise */
  417. int8_t visible; /**< Can be used to easily hide the model. */
  418. } S3L_DrawConfig;
  419. void S3L_initDrawConfig(S3L_DrawConfig *config);
  420. typedef struct
  421. {
  422. const S3L_Unit *vertices;
  423. S3L_Index vertexCount;
  424. const S3L_Index *triangles;
  425. S3L_Index triangleCount;
  426. S3L_Transform3D transform;
  427. S3L_Mat4 *customTransformMatrix; /**< This can be used to override the
  428. transform (if != 0) with a custom
  429. transform matrix, which is more
  430. general. */
  431. S3L_DrawConfig config;
  432. } S3L_Model3D; ///< Represents a 3D model.
  433. void S3L_initModel3D(
  434. const S3L_Unit *vertices,
  435. S3L_Unit vertexCount,
  436. const S3L_Index *triangles,
  437. S3L_Index triangleCount,
  438. S3L_Model3D *model);
  439. typedef struct
  440. {
  441. S3L_Model3D *models;
  442. S3L_Index modelCount;
  443. S3L_Camera camera;
  444. } S3L_Scene; ///< Represent the 3D scene to be rendered.
  445. void S3L_initScene(
  446. S3L_Model3D *models,
  447. S3L_Index modelCount,
  448. S3L_Scene *scene);
  449. typedef struct
  450. {
  451. S3L_ScreenCoord x; ///< Screen X coordinate.
  452. S3L_ScreenCoord y; ///< Screen Y coordinate.
  453. S3L_Unit barycentric[3]; /**< Barycentric coords correspond to the three
  454. vertices. These serve to locate the pixel on a
  455. triangle and interpolate values between it's
  456. three points. Each one goes from 0 to
  457. S3L_FRACTIONS_PER_UNIT (including), but due to
  458. rounding error may fall outside this range (you
  459. can use S3L_correctBarycentricCoords to fix this
  460. for the price of some performance). The sum of
  461. the three coordinates will always be exactly
  462. S3L_FRACTIONS_PER_UNIT. */
  463. S3L_Index modelIndex; ///< Model index within the scene.
  464. S3L_Index triangleIndex; ///< Triangle index within the model.
  465. uint32_t triangleID; /**< Unique ID of the triangle withing the whole
  466. scene. This can be used e.g. by a cache to
  467. quickly find out if a triangle has changed. */
  468. S3L_Unit depth; ///< Depth (only if depth is turned on).
  469. S3L_Unit previousZ; /**< Z-buffer value (not necessarily world depth in
  470. S3L_Units!) that was in the z-buffer on the
  471. pixels position before this pixel was
  472. rasterized. This can be used to set the value
  473. back, e.g. for transparency. */
  474. S3L_ScreenCoord triangleSize[2]; /**< Rasterized triangle width and height,
  475. can be used e.g. for MIP mapping. */
  476. } S3L_PixelInfo; /**< Used to pass the info about a rasterized pixel
  477. (fragment) to the user-defined drawing func. */
  478. static inline void S3L_initPixelInfo(S3L_PixelInfo *p);
  479. /** Corrects barycentric coordinates so that they exactly meet the defined
  480. conditions (each fall into <0,S3L_FRACTIONS_PER_UNIT>, sum =
  481. S3L_FRACTIONS_PER_UNIT). Note that doing this per-pixel can slow the program
  482. down significantly. */
  483. static inline void S3L_correctBarycentricCoords(S3L_Unit barycentric[3]);
  484. // general helper functions
  485. static inline S3L_Unit S3L_abs(S3L_Unit value);
  486. static inline S3L_Unit S3L_min(S3L_Unit v1, S3L_Unit v2);
  487. static inline S3L_Unit S3L_max(S3L_Unit v1, S3L_Unit v2);
  488. static inline S3L_Unit S3L_clamp(S3L_Unit v, S3L_Unit v1, S3L_Unit v2);
  489. static inline S3L_Unit S3L_wrap(S3L_Unit value, S3L_Unit mod);
  490. static inline S3L_Unit S3L_nonZero(S3L_Unit value);
  491. static inline S3L_Unit S3L_zeroClamp(S3L_Unit value);
  492. S3L_Unit S3L_sin(S3L_Unit x);
  493. S3L_Unit S3L_asin(S3L_Unit x);
  494. static inline S3L_Unit S3L_cos(S3L_Unit x);
  495. S3L_Unit S3L_vec3Length(S3L_Vec4 v);
  496. S3L_Unit S3L_sqrt(S3L_Unit value);
  497. /** Projects a single point from 3D space to the screen space (pixels), which
  498. can be useful e.g. for drawing sprites. The w component of input and result
  499. holds the point size. If this size is 0 in the result, the sprite is outside
  500. the view. */
  501. void project3DPointToScreen(
  502. S3L_Vec4 point,
  503. S3L_Camera camera,
  504. S3L_Vec4 *result);
  505. /** Computes a normalized normal of given triangle. */
  506. void S3L_triangleNormal(S3L_Vec4 t0, S3L_Vec4 t1, S3L_Vec4 t2,
  507. S3L_Vec4 *n);
  508. /** Helper function for retrieving per-vertex indexed values from an array,
  509. e.g. texturing (UV) coordinates. The 'indices' array contains three indices
  510. for each triangle, each index pointing into 'values' array, which contains
  511. the values, each one consisting of 'numComponents' components (e.g. 2 for
  512. UV coordinates). The three values are retrieved into 'v0', 'v1' and 'v2'
  513. vectors (into x, y, z and w, depending on 'numComponents'). This function is
  514. meant to be used per-triangle (typically from a cache), NOT per-pixel, as it
  515. is not as fast as possible! */
  516. void S3L_getIndexedTriangleValues(
  517. S3L_Index triangleIndex,
  518. const S3L_Index *indices,
  519. const S3L_Unit *values,
  520. uint8_t numComponents,
  521. S3L_Vec4 *v0,
  522. S3L_Vec4 *v1,
  523. S3L_Vec4 *v2);
  524. /** Computes a normalized normal for every vertex of given model (this is
  525. relatively slow and SHOUDN'T be done each frame). The dst array must have a
  526. sufficient size preallocated! The size is: number of model vertices * 3 *
  527. sizeof(S3L_Unit). Note that for advanced allowing sharp edges it is not
  528. sufficient to have per-vertex normals, but must be per-triangle. This
  529. function doesn't support this.
  530. The function computes a normal for each vertex by averaging normals of
  531. the triangles containing the vertex. The maximum number of these triangle
  532. normals that will be averaged is set with
  533. S3L_NORMAL_COMPUTE_MAXIMUM_AVERAGE. */
  534. void S3L_computeModelNormals(S3L_Model3D model, S3L_Unit *dst,
  535. int8_t transformNormals);
  536. /** Interpolated between two values, v1 and v2, in the same ratio as t is to
  537. tMax. Does NOT prevent zero division. */
  538. static inline S3L_Unit S3L_interpolate(
  539. S3L_Unit v1,
  540. S3L_Unit v2,
  541. S3L_Unit t,
  542. S3L_Unit tMax);
  543. /** Same as S3L_interpolate but with v1 == 0. Should be faster. */
  544. static inline S3L_Unit S3L_interpolateFrom0(
  545. S3L_Unit v2,
  546. S3L_Unit t,
  547. S3L_Unit tMax);
  548. /** Like S3L_interpolate, but uses a parameter that goes from 0 to
  549. S3L_FRACTIONS_PER_UNIT - 1, which can be faster. */
  550. static inline S3L_Unit S3L_interpolateByUnit(
  551. S3L_Unit v1,
  552. S3L_Unit v2,
  553. S3L_Unit t);
  554. /** Same as S3L_interpolateByUnit but with v1 == 0. Should be faster. */
  555. static inline S3L_Unit S3L_interpolateByUnitFrom0(
  556. S3L_Unit v2,
  557. S3L_Unit t);
  558. static inline S3L_Unit S3L_distanceManhattan(S3L_Vec4 a, S3L_Vec4 b);
  559. /** Returns a value interpolated between the three triangle vertices based on
  560. barycentric coordinates. */
  561. static inline S3L_Unit S3L_interpolateBarycentric(
  562. S3L_Unit value0,
  563. S3L_Unit value1,
  564. S3L_Unit value2,
  565. S3L_Unit barycentric[3]);
  566. static inline void S3L_mapProjectionPlaneToScreen(
  567. S3L_Vec4 point,
  568. S3L_ScreenCoord *screenX,
  569. S3L_ScreenCoord *screenY);
  570. /** Draws a triangle according to given config. The vertices are specified in
  571. Screen Space space (pixels). If perspective correction is enabled, each
  572. vertex has to have a depth (Z position in camera space) specified in the Z
  573. component. */
  574. void S3L_drawTriangle(
  575. S3L_Vec4 point0,
  576. S3L_Vec4 point1,
  577. S3L_Vec4 point2,
  578. S3L_Index modelIndex,
  579. S3L_Index triangleIndex);
  580. /** This should be called before rendering each frame. The function clears
  581. buffers and does potentially other things needed for the frame. */
  582. void S3L_newFrame(void);
  583. void S3L_zBufferClear(void);
  584. void S3L_stencilBufferClear(void);
  585. /** Writes a value (not necessarily depth! depends on the format of z-buffer)
  586. to z-buffer (if enabled). Does NOT check boundaries! */
  587. void S3L_zBufferWrite(S3L_ScreenCoord x, S3L_ScreenCoord y, S3L_Unit value);
  588. /** Reads a value (not necessarily depth! depends on the format of z-buffer)
  589. from z-buffer (if enabled). Does NOT check boundaries! */
  590. S3L_Unit S3L_zBufferRead(S3L_ScreenCoord x, S3L_ScreenCoord y);
  591. static inline void S3L_rotate2DPoint(S3L_Unit *x, S3L_Unit *y, S3L_Unit angle);
  592. /** Predefined vertices of a cube to simply insert in an array. These come with
  593. S3L_CUBE_TRIANGLES and S3L_CUBE_TEXCOORDS. */
  594. #define S3L_CUBE_VERTICES(m)\
  595. /* 0 front, bottom, right */\
  596. m/2, -m/2, -m/2,\
  597. /* 1 front, bottom, left */\
  598. -m/2, -m/2, -m/2,\
  599. /* 2 front, top, right */\
  600. m/2, m/2, -m/2,\
  601. /* 3 front, top, left */\
  602. -m/2, m/2, -m/2,\
  603. /* 4 back, bottom, right */\
  604. m/2, -m/2, m/2,\
  605. /* 5 back, bottom, left */\
  606. -m/2, -m/2, m/2,\
  607. /* 6 back, top, right */\
  608. m/2, m/2, m/2,\
  609. /* 7 back, top, left */\
  610. -m/2, m/2, m/2
  611. #define S3L_CUBE_VERTEX_COUNT 8
  612. /** Predefined triangle indices of a cube, to be used with S3L_CUBE_VERTICES
  613. and S3L_CUBE_TEXCOORDS. */
  614. #define S3L_CUBE_TRIANGLES\
  615. 3, 0, 2, /* front */\
  616. 1, 0, 3,\
  617. 0, 4, 2, /* right */\
  618. 2, 4, 6,\
  619. 4, 5, 6, /* back */\
  620. 7, 6, 5,\
  621. 3, 7, 1, /* left */\
  622. 1, 7, 5,\
  623. 6, 3, 2, /* top */\
  624. 7, 3, 6,\
  625. 1, 4, 0, /* bottom */\
  626. 5, 4, 1
  627. #define S3L_CUBE_TRIANGLE_COUNT 12
  628. /** Predefined texture coordinates of a cube, corresponding to triangles (NOT
  629. vertices), to be used with S3L_CUBE_VERTICES and S3L_CUBE_TRIANGLES. */
  630. #define S3L_CUBE_TEXCOORDS(m)\
  631. 0,0, m,m, m,0,\
  632. 0,m, m,m, 0,0,\
  633. m,m, m,0, 0,m,\
  634. 0,m, m,0, 0,0,\
  635. m,0, 0,0, m,m,\
  636. 0,m, m,m, 0,0,\
  637. 0,0, 0,m, m,0,\
  638. m,0, 0,m, m,m,\
  639. 0,0, m,m, m,0,\
  640. 0,m, m,m, 0,0,\
  641. m,0, 0,m, m,m,\
  642. 0,0, 0,m, m,0
  643. //=============================================================================
  644. // privates
  645. #define S3L_UNUSED(what) (void)(what) ///< helper macro for unused vars
  646. #define S3L_HALF_RESOLUTION_X (S3L_RESOLUTION_X >> 1)
  647. #define S3L_HALF_RESOLUTION_Y (S3L_RESOLUTION_Y >> 1)
  648. #define S3L_PROJECTION_PLANE_HEIGHT\
  649. ((S3L_RESOLUTION_Y * S3L_FRACTIONS_PER_UNIT * 2) / S3L_RESOLUTION_X)
  650. #if S3L_Z_BUFFER == 1
  651. #define S3L_MAX_DEPTH 2147483647
  652. S3L_Unit S3L_zBuffer[S3L_MAX_PIXELS];
  653. #define S3L_zBufferFormat(depth) (depth)
  654. #elif S3L_Z_BUFFER == 2
  655. #define S3L_MAX_DEPTH 255
  656. uint8_t S3L_zBuffer[S3L_MAX_PIXELS];
  657. #define S3L_zBufferFormat(depth)\
  658. S3L_min(255,(depth) >> S3L_REDUCED_Z_BUFFER_GRANULARITY)
  659. #endif
  660. #if S3L_Z_BUFFER
  661. static inline int8_t S3L_zTest(
  662. S3L_ScreenCoord x,
  663. S3L_ScreenCoord y,
  664. S3L_Unit depth)
  665. {
  666. uint32_t index = y * S3L_RESOLUTION_X + x;
  667. depth = S3L_zBufferFormat(depth);
  668. #if S3L_Z_BUFFER == 2
  669. #define cmp <= /* For reduced z-buffer we need equality test, because
  670. otherwise pixels at the maximum depth (255) would never be
  671. drawn over the background (which also has the depth of
  672. 255). */
  673. #else
  674. #define cmp < /* For normal z-buffer we leave out equality test to not waste
  675. time by drawing over already drawn pixls. */
  676. #endif
  677. if (depth cmp S3L_zBuffer[index])
  678. {
  679. S3L_zBuffer[index] = depth;
  680. return 1;
  681. }
  682. #undef cmp
  683. return 0;
  684. }
  685. #endif
  686. S3L_Unit S3L_zBufferRead(S3L_ScreenCoord x, S3L_ScreenCoord y)
  687. {
  688. #if S3L_Z_BUFFER
  689. return S3L_zBuffer[y * S3L_RESOLUTION_X + x];
  690. #else
  691. S3L_UNUSED(x);
  692. S3L_UNUSED(y);
  693. return 0;
  694. #endif
  695. }
  696. void S3L_zBufferWrite(S3L_ScreenCoord x, S3L_ScreenCoord y, S3L_Unit value)
  697. {
  698. #if S3L_Z_BUFFER
  699. S3L_zBuffer[y * S3L_RESOLUTION_X + x] = value;
  700. #else
  701. S3L_UNUSED(x);
  702. S3L_UNUSED(y);
  703. S3L_UNUSED(value);
  704. #endif
  705. }
  706. #if S3L_STENCIL_BUFFER
  707. #define S3L_STENCIL_BUFFER_SIZE\
  708. ((S3L_RESOLUTION_X * S3L_RESOLUTION_Y - 1) / 8 + 1)
  709. uint8_t S3L_stencilBuffer[S3L_STENCIL_BUFFER_SIZE];
  710. static inline int8_t S3L_stencilTest(
  711. S3L_ScreenCoord x,
  712. S3L_ScreenCoord y)
  713. {
  714. uint32_t index = y * S3L_RESOLUTION_X + x;
  715. uint32_t bit = (index & 0x00000007);
  716. index = index >> 3;
  717. uint8_t val = S3L_stencilBuffer[index];
  718. if ((val >> bit) & 0x1)
  719. return 0;
  720. S3L_stencilBuffer[index] = val | (0x1 << bit);
  721. return 1;
  722. }
  723. #endif
  724. #define S3L_COMPUTE_LERP_DEPTH\
  725. (S3L_COMPUTE_DEPTH && (S3L_PERSPECTIVE_CORRECTION == 0))
  726. #define S3L_SIN_TABLE_LENGTH 128
  727. static const S3L_Unit S3L_sinTable[S3L_SIN_TABLE_LENGTH] =
  728. {
  729. /* 511 was chosen here as a highest number that doesn't overflow during
  730. compilation for S3L_FRACTIONS_PER_UNIT == 1024 */
  731. (0*S3L_FRACTIONS_PER_UNIT)/511, (6*S3L_FRACTIONS_PER_UNIT)/511,
  732. (12*S3L_FRACTIONS_PER_UNIT)/511, (18*S3L_FRACTIONS_PER_UNIT)/511,
  733. (25*S3L_FRACTIONS_PER_UNIT)/511, (31*S3L_FRACTIONS_PER_UNIT)/511,
  734. (37*S3L_FRACTIONS_PER_UNIT)/511, (43*S3L_FRACTIONS_PER_UNIT)/511,
  735. (50*S3L_FRACTIONS_PER_UNIT)/511, (56*S3L_FRACTIONS_PER_UNIT)/511,
  736. (62*S3L_FRACTIONS_PER_UNIT)/511, (68*S3L_FRACTIONS_PER_UNIT)/511,
  737. (74*S3L_FRACTIONS_PER_UNIT)/511, (81*S3L_FRACTIONS_PER_UNIT)/511,
  738. (87*S3L_FRACTIONS_PER_UNIT)/511, (93*S3L_FRACTIONS_PER_UNIT)/511,
  739. (99*S3L_FRACTIONS_PER_UNIT)/511, (105*S3L_FRACTIONS_PER_UNIT)/511,
  740. (111*S3L_FRACTIONS_PER_UNIT)/511, (118*S3L_FRACTIONS_PER_UNIT)/511,
  741. (124*S3L_FRACTIONS_PER_UNIT)/511, (130*S3L_FRACTIONS_PER_UNIT)/511,
  742. (136*S3L_FRACTIONS_PER_UNIT)/511, (142*S3L_FRACTIONS_PER_UNIT)/511,
  743. (148*S3L_FRACTIONS_PER_UNIT)/511, (154*S3L_FRACTIONS_PER_UNIT)/511,
  744. (160*S3L_FRACTIONS_PER_UNIT)/511, (166*S3L_FRACTIONS_PER_UNIT)/511,
  745. (172*S3L_FRACTIONS_PER_UNIT)/511, (178*S3L_FRACTIONS_PER_UNIT)/511,
  746. (183*S3L_FRACTIONS_PER_UNIT)/511, (189*S3L_FRACTIONS_PER_UNIT)/511,
  747. (195*S3L_FRACTIONS_PER_UNIT)/511, (201*S3L_FRACTIONS_PER_UNIT)/511,
  748. (207*S3L_FRACTIONS_PER_UNIT)/511, (212*S3L_FRACTIONS_PER_UNIT)/511,
  749. (218*S3L_FRACTIONS_PER_UNIT)/511, (224*S3L_FRACTIONS_PER_UNIT)/511,
  750. (229*S3L_FRACTIONS_PER_UNIT)/511, (235*S3L_FRACTIONS_PER_UNIT)/511,
  751. (240*S3L_FRACTIONS_PER_UNIT)/511, (246*S3L_FRACTIONS_PER_UNIT)/511,
  752. (251*S3L_FRACTIONS_PER_UNIT)/511, (257*S3L_FRACTIONS_PER_UNIT)/511,
  753. (262*S3L_FRACTIONS_PER_UNIT)/511, (268*S3L_FRACTIONS_PER_UNIT)/511,
  754. (273*S3L_FRACTIONS_PER_UNIT)/511, (278*S3L_FRACTIONS_PER_UNIT)/511,
  755. (283*S3L_FRACTIONS_PER_UNIT)/511, (289*S3L_FRACTIONS_PER_UNIT)/511,
  756. (294*S3L_FRACTIONS_PER_UNIT)/511, (299*S3L_FRACTIONS_PER_UNIT)/511,
  757. (304*S3L_FRACTIONS_PER_UNIT)/511, (309*S3L_FRACTIONS_PER_UNIT)/511,
  758. (314*S3L_FRACTIONS_PER_UNIT)/511, (319*S3L_FRACTIONS_PER_UNIT)/511,
  759. (324*S3L_FRACTIONS_PER_UNIT)/511, (328*S3L_FRACTIONS_PER_UNIT)/511,
  760. (333*S3L_FRACTIONS_PER_UNIT)/511, (338*S3L_FRACTIONS_PER_UNIT)/511,
  761. (343*S3L_FRACTIONS_PER_UNIT)/511, (347*S3L_FRACTIONS_PER_UNIT)/511,
  762. (352*S3L_FRACTIONS_PER_UNIT)/511, (356*S3L_FRACTIONS_PER_UNIT)/511,
  763. (361*S3L_FRACTIONS_PER_UNIT)/511, (365*S3L_FRACTIONS_PER_UNIT)/511,
  764. (370*S3L_FRACTIONS_PER_UNIT)/511, (374*S3L_FRACTIONS_PER_UNIT)/511,
  765. (378*S3L_FRACTIONS_PER_UNIT)/511, (382*S3L_FRACTIONS_PER_UNIT)/511,
  766. (386*S3L_FRACTIONS_PER_UNIT)/511, (391*S3L_FRACTIONS_PER_UNIT)/511,
  767. (395*S3L_FRACTIONS_PER_UNIT)/511, (398*S3L_FRACTIONS_PER_UNIT)/511,
  768. (402*S3L_FRACTIONS_PER_UNIT)/511, (406*S3L_FRACTIONS_PER_UNIT)/511,
  769. (410*S3L_FRACTIONS_PER_UNIT)/511, (414*S3L_FRACTIONS_PER_UNIT)/511,
  770. (417*S3L_FRACTIONS_PER_UNIT)/511, (421*S3L_FRACTIONS_PER_UNIT)/511,
  771. (424*S3L_FRACTIONS_PER_UNIT)/511, (428*S3L_FRACTIONS_PER_UNIT)/511,
  772. (431*S3L_FRACTIONS_PER_UNIT)/511, (435*S3L_FRACTIONS_PER_UNIT)/511,
  773. (438*S3L_FRACTIONS_PER_UNIT)/511, (441*S3L_FRACTIONS_PER_UNIT)/511,
  774. (444*S3L_FRACTIONS_PER_UNIT)/511, (447*S3L_FRACTIONS_PER_UNIT)/511,
  775. (450*S3L_FRACTIONS_PER_UNIT)/511, (453*S3L_FRACTIONS_PER_UNIT)/511,
  776. (456*S3L_FRACTIONS_PER_UNIT)/511, (459*S3L_FRACTIONS_PER_UNIT)/511,
  777. (461*S3L_FRACTIONS_PER_UNIT)/511, (464*S3L_FRACTIONS_PER_UNIT)/511,
  778. (467*S3L_FRACTIONS_PER_UNIT)/511, (469*S3L_FRACTIONS_PER_UNIT)/511,
  779. (472*S3L_FRACTIONS_PER_UNIT)/511, (474*S3L_FRACTIONS_PER_UNIT)/511,
  780. (476*S3L_FRACTIONS_PER_UNIT)/511, (478*S3L_FRACTIONS_PER_UNIT)/511,
  781. (481*S3L_FRACTIONS_PER_UNIT)/511, (483*S3L_FRACTIONS_PER_UNIT)/511,
  782. (485*S3L_FRACTIONS_PER_UNIT)/511, (487*S3L_FRACTIONS_PER_UNIT)/511,
  783. (488*S3L_FRACTIONS_PER_UNIT)/511, (490*S3L_FRACTIONS_PER_UNIT)/511,
  784. (492*S3L_FRACTIONS_PER_UNIT)/511, (494*S3L_FRACTIONS_PER_UNIT)/511,
  785. (495*S3L_FRACTIONS_PER_UNIT)/511, (497*S3L_FRACTIONS_PER_UNIT)/511,
  786. (498*S3L_FRACTIONS_PER_UNIT)/511, (499*S3L_FRACTIONS_PER_UNIT)/511,
  787. (501*S3L_FRACTIONS_PER_UNIT)/511, (502*S3L_FRACTIONS_PER_UNIT)/511,
  788. (503*S3L_FRACTIONS_PER_UNIT)/511, (504*S3L_FRACTIONS_PER_UNIT)/511,
  789. (505*S3L_FRACTIONS_PER_UNIT)/511, (506*S3L_FRACTIONS_PER_UNIT)/511,
  790. (507*S3L_FRACTIONS_PER_UNIT)/511, (507*S3L_FRACTIONS_PER_UNIT)/511,
  791. (508*S3L_FRACTIONS_PER_UNIT)/511, (509*S3L_FRACTIONS_PER_UNIT)/511,
  792. (509*S3L_FRACTIONS_PER_UNIT)/511, (510*S3L_FRACTIONS_PER_UNIT)/511,
  793. (510*S3L_FRACTIONS_PER_UNIT)/511, (510*S3L_FRACTIONS_PER_UNIT)/511,
  794. (510*S3L_FRACTIONS_PER_UNIT)/511, (510*S3L_FRACTIONS_PER_UNIT)/511
  795. };
  796. #define S3L_SIN_TABLE_UNIT_STEP\
  797. (S3L_FRACTIONS_PER_UNIT / (S3L_SIN_TABLE_LENGTH * 4))
  798. void S3L_initVec4(S3L_Vec4 *v)
  799. {
  800. v->x = 0; v->y = 0; v->z = 0; v->w = S3L_FRACTIONS_PER_UNIT;
  801. }
  802. void S3L_setVec4(S3L_Vec4 *v, S3L_Unit x, S3L_Unit y, S3L_Unit z, S3L_Unit w)
  803. {
  804. v->x = x;
  805. v->y = y;
  806. v->z = z;
  807. v->w = w;
  808. }
  809. void S3L_vec3Add(S3L_Vec4 *result, S3L_Vec4 added)
  810. {
  811. result->x += added.x;
  812. result->y += added.y;
  813. result->z += added.z;
  814. }
  815. void S3L_vec3Sub(S3L_Vec4 *result, S3L_Vec4 substracted)
  816. {
  817. result->x -= substracted.x;
  818. result->y -= substracted.y;
  819. result->z -= substracted.z;
  820. }
  821. void S3L_initMat4(S3L_Mat4 *m)
  822. {
  823. #define M(x,y) (*m)[x][y]
  824. #define S S3L_FRACTIONS_PER_UNIT
  825. M(0,0) = S; M(1,0) = 0; M(2,0) = 0; M(3,0) = 0;
  826. M(0,1) = 0; M(1,1) = S; M(2,1) = 0; M(3,1) = 0;
  827. M(0,2) = 0; M(1,2) = 0; M(2,2) = S; M(3,2) = 0;
  828. M(0,3) = 0; M(1,3) = 0; M(2,3) = 0; M(3,3) = S;
  829. #undef M
  830. #undef S
  831. }
  832. S3L_Unit S3L_dotProductVec3(S3L_Vec4 a, S3L_Vec4 b)
  833. {
  834. return (a.x * b.x + a.y * b.y + a.z * b.z) / S3L_FRACTIONS_PER_UNIT;
  835. }
  836. void S3L_reflect(S3L_Vec4 toLight, S3L_Vec4 normal, S3L_Vec4 *result)
  837. {
  838. S3L_Unit d = 2 * S3L_dotProductVec3(toLight,normal);
  839. result->x = (normal.x * d) / S3L_FRACTIONS_PER_UNIT - toLight.x;
  840. result->y = (normal.y * d) / S3L_FRACTIONS_PER_UNIT - toLight.y;
  841. result->z = (normal.z * d) / S3L_FRACTIONS_PER_UNIT - toLight.z;
  842. }
  843. void S3L_crossProduct(S3L_Vec4 a, S3L_Vec4 b, S3L_Vec4 *result)
  844. {
  845. result->x = a.y * b.z - a.z * b.y;
  846. result->y = a.z * b.x - a.x * b.z;
  847. result->z = a.x * b.y - a.y * b.x;
  848. }
  849. void S3L_triangleNormal(S3L_Vec4 t0, S3L_Vec4 t1, S3L_Vec4 t2, S3L_Vec4 *n)
  850. {
  851. #define ANTI_OVERFLOW 32
  852. t1.x = (t1.x - t0.x) / ANTI_OVERFLOW;
  853. t1.y = (t1.y - t0.y) / ANTI_OVERFLOW;
  854. t1.z = (t1.z - t0.z) / ANTI_OVERFLOW;
  855. t2.x = (t2.x - t0.x) / ANTI_OVERFLOW;
  856. t2.y = (t2.y - t0.y) / ANTI_OVERFLOW;
  857. t2.z = (t2.z - t0.z) / ANTI_OVERFLOW;
  858. #undef ANTI_OVERFLOW
  859. S3L_crossProduct(t1,t2,n);
  860. S3L_normalizeVec3(n);
  861. }
  862. void S3L_getIndexedTriangleValues(
  863. S3L_Index triangleIndex,
  864. const S3L_Index *indices,
  865. const S3L_Unit *values,
  866. uint8_t numComponents,
  867. S3L_Vec4 *v0,
  868. S3L_Vec4 *v1,
  869. S3L_Vec4 *v2)
  870. {
  871. uint32_t i0, i1;
  872. S3L_Unit *value;
  873. i0 = triangleIndex * 3;
  874. i1 = indices[i0] * numComponents;
  875. value = (S3L_Unit *) v0;
  876. if (numComponents > 4)
  877. numComponents = 4;
  878. for (uint8_t j = 0; j < numComponents; ++j)
  879. {
  880. *value = values[i1];
  881. i1++;
  882. value++;
  883. }
  884. i0++;
  885. i1 = indices[i0] * numComponents;
  886. value = (S3L_Unit *) v1;
  887. for (uint8_t j = 0; j < numComponents; ++j)
  888. {
  889. *value = values[i1];
  890. i1++;
  891. value++;
  892. }
  893. i0++;
  894. i1 = indices[i0] * numComponents;
  895. value = (S3L_Unit *) v2;
  896. for (uint8_t j = 0; j < numComponents; ++j)
  897. {
  898. *value = values[i1];
  899. i1++;
  900. value++;
  901. }
  902. }
  903. void S3L_computeModelNormals(S3L_Model3D model, S3L_Unit *dst,
  904. int8_t transformNormals)
  905. {
  906. S3L_Index vPos = 0;
  907. S3L_Vec4 n;
  908. n.w = 0;
  909. S3L_Vec4 ns[S3L_NORMAL_COMPUTE_MAXIMUM_AVERAGE];
  910. S3L_Index normalCount;
  911. for (uint32_t i = 0; i < model.vertexCount; ++i)
  912. {
  913. normalCount = 0;
  914. for (uint32_t j = 0; j < model.triangleCount * 3; j += 3)
  915. {
  916. if (
  917. (model.triangles[j] == i) ||
  918. (model.triangles[j + 1] == i) ||
  919. (model.triangles[j + 2] == i))
  920. {
  921. S3L_Vec4 t0, t1, t2;
  922. uint32_t vIndex;
  923. #define getVertex(n)\
  924. vIndex = model.triangles[j + n] * 3;\
  925. t##n.x = model.vertices[vIndex];\
  926. vIndex++;\
  927. t##n.y = model.vertices[vIndex];\
  928. vIndex++;\
  929. t##n.z = model.vertices[vIndex];
  930. getVertex(0)
  931. getVertex(1)
  932. getVertex(2)
  933. #undef getVertex
  934. S3L_triangleNormal(t0,t1,t2,&(ns[normalCount]));
  935. normalCount++;
  936. if (normalCount >= S3L_NORMAL_COMPUTE_MAXIMUM_AVERAGE)
  937. break;
  938. }
  939. }
  940. n.x = S3L_FRACTIONS_PER_UNIT;
  941. n.y = 0;
  942. n.z = 0;
  943. if (normalCount != 0)
  944. {
  945. // compute average
  946. n.x = 0;
  947. for (uint8_t i = 0; i < normalCount; ++i)
  948. {
  949. n.x += ns[i].x;
  950. n.y += ns[i].y;
  951. n.z += ns[i].z;
  952. }
  953. n.x /= normalCount;
  954. n.y /= normalCount;
  955. n.z /= normalCount;
  956. S3L_normalizeVec3(&n);
  957. }
  958. dst[vPos] = n.x;
  959. vPos++;
  960. dst[vPos] = n.y;
  961. vPos++;
  962. dst[vPos] = n.z;
  963. vPos++;
  964. }
  965. S3L_Mat4 m;
  966. S3L_makeWorldMatrix(model.transform,&m);
  967. if (transformNormals)
  968. for (S3L_Index i = 0; i < model.vertexCount * 3; i += 3)
  969. {
  970. n.x = dst[i];
  971. n.y = dst[i + 1];
  972. n.z = dst[i + 2];
  973. S3L_vec4Xmat4(&n,&m);
  974. dst[i] = n.x;
  975. dst[i + 1] = n.y;
  976. dst[i + 2] = n.z;
  977. }
  978. }
  979. void S3L_vec4Xmat4(S3L_Vec4 *v, S3L_Mat4 *m)
  980. {
  981. S3L_Vec4 vBackup;
  982. vBackup.x = v->x;
  983. vBackup.y = v->y;
  984. vBackup.z = v->z;
  985. vBackup.w = v->w;
  986. #define dotCol(col)\
  987. ((vBackup.x * (*m)[col][0]) +\
  988. (vBackup.y * (*m)[col][1]) +\
  989. (vBackup.z * (*m)[col][2]) +\
  990. (vBackup.w * (*m)[col][3])) / S3L_FRACTIONS_PER_UNIT
  991. v->x = dotCol(0);
  992. v->y = dotCol(1);
  993. v->z = dotCol(2);
  994. v->w = dotCol(3);
  995. }
  996. void S3L_vec3Xmat4(S3L_Vec4 *v, S3L_Mat4 *m)
  997. {
  998. S3L_Vec4 vBackup;
  999. #undef dotCol
  1000. #define dotCol(col)\
  1001. (vBackup.x * (*m)[col][0]) / S3L_FRACTIONS_PER_UNIT +\
  1002. (vBackup.y * (*m)[col][1]) / S3L_FRACTIONS_PER_UNIT +\
  1003. (vBackup.z * (*m)[col][2]) / S3L_FRACTIONS_PER_UNIT +\
  1004. (*m)[col][3]
  1005. vBackup.x = v->x;
  1006. vBackup.y = v->y;
  1007. vBackup.z = v->z;
  1008. vBackup.w = v->w;
  1009. v->x = dotCol(0);
  1010. v->y = dotCol(1);
  1011. v->z = dotCol(2);
  1012. v->w = S3L_FRACTIONS_PER_UNIT;
  1013. }
  1014. #undef dotCol
  1015. S3L_Unit S3L_abs(S3L_Unit value)
  1016. {
  1017. return value * (((value >= 0) << 1) - 1);
  1018. }
  1019. S3L_Unit S3L_min(S3L_Unit v1, S3L_Unit v2)
  1020. {
  1021. return v1 >= v2 ? v2 : v1;
  1022. }
  1023. S3L_Unit S3L_max(S3L_Unit v1, S3L_Unit v2)
  1024. {
  1025. return v1 >= v2 ? v1 : v2;
  1026. }
  1027. S3L_Unit S3L_clamp(S3L_Unit v, S3L_Unit v1, S3L_Unit v2)
  1028. {
  1029. return v >= v1 ? (v <= v2 ? v : v2) : v1;
  1030. }
  1031. S3L_Unit S3L_zeroClamp(S3L_Unit value)
  1032. {
  1033. return (value * (value >= 0));
  1034. }
  1035. S3L_Unit S3L_wrap(S3L_Unit value, S3L_Unit mod)
  1036. {
  1037. return value >= 0 ? (value % mod) : (mod + (value % mod) - 1);
  1038. }
  1039. S3L_Unit S3L_nonZero(S3L_Unit value)
  1040. {
  1041. return (value + (value == 0));
  1042. }
  1043. S3L_Unit S3L_interpolate(S3L_Unit v1, S3L_Unit v2, S3L_Unit t, S3L_Unit tMax)
  1044. {
  1045. return v1 + ((v2 - v1) * t) / tMax;
  1046. }
  1047. S3L_Unit S3L_interpolateByUnit(S3L_Unit v1, S3L_Unit v2, S3L_Unit t)
  1048. {
  1049. return v1 + ((v2 - v1) * t) / S3L_FRACTIONS_PER_UNIT;
  1050. }
  1051. S3L_Unit S3L_interpolateByUnitFrom0(S3L_Unit v2, S3L_Unit t)
  1052. {
  1053. return (v2 * t) / S3L_FRACTIONS_PER_UNIT;
  1054. }
  1055. S3L_Unit S3L_interpolateFrom0(S3L_Unit v2, S3L_Unit t, S3L_Unit tMax)
  1056. {
  1057. return (v2 * t) / tMax;
  1058. }
  1059. S3L_Unit S3L_distanceManhattan(S3L_Vec4 a, S3L_Vec4 b)
  1060. {
  1061. return
  1062. S3L_abs(a.x - b.x) +
  1063. S3L_abs(a.y - b.y) +
  1064. S3L_abs(a.z - b.z);
  1065. }
  1066. void S3L_mat4Xmat4(S3L_Mat4 *m1, S3L_Mat4 *m2)
  1067. {
  1068. S3L_Mat4 mat1;
  1069. for (uint16_t row = 0; row < 4; ++row)
  1070. for (uint16_t col = 0; col < 4; ++col)
  1071. mat1[col][row] = (*m1)[col][row];
  1072. for (uint16_t row = 0; row < 4; ++row)
  1073. for (uint16_t col = 0; col < 4; ++col)
  1074. {
  1075. (*m1)[col][row] = 0;
  1076. for (uint16_t i = 0; i < 4; ++i)
  1077. (*m1)[col][row] +=
  1078. (mat1[i][row] * (*m2)[col][i]) / S3L_FRACTIONS_PER_UNIT;
  1079. }
  1080. }
  1081. S3L_Unit S3L_sin(S3L_Unit x)
  1082. {
  1083. x = S3L_wrap(x / S3L_SIN_TABLE_UNIT_STEP,S3L_SIN_TABLE_LENGTH * 4);
  1084. int8_t positive = 1;
  1085. if (x < S3L_SIN_TABLE_LENGTH)
  1086. {
  1087. }
  1088. else if (x < S3L_SIN_TABLE_LENGTH * 2)
  1089. {
  1090. x = S3L_SIN_TABLE_LENGTH * 2 - x - 1;
  1091. }
  1092. else if (x < S3L_SIN_TABLE_LENGTH * 3)
  1093. {
  1094. x = x - S3L_SIN_TABLE_LENGTH * 2;
  1095. positive = 0;
  1096. }
  1097. else
  1098. {
  1099. x = S3L_SIN_TABLE_LENGTH - (x - S3L_SIN_TABLE_LENGTH * 3) - 1;
  1100. positive = 0;
  1101. }
  1102. return positive ? S3L_sinTable[x] : -1 * S3L_sinTable[x];
  1103. }
  1104. S3L_Unit S3L_asin(S3L_Unit x)
  1105. {
  1106. x = S3L_clamp(x,-S3L_FRACTIONS_PER_UNIT,S3L_FRACTIONS_PER_UNIT);
  1107. int8_t sign = 1;
  1108. if (x < 0)
  1109. {
  1110. sign = -1;
  1111. x *= -1;
  1112. }
  1113. int16_t low = 0;
  1114. int16_t high = S3L_SIN_TABLE_LENGTH -1;
  1115. int16_t middle;
  1116. while (low <= high) // binary search
  1117. {
  1118. middle = (low + high) / 2;
  1119. S3L_Unit v = S3L_sinTable[middle];
  1120. if (v > x)
  1121. high = middle - 1;
  1122. else if (v < x)
  1123. low = middle + 1;
  1124. else
  1125. break;
  1126. }
  1127. middle *= S3L_SIN_TABLE_UNIT_STEP;
  1128. return sign * middle;
  1129. }
  1130. S3L_Unit S3L_cos(S3L_Unit x)
  1131. {
  1132. return S3L_sin(x + S3L_FRACTIONS_PER_UNIT / 4);
  1133. }
  1134. void S3L_correctBarycentricCoords(S3L_Unit barycentric[3])
  1135. {
  1136. barycentric[0] = S3L_clamp(barycentric[0],0,S3L_FRACTIONS_PER_UNIT);
  1137. barycentric[1] = S3L_clamp(barycentric[1],0,S3L_FRACTIONS_PER_UNIT);
  1138. S3L_Unit d = S3L_FRACTIONS_PER_UNIT - barycentric[0] - barycentric[1];
  1139. if (d < 0)
  1140. {
  1141. barycentric[0] += d;
  1142. barycentric[2] = 0;
  1143. }
  1144. else
  1145. barycentric[2] = d;
  1146. }
  1147. void S3L_makeTranslationMat(
  1148. S3L_Unit offsetX,
  1149. S3L_Unit offsetY,
  1150. S3L_Unit offsetZ,
  1151. S3L_Mat4 *m)
  1152. {
  1153. #define M(x,y) (*m)[x][y]
  1154. #define S S3L_FRACTIONS_PER_UNIT
  1155. M(0,0) = S; M(1,0) = 0; M(2,0) = 0; M(3,0) = 0;
  1156. M(0,1) = 0; M(1,1) = S; M(2,1) = 0; M(3,1) = 0;
  1157. M(0,2) = 0; M(1,2) = 0; M(2,2) = S; M(3,2) = 0;
  1158. M(0,3) = offsetX; M(1,3) = offsetY; M(2,3) = offsetZ; M(3,3) = S;
  1159. #undef M
  1160. #undef S
  1161. }
  1162. void S3L_makeScaleMatrix(
  1163. S3L_Unit scaleX,
  1164. S3L_Unit scaleY,
  1165. S3L_Unit scaleZ,
  1166. S3L_Mat4 *m)
  1167. {
  1168. #define M(x,y) (*m)[x][y]
  1169. M(0,0) = scaleX; M(1,0) = 0; M(2,0) = 0; M(3,0) = 0;
  1170. M(0,1) = 0; M(1,1) = scaleY; M(2,1) = 0; M(3,1) = 0;
  1171. M(0,2) = 0; M(1,2) = 0; M(2,2) = scaleZ; M(3,2) = 0;
  1172. M(0,3) = 0; M(1,3) = 0; M(2,3) = 0; M(3,3) = S3L_FRACTIONS_PER_UNIT;
  1173. #undef M
  1174. }
  1175. void S3L_makeRotationMatrixZXY(
  1176. S3L_Unit byX,
  1177. S3L_Unit byY,
  1178. S3L_Unit byZ,
  1179. S3L_Mat4 *m)
  1180. {
  1181. byX *= -1;
  1182. byY *= -1;
  1183. byZ *= -1;
  1184. S3L_Unit sx = S3L_sin(byX);
  1185. S3L_Unit sy = S3L_sin(byY);
  1186. S3L_Unit sz = S3L_sin(byZ);
  1187. S3L_Unit cx = S3L_cos(byX);
  1188. S3L_Unit cy = S3L_cos(byY);
  1189. S3L_Unit cz = S3L_cos(byZ);
  1190. #define M(x,y) (*m)[x][y]
  1191. #define S S3L_FRACTIONS_PER_UNIT
  1192. M(0,0) = (cy * cz) / S + (sy * sx * sz) / (S * S);
  1193. M(1,0) = (cx * sz) / S;
  1194. M(2,0) = (cy * sx * sz) / (S * S) - (cz * sy) / S;
  1195. M(3,0) = 0;
  1196. M(0,1) = (cz * sy * sx) / (S * S) - (cy * sz) / S;
  1197. M(1,1) = (cx * cz) / S;
  1198. M(2,1) = (cy * cz * sx) / (S * S) + (sy * sz) / S;
  1199. M(3,1) = 0;
  1200. M(0,2) = (cx * sy) / S;
  1201. M(1,2) = -1 * sx;
  1202. M(2,2) = (cy * cx) / S;
  1203. M(3,2) = 0;
  1204. M(0,3) = 0;
  1205. M(1,3) = 0;
  1206. M(2,3) = 0;
  1207. M(3,3) = S3L_FRACTIONS_PER_UNIT;
  1208. #undef M
  1209. #undef S
  1210. }
  1211. S3L_Unit S3L_sqrt(S3L_Unit value)
  1212. {
  1213. int8_t sign = 1;
  1214. if (value < 0)
  1215. {
  1216. sign = -1;
  1217. value *= -1;
  1218. }
  1219. uint32_t result = 0;
  1220. uint32_t a = value;
  1221. uint32_t b = 1u << 30;
  1222. while (b > a)
  1223. b >>= 2;
  1224. while (b != 0)
  1225. {
  1226. if (a >= result + b)
  1227. {
  1228. a -= result + b;
  1229. result = result + 2 * b;
  1230. }
  1231. b >>= 2;
  1232. result >>= 1;
  1233. }
  1234. return result * sign;
  1235. }
  1236. S3L_Unit S3L_vec3Length(S3L_Vec4 v)
  1237. {
  1238. return S3L_sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
  1239. }
  1240. S3L_Unit S3L_vec2Length(S3L_Vec4 v)
  1241. {
  1242. return S3L_sqrt(v.x * v.x + v.y * v.y);
  1243. }
  1244. void S3L_normalizeVec3(S3L_Vec4 *v)
  1245. {
  1246. #define SCALE 16
  1247. #define BOTTOM_LIMIT 16
  1248. #define UPPER_LIMIT 900
  1249. /* Here we try to decide if the vector is too small and would cause
  1250. inaccurate result due to very its inaccurate length. If so, we scale
  1251. it up. We can't scale up everything as big vectors overflow in length
  1252. calculations. */
  1253. if (
  1254. S3L_abs(v->x) <= BOTTOM_LIMIT &&
  1255. S3L_abs(v->y) <= BOTTOM_LIMIT &&
  1256. S3L_abs(v->z) <= BOTTOM_LIMIT)
  1257. {
  1258. v->x *= SCALE;
  1259. v->y *= SCALE;
  1260. v->z *= SCALE;
  1261. }
  1262. else if (
  1263. S3L_abs(v->x) > UPPER_LIMIT ||
  1264. S3L_abs(v->y) > UPPER_LIMIT ||
  1265. S3L_abs(v->z) > UPPER_LIMIT)
  1266. {
  1267. v->x /= SCALE;
  1268. v->y /= SCALE;
  1269. v->z /= SCALE;
  1270. }
  1271. #undef SCALE
  1272. #undef BOTTOM_LIMIT
  1273. #undef UPPER_LIMIT
  1274. S3L_Unit l = S3L_vec3Length(*v);
  1275. if (l == 0)
  1276. return;
  1277. v->x = (v->x * S3L_FRACTIONS_PER_UNIT) / l;
  1278. v->y = (v->y * S3L_FRACTIONS_PER_UNIT) / l;
  1279. v->z = (v->z * S3L_FRACTIONS_PER_UNIT) / l;
  1280. }
  1281. void S3L_normalizeVec3Fast(S3L_Vec4 *v)
  1282. {
  1283. S3L_Unit l = S3L_vec3Length(*v);
  1284. if (l == 0)
  1285. return;
  1286. v->x = (v->x * S3L_FRACTIONS_PER_UNIT) / l;
  1287. v->y = (v->y * S3L_FRACTIONS_PER_UNIT) / l;
  1288. v->z = (v->z * S3L_FRACTIONS_PER_UNIT) / l;
  1289. }
  1290. void S3L_initTransform3D(S3L_Transform3D *t)
  1291. {
  1292. S3L_initVec4(&(t->translation));
  1293. S3L_initVec4(&(t->rotation));
  1294. t->scale.x = S3L_FRACTIONS_PER_UNIT;
  1295. t->scale.y = S3L_FRACTIONS_PER_UNIT;
  1296. t->scale.z = S3L_FRACTIONS_PER_UNIT;
  1297. t->scale.w = 0;
  1298. }
  1299. /** Performs perspecive division (z-divide). Does NOT check for division by
  1300. zero. */
  1301. static inline void S3L_perspectiveDivide(S3L_Vec4 *vector,
  1302. S3L_Unit focalLength)
  1303. {
  1304. vector->x = (vector->x * focalLength) / vector->z;
  1305. vector->y = (vector->y * focalLength) / vector->z;
  1306. }
  1307. void project3DPointToScreen(
  1308. S3L_Vec4 point,
  1309. S3L_Camera camera,
  1310. S3L_Vec4 *result)
  1311. {
  1312. S3L_Mat4 m;
  1313. S3L_makeCameraMatrix(camera.transform,&m);
  1314. S3L_Unit s = point.w;
  1315. point.w = S3L_FRACTIONS_PER_UNIT;
  1316. S3L_vec3Xmat4(&point,&m);
  1317. point.z = S3L_nonZero(point.z);
  1318. S3L_perspectiveDivide(&point,camera.focalLength);
  1319. S3L_ScreenCoord x, y;
  1320. S3L_mapProjectionPlaneToScreen(point,&x,&y);
  1321. result->x = x;
  1322. result->y = y;
  1323. result->z = point.z;
  1324. result->w =
  1325. (point.z <= 0) ? 0 :
  1326. (
  1327. (s * camera.focalLength * S3L_RESOLUTION_X) /
  1328. (point.z * S3L_FRACTIONS_PER_UNIT)
  1329. );
  1330. }
  1331. void S3L_lookAt(S3L_Vec4 pointTo, S3L_Transform3D *t)
  1332. {
  1333. S3L_Vec4 v;
  1334. v.x = pointTo.x - t->translation.x;
  1335. v.y = pointTo.z - t->translation.z;
  1336. S3L_Unit dx = v.x;
  1337. S3L_Unit l = S3L_vec2Length(v);
  1338. dx = (v.x * S3L_FRACTIONS_PER_UNIT) / S3L_nonZero(l); // normalize
  1339. t->rotation.y = -1 * S3L_asin(dx);
  1340. if (v.y < 0)
  1341. t->rotation.y = S3L_FRACTIONS_PER_UNIT / 2 - t->rotation.y;
  1342. v.x = pointTo.y - t->translation.y;
  1343. v.y = l;
  1344. l = S3L_vec2Length(v);
  1345. dx = (v.x * S3L_FRACTIONS_PER_UNIT) / S3L_nonZero(l);
  1346. t->rotation.x = S3L_asin(dx);
  1347. }
  1348. void S3L_setTransform3D(
  1349. S3L_Unit tx,
  1350. S3L_Unit ty,
  1351. S3L_Unit tz,
  1352. S3L_Unit rx,
  1353. S3L_Unit ry,
  1354. S3L_Unit rz,
  1355. S3L_Unit sx,
  1356. S3L_Unit sy,
  1357. S3L_Unit sz,
  1358. S3L_Transform3D *t)
  1359. {
  1360. t->translation.x = tx;
  1361. t->translation.y = ty;
  1362. t->translation.z = tz;
  1363. t->rotation.x = rx;
  1364. t->rotation.y = ry;
  1365. t->rotation.z = rz;
  1366. t->scale.x = sx;
  1367. t->scale.y = sy;
  1368. t->scale.z = sz;
  1369. }
  1370. void S3L_initCamera(S3L_Camera *camera)
  1371. {
  1372. camera->focalLength = S3L_FRACTIONS_PER_UNIT;
  1373. S3L_initTransform3D(&(camera->transform));
  1374. }
  1375. void S3L_rotationToDirections(
  1376. S3L_Vec4 rotation,
  1377. S3L_Unit length,
  1378. S3L_Vec4 *forw,
  1379. S3L_Vec4 *right,
  1380. S3L_Vec4 *up)
  1381. {
  1382. S3L_Mat4 m;
  1383. S3L_makeRotationMatrixZXY(rotation.x,rotation.y,rotation.z,&m);
  1384. if (forw != 0)
  1385. {
  1386. forw->x = 0;
  1387. forw->y = 0;
  1388. forw->z = length;
  1389. S3L_vec3Xmat4(forw,&m);
  1390. }
  1391. if (right != 0)
  1392. {
  1393. right->x = length;
  1394. right->y = 0;
  1395. right->z = 0;
  1396. S3L_vec3Xmat4(right,&m);
  1397. }
  1398. if (up != 0)
  1399. {
  1400. up->x = 0;
  1401. up->y = length;
  1402. up->z = 0;
  1403. S3L_vec3Xmat4(up,&m);
  1404. }
  1405. }
  1406. void S3L_initPixelInfo(S3L_PixelInfo *p)
  1407. {
  1408. p->x = 0;
  1409. p->y = 0;
  1410. p->barycentric[0] = S3L_FRACTIONS_PER_UNIT;
  1411. p->barycentric[1] = 0;
  1412. p->barycentric[2] = 0;
  1413. p->modelIndex = 0;
  1414. p->triangleIndex = 0;
  1415. p->triangleID = 0;
  1416. p->depth = 0;
  1417. p->previousZ = 0;
  1418. }
  1419. void S3L_initModel3D(
  1420. const S3L_Unit *vertices,
  1421. S3L_Unit vertexCount,
  1422. const S3L_Index *triangles,
  1423. S3L_Index triangleCount,
  1424. S3L_Model3D *model)
  1425. {
  1426. model->vertices = vertices;
  1427. model->vertexCount = vertexCount;
  1428. model->triangles = triangles;
  1429. model->triangleCount = triangleCount;
  1430. model->customTransformMatrix = 0;
  1431. S3L_initTransform3D(&(model->transform));
  1432. S3L_initDrawConfig(&(model->config));
  1433. }
  1434. void S3L_initScene(
  1435. S3L_Model3D *models,
  1436. S3L_Index modelCount,
  1437. S3L_Scene *scene)
  1438. {
  1439. scene->models = models;
  1440. scene->modelCount = modelCount;
  1441. S3L_initCamera(&(scene->camera));
  1442. }
  1443. void S3L_initDrawConfig(S3L_DrawConfig *config)
  1444. {
  1445. config->backfaceCulling = 2;
  1446. config->visible = 1;
  1447. }
  1448. #ifndef S3L_PIXEL_FUNCTION
  1449. #error Pixel rendering function (S3L_PIXEL_FUNCTION) not specified!
  1450. #endif
  1451. static inline void S3L_PIXEL_FUNCTION(S3L_PixelInfo *pixel); // forward decl
  1452. /** Serves to accelerate linear interpolation for performance-critical
  1453. code. Functions such as S3L_interpolate require division to compute each
  1454. interpolated value, while S3L_FastLerpState only requires a division for
  1455. the initiation and a shift for retrieving each interpolated value.
  1456. S3L_FastLerpState stores a value and a step, both scaled (shifted by
  1457. S3L_FAST_LERP_QUALITY) to increase precision. The step is being added to the
  1458. value, which achieves the interpolation. This will only be useful for
  1459. interpolations in which we need to get the interpolated value in every step.
  1460. BEWARE! Shifting a negative value is undefined, so handling shifting of
  1461. negative values has to be done cleverly. */
  1462. typedef struct
  1463. {
  1464. S3L_Unit valueScaled;
  1465. S3L_Unit stepScaled;
  1466. } S3L_FastLerpState;
  1467. #define S3L_getFastLerpValue(state)\
  1468. (state.valueScaled >> S3L_FAST_LERP_QUALITY)
  1469. #define S3L_stepFastLerp(state)\
  1470. state.valueScaled += state.stepScaled
  1471. static inline S3L_Unit S3L_interpolateBarycentric(
  1472. S3L_Unit value0,
  1473. S3L_Unit value1,
  1474. S3L_Unit value2,
  1475. S3L_Unit barycentric[3])
  1476. {
  1477. return
  1478. (
  1479. (value0 * barycentric[0]) +
  1480. (value1 * barycentric[1]) +
  1481. (value2 * barycentric[2])
  1482. ) / S3L_FRACTIONS_PER_UNIT;
  1483. }
  1484. void S3L_mapProjectionPlaneToScreen(
  1485. S3L_Vec4 point,
  1486. S3L_ScreenCoord *screenX,
  1487. S3L_ScreenCoord *screenY)
  1488. {
  1489. *screenX =
  1490. S3L_HALF_RESOLUTION_X +
  1491. (point.x * S3L_HALF_RESOLUTION_X) / S3L_FRACTIONS_PER_UNIT;
  1492. *screenY =
  1493. S3L_HALF_RESOLUTION_Y -
  1494. (point.y * S3L_HALF_RESOLUTION_X) / S3L_FRACTIONS_PER_UNIT;
  1495. }
  1496. void S3L_zBufferClear(void)
  1497. {
  1498. #if S3L_Z_BUFFER
  1499. for (uint32_t i = 0; i < S3L_RESOLUTION_X * S3L_RESOLUTION_Y; ++i)
  1500. S3L_zBuffer[i] = S3L_MAX_DEPTH;
  1501. #endif
  1502. }
  1503. void S3L_stencilBufferClear(void)
  1504. {
  1505. #if S3L_STENCIL_BUFFER
  1506. for (uint32_t i = 0; i < S3L_STENCIL_BUFFER_SIZE; ++i)
  1507. S3L_stencilBuffer[i] = 0;
  1508. #endif
  1509. }
  1510. void S3L_newFrame(void)
  1511. {
  1512. S3L_zBufferClear();
  1513. S3L_stencilBufferClear();
  1514. }
  1515. void S3L_drawTriangle(
  1516. S3L_Vec4 point0,
  1517. S3L_Vec4 point1,
  1518. S3L_Vec4 point2,
  1519. S3L_Index modelIndex,
  1520. S3L_Index triangleIndex)
  1521. {
  1522. S3L_PixelInfo p;
  1523. S3L_initPixelInfo(&p);
  1524. p.modelIndex = modelIndex;
  1525. p.triangleIndex = triangleIndex;
  1526. p.triangleID = (modelIndex << 16) | triangleIndex;
  1527. S3L_Vec4 *tPointSS, *lPointSS, *rPointSS; /* points in Screen Space (in
  1528. S3L_Units, normalized by
  1529. S3L_FRACTIONS_PER_UNIT) */
  1530. S3L_Unit *barycentric0; // bar. coord that gets higher from L to R
  1531. S3L_Unit *barycentric1; // bar. coord that gets higher from R to L
  1532. S3L_Unit *barycentric2; // bar. coord that gets higher from bottom up
  1533. // sort the vertices:
  1534. #define assignPoints(t,a,b)\
  1535. {\
  1536. tPointSS = &point##t;\
  1537. barycentric2 = &(p.barycentric[t]);\
  1538. if (S3L_triangleWinding(point##t.x,point##t.y,point##a.x,point##a.y,\
  1539. point##b.x,point##b.y) >= 0)\
  1540. {\
  1541. lPointSS = &point##a; rPointSS = &point##b;\
  1542. barycentric0 = &(p.barycentric[b]);\
  1543. barycentric1 = &(p.barycentric[a]);\
  1544. }\
  1545. else\
  1546. {\
  1547. lPointSS = &point##b; rPointSS = &point##a;\
  1548. barycentric0 = &(p.barycentric[a]);\
  1549. barycentric1 = &(p.barycentric[b]);\
  1550. }\
  1551. }
  1552. if (point0.y <= point1.y)
  1553. {
  1554. if (point0.y <= point2.y)
  1555. assignPoints(0,1,2)
  1556. else
  1557. assignPoints(2,0,1)
  1558. }
  1559. else
  1560. {
  1561. if (point1.y <= point2.y)
  1562. assignPoints(1,0,2)
  1563. else
  1564. assignPoints(2,0,1)
  1565. }
  1566. #undef assignPoints
  1567. #if S3L_FLAT
  1568. *barycentric0 = S3L_FRACTIONS_PER_UNIT / 3;
  1569. *barycentric1 = S3L_FRACTIONS_PER_UNIT / 3;
  1570. *barycentric2 = S3L_FRACTIONS_PER_UNIT - 2 * (S3L_FRACTIONS_PER_UNIT / 3);
  1571. #endif
  1572. p.triangleSize[0] = rPointSS->x - lPointSS->x;
  1573. p.triangleSize[1] =
  1574. (rPointSS->y > lPointSS->y ? rPointSS->y : lPointSS->y) - tPointSS->y;
  1575. // now draw the triangle line by line:
  1576. S3L_ScreenCoord splitY; // Y of the vertically middle point of the triangle
  1577. S3L_ScreenCoord endY; // bottom Y of the whole triangle
  1578. int splitOnLeft; /* whether splitY is the y coord. of left or right
  1579. point */
  1580. if (rPointSS->y <= lPointSS->y)
  1581. {
  1582. splitY = rPointSS->y;
  1583. splitOnLeft = 0;
  1584. endY = lPointSS->y;
  1585. }
  1586. else
  1587. {
  1588. splitY = lPointSS->y;
  1589. splitOnLeft = 1;
  1590. endY = rPointSS->y;
  1591. }
  1592. S3L_ScreenCoord currentY = tPointSS->y;
  1593. /* We'll be using an algorithm similar to Bresenham line algorithm. The
  1594. specifics of this algorithm are among others:
  1595. - drawing possibly NON-CONTINUOUS line
  1596. - NOT tracing the line exactly, but rather rasterizing one the right
  1597. side of it, according to the pixel CENTERS, INCLUDING the pixel
  1598. centers
  1599. The principle is this:
  1600. - Move vertically by pixels and accumulate the error (abs(dx/dy)).
  1601. - If the error is greater than one (crossed the next pixel center), keep
  1602. moving horizontally and substracting 1 from the error until it is less
  1603. than 1 again.
  1604. - To make this INTEGER ONLY, scale the case so that distance between
  1605. pixels is equal to dy (instead of 1). This way the error becomes
  1606. dx/dy * dy == dx, and we're comparing the error to (and potentially
  1607. substracting) 1 * dy == dy. */
  1608. int16_t
  1609. /* triangle side:
  1610. left right */
  1611. lX, rX, // current x position on the screen
  1612. lDx, rDx, // dx (end point - start point)
  1613. lDy, rDy, // dy (end point - start point)
  1614. lInc, rInc, // direction in which to increment (1 or -1)
  1615. lErr, rErr, // current error (Bresenham)
  1616. lErrCmp, rErrCmp, // helper for deciding comparison (> vs >=)
  1617. lErrAdd, rErrAdd, // error value to add in each Bresenham cycle
  1618. lErrSub, rErrSub; // error value to substract when moving in x direction
  1619. S3L_FastLerpState lSideFLS, rSideFLS;
  1620. #if S3L_COMPUTE_LERP_DEPTH
  1621. S3L_FastLerpState lDepthFLS, rDepthFLS;
  1622. #define initDepthFLS(s,p1,p2)\
  1623. s##DepthFLS.valueScaled = p1##PointSS->z << S3L_FAST_LERP_QUALITY;\
  1624. s##DepthFLS.stepScaled = ((p2##PointSS->z << S3L_FAST_LERP_QUALITY) -\
  1625. s##DepthFLS.valueScaled) / (s##Dy != 0 ? s##Dy : 1);
  1626. #else
  1627. #define initDepthFLS(s,p1,p2) ;
  1628. #endif
  1629. /* init side for the algorithm, params:
  1630. s - which side (l or r)
  1631. p1 - point from (t, l or r)
  1632. p2 - point to (t, l or r)
  1633. down - whether the side coordinate goes top-down or vice versa */
  1634. #define initSide(s,p1,p2,down)\
  1635. s##X = p1##PointSS->x;\
  1636. s##Dx = p2##PointSS->x - p1##PointSS->x;\
  1637. s##Dy = p2##PointSS->y - p1##PointSS->y;\
  1638. initDepthFLS(s,p1,p2)\
  1639. s##SideFLS.stepScaled = (S3L_FRACTIONS_PER_UNIT << S3L_FAST_LERP_QUALITY)\
  1640. / (s##Dy != 0 ? s##Dy : 1);\
  1641. s##SideFLS.valueScaled = 0;\
  1642. if (!down)\
  1643. {\
  1644. s##SideFLS.valueScaled =\
  1645. S3L_FRACTIONS_PER_UNIT << S3L_FAST_LERP_QUALITY;\
  1646. s##SideFLS.stepScaled *= -1;\
  1647. }\
  1648. s##Inc = s##Dx >= 0 ? 1 : -1;\
  1649. if (s##Dx < 0)\
  1650. {s##Err = 0; s##ErrCmp = 0;}\
  1651. else\
  1652. {s##Err = s##Dy; s##ErrCmp = 1;}\
  1653. s##ErrAdd = S3L_abs(s##Dx);\
  1654. s##ErrSub = s##Dy != 0 ? s##Dy : 1; /* don't allow 0, could lead to an
  1655. infinite substracting loop */
  1656. #define stepSide(s)\
  1657. while (s##Err - s##Dy >= s##ErrCmp)\
  1658. {\
  1659. s##X += s##Inc;\
  1660. s##Err -= s##ErrSub;\
  1661. }\
  1662. s##Err += s##ErrAdd;
  1663. initSide(r,t,r,1)
  1664. initSide(l,t,l,1)
  1665. #if S3L_PERSPECTIVE_CORRECTION
  1666. /* PC is done by linearly interpolating reciprocals from which the corrected
  1667. velues can be computed. See
  1668. http://www.lysator.liu.se/~mikaelk/doc/perspectivetexture/ */
  1669. #if S3L_PERSPECTIVE_CORRECTION == 1
  1670. #define Z_RECIP_NUMERATOR\
  1671. (S3L_FRACTIONS_PER_UNIT * S3L_FRACTIONS_PER_UNIT * S3L_FRACTIONS_PER_UNIT)
  1672. #elif S3L_PERSPECTIVE_CORRECTION == 2
  1673. #define Z_RECIP_NUMERATOR\
  1674. (S3L_FRACTIONS_PER_UNIT * S3L_FRACTIONS_PER_UNIT)
  1675. #endif
  1676. /* ^ This numerator is a number by which we divide values for the
  1677. reciprocals. For PC == 2 it has to be lower because linear interpolation
  1678. scaling would make it overflow -- this results in lower depth precision
  1679. in bigger distance for PC == 2. */
  1680. S3L_Unit
  1681. tPointRecipZ, lPointRecipZ, rPointRecipZ, /* Reciprocals of the depth of
  1682. each triangle point. */
  1683. lRecip0, lRecip1, rRecip0, rRecip1; /* Helper variables for swapping
  1684. the above after split. */
  1685. tPointRecipZ = Z_RECIP_NUMERATOR / S3L_nonZero(tPointSS->z);
  1686. lPointRecipZ = Z_RECIP_NUMERATOR / S3L_nonZero(lPointSS->z);
  1687. rPointRecipZ = Z_RECIP_NUMERATOR / S3L_nonZero(rPointSS->z);
  1688. lRecip0 = tPointRecipZ;
  1689. lRecip1 = lPointRecipZ;
  1690. rRecip0 = tPointRecipZ;
  1691. rRecip1 = rPointRecipZ;
  1692. #define manageSplitPerspective(b0,b1)\
  1693. b1##Recip0 = b0##PointRecipZ;\
  1694. b1##Recip1 = b1##PointRecipZ;\
  1695. b0##Recip0 = b0##PointRecipZ;\
  1696. b0##Recip1 = tPointRecipZ;
  1697. #else
  1698. #define manageSplitPerspective(b0,b1) ;
  1699. #endif
  1700. // clip to the screen in y dimension:
  1701. endY = S3L_min(endY,S3L_RESOLUTION_Y);
  1702. /* Clipping above the screen (y < 0) can't be easily done here, will be
  1703. handled inside the loop. */
  1704. while (currentY < endY) /* draw the triangle from top to bottom -- the
  1705. bottom-most row is left out because, following
  1706. from the rasterization rules (see start of the
  1707. file), it is to never be rasterized. */
  1708. {
  1709. if (currentY == splitY) // reached a vertical split of the triangle?
  1710. {
  1711. #define manageSplit(b0,b1,s0,s1)\
  1712. S3L_Unit *tmp = barycentric##b0;\
  1713. barycentric##b0 = barycentric##b1;\
  1714. barycentric##b1 = tmp;\
  1715. s0##SideFLS.valueScaled = (S3L_FRACTIONS_PER_UNIT\
  1716. << S3L_FAST_LERP_QUALITY) - s0##SideFLS.valueScaled;\
  1717. s0##SideFLS.stepScaled *= -1;\
  1718. manageSplitPerspective(s0,s1)
  1719. if (splitOnLeft)
  1720. {
  1721. initSide(l,l,r,0);
  1722. manageSplit(0,2,r,l)
  1723. }
  1724. else
  1725. {
  1726. initSide(r,r,l,0);
  1727. manageSplit(1,2,l,r)
  1728. }
  1729. }
  1730. stepSide(r)
  1731. stepSide(l)
  1732. if (currentY >= 0) /* clipping of pixels whose y < 0 (can't be easily done
  1733. outside the loop because of the Bresenham-like
  1734. algorithm steps) */
  1735. {
  1736. p.y = currentY;
  1737. // draw the horizontal line
  1738. #if !S3L_FLAT
  1739. S3L_Unit rowLength = S3L_nonZero(rX - lX - 1); // prevent zero div
  1740. #if S3L_PERSPECTIVE_CORRECTION
  1741. S3L_Unit lOverZ, lRecipZ, rOverZ, rRecipZ, lT, rT;
  1742. lT = S3L_getFastLerpValue(lSideFLS);
  1743. rT = S3L_getFastLerpValue(rSideFLS);
  1744. lOverZ = S3L_interpolateByUnitFrom0(lRecip1,lT);
  1745. lRecipZ = S3L_interpolateByUnit(lRecip0,lRecip1,lT);
  1746. rOverZ = S3L_interpolateByUnitFrom0(rRecip1,rT);
  1747. rRecipZ = S3L_interpolateByUnit(rRecip0,rRecip1,rT);
  1748. #else
  1749. S3L_FastLerpState b0FLS, b1FLS;
  1750. #if S3L_COMPUTE_LERP_DEPTH
  1751. S3L_FastLerpState depthFLS;
  1752. depthFLS.valueScaled = lDepthFLS.valueScaled;
  1753. depthFLS.stepScaled =
  1754. (rDepthFLS.valueScaled - lDepthFLS.valueScaled) / rowLength;
  1755. #endif
  1756. b0FLS.valueScaled = 0;
  1757. b1FLS.valueScaled = lSideFLS.valueScaled;
  1758. b0FLS.stepScaled = rSideFLS.valueScaled / rowLength;
  1759. b1FLS.stepScaled = -1 * lSideFLS.valueScaled / rowLength;
  1760. #endif
  1761. #endif
  1762. // clip to the screen in x dimension:
  1763. S3L_ScreenCoord rXClipped = S3L_min(rX,S3L_RESOLUTION_X),
  1764. lXClipped = lX;
  1765. if (lXClipped < 0)
  1766. {
  1767. lXClipped = 0;
  1768. #if !S3L_PERSPECTIVE_CORRECTION && !S3L_FLAT
  1769. b0FLS.valueScaled -= lX * b0FLS.stepScaled;
  1770. b1FLS.valueScaled -= lX * b1FLS.stepScaled;
  1771. #if S3L_COMPUTE_LERP_DEPTH
  1772. depthFLS.valueScaled -= lX * depthFLS.stepScaled;
  1773. #endif
  1774. #endif
  1775. }
  1776. #if S3L_PERSPECTIVE_CORRECTION
  1777. S3L_ScreenCoord i = lXClipped - lX; /* helper var to save one
  1778. substraction in the inner
  1779. loop */
  1780. #endif
  1781. #if S3L_PERSPECTIVE_CORRECTION == 2
  1782. S3L_FastLerpState
  1783. depthPC, // interpolates depth between row segments
  1784. b0PC, // interpolates barycentric0 between row segments
  1785. b1PC; // interpolates barycentric1 between row segments
  1786. /* ^ These interpolate values between row segments (lines of pixels
  1787. of S3L_PC_APPROX_LENGTH length). After each row segment perspective
  1788. correction is recomputed. */
  1789. depthPC.valueScaled =
  1790. (Z_RECIP_NUMERATOR /
  1791. S3L_nonZero(S3L_interpolate(lRecipZ,rRecipZ,i,rowLength)))
  1792. << S3L_FAST_LERP_QUALITY;
  1793. b0PC.valueScaled =
  1794. (
  1795. S3L_interpolateFrom0(rOverZ,i,rowLength)
  1796. * depthPC.valueScaled
  1797. ) / (Z_RECIP_NUMERATOR / S3L_FRACTIONS_PER_UNIT);
  1798. b1PC.valueScaled =
  1799. (
  1800. (lOverZ - S3L_interpolateFrom0(lOverZ,i,rowLength))
  1801. * depthPC.valueScaled
  1802. ) / (Z_RECIP_NUMERATOR / S3L_FRACTIONS_PER_UNIT);
  1803. int8_t rowCount = S3L_PC_APPROX_LENGTH;
  1804. #endif
  1805. #if S3L_Z_BUFFER
  1806. uint32_t zBufferIndex = p.y * S3L_RESOLUTION_X + lXClipped;
  1807. #endif
  1808. // draw the row -- inner loop:
  1809. for (S3L_ScreenCoord x = lXClipped; x < rXClipped; ++x)
  1810. {
  1811. int8_t testsPassed = 1;
  1812. #if S3L_STENCIL_BUFFER
  1813. if (!S3L_stencilTest(x,p.y))
  1814. testsPassed = 0;
  1815. #endif
  1816. p.x = x;
  1817. #if S3L_COMPUTE_DEPTH
  1818. #if S3L_PERSPECTIVE_CORRECTION == 1
  1819. p.depth = Z_RECIP_NUMERATOR /
  1820. S3L_nonZero(S3L_interpolate(lRecipZ,rRecipZ,i,rowLength));
  1821. #elif S3L_PERSPECTIVE_CORRECTION == 2
  1822. if (rowCount >= S3L_PC_APPROX_LENGTH)
  1823. {
  1824. // init the linear interpolation to the next PC correct value
  1825. rowCount = 0;
  1826. S3L_Unit nextI = i + S3L_PC_APPROX_LENGTH;
  1827. if (nextI < rowLength)
  1828. {
  1829. S3L_Unit nextDepthScaled =
  1830. (
  1831. Z_RECIP_NUMERATOR /
  1832. S3L_nonZero(S3L_interpolate(lRecipZ,rRecipZ,nextI,rowLength))
  1833. ) << S3L_FAST_LERP_QUALITY;
  1834. depthPC.stepScaled =
  1835. (nextDepthScaled - depthPC.valueScaled) / S3L_PC_APPROX_LENGTH;
  1836. S3L_Unit nextValue =
  1837. (
  1838. S3L_interpolateFrom0(rOverZ,nextI,rowLength)
  1839. * nextDepthScaled
  1840. ) / (Z_RECIP_NUMERATOR / S3L_FRACTIONS_PER_UNIT);
  1841. b0PC.stepScaled =
  1842. (nextValue - b0PC.valueScaled) / S3L_PC_APPROX_LENGTH;
  1843. nextValue =
  1844. (
  1845. (lOverZ - S3L_interpolateFrom0(lOverZ,nextI,rowLength))
  1846. * nextDepthScaled
  1847. ) / (Z_RECIP_NUMERATOR / S3L_FRACTIONS_PER_UNIT);
  1848. b1PC.stepScaled =
  1849. (nextValue - b1PC.valueScaled) / S3L_PC_APPROX_LENGTH;
  1850. }
  1851. else
  1852. {
  1853. /* A special case where we'd be interpolating outside the triangle.
  1854. It seems like a valid approach at first, but it creates a bug
  1855. in a case when the rasaterized triangle is near screen 0 and can
  1856. actually never reach the extrapolated screen position. So we
  1857. have to clamp to the actual end of the triangle here. */
  1858. S3L_Unit maxI = S3L_nonZero(rowLength - i);
  1859. S3L_Unit nextDepthScaled =
  1860. (
  1861. Z_RECIP_NUMERATOR /
  1862. S3L_nonZero(rRecipZ)
  1863. ) << S3L_FAST_LERP_QUALITY;
  1864. depthPC.stepScaled =
  1865. (nextDepthScaled - depthPC.valueScaled) / maxI;
  1866. S3L_Unit nextValue =
  1867. (
  1868. rOverZ
  1869. * nextDepthScaled
  1870. ) / (Z_RECIP_NUMERATOR / S3L_FRACTIONS_PER_UNIT);
  1871. b0PC.stepScaled =
  1872. (nextValue - b0PC.valueScaled) / maxI;
  1873. b1PC.stepScaled =
  1874. -1 * b1PC.valueScaled / maxI;
  1875. }
  1876. }
  1877. p.depth = S3L_getFastLerpValue(depthPC);
  1878. #else
  1879. p.depth = S3L_getFastLerpValue(depthFLS);
  1880. S3L_stepFastLerp(depthFLS);
  1881. #endif
  1882. #else // !S3L_COMPUTE_DEPTH
  1883. p.depth = (tPointSS->z + lPointSS->z + rPointSS->z) / 3;
  1884. #endif
  1885. #if S3L_Z_BUFFER
  1886. p.previousZ = S3L_zBuffer[zBufferIndex];
  1887. zBufferIndex++;
  1888. if (!S3L_zTest(p.x,p.y,p.depth))
  1889. testsPassed = 0;
  1890. #endif
  1891. if (testsPassed)
  1892. {
  1893. #if !S3L_FLAT
  1894. #if S3L_PERSPECTIVE_CORRECTION == 0
  1895. *barycentric0 = S3L_getFastLerpValue(b0FLS);
  1896. *barycentric1 = S3L_getFastLerpValue(b1FLS);
  1897. #elif S3L_PERSPECTIVE_CORRECTION == 1
  1898. *barycentric0 =
  1899. (
  1900. S3L_interpolateFrom0(rOverZ,i,rowLength)
  1901. * p.depth
  1902. ) / (Z_RECIP_NUMERATOR / S3L_FRACTIONS_PER_UNIT);
  1903. *barycentric1 =
  1904. (
  1905. (lOverZ - S3L_interpolateFrom0(lOverZ,i,rowLength))
  1906. * p.depth
  1907. ) / (Z_RECIP_NUMERATOR / S3L_FRACTIONS_PER_UNIT);
  1908. #elif S3L_PERSPECTIVE_CORRECTION == 2
  1909. *barycentric0 = S3L_getFastLerpValue(b0PC);
  1910. *barycentric1 = S3L_getFastLerpValue(b1PC);
  1911. #endif
  1912. *barycentric2 =
  1913. S3L_FRACTIONS_PER_UNIT - *barycentric0 - *barycentric1;
  1914. #endif
  1915. S3L_PIXEL_FUNCTION(&p);
  1916. } // tests passed
  1917. #if !S3L_FLAT
  1918. #if S3L_PERSPECTIVE_CORRECTION
  1919. i++;
  1920. #if S3L_PERSPECTIVE_CORRECTION == 2
  1921. rowCount++;
  1922. S3L_stepFastLerp(depthPC);
  1923. S3L_stepFastLerp(b0PC);
  1924. S3L_stepFastLerp(b1PC);
  1925. #endif
  1926. #else
  1927. S3L_stepFastLerp(b0FLS);
  1928. S3L_stepFastLerp(b1FLS);
  1929. #endif
  1930. #endif
  1931. } // inner loop
  1932. } // y clipping
  1933. #if !S3L_FLAT
  1934. S3L_stepFastLerp(lSideFLS);
  1935. S3L_stepFastLerp(rSideFLS);
  1936. #if S3L_COMPUTE_LERP_DEPTH
  1937. S3L_stepFastLerp(lDepthFLS);
  1938. S3L_stepFastLerp(rDepthFLS);
  1939. #endif
  1940. #endif
  1941. ++currentY;
  1942. } // row drawing
  1943. #undef manageSplit
  1944. #undef initPC
  1945. #undef initSide
  1946. #undef stepSide
  1947. #undef Z_RECIP_NUMERATOR
  1948. }
  1949. void S3L_rotate2DPoint(S3L_Unit *x, S3L_Unit *y, S3L_Unit angle)
  1950. {
  1951. if (angle < S3L_SIN_TABLE_UNIT_STEP)
  1952. return; // no visible rotation
  1953. S3L_Unit angleSin = S3L_sin(angle);
  1954. S3L_Unit angleCos = S3L_cos(angle);
  1955. S3L_Unit xBackup = *x;
  1956. *x =
  1957. (angleCos * (*x)) / S3L_FRACTIONS_PER_UNIT -
  1958. (angleSin * (*y)) / S3L_FRACTIONS_PER_UNIT;
  1959. *y =
  1960. (angleSin * xBackup) / S3L_FRACTIONS_PER_UNIT +
  1961. (angleCos * (*y)) / S3L_FRACTIONS_PER_UNIT;
  1962. }
  1963. void S3L_makeWorldMatrix(S3L_Transform3D worldTransform, S3L_Mat4 *m)
  1964. {
  1965. S3L_makeScaleMatrix(
  1966. worldTransform.scale.x,
  1967. worldTransform.scale.y,
  1968. worldTransform.scale.z,
  1969. m
  1970. );
  1971. S3L_Mat4 t;
  1972. S3L_makeRotationMatrixZXY(
  1973. worldTransform.rotation.x,
  1974. worldTransform.rotation.y,
  1975. worldTransform.rotation.z,
  1976. &t);
  1977. S3L_mat4Xmat4(m,&t);
  1978. S3L_makeTranslationMat(
  1979. worldTransform.translation.x,
  1980. worldTransform.translation.y,
  1981. worldTransform.translation.z,
  1982. &t);
  1983. S3L_mat4Xmat4(m,&t);
  1984. }
  1985. void S3L_transposeMat4(S3L_Mat4 *m)
  1986. {
  1987. S3L_Unit tmp;
  1988. for (uint8_t y = 0; y < 3; ++y)
  1989. for (uint8_t x = 1 + y; x < 4; ++x)
  1990. {
  1991. tmp = (*m)[x][y];
  1992. (*m)[x][y] = (*m)[y][x];
  1993. (*m)[y][x] = tmp;
  1994. }
  1995. }
  1996. void S3L_makeCameraMatrix(S3L_Transform3D cameraTransform, S3L_Mat4 *m)
  1997. {
  1998. S3L_makeTranslationMat(
  1999. -1 * cameraTransform.translation.x,
  2000. -1 * cameraTransform.translation.y,
  2001. -1 * cameraTransform.translation.z,
  2002. m);
  2003. S3L_Mat4 r;
  2004. S3L_makeRotationMatrixZXY(
  2005. cameraTransform.rotation.x,
  2006. cameraTransform.rotation.y,
  2007. cameraTransform.rotation.z,
  2008. &r);
  2009. S3L_transposeMat4(&r); // transposing creates an inverse transform
  2010. S3L_mat4Xmat4(m,&r);
  2011. }
  2012. int8_t S3L_triangleWinding(
  2013. S3L_ScreenCoord x0,
  2014. S3L_ScreenCoord y0,
  2015. S3L_ScreenCoord x1,
  2016. S3L_ScreenCoord y1,
  2017. S3L_ScreenCoord x2,
  2018. S3L_ScreenCoord y2)
  2019. {
  2020. int32_t winding =
  2021. (y1 - y0) * (x2 - x1) - (x1 - x0) * (y2 - y1);
  2022. // ^ cross product for points with z == 0
  2023. return winding > 0 ? 1 : (winding < 0 ? -1 : 0);
  2024. }
  2025. /**
  2026. Checks if given triangle (in Screen Space) is at least partially visible,
  2027. i.e. returns false if the triangle is either completely outside the frustum
  2028. (left, right, top, bottom, near) or is invisible due to backface culling.
  2029. */
  2030. static inline int8_t S3L_triangleIsVisible(
  2031. S3L_Vec4 p0,
  2032. S3L_Vec4 p1,
  2033. S3L_Vec4 p2,
  2034. uint8_t backfaceCulling)
  2035. {
  2036. #define clipTest(c,cmp,v)\
  2037. (p0.c cmp (v) && p1.c cmp (v) && p2.c cmp (v))
  2038. if ( // outside frustum?
  2039. #if S3L_NEAR_CROSS_STRATEGY == 0
  2040. p0.z <= S3L_NEAR || p1.z <= S3L_NEAR || p2.z <= S3L_NEAR ||
  2041. // ^ partially in front of NEAR?
  2042. #else
  2043. clipTest(z,<=,S3L_NEAR) || // completely in front of NEAR?
  2044. #endif
  2045. clipTest(x,<,0) ||
  2046. clipTest(x,>=,S3L_RESOLUTION_X) ||
  2047. clipTest(y,<,0) ||
  2048. clipTest(y,>,S3L_RESOLUTION_Y)
  2049. )
  2050. return 0;
  2051. #undef clipTest
  2052. if (backfaceCulling != 0)
  2053. {
  2054. int8_t winding =
  2055. S3L_triangleWinding(p0.x,p0.y,p1.x,p1.y,p2.x,p2.y);
  2056. if ((backfaceCulling == 1 && winding > 0) ||
  2057. (backfaceCulling == 2 && winding < 0))
  2058. return 0;
  2059. }
  2060. return 1;
  2061. }
  2062. #if S3L_SORT != 0
  2063. typedef struct
  2064. {
  2065. uint8_t modelIndex;
  2066. S3L_Index triangleIndex;
  2067. uint16_t sortValue;
  2068. } _S3L_TriangleToSort;
  2069. _S3L_TriangleToSort S3L_sortArray[S3L_MAX_TRIANGES_DRAWN];
  2070. uint16_t S3L_sortArrayLength;
  2071. #endif
  2072. void _S3L_projectVertex(
  2073. const S3L_Model3D *model,
  2074. S3L_Index triangleIndex,
  2075. uint8_t vertex,
  2076. S3L_Mat4 *projectionMatrix,
  2077. S3L_Vec4 *result)
  2078. {
  2079. uint32_t vertexIndex = model->triangles[triangleIndex * 3 + vertex] * 3;
  2080. result->x = model->vertices[vertexIndex];
  2081. result->y = model->vertices[vertexIndex + 1];
  2082. result->z = model->vertices[vertexIndex + 2];
  2083. result->w = S3L_FRACTIONS_PER_UNIT; // needed for translation
  2084. S3L_vec3Xmat4(result,projectionMatrix);
  2085. result->w = result->z;
  2086. /* We'll keep the non-clamped z in w for sorting. */
  2087. }
  2088. void _S3L_mapProjectedVertexToScreen(S3L_Vec4 *vertex, S3L_Unit focalLength)
  2089. {
  2090. vertex->z = vertex->z >= S3L_NEAR ? vertex->z : S3L_NEAR;
  2091. /* ^ This firstly prevents zero division in the follwoing z-divide and
  2092. secondly "pushes" vertices that are in front of near a little bit forward,
  2093. which makes them behave a bit better. If all three vertices end up exactly
  2094. on NEAR, the triangle will be culled. */
  2095. S3L_perspectiveDivide(vertex,focalLength);
  2096. S3L_ScreenCoord sX, sY;
  2097. S3L_mapProjectionPlaneToScreen(*vertex,&sX,&sY);
  2098. vertex->x = sX;
  2099. vertex->y = sY;
  2100. }
  2101. /**
  2102. Projects a triangle to the screen. If enabled, a triangle can be potentially
  2103. subdivided into two if it crosses the near plane, in which case two projected
  2104. triangles are returned (return value will be 1).
  2105. */
  2106. uint8_t _S3L_projectTriangle(
  2107. const S3L_Model3D *model,
  2108. S3L_Index triangleIndex,
  2109. S3L_Mat4 *matrix,
  2110. uint32_t focalLength,
  2111. S3L_Vec4 transformed[6])
  2112. {
  2113. _S3L_projectVertex(model,triangleIndex,0,matrix,&(transformed[0]));
  2114. _S3L_projectVertex(model,triangleIndex,1,matrix,&(transformed[1]));
  2115. _S3L_projectVertex(model,triangleIndex,2,matrix,&(transformed[2]));
  2116. uint8_t result = 0;
  2117. #if S3L_NEAR_CROSS_STRATEGY == 2
  2118. uint8_t infront = 0;
  2119. uint8_t behind = 0;
  2120. uint8_t infrontI[3];
  2121. uint8_t behindI[3];
  2122. for (uint8_t i = 0; i < 3; ++i)
  2123. if (transformed[i].z < S3L_NEAR)
  2124. {
  2125. infrontI[infront] = i;
  2126. infront++;
  2127. }
  2128. else
  2129. {
  2130. behindI[behind] = i;
  2131. behind++;
  2132. }
  2133. #define interpolateVertex \
  2134. S3L_Unit ratio =\
  2135. ((transformed[be].z - S3L_NEAR) * S3L_FRACTIONS_PER_UNIT) /\
  2136. (transformed[be].z - transformed[in].z);\
  2137. transformed[in].x = transformed[be].x - \
  2138. ((transformed[be].x - transformed[in].x) * ratio) /\
  2139. S3L_FRACTIONS_PER_UNIT;\
  2140. transformed[in].y = transformed[be].y -\
  2141. ((transformed[be].y - transformed[in].y) * ratio) /\
  2142. S3L_FRACTIONS_PER_UNIT;\
  2143. transformed[in].z = S3L_NEAR;
  2144. if (infront == 2)
  2145. {
  2146. // shift the two vertices forward along the edge
  2147. for (uint8_t i = 0; i < 2; ++i)
  2148. {
  2149. uint8_t be = behindI[0], in = infrontI[i];
  2150. interpolateVertex
  2151. }
  2152. }
  2153. else if (infront == 1)
  2154. {
  2155. // create another triangle and do the shifts
  2156. transformed[3] = transformed[behindI[1]];
  2157. transformed[4] = transformed[infrontI[0]];
  2158. transformed[5] = transformed[infrontI[0]];
  2159. for (uint8_t i = 0; i < 2; ++i)
  2160. {
  2161. uint8_t be = behindI[i], in = i + 4;
  2162. interpolateVertex
  2163. }
  2164. transformed[infrontI[0]] = transformed[4];
  2165. _S3L_mapProjectedVertexToScreen(&transformed[3],focalLength);
  2166. _S3L_mapProjectedVertexToScreen(&transformed[4],focalLength);
  2167. _S3L_mapProjectedVertexToScreen(&transformed[5],focalLength);
  2168. result = 1;
  2169. }
  2170. #undef interpolateVertex
  2171. #endif // S3L_NEAR_CROSS_STRATEGY == 2
  2172. _S3L_mapProjectedVertexToScreen(&transformed[0],focalLength);
  2173. _S3L_mapProjectedVertexToScreen(&transformed[1],focalLength);
  2174. _S3L_mapProjectedVertexToScreen(&transformed[2],focalLength);
  2175. return result;
  2176. }
  2177. void S3L_drawScene(S3L_Scene scene)
  2178. {
  2179. S3L_Mat4 matFinal, matCamera;
  2180. S3L_Vec4 transformed[6]; // transformed triangle coords, for 2 triangles
  2181. const S3L_Model3D *model;
  2182. S3L_Index modelIndex, triangleIndex;
  2183. S3L_makeCameraMatrix(scene.camera.transform,&matCamera);
  2184. #if S3L_SORT != 0
  2185. uint16_t previousModel = 0;
  2186. S3L_sortArrayLength = 0;
  2187. #endif
  2188. for (modelIndex = 0; modelIndex < scene.modelCount; ++modelIndex)
  2189. {
  2190. if (!scene.models[modelIndex].config.visible)
  2191. continue;
  2192. #if S3L_SORT != 0
  2193. if (S3L_sortArrayLength >= S3L_MAX_TRIANGES_DRAWN)
  2194. break;
  2195. previousModel = modelIndex;
  2196. #endif
  2197. if (scene.models[modelIndex].customTransformMatrix == 0)
  2198. S3L_makeWorldMatrix(scene.models[modelIndex].transform,&matFinal);
  2199. else
  2200. {
  2201. S3L_Mat4 *m = scene.models[modelIndex].customTransformMatrix;
  2202. for (int8_t j = 0; j < 4; ++j)
  2203. for (int8_t i = 0; i < 4; ++i)
  2204. matFinal[i][j] = (*m)[i][j];
  2205. }
  2206. S3L_mat4Xmat4(&matFinal,&matCamera);
  2207. S3L_Index triangleCount = scene.models[modelIndex].triangleCount;
  2208. triangleIndex = 0;
  2209. while (triangleIndex < triangleCount)
  2210. {
  2211. model = &(scene.models[modelIndex]);
  2212. /* Some kind of cache could be used in theory to not project perviously
  2213. already projected vertices, but after some testing this was abandoned,
  2214. no gain was seen. */
  2215. uint8_t split = _S3L_projectTriangle(model,triangleIndex,&matFinal,
  2216. scene.camera.focalLength,transformed);
  2217. if (S3L_triangleIsVisible(transformed[0],transformed[1],transformed[2],
  2218. model->config.backfaceCulling))
  2219. {
  2220. #if S3L_SORT == 0
  2221. // without sorting draw right away
  2222. S3L_drawTriangle(transformed[0],transformed[1],transformed[2],modelIndex,
  2223. triangleIndex);
  2224. if (split) // draw potential subtriangle
  2225. S3L_drawTriangle(transformed[3],transformed[4],transformed[5],
  2226. modelIndex, triangleIndex);
  2227. #else
  2228. S3L_UNUSED(split);
  2229. if (S3L_sortArrayLength >= S3L_MAX_TRIANGES_DRAWN)
  2230. break;
  2231. // with sorting add to a sort list
  2232. S3L_sortArray[S3L_sortArrayLength].modelIndex = modelIndex;
  2233. S3L_sortArray[S3L_sortArrayLength].triangleIndex = triangleIndex;
  2234. S3L_sortArray[S3L_sortArrayLength].sortValue = S3L_zeroClamp(
  2235. transformed[0].w + transformed[1].w + transformed[2].w) >> 2;
  2236. /* ^
  2237. The w component here stores non-clamped z.
  2238. As a simple approximation we sort by the triangle center point,
  2239. which is a mean coordinate -- we don't actually have to divide by 3
  2240. (or anything), that is unnecessary for sorting! We shift by 2 just
  2241. as a fast operation to prevent overflow of the sum over uint_16t. */
  2242. S3L_sortArrayLength++;
  2243. #endif
  2244. }
  2245. triangleIndex++;
  2246. }
  2247. }
  2248. #if S3L_SORT != 0
  2249. #if S3L_SORT == 1
  2250. #define cmp <
  2251. #else
  2252. #define cmp >
  2253. #endif
  2254. /* Sort the triangles. We use insertion sort, because it has many advantages,
  2255. especially for smaller arrays (better than bubble sort, in-place, stable,
  2256. simple, ...). */
  2257. for (int16_t i = 1; i < S3L_sortArrayLength; ++i)
  2258. {
  2259. _S3L_TriangleToSort tmp = S3L_sortArray[i];
  2260. int16_t j = i - 1;
  2261. while (j >= 0 && S3L_sortArray[j].sortValue cmp tmp.sortValue)
  2262. {
  2263. S3L_sortArray[j + 1] = S3L_sortArray[j];
  2264. j--;
  2265. }
  2266. S3L_sortArray[j + 1] = tmp;
  2267. }
  2268. #undef cmp
  2269. for (S3L_Index i = 0; i < S3L_sortArrayLength; ++i) // draw sorted triangles
  2270. {
  2271. modelIndex = S3L_sortArray[i].modelIndex;
  2272. triangleIndex = S3L_sortArray[i].triangleIndex;
  2273. model = &(scene.models[modelIndex]);
  2274. if (modelIndex != previousModel)
  2275. {
  2276. // only recompute the matrix when the model has changed
  2277. S3L_makeWorldMatrix(model->transform,&matFinal);
  2278. S3L_mat4Xmat4(&matFinal,&matCamera);
  2279. previousModel = modelIndex;
  2280. }
  2281. /* Here we project the points again, which is redundant and slow as they've
  2282. already been projected above, but saving the projected points would
  2283. require a lot of memory, which for small resolutions could be even
  2284. worse than z-bufer. So this seems to be the best way memory-wise. */
  2285. uint8_t split = _S3L_projectTriangle(model,triangleIndex,&matFinal,
  2286. scene.camera.focalLength,transformed);
  2287. S3L_drawTriangle(transformed[0],transformed[1],transformed[2],modelIndex,
  2288. triangleIndex);
  2289. if (split)
  2290. S3L_drawTriangle(transformed[3],transformed[4],transformed[5],
  2291. modelIndex, triangleIndex);
  2292. }
  2293. #endif
  2294. }
  2295. #endif // guard