view org/touch.org @ 245:102ac596cc3f

minor formatting changes
author Robert McIntyre <rlm@mit.edu>
date Sun, 12 Feb 2012 14:33:52 -0700
parents f23217324f72
children 63da037ce1c5
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
9 * Touch
11 Touch is critical to navigation and spatial reasoning and as such I
12 need a simulated version of it to give to my AI creatures.
14 However, touch in my virtual can not exactly correspond to human touch
15 because my creatures are made out of completely rigid segments that
16 don't deform like human skin.
18 Human skin has a wide array of touch sensors, each of which speciliaze
19 in detecting different vibrational modes and pressures. These sensors
20 can integrate a vast expanse of skin (i.e. your entire palm), or a
21 tiny patch of skin at the tip of your finger. The hairs of the skin
22 help detect objects before they even come into contact with the skin
23 proper.
25 Instead of measuring deformation or vibration, I surround each rigid
26 part with a plenitude of hair-like objects which do not interact with
27 the physical world. Physical objects can pass through them with no
28 effect. The hairs are able to measure contact with other objects, and
29 constantly report how much of their extent is covered. So, even though
30 the creature's body parts do not deform, the hairs create a margin
31 around those body parts which achieves a sense of touch which is a
32 hybrid between a human's sense of deformation and sense from hairs.
34 Implementing touch in jMonkeyEngine follows a different techinal route
35 than vision and hearing. Those two senses piggybacked off
36 jMonkeyEngine's 3D audio and video rendering subsystems. To simulate
37 Touch, I use jMonkeyEngine's physics system to execute many small
38 collision detections, one for each "hair". The placement of the
39 "hairs" is determined by a UV-mapped image which shows where each hair
40 should be on the 3D surface of the body.
43 * Defining Touch Meta-Data in Blender
45 Each geometry can have a single UV map which describes the position of
46 the "hairs" which will constitute its sense of touch. This image path
47 is stored under the "touch" key. The image itself is black and white,
48 with black meaning a hair length of 0 (no hair is present) and white
49 meaning a hair length of =scale=, which is a float stored under the
50 key "scale". I call these "hairs" /feelers/.
52 #+name: meta-data
53 #+begin_src clojure
54 (defn tactile-sensor-profile
55 "Return the touch-sensor distribution image in BufferedImage format,
56 or nil if it does not exist."
57 [#^Geometry obj]
58 (if-let [image-path (meta-data obj "touch")]
59 (load-image image-path)))
61 (defn tactile-scale
62 "Return the maximum length of a hair. All hairs are scalled between
63 0.0 and this length, depending on their color. Black is 0, and
64 white is maximum length, and everything in between is scalled
65 linearlly. Default scale is 0.01 jMonkeyEngine units."
66 [#^Geometry obj]
67 (if-let [scale (meta-data obj "scale")]
68 scale 0.1))
69 #+end_src
71 ** TODO add image showing example touch-uv map
72 ** TODO add metadata display for worm
75 * Skin Creation
77 =(touch-kernel)= generates the functions which implement the sense of
78 touch for a creature. These functions must do 6 things to obtain touch
79 data.
81 - Get the tactile profile image and scale paramaters which describe
82 the layout of feelers along the object's surface.
83 =(tactile-sensor-profile)=, =(tactile-scale)=
85 - Find the triangles which make up the mesh in pixel-space and in
86 world-space.
87 =(triangles)= =(pixel-triangles)=
89 - Find the coordinates of each pixel in pixel space. These
90 coordinates are used to make the touch-topology.
91 =(feeler-pixel-coords)=
93 - Find the coordinates of each pixel in world-space. These
94 coordinates are the origins of the feelers. =(feeler-origins)=
96 - Calculate the normals of the triangles in world space, and add
97 them to each of the origins of the feelers. These are the
98 normalized coordinates of the tips of the feelers.
99 For both of these, =(feeler-tips)=
101 - Generate some sort of topology for the sensors.
102 =(touch-topology)=
105 #+name: kernel
106 #+begin_src clojure
107 (in-ns 'cortex.touch)
109 (defn set-ray [#^Ray ray #^Matrix4f transform
110 #^Vector3f origin #^Vector3f tip]
111 ;; Doing everything locally recduces garbage collection by enough to
112 ;; be worth it.
113 (.mult transform origin (.getOrigin ray))
115 (.mult transform tip (.getDirection ray))
116 (.subtractLocal (.getDirection ray) (.getOrigin ray)))
118 (defn touch-kernel
119 "Constructs a function which will return tactile sensory data from
120 'geo when called from inside a running simulation"
121 [#^Geometry geo]
122 (if-let
123 [profile (tactile-sensor-profile geo)]
124 (let [ray-reference-origins (feeler-origins geo profile)
125 ray-reference-tips (feeler-tips geo profile)
126 ray-length (tactile-scale geo)
127 current-rays (map (fn [_] (Ray.)) ray-reference-origins)
128 topology (touch-topology geo profile)]
129 (dorun (map #(.setLimit % ray-length) current-rays))
130 (fn [node]
131 (let [transform (.getWorldMatrix geo)]
132 (dorun
133 (map (fn [ray ref-origin ref-tip]
134 (set-ray ray transform ref-origin ref-tip))
135 current-rays ray-reference-origins
136 ray-reference-tips))
137 (vector
138 topology
139 (vec
140 (for [ray current-rays]
141 (do
142 (let [results (CollisionResults.)]
143 (.collideWith node ray results)
144 (let [touch-objects
145 (filter #(not (= geo (.getGeometry %)))
146 results)]
147 [(if (empty? touch-objects)
148 (.getLimit ray)
149 (.getDistance (first touch-objects)))
150 (.getLimit ray)])))))))))))
152 (defn touch!
153 "Endow the creature with the sense of touch. Returns a sequence of
154 functions, one for each body part with a tactile-sensor-proile,
155 each of which when called returns sensory data for that body part."
156 [#^Node creature]
157 (filter
158 (comp not nil?)
159 (map touch-kernel
160 (filter #(isa? (class %) Geometry)
161 (node-seq creature)))))
162 #+end_src
164 * Sensor Related Functions
166 These functions analyze the touch-sensor-profile image convert the
167 location of each touch sensor from pixel coordinates to UV-coordinates
168 and XYZ-coordinates.
170 #+name: sensors
171 #+begin_src clojure
172 (in-ns 'cortex.touch)
174 (defn feeler-pixel-coords
175 "Returns the coordinates of the feelers in pixel space in lists, one
176 list for each triangle, ordered in the same way as (triangles) and
177 (pixel-triangles)."
178 [#^Geometry geo image]
179 (map
180 (fn [pixel-triangle]
181 (filter
182 (fn [coord]
183 (inside-triangle? (->triangle pixel-triangle)
184 (->vector3f coord)))
185 (white-coordinates image (convex-bounds pixel-triangle))))
186 (pixel-triangles geo image)))
188 (defn feeler-world-coords [#^Geometry geo image]
189 (let [transforms
190 (map #(triangles->affine-transform
191 (->triangle %1) (->triangle %2))
192 (pixel-triangles geo image)
193 (triangles geo))]
194 (map (fn [transform coords]
195 (map #(.mult transform (->vector3f %)) coords))
196 transforms (feeler-pixel-coords geo image))))
198 (defn feeler-origins [#^Geometry geo image]
199 (reduce concat (feeler-world-coords geo image)))
201 (defn feeler-tips [#^Geometry geo image]
202 (let [world-coords (feeler-world-coords geo image)
203 normals
204 (map
205 (fn [triangle]
206 (.calculateNormal triangle)
207 (.clone (.getNormal triangle)))
208 (map ->triangle (triangles geo)))]
210 (mapcat (fn [origins normal]
211 (map #(.add % normal) origins))
212 world-coords normals)))
214 (defn touch-topology [#^Geometry geo image]
215 (collapse (reduce concat (feeler-pixel-coords geo image))))
216 #+end_src
218 * Visualizing Touch
219 #+name: visualization
220 #+begin_src clojure
221 (in-ns 'cortex.touch)
223 (defn touch->gray
224 "Convert a pair of [distance, max-distance] into a grayscale pixel."
225 [distance max-distance]
226 (gray (- 255 (rem (int (* 255 (/ distance max-distance))) 256))))
228 (defn view-touch
229 "Creates a function which accepts a list of touch sensor-data and
230 displays each element to the screen."
231 []
232 (view-sense
233 (fn
234 [[coords sensor-data]]
235 (let [image (points->image coords)]
236 (dorun
237 (for [i (range (count coords))]
238 (.setRGB image ((coords i) 0) ((coords i) 1)
239 (apply touch->gray (sensor-data i)))))
240 image))))
241 #+end_src
245 * Triangle Manipulation Functions
247 The rigid bodies which make up a creature have an underlying
248 =Geometry=, which is a =Mesh= plus a =Material= and other important
249 data involved with displaying the body.
251 A =Mesh= is composed of =Triangles=, and each =Triangle= has three
252 verticies which have coordinates in XYZ space and UV space.
254 Here, =(triangles)= gets all the triangles which compose a mesh, and
255 =(triangle-UV-coord)= returns the the UV coordinates of the verticies
256 of a triangle.
258 #+name: triangles-1
259 #+begin_src clojure
260 (in-ns 'cortex.touch)
262 (defn vector3f-seq [#^Vector3f v]
263 [(.getX v) (.getY v) (.getZ v)])
265 (defn triangle-seq [#^Triangle tri]
266 [(vector3f-seq (.get1 tri))
267 (vector3f-seq (.get2 tri))
268 (vector3f-seq (.get3 tri))])
270 (defn ->vector3f
271 ([coords] (Vector3f. (nth coords 0 0)
272 (nth coords 1 0)
273 (nth coords 2 0))))
275 (defn ->triangle [points]
276 (apply #(Triangle. %1 %2 %3) (map ->vector3f points)))
278 (defn triangle
279 "Get the triangle specified by triangle-index from the mesh."
280 [#^Geometry geo triangle-index]
281 (triangle-seq
282 (let [scratch (Triangle.)]
283 (.getTriangle (.getMesh geo) triangle-index scratch) scratch)))
285 (defn triangles
286 "Return a sequence of all the Triangles which compose a given
287 Geometry."
288 [#^Geometry geo]
289 (map (partial triangle geo) (range (.getTriangleCount (.getMesh geo)))))
291 (defn triangle-vertex-indices
292 "Get the triangle vertex indices of a given triangle from a given
293 mesh."
294 [#^Mesh mesh triangle-index]
295 (let [indices (int-array 3)]
296 (.getTriangle mesh triangle-index indices)
297 (vec indices)))
299 (defn vertex-UV-coord
300 "Get the UV-coordinates of the vertex named by vertex-index"
301 [#^Mesh mesh vertex-index]
302 (let [UV-buffer
303 (.getData
304 (.getBuffer
305 mesh
306 VertexBuffer$Type/TexCoord))]
307 [(.get UV-buffer (* vertex-index 2))
308 (.get UV-buffer (+ 1 (* vertex-index 2)))]))
310 (defn pixel-triangle [#^Geometry geo image index]
311 (let [mesh (.getMesh geo)
312 width (.getWidth image)
313 height (.getHeight image)]
314 (vec (map (fn [[u v]] (vector (* width u) (* height v)))
315 (map (partial vertex-UV-coord mesh)
316 (triangle-vertex-indices mesh index))))))
318 (defn pixel-triangles [#^Geometry geo image]
319 (let [height (.getHeight image)
320 width (.getWidth image)]
321 (map (partial pixel-triangle geo image)
322 (range (.getTriangleCount (.getMesh geo))))))
324 #+end_src
326 * Triangle Affine Transforms
328 The position of each hair is stored in a 2D image in UV
329 coordinates. To place the hair in 3D space we must convert from UV
330 coordinates to XYZ coordinates. Each =Triangle= has coordinates in
331 both UV-space and XYZ-space, which defines a unique [[http://mathworld.wolfram.com/AffineTransformation.html ][Affine Transform]]
332 for translating any coordinate within the UV triangle to the
333 cooresponding coordinate in the XYZ triangle.
335 #+name: triangles-3
336 #+begin_src clojure
337 (in-ns 'cortex.touch)
339 (defn triangle->matrix4f
340 "Converts the triangle into a 4x4 matrix: The first three columns
341 contain the vertices of the triangle; the last contains the unit
342 normal of the triangle. The bottom row is filled with 1s."
343 [#^Triangle t]
344 (let [mat (Matrix4f.)
345 [vert-1 vert-2 vert-3]
346 ((comp vec map) #(.get t %) (range 3))
347 unit-normal (do (.calculateNormal t)(.getNormal t))
348 vertices [vert-1 vert-2 vert-3 unit-normal]]
349 (dorun
350 (for [row (range 4) col (range 3)]
351 (do
352 (.set mat col row (.get (vertices row)col))
353 (.set mat 3 row 1)))) mat))
355 (defn triangles->affine-transform
356 "Returns the affine transformation that converts each vertex in the
357 first triangle into the corresponding vertex in the second
358 triangle."
359 [#^Triangle tri-1 #^Triangle tri-2]
360 (.mult
361 (triangle->matrix4f tri-2)
362 (.invert (triangle->matrix4f tri-1))))
363 #+end_src
366 * Schrapnel Conversion Functions
368 It is convienent to treat a =Triangle= as a sequence of verticies, and
369 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion
370 functions make this easy. If these classes implemented =Iterable= then
371 this code would not be necessary. Hopefully they will in the future.
374 * Triangle Boundaries
376 For efficiency's sake I will divide the UV-image into small squares
377 which inscribe each UV-triangle, then extract the points which lie
378 inside the triangle and map them to 3D-space using
379 =(triangle-transform)= above. To do this I need a function,
380 =(inside-triangle?)=, which determines whether a point is inside a
381 triangle in 2D UV-space.
383 #+name: triangles-4
384 #+begin_src clojure
385 (defn convex-bounds
386 "Returns the smallest square containing the given vertices, as a
387 vector of integers [left top width height]."
388 [verts]
389 (let [xs (map first verts)
390 ys (map second verts)
391 x0 (Math/floor (apply min xs))
392 y0 (Math/floor (apply min ys))
393 x1 (Math/ceil (apply max xs))
394 y1 (Math/ceil (apply max ys))]
395 [x0 y0 (- x1 x0) (- y1 y0)]))
397 (defn same-side?
398 "Given the points p1 and p2 and the reference point ref, is point p
399 on the same side of the line that goes through p1 and p2 as ref is?"
400 [p1 p2 ref p]
401 (<=
402 0
403 (.dot
404 (.cross (.subtract p2 p1) (.subtract p p1))
405 (.cross (.subtract p2 p1) (.subtract ref p1)))))
407 (defn inside-triangle?
408 "Is the point inside the triangle?"
409 {:author "Dylan Holmes"}
410 [#^Triangle tri #^Vector3f p]
411 (let [[vert-1 vert-2 vert-3] [(.get1 tri) (.get2 tri) (.get3 tri)]]
412 (and
413 (same-side? vert-1 vert-2 vert-3 p)
414 (same-side? vert-2 vert-3 vert-1 p)
415 (same-side? vert-3 vert-1 vert-2 p))))
416 #+end_src
418 * Physics Collision Objects
420 The "hairs" are actually =Rays= which extend from a point on a
421 =Triangle= in the =Mesh= normal to the =Triangle's= surface.
423 * Headers
425 #+name: touch-header
426 #+begin_src clojure
427 (ns cortex.touch
428 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry
429 to be outfitted with touch sensors with density determined by a UV
430 image. In this way a Geometry can know what parts of itself are
431 touching nearby objects. Reads specially prepared blender files to
432 construct this sense automatically."
433 {:author "Robert McIntyre"}
434 (:use (cortex world util sense))
435 (:use clojure.contrib.def)
436 (:import (com.jme3.scene Geometry Node Mesh))
437 (:import com.jme3.collision.CollisionResults)
438 (:import com.jme3.scene.VertexBuffer$Type)
439 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))
440 #+end_src
442 * Adding Touch to the Worm
444 #+name: test-touch
445 #+begin_src clojure
446 (ns cortex.test.touch
447 (:use (cortex world util sense body touch))
448 (:use cortex.test.body))
450 (cortex.import/mega-import-jme3)
452 (defn test-touch []
453 (let [the-worm (doto (worm) (body!))
454 touch (touch! the-worm)
455 touch-display (view-touch)]
456 (world (nodify [the-worm (floor)])
457 standard-debug-controls
459 (fn [world]
460 (speed-up world)
461 (light-up-everything world))
463 (fn [world tpf]
464 (touch-display (map #(% (.getRootNode world)) touch))
465 ))))
466 #+end_src
467 * Source Listing
468 * Next
471 * COMMENT Code Generation
472 #+begin_src clojure :tangle ../src/cortex/touch.clj
473 <<touch-header>>
474 <<meta-data>>
475 <<triangles-1>>
476 <<triangles-3>>
477 <<triangles-4>>
478 <<sensors>>
479 <<kernel>>
480 <<visualization>>
481 #+end_src
484 #+begin_src clojure :tangle ../src/cortex/test/touch.clj
485 <<test-touch>>
486 #+end_src