//Clair(sijing) Sun //sijings@andrew.cmu.edu //Assignment-5 var lineP=[]; var boolDoRefresh; var numberofL=10; function setup() { createCanvas(480, 480); boolDoRefresh = false; for (var i=0; i<numberofL; i++){ var x1 = random(0,width); var x2 = random(0,width); var y1 = random(0,height); var y2 = random(9,height); lineP[i] = [x1,y1,x2,y2]; } } function draw() { background(200); //regenerate if mousePressed if (boolDoRefresh) { for (var i=0; i<numberofL; i++){ var x1 = random(0,width); var x2 = random(0,width); var y1 = random(0,height); var y2 = random(9,height); lineP[i] = [x1,y1,x2,y2]; } boolDoRefresh=false } //for drawing the lines for (var i = 0; i < numberofL; i += 1){ line(lineP[i][0],lineP[i][1],lineP[i][2],lineP[i][3]); } //for drawing the intersections, spliting to two lines each time for (var j = 0; j < numberofL; j += 1){ for (var i = 0; i < numberofL; i += 1){ var x1 = lineP[j][0]; var y1 = lineP[j][1]; var x2 = lineP[j][2]; var y2 = lineP[j][3]; var x3 = lineP[i][0]; var y3 = lineP[i][1]; var x4 = lineP[i][2]; var y4 = lineP[i][3]; intersect(x1, y1, x2, y2, x3, y3, x4, y4); } } } // Modified from line intercept math by Paul Bourke http://paulbourke.net/geometry/pointlineplane/ // Determine the intersection point of two line segments // Modified from http://paulbourke.net/geometry/pointlineplane/javascript.txt function intersect(x1, y1, x2, y2, x3, y3, x4, y4) { if ((x1 == x2 && y1 == y2) || (x3 == x4 && y3 == y4)) { return false } var denom = ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)) if (denom === 0) { return false } var ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denom var ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denom // is the intersection along the segments if (ua < 0 || ua > 1 || ub < 0 || ub > 1) { return false } fill(0); ellipse (x1 + ua * (x2 - x1),y1 + ua * (y2 - y1),15); } function mousePressed() { boolDoRefresh = true; }