1
0
mirror of https://github.com/ssloy/tinyraytracer.git synced 2025-08-19 04:21:18 +02:00

Updated Home (markdown)

Dmitry V. Sokolov
2019-01-20 19:17:27 +01:00
parent abd78f2b1d
commit 2152ca723f

17
Home.md

@@ -131,13 +131,13 @@ At this point, I recommend you to take a pencil and check on paper all the calcu
<li>view direction, along the z-axis, in the direction of minus infinity</li>
</ul>
<h1>Этап третий: добавляем ещё сфер</h1>
Всё самое сложное уже позади, теперь наш путь безоблачен. Если мы умеем нарисовать одну сферу. то явно добавить ещё несколько труда не составит. <a href="https://github.com/ssloy/tinyraytracer/commit/c19c430151cb659372b4988876173b022164e371">Вот тут</a> смотреть изменения в коде, а вот так выглядит результат:
<h1>Step 3: add more spheres</h1>
The hardest part is over, and now our path is clear. If we know how to draw one sphere, it will not take us long to add few more. <a href="https://github.com/ssloy/tinyraytracer/commit/c19c430151cb659372b4988876173b022164e371">Check the changes</a> in the code, and this is the resulting image:
<img src="https://raw.githubusercontent.com/ssloy/tinyraytracer/c19c430151cb659372b4988876173b022164e371/out.jpg"/>
<h1>Этап четвёртый: освещение</h1>
Всем хороша наша картинка, да вот только освещения не хватает. На протяжении всей оставшейся статьи мы об этом только и будем разговаривать. Добавим несколько точечных источников освещения:
<h1>Stage 4: lighting</h1>
The image is perfect in all aspects, except for the lack of light. Throughout the rest of the article we will talk about lighting. Let's add few point light sources:
```c++
struct Light {
Light(const Vec3f &p, const float &i) : position(p), intensity(i) {}
@@ -146,9 +146,12 @@ struct Light {
};
```
Считать настоящее освещение - это очень и очень непростая задача, поэтому, как и все, мы будем обманывать глаз, рисуя совершенно нефизичные, но максимально возможно правдоподобные результаты. Первое замечание: почему зимой холодно, а летом жарко? Потому что нагрев поверхности земли зависит от угла падения солнечных лучей. Чем выше солнце над горизонтом, тем ярче освещается поверхность. И наоборот, чем ниже над горизонтом, тем слабее. Ну а после того, как солнце сядет за горизонт, до нас и вовсе фотоны не долетают. Применительно к нашим сферам: вот наш луч, испущенный из камеры (никакого отношения к фотонам, обратите внимание!) пересёкся со сферой. Как нам понять, как освещена точка пересечения? Можно просто посмотреть на угол между нормальным вектором в этой точке и вектором, описывающим направление света. Чем меньше угол, тем лучше освещена поверхность. Чтобы считать было ещё удобнее, можно просто взять скалярное произвдение между вектором нормали и вектором освещения. Напоминаю, что скалярное произвдение между двумя векторами a и b равно произведению норм векторов на косинус угла между векторами: a*b = |a| |b| cos(alpha(a,b)). Если взять векторы единичной длины, то простейшее скалярное произведение даст нам интенсивность освещения поверхности.
Computing real global illumination is a very, very difficult task, so like everyone else, we will trick the eye by drawing completely non-physical, but visually plausible results. To start with: why is it cold in winter and hot in summer? Because the heating of the Earth's surface depends on the angle of incidence of the Sun's rays. The higher the sun rises above the horizon, the brighter the surface is. Conversely, the lower it is above the horizon, the dimmer it is. And after the sun sets over the horizon, photons don't even reach us at all.
Таким образом, в функции cast_ray вместо постоянного цвета будем возвращать цвет с учётом источников освещения:
Back our spheres: we emit a ray from the camera (no relation to photons!) at it stops at a sphere. How do we know the intensity of the intersection point illumination? In fact, it suffices to check the angle between a normal vector in this point and the vector describing a direction of light. The smaller the angle, the better the surface is illuminated. Recall that the scalar product between two vectors a and b is equal to product of norms of vectors times the cosine of the angle between the vectors: a*b = |a| |b| cos(alpha(a,b)). If we take vectors of unit length, the scalar product will give us the intensity of surface illumination.
Thus, in the cast_ray function, instead of a constant color we will return the color taking into account the light sources:
```c++
Vec3f cast_ray(const Vec3f &orig, const Vec3f &dir, const Sphere &sphere) {
[...]
@@ -161,7 +164,7 @@ Vec3f cast_ray(const Vec3f &orig, const Vec3f &dir, const Sphere &sphere) {
}
```
Измениия <a href="https://github.com/ssloy/tinyraytracer/commit/9a728fff2bbebb1eedd86e1ac89f657d43191609">смотреть тут</a>, а вот результат работы программы:
The modifications w.r.t the previous step <a href="https://github.com/ssloy/tinyraytracer/commit/9a728fff2bbebb1eedd86e1ac89f657d43191609">are available here</a>, and here is the result:
<img src="https://raw.githubusercontent.com/ssloy/tinyraytracer/9a728fff2bbebb1eedd86e1ac89f657d43191609/out.jpg"/>