├── .gitignore
├── CMakeLists.txt
├── LICENSE
├── README.md
├── cmake
├── FindSDL2.cmake
└── config.h.in
├── docs
├── interpolation_compare.png
├── man.png
├── rtg.png
├── texturing.png
└── texturing2.png
├── include
├── smol.h
└── stb_image.h
└── src
├── CMakeLists.txt
├── main.c
├── shader.c
├── sre
├── sre.c
├── sre.h
├── sredefs.h
├── srerasterizer.c
├── sretexbuffer.c
├── sretypes.h
└── srmesh
│ ├── README.md
│ ├── srmesh.c
│ └── srmesh.h
└── test
├── CMakeLists.txt
├── minunit.h
└── test_objloader.c
/.gitignore:
--------------------------------------------------------------------------------
1 | # CMake Generated Content
2 | CMakeCache.txt
3 | CMakeFiles
4 | CMakeScripts
5 | Testing
6 | Makefile
7 | cmake_install.cmake
8 | install_manifest.txt
9 | compile_commands.json
10 | CTestTestfile.cmake
11 |
12 | #VSCode
13 | .vscode/
14 | *.vcxproj*
15 |
16 | # Emacs
17 | *~
18 | \#*\#
19 | /.emacs.desktop
20 | /.emacs.desktop.lock
21 | *.elc
22 | auto-save-list
23 | tramp
24 | .\#*
25 |
26 | # Other
27 | .clangd
28 | build/*
29 | bin/*
30 | lib/*
31 | include/config.h
32 |
--------------------------------------------------------------------------------
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #### Root CMakeLists file of the project
2 | #### Configuration file is build for GNU/Linux Systems
3 | #### Resort to your local CMake guide for how to configure for Windows
4 | cmake_minimum_required (VERSION 3.15)
5 |
6 | # General Project Settings
7 | project (SoftwareRasterizationEngine C)
8 | set (EXECUTABLE_NAME "rtg")
9 | set(CMAKE_BUILD_TYPE Debug)
10 |
11 |
12 | # External dependencies
13 | set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/")
14 |
15 | find_package(OpenGL REQUIRED)
16 | find_package(SDL2 REQUIRED)
17 |
18 |
19 | # Directory Structure
20 | set (SRC_DIR "${CMAKE_SOURCE_DIR}/src") # Source Files
21 | set (BIN_DIR "${CMAKE_SOURCE_DIR}/bin") # Binaries
22 | set (LIB_DIR "${CMAKE_SOURCE_DIR}/lib") # Static libraries
23 | set (INC_DIR "${CMAKE_SOURCE_DIR}/include") # Addition include
24 |
25 | set (INCS ${INC_DIR} ${SDL2_INCLUDE_DIRS}) # Include directories for compiling
26 | set (LIBS GL dl m smol ${SDL2_LIBRARIES}) # Libraries to link target against
27 |
28 |
29 | # Configuration
30 | set (PROJECT_VERSION_MAJOR 1)
31 | set (PROJECT_VERSION_MINOR 0)
32 |
33 | configure_file (
34 | "${CMAKE_SOURCE_DIR}/cmake/config.h.in"
35 | "${INC_DIR}/config.h")
36 |
37 |
38 | # Compiler Config
39 | set(CMAKE_C_FLAGS "-Wall -Wextra -Wpedantic -Wno-unused-variable")
40 | set(CMAKE_C_FLAGS_DEBUG "-g")
41 | set(CMAKE_C_FLAGS_RELEASE "-O3")
42 |
43 | if(NOT CMAKE_BUILD_TYPE)
44 | set(CMAKE_BUILD_TYPE Release)
45 | endif()
46 |
47 | set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
48 |
49 | # Input Path
50 | include_directories(${INCS}) # Include these targets for the compiling process
51 | link_directories(${LIB_DIR}) # Link targets against following libraries
52 |
53 | # Output Path
54 | set(LIBRARY_OUTPUT_PATH ${LIB_DIR})
55 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${BIN_DIR}/${CMAKE_BUILD_TYPE})
56 |
57 |
58 | # Main Source directory
59 | add_subdirectory(src)
60 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # C Real-Time Software Rasterization Engine
2 |
3 | 
4 |
5 | A small project for the sole purpose of learning the basics of computer graphics and bare bones C programming.
6 |
7 | The project consists of three major parts:
8 | * A basic software rendering engine.
9 | * A small matrix operations library (smol, outsourced as seperate library).
10 | * A simple application demo of the above.
11 |
12 | I greatly appreciate any critique and pointers concerning programming style and performance or any mistakes I may have done.
13 |
14 | ## Features
15 | * Triangle Rasterization
16 | * Vertex & Index Buffers
17 | * Texture Buffers & Interpolation
18 | * Vertex Array Objects with Vertex Attributes
19 | * Perspective Vertex Attribute Interpolation
20 | * Simple (Wavefront) Mesh Loading
21 | * Trivial Triangle Clipping
22 | * Vertex & Fragment Shader
23 | * Z-buffering
24 | * Texturing
25 |
26 | ## Todo
27 | * Better Model loading capabilities
28 | * Performant texturing
29 | * Polygon clipping
30 | * Mip-Mapping
31 | * Anisotropic filtering
32 | * Geometry Anti-Aliasing
33 |
34 | ## Bugs
35 | * Fix issues with Bresenheim Line Rendering, currently not used
36 |
37 | ## Libraries
38 | #### [SDL2](https://www.libsdl.org/),
39 | Used for hosting display output and processing events. Follow the installation guideline for your platform.
40 |
41 | #### [stb_images.h](https://github.com/nothings/stb/blob/master/stb_image.h)
42 | A single header image library used to load image data into textures.
43 | File already included in the `inc` directory.
44 |
45 | #### [SMOL](https://github.com/BeratE/smol)
46 |
47 | ## Licence
48 | This software is published under the GNU GPLv3.
49 |
--------------------------------------------------------------------------------
/cmake/FindSDL2.cmake:
--------------------------------------------------------------------------------
1 | # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
2 | # file Copyright.txt or https://cmake.org/licensing for details.
3 |
4 | #.rst:
5 | # FindSDL2
6 | # -------
7 | #
8 | # Locate SDL2 library
9 | #
10 | # This module defines
11 | #
12 | # ::
13 | #
14 | # SDL2_LIBRARY, the name of the library to link against
15 | # SDL2_FOUND, if false, do not try to link to SDL
16 | # SDL2_INCLUDE_DIR, where to find SDL.h
17 | # SDL2_VERSION_STRING, human-readable string containing the version of SDL
18 | #
19 | #
20 | #
21 | # This module responds to the flag:
22 | #
23 | # ::
24 | #
25 | # SDL2_BUILDING_LIBRARY
26 | # If this is defined, then no SDL2_main will be linked in because
27 | # only applications need main().
28 | # Otherwise, it is assumed you are building an application and this
29 | # module will attempt to locate and set the proper link flags
30 | # as part of the returned SDL2_LIBRARY variable.
31 | #
32 | #
33 | #
34 | # Don't forget to include SDLmain.h and SDLmain.m your project for the
35 | # OS X framework based version. (Other versions link to -lSDLmain which
36 | # this module will try to find on your behalf.) Also for OS X, this
37 | # module will automatically add the -framework Cocoa on your behalf.
38 | #
39 | #
40 | #
41 | # Additional Note: If you see an empty SDL2_LIBRARY_TEMP in your
42 | # configuration and no SDL2_LIBRARY, it means CMake did not find your SDL
43 | # library (SDL.dll, libsdl.so, SDL.framework, etc). Set
44 | # SDL2_LIBRARY_TEMP to point to your SDL library, and configure again.
45 | # Similarly, if you see an empty SDLMAIN_LIBRARY, you should set this
46 | # value as appropriate. These values are used to generate the final
47 | # SDL2_LIBRARY variable, but when these values are unset, SDL2_LIBRARY
48 | # does not get created.
49 | #
50 | #
51 | #
52 | # $SDL2DIR is an environment variable that would correspond to the
53 | # ./configure --prefix=$SDL2DIR used in building SDL. l.e.galup 9-20-02
54 | #
55 | # Modified by Eric Wing. Added code to assist with automated building
56 | # by using environmental variables and providing a more
57 | # controlled/consistent search behavior. Added new modifications to
58 | # recognize OS X frameworks and additional Unix paths (FreeBSD, etc).
59 | # Also corrected the header search path to follow "proper" SDL
60 | # guidelines. Added a search for SDLmain which is needed by some
61 | # platforms. Added a search for threads which is needed by some
62 | # platforms. Added needed compile switches for MinGW.
63 | #
64 | # On OSX, this will prefer the Framework version (if found) over others.
65 | # People will have to manually change the cache values of SDL2_LIBRARY to
66 | # override this selection or set the CMake environment
67 | # CMAKE_INCLUDE_PATH to modify the search paths.
68 | #
69 | # Note that the header path has changed from SDL/SDL.h to just SDL.h
70 | # This needed to change because "proper" SDL convention is #include
71 | # "SDL.h", not . This is done for portability reasons
72 | # because not all systems place things in SDL/ (see FreeBSD).
73 |
74 | if(NOT SDL2_DIR)
75 | set(SDL2_DIR "" CACHE PATH "SDL2 directory")
76 | endif()
77 |
78 | find_path(SDL2_INCLUDE_DIR SDL.h
79 | HINTS
80 | ENV SDL2DIR
81 | ${SDL2_DIR}
82 | PATH_SUFFIXES SDL2
83 | # path suffixes to search inside ENV{SDL2DIR}
84 | include/SDL2 include
85 | )
86 |
87 | if(CMAKE_SIZEOF_VOID_P EQUAL 8)
88 | set(VC_LIB_PATH_SUFFIX lib/x64)
89 | else()
90 | set(VC_LIB_PATH_SUFFIX lib/x86)
91 | endif()
92 |
93 | find_library(SDL2_LIBRARY_TEMP
94 | NAMES SDL2
95 | HINTS
96 | ENV SDL2DIR
97 | ${SDL2_DIR}
98 | PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX}
99 | )
100 |
101 | # Hide this cache variable from the user, it's an internal implementation
102 | # detail. The documented library variable for the user is SDL2_LIBRARY
103 | # which is derived from SDL2_LIBRARY_TEMP further below.
104 | set_property(CACHE SDL2_LIBRARY_TEMP PROPERTY TYPE INTERNAL)
105 |
106 | if(NOT SDL2_BUILDING_LIBRARY)
107 | if(NOT SDL2_INCLUDE_DIR MATCHES ".framework")
108 | # Non-OS X framework versions expect you to also dynamically link to
109 | # SDLmain. This is mainly for Windows and OS X. Other (Unix) platforms
110 | # seem to provide SDLmain for compatibility even though they don't
111 | # necessarily need it.
112 | find_library(SDL2MAIN_LIBRARY
113 | NAMES SDL2main
114 | HINTS
115 | ENV SDL2DIR
116 | ${SDL2_DIR}
117 | PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX}
118 | PATHS
119 | /sw
120 | /opt/local
121 | /opt/csw
122 | /opt
123 | )
124 | endif()
125 | endif()
126 |
127 | # SDL may require threads on your system.
128 | # The Apple build may not need an explicit flag because one of the
129 | # frameworks may already provide it.
130 | # But for non-OSX systems, I will use the CMake Threads package.
131 | if(NOT APPLE)
132 | find_package(Threads)
133 | endif()
134 |
135 | # MinGW needs an additional link flag, -mwindows
136 | # It's total link flags should look like -lmingw32 -lSDLmain -lSDL -mwindows
137 | if(MINGW)
138 | set(MINGW32_LIBRARY mingw32 "-mwindows" CACHE STRING "link flags for MinGW")
139 | endif()
140 |
141 | if(SDL2_LIBRARY_TEMP)
142 | # For SDLmain
143 | if(SDL2MAIN_LIBRARY AND NOT SDL2_BUILDING_LIBRARY)
144 | list(FIND SDL2_LIBRARY_TEMP "${SDLMAIN_LIBRARY}" _SDL2_MAIN_INDEX)
145 | if(_SDL2_MAIN_INDEX EQUAL -1)
146 | set(SDL2_LIBRARY_TEMP "${SDLMAIN_LIBRARY}" ${SDL2_LIBRARY_TEMP})
147 | endif()
148 | unset(_SDL2_MAIN_INDEX)
149 | endif()
150 |
151 | # For OS X, SDL uses Cocoa as a backend so it must link to Cocoa.
152 | # CMake doesn't display the -framework Cocoa string in the UI even
153 | # though it actually is there if I modify a pre-used variable.
154 | # I think it has something to do with the CACHE STRING.
155 | # So I use a temporary variable until the end so I can set the
156 | # "real" variable in one-shot.
157 | if(APPLE)
158 | set(SDL2_LIBRARY_TEMP ${SDL2_LIBRARY_TEMP} "-framework Cocoa")
159 | endif()
160 |
161 | # For threads, as mentioned Apple doesn't need this.
162 | # In fact, there seems to be a problem if I used the Threads package
163 | # and try using this line, so I'm just skipping it entirely for OS X.
164 | if(NOT APPLE)
165 | set(SDL2_LIBRARY_TEMP ${SDL2_LIBRARY_TEMP} ${CMAKE_THREAD_LIBS_INIT})
166 | endif()
167 |
168 | # For MinGW library
169 | if(MINGW)
170 | set(SDL2_LIBRARY_TEMP ${MINGW32_LIBRARY} ${SDL2_LIBRARY_TEMP})
171 | endif()
172 |
173 | # Set the final string here so the GUI reflects the final state.
174 | set(SDL2_LIBRARY ${SDL2_LIBRARY_TEMP} CACHE STRING "Where the SDL Library can be found")
175 | endif()
176 |
177 | if(SDL2_INCLUDE_DIR AND EXISTS "${SDL2_INCLUDE_DIR}/SDL2_version.h")
178 | file(STRINGS "${SDL2_INCLUDE_DIR}/SDL2_version.h" SDL2_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL2_MAJOR_VERSION[ \t]+[0-9]+$")
179 | file(STRINGS "${SDL2_INCLUDE_DIR}/SDL2_version.h" SDL2_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL2_MINOR_VERSION[ \t]+[0-9]+$")
180 | file(STRINGS "${SDL2_INCLUDE_DIR}/SDL2_version.h" SDL2_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL2_PATCHLEVEL[ \t]+[0-9]+$")
181 | string(REGEX REPLACE "^#define[ \t]+SDL2_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_VERSION_MAJOR "${SDL2_VERSION_MAJOR_LINE}")
182 | string(REGEX REPLACE "^#define[ \t]+SDL2_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_VERSION_MINOR "${SDL2_VERSION_MINOR_LINE}")
183 | string(REGEX REPLACE "^#define[ \t]+SDL2_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_VERSION_PATCH "${SDL2_VERSION_PATCH_LINE}")
184 | set(SDL2_VERSION_STRING ${SDL2_VERSION_MAJOR}.${SDL2_VERSION_MINOR}.${SDL2_VERSION_PATCH})
185 | unset(SDL2_VERSION_MAJOR_LINE)
186 | unset(SDL2_VERSION_MINOR_LINE)
187 | unset(SDL2_VERSION_PATCH_LINE)
188 | unset(SDL2_VERSION_MAJOR)
189 | unset(SDL2_VERSION_MINOR)
190 | unset(SDL2_VERSION_PATCH)
191 | endif()
192 |
193 | set(SDL2_LIBRARIES ${SDL2_LIBRARY} ${SDL2MAIN_LIBRARY})
194 | set(SDL2_INCLUDE_DIRS ${SDL2_INCLUDE_DIR})
195 |
196 | include(FindPackageHandleStandardArgs)
197 |
198 | FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL
199 | REQUIRED_VARS SDL2_LIBRARY SDL2_INCLUDE_DIR
200 | VERSION_VAR SDL2_VERSION_STRING)
201 |
--------------------------------------------------------------------------------
/cmake/config.h.in:
--------------------------------------------------------------------------------
1 | /** Configuration settings automatically created by CMake */
2 | #define ROOT_DIR "@CMAKE_SOURCE_DIR@/"
3 | #define PROJECT_NAME "@PROJECT_NAME@"
4 | #define PROJECT_VERSION_MAJOR @PROJECT_VERSION_MAJOR@
5 | #define PROJECT_VERSION_MINOR @PROJECT_VERSION_MINOR@
6 |
--------------------------------------------------------------------------------
/docs/interpolation_compare.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BeratE/SoftwareRasterizer/1a6bf1deb532d43f11710caf971e33905916648e/docs/interpolation_compare.png
--------------------------------------------------------------------------------
/docs/man.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BeratE/SoftwareRasterizer/1a6bf1deb532d43f11710caf971e33905916648e/docs/man.png
--------------------------------------------------------------------------------
/docs/rtg.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BeratE/SoftwareRasterizer/1a6bf1deb532d43f11710caf971e33905916648e/docs/rtg.png
--------------------------------------------------------------------------------
/docs/texturing.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BeratE/SoftwareRasterizer/1a6bf1deb532d43f11710caf971e33905916648e/docs/texturing.png
--------------------------------------------------------------------------------
/docs/texturing2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BeratE/SoftwareRasterizer/1a6bf1deb532d43f11710caf971e33905916648e/docs/texturing2.png
--------------------------------------------------------------------------------
/include/smol.h:
--------------------------------------------------------------------------------
1 | #ifndef SMOL_MATRIX_H
2 | #define SMOL_MATRIX_H
3 | /* Simple Matrix Operation Library (smol). Small collection of handy matrix operations. */
4 |
5 | #include
6 | #include
7 |
8 | typedef struct SMOL_Matrix {
9 | size_t nRows;
10 | size_t nCols;
11 | float *fields;
12 | } SMOL_Matrix;
13 |
14 | /* Enums */
15 | enum SMOL_TYPE {SMOL_TYPE_NULL,
16 | SMOL_TYPE_SCALAR,
17 | SMOL_TYPE_MATRIX,
18 | SMOL_TYPE_VECTOR,
19 | SMOL_TYPE_ROW_VECTOR,
20 | SMOL_TYPE_COLUMN_VECTOR};
21 |
22 | enum SMOL_STATUS {SMOL_STATUS_OK,
23 | SMOL_STATUS_NO_VALUE,
24 | SMOL_STATUS_INVALID_TYPE,
25 | SMOL_STATUS_INVALID_ARGUMENTS,
26 | SMOL_STATUS_INCOMPATIBLE_SIZES,
27 | SMOL_STATUS_ARRAY_OUT_OF_BOUNDS};
28 |
29 | /* Macros */
30 | #define SMOL_NULLMATRIX (SMOL_Matrix){.nRows = 0, .nCols = 0, .fields = NULL}
31 |
32 | /* Matrix Allocation */
33 | int SMOL_AllocMatrix(SMOL_Matrix* lhs, size_t nRows, size_t nCols);
34 | int SMOL_RandomMatrix(SMOL_Matrix *lhs, size_t nRows, size_t nCols, size_t mod);
35 | int SMOL_CopyMatrix(SMOL_Matrix *lhs, const SMOL_Matrix *rhs);
36 | int SMOL_CopySubMatrix(SMOL_Matrix *lhs, const SMOL_Matrix *rhs, size_t r0, size_t c0, size_t r1, size_t c1);
37 | int SMOL_EyeMatrix(SMOL_Matrix *lhs, size_t size);
38 | int SMOL_PerspectiveMatrix(SMOL_Matrix* lhs, float fov, float ratio, float near, float far);
39 | int SMOL_CameraMatrix(SMOL_Matrix* lhs, const float* vec3eye, const float* vec3front, const float* vec3up);
40 | int SMOL_RotationMatrix(SMOL_Matrix *lhs, const float* axis, float angle);
41 |
42 | /* Elementary Row Operations */
43 | int SMOL_SwapRows(SMOL_Matrix* lhs, size_t ri, size_t rj);
44 | int SMOL_MultiplyRow(SMOL_Matrix* lhs, size_t row, float scalar);
45 | int SMOL_AddRows(SMOL_Matrix *lhs, size_t dest_row, size_t src_row, float scalar);
46 |
47 | /* Linear Equation Systems */
48 | int SMOL_Echelon(SMOL_Matrix *lhs, size_t *outrank, int reduced);
49 | int SMOL_Invert(SMOL_Matrix *lhs);
50 |
51 | /* Basic Operations */
52 | int SMOL_Fill(SMOL_Matrix *lhs, float value);
53 | int SMOL_Add(SMOL_Matrix *lhs, const SMOL_Matrix *rhs);
54 | int SMOL_AddV(SMOL_Matrix *lhs, size_t count, ...);
55 | int SMOL_Subtract(SMOL_Matrix *lhs, const SMOL_Matrix *rhs);
56 | int SMOL_SubtractV(SMOL_Matrix *lhs, size_t count, ...);
57 | int SMOL_Multiply(SMOL_Matrix *lhs, const SMOL_Matrix *rhsA, const SMOL_Matrix *rhsB);
58 | int SMOL_MultiplyV(SMOL_Matrix *lhs, size_t count, ...);
59 | int SMOL_Transpose(SMOL_Matrix *lhs);
60 | int SMOL_Scale(SMOL_Matrix *lhs, float scalar);
61 |
62 | /* Vector Operations */
63 | int SMOL_VectorNormalize(SMOL_Matrix *lhs);
64 | int SMOL_VectorCross(SMOL_Matrix *lhs, const SMOL_Matrix *rhsA, const SMOL_Matrix *rhsB);
65 | int SMOL_VectorLength(float* lhs, const SMOL_Matrix *vec);
66 | int SMOL_VectorLentghSquare(float *lhs, const SMOL_Matrix *vec);
67 | int SMOL_VectorDot(float* lhs, const SMOL_Matrix *vecA, const SMOL_Matrix *vecB);
68 |
69 | /* Setters and Accessors */
70 | int SMOL_SetField(SMOL_Matrix* lhs, size_t row, size_t col, float value);
71 | int SMOL_SetRow(SMOL_Matrix *lhs, size_t row, const SMOL_Matrix *vec);
72 | int SMOL_SetColumn(SMOL_Matrix *lhs, size_t col, const SMOL_Matrix *vec);
73 | int SMOL_GetField(float *lhs, const SMOL_Matrix* mat, size_t row, size_t col);
74 | int SMOL_GetRow(SMOL_Matrix *lhs, const SMOL_Matrix *mat, size_t row);
75 | int SMOL_GetColumn(SMOL_Matrix *lhs, const SMOL_Matrix *mat, size_t col);
76 |
77 | /* Matrix Manipulation */
78 | int SMOL_AppendRows(SMOL_Matrix* lhs, const SMOL_Matrix *rhs);
79 | int SMOL_AppendColumns(SMOL_Matrix* lhs, const SMOL_Matrix *rhs);
80 |
81 | /* Misc. functions */
82 | int SMOL_TypeOf(const SMOL_Matrix *mat);
83 | void SMOL_PrintMatrix(const SMOL_Matrix* mat);
84 | void SMOL_PrintError(enum SMOL_STATUS status);
85 | void SMOL_Free(SMOL_Matrix* mat);
86 | void SMOL_FreeV(int count, ...);
87 |
88 | #endif // SMOL_MATRIX_H
89 |
--------------------------------------------------------------------------------
/src/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #### Source Cmake file
2 | cmake_minimum_required (VERSION 3.15)
3 |
4 | ### Software Rendering Engine library
5 | set (SRE_TGT sre) # Name of target library
6 | set (SRE_DIR "${SRC_DIR}/sre")
7 | set (SRE_FILES
8 | # Header
9 | ${SRE_DIR}/sre.h
10 | ${SRE_DIR}/sredefs.h
11 | ${SRE_DIR}/sretypes.h
12 | ${SRE_DIR}/srmesh/srmesh.h
13 | # Source
14 | ${SRE_DIR}/sre.c
15 | ${SRE_DIR}/sretexbuffer.c
16 | ${SRE_DIR}/srerasterizer.c
17 | ${SRE_DIR}/srmesh/srmesh.c)
18 |
19 |
20 | ### Application files
21 | set (APP_FILES
22 | # Header
23 | # Source
24 | ${SRC_DIR}/main.c
25 | ${SRC_DIR}/shader.c)
26 |
27 | ### Target libraries
28 | add_library(${SRE_TGT} ${SRE_FILES})
29 |
30 | ### Final target executable
31 | add_executable (${EXECUTABLE_NAME} ${APP_FILES})
32 | target_link_libraries(${EXECUTABLE_NAME} ${LIBS} ${SRE_TGT})
33 |
34 | # Unit testing
35 | enable_testing()
36 | add_subdirectory(test)
37 |
--------------------------------------------------------------------------------
/src/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include "SDL2/SDL.h"
5 | #include
6 | #include "config.h"
7 | #include "sre/sre.h"
8 | #include "sre/srmesh/srmesh.h"
9 |
10 | #define STB_IMAGE_IMPLEMENTATION
11 | #include "stb_image.h"
12 |
13 | /* Global state */
14 | SDL_Window *_window = NULL;
15 | SDL_Renderer *_renderer = NULL;
16 |
17 | unsigned int _texWidth = 400;
18 | unsigned int _texHeight = 400;
19 | SDL_Texture* _texture = NULL;
20 |
21 | const int NUM_CUBES = 1;
22 | SMOL_Matrix _cubeMats[1];
23 | size_t _frame = 0;
24 | double _runTime = 0;
25 | Uint64 _lastTime, _currTime;
26 |
27 | SMOL_Matrix _perspectiveMat;
28 | SMOL_Matrix _viewMat;
29 | SMOL_Matrix _modelMat;
30 |
31 | SR_TexBuffer2D _image;
32 |
33 | size_t _vDataCount, _indexCount;
34 | size_t _theVao;
35 | /* ~/Global state/~ */
36 |
37 |
38 | /* Function definitions */
39 | void vertexShader(size_t count, SR_Vecf *attribs, SR_Vec4f *vPos);
40 | void fragmentShader(size_t count, SR_Vecf *attribs, SR_Vec4f *oColor);
41 | /* ~/Function definitions/~ */
42 |
43 |
44 | static void sdl_die(const char * message)
45 | /* Print Error Message and Die. */
46 | {
47 | fprintf(stderr, "%s: %s.\n", message, SDL_GetError());
48 | exit(2);
49 | }
50 |
51 | void init_window()
52 | /* Initialize the window display and screen texture as well as the required renderer.
53 | * Initialize basic states and configurations of said resources. */
54 | {
55 | if (SDL_Init(SDL_INIT_VIDEO) < 0)
56 | sdl_die("Error initializing SDL");
57 | atexit(SDL_Quit);
58 |
59 | _window = SDL_CreateWindow( PROJECT_NAME, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
60 | 1024, 1024, SDL_WINDOW_SHOWN);
61 |
62 | if (_window == NULL)
63 | sdl_die("Error setting video mode");
64 |
65 | _renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_ACCELERATED);
66 |
67 | SDL_RendererInfo info;
68 | SDL_GetRendererInfo(_renderer, &info);
69 | printf("Renderer: %s\n", info.name);
70 |
71 | _texture = SDL_CreateTexture(_renderer,
72 | SDL_PIXELFORMAT_ABGR8888,
73 | SDL_TEXTUREACCESS_STREAMING, _texWidth, _texHeight);
74 |
75 | SDL_SetRenderDrawColor(_renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
76 | }
77 |
78 | void init ()
79 | {
80 | init_window();
81 | SR_Init();
82 | SR_SetViewPort(_texWidth, _texHeight);
83 |
84 | SMOL_PerspectiveMatrix(&_perspectiveMat, 90, _texWidth/_texHeight, 0.5, 100);
85 | SMOL_CameraMatrix(&_viewMat,
86 | (float[]){0.0, 0.0, 10.0},
87 | (float[]){0.0, 0.0, 0.0},
88 | (float[]){0.0, 1.0, 0.0});
89 |
90 | for (int i = 0; i < NUM_CUBES; i++) {
91 | SMOL_EyeMatrix(&_cubeMats[i], 4);
92 | /* SMOL_SetField(&_cubeMats[i], 0, 3, (rand()%7) * ((rand()%2) ? 1.0 : -1.0)); */
93 | /* SMOL_SetField(&_cubeMats[i], 1, 3, (rand()%7) * ((rand()%2) ? 1.0 : -1.0)); */
94 | /* SMOL_SetField(&_cubeMats[i], 2, 3, (rand()%20)); */
95 | }
96 |
97 | _theVao = SR_GenVertexArray();
98 | SR_BindVertexArray(_theVao);
99 |
100 |
101 | // Load Mesh
102 | SRM_Mesh mesh;
103 | SRM_LoadMesh(&mesh, "/home/berat/Projects/assets/Models/sign.obj");
104 |
105 | // Collect Indexed Mesh Vertex Data
106 | size_t vertexCount;
107 | SRM_IndexedVertexData(&mesh, NULL, NULL, &vertexCount);
108 |
109 | _vDataCount = vertexCount * 8;
110 | _indexCount = mesh.nFaces * 3;
111 | float vertexData[_vDataCount];
112 | size_t indices[_indexCount];
113 |
114 | SRM_IndexedVertexData(&mesh, vertexData, indices, NULL);
115 |
116 | SR_SetBufferData(SR_BT_VERTEX_BUFFER, vertexData, sizeof(vertexData));
117 | SR_SetBufferData(SR_BT_INDEX_BUFFER, indices, sizeof(indices));
118 |
119 | SRM_DeleteMesh(&mesh);
120 |
121 | // Vertex Input
122 | SR_SetVertexAttributeCount(3);
123 | SR_SetVertexAttribute(0, 3, sizeof(float)*8, 0); // Vertices
124 | SR_SetVertexAttribute(1, 2, sizeof(float)*8, sizeof(float)*3); // UV
125 | SR_SetVertexAttribute(2, 3, sizeof(float)*8, sizeof(float)*5); // Normals
126 | // Vertex Output
127 | SR_SetVertexStageOutputCount(2);
128 |
129 | SR_BindShader(SR_ST_VERTEX_SHADER, &vertexShader);
130 | SR_BindShader(SR_ST_FRAGMENT_SHADER, &fragmentShader);
131 |
132 |
133 | int width, height, nChannels;
134 | _image.values = stbi_load("/home/berat/Projects/assets/Textures/sign.png",
135 | &width, &height, &nChannels, 4);
136 | _image.width = width;
137 | _image.height = height;
138 | _image.format = SR_TEX_FORMAT_RGBA8;
139 | }
140 |
141 | int main ()
142 | {
143 | printf("\n%s Version %d.%d\n", PROJECT_NAME, PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR);
144 |
145 | init();
146 |
147 | SDL_Event event;
148 | int isRunning = 1;
149 |
150 | float rotation[2] = {0.0};
151 | SMOL_Matrix translation;
152 | SMOL_EyeMatrix(&translation, 4);
153 |
154 | // Main loop
155 | _lastTime = SDL_GetPerformanceCounter();
156 | _currTime = SDL_GetPerformanceCounter();
157 | double deltaTime = 0;
158 |
159 | while (isRunning) {
160 | _lastTime = _currTime;
161 | _currTime = SDL_GetPerformanceCounter();
162 | deltaTime = (_currTime - _lastTime) / (double)SDL_GetPerformanceFrequency();
163 |
164 | while (SDL_PollEvent(&event)) {
165 | if (event.type == SDL_QUIT) {
166 | isRunning = 0;
167 | break;
168 | }
169 | if (event.type == SDL_KEYDOWN) {
170 | if (event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) {
171 | isRunning = 0;
172 | break;
173 | }
174 | // Rotation
175 | const float rotVel = 4.0;
176 | const float posVel = 0.55;
177 | if (event.key.keysym.scancode == SDL_SCANCODE_UP)
178 | rotation[0] += rotVel;
179 | if (event.key.keysym.scancode == SDL_SCANCODE_DOWN)
180 | rotation[0] -= rotVel;
181 | if (event.key.keysym.scancode == SDL_SCANCODE_RIGHT)
182 | rotation[1] += rotVel;
183 | if (event.key.keysym.scancode == SDL_SCANCODE_LEFT)
184 | rotation[1] -= rotVel;
185 | // Translation
186 | if (event.key.keysym.scancode == SDL_SCANCODE_W)
187 | SMOL_SetField(&translation, 2, 3, translation.fields[11] + posVel);
188 | if (event.key.keysym.scancode == SDL_SCANCODE_S)
189 | SMOL_SetField(&translation, 2, 3, translation.fields[11] - posVel);
190 | if (event.key.keysym.scancode == SDL_SCANCODE_A)
191 | SMOL_SetField(&translation, 0, 3, translation.fields[3] + posVel);
192 | if (event.key.keysym.scancode == SDL_SCANCODE_D)
193 | SMOL_SetField(&translation, 0, 3, translation.fields[3] - posVel);
194 | }
195 | }
196 |
197 | // Rendering
198 | SR_Clear(SR_RTB_COLOR_BUFFER_BIT | SR_RTB_DEPTH_BUFFER_BIT);
199 |
200 | double t = _currTime/6000000.0;
201 | for (int i = 0; i < NUM_CUBES; i++) {
202 | SMOL_Matrix rotX, rotY;
203 | SMOL_RotationMatrix(&rotX, (float[]){1.0, 0.0, 0.0}, (rotation[0])*(M_PI/180));
204 | SMOL_RotationMatrix(&rotY, (float[]){0.0, 1.0, 0.0}, (rotation[1])*(M_PI/180));
205 |
206 | SMOL_MultiplyV(&_modelMat, 4, &_cubeMats[i], &rotX, &rotY, &translation);
207 |
208 | SR_DrawArray(SR_PT_TRIANGLES, _indexCount, 0);
209 |
210 | SMOL_FreeV(3, &rotX, &rotY, &_modelMat);
211 | }
212 |
213 | // Blit texture content to the screen
214 | SDL_UpdateTexture(_texture, NULL,
215 | &(SR_GetFrameBuffer().color.values[0]), _texWidth * 4);
216 | SDL_RenderCopyEx(_renderer, _texture, NULL, NULL, 0, NULL, SDL_FLIP_VERTICAL);
217 | SDL_RenderPresent(_renderer);
218 |
219 | _frame++;
220 | _runTime += deltaTime;
221 | }
222 |
223 | printf("\nNumber of frames: %lu\nTotal Runtime %f\n", _frame, _runTime);
224 | printf("Average FPS: %f\n\n", 1.0 / (_runTime / _frame));
225 |
226 | // Shutdown
227 |
228 | // Free matrices
229 | SMOL_Free(&translation);
230 | SMOL_FreeV(2, &_perspectiveMat, &_viewMat);
231 | for (int i = 0; i < NUM_CUBES; i++) {
232 | SMOL_Free(&_cubeMats[i]);
233 | }
234 |
235 | stbi_image_free(_image.values);
236 |
237 | SR_Shutdown();
238 | SDL_DestroyRenderer(_renderer);
239 | SDL_DestroyWindow(_window);
240 | SDL_Quit();
241 |
242 | return 0;
243 | }
244 |
245 |
--------------------------------------------------------------------------------
/src/shader.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include "sre/sre.h"
4 | #include "sre/sretypes.h"
5 |
6 | /* Global state */
7 | extern SMOL_Matrix _perspectiveMat;
8 | extern SMOL_Matrix _viewMat;
9 | extern SMOL_Matrix _modelMat;
10 |
11 | extern SR_TexBuffer2D _image;
12 | /* ~/Global state/~ */
13 |
14 | /* Shader functions */
15 | void vertexShader(size_t count, SR_Vecf *attribs, SR_Vec4f *vPos)
16 | {
17 | if (count < 3)
18 | return;
19 |
20 | // Vertex Input
21 | SR_Vec3f aPos = attribs[0].vec3f;
22 | SR_Vec2f aUV = attribs[1].vec2f;
23 | SR_Vec3f aNormal = attribs[2].vec3f;
24 |
25 | SMOL_Matrix p = (SMOL_Matrix){.nRows = 4, .nCols = 1, .fields = (float*)&aPos};
26 | p.fields[3] = 1.0;
27 |
28 | SMOL_Matrix mvp;
29 | SMOL_MultiplyV(&mvp, 3, &_modelMat, &_viewMat, &_perspectiveMat);
30 |
31 | // Set Vertex Position
32 | SMOL_Multiply(&p, &mvp, &p);
33 | memcpy(vPos, p.fields, sizeof(float)*4);
34 |
35 | // Set Vertex Output
36 | SR_SetVertexStageOutput(0, (SR_Vecf*)&aUV);
37 | SR_SetVertexStageOutput(1, (SR_Vecf*)&aNormal);
38 |
39 | SMOL_FreeV(2, &p, &mvp);
40 | }
41 |
42 |
43 | void fragmentShader(size_t count, SR_Vecf *attribs, SR_Vec4f *fColor)
44 | {
45 | if (count < 2)
46 | return;
47 |
48 | SR_Vec2f aUV = attribs[0].vec2f;
49 | SR_Vec3f aNormal = attribs[1].vec3f;
50 | uint8_t c[4];
51 | //SR_TexBufferRead(&_image, &c, aUV.x*_image.width, aUV.y*_image.height);
52 | SR_TexBufferSample(&_image, &c, aUV.x*_image.width, aUV.y*_image.height);
53 | // uv coordinates in [0, 1]
54 | fColor->x = c[0]/255.0;
55 | fColor->y = c[1]/255.0;
56 | fColor->z = c[2]/255.0;
57 | fColor->w = c[3]/255.0;
58 | //*fColor = (SR_Vec4f){.x=1.0, .y=0.0, .z=0.0, .w=1.0};
59 | }
60 | /* ~/Shader functions/~ */
61 |
--------------------------------------------------------------------------------
/src/sre/sre.c:
--------------------------------------------------------------------------------
1 | #include "sre.h"
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | /* ~Global State~ */
8 | SR_Pipeline __sr_pipeline; // Currently bound shader pipeline
9 |
10 | /* ~/Global State/~ */
11 |
12 | /* ~Local State ~*/
13 | static SR_FrameBuffer __sr_framebuffer; // Currently bound framebuffer
14 |
15 | // Linked list of Vertex Array objects
16 | static size_t __sr_nextListIndex;
17 | static struct listVAO {
18 | size_t index;
19 | SR_VertexArray* pArrayObject;
20 | struct listVAO* pNext;
21 | } *__sr_listHead;
22 |
23 | static SR_VertexArray *__sr_pCurrVAO; // Pointer to currently bound VAO
24 |
25 | /* ~Local State ~*/
26 |
27 |
28 | /* Static functions */
29 |
30 | static inline void collectVertexAttribs(SR_Vecf *attribs, size_t elementIndex)
31 | /* Collect Vertex Attributes from the currently bound buffer,
32 | * starting at the given element index. */
33 | {
34 | for (size_t ai = 0; ai < __sr_pCurrVAO->attributesCount; ai++) {
35 | const SR_VertexAttribute va = __sr_pCurrVAO->attributes[ai];
36 | // Pointer to vertex attribute location
37 | const uint8_t *pVertexData = ((uint8_t *)__sr_pCurrVAO->vertexBuffer)
38 | + va.offset + (elementIndex * va.stride);
39 |
40 | switch (va.count) {
41 | case 4: attribs[ai].vec4f.w = *(((float*)pVertexData)+3); /* FALLTHRU */
42 | case 3: attribs[ai].vec3f.z = *(((float*)pVertexData)+2); /* FALLTHRU */
43 | case 2: attribs[ai].vec2f.y = *(((float*)pVertexData)+1); /* FALLTHRU */
44 | case 1: attribs[ai].vec1f.x = *(((float*)pVertexData)+0);
45 | break;
46 | }
47 | }
48 | }
49 |
50 | static inline void perspectiveDivide(SR_Vec4f *p)
51 | {
52 | if (p->w != 0) {
53 | p->x /= p->w;
54 | p->y /= p->w;
55 | }
56 | }
57 |
58 | /* ~/Static functions/~ */
59 |
60 |
61 | /*
62 | * Setup, Shutdown
63 | */
64 |
65 | void SR_Init()
66 | /* Initialize the software rasterization engine. */
67 | {
68 | SR_SetViewPort(0, 0);
69 |
70 | __sr_pipeline = (SR_Pipeline){.vertexShader = NULL,
71 | .fragmentShader = NULL,
72 | .currVertexStageOutput = NULL,
73 | .pVertexStageOutput = NULL,
74 | .vertexStageOutputCount = 0};
75 |
76 | __sr_listHead = NULL;
77 | __sr_pCurrVAO = NULL;
78 | __sr_nextListIndex = 0;
79 | }
80 |
81 | void SR_Shutdown()
82 | /* Clean up resources. */
83 | {
84 | // Free Framebuffer
85 | SR_TexBufferFree(&__sr_framebuffer.color);
86 | SR_TexBufferFree(&__sr_framebuffer.depth);
87 |
88 | if (__sr_pipeline.currVertexStageOutput != NULL)
89 | free(__sr_pipeline.currVertexStageOutput);
90 |
91 | // Free Vertex Array Data
92 | struct listVAO *listp = __sr_listHead;
93 | while (listp != NULL) {
94 | if (listp->pArrayObject != NULL) {
95 | free(listp->pArrayObject->indexBuffer);
96 | free(listp->pArrayObject->vertexBuffer);
97 | free(listp->pArrayObject->attributes);
98 | free(listp->pArrayObject);
99 | listp->pArrayObject = NULL;
100 | }
101 | struct listVAO *next = listp->pNext;
102 | free(listp);
103 | listp = next;
104 | }
105 | }
106 |
107 |
108 | /*
109 | * Framebuffer
110 | */
111 |
112 | SR_FrameBuffer SR_GetFrameBuffer()
113 | /* Temporary solution. */
114 | {
115 | return __sr_framebuffer;
116 | }
117 |
118 | void SR_SetViewPort(int w, int h)
119 | /* Set global viewport state parameters. */
120 | {
121 | SR_TexBufferFree(&__sr_framebuffer.color);
122 | SR_TexBufferFree(&__sr_framebuffer.depth);
123 | __sr_framebuffer.color = SR_TexBufferCreate(w, h, SR_TEX_FORMAT_RGBA8);
124 | __sr_framebuffer.depth = SR_TexBufferCreate(w, h, SR_TEX_FORMAT_F32);
125 | }
126 |
127 | void SR_Clear(enum SR_RENDER_TARGET_BIT buffermask)
128 | /* Clear the target buffer with zero-values. */
129 | {
130 | if (buffermask & SR_RTB_COLOR_BUFFER_BIT) {
131 | int clearVal = 0;
132 | SR_TexBufferClear(&__sr_framebuffer.color, &clearVal);
133 | }
134 | if (buffermask & SR_RTB_DEPTH_BUFFER_BIT) {
135 | float clearVal = FLT_MAX;
136 | SR_TexBufferClear(&__sr_framebuffer.depth, &clearVal);
137 | }
138 | }
139 |
140 |
141 | /*
142 | * Vertex Array Objects
143 | */
144 |
145 | size_t SR_GenVertexArray()
146 | /* Generate a new vertex array object and return the object handle. */
147 | {
148 | size_t returnindex;
149 | if (__sr_listHead == NULL) {
150 | __sr_listHead = malloc(sizeof(struct listVAO));
151 | __sr_listHead->index = ++__sr_nextListIndex;
152 | __sr_listHead->pNext = NULL;
153 |
154 | __sr_listHead->pArrayObject = malloc(sizeof(SR_VertexArray));
155 | __sr_listHead->pArrayObject->indexBuffer = NULL;
156 | __sr_listHead->pArrayObject->vertexBuffer = NULL;
157 | __sr_listHead->pArrayObject->attributes = NULL;
158 | __sr_listHead->pArrayObject->attributesCount = 0;
159 |
160 | returnindex = __sr_listHead->index;
161 | } else {
162 | struct listVAO *listp = __sr_listHead;
163 | while ((listp->pNext != NULL) && (listp = listp->pNext))
164 | ;
165 |
166 | listp->pNext = malloc(sizeof(struct listVAO));
167 | listp->pNext->index = ++__sr_nextListIndex;
168 | listp->pNext->pNext = NULL;
169 |
170 | listp->pNext->pArrayObject = malloc(sizeof(SR_VertexArray));
171 | listp->pNext->pArrayObject->indexBuffer = NULL;
172 | listp->pNext->pArrayObject->vertexBuffer = NULL;
173 | listp->pNext->pArrayObject->attributes = NULL;
174 | listp->pNext->pArrayObject->attributesCount = 0;
175 |
176 | returnindex = listp->pNext->index;
177 | }
178 | return returnindex;
179 | }
180 |
181 | void SR_DestroyVertexArray(size_t handle)
182 | /* Destroy the vertex shader indexed by the given handle.*/
183 | {
184 | if (__sr_listHead == NULL || handle > __sr_nextListIndex)
185 | return;
186 |
187 | struct listVAO *listp = __sr_listHead;
188 | struct listVAO *nextp = __sr_listHead->pNext;
189 | if (__sr_listHead->index == handle) {
190 | __sr_listHead = nextp;
191 | free(listp->pArrayObject->indexBuffer);
192 | free(listp->pArrayObject->vertexBuffer);
193 | free(listp->pArrayObject->attributes);
194 | free(listp->pArrayObject);
195 | free(listp);
196 | } else {
197 | while (nextp != NULL && nextp->index != handle) {
198 | listp = nextp;
199 | nextp = nextp->pNext;
200 | }
201 | }
202 | }
203 |
204 | void SR_BindVertexArray(size_t handle)
205 | /* Set the vertex array object identified by handle
206 | * as the currently bound vao. */
207 | {
208 | struct listVAO *listp = __sr_listHead;
209 | while ((listp != NULL) && (listp->index != handle) && (listp = listp->pNext));
210 | ;
211 | if (listp != NULL)
212 | __sr_pCurrVAO = listp->pArrayObject;
213 | else
214 | __sr_pCurrVAO = NULL;
215 | }
216 |
217 | void SR_SetBufferData(enum SR_BUFFER_TYPE target, void *data, size_t size)
218 | /* Set the vertex buffer data of the currently bound vao. */
219 | {
220 | if (__sr_pCurrVAO == NULL)
221 | return;
222 |
223 | void **buffer = NULL;
224 | switch (target) {
225 | case SR_BT_VERTEX_BUFFER:
226 | __sr_pCurrVAO->vertexBufferSize = size;
227 | buffer = (void **)&__sr_pCurrVAO->vertexBuffer;
228 | break;
229 | case SR_BT_INDEX_BUFFER:
230 | __sr_pCurrVAO->indexBufferSize = size;
231 | buffer = (void **)&__sr_pCurrVAO->indexBuffer;
232 | break;
233 | }
234 |
235 | if (buffer != NULL) {
236 | (*buffer) = malloc(size);
237 | memcpy((*buffer), data, size);
238 | }
239 | }
240 |
241 |
242 | /*
243 | * Vertex Attributes
244 | */
245 |
246 | void SR_SetVertexAttributeCount(size_t count)
247 | /* Set the number of vertex attributes passed in the currently bound vao. */
248 | {
249 | if (__sr_pCurrVAO == NULL)
250 | return;
251 | if (__sr_pCurrVAO->attributes != NULL)
252 | free(__sr_pCurrVAO->attributes);
253 |
254 | __sr_pCurrVAO->attributes = malloc(sizeof(SR_VertexAttribute) * count);
255 | __sr_pCurrVAO->attributesCount = count;
256 | }
257 |
258 | void SR_SetVertexAttribute(size_t index, size_t count,
259 | size_t stride, size_t offset)
260 | /* Set the pointer to a vertex attribute in the vertex buffer of the
261 | currently bound vao. */
262 | {
263 | if (__sr_pCurrVAO == NULL || index >= __sr_pCurrVAO->attributesCount)
264 | return;
265 |
266 | __sr_pCurrVAO->attributes[index] =
267 | (SR_VertexAttribute){.count = count, .stride = stride, .offset = offset};
268 | }
269 |
270 |
271 | /*
272 | * Pipeline
273 | */
274 |
275 | void SR_BindShader(enum SR_SHADER_TYPE shader_type, SR_ShaderCB shader)
276 | /* Set the callback to the shader function of the given type. */
277 | {
278 | switch (shader_type) {
279 | case SR_ST_VERTEX_SHADER:
280 | __sr_pipeline.vertexShader = shader;
281 | break;
282 | case SR_ST_FRAGMENT_SHADER:
283 | __sr_pipeline.fragmentShader = shader;
284 | break;
285 | };
286 | }
287 |
288 | void SR_SetVertexStageOutputCount(size_t count)
289 | /* Set the number of output values of the vertex shader stage. */
290 | {
291 | if (__sr_pipeline.currVertexStageOutput != NULL)
292 | free(__sr_pipeline.currVertexStageOutput);
293 |
294 | __sr_pipeline.vertexStageOutputCount = count;
295 | __sr_pipeline.currVertexStageOutput = malloc(count * sizeof(SR_Vecf));
296 | }
297 |
298 | void SR_SetVertexStageOutput(size_t index, SR_Vecf *value)
299 | /* Set the value of the vertex stage output at the given index. */
300 | {
301 | if (__sr_pipeline.currVertexStageOutput == NULL)
302 | return;
303 |
304 | memcpy(&__sr_pipeline.currVertexStageOutput[index], value, sizeof(*value));
305 | }
306 |
307 | void SR_DrawArray(enum SR_PRIMITIVE_TYPE prim_type,
308 | size_t count, size_t startindex)
309 | /* Initiate the pipeline. */
310 | {
311 | if (__sr_pCurrVAO == NULL || __sr_pCurrVAO->indexBuffer == NULL ||
312 | __sr_pCurrVAO->vertexBuffer == NULL || __sr_pipeline.vertexShader == NULL)
313 | return;
314 |
315 | const size_t indexBufferCount =
316 | __sr_pCurrVAO->indexBufferSize / sizeof(*__sr_pCurrVAO->indexBuffer);
317 | if (startindex + count > indexBufferCount) // Index out of bounds
318 | return;
319 |
320 | // Determine appropiate write function for primitive type
321 | SR_Write cbWrite = NULL;
322 | switch (prim_type) {
323 | // case SR_POINTS: cbWrite = &SR_WritePixel; break;
324 | case SR_PT_LINES:
325 | cbWrite = &SR_WriteLine;
326 | break;
327 | case SR_PT_TRIANGLES:
328 | cbWrite = &SR_WriteTriangle;
329 | break;
330 | default:
331 | break;
332 | }
333 | if (cbWrite == NULL)
334 | return;
335 |
336 | const size_t VERT_PER_PRIM = prim_type;
337 | const size_t VERT_OUTPUT_N = __sr_pipeline.vertexStageOutputCount;
338 | const size_t WIDTH = __sr_framebuffer.color.width;
339 | const size_t HEIGHT = __sr_framebuffer.color.height;
340 |
341 | // Per Patch
342 | SR_VecScreen patchScreenCoords[VERT_PER_PRIM];
343 | SR_Vec4f patchVertPos[VERT_PER_PRIM];
344 | SR_Vecf patchVertStageOutput[VERT_PER_PRIM][VERT_OUTPUT_N];
345 | __sr_pipeline.pVertexStageOutput = (SR_Vecf *)patchVertStageOutput;
346 | //Per Vertex
347 | SR_Vecf vertAttribs[__sr_pCurrVAO->attributesCount];
348 |
349 | // Vertex iteration
350 | for (size_t i = 0; i < count; i++) {
351 | const size_t patchVertNum = i % VERT_PER_PRIM;
352 | const size_t elementIndex = __sr_pCurrVAO->indexBuffer[startindex + i];
353 |
354 | // Collect vertex attributes from buffer
355 | collectVertexAttribs(vertAttribs, elementIndex);
356 |
357 | // Vertex assembly
358 | SR_Vec4f vPos = (SR_Vec4f){0, 0, 0, 0};
359 | (*__sr_pipeline.vertexShader)(__sr_pCurrVAO->attributesCount,
360 | vertAttribs, &vPos);
361 |
362 | // Collect vertex stage output
363 | memcpy(&patchVertStageOutput[patchVertNum][0],
364 | __sr_pipeline.currVertexStageOutput,
365 | sizeof(SR_Vecf) * VERT_OUTPUT_N);
366 |
367 | // Perspective divide
368 | perspectiveDivide(&vPos);
369 |
370 | // Collect patch vertices
371 | patchVertPos[patchVertNum] = vPos;
372 | if (patchVertNum == (VERT_PER_PRIM - 1)) {
373 | // Viewport transform;
374 | for(size_t k = 0; k < VERT_PER_PRIM; k++) {
375 | patchScreenCoords[k].x = patchVertPos[k].x * WIDTH/2 + WIDTH/2;
376 | patchScreenCoords[k].y = patchVertPos[k].y * HEIGHT/2 + HEIGHT/2;
377 | patchScreenCoords[k].z = patchVertPos[k].z;
378 | }
379 |
380 | // Rasterization
381 | (*cbWrite)(&__sr_framebuffer, patchScreenCoords, &__sr_pipeline);
382 | }
383 | }
384 |
385 | // Cleanup
386 | __sr_pipeline.pVertexStageOutput = NULL;
387 | }
388 |
--------------------------------------------------------------------------------
/src/sre/sre.h:
--------------------------------------------------------------------------------
1 | #ifndef SRE_H
2 | #define SRE_H
3 | /* Software rasterization pipeline. */
4 |
5 | #include "sredefs.h"
6 | #include "sretypes.h"
7 |
8 | // Setup, Shutdown
9 | void SR_Init();
10 | void SR_Shutdown();
11 |
12 | // Framebuffers
13 | SR_FrameBuffer SR_GetFrameBuffer();
14 | void SR_SetViewPort(int w, int h);
15 | void SR_Clear(enum SR_RENDER_TARGET_BIT buffermask);
16 |
17 | // Vertex Array Objects
18 | size_t SR_GenVertexArray();
19 | void SR_BindVertexArray(size_t handle);
20 | void SR_DestroyVertexArray(size_t handle);
21 | void SR_SetBufferData(enum SR_BUFFER_TYPE target, void* data, size_t size);
22 |
23 | // Vertex Attributes
24 | void SR_SetVertexAttributeCount(size_t count);
25 | void SR_SetVertexAttribute(size_t index, size_t count, size_t stride, size_t offset);
26 |
27 | // Pipeline
28 | void SR_BindShader(enum SR_SHADER_TYPE shader_type, SR_ShaderCB shader);
29 | void SR_SetVertexStageOutputCount(size_t count);
30 | void SR_SetVertexStageOutput(size_t index, SR_Vecf* value);
31 | void SR_DrawArray(enum SR_PRIMITIVE_TYPE type, size_t count, size_t startxindex);
32 |
33 | // Texture buffers
34 | SR_TexBuffer2D SR_TexBufferCreate(size_t width, size_t height, uint16_t format);
35 | SR_TexBuffer2D SR_TexBufferCopy(const SR_TexBuffer2D* buffer);
36 | void SR_TexBufferRead(const SR_TexBuffer2D *buffer, void* outValue, size_t x, size_t y);
37 | void SR_TexBufferSample(const SR_TexBuffer2D *buffer, void* outValue, float x, float y);
38 | void SR_TexBufferWrite(SR_TexBuffer2D *buffer, const void *value, size_t x, size_t y);
39 | void SR_TexBufferClear(SR_TexBuffer2D *buffer, const void *value);
40 | void SR_TexBufferFree(SR_TexBuffer2D *buffer);
41 | size_t SR_TexBufferSize(const SR_TexBuffer2D *buffer);
42 | size_t SR_TexBufferFormatSize(const SR_TexBuffer2D *buffer);
43 | uint16_t SR_TexBufferFormatType(const SR_TexBuffer2D *buffer);
44 | uint16_t SR_TexBufferFormatNComps(const SR_TexBuffer2D *buffer);
45 | uint16_t SR_TexBufferFormatNBytes(const SR_TexBuffer2D *buffer);
46 |
47 | // Rasterization
48 | void SR_WritePixel(SR_FrameBuffer *buffer, const SR_VecScreen *pos, const void* value);
49 | void SR_WriteLine(SR_FrameBuffer *buffer, const SR_VecScreen *pos, const SR_Pipeline* pipeline);
50 | void SR_WriteTriangle(SR_FrameBuffer *buffer, const SR_VecScreen *pos, const SR_Pipeline* pipeline);
51 |
52 | #endif // SRE_H
53 |
--------------------------------------------------------------------------------
/src/sre/sredefs.h:
--------------------------------------------------------------------------------
1 | /* Common and shared definitions. */
2 |
3 | #ifndef SREDEFS_H
4 | #define SREDEFS_H
5 |
6 | #include
7 | #include
8 |
9 | /* Macros */
10 | #define MIN3(a, b, c) (a < b) ? (a < c ? a : c) : (b < c ? b : c)
11 | #define MAX3(a, b, c) (a > b) ? (a > c ? a : c) : (b > c ? b : c)
12 | #define CLAMP(x, a, b) (x < b) ? ((x < a) ? a : x) : b // clamp x between (a, b)
13 | /* ~/Macros/~ */
14 |
15 | // Common Constants and Enumerations
16 |
17 | enum SR_PRIMITIVE_TYPE {
18 | SR_PT_POINTS = 1,
19 | SR_PT_LINES,
20 | SR_PT_TRIANGLES,
21 | SR_PT_QUADS
22 | };
23 |
24 | enum SR_BUFFER_TYPE {
25 | SR_BT_VERTEX_BUFFER,
26 | SR_BT_INDEX_BUFFER
27 | };
28 |
29 | enum SR_SHADER_TYPE{
30 | SR_ST_VERTEX_SHADER,
31 | SR_ST_FRAGMENT_SHADER
32 | };
33 |
34 | enum SR_RENDER_TARGET_BIT {
35 | SR_RTB_COLOR_BUFFER_BIT = 0x1,
36 | SR_RTB_DEPTH_BUFFER_BIT = 0x2
37 | };
38 |
39 |
40 | // Texture Format
41 | enum SR_TEXTURE_FORMAT_MASK {
42 | SR_TF_MASK_TYPE = 0xF000,
43 | SR_TF_MASK_NCOMPS = 0x00F0,
44 | SR_TF_MASK_NBYTES = 0x000F,
45 | };
46 |
47 | enum SR_TEXTURE_FORMAT_TYPE {
48 | SR_TF_TYPE_UINT = 0x0000,
49 | SR_TF_TYPE_FLOAT = 0x1000,
50 | };
51 |
52 | enum SR_TEXTURE_FORMAT {
53 | /* Bytecoded Format = [ Type | N Comp. | 0 | Num Bytes] */
54 | // Composite Integer Types - 0
55 | SR_TEX_FORMAT_NULL = 0,
56 | SR_TEX_FORMAT_R8 = SR_TF_TYPE_UINT | (1 << 4) | sizeof(uint8_t),
57 | SR_TEX_FORMAT_RG8 = SR_TF_TYPE_UINT | (2 << 4) | sizeof(uint8_t),
58 | SR_TEX_FORMAT_RGB8 = SR_TF_TYPE_UINT | (3 << 4) | sizeof(uint8_t),
59 | SR_TEX_FORMAT_RGBA8 = SR_TF_TYPE_UINT | (4 << 4) | sizeof(uint8_t),
60 | SR_TEX_FORMAT_R16 = SR_TF_TYPE_UINT | (1 << 4) | sizeof(uint16_t),
61 | SR_TEX_FORMAT_RG16 = SR_TF_TYPE_UINT | (2 << 4) | sizeof(uint16_t),
62 | SR_TEX_FORMAT_RGB16 = SR_TF_TYPE_UINT | (3 << 4) | sizeof(uint16_t),
63 | SR_TEX_FORMAT_RGBA16 = SR_TF_TYPE_UINT | (4 << 4) | sizeof(uint16_t),
64 | // Floating Point Types - 1
65 | SR_TEX_FORMAT_F32 = SR_TF_TYPE_FLOAT | (1 << 4) | sizeof(float),
66 | };
67 |
68 |
69 | #endif // SREDEFS_H
70 |
--------------------------------------------------------------------------------
/src/sre/srerasterizer.c:
--------------------------------------------------------------------------------
1 | #include "sre.h"
2 | #include
3 | #include
4 | #include
5 |
6 | /* Static functions */
7 |
8 | static inline void mixAttribsTriangle(SR_Vecf *attribs, const SR_VecScreen *fpos, const SR_VecScreen *pos,
9 | const float *baryc, const SR_Pipeline *pipeline)
10 | {
11 | const size_t ATTRIB_COUNT = pipeline->vertexStageOutputCount;
12 | for (size_t i = 0; i < ATTRIB_COUNT; i++) {
13 | const SR_Vec4f aiV0 = pipeline->pVertexStageOutput[(ATTRIB_COUNT*0) + i].vec4f;
14 | const SR_Vec4f aiV1 = pipeline->pVertexStageOutput[(ATTRIB_COUNT*1) + i].vec4f;
15 | const SR_Vec4f aiV2 = pipeline->pVertexStageOutput[(ATTRIB_COUNT*2) + i].vec4f;
16 |
17 | attribs[i] = (SR_Vecf)(SR_Vec4f){
18 | .x = fpos->z*(baryc[0]*(aiV0.x/pos[0].z) + baryc[1]*(aiV1.x/pos[1].z) + baryc[2]*(aiV2.x/pos[2].z)),
19 | .y = fpos->z*(baryc[0]*(aiV0.y/pos[0].z) + baryc[1]*(aiV1.y/pos[1].z) + baryc[2]*(aiV2.y/pos[2].z)),
20 | .z = fpos->z*(baryc[0]*(aiV0.z/pos[0].z) + baryc[1]*(aiV1.z/pos[1].z) + baryc[2]*(aiV2.z/pos[2].z)),
21 | .w = fpos->z*(baryc[0]*(aiV0.w/pos[0].z) + baryc[1]*(aiV1.w/pos[1].z) + baryc[2]*(aiV2.w/pos[2].z)),
22 | };
23 | }
24 | }
25 |
26 | /* ~/Static functions/~ */
27 |
28 |
29 | void SR_WritePixel(SR_FrameBuffer *buffer, const SR_VecScreen *pos, const void* value)
30 | /* Writes the desired color values in the (x, y) coordinates of the color buffer. */
31 | {
32 | float depth;
33 | SR_TexBufferRead(&buffer->depth, &depth, pos->x, pos->y);
34 | if (pos->z < depth) {
35 | SR_TexBufferWrite(&buffer->depth, &pos->z, pos->x, pos->y);
36 | SR_TexBufferWrite(&buffer->color, value, pos->x, pos->y);
37 | }
38 | }
39 |
40 | void SR_WriteLine(SR_FrameBuffer *buffer, const SR_VecScreen *pos, const SR_Pipeline* pipeline)
41 | /* Bresenheim Midpoint Line Rasterization. */
42 | {
43 | /*
44 | int dx = pos[2] - pos[0];
45 | int dy = pos[3] - pos[1];
46 | int inc[2] = {1, 1};
47 | if (dx < 0) {
48 | dx = -dx;
49 | inc[0] = -1;
50 | }
51 | if (dy < 0) {
52 | dy = -dy;
53 | inc[1] = -1;
54 | }
55 |
56 | // 0 <= f' <= 1
57 | int d = 2*dy - dx;
58 | int smallerIncr = 2*dy; // Step into E | N
59 | int greaterIncr = 2*(dy - dx); // Step into NE
60 | int grIncX = inc[0];
61 | int smIncY = 0;
62 | // 1 < f'
63 | if (dy > dx) {
64 | d = dy - 2*dx;
65 | smallerIncr = greaterIncr;
66 | greaterIncr = -2*dx;
67 | grIncX = 0;
68 | smIncY = inc[1];
69 | }
70 |
71 | // Incremental Rasterization
72 | int linep[2] = {pos[0], pos[1]};
73 | while (linep[0] != pos[2] || linep[1] != pos[3]) {
74 | SR_WritePixel(buffer, linep, shader);
75 | if (d <= 0) {
76 | d += smallerIncr;
77 | linep[0] += inc[0];
78 | linep[1] += smIncY;
79 | }
80 | else {
81 | d += greaterIncr;
82 | linep[0] += grIncX;
83 | linep[1] += inc[1];
84 | }
85 | }
86 | */
87 | }
88 |
89 | void SR_WriteTriangle(SR_FrameBuffer *buffer, const SR_VecScreen *pos, const SR_Pipeline* pipeline)
90 | /* Triangle rastierization using the pineda algorithm. */
91 | {
92 | const int WIDTH = (int)buffer->color.width-1;
93 | const int HEIGHT = (int)buffer->color.height-1;
94 | // Bounding box
95 | int bx = MIN3(pos[0].x, pos[1].x, pos[2].x);
96 | int by = MIN3(pos[0].y, pos[1].y, pos[2].y);
97 | int bw = MAX3(pos[0].x, pos[1].x, pos[2].x);
98 | int bh = MAX3(pos[0].y, pos[1].y, pos[2].y);
99 | bx = CLAMP(bx, 0, WIDTH);
100 | by = CLAMP(by, 0, HEIGHT);
101 | bw = CLAMP(bw, 0, WIDTH);
102 | bh = CLAMP(bh, 0, HEIGHT);
103 |
104 | // Edges
105 | const int d02[2] = {pos[2].x -pos[0].x, pos[2].y -pos[0].y};
106 | const int d01[2] = {pos[1].x -pos[0].x, pos[1].y -pos[0].y};
107 | const int d12[2] = {pos[2].x -pos[1].x, pos[2].y -pos[1].y};
108 | const int d20[2] = {pos[0].x -pos[2].x, pos[0].y -pos[2].y};
109 | const int area = d02[0]*d01[1] - d02[1]*d01[0]; // Triangle Area x 2
110 |
111 | // Interpolated Vertex Attributes
112 | const size_t ATTRIB_COUNT = pipeline->vertexStageOutputCount;
113 | SR_Vecf attribs[ATTRIB_COUNT];
114 |
115 | SR_VecScreen fpos; // Fragment position
116 | float baryc[3]; // Barycentric coordinates
117 | int e01, e12, e20; // Edge values
118 |
119 | // Iterate bounding box
120 | for (fpos.y = by; fpos.y <= bh; fpos.y++) {
121 | e12 = (bx-pos[1].x)*d12[1] - (fpos.y-pos[1].y)*d12[0]; //vertex 0
122 | e20 = (bx-pos[2].x)*d20[1] - (fpos.y-pos[2].y)*d20[0]; //vertex 1
123 | e01 = (bx-pos[0].x)*d01[1] - (fpos.y-pos[0].y)*d01[0]; //vertex 2
124 |
125 | for (fpos.x = bx; fpos.x <= bw; fpos.x++) {
126 | if ((e01 >= 0) && (e12 >= 0) && (e20 >= 0)) {
127 | // Calculate Barycentric coordinates
128 | baryc[0] = (float)e12/area;
129 | baryc[1] = (float)e20/area;
130 | baryc[2] = (float)e01/area;
131 |
132 | // Z-Interpolation
133 | fpos.z = 1.0 / (baryc[0]/pos[0].z+baryc[1]/pos[1].z+baryc[2]/pos[2].z);
134 |
135 | // Attribute interpolation
136 | mixAttribsTriangle(attribs, &fpos, pos, baryc, pipeline);
137 |
138 | // Fragment shading
139 | SR_Vec4f color = (SR_Vec4f){0.0, 0.0, 0.0, 0.0};
140 | (*(pipeline->fragmentShader))(ATTRIB_COUNT, attribs, &color);
141 | uint8_t texel[] = {color.x*255,
142 | color.y*255,
143 | color.z*255,
144 | color.w*255};
145 |
146 | SR_WritePixel(buffer, &fpos, &texel);
147 | }
148 |
149 | e01 += d01[1];
150 | e12 += d12[1];
151 | e20 += d20[1];
152 | }
153 | }
154 | }
155 |
--------------------------------------------------------------------------------
/src/sre/sretexbuffer.c:
--------------------------------------------------------------------------------
1 | #include "sre.h"
2 | #include
3 | #include
4 |
5 | SR_TexBuffer2D SR_TexBufferCreate(size_t width, size_t height, uint16_t format)
6 | /* Return a new ColorBuffer with allocated memory. */
7 | {
8 | SR_TexBuffer2D b = (SR_TexBuffer2D){
9 | .format = format,
10 | .width = width,
11 | .height = height
12 | };
13 | const size_t size = SR_TexBufferSize(&b);
14 | b.values = malloc(size);
15 | memset(b.values, 0, size);
16 | return b;
17 | }
18 |
19 | SR_TexBuffer2D SR_TexBufferCopy(const SR_TexBuffer2D *buffer)
20 | /* Copy the contents of the given texture buffer into
21 | * a newly allocated buffer. */
22 | {
23 | SR_TexBuffer2D tex = SR_TexBufferCreate(buffer->width, buffer->height,
24 | buffer->format);
25 | memcpy(tex.values, buffer->values, SR_TexBufferSize(buffer));
26 | return tex;
27 | }
28 |
29 | void SR_TexBufferRead(const SR_TexBuffer2D *buffer, void *outValue,
30 | size_t x, size_t y)
31 | /* Read the value at psoition (x,y) into the out value.*/
32 | {
33 | const size_t fsize = SR_TexBufferFormatSize(buffer);
34 | const size_t offset = (y * buffer->width + x) * fsize;
35 | memcpy(outValue, &buffer->values[offset], fsize);
36 | }
37 |
38 | void SR_TexBufferSample(const SR_TexBuffer2D *buffer, void *outValue,
39 | float x, float y)
40 | /* Sample position with bilinear interpolation.*/
41 | {
42 | // Sample positions
43 | int x0 = (size_t)x;
44 | int y0 = (size_t)y;
45 | int x1 = x0 + 1;
46 | int y1 = y0 + 1;
47 | x0 = CLAMP(x0, 0, (int)buffer->width);
48 | y0 = CLAMP(y0, 0, (int)buffer->height);
49 | x1 = CLAMP(x1, 0, (int)buffer->width);
50 | y1 = CLAMP(y1, 0, (int)buffer->height);
51 |
52 | // Samples
53 | const uint16_t type = SR_TexBufferFormatType(buffer);
54 | const uint16_t ncomp = SR_TexBufferFormatNComps(buffer);
55 | const uint16_t nbytes = SR_TexBufferFormatNBytes(buffer);
56 | const size_t fsize = SR_TexBufferFormatSize(buffer);
57 |
58 | uint8_t* samples = malloc(4 * fsize);
59 | SR_TexBufferRead(buffer, &samples[0*fsize], x0, y0);
60 | SR_TexBufferRead(buffer, &samples[1*fsize], x1, y0);
61 | SR_TexBufferRead(buffer, &samples[2*fsize], x0, y1);
62 | SR_TexBufferRead(buffer, &samples[3*fsize], x1, y1);
63 |
64 | // Interpolation
65 | const float tx = x - floor(x); // [0, 1]
66 | const float ty = y - floor(y); // [0, 1]
67 |
68 | switch(type) {
69 | case SR_TF_TYPE_UINT:
70 | for (uint8_t i = 0; i < ncomp; i++) {
71 | // Collect values of sample components
72 | size_t values[4] = {0};
73 | for (int j = 0; j < 4; j++)
74 | memcpy(&values[j], &samples[(j*fsize)+(i*nbytes)], nbytes);
75 |
76 | // Interpolate in x direction
77 | size_t sx1 = (1-tx)*values[0] + tx*values[1];
78 | size_t sx2 = (1-tx)*values[2] + tx*values[3];
79 |
80 | // Interpolate in y direction
81 | size_t sy = (1-ty)*sx1 + ty*sx2;
82 | memcpy(&((uint8_t*)outValue)[i*nbytes], &sy, nbytes);
83 | }
84 | break;
85 |
86 | case SR_TF_TYPE_FLOAT:
87 | for (uint16_t i = 0; i < ncomp; i++) {
88 | // Interpolate in x direction
89 | float sx1 = (1-tx)*((float*)samples)[(0*ncomp)+i] + tx*((float*)samples)[(1*ncomp)+i];
90 | float sx2 = (1-tx)*((float*)samples)[(2*ncomp)+i] + tx*((float*)samples)[(3*ncomp)+i];
91 | // Interpolate in y direction
92 | ((float*)outValue)[i] = (1-ty)*sx1 + ty*sx2;
93 | }
94 | break;
95 | };
96 |
97 | free(samples);
98 | }
99 |
100 | void SR_TexBufferWrite(SR_TexBuffer2D *buffer, const void *value, size_t x,
101 | size_t y)
102 | /* Write the given value (of format size) into the texture buffer
103 | * at position (x,y). */
104 | {
105 | const size_t fsize = SR_TexBufferFormatSize(buffer);
106 | const size_t offset = (y * buffer->width + x) * fsize;
107 | memcpy(&buffer->values[offset], value, fsize);
108 | }
109 |
110 | void SR_TexBufferClear(SR_TexBuffer2D *buffer, const void *value)
111 | /* Clears the elements of the color buffer array with the given value. */
112 | {
113 | const size_t fsize = SR_TexBufferFormatSize(buffer);
114 | for (size_t i = 0; i < buffer->width*buffer->height; i++) {
115 | memcpy(&buffer->values[i*fsize], value, fsize);
116 | }
117 | }
118 |
119 | void SR_TexBufferFree(SR_TexBuffer2D *buffer)
120 | /* Free allocated memory for the texture buffer. */
121 | {
122 | if (buffer->values != NULL) {
123 | free(buffer->values);
124 | }
125 | *buffer = SR_NULL_TEXBUFFER;
126 | }
127 |
128 | size_t SR_TexBufferSize(const SR_TexBuffer2D *buffer)
129 | /* Return the size of the texture buffer in bytes. */
130 | {
131 | return buffer->width*buffer->height*SR_TexBufferFormatSize(buffer);
132 | }
133 |
134 |
135 | // Texture Format
136 |
137 | size_t SR_TexBufferFormatSize(const SR_TexBuffer2D *buffer)
138 | /* Return the byte size of the textures format. */
139 | {
140 | return SR_TexBufferFormatNBytes(buffer)*SR_TexBufferFormatNComps(buffer);
141 | }
142 |
143 | uint16_t SR_TexBufferFormatType(const SR_TexBuffer2D *buffer)
144 | /* Return the texture buffer format type.*/
145 | {
146 | return (buffer->format & SR_TF_MASK_TYPE);
147 | }
148 |
149 | uint16_t SR_TexBufferFormatNComps(const SR_TexBuffer2D *buffer)
150 | /* Return the number of components of the texture buffer formats. */
151 | {
152 | return (buffer->format & SR_TF_MASK_NCOMPS) >> 4;
153 | }
154 |
155 | uint16_t SR_TexBufferFormatNBytes(const SR_TexBuffer2D *buffer)
156 | /* Return the number of bytes per components of the texture buffer format. */
157 | {
158 | return (buffer->format & SR_TF_MASK_NBYTES);
159 | }
160 |
--------------------------------------------------------------------------------
/src/sre/sretypes.h:
--------------------------------------------------------------------------------
1 | /* Declarations and definitions of common typedefs and structs. */
2 | #ifndef SRETYPES_H
3 | #define SRETYPES_H
4 |
5 | #include
6 | #include
7 |
8 | typedef enum {
9 | FALSE, TRUE
10 | } SR_Boolean;
11 |
12 | // Texturebuffer
13 | typedef struct {
14 | size_t width;
15 | size_t height;
16 | uint16_t format;
17 | uint8_t *values;
18 | } SR_TexBuffer2D;
19 | #define SR_NULL_TEXBUFFER (SR_TexBuffer2D) { \
20 | .width = 0, .height = 0, .format = 0, \
21 | .values = NULL} \
22 |
23 | // Common vector types
24 | typedef struct { float x; } SR_Vec1f;
25 | typedef struct { float x, y; } SR_Vec2f;
26 | typedef struct { float x, y, z; } SR_Vec3f;
27 | typedef struct { float x, y, z, w; } SR_Vec4f;
28 | typedef union {
29 | SR_Vec1f vec1f;
30 | SR_Vec2f vec2f;
31 | SR_Vec3f vec3f;
32 | SR_Vec4f vec4f;
33 | } SR_Vecf;
34 |
35 | // Composite vector types
36 | typedef struct {
37 | int x, y;
38 | float z;
39 | } SR_VecScreen;
40 |
41 | // Vertex attribute data
42 | typedef struct {
43 | size_t count; // Package size
44 | size_t stride; // Stride in bytes
45 | size_t offset; // Offset in bytes
46 | } SR_VertexAttribute;
47 |
48 | // Vertex, index and attribute data collection
49 | typedef struct {
50 | float* vertexBuffer;
51 | size_t* indexBuffer;
52 | size_t vertexBufferSize;
53 | size_t indexBufferSize;
54 | size_t attributesCount;
55 | SR_VertexAttribute* attributes;
56 | } SR_VertexArray;
57 |
58 | // Framebuffer
59 | typedef struct {
60 | SR_TexBuffer2D color;
61 | SR_TexBuffer2D depth;
62 | } SR_FrameBuffer;
63 |
64 | // Shader functions
65 | typedef void(*SR_ShaderCB)(size_t attributeCount, // Number of input attributes
66 | SR_Vecf* attributes, // Array of input attribes
67 | SR_Vec4f* output); // Single vec4 output attribute
68 |
69 | // Collection of shader objects in a pipeline
70 | typedef struct {
71 | SR_ShaderCB vertexShader; // Currently bound vertex shader callback
72 | SR_ShaderCB fragmentShader; // Currently bound fragment shader callback
73 | size_t vertexStageOutputCount; // Number of vertex output elements
74 | SR_Vecf *currVertexStageOutput; // Output of single vertex shader
75 | SR_Vecf *pVertexStageOutput; // Pointer to collected vertex output
76 | } SR_Pipeline;
77 |
78 | // Write functions
79 | typedef void (*SR_Write)(SR_FrameBuffer *buffer, const SR_VecScreen *pos,
80 | const SR_Pipeline *pipeline);
81 |
82 | #endif // SRETYPES_H
83 |
--------------------------------------------------------------------------------
/src/sre/srmesh/README.md:
--------------------------------------------------------------------------------
1 | ## SR_Mesh
2 | Capable of loading simple wavefront(.obj) files. Currently Supports:
3 | * Geometric data(v)(vt)(vn)
4 | * Face indexing
5 | * Quad faces
6 |
7 | There will be no support for free-form curves and surfaces as wel as grouping.
8 | Faces up to quadliterals are supported.
9 |
10 | Indexed Vertex Data constructs a continous array of vertex data of the form (v, vt, vn)
11 | with stride 8 and offsets 0, 3, 5.
12 |
13 | ### TODO
14 | * Convert quad faces to triangle faces
15 | * Support optional v, w texture coordinates
16 | * Support optional w vertex coordinate
17 | * Support points and lines
18 | * Support texture and material data
19 |
--------------------------------------------------------------------------------
/src/sre/srmesh/srmesh.c:
--------------------------------------------------------------------------------
1 | #include "srmesh.h"
2 | #include "SDL_video.h"
3 | #include
4 | #include
5 | #include
6 |
7 | /* Static function */
8 |
9 | #define SKIP_WHITESPACE(lp) while(*lp == ' ' && lp++)
10 |
11 |
12 | static void pushFace(SRM_Mesh *mesh, SRM_Face *face)
13 | {
14 | mesh->faces = realloc(mesh->faces, (mesh->nFaces+1)*sizeof(SRM_Face));
15 | memcpy(&mesh->faces[mesh->nFaces], face, 3*3*sizeof(size_t));
16 | mesh->nFaces++;
17 | }
18 |
19 | static int collectFaceVertex(char **lpp, size_t *indices) {
20 | char *lp = *lpp;
21 | for (int i = 0; i < 3; i++) {
22 | indices[i] = atoi(lp);
23 | // Skip to next delimiter
24 | while (*lp != OBJ_DELIMITER && // Next Attribute
25 | *lp != WHITESPACE && // Next Vertex Tuples
26 | *lp != NEWLINE && // End of face
27 | *lp != EOS) // End of string
28 | lp++;
29 | if (*lp == WHITESPACE || *lp == NEWLINE) {
30 | lp++;
31 | break;
32 | }
33 | if (*lp == EOS)
34 | break;
35 | lp++;
36 | }
37 | *lpp = lp;
38 | }
39 |
40 | static SR_Boolean lineProcessFace(char *lp, SRM_Mesh *mesh) {
41 | SKIP_WHITESPACE(lp);
42 |
43 | SRM_Face face;
44 | int vertexCount = 0;
45 | // Collect vertex data up to 3 data tuples
46 | while(*lp != EOS && vertexCount < 3) {
47 | collectFaceVertex(&lp, &face.indices[3*vertexCount]);
48 | vertexCount++;
49 | }
50 |
51 | // There shouldnt be faces with less than 3 vertices
52 | if (vertexCount < 3)
53 | return FALSE;
54 |
55 | pushFace(mesh, &face);
56 |
57 | // Parse a 4th component, quad in (1,2,3,4)->(1,2,3),(1,3,4)
58 | if (*lp != EOS) {
59 | memcpy(&face.indices[3], &face.indices[6], 3*sizeof(size_t));
60 | collectFaceVertex(&lp, &face.indices[6]);
61 | pushFace(mesh, &face);
62 | }
63 |
64 | return TRUE;
65 | }
66 |
67 | static void collectLineFloat(char *lp, float **array, size_t *num)
68 | {
69 | while(*(++lp) == ' ');
70 | ;
71 | while (*lp != '\0') {
72 | (*array) = realloc((*array), ((*num)+1)*sizeof(float));
73 | (*array)[*num] = atof(lp);
74 | (*num)++;
75 | while(*(++lp) != ' ' && *lp != '\0');
76 | ;
77 | }
78 | }
79 |
80 | static void lineCopyString(char *lp, char **str) {
81 | SKIP_WHITESPACE(lp);
82 | (*str) = malloc(strlen(lp) + 1);
83 | strcpy((*str), lp);
84 | }
85 |
86 | /* ~Static function~ */
87 |
88 |
89 | SR_Boolean SRM_LoadMesh(SRM_Mesh *mesh, const char *filepath)
90 | /* Return a mesh object created from the contents of the given
91 | * wavefront file. */
92 | {
93 | FILE *file = fopen(filepath, "r");
94 | if (file == NULL) {
95 | perror("Error opening file");
96 | return FALSE;
97 | }
98 |
99 | *mesh = SRM_NULL_MESH;
100 | char linebuffer[255];
101 |
102 | SR_Boolean status = TRUE;
103 |
104 | while (fgets(linebuffer, 255, file) != NULL) {
105 | // Pointer to current character in linebuffer
106 | char *lp = linebuffer;
107 |
108 | // skip empty lines and comments
109 | SKIP_WHITESPACE(lp);
110 | if (*lp == OBJ_COMMENT || *lp == NEWLINE || *lp == EOS)
111 | continue;
112 |
113 | // Object Name
114 | if (*lp == OBJ_NAME) {
115 | lineCopyString(lp, &mesh->name);
116 | }
117 |
118 | // Vertex Data
119 | else if (*lp == OBJ_VERTEX) {
120 | lp++;
121 | if (*lp == WHITESPACE) {
122 | collectLineFloat(lp, &mesh->vertices, &mesh->nVertices);
123 | } else if (*lp == OBJ_VERTEX_TEXTURE) {
124 | collectLineFloat(lp, &mesh->textureUVs, &mesh->nTextureUVs);
125 | } else if (*lp == OBJ_VERTEX_NORMAL) {
126 | collectLineFloat(lp, &mesh->normals, &mesh->nNormals);
127 | }
128 | }
129 |
130 | // Face Data
131 | else if (*lp == OBJ_FACE) {
132 | if (*(++lp) != WHITESPACE ||
133 | lineProcessFace(lp, mesh) == FALSE) {
134 | status = FALSE;
135 | break;
136 | }
137 | }
138 | }
139 |
140 | fclose(file);
141 | mesh->isInit = status;
142 | return status;
143 | }
144 |
145 | int SRM_IndexedVertexData(SRM_Mesh *mesh, float *outVertexData,
146 | size_t *outIndices, size_t *outVertexCount)
147 | /* Parse the data in the mesh into a indexed mesh vertex data format.
148 | * The vertices are stored as a continous array of
149 | * (vx, vy, vz, u, v, nx, ny,nz). The number of distinct vertex
150 | * combinations is returned in the outVertexcount. */
151 | {
152 | if (!mesh->isInit)
153 | return FALSE;
154 |
155 | const size_t VERTS_PER_FACE = 3;
156 | const size_t MAX_VERT_COUNT = mesh->nFaces * VERTS_PER_FACE;
157 |
158 | size_t indices[MAX_VERT_COUNT];
159 | float vData[MAX_VERT_COUNT * 8];
160 |
161 | memset(indices, 0, MAX_VERT_COUNT*sizeof(size_t));
162 |
163 | size_t nVerts = 0; // Number of vertices
164 | for (size_t i = 0; i < MAX_VERT_COUNT; i++) {
165 | const size_t f_i = i / VERTS_PER_FACE; // face index [0, .., nFaces]
166 | const size_t v_i = i % VERTS_PER_FACE; // local vertex index [0, 1, 2]
167 | const size_t *vert_i = &mesh->faces[f_i].indices[3*v_i];
168 |
169 | // Check if this vertex was visited
170 | size_t visited = 0;
171 | for (size_t j = 0; j < i; j++) {
172 | if (indices[j] == 0)
173 | break;
174 |
175 | const size_t f_j = j / VERTS_PER_FACE;
176 | const size_t v_j = j % VERTS_PER_FACE;
177 | const size_t *vert_j = &mesh->faces[f_j].indices[3*v_j];
178 |
179 | if (vert_i[0] == vert_j[0] &&
180 | vert_i[1] == vert_j[1] &&
181 | vert_i[2] == vert_j[2]) {
182 | visited = indices[j];
183 | break;
184 | }
185 | }
186 |
187 | if (!visited) {
188 | if (outVertexData != NULL) {
189 | memcpy(&vData[nVerts * 8 + 0],
190 | &mesh->vertices[(vert_i[0]-1)*3],
191 | 3 * sizeof(float));
192 | if (vert_i[1]) {
193 | memcpy(&vData[nVerts*8+3], &mesh->textureUVs[(vert_i[1]-1)*2],
194 | 2 * sizeof(float));
195 | }
196 | if (vert_i[2]) {
197 | memcpy(&vData[nVerts *8+5], &mesh->normals[(vert_i[2]-1)*3],
198 | 3 * sizeof(float));
199 | }
200 | }
201 | indices[i] = ++nVerts;
202 | } else {
203 | indices[i] = visited;
204 | }
205 | }
206 |
207 | if (outVertexCount != NULL)
208 | *outVertexCount = nVerts;
209 | if (outIndices != NULL) {
210 | // Convert back to 0-based indexing
211 | for (size_t i = 0; i < MAX_VERT_COUNT; i++)
212 | outIndices[i] = indices[i] - 1;
213 | }
214 | if (outVertexData != NULL)
215 | memcpy(outVertexData, vData, nVerts*8*sizeof(float));
216 |
217 | return TRUE;
218 | }
219 |
220 |
221 | void SRM_DeleteMesh(SRM_Mesh *mesh)
222 | /* Frees the memory allocated by a mesh data structure. */
223 | {
224 | mesh->isInit = FALSE;
225 |
226 | if (mesh->name != NULL) {
227 | free(mesh->name);
228 | mesh->name = NULL;
229 | }
230 | if (mesh->vertices != NULL) {
231 | free(mesh->vertices);
232 | mesh->vertices = NULL;
233 | }
234 | if (mesh->textureUVs != NULL) {
235 | free(mesh->textureUVs);
236 | mesh->textureUVs = NULL;
237 | }
238 | if (mesh->normals != NULL) {
239 | free(mesh->normals);
240 | mesh->normals = NULL;
241 | }
242 | if (mesh->faces != NULL) {
243 | free(mesh->faces);
244 | mesh->faces = NULL;
245 | }
246 |
247 | mesh->nFaces = 0;
248 | mesh->nNormals = 0;
249 | mesh->nVertices = 0;
250 | mesh->nTextureUVs = 0;
251 | }
252 |
253 |
254 | void SRM_PrintMesh(SRM_Mesh *mesh)
255 | /* Print the contents of the given mesh in human readable form. */
256 | {
257 | if (!mesh->isInit)
258 | return;
259 |
260 | printf("Printing mesh data at %p.\n", (void*)mesh);
261 | if (mesh->name != NULL)
262 | printf("Name: %s\n", mesh->name);
263 |
264 | if (mesh->vertices != NULL) {
265 | printf("Vertices:\n");
266 | for (unsigned int i = 0; i < mesh->nVertices; i++) {
267 | printf("%f, ", mesh->vertices[i]);
268 | if (((i + 1) % 3) == 0)
269 | printf("\n");
270 | }
271 | }
272 |
273 | if (mesh->textureUVs != NULL) {
274 | printf("\nTextureUVs:\n");
275 | for (unsigned int i = 0; i < mesh->nTextureUVs; i++) {
276 | printf("%f, ", mesh->textureUVs[i]);
277 | if (((i + 1) % 2) == 0)
278 | printf("\n");
279 | }
280 | }
281 |
282 | if (mesh->normals != NULL) {
283 | printf("\nNormals:\n");
284 | for (unsigned int i = 0; i < mesh->nNormals; i++) {
285 | printf("%f, ", mesh->normals[i]);
286 | if (((i + 1) % 3) == 0)
287 | printf("\n");
288 | }
289 | }
290 |
291 | if (mesh->faces != NULL) {
292 | printf("\nFace Indices:\n");
293 | for (unsigned int i = 0; i < mesh->nFaces; i++) {
294 | for (int j = 0; j < 3; j++) {
295 | for(int k = 0; k < 3; k++) {
296 | printf("%ld/", mesh->faces[i].indices[(3*j)+k]);
297 | }
298 | printf(" ");
299 | }
300 | printf("\n");
301 | }
302 | }
303 | }
304 |
--------------------------------------------------------------------------------
/src/sre/srmesh/srmesh.h:
--------------------------------------------------------------------------------
1 | /* Model loading and mesh generation. */
2 | #ifndef SRMESH_H
3 | #define SRMESH_H
4 |
5 | #include "../sretypes.h"
6 |
7 | // Common defintions
8 | #define EOS '\0'
9 | #define NEWLINE '\n'
10 | #define WHITESPACE ' '
11 |
12 | // Wavefront object format
13 | #define OBJ_COMMENT '#'
14 | #define OBJ_NAME 'o'
15 | #define OBJ_VERTEX 'v'
16 | #define OBJ_VERTEX_TEXTURE 't'
17 | #define OBJ_VERTEX_NORMAL 'n'
18 | #define OBJ_FACE 'f'
19 | #define OBJ_DELIMITER '/'
20 |
21 |
22 | typedef struct {
23 | /* A Face is a collection of (1-based) indices into the vertex data of
24 | * the mesh. An index of 0 means that there is no corresponding value.
25 | * The face consists of three vertex tuples of (vertex, texture, normal)
26 | * indices each. */
27 | size_t indices[9];
28 | } SRM_Face;
29 |
30 | typedef struct {
31 | SR_Boolean isInit;
32 | char *name;
33 | size_t nFaces;
34 | size_t nTextureUVs;
35 | size_t nVertices;
36 | size_t nNormals;
37 | // Vertex Data
38 | union {
39 | float *vertices;
40 | SR_Vec3f *vertexTuples;
41 | };
42 | union {
43 | float *textureUVs;
44 | SR_Vec2f *uvTuples;
45 | };
46 | union {
47 | float *normals;
48 | SR_Vec3f *normalTuples;
49 | };
50 | // Face Data
51 | SRM_Face *faces;
52 | } SRM_Mesh;
53 | #define SRM_NULL_MESH (SRM_Mesh) { \
54 | .isInit = FALSE, \
55 | .name = NULL, \
56 | .vertices = NULL, \
57 | .textureUVs = NULL, \
58 | .normals = NULL, \
59 | .faces = NULL, \
60 | .nFaces = 0, \
61 | .nNormals = 0, \
62 | .nVertices = 0, \
63 | .nTextureUVs = 0}
64 |
65 |
66 |
67 |
68 | SR_Boolean SRM_LoadMesh(SRM_Mesh *mesh, const char *filepath);
69 | int SRM_IndexedVertexData(SRM_Mesh *mesh, float *outVertexData,
70 | size_t *outIndices, size_t *outVertexCount);
71 | void SRM_DeleteMesh(SRM_Mesh *mesh);
72 | void SRM_PrintMesh(SRM_Mesh *mesh);
73 |
74 | #endif // SRMESH_H
75 |
--------------------------------------------------------------------------------
/src/test/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #### CTest Units
2 | cmake_minimum_required (VERSION 3.15)
3 |
4 | set (BASE_FILES
5 | minunit.h)
6 |
7 | include_directories(${SRC_DIR})
8 |
9 | ### Test Object Loader
10 | add_executable(test_obloader test_objloader.c ${BASE_FILES})
11 | target_link_libraries(test_obloader ${LIBS} ${SRE_TGT})
12 | add_test(TestOBJLOADER test_obloader)
13 |
--------------------------------------------------------------------------------
/src/test/minunit.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012 David Siñuela Pastor, siu.4coders@gmail.com
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining
5 | * a copy of this software and associated documentation files (the
6 | * "Software"), to deal in the Software without restriction, including
7 | * without limitation the rights to use, copy, modify, merge, publish,
8 | * distribute, sublicense, and/or sell copies of the Software, and to
9 | * permit persons to whom the Software is furnished to do so, subject to
10 | * the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be
13 | * included in all copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 | */
23 | #ifndef MINUNIT_MINUNIT_H
24 | #define MINUNIT_MINUNIT_H
25 |
26 | #ifdef __cplusplus
27 | extern "C" {
28 | #endif
29 |
30 | #if defined(_WIN32)
31 | #include
32 | #if defined(_MSC_VER) && _MSC_VER < 1900
33 | #define snprintf _snprintf
34 | #define __func__ __FUNCTION__
35 | #endif
36 |
37 | #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
38 |
39 | /* Change POSIX C SOURCE version for pure c99 compilers */
40 | #if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200112L
41 | #undef _POSIX_C_SOURCE
42 | #define _POSIX_C_SOURCE 200112L
43 | #endif
44 |
45 | #include /* POSIX flags */
46 | #include /* clock_gettime(), time() */
47 | #include /* gethrtime(), gettimeofday() */
48 | #include
49 | #include
50 | #include
51 |
52 | #if defined(__MACH__) && defined(__APPLE__)
53 | #include
54 | #include
55 | #endif
56 |
57 | #else
58 | #error "Unable to define timers for an unknown OS."
59 | #endif
60 |
61 | #include
62 | #include
63 |
64 | /* Maximum length of last message */
65 | #define MINUNIT_MESSAGE_LEN 1024
66 | /* Accuracy with which floats are compared */
67 | #define MINUNIT_EPSILON 1E-12
68 |
69 | /* Misc. counters */
70 | static int minunit_run = 0;
71 | static int minunit_assert = 0;
72 | static int minunit_fail = 0;
73 | static int minunit_status = 0;
74 |
75 | /* Timers */
76 | static double minunit_real_timer = 0;
77 | static double minunit_proc_timer = 0;
78 |
79 | /* Last message */
80 | static char minunit_last_message[MINUNIT_MESSAGE_LEN];
81 |
82 | /* Test setup and teardown function pointers */
83 | static void (*minunit_setup)(void) = NULL;
84 | static void (*minunit_teardown)(void) = NULL;
85 |
86 | /* Definitions */
87 | #define MU_TEST(method_name) static void method_name(void)
88 | #define MU_TEST_SUITE(suite_name) static void suite_name(void)
89 |
90 | #define MU__SAFE_BLOCK(block) do {\
91 | block\
92 | } while(0)
93 |
94 | /* Run test suite and unset setup and teardown functions */
95 | #define MU_RUN_SUITE(suite_name) MU__SAFE_BLOCK(\
96 | suite_name();\
97 | minunit_setup = NULL;\
98 | minunit_teardown = NULL;\
99 | )
100 |
101 | /* Configure setup and teardown functions */
102 | #define MU_SUITE_CONFIGURE(setup_fun, teardown_fun) MU__SAFE_BLOCK(\
103 | minunit_setup = setup_fun;\
104 | minunit_teardown = teardown_fun;\
105 | )
106 |
107 | /* Test runner */
108 | #define MU_RUN_TEST(test) MU__SAFE_BLOCK(\
109 | if (minunit_real_timer==0 && minunit_proc_timer==0) {\
110 | minunit_real_timer = mu_timer_real();\
111 | minunit_proc_timer = mu_timer_cpu();\
112 | }\
113 | if (minunit_setup) (*minunit_setup)();\
114 | minunit_status = 0;\
115 | test();\
116 | minunit_run++;\
117 | if (minunit_status) {\
118 | minunit_fail++;\
119 | printf("F");\
120 | printf("\n%s\n", minunit_last_message);\
121 | }\
122 | fflush(stdout);\
123 | if (minunit_teardown) (*minunit_teardown)();\
124 | )
125 |
126 | /* Report */
127 | #define MU_REPORT() MU__SAFE_BLOCK(\
128 | double minunit_end_real_timer;\
129 | double minunit_end_proc_timer;\
130 | printf("\n\n%d tests, %d assertions, %d failures\n", minunit_run, minunit_assert, minunit_fail);\
131 | minunit_end_real_timer = mu_timer_real();\
132 | minunit_end_proc_timer = mu_timer_cpu();\
133 | printf("\nFinished in %.8f seconds (real) %.8f seconds (proc)\n\n",\
134 | minunit_end_real_timer - minunit_real_timer,\
135 | minunit_end_proc_timer - minunit_proc_timer);\
136 | )
137 |
138 | /* Assertions */
139 | #define mu_check(test) MU__SAFE_BLOCK(\
140 | minunit_assert++;\
141 | if (!(test)) {\
142 | snprintf(minunit_last_message, MINUNIT_MESSAGE_LEN, "%s failed:\n\t%s:%d: %s", __func__, __FILE__, __LINE__, #test);\
143 | minunit_status = 1;\
144 | return;\
145 | } else {\
146 | printf(".");\
147 | }\
148 | )
149 |
150 | #define mu_fail(message) MU__SAFE_BLOCK(\
151 | minunit_assert++;\
152 | snprintf(minunit_last_message, MINUNIT_MESSAGE_LEN, "%s failed:\n\t%s:%d: %s", __func__, __FILE__, __LINE__, message);\
153 | minunit_status = 1;\
154 | return;\
155 | )
156 |
157 | #define mu_assert(test, message) MU__SAFE_BLOCK(\
158 | minunit_assert++;\
159 | if (!(test)) {\
160 | snprintf(minunit_last_message, MINUNIT_MESSAGE_LEN, "%s failed:\n\t%s:%d: %s", __func__, __FILE__, __LINE__, message);\
161 | minunit_status = 1;\
162 | return;\
163 | } else {\
164 | printf(".");\
165 | }\
166 | )
167 |
168 | #define mu_assert_int_eq(expected, result) MU__SAFE_BLOCK(\
169 | int minunit_tmp_e;\
170 | int minunit_tmp_r;\
171 | minunit_assert++;\
172 | minunit_tmp_e = (expected);\
173 | minunit_tmp_r = (result);\
174 | if (minunit_tmp_e != minunit_tmp_r) {\
175 | snprintf(minunit_last_message, MINUNIT_MESSAGE_LEN, "%s failed:\n\t%s:%d: %d expected but was %d", __func__, __FILE__, __LINE__, minunit_tmp_e, minunit_tmp_r);\
176 | minunit_status = 1;\
177 | return;\
178 | } else {\
179 | printf(".");\
180 | }\
181 | )
182 |
183 | #define mu_assert_double_eq(expected, result) MU__SAFE_BLOCK(\
184 | double minunit_tmp_e;\
185 | double minunit_tmp_r;\
186 | minunit_assert++;\
187 | minunit_tmp_e = (expected);\
188 | minunit_tmp_r = (result);\
189 | if (fabs(minunit_tmp_e-minunit_tmp_r) > MINUNIT_EPSILON) {\
190 | int minunit_significant_figures = 1 - log10(MINUNIT_EPSILON);\
191 | snprintf(minunit_last_message, MINUNIT_MESSAGE_LEN, "%s failed:\n\t%s:%d: %.*g expected but was %.*g", __func__, __FILE__, __LINE__, minunit_significant_figures, minunit_tmp_e, minunit_significant_figures, minunit_tmp_r);\
192 | minunit_status = 1;\
193 | return;\
194 | } else {\
195 | printf(".");\
196 | }\
197 | )
198 |
199 | #define mu_assert_string_eq(expected, result) MU__SAFE_BLOCK(\
200 | const char* minunit_tmp_e = expected;\
201 | const char* minunit_tmp_r = result;\
202 | minunit_assert++;\
203 | if (!minunit_tmp_e) {\
204 | minunit_tmp_e = "";\
205 | }\
206 | if (!minunit_tmp_r) {\
207 | minunit_tmp_r = "";\
208 | }\
209 | if(strcmp(minunit_tmp_e, minunit_tmp_r)) {\
210 | snprintf(minunit_last_message, MINUNIT_MESSAGE_LEN, "%s failed:\n\t%s:%d: '%s' expected but was '%s'", __func__, __FILE__, __LINE__, minunit_tmp_e, minunit_tmp_r);\
211 | minunit_status = 1;\
212 | return;\
213 | } else {\
214 | printf(".");\
215 | }\
216 | )
217 |
218 | /*
219 | * The following two functions were written by David Robert Nadeau
220 | * from http://NadeauSoftware.com/ and distributed under the
221 | * Creative Commons Attribution 3.0 Unported License
222 | */
223 |
224 | /**
225 | * Returns the real time, in seconds, or -1.0 if an error occurred.
226 | *
227 | * Time is measured since an arbitrary and OS-dependent start time.
228 | * The returned real time is only useful for computing an elapsed time
229 | * between two calls to this function.
230 | */
231 | static double mu_timer_real(void)
232 | {
233 | #if defined(_WIN32)
234 | /* Windows 2000 and later. ---------------------------------- */
235 | LARGE_INTEGER Time;
236 | LARGE_INTEGER Frequency;
237 |
238 | QueryPerformanceFrequency(&Frequency);
239 | QueryPerformanceCounter(&Time);
240 |
241 | Time.QuadPart *= 1000000;
242 | Time.QuadPart /= Frequency.QuadPart;
243 |
244 | return (double)Time.QuadPart / 1000000.0;
245 |
246 | #elif (defined(__hpux) || defined(hpux)) || ((defined(__sun__) || defined(__sun) || defined(sun)) && (defined(__SVR4) || defined(__svr4__)))
247 | /* HP-UX, Solaris. ------------------------------------------ */
248 | return (double)gethrtime( ) / 1000000000.0;
249 |
250 | #elif defined(__MACH__) && defined(__APPLE__)
251 | /* OSX. ----------------------------------------------------- */
252 | static double timeConvert = 0.0;
253 | if ( timeConvert == 0.0 )
254 | {
255 | mach_timebase_info_data_t timeBase;
256 | (void)mach_timebase_info( &timeBase );
257 | timeConvert = (double)timeBase.numer /
258 | (double)timeBase.denom /
259 | 1000000000.0;
260 | }
261 | return (double)mach_absolute_time( ) * timeConvert;
262 |
263 | #elif defined(_POSIX_VERSION)
264 | /* POSIX. --------------------------------------------------- */
265 | struct timeval tm;
266 | #if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0)
267 | {
268 | struct timespec ts;
269 | #if defined(CLOCK_MONOTONIC_PRECISE)
270 | /* BSD. --------------------------------------------- */
271 | const clockid_t id = CLOCK_MONOTONIC_PRECISE;
272 | #elif defined(CLOCK_MONOTONIC_RAW)
273 | /* Linux. ------------------------------------------- */
274 | const clockid_t id = CLOCK_MONOTONIC_RAW;
275 | #elif defined(CLOCK_HIGHRES)
276 | /* Solaris. ----------------------------------------- */
277 | const clockid_t id = CLOCK_HIGHRES;
278 | #elif defined(CLOCK_MONOTONIC)
279 | /* AIX, BSD, Linux, POSIX, Solaris. ----------------- */
280 | const clockid_t id = CLOCK_MONOTONIC;
281 | #elif defined(CLOCK_REALTIME)
282 | /* AIX, BSD, HP-UX, Linux, POSIX. ------------------- */
283 | const clockid_t id = CLOCK_REALTIME;
284 | #else
285 | const clockid_t id = (clockid_t)-1; /* Unknown. */
286 | #endif /* CLOCK_* */
287 | if ( id != (clockid_t)-1 && clock_gettime( id, &ts ) != -1 )
288 | return (double)ts.tv_sec +
289 | (double)ts.tv_nsec / 1000000000.0;
290 | /* Fall thru. */
291 | }
292 | #endif /* _POSIX_TIMERS */
293 |
294 | /* AIX, BSD, Cygwin, HP-UX, Linux, OSX, POSIX, Solaris. ----- */
295 | gettimeofday( &tm, NULL );
296 | return (double)tm.tv_sec + (double)tm.tv_usec / 1000000.0;
297 | #else
298 | return -1.0; /* Failed. */
299 | #endif
300 | }
301 |
302 | /**
303 | * Returns the amount of CPU time used by the current process,
304 | * in seconds, or -1.0 if an error occurred.
305 | */
306 | static double mu_timer_cpu(void)
307 | {
308 | #if defined(_WIN32)
309 | /* Windows -------------------------------------------------- */
310 | FILETIME createTime;
311 | FILETIME exitTime;
312 | FILETIME kernelTime;
313 | FILETIME userTime;
314 |
315 | /* This approach has a resolution of 1/64 second. Unfortunately, Windows' API does not offer better */
316 | if ( GetProcessTimes( GetCurrentProcess( ),
317 | &createTime, &exitTime, &kernelTime, &userTime ) != 0 )
318 | {
319 | ULARGE_INTEGER userSystemTime;
320 | memcpy(&userSystemTime, &userTime, sizeof(ULARGE_INTEGER));
321 | return (double)userSystemTime.QuadPart / 10000000.0;
322 | }
323 |
324 | #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
325 | /* AIX, BSD, Cygwin, HP-UX, Linux, OSX, and Solaris --------- */
326 |
327 | #if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0)
328 | /* Prefer high-res POSIX timers, when available. */
329 | {
330 | clockid_t id;
331 | struct timespec ts;
332 | #if _POSIX_CPUTIME > 0
333 | /* Clock ids vary by OS. Query the id, if possible. */
334 | if ( clock_getcpuclockid( 0, &id ) == -1 )
335 | #endif
336 | #if defined(CLOCK_PROCESS_CPUTIME_ID)
337 | /* Use known clock id for AIX, Linux, or Solaris. */
338 | id = CLOCK_PROCESS_CPUTIME_ID;
339 | #elif defined(CLOCK_VIRTUAL)
340 | /* Use known clock id for BSD or HP-UX. */
341 | id = CLOCK_VIRTUAL;
342 | #else
343 | id = (clockid_t)-1;
344 | #endif
345 | if ( id != (clockid_t)-1 && clock_gettime( id, &ts ) != -1 )
346 | return (double)ts.tv_sec +
347 | (double)ts.tv_nsec / 1000000000.0;
348 | }
349 | #endif
350 |
351 | #if defined(RUSAGE_SELF)
352 | {
353 | struct rusage rusage;
354 | if ( getrusage( RUSAGE_SELF, &rusage ) != -1 )
355 | return (double)rusage.ru_utime.tv_sec +
356 | (double)rusage.ru_utime.tv_usec / 1000000.0;
357 | }
358 | #endif
359 |
360 | #if defined(_SC_CLK_TCK)
361 | {
362 | const double ticks = (double)sysconf( _SC_CLK_TCK );
363 | struct tms tms;
364 | if ( times( &tms ) != (clock_t)-1 )
365 | return (double)tms.tms_utime / ticks;
366 | }
367 | #endif
368 |
369 | #if defined(CLOCKS_PER_SEC)
370 | {
371 | clock_t cl = clock( );
372 | if ( cl != (clock_t)-1 )
373 | return (double)cl / (double)CLOCKS_PER_SEC;
374 | }
375 | #endif
376 |
377 | #endif
378 |
379 | return -1; /* Failed. */
380 | }
381 |
382 | #ifdef __cplusplus
383 | }
384 | #endif
385 |
386 | #endif /* MINUNIT_MINUNIT_H */
387 |
--------------------------------------------------------------------------------
/src/test/test_objloader.c:
--------------------------------------------------------------------------------
1 | #include "minunit.h"
2 | #include "sre/srmesh/srmesh.h"
3 |
4 | int main () {
5 | SRM_Mesh mesh;
6 | SRM_LoadMesh(&mesh, "/home/berat/Projects/cepples/rtg/assets/cube.obj");
7 | SRM_PrintMesh(&mesh);
8 |
9 | // Collect Indexed Mesh Vertex Data
10 | /* size_t vertexCount; */
11 | /* SRM_IndexedVertexData(&mesh, NULL, NULL, &vertexCount); */
12 |
13 | /* const size_t INDEX_COUNT = mesh.nFaces * 3; */
14 | /* const size_t VDATA_COUNT = vertexCount * 8; */
15 | /* size_t indices[INDEX_COUNT]; */
16 | /* float vertexData[VDATA_COUNT]; */
17 |
18 | /* SRM_IndexedVertexData(&mesh, vertexData, indices, NULL); */
19 |
20 | /* printf("\nIndices:\n"); */
21 | /* for (size_t i = 0; i < INDEX_COUNT; i++) { */
22 | /* printf("%ld", indices[i]); */
23 | /* if (!((i+1)%6)) */
24 | /* printf("\n"); */
25 | /* else */
26 | /* printf(", "); */
27 | /* } */
28 |
29 | /* printf("\nVertex Data:\n"); */
30 | /* for (size_t i = 0; i < VDATA_COUNT; i++) { */
31 | /* printf("%.1f\t", vertexData[i]); */
32 | /* if (!((i+1)%8)) */
33 | /* printf("\n"); */
34 | /* else */
35 | /* printf(", "); */
36 | /* } */
37 |
38 | SRM_DeleteMesh(&mesh);
39 |
40 | return 0;
41 | }
42 |
--------------------------------------------------------------------------------