You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.3 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. #include "Scene.h"
  2. #include "util.h"
  3. #include "Camera.h"
  4. #include "Ray.h"
  5. #include "Vector3.h"
  6. #include "Sphere.h"
  7. #pragma comment(lib, "winmm.lib")
  8. static int sTotalPixelCount = 0;
  9. static int sViewportWidth = 0, sViewportHeight = 0;
  10. static Camera* sCamera = nullptr;
  11. Sphere sphere(Vector3(0.0f, 0.0f, -5.0f), 0.5f);
  12. void Init(int width, int height)
  13. {
  14. sTotalPixelCount = width * height;
  15. sViewportWidth = width;
  16. sViewportHeight = height;
  17. sCamera = new Camera(45.0f, float(width) / float(height));
  18. sCamera->LookAt(Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, 0.0f, -1.0f), Vector3(0.0f, 1.0f, 0.0f));
  19. }
  20. float GetEscaptedTime() {
  21. static unsigned long sTimeSinceComputerStart = 0;
  22. static unsigned long sLastFrameTime = 0;
  23. sTimeSinceComputerStart = timeGetTime();
  24. unsigned long frame_time = sLastFrameTime == 0 ? 0 : sTimeSinceComputerStart - sLastFrameTime;
  25. sLastFrameTime = sTimeSinceComputerStart;
  26. return float(frame_time) / 1000.0f;
  27. }
  28. Vector3 GetEnviromentColor(const Ray& input_ray) {
  29. Vector3 bottom_color(1.0f, 1.0f, 1.0f);
  30. Vector3 top_color(0.5f, 0.7f, 1.0f);
  31. float factor = 0.5f * input_ray.mDirection.y + 0.5f;
  32. return factor * top_color + (1.0f - factor) * bottom_color;
  33. }
  34. void RenderOnePixel(int pixel_index) {
  35. int x = pixel_index % sViewportWidth;
  36. int y = pixel_index / sViewportWidth;
  37. float u = float(x) / sViewportWidth;
  38. float v = float(y) / sViewportHeight;
  39. Ray ray = sCamera->GetRay(u,v);
  40. HitPoint hit_point;
  41. if (sphere.HitTest(ray, 0.0f, 100.0f, hit_point)) {
  42. float rf = hit_point.mNormal.x * 0.5f + 0.5f;
  43. float gf = hit_point.mNormal.y * 0.5f + 0.5f;
  44. float bf = hit_point.mNormal.z * 0.5f + 0.5f;
  45. AByte r = AByte(rf * 255.0f);
  46. AByte g = AByte(gf * 255.0f);
  47. AByte b = AByte(bf * 255.0f);
  48. SetColor(x, y, r, g, b, 255);
  49. }
  50. else {
  51. Vector3 color = GetEnviromentColor(ray);
  52. AByte r = AByte(color.x * 255.0f);
  53. AByte g = AByte(color.y * 255.0f);
  54. AByte b = AByte(color.z * 255.0f);
  55. SetColor(x, y, r, g, b, 255);
  56. }
  57. }
  58. void Render()
  59. {
  60. static int sCurrentRenderPixel = 0;
  61. float current_render_time = 0.0f;
  62. while (sCurrentRenderPixel < sTotalPixelCount) {
  63. RenderOnePixel(sCurrentRenderPixel);
  64. sCurrentRenderPixel++;
  65. current_render_time = GetEscaptedTime();
  66. if (current_render_time > 0.016f) {
  67. break;
  68. }
  69. }
  70. }