Determine all points of intersection for two 3D (coplanar) triangles - java

I am trying to determine all of the points where two 3D but coplanar triangles intersect. I have found methods that detect if the triangles intersect but what I truly need is the actual points where the intersection occurs. Below I have shown a few cases of this situation.
Also, I will be coding this in Java but I am sure I could convert a different language as long as I understand the math!
I know all the vertices but that is it!
Edited for clarification.
Thanks,
Michael
https://www.dropbox.com/s/yoszrlfqbx3usrf/cases.png?dl=0

if you don't have the equation for the plane you'll need to calculate it.
ignore the z axis for now (unless that makes all your points fall on the same line in which case ignore another axis :)
find the intersections for every edge of the first triangle and every edge of the other triangle
plug the intersections back into the equation of your plane to recover z
for step 3: from line line intersection wikipedia article
discard any intersections that don't fall on both edges
here's a js snippet that does step 3
var a;
var b;
var bs = document.body.style;
var ds = document.documentElement.style;
bs.height = bs.width = ds.height = ds.width = "100%";
bs.border = bs.margin = bs.padding = 0;
var c = document.createElement("canvas");
c.style.display = "block";
c.addEventListener("mousedown", randomize, false);
c.addEventListener("mousemove", follow, false);
document.body.appendChild(c);
var ctx = c.getContext("2d");
window.addEventListener("resize", redraw);
randomize();
function randomPoint() {
return {x:Math.random() * window.innerWidth,
y: Math.random() * window.innerHeight};
}
function randomize(e) {
a = [];
b = [];
for (var i = 0; i < 3; i++) {
a[i] = randomPoint();
b[i] = randomPoint();
}
redraw();
}
function follow(e) {
var average = {x:0, y:0};
for (var i = 0; i < 3; i++) {
average.x += a[i].x / 3;
average.y += a[i].y / 3;
}
for (var i = 0; i < 3; i++) {
a[i].x += e.clientX - average.x;
a[i].y += e.clientY - average.y;
}
redraw();
}
function drawPoint(p, color) {
ctx.strokeStyle = color;
ctx.beginPath();
ctx.arc(p.x, p.y, 10, 0, 2 * Math.PI, true);
ctx.closePath();
ctx.stroke();
}
function isPointOnLine(p, v1, v2) {
if (v1.x === v2.x)
return (Math.max(v1.y, v2.y) >= p.y && Math.min(v1.y, v2.y) <= p.y)
else
return (Math.max(v1.x, v2.x) >= p.x && Math.min(v1.x, v2.x) <= p.x)
}
function calculateIntersection(a1, a2, b1, b2) {
var d = (a1.x - a2.x)*(b1.y - b2.y) -
(a1.y - a2.y)*(b1.x - b2.x);
if (!d) return null;
return {
x:((a1.x*a2.y - a1.y*a2.x)*(b1.x - b2.x) -
(a1.x - a2.x)*(b1.x*b2.y - b1.y*b2.x)) / d,
y:((a1.x*a2.y - a1.y*a2.x)*(b1.y - b2.y) -
(a1.y - a2.y)*(b1.x*b2.y - b1.y*b2.x)) / d
};
}
function drawIntersections(a, b) {
a.forEach(function (a1, i) {
var a2 = a[(i + 1) % a.length];
b.forEach(function (b1, j) {
var b2 = b[(j + 1) % b.length];
var p = calculateIntersection(a1, a2, b1, b2);
if(!p) return;
if (isPointOnLine(p, a1, a2) && isPointOnLine(p, b1, b2))
drawPoint(p, "red");
else
drawPoint(p, "yellow");
});
});
}
function drawShape(shape) {
ctx.strokeStyle = "black";
ctx.beginPath();
ctx.moveTo(shape[0].x, shape[0].y);
for (var i = 1; i <= shape.length; i++) {
ctx.lineTo(shape[i % shape.length].x, shape[i % shape.length].y);
}
ctx.closePath();
ctx.stroke();
}
function redraw() {
c.width = window.innerWidth;
c.height = window.innerHeight;
ctx.clearRect(0, 0, c.width, c.height);
ctx.fillStyle = "rgb(200, 200, 200)";
ctx.font = "40px serif";
ctx.fillText("click to randomize", 20, 40);
drawShape(a);
drawShape(b);
drawIntersections(a, b);
}

