intersectRay method

Vector3? intersectRay(
  1. Ray ray,
  2. Vector3 result
)

Performs a ray/BVH node intersection test and stores the closest intersection point to the given 3D vector. If no intersection is detected, null is returned.

Implementation

Vector3? intersectRay(Ray ray, Vector3 result ) {
	// gather all intersection points along the hierarchy
	if ( ray.intersectAABB( boundingVolume, result ) != null ) {
		if ( leaf() == true ) {
			final vertices = primitives;

			for ( int i = 0, l = vertices.length; i < l; i += 9 ) {
				// remember: we assume primitives are triangles
				_triangle['a']?.fromArray( vertices, i );
				_triangle['b']?.fromArray( vertices, i + 3 );
				_triangle['c']?.fromArray( vertices, i + 6 );

				if ( ray.intersectTriangle( _triangle, true, result ) != null ) {
					_intersections.add( result.clone() );
				}
			}
		}
      else {
			// process childs
			for ( int i = 0, l = children.length; i < l; i ++ ) {
				children[ i ].intersectRay( ray, result );
			}
		}
	}

	// determine the closest intersection point in the root node (so after
	// the hierarchy was processed)
	if ( root() == true ) {
		if ( _intersections.isNotEmpty ) {
			double minDistance = double.infinity;

			for ( int i = 0, l = _intersections.length; i < l; i ++ ) {
				final squaredDistance = ray.origin.squaredDistanceTo( _intersections[ i ] );

				if ( squaredDistance < minDistance ) {
					minDistance = squaredDistance;
					result.copy( _intersections[ i ] );
				}
			}

			// reset array
			_intersections.length = 0;

			// return closest intersection point
			return result;
		}
      else {
			// no intersection detected
			return null;
		}
	}
    else {
		// always return null for non-root nodes
		return null;
	}
}