/*-
 * Copyright (c) 2001 Jordan DeLong
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the author nor the names of contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
#include "wm.h"

/* find intersection length of two lines */
static __inline int lineisect(int p1, int l1, int p2, int l2) {
	int tmp;

	/* make sure p1 <= p2 */
	if (p1 > p2) {
		swap(tmp, p1, p2);
		swap(tmp, l1, l2);
	}

	/* calculate the intersection */
	if (p1 + l1 < p2)
		return 0;
	else if (p2 + l2 < p1 + l1)
		return l2;
	else
		return p1 + l1 - p2;
}

/*
 * find the area of the intersection of two
 * rectangles.
 */
int rect_intersection(rect_t *r1, rect_t *r2) {
	int xsect, ysect;

	/*
	 * find intersection of lines in the x and
	 * y directions, multiply for the area of
	 * the intersection rectangle.
	 */
	xsect = lineisect(r1->x1, r1->x2 - r1->x1, r2->x1,
		r2->x2 - r2->x1);
	ysect = lineisect(r1->y1, r1->y2 - r1->y1, r2->y1,
		r2->y2 - r2->y1);

	return ysect * xsect;
}
