view org/touch.org @ 230:f9b7d674aed8

reorganizing touch
author Robert McIntyre <rlm@mit.edu>
date Sat, 11 Feb 2012 19:28:36 -0700
parents 6f1be9525e40
children e29dd0024a9e
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
309 The "hairs" are actually rays which extend from a point on a
310 =Triangle= in the =Mesh= normal to the =Triangle's= surface.
312 #+begin_src clojure
313 (defn get-ray-origin
314 "Return the origin which a Ray would have to have to be in the exact
315 center of a particular Triangle in the Geometry in World
316 Coordinates."
317 [geom tri]
318 (let [new (Vector3f.)]
319 (.calculateCenter tri)
320 (.localToWorld geom (.getCenter tri) new) new))
322 (defn get-ray-direction
323 "Return the direction which a Ray would have to have to be to point
324 normal to the Triangle, in coordinates relative to the center of the
325 Triangle."
326 [geom tri]
327 (let [n+c (Vector3f.)]
328 (.calculateNormal tri)
329 (.calculateCenter tri)
330 (.localToWorld
331 geom
332 (.add (.getCenter tri) (.getNormal tri)) n+c)
333 (.subtract n+c (get-ray-origin geom tri))))
334 #+end_src
337 * Skin Creation
339 #+begin_src clojure
340 (defn touch-fn
341 "Returns a function which returns tactile sensory data when called
342 inside a running simulation."
343 [#^Geometry geo]
344 (let [feeler-coords (feeler-coordinates geo)
345 tris (triangles geo)
346 limit 0.1
347 ;;results (CollisionResults.)
348 ]
349 (if (empty? (touch-topology geo))
350 nil
351 (fn [node]
352 (let [sensor-origins
353 (map
354 #(map (partial local-to-world geo) %)
355 feeler-coords)
356 triangle-normals
357 (map (partial get-ray-direction geo)
358 tris)
359 rays
360 (flatten
361 (map (fn [origins norm]
362 (map #(doto (Ray. % norm)
363 (.setLimit limit)) origins))
364 sensor-origins triangle-normals))]
365 (vector
366 (touch-topology geo)
367 (vec
368 (for [ray rays]
369 (do
370 (let [results (CollisionResults.)]
371 (.collideWith node ray results)
372 (let [touch-objects
373 (filter #(not (= geo (.getGeometry %)))
374 results)]
375 (- 255
376 (if (empty? touch-objects) 255
377 (rem
378 (int
379 (* 255 (/ (.getDistance
380 (first touch-objects)) limit)))
381 256))))))))))))))
383 (defn touch!
384 "Endow the creature with the sense of touch. Returns a sequence of
385 functions, one for each body part with a tactile-sensor-proile,
386 each of which when called returns sensory data for that body part."
387 [#^Node creature]
388 (filter
389 (comp not nil?)
390 (map touch-fn
391 (filter #(isa? (class %) Geometry)
392 (node-seq creature)))))
393 #+end_src
395 * Visualizing Touch
397 #+begin_src clojure
398 (defn view-touch
399 "Creates a function which accepts a list of touch sensor-data and
400 displays each element to the screen."
401 []
402 (view-sense
403 (fn
404 [[coords sensor-data]]
405 (let [image (points->image coords)]
406 (dorun
407 (for [i (range (count coords))]
408 (.setRGB image ((coords i) 0) ((coords i) 1)
409 (gray (sensor-data i)))))
410 image))))
411 #+end_src
413 * Headers
414 #+begin_src clojure
415 (ns cortex.touch
416 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry
417 to be outfitted with touch sensors with density determined by a UV
418 image. In this way a Geometry can know what parts of itself are
419 touching nearby objects. Reads specially prepared blender files to
420 construct this sense automatically."
421 {:author "Robert McIntyre"}
422 (:use (cortex world util sense))
423 (:use clojure.contrib.def)
424 (:import (com.jme3.scene Geometry Node Mesh))
425 (:import com.jme3.collision.CollisionResults)
426 (:import com.jme3.scene.VertexBuffer$Type)
427 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))
428 #+end_src
431 * Source Listing
432 * Next
435 * COMMENT Code Generation
436 #+begin_src clojure :tangle ../src/cortex/touch.clj
437 <<skin-main>>
438 #+end_src
440 #+begin_src clojure :tangle ../src/cortex/test/touch.clj
441 #+end_src