~mrol-dev/mrol/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#! /usr/bin/python
'''Displays the points in an xyz file the name of which is supplied on the 
command line. The file should have a format like
0 0 0
0.2 1 0.2
1 2 3
1 2 3.3

Author: Julian Ryde
'''
#Copyright 2010-2011, Julian Ryde and Nicholas Hillier.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU Lesser General Public License for more details.
#
#You should have received a copy of the GNU Lesser General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.

# TODO circular references between dispxyz and robotvisualiser
# fixed for now with delayed import statements, however should really fix 
# properly


import os
import time
import numpy as np
import visual
import sys
import matplotlib.cm

import mrol_mapping.pointcloud as pointcloud
import mrol_mapping.poseutil as poseutil

from threading import Thread

class EnableMouseThread(Thread):
    def __init__(self, scene):
        Thread.__init__(self)
        self.mouse_thread_enabled = True
        self.scene = scene
        
    def run(self):
        delta = 0
        self.dragging = False
        while self.mouse_thread_enabled:
            if self.scene.mouse.events:
                m1 = self.scene.mouse.getevent()
                if m1.click == 'left':
                    if m1.pickpos != None:
                        self.scene.center = m1.pickpos
                if m1.drag == 'left' and self.dragging == False:
                    self.drag_pos = np.asarray(self.scene.mouse.pos)
                    self.dragging = True
                if m1.drop == 'left':
                    self.dragging = False
            if self.dragging:
                new_pos = np.asarray(self.scene.mouse.pos)
                if (new_pos + delta != self.drag_pos).all(): # if mouse has moved
                    delta = (self.drag_pos - new_pos)
                    self.scene.center = self.scene.center + delta
                    self.drag_pos = new_pos + delta # update drag position
            time.sleep(0.01)
    def stop(self):
        self.mouse_thread_enabled = False


def rotating(xyzs):
    """ function used externally by other programs to show continuosly rotating 
    plot of points """
    plotgrid(xyzs)

    az = 0
    daz = np.radians(1)
    visual.scene.up = (0, 0, 1)
    while True:
        time.sleep(0.05)
        az += daz
        visual.scene.forward = (np.sin(az), np.cos(az), -1)

def colors(X, bounds=None):
    assert len(X) > 0
    if bounds == None:
        minx = min(X)
        maxx = max(X)
    else:
        minx = bounds[0]
        maxx = bounds[1]

    mcm = matplotlib.cm.jet
    #mcm = matplotlib.cm.GnBu
    #mcm = matplotlib.cm.gray
    return mcm((X-minx)/(maxx-minx))[:, :3]

def showpts(xyzs, pose=None, size=2, color=None):
    if pose is not None:
        xyzs = pose.transformPoints(xyzs)
        # draw origin
        import mrol_mapping.visualiser.robotvisualiser as robotvisualiser
        robotvisualiser._draw_axes((0,0,0))

    if color is None:
        C = colors(xyzs[:, 2])
    else:
        C = color
    P = visual.points(pos=xyzs, color=C, shape='square', size=size)
    #P.visible = False
    #visual.scene.visible = False
    #del P
    return P

def plotgrid(xyzs, separation=1, pointsize=2, grid_pt_size=1):
    global vis_gridpts
    mins = np.amin(xyzs, 0).astype(int)
    maxs = np.amax(xyzs, 0).astype(int)
    minz = np.amin(xyzs[:, 2])
    d = separation
    XX, YY = np.meshgrid(range(mins[0]/d, maxs[0]/d), range(mins[1]/d, maxs[1]/d)) 
    XX = d*XX.ravel()
    YY = d*YY.ravel()
    ZZ = minz*np.ones_like(XX)
    gridpts = np.vstack((XX, YY, ZZ)).T
    visual.scene.background = (1, 1, 1)
    vis_gridpts = visual.points(pos=gridpts, size=grid_pt_size, color=(0, 0, 0))
    vis_pts = showpts(xyzs, size=pointsize)
    return vis_pts
    
def plot2ptlines(pts1, pts2, color=None):
    pts1 = np.asarray(pts1)
    pts2 = np.asarray(pts2)
    assert pts1.shape == pts2.shape, 'pts1 and pts2 must have the sime dimensions'
    assert pts1.shape[1] == 3, 'pts must be Nx3'
    assert pts2.shape[1] == 3, 'pts must be Nx3'
    
    dist = np.zeros(pts1.shape[0])
    handles = []
    for i, p1 in enumerate(pts1):
        p2 = pts2[i,:]
        dist[i] = np.sqrt(np.abs(np.sum(p2**2 - p1**2)))
        assert not np.isnan(dist[i])
    if color == None:    
        C = colors(dist)
    else:
        C = np.asarray(color)
    for i in range(pts1.shape[0]):
        handles.append(visual.curve(pos=[pts1[i,:],pts2[i,:]], color=C[i,:]))
    return handles
    
def plotaxis(length=1.):
    return plot2ptlines([(0,0,0),(0,0,0),(0,0,0)],[(length,0,0),(0,length,0),(0,0,length)],color=[(1,0,0),(0,1,0),(0,0,1)])

# TODO merge the rotating code below with the rotating function
if __name__ == '__main__':
    if len(sys.argv) == 1:
        print __doc__
        sys.exit()
    fname = sys.argv[1]
    rotate = '--rotating' in sys.argv[1:]
    grid = '--grid' in sys.argv[1:]
    az = 0
    daz = np.radians(1)
    visual.scene.select()
    visual.scene.up = (0, 0, 1)
    visual.scene.forward = (np.sin(az), np.cos(az), -1)
    M = pointcloud.load(fname)

    # approximately center the view on the point cloud
    visual.scene.center = M.points.mean(axis=0) 
    if not rotate:
        MT = EnableMouseThread(visual.scene)
        MT.start()

    while True:
        pc = pointcloud.load(fname)
        M = pc.points
        if grid:
            vis_pts = plotgrid(M)
        else:
            vis_pts = showpts(M)

    # wait for file to change
        lastmodified = os.path.getmtime(fname)
        print 'Displaying ', len(M), 'points'
        while lastmodified == os.path.getmtime(fname):
            time.sleep(0.05)
            if rotate:
                az += daz 
                visual.scene.forward = (np.sin(az), np.cos(az), -1)
        vis_pts.visible = False
        vis_gridpts.visible=False