Mercurial > cortex
view org/touch.org @ 229:6f1be9525e40
fleshing out text in touch.org
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sat, 11 Feb 2012 19:13:39 -0700 |
parents | 0589c35f04f2 |
children | f9b7d674aed8 |
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 Objects308 #+begin_src clojure309 (defn get-ray-origin310 "Return the origin which a Ray would have to have to be in the exact311 center of a particular Triangle in the Geometry in World312 Coordinates."313 [geom tri]314 (let [new (Vector3f.)]315 (.calculateCenter tri)316 (.localToWorld geom (.getCenter tri) new) new))318 (defn get-ray-direction319 "Return the direction which a Ray would have to have to be to point320 normal to the Triangle, in coordinates relative to the center of the321 Triangle."322 [geom tri]323 (let [n+c (Vector3f.)]324 (.calculateNormal tri)325 (.calculateCenter tri)326 (.localToWorld327 geom328 (.add (.getCenter tri) (.getNormal tri)) n+c)329 (.subtract n+c (get-ray-origin geom tri))))330 #+end_src333 * Skin Creation335 #+begin_src clojure336 (defn touch-fn337 "Returns a function which returns tactile sensory data when called338 inside a running simulation."339 [#^Geometry geo]340 (let [feeler-coords (feeler-coordinates geo)341 tris (triangles geo)342 limit 0.1343 ;;results (CollisionResults.)344 ]345 (if (empty? (touch-topology geo))346 nil347 (fn [node]348 (let [sensor-origins349 (map350 #(map (partial local-to-world geo) %)351 feeler-coords)352 triangle-normals353 (map (partial get-ray-direction geo)354 tris)355 rays356 (flatten357 (map (fn [origins norm]358 (map #(doto (Ray. % norm)359 (.setLimit limit)) origins))360 sensor-origins triangle-normals))]361 (vector362 (touch-topology geo)363 (vec364 (for [ray rays]365 (do366 (let [results (CollisionResults.)]367 (.collideWith node ray results)368 (let [touch-objects369 (filter #(not (= geo (.getGeometry %)))370 results)]371 (- 255372 (if (empty? touch-objects) 255373 (rem374 (int375 (* 255 (/ (.getDistance376 (first touch-objects)) limit)))377 256))))))))))))))379 (defn touch!380 "Endow the creature with the sense of touch. Returns a sequence of381 functions, one for each body part with a tactile-sensor-proile,382 each of which when called returns sensory data for that body part."383 [#^Node creature]384 (filter385 (comp not nil?)386 (map touch-fn387 (filter #(isa? (class %) Geometry)388 (node-seq creature)))))389 #+end_src391 * Visualizing Touch393 #+begin_src clojure394 (defn view-touch395 "Creates a function which accepts a list of touch sensor-data and396 displays each element to the screen."397 []398 (view-sense399 (fn400 [[coords sensor-data]]401 (let [image (points->image coords)]402 (dorun403 (for [i (range (count coords))]404 (.setRGB image ((coords i) 0) ((coords i) 1)405 (gray (sensor-data i)))))406 image))))407 #+end_src409 * Headers410 #+begin_src clojure411 (ns cortex.touch412 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry413 to be outfitted with touch sensors with density determined by a UV414 image. In this way a Geometry can know what parts of itself are415 touching nearby objects. Reads specially prepared blender files to416 construct this sense automatically."417 {:author "Robert McIntyre"}418 (:use (cortex world util sense))419 (:use clojure.contrib.def)420 (:import (com.jme3.scene Geometry Node Mesh))421 (:import com.jme3.collision.CollisionResults)422 (:import com.jme3.scene.VertexBuffer$Type)423 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))424 #+end_src427 * Source Listing428 * Next431 * COMMENT Code Generation432 #+begin_src clojure :tangle ../src/cortex/touch.clj433 <<skin-main>>434 #+end_src436 #+begin_src clojure :tangle ../src/cortex/test/touch.clj437 #+end_src