Skip to content

Instantly share code, notes, and snippets.

@stdk
Created December 4, 2013 22:00
Show Gist options
  • Save stdk/7796367 to your computer and use it in GitHub Desktop.
Save stdk/7796367 to your computer and use it in GitHub Desktop.
from numpy import array, cross, dot
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QApplication, QWidget, QPainter, QTransform, QBrush, QColor
import sys
from itertools import izip
def cycle_list(lst, skip=0):
for i in lst[skip:]:
yield i
while True:
for i in lst:
yield i
colours = cycle_list([Qt.lightGray, Qt.darkGreen, Qt.darkBlue, Qt.darkGray, Qt.darkRed, Qt.yellow])
class Widget(QWidget):
def __init__(self):
QWidget.__init__(self)
self.triangle = []
self.np_triangle = []
self.points = []
self.normal = []
def is_inside(self, point):
point = array([point.x(), point.y(), 0])
x = dot(cross(self.np_triangle[1] - self.np_triangle[0], point - self.np_triangle[0]), self.normal)
print 'x', x
if x < 0:
return False
y = dot(cross(point - self.np_triangle[0], self.np_triangle[2] - self.np_triangle[0]), self.normal)
print 'y', y
if y < 0:
return False
if dot(cross(self.np_triangle[2] - self.np_triangle[1], point - self.np_triangle[1]), self.normal) < 0:
return False
return True
def paintEvent(self, event):
painter = QPainter(self)
painter.scale(self.width(), self.height())
for a, b in izip(self.triangle, cycle_list(self.triangle, skip=1)):
painter.drawLine(a, b)
for point in self.points:
painter.setBrush(QBrush(QColor(Qt.green if self.is_inside(point) else Qt.red)))
painter.drawEllipse(point, 0.005, 0.005)
def mouseReleaseEvent(self, event):
transform = QTransform()
transform.scale(self.width(), self.height())
transform = transform.inverted()[0]
if len(self.triangle) < 3:
point = transform.map(event.posF())
self.triangle.append(point)
self.np_triangle.append(array([point.x(), point.y(), 0]))
if len(self.np_triangle) == 3:
self.normal = cross(self.np_triangle[1] - self.np_triangle[0], self.np_triangle[2] - self.np_triangle[0])
print 'normal', self.normal
else:
self.points.append(transform.map(event.posF()))
self.repaint()
app = QApplication(sys.argv)
widget = Widget()
widget.show()
app.exec_()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment