Mercurial > cortex
view org/touch.org @ 233:f27c9fd9134d
seperated out image generating code from touch-kernel
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sun, 12 Feb 2012 06:21:30 -0700 |
parents | b7762699eeb5 |
children | 712bd7e5b148 |
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=.55 #+name: meta-data56 #+begin_src clojure57 (defn tactile-sensor-profile58 "Return the touch-sensor distribution image in BufferedImage format,59 or nil if it does not exist."60 [#^Geometry obj]61 (if-let [image-path (meta-data obj "touch")]62 (load-image image-path)))64 (defn tactile-scale65 "Return the maximum length of a hair. All hairs are scalled between66 0.0 and this length, depending on their color. Black is 0, and67 white is maximum length, and everything in between is scalled68 linearlly. Default scale is 0.01 jMonkeyEngine units."69 [#^Geometry obj]70 (if-let [scale (meta-data obj "scale")]71 scale 0.1))72 #+end_src74 ** TODO add image showing example touch-uv map75 ** TODO add metadata display for worm77 * Skin Creation78 #+name: kernel79 #+begin_src clojure80 (in-ns 'cortex.touch)82 (defn touch-kernel83 "Returns a function which returns tactile sensory data when called84 inside a running simulation."85 [#^Geometry geo]86 (let [feeler-coords (feeler-coordinates geo)87 tris (triangles geo)88 limit (tactile-scale geo)]89 (if (empty? (touch-topology geo))90 nil91 (fn [node]92 (let [sensor-origins93 (map94 #(map (partial local-to-world geo) %)95 feeler-coords)96 triangle-normals97 (map (partial get-ray-direction geo)98 tris)99 rays100 (flatten101 (map (fn [origins norm]102 (map #(doto (Ray. % norm)103 (.setLimit limit)) origins))104 sensor-origins triangle-normals))]105 (vector106 (touch-topology geo)107 (vec108 (for [ray rays]109 (do110 (let [results (CollisionResults.)]111 (.collideWith node ray results)112 (let [touch-objects113 (filter #(not (= geo (.getGeometry %)))114 results)]115 [(if (empty? touch-objects)116 limit (.getDistance (first touch-objects)))117 limit])))))))))))119 (defn touch!120 "Endow the creature with the sense of touch. Returns a sequence of121 functions, one for each body part with a tactile-sensor-proile,122 each of which when called returns sensory data for that body part."123 [#^Node creature]124 (filter125 (comp not nil?)126 (map touch-kernel127 (filter #(isa? (class %) Geometry)128 (node-seq creature)))))129 #+end_src131 * Visualizing Touch132 #+name: visualization133 #+begin_src clojure134 (in-ns 'cortex.touch)136 (defn touch->gray137 "Convert a pair of [distance, max-distance] into a grayscale pixel"138 [distance max-distance]139 (gray140 (- 255141 (rem142 (int143 (* 255 (/ distance max-distance)))144 256))))146 (defn view-touch147 "Creates a function which accepts a list of touch sensor-data and148 displays each element to the screen."149 []150 (view-sense151 (fn152 [[coords sensor-data]]153 (let [image (points->image coords)]154 (dorun155 (for [i (range (count coords))]156 (.setRGB image ((coords i) 0) ((coords i) 1)157 (apply touch->gray (sensor-data i)))))158 image))))159 #+end_src163 * Triangle Manipulation Functions165 The rigid bodies which make up a creature have an underlying166 =Geometry=, which is a =Mesh= plus a =Material= and other important167 data involved with displaying the body.169 A =Mesh= is composed of =Triangles=, and each =Triangle= has three170 verticies which have coordinates in XYZ space and UV space.172 Here, =(triangles)= gets all the triangles which compose a mesh, and173 =(triangle-UV-coord)= returns the the UV coordinates of the verticies174 of a triangle.176 #+name: triangles-1177 #+begin_src clojure178 (defn triangles179 "Return a sequence of all the Triangles which compose a given180 Geometry."181 [#^Geometry geom]182 (let183 [mesh (.getMesh geom)184 triangles (transient [])]185 (dorun186 (for [n (range (.getTriangleCount mesh))]187 (let [tri (Triangle.)]188 (.getTriangle mesh n tri)189 ;; (.calculateNormal tri)190 ;; (.calculateCenter tri)191 (conj! triangles tri))))192 (persistent! triangles)))194 (defn mesh-triangle195 "Get the triangle specified by triangle-index from the mesh within196 bounds."197 [#^Mesh mesh triangle-index]198 (let [scratch (Triangle.)]199 (.getTriangle mesh triangle-index scratch)200 scratch))202 (defn triangle-vertex-indices203 "Get the triangle vertex indices of a given triangle from a given204 mesh."205 [#^Mesh mesh triangle-index]206 (let [indices (int-array 3)]207 (.getTriangle mesh triangle-index indices)208 (vec indices)))210 (defn vertex-UV-coord211 "Get the UV-coordinates of the vertex named by vertex-index"212 [#^Mesh mesh vertex-index]213 (let [UV-buffer214 (.getData215 (.getBuffer216 mesh217 VertexBuffer$Type/TexCoord))]218 [(.get UV-buffer (* vertex-index 2))219 (.get UV-buffer (+ 1 (* vertex-index 2)))]))221 (defn triangle-UV-coord222 "Get the UV-cooridnates of the triangle's verticies."223 [#^Mesh mesh width height triangle-index]224 (map (fn [[u v]] (vector (* width u) (* height v)))225 (map (partial vertex-UV-coord mesh)226 (triangle-vertex-indices mesh triangle-index))))227 #+end_src229 * Schrapnel Conversion Functions231 It is convienent to treat a =Triangle= as a sequence of verticies, and232 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion233 functions make this easy. If these classes implemented =Iterable= then234 this code would not be necessary. Hopefully they will in the future.236 #+name: triangles-2237 #+begin_src clojure238 (defn triangle-seq [#^Triangle tri]239 [(.get1 tri) (.get2 tri) (.get3 tri)])241 (defn vector3f-seq [#^Vector3f v]242 [(.getX v) (.getY v) (.getZ v)])244 (defn point->vector2f [[u v]]245 (Vector2f. u v))247 (defn vector2f->vector3f [v]248 (Vector3f. (.getX v) (.getY v) 0))250 (defn map-triangle [f #^Triangle tri]251 (Triangle.252 (f 0 (.get1 tri))253 (f 1 (.get2 tri))254 (f 2 (.get3 tri))))256 (defn points->triangle257 "Convert a list of points into a triangle."258 [points]259 (apply #(Triangle. %1 %2 %3)260 (map (fn [point]261 (let [point (vec point)]262 (Vector3f. (get point 0 0)263 (get point 1 0)264 (get point 2 0))))265 (take 3 points))))266 #+end_src268 * Triangle Affine Transforms270 The position of each hair is stored in a 2D image in UV271 coordinates. To place the hair in 3D space we must convert from UV272 coordinates to XYZ coordinates. Each =Triangle= has coordinates in273 both UV-space and XYZ-space, which defines a unique [[http://mathworld.wolfram.com/AffineTransformation.html ][Affine Transform]]274 for translating any coordinate within the UV triangle to the275 cooresponding coordinate in the XYZ triangle.277 #+name: triangles-3278 #+begin_src clojure279 (defn triangle->matrix4f280 "Converts the triangle into a 4x4 matrix: The first three columns281 contain the vertices of the triangle; the last contains the unit282 normal of the triangle. The bottom row is filled with 1s."283 [#^Triangle t]284 (let [mat (Matrix4f.)285 [vert-1 vert-2 vert-3]286 ((comp vec map) #(.get t %) (range 3))287 unit-normal (do (.calculateNormal t)(.getNormal t))288 vertices [vert-1 vert-2 vert-3 unit-normal]]289 (dorun290 (for [row (range 4) col (range 3)]291 (do292 (.set mat col row (.get (vertices row)col))293 (.set mat 3 row 1))))294 mat))296 (defn triangle-transformation297 "Returns the affine transformation that converts each vertex in the298 first triangle into the corresponding vertex in the second299 triangle."300 [#^Triangle tri-1 #^Triangle tri-2]301 (.mult302 (triangle->matrix4f tri-2)303 (.invert (triangle->matrix4f tri-1))))304 #+end_src306 * Triangle Boundaries308 For efficiency's sake I will divide the UV-image into small squares309 which inscribe each UV-triangle, then extract the points which lie310 inside the triangle and map them to 3D-space using311 =(triangle-transform)= above. To do this I need a function,312 =(inside-triangle?)=, which determines whether a point is inside a313 triangle in 2D UV-space.315 #+name: triangles-4316 #+begin_src clojure317 (defn convex-bounds318 "Returns the smallest square containing the given vertices, as a319 vector of integers [left top width height]."320 [uv-verts]321 (let [xs (map first uv-verts)322 ys (map second uv-verts)323 x0 (Math/floor (apply min xs))324 y0 (Math/floor (apply min ys))325 x1 (Math/ceil (apply max xs))326 y1 (Math/ceil (apply max ys))]327 [x0 y0 (- x1 x0) (- y1 y0)]))329 (defn same-side?330 "Given the points p1 and p2 and the reference point ref, is point p331 on the same side of the line that goes through p1 and p2 as ref is?"332 [p1 p2 ref p]333 (<=334 0335 (.dot336 (.cross (.subtract p2 p1) (.subtract p p1))337 (.cross (.subtract p2 p1) (.subtract ref p1)))))339 (defn inside-triangle?340 "Is the point inside the triangle?"341 {:author "Dylan Holmes"}342 [#^Triangle tri #^Vector3f p]343 (let [[vert-1 vert-2 vert-3] (triangle-seq tri)]344 (and345 (same-side? vert-1 vert-2 vert-3 p)346 (same-side? vert-2 vert-3 vert-1 p)347 (same-side? vert-3 vert-1 vert-2 p))))348 #+end_src352 * Sensor Related Functions354 These functions analyze the touch-sensor-profile image convert the355 location of each touch sensor from pixel coordinates to UV-coordinates356 and XYZ-coordinates.358 #+name: sensors359 #+begin_src clojure360 (defn sensors-in-triangle361 "Locate the touch sensors in the triangle, returning a map of their362 UV and geometry-relative coordinates."363 [image mesh tri-index]364 (let [width (.getWidth image)365 height (.getHeight image)366 UV-vertex-coords (triangle-UV-coord mesh width height tri-index)367 bounds (convex-bounds UV-vertex-coords)369 cutout-triangle (points->triangle UV-vertex-coords)370 UV-sensor-coords371 (filter (comp (partial inside-triangle? cutout-triangle)372 (fn [[u v]] (Vector3f. u v 0)))373 (white-coordinates image bounds))374 UV->geometry (triangle-transformation375 cutout-triangle376 (mesh-triangle mesh tri-index))377 geometry-sensor-coords378 (map (fn [[u v]] (.mult UV->geometry (Vector3f. u v 0)))379 UV-sensor-coords)]380 {:UV UV-sensor-coords :geometry geometry-sensor-coords}))382 (defn-memo locate-feelers383 "Search the geometry's tactile UV profile for touch sensors,384 returning their positions in geometry-relative coordinates."385 [#^Geometry geo]386 (let [mesh (.getMesh geo)387 num-triangles (.getTriangleCount mesh)]388 (if-let [image (tactile-sensor-profile geo)]389 (map390 (partial sensors-in-triangle image mesh)391 (range num-triangles))392 (repeat (.getTriangleCount mesh) {:UV nil :geometry nil}))))394 (defn-memo touch-topology395 "Return a sequence of vectors of the form [x y] describing the396 \"topology\" of the tactile sensors. Points that are close together397 in the touch-topology are generally close together in the simulation."398 [#^Gemoetry geo]399 (vec (collapse (reduce concat (map :UV (locate-feelers geo))))))401 (defn-memo feeler-coordinates402 "The location of the touch sensors in world-space coordinates."403 [#^Geometry geo]404 (vec (map :geometry (locate-feelers geo))))405 #+end_src407 * Physics Collision Objects409 The "hairs" are actually rays which extend from a point on a410 =Triangle= in the =Mesh= normal to the =Triangle's= surface.412 #+name: rays413 #+begin_src clojure414 (defn get-ray-origin415 "Return the origin which a Ray would have to have to be in the exact416 center of a particular Triangle in the Geometry in World417 Coordinates."418 [geom tri]419 (let [new (Vector3f.)]420 (.calculateCenter tri)421 (.localToWorld geom (.getCenter tri) new) new))423 (defn get-ray-direction424 "Return the direction which a Ray would have to have to be to point425 normal to the Triangle, in coordinates relative to the center of the426 Triangle."427 [geom tri]428 (let [n+c (Vector3f.)]429 (.calculateNormal tri)430 (.calculateCenter tri)431 (.localToWorld432 geom433 (.add (.getCenter tri) (.getNormal tri)) n+c)434 (.subtract n+c (get-ray-origin geom tri))))435 #+end_src439 * Headers441 #+name: touch-header442 #+begin_src clojure443 (ns cortex.touch444 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry445 to be outfitted with touch sensors with density determined by a UV446 image. In this way a Geometry can know what parts of itself are447 touching nearby objects. Reads specially prepared blender files to448 construct this sense automatically."449 {:author "Robert McIntyre"}450 (:use (cortex world util sense))451 (:use clojure.contrib.def)452 (:import (com.jme3.scene Geometry Node Mesh))453 (:import com.jme3.collision.CollisionResults)454 (:import com.jme3.scene.VertexBuffer$Type)455 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))456 #+end_src458 * Adding Touch to the Worm460 #+name: test-touch461 #+begin_src clojure462 (ns cortex.test.touch463 (:use (cortex world util sense body touch))464 (:use cortex.test.body))466 (cortex.import/mega-import-jme3)468 (defn test-touch []469 (let [the-worm (doto (worm) (body!))470 touch (touch! the-worm)471 touch-display (view-touch)]472 (world (nodify [the-worm (floor)])473 standard-debug-controls475 (fn [world]476 (light-up-everything world))478 (fn [world tpf]479 (touch-display (map #(% (.getRootNode world)) touch))))))480 #+end_src482 * Source Listing483 * Next486 * COMMENT Code Generation487 #+begin_src clojure :tangle ../src/cortex/touch.clj488 <<touch-header>>489 <<meta-data>>490 <<triangles-1>>491 <<triangles-2>>492 <<triangles-3>>493 <<triangles-4>>494 <<sensors>>495 <<rays>>496 <<kernel>>497 <<visualization>>498 #+end_src501 #+begin_src clojure :tangle ../src/cortex/test/touch.clj502 <<test-touch>>503 #+end_src