Mercurial > cortex
view org/touch.org @ 246:63da037ce1c5
added image
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sun, 12 Feb 2012 14:40:58 -0700 |
parents | 102ac596cc3f |
children | 4e220c8fb1ed |
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 which do not interact with27 the physical world. Physical objects can pass through them with no28 effect. The hairs are able to measure contact with other objects, and29 constantly report how much of their extent is covered. So, even though30 the creature's body parts do not deform, the hairs create a margin31 around those body parts which achieves a sense of touch which is a32 hybrid between a human's sense of deformation and sense from hairs.34 Implementing touch in jMonkeyEngine follows a different techinal route35 than vision and hearing. Those two senses piggybacked off36 jMonkeyEngine's 3D audio and video rendering subsystems. To simulate37 Touch, I use jMonkeyEngine's physics system to execute many small38 collision detections, one for each "hair". The placement of the39 "hairs" is determined by a UV-mapped image which shows where each hair40 should be on the 3D surface of the body.42 * Defining Touch Meta-Data in Blender44 Each geometry can have a single UV map which describes the position of45 the "hairs" which will constitute its sense of touch. This image path46 is stored under the "touch" key. The image itself is black and white,47 with black meaning a hair length of 0 (no hair is present) and white48 meaning a hair length of =scale=, which is a float stored under the49 key "scale". I call these "hairs" /feelers/.51 #+name: meta-data52 #+begin_src clojure53 (defn tactile-sensor-profile54 "Return the touch-sensor distribution image in BufferedImage format,55 or nil if it does not exist."56 [#^Geometry obj]57 (if-let [image-path (meta-data obj "touch")]58 (load-image image-path)))60 (defn tactile-scale61 "Return the maximum length of a hair. All hairs are scalled between62 0.0 and this length, depending on their color. Black is 0, and63 white is maximum length, and everything in between is scalled64 linearlly. Default scale is 0.01 jMonkeyEngine units."65 [#^Geometry obj]66 (if-let [scale (meta-data obj "scale")]67 scale 0.1))68 #+end_src70 Here is an example of a UV-map which specifies the position of touch71 sensors along the surface of the worm.73 #+attr_html: width=75574 #+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).75 [[../images/finger-UV.png]]77 * Skin Creation79 =(touch-kernel)= generates the functions which implement the sense of80 touch for a creature. These functions must do 6 things to obtain touch81 data.83 - Get the tactile profile image and scale paramaters which describe84 the layout of feelers along the object's surface.85 =(tactile-sensor-profile)=, =(tactile-scale)=87 - Find the triangles which make up the mesh in pixel-space and in88 world-space.89 =(triangles)= =(pixel-triangles)=91 - Find the coordinates of each pixel in pixel space. These92 coordinates are used to make the touch-topology.93 =(feeler-pixel-coords)=95 - Find the coordinates of each pixel in world-space. These96 coordinates are the 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.101 For both of these, =(feeler-tips)=103 - Generate some sort of topology for the sensors.104 =(touch-topology)=107 #+name: kernel108 #+begin_src clojure109 (in-ns 'cortex.touch)111 (defn set-ray [#^Ray ray #^Matrix4f transform112 #^Vector3f origin #^Vector3f tip]113 ;; Doing everything locally recduces garbage collection by enough to114 ;; be worth it.115 (.mult transform origin (.getOrigin ray))117 (.mult transform tip (.getDirection ray))118 (.subtractLocal (.getDirection ray) (.getOrigin ray)))120 (defn touch-kernel121 "Constructs a function which will return tactile sensory data from122 'geo when called from inside a running simulation"123 [#^Geometry geo]124 (if-let125 [profile (tactile-sensor-profile geo)]126 (let [ray-reference-origins (feeler-origins geo profile)127 ray-reference-tips (feeler-tips geo profile)128 ray-length (tactile-scale geo)129 current-rays (map (fn [_] (Ray.)) ray-reference-origins)130 topology (touch-topology geo profile)]131 (dorun (map #(.setLimit % ray-length) current-rays))132 (fn [node]133 (let [transform (.getWorldMatrix geo)]134 (dorun135 (map (fn [ray ref-origin ref-tip]136 (set-ray ray transform ref-origin ref-tip))137 current-rays ray-reference-origins138 ray-reference-tips))139 (vector140 topology141 (vec142 (for [ray current-rays]143 (do144 (let [results (CollisionResults.)]145 (.collideWith node ray results)146 (let [touch-objects147 (filter #(not (= geo (.getGeometry %)))148 results)]149 [(if (empty? touch-objects)150 (.getLimit ray)151 (.getDistance (first touch-objects)))152 (.getLimit ray)])))))))))))154 (defn touch!155 "Endow the creature with the sense of touch. Returns a sequence of156 functions, one for each body part with a tactile-sensor-proile,157 each of which when called returns sensory data for that body part."158 [#^Node creature]159 (filter160 (comp not nil?)161 (map touch-kernel162 (filter #(isa? (class %) Geometry)163 (node-seq creature)))))164 #+end_src166 * Sensor Related Functions168 These functions analyze the touch-sensor-profile image convert the169 location of each touch sensor from pixel coordinates to UV-coordinates170 and XYZ-coordinates.172 #+name: sensors173 #+begin_src clojure174 (in-ns 'cortex.touch)176 (defn feeler-pixel-coords177 "Returns the coordinates of the feelers in pixel space in lists, one178 list for each triangle, ordered in the same way as (triangles) and179 (pixel-triangles)."180 [#^Geometry geo image]181 (map182 (fn [pixel-triangle]183 (filter184 (fn [coord]185 (inside-triangle? (->triangle pixel-triangle)186 (->vector3f coord)))187 (white-coordinates image (convex-bounds pixel-triangle))))188 (pixel-triangles geo image)))190 (defn feeler-world-coords [#^Geometry geo image]191 (let [transforms192 (map #(triangles->affine-transform193 (->triangle %1) (->triangle %2))194 (pixel-triangles geo image)195 (triangles geo))]196 (map (fn [transform coords]197 (map #(.mult transform (->vector3f %)) coords))198 transforms (feeler-pixel-coords geo image))))200 (defn feeler-origins [#^Geometry geo image]201 (reduce concat (feeler-world-coords geo image)))203 (defn feeler-tips [#^Geometry geo image]204 (let [world-coords (feeler-world-coords geo image)205 normals206 (map207 (fn [triangle]208 (.calculateNormal triangle)209 (.clone (.getNormal triangle)))210 (map ->triangle (triangles geo)))]212 (mapcat (fn [origins normal]213 (map #(.add % normal) origins))214 world-coords normals)))216 (defn touch-topology [#^Geometry geo image]217 (collapse (reduce concat (feeler-pixel-coords geo image))))218 #+end_src220 * Visualizing Touch221 #+name: visualization222 #+begin_src clojure223 (in-ns 'cortex.touch)225 (defn touch->gray226 "Convert a pair of [distance, max-distance] into a grayscale pixel."227 [distance max-distance]228 (gray (- 255 (rem (int (* 255 (/ distance max-distance))) 256))))230 (defn view-touch231 "Creates a function which accepts a list of touch sensor-data and232 displays each element to the screen."233 []234 (view-sense235 (fn [[coords sensor-data]]236 (let [image (points->image coords)]237 (dorun238 (for [i (range (count coords))]239 (.setRGB image ((coords i) 0) ((coords i) 1)240 (apply touch->gray (sensor-data i))))) image))))241 #+end_src245 * Triangle Manipulation Functions247 The rigid bodies which make up a creature have an underlying248 =Geometry=, which is a =Mesh= plus a =Material= and other important249 data involved with displaying the body.251 A =Mesh= is composed of =Triangles=, and each =Triangle= has three252 verticies which have coordinates in XYZ space and UV space.254 Here, =(triangles)= gets all the triangles which compose a mesh, and255 =(triangle-UV-coord)= returns the the UV coordinates of the verticies256 of a triangle.258 #+name: triangles-1259 #+begin_src clojure260 (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 ->vector3f271 ([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 triangle279 "Get the triangle specified by triangle-index from the mesh."280 [#^Geometry geo triangle-index]281 (triangle-seq282 (let [scratch (Triangle.)]283 (.getTriangle (.getMesh geo) triangle-index scratch) scratch)))285 (defn triangles286 "Return a sequence of all the Triangles which compose a given287 Geometry."288 [#^Geometry geo]289 (map (partial triangle geo) (range (.getTriangleCount (.getMesh geo)))))291 (defn triangle-vertex-indices292 "Get the triangle vertex indices of a given triangle from a given293 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-coord300 "Get the UV-coordinates of the vertex named by vertex-index"301 [#^Mesh mesh vertex-index]302 (let [UV-buffer303 (.getData304 (.getBuffer305 mesh306 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_src326 * Triangle Affine Transforms328 The position of each hair is stored in a 2D image in UV329 coordinates. To place the hair in 3D space we must convert from UV330 coordinates to XYZ coordinates. Each =Triangle= has coordinates in331 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 the333 cooresponding coordinate in the XYZ triangle.335 #+name: triangles-3336 #+begin_src clojure337 (in-ns 'cortex.touch)339 (defn triangle->matrix4f340 "Converts the triangle into a 4x4 matrix: The first three columns341 contain the vertices of the triangle; the last contains the unit342 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 (dorun350 (for [row (range 4) col (range 3)]351 (do352 (.set mat col row (.get (vertices row)col))353 (.set mat 3 row 1)))) mat))355 (defn triangles->affine-transform356 "Returns the affine transformation that converts each vertex in the357 first triangle into the corresponding vertex in the second358 triangle."359 [#^Triangle tri-1 #^Triangle tri-2]360 (.mult361 (triangle->matrix4f tri-2)362 (.invert (triangle->matrix4f tri-1))))363 #+end_src366 * Schrapnel Conversion Functions368 It is convienent to treat a =Triangle= as a sequence of verticies, and369 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion370 functions make this easy. If these classes implemented =Iterable= then371 this code would not be necessary. Hopefully they will in the future.373 * Triangle Boundaries375 For efficiency's sake I will divide the UV-image into small squares376 which inscribe each UV-triangle, then extract the points which lie377 inside the triangle and map them to 3D-space using378 =(triangle-transform)= above. To do this I need a function,379 =(inside-triangle?)=, which determines whether a point is inside a380 triangle in 2D UV-space.382 #+name: triangles-4383 #+begin_src clojure384 (defn convex-bounds385 "Returns the smallest square containing the given vertices, as a386 vector of integers [left top width height]."387 [verts]388 (let [xs (map first verts)389 ys (map second verts)390 x0 (Math/floor (apply min xs))391 y0 (Math/floor (apply min ys))392 x1 (Math/ceil (apply max xs))393 y1 (Math/ceil (apply max ys))]394 [x0 y0 (- x1 x0) (- y1 y0)]))396 (defn same-side?397 "Given the points p1 and p2 and the reference point ref, is point p398 on the same side of the line that goes through p1 and p2 as ref is?"399 [p1 p2 ref p]400 (<=401 0402 (.dot403 (.cross (.subtract p2 p1) (.subtract p p1))404 (.cross (.subtract p2 p1) (.subtract ref p1)))))406 (defn inside-triangle?407 "Is the point inside the triangle?"408 {:author "Dylan Holmes"}409 [#^Triangle tri #^Vector3f p]410 (let [[vert-1 vert-2 vert-3] [(.get1 tri) (.get2 tri) (.get3 tri)]]411 (and412 (same-side? vert-1 vert-2 vert-3 p)413 (same-side? vert-2 vert-3 vert-1 p)414 (same-side? vert-3 vert-1 vert-2 p))))415 #+end_src417 * Physics Collision Objects419 The "hairs" are actually =Rays= which extend from a point on a420 =Triangle= in the =Mesh= normal to the =Triangle's= surface.422 * Headers424 #+name: touch-header425 #+begin_src clojure426 (ns cortex.touch427 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry428 to be outfitted with touch sensors with density determined by a UV429 image. In this way a Geometry can know what parts of itself are430 touching nearby objects. Reads specially prepared blender files to431 construct this sense automatically."432 {:author "Robert McIntyre"}433 (:use (cortex world util sense))434 (:use clojure.contrib.def)435 (:import (com.jme3.scene Geometry Node Mesh))436 (:import com.jme3.collision.CollisionResults)437 (:import com.jme3.scene.VertexBuffer$Type)438 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))439 #+end_src441 * Adding Touch to the Worm443 #+name: test-touch444 #+begin_src clojure445 (ns cortex.test.touch446 (:use (cortex world util sense body touch))447 (:use cortex.test.body))449 (cortex.import/mega-import-jme3)451 (defn test-touch []452 (let [the-worm (doto (worm) (body!))453 touch (touch! the-worm)454 touch-display (view-touch)]455 (world (nodify [the-worm (floor)])456 standard-debug-controls458 (fn [world]459 (speed-up world)460 (light-up-everything world))462 (fn [world tpf]463 (touch-display464 (map #(% (.getRootNode world)) touch))))))465 #+end_src466 * Source Listing467 * Next470 * COMMENT Code Generation471 #+begin_src clojure :tangle ../src/cortex/touch.clj472 <<touch-header>>473 <<meta-data>>474 <<triangles-1>>475 <<triangles-3>>476 <<triangles-4>>477 <<sensors>>478 <<kernel>>479 <<visualization>>480 #+end_src483 #+begin_src clojure :tangle ../src/cortex/test/touch.clj484 <<test-touch>>485 #+end_src