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 Line * line = new Line(Vector(5, 5), Vector(50, 40), &document);
55 document.Add(new Line(Vector(50, 40), Vector(10, 83), &document));
56 document.Add(new Line(Vector(10, 83), Vector(17, 2), &document));
57 document.Add(new Circle(Vector(100, 100), 36, &document));
58 document.Add(new Circle(Vector(50, 150), 49, &document));
59 document.Add(new Arc(Vector(300, 300), 32, PI / 4.0, PI * 1.3, &document)),
60 document.Add(new Arc(Vector(200, 200), 60, PI / 2.0, PI * 1.5, &document));
61 Dimension * dimension = new Dimension(Vector(0, 0), Vector(0, 0), &document);
62 line->SetDimensionOnPoint1(dimension);
63 line->SetDimensionOnPoint2(dimension);
64 document.Add(dimension);
67 QPoint DrawingView::GetAdjustedMousePosition(QMouseEvent * event)
69 // This is undoing the transform, e.g. going from client coords to local coords.
70 // In essence, the height - y is height + (y * -1), the (y * -1) term doing the
71 // conversion of the y-axis from increasing bottom to top.
72 return QPoint(offsetX + event->x(), offsetY + (size().height() - event->y()));
75 QPoint DrawingView::GetAdjustedClientPosition(int x, int y)
77 // VOODOO ALERT (ON Y COMPONENT!!!!) (eh?)
78 // No voodoo here, it's just grouped wrong to see it. It should be:
79 // -offsetY + (size.height() + (y * -1.0)) <-- this is wrong, offsetY should be positive
80 return QPoint(-offsetX + x, (size().height() - (-offsetY + y)) * +1.0);
83 void DrawingView::paintEvent(QPaintEvent * /*event*/)
85 QPainter painter(this);
86 painter.setRenderHint(QPainter::Antialiasing);
89 painter.translate(QPoint(-offsetX, size.height() - (-offsetY)));
90 painter.scale(1.0, -1.0);
93 //order of operations is important! N.B.: Can't use scaling other than 1.0, it
94 //causes lines to look strange (i.e., it scales the pen strokes too)
95 // transform.translate(-offsetX, size().height() - (-offsetY));
96 transform.scale(1.0, -1.0);
97 transform.translate(-offsetX, -size().height() - offsetY);
98 // transform.scale(0.25, 0.25);
99 painter.setTransform(transform);
101 Object::SetViewportHeight(size().height());
103 // Draw coordinate axes
105 painter.setPen(QPen(Qt::blue, 1.0, Qt::DotLine));
106 painter.drawLine(0, -16384, 0, 16384);
107 painter.drawLine(-16384, 0, 16384, 0);
109 // Maybe we can make the grid into a background brush instead, and let Qt deal
114 painter.setPen(QPen(QColor(90, 90, 90), 1.0, Qt::DotLine));
116 //these two loops kill performance!
117 for(double x=0; x<size().width(); x+=gridSpacing*10.0)
118 p.drawLine((int)x, -16384, (int)x, 16384);
120 for(double y=0; y<size().height(); y+=gridSpacing*10.0)
121 p.drawLine(-16384, (int)y, 16384, (int)y);
124 painter.setPen(QPen(Qt::black, 1.0, Qt::SolidLine));
126 for(double x=0; x<size().width(); x+=gridSpacing)
127 for(double y=0; y<size().height(); y+=gridSpacing)
128 painter.drawPoint((int)x, (int)y);
130 // The top level document takes care of rendering for us...
131 document.Draw(&painter);
134 void DrawingView::mousePressEvent(QMouseEvent * event)
136 if (event->button() == Qt::LeftButton)
138 QPoint pt = GetAdjustedMousePosition(event);
139 Vector point(pt.x(), pt.y());
141 collided = document.Collided(point);
144 update(); // Do an update if collided with at least *one* object in the document
148 void DrawingView::mouseMoveEvent(QMouseEvent * event)
150 QPoint pt = GetAdjustedMousePosition(event);
151 Vector point(pt.x(), pt.y());
153 // Grid processing...
155 // This looks strange, but it's really quite simple: We want a point that's
156 // more than half-way to the next grid point to snap there while conversely
157 // we want a point that's less than half-way to to the next grid point then
158 // snap to the one before it. So we add half of the grid spacing to the
159 // point, then divide by it so that we can remove the fractional part, then
160 // multiply it back to get back to the correct answer.
161 if (event->buttons() & Qt::LeftButton)
163 point += gridSpacing / 2.0; // *This* adds to Z!!!
164 point /= gridSpacing;
165 point.x = floor(point.x);//need to fix this for negative numbers...
166 point.y = floor(point.y);
167 point.z = 0; // Make *sure* Z doesn't go anywhere!!!
168 point *= gridSpacing;
171 //we should keep track of the last point here and only pass this down *if* the point
173 document.PointerMoved(point);
175 if (document.NeedsUpdate())
179 void DrawingView::mouseReleaseEvent(QMouseEvent * event)
181 if (event->button() == Qt::LeftButton)
183 document.PointerReleased();
185 //We need to update especially if nothing collided and the state needs to change. !!! FIX !!!
186 //could set it up to use the document's update function (assumes that all object updates
187 //are being reported correctly:
188 // if (document.NeedsUpdate())
190 update(); // Do an update if collided with at least *one* object in the document
196 QSize DrawingView::minimumSizeHint() const
198 return QSize(50, 50);
201 QSize DrawingView::sizeHint() const
203 return QSize(400, 400);
206 void DrawingView::CreateCursors(void)
208 int hotx[8] = { 1, 1, 11, 15, 1, 1, 1, 1 };
209 int hoty[8] = { 1, 1, 11, 13, 1, 1, 1, 1 };
211 for(int i=0; i<8; i++)
214 s.sprintf(":/res/cursor%u.png", i+1);
216 cur[i] = QCursor(pmTmp, hotx[i], hoty[i]);
222 o Different colors for polys on selected points
223 o Different colors for handles on non-selected polys
224 o Line of sight (dashed, dotted) for off-curve points
225 o Repaints for press/release of CTRL/SHIFT during point creation
227 void DrawingView::paintEvent(QPaintEvent * /*event*/)
231 // p.setRenderHint(QPainter::Antialiasing);
233 //dc.SetBackground(*wxWHITE_BRUSH);
235 // Due to the screwiness of wxWidgets coord system, the origin is ALWAYS
236 // the upper left corner--regardless of axis orientation, etc...
237 // int width, height;
238 // dc.GetSize(&width, &height);
239 QSize winSize = size();
241 // dc.SetDeviceOrigin(-offsetX, height - (-offsetY));
242 // dc.SetAxisOrientation(true, true);
243 p.translate(QPoint(-offsetX, winSize.height() - (-offsetY)));
246 // Scrolling can be done by using OffsetViewportOrgEx
247 // Scaling can be done by adjusting SetWindowExtEx (it's denominator of txform)
248 // you'd use: % = ViewportExt / WindowExt
249 // But it makes the window look like crap: fuggetuboutit.
250 // Instead, we have to scale EVERYTHING by hand. Crap!
251 // It's not *that* bad, but not as convenient either...
253 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0x00, 0x00, 0xFF), 1, wxDOT)));
254 //// dc.DrawLine(0, 0, 10, 10);
255 p.setPen(QPen(Qt::blue, 1.0, Qt::DotLine));
257 // Draw coordinate axes
259 // dc.CrossHair(0, 0);
260 p.drawLine(0, -16384, 0, 16384);
261 p.drawLine(-16384, 0, 16384, 0);
265 for(int i=0; i<pts.GetNumPoints(); i++)
267 if (i == ptHighlight)
269 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0xFF, 0x00, 0x00), 1, wxSOLID)));
270 //// SelectObject(hdc, hRedPen1);
271 p.setPen(QPen(Qt::red, 1.0, Qt::SolidLine));
273 if (pts.GetOnCurve(i))
275 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 7);
276 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 9);
280 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 7);
281 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 9);
284 else if ((i == ptHighlight || i == ptNextHighlight) && tool == TOOLAddPt)
286 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0x00, 0xAF, 0x00), 1, wxSOLID)));
287 //// SelectObject(hdc, hGreenPen1);
288 p.setPen(QPen(Qt::green, 1.0, Qt::SolidLine));
290 if (pts.GetOnCurve(i))
292 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 7);
293 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 9);
297 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 7);
298 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 9);
303 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0x00, 0x00, 0x00), 1, wxSOLID)));
304 //// SelectObject(hdc, hBlackPen1);
305 p.setPen(QPen(Qt::black, 1.0, Qt::SolidLine));
307 if (pts.GetOnCurve(i))
308 DrawSquareDot(p, pts.GetX(i), pts.GetY(i));
310 DrawRoundDot(p, pts.GetX(i), pts.GetY(i));
313 if (tool == TOOLDelPt && i == ptHighlight)
316 dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0xFF, 0x00, 0x00), 1, wxSOLID)));
317 // SelectObject(hdc, hRedPen1);
318 // MoveToEx(hdc, pts.GetX(i) - 5, pts.GetY(i) - 5, NULL);
319 // LineTo(hdc, pts.GetX(i) + 5, pts.GetY(i) + 5);
320 // LineTo(hdc, pts.GetX(i) - 5, pts.GetY(i) - 5);//Lameness!
321 // MoveToEx(hdc, pts.GetX(i) - 5, pts.GetY(i) + 5, NULL);
322 // LineTo(hdc, pts.GetX(i) + 5, pts.GetY(i) - 5);
323 // LineTo(hdc, pts.GetX(i) - 5, pts.GetY(i) + 5);//More lameness!!
325 p.setPen(QPen(Qt::red, 1.0, Qt::SolidLine));
326 p.drawLine(pts.GetX(i) - 5, pts.GetY(i) - 5, pts.GetX(i) + 5, pts.GetY(i) + 5);
327 p.drawLine(pts.GetX(i) + 5, pts.GetY(i) - 5, pts.GetX(i) - 5, pts.GetY(i) + 5);
331 //// SelectObject(hdc, hBlackPen1);
332 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0x00, 0x00, 0x00), 1, wxSOLID)));
333 p.setPen(QPen(Qt::black, 1.0, Qt::SolidLine));
335 // Draw curve formed by points
337 for(int poly=0; poly<pts.GetNumPolys(); poly++)
339 if (pts.GetNumPoints(poly) > 2)
342 // If it's not on curve, then move to it, otherwise move to last point...
346 if (pts.GetOnCurve(poly, pts.GetNumPoints(poly) - 1))
347 x = (int)pts.GetX(poly, pts.GetNumPoints(poly) - 1), y = (int)pts.GetY(poly, pts.GetNumPoints(poly) - 1);
349 x = (int)pts.GetX(poly, 0), y = (int)pts.GetY(poly, 0);
351 for(int i=0; i<pts.GetNumPoints(poly); i++)
353 if (pts.GetOnCurve(poly, i))
354 // LineTo(hdc, pts.GetX(poly, i), pts.GetY(poly, i));
356 p.drawLine(x, y, pts.GetX(poly, i), pts.GetY(poly, i));
357 x = (int)pts.GetX(poly, i), y = (int)pts.GetY(poly, i);
361 uint32 prev = pts.GetPrev(poly, i), next = pts.GetNext(poly, i);
362 float px = pts.GetX(poly, prev), py = pts.GetY(poly, prev),
363 nx = pts.GetX(poly, next), ny = pts.GetY(poly, next);
365 if (!pts.GetOnCurve(poly, prev))
366 px = (px + pts.GetX(poly, i)) / 2.0f,
367 py = (py + pts.GetY(poly, i)) / 2.0f;
369 if (!pts.GetOnCurve(poly, next))
370 nx = (nx + pts.GetX(poly, i)) / 2.0f,
371 ny = (ny + pts.GetY(poly, i)) / 2.0f;
373 Bezier(p, point(px, py), point(pts.GetX(poly, i), pts.GetY(poly, i)), point(nx, ny));
374 x = (int)nx, y = (int)ny;
376 if (pts.GetOnCurve(poly, next))
377 i++; // Following point is on curve, so move past it
384 void DrawingView::mousePressEvent(QMouseEvent * event)
386 if (event->button() == Qt::RightButton)
388 toolPalette->move(event->globalPos());
389 toolPalette->setVisible(true);
390 setCursor(cur[TOOLSelect]);
391 toolPalette->prevTool = TOOLSelect;
393 else if (event->button() == Qt::MidButton)
395 setCursor(cur[2]); // Scrolling cursor
397 else if (event->button() == Qt::LeftButton)
399 if (tool == TOOLScroll || tool == TOOLZoom)
400 ;//meh CaptureMouse(); // Make sure we capture the mouse when in scroll/zoom mode
401 else if (tool == TOOLAddPt) // "Add Point" tool
403 if (pts.GetNumPoints() > 0)
405 QPoint pt = GetAdjustedMousePosition(event);
406 pts.InsertPoint(pts.GetNext(ptHighlight), pt.x(), pt.y(), ((event->modifiers() == Qt::ShiftModifier || event->modifiers() == Qt::ControlModifier) ? false : true));
407 ptHighlight = ptNextHighlight;
411 else if (tool == TOOLAddPoly) // "Add Poly" tool
414 WriteLogMsg("Adding point... # polys: %u, # points: %u", pts.GetNumPolys(), pts.GetNumPoints());
418 polyFirstPoint = false;
419 pts.AddNewPolyAtEnd();
422 QPoint pt = GetAdjustedMousePosition(event);
423 //printf("GetAdjustedMousePosition = %i, %i\n", pt.x(), pt.y());
424 // Append a point to the end of the structure
425 pts += IPoint(pt.x(), pt.y(), ((event->modifiers() == Qt::ShiftModifier || event->modifiers() == Qt::ControlModifier) ? false : true));
426 ptHighlight = pts.GetNumPoints() - 1;
429 WriteLogMsg(" --> [# polys: %u, # points: %u]\n", pts.GetNumPolys(), pts.GetNumPoints());
432 else if (tool == TOOLSelect || tool == TOOLPolySelect)
434 if (pts.GetNumPoints() > 0)
436 pt = GetAdjustedClientPosition(pts.GetX(ptHighlight), pts.GetY(ptHighlight));
437 //printf("GetAdjustedClientPosition = %i, %i\n", pt.x(), pt.y());
438 // WarpPointer(pt.x, pt.y);
439 QCursor::setPos(mapToGlobal(pt));
441 if (event->modifiers() == Qt::ShiftModifier || event->modifiers() == Qt::ControlModifier)
443 pts.SetOnCurve(ptHighlight, !pts.GetOnCurve(ptHighlight));
448 else if (tool == TOOLDelPt)
450 if (pts.GetNumPoints() > 0)
452 // if (ptHighlight != -1)
454 //This assumes that WM_MOUSEMOVE happens before this!
455 //The above commented out line should take care of this contingency... !!! FIX !!!
456 pts.DeletePoint(ptHighlight);
465 void DrawingView::mouseMoveEvent(QMouseEvent * event)
467 if (event->buttons() == Qt::RightButton)
469 ToolType newTool = toolPalette->FindSelectedTool();
471 if (newTool != toolPalette->prevTool)
473 toolPalette->prevTool = newTool;
474 toolPalette->repaint();
477 else if (event->buttons() == Qt::MidButton)
479 // Calc offset from previous point
481 ptOffset = QPoint(pt.x() - ptPrevious.x(), pt.y() - ptPrevious.y());
483 // Then multiply it by the scaling factor. Whee!
484 // This looks wacky because we're using screen coords for the offset...
485 // Otherwise, we would subtract both offsets!
486 offsetX -= ptOffset.x(), offsetY += ptOffset.y();
490 else if (event->buttons() == Qt::LeftButton)
493 if (tool == TOOLScroll)
495 // Extract current point from lParam/calc offset from previous point
497 pt = e.GetPosition();
498 ptOffset.x = pt.x - ptPrevious.x,
499 ptOffset.y = pt.y - ptPrevious.y;
501 // NOTE: OffsetViewportOrg operates in DEVICE UNITS...
503 //Seems there's no equivalent for this in wxWidgets...!
505 // hdc = GetDC(hWnd);
506 // OffsetViewportOrgEx(hdc, ptOffset.x, ptOffset.y, NULL);
507 // ReleaseDC(hWnd, hdc);
509 // this shows that it works, so the logic above must be faulty...
510 // And it is. It should convert the coords first, then do the subtraction to figure the offset...
512 // Then multiply it by the scaling factor. Whee!
513 // This looks wacky because we're using screen coords for the offset...
514 // Otherwise, we would subtract both offsets!
515 offsetX -= ptOffset.x, offsetY += ptOffset.y;
520 if (tool == TOOLAddPt || tool == TOOLAddPoly || tool == TOOLSelect)
522 if (tool != TOOLAddPt || pts.GetNumPoints() > 0)//yecch.
524 //temporary, for testing. BTW, Select drag bug is here...!
526 QPoint pt2 = GetAdjustedMousePosition(event);
527 pts.SetXY(ptHighlight, pt2.x(), pt2.y());
532 else if (tool == TOOLPolySelect)
534 if (pts.GetNumPoints() > 0)
536 QPoint pt2 = GetAdjustedMousePosition(event);
537 // Should also set onCurve here as well, depending on keystate
539 pts.OffsetPoly(pts.GetPoly(ptHighlight), pt2.x() - pts.GetX(ptHighlight), pt2.y() - pts.GetY(ptHighlight));
544 else if (event->buttons() == Qt::NoButton)
546 // Moving, not dragging...
547 if (tool == TOOLSelect || tool == TOOLDelPt || tool == TOOLAddPt
548 || tool == TOOLPolySelect)// || tool == TOOLAddPoly)
550 QPoint pt2 = GetAdjustedMousePosition(event);
551 double closest = 1.0e+99;
553 for(int i=0; i<pts.GetNumPoints(); i++)
555 double dist = ((pt2.x() - pts.GetX(i)) * (pt2.x() - pts.GetX(i)))
556 + ((pt2.y() - pts.GetY(i)) * (pt2.y() - pts.GetY(i)));
559 closest = dist, ptHighlight = i;
562 if (ptHighlight != oldPtHighlight)
564 oldPtHighlight = ptHighlight;
568 // What follows here looks like voodoo, but is really simple. What we do is
569 // check to see if the mouse point has a perpendicular intersection with any of
570 // the line segments. If it does, calculate the length of the perpendicular
571 // and choose the smallest length. If there is no perpendicular, then choose the
572 // length of line connecting the closer of either the first endpoint or the
573 // second and choose the smallest of those.
575 // There is one bit of math that looks like voodoo to me ATM--will explain once
576 // I understand it better (the calculation of the length of the perpendicular).
578 if (pts.GetNumPoints() > 1 && tool == TOOLAddPt)
580 double smallest = 1.0e+99;
582 for(int i=0; i<pts.GetNumPoints(); i++)
584 int32 p1x = pts.GetX(i), p1y = pts.GetY(i),
585 p2x = pts.GetX(pts.GetNext(i)), p2y = pts.GetY(pts.GetNext(i));
587 vector ls(p2x, p2y, 0, p1x, p1y, 0), v1(pt2.x(), pt2.y(), 0, p1x, p1y, 0),
588 v2(pt2.x(), pt2.y(), 0, p2x, p2y, 0);
589 double pp = ls.dot(v1) / ls.length(), dist;
590 // Geometric interpretation:
591 // pp is the paremeterized point on the vector ls where the perpendicular intersects ls.
592 // If pp < 0, then the perpendicular lies beyond the 1st endpoint. If pp > length of ls,
593 // then the perpendicular lies beyond the 2nd endpoint.
597 else if (pp > ls.length())
599 else // distance = ?Det?(ls, v1) / |ls|
600 dist = fabs((ls.x * v1.y - v1.x * ls.y) / ls.length());
602 //The answer to the above looks like it might be found here:
604 //If the segment endpoints are s and e, and the point is p, then the test for the perpendicular
605 //intercepting the segment is equivalent to insisting that the two dot products {s-e}.{s-p} and
606 //{e-s}.{e-p} are both non-negative. Perpendicular distance from the point to the segment is
607 //computed by first computing the area of the triangle the three points form, then dividing by the
608 //length of the segment. Distances are done just by the Pythagorean theorem. Twice the area of the
609 //triangle formed by three points is the determinant of the following matrix:
615 //By translating the start point to the origin, this can be rewritten as:
616 //By subtracting row 1 from all rows, you get the following:
617 //[because sx = sy = 0. you could leave out the -sx/y terms below. because we subtracted
618 // row 1 from all rows (including row 1) row 1 turns out to be zero. duh!]
621 //(ex - sx) (ey - sy) 0
622 //(px - sx) (py - sy) 0
624 //which greatly simplifies the calculation of the determinant.
627 smallest = dist, ptNextHighlight = pts.GetNext(i), ptHighlight = i;
630 if (ptNextHighlight != oldPtNextHighlight)
632 oldPtNextHighlight = ptNextHighlight;
638 ptPrevious = event->pos();
644 void DrawingView::mouseReleaseEvent(QMouseEvent * event)
646 if (event->button() == Qt::RightButton)
648 ToolType newTool = toolPalette->FindSelectedTool();
650 // We only change the tool if a new one was actually selected. Otherwise, we do nothing.
651 if (newTool != TOOLNone)
655 if (tool == TOOLScroll || tool == TOOLZoom || tool == TOOLAddPoly
656 || tool == TOOLDelPoly)
659 if (tool == TOOLAddPoly)
660 polyFirstPoint = true;
663 toolPalette->setVisible(false);
664 setCursor(cur[tool]);
665 // Just in case we changed highlighting style with the new tool...
668 else if (event->button() == Qt::MidButton)
670 setCursor(cur[tool]); // Restore previous cursor
672 else if (event->button() == Qt::LeftButton)
674 // if (tool == TOOLScroll || tool == TOOLZoom)
676 //this is prolly too much
677 ((TTEdit *)qApp)->charWnd->MakePathFromPoints(&pts);
678 ((TTEdit *)qApp)->charWnd->update();