Related

Java - get alpha value between 0 - 255 using distance between two objects

I am working on a 2D platformer game. There are star objects in the background and these stars move around. I wanted to draw lines between them and I've managed to do this without much effort. What I am now trying to do is to add an alpha value(transparency) to the lines being drawn.
I have tried to write an equation where alpha value is inversely proportional to the value of distance between two objects but have not succeeded.
How do I mathematically express the following rule ?
The larger the distance is, the lesser value of alpha gets
For example, if the distance is 400 then the transparency value should be 0 (java.awt.Color uses 0 as 100% transparency and 255 as no transparency)
here is an example of what I am trying to achieve:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var stars = [], // Array that contains the stars
FPS = 60, // Frames per second
x = 40, // Number of stars
mouse = {
x: 0,
y: 0
}; // mouse location
// Push stars to the array
for (var i = 0; i < x; i++) {
stars.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
radius: Math.random() * 1 + 1,
vx: Math.floor(Math.random() * 50) - 25,
vy: Math.floor(Math.random() * 50) - 25
});
}
// Draw the scene
function draw() {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.globalCompositeOperation = "lighter";
for (var i = 0, x = stars.length; i < x; i++) {
var s = stars[i];
ctx.fillStyle = "#fff";
ctx.beginPath();
ctx.arc(s.x, s.y, s.radius, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = 'black';
ctx.stroke();
}
ctx.beginPath();
for (var i = 0, x = stars.length; i < x; i++) {
var starI = stars[i];
ctx.moveTo(starI.x,starI.y);
if(distance(mouse, starI) < 150) ctx.lineTo(mouse.x, mouse.y);
for (var j = 0, x = stars.length; j < x; j++) {
var starII = stars[j];
if(distance(starI, starII) < 150) {
//ctx.globalAlpha = (1 / 150 * distance(starI, starII).toFixed(1));
ctx.lineTo(starII.x,starII.y);
}
}
}
ctx.lineWidth = 0.05;
ctx.strokeStyle = 'white';
ctx.stroke();
}
function distance( point1, point2 ){
var xs = 0;
var ys = 0;
xs = point2.x - point1.x;
xs = xs * xs;
ys = point2.y - point1.y;
ys = ys * ys;
return Math.sqrt( xs + ys );
}
// Update star locations
function update() {
for (var i = 0, x = stars.length; i < x; i++) {
var s = stars[i];
s.x += s.vx / FPS;
s.y += s.vy / FPS;
if (s.x < 0 || s.x > canvas.width) s.vx = -s.vx;
if (s.y < 0 || s.y > canvas.height) s.vy = -s.vy;
}
}
canvas.addEventListener('mousemove', function(e){
mouse.x = e.clientX;
mouse.y = e.clientY;
});
// Update and draw
function tick() {
draw();
update();
requestAnimationFrame(tick);
}
tick();
canvas {
background: #232323;
}
<canvas id="canvas"></canvas>
You should use:
((MAX_DISTANCE - distance) / MAX_DISTANCE) * 255
Explanation:
(MAX_DISTANCE - distance) makes sure that the larger the distance, the smaller the result.
Then, diving by MAX_DISTANCE and multiplying by 255, scales it from 0-MAX_DISTANCE to 0-255.

How to detect if two paths intersect in android?

I'm making a small sprouts app where the user can draw paths between dots or on the screen with paths. I create arraylists of the coordinates of the paths and then attempt to compare them four points at a time to see if they intersect with paths already drawn. Right now, it isn't detecting any collisions. Here some of my code so far:
//ArrayList of the currentPath that is being drawn
ArrayList<float[]> currentPath = new ArrayList<>();
//ArrayList of Paths that have been drawn so far
private ArrayList <ArrayList<float[]>> paths = new ArrayList<>();
public boolean checkPath() {
if (paths.size() == 0) {
return true;
} else {
boolean noCollisions = true;
for (int i = 0; i < paths.size(); i++) { //Loop through path array to compare each path
for (int j = 0; j < paths.get(i).size() - 1; j++) { //Loop through each path to compare points
for (int k = 0; k < currentPath.size() - 1; k++) {
float end1Y = currentPath.get(k + 1)[1];
float start1Y = currentPath.get(k)[1];
float start1X = currentPath.get(k)[0];
float end1X = currentPath.get(k + 1)[0];
float end2Y = paths.get(i).get(j + 1)[1];
float start2Y = paths.get(i).get(j)[1];
float start2X = paths.get(i).get(j)[0];
float end2X = paths.get(i).get(j + 1)[0];
double A1 = end1Y - start1Y;
double B1 = start1X - end1X;
double C1 = A1 * start1X + B1 + start1Y;
double A2 = end2Y - start2Y;
double B2 = start2X - end2X;
double C2 = A2 * start2X + B2 * start2Y;
double det = (A1 * B2) - (A2 * B1);
if (det == 0) {
//Lines are either parallel, are collinear or overlapping partially
if ((A1 * start2X) + (B1 * start2Y) == C1) {
//they are the on the same line, check if they are in the same space
if ((Math.min(start1X, end1X) < start2X) && (Math.max(start1X, end1X) > start2X)) {
noCollisions = false;
}
//one end point is okay, now checking the other
if ((Math.min(start1X, end1X) < end2X) && (Math.max(start1X, end1X) > end2X)) {
noCollisions = false;
} else{
noCollisions = true;
}
}
} else {
//Lines intersect somewhere, but do the segments intersect?
double x = (B2 * C1 - B1 * C2) / det;
double y = (A1 * C2 - A2 * C1) / det;
//check to see if the intersection is within the bounding box of the segments.
if((x > Math.min(start1X, end1X) && x < Math.max(start1X, end1X)) && (y > Math.min(start1Y, end1Y) && y < Math.max(start1Y, end1Y))){
//We are within the bounding box of the first line segment, now check the second
if((x > Math.min(start2X, end2X) && x < Math.max(start2X, end2X)) && (y > Math.min(start2Y, end2Y) && y < Math.max(start2Y, end2Y))){
//the segments intersect
noCollisions = false;
}
} else {
noCollisions = true;
}
}
}
}
}
return noCollisions;
}
}
I'm trying to use matrices and determinantes to figure out if there is any intersection occurring.
Please try to replace below line
double C1 = A1 * start1X + B1 + start1Y;
by following line
double C1 = A1 * start1X + B1 * start1Y;
Ain't this easier?
Region region1, region2;
boolean intersect;
Region clip = new Region(0, 0, screenWidth, screenHeight);
region1.setPath(path1, clip);
region2.setPath(path2, clip);
if (!region1.quickReject(region2))
intersect = true;
else intersect = false;
(I know I'm late)

Computing area of a polygon in Java

I have a class called SimplePolygon that creates a polygon with coordinates provided by the user. I am trying to define a method to compute the area of the polygon. It's an assignment and course instructor wants us to use the following formula to compute the area.
I can use either formula. I chose the right one.
My code gives me the wrong area. I don't know what's wrong.
public class SimplePolygon implements Polygon {
protected int n; // number of vertices of the polygon
protected Point2D.Double[] vertices; // vertices[0..n-1] around the polygon
public double area() throws NonSimplePolygonException {
try
{
if(isSimple()==false)
throw new NonSimplePolygonException();
else
{
double sum = 0;
for(int i = 0; i < vertices.length - 1; i++)
if(i == 0)
sum += vertices[i].x * (vertices[i+1].y - vertices[vertices.length - 1].y);
else
sum += vertices[i].x * (vertices[i+1].y - vertices[i-1].y);
double area = 0.5 * Math.abs(sum);
return area;
}
}
catch(NonSimplePolygonException e)
{
System.out.println("The Polygon is not simple.");
}
return 0.0;
}
The following is a tester code. The polygon is a rectangle with area 2, but the output is 2.5
Point2D.Double a = new Point2D.Double(1,1);
Point2D.Double b = new Point2D.Double(3,1);
Point2D.Double c = new Point2D.Double(3,2);
Point2D.Double d = new Point2D.Double(1,2);
SimplePolygon poly = new SimplePolygon(4);
poly.vertices[0] = a;
poly.vertices[1] = b;
poly.vertices[2] = c;
poly.vertices[3] = d;
System.out.println(poly.area());
Now that you've fixed the trivial boundary case, you're missing another boundary and your loop is wrong. Corrected code with debug:
public double area()
{
double sum = 0;
for (int i = 0; i < vertices.length ; i++)
{
if (i == 0)
{
System.out.println(vertices[i].x + "x" + (vertices[i + 1].y + "-" + vertices[vertices.length - 1].y));
sum += vertices[i].x * (vertices[i + 1].y - vertices[vertices.length - 1].y);
}
else if (i == vertices.length - 1)
{
System.out.println(vertices[i].x + "x" + (vertices[0].y + "-" + vertices[i - 1].y));
sum += vertices[i].x * (vertices[0].y - vertices[i - 1].y);
}
else
{
System.out.println(vertices[i].x + "x" + (vertices[i + 1].y + "-" + vertices[i - 1].y));
sum += vertices[i].x * (vertices[i + 1].y - vertices[i - 1].y);
}
}
double area = 0.5 * Math.abs(sum);
return area;
}
There is one missing term from the sum: vertices[n-1].x * (vertices[0].y - vertices[n-2].y).
Before the edit of the question there was also a problem with the first term:
Furthermore, if i==0 the term should be vertices[i].x * (vertices[i+1].y - vertices[n-1].y).
Assuming that n is equal to vertices.length.
The simplest way to code the loop is probably:
n = vertices.length;
sum =0;
for (int i = 0; i < n; i++) {
sum += vertices[i].x * (vertices[(i + 1) % n].y - vertices[(i + n - 1) % n].y);
}
I found another way,
Add first element again into polygon array
So that we can avoid "Out of bound" case as well as many If conditions.
Here is my solution:
public class PolygonArea {
public static void main(String[] args) {
PolygonArea p = new PolygonArea();
System.out.println(p.calculateArea());
}
Point[] points = new Point[5];
public double calculateArea() {
points[0] = new Point("A", 4, 10);
points[1] = new Point("B", 9, 7);
points[2] = new Point("C", 11, 2);
points[3] = new Point("D", 2, 2);
/** Add first entry again to polygon */
points[4] = new Point("A", 4, 10);
double sum = 0.0;
for (int i = 0; i < points.length - 1; ++i) {
sum += (points[i].X * points[i + 1].Y) - (points[i + 1].X * points[i].Y);
}
return Math.abs(sum / 2);
}
class Point {
final String _ID;
final int X;
final int Y;
public Point(String id, int x, int y) {
_ID = id;
X = x;
Y = y;
}
}
}

Perspective View to Parallel View

in the example which is given in the book "Computer Graphics for Java Programmers, Second Edition"
there is transformation with view vector
private void shiftToOrigin()
{ float xwC = 0.5F * (xMin + xMax),
ywC = 0.5F * (yMin + yMax),
zwC = 0.5F * (zMin + zMax);
int n = w.size();
for (int i=1; i<n; i++)
if (w.elementAt(i) != null)
{ ((Point3D)w.elementAt(i)).x -= xwC;
((Point3D)w.elementAt(i)).y -= ywC;
((Point3D)w.elementAt(i)).z -= zwC;
}
float dx = xMax - xMin, dy = yMax - yMin, dz = zMax - zMin;
rhoMin = 0.6F * (float) Math.sqrt(dx * dx + dy * dy + dz * dz);
rhoMax = 1000 * rhoMin;
rho = 3 * rhoMin;
}
private void initPersp()
{
float costh = (float)Math.cos(theta),
sinth = (float)Math.sin(theta),
cosph = (float)Math.cos(phi),
sinph = (float)Math.sin(phi);
v11 = -sinth; v12 = -cosph * costh; v13 = sinph * costh;
v21 = costh; v22 = -cosph * sinth; v23 = sinph * sinth;
v32 = sinph; v33 = cosph;
v43 = -rho;
}
float eyeAndScreen(Dimension dim)
// Called in paint method of Canvas class
{ initPersp();
int n = w.size();
e = new Point3D[n];
vScr = new Point2D[n];
float xScrMin=1e30F, xScrMax=-1e30F,
yScrMin=1e30F, yScrMax=-1e30F;
for (int i=1; i<n; i++)
{
Point3D P = (Point3D)(w.elementAt(i));
if (P == null)
{ e[i] = null; vScr[i] = null;
}
else
{ float x = v11 * P.x + v21 * P.y;
float y = v12 * P.x + v22 * P.y + v32 * P.z;
float z = v13 * P.x + v23 * P.y + v33 * P.z + v43;
Point3D Pe = e[i] = new Point3D(x, y, z);
float xScr = -Pe.x/Pe.z, yScr = -Pe.y/Pe.z;
vScr[i] = new Point2D(xScr, yScr);
if (xScr < xScrMin) xScrMin = xScr;
if (xScr > xScrMax) xScrMax = xScr;
if (yScr < yScrMin) yScrMin = yScr;
if (yScr > yScrMax) yScrMax = yScr;
}
}
float rangeX = xScrMax - xScrMin, rangeY = yScrMax - yScrMin;
d = 0.95F * Math.min(dim.width/rangeX, dim.height/rangeY); //d burada
imgCenter = new Point2D(d * (xScrMin + xScrMax)/2,
d * (yScrMin + yScrMax)/2);
for (int i=1; i<n; i++)
{
if (vScr[i] != null){vScr[i].x *= d; vScr[i].y *= d;}
}
return d * Math.max(rangeX, rangeY);
// Maximum screen-coordinate range used in CvHLines for HP-GL
}
here float xScr = -Pe.x/Pe.z, yScr = -Pe.y/Pe.z; when we divide x and y with z that give as a perspective view if we don't divide it with z the view will be parallel(orthogonal)
this is OK but if we want to this parallel view coordinates with hidden line algorithm in same book it calculates lines wrongly. I couldn't find where problem is. What can cause this problem?
here hidden line algorithm:
private void lineSegment(Graphics g, Point3D Pe, Point3D Qe,
Point2D PScr, Point2D QScr, int iP, int iQ, int iStart)
{
double u1 = QScr.x - PScr.x; //t
double u2 = QScr.y - PScr.y; //t
double minPQx = Math.min(PScr.x, QScr.x);//t
double maxPQx = Math.max(PScr.x, QScr.x);//t
double minPQy = Math.min(PScr.y, QScr.y);//t
double maxPQy = Math.max(PScr.y, QScr.y);//t
double zP = Pe.z; //t
double zQ = Qe.z; //t
double minPQz = Math.min(zP, zQ);//t
Point3D[] e = obj.getE();//e eye
Point2D[] vScr = obj.getVScr(); //vscr screen
for (int i=iStart; i<nTria; i++)//t
{
Tria t = tr[i];
int iA = t.iA, iB = t.iB, iC = t.iC;
Point2D AScr = vScr[iA], BScr = vScr[iB], CScr = vScr[iC];
// 1. Minimax test for x and y screen coordinates: //t
if (maxPQx <= AScr.x && maxPQx <= BScr.x && maxPQx <= CScr.x
|| minPQx >= AScr.x && minPQx >= BScr.x && minPQx >= CScr.x
|| maxPQy <= AScr.y && maxPQy <= BScr.y && maxPQy <= CScr.y
|| minPQy >= AScr.y && minPQy >= BScr.y && minPQy >= CScr.y)
continue;
// 2. Test if PQ is an edge of ABC: //t
if ((iP == iA || iP == iB || iP == iC) &&
(iQ == iA || iQ == iB || iQ == iC))
continue;
// 3. Test if PQ is clearly nearer than ABC://t
Point3D Ae = e[iA], Be = e[iB], Ce = e[iC];
double zA = Ae.z, zB = Be.z, zC = Ce.z;
if (minPQz >= zA && minPQz >= zB && minPQz >= zC)
continue;
// 4. Do P and Q (in 2D) lie in a half plane defined
// by line AB, on the side other than that of C?
// Similar for the edges BC and CA.
double eps = 0.1; // Relative to numbers of pixels //t
if (Tools2D.area2(AScr, BScr, PScr) < eps &&
Tools2D.area2(AScr, BScr, QScr) < eps ||
Tools2D.area2(BScr, CScr, PScr) < eps &&
Tools2D.area2(BScr, CScr, QScr) < eps ||
Tools2D.area2(CScr, AScr, PScr) < eps &&
Tools2D.area2(CScr, AScr, QScr) < eps)
continue;
// 5. Test (2D) if A, B and C lie on the same side
// of the infinite line through P and Q://t
double PQA = Tools2D.area2(PScr, QScr, AScr);
double PQB = Tools2D.area2(PScr, QScr, BScr);
double PQC = Tools2D.area2(PScr, QScr, CScr);
if (PQA < +eps && PQB < +eps && PQC < +eps ||
PQA > -eps && PQB > -eps && PQC > -eps)
continue;
// 6. Test if neither P nor Q lies behind the
// infinite plane through A, B and C://t
int iPol = refPol[i];
Polygon3D pol = (Polygon3D)polyList.elementAt(iPol);
double a = pol.getA(), b = pol.getB(), c = pol.getC(),
h = pol.getH(), eps1 = 1e-5 * Math.abs(h),
hP = a * Pe.x + b * Pe.y + c * Pe.z,
hQ = a * Qe.x + b * Qe.y + c * Qe.z;
if (hP > h - eps1 && hQ > h - eps1)
continue;
// 7. Test if both P and Q behind triangle ABC://t
boolean PInside =
Tools2D.insideTriangle(AScr, BScr, CScr, PScr);
boolean QInside =
Tools2D.insideTriangle(AScr, BScr, CScr, QScr);
if (PInside && QInside)
return;
// 8. If P nearer than ABC and inside, PQ visible;//t
// the same for Q:
double h1 = h + eps1;
boolean PNear = hP > h1, QNear = hQ > h1;
if (PNear && PInside || QNear && QInside)
continue;
// 9. Compute the intersections I and J of PQ
// with ABC in 2D.
// If, in 3D, such an intersection lies in front of
// ABC, this triangle does not obscure PQ.
// Otherwise, the intersections lie behind ABC and
// this triangle obscures part of PQ:
double lambdaMin = 1.0, lambdaMax = 0.0;
for (int ii=0; ii<3; ii++)
{ double v1 = BScr.x - AScr.x, v2 = BScr.y - AScr.y,
w1 = AScr.x - PScr.x, w2 = AScr.y - PScr.y,
denom = u2 * v1 - u1 * v2;
if (denom != 0)
{ double mu = (u1 * w2 - u2 * w1)/denom;
// mu = 0 gives A and mu = 1 gives B.
if (mu > -0.0001 && mu < 1.0001)
{ double lambda = (v1 * w2 - v2 * w1)/denom;
// lambda = PI/PQ
// (I is point of intersection)
if (lambda > -0.0001 && lambda < 1.0001)
{ if (PInside != QInside &&
lambda > 0.0001 && lambda < 0.9999)
{ lambdaMin = lambdaMax = lambda;
break;
// Only one point of intersection
}
if (lambda < lambdaMin) lambdaMin = lambda;
if (lambda > lambdaMax) lambdaMax = lambda;
}
}
}
Point2D temp = AScr; AScr = BScr;
BScr = CScr; CScr = temp;
}
float d = obj.getD();
if (!PInside && lambdaMin > 0.001)
{ double IScrx = PScr.x + lambdaMin * u1,
IScry = PScr.y + lambdaMin * u2;
// Back from screen to eye coordinates:
double zI = 1/(lambdaMin/zQ + (1 - lambdaMin)/zP),
xI = -zI * IScrx / d, yI = -zI * IScry / d;
if (a * xI + b * yI + c * zI > h1) continue;
Point2D IScr = new Point2D((float)IScrx, (float)IScry);
if (Tools2D.distance2(IScr, PScr) >= 1.0)
lineSegment(g, Pe, new Point3D(xI, yI, zI), PScr,
IScr, iP, -1, i + 1);
}
if (!QInside && lambdaMax < 0.999)
{ double JScrx = PScr.x + lambdaMax * u1,
JScry = PScr.y + lambdaMax * u2;
double zJ =
1/(lambdaMax/zQ + (1 - lambdaMax)/zP),
xJ = -zJ * JScrx / d, yJ = -zJ * JScry / d;
if (a * xJ + b * yJ + c * zJ > h1) continue;
Point2D JScr = new Point2D((float)JScrx, (float)JScry);
if (Tools2D.distance2(JScr, QScr) >= 1.0)
lineSegment(g, Qe, new Point3D(xJ, yJ, zJ),
QScr, JScr, iQ, -1, i + 1);
}
return;
// if no continue-statement has been executed
}
drawLine(g, PScr.x, PScr.y, QScr.x, QScr.y);
}
}

Processing/Line Graphing - Help

I posted something similar yesterday, but got nothing. I spent a few hours today problem-solving, but didn't progress any.
I'm using Processing (the language) and trying to implement a method that draws a line between two points. (I don't want to use the library's line() method.)
My lineCreate method works great for positive slopes, but fails with negative slopes. Can you help figure out why?
Here's the lineCreate() code:
void createLine(int x0, int y0, int x1, int y1){
//...
// Handle slanted lines...
double tempDX = x1 - x0;
double tempDY = y1 - y0; // Had to create dx and dy as doubles because typecasting dy/dx to a double data type wasn't working.
double m = (-tempDY / tempDX); // m = line slope. (Note - The dy value is negative
int deltaN = (2 * -dx); // deltaX is the amount to increment d after choosing the next pixel on the line.
int deltaNE = (2 * (-dy - dx)); // ...where X is the direction moved for that next pixel.
int deltaE = (2 * -dy); // deltaX variables are used below to plot line.
int deltaSE = (2 * (dy + dx));
int deltaS = (2 * dx);
int x = x0;
int y = y0;
int d = 0; // d = Amount d-value changes from pixel to pixel. Depends on slope.
int region = 0; // region = Variable to store slope region. Different regions require different formulas.
if(m > 1){ // if-statement: Initializes d, depending on the slope of the line.
d = -dy - (2 * dx); // If slope is 1-Infiniti. -> Use NE/N initialization for d.
region = 1;
}
else if(m == 1)
region = 2;
else if(m > 0 && m < 1){
d = (2 * -dy) - dx; // If slope is 0-1 -> Use NE/E initialization for d.
region = 3;
}
else if(m < 0 && m > -1){
d = (2 * dy) + dx; // If slope is 0-(-1) -> Use E/SE initliazation for d.
region = 4;
}
else if(m == -1)
region = 5;
else if(m < -1){
d = dy + (2 * dx); // If slope is (-1)-(-Infiniti) -> Use SE/S initialization for d.
region = 6;
}
while(x < x1){ // Until points are connected...
if(region == 1){ // If in region one...
if(d <= 0){ // and d<=0...
d += deltaNE; // Add deltaNE to d, and increment x and y.
x = x + 1;
y = y - 1;
}
else{
d += deltaN; // If d > 0 -> Add deltaN, and increment y.
y = y - 1;
}
}
else if(region == 2){
x = x + 1;
y = y - 1;
}
else if(region == 3){ // If region two...
if(d <= 0){
d += deltaE;
x = x + 1;
}
else{
d += deltaNE;
x = x + 1;
y = y - 1;
}
}
else if(region == 4){ // If region three...
if(d <= 0){
d += deltaSE;
x = x + 1;
y = y + 1;
}
else{
d += deltaE;
x = x + 1;
}
}
else if(region == 5){
x = x + 1;
y = y + 1;
}
else if(region == 6){ // If region four...
if(d <= 0){
d += deltaSE;
x = x + 1;
y = y + 1;
}
else{
d += deltaS;
y = y + 1;
}
}
point(x, y); // Paints new pixel on line going towards (x1,y1).
}
return;
}
Have a look at this page. It explains the whole theory behind line drawing with code examples.
There are a number of known algorithm for line drawing. Read about them here.

Categories