Sphere类定义

这个类是球体,也就是一会要显示的球体了。这个类继承于Geometrics类,并实现了自己的碰撞检测,碰撞原理,书上也说的很清楚了啊,大家多看。然后对照代码就明白了。

类定义:

#pragma once
#ifndef __SPHERE_HEADER__
#define __SPHERE_HEADER__

#include "../geometics.h"

class Sphere :public Geometrics {
public:
	Sphere();
	~Sphere();
	Sphere(const Point3& center, ldouble radius);
	Sphere(const Sphere& sp);
	virtual Geometrics* clone() const;
	virtual bool hit(const Ray& ray, ldouble& tmin, ShadeRec& sr) const;
	Sphere& operator=(const Sphere& sp);
	void set_center(const Point3& p);
	Point3 get_center() const;
	void set_radius(const ldouble rd);
	ldouble get_radius() const;
private:
	Point3 c;
	ldouble r;
};
#endif

类实现:

#include "pch.h"
#include "sphere.h"

Sphere::Sphere() :Geometrics(), c(), r(0) {}

Sphere::~Sphere() {}

Sphere::Sphere(const Point3& center, ldouble radius) : Geometrics(), c(center), r(radius) {}

Sphere::Sphere(const Sphere& sp) : Geometrics(sp), c(sp.c), r(sp.r) {}

Geometrics* Sphere::clone() const {
	return new Sphere(*this);
}

bool Sphere::hit(const Ray& ray, ldouble& tmin, ShadeRec& sr) const {
	ldouble t;
	Vector3 oc = ray.o - c;
	ldouble a = ray.d * ray.d,
		b = 2.0 * oc * ray.d,
		c = oc * oc - r * r,
		disc = b * b - 4.0 * a * c;
	if (disc >= 0) {
		t = (-b - std::sqrt(disc)) / (2.0 * a);
		if (t > 0) {
			tmin = t;
			sr.normal = (oc + t * ray.d) / r;
			sr.local_hit_point = ray.o + t * ray.d;
			return true;
		}
		t = (-b + std::sqrt(disc)) / (2.0 * a);
		if (t > 0) {
			tmin = t;
			sr.normal = (oc + t * ray.d) / r;
			sr.local_hit_point = ray.o + t * ray.d;
			return true;
		}
	}
	return false;
}

Sphere& Sphere::operator=(const Sphere& sp) {
	if (this == &sp)
		return *this;
	Geometrics::operator=(sp);
	c = sp.c;
	r = sp.r;
	return *this;
}

void Sphere::set_center(const Point3& p) {
	c = p;
}

Point3 Sphere::get_center() const {
	return c;
}

void Sphere::set_radius(const ldouble rd) {
	r = rd;
}

ldouble Sphere::get_radius() const {
	return r;
}

  

猜你喜欢

转载自www.cnblogs.com/dalgleish/p/12602731.html