Mercurial > cortex
view org/touch.org @ 247:4e220c8fb1ed
first pass at rough draft complete
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sun, 12 Feb 2012 15:46:01 -0700 |
parents | 63da037ce1c5 |
children | 267add63b168 |
line wrap: on
line source
1 #+title: Simulated Sense of Touch2 #+author: Robert McIntyre3 #+email: rlm@mit.edu4 #+description: Simulated touch for AI research using JMonkeyEngine and clojure.5 #+keywords: simulation, tactile sense, jMonkeyEngine3, clojure6 #+SETUPFILE: ../../aurellem/org/setup.org7 #+INCLUDE: ../../aurellem/org/level-0.org9 * Touch11 Touch is critical to navigation and spatial reasoning and as such I12 need a simulated version of it to give to my AI creatures.14 However, touch in my virtual can not exactly correspond to human touch15 because my creatures are made out of completely rigid segments that16 don't deform like human skin.18 Human skin has a wide array of touch sensors, each of which speciliaze19 in detecting different vibrational modes and pressures. These sensors20 can integrate a vast expanse of skin (i.e. your entire palm), or a21 tiny patch of skin at the tip of your finger. The hairs of the skin22 help detect objects before they even come into contact with the skin23 proper.25 Instead of measuring deformation or vibration, I surround each rigid26 part with a plenitude of hair-like objects (/feelers/) which do not27 interact with the physical world. Physical objects can pass through28 them with no effect. The feelers are able to measure contact with29 other objects, and constantly report how much of their extent is30 covered. So, even though the creature's body parts do not deform, the31 feelers create a margin around those body parts which achieves a sense32 of touch which is a hybrid between a human's sense of deformation and33 sense from hairs.35 Implementing touch in jMonkeyEngine follows a different techinal route36 than vision and hearing. Those two senses piggybacked off37 jMonkeyEngine's 3D audio and video rendering subsystems. To simulate38 touch, I use jMonkeyEngine's physics system to execute many small39 collision detections, one for each feeler. The placement of the40 feelers is determined by a UV-mapped image which shows where each41 feeler should be on the 3D surface of the body.43 * Defining Touch Meta-Data in Blender45 Each geometry can have a single UV map which describes the position of46 the feelers which will constitute its sense of touch. This image path47 is stored under the "touch" key. The image itself is black and white,48 with black meaning a feeler length of 0 (no feeler is present) and49 white meaning a feeler length of =scale=, which is a float stored50 under the key "scale".52 #+name: meta-data53 #+begin_src clojure54 (defn tactile-sensor-profile55 "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-scale62 "Return the length of each feeler. Default scale is 0.0163 jMonkeyEngine units."64 [#^Geometry obj]65 (if-let [scale (meta-data obj "scale")]66 scale 0.1))67 #+end_src69 Here is an example of a UV-map which specifies the position of touch70 sensors along the surface of the upper segment of the worm.72 #+attr_html: width=75573 #+caption: This is the tactile-sensor-profile for the upper segment of the worm. It defines regions of high touch sensitivity (where there are many white pixels) and regions of low sensitivity (where white pixels are sparse).74 [[../images/finger-UV.png]]76 * Implementation Summary78 To simulate touch there are three conceptual steps. For each solid79 object in the creature, you first have to get UV image and scale80 paramater which define the position and length of the feelers. Then,81 you use the triangles which compose the mesh and the UV data stored in82 the mesh to determine the world-space position and orientation of each83 feeler. Once every frame, update these positions and orientations to84 match the current position and orientation of the object, and use85 physics collision detection to gather tactile data.87 Extracting the meta-data has already been described. The third step,88 physics collision detection, is handled in =(touch-kernel)=.89 Translating the positions and orientations of the feelers from the90 UV-map to world-space is also a three-step process.92 - Find the triangles which make up the mesh in pixel-space and in93 world-space. =(triangles)= =(pixel-triangles)=.95 - Find the coordinates of each feeler in world-space. These are the96 origins of the feelers. =(feeler-origins)=.98 - Calculate the normals of the triangles in world space, and add99 them to each of the origins of the feelers. These are the100 normalized coordinates of the tips of the feelers. =(feeler-tips)=.102 * Triangle Math103 ** Schrapnel Conversion Functions105 #+name: triangles-1106 #+begin_src clojure107 (defn vector3f-seq [#^Vector3f v]108 [(.getX v) (.getY v) (.getZ v)])110 (defn triangle-seq [#^Triangle tri]111 [(vector3f-seq (.get1 tri))112 (vector3f-seq (.get2 tri))113 (vector3f-seq (.get3 tri))])115 (defn ->vector3f116 ([coords] (Vector3f. (nth coords 0 0)117 (nth coords 1 0)118 (nth coords 2 0))))120 (defn ->triangle [points]121 (apply #(Triangle. %1 %2 %3) (map ->vector3f points)))122 #+end_src124 It is convienent to treat a =Triangle= as a sequence of verticies, and125 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion126 functions make this easy. If these classes implemented =Iterable= then127 =(seq)= would work on them automitacally.128 ** Decomposing a 3D shape into Triangles130 The rigid bodies which make up a creature have an underlying131 =Geometry=, which is a =Mesh= plus a =Material= and other important132 data involved with displaying the body.134 A =Mesh= is composed of =Triangles=, and each =Triangle= has three135 verticies which have coordinates in world space and UV space.137 Here, =(triangles)= gets all the world-space triangles which compose a138 mesh, while =(pixel-triangles)= gets those same triangles expressed in139 pixel coordinates (which are UV coordinates scaled to fit the height140 and width of the UV image).142 #+name: triangles-2143 #+begin_src clojure144 (in-ns 'cortex.touch)145 (defn triangle146 "Get the triangle specified by triangle-index from the mesh."147 [#^Geometry geo triangle-index]148 (triangle-seq149 (let [scratch (Triangle.)]150 (.getTriangle (.getMesh geo) triangle-index scratch) scratch)))152 (defn triangles153 "Return a sequence of all the Triangles which compose a given154 Geometry."155 [#^Geometry geo]156 (map (partial triangle geo) (range (.getTriangleCount (.getMesh geo)))))158 (defn triangle-vertex-indices159 "Get the triangle vertex indices of a given triangle from a given160 mesh."161 [#^Mesh mesh triangle-index]162 (let [indices (int-array 3)]163 (.getTriangle mesh triangle-index indices)164 (vec indices)))166 (defn vertex-UV-coord167 "Get the UV-coordinates of the vertex named by vertex-index"168 [#^Mesh mesh vertex-index]169 (let [UV-buffer170 (.getData171 (.getBuffer172 mesh173 VertexBuffer$Type/TexCoord))]174 [(.get UV-buffer (* vertex-index 2))175 (.get UV-buffer (+ 1 (* vertex-index 2)))]))177 (defn pixel-triangle [#^Geometry geo image index]178 (let [mesh (.getMesh geo)179 width (.getWidth image)180 height (.getHeight image)]181 (vec (map (fn [[u v]] (vector (* width u) (* height v)))182 (map (partial vertex-UV-coord mesh)183 (triangle-vertex-indices mesh index))))))185 (defn pixel-triangles [#^Geometry geo image]186 (let [height (.getHeight image)187 width (.getWidth image)]188 (map (partial pixel-triangle geo image)189 (range (.getTriangleCount (.getMesh geo))))))190 #+end_src191 ** The Affine Transform from one Triangle to Another193 =(pixel-triangles)= gives us the mesh triangles expressed in pixel194 coordinates and =(triangles)= gives us the mesh triangles expressed in195 world coordinates. The tactile-sensor-profile gives the position of196 each feeler in pixel-space. In order to convert pixel-dpace197 coordinates into world-space coordinates we need something that takes198 coordinates on the surface of one triangle and gives the corresponding199 coordinates on the surface of another triangle.201 Triangles are [[http://mathworld.wolfram.com/AffineTransformation.html ][affine]], which means any triangle can be transformed into202 any other by a combination of translation, scaling, and203 rotation. jMonkeyEngine's =Matrix4f= objects can describe any affine204 transformation. The affine transformation from one triangle to another205 is readily computable if the triangle is expressed in terms of a $4x4$206 matrix.208 \begin{bmatrix}209 x_1 & x_2 & x_3 & n_x \\210 y_1 & y_2 & y_3 & n_y \\211 z_1 & z_2 & z_3 & n_z \\212 1 & 1 & 1 & 1213 \end{bmatrix}215 Here, the first three columns of the matrix are the verticies of the216 triangle. The last column is the right-handed unit normal of the217 triangle.219 With two triangles $T_{1}$ and $T_{2}$ each expressed as a matrix like220 above, the affine transform from $T_{1}$ to $T_{2}$ is222 $T_{2}T_{1}^{-1}$224 The clojure code below recaptiulates the formulas above.226 #+name: triangles-3227 #+begin_src clojure228 (in-ns 'cortex.touch)230 (defn triangle->matrix4f231 "Converts the triangle into a 4x4 matrix: The first three columns232 contain the vertices of the triangle; the last contains the unit233 normal of the triangle. The bottom row is filled with 1s."234 [#^Triangle t]235 (let [mat (Matrix4f.)236 [vert-1 vert-2 vert-3]237 ((comp vec map) #(.get t %) (range 3))238 unit-normal (do (.calculateNormal t)(.getNormal t))239 vertices [vert-1 vert-2 vert-3 unit-normal]]240 (dorun241 (for [row (range 4) col (range 3)]242 (do243 (.set mat col row (.get (vertices row) col))244 (.set mat 3 row 1)))) mat))246 (defn triangles->affine-transform247 "Returns the affine transformation that converts each vertex in the248 first triangle into the corresponding vertex in the second249 triangle."250 [#^Triangle tri-1 #^Triangle tri-2]251 (.mult252 (triangle->matrix4f tri-2)253 (.invert (triangle->matrix4f tri-1))))254 #+end_src255 ** Triangle Boundaries257 For efficiency's sake I will divide the tactile-profile image into258 small squares which inscribe each pixel-triangle, then extract the259 points which lie inside the triangle and map them to 3D-space using260 =(triangle-transform)= above. To do this I need a function,261 =(convex-bounds)= which finds the smallest box which inscribes a 2D262 triangle.264 =(inside-triangle?)= determines whether a point is inside a triangle265 in 2D pixel-space.267 #+name: triangles-4268 #+begin_src clojure269 (defn convex-bounds270 "Returns the smallest square containing the given vertices, as a271 vector of integers [left top width height]."272 [verts]273 (let [xs (map first verts)274 ys (map second verts)275 x0 (Math/floor (apply min xs))276 y0 (Math/floor (apply min ys))277 x1 (Math/ceil (apply max xs))278 y1 (Math/ceil (apply max ys))]279 [x0 y0 (- x1 x0) (- y1 y0)]))281 (defn same-side?282 "Given the points p1 and p2 and the reference point ref, is point p283 on the same side of the line that goes through p1 and p2 as ref is?"284 [p1 p2 ref p]285 (<=286 0287 (.dot288 (.cross (.subtract p2 p1) (.subtract p p1))289 (.cross (.subtract p2 p1) (.subtract ref p1)))))291 (defn inside-triangle?292 "Is the point inside the triangle?"293 {:author "Dylan Holmes"}294 [#^Triangle tri #^Vector3f p]295 (let [[vert-1 vert-2 vert-3] [(.get1 tri) (.get2 tri) (.get3 tri)]]296 (and297 (same-side? vert-1 vert-2 vert-3 p)298 (same-side? vert-2 vert-3 vert-1 p)299 (same-side? vert-3 vert-1 vert-2 p))))300 #+end_src302 * Feeler Coordinates304 The triangle-related functions above make short work of calculating305 the positions and orientations of each feeler in world-space.307 #+name: sensors308 #+begin_src clojure309 (in-ns 'cortex.touch)311 (defn feeler-pixel-coords312 "Returns the coordinates of the feelers in pixel space in lists, one313 list for each triangle, ordered in the same way as (triangles) and314 (pixel-triangles)."315 [#^Geometry geo image]316 (map317 (fn [pixel-triangle]318 (filter319 (fn [coord]320 (inside-triangle? (->triangle pixel-triangle)321 (->vector3f coord)))322 (white-coordinates image (convex-bounds pixel-triangle))))323 (pixel-triangles geo image)))325 (defn feeler-world-coords326 "Returns the coordinates of the feelers in world space in lists, one327 list for each triangle, ordered in the same way as (triangles) and328 (pixel-triangles)."329 [#^Geometry geo image]330 (let [transforms331 (map #(triangles->affine-transform332 (->triangle %1) (->triangle %2))333 (pixel-triangles geo image)334 (triangles geo))]335 (map (fn [transform coords]336 (map #(.mult transform (->vector3f %)) coords))337 transforms (feeler-pixel-coords geo image))))339 (defn feeler-origins340 "The world space coordinates of the root of each feeler."341 [#^Geometry geo image]342 (reduce concat (feeler-world-coords geo image)))344 (defn feeler-tips345 "The world space coordinates of the tip of each feeler."346 [#^Geometry geo image]347 (let [world-coords (feeler-world-coords geo image)348 normals349 (map350 (fn [triangle]351 (.calculateNormal triangle)352 (.clone (.getNormal triangle)))353 (map ->triangle (triangles geo)))]355 (mapcat (fn [origins normal]356 (map #(.add % normal) origins))357 world-coords normals)))359 (defn touch-topology360 "touch-topology? is not a function."361 [#^Geometry geo image]362 (collapse (reduce concat (feeler-pixel-coords geo image))))363 #+end_src364 * Simulated Touch366 =(touch-kernel)= generates functions to be called from within a367 simulation that perform the necessary physics collisions to collect368 tactile data, and =(touch!)= recursively applies it to every node in369 the creature.371 #+name: kernel372 #+begin_src clojure373 (in-ns 'cortex.touch)375 (defn set-ray [#^Ray ray #^Matrix4f transform376 #^Vector3f origin #^Vector3f tip]377 ;; Doing everything locally recduces garbage collection by enough to378 ;; be worth it.379 (.mult transform origin (.getOrigin ray))381 (.mult transform tip (.getDirection ray))382 (.subtractLocal (.getDirection ray) (.getOrigin ray)))384 (defn touch-kernel385 "Constructs a function which will return tactile sensory data from386 'geo when called from inside a running simulation"387 [#^Geometry geo]388 (if-let389 [profile (tactile-sensor-profile geo)]390 (let [ray-reference-origins (feeler-origins geo profile)391 ray-reference-tips (feeler-tips geo profile)392 ray-length (tactile-scale geo)393 current-rays (map (fn [_] (Ray.)) ray-reference-origins)394 topology (touch-topology geo profile)]395 (dorun (map #(.setLimit % ray-length) current-rays))396 (fn [node]397 (let [transform (.getWorldMatrix geo)]398 (dorun399 (map (fn [ray ref-origin ref-tip]400 (set-ray ray transform ref-origin ref-tip))401 current-rays ray-reference-origins402 ray-reference-tips))403 (vector404 topology405 (vec406 (for [ray current-rays]407 (do408 (let [results (CollisionResults.)]409 (.collideWith node ray results)410 (let [touch-objects411 (filter #(not (= geo (.getGeometry %)))412 results)]413 [(if (empty? touch-objects)414 (.getLimit ray)415 (.getDistance (first touch-objects)))416 (.getLimit ray)])))))))))))418 (defn touch!419 "Endow the creature with the sense of touch. Returns a sequence of420 functions, one for each body part with a tactile-sensor-proile,421 each of which when called returns sensory data for that body part."422 [#^Node creature]423 (filter424 (comp not nil?)425 (map touch-kernel426 (filter #(isa? (class %) Geometry)427 (node-seq creature)))))428 #+end_src430 * Visualizing Touch432 #+name: visualization433 #+begin_src clojure434 (in-ns 'cortex.touch)436 (defn touch->gray437 "Convert a pair of [distance, max-distance] into a grayscale pixel."438 [distance max-distance]439 (gray (- 255 (rem (int (* 255 (/ distance max-distance))) 256))))441 (defn view-touch442 "Creates a function which accepts a list of touch sensor-data and443 displays each element to the screen."444 []445 (view-sense446 (fn [[coords sensor-data]]447 (let [image (points->image coords)]448 (dorun449 (for [i (range (count coords))]450 (.setRGB image ((coords i) 0) ((coords i) 1)451 (apply touch->gray (sensor-data i))))) image))))452 #+end_src453 * Adding Touch to the Worm455 #+name: test-touch456 #+begin_src clojure457 (ns cortex.test.touch458 (:use (cortex world util sense body touch))459 (:use cortex.test.body))461 (cortex.import/mega-import-jme3)463 (defn test-touch []464 (let [the-worm (doto (worm) (body!))465 touch (touch! the-worm)466 touch-display (view-touch)]467 (world (nodify [the-worm (floor)])468 standard-debug-controls470 (fn [world]471 (speed-up world)472 (light-up-everything world))474 (fn [world tpf]475 (touch-display476 (map #(% (.getRootNode world)) touch))))))477 #+end_src479 * Headers481 #+name: touch-header482 #+begin_src clojure483 (ns cortex.touch484 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry485 to be outfitted with touch sensors with density determined by a UV486 image. In this way a Geometry can know what parts of itself are487 touching nearby objects. Reads specially prepared blender files to488 construct this sense automatically."489 {:author "Robert McIntyre"}490 (:use (cortex world util sense))491 (:use clojure.contrib.def)492 (:import (com.jme3.scene Geometry Node Mesh))493 (:import com.jme3.collision.CollisionResults)494 (:import com.jme3.scene.VertexBuffer$Type)495 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))496 #+end_src498 * Source Listing499 * Next502 * COMMENT Code Generation503 #+begin_src clojure :tangle ../src/cortex/touch.clj504 <<touch-header>>505 <<meta-data>>506 <<triangles-1>>507 <<triangles-2>>508 <<triangles-3>>509 <<triangles-4>>510 <<sensors>>511 <<kernel>>512 <<visualization>>513 #+end_src516 #+begin_src clojure :tangle ../src/cortex/test/touch.clj517 <<test-touch>>518 #+end_src