#+TITLE: Python CAD Tutorial 07 - Drawing a grid #+DATE: 2013-10-07 12:00:00 UTC #+DESCRIPTION: Drawing a grid in 3d space using gl lines #+FILETAGS: GTK-3:python:cad:opengl #+CATEGORY: python #+SLUG: 07-cad-drawing-a-grid #+THUMBNAIL: ../../../images/cad/tut07-interface.png #+BEGIN_COMMENT .. title: Python CAD Tutorial 07 - Drawing a grid .. slug: 07-cad-drawing-a-grid.org .. date: 2013-10-07 12:00:00 UTC .. tags: GTK-3, python, cad, opengl .. category: python .. description: Drawing a grid in 3d space using gl lines .. type: text #+END_COMMENT [[https://code.launchpad.net/~oly/fabricad/tut07][View/Download Code]] #+CAPTION: Grid [[../../../images/cad/tut07-interface.png]] We created a plane in the previous tutorial. Now we will inherit that class to create a grid, at a later stage we will add snap to grid functionality.The new grid class will take three parameters: a centre point, a spacing value and a size value. We will set the size value to be the size of the viewport and will set a default spacing between the lines.The new methods for the class are below: + The grid_spacing method shifts the lines by the amount specified in the spacing parameter until the maximum size has been reached. + The draw method draws lines to make up the grid. On every tenth line it changes the colour to a darker line. Future tutorials will deal with snap to grid functionality and auto calculating based on the zoom level, but for now we have something to work with. #+BEGIN_SRC python import math from point import createpoint from plane import createplanesimple class creategrid: display_color = (0.6, 0.6, 0.6) large_grid = 10 small_grid = 2.5 def __init__(self, p1, spacing=1.5, size=65): self.plane = createplanesimple(p1, size * 2) self.p1 = createpoint(p1) self.normal = createpoint((0, 1, 0)) self.size = size self.small_grid = spacing self.large_grid = spacing * 10 def grid_spacing(self): #work out how many times the grid units fit inside our grid size and make it a whole number size = math.ceil(self.size / self.small_grid) * self.small_grid #adjust x by size so we can draw the lines x = self.p1.x - size #loop from start until our lines are greater than our max size while x < (self.p1.x + size): x += self.small_grid yield x def draw(self): self.plane.draw() glColor3f(*self.display_color) glBegin(GL_LINES) for item in self.grid_spacing(): #coordinate modulus large_grid (returns 0 if there is no remaineder), so lets draw a different colour line if (item % self.large_grid) == 0: glColor3f(0.4, 0.4, 0.4) else: glColor3f(*self.display_color) glVertex3f(item, self.p1.y - self.size, self.p1.z) glVertex3f(item, self.p1.y + self.size, self.p1.z) glVertex3f(self.p1.x - self.size, item, self.p1.z) glVertex3f(self.p1.x + self.size, item, self.p1.z) glEnd() #+END_SRC