9
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PR: デジタル創作サークルUniProject
UniProject公式HP

C++レイトレーサー自作シリーズ

Part1 レイ/ベクトル Part2 交差判定 Part3 反射/屈折 Part4 マテリアル Part5 BVH Part6 パストレ
✅ ✅ 👈 Now - - -

はじめに

前回は球や平面を描けるようになった。

今回は反射と屈折を実装して、鏡やガラスを表現しよう。

拡散反射(Diffuse)

まずは基本的な拡散反射から。

拡散反射は、光が物体表面でランダムな方向に散乱する現象。

┌──────────────────────────────────────────────────────────────┐
│ 拡散反射                                                     │
│                                                              │
│       入射光                                                 │
│         ↓                                                    │
│   ──────●────── 表面                                        │
│        /|\                                                   │
│       / | \                                                  │
│      ↙  ↓  ↘   ランダムな方向に散乱                         │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Lambertian拡散

最も単純な拡散モデル。反射方向は法線を中心とした半球からランダムに選ぶ。

// 単位球内のランダムな点
Vec3 random_in_unit_sphere() {
    while (true) {
        auto p = Vec3(
            random_double(-1, 1),
            random_double(-1, 1),
            random_double(-1, 1)
        );
        if (p.length_squared() < 1) {
            return p;
        }
    }
}

// 単位球面上のランダムな点
Vec3 random_unit_vector() {
    return normalize(random_in_unit_sphere());
}

// Lambertian拡散の反射方向
Vec3 random_in_hemisphere(const Vec3& normal) {
    Vec3 in_unit_sphere = random_in_unit_sphere();
    if (dot(in_unit_sphere, normal) > 0.0) {
        return in_unit_sphere;  // 法線と同じ側
    } else {
        return -in_unit_sphere; // 反対側なら反転
    }
}

True Lambertian

より物理的に正確な方法は、法線方向にオフセットしてからランダム方向を足す。

Vec3 target = rec.p + rec.normal + random_unit_vector();
return ray_color(Ray(rec.p, target - rec.p), world, depth - 1);

鏡面反射(Specular)

鏡のような完全反射を実装しよう。

┌──────────────────────────────────────────────────────────────┐
│ 鏡面反射                                                     │
│                                                              │
│       入射光 ↘      ↗ 反射光                                │
│              ↘    ↗                                         │
│               ↘  ↗                                          │
│   ─────────────●─────────── 表面                            │
│                 ↑ 法線                                       │
│                                                              │
│   反射角 = 入射角                                            │
└──────────────────────────────────────────────────────────────┘

反射ベクトルの計算

Vec3 reflect(const Vec3& v, const Vec3& n) {
    return v - 2 * dot(v, n) * n;
}

導出

入射ベクトル $\vec{v}$ を法線 $\vec{n}$ に対して反射。

  1. $\vec{v}$ の法線方向成分: $(\vec{v} \cdot \vec{n}) \vec{n}$
  2. 反射で法線方向成分は反転: $\vec{r} = \vec{v} - 2(\vec{v} \cdot \vec{n}) \vec{n}$

屈折(Refraction)

ガラスや水を通る光は屈折する。

┌──────────────────────────────────────────────────────────────┐
│ 屈折(スネルの法則)                                         │
│                                                              │
│   空気 (n=1.0)                                               │
│       入射光 ↘                                               │
│              ↘ θ₁                                           │
│   ────────────●────────── 境界面                            │
│               ↘ θ₂                                          │
│                ↘                                             │
│   ガラス (n=1.5)   屈折光                                    │
│                                                              │
│   n₁ sin(θ₁) = n₂ sin(θ₂)                                   │
└──────────────────────────────────────────────────────────────┘

スネルの法則

$$n_1 \sin\theta_1 = n_2 \sin\theta_2$$

屈折率の比: $\eta = n_1 / n_2$

屈折ベクトルの計算

