Mercurial > cortex
view org/util.org @ 81:10f495560c59
correcting problem with joints
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Thu, 05 Jan 2012 21:31:34 -0700 |
parents | 77b506ac64f3 |
children | 92b857b6145d |
line wrap: on
line source
1 #+title: Clojure Utilities for jMonkeyEngine32 #+author: Robert McIntyre3 #+email: rlm@mit.edu4 #+description:5 #+keywords: JME3, clojure, import, utilities6 #+SETUPFILE: ../../aurellem/org/setup.org7 #+INCLUDE: ../../aurellem/org/level-0.org9 [TABLE-OF-CONTENTS]11 These are a collection of functions to make programming jMonkeyEngine12 in clojure easier.14 * Imports16 #+name: import17 #+begin_src clojure :results silent18 (ns cortex.import19 (:require swank.util.class-browse))21 (defn permissive-import22 [classname]23 (eval `(try (import '~classname)24 (catch java.lang.Exception e#25 (println "couldn't import " '~classname))))26 classname)28 (defn jme-class? [classname]29 (and30 (.startsWith classname "com.jme3.")31 ;; Don't import the Lwjgl stuff since it can throw exceptions32 ;; upon being loaded.33 (not (re-matches #".*Lwjgl.*" classname))))35 (defn jme-classes36 "returns a list of all jme3 classes"37 []38 (filter39 jme-class?40 (map :name41 swank.util.class-browse/available-classes)))43 (defn mega-import-jme344 "Import ALL the jme classes. For REPL use."45 []46 (doall47 (map (comp permissive-import symbol) (jme-classes))))48 #+end_src50 jMonkeyEngine3 has a plethora of classes which can be overwhelming to51 manage. This code uses reflection to import all of them. Once I'm52 happy with the general structure of a namespace I can deal with53 importing only the classes it actually needs.55 The =mega-import-jme3= is quite usefull for debugging purposes since56 it allows completion for almost all of JME's classes from the REPL.58 Out of curiousity, let's see just how many classes =mega-import-jme3=59 imports:61 #+begin_src clojure :exports both :results output62 (println (clojure.core/count (cortex.import/jme-classes)) "classes")63 #+end_src65 #+results:66 : 955 classes69 * Utilities71 The utilities here come in three main groups:72 - Changing settings in a running =Application=73 - Creating objects74 - Debug Actions75 - Visualizing objects77 *** Changing Settings79 #+name: util80 #+begin_src clojure81 (ns cortex.util82 "Utility functions for making jMonkeyEngine3 easier to program from83 clojure."84 {:author "Robert McIntyre"}85 (:use cortex.world)86 (:use clojure.contrib.def)87 (:import com.jme3.math.Vector3f)88 (:import com.jme3.math.Quaternion)89 (:import com.jme3.asset.TextureKey)90 (:import com.jme3.bullet.control.RigidBodyControl)91 (:import com.jme3.bullet.collision.shapes.GImpactCollisionShape)92 (:import com.jme3.scene.shape.Box)93 (:import com.jme3.scene.Node)94 (:import com.jme3.scene.shape.Sphere)95 (:import com.jme3.light.AmbientLight)96 (:import com.jme3.light.DirectionalLight)97 (:import com.jme3.math.ColorRGBA)98 (:import com.jme3.bullet.BulletAppState)99 (:import com.jme3.material.Material)100 (:import com.jme3.scene.Geometry)101 (:import (java.util.logging Level Logger)))105 (defvar println-repl106 (bound-fn [& args] (apply println args))107 "println called from the LWJGL thread will not go to the REPL, but108 instead to whatever terminal started the JVM process. This function109 will always output to the REPL")111 (defn position-camera112 "Change the position of the in-world camera."113 ([world position direction up]114 (doto (.getCamera world)115 (.setLocation )116 (.lookAt direction up)))117 ([world position direction]118 (position-camera119 world position direction Vector3f/UNIT_Y)))121 (defn enable-debug122 "Turn on debug wireframes for every object in this simulation."123 [world]124 (.enableDebug125 (.getPhysicsSpace126 (.getState127 (.getStateManager world)128 BulletAppState))129 (asset-manager)))131 (defn speed-up132 "Increase the dismally slow speed of the world's camera."133 [world]134 (.setMoveSpeed (.getFlyByCamera world)135 (float 100))136 (.setRotationSpeed (.getFlyByCamera world)137 (float 20))138 world)141 (defn no-logging142 "Disable all of jMonkeyEngine's logging."143 []144 (.setLevel (Logger/getLogger "com.jme3") Level/OFF))146 (defn set-accuracy147 "Change the accuracy at which the World's Physics is calculated."148 [world new-accuracy]149 (let [physics-manager150 (.getState151 (.getStateManager world) BulletAppState)]152 (.setAccuracy153 (.getPhysicsSpace physics-manager)154 (float new-accuracy))))157 (defn set-gravity158 "In order to change the gravity of a scene, it is not only necessary159 to set the gravity variable, but to \"tap\" every physics object in160 the scene to reactivate physics calculations."161 [world gravity]162 (traverse163 (fn [geom]164 (if-let165 ;; only set gravity for physical objects.166 [control (.getControl geom RigidBodyControl)]167 (do168 (.setGravity control gravity)169 ;; tappsies!170 (.applyImpulse control Vector3f/ZERO Vector3f/ZERO))))171 (.getRootNode world)))173 (defn add-element174 "Add the Spatial to the world's environment"175 ([world element node]176 (.addAll177 (.getPhysicsSpace178 (.getState179 (.getStateManager world)180 BulletAppState))181 element)182 (.attachChild node element))183 ([world element]184 (add-element world element (.getRootNode world))))186 (defn apply-map187 "Like apply, but works for maps and functions that expect an188 implicit map and nothing else as in (fn [& {}]).189 ------- Example -------190 (defn demo [& {:keys [www] :or {www \"oh yeah\"} :as env}]191 (println www))192 (apply-map demo {:www \"hello!\"})193 -->\"hello\""194 [fn m]195 (apply fn (reduce #(into %1 %2) [] m)))197 #+end_src199 #+results: util200 : #'cortex.util/apply-map203 *** Creating Basic Shapes205 #+name: shapes206 #+begin_src clojure :results silent207 (in-ns 'cortex.util)209 (defrecord shape-description210 [name211 color212 mass213 friction214 texture215 material216 position217 rotation218 shape219 physical?220 GImpact?221 ])223 (defvar base-shape224 (shape-description.225 "default-shape"226 false227 ;;ColorRGBA/Blue228 1.0 ;; mass229 1.0 ;; friction230 ;; texture231 "Textures/Terrain/BrickWall/BrickWall.jpg"232 ;; material233 "Common/MatDefs/Misc/Unshaded.j3md"234 Vector3f/ZERO235 Quaternion/IDENTITY236 (Box. Vector3f/ZERO 0.5 0.5 0.5)237 true238 false)239 "Basic settings for shapes.")241 (defn make-shape242 [#^shape-description d]243 (let [asset-manager (asset-manager)244 mat (Material. asset-manager (:material d))245 geom (Geometry. (:name d) (:shape d))]246 (if (:texture d)247 (let [key (TextureKey. (:texture d))]248 ;;(.setGenerateMips key true)249 ;;(.setTexture mat "ColorMap" (.loadTexture asset-manager key))250 ))251 (if (:color d) (.setColor mat "Color" (:color d)))252 (.setMaterial geom mat)253 (if-let [rotation (:rotation d)] (.rotate geom rotation))254 (.setLocalTranslation geom (:position d))255 (if (:physical? d)256 (let [physics-control257 (if (:GImpact d)258 ;; Create an accurate mesh collision shape if desired.259 (RigidBodyControl.260 (doto (GImpactCollisionShape.261 (.getMesh geom))262 (.createJmeMesh)263 ;;(.setMargin 0)264 )265 (float (:mass d)))266 ;; otherwise use jme3's default267 (RigidBodyControl. (float (:mass d))))]268 (.addControl geom physics-control)269 ;;(.setSleepingThresholds physics-control (float 0) (float 0))270 (.setFriction physics-control (:friction d))))271 geom))273 (defn box274 ([l w h & {:as options}]275 (let [options (merge base-shape options)]276 (make-shape (assoc options277 :shape (Box. l w h)))))278 ([] (box 0.5 0.5 0.5)))280 (defn sphere281 ([r & {:as options}]282 (let [options (merge base-shape options)]283 (make-shape (assoc options284 :shape (Sphere. 32 32 (float r))))))285 ([] (sphere 0.5)))287 (defn green-x-ray288 "A usefull material for debuging -- it can be seen no matter what289 object occuldes it."290 []291 (doto (Material. (asset-manager)292 "Common/MatDefs/Misc/Unshaded.j3md")293 (.setColor "Color" ColorRGBA/Green)294 (-> (.getAdditionalRenderState)295 (.setDepthTest false))))297 (defn node-seq298 "Take a node and return a seq of all its children299 recursively. There will be no nodes left in the resulting300 structure"301 [#^Node node]302 (tree-seq #(isa? (class %) Node) #(.getChildren %) node))304 (defn nodify305 "Take a sequence of things that can be attached to a node and return306 a node with all of them attached"307 ([name children]308 (let [node (Node. name)]309 (dorun (map #(.attachChild node %) children))310 node))311 ([children] (nodify "" children)))314 #+end_src317 *** Debug Actions318 #+name: debug-actions319 #+begin_src clojure :results silent320 (in-ns 'cortex.util)322 (defn basic-light-setup323 "returns a sequence of lights appropiate for fully lighting a scene"324 []325 (conj326 (doall327 (map328 (fn [direction]329 (doto (DirectionalLight.)330 (.setDirection direction)331 (.setColor ColorRGBA/White)))332 [;; six faces of a cube333 Vector3f/UNIT_X334 Vector3f/UNIT_Y335 Vector3f/UNIT_Z336 (.mult Vector3f/UNIT_X (float -1))337 (.mult Vector3f/UNIT_Y (float -1))338 (.mult Vector3f/UNIT_Z (float -1))]))339 (doto (AmbientLight.)340 (.setColor ColorRGBA/White))))342 (defn light-up-everything343 "Add lights to a world appropiate for quickly seeing everything344 in the scene. Adds six DirectionalLights facing in orthogonal345 directions, and one AmbientLight to provide overall lighting346 coverage."347 [world]348 (dorun349 (map350 #(.addLight (.getRootNode world) %)351 (basic-light-setup))))353 (defn fire-cannon-ball354 "Creates a function that fires a cannon-ball from the current game's355 camera. The cannon-ball will be attached to the node if provided, or356 to the game's RootNode if no node is provided."357 ([node]358 (fn [game value]359 (if (not value)360 (let [camera (.getCamera game)361 cannon-ball362 (sphere 0.7363 :material "Common/MatDefs/Misc/Unshaded.j3md"364 :texture "Textures/PokeCopper.jpg"365 :position366 (.add (.getLocation camera)367 (.mult (.getDirection camera) (float 1)))368 :mass 3)] ;200 0.05369 (.setLinearVelocity370 (.getControl cannon-ball RigidBodyControl)371 (.mult (.getDirection camera) (float 50))) ;50372 (add-element game cannon-ball (if node node (.getRootNode game)))))))373 ([]374 (fire-cannon-ball false)))376 (def standard-debug-controls377 {"key-space" (fire-cannon-ball)})382 #+end_src385 *** Viewing Objects387 #+name: world-view388 #+begin_src clojure :results silent389 (in-ns 'cortex.util)391 (defprotocol Viewable392 (view [something]))394 (extend-type com.jme3.scene.Geometry395 Viewable396 (view [geo]397 (view (doto (Node.)(.attachChild geo)))))399 (extend-type com.jme3.scene.Node400 Viewable401 (view402 [node]403 (.start404 (world405 node406 {}407 (fn [world]408 (enable-debug world)409 (set-gravity world Vector3f/ZERO)410 (light-up-everything world))411 no-op))))413 (extend-type com.jme3.math.ColorRGBA414 Viewable415 (view416 [color]417 (view (doto (Node.)418 (.attachChild (box 1 1 1 :color color))))))420 (defprotocol Textual421 (text [something]422 "Display a detailed textual analysis of the given object."))424 (extend-type com.jme3.scene.Node425 Textual426 (text [node]427 (println "Total Vertexes: " (.getVertexCount node))428 (println "Total Triangles: " (.getTriangleCount node))429 (println "Controls :")430 (dorun (map #(text (.getControl node %)) (range (.getNumControls node))))431 (println "Has " (.getQuantity node) " Children:")432 (doall (map text (.getChildren node)))))434 (extend-type com.jme3.animation.AnimControl435 Textual436 (text [control]437 (let [animations (.getAnimationNames control)]438 (println "Animation Control with " (count animations) " animation(s):")439 (dorun (map println animations)))))441 (extend-type com.jme3.animation.SkeletonControl442 Textual443 (text [control]444 (println "Skeleton Control with the following skeleton:")445 (println (.getSkeleton control))))447 (extend-type com.jme3.bullet.control.KinematicRagdollControl448 Textual449 (text [control]450 (println "Ragdoll Control")))452 (extend-type com.jme3.scene.Geometry453 Textual454 (text [control]455 (println "...geo...")))456 #+end_src458 Here I make the =Viewable= protocol and extend it to JME's types. Now459 JME3's =hello-world= can be written as easily as:461 #+begin_src clojure :results silent462 (cortex.util/view (cortex.util/box))463 #+end_src466 * COMMENT code generation467 #+begin_src clojure :tangle ../src/cortex/import.clj468 <<import>>469 #+end_src472 #+begin_src clojure :tangle ../src/cortex/util.clj :noweb yes473 <<util>>474 <<shapes>>475 <<debug-actions>>476 <<world-view>>477 #+end_src