1 // line.cpp: Line object
3 // Part of the Architektonas Project
4 // (C) 2011 Underground Software
5 // See the README and GPLv3 files for licensing and warranty information
7 // JLH = James Hammons <jlhamm@acm.org>
10 // --- ---------- ------------------------------------------------------------
11 // JLH 03/22/2011 Created this file
12 // JLH 04/11/2011 Fixed attached dimensions to stay at correct length when
13 // "Fixed Length" button is down
14 // JLH 04/27/2011 Fixed attached dimension to stay a correct length when
15 // "Fixed Length" button is *not* down ;-)
16 // JLH 05/29/2011 Added (some) mouseover hints
22 #include "container.h"
23 #include "dimension.h"
24 #include "mathconstants.h"
28 Line::Line(Vector p1, Vector p2, Object * p/*= NULL*/): Object(p1, p),
29 /*type(OTLine),*/ endpoint(p2),
30 draggingLine(false), draggingHandle1(false), draggingHandle2(false), //needUpdate(false),
31 length(Vector::Magnitude(p2, p1)), angle(Vector(endpoint - position).Unit()),
32 hitPoint1(false), hitPoint2(false), hitLine(false)
40 // Taking care of connections should be done by the Container, as we don't know
41 // anything about any other object connected to this one.
43 // If there are any attached Dimensions, we must set the attachment points
44 // to NULL since they will no longer be valid.
45 if (attachedDimension)
47 attachedDimension->SetPoint1(NULL);
48 attachedDimension->SetPoint2(NULL);
50 // IT WOULD BE NICE to have any object points attached to this line automagically
51 // connect to this dimension object at this point, instead of just becoming
57 /*virtual*/ void Line::Draw(Painter * painter)
59 painter->SetPen(QPen(Qt::red, 2.0, Qt::DotLine));
61 if ((state == OSSelected) || ((state == OSInactive) && hitPoint1))
62 painter->DrawHandle(position);
64 if ((state == OSSelected) || ((state == OSInactive) && hitPoint2))
65 painter->DrawHandle(endpoint);
67 if ((state == OSInactive) && !hitLine)
68 painter->SetPen(QPen(Qt::black, 1.0, Qt::SolidLine));
70 if (Object::fixedLength && (draggingHandle1 || draggingHandle2))
72 Vector point1 = (draggingHandle1 ? endpoint : position);
73 Vector point2 = (draggingHandle1 ? position : endpoint);
75 Vector current(point2 - point1);
76 Vector v = current.Unit() * length;
77 Vector v2 = point1 + v;
78 // painter->DrawLine((int)point1.x, (int)point1.y, (int)v2.x, (int)v2.y);
79 painter->DrawLine(point1, v2);
81 if (current.Magnitude() > length)
83 painter->SetPen(QPen(QColor(128, 0, 0), 1.0, Qt::DashLine));
84 // painter->DrawLine((int)v2.x, (int)v2.y, (int)point2.x, (int)point2.y);
85 painter->DrawLine(v2, point2);
88 // Problem: when drawing at large zoom levels, this throws away precision thus
89 // causing the line to rendered too short. !!! FIX !!! [DONE]
91 // painter->DrawLine((int)position.x, (int)position.y, (int)endpoint.x, (int)endpoint.y);
92 painter->DrawLine(position, endpoint);
94 // If we're rotating or setting the span, draw an information panel
95 // showing both absolute and relative angles being set.
96 if (draggingHandle1 || draggingHandle2)
98 double absAngle = (Vector(endpoint - position).Angle()) * RADIANS_TO_DEGREES;
99 // double relAngle = (startAngle >= oldAngle ? startAngle - oldAngle :
100 // startAngle - oldAngle + (2.0 * PI)) * RADIANS_TO_DEGREES;
101 double absLength = Vector(position - endpoint).Magnitude();
105 text = QObject::tr("Length: %1 in.\n") + QChar(0x2221) + QObject::tr(": %2");
106 text = text.arg(absLength).arg(absAngle);
108 QPen pen = QPen(QColor(0x00, 0xFF, 0x00), 1.0, Qt::SolidLine);
109 painter->SetPen(pen);
110 painter->SetBrush(QBrush(QColor(0x40, 0xFF, 0x40, 0x9F)));
111 QRectF textRect(10.0, 10.0, 270.0, 70.0); // x, y, w, h
112 painter->DrawRoundedRect(textRect, 7.0, 7.0);
114 textRect.setLeft(textRect.left() + 14);
115 painter->SetFont(*Object::font);
116 // pen = QPen(QColor(0xDF, 0x5F, 0x00), 1.0, Qt::SolidLine);
117 pen = QPen(QColor(0x00, 0x5F, 0xDF));
118 painter->SetPen(pen);
119 painter->DrawText(textRect, Qt::AlignVCenter, text);
120 // painter->SetPen(QPen(QColor(0xDF, 0x5F, 0x00)));
124 /*virtual*/ Vector Line::Center(void)
126 // Technically, this is the midpoint but who are we to quibble? :-)
127 Vector v((position.x - endpoint.x) / 2.0, (position.y - endpoint.y) / 2.0);
131 /*virtual*/ bool Line::Collided(Vector point)
133 // We can assume this, since this is a mouse down event here.
134 objectWasDragged = false;
137 // return StateChanged();
139 // this is shite. this should be checked for in the Container, not here!
140 // If we're part of a non-top-level container, send this signal to it
141 if (parent->type == OTContainer && !((Container *)parent)->isTopLevelContainer
142 && (hitLine || hitPoint1 || hitPoint2))
144 parent->state = OSSelected;
149 There's a small problem here with the implementation: You can have a dimension tied
150 to only one point while at the same time you can have a dimension sitting on this line.
151 Since there's only *one* dimPoint for each point, this can be problematic...
153 We solve this by allowing only *one* Dimension object to be attached to the Line,
154 Arc, etc. and by giving the Dimension object a pointer to our endpoints.
156 Problem still arises when we delete this object; The attached Dimension object will
157 then have bad pointers! What it *should* do is delete the object if and only if this
158 line is not attached to any other object. If it is, then one of those attachment
159 points should be sent to the dimension object (done for position & endpoint).
161 NOTE: The STL vector<T> *does not* take ownership of pointers, therefore is suitable
164 Also: It would be nice to have a preview of the dimension being drawn, with a modifier
165 key to make it draw/show on the other side...
167 TODO: Make Dimension preview with modifier keys for showing on other side
169 // Is the dimension tool active? Let's use it:
172 // User clicked on the line itself (endpoint checks should preceed this one):
173 // (Priorities are taken care of in HitTest()...)
177 if (attachedDimension == NULL)
179 // How to get this object into the top level container???
181 The real question is do we care. I think so, because if this isn't in the top
182 level container, it won't get drawn...
183 But we can fix that by making this object call any attached object's (like
184 a dimension only) Draw() function... :-/
186 attachedDimension = new Dimension(&position, &endpoint, DTLinear, this);
189 parent->Add(attachedDimension);
193 // If there's one already there, tell it to flip sides...
194 attachedDimension->FlipSides();
197 // New approach here: We look for connected objects.
198 Object * attachedDimension = FindAttachedDimension();
200 if (attachedDimension)
202 // If there's an attached Dimension, tell it to switch sides...
203 ((Dimension *)attachedDimension)->FlipSides();
207 // Otherwise, we make a new one and attach it here.
208 attachedDimension = new Dimension(Connection(this, 0), Connection(this, 1.0), DTLinear, this);
209 connected.push_back(Connection(attachedDimension, 0));
210 connected.push_back(Connection(attachedDimension, 1.0));
213 parent->Add(attachedDimension);
222 if (state == OSInactive)
224 //printf("Line: pp = %lf, length = %lf, distance = %lf\n", parameterizedPoint, lineSegment.Magnitude(), distance);
225 //printf(" v1.Magnitude = %lf, v2.Magnitude = %lf\n", v1.Magnitude(), v2.Magnitude());
226 //printf(" point = %lf,%lf,%lf; p1 = %lf,%lf,%lf; p2 = %lf,%lf,%lf\n", point.x, point.y, point.z, position.x, position.y, position.z, endpoint.x, endpoint.y, endpoint.z);
228 //How to translate this into pixels from Document space???
229 //Maybe we need to pass a scaling factor in here from the caller? That would make sense, as
230 //the caller knows about the zoom factor and all that good kinda crap
231 //I think what's needed is an Object class variable/method that can be changed by the TLC and
232 //called in derived classes to properly scale the location to the current zoom level. That *should* work.
234 // ALSO: Need to code a global (read: Object class) variable that tells use whether a modifier
235 // key was pressed in addition to the mouse click, so we can do stuff like, say, hold
236 // down CTRL and be able to do multiple selecting of objects (in that case, we would
237 // keep the Object state from changing).
242 oldPoint = position; //maybe "position"?
243 draggingHandle1 = true;
250 oldPoint = endpoint; //maybe "position"?
251 draggingHandle2 = true;
263 else if (state == OSSelected)
265 // Here we test for collision with handles as well! (SOON!) [I think it works...NOPE]
268 if (v1.Magnitude() < 2.0) // Handle #1
269 else if (v2.Magnitude() < 2.0) // Handle #2
274 // state = OSInactive;
278 // Toggle selected state if CTRL held
279 if (qApp->keyboardModifiers() == Qt::ControlModifier)
286 // If CTRL is held, then we bypass the "turn off" code. Still didn't hit
287 // *this* object though. :-)
288 if (qApp->keyboardModifiers() == Qt::ControlModifier)
291 // If we got here, we clicked on nothing, so set the object to inactive.
292 // (Once we can read key modifiers, we can override this to allow multiple selection.)
298 /*virtual*/ void Line::PointerMoved(Vector point)
300 if (selectionInProgress)
302 // Check for whether or not the rect contains this line
304 if (selection.normalized().contains(Extents()))
306 // if (selection.normalized().contains(position.x, position.y)
307 // && selection.normalized().contains(endpoint.x, endpoint.y))
308 if (selection.contains(position.x, position.y)
309 && selection.contains(endpoint.x, endpoint.y))
318 // Hit test tells us what we hit (if anything) through boolean variables. (It
319 // also tells us whether or not the state changed. --not any more)
322 needUpdate = StateChanged();
324 objectWasDragged = (draggingLine | draggingHandle1 | draggingHandle2);
326 if (objectWasDragged)
328 Vector delta = point - oldPoint;
330 if (draggingHandle1 || draggingLine)
333 if (draggingHandle2 || draggingLine)
339 //doesn't work QMainWindow::statusBar()->setText("You are manipulating a line");
343 We can't count on any coupling between the dimension object and us, so how do we do this???
344 Also, there may be more than one Dimension object connected to a single endpoint!
347 - Keep track of the state of the connected dimension
348 - Pass the Dimension the point that's being changed and the delta
351 - Pass the point in a notification function (how?)
352 - Pass the point as a reference to the class instance object (&endpoint). This
353 way, the line doesn't have to care about keeping track of Dimensions
354 connected to it. But still have to care about other connected entities
355 (other Lines, Circles, Arcs, Splines, Texts, etc). I think I'd be OK with
356 this. Since the Dimension has a pointer to our object, all we have to do is
357 update our coordinates and the Dimension object will adjust itself on the
358 next repaint. Problem solved, and we don't have to know anything about how
359 many Dimensions are connected to us, or where! \o/
360 The question then becomes, how do we do this kind of coupling???
362 We need to know about connected entities so that we can have them either move
363 in expected ways or constrain the movement of this Line object. This is how we
364 will be a cut above all other CAD software currently out there: the GUI will
365 try to do the right thing, most of the time. :-)
369 // should only do this if "Fixed Length" is set... !!! FIX !!! [DONE]
370 Vector point1 = (draggingHandle1 ? endpoint : position);
371 Vector point2 = (draggingHandle1 ? position : endpoint);
373 if (Object::fixedAngle)
375 // Here we calculate the component of the current vector along the fixed angle.
376 // A_compB = (A . Bu) * Bu
377 double magnitudeAlongB = Vector::Dot(Vector(point2 - point1), angle);
379 Actually, this isn't quite right. What we want to do is look for the intersection along either
380 the horizontal line or vertical line that intersects from the current mouse position.
384 position = endpoint + (angle * magnitudeAlongB);
387 endpoint = position + (angle * magnitudeAlongB);
392 //If we tell the dimension to flip sides, this is no longer a valid
393 //assumption. !!! FIX !!!
394 //Ideally, we should just send the point that's changing to the Dimension object
395 //and have it figure out which point needs to move... Or is it???
396 // Ideally, we shouldn't have to fuck around with this shit. We need to fix the rendering code
397 // so that we don't have to wait until the dragging is done to correct the position of the
398 // point in question, but we'd need another variable tho.
401 dimPoint1->SetPoint1(draggingHandle1 ? v2 : position);
404 dimPoint2->SetPoint2(draggingHandle2 ? v2 : endpoint);
410 /*virtual*/ void Line::PointerReleased(void)
412 if (draggingHandle1 || draggingHandle2)
414 // Set the length (in case the global state was set to fixed (or not))
415 if (Object::fixedLength)
417 if (draggingHandle1) // startpoint
419 Vector v = Vector(position - endpoint).Unit() * length;
420 position = endpoint + v;
424 Vector v = Vector(endpoint - position).Unit() * length;
425 endpoint = position + v;
430 // Otherwise, we calculate the new length, just in case on the next
431 // move it turns out to have a fixed length. :-)
432 length = Vector(endpoint - position).Magnitude();
435 if (!Object::fixedAngle)
437 // Calculate the new angle, just in case on the next move it turns
438 // out to be fixed. :-)
439 angle = Vector(endpoint - position).Unit();
443 draggingLine = false;
444 draggingHandle1 = false;
445 draggingHandle2 = false;
447 if (objectWasDragged)
452 /*virtual*/ bool Line::HitTest(Point point)
456 hitPoint1 = hitPoint2 = hitLine = false;
457 Vector lineSegment = endpoint - position;
458 Vector v1 = point - position;
459 Vector v2 = point - endpoint;
460 double t = Vector::Parameter(position, endpoint, point);
463 // Geometric interpretation:
464 // The parameter "t" on the vector lineSegment is where the normal of
465 // lineSegment coincides with point. If t < 0, the normal lies beyond the
466 // 1st endpoint. If t > 1, then the normal lies beyond the 2nd endpoint. We
467 // only calculate the length of the normal between the point and the
468 // lineSegment when the parameter is between 0 and 1.
470 // Geometric interpretation of "distance = ?Det?(ls, v1) / |ls|":
471 // If the segment endpoints are s and e, and the point is p, then the test
472 // for the perpendicular intercepting the segment is equivalent to insisting
473 // that the two dot products {s-e}.{s-p} and {e-s}.{e-p} are both non-negative.
474 // Perpendicular distance from the point to the segment is computed by first
475 // computing the area of the triangle the three points form, then dividing by
476 // the length of the segment. Distances are done just by the Pythagorean
477 // theorem. Twice the area of the triangle formed by three points is the
478 // determinant of the following matrix:
480 // sx sy 1 0 0 1 0 0 0
481 // ex ey 1 ==> ex ey 1 ==> ex ey 0
482 // px py 1 px py 1 px py 0
484 // By translating the start point to the origin, and subtracting row 1 from
485 // all other rows, we end up with the matrix on the right which greatly
486 // simplifies the calculation of the determinant.
489 distance = v1.Magnitude();
491 distance = v2.Magnitude();
493 // distance = ?Det?(ls, v1) / |ls|
494 distance = fabs((lineSegment.x * v1.y - v1.x * lineSegment.y)
495 / lineSegment.Magnitude());
497 if ((v1.Magnitude() * Painter::zoom) < 8.0)
499 else if ((v2.Magnitude() * Painter::zoom) < 8.0)
501 else if ((distance * Painter::zoom) < 5.0)
504 return (hitPoint1 | hitPoint2 | hitLine ? true : false);
505 // return StateChanged();
509 // Check to see if the point passed in coincides with any we have. If so, return a
510 // pointer to it; otherwise, return NULL.
511 /*virtual*/ Vector * Line::GetPointAt(Vector v)
515 else if (v == endpoint)
522 /*virtual*/ void Line::Enumerate(FILE * file)
524 fprintf(file, "LINE (%lf,%lf) (%lf,%lf)\n", position.x, position.y, endpoint.x, endpoint.y);
528 /*virtual*/ Object * Line::Copy(void)
530 #warning "!!! This doesn't take care of attached Dimensions !!!"
532 This is a real problem. While having a pointer in the Dimension to this line's points
533 is fast & easy, it creates a huge problem when trying to replicate an object like this.
535 Maybe a way to fix that then, is to have reference numbers instead of pointers. That
536 way, if you copy them, ... you might still have problems. Because you can't be sure if
537 a copy will be persistant or not, you then *definitely* do not want them to have the
538 same reference number.
540 return new Line(position, endpoint, parent);
544 /*virtual*/ Vector Line::GetPointAtParameter(double parameter)
548 else if (parameter >= 1.0)
551 // Our parameter lies between zero and one, so calculate it!
552 Vector v(endpoint, position);
553 double length = v.Magnitude();
554 // We scale the magnitude of v so that it lies between 0 and 1...
555 // By multiplying the parameter by the magnitude, we obtain the point we
556 // want. No scaling necessary as it's inherent in the approach!
557 double spotOnLength = length * parameter;
559 // To get our point, we use the initial point of the line and add in our
561 Vector result = position + (v * spotOnLength);
566 /*virtual*/ QRectF Line::Extents(void)
568 QRectF rect(QPointF(position.x, position.y), QPointF(endpoint.x, endpoint.y));
569 return rect.normalized();
573 /*virtual*/ void Line::Translate(Vector amount)
580 /*virtual*/ void Line::Rotate(Vector point, double angle)
585 /*virtual*/ void Line::Scale(Vector point, double amount)
590 void Line::SetDimensionOnLine(Dimension * dimension/*=NULL*/)
592 // If they don't pass one in, create it for the caller.
593 if (dimension == NULL)
595 //printf("Line::SetDimensionOnLine(): Creating new dimension...\n");
596 // dimension = new Dimension(position, endpoint, DTLinear, this);
597 dimension = new Dimension(Connection(this, 0), Connection(this, 1.0), DTLinear, this);
601 //printf("Line::SetDimensionOnLine(): Adding to parent...\n");
602 parent->Add(dimension);
607 dimension->Connect(this, 0);
608 dimension->Connect(this, 1.0);
611 // Make sure the Dimension is connected to us...
612 Connect(dimension, 0);
613 Connect(dimension, 1.0);
617 Object * Line::FindAttachedDimension(void)
619 // Is there anything connected to this line? If not, return NULL
620 if (connected.size() < 2)
623 // Otherwise, we have to search our objects to see if there's a likely
624 // candidate. In this case, we're looking for a pointer to the same object
625 // with a parameter of 0 and 1 respectively. This is O((n^2)/2).
626 for(uint i=0; i<connected.size(); i++)
628 for(uint j=i+1; j<connected.size(); j++)
630 //printf("Line: connected[i]=%X, connected[j]=%X, connected[i].t=%lf, connected[j].t=%lf\n", connected[i].object, connected[j].object, connected[i].t, connected[j].t);
631 if ((connected[i].object == connected[j].object)
632 && ((connected[i].t == 0 && connected[j].t == 1.0)
633 || (connected[i].t == 1.0 && connected[j].t == 0)))
634 return connected[i].object;
638 // Didn't find anything, so return NULL
643 void Line::SaveState(void)
645 oldHitPoint1 = hitPoint1;
646 oldHitPoint2 = hitPoint2;
647 oldHitLine = hitLine;
651 bool Line::StateChanged(void)
653 if ((hitPoint1 != oldHitPoint1) || (hitPoint2 != oldHitPoint2) || (hitLine != oldHitLine))
661 Intersection of two lines:
663 Find where the lines with equations r = i + j + t (3i - j) and r = -i + s (j) intersect.
665 When they intersect, we can set the equations equal to one another:
667 i + j + t (3i - j) = -i + s (j)
669 Equating coefficients:
670 1 + 3t = -1 and 1 - t = s
671 So t = -2/3 and s = 5/3
673 The position vector of the intersection point is therefore given by putting t = -2/3 or s = 5/3 into one of the above equations. This gives -i +5j/3 .
676 so, let's say we have two lines, l1 and l2. Points are v0(p0x, p0y), v1(p1x, p1y) for l1
677 and v2(p2x, p2y), v3(p3x, p3y) for l2.
679 d1 = v1 - v0, d2 = v3 - v2
681 Our parametric equations for the line then are:
686 Set r1 = r2, thus we have:
688 v0 + t(d1) = v2 + s(d2)
690 Taking coefficients, we have:
692 p0x + t(d1x) = p2x + s(d2x)
693 p0y + t(d1y) = p2y + s(d2y)
697 t(d1x) - s(d2x) = p2x - p0x
698 t(d1y) - s(d2y) = p2y - p0y
700 Determinant D is ad - bc where the matrix looks like:
705 so D = (d1x)(d2y) - (d2x)(d1y)
706 if D = 0, the lines are parallel.
707 Dx = (p2x - p0x)(d2y) - (d2x)(p2y - p0y)
708 Dy = (d1x)(p2y - p0y) - (p2x - p0x)(d1y)
711 We only need to calculate t, as we can then multiply it by d1 to get the intersection point.
713 ---------------------------------------------------------------------------------------------------
715 The first and most preferred method for intersection calculation is the perp-product calculation. There are two vectors, v1 and v2. Create a third vector vector between the starting points of these vectors, and calculate the perp product of v2 and the two other vectors. These two scalars have to be divided to get the mulitplication ratio of v1 to reach intersection point. So:
721 Perp product is equal with dot product of normal of first vector and the second vector, so we need normals:
728 dp1 = n3 . v2 = -by3 * bx2 + bx3 * by2;
729 dp2 = n1 . v2 = -by1 * bx2 + bx1 * by2;
732 crossing vector = v1 * ratio;
736 -----------------------------------
738 So... to code this, let's say we have two Lines: l1 & l2.
740 Vector v1 = l1.endpoint - l1.position;
741 Vector v2 = l2.endpoint - l2.position;
744 Vector normal1(-v1.y, v1.x);
745 Vector normal3(-v3.y, v3.x);
747 double dotProduct1 = v2.Dot(normal1);
748 double dotProduct2 = v2.Dot(normal3);
750 if (dotProduct2 == 0)
751 return ParallelLines;
754 // I think we'd still have to add the intersection to the position point to get the intersection...
755 Point intersection = v1 * (dotProduct1 / dotProduct2);