main.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /*
  2. * 3D Engine
  3. * main.c:
  4. * Based on pikuma.com 3D software renderer in C
  5. * Copyright (c) 2021 986-Studio. All rights reserved.
  6. *
  7. * Created by Manoël Trapier on 01/03/2021.
  8. */
  9. #include <stdio.h>
  10. #include <stdint.h>
  11. #include <stdbool.h>
  12. #include <libc.h>
  13. #include <SDL.h>
  14. #include <log.h>
  15. #include <array.h>
  16. #include <matrix.h>
  17. #include <triangle.h>
  18. #include <display.h>
  19. #include <vector.h>
  20. #include <mesh.h>
  21. #include <light.h>
  22. bool isRunning = true;
  23. int previousFrameTime = 0;
  24. typedef enum displayMode_t
  25. {
  26. DISPLAY_MODE_WIREFRAME,
  27. DISPLAY_MODE_SOLID,
  28. DISPLAY_MODE_SOLID_WIRE,
  29. DISPLAY_MODE_TEXTURED,
  30. DISPLAY_MODE_TEXTURED_WIRE,
  31. } displayMode_t;
  32. bool displayVertex = false;
  33. bool doNotCull = false;
  34. bool doZBuffer = true;
  35. enum displayMode_t currentDisplayMode = DISPLAY_MODE_SOLID;
  36. matrix4_t projectionMatrix;
  37. light_t globalLight;
  38. double updateTime, renderTime, waitTime;
  39. int trianglesCount, trianglesTotal;
  40. vec3_t cameraPosition =
  41. {
  42. .x = 0,
  43. .y = 0,
  44. .z = 0,
  45. };
  46. triangle_t *projectedTriangles = NULL;
  47. void setup()
  48. {
  49. frameBuffer = (uint32_t *)calloc(windowWidth * windowHeight, sizeof(uint32_t));
  50. if (!frameBuffer)
  51. {
  52. Log(TLOG_PANIC, NULL, "Memory allocation error.");
  53. goto exit;
  54. }
  55. zBuffer = (double *)calloc(windowWidth * windowHeight, sizeof(double));
  56. if (!frameBuffer)
  57. {
  58. Log(TLOG_PANIC, NULL, "Memory allocation error.");
  59. goto exit;
  60. }
  61. frameBufferTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STREAMING, windowWidth,
  62. windowHeight);
  63. if (frameBufferTexture == NULL)
  64. {
  65. Log(TLOG_PANIC, NULL, "SDL Texture creation error: %s", SDL_GetError());
  66. goto exit;
  67. }
  68. projectionMatrix = mat4Perspective((double)windowHeight / windowWidth, 90, 0.1, 100);
  69. globalLight.direction.x = 0;
  70. globalLight.direction.y = 0;
  71. globalLight.direction.z = 1;
  72. vec3Normalize(&globalLight.direction);
  73. /* Load texture */
  74. //meshTexture = (colour_t *)REDBRICK_TEXTURE;
  75. loadTextureDateFromPng("assets/cube.png");
  76. /* Load object */
  77. loadOBJFile("assets/f22.obj");
  78. //loadCubeMeshData();
  79. trianglesTotal = arrayGetSize(mesh.faces);
  80. exit:
  81. return;
  82. }
  83. void processInput()
  84. {
  85. SDL_Event event;
  86. SDL_PollEvent(&event);
  87. switch (event.type)
  88. {
  89. case SDL_QUIT:isRunning = false;
  90. break;
  91. case SDL_KEYDOWN:
  92. switch(event.key.keysym.sym)
  93. {
  94. case SDLK_ESCAPE:
  95. isRunning = false;
  96. break;
  97. case SDLK_1:
  98. displayVertex = true;
  99. currentDisplayMode = DISPLAY_MODE_WIREFRAME;
  100. break;
  101. case SDLK_2:
  102. displayVertex = false;
  103. currentDisplayMode = DISPLAY_MODE_WIREFRAME;
  104. break;
  105. case SDLK_3:
  106. displayVertex = false;
  107. currentDisplayMode = DISPLAY_MODE_SOLID;
  108. break;
  109. case SDLK_4:
  110. displayVertex = false;
  111. currentDisplayMode = DISPLAY_MODE_SOLID_WIRE;
  112. break;
  113. case SDLK_5:
  114. displayVertex = false;
  115. currentDisplayMode = DISPLAY_MODE_TEXTURED;
  116. break;
  117. case SDLK_6:
  118. displayVertex = false;
  119. currentDisplayMode = DISPLAY_MODE_TEXTURED_WIRE;
  120. break;
  121. case SDLK_c:
  122. doNotCull = false;
  123. break;
  124. case SDLK_d:
  125. doNotCull = true;
  126. break;
  127. case SDLK_f:
  128. doPerpectiveCorrection = false;
  129. break;
  130. case SDLK_v:
  131. doPerpectiveCorrection = true;
  132. break;
  133. case SDLK_b:
  134. doZBuffer = true;
  135. break;
  136. case SDLK_g:
  137. doZBuffer = false;
  138. break;
  139. }
  140. break;
  141. default:
  142. break;
  143. }
  144. }
  145. uint32_t getMicroSecTime()
  146. {
  147. struct timeval curTime;
  148. gettimeofday(&curTime, NULL);
  149. return ((curTime.tv_sec) * 1000 * 1000) + (curTime.tv_usec);
  150. }
  151. void update()
  152. {
  153. uint32_t i, j;
  154. uint32_t faceCount;
  155. uint32_t timeToWait = FRAME_TARGET_TIME - (SDL_GetTicks() - previousFrameTime);
  156. matrix4_t worldMatrix;
  157. uint32_t ticks = getMicroSecTime();
  158. if (timeToWait <= FRAME_TARGET_TIME)
  159. {
  160. SDL_Delay(timeToWait);
  161. }
  162. previousFrameTime = SDL_GetTicks();
  163. waitTime = (waitTime + (getMicroSecTime() - ticks) / 1000.) / 2.0;
  164. ticks = getMicroSecTime();
  165. mesh.rotation.x += 0.001;
  166. mesh.rotation.y += 0.01;
  167. mesh.translation.z = 5;
  168. worldMatrix = mat4Identity;
  169. worldMatrix = mat4ProdMat4(mat4Scale(mesh.scale.x, mesh.scale.y, mesh.scale.z), worldMatrix);
  170. worldMatrix = mat4ProdMat4(mat4RotationZ(mesh.rotation.z), worldMatrix);
  171. worldMatrix = mat4ProdMat4(mat4RotationY(mesh.rotation.y), worldMatrix);
  172. worldMatrix = mat4ProdMat4(mat4RotationX(mesh.rotation.x), worldMatrix);
  173. worldMatrix = mat4ProdMat4(mat4Translate(mesh.translation.x, mesh.translation.y, mesh.translation.z), worldMatrix);
  174. arrayEmpty(projectedTriangles);
  175. faceCount = arrayGetSize(mesh.faces);
  176. for(i = 0; i < faceCount; i++)
  177. {
  178. triangle_t currentTriangle =
  179. {
  180. .textureCoordinates =
  181. {
  182. [0] = { mesh.faces[i].a_uv.u, mesh.faces[i].a_uv.v },
  183. [1] = { mesh.faces[i].b_uv.u, mesh.faces[i].b_uv.v },
  184. [2] = { mesh.faces[i].c_uv.u, mesh.faces[i].c_uv.v }
  185. }
  186. };
  187. vec4_t transformedVertices[3];
  188. vec3_t triangleNormal;
  189. vec3_t vertices[3] =
  190. {
  191. mesh.vertices[mesh.faces[i].a],
  192. mesh.vertices[mesh.faces[i].b],
  193. mesh.vertices[mesh.faces[i].c],
  194. };
  195. for(j = 0; j < 3; j++)
  196. {
  197. transformedVertices[j] = vec4FromVec3(vertices[j]);
  198. transformedVertices[j] = mat4ProdVec4(worldMatrix, transformedVertices[j]);
  199. }
  200. vec3_t vectorBA = vec3SubVectors(vec3FromVec4(transformedVertices[1]), vec3FromVec4(transformedVertices[0]));
  201. vec3_t vectorCA = vec3SubVectors(vec3FromVec4(transformedVertices[2]), vec3FromVec4(transformedVertices[0]));
  202. vec3Normalize(&vectorBA);
  203. vec3Normalize(&vectorCA);
  204. triangleNormal = vec3Cross(vectorBA, vectorCA);
  205. vec3Normalize(&triangleNormal);
  206. if (!doNotCull)
  207. {
  208. vec3_t cameraRay = vec3SubVectors(cameraPosition, vec3FromVec4(transformedVertices[0]));
  209. vec3Normalize(&cameraRay);
  210. double cameraDotTriangle = vec3Dot(triangleNormal, cameraRay);
  211. if (cameraDotTriangle < 0)
  212. {
  213. continue;
  214. }
  215. }
  216. for (j = 0 ; j < 3 ; j++)
  217. {
  218. vec4_t projected = mat4ProdVec4Project(projectionMatrix, transformedVertices[j]);
  219. projected.x *= windowWidth / 2.;
  220. projected.y *= windowHeight / 2.;
  221. /* Screen Y axis increase down, 3D world Y grows up, so we need to invert. */
  222. projected.y *= -1.0;
  223. projected.x += (windowWidth / 2.);
  224. projected.y += (windowHeight / 2.);
  225. currentTriangle.points[j].x = projected.x;
  226. currentTriangle.points[j].y = projected.y;
  227. currentTriangle.points[j].w = projected.w;
  228. currentTriangle.points[j].z = projected.z;
  229. }
  230. double lightLevel = -vec3Dot(triangleNormal, globalLight.direction);
  231. currentTriangle.colour = applyLight(mesh.faces[i].colour, lightLevel);
  232. currentTriangle.averageDepth = (transformedVertices[0].z +
  233. transformedVertices[1].z +
  234. transformedVertices[2].z) / 3.0;
  235. currentTriangle.texture = meshTexture;
  236. arrayAdd(projectedTriangles, currentTriangle);
  237. }
  238. if (!doZBuffer)
  239. {
  240. trianglesCount = arrayGetSize(projectedTriangles);
  241. qsort(projectedTriangles, trianglesCount, sizeof(triangle_t), compareTrianglesZOrder);
  242. }
  243. updateTime = (updateTime + (getMicroSecTime() - ticks) / 1000.) / 2.0;
  244. }
  245. void render()
  246. {
  247. int i;
  248. uint32_t ticks = getMicroSecTime();
  249. SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
  250. SDL_RenderClear(renderer);
  251. int triangleCount = arrayGetSize(projectedTriangles);
  252. for(i = 0; i < triangleCount; i++)
  253. {
  254. switch(currentDisplayMode)
  255. {
  256. case DISPLAY_MODE_SOLID:
  257. case DISPLAY_MODE_SOLID_WIRE:
  258. drawFilledTriangle(&projectedTriangles[i]);
  259. break;
  260. case DISPLAY_MODE_TEXTURED:
  261. case DISPLAY_MODE_TEXTURED_WIRE:
  262. drawTextureTriangle(&projectedTriangles[i]);
  263. break;
  264. default:
  265. break;
  266. }
  267. switch (currentDisplayMode)
  268. {
  269. case DISPLAY_MODE_SOLID_WIRE:
  270. case DISPLAY_MODE_TEXTURED_WIRE:
  271. case DISPLAY_MODE_WIREFRAME:
  272. drawTriangle(projectedTriangles[i].points[0].x, projectedTriangles[i].points[0].y,
  273. projectedTriangles[i].points[1].x, projectedTriangles[i].points[1].y,
  274. projectedTriangles[i].points[2].x, projectedTriangles[i].points[2].y,
  275. projectedTriangles[i].colour);
  276. break;
  277. default:
  278. break;
  279. }
  280. if (displayVertex)
  281. {
  282. int j;
  283. for(j = 0; j < 3; j++)
  284. {
  285. drawRectangle(projectedTriangles[i].points[j].x - 1,
  286. projectedTriangles[i].points[j].y - 1,
  287. 3, 3,
  288. 0xFFFF0000);
  289. }
  290. }
  291. }
  292. renderFrameBuffer();
  293. clearFrameBuffer(MAKE_RGB(0, 0, 0));
  294. clearZBuffer();
  295. renderTime = (renderTime + (getMicroSecTime() - ticks) / 1000.) / 2.0;
  296. drawText(5, 5, 0x11FF22, "Wait time: %02.2f ms", waitTime);
  297. drawText(5, 17, 0x11FF22, "Update time: %02.2f ms", updateTime);
  298. drawText(5, 29, 0x11FF22, "Render time: %02.2f ms", renderTime);
  299. drawText(5, 41, 0x11FF22, "FPS: %.2f", 1000 / (waitTime + updateTime + renderTime));
  300. drawText(5, 53, 0x11FF22, "Triangles: %d / %d", triangleCount, trianglesTotal);
  301. drawText(5, 65, 0x11FF22, "Cull: %s | PeCo: %s | ZB: %s",
  302. doNotCull?"N":"Y", doPerpectiveCorrection?"Y":"N", doZBuffer?"Y":"N");
  303. SDL_RenderPresent(renderer);
  304. }
  305. int main(int argc, char *argv[])
  306. {
  307. int param_i;
  308. bool fullScreen = false;
  309. MAX_DEBUG_LEVEL = TLOG_DEBUG;
  310. Log(TLOG_ALWAYS, NULL, "Booting 3D Engine (version %s)!", VERSION);
  311. for (param_i = 1 ; (param_i < argc) && (argv[param_i][0] == '-') ; param_i++)
  312. {
  313. switch (argv[param_i][1])
  314. {
  315. default: exit(-1); /* Option not recognized */
  316. case 'f': fullScreen = true; break;
  317. case 'w': windowWidth = atoi(argv[++param_i]);
  318. case 'h': windowHeight = atoi(argv[++param_i]); break;
  319. #ifdef DYNA_LOG_LEVEL
  320. case 'l': MAX_DEBUG_LEVEL = atoi(argv[++param_i]); break;
  321. #endif
  322. case '-': goto no_more_params; /* Could use break, but this is more clear */
  323. }
  324. }
  325. no_more_params:
  326. isRunning = initialiseWindow(fullScreen);
  327. setup();
  328. while (isRunning)
  329. {
  330. processInput();
  331. update();
  332. render();
  333. }
  334. arrayFree(projectedTriangles);
  335. textureCleanup();
  336. meshFree();
  337. destroyWindow();
  338. return 0;
  339. }