view org/touch.org @ 229:6f1be9525e40

fleshing out text in touch.org
author Robert McIntyre <rlm@mit.edu>
date Sat, 11 Feb 2012 19:13:39 -0700
parents 0589c35f04f2
children f9b7d674aed8
line wrap: on
line source
1 #+title: Simulated Sense of Touch
2 #+author: Robert McIntyre
3 #+email: rlm@mit.edu
4 #+description: Simulated touch for AI research using JMonkeyEngine and clojure.
5 #+keywords: simulation, tactile sense, jMonkeyEngine3, clojure
6 #+SETUPFILE: ../../aurellem/org/setup.org
7 #+INCLUDE: ../../aurellem/org/level-0.org
11 * Touch
13 Touch is critical to navigation and spatial reasoning and as such I
14 need a simulated version of it to give to my AI creatures.
16 However, touch in my virtual can not exactly correspond to human touch
17 because my creatures are made out of completely rigid segments that
18 don't deform like human skin.
20 Human skin has a wide array of touch sensors, each of which speciliaze
21 in detecting different vibrational modes and pressures. These sensors
22 can integrate a vast expanse of skin (i.e. your entire palm), or a
23 tiny patch of skin at the tip of your finger. The hairs of the skin
24 help detect objects before they even come into contact with the skin
25 proper.
27 Instead of measuring deformation or vibration, I surround each rigid
28 part with a plenitude of hair-like objects which do not interact with
29 the physical world. Physical objects can pass through them with no
30 effect. The hairs are able to measure contact with other objects, and
31 constantly report how much of their extent is covered. So, even though
32 the creature's body parts do not deform, the hairs create a margin
33 around those body parts which achieves a sense of touch which is a
34 hybrid between a human's sense of deformation and sense from hairs.
36 Implementing touch in jMonkeyEngine follows a different techinal route
37 than vision and hearing. Those two senses piggybacked off
38 jMonkeyEngine's 3D audio and video rendering subsystems. To simulate
39 Touch, I use jMonkeyEngine's physics system to execute many small
40 collision detections, one for each "hair". The placement of the
41 "hairs" is determined by a UV-mapped image which shows where each hair
42 should be on the 3D surface of the body.
45 * Defining Touch Meta-Data in Blender
47 Each geometry can have a single UV map which describes the position
48 and length of the "hairs" which will constitute its sense of
49 touch. This image path is stored under the "touch" key. The image
50 itself is grayscale, with black meaning a hair length of 0 (no hair is
51 present) and white meaning a hair length of =scale=, which is a float
52 stored under the key "scale". If the pixel is gray then the resultant
53 hair length is linearly interpolated between 0 and =scale=.
55 #+begin_src clojure
56 (defn tactile-sensor-profile
57 "Return the touch-sensor distribution image in BufferedImage format,
58 or nil if it does not exist."
59 [#^Geometry obj]
60 (if-let [image-path (meta-data obj "touch")]
61 (load-image image-path)))
62 #+end_src
65 ** TODO add image showing example touch-uv map
66 ** TODO add metadata display for worm
68 * Triangle Manipulation Functions
70 The rigid bodies which make up a creature have an underlying
71 =Geometry=, which is a =Mesh= plus a =Material= and other important
72 data involved with displaying the body.
74 A =Mesh= is composed of =Triangles=, and each =Triangle= has three
75 verticies which have coordinates in XYZ space and UV space.
77 Here, =(triangles)= gets all the triangles which compose a mesh, and
78 =(triangle-UV-coord)= returns the the UV coordinates of the verticies
79 of a triangle.
81 #+begin_src clojure
82 (defn triangles
83 "Return a sequence of all the Triangles which compose a given
84 Geometry."
85 [#^Geometry geom]
86 (let
87 [mesh (.getMesh geom)
88 triangles (transient [])]
89 (dorun
90 (for [n (range (.getTriangleCount mesh))]
91 (let [tri (Triangle.)]
92 (.getTriangle mesh n tri)
93 ;; (.calculateNormal tri)
94 ;; (.calculateCenter tri)
95 (conj! triangles tri))))
96 (persistent! triangles)))
98 (defn mesh-triangle
99 "Get the triangle specified by triangle-index from the mesh within
100 bounds."
101 [#^Mesh mesh triangle-index]
102 (let [scratch (Triangle.)]
103 (.getTriangle mesh triangle-index scratch)
104 scratch))
106 (defn triangle-vertex-indices
107 "Get the triangle vertex indices of a given triangle from a given
108 mesh."
109 [#^Mesh mesh triangle-index]
110 (let [indices (int-array 3)]
111 (.getTriangle mesh triangle-index indices)
112 (vec indices)))
114 (defn vertex-UV-coord
115 "Get the UV-coordinates of the vertex named by vertex-index"
116 [#^Mesh mesh vertex-index]
117 (let [UV-buffer
118 (.getData
119 (.getBuffer
120 mesh
121 VertexBuffer$Type/TexCoord))]
122 [(.get UV-buffer (* vertex-index 2))
123 (.get UV-buffer (+ 1 (* vertex-index 2)))]))
125 (defn triangle-UV-coord
126 "Get the UV-cooridnates of the triangle's verticies."
127 [#^Mesh mesh width height triangle-index]
128 (map (fn [[u v]] (vector (* width u) (* height v)))
129 (map (partial vertex-UV-coord mesh)
130 (triangle-vertex-indices mesh triangle-index))))
131 #+end_src
133 * Schrapnel Conversion Functions
135 It is convienent to treat a =Triangle= as a sequence of verticies, and
136 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion
137 functions make this easy. If these classes implemented =Iterable= then
138 this code would not be necessary. Hopefully they will in the future.
140 #+begin_src clojure
141 (defn triangle-seq [#^Triangle tri]
142 [(.get1 tri) (.get2 tri) (.get3 tri)])
144 (defn vector3f-seq [#^Vector3f v]
145 [(.getX v) (.getY v) (.getZ v)])
147 (defn point->vector2f [[u v]]
148 (Vector2f. u v))
150 (defn vector2f->vector3f [v]
151 (Vector3f. (.getX v) (.getY v) 0))
153 (defn map-triangle [f #^Triangle tri]
154 (Triangle.
155 (f 0 (.get1 tri))
156 (f 1 (.get2 tri))
157 (f 2 (.get3 tri))))
159 (defn points->triangle
160 "Convert a list of points into a triangle."
161 [points]
162 (apply #(Triangle. %1 %2 %3)
163 (map (fn [point]
164 (let [point (vec point)]
165 (Vector3f. (get point 0 0)
166 (get point 1 0)
167 (get point 2 0))))
168 (take 3 points))))
169 #+end_src
171 * Triangle Affine Transforms
173 The position of each hair is stored in a 2D image in UV
174 coordinates. To place the hair in 3D space we must convert from UV
175 coordinates to XYZ coordinates. Each =Triangle= has coordinates in
176 both UV-space and XYZ-space, which defines a unique [[http://mathworld.wolfram.com/AffineTransformation.html ][Affine Transform]]
177 for translating any coordinate within the UV triangle to the
178 cooresponding coordinate in the XYZ triangle.
180 #+begin_src clojure
181 (defn triangle->matrix4f
182 "Converts the triangle into a 4x4 matrix: The first three columns
183 contain the vertices of the triangle; the last contains the unit
184 normal of the triangle. The bottom row is filled with 1s."
185 [#^Triangle t]
186 (let [mat (Matrix4f.)
187 [vert-1 vert-2 vert-3]
188 ((comp vec map) #(.get t %) (range 3))
189 unit-normal (do (.calculateNormal t)(.getNormal t))
190 vertices [vert-1 vert-2 vert-3 unit-normal]]
191 (dorun
192 (for [row (range 4) col (range 3)]
193 (do
194 (.set mat col row (.get (vertices row)col))
195 (.set mat 3 row 1))))
196 mat))
198 (defn triangle-transformation
199 "Returns the affine transformation that converts each vertex in the
200 first triangle into the corresponding vertex in the second
201 triangle."
202 [#^Triangle tri-1 #^Triangle tri-2]
203 (.mult
204 (triangle->matrix4f tri-2)
205 (.invert (triangle->matrix4f tri-1))))
206 #+end_src
208 * Triangle Boundaries
210 For efficiency's sake I will divide the UV-image into small squares
211 which inscribe each UV-triangle, then extract the points which lie
212 inside the triangle and map them to 3D-space using
213 =(triangle-transform)= above. To do this I need a function,
214 =(inside-triangle?)=, which determines whether a point is inside a
215 triangle in 2D UV-space.
217 #+begin_src clojure
218 (defn convex-bounds
219 "Returns the smallest square containing the given vertices, as a
220 vector of integers [left top width height]."
221 [uv-verts]
222 (let [xs (map first uv-verts)
223 ys (map second uv-verts)
224 x0 (Math/floor (apply min xs))
225 y0 (Math/floor (apply min ys))
226 x1 (Math/ceil (apply max xs))
227 y1 (Math/ceil (apply max ys))]
228 [x0 y0 (- x1 x0) (- y1 y0)]))
230 (defn same-side?
231 "Given the points p1 and p2 and the reference point ref, is point p
232 on the same side of the line that goes through p1 and p2 as ref is?"
233 [p1 p2 ref p]
234 (<=
235 0
236 (.dot
237 (.cross (.subtract p2 p1) (.subtract p p1))
238 (.cross (.subtract p2 p1) (.subtract ref p1)))))
240 (defn inside-triangle?
241 "Is the point inside the triangle?"
242 {:author "Dylan Holmes"}
243 [#^Triangle tri #^Vector3f p]
244 (let [[vert-1 vert-2 vert-3] (triangle-seq tri)]
245 (and
246 (same-side? vert-1 vert-2 vert-3 p)
247 (same-side? vert-2 vert-3 vert-1 p)
248 (same-side? vert-3 vert-1 vert-2 p))))
249 #+end_src
253 * Sensor Related Functions
255 These functions analyze the touch-sensor-profile image convert the
256 location of each touch sensor from pixel coordinates to UV-coordinates
257 and XYZ-coordinates.
259 #+begin_src clojure
260 (defn sensors-in-triangle
261 "Locate the touch sensors in the triangle, returning a map of their
262 UV and geometry-relative coordinates."
263 [image mesh tri-index]
264 (let [width (.getWidth image)
265 height (.getHeight image)
266 UV-vertex-coords (triangle-UV-coord mesh width height tri-index)
267 bounds (convex-bounds UV-vertex-coords)
269 cutout-triangle (points->triangle UV-vertex-coords)
270 UV-sensor-coords
271 (filter (comp (partial inside-triangle? cutout-triangle)
272 (fn [[u v]] (Vector3f. u v 0)))
273 (white-coordinates image bounds))
274 UV->geometry (triangle-transformation
275 cutout-triangle
276 (mesh-triangle mesh tri-index))
277 geometry-sensor-coords
278 (map (fn [[u v]] (.mult UV->geometry (Vector3f. u v 0)))
279 UV-sensor-coords)]
280 {:UV UV-sensor-coords :geometry geometry-sensor-coords}))
282 (defn-memo locate-feelers
283 "Search the geometry's tactile UV profile for touch sensors,
284 returning their positions in geometry-relative coordinates."
285 [#^Geometry geo]
286 (let [mesh (.getMesh geo)
287 num-triangles (.getTriangleCount mesh)]
288 (if-let [image (tactile-sensor-profile geo)]
289 (map
290 (partial sensors-in-triangle image mesh)
291 (range num-triangles))
292 (repeat (.getTriangleCount mesh) {:UV nil :geometry nil}))))
294 (defn-memo touch-topology
295 "Return a sequence of vectors of the form [x y] describing the
296 \"topology\" of the tactile sensors. Points that are close together
297 in the touch-topology are generally close together in the simulation."
298 [#^Gemoetry geo]
299 (vec (collapse (reduce concat (map :UV (locate-feelers geo))))))
301 (defn-memo feeler-coordinates
302 "The location of the touch sensors in world-space coordinates."
303 [#^Geometry geo]
304 (vec (map :geometry (locate-feelers geo))))
305 #+end_src
307 * Physics Collision Objects
308 #+begin_src clojure
309 (defn get-ray-origin
310 "Return the origin which a Ray would have to have to be in the exact
311 center of a particular Triangle in the Geometry in World
312 Coordinates."
313 [geom tri]
314 (let [new (Vector3f.)]
315 (.calculateCenter tri)
316 (.localToWorld geom (.getCenter tri) new) new))
318 (defn get-ray-direction
319 "Return the direction which a Ray would have to have to be to point
320 normal to the Triangle, in coordinates relative to the center of the
321 Triangle."
322 [geom tri]
323 (let [n+c (Vector3f.)]
324 (.calculateNormal tri)
325 (.calculateCenter tri)
326 (.localToWorld
327 geom
328 (.add (.getCenter tri) (.getNormal tri)) n+c)
329 (.subtract n+c (get-ray-origin geom tri))))
330 #+end_src
333 * Skin Creation
335 #+begin_src clojure
336 (defn touch-fn
337 "Returns a function which returns tactile sensory data when called
338 inside a running simulation."
339 [#^Geometry geo]
340 (let [feeler-coords (feeler-coordinates geo)
341 tris (triangles geo)
342 limit 0.1
343 ;;results (CollisionResults.)
344 ]
345 (if (empty? (touch-topology geo))
346 nil
347 (fn [node]
348 (let [sensor-origins
349 (map
350 #(map (partial local-to-world geo) %)
351 feeler-coords)
352 triangle-normals
353 (map (partial get-ray-direction geo)
354 tris)
355 rays
356 (flatten
357 (map (fn [origins norm]
358 (map #(doto (Ray. % norm)
359 (.setLimit limit)) origins))
360 sensor-origins triangle-normals))]
361 (vector
362 (touch-topology geo)
363 (vec
364 (for [ray rays]
365 (do
366 (let [results (CollisionResults.)]
367 (.collideWith node ray results)
368 (let [touch-objects
369 (filter #(not (= geo (.getGeometry %)))
370 results)]
371 (- 255
372 (if (empty? touch-objects) 255
373 (rem
374 (int
375 (* 255 (/ (.getDistance
376 (first touch-objects)) limit)))
377 256))))))))))))))
379 (defn touch!
380 "Endow the creature with the sense of touch. Returns a sequence of
381 functions, one for each body part with a tactile-sensor-proile,
382 each of which when called returns sensory data for that body part."
383 [#^Node creature]
384 (filter
385 (comp not nil?)
386 (map touch-fn
387 (filter #(isa? (class %) Geometry)
388 (node-seq creature)))))
389 #+end_src
391 * Visualizing Touch
393 #+begin_src clojure
394 (defn view-touch
395 "Creates a function which accepts a list of touch sensor-data and
396 displays each element to the screen."
397 []
398 (view-sense
399 (fn
400 [[coords sensor-data]]
401 (let [image (points->image coords)]
402 (dorun
403 (for [i (range (count coords))]
404 (.setRGB image ((coords i) 0) ((coords i) 1)
405 (gray (sensor-data i)))))
406 image))))
407 #+end_src
409 * Headers
410 #+begin_src clojure
411 (ns cortex.touch
412 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry
413 to be outfitted with touch sensors with density determined by a UV
414 image. In this way a Geometry can know what parts of itself are
415 touching nearby objects. Reads specially prepared blender files to
416 construct this sense automatically."
417 {:author "Robert McIntyre"}
418 (:use (cortex world util sense))
419 (:use clojure.contrib.def)
420 (:import (com.jme3.scene Geometry Node Mesh))
421 (:import com.jme3.collision.CollisionResults)
422 (:import com.jme3.scene.VertexBuffer$Type)
423 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))
424 #+end_src
427 * Source Listing
428 * Next
431 * COMMENT Code Generation
432 #+begin_src clojure :tangle ../src/cortex/touch.clj
433 <<skin-main>>
434 #+end_src
436 #+begin_src clojure :tangle ../src/cortex/test/touch.clj
437 #+end_src