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 L. Hammons <jlhamm@acm.org>
10 // --- ---------- -------------------------------------------------------------
11 // JLH 03/22/2011 Created this file
21 // Uncomment this for debugging...
23 //#define DEBUGFOO // Various tool debugging...
24 //#define DEBUGTP // Toolpalette debugging...
26 #include "drawingview.h"
29 #include "mathconstants.h"
33 #include "dimension.h"
37 DrawingView::DrawingView(QWidget * parent/*= NULL*/): QWidget(parent),
38 // scale(1.0), offsetX(-10), offsetY(-10), tool(TOOLSelect),
39 // ptHighlight(-1), oldPtHighlight(-1), ptNextHighlight(-1), oldPtNextHighlight(-1),
40 // polyFirstPoint(true)
41 scale(1.0), offsetX(-10), offsetY(-10),
42 document(Vector(0, 0)),
43 gridSpacing(32.0), collided(false)
45 setBackgroundRole(QPalette::Base);
46 setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
48 // toolPalette = new ToolWindow();
50 // setCursor(cur[TOOLSelect]);
51 // setMouseTracking(true);
53 document.Add(new Line(Vector(5, 5), Vector(50, 40), &document));
54 document.Add(new Line(Vector(50, 40), Vector(10, 83), &document));
55 document.Add(new Line(Vector(10, 83), Vector(17, 2), &document));
56 document.Add(new Circle(Vector(100, 100), 36, &document));
57 document.Add(new Circle(Vector(50, 150), 49, &document));
58 document.Add(new Arc(Vector(300, 300), 32, PI / 4.0, PI * 1.3, &document)),
59 document.Add(new Arc(Vector(200, 200), 60, PI / 2.0, PI * 1.5, &document));
60 document.Add(new Dimension(Vector(5, 5), Vector(50, 40), &document));
63 QPoint DrawingView::GetAdjustedMousePosition(QMouseEvent * event)
65 // This is undoing the transform, e.g. going from client coords to local coords.
66 // In essence, the height - y is height + (y * -1), the (y * -1) term doing the
67 // conversion of the y-axis from increasing bottom to top.
68 return QPoint(offsetX + event->x(), offsetY + (size().height() - event->y()));
71 QPoint DrawingView::GetAdjustedClientPosition(int x, int y)
73 // VOODOO ALERT (ON Y COMPONENT!!!!) (eh?)
74 // No voodoo here, it's just grouped wrong to see it. It should be:
75 // -offsetY + (size.height() + (y * -1.0)) <-- this is wrong, offsetY should be positive
76 return QPoint(-offsetX + x, (size().height() - (-offsetY + y)) * +1.0);
79 void DrawingView::paintEvent(QPaintEvent * /*event*/)
81 QPainter painter(this);
82 painter.setRenderHint(QPainter::Antialiasing);
85 painter.translate(QPoint(-offsetX, size.height() - (-offsetY)));
86 painter.scale(1.0, -1.0);
89 //order of operations is important! N.B.: Can't use scaling other than 1.0, it
90 //causes lines to look strange (i.e., it scales the pen strokes too)
91 // transform.translate(-offsetX, size().height() - (-offsetY));
92 transform.scale(1.0, -1.0);
93 transform.translate(-offsetX, -size().height() - offsetY);
94 // transform.scale(0.25, 0.25);
95 painter.setTransform(transform);
97 Object::SetViewportHeight(size().height());
99 // Draw coordinate axes
101 painter.setPen(QPen(Qt::blue, 1.0, Qt::DotLine));
102 painter.drawLine(0, -16384, 0, 16384);
103 painter.drawLine(-16384, 0, 16384, 0);
105 // Maybe we can make the grid into a background brush instead, and let Qt deal
110 painter.setPen(QPen(QColor(90, 90, 90), 1.0, Qt::DotLine));
112 //these two loops kill performance!
113 for(double x=0; x<size().width(); x+=gridSpacing*10.0)
114 p.drawLine((int)x, -16384, (int)x, 16384);
116 for(double y=0; y<size().height(); y+=gridSpacing*10.0)
117 p.drawLine(-16384, (int)y, 16384, (int)y);
120 painter.setPen(QPen(Qt::black, 1.0, Qt::SolidLine));
122 for(double x=0; x<size().width(); x+=gridSpacing)
123 for(double y=0; y<size().height(); y+=gridSpacing)
124 painter.drawPoint((int)x, (int)y);
126 // The top level document takes care of rendering for us...
127 document.Draw(&painter);
130 void DrawingView::mousePressEvent(QMouseEvent * event)
132 if (event->button() == Qt::LeftButton)
134 QPoint pt = GetAdjustedMousePosition(event);
135 Vector point(pt.x(), pt.y());
137 collided = document.Collided(point);
140 update(); // Do an update if collided with at least *one* object in the document
144 void DrawingView::mouseMoveEvent(QMouseEvent * event)
146 QPoint pt = GetAdjustedMousePosition(event);
147 Vector point(pt.x(), pt.y());
149 // Grid processing...
151 // This looks strange, but it's really quite simple: We want a point that's
152 // more than half-way to the next grid point to snap there while conversely
153 // we want a point that's less than half-way to to the next grid point then
154 // snap to the one before it. So we add half of the grid spacing to the
155 // point, then divide by it so that we can remove the fractional part, then
156 // multiply it back to get back to the correct answer.
157 point += gridSpacing / 2.0; // *This* adds to Z!!!
158 point /= gridSpacing;
159 point.x = floor(point.x);//need to fix this for negative numbers...
160 point.y = floor(point.y);
161 point.z = 0; // Make *sure* Z doesn't go anywhere!!!
162 point *= gridSpacing;
164 //we should keep track of the last point here and only pass this down *if* the point
166 document.PointerMoved(point);
168 if (document.NeedsUpdate())
172 void DrawingView::mouseReleaseEvent(QMouseEvent * event)
174 if (event->button() == Qt::LeftButton)
176 document.PointerReleased();
178 //We need to update especially if nothing collided and the state needs to change. !!! FIX !!!
179 //could set it up to use the document's update function (assumes that all object updates
180 //are being reported correctly:
181 // if (document.NeedsUpdate())
183 update(); // Do an update if collided with at least *one* object in the document
189 QSize DrawingView::minimumSizeHint() const
191 return QSize(50, 50);
194 QSize DrawingView::sizeHint() const
196 return QSize(400, 400);
199 void DrawingView::CreateCursors(void)
201 int hotx[8] = { 1, 1, 11, 15, 1, 1, 1, 1 };
202 int hoty[8] = { 1, 1, 11, 13, 1, 1, 1, 1 };
204 for(int i=0; i<8; i++)
207 s.sprintf(":/res/cursor%u.png", i+1);
209 cur[i] = QCursor(pmTmp, hotx[i], hoty[i]);
215 o Different colors for polys on selected points
216 o Different colors for handles on non-selected polys
217 o Line of sight (dashed, dotted) for off-curve points
218 o Repaints for press/release of CTRL/SHIFT during point creation
220 void DrawingView::paintEvent(QPaintEvent * /*event*/)
224 // p.setRenderHint(QPainter::Antialiasing);
226 //dc.SetBackground(*wxWHITE_BRUSH);
228 // Due to the screwiness of wxWidgets coord system, the origin is ALWAYS
229 // the upper left corner--regardless of axis orientation, etc...
230 // int width, height;
231 // dc.GetSize(&width, &height);
232 QSize winSize = size();
234 // dc.SetDeviceOrigin(-offsetX, height - (-offsetY));
235 // dc.SetAxisOrientation(true, true);
236 p.translate(QPoint(-offsetX, winSize.height() - (-offsetY)));
239 // Scrolling can be done by using OffsetViewportOrgEx
240 // Scaling can be done by adjusting SetWindowExtEx (it's denominator of txform)
241 // you'd use: % = ViewportExt / WindowExt
242 // But it makes the window look like crap: fuggetuboutit.
243 // Instead, we have to scale EVERYTHING by hand. Crap!
244 // It's not *that* bad, but not as convenient either...
246 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0x00, 0x00, 0xFF), 1, wxDOT)));
247 //// dc.DrawLine(0, 0, 10, 10);
248 p.setPen(QPen(Qt::blue, 1.0, Qt::DotLine));
250 // Draw coordinate axes
252 // dc.CrossHair(0, 0);
253 p.drawLine(0, -16384, 0, 16384);
254 p.drawLine(-16384, 0, 16384, 0);
258 for(int i=0; i<pts.GetNumPoints(); i++)
260 if (i == ptHighlight)
262 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0xFF, 0x00, 0x00), 1, wxSOLID)));
263 //// SelectObject(hdc, hRedPen1);
264 p.setPen(QPen(Qt::red, 1.0, Qt::SolidLine));
266 if (pts.GetOnCurve(i))
268 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 7);
269 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 9);
273 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 7);
274 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 9);
277 else if ((i == ptHighlight || i == ptNextHighlight) && tool == TOOLAddPt)
279 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0x00, 0xAF, 0x00), 1, wxSOLID)));
280 //// SelectObject(hdc, hGreenPen1);
281 p.setPen(QPen(Qt::green, 1.0, Qt::SolidLine));
283 if (pts.GetOnCurve(i))
285 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 7);
286 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 9);
290 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 7);
291 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 9);
296 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0x00, 0x00, 0x00), 1, wxSOLID)));
297 //// SelectObject(hdc, hBlackPen1);
298 p.setPen(QPen(Qt::black, 1.0, Qt::SolidLine));
300 if (pts.GetOnCurve(i))
301 DrawSquareDot(p, pts.GetX(i), pts.GetY(i));
303 DrawRoundDot(p, pts.GetX(i), pts.GetY(i));
306 if (tool == TOOLDelPt && i == ptHighlight)
309 dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0xFF, 0x00, 0x00), 1, wxSOLID)));
310 // SelectObject(hdc, hRedPen1);
311 // MoveToEx(hdc, pts.GetX(i) - 5, pts.GetY(i) - 5, NULL);
312 // LineTo(hdc, pts.GetX(i) + 5, pts.GetY(i) + 5);
313 // LineTo(hdc, pts.GetX(i) - 5, pts.GetY(i) - 5);//Lameness!
314 // MoveToEx(hdc, pts.GetX(i) - 5, pts.GetY(i) + 5, NULL);
315 // LineTo(hdc, pts.GetX(i) + 5, pts.GetY(i) - 5);
316 // LineTo(hdc, pts.GetX(i) - 5, pts.GetY(i) + 5);//More lameness!!
318 p.setPen(QPen(Qt::red, 1.0, Qt::SolidLine));
319 p.drawLine(pts.GetX(i) - 5, pts.GetY(i) - 5, pts.GetX(i) + 5, pts.GetY(i) + 5);
320 p.drawLine(pts.GetX(i) + 5, pts.GetY(i) - 5, pts.GetX(i) - 5, pts.GetY(i) + 5);
324 //// SelectObject(hdc, hBlackPen1);
325 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0x00, 0x00, 0x00), 1, wxSOLID)));
326 p.setPen(QPen(Qt::black, 1.0, Qt::SolidLine));
328 // Draw curve formed by points
330 for(int poly=0; poly<pts.GetNumPolys(); poly++)
332 if (pts.GetNumPoints(poly) > 2)
335 // If it's not on curve, then move to it, otherwise move to last point...
339 if (pts.GetOnCurve(poly, pts.GetNumPoints(poly) - 1))
340 x = (int)pts.GetX(poly, pts.GetNumPoints(poly) - 1), y = (int)pts.GetY(poly, pts.GetNumPoints(poly) - 1);
342 x = (int)pts.GetX(poly, 0), y = (int)pts.GetY(poly, 0);
344 for(int i=0; i<pts.GetNumPoints(poly); i++)
346 if (pts.GetOnCurve(poly, i))
347 // LineTo(hdc, pts.GetX(poly, i), pts.GetY(poly, i));
349 p.drawLine(x, y, pts.GetX(poly, i), pts.GetY(poly, i));
350 x = (int)pts.GetX(poly, i), y = (int)pts.GetY(poly, i);
354 uint32 prev = pts.GetPrev(poly, i), next = pts.GetNext(poly, i);
355 float px = pts.GetX(poly, prev), py = pts.GetY(poly, prev),
356 nx = pts.GetX(poly, next), ny = pts.GetY(poly, next);
358 if (!pts.GetOnCurve(poly, prev))
359 px = (px + pts.GetX(poly, i)) / 2.0f,
360 py = (py + pts.GetY(poly, i)) / 2.0f;
362 if (!pts.GetOnCurve(poly, next))
363 nx = (nx + pts.GetX(poly, i)) / 2.0f,
364 ny = (ny + pts.GetY(poly, i)) / 2.0f;
366 Bezier(p, point(px, py), point(pts.GetX(poly, i), pts.GetY(poly, i)), point(nx, ny));
367 x = (int)nx, y = (int)ny;
369 if (pts.GetOnCurve(poly, next))
370 i++; // Following point is on curve, so move past it
377 void DrawingView::mousePressEvent(QMouseEvent * event)
379 if (event->button() == Qt::RightButton)
381 toolPalette->move(event->globalPos());
382 toolPalette->setVisible(true);
383 setCursor(cur[TOOLSelect]);
384 toolPalette->prevTool = TOOLSelect;
386 else if (event->button() == Qt::MidButton)
388 setCursor(cur[2]); // Scrolling cursor
390 else if (event->button() == Qt::LeftButton)
392 if (tool == TOOLScroll || tool == TOOLZoom)
393 ;//meh CaptureMouse(); // Make sure we capture the mouse when in scroll/zoom mode
394 else if (tool == TOOLAddPt) // "Add Point" tool
396 if (pts.GetNumPoints() > 0)
398 QPoint pt = GetAdjustedMousePosition(event);
399 pts.InsertPoint(pts.GetNext(ptHighlight), pt.x(), pt.y(), ((event->modifiers() == Qt::ShiftModifier || event->modifiers() == Qt::ControlModifier) ? false : true));
400 ptHighlight = ptNextHighlight;
404 else if (tool == TOOLAddPoly) // "Add Poly" tool
407 WriteLogMsg("Adding point... # polys: %u, # points: %u", pts.GetNumPolys(), pts.GetNumPoints());
411 polyFirstPoint = false;
412 pts.AddNewPolyAtEnd();
415 QPoint pt = GetAdjustedMousePosition(event);
416 //printf("GetAdjustedMousePosition = %i, %i\n", pt.x(), pt.y());
417 // Append a point to the end of the structure
418 pts += IPoint(pt.x(), pt.y(), ((event->modifiers() == Qt::ShiftModifier || event->modifiers() == Qt::ControlModifier) ? false : true));
419 ptHighlight = pts.GetNumPoints() - 1;
422 WriteLogMsg(" --> [# polys: %u, # points: %u]\n", pts.GetNumPolys(), pts.GetNumPoints());
425 else if (tool == TOOLSelect || tool == TOOLPolySelect)
427 if (pts.GetNumPoints() > 0)
429 pt = GetAdjustedClientPosition(pts.GetX(ptHighlight), pts.GetY(ptHighlight));
430 //printf("GetAdjustedClientPosition = %i, %i\n", pt.x(), pt.y());
431 // WarpPointer(pt.x, pt.y);
432 QCursor::setPos(mapToGlobal(pt));
434 if (event->modifiers() == Qt::ShiftModifier || event->modifiers() == Qt::ControlModifier)
436 pts.SetOnCurve(ptHighlight, !pts.GetOnCurve(ptHighlight));
441 else if (tool == TOOLDelPt)
443 if (pts.GetNumPoints() > 0)
445 // if (ptHighlight != -1)
447 //This assumes that WM_MOUSEMOVE happens before this!
448 //The above commented out line should take care of this contingency... !!! FIX !!!
449 pts.DeletePoint(ptHighlight);
458 void DrawingView::mouseMoveEvent(QMouseEvent * event)
460 if (event->buttons() == Qt::RightButton)
462 ToolType newTool = toolPalette->FindSelectedTool();
464 if (newTool != toolPalette->prevTool)
466 toolPalette->prevTool = newTool;
467 toolPalette->repaint();
470 else if (event->buttons() == Qt::MidButton)
472 // Calc offset from previous point
474 ptOffset = QPoint(pt.x() - ptPrevious.x(), pt.y() - ptPrevious.y());
476 // Then multiply it by the scaling factor. Whee!
477 // This looks wacky because we're using screen coords for the offset...
478 // Otherwise, we would subtract both offsets!
479 offsetX -= ptOffset.x(), offsetY += ptOffset.y();
483 else if (event->buttons() == Qt::LeftButton)
486 if (tool == TOOLScroll)
488 // Extract current point from lParam/calc offset from previous point
490 pt = e.GetPosition();
491 ptOffset.x = pt.x - ptPrevious.x,
492 ptOffset.y = pt.y - ptPrevious.y;
494 // NOTE: OffsetViewportOrg operates in DEVICE UNITS...
496 //Seems there's no equivalent for this in wxWidgets...!
498 // hdc = GetDC(hWnd);
499 // OffsetViewportOrgEx(hdc, ptOffset.x, ptOffset.y, NULL);
500 // ReleaseDC(hWnd, hdc);
502 // this shows that it works, so the logic above must be faulty...
503 // And it is. It should convert the coords first, then do the subtraction to figure the offset...
505 // Then multiply it by the scaling factor. Whee!
506 // This looks wacky because we're using screen coords for the offset...
507 // Otherwise, we would subtract both offsets!
508 offsetX -= ptOffset.x, offsetY += ptOffset.y;
513 if (tool == TOOLAddPt || tool == TOOLAddPoly || tool == TOOLSelect)
515 if (tool != TOOLAddPt || pts.GetNumPoints() > 0)//yecch.
517 //temporary, for testing. BTW, Select drag bug is here...!
519 QPoint pt2 = GetAdjustedMousePosition(event);
520 pts.SetXY(ptHighlight, pt2.x(), pt2.y());
525 else if (tool == TOOLPolySelect)
527 if (pts.GetNumPoints() > 0)
529 QPoint pt2 = GetAdjustedMousePosition(event);
530 // Should also set onCurve here as well, depending on keystate
532 pts.OffsetPoly(pts.GetPoly(ptHighlight), pt2.x() - pts.GetX(ptHighlight), pt2.y() - pts.GetY(ptHighlight));
537 else if (event->buttons() == Qt::NoButton)
539 // Moving, not dragging...
540 if (tool == TOOLSelect || tool == TOOLDelPt || tool == TOOLAddPt
541 || tool == TOOLPolySelect)// || tool == TOOLAddPoly)
543 QPoint pt2 = GetAdjustedMousePosition(event);
544 double closest = 1.0e+99;
546 for(int i=0; i<pts.GetNumPoints(); i++)
548 double dist = ((pt2.x() - pts.GetX(i)) * (pt2.x() - pts.GetX(i)))
549 + ((pt2.y() - pts.GetY(i)) * (pt2.y() - pts.GetY(i)));
552 closest = dist, ptHighlight = i;
555 if (ptHighlight != oldPtHighlight)
557 oldPtHighlight = ptHighlight;
561 // What follows here looks like voodoo, but is really simple. What we do is
562 // check to see if the mouse point has a perpendicular intersection with any of
563 // the line segments. If it does, calculate the length of the perpendicular
564 // and choose the smallest length. If there is no perpendicular, then choose the
565 // length of line connecting the closer of either the first endpoint or the
566 // second and choose the smallest of those.
568 // There is one bit of math that looks like voodoo to me ATM--will explain once
569 // I understand it better (the calculation of the length of the perpendicular).
571 if (pts.GetNumPoints() > 1 && tool == TOOLAddPt)
573 double smallest = 1.0e+99;
575 for(int i=0; i<pts.GetNumPoints(); i++)
577 int32 p1x = pts.GetX(i), p1y = pts.GetY(i),
578 p2x = pts.GetX(pts.GetNext(i)), p2y = pts.GetY(pts.GetNext(i));
580 vector ls(p2x, p2y, 0, p1x, p1y, 0), v1(pt2.x(), pt2.y(), 0, p1x, p1y, 0),
581 v2(pt2.x(), pt2.y(), 0, p2x, p2y, 0);
582 double pp = ls.dot(v1) / ls.length(), dist;
583 // Geometric interpretation:
584 // pp is the paremeterized point on the vector ls where the perpendicular intersects ls.
585 // If pp < 0, then the perpendicular lies beyond the 1st endpoint. If pp > length of ls,
586 // then the perpendicular lies beyond the 2nd endpoint.
590 else if (pp > ls.length())
592 else // distance = ?Det?(ls, v1) / |ls|
593 dist = fabs((ls.x * v1.y - v1.x * ls.y) / ls.length());
595 //The answer to the above looks like it might be found here:
597 //If the segment endpoints are s and e, and the point is p, then the test for the perpendicular
598 //intercepting the segment is equivalent to insisting that the two dot products {s-e}.{s-p} and
599 //{e-s}.{e-p} are both non-negative. Perpendicular distance from the point to the segment is
600 //computed by first computing the area of the triangle the three points form, then dividing by the
601 //length of the segment. Distances are done just by the Pythagorean theorem. Twice the area of the
602 //triangle formed by three points is the determinant of the following matrix:
608 //By translating the start point to the origin, this can be rewritten as:
609 //By subtracting row 1 from all rows, you get the following:
610 //[because sx = sy = 0. you could leave out the -sx/y terms below. because we subtracted
611 // row 1 from all rows (including row 1) row 1 turns out to be zero. duh!]
614 //(ex - sx) (ey - sy) 0
615 //(px - sx) (py - sy) 0
617 //which greatly simplifies the calculation of the determinant.
620 smallest = dist, ptNextHighlight = pts.GetNext(i), ptHighlight = i;
623 if (ptNextHighlight != oldPtNextHighlight)
625 oldPtNextHighlight = ptNextHighlight;
631 ptPrevious = event->pos();
637 void DrawingView::mouseReleaseEvent(QMouseEvent * event)
639 if (event->button() == Qt::RightButton)
641 ToolType newTool = toolPalette->FindSelectedTool();
643 // We only change the tool if a new one was actually selected. Otherwise, we do nothing.
644 if (newTool != TOOLNone)
648 if (tool == TOOLScroll || tool == TOOLZoom || tool == TOOLAddPoly
649 || tool == TOOLDelPoly)
652 if (tool == TOOLAddPoly)
653 polyFirstPoint = true;
656 toolPalette->setVisible(false);
657 setCursor(cur[tool]);
658 // Just in case we changed highlighting style with the new tool...
661 else if (event->button() == Qt::MidButton)
663 setCursor(cur[tool]); // Restore previous cursor
665 else if (event->button() == Qt::LeftButton)
667 // if (tool == TOOLScroll || tool == TOOLZoom)
669 //this is prolly too much
670 ((TTEdit *)qApp)->charWnd->MakePathFromPoints(&pts);
671 ((TTEdit *)qApp)->charWnd->update();