Mercurial > cortex
view org/touch.org @ 243:f33fec68f775
touch has been restored, with some very slight speed improvements, and now with much less code
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sun, 12 Feb 2012 14:14:57 -0700 |
parents | a7f26a074071 |
children | f23217324f72 |
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.org11 * Touch13 Touch is critical to navigation and spatial reasoning and as such I14 need a simulated version of it to give to my AI creatures.16 However, touch in my virtual can not exactly correspond to human touch17 because my creatures are made out of completely rigid segments that18 don't deform like human skin.20 Human skin has a wide array of touch sensors, each of which speciliaze21 in detecting different vibrational modes and pressures. These sensors22 can integrate a vast expanse of skin (i.e. your entire palm), or a23 tiny patch of skin at the tip of your finger. The hairs of the skin24 help detect objects before they even come into contact with the skin25 proper.27 Instead of measuring deformation or vibration, I surround each rigid28 part with a plenitude of hair-like objects which do not interact with29 the physical world. Physical objects can pass through them with no30 effect. The hairs are able to measure contact with other objects, and31 constantly report how much of their extent is covered. So, even though32 the creature's body parts do not deform, the hairs create a margin33 around those body parts which achieves a sense of touch which is a34 hybrid between a human's sense of deformation and sense from hairs.36 Implementing touch in jMonkeyEngine follows a different techinal route37 than vision and hearing. Those two senses piggybacked off38 jMonkeyEngine's 3D audio and video rendering subsystems. To simulate39 Touch, I use jMonkeyEngine's physics system to execute many small40 collision detections, one for each "hair". The placement of the41 "hairs" is determined by a UV-mapped image which shows where each hair42 should be on the 3D surface of the body.45 * Defining Touch Meta-Data in Blender47 Each geometry can have a single UV map which describes the position48 and length of the "hairs" which will constitute its sense of49 touch. This image path is stored under the "touch" key. The image50 itself is grayscale, with black meaning a hair length of 0 (no hair is51 present) and white meaning a hair length of =scale=, which is a float52 stored under the key "scale". If the pixel is gray then the resultant53 hair length is linearly interpolated between 0 and =scale=. I call54 these "hairs" /feelers/.56 #+name: meta-data57 #+begin_src clojure58 (defn tactile-sensor-profile59 "Return the touch-sensor distribution image in BufferedImage format,60 or nil if it does not exist."61 [#^Geometry obj]62 (if-let [image-path (meta-data obj "touch")]63 (load-image image-path)))65 (defn tactile-scale66 "Return the maximum length of a hair. All hairs are scalled between67 0.0 and this length, depending on their color. Black is 0, and68 white is maximum length, and everything in between is scalled69 linearlly. Default scale is 0.01 jMonkeyEngine units."70 [#^Geometry obj]71 (if-let [scale (meta-data obj "scale")]72 scale 0.1))73 #+end_src75 ** TODO add image showing example touch-uv map76 ** TODO add metadata display for worm79 * Skin Creation80 * TODO get the actual lengths for each feeler83 =(touch-kernel)= generates the functions which implement the sense of84 touch for a creature. These functions must do 6 things to obtain touch85 data.87 - Get the tactile profile image and scale paramaters which describe88 the layout of feelers along the object's surface.89 =(tactile-sensor-profile)=, =(tactile-scale)=91 - Get the lengths of each feeler by analyzing the color of the92 pixels in the tactile profile image.93 NOT IMPLEMENTED YET95 - Find the triangles which make up the mesh in pixel-space and in96 world-space.97 =(triangles)= =(pixel-triangles)=99 - Find the coordinates of each pixel in pixel space. These100 coordinates are used to make the touch-topology.101 =(feeler-pixel-coords)=103 - Find the coordinates of each pixel in world-space. These104 coordinates are the origins of the feelers. =(feeler-origins)=106 - Calculate the normals of the triangles in world space, and add107 them to each of the origins of the feelers. These are the108 normalized coordinates of the tips of the feelers.109 For both of these, =(feeler-tips)=111 - Generate some sort of topology for the sensors.112 =(touch-topology)=115 #+name: kernel116 #+begin_src clojure117 (in-ns 'cortex.touch)119 (declare touch-topology feelers set-ray)121 (defn set-ray [#^Ray ray #^Matrix4f transform #^Vector3f origin122 #^Vector3f tip length]123 ;; Doing everything locally recduces garbage collection by enough to124 ;; be worth it.125 (.mult transform origin (.getOrigin ray))127 (.mult transform tip (.getDirection ray))128 (.subtractLocal (.getDirection ray) (.getOrigin ray))129 (.setLimit ray length))131 (defn touch-kernel132 "Constructs a function which will return tactile sensory data from133 'geo when called from inside a running simulation"134 [#^Geometry geo]135 (if-let136 [profile (tactile-sensor-profile geo)]137 (let [ray-reference-origins (feeler-origins geo profile)138 ray-reference-tips (feeler-tips geo profile)139 ray-lengths (repeat 9000 0.1)140 current-rays (map (fn [_] (Ray.)) ray-reference-origins)141 topology (touch-topology geo profile)]142 (fn [node]143 (let [transform (.getWorldMatrix geo)]144 (dorun145 (map (fn [ray ref-origin ref-tip length]146 (set-ray ray transform ref-origin ref-tip length))147 current-rays ray-reference-origins148 ray-reference-tips ray-lengths))149 (vector150 topology151 (vec152 (for [ray current-rays]153 (do154 (let [results (CollisionResults.)]155 (.collideWith node ray results)156 (let [touch-objects157 (filter #(not (= geo (.getGeometry %)))158 results)]159 [(if (empty? touch-objects)160 (.getLimit ray)161 (.getDistance (first touch-objects)))162 (.getLimit ray)])))))))))))164 (defn touch!165 "Endow the creature with the sense of touch. Returns a sequence of166 functions, one for each body part with a tactile-sensor-proile,167 each of which when called returns sensory data for that body part."168 [#^Node creature]169 (filter170 (comp not nil?)171 (map touch-kernel172 (filter #(isa? (class %) Geometry)173 (node-seq creature)))))174 #+end_src176 #+results: kernel177 : #'cortex.touch/touch!179 * Sensor Related Functions181 These functions analyze the touch-sensor-profile image convert the182 location of each touch sensor from pixel coordinates to UV-coordinates183 and XYZ-coordinates.185 #+name: sensors186 #+begin_src clojure187 (in-ns 'cortex.touch)189 (defn feeler-pixel-coords190 "Returns the coordinates of the feelers in pixel space in lists, one191 list for each triangle, ordered in the same way as (triangles) and192 (pixel-triangles)."193 [#^Geometry geo image]194 (map195 (fn [pixel-triangle]196 (filter197 (fn [coord]198 (inside-triangle? (->triangle pixel-triangle)199 (->vector3f coord)))200 (white-coordinates image (convex-bounds pixel-triangle))))201 (pixel-triangles geo image)))203 (defn feeler-world-coords [#^Geometry geo image]204 (let [transforms205 (map #(triangles->affine-transform206 (->triangle %1) (->triangle %2))207 (pixel-triangles geo image)208 (triangles geo))]209 (map (fn [transform coords]210 (map #(.mult transform (->vector3f %)) coords))211 transforms (feeler-pixel-coords geo image))))213 (defn feeler-origins [#^Geometry geo image]214 (reduce concat (feeler-world-coords geo image)))216 (defn feeler-tips [#^Geometry geo image]217 (let [world-coords (feeler-world-coords geo image)218 normals219 (map220 (fn [triangle]221 (.calculateNormal triangle)222 (.clone (.getNormal triangle)))223 (map ->triangle (triangles geo)))]225 (mapcat (fn [origins normal]226 (map #(.add % normal) origins))227 world-coords normals)))230 (defn touch-topology [#^Geometry geo image]231 (collapse (reduce concat (feeler-pixel-coords geo image))))232 #+end_src234 * Visualizing Touch235 #+name: visualization236 #+begin_src clojure237 (in-ns 'cortex.touch)239 (defn touch->gray240 "Convert a pair of [distance, max-distance] into a grayscale pixel"241 [distance max-distance]242 (gray243 (- 255244 (rem245 (int246 (* 255 (/ distance max-distance)))247 256))))249 (defn view-touch250 "Creates a function which accepts a list of touch sensor-data and251 displays each element to the screen."252 []253 (view-sense254 (fn255 [[coords sensor-data]]256 (let [image (points->image coords)]257 (dorun258 (for [i (range (count coords))]259 (.setRGB image ((coords i) 0) ((coords i) 1)260 (apply touch->gray (sensor-data i)))))261 image))))262 #+end_src266 * Triangle Manipulation Functions268 The rigid bodies which make up a creature have an underlying269 =Geometry=, which is a =Mesh= plus a =Material= and other important270 data involved with displaying the body.272 A =Mesh= is composed of =Triangles=, and each =Triangle= has three273 verticies which have coordinates in XYZ space and UV space.275 Here, =(triangles)= gets all the triangles which compose a mesh, and276 =(triangle-UV-coord)= returns the the UV coordinates of the verticies277 of a triangle.279 #+name: triangles-1280 #+begin_src clojure281 (in-ns 'cortex.touch)283 (defn vector3f-seq [#^Vector3f v]284 [(.getX v) (.getY v) (.getZ v)])286 (defn triangle-seq [#^Triangle tri]287 [(vector3f-seq (.get1 tri))288 (vector3f-seq (.get2 tri))289 (vector3f-seq (.get3 tri))])291 (defn ->vector3f292 ([coords] (Vector3f. (nth coords 0 0)293 (nth coords 1 0)294 (nth coords 2 0))))296 (defn ->triangle [points]297 (apply #(Triangle. %1 %2 %3) (map ->vector3f points)))299 (defn triangle300 "Get the triangle specified by triangle-index from the mesh within301 bounds."302 [#^Geometry geo triangle-index]303 (triangle-seq304 (let [scratch (Triangle.)]305 (.getTriangle (.getMesh geo) triangle-index scratch) scratch)))307 (defn triangles308 "Return a sequence of all the Triangles which compose a given309 Geometry."310 [#^Geometry geo]311 (map (partial triangle geo) (range (.getTriangleCount (.getMesh geo)))))313 (defn triangle-vertex-indices314 "Get the triangle vertex indices of a given triangle from a given315 mesh."316 [#^Mesh mesh triangle-index]317 (let [indices (int-array 3)]318 (.getTriangle mesh triangle-index indices)319 (vec indices)))321 (defn vertex-UV-coord322 "Get the UV-coordinates of the vertex named by vertex-index"323 [#^Mesh mesh vertex-index]324 (let [UV-buffer325 (.getData326 (.getBuffer327 mesh328 VertexBuffer$Type/TexCoord))]329 [(.get UV-buffer (* vertex-index 2))330 (.get UV-buffer (+ 1 (* vertex-index 2)))]))332 (defn pixel-triangle [#^Geometry geo image index]333 (let [mesh (.getMesh geo)334 width (.getWidth image)335 height (.getHeight image)]336 (vec (map (fn [[u v]] (vector (* width u) (* height v)))337 (map (partial vertex-UV-coord mesh)338 (triangle-vertex-indices mesh index))))))340 (defn pixel-triangles [#^Geometry geo image]341 (let [height (.getHeight image)342 width (.getWidth image)]343 (map (partial pixel-triangle geo image)344 (range (.getTriangleCount (.getMesh geo))))))346 #+end_src348 * Triangle Affine Transforms350 The position of each hair is stored in a 2D image in UV351 coordinates. To place the hair in 3D space we must convert from UV352 coordinates to XYZ coordinates. Each =Triangle= has coordinates in353 both UV-space and XYZ-space, which defines a unique [[http://mathworld.wolfram.com/AffineTransformation.html ][Affine Transform]]354 for translating any coordinate within the UV triangle to the355 cooresponding coordinate in the XYZ triangle.357 #+name: triangles-3358 #+begin_src clojure359 (in-ns 'cortex.touch)361 (defn triangle->matrix4f362 "Converts the triangle into a 4x4 matrix: The first three columns363 contain the vertices of the triangle; the last contains the unit364 normal of the triangle. The bottom row is filled with 1s."365 [#^Triangle t]366 (let [mat (Matrix4f.)367 [vert-1 vert-2 vert-3]368 ((comp vec map) #(.get t %) (range 3))369 unit-normal (do (.calculateNormal t)(.getNormal t))370 vertices [vert-1 vert-2 vert-3 unit-normal]]371 (dorun372 (for [row (range 4) col (range 3)]373 (do374 (.set mat col row (.get (vertices row)col))375 (.set mat 3 row 1))))376 mat))378 (defn triangles->affine-transform379 "Returns the affine transformation that converts each vertex in the380 first triangle into the corresponding vertex in the second381 triangle."382 [#^Triangle tri-1 #^Triangle tri-2]383 (.mult384 (triangle->matrix4f tri-2)385 (.invert (triangle->matrix4f tri-1))))386 #+end_src389 * Schrapnel Conversion Functions391 It is convienent to treat a =Triangle= as a sequence of verticies, and392 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion393 functions make this easy. If these classes implemented =Iterable= then394 this code would not be necessary. Hopefully they will in the future.397 * Triangle Boundaries399 For efficiency's sake I will divide the UV-image into small squares400 which inscribe each UV-triangle, then extract the points which lie401 inside the triangle and map them to 3D-space using402 =(triangle-transform)= above. To do this I need a function,403 =(inside-triangle?)=, which determines whether a point is inside a404 triangle in 2D UV-space.406 #+name: triangles-4407 #+begin_src clojure408 (defn convex-bounds409 "Returns the smallest square containing the given vertices, as a410 vector of integers [left top width height]."411 [verts]412 (let [xs (map first verts)413 ys (map second verts)414 x0 (Math/floor (apply min xs))415 y0 (Math/floor (apply min ys))416 x1 (Math/ceil (apply max xs))417 y1 (Math/ceil (apply max ys))]418 [x0 y0 (- x1 x0) (- y1 y0)]))420 (defn same-side?421 "Given the points p1 and p2 and the reference point ref, is point p422 on the same side of the line that goes through p1 and p2 as ref is?"423 [p1 p2 ref p]424 (<=425 0426 (.dot427 (.cross (.subtract p2 p1) (.subtract p p1))428 (.cross (.subtract p2 p1) (.subtract ref p1)))))430 (defn inside-triangle?431 "Is the point inside the triangle?"432 {:author "Dylan Holmes"}433 [#^Triangle tri #^Vector3f p]434 (let [[vert-1 vert-2 vert-3] [(.get1 tri) (.get2 tri) (.get3 tri)]]435 (and436 (same-side? vert-1 vert-2 vert-3 p)437 (same-side? vert-2 vert-3 vert-1 p)438 (same-side? vert-3 vert-1 vert-2 p))))439 #+end_src441 * Physics Collision Objects443 The "hairs" are actually =Rays= which extend from a point on a444 =Triangle= in the =Mesh= normal to the =Triangle's= surface.446 * Headers448 #+name: touch-header449 #+begin_src clojure450 (ns cortex.touch451 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry452 to be outfitted with touch sensors with density determined by a UV453 image. In this way a Geometry can know what parts of itself are454 touching nearby objects. Reads specially prepared blender files to455 construct this sense automatically."456 {:author "Robert McIntyre"}457 (:use (cortex world util sense))458 (:use clojure.contrib.def)459 (:import (com.jme3.scene Geometry Node Mesh))460 (:import com.jme3.collision.CollisionResults)461 (:import com.jme3.scene.VertexBuffer$Type)462 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))463 #+end_src465 * Adding Touch to the Worm467 #+name: test-touch468 #+begin_src clojure469 (ns cortex.test.touch470 (:use (cortex world util sense body touch))471 (:use cortex.test.body))473 (cortex.import/mega-import-jme3)475 (defn test-touch []476 (let [the-worm (doto (worm) (body!))477 touch (touch! the-worm)478 touch-display (view-touch)]479 (world (nodify [the-worm (floor)])480 standard-debug-controls482 (fn [world]483 (light-up-everything world))485 (fn [world tpf]488 (dorun (map #(% (.getRootNode world)) touch))491 ))))492 #+end_src493 * Source Listing494 * Next497 * COMMENT Code Generation498 #+begin_src clojure :tangle ../src/cortex/touch.clj499 <<touch-header>>500 <<meta-data>>501 <<triangles-1>>502 <<triangles-3>>503 <<triangles-4>>504 <<sensors>>505 <<kernel>>506 <<visualization>>507 #+end_src510 #+begin_src clojure :tangle ../src/cortex/test/touch.clj511 <<test-touch>>512 #+end_src