Mercurial > cortex
view org/touch.org @ 178:6fba17a74a57
refactored touch
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sat, 04 Feb 2012 07:05:54 -0700 |
parents | 5af4ebe72b97 |
children | 11bd5f0625ad |
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 My creatures need to be able to feel their environments. The idea here12 is to create thousands of small /touch receptors/ along the geometries13 which make up the creature's body. The number of touch receptors in a14 given area is determined by how complicated that area is, as15 determined by the total number of triangles in that region. This way,16 complicated regions like the hands/face, etc. get more touch receptors17 than simpler areas of the body.19 #+name: skin-main20 #+begin_src clojure21 (ns cortex.touch22 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry23 to be outfitted with touch sensors with density proportional to the24 density of triangles along the surface of the Geometry. Enables a25 Geometry to know what parts of itself are touching nearby objects."26 {:author "Robert McIntyre"}27 (:use (cortex world util sense))28 (:use clojure.contrib.def)29 (:import com.jme3.scene.Geometry)30 (:import com.jme3.collision.CollisionResults)31 (:import jme3tools.converters.ImageToAwt)32 (:import (com.jme3.math Triangle Vector3f Ray)))34 (cortex.import/mega-import-jme3)36 (defn triangles37 "Return a sequence of all the Triangles which compose a given38 Geometry."39 [#^Geometry geom]40 (let41 [mesh (.getMesh geom)42 triangles (transient [])]43 (dorun44 (for [n (range (.getTriangleCount mesh))]45 (let [tri (Triangle.)]46 (.getTriangle mesh n tri)47 ;; (.calculateNormal tri)48 ;; (.calculateCenter tri)49 (conj! triangles tri))))50 (persistent! triangles)))52 (defn get-ray-origin53 "Return the origin which a Ray would have to have to be in the exact54 center of a particular Triangle in the Geometry in World55 Coordinates."56 [geom tri]57 (let [new (Vector3f.)]58 (.calculateCenter tri)59 (.localToWorld geom (.getCenter tri) new) new))61 (defn get-ray-direction62 "Return the direction which a Ray would have to have to be to point63 normal to the Triangle, in coordinates relative to the center of the64 Triangle."65 [geom tri]66 (let [n+c (Vector3f.)]67 (.calculateNormal tri)68 (.calculateCenter tri)69 (.localToWorld70 geom71 (.add (.getCenter tri) (.getNormal tri)) n+c)72 (.subtract n+c (get-ray-origin geom tri))))74 ;; Every Mesh has many triangles, each with its own index.75 ;; Every vertex has its own index as well.77 (defn tactile-sensor-profile78 "Return the touch-sensor distribution image in BufferedImage format,79 or nil if it does not exist."80 [#^Geometry obj]81 (if-let [image-path (meta-data obj "touch")]82 (load-image image-path)))84 (defn triangle85 "Get the triangle specified by triangle-index from the mesh within86 bounds."87 [#^Mesh mesh triangle-index]88 (let [scratch (Triangle.)]89 (.getTriangle mesh triangle-index scratch)90 scratch))92 (defn triangle-vertex-indices93 "Get the triangle vertex indices of a given triangle from a given94 mesh."95 [#^Mesh mesh triangle-index]96 (let [indices (int-array 3)]97 (.getTriangle mesh triangle-index indices)98 (vec indices)))100 (defn vertex-UV-coord101 "Get the uv-coordinates of the vertex named by vertex-index"102 [#^Mesh mesh vertex-index]103 (let [UV-buffer104 (.getData105 (.getBuffer106 mesh107 VertexBuffer$Type/TexCoord))]108 [(.get UV-buffer (* vertex-index 2))109 (.get UV-buffer (+ 1 (* vertex-index 2)))]))111 (defn triangle-UV-coord112 "Get the uv-cooridnates of the triangle's verticies."113 [#^Mesh mesh width height triangle-index]114 (map (fn [[u v]] (vector (* width u) (* height v)))115 (map (partial vertex-UV-coord mesh)116 (triangle-vertex-indices mesh triangle-index))))118 (defn same-side?119 "Given the points p1 and p2 and the reference point ref, is point p120 on the same side of the line that goes through p1 and p2 as ref is?"121 [p1 p2 ref p]122 (<=123 0124 (.dot125 (.cross (.subtract p2 p1) (.subtract p p1))126 (.cross (.subtract p2 p1) (.subtract ref p1)))))128 (defn triangle-seq [#^Triangle tri]129 [(.get1 tri) (.get2 tri) (.get3 tri)])131 (defn vector3f-seq [#^Vector3f v]132 [(.getX v) (.getY v) (.getZ v)])134 (defn inside-triangle?135 "Is the point inside the triangle?"136 {:author "Dylan Holmes"}137 [#^Triangle tri #^Vector3f p]138 (let [[vert-1 vert-2 vert-3] (triangle-seq tri)]139 (and140 (same-side? vert-1 vert-2 vert-3 p)141 (same-side? vert-2 vert-3 vert-1 p)142 (same-side? vert-3 vert-1 vert-2 p))))144 (defn triangle->matrix4f145 "Converts the triangle into a 4x4 matrix: The first three columns146 contain the vertices of the triangle; the last contains the unit147 normal of the triangle. The bottom row is filled with 1s."148 [#^Triangle t]149 (let [mat (Matrix4f.)150 [vert-1 vert-2 vert-3]151 ((comp vec map) #(.get t %) (range 3))152 unit-normal (do (.calculateNormal t)(.getNormal t))153 vertices [vert-1 vert-2 vert-3 unit-normal]]154 (dorun155 (for [row (range 4) col (range 3)]156 (do157 (.set mat col row (.get (vertices row)col))158 (.set mat 3 row 1))))159 mat))161 (defn triangle-transformation162 "Returns the affine transformation that converts each vertex in the163 first triangle into the corresponding vertex in the second164 triangle."165 [#^Triangle tri-1 #^Triangle tri-2]166 (.mult167 (triangle->matrix4f tri-2)168 (.invert (triangle->matrix4f tri-1))))170 (defn point->vector2f [[u v]]171 (Vector2f. u v))173 (defn vector2f->vector3f [v]174 (Vector3f. (.getX v) (.getY v) 0))176 (defn map-triangle [f #^Triangle tri]177 (Triangle.178 (f 0 (.get1 tri))179 (f 1 (.get2 tri))180 (f 2 (.get3 tri))))182 (defn points->triangle183 "Convert a list of points into a triangle."184 [points]185 (apply #(Triangle. %1 %2 %3)186 (map (fn [point]187 (let [point (vec point)]188 (Vector3f. (get point 0 0)189 (get point 1 0)190 (get point 2 0))))191 (take 3 points))))193 (defn convex-bounds194 "Returns the smallest square containing the given vertices, as a195 vector of integers [left top width height]."196 [uv-verts]197 (let [xs (map first uv-verts)198 ys (map second uv-verts)199 x0 (Math/floor (apply min xs))200 y0 (Math/floor (apply min ys))201 x1 (Math/ceil (apply max xs))202 y1 (Math/ceil (apply max ys))]203 [x0 y0 (- x1 x0) (- y1 y0)]))205 (defn sensors-in-triangle206 "Locate the touch sensors in the triangle, returning a map of their207 UV and geometry-relative coordinates."208 [image mesh tri-index]209 (let [width (.getWidth image)210 height (.getHeight image)211 UV-vertex-coords (triangle-UV-coord mesh width height tri-index)212 bounds (convex-bounds UV-vertex-coords)214 cutout-triangle (points->triangle UV-vertex-coords)215 UV-sensor-coords216 (filter (comp (partial inside-triangle? cutout-triangle)217 (fn [[u v]] (Vector3f. u v 0)))218 (white-coordinates image bounds))219 UV->geometry (triangle-transformation220 cutout-triangle221 (triangle mesh tri-index))222 geometry-sensor-coords223 (map (fn [[u v]] (.mult UV->geometry (Vector3f. u v 0)))224 UV-sensor-coords)]225 {:UV UV-sensor-coords :geometry geometry-sensor-coords}))227 (defn-memo locate-feelers228 "Search the geometry's tactile UV profile for touch sensors,229 returning their positions in geometry-relative coordinates."230 [#^Geometry geo]231 (let [mesh (.getMesh geo)232 num-triangles (.getTriangleCount mesh)]233 (if-let [image (tactile-sensor-profile geo)]234 (map235 (partial sensors-in-triangle image mesh)236 (range num-triangles))237 (repeat (.getTriangleCount mesh) {:UV nil :geometry nil}))))239 (defn-memo touch-topology240 "Return a sequence of vectors of the form [x y] describing the241 \"topology\" of the tactile sensors. Points that are close together242 in the touch-topology are generally close together in the simulation."243 [#^Gemoetry geo]244 (vec (collapse (reduce concat (map :UV (locate-feelers geo))))))246 (defn-memo feeler-coordinates247 "The location of the touch sensors in world-space coordinates."248 [#^Geometry geo]249 (vec (map :geometry (locate-feelers geo))))251 (defn touch-fn252 "Returns a function which returns tactile sensory data when called253 inside a running simulation."254 [#^Geometry geo]255 (let [feeler-coords (feeler-coordinates geo)256 tris (triangles geo)257 limit 0.1258 ;;results (CollisionResults.)259 ]260 (if (empty? (touch-topology geo))261 nil262 (fn [node]263 (let [sensor-origins264 (map265 #(map (partial local-to-world geo) %)266 feeler-coords)267 triangle-normals268 (map (partial get-ray-direction geo)269 tris)270 rays271 (flatten272 (map (fn [origins norm]273 (map #(doto (Ray. % norm)274 (.setLimit limit)) origins))275 sensor-origins triangle-normals))]276 (vector277 (touch-topology geo)278 (vec279 (for [ray rays]280 (do281 (let [results (CollisionResults.)]282 (.collideWith node ray results)283 (let [touch-objects284 (filter #(not (= geo (.getGeometry %)))285 results)]286 (- 255287 (if (empty? touch-objects) 255288 (rem289 (int290 (* 255 (/ (.getDistance291 (first touch-objects)) limit)))292 256))))))))))))))294 (defn touch!295 "Endow the creature with the sense of touch. Returns a sequence of296 functions, one for each body part with a tactile-sensor-proile,297 each of which when called returns sensory data for that body part."298 [#^Node creature]299 (filter300 (comp not nil?)301 (map touch-fn302 (filter #(isa? (class %) Geometry)303 (node-seq creature)))))306 #+end_src309 * Example311 #+name: touch-test312 #+begin_src clojure313 (ns cortex.test.touch314 (:use (cortex world util touch))315 (:import316 com.jme3.scene.shape.Sphere317 com.jme3.math.ColorRGBA318 com.jme3.math.Vector3f319 com.jme3.material.RenderState$BlendMode320 com.jme3.renderer.queue.RenderQueue$Bucket321 com.jme3.scene.shape.Box322 com.jme3.scene.Node))324 (defn ray-origin-debug325 [ray color]326 (make-shape327 (assoc base-shape328 :shape (Sphere. 5 5 0.05)329 :name "arrow"330 :color color331 :texture false332 :physical? false333 :position334 (.getOrigin ray))))336 (defn ray-debug [ray color]337 (make-shape338 (assoc339 base-shape340 :name "debug-ray"341 :physical? false342 :shape (com.jme3.scene.shape.Line.343 (.getOrigin ray)344 (.add345 (.getOrigin ray)346 (.mult (.getDirection ray)347 (float (.getLimit ray))))))))350 (defn contact-color [contacts]351 (case contacts352 0 ColorRGBA/Gray353 1 ColorRGBA/Red354 2 ColorRGBA/Green355 3 ColorRGBA/Yellow356 4 ColorRGBA/Orange357 5 ColorRGBA/Red358 6 ColorRGBA/Magenta359 7 ColorRGBA/Pink360 8 ColorRGBA/White))362 (defn update-ray-debug [node ray contacts]363 (let [origin (.getChild node 0)]364 (.setLocalTranslation origin (.getOrigin ray))365 (.setColor (.getMaterial origin) "Color" (contact-color contacts))))367 (defn init-node368 [debug-node rays]369 (.detachAllChildren debug-node)370 (dorun371 (for [ray rays]372 (do373 (.attachChild374 debug-node375 (doto (Node.)376 (.attachChild (ray-origin-debug ray ColorRGBA/Gray))377 (.attachChild (ray-debug ray ColorRGBA/Gray))378 ))))))380 (defn manage-ray-debug-node [debug-node geom touch-data limit]381 (let [rays (normal-rays limit geom)]382 (if (not= (count (.getChildren debug-node)) (count touch-data))383 (init-node debug-node rays))384 (dorun385 (for [n (range (count touch-data))]386 (update-ray-debug387 (.getChild debug-node n) (nth rays n) (nth touch-data n))))))389 (defn transparent-sphere []390 (doto391 (make-shape392 (merge base-shape393 {:position (Vector3f. 0 2 0)394 :name "the blob."395 :material "Common/MatDefs/Misc/Unshaded.j3md"396 :texture "Textures/purpleWisp.png"397 :physical? true398 :mass 70399 :color ColorRGBA/Blue400 :shape (Sphere. 10 10 1)}))401 (-> (.getMaterial)402 (.getAdditionalRenderState)403 (.setBlendMode RenderState$BlendMode/Alpha))404 (.setQueueBucket RenderQueue$Bucket/Transparent)))406 (defn transparent-box []407 (doto408 (make-shape409 (merge base-shape410 {:position (Vector3f. 0 2 0)411 :name "box"412 :material "Common/MatDefs/Misc/Unshaded.j3md"413 :texture "Textures/purpleWisp.png"414 :physical? true415 :mass 70416 :color ColorRGBA/Blue417 :shape (Box. 1 1 1)}))418 (-> (.getMaterial)419 (.getAdditionalRenderState)420 (.setBlendMode RenderState$BlendMode/Alpha))421 (.setQueueBucket RenderQueue$Bucket/Transparent)))423 (defn transparent-floor []424 (doto425 (box 5 0.2 5 :mass 0 :position (Vector3f. 0 -2 0)426 :material "Common/MatDefs/Misc/Unshaded.j3md"427 :texture "Textures/redWisp.png"428 :name "floor")429 (-> (.getMaterial)430 (.getAdditionalRenderState)431 (.setBlendMode RenderState$BlendMode/Alpha))432 (.setQueueBucket RenderQueue$Bucket/Transparent)))434 (defn test-skin435 "Testing touch:436 you should see a ball which responds to the table437 and whatever balls hit it."438 []439 (let [b440 ;;(transparent-box)441 (transparent-sphere)442 ;;(sphere)443 f (transparent-floor)444 debug-node (Node.)445 node (doto (Node.) (.attachChild b) (.attachChild f))446 root-node (doto (Node.) (.attachChild node)447 (.attachChild debug-node))448 ]450 (world451 root-node452 {"key-return" (fire-cannon-ball node)}453 (fn [world]454 ;; (Capture/SimpleCaptureVideo455 ;; world456 ;; (file-str "/home/r/proj/cortex/tmp/blob.avi"))457 ;; (no-logging)458 ;;(enable-debug world)459 ;; (set-accuracy world (/ 1 60))460 )462 (fn [& _]463 (let [sensitivity 0.2464 touch-data (touch-percieve sensitivity b node)]465 (manage-ray-debug-node debug-node b touch-data sensitivity))466 ))))469 #+end_src475 * COMMENT code generation476 #+begin_src clojure :tangle ../src/cortex/touch.clj477 <<skin-main>>478 #+end_src480 #+begin_src clojure :tangle ../src/cortex/test/touch.clj481 <<touch-test>>482 #+end_src