root / PyOpenGLDemo / NeHe / lesson44 / glVector.py @ 1
History  View  Annotate  Download (2 kB)
1 
# mirros glVector.cpp  slow no nummarray


2 
import math 
3  
4  
5 
# The glVector of lesson 44 has three componenets only

6 
# i j k

7 
class glVector: 
8 
# Need to create from a point?

9 
def __init__ (self, *args): 
10 
if (len (args) == 3): 
11 
self.i = args [0] 
12 
self.j = args [1] 
13 
self.k = args [2] 
14 
return

15 
if (len (args) == 1): 
16 
# // Assign this vector to the vector passed in.

17 
src_v = args [0]

18 
if (not isinstance (src_v, glVector)): 
19 
raise TypeError, "Invalid ctor argument for glVector" 
20 
self.i = src_v.i

21 
self.j = src_v.j

22 
self.k = src_v.k

23 
return

24 
elif (len (args) == 0): 
25 
self.i = 0 
26 
self.j = 0 
27 
self.k = 0 
28 
return

29 
else:

30 
raise TypeError, "Invalid ctor argument for glVector" 
31  
32 
# def __setattr__ (self, name, value)

33 
# """ We want to """

34 
# self.name = value

35  
36 
def Magnitude (self): 
37 
Mag = math.sqrt (self.i * self.i + self.j * self.j + self.k * self.k) 
38 
return Mag

39  
40 
def Normalize (self): 
41 
mag = self.Magnitude ()

42 
if (mag != 0.0): 
43 
self.i = self.i / mag 
44 
self.j = self.j / mag 
45 
self.k = self.k / mag 
46 
return

47  
48 
def __mul__ (self, scalar): 
49 
result = glVector (self)

50 
result *= scalar 
51 
return result

52  
53 
def __imul__ (self, other): 
54 
if (type (other) == int): 
55 
scalar = other 
56 
self.i *= scalar

57 
self.j *= scalar

58 
self.k *= scalar

59 
elif (type (other) == float): 
60 
scalar = other 
61 
self.i *= scalar

62 
self.j *= scalar

63 
self.k *= scalar

64 
else:

65 
raise TypeError, "Invalid type (%s) for multiplication argument" % (str (type (other))) 
66  
67 
return self 
68  
69  
70 
def __add__ (self, v): 
71 
result = copy.copy (self)

72 
result += v 
73 
return result

74  
75 
def __iadd__ (self, v): 
76 
self.i += v.i

77 
self.j += v.j

78 
self.k += v.k

79 
return self 
80  
81 
def __sub__ (self, other): 
82 
self.i = v.i

83 
self.j = v.j

84 
self.k = v.k

85 
return self 
86  
87 
def __str__ (self): 
88 
return "i=%f j=%f k=%f, magnitude=%f" % (self.i, self.j, self.k, self.Magnitude ()) 
89  
90  
91  
92 
# Unit Test harness if this python module is run directly.

93 
if __name__ == "__main__": 
94 
print "testing slow glpoint/vect.\n" 
95 
v = glVector () 
96 
v.i = 1.1

97 
v.Magnitude () 
98 
print v

99 
print "mult new" 
100 
print (v * 2) 
101 
print "Done" 