view org/cortex.org @ 4:50c92af2018e

fixed headers, make compat symlink
author Robert McIntyre <rlm@mit.edu>
date Thu, 20 Oct 2011 15:10:38 -0700
parents 92f8d83b5d0b
children e3c6d1c1cb00
line wrap: on
line source
1 #+title: Simulated Senses
2 #+author: Robert McIntyre
3 #+email: rlm@mit.edu
4 #+description: Simulating senses for AI research using JMonkeyEngine3
5 #+SETUPFILE: ../../aurellem/org/setup.org
6 #+INCLUDE: ../../aurellem/org/level-0.org
9 * Background
10 Artificial Intelligence has tried and failed for more than half a
11 century to produce programs as flexible, creative, and “intelligent”
12 as the human mind itself. Clearly, we are still missing some important
13 ideas concerning intelligent programs or we would have strong AI
14 already. What idea could be missing?
16 When Turing first proposed his famous “Turing Test” in the
17 groundbreaking paper [[./sources/turing.pdf][/Computing Machines and Intelligence/]], he gave
18 little importance to how a computer program might interact with the
19 world:
21 #+BEGIN_QUOTE
22 \ldquo{}We need not be too concerned about the legs, eyes, etc. The example of
23 Miss Helen Keller shows that education can take place provided that
24 communication in both directions between teacher and pupil can take
25 place by some means or other.\rdquo{}
26 #+END_QUOTE
28 And from the example of Hellen Keller he went on to assume that the
29 only thing a fledgling AI program could need by way of communication
30 is a teletypewriter. But Hellen Keller did possess vision and hearing
31 for the first few months of her life, and her tactile sense was far
32 more rich than any text-stream could hope to achieve. She possessed a
33 body she could move freely, and had continual access to the real world
34 to learn from her actions.
36 I believe that our programs are suffering from too little sensory
37 input to become really intelligent. Imagine for a moment that you
38 lived in a world completely cut off form all sensory stimulation. You
39 have no eyes to see, no ears to hear, no mouth to speak. No body, no
40 taste, no feeling whatsoever. The only sense you get at all is a
41 single point of light, flickering on and off in the void. If this was
42 your life from birth, you would never learn anything, and could never
43 become intelligent. Actual humans placed in sensory deprivation
44 chambers experience hallucinations and can begin to loose their sense
45 of reality in as little as 15 minutes[sensory-deprivation]. Most of
46 the time, the programs we write are in exactly this situation. They do
47 not interface with cameras and microphones, and they do not control a
48 real or simulated body or interact with any sort of world.
51 * Simulation vs. Reality
52 I want demonstrate that multiple senses are what enable
53 intelligence. There are two ways of playing around with senses and
54 computer programs:
56 The first is to go entirely with simulation: virtual world, virtual
57 character, virtual senses. The advantages are that when everything is
58 a simulation, experiments in that simulation are absolutely
59 reproducible. It's also easier to change the character and world to
60 explore new situations and different sensory combinations.
63 ** Issues with Simulation
65 If the world is to be simulated on a computer, then not only do you
66 have to worry about whether the character's senses are rich enough to
67 learn from the world, but whether the world itself is rendered with
68 enough detail and realism to give enough working material to the
69 character's senses. To name just a few difficulties facing modern
70 physics simulators: destructibility of the environment, simulation of
71 water/other fluids, large areas, nonrigid bodies, lots of objects,
72 smoke. I don't know of any computer simulation that would allow a
73 character to take a rock and grind it into fine dust, then use that
74 dust to make a clay sculpture, at least not without spending years
75 calculating the interactions of every single small grain of
76 dust. Maybe a simulated world with today's limitations doesn't provide
77 enough richness for real intelligence to evolve.
79 ** Issues with Reality
81 The other approach for playing with senses is to hook your software up
82 to real cameras, microphones, robots, etc., and let it loose in the
83 real world. This has the advantage of eliminating concerns about
84 simulating the world at the expense of increasing the complexity of
85 implementing the senses. Instead of just grabbing the current rendered
86 frame for processing, you have to use an actual camera with real
87 lenses and interact with photons to get an image. It is much harder to
88 change the character, which is now partly a physical robot of some
89 sort, since doing so involves changing things around in the real world
90 instead of modifying lines of code. While the real world is very rich
91 and definitely provides enough stimulation for intelligence to develop
92 as evidenced by our own existence, it is also uncontrollable in the
93 sense that a particular situation cannot be recreated perfectly or
94 saved for later use. It is harder to conduct science because it is
95 harder to repeat an experiment. The worst thing about using the real
96 world instead of a simulation is the matter of time. Instead of
97 simulated time you get the constant and unstoppable flow of real
98 time. This severely limits the sorts of software you can use to
99 program the AI because all sense inputs must be handled in real
100 time. Complicated ideas may have to be implemented in hardware or may
101 simply be impossible given the current speed of our
102 processors. Contrast this with a simulation, in which the flow of time
103 in the simulated world can be slowed down to accommodate the
104 limitations of the character's programming. In terms of cost, doing
105 everything in software is far cheaper than building custom real-time
106 hardware. All you need is a laptop and some patience.
108 * Choose a Simulation Engine
110 Mainly because of issues with controlling the flow of time, I chose to
111 simulate both the world and the character. I set out to make a minimal
112 world in which I could embed a character with multiple senses. My main
113 goal is to make an environment where I can perform further experiments
114 in simulated senses.
116 As Carl Sagan once said, "If you wish to make an apple pie from
117 scratch, you must first invent the universe.” I examined many
118 different 3D environments to try and find something I would use as the
119 base for my simulation; eventually the choice came down to three
120 engines: the Quake II engine, the Source Engine, and jMonkeyEngine.
122 ** Quake II/Jake2
124 I spent a bit more than a month working with the Quake II Engine from
125 ID software to see if I could use it for my purposes. All the source
126 code was released by ID software into the Public Domain several years
127 ago, and as a result it has been ported and modified for many
128 different reasons. This engine was famous for its advanced use of
129 realistic shading and had decent and fast physics
130 simulation. Researchers at Princeton [[http://www.nature.com/nature/journal/v461/n7266/pdf/nature08499.pdf][used this code]] to study spatial
131 information encoding in the hippocampal cells of rats. Those
132 researchers created a special Quake II level that simulated a maze,
133 and added an interface where a mouse could run around inside a ball in
134 various directions to move the character in the simulated maze. They
135 measured hippocampal activity during this exercise to try and tease
136 out the method in which spatial data was stored in that area of the
137 brain. I find this promising because if a real living rat can interact
138 with a computer simulation of a maze in the same way as it interacts
139 with a real-world maze, then maybe that simulation is close enough to
140 reality that a simulated sense of vision and motor control interacting
141 with that simulation could reveal useful information about the real
142 thing. It happens that there is a Java port of the original C source
143 code called Jake2. The port demonstrates Java's OpenGL bindings and
144 runs anywhere from 90% to 105% as fast as the C version. After
145 reviewing much of the source of Jake2, I eventually rejected it
146 because the engine is too tied to the concept of a first-person
147 shooter game. One of the problems I had was that there does not seem
148 to be any easy way to attach multiple cameras to a single
149 character. There are also several physics clipping issues that are
150 corrected in a way that only applies to the main character and does
151 not apply to arbitrary objects. While there is a large community of
152 level modders, I couldn't find a community to support using the engine
153 to make new things.
155 ** Source Engine
157 The Source Engine evolved from the Quake II and Quake I engines and is
158 used by Valve in the Half-Life series of games. The physics simulation
159 in the Source Engine is quite accurate and probably the best out of
160 all the engines I investigated. There is also an extensive community
161 actively working with the engine. However, applications that use the
162 Source Engine must be written in C++, the code is not open, it only
163 runs on Windows, and the tools that come with the SDK to handle models
164 and textures are complicated and awkward to use.
166 ** jMonkeyEngine
168 jMonkeyEngine is a new library for creating games in Java. It uses
169 OpenGL to render to the screen and uses screengraphs to avoid drawing
170 things that do not appear on the screen. It has an active community
171 and several games in the pipeline. The engine was not built to serve
172 any particular game but is instead meant to be used for any 3D
173 game. After experimenting with each of these three engines and a few
174 others for about 2 months I settled on jMonkeyEngine. I chose it
175 because it had the most features out of all the open projects I looked
176 at, and because I could then write my code in Clojure, an
177 implementation of LISP that runs on the JVM.
179 * Setup
181 First, I checked out the source to jMonkeyEngine:
183 #+srcname: checkout
184 #+begin_src sh :results verbatim
185 svn checkout http://jmonkeyengine.googlecode.com/svn/trunk/engine jme3
186 #+end_src
188 #+results: checkout
189 : Checked out revision 7975.
192 Building jMonkeyEngine is easy enough:
194 #+srcname: build
195 #+begin_src sh :results verbatim
196 cd jme3
197 ant jar | tail -n 2
198 #+end_src
200 #+results: build
201 : BUILD SUCCESSFUL
202 : Total time: 15 seconds
205 Also build the javadoc:
207 #+srcname: javadoc
208 #+begin_src sh :results verbatim
209 cd jme3
210 ant javadoc | tail -n 2
211 #+end_src
213 #+results: javadoc
214 : BUILD SUCCESSFUL
215 : Total time: 12 seconds
217 Now, move the jars from the compilation into the project's lib folder.
219 #+srcname: move-jars
220 #+begin_src sh :results verbatim
221 mkdir -p lib
222 mkdir -p src
223 cp jme3/dist/jMonkeyEngine3.jar lib/
224 cp jme3/dist/lib/* lib/
225 ls lib
226 #+end_src
228 #+results: move-jars
229 #+begin_example
230 eventbus-1.4.jar
231 jbullet.jar
232 jheora-jst-debug-0.6.0.jar
233 jinput.jar
234 jME3-jbullet.jar
235 jME3-lwjgl-natives.jar
236 jME3-testdata.jar
237 jME3-test.jar
238 jMonkeyEngine3.jar
239 j-ogg-oggd.jar
240 j-ogg-vorbisd.jar
241 lwjgl.jar
242 nifty-1.3.jar
243 nifty-default-controls-1.3.jar
244 nifty-examples-1.3.jar
245 nifty-lwjgl-renderer-1.3.jar
246 nifty-openal-soundsystem-1.0.jar
247 nifty-style-black-1.3.jar
248 nifty-style-grey-1.0.jar
249 noise-0.0.1-SNAPSHOT.jar
250 stack-alloc.jar
251 vecmath.jar
252 xmlpull-xpp3-1.1.4c.jar
253 #+end_example
255 It's good to create a =assets= directory in the style that the
256 =AssetManager= will like.
258 #+srcname: create-assets
259 #+begin_src sh :results verbatim
260 mkdir -p assets
261 mkdir -p assets/Interface
262 mkdir -p assets/Materials
263 mkdir -p assets/MatDefs
264 mkdir -p assets/Models
265 mkdir -p assets/Scenes
266 mkdir -p assets/Shaders
267 mkdir -p assets/Sounds
268 mkdir -p assets/Textures
269 tree -L 1 assets
270 #+end_src
272 #+results: create-assets
273 #+begin_example
274 assets
275 |-- Interface
276 |-- MatDefs
277 |-- Materials
278 |-- Models
279 |-- Scenes
280 |-- Shaders
281 |-- Sounds
282 `-- Textures
284 8 directories, 0 files
285 #+end_example
288 The java classpath should have all the jars contained in the =lib=
289 directory as well as the src directory.
291 For example, here is the file I use to run my REPL for clojure.
293 #+include: "~/swank-all" src sh :exports code
295 The important thing here is that =cortex/lib/*=, =cortex/src=, and
296 =cortex/assets= appear on the classpath. (=cortex= is the base
297 directory of this project.)
299 #+srcname: pwd
300 #+begin_src sh
301 pwd
302 #+end_src
304 #+results: pwd
305 : /home/r/cortex
308 * Simulation Base
310 ** Imports
311 First, I'll import jme core classes.
312 #+srcname: import
313 #+begin_src clojure :results silent
314 (ns cortex.import
315 (:require swank.util.class-browse))
317 (defn import-jme3 []
318 (import '[com.jme3.system AppSettings JmeSystem])
319 (import '[com.jme3.app Application SimpleApplication])
320 (import 'com.jme3.material.Material)
321 (import '[com.jme3.math Vector3f ColorRGBA Quaternion Transform])
322 (import '[com.jme3.scene Node Geometry])
323 (import '[com.jme3.scene.shape Box Sphere Sphere$TextureMode])
324 (import 'com.jme3.font.BitmapText)
325 (import '[com.jme3.input KeyInput InputManager])
326 (import '[com.jme3.input.controls
327 ActionListener AnalogListener KeyTrigger MouseButtonTrigger])
328 (import '[com.jme3.asset AssetManager DesktopAssetManager] )
329 (import '[com.jme3.asset.plugins HttpZipLocator ZipLocator])
330 (import '[com.jme3.light PointLight DirectionalLight])
331 (import '[com.jme3.animation AnimControl Skeleton Bone])
332 (import '[com.jme3.bullet.collision.shapes
333 MeshCollisionShape SphereCollisionShape BoxCollisionShape])
334 (import 'com.jme3.renderer.queue.RenderQueue$ShadowMode)
335 (import 'jme3test.TestChooser)
336 (import '[com.jme3.bullet PhysicsTickListener PhysicsSpace])
337 (import '[com.jme3.bullet.joints SixDofJoint HingeJoint
338 SliderJoint Point2PointJoint ConeJoint]))
341 (defmacro permissive-import* [class-symbol]
342 `(try
343 (import ~class-symbol)
344 (catch Exception e#
345 (println "can't import " ~class-symbol))))
347 (defn permissive-import [class-symbol]
348 (eval (list 'cortex.import/permissive-import* class-symbol)))
350 (defn selection-import [selection-fn]
351 (dorun
352 (map (comp permissive-import symbol)
353 (filter selection-fn
354 (map :name
355 swank.util.class-browse/available-classes)))))
357 (defn mega-import-jme3
358 "ALL the jme classes. For REPL use."
359 []
360 (selection-import
361 #(and
362 (.startsWith % "com.jme3.")
363 ;; Don't import the Lwjgl stuff since it can throw exceptions
364 ;; upon being loaded.
365 (not (re-matches #".*Lwjgl.*" %)))))
366 #+end_src
368 The =mega-import-jme3= is quite usefull for debugging purposes since
369 it allows completion for almost all of JME's classes
371 ** Simplification
372 *** World
374 It is comvienent to wrap the JME elements that deal with creating a
375 world, creation of basic objects, and Keyboard input with a nicer
376 interface (at least for my purposes).
378 #+srcname: world-inputs
379 #+begin_src clojure :results silent
380 (ns cortex.world)
381 (require 'cortex.import)
382 (use 'clojure.contrib.def)
383 (rlm.rlm-commands/help)
384 (cortex.import/mega-import-jme3)
386 (defvar *app-settings*
387 (doto (AppSettings. true)
388 (.setFullscreen false)
389 (.setTitle "Aurellem.")
390 ;; disable 32 bit stuff for now
391 (.setAudioRenderer "Send")
392 )
393 "These settings control how the game is displayed on the screen for
394 debugging purposes. Use binding forms to change this if desired.
395 Full-screen mode does not work on some computers.")
397 (defn asset-manager
398 "returns a new, configured assetManager" []
399 (JmeSystem/newAssetManager
400 (.getResource
401 (.getContextClassLoader (Thread/currentThread))
402 "com/jme3/asset/Desktop.cfg")))
404 (defmacro no-exceptions
405 "Sweet relief like I never knew."
406 [& forms]
407 `(try ~@forms (catch Exception e# (.printStackTrace e#))))
409 (defn thread-exception-removal []
410 (println "removing exceptions from " (Thread/currentThread))
411 (.setUncaughtExceptionHandler
412 (Thread/currentThread)
413 (proxy [Thread$UncaughtExceptionHandler] []
414 (uncaughtException
415 [thread thrown]
416 (println "uncaught-exception thrown in " thread)
417 (println (.getMessage thrown))))))
419 (def println-repl (bound-fn [& args] (apply println args)))
421 (use '[pokemon [lpsolve :only [constant-map]]])
423 (defn no-op [& _])
425 (defn all-keys
426 "Construct a map of strings representing all the manual inputs from
427 either the keyboard or mouse."
428 []
429 (let [inputs (constant-map KeyInput)]
430 (assoc
431 (zipmap (map (fn [field]
432 (.toLowerCase (re-gsub #"_" "-" field))) (vals inputs))
433 (map (fn [val] (KeyTrigger. val)) (keys inputs)))
434 ;;explicitly add mouse controls
435 "mouse-left" (MouseButtonTrigger. 0)
436 "mouse-middle" (MouseButtonTrigger. 2)
437 "mouse-right" (MouseButtonTrigger. 1))))
439 (defn initialize-inputs
440 "more java-interop cruft to establish keybindings for a particular virtual world"
441 [game input-manager key-map]
442 (doall (map (fn [[name trigger]]
443 (.addMapping ^InputManager input-manager
444 name (into-array (class trigger) [trigger]))) key-map))
445 (doall (map (fn [name]
446 (.addListener ^InputManager input-manager game
447 (into-array String [name]))) (keys key-map))))
449 #+end_src
451 These functions are all for debug controlling of the world through
452 keyboard and mouse.
454 We reuse =constant-map= from =pokemon.lpsolve= to get the numerical
455 values for all the keys defined in the =KeyInput= class. The
456 documentation for =constant-map= is:
458 #+begin_src clojure :results output
459 (doc pokemon.lpsolve/constant-map)
460 #+end_src
462 #+results:
463 : -------------------------
464 : pokemon.lpsolve/constant-map
465 : ([class])
466 : Takes a class and creates a map of the static constant integer
467 : fields with their names. This helps with C wrappers where they have
468 : just defined a bunch of integer constants instead of enums
471 Then, =all-keys= converts the constant names like =KEY_J= to the more
472 clojure-like =key-j=, and returns a map from these keys to
473 jMonkeyEngine KeyTrigger objects, the use of which will soon become
474 apparent. =all-keys= also adds the three mouse button controls to the
475 map.
477 #+srcname: world
478 #+begin_src clojure :results silent
479 (in-ns 'cortex.world)
481 (defn traverse
482 "apply f to every non-node, deeply"
483 [f node]
484 (if (isa? (class node) Node)
485 (dorun (map (partial traverse f) (.getChildren node)))
486 (f node)))
488 (def gravity (Vector3f. 0 -9.81 0))
490 (defn world
491 [root-node key-map setup-fn update-fn]
492 (let [physics-manager (BulletAppState.)
493 shadow-renderer (BasicShadowRenderer. (asset-manager) (int 256))
494 ;;maybe use a better shadow renderer someday!
495 ;;shadow-renderer (PssmShadowRenderer. (asset-manager) 256 1)
496 ]
497 (doto
498 (proxy [SimpleApplication ActionListener] []
499 (simpleInitApp
500 []
501 (no-exceptions
502 (.setTimer this (IsoTimer. 60))
503 ;; Create key-map.
504 (.setFrustumFar (.getCamera this) 300)
505 (initialize-inputs this (.getInputManager this) (all-keys))
506 ;; Don't take control of the mouse
507 (org.lwjgl.input.Mouse/setGrabbed false)
508 ;; add all objects to the world
509 (.attachChild (.getRootNode this) root-node)
510 ;; enable physics
511 ;; add a physics manager
512 (.attach (.getStateManager this) physics-manager)
513 (.setGravity (.getPhysicsSpace physics-manager) gravity)
516 ;; go through every object and add it to the physics manager
517 ;; if relavant.
518 (traverse (fn [geom]
519 (dorun
520 (for [n (range (.getNumControls geom))]
521 (do
522 (println-repl "adding control " (.getControl geom n))
523 (.add (.getPhysicsSpace physics-manager)
524 (.getControl geom n))))))
525 (.getRootNode this))
526 ;;(.addAll (.getPhysicsSpace physics-manager) (.getRootNode this))
528 (setup-fn this)
529 (.setDirection shadow-renderer
530 (.normalizeLocal (Vector3f. -1 -1 -1)))
531 (.addProcessor (.getViewPort this) shadow-renderer)
532 (.setShadowMode (.getRootNode this) RenderQueue$ShadowMode/Off)
533 ))
534 (simpleUpdate
535 [tpf]
536 (no-exceptions
537 (update-fn this tpf)))
538 (onAction
539 [binding value tpf]
540 ;; whenever a key is pressed, call the function returned from
541 ;; key-map.
542 (no-exceptions
543 (if-let [react (key-map binding)]
544 (react this value)))))
545 ;; don't show a menu to change options.
547 (.setShowSettings false)
548 (.setPauseOnLostFocus false)
549 (.setSettings *app-settings*))))
551 (defn apply-map
552 "Like apply, but works for maps and functions that expect an implicit map
553 and nothing else as in (fn [& {}]).
554 ------- Example -------
555 (defn jjj [& {:keys [www] :or {www \"oh yeah\"} :as env}] (println www))
556 (apply-map jjj {:www \"whatever\"})
557 -->\"whatever\""
558 [fn m]
559 (apply fn (reduce #(into %1 %2) [] m)))
561 #+end_src
564 =world= is the most important function here.
565 *** TODO more documentation
567 #+srcname: world-shapes
568 #+begin_src clojure :results silent
569 (in-ns 'cortex.world)
570 (defrecord shape-description
571 [name
572 color
573 mass
574 friction
575 texture
576 material
577 position
578 rotation
579 shape
580 physical?])
582 (def base-shape
583 (shape-description.
584 "default-shape"
585 false
586 ;;ColorRGBA/Blue
587 1.0 ;; mass
588 1.0 ;; friction
589 ;; texture
590 "Textures/Terrain/BrickWall/BrickWall.jpg"
591 ;; material
592 "Common/MatDefs/Misc/Unshaded.j3md"
593 Vector3f/ZERO
594 Quaternion/IDENTITY
595 (Box. Vector3f/ZERO 0.5 0.5 0.5)
596 true))
598 (defn make-shape
599 [#^shape-description d]
600 (let [mat (Material. (asset-manager) (:material d))
601 geom (Geometry. (:name d) (:shape d))]
602 (if (:texture d)
603 (let [key (TextureKey. (:texture d))]
604 (.setGenerateMips key true)
605 (.setTexture mat "ColorMap" (.loadTexture (asset-manager) key))))
606 (if (:color d) (.setColor mat "Color" (:color d)))
607 (.setMaterial geom mat)
608 (if-let [rotation (:rotation d)] (.rotate geom rotation))
609 (.setLocalTranslation geom (:position d))
610 (if (:physical? d)
611 (let [impact-shape (doto (GImpactCollisionShape. (.getMesh geom)) (.setMargin 0))
612 physics-control (RigidBodyControl.
613 impact-shape
614 (float (:mass d)))]
615 (.createJmeMesh impact-shape)
616 (.addControl geom physics-control)
617 ;;(.setSleepingThresholds physics-control (float 0) (float 0))
618 (.setFriction physics-control (:friction d))))
619 ;;the default is to keep this node in the physics engine forever.
620 ;;these commands must come after the control is added to the geometry.
621 ;;
622 geom))
624 (defn box
625 ([l w h & {:as options}]
626 (let [options (merge base-shape options)]
627 (make-shape (assoc options
628 :shape (Box. l w h)))))
629 ([] (box 0.5 0.5 0.5)))
631 (defn sphere
632 ([r & {:as options}]
633 (let [options (merge base-shape options)]
634 (make-shape (assoc options
635 :shape (Sphere. 32 32 (float r))))))
636 ([] (sphere 0.5)))
638 (defn add-element [game node]
639 (.addAll
640 (.getPhysicsSpace
641 (.getState
642 (.getStateManager game)
643 BulletAppState))
644 node)
645 (.attachChild (.getRootNode game) node))
647 (defn set-gravity*
648 [game gravity]
649 (traverse
650 (fn [geom]
651 (if-let
652 [control (.getControl geom RigidBodyControl)]
653 (do
654 (.setGravity control gravity)
655 (.applyImpulse control Vector3f/ZERO Vector3f/ZERO)
656 )))
657 (.getRootNode game)))
659 #+end_src
661 These are convienence functions for creating JME objects and
662 manipulating a world.
664 #+srcname: world-view
665 #+begin_src clojure :results silent
666 (in-ns 'cortex.world)
668 (defprotocol Viewable
669 (view [something]))
671 (extend-type com.jme3.scene.Geometry
672 Viewable
673 (view [geo]
674 (view (doto (Node.)(.attachChild geo)))))
676 (extend-type com.jme3.scene.Node
677 Viewable
678 (view [node]
679 (.start
680 (world node
681 {}
682 (fn [world]
683 (.enableDebug
684 (.getPhysicsSpace
685 (.getState
686 (.getStateManager world)
687 BulletAppState))
688 (asset-manager))
689 (set-gravity* world Vector3f/ZERO)
690 ;; (set-gravity* world (Vector3f. 0 (float -0.4) 0))
691 (let [sun (doto (DirectionalLight.)
692 (.setDirection (.normalizeLocal (Vector3f. 1 0 -2)))
693 (.setColor ColorRGBA/White))]
694 (.addLight (.getRootNode world) sun)))
695 no-op))))
697 (defn position-camera [game]
698 (doto (.getCamera game)
699 (.setLocation (Vector3f. 0 6 6))
700 (.lookAt Vector3f/ZERO (Vector3f. 0 1 0))))
702 #+end_src
704 Here I make the =Viewable= protocol and extend it to JME's types. Now
705 hello-world can be written as easily as:
707 #+begin_src clojure :results silent
708 (cortex.world/view (cortex.world/box))
709 #+end_src
711 ** Hello
712 Here are the jmonkeyengine "Hello" programs translated to clojure.
713 *** Hello Simple App
714 Here is the hello world example for jme3 in clojure.
715 It's a more or less direct translation from the java source
716 from
717 http://jmonkeyengine.org/wiki/doku.php/jme3:beginner:hello_simpleapplication.
719 Of note is the fact that since we don't have access to the
720 =AssetManager= via extendig =SimpleApplication=, we have to build one
721 ourselves.
723 #+srcname: hello-simple-app
724 #+begin_src clojure :results silent
725 (ns hello.hello-simple-app)
726 (require 'cortex.import)
727 (use 'clojure.contrib.def)
728 (rlm.rlm-commands/help)
729 (cortex.import/import-jme3)
730 (use 'cortex.world)
733 (def cube (Box. Vector3f/ZERO 1 1 1))
735 (def geom (Geometry. "Box" cube))
737 (def mat (Material. (asset-manager) "Common/MatDefs/Misc/Unshaded.j3md"))
739 (.setColor mat "Color" ColorRGBA/Blue)
741 (.setMaterial geom mat)
743 (defn simple-app []
744 (doto
745 (proxy [SimpleApplication] []
746 (simpleInitApp
747 []
748 ;; Don't take control of the mouse
749 (org.lwjgl.input.Mouse/setGrabbed false)
750 (.attachChild (.getRootNode this) geom)))
751 ;; don't show a menu to change options.
752 (.setShowSettings false)
753 (.setPauseOnLostFocus false)
754 (.setSettings *app-settings*)))
755 #+end_src
757 Running this program will begin a new jMonkeyEngine game which
758 displays a single blue cube.
760 #+begin_src clojure :exports code :results silent
761 (.start (hello.hello-simple-app/simple-app))
762 #+end_src
764 #+caption: the simplest JME game.
765 [[./images/simple-app.jpg]]
769 *** Hello Physics
770 From http://jmonkeyengine.org/wiki/doku.php/jme3:beginner:hello_physics
772 #+srcname: brick-wall-header
773 #+begin_src clojure :results silent
774 (ns hello.brick-wall)
775 (require 'cortex.import)
776 (use 'clojure.contrib.def)
777 (rlm.rlm-commands/help)
778 (cortex.import/mega-import-jme3)
779 (use '[pokemon [lpsolve :only [constant-map]]])
780 (use 'cortex.world)
781 #+end_src
783 #+srcname: brick-wall-body
784 #+begin_src clojure :results silent
785 (in-ns 'hello.brick-wall)
787 (defn floor
788 "make a sturdy, unmovable physical floor"
789 []
790 (box 20 1 20 :mass 0 :color false :position (Vector3f. 0 -2 0)))
792 (def brick-length 0.48)
793 (def brick-width 0.24)
794 (def brick-height 0.12)
797 (defn brick* [position]
798 (doto (box brick-length brick-height brick-width
799 :position position :name "brick"
800 :material "Common/MatDefs/Misc/Unshaded.j3md"
801 :texture "Textures/Terrain/BrickWall/BrickWall.jpg"
802 :mass 36)
803 (->
804 (.getMesh)
805 (.scaleTextureCoordinates (Vector2f. 1 0.5)))
806 ;;(.setShadowMode RenderQueue$ShadowMode/CastAndReceive)
807 )
808 )
810 (defn inception-brick-wall
811 "construct a physical brick wall"
812 []
813 (let [node (Node. "brick-wall")]
814 (dorun
815 (map (comp #(.attachChild node %) brick*)
816 (for
817 [x (range 15)
818 y (range 10)
819 z (range 1)]
820 (Vector3f.
821 (* brick-length x 1.03)
822 (* brick-width y y 10)
823 (* brick-height z)))))
824 node))
826 (defn gravity-toggle
827 [new-value]
828 (fn [game value]
829 (println-repl "set gravity to " new-value)
830 (if value
831 (set-gravity* game new-value)
832 (set-gravity* game gravity))))
834 (defn fire-cannon-ball []
835 (fn [game value]
836 (if (not value)
837 (let [camera (.getCamera game)
838 cannon-ball
839 (sphere 0.7
840 :material "Common/MatDefs/Misc/Unshaded.j3md"
841 :texture "Textures/PokeCopper.jpg"
842 :position
843 (.add (.getLocation camera)
844 (.mult (.getDirection camera) (float 1)))
845 :mass 3)] ;200 0.05
846 (.setShadowMode cannon-ball RenderQueue$ShadowMode/CastAndReceive)
847 (.setLinearVelocity
848 (.getControl cannon-ball RigidBodyControl)
849 (.mult (.getDirection camera) (float 50))) ;50
850 (add-element game cannon-ball)))))
852 (defn floor* []
853 (doto (box 10 0.1 5 :name "floor" ;10 0.1 5 ; 240 0.1 240
854 :material "Common/MatDefs/Misc/Unshaded.j3md"
855 :texture "Textures/Terrain/Pond/Pond.png"
856 :position (Vector3f. 0 -0.1 0 )
857 :mass 0)
858 (->
859 (.getMesh)
860 (.scaleTextureCoordinates (Vector2f. 3 6)));64 64
861 (->
862 (.getMaterial)
863 (.getTextureParam "ColorMap")
864 (.getTextureValue)
865 (.setWrap Texture$WrapMode/Repeat))
866 (.setShadowMode RenderQueue$ShadowMode/Receive)
867 ))
869 (defn brick-wall* []
870 (let [node (Node. "brick-wall")]
871 (dorun
872 (map
873 (comp #(.attachChild node %) brick*)
874 (for [y (range 15)
875 x (range 4)
876 z (range 1)]
877 (Vector3f.
878 (+ (* 2 x brick-length)
879 (if (even? (+ y z))
880 (/ brick-length 4) (/ brick-length -4)))
881 (+ (* brick-height (inc (* 2 y))))
882 (* 2 z brick-width) ))))
883 (.setShadowMode node RenderQueue$ShadowMode/CastAndReceive)
884 node))
886 (defn brick-wall-game-run []
887 (doto
888 (world
889 (doto (Node.) (.attachChild (floor*))
890 (.attachChild (brick-wall*))
891 )
892 {"key-i" (gravity-toggle (Vector3f. 0 0 -9.81))
893 "key-m" (gravity-toggle (Vector3f. 0 0 9.81))
894 "key-l" (gravity-toggle (Vector3f. 9.81 0 0))
895 "key-j" (gravity-toggle (Vector3f. -9.81 0 0))
896 "key-k" (gravity-toggle Vector3f/ZERO)
897 "key-u" (gravity-toggle (Vector3f. 0 9.81 0))
898 "key-o" (gravity-toggle (Vector3f. 0 -9.81 0))
899 "key-f" (fn[game value]
900 (if (not value) (add-element game (brick-wall*))))
901 "key-return" (fire-cannon-ball)}
902 position-camera
903 (fn [& _]))
904 (.start)))
905 #+end_src
907 #+begin_src clojure :results silent
908 (hello.brick-wall/brick-wall-game-run)
909 #+end_src
911 #+caption: the brick wall standing
912 [[./images/brick-wall-standing.jpg]]
914 #+caption: the brick wall after it has been knocked over by a "pok\eacute{}ball"
915 [[./images/brick-wall-knocked-down.jpg]]
917 *** Other Brick Games
918 #+srcname: other-games
919 #+begin_src clojure :results silent
920 (ns cortex.other-games
921 {:author "Dylan Holmes"})
922 (use 'cortex.world)
923 (use 'hello.brick-wall)
924 (use 'cortex.import)
925 (cortex.import/mega-import-jme3)
927 (defn scad [position]
928 (doto (box 0.1 0.1 0.1
929 :position position :name "brick"
930 :material "Common/MatDefs/Misc/Unshaded.j3md"
931 :texture "Textures/Terrain/BrickWall/BrickWall.jpg"
932 :mass 20)
933 (->
934 (.getMesh)
935 (.scaleTextureCoordinates (Vector2f. 1 0.5))
936 )
937 (-> (.getControl RigidBodyControl)
938 (.setLinearVelocity (Vector3f. 0 100 0))
939 )
941 ;;(.setShadowMode RenderQueue$ShadowMode/Cast)
942 ))
945 (defn shrapnel []
946 (let [node (Node. "explosion-day")]
947 (dorun
948 (map
949 (comp #(.attachChild node %) scad)
950 (for [y (range 15)
951 x (range 4)
952 z (range 1)]
953 (Vector3f.
954 (+ (* 2 x brick-height)
955 (if (even? (+ y z)) (/ brick-height 4) (/ brick-height -4)))
956 (+ (* brick-height (inc (* 2 y))))
957 (* 2 z brick-height) ))))
958 node))
961 (def domino-height 0.48)
962 (def domino-thickness 0.12)
963 (def domino-width 0.24)
965 (def domino-thickness 0.05)
966 (def domino-width 0.5)
967 (def domino-height 1)
969 (defn domino
970 ([position]
971 (domino position (Quaternion/IDENTITY)))
972 ([position rotation]
973 (doto (box domino-width domino-height domino-thickness
974 :position position :name "domino"
975 :material "Common/MatDefs/Misc/Unshaded.j3md"
976 :texture "Textures/Terrain/BrickWall/BrickWall.jpg"
977 :mass 1
978 :rotation rotation)
979 (.setShadowMode RenderQueue$ShadowMode/CastAndReceive)
980 )))
983 (defn domino-row []
984 (let [node (Node. "domino-row")]
985 (dorun
986 (map
987 (comp #(.attachChild node %) domino)
988 (for [
989 z (range 10)
990 x (range 5)
991 ]
992 (Vector3f.
993 (+ (* z domino-width) (* x 5 domino-width))
994 (/ domino-height 1)
995 (* -5.5 domino-thickness z) ))))
997 node))
999 (defn domino-cycle []
1000 (let [node (Node. "domino-cycle")]
1001 (dorun
1002 (map
1003 (comp #(.attachChild node %) (partial apply domino) )
1004 (for [n (range 720)]
1005 (let [space (* domino-height 5.5)
1006 r (fn[n] (* (+ n 3) domino-width 0.5))
1007 t (fn[n] (reduce
1009 (map
1010 (fn dt[n] (/ space (* 2 (Math/PI) (r n))))
1011 (range n))))
1012 t (t n)
1013 r (r n)
1014 ct (Math/cos t)
1015 st (Math/sin t)
1017 (list
1018 (Vector3f.
1019 (* -1 r st)
1020 (/ domino-height 1)
1021 (* r ct))
1022 (.fromAngleAxis (Quaternion.)
1023 (- (/ 3.1415926 2) t) (Vector3f. 0 1 0))
1024 )))
1025 ))
1026 node))
1029 (defn domino-game-run []
1030 (doto
1031 (world
1032 (doto (Node.) (.attachChild (floor*))
1034 {"key-i" (gravity-toggle (Vector3f. 0 0 -9.81))
1035 "key-m" (gravity-toggle (Vector3f. 0 0 9.81))
1036 "key-l" (gravity-toggle (Vector3f. 9.81 0 0))
1037 "key-j" (gravity-toggle (Vector3f. -9.81 0 0))
1038 "key-k" (gravity-toggle (Vector3f. 0 9.81 0) )
1039 "key-u" (fn[g v] ((gravity-toggle (Vector3f. 0 -0 0)) g true))
1040 "key-o" (gravity-toggle (Vector3f. 0 -9.81 0))
1042 "key-space"
1043 (fn[game value]
1045 (if (not value)
1046 (let [d (domino (Vector3f. 0 (/ domino-height 0.25) 0)
1047 (.fromAngleAxis (Quaternion.)
1048 (/ Math/PI 2) (Vector3f. 0 1 0)))]
1049 (add-element game d))))
1050 "key-f"
1051 (fn[game value](if (not value) (add-element game (domino-cycle))))
1052 "key-return" (fire-cannon-ball)}
1053 position-camera
1054 (fn [& _]))
1055 (.start)))
1056 #+end_src
1058 #+begin_src clojure :results silent
1059 (cortex.other-games/domino-game-run)
1060 #+end_src
1062 #+caption: floating dominos
1063 [[./images/dominos.jpg]]
1065 *** Hello Loop
1066 #+srcname: hello-loop
1067 #+begin_src clojure :results silent
1068 (ns hello.loop)
1069 (use 'cortex.world)
1070 (use 'cortex.import)
1071 (cortex.import/mega-import-jme3)
1072 (rlm.rlm-commands/help)
1074 (defn blue-cube []
1075 (box 1 1 1
1076 :color ColorRGBA/Blue
1077 :texture false
1078 :material "Common/MatDefs/Misc/Unshaded.j3md"
1079 :name "blue-cube"
1080 :physical? false))
1082 (defn blue-cube-game []
1083 (let [cube (blue-cube)
1084 root (doto (Node.) (.attachChild cube))]
1085 (world root
1086 {}
1087 no-op
1088 (fn [game tpf]
1089 (.rotate cube 0.0 (* 2 tpf) 0.0)))))
1090 #+end_src
1092 *** Hello Collision
1094 #+srcname: hello-collision
1095 #+begin_src clojure :results silent
1096 (ns hello.collision)
1097 (use 'cortex.world)
1098 (use 'cortex.import)
1099 (use 'clojure.contrib.def)
1102 (cortex.import/mega-import-jme3)
1103 (rlm.rlm-commands/help)
1104 (use '[hello [brick-wall :only [fire-cannon-ball brick-wall*]]])
1107 (defn environment []
1108 (let
1109 [scene-model
1110 (doto
1111 (.loadModel
1112 (doto (asset-manager)
1113 (.registerLocator
1114 "/home/r/cortex/assets/zips/town.zip" ZipLocator))
1115 "main.scene")
1116 (.setLocalScale (float 2.0)))
1117 collision-shape
1118 (CollisionShapeFactory/createMeshShape #^Node scene-model)
1119 landscape (RigidBodyControl. collision-shape 0)]
1120 (.setShadowMode scene-model RenderQueue$ShadowMode/CastAndReceive)
1121 (.addControl scene-model landscape)
1122 scene-model))
1124 (defn player-fn []
1125 (doto
1126 (CharacterControl.
1127 (CapsuleCollisionShape. (float 1.5) (float 6)(float 1))
1128 (float 0.05))
1129 (.setJumpSpeed 20)
1130 (.setFallSpeed 30)
1131 (.setGravity 30) ;30
1132 (.setPhysicsLocation (Vector3f. 0 10 0))))
1134 (defn lights []
1135 [(doto (AmbientLight.) (.setColor (.mult (ColorRGBA. 1 1 1 1) (float 1))))
1136 (doto (AmbientLight.) (.setColor (.mult (ColorRGBA. 1 0.7 0 1) (float 1))))
1137 (doto (DirectionalLight.)
1138 (.setColor (.mult ColorRGBA/White (float 0.9) ))
1139 (.setDirection (.normalizeLocal (Vector3f. 2.8 -28 2.8))))])
1141 (defn night-lights []
1142 [(doto (AmbientLight.) (.setColor (.mult (ColorRGBA. 0.275 0.467 0.784 1) (float 0.3))))
1143 (doto (DirectionalLight.)
1144 (.setColor (.mult ColorRGBA/White (float 0.2) ))
1145 (.setDirection (.normalizeLocal (Vector3f. 2.8 -28 2.8))))])
1147 (def player (atom (player-fn)))
1149 (defn setup-fn [game]
1150 (dorun (map #(.addLight (.getRootNode game) %) (lights)))
1151 ;; set the color of the sky
1152 (.setBackgroundColor (.getViewPort game) (ColorRGBA. 0.3 0.4 0.9 1))
1153 ;(.setBackgroundColor (.getViewPort game) (ColorRGBA. 0 0 0 1)
1154 (doto (.getFlyByCamera game)
1155 (.setMoveSpeed (float 100))
1156 (.setRotationSpeed 3))
1157 (.add
1158 (.getPhysicsSpace
1159 (.getState (.getStateManager game) BulletAppState))
1160 @player)
1162 (doto (Node.) (.attachChild (.getRootNode game))
1163 (.attachChild (brick-wall*))
1169 (def walking-up? (atom false))
1170 (def walking-down? (atom false))
1171 (def walking-left? (atom false))
1172 (def walking-right? (atom false))
1174 (defn set-walk [walk-atom game value]
1175 ;;(println-repl "setting stuff to " value)
1176 (reset! walk-atom value))
1178 (defn responses []
1179 {"key-w" (partial set-walk walking-up?)
1180 "key-d" (partial set-walk walking-right?)
1181 "key-s" (partial set-walk walking-down?)
1182 "key-a" (partial set-walk walking-left?)
1183 "key-return" (fire-cannon-ball)
1184 "key-space" (fn [game value] (.jump @player))
1185 })
1187 (defn update-fn
1188 [game tpf]
1189 (let [camera (.getCamera game)
1190 cam-dir (.multLocal
1191 (.clone
1192 (.getDirection camera)) (float 0.6))
1193 cam-left (.multLocal
1194 (.clone
1195 (.getLeft camera)) (float 0.4))
1196 walk-direction (Vector3f. 0 0 0)]
1198 (cond
1199 @walking-up? (.addLocal walk-direction cam-dir)
1200 @walking-right? (.addLocal walk-direction (.negate cam-left))
1201 @walking-down? (.addLocal walk-direction (.negate cam-dir))
1202 @walking-left? (.addLocal walk-direction cam-left))
1203 (.setWalkDirection @player walk-direction)
1204 (.setLocation camera (.getPhysicsLocation @player))))
1206 (defn run-game []
1207 (.start
1208 (world (environment)
1209 (responses)
1210 setup-fn
1211 update-fn)))
1212 #+end_src
1214 *** Hello Terrain
1215 #+srcname: hello-terrain
1216 #+begin_src clojure :results silent
1217 (ns hello.terrain)
1218 (use 'cortex.world)
1219 (use 'cortex.import)
1220 (use 'clojure.contrib.def)
1221 (import jme3tools.converters.ImageToAwt)
1224 (cortex.import/mega-import-jme3)
1225 (rlm.rlm-commands/help)
1226 (use '[hello [brick-wall :only [fire-cannon-ball brick-wall*]]])
1229 (defn setup-fn [type game]
1230 (.setMoveSpeed (.getFlyByCamera game) 50)
1231 (.setFrustumFar (.getCamera game) 10000)
1232 (let [env (environment type)
1233 cameras [(.getCamera game)]
1234 control (TerrainLodControl. env cameras)]
1235 ;;(.addControl env control)
1236 (.attachChild (.getRootNode game) env)))
1238 (defn environment [type]
1239 (let
1240 [mat_terrain
1241 (Material. (asset-manager) "Common/MatDefs/Terrain/Terrain.j3md")
1242 grass (.loadTexture (asset-manager) "Textures/Terrain/splat/grass.jpg")
1243 dirt (.loadTexture (asset-manager) "Textures/Terrain/splat/dirt.jpg")
1244 rock (.loadTexture (asset-manager) "Textures/Terrain/splat/road.jpg")
1245 heightmap-image (.loadTexture (asset-manager)
1246 ({:mountain "Textures/Terrain/splat/mountains512.png"
1247 :fortress "Textures/Terrain/splat/fortress512.png"
1248 }type))
1249 heightmap (ImageBasedHeightMap.
1250 (ImageToAwt/convert (.getImage heightmap-image) false true 0))
1251 terrain (do (.load heightmap)
1252 (TerrainQuad. "my terrain" 65 513 (.getHeightMap heightmap)))
1255 (dorun (map #(.setWrap % Texture$WrapMode/Repeat)
1256 [grass dirt rock]))
1258 (doto mat_terrain
1259 (.setTexture "Tex1" grass)
1260 (.setFloat "Tex1Scale" (float 64))
1262 (.setTexture "Tex2" dirt)
1263 (.setFloat "Tex2Scale" (float 32))
1265 (.setTexture "Tex3" rock)
1266 (.setFloat "Tex3Scale" (float 128))
1268 (.setTexture "Alpha"
1269 (.loadTexture
1270 (asset-manager)
1271 ({:mountain "Textures/Terrain/splat/alphamap.png"
1272 :fortress "Textures/Terrain/splat/alphamap2.png"} type))))
1274 (doto terrain
1275 (.setMaterial mat_terrain)
1276 (.setLocalTranslation 0 -100 0)
1277 (.setLocalScale 2 1 2))))
1281 (defn run-terrain-game [type]
1282 (.start
1283 (world
1284 (Node.)
1285 {}
1286 (partial setup-fn type)
1287 no-op)))
1288 #+end_src
1292 #+srcname: hello-animation
1293 #+begin_src clojure :results silent
1294 (ns hello.animation)
1295 (use 'cortex.world)
1296 (use 'cortex.import)
1297 (use 'clojure.contrib.def)
1298 (cortex.import/mega-import-jme3)
1299 (rlm.rlm-commands/help)
1300 (use '[hello [collision :only [lights]]])
1302 (defn stand
1303 [channel]
1304 (doto channel
1305 (.setAnim "stand" (float 0.5))
1306 (.setLoopMode LoopMode/DontLoop)
1307 (.setSpeed (float 1))))
1309 (defn anim-listener []
1310 (proxy [AnimEventListener] []
1311 (onAnimChange
1312 [control channel animation-name]
1313 (println-repl "RLM --- onAnimChange"))
1314 (onAnimCycleDone
1315 [control channel animation-name]
1316 (if (= animation-name "Walk")
1317 (stand channel)
1318 ))))
1320 (defn setup-fn [channel game]
1321 (dorun (map #(.addLight (.getRootNode game) %) (lights)))
1322 ;; set the color of the sky
1323 (.setBackgroundColor (.getViewPort game) (ColorRGBA. 0.3 0.4 0.9 1))
1324 ;(.setBackgroundColor (.getViewPort game) (ColorRGBA. 0 0 0 1)
1325 (.setAnim channel "stand")
1326 (doto (.getFlyByCamera game)
1327 (.setMoveSpeed (float 10))
1328 (.setRotationSpeed 1)))
1330 (defn walk [channel]
1331 (println-repl "zzz")
1332 (doto channel
1333 (.setAnim "Walk" (float 0.5))
1334 (.setLoopMode LoopMode/Loop)))
1337 (defn key-map [channel]
1338 {"key-space" (fn [game value]
1339 (if (not value)
1340 (walk channel)))})
1342 (defn player []
1343 (let [model (.loadModel (asset-manager) "Models/Oto/Oto.mesh.xml")
1344 control (.getControl model AnimControl)]
1345 (.setLocalScale model (float 0.5))
1346 (.clearListeners control)
1347 (.addListener control (anim-control))
1348 model))
1352 (defn run-anim-game []
1353 (let [ninja (player)
1354 control (.getControl ninja AnimControl)
1355 channel (.createChannel control)]
1356 (.start
1357 (world
1358 ninja
1359 (key-map channel)
1360 (partial setup-fn channel)
1361 no-op))))
1362 #+end_src
1364 *** Hello Materials
1365 #+srcname: material
1366 #+begin_src clojure :results silent
1367 (ns hello.material)
1368 (use 'cortex.world)
1369 (use 'cortex.import)
1370 (use 'clojure.contrib.def)
1371 (cortex.import/mega-import-jme3)
1372 (rlm.rlm-commands/help)
1374 (defn simple-cube []
1375 (box 1 1 1
1376 :position (Vector3f. -3 1.1 0)
1377 :material "Common/MatDefs/Misc/Unshaded.j3md"
1378 :texture "Interface/Logo/Monkey.jpg"
1379 :physical? false))
1381 (defn leaky-box []
1382 (box 1 1 1
1383 :position (Vector3f. 3 -1 0)
1384 :material "Common/MatDefs/Misc/ColoredTextured.j3md"
1385 :texture "Textures/ColoredTex/Monkey.png"
1386 :color (ColorRGBA. 1 0 1 1)
1387 :physical? false))
1389 (defn transparent-box []
1390 (doto
1391 (box 1 1 0.1
1392 :position Vector3f/ZERO
1393 :name "window frame"
1394 :material "Common/MatDefs/Misc/Unshaded.j3md"
1395 :texture "Textures/ColoredTex/Monkey.png"
1396 :physical? false)
1397 (-> (.getMaterial)
1398 (.getAdditionalRenderState)
1399 (.setBlendMode RenderState$BlendMode/Alpha))
1400 (.setQueueBucket RenderQueue$Bucket/Transparent)))
1402 (defn bumpy-sphere []
1403 (doto
1404 (sphere 2
1405 :position (Vector3f. 0 2 -2)
1406 :name "Shiny rock"
1407 :material "Common/MatDefs/Light/Lighting.j3md"
1408 :texture false
1409 :physical? false)
1410 (-> (.getMesh)
1411 (doto
1412 (.setTextureMode Sphere$TextureMode/Projected)
1413 (TangentBinormalGenerator/generate)))
1414 (-> (.getMaterial)
1415 (doto
1416 (.setTexture "DiffuseMap" (.loadTexture (asset-manager)
1417 "Textures/Terrain/Pond/Pond.png"))
1418 (.setTexture "NormalMap" (.loadTexture (asset-manager)
1419 "Textures/Terrain/Pond/Pond_normal.png"))
1420 (.setFloat "Shininess" (float 5))))
1421 (.rotate (float 1.6) 0 0)))
1424 (defn start-game []
1425 (.start
1426 (world
1427 (let [root (Node.)]
1428 (dorun (map #(.attachChild root %)
1429 [(simple-cube) (leaky-box) (transparent-box) (bumpy-sphere)]))
1430 root)
1431 {}
1432 (fn [world]
1433 (let [sun (doto (DirectionalLight.)
1434 (.setDirection (.normalizeLocal (Vector3f. 1 0 -2)))
1435 (.setColor ColorRGBA/White))]
1436 (.addLight (.getRootNode world) sun)))
1437 no-op
1438 )))
1439 #+end_src
1443 * The Body
1444 ** Eyes
1446 Ultimately I want to make creatures with eyes. Each eye can be
1447 independely moved and should see its own version of the world
1448 depending on where it is.
1449 #+srcname: eyes
1450 #+begin_src clojure
1451 (ns body.eye)
1452 (use 'cortex.world)
1453 (use 'cortex.import)
1454 (use 'clojure.contrib.def)
1455 (cortex.import/mega-import-jme3)
1456 (rlm.rlm-commands/help)
1457 (import java.nio.ByteBuffer)
1458 (import java.awt.image.BufferedImage)
1459 (import java.awt.Color)
1460 (import java.awt.Dimension)
1461 (import java.awt.Graphics)
1462 (import java.awt.Graphics2D)
1463 (import java.awt.event.WindowAdapter)
1464 (import java.awt.event.WindowEvent)
1465 (import java.awt.image.BufferedImage)
1466 (import java.nio.ByteBuffer)
1467 (import javax.swing.JFrame)
1468 (import javax.swing.JPanel)
1469 (import javax.swing.SwingUtilities)
1470 (import javax.swing.ImageIcon)
1471 (import javax.swing.JOptionPane)
1472 (import java.awt.image.ImageObserver)
1476 (defn scene-processor
1477 "deals with converting FrameBuffers to BufferedImages so
1478 that the continuation function can be defined only in terms
1479 of what it does with BufferedImages"
1480 [continuation]
1481 (let [byte-buffer (atom nil)
1482 renderer (atom nil)
1483 image (atom nil)]
1484 (proxy [SceneProcessor] []
1485 (initialize
1486 [renderManager viewPort]
1487 (let [cam (.getCamera viewPort)
1488 width (.getWidth cam)
1489 height (.getHeight cam)]
1490 (reset! renderer (.getRenderer renderManager))
1491 (reset! byte-buffer
1492 (BufferUtils/createByteBuffer
1493 (* width height 4)))
1494 (reset! image (BufferedImage. width height
1495 BufferedImage/TYPE_4BYTE_ABGR))))
1496 (isInitialized [] (not (nil? @byte-buffer)))
1497 (reshape [_ _ _])
1498 (preFrame [_])
1499 (postQueue [_])
1500 (postFrame
1501 [#^FrameBuffer fb]
1502 (.clear @byte-buffer)
1503 (.readFrameBuffer @renderer fb @byte-buffer)
1504 (Screenshots/convertScreenShot @byte-buffer @image)
1505 (continuation @image))
1506 (cleanup []))))
1508 (defn add-eye
1509 "Add an eye to the world, and call continuation on
1510 every frame produced"
1511 [world camera continuation]
1512 (let [width (.getWidth camera)
1513 height (.getHeight camera)
1514 render-manager (.getRenderManager world)
1515 viewport (.createMainView render-manager "eye-view" camera)]
1516 (doto viewport
1517 (.setBackgroundColor ColorRGBA/Black)
1518 (.setClearFlags true true true)
1519 (.addProcessor (scene-processor continuation))
1520 (.attachScene (.getRootNode world)))))
1522 (defn make-display-frame [display width height]
1523 (SwingUtilities/invokeLater
1524 (fn []
1525 (.setPreferredSize display (Dimension. width height))
1526 (doto (JFrame. "Eye Camera!")
1527 (-> (.getContentPane) (.add display))
1528 (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)
1529 (.pack)
1530 (.setLocationRelativeTo nil)
1531 (.setResizable false)
1532 (.setVisible true)))))
1534 (defn image-monitor [#^BufferedImage image]
1535 (proxy [JPanel] []
1536 (paintComponent
1537 [g]
1538 (proxy-super paintComponent g)
1539 (locking image
1540 (.drawImage g image 0 0
1541 (proxy [ImageObserver]
1542 []
1543 (imageUpdate
1544 []
1545 (proxy-super imageUpdate))))))))
1547 (defn movie-image []
1548 (let [setup
1549 (runonce
1550 (fn [#^BufferedImage image]
1551 (let [width (.getWidth image)
1552 height (.getHeight image)
1553 display (image-monitor image)
1554 frame (make-display-frame display width height)]
1555 display)))]
1556 (fn [#^BufferedImage image]
1557 (.repaint (setup image)))))
1560 (defn observer
1561 "place thy eye!"
1562 [world camera]
1563 (let [eye camera
1564 width (.getWidth eye)
1565 height (.getHeight eye)]
1566 (no-exceptions
1567 (add-eye
1568 world
1569 eye
1570 (movie-image)))))
1571 #+end_src
1573 #+srcname: test-vision
1574 #+begin_src clojure
1576 (ns test.vision)
1577 (use 'cortex.world)
1578 (use 'cortex.import)
1579 (use 'clojure.contrib.def)
1580 (use 'body.eye)
1581 (cortex.import/mega-import-jme3)
1582 (rlm.rlm-commands/help)
1583 (import java.nio.ByteBuffer)
1584 (import java.awt.image.BufferedImage)
1585 (import java.awt.Color)
1586 (import java.awt.Dimension)
1587 (import java.awt.Graphics)
1588 (import java.awt.Graphics2D)
1589 (import java.awt.event.WindowAdapter)
1590 (import java.awt.event.WindowEvent)
1591 (import java.awt.image.BufferedImage)
1592 (import java.nio.ByteBuffer)
1593 (import javax.swing.JFrame)
1594 (import javax.swing.JPanel)
1595 (import javax.swing.SwingUtilities)
1596 (import javax.swing.ImageIcon)
1597 (import javax.swing.JOptionPane)
1598 (import java.awt.image.ImageObserver)
1601 (def width 200)
1602 (def height 200)
1604 (defn camera []
1605 (doto (Camera. width height)
1606 (.setFrustumPerspective 45 1 1 1000)
1607 (.setLocation (Vector3f. -3 0 -5))
1608 (.lookAt Vector3f/ZERO Vector3f/UNIT_Y)))
1610 (defn camera2 []
1611 (doto (Camera. width height)
1612 (.setFrustumPerspective 45 1 1 1000)
1613 (.setLocation (Vector3f. 3 0 -5))
1614 (.lookAt Vector3f/ZERO Vector3f/UNIT_Y)))
1616 (defn setup-fn [world]
1617 (let [eye (camera)
1618 width (.getWidth eye)
1619 height (.getHeight eye)]
1620 (no-exceptions
1621 (add-eye
1622 world
1623 eye
1624 (runonce visual))
1625 (add-eye
1626 world
1627 (camera2)
1628 (runonce visual)))))
1630 (defn spider-eye [position]
1631 (doto (Camera. 200 200 )
1632 (.setFrustumPerspective 45 1 1 1000)
1633 (.setLocation position)
1634 (.lookAt Vector3f/ZERO Vector3f/UNIT_Y)))
1636 (defn setup-fn* [world]
1637 (let [eye (camera)
1638 width (.getWidth eye)
1639 height (.getHeight eye)]
1640 ;;(.setClearFlags (.getViewPort world) true true true)
1641 (observer world (.getCamera world))
1642 (observer world (spider-eye (Vector3f. 3 0 -5)))
1643 ;;(observer world (spider-eye (Vector3f. 0 0 -5)))
1644 ;; (observer world (spider-eye (Vector3f. -3 0 -5)))
1645 ;; (observer world (spider-eye (Vector3f. 0 3 -5)))
1646 ;; (observer world (spider-eye (Vector3f. 0 -3 -5)))
1647 ;; (observer world (spider-eye (Vector3f. 3 3 -5)))
1648 ;; (observer world (spider-eye (Vector3f. -3 3 -5)))
1649 ;; (observer world (spider-eye (Vector3f. 3 -3 -5)))
1650 ;; (observer world (spider-eye (Vector3f. -3 -3 -5)))
1653 world)
1655 (defn test-world []
1656 (let [thing (box 1 1 1 :physical? false)]
1657 (world
1658 (doto (Node.)
1659 (.attachChild thing))
1660 {}
1661 setup-fn
1662 (fn [world tpf]
1663 (.rotate thing (* tpf 0.2) 0 0)
1664 ))))
1667 #+end_src
1670 #+results: eyes
1671 : #'body.eye/test-world
1673 Note the use of continuation passing style for connecting the eye to a
1674 function to process the output. The example code will create two
1675 videos of the same rotating cube from different angles, sutiable for
1676 stereoscopic vision.
1683 * COMMENT code generation
1684 #+begin_src clojure :tangle ../src/cortex/import.clj
1685 <<import>>
1686 #+end_src
1688 #+begin_src clojure :tangle ../src/hello/brick_wall.clj
1689 <<brick-wall-header>>
1690 <<brick-wall-body>>
1691 #+end_src
1693 #+begin_src clojure :tangle ../src/hello/hello_simple_app.clj
1694 <<hello-simple-app>>
1695 #+end_src
1697 #+begin_src clojure :tangle ../src/cortex/world.clj
1698 <<world-inputs>>
1699 <<world>>
1700 <<world-shapes>>
1701 <<world-view>>
1702 #+end_src
1704 #+begin_src clojure :tangle ../src/cortex/other_games.clj
1705 <<other-games>>
1706 #+end_src
1708 #+begin_src clojure :tangle ../src/hello/loop.clj
1709 <<hello-loop>>
1710 #+end_src
1712 #+begin_src clojure :tangle ../src/hello/collision.clj
1713 <<hello-collision>>
1714 #+end_src
1716 #+begin_src clojure :tangle ../src/hello/terrain.clj
1717 <<hello-terrain>>
1718 #+end_src
1720 #+begin_src clojure :tangle ../src/hello/animation.clj
1721 <<hello-animation>>
1722 #+end_src
1724 #+begin_src clojure :tangle ../src/hello/material.clj
1725 <<material>>
1726 #+end_src
1728 #+begin_src clojure :tangle ../src/body/eye.clj
1729 <<eyes>>
1730 #+end_src
1732 #+begin_src clojure :tangle ../src/test/vision.clj
1733 <<test-vision>>
1734 #+end_src