Mercurial > cortex
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 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 #+begin_src clojure56 (defn tactile-sensor-profile57 "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_src65 ** TODO add image showing example touch-uv map66 ** TODO add metadata display for worm68 * Triangle Manipulation Functions70 The rigid bodies which make up a creature have an underlying71 =Geometry=, which is a =Mesh= plus a =Material= and other important72 data involved with displaying the body.74 A =Mesh= is composed of =Triangles=, and each =Triangle= has three75 verticies which have coordinates in XYZ space and UV space.77 Here, =(triangles)= gets all the triangles which compose a mesh, and78 =(triangle-UV-coord)= returns the the UV coordinates of the verticies79 of a triangle.81 #+begin_src clojure82 (defn triangles83 "Return a sequence of all the Triangles which compose a given84 Geometry."85 [#^Geometry geom]86 (let87 [mesh (.getMesh geom)88 triangles (transient [])]89 (dorun90 (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-triangle99 "Get the triangle specified by triangle-index from the mesh within100 bounds."101 [#^Mesh mesh triangle-index]102 (let [scratch (Triangle.)]103 (.getTriangle mesh triangle-index scratch)104 scratch))106 (defn triangle-vertex-indices107 "Get the triangle vertex indices of a given triangle from a given108 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-coord115 "Get the UV-coordinates of the vertex named by vertex-index"116 [#^Mesh mesh vertex-index]117 (let [UV-buffer118 (.getData119 (.getBuffer120 mesh121 VertexBuffer$Type/TexCoord))]122 [(.get UV-buffer (* vertex-index 2))123 (.get UV-buffer (+ 1 (* vertex-index 2)))]))125 (defn triangle-UV-coord126 "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_src133 * Schrapnel Conversion Functions135 It is convienent to treat a =Triangle= as a sequence of verticies, and136 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion137 functions make this easy. If these classes implemented =Iterable= then138 this code would not be necessary. Hopefully they will in the future.140 #+begin_src clojure141 (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->triangle160 "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_src171 * Triangle Affine Transforms173 The position of each hair is stored in a 2D image in UV174 coordinates. To place the hair in 3D space we must convert from UV175 coordinates to XYZ coordinates. Each =Triangle= has coordinates in176 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 the178 cooresponding coordinate in the XYZ triangle.180 #+begin_src clojure181 (defn triangle->matrix4f182 "Converts the triangle into a 4x4 matrix: The first three columns183 contain the vertices of the triangle; the last contains the unit184 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 (dorun192 (for [row (range 4) col (range 3)]193 (do194 (.set mat col row (.get (vertices row)col))195 (.set mat 3 row 1))))196 mat))198 (defn triangle-transformation199 "Returns the affine transformation that converts each vertex in the200 first triangle into the corresponding vertex in the second201 triangle."202 [#^Triangle tri-1 #^Triangle tri-2]203 (.mult204 (triangle->matrix4f tri-2)205 (.invert (triangle->matrix4f tri-1))))206 #+end_src208 * Triangle Boundaries210 For efficiency's sake I will divide the UV-image into small squares211 which inscribe each UV-triangle, then extract the points which lie212 inside the triangle and map them to 3D-space using213 =(triangle-transform)= above. To do this I need a function,214 =(inside-triangle?)=, which determines whether a point is inside a215 triangle in 2D UV-space.217 #+begin_src clojure218 (defn convex-bounds219 "Returns the smallest square containing the given vertices, as a220 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 p232 on the same side of the line that goes through p1 and p2 as ref is?"233 [p1 p2 ref p]234 (<=235 0236 (.dot237 (.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 (and246 (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_src253 * Sensor Related Functions255 These functions analyze the touch-sensor-profile image convert the256 location of each touch sensor from pixel coordinates to UV-coordinates257 and XYZ-coordinates.259 #+begin_src clojure260 (defn sensors-in-triangle261 "Locate the touch sensors in the triangle, returning a map of their262 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-coords271 (filter (comp (partial inside-triangle? cutout-triangle)272 (fn [[u v]] (Vector3f. u v 0)))273 (white-coordinates image bounds))274 UV->geometry (triangle-transformation275 cutout-triangle276 (mesh-triangle mesh tri-index))277 geometry-sensor-coords278 (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-feelers283 "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 (map290 (partial sensors-in-triangle image mesh)291 (range num-triangles))292 (repeat (.getTriangleCount mesh) {:UV nil :geometry nil}))))294 (defn-memo touch-topology295 "Return a sequence of vectors of the form [x y] describing the296 \"topology\" of the tactile sensors. Points that are close together297 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-coordinates302 "The location of the touch sensors in world-space coordinates."303 [#^Geometry geo]304 (vec (map :geometry (locate-feelers geo))))305 #+end_src307 * Physics Collision Objects309 The "hairs" are actually rays which extend from a point on a310 =Triangle= in the =Mesh= normal to the =Triangle's= surface.312 #+begin_src clojure313 (defn get-ray-origin314 "Return the origin which a Ray would have to have to be in the exact315 center of a particular Triangle in the Geometry in World316 Coordinates."317 [geom tri]318 (let [new (Vector3f.)]319 (.calculateCenter tri)320 (.localToWorld geom (.getCenter tri) new) new))322 (defn get-ray-direction323 "Return the direction which a Ray would have to have to be to point324 normal to the Triangle, in coordinates relative to the center of the325 Triangle."326 [geom tri]327 (let [n+c (Vector3f.)]328 (.calculateNormal tri)329 (.calculateCenter tri)330 (.localToWorld331 geom332 (.add (.getCenter tri) (.getNormal tri)) n+c)333 (.subtract n+c (get-ray-origin geom tri))))334 #+end_src337 * Skin Creation339 #+begin_src clojure340 (defn touch-fn341 "Returns a function which returns tactile sensory data when called342 inside a running simulation."343 [#^Geometry geo]344 (let [feeler-coords (feeler-coordinates geo)345 tris (triangles geo)346 limit 0.1347 ;;results (CollisionResults.)348 ]349 (if (empty? (touch-topology geo))350 nil351 (fn [node]352 (let [sensor-origins353 (map354 #(map (partial local-to-world geo) %)355 feeler-coords)356 triangle-normals357 (map (partial get-ray-direction geo)358 tris)359 rays360 (flatten361 (map (fn [origins norm]362 (map #(doto (Ray. % norm)363 (.setLimit limit)) origins))364 sensor-origins triangle-normals))]365 (vector366 (touch-topology geo)367 (vec368 (for [ray rays]369 (do370 (let [results (CollisionResults.)]371 (.collideWith node ray results)372 (let [touch-objects373 (filter #(not (= geo (.getGeometry %)))374 results)]375 (- 255376 (if (empty? touch-objects) 255377 (rem378 (int379 (* 255 (/ (.getDistance380 (first touch-objects)) limit)))381 256))))))))))))))383 (defn touch!384 "Endow the creature with the sense of touch. Returns a sequence of385 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 (filter389 (comp not nil?)390 (map touch-fn391 (filter #(isa? (class %) Geometry)392 (node-seq creature)))))393 #+end_src395 * Visualizing Touch397 #+begin_src clojure398 (defn view-touch399 "Creates a function which accepts a list of touch sensor-data and400 displays each element to the screen."401 []402 (view-sense403 (fn404 [[coords sensor-data]]405 (let [image (points->image coords)]406 (dorun407 (for [i (range (count coords))]408 (.setRGB image ((coords i) 0) ((coords i) 1)409 (gray (sensor-data i)))))410 image))))411 #+end_src413 * Headers414 #+begin_src clojure415 (ns cortex.touch416 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry417 to be outfitted with touch sensors with density determined by a UV418 image. In this way a Geometry can know what parts of itself are419 touching nearby objects. Reads specially prepared blender files to420 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_src431 * Source Listing432 * Next435 * COMMENT Code Generation436 #+begin_src clojure :tangle ../src/cortex/touch.clj437 <<skin-main>>438 #+end_src440 #+begin_src clojure :tangle ../src/cortex/test/touch.clj441 #+end_src