view org/test-creature.org @ 105:3334bf15854b

removed useless code
author Robert McIntyre <rlm@mit.edu>
date Sat, 14 Jan 2012 23:06:44 -0700
parents ee302b65213b
children 40e72c6943d8
line wrap: on
line source
1 #+title: First attempt at a creature!
2 #+author: Robert McIntyre
3 #+email: rlm@mit.edu
4 #+description:
5 #+keywords: simulation, jMonkeyEngine3, clojure
6 #+SETUPFILE: ../../aurellem/org/setup.org
7 #+INCLUDE: ../../aurellem/org/level-0.org
9 * objectives
10 - [X] get an overall bitmap-like image for touch
11 - [X] write code to visuliaze this bitmap
12 - [ ] directly change the UV-pixels to show touch sensor activation
13 - [ ] write an explination for why b&w bitmaps for senses is appropiate
14 - [ ] clean up touch code and write visulazation test
15 - [ ] do the same for eyes
17 * Intro
18 So far, I've made the following senses --
19 - Vision
20 - Hearing
21 - Touch
22 - Proprioception
24 And one effector:
25 - Movement
27 However, the code so far has only enabled these senses, but has not
28 actually implemented them. For example, there is still a lot of work
29 to be done for vision. I need to be able to create an /eyeball/ in
30 simulation that can be moved around and see the world from different
31 angles. I also need to determine weather to use log-polar or cartesian
32 for the visual input, and I need to determine how/wether to
33 disceritise the visual input.
35 I also want to be able to visualize both the sensors and the
36 effectors in pretty pictures. This semi-retarted creature will be my
37 first attempt at bringing everything together.
39 * The creature's body
41 Still going to do an eve-like body in blender, but due to problems
42 importing the joints, etc into jMonkeyEngine3, I'm going to do all
43 the connecting here in clojure code, using the names of the individual
44 components and trial and error. Later, I'll maybe make some sort of
45 creature-building modifications to blender that support whatever
46 discreitized senses I'm going to make.
48 #+name: body-1
49 #+begin_src clojure
50 (ns cortex.silly
51 "let's play!"
52 {:author "Robert McIntyre"})
54 ;; TODO remove this!
55 (require 'cortex.import)
56 (cortex.import/mega-import-jme3)
57 (use '(cortex world util body hearing touch vision))
59 (rlm.rlm-commands/help)
60 (import java.awt.image.BufferedImage)
61 (import javax.swing.JPanel)
62 (import javax.swing.SwingUtilities)
63 (import java.awt.Dimension)
64 (import javax.swing.JFrame)
65 (import java.awt.Dimension)
66 (declare joint-create)
68 (defn view-image
69 "Initailizes a JPanel on which you may draw a BufferedImage.
70 Returns a function that accepts a BufferedImage and draws it to the
71 JPanel."
72 []
73 (let [image
74 (atom
75 (BufferedImage. 1 1 BufferedImage/TYPE_4BYTE_ABGR))
76 panel
77 (proxy [JPanel] []
78 (paint
79 [graphics]
80 (proxy-super paintComponent graphics)
81 (.drawImage graphics @image 0 0 nil)))
82 frame (JFrame. "Display Image")]
83 (SwingUtilities/invokeLater
84 (fn []
85 (doto frame
86 (-> (.getContentPane) (.add panel))
87 (.pack)
88 (.setLocationRelativeTo nil)
89 (.setResizable true)
90 (.setVisible true))))
91 (fn [#^BufferedImage i]
92 (reset! image i)
93 (.setSize frame (+ 8 (.getWidth i)) (+ 28 (.getHeight i)))
94 (.repaint panel 0 0 (.getWidth i) (.getHeight i)))))
96 (defn points->image
97 "Take a sparse collection of points and visuliaze it as a
98 BufferedImage."
100 ;; TODO maybe parallelize this since it's easy
102 [points]
103 (let [xs (vec (map first points))
104 ys (vec (map second points))
105 x0 (apply min xs)
106 y0 (apply min ys)
107 width (- (apply max xs) x0)
108 height (- (apply max ys) y0)
109 image (BufferedImage. (inc width) (inc height)
110 BufferedImage/TYPE_BYTE_BINARY)]
111 (dorun
112 (for [index (range (count points))]
113 (.setRGB image (- (xs index) x0) (- (ys index) y0) -1)))
115 image))
117 (defn test-data
118 []
119 (vec
120 (for [a (range 0 1000 2)
121 b (range 0 1000 2)]
122 (vector a b))
123 ))
125 (defn average [coll]
126 (/ (reduce + coll) (count coll)))
128 (defn collapse-1d
129 "One dimensional analogue of collapse"
130 [center line]
131 (let [length (count line)
132 num-above (count (filter (partial < center) line))
133 num-below (- length num-above)]
134 (range (- center num-below)
135 (+ center num-above))
136 ))
138 (defn collapse
139 "Take a set of pairs of integers and collapse them into a
140 contigous bitmap."
141 [points]
142 (let
143 [num-points (count points)
144 center (vector
145 (int (average (map first points)))
146 (int (average (map first points))))
147 flattened
148 (reduce
149 concat
150 (map
151 (fn [column]
152 (map vector
153 (map first column)
154 (collapse-1d (second center)
155 (map second column))))
156 (partition-by first (sort-by first points))))
157 squeezed
158 (reduce
159 concat
160 (map
161 (fn [row]
162 (map vector
163 (collapse-1d (first center)
164 (map first row))
165 (map second row)))
166 (partition-by second (sort-by second flattened))))
167 relocate
168 (let [min-x (apply min (map first squeezed))
169 min-y (apply min (map second squeezed))]
170 (map (fn [[x y]]
171 [(- x min-x)
172 (- y min-y)])
173 squeezed))]
174 relocate
175 ))
177 (defn load-bullet []
178 (let [sim (world (Node.) {} no-op no-op)]
179 (doto sim
180 (.enqueue
181 (fn []
182 (.stop sim)))
183 (.start))))
185 (defn load-blender-model
186 "Load a .blend file using an asset folder relative path."
187 [^String model]
188 (.loadModel
189 (doto (asset-manager)
190 (.registerLoader BlenderModelLoader (into-array String ["blend"])))
191 model))
193 (defn meta-data [blender-node key]
194 (if-let [data (.getUserData blender-node "properties")]
195 (.findValue data key)
196 nil))
198 (defn blender-to-jme
199 "Convert from Blender coordinates to JME coordinates"
200 [#^Vector3f in]
201 (Vector3f. (.getX in)
202 (.getZ in)
203 (- (.getY in))))
205 (defn jme-to-blender
206 "Convert from JME coordinates to Blender coordinates"
207 [#^Vector3f in]
208 (Vector3f. (.getX in)
209 (- (.getZ in))
210 (.getY in)))
212 (defn joint-targets
213 "Return the two closest two objects to the joint object, ordered
214 from bottom to top according to the joint's rotation."
215 [#^Node parts #^Node joint]
216 ;;(println (meta-data joint "joint"))
217 (.getWorldRotation joint)
218 (loop [radius (float 0.01)]
219 (let [results (CollisionResults.)]
220 (.collideWith
221 parts
222 (BoundingBox. (.getWorldTranslation joint)
223 radius radius radius)
224 results)
225 (let [targets
226 (distinct
227 (map #(.getGeometry %) results))]
228 (if (>= (count targets) 2)
229 (sort-by
230 #(let [v
231 (jme-to-blender
232 (.mult
233 (.inverse (.getWorldRotation joint))
234 (.subtract (.getWorldTranslation %)
235 (.getWorldTranslation joint))))]
236 (println-repl (.getName %) ":" v)
237 (.dot (Vector3f. 1 1 1)
238 v))
239 (take 2 targets))
240 (recur (float (* radius 2))))))))
242 (defn world-to-local
243 "Convert the world coordinates into coordinates relative to the
244 object (i.e. local coordinates), taking into account the rotation
245 of object."
246 [#^Spatial object world-coordinate]
247 (let [out (Vector3f.)]
248 (.worldToLocal object world-coordinate out) out))
250 (defn local-to-world
251 "Convert the local coordinates into coordinates into world relative
252 coordinates"
253 [#^Spatial object local-coordinate]
254 (let [world-coordinate (Vector3f.)]
255 (.localToWorld object local-coordinate world-coordinate)
256 world-coordinate))
259 (defmulti joint-dispatch
260 "Translate blender pseudo-joints into real JME joints."
261 (fn [constraints & _]
262 (:type constraints)))
264 (defmethod joint-dispatch :point
265 [constraints control-a control-b pivot-a pivot-b rotation]
266 (println-repl "creating POINT2POINT joint")
267 (Point2PointJoint.
268 control-a
269 control-b
270 pivot-a
271 pivot-b))
273 (defmethod joint-dispatch :hinge
274 [constraints control-a control-b pivot-a pivot-b rotation]
275 (println-repl "creating HINGE joint")
276 (let [axis
277 (if-let
278 [axis (:axis constraints)]
279 axis
280 Vector3f/UNIT_X)
281 [limit-1 limit-2] (:limit constraints)
282 hinge-axis
283 (.mult
284 rotation
285 (blender-to-jme axis))]
286 (doto
287 (HingeJoint.
288 control-a
289 control-b
290 pivot-a
291 pivot-b
292 hinge-axis
293 hinge-axis)
294 (.setLimit limit-1 limit-2))))
296 (defmethod joint-dispatch :cone
297 [constraints control-a control-b pivot-a pivot-b rotation]
298 (let [limit-xz (:limit-xz constraints)
299 limit-xy (:limit-xy constraints)
300 twist (:twist constraints)]
302 (println-repl "creating CONE joint")
303 (println-repl rotation)
304 (println-repl
305 "UNIT_X --> " (.mult rotation (Vector3f. 1 0 0)))
306 (println-repl
307 "UNIT_Y --> " (.mult rotation (Vector3f. 0 1 0)))
308 (println-repl
309 "UNIT_Z --> " (.mult rotation (Vector3f. 0 0 1)))
310 (doto
311 (ConeJoint.
312 control-a
313 control-b
314 pivot-a
315 pivot-b
316 rotation
317 rotation)
318 (.setLimit (float limit-xz)
319 (float limit-xy)
320 (float twist)))))
322 (defn connect
323 "here are some examples:
324 {:type :point}
325 {:type :hinge :limit [0 (/ Math/PI 2)] :axis (Vector3f. 0 1 0)}
326 (:axis defaults to (Vector3f. 1 0 0) if not provided for hinge joints)
328 {:type :cone :limit-xz 0]
329 :limit-xy 0]
330 :twist 0]} (use XZY rotation mode in blender!)"
331 [#^Node obj-a #^Node obj-b #^Node joint]
332 (let [control-a (.getControl obj-a RigidBodyControl)
333 control-b (.getControl obj-b RigidBodyControl)
334 joint-center (.getWorldTranslation joint)
335 joint-rotation (.toRotationMatrix (.getWorldRotation joint))
336 pivot-a (world-to-local obj-a joint-center)
337 pivot-b (world-to-local obj-b joint-center)]
339 (if-let [constraints
340 (map-vals
341 eval
342 (read-string
343 (meta-data joint "joint")))]
344 ;; A side-effect of creating a joint registers
345 ;; it with both physics objects which in turn
346 ;; will register the joint with the physics system
347 ;; when the simulation is started.
348 (do
349 (println-repl "creating joint between"
350 (.getName obj-a) "and" (.getName obj-b))
351 (joint-dispatch constraints
352 control-a control-b
353 pivot-a pivot-b
354 joint-rotation))
355 (println-repl "could not find joint meta-data!"))))
357 (defn assemble-creature [#^Node pieces joints]
358 (dorun
359 (map
360 (fn [geom]
361 (let [physics-control
362 (RigidBodyControl.
363 (HullCollisionShape.
364 (.getMesh geom))
365 (if-let [mass (meta-data geom "mass")]
366 (do
367 (println-repl
368 "setting" (.getName geom) "mass to" (float mass))
369 (float mass))
370 (float 1)))]
372 (.addControl geom physics-control)))
373 (filter #(isa? (class %) Geometry )
374 (node-seq pieces))))
375 (dorun
376 (map
377 (fn [joint]
378 (let [[obj-a obj-b]
379 (joint-targets pieces joint)]
380 (connect obj-a obj-b joint)))
381 joints))
382 pieces)
384 (defn blender-creature [blender-path]
385 (let [model (load-blender-model blender-path)
386 joints
387 (if-let [joint-node (.getChild model "joints")]
388 (seq (.getChildren joint-node))
389 (do (println-repl "could not find joints node")
390 []))]
391 (assemble-creature model joints)))
393 (def hand "Models/creature1/one.blend")
395 (def worm "Models/creature1/try-again.blend")
397 (def touch "Models/creature1/touch.blend")
399 (defn worm-model [] (load-blender-model worm))
401 (defn x-ray [#^ColorRGBA color]
402 (doto (Material. (asset-manager)
403 "Common/MatDefs/Misc/Unshaded.j3md")
404 (.setColor "Color" color)
405 (-> (.getAdditionalRenderState)
406 (.setDepthTest false))))
408 (defn test-creature [thing]
409 (let [x-axis
410 (box 1 0.01 0.01 :physical? false :color ColorRGBA/Red)
411 y-axis
412 (box 0.01 1 0.01 :physical? false :color ColorRGBA/Green)
413 z-axis
414 (box 0.01 0.01 1 :physical? false :color ColorRGBA/Blue)]
415 (world
416 (nodify [(blender-creature thing)
417 (box 10 2 10 :position (Vector3f. 0 -9 0)
418 :color ColorRGBA/Gray :mass 0)
419 x-axis y-axis z-axis
420 ])
421 standard-debug-controls
422 (fn [world]
423 (light-up-everything world)
424 (enable-debug world)
425 ;;(com.aurellem.capture.Capture/captureVideo
426 ;; world (file-str "/home/r/proj/ai-videos/hand"))
427 (.setTimer world (NanoTimer.))
428 (set-gravity world (Vector3f. 0 0 0))
429 (speed-up world)
430 )
431 no-op
432 ;;(let [timer (atom 0)]
433 ;; (fn [_ _]
434 ;; (swap! timer inc)
435 ;; (if (= (rem @timer 60) 0)
436 ;; (println-repl (float (/ @timer 60))))))
437 )))
439 (defn colorful []
440 (.getChild (worm-model) "worm-21"))
442 (import jme3tools.converters.ImageToAwt)
444 (import ij.ImagePlus)
446 (defn triangle-indices
447 "Get the triangle vertex indices of a given triangle from a given
448 mesh."
449 [#^Mesh mesh triangle-index]
450 (let [indices (int-array 3)]
451 (.getTriangle mesh triangle-index indices)
452 (vec indices)))
454 (defn uv-coord
455 "Get the uv-coordinates of the vertex named by vertex-index"
456 [#^Mesh mesh vertex-index]
457 (let [UV-buffer
458 (.getData
459 (.getBuffer
460 mesh
461 VertexBuffer$Type/TexCoord))]
462 (Vector2f.
463 (.get UV-buffer (* vertex-index 2))
464 (.get UV-buffer (+ 1 (* vertex-index 2))))))
466 (defn tri-uv-coord
467 "Get the uv-cooridnates of the triangle's verticies."
468 [#^Mesh mesh #^Triangle triangle]
469 (map (partial uv-coord mesh)
470 (triangle-indices mesh (.getIndex triangle))))
472 (defn touch-receptor-image
473 "Return the touch-sensor distribution image in ImagePlus format, or
474 nil if it does not exist."
475 [#^Geometry obj]
476 (let [mat (.getMaterial obj)]
477 (if-let [texture-param
478 (.getTextureParam
479 mat
480 MaterialHelper/TEXTURE_TYPE_DIFFUSE)]
481 (let
482 [texture
483 (.getTextureValue texture-param)
484 im (.getImage texture)]
485 (ImagePlus.
486 "UV-map"
487 (ImageToAwt/convert im false false 0))))))
489 (import ij.process.ImageProcessor)
490 (import java.awt.image.BufferedImage)
492 (defprotocol Frame
493 (frame [this]))
495 (extend-type BufferedImage
496 Frame
497 (frame [image]
498 (merge
499 (apply
500 hash-map
501 (interleave
502 (doall (for [x (range (.getWidth image)) y (range (.getHeight image))]
503 (vector x y)))
504 (doall (for [x (range (.getWidth image)) y (range (.getHeight image))]
505 (let [data (.getRGB image x y)]
506 (hash-map :r (bit-shift-right (bit-and 0xff0000 data) 16)
507 :g (bit-shift-right (bit-and 0x00ff00 data) 8)
508 :b (bit-and 0x0000ff data)))))))
509 {:width (.getWidth image) :height (.getHeight image)})))
512 (extend-type ImagePlus
513 Frame
514 (frame [image+]
515 (frame (.getBufferedImage image+))))
518 (def white -1)
520 (defn filter-pixels
521 "List the coordinates of all pixels matching pred."
522 {:author "Dylan Holmes"}
523 [pred #^ImageProcessor ip]
524 (let
525 [width (.getWidth ip)
526 height (.getHeight ip)]
527 ((fn accumulate [x y matches]
528 (cond
529 (>= y height) matches
530 (>= x width) (recur 0 (inc y) matches)
531 (pred (.getPixel ip x y))
532 (recur (inc x) y (conj matches (Vector2f. x y)))
533 :else (recur (inc x) y matches)))
534 0 0 [])))
536 (defn white-coordinates
537 "List the coordinates of all the white pixels in an image."
538 [#^ImageProcessor ip]
539 (filter-pixels #(= % white) ip))
541 (defn same-side?
542 "Given the points p1 and p2 and the reference point ref, is point p
543 on the same side of the line that goes through p1 and p2 as ref is?"
544 [p1 p2 ref p]
545 (<=
546 0
547 (.dot
548 (.cross (.subtract p2 p1) (.subtract p p1))
549 (.cross (.subtract p2 p1) (.subtract ref p1)))))
551 (defn triangle->matrix4f
552 "Converts the triangle into a 4x4 matrix of vertices: The first
553 three columns contain the vertices of the triangle; the last
554 contains the unit normal of the triangle. The bottom row is filled
555 with 1s."
556 [#^Triangle t]
557 (let [mat (Matrix4f.)
558 [vert-1 vert-2 vert-3]
559 ((comp vec map) #(.get t %) (range 3))
560 unit-normal (do (.calculateNormal t)(.getNormal t))
561 vertices [vert-1 vert-2 vert-3 unit-normal]]
562 (dorun
563 (for [row (range 4) col (range 3)]
564 (do
565 (.set mat col row (.get (vertices row)col))
566 (.set mat 3 row 1))))
567 mat))
569 (defn triangle-transformation
570 "Returns the affine transformation that converts each vertex in the
571 first triangle into the corresponding vertex in the second
572 triangle."
573 [#^Triangle tri-1 #^Triangle tri-2]
574 (.mult
575 (triangle->matrix4f tri-2)
576 (.invert (triangle->matrix4f tri-1))))
578 (def death (Triangle.
579 (Vector3f. 1 1 1)
580 (Vector3f. 1 2 3)
581 (Vector3f. 5 6 7)))
583 (def death-2 (Triangle.
584 (Vector3f. 2 2 2)
585 (Vector3f. 1 1 1)
586 (Vector3f. 0 1 0)))
588 (defn vector2f->vector3f [v]
589 (Vector3f. (.getX v) (.getY v) 0))
591 (extend-type Triangle
592 Textual
593 (text [t]
594 (println "Triangle: " \newline (.get1 t) \newline
595 (.get2 t) \newline (.get3 t))))
597 (defn map-triangle [f #^Triangle tri]
598 (Triangle.
599 (f 0 (.get1 tri))
600 (f 1 (.get2 tri))
601 (f 2 (.get3 tri))))
603 (defn triangle-seq [#^Triangle tri]
604 [(.get1 tri) (.get2 tri) (.get3 tri)])
606 (defn vector3f-seq [#^Vector3f v]
607 [(.getX v) (.getY v) (.getZ v)])
609 (defn inside-triangle?
610 "Is the point inside the triangle? Now what do we do?
611 You might want to hold on there"
612 {:author "Dylan Holmes"}
613 [tri p]
614 (let [[vert-1 vert-2 vert-3] (triangle-seq tri)]
615 (and
616 (same-side? vert-1 vert-2 vert-3 p)
617 (same-side? vert-2 vert-3 vert-1 p)
618 (same-side? vert-3 vert-1 vert-2 p))))
620 (defn uv-triangle
621 "Convert the mesh triangle into the cooresponding triangle in
622 UV-space. Z-component of these triangles is always zero."
623 [#^Mesh mesh #^Triangle tri]
624 (apply #(Triangle. %1 %2 %3)
625 (map vector2f->vector3f
626 (tri-uv-coord mesh tri))))
628 (defn pixel-triangle
629 "Convert the mesh triangle into the corresponding triangle in
630 UV-pixel-space. Z compenent will be zero."
631 [#^Mesh mesh #^Triangle tri width height]
632 (map-triangle (fn [_ v]
633 (Vector3f. (* width (.getX v))
634 (* height (.getY v))
635 0))
636 (uv-triangle mesh tri)))
638 (def rasterize pixel-triangle)
641 (defn triangle-bounds
642 "Dimensions of the bounding square of the triangle in the form
643 [x y width height].
644 Assumes that the triangle lies in the XY plane."
645 [#^Triangle tri]
646 (let [verts (map vector3f-seq (triangle-seq tri))
647 x (apply min (map first verts))
648 y (apply min (map second verts))]
649 [x y
650 (- (apply max (map first verts)) x)
651 (- (apply max (map second verts)) y)
652 ]))
655 (defn locate-feelers
656 "Search the geometry's tactile UV image for touch sensors, returning
657 their positions in geometry-relative coordinates."
658 [#^Geometry geo]
659 (if-let [image (touch-receptor-image geo)]
660 (let [mesh (.getMesh geo)
661 tris (triangles geo)
663 width (.getWidth image)
664 height (.getHeight image)
666 ;; for each triangle
667 sensor-coords
668 (fn [tri]
669 ;; translate triangle to uv-pixel-space
670 (let [uv-tri
671 (pixel-triangle mesh tri width height)
672 bounds (vec (triangle-bounds uv-tri))]
674 ;; get that part of the picture
676 (apply #(.setRoi image %1 %2 %3 %4) bounds)
677 (let [cutout (.crop (.getProcessor image))
678 ;; extract white pixels inside triangle
679 cutout-tri
680 (map-triangle
681 (fn [_ v]
682 (.subtract
683 v
684 (Vector3f. (bounds 0) (bounds 1) (float 0))))
685 uv-tri)
686 whites (filter (partial inside-triangle? cutout-tri)
687 (map vector2f->vector3f
688 (white-coordinates cutout)))
689 ;; translate pixel coordinates to world-space
690 transform (triangle-transformation cutout-tri tri)]
691 (map #(.mult transform %) whites))))]
692 (vec (map sensor-coords tris)))
693 (repeat (count (triangles geo)) [])))
695 (use 'clojure.contrib.def)
697 (defn-memo touch-topology [#^Gemoetry geo]
698 (let [feeler-coords
699 (map
700 #(vector (int (.getX %)) (int (.getY %)))
701 (white-coordinates
702 (.getProcessor (touch-receptor-image (colorful)))))]
703 (vec (collapse feeler-coords))))
705 (defn enable-touch [#^Geometry geo]
706 (let [feeler-coords (locate-feelers geo)
707 tris (triangles geo)
708 limit 0.1]
709 (fn [node]
710 (let [sensor-origins
711 (map
712 #(map (partial local-to-world geo) %)
713 feeler-coords)
714 triangle-normals
715 (map (partial get-ray-direction geo)
716 tris)
717 rays
718 (flatten
719 (map (fn [origins norm]
720 (map #(doto (Ray. % norm)
721 (.setLimit limit)) origins))
722 sensor-origins triangle-normals))]
723 (vector
724 (touch-topology geo)
725 (vec
726 (for [ray rays]
727 (do
728 (let [results (CollisionResults.)]
729 (.collideWith node ray results)
730 (let [touch-objects
731 (set
732 (filter #(not (= geo %))
733 (map #(.getGeometry %) results)))]
734 (if (> (count touch-objects) 0)
735 1 0)))))))))))
737 (defn touch [#^Node pieces]
738 (map enable-touch
739 (filter #(isa? (class %) Geometry)
740 (node-seq pieces))))
742 (defn debug-window
743 "creates function that offers a debug view of sensor data"
744 []
745 (let [vi (view-image)]
746 (fn
747 [[coords sensor-data]]
748 (let [image (points->image coords)]
749 (dorun
750 (for [i (range (count coords))]
751 (.setRGB image ((coords i) 0) ((coords i) 1)
752 ({0 -16777216
753 1 -1} (sensor-data i)))))
754 (vi image)))))
756 (defn world-setup [joint]
757 (let [joint-position (Vector3f. 0 0 0)
758 joint-rotation
759 (.toRotationMatrix
760 (.mult
761 (doto (Quaternion.)
762 (.fromAngleAxis
763 (* 1 (/ Math/PI 4))
764 (Vector3f. -1 0 0)))
765 (doto (Quaternion.)
766 (.fromAngleAxis
767 (* 1 (/ Math/PI 2))
768 (Vector3f. 0 0 1)))))
769 top-position (.mult joint-rotation (Vector3f. 8 0 0))
771 origin (doto
772 (sphere 0.1 :physical? false :color ColorRGBA/Cyan
773 :position top-position))
774 top (doto
775 (sphere 0.1 :physical? false :color ColorRGBA/Yellow
776 :position top-position)
778 (.addControl
779 (RigidBodyControl.
780 (CapsuleCollisionShape. 0.5 1.5 1) (float 20))))
781 bottom (doto
782 (sphere 0.1 :physical? false :color ColorRGBA/DarkGray
783 :position (Vector3f. 0 0 0))
784 (.addControl
785 (RigidBodyControl.
786 (CapsuleCollisionShape. 0.5 1.5 1) (float 0))))
787 table (box 10 2 10 :position (Vector3f. 0 -20 0)
788 :color ColorRGBA/Gray :mass 0)
789 a (.getControl top RigidBodyControl)
790 b (.getControl bottom RigidBodyControl)]
792 (cond
793 (= joint :cone)
795 (doto (ConeJoint.
796 a b
797 (world-to-local top joint-position)
798 (world-to-local bottom joint-position)
799 joint-rotation
800 joint-rotation
801 )
804 (.setLimit (* (/ 10) Math/PI)
805 (* (/ 4) Math/PI)
806 0)))
807 [origin top bottom table]))
809 (defn test-joint [joint]
810 (let [[origin top bottom floor] (world-setup joint)
811 control (.getControl top RigidBodyControl)
812 move-up? (atom false)
813 move-down? (atom false)
814 move-left? (atom false)
815 move-right? (atom false)
816 roll-left? (atom false)
817 roll-right? (atom false)
818 timer (atom 0)]
820 (world
821 (nodify [top bottom floor origin])
822 (merge standard-debug-controls
823 {"key-r" (fn [_ pressed?] (reset! move-up? pressed?))
824 "key-t" (fn [_ pressed?] (reset! move-down? pressed?))
825 "key-f" (fn [_ pressed?] (reset! move-left? pressed?))
826 "key-g" (fn [_ pressed?] (reset! move-right? pressed?))
827 "key-v" (fn [_ pressed?] (reset! roll-left? pressed?))
828 "key-b" (fn [_ pressed?] (reset! roll-right? pressed?))})
830 (fn [world]
831 (light-up-everything world)
832 (enable-debug world)
833 (set-gravity world (Vector3f. 0 0 0))
834 )
836 (fn [world _]
837 (if (zero? (rem (swap! timer inc) 100))
838 (do
839 ;; (println-repl @timer)
840 (.attachChild (.getRootNode world)
841 (sphere 0.05 :color ColorRGBA/Yellow
842 :position (.getWorldTranslation top)
843 :physical? false))
844 (.attachChild (.getRootNode world)
845 (sphere 0.05 :color ColorRGBA/LightGray
846 :position (.getWorldTranslation bottom)
847 :physical? false))))
849 (if @move-up?
850 (.applyTorque control
851 (.mult (.getPhysicsRotation control)
852 (Vector3f. 0 0 10))))
853 (if @move-down?
854 (.applyTorque control
855 (.mult (.getPhysicsRotation control)
856 (Vector3f. 0 0 -10))))
857 (if @move-left?
858 (.applyTorque control
859 (.mult (.getPhysicsRotation control)
860 (Vector3f. 0 10 0))))
861 (if @move-right?
862 (.applyTorque control
863 (.mult (.getPhysicsRotation control)
864 (Vector3f. 0 -10 0))))
865 (if @roll-left?
866 (.applyTorque control
867 (.mult (.getPhysicsRotation control)
868 (Vector3f. -1 0 0))))
869 (if @roll-right?
870 (.applyTorque control
871 (.mult (.getPhysicsRotation control)
872 (Vector3f. 1 0 0))))))))
875 #+end_src
877 #+results: body-1
878 : #'cortex.silly/tactile-coords
881 * COMMENT purgatory
882 #+begin_src clojure
883 (defn bullet-trans []
884 (let [obj-a (sphere 0.5 :color ColorRGBA/Red
885 :position (Vector3f. -10 5 0))
886 obj-b (sphere 0.5 :color ColorRGBA/Blue
887 :position (Vector3f. -10 -5 0)
888 :mass 0)
889 control-a (.getControl obj-a RigidBodyControl)
890 control-b (.getControl obj-b RigidBodyControl)
891 swivel
892 (.toRotationMatrix
893 (doto (Quaternion.)
894 (.fromAngleAxis (/ Math/PI 2)
895 Vector3f/UNIT_X)))]
896 (doto
897 (ConeJoint.
898 control-a control-b
899 (Vector3f. 0 5 0)
900 (Vector3f. 0 -5 0)
901 swivel swivel)
902 (.setLimit (* 0.6 (/ Math/PI 4))
903 (/ Math/PI 4)
904 (* Math/PI 0.8)))
905 (world (nodify
906 [obj-a obj-b])
907 standard-debug-controls
908 enable-debug
909 no-op)))
912 (defn bullet-trans* []
913 (let [obj-a (box 1.5 0.5 0.5 :color ColorRGBA/Red
914 :position (Vector3f. 5 0 0)
915 :mass 90)
916 obj-b (sphere 0.5 :color ColorRGBA/Blue
917 :position (Vector3f. -5 0 0)
918 :mass 0)
919 control-a (.getControl obj-a RigidBodyControl)
920 control-b (.getControl obj-b RigidBodyControl)
921 move-up? (atom nil)
922 move-down? (atom nil)
923 move-left? (atom nil)
924 move-right? (atom nil)
925 roll-left? (atom nil)
926 roll-right? (atom nil)
927 force 100
928 swivel
929 (.toRotationMatrix
930 (doto (Quaternion.)
931 (.fromAngleAxis (/ Math/PI 2)
932 Vector3f/UNIT_X)))
933 x-move
934 (doto (Matrix3f.)
935 (.fromStartEndVectors Vector3f/UNIT_X
936 (.normalize (Vector3f. 1 1 0))))
938 timer (atom 0)]
939 (doto
940 (ConeJoint.
941 control-a control-b
942 (Vector3f. -8 0 0)
943 (Vector3f. 2 0 0)
944 ;;swivel swivel
945 ;;Matrix3f/IDENTITY Matrix3f/IDENTITY
946 x-move Matrix3f/IDENTITY
947 )
948 (.setCollisionBetweenLinkedBodys false)
949 (.setLimit (* 1 (/ Math/PI 4)) ;; twist
950 (* 1 (/ Math/PI 4)) ;; swing span in X-Y plane
951 (* 0 (/ Math/PI 4)))) ;; swing span in Y-Z plane
952 (world (nodify
953 [obj-a obj-b])
954 (merge standard-debug-controls
955 {"key-r" (fn [_ pressed?] (reset! move-up? pressed?))
956 "key-t" (fn [_ pressed?] (reset! move-down? pressed?))
957 "key-f" (fn [_ pressed?] (reset! move-left? pressed?))
958 "key-g" (fn [_ pressed?] (reset! move-right? pressed?))
959 "key-v" (fn [_ pressed?] (reset! roll-left? pressed?))
960 "key-b" (fn [_ pressed?] (reset! roll-right? pressed?))})
962 (fn [world]
963 (enable-debug world)
964 (set-gravity world Vector3f/ZERO)
965 )
967 (fn [world _]
969 (if @move-up?
970 (.applyForce control-a
971 (Vector3f. force 0 0)
972 (Vector3f. 0 0 0)))
973 (if @move-down?
974 (.applyForce control-a
975 (Vector3f. (- force) 0 0)
976 (Vector3f. 0 0 0)))
977 (if @move-left?
978 (.applyForce control-a
979 (Vector3f. 0 force 0)
980 (Vector3f. 0 0 0)))
981 (if @move-right?
982 (.applyForce control-a
983 (Vector3f. 0 (- force) 0)
984 (Vector3f. 0 0 0)))
986 (if @roll-left?
987 (.applyForce control-a
988 (Vector3f. 0 0 force)
989 (Vector3f. 0 0 0)))
990 (if @roll-right?
991 (.applyForce control-a
992 (Vector3f. 0 0 (- force))
993 (Vector3f. 0 0 0)))
995 (if (zero? (rem (swap! timer inc) 100))
996 (.attachChild
997 (.getRootNode world)
998 (sphere 0.05 :color ColorRGBA/Yellow
999 :physical? false :position
1000 (.getWorldTranslation obj-a)))))
1002 ))
1004 (defn transform-trianglesdsd
1005 "Transform that converts each vertex in the first triangle
1006 into the corresponding vertex in the second triangle."
1007 [#^Triangle tri-1 #^Triangle tri-2]
1008 (let [in [(.get1 tri-1)
1009 (.get2 tri-1)
1010 (.get3 tri-1)]
1011 out [(.get1 tri-2)
1012 (.get2 tri-2)
1013 (.get3 tri-2)]]
1014 (let [translate (doto (Matrix4f.) (.setTranslation (.negate (in 0))))
1015 in* [(.mult translate (in 0))
1016 (.mult translate (in 1))
1017 (.mult translate (in 2))]
1018 final-translation
1019 (doto (Matrix4f.)
1020 (.setTranslation (out 1)))
1022 rotate-1
1023 (doto (Matrix3f.)
1024 (.fromStartEndVectors
1025 (.normalize
1026 (.subtract
1027 (in* 1) (in* 0)))
1028 (.normalize
1029 (.subtract
1030 (out 1) (out 0)))))
1031 in** [(.mult rotate-1 (in* 0))
1032 (.mult rotate-1 (in* 1))
1033 (.mult rotate-1 (in* 2))]
1034 scale-factor-1
1035 (.mult
1036 (.normalize
1037 (.subtract
1038 (out 1)
1039 (out 0)))
1040 (/ (.length
1041 (.subtract (out 1)
1042 (out 0)))
1043 (.length
1044 (.subtract (in** 1)
1045 (in** 0)))))
1046 scale-1 (doto (Matrix4f.) (.setScale scale-factor-1))
1047 in*** [(.mult scale-1 (in** 0))
1048 (.mult scale-1 (in** 1))
1049 (.mult scale-1 (in** 2))]
1057 (dorun (map println in))
1058 (println)
1059 (dorun (map println in*))
1060 (println)
1061 (dorun (map println in**))
1062 (println)
1063 (dorun (map println in***))
1064 (println)
1066 ))))
1071 #+end_src
1074 * COMMENT generate source
1075 #+begin_src clojure :tangle ../src/cortex/silly.clj
1076 <<body-1>>
1077 #+end_src