Vec3 refract(const Vec3& uv, const Vec3& n, double etai_over_etat) {
    auto cos_theta = std::fmin(dot(-uv, n), 1.0);
    Vec3 r_out_perp = etai_over_etat * (uv + cos_theta * n);
    Vec3 r_out_parallel = -std::sqrt(std::fabs(1.0 - r_out_perp.length_squared())) * n;
    return r_out_perp + r_out_parallel;
}

全反射

入射角が臨界角を超えると、光は屈折せずに全て反射する。

$$\sin\theta_c = \frac{n_2}{n_1}$$

bool cannot_refract = etai_over_etat * sin_theta > 1.0;
if (cannot_refract) {
    // 全反射
    direction = reflect(unit_direction, rec.normal);
} else {
    // 屈折
    direction = refract(unit_direction, rec.normal, etai_over_etat);
}

マテリアルクラス

反射の種類をマテリアルとして抽象化しよう。

class Material {
public:
    virtual ~Material() = default;
    
    virtual bool scatter(
        const Ray& r_in,
        const HitRecord& rec,
        Color& attenuation,
        Ray& scattered
    ) const = 0;
};

Lambertian(拡散反射)

class Lambertian : public Material {
public:
    Color albedo;  // 反射率
    
    Lambertian(const Color& albedo) : albedo(albedo) {}
    
    bool scatter(const Ray& r_in, const HitRecord& rec,
                 Color& attenuation, Ray& scattered) const override {
        auto scatter_direction = rec.normal + random_unit_vector();
        
        // ゼロベクトル対策
        if (scatter_direction.near_zero()) {
            scatter_direction = rec.normal;
        }
        
        scattered = Ray(rec.p, scatter_direction);
        attenuation = albedo;
        return true;
    }
};

Metal(金属反射)

class Metal : public Material {
public:
    Color albedo;
    double fuzz;  // 粗さ(0=鏡、1=ぼやける)
    
    Metal(const Color& albedo, double fuzz) 
        : albedo(albedo), fuzz(fuzz < 1 ? fuzz : 1) {}
    
    bool scatter(const Ray& r_in, const HitRecord& rec,
                 Color& attenuation, Ray& scattered) const override {
        Vec3 reflected = reflect(normalize(r_in.direction), rec.normal);
        scattered = Ray(rec.p, reflected + fuzz * random_in_unit_sphere());
        attenuation = albedo;
        return (dot(scattered.direction, rec.normal) > 0);
    }
};

fuzzパラメータで反射のぼやけ具合を制御できる。

Dielectric(誘電体/ガラス)

class Dielectric : public Material {
public:
    double ir;  // 屈折率
    
    Dielectric(double index_of_refraction) : ir(index_of_refraction) {}
    
    bool scatter(const Ray& r_in, const HitRecord& rec,
                 Color& attenuation, Ray& scattered) const override {
        attenuation = Color(1.0, 1.0, 1.0);  // ガラスは減衰なし
        
        double refraction_ratio = rec.front_face ? (1.0 / ir) : ir;
        
        Vec3 unit_direction = normalize(r_in.direction);
        double cos_theta = std::fmin(dot(-unit_direction, rec.normal), 1.0);
        double sin_theta = std::sqrt(1.0 - cos_theta * cos_theta);
        
        bool cannot_refract = refraction_ratio * sin_theta > 1.0;
        Vec3 direction;
        
        if (cannot_refract || reflectance(cos_theta, refraction_ratio) > random_double()) {
            direction = reflect(unit_direction, rec.normal);
        } else {
            direction = refract(unit_direction, rec.normal, refraction_ratio);
        }
        
        scattered = Ray(rec.p, direction);
        return true;
    }

private:
    // Schlickの近似式
    static double reflectance(double cosine, double ref_idx) {
        auto r0 = (1 - ref_idx) / (1 + ref_idx);
        r0 = r0 * r0;
        return r0 + (1 - r0) * std::pow((1 - cosine), 5);
    }
};

Schlickの近似式

