492d31fc88c3852f3153778f38465a89e073ca44
[nit.git] / lib / geometry / points_and_lines.nit
1 # This file is part of NIT (http://www.nitlanguage.org).
2 #
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Provides interfaces and classes to represent basic geometry needs.
18 module points_and_lines
19
20 # An abstract 2d point, strongly linked to its implementation `Point`
21 interface IPoint[N: Numeric]
22 # horizontal coordinate
23 fun x: N is abstract
24 # vertical coordinate
25 fun y: N is abstract
26
27 redef fun to_s do return "({x}, {y})"
28 end
29
30 # A 2d point and an implementation of `IPoint`
31 class Point[N: Numeric]
32 super IPoint[N]
33
34 redef var x: N
35 redef var y: N
36
37 init(x, y: N)
38 do
39 self.x = x
40 self.y = y
41 end
42 end
43
44 # An abstract 3d point, strongly linked to its implementation `Point3d`
45 interface IPoint3d[N: Numeric]
46 super IPoint[N]
47
48 # depth coordinate
49 fun z: N is abstract
50
51 redef fun to_s do return "({x}, {y}, {z})"
52 end
53
54 # A 3d point and an implementation of `IPoint3d`
55 class Point3d[N: Numeric]
56 super IPoint3d[N]
57 super Point[N]
58
59 redef var z: N
60
61 init(x, y, z: N)
62 do
63 super
64 self.z = z
65 end
66 end
67
68 # An abstract 2d line segment
69 interface ILine[N: Numeric]
70 type P: IPoint[N]
71
72 fun point_left: P is abstract
73 fun point_right: P is abstract
74
75 redef fun to_s do return "{point_left}--{point_right}"
76 end
77
78 # A 2d line segment
79 class Line[N: Numeric]
80 super ILine[N]
81
82 redef var point_left: P
83 redef var point_right: P
84
85 init(a, b: P)
86 do
87 if a.x < b.x then
88 point_left = a
89 point_right = b
90 else
91 point_left = b
92 point_right = a
93 end
94 end
95
96 end
97
98 # An abstract 3d line segment
99 interface ILine3d[N: Numeric]
100 super ILine[N]
101
102 redef type P: IPoint3d[N]
103 end
104
105 # A 3d line segment
106 class Line3d[N: Numeric]
107 super Line[N]
108 super ILine3d[N]
109 end