ガラスは角度によって反射率が変わる(フレネル効果)。

正確な計算は重いので、Schlickの近似式を使う:

$$R(\theta) = R_0 + (1 - R_0)(1 - \cos\theta)^5$$

$$R_0 = \left(\frac{n_1 - n_2}{n_1 + n_2}\right)^2$$

HitRecordにマテリアルを追加

struct HitRecord {
    Point3 p;
    Vec3 normal;
    std::shared_ptr<Material> mat_ptr;  // 追加
    double t;
    bool front_face;
    
    // ...
};

レイの色を計算(再帰)

Color ray_color(const Ray& r, const Hittable& world, int depth) {
    // 反射回数の上限
    if (depth <= 0) {
        return Color(0, 0, 0);
    }
    
    HitRecord rec;
    
    if (world.hit(r, 0.001, infinity, rec)) {
        Ray scattered;
        Color attenuation;
        
        if (rec.mat_ptr->scatter(r, rec, attenuation, scattered)) {
            return attenuation * ray_color(scattered, world, depth - 1);
        }
        
        return Color(0, 0, 0);
    }
    
    // 背景
    Vec3 unit_direction = normalize(r.direction);
    auto t = 0.5 * (unit_direction.y + 1.0);
    return (1.0 - t) * Color(1.0, 1.0, 1.0) + t * Color(0.5, 0.7, 1.0);
}

0.001をt_minにしているのは、シャドウアクネを防ぐため。浮動小数点の誤差で自分自身にヒットしてしまうのを避ける。

シーンの例

HittableList world;

// 地面
auto ground = std::make_shared<Lambertian>(Color(0.8, 0.8, 0.0));
world.add(std::make_shared<Sphere>(Point3(0, -100.5, -1), 100, ground));

// 中央の球(拡散)
auto center = std::make_shared<Lambertian>(Color(0.1, 0.2, 0.5));
world.add(std::make_shared<Sphere>(Point3(0, 0, -1), 0.5, center));

// 左の球(ガラス)
auto left = std::make_shared<Dielectric>(1.5);
world.add(std::make_shared<Sphere>(Point3(-1, 0, -1), 0.5, left));

// 左の球(中空ガラス)
world.add(std::make_shared<Sphere>(Point3(-1, 0, -1), -0.45, left));

// 右の球(金属)
auto right = std::make_shared<Metal>(Color(0.8, 0.6, 0.2), 0.0);
world.add(std::make_shared<Sphere>(Point3(1, 0, -1), 0.5, right));

負の半径を使うと、法線が内側を向く中空の球が作れる。ガラス玉の中を表現できる。

各マテリアルの特徴

マテリアル 屈折率 例
真空 1.0 -
空気 1.0003 -
水 1.33 プール
ガラス 1.5 窓
ダイヤモンド 2.4 宝石

視覚効果

色付きガラス

attenuationを変えると色付きガラスになる。

// 赤いガラス
attenuation = Color(1.0, 0.2, 0.2);

ファジー反射

金属のfuzzを上げると、ブラシ仕上げの金属みたいになる。

auto brushed_metal = std::make_shared<Metal>(Color(0.8, 0.8, 0.8), 0.3);

デバッグTips

法線の確認

何か変なとき、まず法線を色として出力してみる。

// デバッグ用
return 0.5 * (rec.normal + Color(1, 1, 1));

反射回数の制限

無限ループに入らないよう、必ずdepthをチェック。

const int max_depth = 50;
ray_color(r, world, max_depth);

まとめ

トピック ポイント
拡散反射 ランダムな方向に散乱
鏡面反射 入射角 = 反射角
屈折 スネルの法則
全反射 臨界角を超えると反射
フレネル効果 角度で反射率が変わる
Schlickの近似 フレネル効果の近似

次回はマテリアルとテクスチャで、より複雑な見た目を実現するよ。

この記事が役に立ったら、いいね・ストックしてもらえると嬉しいです!

9
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?