Browse Source

direct: add .pylintrc, perform major code cleanup pass

Closes #989

Co-authored-by: Daniel Stokes <[email protected]>
rdb 5 years ago
parent
commit
be9dde1eee
100 changed files with 1539 additions and 1277 deletions
  1. 533 0
      .pylintrc
  2. 68 75
      direct/src/actor/Actor.py
  3. 3 7
      direct/src/actor/DistributedActor.py
  4. 35 40
      direct/src/cluster/ClusterClient.py
  5. 0 1
      direct/src/cluster/ClusterConfig.py
  6. 10 19
      direct/src/cluster/ClusterMsgs.py
  7. 28 30
      direct/src/cluster/ClusterServer.py
  8. 2 148
      direct/src/controls/BattleWalker.py
  9. 9 9
      direct/src/controls/ControlManager.py
  10. 2 0
      direct/src/controls/DevWalker.py
  11. 10 8
      direct/src/controls/GravityWalker.py
  12. 2 0
      direct/src/controls/InputState.py
  13. 7 5
      direct/src/controls/NonPhysicsWalker.py
  14. 0 5
      direct/src/controls/ObserverWalker.py
  15. 98 135
      direct/src/controls/PhysicsWalker.py
  16. 1 0
      direct/src/controls/TwoDWalker.py
  17. 2 15
      direct/src/directbase/TestStart.py
  18. 5 17
      direct/src/directbase/ThreeUpStart.py
  19. 17 16
      direct/src/directdevices/DirectDeviceManager.py
  20. 3 6
      direct/src/directdevices/DirectFastrak.py
  21. 13 16
      direct/src/directdevices/DirectJoybox.py
  22. 12 13
      direct/src/directdevices/DirectRadamec.py
  23. 3 3
      direct/src/directnotify/DirectNotify.py
  24. 11 26
      direct/src/directnotify/Logger.py
  25. 11 12
      direct/src/directnotify/Notifier.py
  26. 22 17
      direct/src/directscripts/eggcacher.py
  27. 2 2
      direct/src/directscripts/extract_docs.py
  28. 8 8
      direct/src/directtools/DirectCameraControl.py
  29. 3 4
      direct/src/directtools/DirectGeometry.py
  30. 0 1
      direct/src/directtools/DirectGlobals.py
  31. 4 3
      direct/src/directtools/DirectGrid.py
  32. 8 9
      direct/src/directtools/DirectLights.py
  33. 56 55
      direct/src/directtools/DirectManipulation.py
  34. 9 9
      direct/src/directtools/DirectSelection.py
  35. 8 11
      direct/src/directtools/DirectSession.py
  36. 1 1
      direct/src/directtools/DirectUtil.py
  37. 2 0
      direct/src/directutil/DistributedLargeBlobSender.py
  38. 1 1
      direct/src/directutil/DistributedLargeBlobSenderAI.py
  39. 23 24
      direct/src/directutil/Mopath.py
  40. 18 16
      direct/src/dist/FreezeTool.py
  41. 1 6
      direct/src/dist/commands.py
  42. 1 1
      direct/src/dist/icon.py
  43. 0 1
      direct/src/dist/installers.py
  44. 2 0
      direct/src/dist/pefile.py
  45. 1 1
      direct/src/dist/pfreeze.py
  46. 3 1
      direct/src/distributed/AsyncRequest.py
  47. 7 4
      direct/src/distributed/CRCache.py
  48. 0 1
      direct/src/distributed/CRDataCache.py
  49. 4 4
      direct/src/distributed/CartesianGridBase.py
  50. 9 8
      direct/src/distributed/ClientRepository.py
  51. 13 11
      direct/src/distributed/ClientRepositoryBase.py
  52. 3 3
      direct/src/distributed/ClockDelta.py
  53. 9 7
      direct/src/distributed/ConnectionRepository.py
  54. 3 3
      direct/src/distributed/DistributedCamera.py
  55. 9 9
      direct/src/distributed/DistributedCartesianGrid.py
  56. 8 8
      direct/src/distributed/DistributedCartesianGridAI.py
  57. 4 8
      direct/src/distributed/DistributedNode.py
  58. 3 5
      direct/src/distributed/DistributedNodeAI.py
  59. 3 5
      direct/src/distributed/DistributedNodeUD.py
  60. 15 20
      direct/src/distributed/DistributedObject.py
  61. 27 32
      direct/src/distributed/DistributedObjectAI.py
  62. 1 8
      direct/src/distributed/DistributedObjectBase.py
  63. 0 1
      direct/src/distributed/DistributedObjectGlobal.py
  64. 6 7
      direct/src/distributed/DistributedObjectGlobalAI.py
  65. 3 3
      direct/src/distributed/DistributedObjectGlobalUD.py
  66. 8 11
      direct/src/distributed/DistributedObjectOV.py
  67. 25 27
      direct/src/distributed/DistributedObjectUD.py
  68. 12 12
      direct/src/distributed/DistributedSmoothNode.py
  69. 1 2
      direct/src/distributed/DistributedSmoothNodeAI.py
  70. 3 3
      direct/src/distributed/DistributedSmoothNodeBase.py
  71. 9 10
      direct/src/distributed/DoCollectionManager.py
  72. 2 2
      direct/src/distributed/DoHierarchy.py
  73. 4 2
      direct/src/distributed/DoInterestManager.py
  74. 2 1
      direct/src/distributed/GridChild.py
  75. 2 4
      direct/src/distributed/GridParent.py
  76. 8 8
      direct/src/distributed/InterestWatcher.py
  77. 0 2
      direct/src/distributed/NetMessenger.py
  78. 1 1
      direct/src/distributed/ParentMgr.py
  79. 1 1
      direct/src/distributed/PyDatagram.py
  80. 5 5
      direct/src/distributed/RelatedObjectMgr.py
  81. 6 5
      direct/src/distributed/ServerRepository.py
  82. 0 1
      direct/src/distributed/StagedObject.py
  83. 2 3
      direct/src/distributed/TimeManager.py
  84. 1 1
      direct/src/distributed/TimeManagerAI.py
  85. 1 1
      direct/src/extensions_native/CInterval_extensions.py
  86. 1 4
      direct/src/extensions_native/HTTPChannel_extensions.py
  87. 5 5
      direct/src/extensions_native/Mat3_extensions.py
  88. 87 62
      direct/src/extensions_native/NodePath_extensions.py
  89. 103 97
      direct/src/filter/CommonFilters.py
  90. 24 23
      direct/src/filter/FilterManager.py
  91. 13 20
      direct/src/fsm/ClassicFSM.py
  92. 6 9
      direct/src/fsm/FSM.py
  93. 0 1
      direct/src/fsm/FourState.py
  94. 1 1
      direct/src/fsm/FourStateAI.py
  95. 1 0
      direct/src/fsm/SampleFSM.py
  96. 13 13
      direct/src/fsm/State.py
  97. 1 0
      direct/src/fsm/StatePush.py
  98. 0 2
      direct/src/gui/DirectButton.py
  99. 0 1
      direct/src/gui/DirectCheckBox.py
  100. 6 13
      direct/src/gui/DirectCheckButton.py

+ 533 - 0
.pylintrc

@@ -0,0 +1,533 @@
+[MASTER]
+
+# A comma-separated list of package or module names from where C extensions may
+# be loaded. Extensions are loading into the active Python interpreter and may
+# run arbitrary code.
+extension-pkg-whitelist=panda3d
+
+# Specify a score threshold to be exceeded before program exits with error.
+fail-under=10.0
+
+# Add files or directories to the blacklist. They should be base names, not
+# paths.
+ignore=thirdparty
+
+# Add files or directories matching the regex patterns to the blacklist. The
+# regex matches against base names, not paths.
+ignore-patterns=
+
+# Python code to execute, usually for sys.path manipulation such as
+# pygtk.require().
+#init-hook=
+
+# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
+# number of processors available to use.
+jobs=1
+
+# Control the amount of potential inferred values when inferring a single
+# object. This can help the performance when dealing with large functions or
+# complex, nested conditions.
+limit-inference-results=100
+
+# List of plugins (as comma separated values of python module names) to load,
+# usually to register additional checkers.
+load-plugins=
+
+# Pickle collected data for later comparisons.
+persistent=yes
+
+# When enabled, pylint would attempt to guess common misconfiguration and emit
+# user-friendly hints instead of false-positive error messages.
+suggestion-mode=yes
+
+# Allow loading of arbitrary C extensions. Extensions are imported into the
+# active Python interpreter and may run arbitrary code.
+unsafe-load-any-extension=no
+
+
+[MESSAGES CONTROL]
+
+# Only show warnings with the listed confidence levels. Leave empty to show
+# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
+confidence=
+
+# Disable the message, report, category or checker with the given id(s). You
+# can either give multiple identifiers separated by comma (,) or put this
+# option multiple times (only on the command line, not in the configuration
+# file where it should appear only once). You can also use "--disable=all" to
+# disable everything first and then reenable specific checks. For example, if
+# you want to run only the similarities checker, you can use "--disable=all
+# --enable=similarities". If you want to run only the classes checker, but have
+# no Warning level messages displayed, use "--disable=all --enable=classes
+# --disable=W".
+disable=attribute-defined-outside-init,
+        broad-except,
+        comparison-with-callable,
+        dangerous-default-value,
+        global-statement,
+        import-outside-toplevel,
+        invalid-name,
+        line-too-long,
+        misplaced-comparison-constant,
+        missing-class-docstring,
+        missing-function-docstring,
+        missing-module-docstring,
+        protected-access,
+        r,
+        raise-missing-from,
+        redefined-builtin,
+        too-many-lines,
+        unused-argument,
+        unused-variable,
+        unused-wildcard-import,
+        using-constant-test,
+        wildcard-import,
+        wrong-import-order,
+        wrong-import-position
+
+# Enable the message, report, category or checker with the given id(s). You can
+# either give multiple identifier separated by comma (,) or put this option
+# multiple time (only on the command line, not in the configuration file where
+# it should appear only once). See also the "--disable" option for examples.
+enable=c-extension-no-member
+
+
+[REPORTS]
+
+# Python expression which should return a score less than or equal to 10. You
+# have access to the variables 'error', 'warning', 'refactor', and 'convention'
+# which contain the number of messages in each category, as well as 'statement'
+# which is the total number of statements analyzed. This score is used by the
+# global evaluation report (RP0004).
+evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
+
+# Template used to display messages. This is a python new-style format string
+# used to format the message information. See doc for all details.
+#msg-template=
+
+# Set the output format. Available formats are text, parseable, colorized, json
+# and msvs (visual studio). You can also give a reporter class, e.g.
+# mypackage.mymodule.MyReporterClass.
+output-format=text
+
+# Tells whether to display a full report or only the messages.
+reports=no
+
+# Activate the evaluation score.
+score=yes
+
+
+[REFACTORING]
+
+# Maximum number of nested blocks for function / method body
+max-nested-blocks=5
+
+# Complete name of functions that never returns. When checking for
+# inconsistent-return-statements if a never returning function is called then
+# it will be considered as an explicit return statement and no message will be
+# printed.
+never-returning-functions=sys.exit
+
+
+[FORMAT]
+
+# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
+expected-line-ending-format=LF
+
+# Regexp for a line that is allowed to be longer than the limit.
+ignore-long-lines=^\s*(# )?<?https?://\S+>?$
+
+# Number of spaces of indent required inside a hanging or continued line.
+indent-after-paren=4
+
+# String used as indentation unit. This is usually "    " (4 spaces) or "\t" (1
+# tab).
+indent-string='    '
+
+# Maximum number of characters on a single line.
+max-line-length=100
+
+# Maximum number of lines in a module.
+max-module-lines=1000
+
+# Allow the body of a class to be on the same line as the declaration if body
+# contains single statement.
+single-line-class-stmt=no
+
+# Allow the body of an if to be on the same line as the test if there is no
+# else.
+single-line-if-stmt=no
+
+
+[SPELLING]
+
+# Limits count of emitted suggestions for spelling mistakes.
+max-spelling-suggestions=4
+
+# Spelling dictionary name. Available dictionaries: none. To make it work,
+# install the python-enchant package.
+spelling-dict=
+
+# List of comma separated words that should not be checked.
+spelling-ignore-words=
+
+# A path to a file that contains the private dictionary; one word per line.
+spelling-private-dict-file=
+
+# Tells whether to store unknown words to the private dictionary (see the
+# --spelling-private-dict-file option) instead of raising a message.
+spelling-store-unknown-words=no
+
+
+[TYPECHECK]
+
+# List of decorators that produce context managers, such as
+# contextlib.contextmanager. Add to this list to register other decorators that
+# produce valid context managers.
+contextmanager-decorators=contextlib.contextmanager
+
+# List of members which are set dynamically and missed by pylint inference
+# system, and so shouldn't trigger E1101 when accessed. Python regular
+# expressions are accepted.
+generated-members=
+
+# Tells whether missing members accessed in mixin class should be ignored. A
+# mixin class is detected if its name ends with "mixin" (case insensitive).
+ignore-mixin-members=yes
+
+# Tells whether to warn about missing members when the owner of the attribute
+# is inferred to be None.
+ignore-none=yes
+
+# This flag controls whether pylint should warn about no-member and similar
+# checks whenever an opaque object is returned when inferring. The inference
+# can return multiple potential results while evaluating a Python object, but
+# some branches might not be evaluated, which results in partial inference. In
+# that case, it might be useful to still emit no-member and other checks for
+# the rest of the inferred objects.
+ignore-on-opaque-inference=yes
+
+# List of class names for which member attributes should not be checked (useful
+# for classes with dynamically set attributes). This supports the use of
+# qualified names.
+ignored-classes=optparse.Values,thread._local,_thread._local,direct.showbase.PythonUtil.ScratchPad
+
+# List of module names for which member attributes should not be checked
+# (useful for modules/projects where namespaces are manipulated during runtime
+# and thus existing member attributes cannot be deduced by static analysis). It
+# supports qualified module names, as well as Unix pattern matching.
+ignored-modules=
+
+# Show a hint with possible names when a member name was not found. The aspect
+# of finding the hint is based on edit distance.
+missing-member-hint=yes
+
+# The minimum edit distance a name should have in order to be considered a
+# similar match for a missing member name.
+missing-member-hint-distance=1
+
+# The total number of similar names that should be taken in consideration when
+# showing a hint for a missing member.
+missing-member-max-choices=1
+
+# List of decorators that change the signature of a decorated function.
+signature-mutators=
+
+
+[SIMILARITIES]
+
+# Ignore comments when computing similarities.
+ignore-comments=yes
+
+# Ignore docstrings when computing similarities.
+ignore-docstrings=yes
+
+# Ignore imports when computing similarities.
+ignore-imports=no
+
+# Minimum lines number of a similarity.
+min-similarity-lines=4
+
+
+[VARIABLES]
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid defining new builtins when possible.
+additional-builtins=base,simbase,__dev__,onScreenDebug,globalClock,render,hidden,cluster
+
+# Tells whether unused global variables should be treated as a violation.
+allow-global-unused-variables=yes
+
+# List of strings which can identify a callback function by name. A callback
+# name must start or end with one of those strings.
+callbacks=cb_,
+          _cb
+
+# A regular expression matching the name of dummy variables (i.e. expected to
+# not be used).
+dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
+
+# Argument names that match this expression will be ignored. Default to name
+# with leading underscore.
+ignored-argument-names=_.*|^ignored_|^unused_
+
+# Tells whether we should check for unused import in __init__ files.
+init-import=no
+
+# List of qualified module names which can have objects that can redefine
+# builtins.
+redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
+
+
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=FIXME,
+      XXX,
+      TODO
+
+# Regular expression of note tags to take in consideration.
+#notes-rgx=
+
+
+[BASIC]
+
+# Naming style matching correct argument names.
+argument-naming-style=snake_case
+
+# Regular expression matching correct argument names. Overrides argument-
+# naming-style.
+#argument-rgx=
+
+# Naming style matching correct attribute names.
+attr-naming-style=snake_case
+
+# Regular expression matching correct attribute names. Overrides attr-naming-
+# style.
+#attr-rgx=
+
+# Bad variable names which should always be refused, separated by a comma.
+bad-names=foo,
+          bar,
+          baz,
+          toto,
+          tutu,
+          tata
+
+# Bad variable names regexes, separated by a comma. If names match any regex,
+# they will always be refused
+bad-names-rgxs=
+
+# Naming style matching correct class attribute names.
+class-attribute-naming-style=any
+
+# Regular expression matching correct class attribute names. Overrides class-
+# attribute-naming-style.
+#class-attribute-rgx=
+
+# Naming style matching correct class names.
+class-naming-style=PascalCase
+
+# Regular expression matching correct class names. Overrides class-naming-
+# style.
+#class-rgx=
+
+# Naming style matching correct constant names.
+const-naming-style=UPPER_CASE
+
+# Regular expression matching correct constant names. Overrides const-naming-
+# style.
+#const-rgx=
+
+# Minimum line length for functions/classes that require docstrings, shorter
+# ones are exempt.
+docstring-min-length=-1
+
+# Naming style matching correct function names.
+function-naming-style=snake_case
+
+# Regular expression matching correct function names. Overrides function-
+# naming-style.
+#function-rgx=
+
+# Good variable names which should always be accepted, separated by a comma.
+good-names=i,
+           j,
+           k,
+           ex,
+           Run,
+           _
+
+# Good variable names regexes, separated by a comma. If names match any regex,
+# they will always be accepted
+good-names-rgxs=
+
+# Include a hint for the correct naming format with invalid-name.
+include-naming-hint=no
+
+# Naming style matching correct inline iteration names.
+inlinevar-naming-style=any
+
+# Regular expression matching correct inline iteration names. Overrides
+# inlinevar-naming-style.
+#inlinevar-rgx=
+
+# Naming style matching correct method names.
+method-naming-style=snake_case
+
+# Regular expression matching correct method names. Overrides method-naming-
+# style.
+#method-rgx=
+
+# Naming style matching correct module names.
+module-naming-style=snake_case
+
+# Regular expression matching correct module names. Overrides module-naming-
+# style.
+#module-rgx=
+
+# Colon-delimited sets of names that determine each other's naming style when
+# the name regexes allow several styles.
+name-group=
+
+# Regular expression which should only match function or class names that do
+# not require a docstring.
+no-docstring-rgx=^_
+
+# List of decorators that produce properties, such as abc.abstractproperty. Add
+# to this list to register other decorators that produce valid properties.
+# These decorators are taken in consideration only for invalid-name.
+property-classes=abc.abstractproperty
+
+# Naming style matching correct variable names.
+variable-naming-style=snake_case
+
+# Regular expression matching correct variable names. Overrides variable-
+# naming-style.
+#variable-rgx=
+
+
+[LOGGING]
+
+# The type of string formatting that logging methods do. `old` means using %
+# formatting, `new` is for `{}` formatting.
+logging-format-style=old
+
+# Logging modules to check that the string format arguments are in logging
+# function parameter format.
+logging-modules=logging
+
+
+[STRING]
+
+# This flag controls whether inconsistent-quotes generates a warning when the
+# character used as a quote delimiter is used inconsistently within a module.
+check-quote-consistency=no
+
+# This flag controls whether the implicit-str-concat should generate a warning
+# on implicit string concatenation in sequences defined over several lines.
+check-str-concat-over-line-jumps=no
+
+
+[DESIGN]
+
+# Maximum number of arguments for function / method.
+max-args=5
+
+# Maximum number of attributes for a class (see R0902).
+max-attributes=7
+
+# Maximum number of boolean expressions in an if statement (see R0916).
+max-bool-expr=5
+
+# Maximum number of branch for function / method body.
+max-branches=12
+
+# Maximum number of locals for function / method body.
+max-locals=15
+
+# Maximum number of parents for a class (see R0901).
+max-parents=7
+
+# Maximum number of public methods for a class (see R0904).
+max-public-methods=20
+
+# Maximum number of return / yield for function / method body.
+max-returns=6
+
+# Maximum number of statements in function / method body.
+max-statements=50
+
+# Minimum number of public methods for a class (see R0903).
+min-public-methods=2
+
+
+[IMPORTS]
+
+# List of modules that can be imported at any level, not just the top level
+# one.
+allow-any-import-level=
+
+# Allow wildcard imports from modules that define __all__.
+allow-wildcard-with-all=no
+
+# Analyse import fallback blocks. This can be used to support both Python 2 and
+# 3 compatible code, which means that the block might have code that exists
+# only in one or another interpreter, leading to false positives when analysed.
+analyse-fallback-blocks=no
+
+# Deprecated modules which should not be used, separated by a comma.
+deprecated-modules=optparse,tkinter.tix
+
+# Create a graph of external dependencies in the given file (report RP0402 must
+# not be disabled).
+ext-import-graph=
+
+# Create a graph of every (i.e. internal and external) dependencies in the
+# given file (report RP0402 must not be disabled).
+import-graph=
+
+# Create a graph of internal dependencies in the given file (report RP0402 must
+# not be disabled).
+int-import-graph=
+
+# Force import order to recognize a module as part of the standard
+# compatibility libraries.
+known-standard-library=
+
+# Force import order to recognize a module as part of a third party library.
+known-third-party=enchant
+
+# Couples of modules and preferred modules, separated by a comma.
+preferred-modules=
+
+
+[CLASSES]
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,
+                      __new__,
+                      setUp,
+                      __post_init__
+
+# List of member names, which should be excluded from the protected access
+# warning.
+exclude-protected=_asdict,
+                  _fields,
+                  _replace,
+                  _source,
+                  _make
+
+# List of valid names for the first argument in a class method.
+valid-classmethod-first-arg=cls
+
+# List of valid names for the first argument in a metaclass class method.
+valid-metaclass-classmethod-first-arg=cls
+
+
+[EXCEPTIONS]
+
+# Exceptions that will emit a warning when being caught. Defaults to
+# "BaseException, Exception".
+overgeneral-exceptions=BaseException,
+                       Exception

+ 68 - 75
direct/src/actor/Actor.py

@@ -163,10 +163,7 @@ class Actor(DirectObject, NodePath):
             #the actor for a few frames, otherwise it has no effect
             #the actor for a few frames, otherwise it has no effect
             a.fixBounds()
             a.fixBounds()
         """
         """
-        try:
-            self.Actor_initialized
-            return
-        except:
+        if not hasattr(self, 'Actor_initialized'):
             self.Actor_initialized = 1
             self.Actor_initialized = 1
 
 
         # initialize our NodePath essence
         # initialize our NodePath essence
@@ -252,9 +249,9 @@ class Actor(DirectObject, NodePath):
             # make sure we have models
             # make sure we have models
             if models:
             if models:
                 # do we have a dictionary of models?
                 # do we have a dictionary of models?
-                if type(models) == dict:
+                if isinstance(models, dict):
                     # if this is a dictionary of dictionaries
                     # if this is a dictionary of dictionaries
-                    if type(models[next(iter(models))]) == dict:
+                    if isinstance(models[next(iter(models))], dict):
                         # then it must be a multipart actor w/LOD
                         # then it must be a multipart actor w/LOD
                         self.setLODNode(node = lodNode)
                         self.setLODNode(node = lodNode)
                         # preserve numerical order for lod's
                         # preserve numerical order for lod's
@@ -271,7 +268,7 @@ class Actor(DirectObject, NodePath):
                                                modelName, lodName, copy = copy,
                                                modelName, lodName, copy = copy,
                                                okMissing = okMissing)
                                                okMissing = okMissing)
                     # then if there is a dictionary of dictionaries of anims
                     # then if there is a dictionary of dictionaries of anims
-                    elif type(anims[next(iter(anims))]) == dict:
+                    elif isinstance(anims[next(iter(anims))], dict):
                         # then this is a multipart actor w/o LOD
                         # then this is a multipart actor w/o LOD
                         for partName in models:
                         for partName in models:
                             # pass in each part
                             # pass in each part
@@ -297,10 +294,10 @@ class Actor(DirectObject, NodePath):
             if anims:
             if anims:
                 if len(anims) >= 1:
                 if len(anims) >= 1:
                     # if so, does it have a dictionary of dictionaries?
                     # if so, does it have a dictionary of dictionaries?
-                    if type(anims[next(iter(anims))]) == dict:
+                    if isinstance(anims[next(iter(anims))], dict):
                         # are the models a dict of dicts too?
                         # are the models a dict of dicts too?
-                        if type(models) == dict:
-                            if type(models[next(iter(models))]) == dict:
+                        if isinstance(models, dict):
+                            if isinstance(models[next(iter(models))], dict):
                                 # then we have a multi-part w/ LOD
                                 # then we have a multi-part w/ LOD
                                 sortedKeys = list(models.keys())
                                 sortedKeys = list(models.keys())
                                 sortedKeys.sort()
                                 sortedKeys.sort()
@@ -313,7 +310,7 @@ class Actor(DirectObject, NodePath):
                                 # then it must be multi-part w/o LOD
                                 # then it must be multi-part w/o LOD
                                 for partName in anims:
                                 for partName in anims:
                                     self.loadAnims(anims[partName], partName)
                                     self.loadAnims(anims[partName], partName)
-                    elif type(models) == dict:
+                    elif isinstance(models, dict):
                         # then we have single-part w/ LOD
                         # then we have single-part w/ LOD
                         sortedKeys = list(models.keys())
                         sortedKeys = list(models.keys())
                         sortedKeys.sort()
                         sortedKeys.sort()
@@ -344,50 +341,46 @@ class Actor(DirectObject, NodePath):
             self.__geomNode.node().setFinal(1)
             self.__geomNode.node().setFinal(1)
 
 
     def delete(self):
     def delete(self):
-        try:
-            self.Actor_deleted
-            return
-        except:
+        if not hasattr(self, 'Actor_deleted'):
             self.Actor_deleted = 1
             self.Actor_deleted = 1
             self.cleanup()
             self.cleanup()
 
 
     def copyActor(self, other, overwrite=False):
     def copyActor(self, other, overwrite=False):
-            # act like a copy constructor
-            self.gotName = other.gotName
-
-            # copy the scene graph elements of other
-            if overwrite:
-                otherCopy = other.copyTo(NodePath())
-                otherCopy.detachNode()
-                # assign these elements to ourselve (overwrite)
-                self.assign(otherCopy)
-            else:
-                # just copy these to ourselves
-                otherCopy = other.copyTo(self)
-            # masad: check if otherCopy has a geomNode as its first child
-            # if actor is initialized with flattenable, then otherCopy, not
-            # its first child, is the geom node; check __init__, for reference
-            if other.getGeomNode().getName() == other.getName():
-                self.setGeomNode(otherCopy)
-            else:
-                self.setGeomNode(otherCopy.getChild(0))
-
-            # copy the switches for lods
-            self.switches = other.switches
-            self.__LODNode = self.find('**/+LODNode')
-            self.__hasLOD = 0
-            if not self.__LODNode.isEmpty():
-                self.__hasLOD = 1
+        # act like a copy constructor
+        self.gotName = other.gotName
+
+        # copy the scene graph elements of other
+        if overwrite:
+            otherCopy = other.copyTo(NodePath())
+            otherCopy.detachNode()
+            # assign these elements to ourselve (overwrite)
+            self.assign(otherCopy)
+        else:
+            # just copy these to ourselves
+            otherCopy = other.copyTo(self)
+        # masad: check if otherCopy has a geomNode as its first child
+        # if actor is initialized with flattenable, then otherCopy, not
+        # its first child, is the geom node; check __init__, for reference
+        if other.getGeomNode().getName() == other.getName():
+            self.setGeomNode(otherCopy)
+        else:
+            self.setGeomNode(otherCopy.getChild(0))
 
 
+        # copy the switches for lods
+        self.switches = other.switches
+        self.__LODNode = self.find('**/+LODNode')
+        self.__hasLOD = 0
+        if not self.__LODNode.isEmpty():
+            self.__hasLOD = 1
 
 
-            # copy the part dictionary from other
-            self.__copyPartBundles(other)
-            self.__copySubpartDict(other)
-            self.__subpartsComplete = other.__subpartsComplete
 
 
-            # copy the anim dictionary from other
-            self.__copyAnimControls(other)
+        # copy the part dictionary from other
+        self.__copyPartBundles(other)
+        self.__copySubpartDict(other)
+        self.__subpartsComplete = other.__subpartsComplete
 
 
+        # copy the anim dictionary from other
+        self.__copyAnimControls(other)
 
 
     def __cmp__(self, other):
     def __cmp__(self, other):
         # Actor inherits from NodePath, which inherits a definition of
         # Actor inherits from NodePath, which inherits a definition of
@@ -514,7 +507,7 @@ class Actor(DirectObject, NodePath):
         self.stop(None)
         self.stop(None)
         self.clearPythonData()
         self.clearPythonData()
         self.flush()
         self.flush()
-        if(self.__geomNode):
+        if self.__geomNode:
             self.__geomNode.removeNode()
             self.__geomNode.removeNode()
             self.__geomNode = None
             self.__geomNode = None
         if not self.isEmpty():
         if not self.isEmpty():
@@ -597,12 +590,10 @@ class Actor(DirectObject, NodePath):
                         'l':1,
                         'l':1,
                         'f':0}
                         'f':0}
 
 
-                """
-                sx = smap.get(x[0], None)
-
-                if sx is None:
-                    self.notify.error('Invalid lodName: %s' % x)
-                """
+                #sx = smap.get(x[0], None)
+                #
+                #if sx is None:
+                #    self.notify.error('Invalid lodName: %s' % x)
                 return smap[x[0]]
                 return smap[x[0]]
             else:
             else:
                 return int(x)
                 return int(x)
@@ -1471,7 +1462,7 @@ class Actor(DirectObject, NodePath):
             #iterate through for a specific part
             #iterate through for a specific part
             for lodData in self.__partBundleDict.values():
             for lodData in self.__partBundleDict.values():
                 partData = lodData.get(partName)
                 partData = lodData.get(partName)
-                if(partData):
+                if partData:
                     char = partData.partBundleNP
                     char = partData.partBundleNP
                     char.node().update()
                     char.node().update()
                     geomNodes = char.findAllMatches("**/+GeomNode")
                     geomNodes = char.findAllMatches("**/+GeomNode")
@@ -1693,11 +1684,20 @@ class Actor(DirectObject, NodePath):
         else:
         else:
             lodName = 'lodRoot'
             lodName = 'lodRoot'
 
 
-        try:
-            return self.__animControlDict[lodName][partName][animName].filename
-        except:
+        partDict = self.__animControlDict.get(lodName)
+        if partDict is None:
+            return None
+
+        animDict = partDict.get(partName)
+        if animDict is None:
+            return None
+
+        anim = animDict.get(animName)
+        if anim is None:
             return None
             return None
 
 
+        return anim.filename
+
     def getAnimControl(self, animName, partName=None, lodName=None,
     def getAnimControl(self, animName, partName=None, lodName=None,
                        allowAsyncBind = True):
                        allowAsyncBind = True):
         """
         """
@@ -1731,7 +1731,6 @@ class Actor(DirectObject, NodePath):
             if anim is None:
             if anim is None:
                 # anim was not present
                 # anim was not present
                 assert Actor.notify.debug("couldn't find anim: %s" % (animName))
                 assert Actor.notify.debug("couldn't find anim: %s" % (animName))
-                pass
             else:
             else:
                 # bind the animation first if we need to
                 # bind the animation first if we need to
                 if not anim.animControl:
                 if not anim.animControl:
@@ -1852,7 +1851,6 @@ class Actor(DirectObject, NodePath):
                         if anim is None:
                         if anim is None:
                             # anim was not present
                             # anim was not present
                             assert Actor.notify.debug("couldn't find anim: %s" % (animName))
                             assert Actor.notify.debug("couldn't find anim: %s" % (animName))
-                            pass
                         else:
                         else:
                             # bind the animation first if we need to
                             # bind the animation first if we need to
                             animControl = anim.animControl
                             animControl = anim.animControl
@@ -1987,7 +1985,7 @@ class Actor(DirectObject, NodePath):
 
 
         node = bundleNP.node()
         node = bundleNP.node()
         # A model loaded from disk will always have just one bundle.
         # A model loaded from disk will always have just one bundle.
-        assert(node.getNumBundles() == 1)
+        assert node.getNumBundles() == 1
         bundleHandle = node.getBundleHandle(0)
         bundleHandle = node.getBundleHandle(0)
 
 
         if self.mergeLODBundles:
         if self.mergeLODBundles:
@@ -2003,7 +2001,7 @@ class Actor(DirectObject, NodePath):
         bundleDict[partName] = Actor.PartDef(bundleNP, bundleHandle, partModel)
         bundleDict[partName] = Actor.PartDef(bundleNP, bundleHandle, partModel)
 
 
 
 
-    def makeSubpart(self, partName, includeJoints, excludeJoints = [],
+    def makeSubpart(self, partName, includeJoints, excludeJoints = (),
                     parent="modelRoot", overlapping = False):
                     parent="modelRoot", overlapping = False):
 
 
         """Defines a new "part" of the Actor that corresponds to the
         """Defines a new "part" of the Actor that corresponds to the
@@ -2128,10 +2126,7 @@ class Actor(DirectObject, NodePath):
             lodNames = ['common']
             lodNames = ['common']
         elif lodName == 'all':
         elif lodName == 'all':
             reload = False
             reload = False
-            lodNames = list(self.switches.keys())
-            lodNames.sort()
-            for i in range(0, len(lodNames)):
-                lodNames[i] = str(lodNames[i])
+            lodNames = list(map(str, sorted(self.switches.keys())))
         else:
         else:
             lodNames = [lodName]
             lodNames = [lodName]
 
 
@@ -2140,11 +2135,10 @@ class Actor(DirectObject, NodePath):
 
 
         firstLoad = True
         firstLoad = True
         if not reload:
         if not reload:
-            try:
-                self.__animControlDict[lodNames[0]][partName]
+            if lodNames[0] in self.__animControlDict and \
+               partName in self.__animControlDict[lodNames[0]]:
                 firstLoad = False
                 firstLoad = False
-            except:
-                pass
+
         for lName in lodNames:
         for lName in lodNames:
             if firstLoad:
             if firstLoad:
                 self.__animControlDict.setdefault(lName, {})
                 self.__animControlDict.setdefault(lName, {})
@@ -2438,7 +2432,7 @@ class Actor(DirectObject, NodePath):
         bundles in our part bundle dict that have matching names, and
         bundles in our part bundle dict that have matching names, and
         store the resulting anim controls in our own part bundle dict"""
         store the resulting anim controls in our own part bundle dict"""
 
 
-        assert(other.mergeLODBundles == self.mergeLODBundles)
+        assert other.mergeLODBundles == self.mergeLODBundles
 
 
         for lodName in other.__animControlDict:
         for lodName in other.__animControlDict:
             self.__animControlDict[lodName] = {}
             self.__animControlDict[lodName] = {}
@@ -2509,11 +2503,10 @@ class Actor(DirectObject, NodePath):
         for lodName, animList in self.getAnimBlends(animName, partName, lodName):
         for lodName, animList in self.getAnimBlends(animName, partName, lodName):
             print('LOD %s:' % (lodName))
             print('LOD %s:' % (lodName))
             for animName, blendList in animList:
             for animName, blendList in animList:
-
-                list = []
+                strings = []
                 for partName, effect in blendList:
                 for partName, effect in blendList:
-                    list.append('%s:%.3f' % (partName, effect))
-                print('  %s: %s' % (animName, ', '.join(list)))
+                    strings.append('%s:%.3f' % (partName, effect))
+                print('  %s: %s' % (animName, ', '.join(strings)))
 
 
     def osdAnimBlends(self, animName=None, partName=None, lodName=None):
     def osdAnimBlends(self, animName=None, partName=None, lodName=None):
         if not onScreenDebug.enabled:
         if not onScreenDebug.enabled:

+ 3 - 7
direct/src/actor/DistributedActor.py

@@ -8,9 +8,7 @@ from . import Actor
 
 
 class DistributedActor(DistributedNode.DistributedNode, Actor.Actor):
 class DistributedActor(DistributedNode.DistributedNode, Actor.Actor):
     def __init__(self, cr):
     def __init__(self, cr):
-        try:
-            self.DistributedActor_initialized
-        except:
+        if not hasattr(self, 'DistributedActor_initialized'):
             self.DistributedActor_initialized = 1
             self.DistributedActor_initialized = 1
             Actor.Actor.__init__(self)
             Actor.Actor.__init__(self)
             DistributedNode.DistributedNode.__init__(self, cr)
             DistributedNode.DistributedNode.__init__(self, cr)
@@ -20,14 +18,12 @@ class DistributedActor(DistributedNode.DistributedNode, Actor.Actor):
 
 
     def disable(self):
     def disable(self):
         # remove all anims, on all parts and all lods
         # remove all anims, on all parts and all lods
-        if (not self.isEmpty()):
+        if not self.isEmpty():
             Actor.Actor.unloadAnims(self, None, None, None)
             Actor.Actor.unloadAnims(self, None, None, None)
         DistributedNode.DistributedNode.disable(self)
         DistributedNode.DistributedNode.disable(self)
 
 
     def delete(self):
     def delete(self):
-        try:
-            self.DistributedActor_deleted
-        except:
+        if not hasattr(self, 'DistributedActor_deleted'):
             self.DistributedActor_deleted = 1
             self.DistributedActor_deleted = 1
             DistributedNode.DistributedNode.delete(self)
             DistributedNode.DistributedNode.delete(self)
             Actor.Actor.delete(self)
             Actor.Actor.delete(self)

+ 35 - 40
direct/src/cluster/ClusterClient.py

@@ -6,6 +6,7 @@ from .ClusterConfig import *
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
 from direct.showbase import DirectObject
 from direct.showbase import DirectObject
 from direct.task import Task
 from direct.task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 import os
 import os
 
 
 
 
@@ -70,7 +71,7 @@ class ClusterClient(DirectObject.DirectObject):
             server = DisplayConnection(
             server = DisplayConnection(
                 self.qcm, serverConfig.serverName,
                 self.qcm, serverConfig.serverName,
                 serverConfig.serverMsgPort, self.msgHandler)
                 serverConfig.serverMsgPort, self.msgHandler)
-            if server == None:
+            if server is None:
                 self.notify.error('Could not open %s on %s port %d' %
                 self.notify.error('Could not open %s on %s port %d' %
                                   (serverConfig.serverConfigName,
                                   (serverConfig.serverConfigName,
                                    serverConfig.serverName,
                                    serverConfig.serverName,
@@ -138,15 +139,14 @@ class ClusterClient(DirectObject.DirectObject):
             object     = pair[1]
             object     = pair[1]
             name       = self.controlMappings[object][0]
             name       = self.controlMappings[object][0]
             serverList = self.controlMappings[object][1]
             serverList = self.controlMappings[object][1]
-            if (object in self.objectMappings):
+            if object in self.objectMappings:
                 self.moveObject(self.objectMappings[object],name,serverList,
                 self.moveObject(self.objectMappings[object],name,serverList,
                                 self.controlOffsets[object], self.objectHasColor[object])
                                 self.controlOffsets[object], self.objectHasColor[object])
         self.sendNamedMovementDone()
         self.sendNamedMovementDone()
         return Task.cont
         return Task.cont
 
 
     def sendNamedMovementDone(self, serverList = None):
     def sendNamedMovementDone(self, serverList = None):
-
-        if (serverList == None):
+        if serverList is None:
             serverList = range(len(self.serverList))
             serverList = range(len(self.serverList))
 
 
         for server in serverList:
         for server in serverList:
@@ -155,7 +155,6 @@ class ClusterClient(DirectObject.DirectObject):
 
 
 
 
     def redoSortedPriorities(self):
     def redoSortedPriorities(self):
-
         self.sortedControlMappings = []
         self.sortedControlMappings = []
         for key in self.controlMappings:
         for key in self.controlMappings:
             self.sortedControlMappings.append([self.controlPriorities[key],
             self.sortedControlMappings.append([self.controlPriorities[key],
@@ -169,7 +168,7 @@ class ClusterClient(DirectObject.DirectObject):
         hpr = nodePath.getHpr(render)
         hpr = nodePath.getHpr(render)
         scale = nodePath.getScale(render)
         scale = nodePath.getScale(render)
         hidden = nodePath.isHidden()
         hidden = nodePath.isHidden()
-        if (hasColor):
+        if hasColor:
             color = nodePath.getColor()
             color = nodePath.getColor()
         else:
         else:
             color = [1,1,1,1]
             color = [1,1,1,1]
@@ -193,7 +192,7 @@ class ClusterClient(DirectObject.DirectObject):
 
 
     def moveSelectedTask(self, state):
     def moveSelectedTask(self, state):
         # Update cluster if current display is a cluster client
         # Update cluster if current display is a cluster client
-        if (last is not None):
+        if last is not None:
             self.notify.debug('moving selected node path')
             self.notify.debug('moving selected node path')
             xyz = Point3(0)
             xyz = Point3(0)
             hpr = VBase3(0)
             hpr = VBase3(0)
@@ -204,24 +203,24 @@ class ClusterClient(DirectObject.DirectObject):
         return Task.cont
         return Task.cont
 
 
 
 
-    def addNamedObjectMapping(self,object,name,hasColor = True):
-        if (name not in self.objectMappings):
+    def addNamedObjectMapping(self, object, name, hasColor = True):
+        if name not in self.objectMappings:
             self.objectMappings[name] = object
             self.objectMappings[name] = object
             self.objectHasColor[name] = hasColor
             self.objectHasColor[name] = hasColor
         else:
         else:
             self.notify.debug('attempt to add duplicate named object: '+name)
             self.notify.debug('attempt to add duplicate named object: '+name)
 
 
     def removeObjectMapping(self,name):
     def removeObjectMapping(self,name):
-        if (name in self.objectMappings):
+        if name in self.objectMappings:
             self.objectMappings.pop(name)
             self.objectMappings.pop(name)
 
 
 
 
-    def addControlMapping(self,objectName,controlledName, serverList = None,
+    def addControlMapping(self, objectName, controlledName, serverList = None,
                           offset = None, priority = 0):
                           offset = None, priority = 0):
-        if (objectName not in self.controlMappings):
-            if (serverList == None):
+        if objectName not in self.controlMappings:
+            if serverList is None:
                 serverList = range(len(self.serverList))
                 serverList = range(len(self.serverList))
-            if (offset == None):
+            if offset is None:
                 offset = Vec3(0,0,0)
                 offset = Vec3(0,0,0)
 
 
             self.controlMappings[objectName] = [controlledName,serverList]
             self.controlMappings[objectName] = [controlledName,serverList]
@@ -233,30 +232,29 @@ class ClusterClient(DirectObject.DirectObject):
             for item in oldList:
             for item in oldList:
                 mergedList.append(item)
                 mergedList.append(item)
             for item in serverList:
             for item in serverList:
-                if (item not in mergedList):
+                if item not in mergedList:
                     mergedList.append(item)
                     mergedList.append(item)
 
 
         self.redoSortedPriorities()
         self.redoSortedPriorities()
             #self.notify.debug('attempt to add duplicate controlled object: '+name)
             #self.notify.debug('attempt to add duplicate controlled object: '+name)
 
 
-    def setControlMappingOffset(self,objectName,offset):
-        if (objectName in self.controlMappings):
+    def setControlMappingOffset(self, objectName, offset):
+        if objectName in self.controlMappings:
             self.controlOffsets[objectName] = offset
             self.controlOffsets[objectName] = offset
 
 
-    def removeControlMapping(self,name, serverList = None):
-        if (name in self.controlMappings):
-
-            if (serverList == None):
+    def removeControlMapping(self, name, serverList = None):
+        if name in self.controlMappings:
+            if serverList is None:
                 self.controlMappings.pop(name)
                 self.controlMappings.pop(name)
                 self.controlPriorities.pop(name)
                 self.controlPriorities.pop(name)
             else:
             else:
-                list = self.controlMappings[key][1]
+                oldList = self.controlMappings[key][1]
                 newList = []
                 newList = []
-                for server in list:
-                    if (server not in serverList):
+                for server in oldList:
+                    if server not in serverList:
                         newList.append(server)
                         newList.append(server)
                 self.controlMappings[key][1] = newList
                 self.controlMappings[key][1] = newList
-                if (len(newList) == 0):
+                if len(newList) == 0:
                     self.controlMappings.pop(name)
                     self.controlMappings.pop(name)
                     self.controlPriorities.pop(name)
                     self.controlPriorities.pop(name)
         self.redoSortedPriorities()
         self.redoSortedPriorities()
@@ -303,7 +301,7 @@ class ClusterClient(DirectObject.DirectObject):
             tag = self.taggedObjects[name]
             tag = self.taggedObjects[name]
             function = tag["selectFunction"]
             function = tag["selectFunction"]
             args     = tag["selectArgs"]
             args     = tag["selectArgs"]
-            if (function != None):
+            if function is not None:
                 function(*args)
                 function(*args)
         else:
         else:
             self(self.getNodePathFindCmd(nodePath) + '.select()', 0)
             self(self.getNodePathFindCmd(nodePath) + '.select()', 0)
@@ -315,7 +313,7 @@ class ClusterClient(DirectObject.DirectObject):
             tag = self.taggedObjects[name]
             tag = self.taggedObjects[name]
             function = tag["deselectFunction"]
             function = tag["deselectFunction"]
             args     = tag["deselectArgs"]
             args     = tag["deselectArgs"]
-            if (function != None):
+            if function is not None:
                 function(*args)
                 function(*args)
             self.startMoveSelectedTask()
             self.startMoveSelectedTask()
         self(self.getNodePathFindCmd(nodePath) + '.deselect()', 0)
         self(self.getNodePathFindCmd(nodePath) + '.deselect()', 0)
@@ -348,24 +346,23 @@ class ClusterClient(DirectObject.DirectObject):
 
 
 
 
     def handleDatagram(self,dgi,type,server):
     def handleDatagram(self,dgi,type,server):
-        if (type == CLUSTER_NONE):
+        if type == CLUSTER_NONE:
             pass
             pass
-        elif (type == CLUSTER_NAMED_OBJECT_MOVEMENT):
+        elif type == CLUSTER_NAMED_OBJECT_MOVEMENT:
             self.serverQueues[server].append(self.msgHandler.parseNamedMovementDatagram(dgi))
             self.serverQueues[server].append(self.msgHandler.parseNamedMovementDatagram(dgi))
             #self.handleNamedMovement(dgi)
             #self.handleNamedMovement(dgi)
         # when we recieve a 'named movement done' packet from a server we handle
         # when we recieve a 'named movement done' packet from a server we handle
         # all of its messages
         # all of its messages
-        elif (type == CLUSTER_NAMED_MOVEMENT_DONE):
+        elif type == CLUSTER_NAMED_MOVEMENT_DONE:
             self.handleMessageQueue(server)
             self.handleMessageQueue(server)
         else:
         else:
             self.notify.warning("Received unsupported packet type:" % type)
             self.notify.warning("Received unsupported packet type:" % type)
         return type
         return type
 
 
     def handleMessageQueue(self,server):
     def handleMessageQueue(self,server):
-
-        list = self.serverQueues[server]
+        queue = self.serverQueues[server]
         # handle all messages in the queue
         # handle all messages in the queue
-        for data in list:
+        for data in queue:
             #print dgi
             #print dgi
             self.handleNamedMovement(data)
             self.handleNamedMovement(data)
 
 
@@ -378,14 +375,14 @@ class ClusterClient(DirectObject.DirectObject):
 
 
         (name,x, y, z, h, p, r, sx, sy, sz,red,g,b,a, hidden) = data
         (name,x, y, z, h, p, r, sx, sy, sz,red,g,b,a, hidden) = data
         #print "name"
         #print "name"
-        #if (name == "camNode"):
+        #if name == "camNode":
         #    print x,y,z,h,p,r, sx, sy, sz,red,g,b,a, hidden
         #    print x,y,z,h,p,r, sx, sy, sz,red,g,b,a, hidden
-        if (name in self.objectMappings):
+        if name in self.objectMappings:
             self.objectMappings[name].setPosHpr(render, x, y, z, h, p, r)
             self.objectMappings[name].setPosHpr(render, x, y, z, h, p, r)
             self.objectMappings[name].setScale(render,sx,sy,sz)
             self.objectMappings[name].setScale(render,sx,sy,sz)
-            if (self.objectHasColor[name]):
+            if self.objectHasColor[name]:
                 self.objectMappings[name].setColor(red,g,b,a)
                 self.objectMappings[name].setColor(red,g,b,a)
-            if (hidden):
+            if hidden:
                 self.objectMappings[name].hide()
                 self.objectMappings[name].hide()
             else:
             else:
                 self.objectMappings[name].show()
                 self.objectMappings[name].show()
@@ -451,7 +448,7 @@ class DisplayConnection:
         self.tcpConn = qcm.openTCPClientConnection(
         self.tcpConn = qcm.openTCPClientConnection(
             serverName, port, gameServerTimeoutMs)
             serverName, port, gameServerTimeoutMs)
         # Test for bad connection
         # Test for bad connection
-        if self.tcpConn == None:
+        if self.tcpConn is None:
             return None
             return None
         else:
         else:
             self.tcpConn.setNoDelay(1)
             self.tcpConn.setNoDelay(1)
@@ -680,5 +677,3 @@ class DummyClusterClient(DirectObject.DirectObject):
         if fLocally:
         if fLocally:
             # Execute locally
             # Execute locally
             exec(commandString, __builtins__)
             exec(commandString, __builtins__)
-
-

+ 0 - 1
direct/src/cluster/ClusterConfig.py

@@ -165,4 +165,3 @@ ClientConfigs = {
                               }
                               }
                              ],
                              ],
     }
     }
-

+ 10 - 19
direct/src/cluster/ClusterMsgs.py

@@ -59,17 +59,17 @@ class ClusterMsgHandler:
         if qcr.dataAvailable():
         if qcr.dataAvailable():
             datagram = NetDatagram()
             datagram = NetDatagram()
             if qcr.getData(datagram):
             if qcr.getData(datagram):
-                (dgi, type) = self.readHeader(datagram)
+                (dgi, dtype) = self.readHeader(datagram)
             else:
             else:
                 dgi = None
                 dgi = None
-                type = CLUSTER_NONE
+                dtype = CLUSTER_NONE
                 self.notify.warning("getData returned false")
                 self.notify.warning("getData returned false")
         else:
         else:
             datagram = None
             datagram = None
             dgi = None
             dgi = None
-            type = CLUSTER_NONE
+            dtype = CLUSTER_NONE
         # Note, return datagram to keep a handle on the data
         # Note, return datagram to keep a handle on the data
-        return (datagram, dgi, type)
+        return (datagram, dgi, dtype)
 
 
     def blockingRead(self, qcr):
     def blockingRead(self, qcr):
         """
         """
@@ -85,19 +85,19 @@ class ClusterMsgHandler:
         # Data is available, create a datagram iterator
         # Data is available, create a datagram iterator
         datagram = NetDatagram()
         datagram = NetDatagram()
         if qcr.getData(datagram):
         if qcr.getData(datagram):
-            (dgi, type) = self.readHeader(datagram)
+            (dgi, dtype) = self.readHeader(datagram)
         else:
         else:
-            (dgi, type) = (None, CLUSTER_NONE)
+            (dgi, dtype) = (None, CLUSTER_NONE)
             self.notify.warning("getData returned false")
             self.notify.warning("getData returned false")
         # Note, return datagram to keep a handle on the data
         # Note, return datagram to keep a handle on the data
-        return (datagram, dgi, type)
+        return (datagram, dgi, dtype)
 
 
     def readHeader(self, datagram):
     def readHeader(self, datagram):
         dgi = PyDatagramIterator(datagram)
         dgi = PyDatagramIterator(datagram)
         number = dgi.getUint32()
         number = dgi.getUint32()
-        type = dgi.getUint8()
-        self.notify.debug("Packet %d type %d received" % (number, type))
-        return (dgi, type)
+        dtype = dgi.getUint8()
+        self.notify.debug("Packet %d type %d received" % (number, dtype))
+        return (dgi, dtype)
 
 
     def makeCamOffsetDatagram(self, xyz, hpr):
     def makeCamOffsetDatagram(self, xyz, hpr):
         datagram = PyDatagram()
         datagram = PyDatagram()
@@ -298,12 +298,3 @@ class ClusterMsgHandler:
         dt=dgi.getFloat32()
         dt=dgi.getFloat32()
         self.notify.debug('time data=%f %f' % (frameTime, dt))
         self.notify.debug('time data=%f %f' % (frameTime, dt))
         return (frameCount, frameTime, dt)
         return (frameCount, frameTime, dt)
-
-
-
-
-
-
-
-
-

+ 28 - 30
direct/src/cluster/ClusterServer.py

@@ -4,6 +4,7 @@ from direct.distributed.MsgTypes import *
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
 from direct.showbase import DirectObject
 from direct.showbase import DirectObject
 from direct.task import Task
 from direct.task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 
 
 # NOTE: This assumes the following variables are set via bootstrap command line
 # NOTE: This assumes the following variables are set via bootstrap command line
 # arguments on server startup:
 # arguments on server startup:
@@ -100,16 +101,16 @@ class ClusterServer(DirectObject.DirectObject):
         return Task.cont
         return Task.cont
 
 
 
 
-    def addNamedObjectMapping(self,object,name,hasColor = True,
+    def addNamedObjectMapping(self, object, name, hasColor = True,
                               priority = 0):
                               priority = 0):
-        if (name not in self.objectMappings):
+        if name not in self.objectMappings:
             self.objectMappings[name] = object
             self.objectMappings[name] = object
             self.objectHasColor[name] = hasColor
             self.objectHasColor[name] = hasColor
         else:
         else:
             self.notify.debug('attempt to add duplicate named object: '+name)
             self.notify.debug('attempt to add duplicate named object: '+name)
 
 
-    def removeObjectMapping(self,name):
-        if (name in self.objectMappings):
+    def removeObjectMapping(self, name):
+        if name in self.objectMappings:
             self.objectMappings.pop(name)
             self.objectMappings.pop(name)
 
 
 
 
@@ -123,11 +124,11 @@ class ClusterServer(DirectObject.DirectObject):
         self.sortedControlMappings.sort()
         self.sortedControlMappings.sort()
 
 
 
 
-    def addControlMapping(self,objectName,controlledName, offset = None,
+    def addControlMapping(self, objectName, controlledName, offset = None,
                           priority = 0):
                           priority = 0):
-        if (objectName not in self.controlMappings):
+        if objectName not in self.controlMappings:
             self.controlMappings[objectName] = controlledName
             self.controlMappings[objectName] = controlledName
-            if (offset == None):
+            if offset is None:
                 offset = Vec3(0,0,0)
                 offset = Vec3(0,0,0)
             self.controlOffsets[objectName]  = offset
             self.controlOffsets[objectName]  = offset
             self.controlPriorities[objectName] = priority
             self.controlPriorities[objectName] = priority
@@ -135,13 +136,13 @@ class ClusterServer(DirectObject.DirectObject):
         else:
         else:
             self.notify.debug('attempt to add duplicate controlled object: '+name)
             self.notify.debug('attempt to add duplicate controlled object: '+name)
 
 
-    def setControlMappingOffset(self,objectName,offset):
-        if (objectName in self.controlMappings):
+    def setControlMappingOffset(self, objectName, offset):
+        if objectName in self.controlMappings:
             self.controlOffsets[objectName] = offset
             self.controlOffsets[objectName] = offset
 
 
 
 
-    def removeControlMapping(self,name):
-        if (name in self.controlMappings):
+    def removeControlMapping(self, name):
+        if name in self.controlMappings:
             self.controlMappings.pop(name)
             self.controlMappings.pop(name)
             self.controlPriorities.pop(name)
             self.controlPriorities.pop(name)
         self.redoSortedPriorities()
         self.redoSortedPriorities()
@@ -156,7 +157,7 @@ class ClusterServer(DirectObject.DirectObject):
         for pair in self.sortedControlPriorities:
         for pair in self.sortedControlPriorities:
             object = pair[1]
             object = pair[1]
             name   = self.controlMappings[object]
             name   = self.controlMappings[object]
-            if (object in self.objectMappings):
+            if object in self.objectMappings:
                 self.moveObject(self.objectMappings[object],name,self.controlOffsets[object],
                 self.moveObject(self.objectMappings[object],name,self.controlOffsets[object],
                                 self.objectHasColor[object])
                                 self.objectHasColor[object])
 
 
@@ -165,7 +166,6 @@ class ClusterServer(DirectObject.DirectObject):
 
 
 
 
     def sendNamedMovementDone(self):
     def sendNamedMovementDone(self):
-
         self.notify.debug("named movement done")
         self.notify.debug("named movement done")
         datagram = self.msgHandler.makeNamedMovementDone()
         datagram = self.msgHandler.makeNamedMovementDone()
         self.cw.send(datagram,self.lastConnection)
         self.cw.send(datagram,self.lastConnection)
@@ -176,7 +176,7 @@ class ClusterServer(DirectObject.DirectObject):
         xyz = nodePath.getPos(render) + offset
         xyz = nodePath.getPos(render) + offset
         hpr = nodePath.getHpr(render)
         hpr = nodePath.getHpr(render)
         scale = nodePath.getScale(render)
         scale = nodePath.getScale(render)
-        if (hasColor):
+        if hasColor:
             color = nodePath.getColor()
             color = nodePath.getColor()
         else:
         else:
             color = [1,1,1,1]
             color = [1,1,1,1]
@@ -243,34 +243,34 @@ class ClusterServer(DirectObject.DirectObject):
 
 
     def handleDatagram(self, dgi, type):
     def handleDatagram(self, dgi, type):
         """ Process a datagram depending upon type flag """
         """ Process a datagram depending upon type flag """
-        if (type == CLUSTER_NONE):
+        if type == CLUSTER_NONE:
             pass
             pass
-        elif (type == CLUSTER_EXIT):
+        elif type == CLUSTER_EXIT:
             print('GOT EXIT')
             print('GOT EXIT')
             import sys
             import sys
             sys.exit()
             sys.exit()
-        elif (type == CLUSTER_CAM_OFFSET):
+        elif type == CLUSTER_CAM_OFFSET:
             self.handleCamOffset(dgi)
             self.handleCamOffset(dgi)
-        elif (type == CLUSTER_CAM_FRUSTUM):
+        elif type == CLUSTER_CAM_FRUSTUM:
             self.handleCamFrustum(dgi)
             self.handleCamFrustum(dgi)
-        elif (type == CLUSTER_CAM_MOVEMENT):
+        elif type == CLUSTER_CAM_MOVEMENT:
             self.handleCamMovement(dgi)
             self.handleCamMovement(dgi)
-        elif (type == CLUSTER_SELECTED_MOVEMENT):
+        elif type == CLUSTER_SELECTED_MOVEMENT:
             self.handleSelectedMovement(dgi)
             self.handleSelectedMovement(dgi)
-        elif (type == CLUSTER_COMMAND_STRING):
+        elif type == CLUSTER_COMMAND_STRING:
             self.handleCommandString(dgi)
             self.handleCommandString(dgi)
-        elif (type == CLUSTER_SWAP_READY):
+        elif type == CLUSTER_SWAP_READY:
             pass
             pass
-        elif (type == CLUSTER_SWAP_NOW):
+        elif type == CLUSTER_SWAP_NOW:
             self.notify.debug('swapping')
             self.notify.debug('swapping')
             base.graphicsEngine.flipFrame()
             base.graphicsEngine.flipFrame()
-        elif (type == CLUSTER_TIME_DATA):
+        elif type == CLUSTER_TIME_DATA:
             self.notify.debug('time data')
             self.notify.debug('time data')
             self.handleTimeData(dgi)
             self.handleTimeData(dgi)
-        elif (type == CLUSTER_NAMED_OBJECT_MOVEMENT):
+        elif type == CLUSTER_NAMED_OBJECT_MOVEMENT:
             self.messageQueue.append(self.msgHandler.parseNamedMovementDatagram(dgi))
             self.messageQueue.append(self.msgHandler.parseNamedMovementDatagram(dgi))
             #self.handleNamedMovement(dgi)
             #self.handleNamedMovement(dgi)
-        elif (type == CLUSTER_NAMED_MOVEMENT_DONE):
+        elif type == CLUSTER_NAMED_MOVEMENT_DONE:
             #print "got done",self.messageQueue
             #print "got done",self.messageQueue
             #if (len(self.messageQueue) > 0):
             #if (len(self.messageQueue) > 0):
             #    print self.messageQueue[0]
             #    print self.messageQueue[0]
@@ -297,11 +297,11 @@ class ClusterServer(DirectObject.DirectObject):
     def handleNamedMovement(self, data):
     def handleNamedMovement(self, data):
         """ Update cameraJig position to reflect latest position """
         """ Update cameraJig position to reflect latest position """
         (name,x, y, z, h, p, r,sx,sy,sz, red, g, b, a, hidden) = data
         (name,x, y, z, h, p, r,sx,sy,sz, red, g, b, a, hidden) = data
-        if (name in self.objectMappings):
+        if name in self.objectMappings:
             self.objectMappings[name].setPosHpr(render, x, y, z, h, p, r)
             self.objectMappings[name].setPosHpr(render, x, y, z, h, p, r)
             self.objectMappings[name].setScale(render,sx,sy,sz)
             self.objectMappings[name].setScale(render,sx,sy,sz)
             self.objectMappings[name].setColor(red,g,b,a)
             self.objectMappings[name].setColor(red,g,b,a)
-            if (hidden):
+            if hidden:
                 self.objectMappings[name].hide()
                 self.objectMappings[name].hide()
             else:
             else:
                 self.objectMappings[name].show()
                 self.objectMappings[name].show()
@@ -346,5 +346,3 @@ class ClusterServer(DirectObject.DirectObject):
             exec(command, __builtins__)
             exec(command, __builtins__)
         except:
         except:
             pass
             pass
-
-

+ 2 - 148
direct/src/controls/BattleWalker.py

@@ -1,5 +1,6 @@
 
 
 from direct.showbase.InputStateGlobal import inputState
 from direct.showbase.InputStateGlobal import inputState
+from direct.showbase.MessengerGlobal import messenger
 from direct.task.Task import Task
 from direct.task.Task import Task
 from panda3d.core import *
 from panda3d.core import *
 from . import GravityWalker
 from . import GravityWalker
@@ -54,7 +55,7 @@ class BattleWalker(GravityWalker.GravityWalker):
 
 
         debugRunning = inputState.isSet("debugRunning")
         debugRunning = inputState.isSet("debugRunning")
 
 
-        if(debugRunning):
+        if debugRunning:
             self.speed*=base.debugRunningMultiplier
             self.speed*=base.debugRunningMultiplier
             self.slideSpeed*=base.debugRunningMultiplier
             self.slideSpeed*=base.debugRunningMultiplier
             self.rotationSpeed*=1.25
             self.rotationSpeed*=1.25
@@ -139,150 +140,3 @@ class BattleWalker(GravityWalker.GravityWalker):
         if self.moving or jump:
         if self.moving or jump:
             messenger.send("avatarMoving")
             messenger.send("avatarMoving")
         return Task.cont
         return Task.cont
-
-    if 0:
-        def handleAvatarControls(self, task):
-            # If targetNp is not available, revert back to GravityWalker.handleAvatarControls.
-            # This situation occurs when the target dies, but we aren't switched out of
-            # battle walker control mode.
-
-            targetNp = self.avatarNodePath.currentTarget
-            if not BattleStrafe or targetNp == None or targetNp.isEmpty():
-                return GravityWalker.GravityWalker.handleAvatarControls(self, task)
-
-            # get the button states:
-            run = inputState.isSet("run")
-            forward = inputState.isSet("forward")
-            reverse = inputState.isSet("reverse")
-            turnLeft = inputState.isSet("turnLeft")
-            turnRight = inputState.isSet("turnRight")
-            slide = inputState.isSet("slide")
-            jump = inputState.isSet("jump")
-            # Determine what the speeds are based on the buttons:
-            self.advanceSpeed=(forward and self.avatarControlForwardSpeed or
-                               reverse and -self.avatarControlReverseSpeed)
-            if run and self.advanceSpeed>0.0:
-                self.advanceSpeed*=2.0 #*#
-            # Should fSlide be renamed slideButton?
-            self.slideSpeed=.15*(turnLeft and -self.avatarControlForwardSpeed or
-                                 turnRight and self.avatarControlForwardSpeed)
-            print('slideSpeed: %s' % self.slideSpeed)
-            self.rotationSpeed=0
-            self.speed=0
-
-            debugRunning = inputState.isSet("debugRunning")
-            if debugRunning:
-                self.advanceSpeed*=4.0
-                self.slideSpeed*=4.0
-                self.rotationSpeed*=1.25
-
-            if self.needToDeltaPos:
-                self.setPriorParentVector()
-                self.needToDeltaPos = 0
-            if self.wantDebugIndicator:
-                self.displayDebugInfo()
-            if self.lifter.isOnGround():
-                if self.isAirborne:
-                    self.isAirborne = 0
-                    assert self.debugPrint("isAirborne 0 due to isOnGround() true")
-                    impact = self.lifter.getImpactVelocity()
-                    if impact < -30.0:
-                        messenger.send("jumpHardLand")
-                        self.startJumpDelay(0.3)
-                    else:
-                        messenger.send("jumpLand")
-                        if impact < -5.0:
-                            self.startJumpDelay(0.2)
-                        # else, ignore the little potholes.
-                assert self.isAirborne == 0
-                self.priorParent = Vec3.zero()
-                if jump and self.mayJump:
-                    # The jump button is down and we're close
-                    # enough to the ground to jump.
-                    self.lifter.addVelocity(self.avatarControlJumpForce)
-                    messenger.send("jumpStart")
-                    self.isAirborne = 1
-                    assert self.debugPrint("isAirborne 1 due to jump")
-            else:
-                if self.isAirborne == 0:
-                    assert self.debugPrint("isAirborne 1 due to isOnGround() false")
-                self.isAirborne = 1
-
-            self.__oldPosDelta = self.avatarNodePath.getPosDelta(render)
-            # How far did we move based on the amount of time elapsed?
-            self.__oldDt = ClockObject.getGlobalClock().getDt()
-            dt=self.__oldDt
-
-            # Before we do anything with position or orientation, make the avatar
-            # face it's target.  Only allow rMax degrees rotation per frame, so
-            # we don't get an unnatural spinning effect
-            curH = self.avatarNodePath.getH()
-            self.avatarNodePath.headsUp(targetNp)
-            newH = self.avatarNodePath.getH()
-            delH = reduceAngle(newH-curH)
-            rMax = 10
-            if delH < -rMax:
-                self.avatarNodePath.setH(curH-rMax)
-                self.rotationSpeed=-self.avatarControlRotateSpeed
-            elif delH > rMax:
-                self.avatarNodePath.setH(curH+rMax)
-                self.rotationSpeed=self.avatarControlRotateSpeed
-
-            # Check to see if we're moving at all:
-            self.moving = self.speed or self.slideSpeed or self.rotationSpeed or (self.priorParent!=Vec3.zero())
-            if self.moving:
-                distance = dt * self.speed
-                slideDistance = dt * self.slideSpeed
-                print('slideDistance: %s' % slideDistance)
-                rotation = dt * self.rotationSpeed
-
-                # Take a step in the direction of our previous heading.
-                self.vel=Vec3(Vec3.forward() * distance +
-                              Vec3.right() * slideDistance)
-                if self.vel != Vec3.zero() or self.priorParent != Vec3.zero():
-                    if 1:
-                        # rotMat is the rotation matrix corresponding to
-                        # our previous heading.
-                        rotMat=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
-                        step=(self.priorParent * dt) + rotMat.xform(self.vel)
-                        self.avatarNodePath.setFluidPos(Point3(
-                                self.avatarNodePath.getPos()+step))
-                self.avatarNodePath.setH(self.avatarNodePath.getH()+rotation)
-            else:
-                self.vel.set(0.0, 0.0, 0.0)
-
-            """
-            # Check to see if we're moving at all:
-            self.moving = self.advanceSpeed or self.slideSpeed or self.rotationSpeed or (self.priorParent!=Vec3.zero())
-            if self.moving:
-                distance = dt * self.advanceSpeed
-                slideDistance = dt * self.slideSpeed
-                rotation = dt * self.rotationSpeed
-
-                # Prevent avatar from getting too close to target
-                d = self.avatarNodePath.getPos(targetNp)
-                # TODO:  make min distance adjust for current weapon
-                if (d[0]*d[0]+d[1]*d[1] < 6.0 and distance > 0):
-                    # move the avatar sideways instead of forward
-                    slideDistance += .2
-                    distance = 0
-
-                # Take a step in the direction of our previous heading.
-                self.vel=Vec3(Vec3.forward() * distance +
-                              Vec3.right() * slideDistance)
-                if self.vel != Vec3.zero() or self.priorParent != Vec3.zero():
-                    # rotMat is the rotation matrix corresponding to
-                    # our previous heading.
-                    rotMat=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
-                    step=rotMat.xform(self.vel) + (self.priorParent * dt)
-                    self.avatarNodePath.setFluidPos(Point3(
-                        self.avatarNodePath.getPos()+step))
-                self.avatarNodePath.setH(self.avatarNodePath.getH()+rotation)
-            else:
-                self.vel.set(0.0, 0.0, 0.0)
-            """
-            if self.moving or jump:
-                messenger.send("avatarMoving")
-            return Task.cont
-
-

+ 9 - 9
direct/src/controls/ControlManager.py

@@ -1,5 +1,6 @@
 
 
 from direct.showbase.InputStateGlobal import inputState
 from direct.showbase.InputStateGlobal import inputState
+from direct.showbase.MessengerGlobal import messenger
 #from DirectGui import *
 #from DirectGui import *
 #from PythonUtil import *
 #from PythonUtil import *
 #from IntervalGlobal import *
 #from IntervalGlobal import *
@@ -292,18 +293,18 @@ class ControlManager:
         self.forceAvJumpToken.release()
         self.forceAvJumpToken.release()
         self.forceAvJumpToken = None
         self.forceAvJumpToken = None
 
 
-    def monitor(self, foo):
+    def monitor(self, _):
         #assert self.debugPrint("monitor()")
         #assert self.debugPrint("monitor()")
         #if 1:
         #if 1:
         #    airborneHeight=self.avatar.getAirborneHeight()
         #    airborneHeight=self.avatar.getAirborneHeight()
         #    onScreenDebug.add("airborneHeight", "% 10.4f"%(airborneHeight,))
         #    onScreenDebug.add("airborneHeight", "% 10.4f"%(airborneHeight,))
-        if 0:
-            onScreenDebug.add("InputState forward", "%d"%(inputState.isSet("forward")))
-            onScreenDebug.add("InputState reverse", "%d"%(inputState.isSet("reverse")))
-            onScreenDebug.add("InputState turnLeft", "%d"%(inputState.isSet("turnLeft")))
-            onScreenDebug.add("InputState turnRight", "%d"%(inputState.isSet("turnRight")))
-            onScreenDebug.add("InputState slideLeft", "%d"%(inputState.isSet("slideLeft")))
-            onScreenDebug.add("InputState slideRight", "%d"%(inputState.isSet("slideRight")))
+        #if 0:
+        #    onScreenDebug.add("InputState forward", "%d"%(inputState.isSet("forward")))
+        #    onScreenDebug.add("InputState reverse", "%d"%(inputState.isSet("reverse")))
+        #    onScreenDebug.add("InputState turnLeft", "%d"%(inputState.isSet("turnLeft")))
+        #    onScreenDebug.add("InputState turnRight", "%d"%(inputState.isSet("turnRight")))
+        #    onScreenDebug.add("InputState slideLeft", "%d"%(inputState.isSet("slideLeft")))
+        #    onScreenDebug.add("InputState slideRight", "%d"%(inputState.isSet("slideRight")))
         return Task.cont
         return Task.cont
 
 
     def setWASDTurn(self, turn):
     def setWASDTurn(self, turn):
@@ -343,4 +344,3 @@ class ControlManager:
 
 
             inputState.set("turnLeft", False, inputSource=inputState.WASD)
             inputState.set("turnLeft", False, inputSource=inputState.WASD)
             inputState.set("turnRight", False, inputSource=inputState.WASD)
             inputState.set("turnRight", False, inputSource=inputState.WASD)
-

+ 2 - 0
direct/src/controls/DevWalker.py

@@ -19,7 +19,9 @@ animations based on walker events.
 from direct.showbase.InputStateGlobal import inputState
 from direct.showbase.InputStateGlobal import inputState
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
 from direct.showbase import DirectObject
 from direct.showbase import DirectObject
+from direct.showbase.MessengerGlobal import messenger
 from direct.task.Task import Task
 from direct.task.Task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 from panda3d.core import *
 from panda3d.core import *
 
 
 
 

+ 10 - 8
direct/src/controls/GravityWalker.py

@@ -19,10 +19,12 @@ from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.showbase import DirectObject
 from direct.showbase import DirectObject
 from direct.controls.ControlManager import CollisionHandlerRayStart
 from direct.controls.ControlManager import CollisionHandlerRayStart
 from direct.showbase.InputStateGlobal import inputState
 from direct.showbase.InputStateGlobal import inputState
+from direct.showbase.MessengerGlobal import messenger
 from direct.task.Task import Task
 from direct.task.Task import Task
-from panda3d.core import *
+from direct.task.TaskManagerGlobal import taskMgr
 from direct.extensions_native import VBase3_extensions
 from direct.extensions_native import VBase3_extensions
 from direct.extensions_native import VBase4_extensions
 from direct.extensions_native import VBase4_extensions
+from panda3d.core import *
 import math
 import math
 
 
 
 
@@ -142,7 +144,7 @@ class GravityWalker(DirectObject.DirectObject):
         cSphereNode.setIntoCollideMask(BitMask32.allOff())
         cSphereNode.setIntoCollideMask(BitMask32.allOff())
 
 
         # set up collision mechanism
         # set up collision mechanism
-        if config.GetBool('want-fluid-pusher', 0):
+        if ConfigVariableBool('want-fluid-pusher', 0):
             self.pusher = CollisionHandlerFluidPusher()
             self.pusher = CollisionHandlerFluidPusher()
         else:
         else:
             self.pusher = CollisionHandlerPusher()
             self.pusher = CollisionHandlerPusher()
@@ -284,11 +286,11 @@ class GravityWalker(DirectObject.DirectObject):
             # make sure we have a shadow traverser
             # make sure we have a shadow traverser
             base.initShadowTrav()
             base.initShadowTrav()
             if active:
             if active:
-                if 1:
-                    # Please let skyler or drose know if this is causing a problem
-                    # This is a bit of a hack fix:
-                    self.avatarNodePath.setP(0.0)
-                    self.avatarNodePath.setR(0.0)
+                # Please let skyler or drose know if this is causing a problem
+                # This is a bit of a hack fix:
+                self.avatarNodePath.setP(0.0)
+                self.avatarNodePath.setR(0.0)
+
                 self.cTrav.addCollider(self.cWallSphereNodePath, self.pusher)
                 self.cTrav.addCollider(self.cWallSphereNodePath, self.pusher)
                 if self.wantFloorSphere:
                 if self.wantFloorSphere:
                     self.cTrav.addCollider(self.cFloorSphereNodePath, self.pusherFloor)
                     self.cTrav.addCollider(self.cFloorSphereNodePath, self.pusherFloor)
@@ -440,7 +442,7 @@ class GravityWalker(DirectObject.DirectObject):
             self.slideSpeed *= GravityWalker.DiagonalFactor
             self.slideSpeed *= GravityWalker.DiagonalFactor
 
 
         debugRunning = inputState.isSet("debugRunning")
         debugRunning = inputState.isSet("debugRunning")
-        if(debugRunning):
+        if debugRunning:
             self.speed*=base.debugRunningMultiplier
             self.speed*=base.debugRunningMultiplier
             self.slideSpeed*=base.debugRunningMultiplier
             self.slideSpeed*=base.debugRunningMultiplier
             self.rotationSpeed*=1.25
             self.rotationSpeed*=1.25

+ 2 - 0
direct/src/controls/InputState.py

@@ -1,6 +1,8 @@
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
 from direct.showbase import DirectObject
 from direct.showbase import DirectObject
 from direct.showbase.PythonUtil import SerialNumGen
 from direct.showbase.PythonUtil import SerialNumGen
+from direct.showbase.MessengerGlobal import messenger
+
 
 
 # internal class, don't create these on your own
 # internal class, don't create these on your own
 class InputStateToken:
 class InputStateToken:

+ 7 - 5
direct/src/controls/NonPhysicsWalker.py

@@ -20,7 +20,9 @@ from direct.directnotify import DirectNotifyGlobal
 from direct.showbase import DirectObject
 from direct.showbase import DirectObject
 from direct.controls.ControlManager import CollisionHandlerRayStart
 from direct.controls.ControlManager import CollisionHandlerRayStart
 from direct.showbase.InputStateGlobal import inputState
 from direct.showbase.InputStateGlobal import inputState
+from direct.showbase.MessengerGlobal import messenger
 from direct.task.Task import Task
 from direct.task.Task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 from panda3d.core import *
 from panda3d.core import *
 
 
 class NonPhysicsWalker(DirectObject.DirectObject):
 class NonPhysicsWalker(DirectObject.DirectObject):
@@ -184,7 +186,7 @@ class NonPhysicsWalker(DirectObject.DirectObject):
         tempCTrav = CollisionTraverser("oneTimeCollide")
         tempCTrav = CollisionTraverser("oneTimeCollide")
         tempCTrav.addCollider(self.cSphereNodePath, self.pusher)
         tempCTrav.addCollider(self.cSphereNodePath, self.pusher)
         tempCTrav.addCollider(self.cRayNodePath, self.lifter)
         tempCTrav.addCollider(self.cRayNodePath, self.lifter)
-        tempCTrav.traverse(render)
+        tempCTrav.traverse(base.render)
 
 
     def addBlastForce(self, vector):
     def addBlastForce(self, vector):
         pass
         pass
@@ -268,12 +270,12 @@ class NonPhysicsWalker(DirectObject.DirectObject):
         else:
         else:
             self.vel.set(0.0, 0.0, 0.0)
             self.vel.set(0.0, 0.0, 0.0)
 
 
-        self.__oldPosDelta = self.avatarNodePath.getPosDelta(render)
+        self.__oldPosDelta = self.avatarNodePath.getPosDelta(base.render)
         self.__oldDt = dt
         self.__oldDt = dt
 
 
-        try:
-            self.worldVelocity = self.__oldPosDelta*(1/self.__oldDt)
-        except:
+        if self.__oldDt != 0:
+            self.worldVelocity = self.__oldPosDelta * (1 / self.__oldDt)
+        else:
             # divide by zero
             # divide by zero
             self.worldVelocity = 0
             self.worldVelocity = 0
 
 

+ 0 - 5
direct/src/controls/ObserverWalker.py

@@ -31,9 +31,6 @@ class ObserverWalker(NonPhysicsWalker.NonPhysicsWalker):
         """
         """
         Set up the avatar for collisions
         Set up the avatar for collisions
         """
         """
-        """
-        Set up the avatar for collisions
-        """
         assert not avatarNodePath.isEmpty()
         assert not avatarNodePath.isEmpty()
 
 
         self.cTrav = collisionTraverser
         self.cTrav = collisionTraverser
@@ -102,11 +99,9 @@ class ObserverWalker(NonPhysicsWalker.NonPhysicsWalker):
         Activate the arrow keys, etc.
         Activate the arrow keys, etc.
         """
         """
         assert self.debugPrint("enableAvatarControls")
         assert self.debugPrint("enableAvatarControls")
-        pass
 
 
     def disableAvatarControls(self):
     def disableAvatarControls(self):
         """
         """
         Ignore the arrow keys, etc.
         Ignore the arrow keys, etc.
         """
         """
         assert self.debugPrint("disableAvatarControls")
         assert self.debugPrint("disableAvatarControls")
-        pass

+ 98 - 135
direct/src/controls/PhysicsWalker.py

@@ -20,12 +20,14 @@ from direct.directnotify import DirectNotifyGlobal
 from direct.showbase import DirectObject
 from direct.showbase import DirectObject
 from direct.controls.ControlManager import CollisionHandlerRayStart
 from direct.controls.ControlManager import CollisionHandlerRayStart
 from direct.showbase.InputStateGlobal import inputState
 from direct.showbase.InputStateGlobal import inputState
+from direct.showbase.MessengerGlobal import messenger
 from direct.task.Task import Task
 from direct.task.Task import Task
-from panda3d.core import *
-from panda3d.physics import *
+from direct.task.TaskManagerGlobal import taskMgr
 from direct.extensions_native import Mat3_extensions
 from direct.extensions_native import Mat3_extensions
 from direct.extensions_native import VBase3_extensions
 from direct.extensions_native import VBase3_extensions
 from direct.extensions_native import VBase4_extensions
 from direct.extensions_native import VBase4_extensions
+from panda3d.core import *
+from panda3d.physics import *
 import math
 import math
 
 
 #import LineStream
 #import LineStream
@@ -131,11 +133,6 @@ class PhysicsWalker(DirectObject.DirectObject):
             assert onScreenDebug.add("height", height.getZ())
             assert onScreenDebug.add("height", height.getZ())
             return height.getZ() - self.floorOffset
             return height.getZ() - self.floorOffset
         else: # useCollisionHandlerQueue
         else: # useCollisionHandlerQueue
-            """
-            returns the height of the avatar above the ground.
-            If there is no floor below the avatar, 0.0 is returned.
-            aka get airborne height.
-            """
             height = 0.0
             height = 0.0
             #*#self.cRayTrav.traverse(render)
             #*#self.cRayTrav.traverse(render)
             if self.cRayQueue.getNumEntries() != 0:
             if self.cRayQueue.getNumEntries() != 0:
@@ -239,7 +236,7 @@ class PhysicsWalker(DirectObject.DirectObject):
         self.floorOffset = floorOffset = 7.0
         self.floorOffset = floorOffset = 7.0
 
 
         self.avatarNodePath = self.setupPhysics(avatarNodePath)
         self.avatarNodePath = self.setupPhysics(avatarNodePath)
-        if 0 or self.useHeightRay:
+        if self.useHeightRay:
             #self.setupRay(floorBitmask, avatarRadius)
             #self.setupRay(floorBitmask, avatarRadius)
             self.setupRay(floorBitmask, 0.0)
             self.setupRay(floorBitmask, 0.0)
         self.setupSphere(wallBitmask|floorBitmask, avatarRadius)
         self.setupSphere(wallBitmask|floorBitmask, avatarRadius)
@@ -257,14 +254,14 @@ class PhysicsWalker(DirectObject.DirectObject):
         self.cSphereNodePath.show()
         self.cSphereNodePath.show()
         if indicator:
         if indicator:
             # Indicator Node:
             # Indicator Node:
-            change=render.attachNewNode("change")
+            change = render.attachNewNode("change")
             #change.setPos(Vec3(1.0, 1.0, 1.0))
             #change.setPos(Vec3(1.0, 1.0, 1.0))
             #change.setHpr(0.0, 0.0, 0.0)
             #change.setHpr(0.0, 0.0, 0.0)
             change.setScale(0.1)
             change.setScale(0.1)
             #change.setColor(Vec4(1.0, 1.0, 1.0, 1.0))
             #change.setColor(Vec4(1.0, 1.0, 1.0, 1.0))
             indicator.reparentTo(change)
             indicator.reparentTo(change)
 
 
-            indicatorNode=render.attachNewNode("physVelocityIndicator")
+            indicatorNode = render.attachNewNode("physVelocityIndicator")
             #indicatorNode.setScale(0.1)
             #indicatorNode.setScale(0.1)
             #indicatorNode.setP(90.0)
             #indicatorNode.setP(90.0)
             indicatorNode.setPos(self.avatarNodePath, 0.0, 0.0, 6.0)
             indicatorNode.setPos(self.avatarNodePath, 0.0, 0.0, 6.0)
@@ -273,7 +270,7 @@ class PhysicsWalker(DirectObject.DirectObject):
 
 
             self.physVelocityIndicator=indicatorNode
             self.physVelocityIndicator=indicatorNode
             # Contact Node:
             # Contact Node:
-            contactIndicatorNode=render.attachNewNode("physContactIndicator")
+            contactIndicatorNode = render.attachNewNode("physContactIndicator")
             contactIndicatorNode.setScale(0.25)
             contactIndicatorNode.setScale(0.25)
             contactIndicatorNode.setP(90.0)
             contactIndicatorNode.setP(90.0)
             contactIndicatorNode.setPos(self.avatarNodePath, 0.0, 0.0, 5.0)
             contactIndicatorNode.setPos(self.avatarNodePath, 0.0, 0.0, 5.0)
@@ -472,137 +469,103 @@ class PhysicsWalker(DirectObject.DirectObject):
                 onScreenDebug.add("posDelta1",
                 onScreenDebug.add("posDelta1",
                     self.avatarNodePath.getPosDelta(render).pPrintValues())
                     self.avatarNodePath.getPosDelta(render).pPrintValues())
 
 
-                if 0:
-                    onScreenDebug.add("posDelta3",
-                        render.getRelativeVector(
-                            self.avatarNodePath,
-                            self.avatarNodePath.getPosDelta(render)).pPrintValues())
-
-                if 0:
-                    onScreenDebug.add("gravity",
-                        self.gravity.getLocalVector().pPrintValues())
-                    onScreenDebug.add("priorParent",
-                        self.priorParent.getLocalVector().pPrintValues())
-                    onScreenDebug.add("avatarViscosity",
-                        "% 10.4f"%(self.avatarViscosity.getCoef(),))
-
-                    onScreenDebug.add("physObject pos",
-                        physObject.getPosition().pPrintValues())
-                    onScreenDebug.add("physObject hpr",
-                        physObject.getOrientation().getHpr().pPrintValues())
-                    onScreenDebug.add("physObject orien",
-                        physObject.getOrientation().pPrintValues())
-
-                if 1:
-                    onScreenDebug.add("physObject vel",
-                        physObject.getVelocity().pPrintValues())
-                    onScreenDebug.add("physObject len",
-                        "% 10.4f"%physObject.getVelocity().length())
-
-                if 0:
-                    onScreenDebug.add("posDelta4",
-                        self.priorParentNp.getRelativeVector(
-                            render,
-                            self.avatarNodePath.getPosDelta(render)).pPrintValues())
-
-                if 1:
-                    onScreenDebug.add("priorParent",
-                        self.priorParent.getLocalVector().pPrintValues())
-
-                if 0:
-                    onScreenDebug.add("priorParent po",
-                        self.priorParent.getVector(physObject).pPrintValues())
-
-                if 0:
-                    onScreenDebug.add("__posDelta",
-                        self.__oldPosDelta.pPrintValues())
-
-                if 1:
-                    onScreenDebug.add("contact",
-                        contact.pPrintValues())
-                    #onScreenDebug.add("airborneHeight", "% 10.4f"%(
-                    #    self.getAirborneHeight(),))
-
-                if 0:
-                    onScreenDebug.add("__oldContact",
-                        contact.pPrintValues())
-                    onScreenDebug.add("__oldAirborneHeight", "% 10.4f"%(
-                        self.getAirborneHeight(),))
-        airborneHeight=self.getAirborneHeight()
+                #onScreenDebug.add("posDelta3",
+                #    render.getRelativeVector(
+                #        self.avatarNodePath,
+                #        self.avatarNodePath.getPosDelta(render)).pPrintValues())
+
+                #onScreenDebug.add("gravity",
+                #    self.gravity.getLocalVector().pPrintValues())
+                #onScreenDebug.add("priorParent",
+                #    self.priorParent.getLocalVector().pPrintValues())
+                #onScreenDebug.add("avatarViscosity",
+                #    "% 10.4f"%(self.avatarViscosity.getCoef(),))
+                #
+                #onScreenDebug.add("physObject pos",
+                #    physObject.getPosition().pPrintValues())
+                #onScreenDebug.add("physObject hpr",
+                #    physObject.getOrientation().getHpr().pPrintValues())
+                #onScreenDebug.add("physObject orien",
+                #    physObject.getOrientation().pPrintValues())
+
+                onScreenDebug.add("physObject vel",
+                    physObject.getVelocity().pPrintValues())
+                onScreenDebug.add("physObject len",
+                    "% 10.4f"%physObject.getVelocity().length())
+
+                #onScreenDebug.add("posDelta4",
+                #    self.priorParentNp.getRelativeVector(
+                #        render,
+                #        self.avatarNodePath.getPosDelta(render)).pPrintValues())
+
+                onScreenDebug.add("priorParent",
+                    self.priorParent.getLocalVector().pPrintValues())
+
+                #onScreenDebug.add("priorParent po",
+                #    self.priorParent.getVector(physObject).pPrintValues())
+
+                #onScreenDebug.add("__posDelta",
+                #    self.__oldPosDelta.pPrintValues())
+
+                onScreenDebug.add("contact",
+                    contact.pPrintValues())
+                #onScreenDebug.add("airborneHeight", "% 10.4f"%(
+                #    self.getAirborneHeight(),))
+
+                #onScreenDebug.add("__oldContact",
+                #    contact.pPrintValues())
+                #onScreenDebug.add("__oldAirborneHeight", "% 10.4f"%(
+                #    self.getAirborneHeight(),))
+        airborneHeight = self.getAirborneHeight()
         if airborneHeight > self.highMark:
         if airborneHeight > self.highMark:
             self.highMark = airborneHeight
             self.highMark = airborneHeight
             if __debug__:
             if __debug__:
                 onScreenDebug.add("highMark", "% 10.4f"%(self.highMark,))
                 onScreenDebug.add("highMark", "% 10.4f"%(self.highMark,))
         #if airborneHeight < 0.1: #contact!=Vec3.zero():
         #if airborneHeight < 0.1: #contact!=Vec3.zero():
-        if 1:
-            if (airborneHeight > self.avatarRadius*0.5
-                    or physObject.getVelocity().getZ() > 0.0
-                    ): # Check stair angles before changing this.
-                # ...the avatar is airborne (maybe a lot or a tiny amount).
-                self.isAirborne = 1
-            else:
-                # ...the avatar is very close to the ground (close enough to be
-                # considered on the ground).
-                if self.isAirborne and physObject.getVelocity().getZ() <= 0.0:
-                    # ...the avatar has landed.
-                    contactLength = contact.length()
-                    if contactLength>self.__hardLandingForce:
-                        #print "jumpHardLand"
-                        messenger.send("jumpHardLand")
-                    else:
-                        #print "jumpLand"
-                        messenger.send("jumpLand")
-                    self.priorParent.setVector(Vec3.zero())
-                    self.isAirborne = 0
-                elif jump:
-                    #print "jump"
-                    #self.__jumpButton=0
-                    messenger.send("jumpStart")
-                    if 0:
-                        # ...jump away from walls and with with the slope normal.
-                        jumpVec=Vec3(contact+Vec3.up())
-                        #jumpVec=Vec3(rotAvatarToPhys.xform(jumpVec))
-                        jumpVec.normalize()
-                    else:
-                        # ...jump straight up, even if next to a wall.
-                        jumpVec=Vec3.up()
-                    jumpVec*=self.avatarControlJumpForce
-                    physObject.addImpulse(Vec3(jumpVec))
-                    self.isAirborne = 1 # Avoid double impulse before fully airborne.
-                else:
-                    self.isAirborne = 0
-            if __debug__:
-                onScreenDebug.add("isAirborne", "%d"%(self.isAirborne,))
+        if (airborneHeight > self.avatarRadius*0.5
+                or physObject.getVelocity().getZ() > 0.0
+                ): # Check stair angles before changing this.
+            # ...the avatar is airborne (maybe a lot or a tiny amount).
+            self.isAirborne = 1
         else:
         else:
-            if contact!=Vec3.zero():
-                # ...the avatar has touched something (but might not be on the ground).
+            # ...the avatar is very close to the ground (close enough to be
+            # considered on the ground).
+            if self.isAirborne and physObject.getVelocity().getZ() <= 0.0:
+                # ...the avatar has landed.
                 contactLength = contact.length()
                 contactLength = contact.length()
-                contact.normalize()
-                angle=contact.dot(Vec3.up())
-                if angle>self.__standableGround:
-                    # ...avatar is on standable ground.
-                    if self.__oldContact==Vec3.zero():
-                    #if self.__oldAirborneHeight > 0.1: #self.__oldContact==Vec3.zero():
-                        # ...avatar was airborne.
-                        self.jumpCount-=1
-                        if contactLength>self.__hardLandingForce:
-                            messenger.send("jumpHardLand")
-                        else:
-                            messenger.send("jumpLand")
-                    elif jump:
-                        self.jumpCount+=1
-                        #self.__jumpButton=0
-                        messenger.send("jumpStart")
-                        jump=Vec3(contact+Vec3.up())
-                        #jump=Vec3(rotAvatarToPhys.xform(jump))
-                        jump.normalize()
-                        jump*=self.avatarControlJumpForce
-                        physObject.addImpulse(Vec3(jump))
-
-        if contact!=self.__oldContact:
+                if contactLength>self.__hardLandingForce:
+                    #print "jumpHardLand"
+                    messenger.send("jumpHardLand")
+                else:
+                    #print "jumpLand"
+                    messenger.send("jumpLand")
+                self.priorParent.setVector(Vec3.zero())
+                self.isAirborne = 0
+            elif jump:
+                #print "jump"
+                #self.__jumpButton = 0
+                messenger.send("jumpStart")
+
+                ## ...jump away from walls and with with the slope normal.
+                #jumpVec=Vec3(contact+Vec3.up())
+                ##jumpVec=Vec3(rotAvatarToPhys.xform(jumpVec))
+                #jumpVec.normalize()
+
+                # ...jump straight up, even if next to a wall.
+                jumpVec=Vec3.up()
+
+                jumpVec *= self.avatarControlJumpForce
+                physObject.addImpulse(Vec3(jumpVec))
+                self.isAirborne = 1 # Avoid double impulse before fully airborne.
+            else:
+                self.isAirborne = 0
+        if __debug__:
+            onScreenDebug.add("isAirborne", "%d"%(self.isAirborne,))
+
+        if contact != self.__oldContact:
             # We must copy the vector to preserve it:
             # We must copy the vector to preserve it:
-            self.__oldContact=Vec3(contact)
-        self.__oldAirborneHeight=airborneHeight
+            self.__oldContact = Vec3(contact)
+        self.__oldAirborneHeight = airborneHeight
 
 
         moveToGround = Vec3.zero()
         moveToGround = Vec3.zero()
         if not self.useHeightRay or self.isAirborne:
         if not self.useHeightRay or self.isAirborne:
@@ -741,7 +704,7 @@ class PhysicsWalker(DirectObject.DirectObject):
     if __debug__:
     if __debug__:
         def setupAvatarPhysicsIndicator(self):
         def setupAvatarPhysicsIndicator(self):
             if self.wantDebugIndicator:
             if self.wantDebugIndicator:
-                indicator=loader.loadModel('phase_5/models/props/dagger')
+                indicator = base.loader.loadModel('phase_5/models/props/dagger')
                 #self.walkControls.setAvatarPhysicsIndicator(indicator)
                 #self.walkControls.setAvatarPhysicsIndicator(indicator)
 
 
         def debugPrint(self, message):
         def debugPrint(self, message):

+ 1 - 0
direct/src/controls/TwoDWalker.py

@@ -3,6 +3,7 @@ TwoDWalker.py is for controlling the avatars in a 2D scroller game environment.
 """
 """
 
 
 from .GravityWalker import *
 from .GravityWalker import *
+from direct.showbase.MessengerGlobal import messenger
 from panda3d.core import ConfigVariableBool
 from panda3d.core import ConfigVariableBool
 
 
 
 

+ 2 - 15
direct/src/directbase/TestStart.py

@@ -7,22 +7,9 @@ from direct.showbase import ShowBase
 base = ShowBase.ShowBase()
 base = ShowBase.ShowBase()
 
 
 # Put an axis in the world:
 # Put an axis in the world:
-loader.loadModel("models/misc/xyzAxis").reparentTo(render)
+base.loader.loadModel("models/misc/xyzAxis").reparentTo(render)
 
 
-if 0:
-    # Hack:
-    # Enable drive mode but turn it off, and reset the camera
-    # This is here because ShowBase sets up a drive interface, this
-    # can be removed if ShowBase is changed to not set that up.
-    base.useDrive()
-    base.disableMouse()
-    if base.mouseInterface:
-        base.mouseInterface.reparentTo(base.dataUnused)
-    if base.mouse2cam:
-        base.mouse2cam.reparentTo(base.dataUnused)
-    # end of hack.
-
-camera.setPosHpr(0, -10.0, 0, 0, 0, 0)
+base.camera.setPosHpr(0, -10.0, 0, 0, 0, 0)
 base.camLens.setFov(52.0)
 base.camLens.setFov(52.0)
 base.camLens.setNearFar(1.0, 10000.0)
 base.camLens.setNearFar(1.0, 10000.0)
 
 

+ 5 - 17
direct/src/directbase/ThreeUpStart.py

@@ -5,25 +5,13 @@ from panda3d.core import *
 
 
 from direct.showbase.PythonUtil import *
 from direct.showbase.PythonUtil import *
 from direct.showbase import ThreeUpShow
 from direct.showbase import ThreeUpShow
-ThreeUpShow.ThreeUpShow()
+
+base = ThreeUpShow.ThreeUpShow()
 
 
 # Put an axis in the world:
 # Put an axis in the world:
-loader.loadModel("models/misc/xyzAxis").reparentTo(render)
-
-if 0:
-    # Hack:
-    # Enable drive mode but turn it off, and reset the camera
-    # This is here because ShowBase sets up a drive interface, this
-    # can be removed if ShowBase is changed to not set that up.
-    base.useDrive()
-    base.disableMouse()
-    if base.mouseInterface:
-        base.mouseInterface.reparentTo(base.dataUnused)
-    if base.mouse2cam:
-        base.mouse2cam.reparentTo(base.dataUnused)
-    # end of hack.
-
-camera.setPosHpr(0, -10.0, 0, 0, 0, 0)
+base.loader.loadModel("models/misc/xyzAxis").reparentTo(render)
+
+base.camera.setPosHpr(0, -10.0, 0, 0, 0, 0)
 base.camLens.setFov(52.0)
 base.camLens.setFov(52.0)
 base.camLens.setNearFar(1.0, 10000.0)
 base.camLens.setNearFar(1.0, 10000.0)
 
 

+ 17 - 16
direct/src/directdevices/DirectDeviceManager.py

@@ -14,7 +14,7 @@ class DirectDeviceManager(VrpnClient, DirectObject):
     def __init__(self, server = None):
     def __init__(self, server = None):
 
 
         # Determine which server to use
         # Determine which server to use
-        if server != None:
+        if server is not None:
             # One given as constructor argument
             # One given as constructor argument
             self.server = server
             self.server = server
         else:
         else:
@@ -77,10 +77,10 @@ class DirectButtons(ButtonNode, DirectObject):
         return self.nodePath
         return self.nodePath
 
 
     def __repr__(self):
     def __repr__(self):
-        str = self.name + ': '
+        string = self.name + ': '
         for val in self:
         for val in self:
-            str = str + '%d' % val + ' '
-        return str
+            string = string + '%d' % val + ' '
+        return string
 
 
 class DirectAnalogs(AnalogNode, DirectObject):
 class DirectAnalogs(AnalogNode, DirectObject):
     analogCount = 0
     analogCount = 0
@@ -149,12 +149,12 @@ class DirectAnalogs(AnalogNode, DirectObject):
         aMin = self.analogMin
         aMin = self.analogMin
         center = self.analogCenter
         center = self.analogCenter
         deadband = self.analogDeadband
         deadband = self.analogDeadband
-        range = self.analogRange
+
         # Zero out values in deadband
         # Zero out values in deadband
-        if (abs(rawValue-center) <= deadband):
+        if abs(rawValue - center) <= deadband:
             return 0.0
             return 0.0
         # Clamp value between aMin and aMax and scale around center
         # Clamp value between aMin and aMax and scale around center
-        if (rawValue >= center):
+        if rawValue >= center:
             # Convert positive values to range 0 to 1
             # Convert positive values to range 0 to 1
             val = min(rawValue * sf, aMax)
             val = min(rawValue * sf, aMax)
             percentVal = ((val - (center + deadband))/
             percentVal = ((val - (center + deadband))/
@@ -165,7 +165,7 @@ class DirectAnalogs(AnalogNode, DirectObject):
             percentVal = -((val - (center - deadband))/
             percentVal = -((val - (center - deadband))/
                            float(aMin - (center - deadband)))
                            float(aMin - (center - deadband)))
         # Normalize values to given minVal and maxVal range
         # Normalize values to given minVal and maxVal range
-        return (((maxVal - minVal) * ((percentVal + 1)/2.0)) + minVal)
+        return ((maxVal - minVal) * ((percentVal + 1)/2.0)) + minVal
 
 
     def normalizeChannel(self, chan, minVal = -1, maxVal = 1, sf = 1.0):
     def normalizeChannel(self, chan, minVal = -1, maxVal = 1, sf = 1.0):
         try:
         try:
@@ -180,13 +180,14 @@ class DirectAnalogs(AnalogNode, DirectObject):
         return self.nodePath
         return self.nodePath
 
 
     def __repr__(self):
     def __repr__(self):
-        str = self.name + ': '
+        string = self.name + ': '
         for val in self:
         for val in self:
-            str = str + '%.3f' % val + ' '
-        return str
+            string = string + '%.3f' % val + ' '
+        return string
 
 
 class DirectTracker(TrackerNode, DirectObject):
 class DirectTracker(TrackerNode, DirectObject):
     trackerCount = 0
     trackerCount = 0
+
     def __init__(self, vrpnClient, device):
     def __init__(self, vrpnClient, device):
         # Keep track of number of trackers created
         # Keep track of number of trackers created
         DirectTracker.trackerCount += 1
         DirectTracker.trackerCount += 1
@@ -257,10 +258,10 @@ class DirectDials(DialNode, DirectObject):
         return self.nodePath
         return self.nodePath
 
 
     def __repr__(self):
     def __repr__(self):
-        str = self.name + ': '
+        string = self.name + ': '
         for i in range(self.getNumDials()):
         for i in range(self.getNumDials()):
-            str = str + '%.3f' % self[i] + ' '
-        return str
+            string = string + '%.3f' % self[i] + ' '
+        return string
 
 
 class DirectTimecodeReader(AnalogNode, DirectObject):
 class DirectTimecodeReader(AnalogNode, DirectObject):
     timecodeReaderCount = 0
     timecodeReaderCount = 0
@@ -316,5 +317,5 @@ class DirectTimecodeReader(AnalogNode, DirectObject):
                 self.totalSeconds)
                 self.totalSeconds)
 
 
     def __repr__(self):
     def __repr__(self):
-        str = ('%s: %d:%d:%d:%d' % ((self.name,) + self.getTime()[:-1]))
-        return str
+        string = ('%s: %d:%d:%d:%d' % ((self.name,) + self.getTime()[:-1]))
+        return string

+ 3 - 6
direct/src/directdevices/DirectFastrak.py

@@ -1,14 +1,12 @@
 """ Class used to create and control radamec device """
 """ Class used to create and control radamec device """
-from math import *
 from direct.showbase.DirectObject import DirectObject
 from direct.showbase.DirectObject import DirectObject
+from direct.task.Task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 from .DirectDeviceManager import *
 from .DirectDeviceManager import *
 
 
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
 
 
-"""
-TODO:
-Handle interaction between widget, followSelectedTask and updateTask
-"""
+#TODO: Handle interaction between widget, followSelectedTask and updateTask
 
 
 # ANALOGS
 # ANALOGS
 NULL_AXIS = -1
 NULL_AXIS = -1
@@ -65,4 +63,3 @@ class DirectFastrak(DirectObject):
                                3.280839895013123 * pos[1],
                                3.280839895013123 * pos[1],
                                3.280839895013123 * pos[0])
                                3.280839895013123 * pos[0])
         self.notify.debug("Tracker(%d) Pos = %s" % (self.deviceNo, repr(self.trackerPos)))
         self.notify.debug("Tracker(%d) Pos = %s" % (self.deviceNo, repr(self.trackerPos)))
-

+ 13 - 16
direct/src/directdevices/DirectJoybox.py

@@ -4,12 +4,10 @@ from .DirectDeviceManager import *
 from direct.directtools.DirectUtil import *
 from direct.directtools.DirectUtil import *
 from direct.gui import OnscreenText
 from direct.gui import OnscreenText
 from direct.task import Task
 from direct.task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 import math
 import math
 
 
-"""
-TODO:
-Handle interaction between widget, followSelectedTask and updateTask
-"""
+#TODO: Handle interaction between widget, followSelectedTask and updateTask
 
 
 # BUTTONS
 # BUTTONS
 L_STICK = 0
 L_STICK = 0
@@ -39,10 +37,11 @@ class DirectJoybox(DirectObject):
     joyboxCount = 0
     joyboxCount = 0
     xyzMultiplier = 1.0
     xyzMultiplier = 1.0
     hprMultiplier = 1.0
     hprMultiplier = 1.0
+
     def __init__(self, device = 'CerealBox', nodePath = base.direct.camera,
     def __init__(self, device = 'CerealBox', nodePath = base.direct.camera,
                  headingNP = base.direct.camera):
                  headingNP = base.direct.camera):
         # See if device manager has been initialized
         # See if device manager has been initialized
-        if base.direct.deviceManager == None:
+        if base.direct.deviceManager is None:
             base.direct.deviceManager = DirectDeviceManager()
             base.direct.deviceManager = DirectDeviceManager()
         # Set name
         # Set name
         DirectJoybox.joyboxCount += 1
         DirectJoybox.joyboxCount += 1
@@ -172,12 +171,12 @@ class DirectJoybox(DirectObject):
         for chan in range(len(self.analogs)):
         for chan in range(len(self.analogs)):
             val = self.analogs.getControlState(chan)
             val = self.analogs.getControlState(chan)
             # Zero out values in deadband
             # Zero out values in deadband
-            if (val < 0):
+            if val < 0:
                 val = min(val + ANALOG_DEADBAND, 0.0)
                 val = min(val + ANALOG_DEADBAND, 0.0)
             else:
             else:
                 val = max(val - ANALOG_DEADBAND, 0.0)
                 val = max(val - ANALOG_DEADBAND, 0.0)
             # Scale up rotating knob values
             # Scale up rotating knob values
-            if (chan == L_TWIST) or (chan == R_TWIST):
+            if chan == L_TWIST or chan == R_TWIST:
                 val *= 3.0
                 val *= 3.0
             # Now clamp value between minVal and maxVal
             # Now clamp value between minVal and maxVal
             val = CLAMP(val, JOYBOX_MIN, JOYBOX_MAX)
             val = CLAMP(val, JOYBOX_MIN, JOYBOX_MAX)
@@ -240,7 +239,7 @@ class DirectJoybox(DirectObject):
 
 
     def joyboxFly(self):
     def joyboxFly(self):
         # Do nothing if no nodePath selected
         # Do nothing if no nodePath selected
-        if self.nodePath == None:
+        if self.nodePath is None:
             return
             return
         hprScale = ((self.aList[L_SLIDE] + 1.0) *
         hprScale = ((self.aList[L_SLIDE] + 1.0) *
                     50.0 * DirectJoybox.hprMultiplier)
                     50.0 * DirectJoybox.hprMultiplier)
@@ -264,14 +263,14 @@ class DirectJoybox(DirectObject):
         # if we are using a heading nodepath, we want
         # if we are using a heading nodepath, we want
         # to drive in the direction we are facing,
         # to drive in the direction we are facing,
         # however, we don't want the z component to change
         # however, we don't want the z component to change
-        if (self.useHeadingNP and self.headingNP != None):
+        if self.useHeadingNP and self.headingNP is not None:
             oldZ = pos.getZ()
             oldZ = pos.getZ()
             pos = self.nodePath.getRelativeVector(self.headingNP,
             pos = self.nodePath.getRelativeVector(self.headingNP,
                                                   pos)
                                                   pos)
             pos.setZ(oldZ)
             pos.setZ(oldZ)
             # if we are using a heading NP we might want to rotate
             # if we are using a heading NP we might want to rotate
             # in place around that NP
             # in place around that NP
-            if (self.rotateInPlace):
+            if self.rotateInPlace:
                 parent = self.nodePath.getParent()
                 parent = self.nodePath.getParent()
                 self.floatingNP.reparentTo(parent)
                 self.floatingNP.reparentTo(parent)
                 self.floatingNP.setPos(self.headingNP,0,0,0)
                 self.floatingNP.setPos(self.headingNP,0,0,0)
@@ -389,7 +388,7 @@ class DirectJoybox(DirectObject):
 
 
     def spaceFly(self):
     def spaceFly(self):
         # Do nothing if no nodePath selected
         # Do nothing if no nodePath selected
-        if self.nodePath == None:
+        if self.nodePath is None:
             return
             return
         hprScale = (self.normalizeChannel(L_SLIDE, 0.1, 100) *
         hprScale = (self.normalizeChannel(L_SLIDE, 0.1, 100) *
                     DirectJoybox.hprMultiplier)
                     DirectJoybox.hprMultiplier)
@@ -408,7 +407,7 @@ class DirectJoybox(DirectObject):
 
 
     def planetFly(self):
     def planetFly(self):
         # Do nothing if no nodePath selected
         # Do nothing if no nodePath selected
-        if self.nodePath == None:
+        if self.nodePath is None:
             return
             return
         hprScale = (self.normalizeChannel(L_SLIDE, 0.1, 100) *
         hprScale = (self.normalizeChannel(L_SLIDE, 0.1, 100) *
                     DirectJoybox.hprMultiplier)
                     DirectJoybox.hprMultiplier)
@@ -459,7 +458,7 @@ class DirectJoybox(DirectObject):
 
 
     def orbitFly(self):
     def orbitFly(self):
         # Do nothing if no nodePath selected
         # Do nothing if no nodePath selected
-        if self.nodePath == None:
+        if self.nodePath is None:
             return
             return
         hprScale = (self.normalizeChannel(L_SLIDE, 0.1, 100) *
         hprScale = (self.normalizeChannel(L_SLIDE, 0.1, 100) *
                     DirectJoybox.hprMultiplier)
                     DirectJoybox.hprMultiplier)
@@ -502,7 +501,7 @@ class DirectJoybox(DirectObject):
     # correct the ranges of the two twist axes of the joybox.
     # correct the ranges of the two twist axes of the joybox.
     def normalizeChannel(self, chan, minVal = -1, maxVal = 1):
     def normalizeChannel(self, chan, minVal = -1, maxVal = 1):
         try:
         try:
-            if (chan == L_TWIST) or (chan == R_TWIST):
+            if chan == L_TWIST or chan == R_TWIST:
                 # These channels have reduced range
                 # These channels have reduced range
                 return self.analogs.normalize(
                 return self.analogs.normalize(
                     self.analogs.getControlState(chan), minVal, maxVal, 3.0)
                     self.analogs.getControlState(chan), minVal, maxVal, 3.0)
@@ -511,5 +510,3 @@ class DirectJoybox(DirectObject):
                     self.analogs.getControlState(chan), minVal, maxVal)
                     self.analogs.getControlState(chan), minVal, maxVal)
         except IndexError:
         except IndexError:
             return 0.0
             return 0.0
-
-

+ 12 - 13
direct/src/directdevices/DirectRadamec.py

@@ -1,15 +1,13 @@
 """ Class used to create and control radamec device """
 """ Class used to create and control radamec device """
 from math import *
 from math import *
 from direct.showbase.DirectObject import DirectObject
 from direct.showbase.DirectObject import DirectObject
+from direct.task.Task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 from .DirectDeviceManager import *
 from .DirectDeviceManager import *
 
 
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
 
 
-
-"""
-TODO:
-Handle interaction between widget, followSelectedTask and updateTask
-"""
+#TODO: Handle interaction between widget, followSelectedTask and updateTask
 
 
 # ANALOGS
 # ANALOGS
 RAD_PAN = 0
 RAD_PAN = 0
@@ -23,7 +21,7 @@ class DirectRadamec(DirectObject):
 
 
     def __init__(self, device = 'Analog0', nodePath = None):
     def __init__(self, device = 'Analog0', nodePath = None):
         # See if device manager has been initialized
         # See if device manager has been initialized
-        if base.direct.deviceManager == None:
+        if base.direct.deviceManager is None:
             base.direct.deviceManager = DirectDeviceManager()
             base.direct.deviceManager = DirectDeviceManager()
         # Set name
         # Set name
         self.name = 'Radamec-' + repr(DirectRadamec.radamecCount)
         self.name = 'Radamec-' + repr(DirectRadamec.radamecCount)
@@ -73,11 +71,12 @@ class DirectRadamec(DirectObject):
     # Normalize to the range [-minVal, maxVal] based on some hard-coded
     # Normalize to the range [-minVal, maxVal] based on some hard-coded
     # max/min numbers of the Radamec device
     # max/min numbers of the Radamec device
     def normalizeChannel(self, chan, minVal = -1, maxVal = 1):
     def normalizeChannel(self, chan, minVal = -1, maxVal = 1):
-        try:
-            maxRange = self.maxRange[chan]
-            minRange = self.minRange[chan]
-        except IndexError:
+        if chan < 0 or chan >= min(len(self.maxRange), len(self.minRange)):
             raise RuntimeError("can't normalize this channel (channel %d)" % chan)
             raise RuntimeError("can't normalize this channel (channel %d)" % chan)
-        range = maxRange - minRange
-        clampedVal = CLAMP(self.aList[chan], minRange, maxRange)
-        return ((maxVal - minVal) * (clampedVal - minRange) / range) + minVal
+
+        maxRange = self.maxRange[chan]
+        minRange = self.minRange[chan]
+
+        diff = maxRange - minRange
+        clampedVal = max(min(self.aList[chan], maxRange), maxRange)
+        return ((maxVal - minVal) * (clampedVal - minRange) / diff) + minVal

+ 3 - 3
direct/src/directnotify/DirectNotify.py

@@ -41,17 +41,17 @@ class DirectNotify:
         """getCategory(self, string)
         """getCategory(self, string)
         Return the category with given name if present, None otherwise
         Return the category with given name if present, None otherwise
         """
         """
-        return (self.__categories.get(categoryName, None))
+        return self.__categories.get(categoryName, None)
 
 
     def newCategory(self, categoryName, logger=None):
     def newCategory(self, categoryName, logger=None):
         """newCategory(self, string)
         """newCategory(self, string)
         Make a new notify category named categoryName. Return new category
         Make a new notify category named categoryName. Return new category
         if no such category exists, else return existing category
         if no such category exists, else return existing category
         """
         """
-        if (categoryName not in self.__categories):
+        if categoryName not in self.__categories:
             self.__categories[categoryName] = Notifier.Notifier(categoryName, logger)
             self.__categories[categoryName] = Notifier.Notifier(categoryName, logger)
             self.setDconfigLevel(categoryName)
             self.setDconfigLevel(categoryName)
-        return (self.getCategory(categoryName))
+        return self.getCategory(categoryName)
 
 
     def setDconfigLevel(self, categoryName):
     def setDconfigLevel(self, categoryName):
         """
         """

+ 11 - 26
direct/src/directnotify/Logger.py

@@ -4,6 +4,7 @@
 import time
 import time
 import math
 import math
 
 
+
 class Logger:
 class Logger:
     def __init__(self, fileName="log"):
     def __init__(self, fileName="log"):
         """
         """
@@ -14,18 +15,17 @@ class Logger:
         self.__logFile = None
         self.__logFile = None
         self.__logFileName = fileName
         self.__logFileName = fileName
 
 
-    def setTimeStamp(self, bool):
+    def setTimeStamp(self, enable):
         """
         """
         Toggle time stamp printing with log entries on and off
         Toggle time stamp printing with log entries on and off
         """
         """
-        self.__timeStamp = bool
+        self.__timeStamp = enable
 
 
     def getTimeStamp(self):
     def getTimeStamp(self):
         """
         """
         Return whether or not we are printing time stamps with log entries
         Return whether or not we are printing time stamps with log entries
         """
         """
-        return(self.__timeStamp)
-
+        return self.__timeStamp
 
 
     # logging control
     # logging control
 
 
@@ -38,13 +38,12 @@ class Logger:
     def log(self, entryString):
     def log(self, entryString):
         """log(self, string)
         """log(self, string)
         Print the given string to the log file"""
         Print the given string to the log file"""
-        if (self.__logFile == None):
+        if self.__logFile is None:
             self.__openLogFile()
             self.__openLogFile()
-        if (self.__timeStamp):
+        if self.__timeStamp:
             self.__logFile.write(self.__getTimeStamp())
             self.__logFile.write(self.__getTimeStamp())
         self.__logFile.write(entryString + '\n')
         self.__logFile.write(entryString + '\n')
 
 
-
     # logging functions
     # logging functions
 
 
     def __openLogFile(self):
     def __openLogFile(self):
@@ -61,7 +60,7 @@ class Logger:
         """
         """
         Close the error/warning output file
         Close the error/warning output file
         """
         """
-        if (self.__logFile != None):
+        if self.__logFile is not None:
             self.__logFile.close()
             self.__logFile.close()
 
 
     def __getTimeStamp(self):
     def __getTimeStamp(self):
@@ -70,22 +69,8 @@ class Logger:
         """
         """
         t = time.time()
         t = time.time()
         dt = t - self.__startTime
         dt = t - self.__startTime
-        if (dt >= 86400):
-            days = int(math.floor(dt/86400))
-            dt = dt%86400
-        else:
-            days = 0
-        if (dt >= 3600):
-            hours = int(math.floor(dt/3600))
-            dt = dt%3600
-        else:
-            hours = 0
-        if (dt >= 60):
-            minutes = int(math.floor(dt/60))
-            dt = dt%60
-        else:
-            minutes = 0
+        days, dt = divmod(dt, 86400)
+        hours, dt = divmod(dt, 3600)
+        minutes, dt = divmod(dt, 60)
         seconds = int(math.ceil(dt))
         seconds = int(math.ceil(dt))
-        return("%02d:%02d:%02d:%02d: " % (days, hours, minutes, seconds))
-
-
+        return "%02d:%02d:%02d:%02d: " % (days, hours, minutes, seconds)

+ 11 - 12
direct/src/directnotify/Notifier.py

@@ -32,7 +32,7 @@ class Notifier:
         """
         """
         self.__name = name
         self.__name = name
 
 
-        if (logger==None):
+        if logger is None:
             self.__logger = defaultLogger
             self.__logger = defaultLogger
         else:
         else:
             self.__logger = logger
             self.__logger = logger
@@ -144,17 +144,17 @@ class Notifier:
             self.__print(string)
             self.__print(string)
         return 1 # to allow assert myNotify.warning("blah")
         return 1 # to allow assert myNotify.warning("blah")
 
 
-    def setWarning(self, bool):
+    def setWarning(self, enable):
         """
         """
         Enable/Disable the printing of warning messages
         Enable/Disable the printing of warning messages
         """
         """
-        self.__warning = bool
+        self.__warning = enable
 
 
     def getWarning(self):
     def getWarning(self):
         """
         """
         Return whether the printing of warning messages is on or off
         Return whether the printing of warning messages is on or off
         """
         """
-        return(self.__warning)
+        return self.__warning
 
 
     # debug funcs
     # debug funcs
     def debug(self, debugString):
     def debug(self, debugString):
@@ -171,11 +171,11 @@ class Notifier:
             self.__print(string)
             self.__print(string)
         return 1 # to allow assert myNotify.debug("blah")
         return 1 # to allow assert myNotify.debug("blah")
 
 
-    def setDebug(self, bool):
+    def setDebug(self, enable):
         """
         """
         Enable/Disable the printing of debug messages
         Enable/Disable the printing of debug messages
         """
         """
-        self.__debug = bool
+        self.__debug = enable
 
 
     def getDebug(self):
     def getDebug(self):
         """
         """
@@ -204,11 +204,11 @@ class Notifier:
         """
         """
         return self.__info
         return self.__info
 
 
-    def setInfo(self, bool):
+    def setInfo(self, enable):
         """
         """
         Enable/Disable informational message  printing
         Enable/Disable informational message  printing
         """
         """
-        self.__info = bool
+        self.__info = enable
 
 
     # log funcs
     # log funcs
     def __log(self, logEntry):
     def __log(self, logEntry):
@@ -222,13 +222,13 @@ class Notifier:
         """
         """
         Return 1 if logging enabled, 0 otherwise
         Return 1 if logging enabled, 0 otherwise
         """
         """
-        return (self.__logging)
+        return self.__logging
 
 
-    def setLogging(self, bool):
+    def setLogging(self, enable):
         """
         """
         Set the logging flag to int (1=on, 0=off)
         Set the logging flag to int (1=on, 0=off)
         """
         """
-        self.__logging = bool
+        self.__logging = enable
 
 
     def __print(self, string):
     def __print(self, string):
         """
         """
@@ -297,4 +297,3 @@ class Notifier:
             self.__log(string)
             self.__log(string)
             self.__print(string)
             self.__print(string)
         return 1 # to allow assert self.notify.debugCall("blah")
         return 1 # to allow assert self.notify.debugCall("blah")
-

+ 22 - 17
direct/src/directscripts/eggcacher.py

@@ -8,7 +8,9 @@
 #
 #
 ##############################################################################
 ##############################################################################
 
 
-import os,sys,gc
+import os
+import sys
+import gc
 from panda3d.core import *
 from panda3d.core import *
 
 
 class EggCacher:
 class EggCacher:
@@ -18,7 +20,7 @@ class EggCacher:
         self.bamcache = BamCache.getGlobalPtr()
         self.bamcache = BamCache.getGlobalPtr()
         self.pandaloader = Loader()
         self.pandaloader = Loader()
         self.loaderopts = LoaderOptions(LoaderOptions.LF_no_ram_cache)
         self.loaderopts = LoaderOptions(LoaderOptions.LF_no_ram_cache)
-        if (self.bamcache.getActive() == 0):
+        if not self.bamcache.getActive():
             print("The model cache is not currently active.")
             print("The model cache is not currently active.")
             print("You must set a model-cache-dir in your config file.")
             print("You must set a model-cache-dir in your config file.")
             sys.exit(1)
             sys.exit(1)
@@ -29,42 +31,44 @@ class EggCacher:
     def parseArgs(self, args):
     def parseArgs(self, args):
         self.concise = 0
         self.concise = 0
         self.pzkeep = 0
         self.pzkeep = 0
-        while len(args):
-            if (args[0]=="--concise"):
+        while len(args) > 0:
+            if args[0] == "--concise":
                 self.concise = 1
                 self.concise = 1
                 args = args[1:]
                 args = args[1:]
-            elif (args[0]=="--pzkeep"):
+            elif args[0] == "--pzkeep":
                 self.pzkeep = 1
                 self.pzkeep = 1
                 args = args[1:]
                 args = args[1:]
             else:
             else:
                 break
                 break
-        if (len(args) < 1):
+        if len(args) < 1:
             print("Usage: eggcacher options file-or-directory")
             print("Usage: eggcacher options file-or-directory")
             sys.exit(1)
             sys.exit(1)
         self.paths = args
         self.paths = args
 
 
     def scanPath(self, eggs, path):
     def scanPath(self, eggs, path):
-        if (os.path.exists(path)==0):
+        if not os.path.exists(path):
             print("No such file or directory: " + path)
             print("No such file or directory: " + path)
             return
             return
-        if (os.path.isdir(path)):
+        if os.path.isdir(path):
             for f in os.listdir(path):
             for f in os.listdir(path):
                 self.scanPath(eggs, os.path.join(path,f))
                 self.scanPath(eggs, os.path.join(path,f))
             return
             return
-        if (path.endswith(".egg")):
+        if path.endswith(".egg"):
             size = os.path.getsize(path)
             size = os.path.getsize(path)
             eggs.append((path,size))
             eggs.append((path,size))
             return
             return
-        if (path.endswith(".egg.pz") or path.endswith(".egg.gz")):
+        if path.endswith(".egg.pz") or path.endswith(".egg.gz"):
             size = os.path.getsize(path)
             size = os.path.getsize(path)
-            if (self.pzkeep): eggs.append((path,size))
-            else: eggs.append((path[:-3],size))
+            if self.pzkeep:
+                eggs.append((path, size))
+            else:
+                eggs.append((path[:-3], size))
 
 
     def scanPaths(self, paths):
     def scanPaths(self, paths):
         eggs = []
         eggs = []
         for path in paths:
         for path in paths:
-            abs = os.path.abspath(path)
-            self.scanPath(eggs,path)
+            #abs = os.path.abspath(path)
+            self.scanPath(eggs, path)
         return eggs
         return eggs
 
 
     def processFiles(self, files):
     def processFiles(self, files):
@@ -72,15 +76,16 @@ class EggCacher:
         for (path, size) in files:
         for (path, size) in files:
             total += size
             total += size
         progress = 0
         progress = 0
-        for (path,size) in files:
+        for (path, size) in files:
             fn = Filename.fromOsSpecific(path)
             fn = Filename.fromOsSpecific(path)
             cached = self.bamcache.lookup(fn, "bam")
             cached = self.bamcache.lookup(fn, "bam")
             percent = (progress * 100) / total
             percent = (progress * 100) / total
             report = path
             report = path
-            if (self.concise): report = os.path.basename(report)
+            if self.concise:
+                report = os.path.basename(report)
             print("Preprocessing Models %2d%% %s" % (percent, report))
             print("Preprocessing Models %2d%% %s" % (percent, report))
             sys.stdout.flush()
             sys.stdout.flush()
-            if (cached) and (cached.hasData()==0):
+            if cached and not cached.hasData():
                 self.pandaloader.loadSync(fn, self.loaderopts)
                 self.pandaloader.loadSync(fn, self.loaderopts)
             gc.collect()
             gc.collect()
             ModelPool.releaseAllModels()
             ModelPool.releaseAllModels()

+ 2 - 2
direct/src/directscripts/extract_docs.py

@@ -10,8 +10,8 @@ from __future__ import print_function
 __all__ = []
 __all__ = []
 
 
 import os
 import os
-from distutils import sysconfig
-import panda3d, pandac
+import panda3d
+import pandac
 from panda3d.interrogatedb import *
 from panda3d.interrogatedb import *
 
 
 
 

+ 8 - 8
direct/src/directtools/DirectCameraControl.py

@@ -6,6 +6,7 @@ from .DirectSelection import SelectionRay
 from direct.interval.IntervalGlobal import Sequence, Func
 from direct.interval.IntervalGlobal import Sequence, Func
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
 from direct.task import Task
 from direct.task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 
 
 CAM_MOVE_DURATION = 1.2
 CAM_MOVE_DURATION = 1.2
 COA_MARKER_SF = 0.0075
 COA_MARKER_SF = 0.0075
@@ -22,7 +23,7 @@ class DirectCameraControl(DirectObject):
         self.orthoViewRoll = 0.0
         self.orthoViewRoll = 0.0
         self.lastView = 0
         self.lastView = 0
         self.coa = Point3(0, 100, 0)
         self.coa = Point3(0, 100, 0)
-        self.coaMarker = loader.loadModel('models/misc/sphere')
+        self.coaMarker = base.loader.loadModel('models/misc/sphere')
         self.coaMarker.setName('DirectCameraCOAMarker')
         self.coaMarker.setName('DirectCameraCOAMarker')
         self.coaMarker.setTransparency(1)
         self.coaMarker.setTransparency(1)
         self.coaMarker.setColor(1, 0, 0, 0)
         self.coaMarker.setColor(1, 0, 0, 0)
@@ -150,7 +151,7 @@ class DirectCameraControl(DirectObject):
     def __startManipulateCamera(self, func = None, task = None, ival = None):
     def __startManipulateCamera(self, func = None, task = None, ival = None):
         self.__stopManipulateCamera()
         self.__stopManipulateCamera()
         if func:
         if func:
-            assert(task is None)
+            assert task is None
             task = Task.Task(func)
             task = Task.Task(func)
         if task:
         if task:
             self.manipulateCameraTask = taskMgr.add(task, 'manipulateCamera')
             self.manipulateCameraTask = taskMgr.add(task, 'manipulateCamera')
@@ -366,7 +367,7 @@ class DirectCameraControl(DirectObject):
                                 moveDir[2],
                                 moveDir[2],
                                 hVal,
                                 hVal,
                                 0.0, 0.0)
                                 0.0, 0.0)
-        if (self.lockRoll == True):
+        if self.lockRoll:
             # flatten roll
             # flatten roll
             base.direct.camera.setR(0)
             base.direct.camera.setR(0)
 
 
@@ -449,7 +450,7 @@ class DirectCameraControl(DirectObject):
                                  (deltaX * base.direct.dr.fovH),
                                  (deltaX * base.direct.dr.fovH),
                                  (-deltaY * base.direct.dr.fovV),
                                  (-deltaY * base.direct.dr.fovV),
                                  0.0)
                                  0.0)
-            if (self.lockRoll == True):
+            if self.lockRoll:
                 # flatten roll
                 # flatten roll
                 base.direct.camera.setR(0)
                 base.direct.camera.setR(0)
             self.camManipRef.setPos(self.coaMarkerPos)
             self.camManipRef.setPos(self.coaMarkerPos)
@@ -466,7 +467,7 @@ class DirectCameraControl(DirectObject):
                                     (deltaY * 180.0),
                                     (deltaY * 180.0),
                                     0.0)
                                     0.0)
 
 
-            if (self.lockRoll == True):
+            if self.lockRoll:
                 # flatten roll
                 # flatten roll
                 self.camManipRef.setR(0)
                 self.camManipRef.setR(0)
             base.direct.camera.setTransform(self.camManipRef, wrt)
             base.direct.camera.setTransform(self.camManipRef, wrt)
@@ -491,7 +492,7 @@ class DirectCameraControl(DirectObject):
         deltaAngle = angle - state.lastAngle
         deltaAngle = angle - state.lastAngle
         state.lastAngle = angle
         state.lastAngle = angle
         self.camManipRef.setHpr(self.camManipRef, 0, 0, deltaAngle)
         self.camManipRef.setHpr(self.camManipRef, 0, 0, deltaAngle)
-        if (self.lockRoll == True):
+        if self.lockRoll:
             # flatten roll
             # flatten roll
             self.camManipRef.setR(0)
             self.camManipRef.setR(0)
         base.direct.camera.setTransform(self.camManipRef, wrt)
         base.direct.camera.setTransform(self.camManipRef, wrt)
@@ -576,7 +577,7 @@ class DirectCameraControl(DirectObject):
         if not coaDist:
         if not coaDist:
             coaDist = Vec3(self.coa - ZERO_POINT).length()
             coaDist = Vec3(self.coa - ZERO_POINT).length()
         # Place the marker in render space
         # Place the marker in render space
-        if ref == None:
+        if ref is None:
             # KEH: use the current display region
             # KEH: use the current display region
             # ref = base.cam
             # ref = base.cam
             ref = base.direct.drList.getCurrentDr().cam
             ref = base.direct.drList.getCurrentDr().cam
@@ -892,4 +893,3 @@ class DirectCameraControl(DirectObject):
 
 
     def removeManipulateCameraTask(self):
     def removeManipulateCameraTask(self):
         self.__stopManipulateCamera()
         self.__stopManipulateCamera()
-

+ 3 - 4
direct/src/directtools/DirectGeometry.py

@@ -163,7 +163,7 @@ def getCrankAngle(center):
     # origin) in screen space
     # origin) in screen space
     x = base.direct.dr.mouseX - center[0]
     x = base.direct.dr.mouseX - center[0]
     y = base.direct.dr.mouseY - center[2]
     y = base.direct.dr.mouseY - center[2]
-    return (180 + rad2Deg(math.atan2(y, x)))
+    return 180 + rad2Deg(math.atan2(y, x))
 
 
 def relHpr(nodePath, base, h, p, r):
 def relHpr(nodePath, base, h, p, r):
     # Compute nodePath2newNodePath relative to base coordinate system
     # Compute nodePath2newNodePath relative to base coordinate system
@@ -205,9 +205,9 @@ def qSlerp(startQuat, endQuat, t):
         startQ.setJ(-1 * startQ.getJ())
         startQ.setJ(-1 * startQ.getJ())
         startQ.setK(-1 * startQ.getK())
         startQ.setK(-1 * startQ.getK())
         startQ.setR(-1 * startQ.getR())
         startQ.setR(-1 * startQ.getR())
-    if ((1.0 + cosOmega) > Q_EPSILON):
+    if (1.0 + cosOmega) > Q_EPSILON:
         # usual case
         # usual case
-        if ((1.0 - cosOmega) > Q_EPSILON):
+        if (1.0 - cosOmega) > Q_EPSILON:
             # usual case
             # usual case
             omega = math.acos(cosOmega)
             omega = math.acos(cosOmega)
             sinOmega = math.sin(omega)
             sinOmega = math.sin(omega)
@@ -240,4 +240,3 @@ def qSlerp(startQuat, endQuat, t):
         destQuat.setK(startScale * startQ.getK() +
         destQuat.setK(startScale * startQ.getK() +
                       endScale * endQuat.getK())
                       endScale * endQuat.getK())
     return destQuat
     return destQuat
-

+ 0 - 1
direct/src/directtools/DirectGlobals.py

@@ -59,4 +59,3 @@ def LE_showInOneCam(nodePath, thisCamName):
     for camName in LE_CAM_MASKS:
     for camName in LE_CAM_MASKS:
         if camName != thisCamName:
         if camName != thisCamName:
             nodePath.hide(LE_CAM_MASKS[camName])
             nodePath.hide(LE_CAM_MASKS[camName])
-

+ 4 - 3
direct/src/directtools/DirectGrid.py

@@ -4,6 +4,7 @@ from direct.showbase.DirectObject import DirectObject
 from .DirectUtil import *
 from .DirectUtil import *
 from .DirectGeometry import *
 from .DirectGeometry import *
 
 
+
 class DirectGrid(NodePath, DirectObject):
 class DirectGrid(NodePath, DirectObject):
     def __init__(self,gridSize=100.0,gridSpacing=5.0,planeColor=(0.5,0.5,0.5,0.5),parent = None):
     def __init__(self,gridSize=100.0,gridSpacing=5.0,planeColor=(0.5,0.5,0.5,0.5),parent = None):
         # Initialize superclass
         # Initialize superclass
@@ -13,7 +14,7 @@ class DirectGrid(NodePath, DirectObject):
 
 
         # Load up grid parts to initialize grid object
         # Load up grid parts to initialize grid object
         # Polygon used to mark grid plane
         # Polygon used to mark grid plane
-        self.gridBack = loader.loadModel('models/misc/gridBack')
+        self.gridBack = base.loader.loadModel('models/misc/gridBack')
         self.gridBack.reparentTo(self)
         self.gridBack.reparentTo(self)
         self.gridBack.setColor(*planeColor)
         self.gridBack.setColor(*planeColor)
 
 
@@ -35,7 +36,7 @@ class DirectGrid(NodePath, DirectObject):
         self.centerLines.setThickness(3)
         self.centerLines.setThickness(3)
 
 
         # Small marker to hilight snap-to-grid point
         # Small marker to hilight snap-to-grid point
-        self.snapMarker = loader.loadModel('models/misc/sphere')
+        self.snapMarker = base.loader.loadModel('models/misc/sphere')
         self.snapMarker.node().setName('gridSnapMarker')
         self.snapMarker.node().setName('gridSnapMarker')
         self.snapMarker.reparentTo(self)
         self.snapMarker.reparentTo(self)
         self.snapMarker.setColor(1, 0, 0, 1)
         self.snapMarker.setColor(1, 0, 0, 1)
@@ -107,7 +108,7 @@ class DirectGrid(NodePath, DirectObject):
         center.create()
         center.create()
         minor.create()
         minor.create()
         major.create()
         major.create()
-        if (self.gridBack):
+        if self.gridBack:
             self.gridBack.setScale(scaledSize)
             self.gridBack.setScale(scaledSize)
 
 
     def setXyzSnap(self, fSnap):
     def setXyzSnap(self, fSnap):

+ 8 - 9
direct/src/directtools/DirectLights.py

@@ -1,5 +1,7 @@
 
 
 from panda3d.core import *
 from panda3d.core import *
+from direct.showbase.MessengerGlobal import messenger
+
 
 
 class DirectLight(NodePath):
 class DirectLight(NodePath):
     def __init__(self, light, parent):
     def __init__(self, light, parent):
@@ -58,21 +60,21 @@ class DirectLights(NodePath):
         nameList.sort()
         nameList.sort()
         return nameList
         return nameList
 
 
-    def create(self, type):
-        type = type.lower()
-        if type == 'ambient':
+    def create(self, ltype):
+        ltype = ltype.lower()
+        if ltype == 'ambient':
             self.ambientCount += 1
             self.ambientCount += 1
             light = AmbientLight('ambient-' + repr(self.ambientCount))
             light = AmbientLight('ambient-' + repr(self.ambientCount))
             light.setColor(VBase4(.3, .3, .3, 1))
             light.setColor(VBase4(.3, .3, .3, 1))
-        elif type == 'directional':
+        elif ltype == 'directional':
             self.directionalCount += 1
             self.directionalCount += 1
             light = DirectionalLight('directional-' + repr(self.directionalCount))
             light = DirectionalLight('directional-' + repr(self.directionalCount))
             light.setColor(VBase4(1))
             light.setColor(VBase4(1))
-        elif type == 'point':
+        elif ltype == 'point':
             self.pointCount += 1
             self.pointCount += 1
             light = PointLight('point-' + repr(self.pointCount))
             light = PointLight('point-' + repr(self.pointCount))
             light.setColor(VBase4(1))
             light.setColor(VBase4(1))
-        elif type == 'spot':
+        elif ltype == 'spot':
             self.spotCount += 1
             self.spotCount += 1
             light = Spotlight('spot-' + repr(self.spotCount))
             light = Spotlight('spot-' + repr(self.spotCount))
             light.setColor(VBase4(1))
             light.setColor(VBase4(1))
@@ -130,6 +132,3 @@ class DirectLights(NodePath):
         Turn off the given directLight
         Turn off the given directLight
         """
         """
         render.clearLight(directLight)
         render.clearLight(directLight)
-
-
-

+ 56 - 55
direct/src/directtools/DirectManipulation.py

@@ -1,4 +1,5 @@
 from direct.showbase.DirectObject import DirectObject
 from direct.showbase.DirectObject import DirectObject
+from direct.showbase.MessengerGlobal import messenger
 from .DirectGlobals import *
 from .DirectGlobals import *
 from .DirectUtil import *
 from .DirectUtil import *
 from .DirectGeometry import *
 from .DirectGeometry import *
@@ -6,6 +7,7 @@ from .DirectSelection import SelectionRay
 from direct.task import Task
 from direct.task import Task
 from copy import deepcopy
 from copy import deepcopy
 
 
+
 class DirectManipulationControl(DirectObject):
 class DirectManipulationControl(DirectObject):
     def __init__(self):
     def __init__(self):
         # Create the grid
         # Create the grid
@@ -201,7 +203,7 @@ class DirectManipulationControl(DirectObject):
             ((abs (endY - startY)) < 0.01)):
             ((abs (endY - startY)) < 0.01)):
             return
             return
 
 
-        self.marquee = LineNodePath(render2d, 'marquee', 0.5, VBase4(.8, .6, .6, 1))
+        self.marquee = LineNodePath(base.render2d, 'marquee', 0.5, VBase4(.8, .6, .6, 1))
         self.marqueeInfo = (startX, startY, endX, endY)
         self.marqueeInfo = (startX, startY, endX, endY)
         self.marquee.drawLines([
         self.marquee.drawLines([
             [(startX, 0, startY), (startX, 0, endY)],
             [(startX, 0, startY), (startX, 0, endY)],
@@ -252,7 +254,7 @@ class DirectManipulationControl(DirectObject):
                 lens.extrude((endX, endY), nlr, flr)
                 lens.extrude((endX, endY), nlr, flr)
                 lens.extrude((startX, endY), nll, fll)
                 lens.extrude((startX, endY), nll, fll)
 
 
-                marqueeFrustum = BoundingHexahedron(fll, flr, fur, ful, nll, nlr, nur, nul);
+                marqueeFrustum = BoundingHexahedron(fll, flr, fur, ful, nll, nlr, nur, nul)
                 marqueeFrustum.xform(base.direct.cam.getNetTransform().getMat())
                 marqueeFrustum.xform(base.direct.cam.getNetTransform().getMat())
 
 
                 base.marqueeFrustum = marqueeFrustum
                 base.marqueeFrustum = marqueeFrustum
@@ -273,13 +275,13 @@ class DirectManipulationControl(DirectObject):
 ##                     elif (skipFlags & SKIP_BACKFACE) and base.direct.iRay.isEntryBackfacing():
 ##                     elif (skipFlags & SKIP_BACKFACE) and base.direct.iRay.isEntryBackfacing():
 ##                         # Skip, if backfacing poly
 ##                         # Skip, if backfacing poly
 ##                         pass
 ##                         pass
-                    elif ((skipFlags & SKIP_CAMERA) and
-                          (camera in geom.getAncestors())):
+                    elif (skipFlags & SKIP_CAMERA) and \
+                         (base.camera in geom.getAncestors()):
                         # Skip if parented to a camera.
                         # Skip if parented to a camera.
                         continue
                         continue
                     # Can pick unpickable, use the first visible node
                     # Can pick unpickable, use the first visible node
-                    elif ((skipFlags & SKIP_UNPICKABLE) and
-                          (geom.getName() in base.direct.iRay.unpickable)):
+                    elif (skipFlags & SKIP_UNPICKABLE) and \
+                         (geom.getName() in base.direct.iRay.unpickable):
                         # Skip if in unpickable list
                         # Skip if in unpickable list
                         continue
                         continue
 
 
@@ -486,7 +488,7 @@ class DirectManipulationControl(DirectObject):
         for tag in self.unmovableTagList:
         for tag in self.unmovableTagList:
             for selected in objects:
             for selected in objects:
                 unmovableTag = selected.getTag(tag)
                 unmovableTag = selected.getTag(tag)
-                if (unmovableTag):
+                if unmovableTag:
                     # check value of unmovableTag to see if it is
                     # check value of unmovableTag to see if it is
                     # completely uneditable or if it allows only certain
                     # completely uneditable or if it allows only certain
                     # types of editing
                     # types of editing
@@ -498,7 +500,7 @@ class DirectManipulationControl(DirectObject):
         selectedList = base.direct.selected.getSelectedAsList()
         selectedList = base.direct.selected.getSelectedAsList()
         # See if any of the selected are completely uneditable
         # See if any of the selected are completely uneditable
         editTypes = self.getEditTypes(selectedList)
         editTypes = self.getEditTypes(selectedList)
-        if (editTypes & EDIT_TYPE_UNEDITABLE == EDIT_TYPE_UNEDITABLE):
+        if (editTypes & EDIT_TYPE_UNEDITABLE) == EDIT_TYPE_UNEDITABLE:
             return
             return
         self.currEditTypes = editTypes
         self.currEditTypes = editTypes
         if selectedList:
         if selectedList:
@@ -633,7 +635,7 @@ class DirectManipulationControl(DirectObject):
                 base.direct.widget.getMat(base.direct.selected.last))
                 base.direct.widget.getMat(base.direct.selected.last))
         else:
         else:
             # Move the objects with the widget
             # Move the objects with the widget
-                base.direct.selected.moveWrtWidgetAll()
+            base.direct.selected.moveWrtWidgetAll()
         # Continue
         # Continue
         return Task.cont
         return Task.cont
 
 
@@ -811,11 +813,11 @@ class DirectManipulationControl(DirectObject):
         widgetAxis.normalize()
         widgetAxis.normalize()
         if type == 'top?':
         if type == 'top?':
             # Check sign of angle between two vectors
             # Check sign of angle between two vectors
-            return (widgetDir.dot(widgetAxis) < 0.)
+            return widgetDir.dot(widgetAxis) < 0.
         elif type == 'edge?':
         elif type == 'edge?':
             # Checking to see if we are viewing edge-on
             # Checking to see if we are viewing edge-on
             # Check angle between two vectors
             # Check angle between two vectors
-            return(abs(widgetDir.dot(widgetAxis)) < .2)
+            return abs(widgetDir.dot(widgetAxis)) < .2
 
 
     ### FREE MANIPULATION METHODS ###
     ### FREE MANIPULATION METHODS ###
     def xlateCamXZ(self, state):
     def xlateCamXZ(self, state):
@@ -1043,7 +1045,7 @@ class DirectManipulationControl(DirectObject):
         entry = base.direct.iRay.pickGeom(
         entry = base.direct.iRay.pickGeom(
             skipFlags = SKIP_HIDDEN | SKIP_BACKFACE | SKIP_CAMERA)
             skipFlags = SKIP_HIDDEN | SKIP_BACKFACE | SKIP_CAMERA)
         # MRM: Need to handle moving COA
         # MRM: Need to handle moving COA
-        if (entry != None) and (base.direct.selected.last != None):
+        if entry is not None and base.direct.selected.last is not None:
             # Record undo point
             # Record undo point
             base.direct.pushUndo(base.direct.selected)
             base.direct.pushUndo(base.direct.selected)
             # Record wrt matrix
             # Record wrt matrix
@@ -1064,7 +1066,7 @@ class ObjectHandles(NodePath, DirectObject):
         NodePath.__init__(self)
         NodePath.__init__(self)
 
 
         # Load up object handles model and assign it to self
         # Load up object handles model and assign it to self
-        self.assign(loader.loadModel('models/misc/objectHandles'))
+        self.assign(base.loader.loadModel('models/misc/objectHandles'))
         self.setName(name)
         self.setName(name)
         self.scalingNode = self.getChild(0)
         self.scalingNode = self.getChild(0)
         self.scalingNode.setName('ohScalingNode')
         self.scalingNode.setName('ohScalingNode')
@@ -1206,7 +1208,7 @@ class ObjectHandles(NodePath, DirectObject):
         self.reparentTo(hidden)
         self.reparentTo(hidden)
 
 
     def enableHandles(self, handles):
     def enableHandles(self, handles):
-        if type(handles) == list:
+        if isinstance(handles, list):
             for handle in handles:
             for handle in handles:
                 self.enableHandle(handle)
                 self.enableHandle(handle)
         elif handles == 'x':
         elif handles == 'x':
@@ -1255,7 +1257,7 @@ class ObjectHandles(NodePath, DirectObject):
             self.zScaleGroup.reparentTo(self.zHandles)
             self.zScaleGroup.reparentTo(self.zHandles)
 
 
     def disableHandles(self, handles):
     def disableHandles(self, handles):
-        if type(handles) == list:
+        if isinstance(handles, list):
             for handle in handles:
             for handle in handles:
                 self.disableHandle(handle)
                 self.disableHandle(handle)
         elif handles == 'x':
         elif handles == 'x':
@@ -1640,7 +1642,7 @@ class ObjectHandles(NodePath, DirectObject):
         # by comparing lineDir with plane normals.  The plane with the
         # by comparing lineDir with plane normals.  The plane with the
         # largest dotProduct is most "normal"
         # largest dotProduct is most "normal"
         if axis == 'x':
         if axis == 'x':
-            if (abs(lineDir.dot(Y_AXIS)) > abs(lineDir.dot(Z_AXIS))):
+            if abs(lineDir.dot(Y_AXIS)) > abs(lineDir.dot(Z_AXIS)):
                 self.hitPt.assign(
                 self.hitPt.assign(
                     planeIntersect(lineOrigin, lineDir, ORIGIN, Y_AXIS))
                     planeIntersect(lineOrigin, lineDir, ORIGIN, Y_AXIS))
             else:
             else:
@@ -1650,7 +1652,7 @@ class ObjectHandles(NodePath, DirectObject):
             self.hitPt.setY(0)
             self.hitPt.setY(0)
             self.hitPt.setZ(0)
             self.hitPt.setZ(0)
         elif axis == 'y':
         elif axis == 'y':
-            if (abs(lineDir.dot(X_AXIS)) > abs(lineDir.dot(Z_AXIS))):
+            if abs(lineDir.dot(X_AXIS)) > abs(lineDir.dot(Z_AXIS)):
                 self.hitPt.assign(
                 self.hitPt.assign(
                     planeIntersect(lineOrigin, lineDir, ORIGIN, X_AXIS))
                     planeIntersect(lineOrigin, lineDir, ORIGIN, X_AXIS))
             else:
             else:
@@ -1660,7 +1662,7 @@ class ObjectHandles(NodePath, DirectObject):
             self.hitPt.setX(0)
             self.hitPt.setX(0)
             self.hitPt.setZ(0)
             self.hitPt.setZ(0)
         elif axis == 'z':
         elif axis == 'z':
-            if (abs(lineDir.dot(X_AXIS)) > abs(lineDir.dot(Y_AXIS))):
+            if abs(lineDir.dot(X_AXIS)) > abs(lineDir.dot(Y_AXIS)):
                 self.hitPt.assign(
                 self.hitPt.assign(
                     planeIntersect(lineOrigin, lineDir, ORIGIN, X_AXIS))
                     planeIntersect(lineOrigin, lineDir, ORIGIN, X_AXIS))
             else:
             else:
@@ -1731,40 +1733,39 @@ class ObjectHandles(NodePath, DirectObject):
         return self.hitPt
         return self.hitPt
 
 
 def drawBox(lines, center, sideLength):
 def drawBox(lines, center, sideLength):
-
-        l = sideLength * 0.5
-        lines.moveTo(center[0] + l, center[1] + l, center[2] + l)
-        lines.drawTo(center[0] + l, center[1] + l, center[2] - l)
-        lines.drawTo(center[0] + l, center[1] - l, center[2] - l)
-        lines.drawTo(center[0] + l, center[1] - l, center[2] + l)
-        lines.drawTo(center[0] + l, center[1] + l, center[2] + l)
-
-        lines.moveTo(center[0] - l, center[1] + l, center[2] + l)
-        lines.drawTo(center[0] - l, center[1] + l, center[2] - l)
-        lines.drawTo(center[0] - l, center[1] - l, center[2] - l)
-        lines.drawTo(center[0] - l, center[1] - l, center[2] + l)
-        lines.drawTo(center[0] - l, center[1] + l, center[2] + l)
-
-        lines.moveTo(center[0] + l, center[1] + l, center[2] + l)
-        lines.drawTo(center[0] + l, center[1] + l, center[2] - l)
-        lines.drawTo(center[0] - l, center[1] + l, center[2] - l)
-        lines.drawTo(center[0] - l, center[1] + l, center[2] + l)
-        lines.drawTo(center[0] + l, center[1] + l, center[2] + l)
-
-        lines.moveTo(center[0] + l, center[1] - l, center[2] + l)
-        lines.drawTo(center[0] + l, center[1] - l, center[2] - l)
-        lines.drawTo(center[0] - l, center[1] - l, center[2] - l)
-        lines.drawTo(center[0] - l, center[1] - l, center[2] + l)
-        lines.drawTo(center[0] + l, center[1] - l, center[2] + l)
-
-        lines.moveTo(center[0] + l, center[1] + l, center[2] + l)
-        lines.drawTo(center[0] - l, center[1] + l, center[2] + l)
-        lines.drawTo(center[0] - l, center[1] - l, center[2] + l)
-        lines.drawTo(center[0] + l, center[1] - l, center[2] + l)
-        lines.drawTo(center[0] + l, center[1] + l, center[2] + l)
-
-        lines.moveTo(center[0] + l, center[1] + l, center[2] - l)
-        lines.drawTo(center[0] - l, center[1] + l, center[2] - l)
-        lines.drawTo(center[0] - l, center[1] - l, center[2] - l)
-        lines.drawTo(center[0] + l, center[1] - l, center[2] - l)
-        lines.drawTo(center[0] + l, center[1] + l, center[2] - l)
+    l = sideLength * 0.5
+    lines.moveTo(center[0] + l, center[1] + l, center[2] + l)
+    lines.drawTo(center[0] + l, center[1] + l, center[2] - l)
+    lines.drawTo(center[0] + l, center[1] - l, center[2] - l)
+    lines.drawTo(center[0] + l, center[1] - l, center[2] + l)
+    lines.drawTo(center[0] + l, center[1] + l, center[2] + l)
+
+    lines.moveTo(center[0] - l, center[1] + l, center[2] + l)
+    lines.drawTo(center[0] - l, center[1] + l, center[2] - l)
+    lines.drawTo(center[0] - l, center[1] - l, center[2] - l)
+    lines.drawTo(center[0] - l, center[1] - l, center[2] + l)
+    lines.drawTo(center[0] - l, center[1] + l, center[2] + l)
+
+    lines.moveTo(center[0] + l, center[1] + l, center[2] + l)
+    lines.drawTo(center[0] + l, center[1] + l, center[2] - l)
+    lines.drawTo(center[0] - l, center[1] + l, center[2] - l)
+    lines.drawTo(center[0] - l, center[1] + l, center[2] + l)
+    lines.drawTo(center[0] + l, center[1] + l, center[2] + l)
+
+    lines.moveTo(center[0] + l, center[1] - l, center[2] + l)
+    lines.drawTo(center[0] + l, center[1] - l, center[2] - l)
+    lines.drawTo(center[0] - l, center[1] - l, center[2] - l)
+    lines.drawTo(center[0] - l, center[1] - l, center[2] + l)
+    lines.drawTo(center[0] + l, center[1] - l, center[2] + l)
+
+    lines.moveTo(center[0] + l, center[1] + l, center[2] + l)
+    lines.drawTo(center[0] - l, center[1] + l, center[2] + l)
+    lines.drawTo(center[0] - l, center[1] - l, center[2] + l)
+    lines.drawTo(center[0] + l, center[1] - l, center[2] + l)
+    lines.drawTo(center[0] + l, center[1] + l, center[2] + l)
+
+    lines.moveTo(center[0] + l, center[1] + l, center[2] - l)
+    lines.drawTo(center[0] - l, center[1] + l, center[2] - l)
+    lines.drawTo(center[0] - l, center[1] - l, center[2] - l)
+    lines.drawTo(center[0] + l, center[1] - l, center[2] - l)
+    lines.drawTo(center[0] + l, center[1] + l, center[2] - l)

+ 9 - 9
direct/src/directtools/DirectSelection.py

@@ -1,4 +1,5 @@
 from direct.showbase.DirectObject import DirectObject
 from direct.showbase.DirectObject import DirectObject
+from direct.showbase.MessengerGlobal import messenger
 from .DirectGlobals import *
 from .DirectGlobals import *
 from .DirectUtil import *
 from .DirectUtil import *
 from .DirectGeometry import *
 from .DirectGeometry import *
@@ -95,7 +96,7 @@ class SelectedNodePaths(DirectObject):
             dnp = self.getDeselectedDict(id)
             dnp = self.getDeselectedDict(id)
             if dnp:
             if dnp:
                 # Remove it from the deselected dictionary
                 # Remove it from the deselected dictionary
-                del(self.deselectedDict[id])
+                del self.deselectedDict[id]
                 # Show its bounding box
                 # Show its bounding box
                 dnp.highlight()
                 dnp.highlight()
             else:
             else:
@@ -125,7 +126,7 @@ class SelectedNodePaths(DirectObject):
             # Hide its bounding box
             # Hide its bounding box
             dnp.dehighlight()
             dnp.dehighlight()
             # Remove it from the selected dictionary
             # Remove it from the selected dictionary
-            del(self.selectedDict[id])
+            del self.selectedDict[id]
             if dnp in self.selectedList: # [gjeon]
             if dnp in self.selectedList: # [gjeon]
                 self.selectedList.remove(dnp)
                 self.selectedList.remove(dnp)
             # And keep track of it in the deselected dictionary
             # And keep track of it in the deselected dictionary
@@ -308,7 +309,7 @@ class DirectBoundingBox:
         # Create a line segments object for the bbox
         # Create a line segments object for the bbox
         lines = LineNodePath(hidden)
         lines = LineNodePath(hidden)
         lines.node().setName('bboxLines')
         lines.node().setName('bboxLines')
-        if (bboxColor):
+        if bboxColor:
             lines.setColor(VBase4(*bboxColor))
             lines.setColor(VBase4(*bboxColor))
         else:
         else:
             lines.setColor(VBase4(1., 0., 0., 1.))
             lines.setColor(VBase4(1., 0., 0., 1.))
@@ -352,7 +353,7 @@ class DirectBoundingBox:
         return lines
         return lines
 
 
     def setBoxColorScale(self, r, g, b, a):
     def setBoxColorScale(self, r, g, b, a):
-        if (self.lines):
+        if self.lines:
             self.lines.reset()
             self.lines.reset()
             self.lines = None
             self.lines = None
         self.lines = self.createBBoxLines((r, g, b, a))
         self.lines = self.createBBoxLines((r, g, b, a))
@@ -564,13 +565,13 @@ class SelectionQueue(CollisionHandlerQueue):
             elif (skipFlags & SKIP_BACKFACE) and self.isEntryBackfacing(entry):
             elif (skipFlags & SKIP_BACKFACE) and self.isEntryBackfacing(entry):
                 # Skip, if backfacing poly
                 # Skip, if backfacing poly
                 pass
                 pass
-            elif ((skipFlags & SKIP_CAMERA) and
-                  (camera in nodePath.getAncestors())):
+            elif (skipFlags & SKIP_CAMERA) and \
+                 (base.camera in nodePath.getAncestors()):
                 # Skip if parented to a camera.
                 # Skip if parented to a camera.
                 pass
                 pass
             # Can pick unpickable, use the first visible node
             # Can pick unpickable, use the first visible node
-            elif ((skipFlags & SKIP_UNPICKABLE) and
-                  (nodePath.getName() in self.unpickable)):
+            elif (skipFlags & SKIP_UNPICKABLE) and\
+                 (nodePath.getName() in self.unpickable):
                 # Skip if in unpickable list
                 # Skip if in unpickable list
                 pass
                 pass
             elif base.direct and\
             elif base.direct and\
@@ -793,4 +794,3 @@ class SelectionSphere(SelectionQueue):
             targetNodePath = render
             targetNodePath = render
         self.collideWithBitMask(bitMask)
         self.collideWithBitMask(bitMask)
         return self.pick(targetNodePath, skipFlags)
         return self.pick(targetNodePath, skipFlags)
-

+ 8 - 11
direct/src/directtools/DirectSession.py

@@ -4,6 +4,7 @@ from panda3d.core import *
 from .DirectUtil import *
 from .DirectUtil import *
 
 
 from direct.showbase.DirectObject import DirectObject
 from direct.showbase.DirectObject import DirectObject
+from direct.showbase.BulletinBoardGlobal import bulletinBoard as bboard
 from direct.task import Task
 from direct.task import Task
 
 
 from .DirectGlobals import DIRECT_NO_MOD
 from .DirectGlobals import DIRECT_NO_MOD
@@ -291,9 +292,8 @@ class DirectSession(DirectObject):
         self.passThroughKeys = ['v','b','l','p', 'r', 'shift-r', 's', 't','shift-a', 'w']
         self.passThroughKeys = ['v','b','l','p', 'r', 'shift-r', 's', 't','shift-a', 'w']
 
 
         if base.wantTk:
         if base.wantTk:
-            from direct.showbase import TkGlobal
             from direct.tkpanels import DirectSessionPanel
             from direct.tkpanels import DirectSessionPanel
-            self.panel = DirectSessionPanel.DirectSessionPanel(parent = tkroot)
+            self.panel = DirectSessionPanel.DirectSessionPanel(parent = base.tkRoot)
         try:
         try:
             # Has the clusterMode been set externally (i.e. via the
             # Has the clusterMode been set externally (i.e. via the
             # bootstrap application?
             # bootstrap application?
@@ -385,14 +385,12 @@ class DirectSession(DirectObject):
     def oobe(self):
     def oobe(self):
         # If oobeMode was never set, set it to false and create the
         # If oobeMode was never set, set it to false and create the
         # structures we need to implement OOBE.
         # structures we need to implement OOBE.
-        try:
-            self.oobeMode
-        except:
+        if not hasattr(self, 'oobeMode'):
             self.oobeMode = 0
             self.oobeMode = 0
 
 
             self.oobeCamera = hidden.attachNewNode('oobeCamera')
             self.oobeCamera = hidden.attachNewNode('oobeCamera')
 
 
-            self.oobeVis = loader.loadModel('models/misc/camera')
+            self.oobeVis = base.loader.loadModel('models/misc/camera')
             if self.oobeVis:
             if self.oobeVis:
                 self.oobeVis.node().setFinal(1)
                 self.oobeVis.node().setFinal(1)
 
 
@@ -710,7 +708,7 @@ class DirectSession(DirectObject):
             else:
             else:
                 self.widget.showWidget()
                 self.widget.showWidget()
             editTypes = self.manipulationControl.getEditTypes([dnp])
             editTypes = self.manipulationControl.getEditTypes([dnp])
-            if (editTypes & EDIT_TYPE_UNEDITABLE == EDIT_TYPE_UNEDITABLE):
+            if (editTypes & EDIT_TYPE_UNEDITABLE) == EDIT_TYPE_UNEDITABLE:
                 self.manipulationControl.disableWidgetMove()
                 self.manipulationControl.disableWidgetMove()
             else:
             else:
                 self.manipulationControl.enableWidgetMove()
                 self.manipulationControl.enableWidgetMove()
@@ -1071,8 +1069,10 @@ class DirectSession(DirectObject):
         for iRay in self.iRayList:
         for iRay in self.iRayList:
             iRay.removeUnpickable(item)
             iRay.removeUnpickable(item)
 
 
+
 class DisplayRegionContext(DirectObject):
 class DisplayRegionContext(DirectObject):
     regionCount = 0
     regionCount = 0
+
     def __init__(self, cam):
     def __init__(self, cam):
         self.cam = cam
         self.cam = cam
         self.camNode = self.cam.node()
         self.camNode = self.cam.node()
@@ -1093,10 +1093,7 @@ class DisplayRegionContext(DirectObject):
         # one display region per camera, since we are defining a
         # one display region per camera, since we are defining a
         # display region on a per-camera basis.  See note in
         # display region on a per-camera basis.  See note in
         # DisplayRegionList.__init__()
         # DisplayRegionList.__init__()
-        try:
-            self.dr = self.camNode.getDr(0)
-        except:
-            self.dr = self.camNode.getDisplayRegion(0)
+        self.dr = self.camNode.getDisplayRegion(0)
         left = self.dr.getLeft()
         left = self.dr.getLeft()
         right = self.dr.getRight()
         right = self.dr.getRight()
         bottom = self.dr.getBottom()
         bottom = self.dr.getBottom()

+ 1 - 1
direct/src/directtools/DirectUtil.py

@@ -2,6 +2,7 @@
 from .DirectGlobals import *
 from .DirectGlobals import *
 from panda3d.core import VBase4
 from panda3d.core import VBase4
 from direct.task.Task import Task
 from direct.task.Task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 
 
 # Routines to adjust values
 # Routines to adjust values
 def ROUND_TO(value, divisor):
 def ROUND_TO(value, divisor):
@@ -84,4 +85,3 @@ def getFileData(filename, separator = ','):
             data = [s.strip() for s in l.split(separator)]
             data = [s.strip() for s in l.split(separator)]
             fileData.append(data)
             fileData.append(data)
     return fileData
     return fileData
-

+ 2 - 0
direct/src/directutil/DistributedLargeBlobSender.py

@@ -2,8 +2,10 @@
 
 
 from direct.distributed import DistributedObject
 from direct.distributed import DistributedObject
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
+from direct.showbase.MessengerGlobal import messenger
 from . import LargeBlobSenderConsts
 from . import LargeBlobSenderConsts
 
 
+
 class DistributedLargeBlobSender(DistributedObject.DistributedObject):
 class DistributedLargeBlobSender(DistributedObject.DistributedObject):
     """DistributedLargeBlobSender: for sending large chunks of data through
     """DistributedLargeBlobSender: for sending large chunks of data through
     the DC system"""
     the DC system"""

+ 1 - 1
direct/src/directutil/DistributedLargeBlobSenderAI.py

@@ -50,7 +50,7 @@ class DistributedLargeBlobSenderAI(DistributedObjectAI.DistributedObjectAI):
                                       'setFilename', [filename])
                                       'setFilename', [filename])
         else:
         else:
             chunkSize = LargeBlobSenderConsts.ChunkSize
             chunkSize = LargeBlobSenderConsts.ChunkSize
-            while len(s):
+            while len(s) > 0:
                 self.sendUpdateToAvatarId(self.targetAvId,
                 self.sendUpdateToAvatarId(self.targetAvId,
                                           'setChunk', [s[:chunkSize]])
                                           'setChunk', [s[:chunkSize]])
                 s = s[chunkSize:]
                 s = s[chunkSize:]

+ 23 - 24
direct/src/directutil/Mopath.py

@@ -1,4 +1,5 @@
 from direct.showbase.DirectObject import DirectObject
 from direct.showbase.DirectObject import DirectObject
+from direct.showbase.MessengerGlobal import messenger
 from direct.directtools.DirectGeometry import *
 from direct.directtools.DirectGeometry import *
 
 
 from panda3d.core import NodePath, LineSegs
 from panda3d.core import NodePath, LineSegs
@@ -8,7 +9,7 @@ class Mopath(DirectObject):
     nameIndex = 1
     nameIndex = 1
 
 
     def __init__(self, name = None, fluid = 1, objectToLoad = None, upVectorNodePath = None, reverseUpVector = False):
     def __init__(self, name = None, fluid = 1, objectToLoad = None, upVectorNodePath = None, reverseUpVector = False):
-        if (name == None):
+        if name is None:
             name = 'mopath%d' % self.nameIndex
             name = 'mopath%d' % self.nameIndex
             self.nameIndex = self.nameIndex + 1
             self.nameIndex = self.nameIndex + 1
         self.name = name
         self.name = name
@@ -35,24 +36,23 @@ class Mopath(DirectObject):
         return self.maxT * self.timeScale
         return self.maxT * self.timeScale
 
 
     def loadFile(self, filename, fReset = 1):
     def loadFile(self, filename, fReset = 1):
-        nodePath = loader.loadModel(filename)
+        nodePath = base.loader.loadModel(filename)
         if nodePath:
         if nodePath:
             self.loadNodePath(nodePath)
             self.loadNodePath(nodePath)
             nodePath.removeNode()
             nodePath.removeNode()
         else:
         else:
             print('Mopath: no data in file: %s' % filename)
             print('Mopath: no data in file: %s' % filename)
 
 
-
     def loadNodePath(self, nodePath, fReset = 1):
     def loadNodePath(self, nodePath, fReset = 1):
         if fReset:
         if fReset:
             self.reset()
             self.reset()
 
 
         self.__extractCurves(nodePath)
         self.__extractCurves(nodePath)
-        if (self.tNurbsCurve != []):
+        if self.tNurbsCurve != []:
             self.maxT = self.tNurbsCurve[-1].getMaxT()
             self.maxT = self.tNurbsCurve[-1].getMaxT()
-        elif (self.xyzNurbsCurve != None):
+        elif self.xyzNurbsCurve is not None:
             self.maxT = self.xyzNurbsCurve.getMaxT()
             self.maxT = self.xyzNurbsCurve.getMaxT()
-        elif (self.hprNurbsCurve != None):
+        elif self.hprNurbsCurve is not None:
             self.maxT = self.hprNurbsCurve.getMaxT()
             self.maxT = self.hprNurbsCurve.getMaxT()
         else:
         else:
             print('Mopath: no valid curves in nodePath: %s' % nodePath)
             print('Mopath: no valid curves in nodePath: %s' % nodePath)
@@ -74,11 +74,11 @@ class Mopath(DirectObject):
             elif node.getCurveType() == PCTHPR:
             elif node.getCurveType() == PCTHPR:
                 self.hprNurbsCurve = node
                 self.hprNurbsCurve = node
             elif node.getCurveType() == PCTNONE:
             elif node.getCurveType() == PCTNONE:
-                if (self.xyzNurbsCurve == None):
+                if self.xyzNurbsCurve is None:
                     self.xyzNurbsCurve = node
                     self.xyzNurbsCurve = node
                 else:
                 else:
                     print('Mopath: got a PCT_NONE curve and an XYZ Curve in nodePath: %s' % nodePath)
                     print('Mopath: got a PCT_NONE curve and an XYZ Curve in nodePath: %s' % nodePath)
-            elif (node.getCurveType() == PCTT):
+            elif node.getCurveType() == PCTT:
                 self.tNurbsCurve.append(node)
                 self.tNurbsCurve.append(node)
         else:
         else:
             # Iterate over children if any
             # Iterate over children if any
@@ -97,29 +97,29 @@ class Mopath(DirectObject):
 
 
     def getFinalState(self):
     def getFinalState(self):
         pos = Point3(0)
         pos = Point3(0)
-        if (self.xyzNurbsCurve != None):
+        if self.xyzNurbsCurve is not None:
             self.xyzNurbsCurve.getPoint(self.maxT, pos)
             self.xyzNurbsCurve.getPoint(self.maxT, pos)
         hpr = Point3(0)
         hpr = Point3(0)
-        if (self.hprNurbsCurve != None):
+        if self.hprNurbsCurve is not None:
             self.hprNurbsCurve.getPoint(self.maxT, hpr)
             self.hprNurbsCurve.getPoint(self.maxT, hpr)
         return (pos, hpr)
         return (pos, hpr)
 
 
     def goTo(self, node, time):
     def goTo(self, node, time):
-        if (self.xyzNurbsCurve == None) and (self.hprNurbsCurve == None):
+        if self.xyzNurbsCurve is None and self.hprNurbsCurve is None:
             print('Mopath: Mopath has no curves')
             print('Mopath: Mopath has no curves')
             return
             return
         time /= self.timeScale
         time /= self.timeScale
         self.playbackTime = self.calcTime(CLAMP(time, 0.0, self.maxT))
         self.playbackTime = self.calcTime(CLAMP(time, 0.0, self.maxT))
-        if (self.xyzNurbsCurve != None):
+        if self.xyzNurbsCurve is not None:
             self.xyzNurbsCurve.getPoint(self.playbackTime, self.posPoint)
             self.xyzNurbsCurve.getPoint(self.playbackTime, self.posPoint)
             if self.fluid:
             if self.fluid:
                 node.setFluidPos(self.posPoint)
                 node.setFluidPos(self.posPoint)
             else:
             else:
                 node.setPos(self.posPoint)
                 node.setPos(self.posPoint)
-        if (self.hprNurbsCurve != None):
+        if self.hprNurbsCurve is not None:
             self.hprNurbsCurve.getPoint(self.playbackTime, self.hprPoint)
             self.hprNurbsCurve.getPoint(self.playbackTime, self.hprPoint)
             node.setHpr(self.hprPoint)
             node.setHpr(self.hprPoint)
-        elif (self.fFaceForward and (self.xyzNurbsCurve != None)):
+        elif self.fFaceForward and self.xyzNurbsCurve is not None:
             if self.faceForwardDelta:
             if self.faceForwardDelta:
                 # Look at a point a bit ahead in parametric time.
                 # Look at a point a bit ahead in parametric time.
                 t = min(self.playbackTime + self.faceForwardDelta, self.xyzNurbsCurve.getMaxT())
                 t = min(self.playbackTime + self.faceForwardDelta, self.xyzNurbsCurve.getMaxT())
@@ -133,18 +133,18 @@ class Mopath(DirectObject):
 
 
             # use the self.upVectorNodePath position if it exists to
             # use the self.upVectorNodePath position if it exists to
             # create an up vector for lookAt
             # create an up vector for lookAt
-            if (self.upVectorNodePath is None):
+            if self.upVectorNodePath is None:
                 node.lookAt(lookPoint)
                 node.lookAt(lookPoint)
             else:
             else:
-                if (self.reverseUpVector == False):
-                     node.lookAt(lookPoint,
-                                 self.upVectorNodePath.getPos() - self.posPoint)
+                if not self.reverseUpVector:
+                    node.lookAt(lookPoint,
+                                self.upVectorNodePath.getPos() - self.posPoint)
                 else:
                 else:
-                     node.lookAt(lookPoint,
-                                 self.posPoint - self.upVectorNodePath.getPos())
+                    node.lookAt(lookPoint,
+                                self.posPoint - self.upVectorNodePath.getPos())
 
 
     def play(self, node, time = 0.0, loop = 0):
     def play(self, node, time = 0.0, loop = 0):
-        if (self.xyzNurbsCurve == None) and (self.hprNurbsCurve == None):
+        if self.xyzNurbsCurve is None and self.hprNurbsCurve is None:
             print('Mopath: Mopath has no curves')
             print('Mopath: Mopath has no curves')
             return
             return
         self.node = node
         self.node = node
@@ -161,11 +161,11 @@ class Mopath(DirectObject):
         time = globalClock.getFrameTime()
         time = globalClock.getFrameTime()
         dTime = time - task.lastTime
         dTime = time - task.lastTime
         task.lastTime = time
         task.lastTime = time
-        if (self.loop):
+        if self.loop:
             cTime = (task.currentTime + dTime) % self.getMaxT()
             cTime = (task.currentTime + dTime) % self.getMaxT()
         else:
         else:
             cTime = task.currentTime + dTime
             cTime = task.currentTime + dTime
-        if ((self.loop == 0) and (cTime > self.getMaxT())):
+        if self.loop == 0 and cTime > self.getMaxT():
             self.stop()
             self.stop()
             messenger.send(self.name + '-done')
             messenger.send(self.name + '-done')
             self.node = None
             self.node = None
@@ -187,4 +187,3 @@ class Mopath(DirectObject):
             ls.drawTo(p)
             ls.drawTo(p)
 
 
         return NodePath(ls.create())
         return NodePath(ls.create())
-

+ 18 - 16
direct/src/dist/FreezeTool.py

@@ -165,23 +165,23 @@ class CompilationEnvironment:
         if self.platform.startswith('win'):
         if self.platform.startswith('win'):
             self.Python = sysconf.PREFIX
             self.Python = sysconf.PREFIX
 
 
-            if ('VCINSTALLDIR' in os.environ):
+            if 'VCINSTALLDIR' in os.environ:
                 self.MSVC = os.environ['VCINSTALLDIR']
                 self.MSVC = os.environ['VCINSTALLDIR']
-            elif (Filename('/c/Program Files/Microsoft Visual Studio 9.0/VC').exists()):
+            elif Filename('/c/Program Files/Microsoft Visual Studio 9.0/VC').exists():
                 self.MSVC = Filename('/c/Program Files/Microsoft Visual Studio 9.0/VC').toOsSpecific()
                 self.MSVC = Filename('/c/Program Files/Microsoft Visual Studio 9.0/VC').toOsSpecific()
-            elif (Filename('/c/Program Files (x86)/Microsoft Visual Studio 9.0/VC').exists()):
+            elif Filename('/c/Program Files (x86)/Microsoft Visual Studio 9.0/VC').exists():
                 self.MSVC = Filename('/c/Program Files (x86)/Microsoft Visual Studio 9.0/VC').toOsSpecific()
                 self.MSVC = Filename('/c/Program Files (x86)/Microsoft Visual Studio 9.0/VC').toOsSpecific()
-            elif (Filename('/c/Program Files/Microsoft Visual Studio .NET 2003/Vc7').exists()):
+            elif Filename('/c/Program Files/Microsoft Visual Studio .NET 2003/Vc7').exists():
                 self.MSVC = Filename('/c/Program Files/Microsoft Visual Studio .NET 2003/Vc7').toOsSpecific()
                 self.MSVC = Filename('/c/Program Files/Microsoft Visual Studio .NET 2003/Vc7').toOsSpecific()
             else:
             else:
                 print('Could not locate Microsoft Visual C++ Compiler! Try running from the Visual Studio Command Prompt.')
                 print('Could not locate Microsoft Visual C++ Compiler! Try running from the Visual Studio Command Prompt.')
                 sys.exit(1)
                 sys.exit(1)
 
 
-            if ('WindowsSdkDir' in os.environ):
+            if 'WindowsSdkDir' in os.environ:
                 self.PSDK = os.environ['WindowsSdkDir']
                 self.PSDK = os.environ['WindowsSdkDir']
-            elif (platform.architecture()[0] == '32bit' and Filename('/c/Program Files/Microsoft Platform SDK for Windows Server 2003 R2').exists()):
+            elif platform.architecture()[0] == '32bit' and Filename('/c/Program Files/Microsoft Platform SDK for Windows Server 2003 R2').exists():
                 self.PSDK = Filename('/c/Program Files/Microsoft Platform SDK for Windows Server 2003 R2').toOsSpecific()
                 self.PSDK = Filename('/c/Program Files/Microsoft Platform SDK for Windows Server 2003 R2').toOsSpecific()
-            elif (os.path.exists(os.path.join(self.MSVC, 'PlatformSDK'))):
+            elif os.path.exists(os.path.join(self.MSVC, 'PlatformSDK')):
                 self.PSDK = os.path.join(self.MSVC, 'PlatformSDK')
                 self.PSDK = os.path.join(self.MSVC, 'PlatformSDK')
             else:
             else:
                 print('Could not locate the Microsoft Windows Platform SDK! Try running from the Visual Studio Command Prompt.')
                 print('Could not locate the Microsoft Windows Platform SDK! Try running from the Visual Studio Command Prompt.')
@@ -199,7 +199,7 @@ class CompilationEnvironment:
                 self.suffix64 = '\\amd64'
                 self.suffix64 = '\\amd64'
 
 
             # If it is run by makepanda, it handles the MSVC and PlatformSDK paths itself.
             # If it is run by makepanda, it handles the MSVC and PlatformSDK paths itself.
-            if ('MAKEPANDA' in os.environ):
+            if 'MAKEPANDA' in os.environ:
                 self.compileObjExe = 'cl /wd4996 /Fo%(basename)s.obj /nologo /c %(MD)s /Zi /O2 /Ob2 /EHsc /Zm300 /W3 /I"%(pythonIPath)s" %(filename)s'
                 self.compileObjExe = 'cl /wd4996 /Fo%(basename)s.obj /nologo /c %(MD)s /Zi /O2 /Ob2 /EHsc /Zm300 /W3 /I"%(pythonIPath)s" %(filename)s'
                 self.compileObjDll = self.compileObjExe
                 self.compileObjDll = self.compileObjExe
                 self.linkExe = 'link /nologo /MAP:NUL /FIXED:NO /OPT:REF /STACK:4194304 /INCREMENTAL:NO /LIBPATH:"%(python)s\\libs"  /out:%(basename)s.exe %(basename)s.obj'
                 self.linkExe = 'link /nologo /MAP:NUL /FIXED:NO /OPT:REF /STACK:4194304 /INCREMENTAL:NO /LIBPATH:"%(python)s\\libs"  /out:%(basename)s.exe %(basename)s.obj'
@@ -237,7 +237,7 @@ class CompilationEnvironment:
             self.linkExe = "%(CC)s -o %(basename)s %(basename)s.o -L/usr/local/lib -lpython%(pythonVersion)s"
             self.linkExe = "%(CC)s -o %(basename)s %(basename)s.o -L/usr/local/lib -lpython%(pythonVersion)s"
             self.linkDll = "%(LDSHARED)s -o %(basename)s.so %(basename)s.o -L/usr/local/lib -lpython%(pythonVersion)s"
             self.linkDll = "%(LDSHARED)s -o %(basename)s.so %(basename)s.o -L/usr/local/lib -lpython%(pythonVersion)s"
 
 
-            if (os.path.isdir("/usr/PCBSD/local/lib")):
+            if os.path.isdir("/usr/PCBSD/local/lib"):
                 self.linkExe += " -L/usr/PCBSD/local/lib"
                 self.linkExe += " -L/usr/PCBSD/local/lib"
                 self.linkDll += " -L/usr/PCBSD/local/lib"
                 self.linkDll += " -L/usr/PCBSD/local/lib"
 
 
@@ -1009,8 +1009,8 @@ class Freezer:
         if not newName:
         if not newName:
             newName = moduleName
             newName = moduleName
 
 
-        assert(moduleName.endswith('.*'))
-        assert(newName.endswith('.*'))
+        assert moduleName.endswith('.*')
+        assert newName.endswith('.*')
 
 
         mdefs = {}
         mdefs = {}
 
 
@@ -1020,7 +1020,7 @@ class Freezer:
         parentNames = [(parentName, newParentName)]
         parentNames = [(parentName, newParentName)]
 
 
         if parentName.endswith('.*'):
         if parentName.endswith('.*'):
-            assert(newParentName.endswith('.*'))
+            assert newParentName.endswith('.*')
             # Another special case.  The parent name "*" means to
             # Another special case.  The parent name "*" means to
             # return all possible directories within a particular
             # return all possible directories within a particular
             # directory.
             # directory.
@@ -1353,7 +1353,7 @@ class Freezer:
         for moduleName, module in list(self.mf.modules.items()):
         for moduleName, module in list(self.mf.modules.items()):
             if module.__code__:
             if module.__code__:
                 co = self.mf.replace_paths_in_code(module.__code__)
                 co = self.mf.replace_paths_in_code(module.__code__)
-                module.__code__ = co;
+                module.__code__ = co
 
 
     def __addPyc(self, multifile, filename, code, compressionLevel):
     def __addPyc(self, multifile, filename, code, compressionLevel):
         if code:
         if code:
@@ -2226,7 +2226,7 @@ class Freezer:
 
 
                 strings = macho_data[stroff:stroff+strsize]
                 strings = macho_data[stroff:stroff+strsize]
 
 
-                for i in range(nsyms):
+                for j in range(nsyms):
                     strx, type, sect, desc, value = struct.unpack_from(nlist_struct, macho_data, symoff)
                     strx, type, sect, desc, value = struct.unpack_from(nlist_struct, macho_data, symoff)
                     symoff += nlist_size
                     symoff += nlist_size
                     name = strings[strx : strings.find(b'\0', strx)]
                     name = strings[strx : strings.find(b'\0', strx)]
@@ -2539,8 +2539,10 @@ class PandaModuleFinder(modulefinder.ModuleFinder):
                     if "*" in fromlist:
                     if "*" in fromlist:
                         have_star = 1
                         have_star = 1
                     fromlist = [f for f in fromlist if f != "*"]
                     fromlist = [f for f in fromlist if f != "*"]
-                if what == "absolute_import": level = 0
-                else: level = -1
+                if what == "absolute_import":
+                    level = 0
+                else:
+                    level = -1
                 self._safe_import_hook(name, m, fromlist, level=level)
                 self._safe_import_hook(name, m, fromlist, level=level)
                 if have_star:
                 if have_star:
                     # We've encountered an "import *". If it is a Python module,
                     # We've encountered an "import *". If it is a Python module,

+ 1 - 6
direct/src/dist/commands.py

@@ -16,7 +16,6 @@ import stat
 import struct
 import struct
 import imp
 import imp
 import string
 import string
-import time
 import tempfile
 import tempfile
 
 
 import setuptools
 import setuptools
@@ -500,11 +499,7 @@ class build_apps(setuptools.Command):
             icon.makeICNS(os.path.join(resdir, 'iconfile.icns'))
             icon.makeICNS(os.path.join(resdir, 'iconfile.icns'))
 
 
         with open(os.path.join(contentsdir, 'Info.plist'), 'wb') as f:
         with open(os.path.join(contentsdir, 'Info.plist'), 'wb') as f:
-            if hasattr(plistlib, 'dump'):
-                plistlib.dump(plist, f)
-            else:
-                plistlib.writePlist(plist, f)
-
+            plistlib.dump(plist, f)
 
 
     def build_runtimes(self, platform, use_wheels):
     def build_runtimes(self, platform, use_wheels):
         """ Builds the distributions for the given platform. """
         """ Builds the distributions for the given platform. """

+ 1 - 1
direct/src/dist/icon.py

@@ -150,7 +150,7 @@ class Icon:
 
 
         # ICO files only support resolutions up to 256x256.
         # ICO files only support resolutions up to 256x256.
         count = 0
         count = 0
-        for size in self.images.keys():
+        for size in self.images:
             if size < 256:
             if size < 256:
                 count += 1
                 count += 1
             if size <= 256:
             if size <= 256:

+ 0 - 1
direct/src/dist/installers.py

@@ -170,4 +170,3 @@ def create_nsis(command, basename, build_dir):
         )
         )
     cmd.append(nsifile.to_os_specific())
     cmd.append(nsifile.to_os_specific())
     subprocess.check_call(cmd)
     subprocess.check_call(cmd)
-

+ 2 - 0
direct/src/dist/pefile.py

@@ -487,6 +487,8 @@ class ResourceTable(object):
             entry.data = data
             entry.data = data
             entry.code_page = code_page
             entry.code_page = code_page
 
 
+        return entry
+
 
 
 class PEFile(object):
 class PEFile(object):
 
 

+ 1 - 1
direct/src/dist/pfreeze.py

@@ -105,7 +105,7 @@ def main(args=None):
         elif opt == '-h':
         elif opt == '-h':
             usage(0)
             usage(0)
         else:
         else:
-            print('illegal option: ' + flag)
+            print('illegal option: ' + opt)
             sys.exit(1)
             sys.exit(1)
 
 
     if not basename:
     if not basename:

+ 3 - 1
direct/src/distributed/AsyncRequest.py

@@ -1,6 +1,7 @@
 #from otp.ai.AIBaseGlobal import *
 #from otp.ai.AIBaseGlobal import *
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
 from direct.showbase.DirectObject import DirectObject
 from direct.showbase.DirectObject import DirectObject
+from direct.showbase.MessengerGlobal import messenger
 from .ConnectionRepository import *
 from .ConnectionRepository import *
 from panda3d.core import ConfigVariableDouble, ConfigVariableInt, ConfigVariableBool
 from panda3d.core import ConfigVariableDouble, ConfigVariableInt, ConfigVariableBool
 
 
@@ -254,7 +255,8 @@ class AsyncRequest(DirectObject):
                         print("\n\nself.avatarId =", self.avatarId)
                         print("\n\nself.avatarId =", self.avatarId)
                     print("\nself.neededObjects =", self.neededObjects)
                     print("\nself.neededObjects =", self.neededObjects)
                     print("\ntimed out after %s seconds.\n\n"%(task.delayTime,))
                     print("\ntimed out after %s seconds.\n\n"%(task.delayTime,))
-                    import pdb; pdb.set_trace()
+                    import pdb
+                    pdb.set_trace()
             self.delete()
             self.delete()
             return Task.done
             return Task.done
 
 

+ 7 - 4
direct/src/distributed/CRCache.py

@@ -1,8 +1,11 @@
 """CRCache module: contains the CRCache class"""
 """CRCache module: contains the CRCache class"""
 
 
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
+from direct.showbase.MessengerGlobal import messenger
+from direct.showbase.PythonUtil import safeRepr, itype
 from . import DistributedObject
 from . import DistributedObject
 
 
+
 class CRCache:
 class CRCache:
     notify = DirectNotifyGlobal.directNotify.newCategory("CRCache")
     notify = DirectNotifyGlobal.directNotify.newCategory("CRCache")
 
 
@@ -41,7 +44,7 @@ class CRCache:
         for distObj in delayDeleted:
         for distObj in delayDeleted:
             if distObj.getDelayDeleteCount() != 0:
             if distObj.getDelayDeleteCount() != 0:
                 delayDeleteLeaks.append(distObj)
                 delayDeleteLeaks.append(distObj)
-        if len(delayDeleteLeaks):
+        if len(delayDeleteLeaks) > 0:
             s = 'CRCache.flush:'
             s = 'CRCache.flush:'
             for obj in delayDeleteLeaks:
             for obj in delayDeleteLeaks:
                 s += ('\n  could not delete %s (%s), delayDeletes=%s' %
                 s += ('\n  could not delete %s (%s), delayDeletes=%s' %
@@ -76,7 +79,7 @@ class CRCache:
                 # if the cache is full, pop the oldest item
                 # if the cache is full, pop the oldest item
                 oldestDistObj = self.fifo.pop(0)
                 oldestDistObj = self.fifo.pop(0)
                 # and remove it from the dictionary
                 # and remove it from the dictionary
-                del(self.dict[oldestDistObj.getDoId()])
+                del self.dict[oldestDistObj.getDoId()]
                 # and delete it
                 # and delete it
                 oldestDistObj.deleteOrDelay()
                 oldestDistObj.deleteOrDelay()
                 if oldestDistObj.getDelayDeleteCount() <= 0:
                 if oldestDistObj.getDelayDeleteCount() <= 0:
@@ -93,7 +96,7 @@ class CRCache:
             # Find the object
             # Find the object
             distObj = self.dict[doId]
             distObj = self.dict[doId]
             # Remove it from the dictionary
             # Remove it from the dictionary
-            del(self.dict[doId])
+            del self.dict[doId]
             # Remove it from the fifo
             # Remove it from the fifo
             self.fifo.remove(distObj)
             self.fifo.remove(distObj)
             # return the distObj
             # return the distObj
@@ -111,7 +114,7 @@ class CRCache:
         # Look it up
         # Look it up
         distObj = self.dict[doId]
         distObj = self.dict[doId]
         # Remove it from the dict and fifo
         # Remove it from the dict and fifo
-        del(self.dict[doId])
+        del self.dict[doId]
         self.fifo.remove(distObj)
         self.fifo.remove(distObj)
         # and delete it
         # and delete it
         distObj.deleteOrDelay()
         distObj.deleteOrDelay()

+ 0 - 1
direct/src/distributed/CRDataCache.py

@@ -114,4 +114,3 @@ if __debug__:
     dc._stopMemLeakCheck()
     dc._stopMemLeakCheck()
     dc.destroy()
     dc.destroy()
     del dc
     del dc
-

+ 4 - 4
direct/src/distributed/CartesianGridBase.py

@@ -29,8 +29,8 @@ class CartesianGridBase:
         # Compute which zone we are in
         # Compute which zone we are in
         zoneId = int(self.startingZone + ((row * self.gridSize) + col))
         zoneId = int(self.startingZone + ((row * self.gridSize) + col))
 
 
-        if (wantRowAndCol):
-            return (zoneId,col,row)
+        if wantRowAndCol:
+            return (zoneId, col, row)
         else:
         else:
             return zoneId
             return zoneId
 
 
@@ -113,9 +113,9 @@ class CartesianGridBase:
             else:
             else:
                 # in a middle column, only look at top and bottom rows
                 # in a middle column, only look at top and bottom rows
                 possibleRows = []
                 possibleRows = []
-                if (topOffset == radius):
+                if topOffset == radius:
                     possibleRows.append(0)
                     possibleRows.append(0)
-                if (bottomOffset == radius):
+                if bottomOffset == radius:
                     possibleRows.append(bottomOffset + topOffset)
                     possibleRows.append(bottomOffset + topOffset)
             #print "on column %s and looking at rows %s"%(currCol,possibleRows)
             #print "on column %s and looking at rows %s"%(currCol,possibleRows)
             for currRow in possibleRows:
             for currRow in possibleRows:

+ 9 - 8
direct/src/distributed/ClientRepository.py

@@ -2,10 +2,11 @@
 
 
 from .ClientRepositoryBase import ClientRepositoryBase
 from .ClientRepositoryBase import ClientRepositoryBase
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
+from direct.showbase.MessengerGlobal import messenger
 from .MsgTypesCMU import *
 from .MsgTypesCMU import *
 from .PyDatagram import PyDatagram
 from .PyDatagram import PyDatagram
 from .PyDatagramIterator import PyDatagramIterator
 from .PyDatagramIterator import PyDatagramIterator
-from panda3d.core import UniqueIdAllocator
+from panda3d.core import UniqueIdAllocator, Notify
 
 
 
 
 class ClientRepository(ClientRepositoryBase):
 class ClientRepository(ClientRepositoryBase):
@@ -68,7 +69,7 @@ class ClientRepository(ClientRepositoryBase):
         zone = di.getUint32()
         zone = di.getUint32()
         for obj in self.doId2do.values():
         for obj in self.doId2do.values():
             if obj.zoneId == zone:
             if obj.zoneId == zone:
-                if (self.isLocalId(obj.doId)):
+                if self.isLocalId(obj.doId):
                     self.resendGenerate(obj)
                     self.resendGenerate(obj)
 
 
     def resendGenerate(self, obj):
     def resendGenerate(self, obj):
@@ -114,12 +115,12 @@ class ClientRepository(ClientRepositoryBase):
             # repeat-generate, synthesized for the benefit of someone
             # repeat-generate, synthesized for the benefit of someone
             # else who just entered the zone.  Accept the new updates,
             # else who just entered the zone.  Accept the new updates,
             # but don't make a formal generate.
             # but don't make a formal generate.
-            assert(self.notify.debug("performing generate-update for %s %s" % (dclass.getName(), doId)))
+            assert self.notify.debug("performing generate-update for %s %s" % (dclass.getName(), doId))
             dclass.receiveUpdateBroadcastRequired(distObj, di)
             dclass.receiveUpdateBroadcastRequired(distObj, di)
             dclass.receiveUpdateOther(distObj, di)
             dclass.receiveUpdateOther(distObj, di)
             return
             return
 
 
-        assert(self.notify.debug("performing generate for %s %s" % (dclass.getName(), doId)))
+        assert self.notify.debug("performing generate for %s %s" % (dclass.getName(), doId))
         dclass.startGenerate()
         dclass.startGenerate()
         # Create a new distributed object, and put it in the dictionary
         # Create a new distributed object, and put it in the dictionary
         distObj = self.generateWithRequiredOtherFields(dclass, doId, di, 0, zoneId)
         distObj = self.generateWithRequiredOtherFields(dclass, doId, di, 0, zoneId)
@@ -200,7 +201,7 @@ class ClientRepository(ClientRepositoryBase):
         if not dclass:
         if not dclass:
             self.notify.error("Unknown distributed class: %s" % (distObj.__class__))
             self.notify.error("Unknown distributed class: %s" % (distObj.__class__))
         classDef = dclass.getClassDef()
         classDef = dclass.getClassDef()
-        if classDef == None:
+        if classDef is None:
             self.notify.error("Could not create an undefined %s object." % (
             self.notify.error("Could not create an undefined %s object." % (
                 dclass.getName()))
                 dclass.getName()))
 
 
@@ -289,13 +290,13 @@ class ClientRepository(ClientRepositoryBase):
         """ Returns true if this doId is one that we're the owner of,
         """ Returns true if this doId is one that we're the owner of,
         false otherwise. """
         false otherwise. """
 
 
-        return ((doId >= self.doIdBase) and (doId < self.doIdLast))
+        return doId >= self.doIdBase and doId < self.doIdLast
 
 
     def haveCreateAuthority(self):
     def haveCreateAuthority(self):
         """ Returns true if this client has been assigned a range of
         """ Returns true if this client has been assigned a range of
         doId's it may use to create objects, false otherwise. """
         doId's it may use to create objects, false otherwise. """
 
 
-        return (self.doIdLast > self.doIdBase)
+        return self.doIdLast > self.doIdBase
 
 
     def getAvatarIdFromSender(self):
     def getAvatarIdFromSender(self):
         """ Returns the doIdBase of the client that originally sent
         """ Returns the doIdBase of the client that originally sent
@@ -306,7 +307,7 @@ class ClientRepository(ClientRepositoryBase):
     def handleDatagram(self, di):
     def handleDatagram(self, di):
         if self.notify.getDebug():
         if self.notify.getDebug():
             print("ClientRepository received datagram:")
             print("ClientRepository received datagram:")
-            di.getDatagram().dumpHex(ostream)
+            di.getDatagram().dumpHex(Notify.out())
 
 
         msgType = self.getMsgType()
         msgType = self.getMsgType()
         self.currentSenderId = None
         self.currentSenderId = None

+ 13 - 11
direct/src/distributed/ClientRepositoryBase.py

@@ -1,16 +1,18 @@
 from panda3d.core import *
 from panda3d.core import *
 from panda3d.direct import *
 from panda3d.direct import *
-from .MsgTypes import *
 from direct.task import Task
 from direct.task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
-from . import CRCache
 from direct.distributed.CRDataCache import CRDataCache
 from direct.distributed.CRDataCache import CRDataCache
 from direct.distributed.ConnectionRepository import ConnectionRepository
 from direct.distributed.ConnectionRepository import ConnectionRepository
-from direct.showbase import PythonUtil
+from direct.showbase.PythonUtil import safeRepr, itype, makeList
+from direct.showbase.MessengerGlobal import messenger
+from .MsgTypes import *
+from . import CRCache
 from . import ParentMgr
 from . import ParentMgr
 from . import RelatedObjectMgr
 from . import RelatedObjectMgr
-import time
 from .ClockDelta import *
 from .ClockDelta import *
+import time
 
 
 
 
 class ClientRepositoryBase(ConnectionRepository):
 class ClientRepositoryBase(ConnectionRepository):
@@ -155,7 +157,7 @@ class ClientRepositoryBase(ConnectionRepository):
         # Look up the dclass
         # Look up the dclass
         assert parentId == self.GameGlobalsId or parentId in self.doId2do
         assert parentId == self.GameGlobalsId or parentId in self.doId2do
         dclass = self.dclassesByNumber[classId]
         dclass = self.dclassesByNumber[classId]
-        assert(self.notify.debug("performing generate for %s %s" % (dclass.getName(), doId)))
+        assert self.notify.debug("performing generate for %s %s" % (dclass.getName(), doId))
         dclass.startGenerate()
         dclass.startGenerate()
         # Create a new distributed object, and put it in the dictionary
         # Create a new distributed object, and put it in the dictionary
         distObj = self.generateWithRequiredOtherFields(dclass, doId, di, parentId, zoneId)
         distObj = self.generateWithRequiredOtherFields(dclass, doId, di, parentId, zoneId)
@@ -189,7 +191,7 @@ class ClientRepositoryBase(ConnectionRepository):
                 for dg, di in updates:
                 for dg, di in updates:
                     # non-DC updates that need to be played back in-order are
                     # non-DC updates that need to be played back in-order are
                     # stored as (msgType, (dg, di))
                     # stored as (msgType, (dg, di))
-                    if type(di) is tuple:
+                    if isinstance(di, tuple):
                         msgType = dg
                         msgType = dg
                         dg, di = di
                         dg, di = di
                         self.replayDeferredGenerate(msgType, (dg, di))
                         self.replayDeferredGenerate(msgType, (dg, di))
@@ -248,7 +250,7 @@ class ClientRepositoryBase(ConnectionRepository):
             # ...it is not in the dictionary or the cache.
             # ...it is not in the dictionary or the cache.
             # Construct a new one
             # Construct a new one
             classDef = dclass.getClassDef()
             classDef = dclass.getClassDef()
-            if classDef == None:
+            if classDef is None:
                 self.notify.error("Could not create an undefined %s object." % (dclass.getName()))
                 self.notify.error("Could not create an undefined %s object." % (dclass.getName()))
             distObj = classDef(self)
             distObj = classDef(self)
             distObj.dclass = dclass
             distObj.dclass = dclass
@@ -296,7 +298,7 @@ class ClientRepositoryBase(ConnectionRepository):
             # ...it is not in the dictionary or the cache.
             # ...it is not in the dictionary or the cache.
             # Construct a new one
             # Construct a new one
             classDef = dclass.getClassDef()
             classDef = dclass.getClassDef()
-            if classDef == None:
+            if classDef is None:
                 self.notify.error("Could not create an undefined %s object." % (dclass.getName()))
                 self.notify.error("Could not create an undefined %s object." % (dclass.getName()))
             distObj = classDef(self)
             distObj = classDef(self)
             distObj.dclass = dclass
             distObj.dclass = dclass
@@ -339,7 +341,7 @@ class ClientRepositoryBase(ConnectionRepository):
             # ...it is not in the dictionary or the cache.
             # ...it is not in the dictionary or the cache.
             # Construct a new one
             # Construct a new one
             classDef = dclass.getOwnerClassDef()
             classDef = dclass.getOwnerClassDef()
-            if classDef == None:
+            if classDef is None:
                 self.notify.error("Could not create an undefined %s object. Have you created an owner view?" % (dclass.getName()))
                 self.notify.error("Could not create an undefined %s object. Have you created an owner view?" % (dclass.getName()))
             distObj = classDef(self)
             distObj = classDef(self)
             distObj.dclass = dclass
             distObj.dclass = dclass
@@ -452,7 +454,7 @@ class ClientRepositoryBase(ConnectionRepository):
             # a dict and adding the avatar handles to that dict when they are created
             # a dict and adding the avatar handles to that dict when they are created
             # then change/remove the old method. I didn't do that because I couldn't think
             # then change/remove the old method. I didn't do that because I couldn't think
             # of a use for it. -JML
             # of a use for it. -JML
-            try :
+            try:
                 handle = self.identifyAvatar(doId)
                 handle = self.identifyAvatar(doId)
                 if handle:
                 if handle:
                     dclass = self.dclassesByName[handle.dclassName]
                     dclass = self.dclassesByName[handle.dclassName]
@@ -477,7 +479,7 @@ class ClientRepositoryBase(ConnectionRepository):
     def handleGoGetLost(self, di):
     def handleGoGetLost(self, di):
         # The server told us it's about to drop the connection on us.
         # The server told us it's about to drop the connection on us.
         # Get ready!
         # Get ready!
-        if (di.getRemainingSize() > 0):
+        if di.getRemainingSize() > 0:
             self.bootedIndex = di.getUint16()
             self.bootedIndex = di.getUint16()
             self.bootedText = di.getString()
             self.bootedText = di.getString()
 
 

+ 3 - 3
direct/src/distributed/ClockDelta.py

@@ -78,7 +78,7 @@ class ClockDelta(DirectObject.DirectObject):
         # representing infinite uncertainty, if we have never received
         # representing infinite uncertainty, if we have never received
         # a time measurement.
         # a time measurement.
 
 
-        if self.uncertainty == None:
+        if self.uncertainty is None:
             return None
             return None
 
 
         now = self.globalClock.getRealTime()
         now = self.globalClock.getRealTime()
@@ -190,7 +190,7 @@ class ClockDelta(DirectObject.DirectObject):
         the new measurement was used, false if it was discarded.
         the new measurement was used, false if it was discarded.
         """
         """
         oldUncertainty = self.getUncertainty()
         oldUncertainty = self.getUncertainty()
-        if oldUncertainty != None:
+        if oldUncertainty is not None:
             self.notify.info(
             self.notify.info(
                 'previous delta at %.3f s, +/- %.3f s.' %
                 'previous delta at %.3f s, +/- %.3f s.' %
                 (self.delta, oldUncertainty))
                 (self.delta, oldUncertainty))
@@ -241,7 +241,7 @@ class ClockDelta(DirectObject.DirectObject):
         minutes of the current local time given in now, or
         minutes of the current local time given in now, or
         getRealTime() if now is not specified.
         getRealTime() if now is not specified.
         """
         """
-        if now == None:
+        if now is None:
             now = self.globalClock.getRealTime()
             now = self.globalClock.getRealTime()
 
 
         # Are we in non-real-time mode (i.e. filming a movie)?  If you
         # Are we in non-real-time mode (i.e. filming a movie)?  If you

+ 9 - 7
direct/src/distributed/ConnectionRepository.py

@@ -1,10 +1,12 @@
 from panda3d.core import *
 from panda3d.core import *
 from panda3d.direct import *
 from panda3d.direct import *
 from direct.task import Task
 from direct.task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.distributed.DoInterestManager import DoInterestManager
 from direct.distributed.DoInterestManager import DoInterestManager
 from direct.distributed.DoCollectionManager import DoCollectionManager
 from direct.distributed.DoCollectionManager import DoCollectionManager
 from direct.showbase import GarbageReport
 from direct.showbase import GarbageReport
+from direct.showbase.MessengerGlobal import messenger
 from .PyDatagramIterator import PyDatagramIterator
 from .PyDatagramIterator import PyDatagramIterator
 
 
 import inspect
 import inspect
@@ -175,7 +177,7 @@ class ConnectionRepository(
         def applyFieldValues(distObj, dclass, values):
         def applyFieldValues(distObj, dclass, values):
             for i in range(dclass.getNumInheritedFields()):
             for i in range(dclass.getNumInheritedFields()):
                 field = dclass.getInheritedField(i)
                 field = dclass.getInheritedField(i)
-                if field.asMolecularField() == None:
+                if field.asMolecularField() is None:
                     value = values.get(field.getName(), None)
                     value = values.get(field.getName(), None)
                     if value is None and field.isRequired():
                     if value is None and field.isRequired():
                         # Gee, this could be better.  What would really be
                         # Gee, this could be better.  What would really be
@@ -214,7 +216,7 @@ class ConnectionRepository(
 
 
         # Construct a new one
         # Construct a new one
         classDef = dclass.getClassDef()
         classDef = dclass.getClassDef()
-        if classDef == None:
+        if classDef is None:
             self.notify.error("Could not create an undefined %s object."%(
             self.notify.error("Could not create an undefined %s object."%(
                 dclass.getName()))
                 dclass.getName()))
         distObj = classDef(self)
         distObj = classDef(self)
@@ -252,7 +254,7 @@ class ConnectionRepository(
             dcFileNames = [dcFileNames]
             dcFileNames = [dcFileNames]
 
 
         dcImports = {}
         dcImports = {}
-        if dcFileNames == None:
+        if dcFileNames is None:
             readResult = dcFile.readAll()
             readResult = dcFile.readAll()
             if not readResult:
             if not readResult:
                 self.notify.error("Could not read dc file.")
                 self.notify.error("Could not read dc file.")
@@ -322,7 +324,7 @@ class ConnectionRepository(
                 classDef = dcImports.get(className)
                 classDef = dcImports.get(className)
 
 
             # Also try it without the dcSuffix.
             # Also try it without the dcSuffix.
-            if classDef == None:
+            if classDef is None:
                 className = dclass.getName()
                 className = dclass.getName()
                 classDef = dcImports.get(className)
                 classDef = dcImports.get(className)
             if classDef is None:
             if classDef is None:
@@ -379,7 +381,7 @@ class ConnectionRepository(
             # in the DC file.
             # in the DC file.
             for i in range(dcFile.getNumClasses()):
             for i in range(dcFile.getNumClasses()):
                 dclass = dcFile.getClass(i)
                 dclass = dcFile.getClass(i)
-                if ((dclass.getName()+ownerDcSuffix) in ownerImportSymbols):
+                if (dclass.getName()+ownerDcSuffix) in ownerImportSymbols:
                     number = dclass.getNumber()
                     number = dclass.getNumber()
                     className = dclass.getName() + ownerDcSuffix
                     className = dclass.getName() + ownerDcSuffix
 
 
@@ -583,7 +585,7 @@ class ConnectionRepository(
         # available.  Returns the HTTPClient (also self.http), or None
         # available.  Returns the HTTPClient (also self.http), or None
         # if not set.
         # if not set.
 
 
-        if self.http == None:
+        if self.http is None:
             try:
             try:
                 self.http = HTTPClient()
                 self.http = HTTPClient()
             except:
             except:
@@ -662,7 +664,7 @@ class ConnectionRepository(
             self.setSimulatedDisconnect(0)
             self.setSimulatedDisconnect(0)
 
 
     def uniqueName(self, idString):
     def uniqueName(self, idString):
-        return ("%s-%s" % (idString, self.uniqueId))
+        return "%s-%s" % (idString, self.uniqueId)
 
 
 class GCTrigger:
 class GCTrigger:
     # used to trigger garbage collection
     # used to trigger garbage collection

+ 3 - 3
direct/src/distributed/DistributedCamera.py

@@ -12,7 +12,7 @@ class Fixture(NodePath, FSM):
         self.lens = PerspectiveLens()
         self.lens = PerspectiveLens()
         self.lens.setFov(base.camLens.getFov())
         self.lens.setFov(base.camLens.getFov())
 
 
-        model = loader.loadModel('models/misc/camera', okMissing = True)
+        model = base.loader.loadModel('models/misc/camera', okMissing = True)
         model.reparentTo(self)
         model.reparentTo(self)
 
 
         self.reparentTo(parent)
         self.reparentTo(parent)
@@ -129,8 +129,8 @@ class Fixture(NodePath, FSM):
 
 
     def enterUsing(self, args = []):
     def enterUsing(self, args = []):
         localAvatar.b_setGameState('Camera')
         localAvatar.b_setGameState('Camera')
-        camera.setPosHpr(0,0,0,0,0,0)
-        camera.reparentTo(self)
+        base.camera.setPosHpr(0,0,0,0,0,0)
+        base.camera.reparentTo(self)
         self.hide()
         self.hide()
 
 
         base.cam.node().setLens(self.lens)
         base.cam.node().setLens(self.lens)

+ 9 - 9
direct/src/distributed/DistributedCartesianGrid.py

@@ -81,7 +81,7 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase):
 
 
     def handleChildArrive(self, child, zoneId):
     def handleChildArrive(self, child, zoneId):
         DistributedNode.handleChildArrive(self, child, zoneId)
         DistributedNode.handleChildArrive(self, child, zoneId)
-        if (zoneId >= self.startingZone):
+        if zoneId >= self.startingZone:
             if not child.gridParent:
             if not child.gridParent:
                 child.gridParent = GridParent(child)
                 child.gridParent = GridParent(child)
             child.gridParent.setGridParent(self, zoneId)
             child.gridParent.setGridParent(self, zoneId)
@@ -91,7 +91,7 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase):
 
 
     def handleChildArriveZone(self, child, zoneId):
     def handleChildArriveZone(self, child, zoneId):
         DistributedNode.handleChildArrive(self, child, zoneId)
         DistributedNode.handleChildArrive(self, child, zoneId)
-        if (zoneId >= self.startingZone):
+        if zoneId >= self.startingZone:
             if not child.gridParent:
             if not child.gridParent:
                 child.gridParent = GridParent(child)
                 child.gridParent = GridParent(child)
             child.gridParent.setGridParent(self, zoneId)
             child.gridParent.setGridParent(self, zoneId)
@@ -150,21 +150,21 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase):
 
 
         # sometimes we also need to remove vis avatar from
         # sometimes we also need to remove vis avatar from
         # my parent if it is also a grid
         # my parent if it is also a grid
-        if (clearAll):
+        if clearAll:
             if event is not None:
             if event is not None:
                 parentEvent = eventGroup.newEvent('%s.parent.removeInterest' % self.doId)
                 parentEvent = eventGroup.newEvent('%s.parent.removeInterest' % self.doId)
             else:
             else:
                 parentEvent = None
                 parentEvent = None
 
 
             ##HACK BANDAID FOR PVP INSTANCES
             ##HACK BANDAID FOR PVP INSTANCES
-            if(hasattr(self.cr.doId2do[self.parentId],"worldGrid")):
+            if hasattr(self.cr.doId2do[self.parentId], "worldGrid"):
                 self.cr.doId2do[self.parentId].worldGrid.stopProcessVisibility(event=parentEvent)
                 self.cr.doId2do[self.parentId].worldGrid.stopProcessVisibility(event=parentEvent)
 
 
     def processVisibility(self, task):
     def processVisibility(self, task):
-        if self.visAvatar == None:
+        if self.visAvatar is None:
             # no avatar to process visibility for
             # no avatar to process visibility for
             return Task.done
             return Task.done
-        if(self.visAvatar.isDisabled()):
+        if self.visAvatar.isDisabled():
             self.visAvatar = None
             self.visAvatar = None
             return Task.done
             return Task.done
         if self.visAvatar.gameFSM.state == 'Cutscene':
         if self.visAvatar.gameFSM.state == 'Cutscene':
@@ -192,7 +192,7 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase):
         zoneId = int(self.startingZone + ((row * self.gridSize) + col))
         zoneId = int(self.startingZone + ((row * self.gridSize) + col))
         assert self.notify.debug("processVisibility: %s: row: %s col: %s zoneId: %s" %
         assert self.notify.debug("processVisibility: %s: row: %s col: %s zoneId: %s" %
                                  (self.doId, row, col, zoneId))
                                  (self.doId, row, col, zoneId))
-        if (zoneId == self.visZone):
+        if zoneId == self.visZone:
             assert self.notify.debug(
             assert self.notify.debug(
                 "processVisibility: %s: interest did not change" % (self.doId))
                 "processVisibility: %s: interest did not change" % (self.doId))
             if self.visDirty:
             if self.visDirty:
@@ -314,7 +314,7 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase):
 
 
             # Load up grid parts to initialize grid object
             # Load up grid parts to initialize grid object
             # Polygon used to mark grid plane
             # Polygon used to mark grid plane
-            # self.gridBack = loader.loadModel('models/misc/gridBack')
+            # self.gridBack = base.loader.loadModel('models/misc/gridBack')
             # self.gridBack.reparentTo(self)
             # self.gridBack.reparentTo(self)
             # self.gridBack.setColor(0.2, 0.2, 0.2, 0.5)
             # self.gridBack.setColor(0.2, 0.2, 0.2, 0.5)
 
 
@@ -397,7 +397,7 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase):
             dx = self.cellWidth * self.gridSize * .5
             dx = self.cellWidth * self.gridSize * .5
             for i in range(self.gridSize):
             for i in range(self.gridSize):
                 for j in range(self.gridSize):
                 for j in range(self.gridSize):
-                    marker = loader.loadModel("models/misc/smiley")
+                    marker = base.loader.loadModel("models/misc/smiley")
                     marker.reparentTo(self.markerParent)
                     marker.reparentTo(self.markerParent)
                     marker.setPos(i * self.cellWidth - dx,
                     marker.setPos(i * self.cellWidth - dx,
                                   j * self.cellWidth - dx,
                                   j * self.cellWidth - dx,

+ 8 - 8
direct/src/distributed/DistributedCartesianGridAI.py

@@ -3,6 +3,7 @@ from panda3d.core import *
 from panda3d.direct import *
 from panda3d.direct import *
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.task import Task
 from direct.task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 from .DistributedNodeAI import DistributedNodeAI
 from .DistributedNodeAI import DistributedNodeAI
 from .CartesianGridBase import CartesianGridBase
 from .CartesianGridBase import CartesianGridBase
 
 
@@ -56,7 +57,7 @@ class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
         # Put the avatar on the grid
         # Put the avatar on the grid
         self.handleAvatarZoneChange(av, useZoneId)
         self.handleAvatarZoneChange(av, useZoneId)
 
 
-        if (not self.updateTaskStarted) and startAutoUpdate:
+        if startAutoUpdate and not self.updateTaskStarted:
             self.startUpdateGridTask()
             self.startUpdateGridTask()
 
 
     def removeObjectFromGrid(self, av):
     def removeObjectFromGrid(self, av):
@@ -100,24 +101,24 @@ class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
         for avId in list(self.gridObjects.keys()):
         for avId in list(self.gridObjects.keys()):
             av = self.gridObjects[avId]
             av = self.gridObjects[avId]
             # handle a missing object after it is already gone?
             # handle a missing object after it is already gone?
-            if (av.isEmpty()):
+            if av.isEmpty():
                 task.setDelay(1.0)
                 task.setDelay(1.0)
                 del self.gridObjects[avId]
                 del self.gridObjects[avId]
                 continue
                 continue
             pos = av.getPos()
             pos = av.getPos()
-            if ((pos[0] < 0 or pos[1] < 0) or
-                (pos[0] > self.cellWidth or pos[1] > self.cellWidth)):
+            if (pos[0] < 0 or pos[1] < 0) or \
+               (pos[0] > self.cellWidth or pos[1] > self.cellWidth):
                 # we are out of the bounds of this current cell
                 # we are out of the bounds of this current cell
                 self.handleAvatarZoneChange(av)
                 self.handleAvatarZoneChange(av)
         # Do this every second, not every frame
         # Do this every second, not every frame
-        if (task):
+        if task:
             task.setDelay(1.0)
             task.setDelay(1.0)
         return Task.again
         return Task.again
 
 
     def handleAvatarZoneChange(self, av, useZoneId=-1):
     def handleAvatarZoneChange(self, av, useZoneId=-1):
         # Calculate zone id
         # Calculate zone id
         # Get position of av relative to this grid
         # Get position of av relative to this grid
-        if (useZoneId == -1):
+        if useZoneId == -1:
             pos = av.getPos(self)
             pos = av.getPos(self)
             zoneId = self.getZoneFromXYZ(pos)
             zoneId = self.getZoneFromXYZ(pos)
         else:
         else:
@@ -137,9 +138,8 @@ class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
 
 
     def handleSetLocation(self, av, parentId, zoneId):
     def handleSetLocation(self, av, parentId, zoneId):
         pass
         pass
-        #if (av.parentId != parentId):
+        #if av.parentId != parentId:
             # parent changed, need to look up instance tree
             # parent changed, need to look up instance tree
             # to see if avatar's named area location information
             # to see if avatar's named area location information
             # changed
             # changed
             #av.requestRegionUpdateTask(regionegionUid)
             #av.requestRegionUpdateTask(regionegionUid)
-

+ 4 - 8
direct/src/distributed/DistributedNode.py

@@ -9,9 +9,7 @@ class DistributedNode(DistributedObject.DistributedObject, NodePath):
     """Distributed Node class:"""
     """Distributed Node class:"""
 
 
     def __init__(self, cr):
     def __init__(self, cr):
-        try:
-            self.DistributedNode_initialized
-        except:
+        if not hasattr(self, 'DistributedNode_initialized'):
             self.DistributedNode_initialized = 1
             self.DistributedNode_initialized = 1
             self.gotStringParentToken = 0
             self.gotStringParentToken = 0
             DistributedObject.DistributedObject.__init__(self, cr)
             DistributedObject.DistributedObject.__init__(self, cr)
@@ -28,9 +26,7 @@ class DistributedNode(DistributedObject.DistributedObject, NodePath):
             DistributedObject.DistributedObject.disable(self)
             DistributedObject.DistributedObject.disable(self)
 
 
     def delete(self):
     def delete(self):
-        try:
-            self.DistributedNode_deleted
-        except:
+        if not hasattr(self, 'DistributedNode_deleted'):
             self.DistributedNode_deleted = 1
             self.DistributedNode_deleted = 1
             if not self.isEmpty():
             if not self.isEmpty():
                 self.removeNode()
                 self.removeNode()
@@ -78,7 +74,7 @@ class DistributedNode(DistributedObject.DistributedObject, NodePath):
     ### setParent ###
     ### setParent ###
 
 
     def b_setParent(self, parentToken):
     def b_setParent(self, parentToken):
-        if type(parentToken) == str:
+        if isinstance(parentToken, str):
             self.setParentStr(parentToken)
             self.setParentStr(parentToken)
         else:
         else:
             self.setParent(parentToken)
             self.setParent(parentToken)
@@ -86,7 +82,7 @@ class DistributedNode(DistributedObject.DistributedObject, NodePath):
         self.d_setParent(parentToken)
         self.d_setParent(parentToken)
 
 
     def d_setParent(self, parentToken):
     def d_setParent(self, parentToken):
-        if type(parentToken) == str:
+        if isinstance(parentToken, str):
             self.sendUpdate("setParentStr", [parentToken])
             self.sendUpdate("setParentStr", [parentToken])
         else:
         else:
             self.sendUpdate("setParent", [parentToken])
             self.sendUpdate("setParent", [parentToken])

+ 3 - 5
direct/src/distributed/DistributedNodeAI.py

@@ -6,9 +6,7 @@ from . import GridParent
 class DistributedNodeAI(DistributedObjectAI.DistributedObjectAI, NodePath):
 class DistributedNodeAI(DistributedObjectAI.DistributedObjectAI, NodePath):
     def __init__(self, air, name=None):
     def __init__(self, air, name=None):
         # Be careful not to create multiple NodePath objects
         # Be careful not to create multiple NodePath objects
-        try:
-            self.DistributedNodeAI_initialized
-        except:
+        if not hasattr(self, 'DistributedNodeAI_initialized'):
             self.DistributedNodeAI_initialized = 1
             self.DistributedNodeAI_initialized = 1
             DistributedObjectAI.DistributedObjectAI.__init__(self, air)
             DistributedObjectAI.DistributedObjectAI.__init__(self, air)
             if name is None:
             if name is None:
@@ -47,14 +45,14 @@ class DistributedNodeAI(DistributedObjectAI.DistributedObjectAI, NodePath):
     ### setParent ###
     ### setParent ###
 
 
     def b_setParent(self, parentToken):
     def b_setParent(self, parentToken):
-        if type(parentToken) == str:
+        if isinstance(parentToken, str):
             self.setParentStr(parentToken)
             self.setParentStr(parentToken)
         else:
         else:
             self.setParent(parentToken)
             self.setParent(parentToken)
         self.d_setParent(parentToken)
         self.d_setParent(parentToken)
 
 
     def d_setParent(self, parentToken):
     def d_setParent(self, parentToken):
-        if type(parentToken) == type(''):
+        if isinstance(parentToken, str):
             self.sendUpdate("setParentStr", [parentToken])
             self.sendUpdate("setParentStr", [parentToken])
         else:
         else:
             self.sendUpdate("setParent", [parentToken])
             self.sendUpdate("setParent", [parentToken])

+ 3 - 5
direct/src/distributed/DistributedNodeUD.py

@@ -3,23 +3,21 @@ from .DistributedObjectUD import DistributedObjectUD
 class DistributedNodeUD(DistributedObjectUD):
 class DistributedNodeUD(DistributedObjectUD):
     def __init__(self, air, name=None):
     def __init__(self, air, name=None):
         # Be careful not to create multiple NodePath objects
         # Be careful not to create multiple NodePath objects
-        try:
-            self.DistributedNodeUD_initialized
-        except:
+        if not hasattr(self, 'DistributedNodeUD_initialized'):
             self.DistributedNodeUD_initialized = 1
             self.DistributedNodeUD_initialized = 1
             DistributedObjectUD.__init__(self, air)
             DistributedObjectUD.__init__(self, air)
             if name is None:
             if name is None:
                 name = self.__class__.__name__
                 name = self.__class__.__name__
 
 
     def b_setParent(self, parentToken):
     def b_setParent(self, parentToken):
-        if type(parentToken) == str:
+        if isinstance(parentToken, str):
             self.setParentStr(parentToken)
             self.setParentStr(parentToken)
         else:
         else:
             self.setParent(parentToken)
             self.setParent(parentToken)
         self.d_setParent(parentToken)
         self.d_setParent(parentToken)
 
 
     def d_setParent(self, parentToken):
     def d_setParent(self, parentToken):
-        if type(parentToken) == type(''):
+        if isinstance(parentToken, str):
             self.sendUpdate("setParentStr", [parentToken])
             self.sendUpdate("setParentStr", [parentToken])
         else:
         else:
             self.sendUpdate("setParent", [parentToken])
             self.sendUpdate("setParent", [parentToken])

+ 15 - 20
direct/src/distributed/DistributedObject.py

@@ -2,6 +2,7 @@
 
 
 from panda3d.core import *
 from panda3d.core import *
 from panda3d.direct import *
 from panda3d.direct import *
+from direct.showbase.MessengerGlobal import messenger
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.distributed.DistributedObjectBase import DistributedObjectBase
 from direct.distributed.DistributedObjectBase import DistributedObjectBase
 #from PyDatagram import PyDatagram
 #from PyDatagram import PyDatagram
@@ -43,9 +44,7 @@ class DistributedObject(DistributedObjectBase):
 
 
     def __init__(self, cr):
     def __init__(self, cr):
         assert self.notify.debugStateCall(self)
         assert self.notify.debugStateCall(self)
-        try:
-            self.DistributedObject_initialized
-        except:
+        if not hasattr(self, 'DistributedObject_initialized'):
             self.DistributedObject_initialized = 1
             self.DistributedObject_initialized = 1
             DistributedObjectBase.__init__(self, cr)
             DistributedObjectBase.__init__(self, cr)
 
 
@@ -96,7 +95,7 @@ class DistributedObject(DistributedObjectBase):
                     flags.append("cacheable")
                     flags.append("cacheable")
 
 
                 flagStr = ""
                 flagStr = ""
-                if len(flags):
+                if len(flags) > 0:
                     flagStr = " (%s)" % (" ".join(flags))
                     flagStr = " (%s)" % (" ".join(flags))
 
 
                 print("%sfrom DistributedObject doId:%s, parent:%s, zone:%s%s" % (
                 print("%sfrom DistributedObject doId:%s, parent:%s, zone:%s%s" % (
@@ -156,25 +155,25 @@ class DistributedObject(DistributedObjectBase):
             self._cachedData = self.cr.doDataCache.popCachedData(self.doId)
             self._cachedData = self.cr.doDataCache.popCachedData(self.doId)
 
 
     def setCachedData(self, name, data):
     def setCachedData(self, name, data):
-        assert type(name) == type('')
+        assert isinstance(name, str)
         # ownership of the data passes to the repository data cache
         # ownership of the data passes to the repository data cache
         self.cr.doDataCache.setCachedData(self.doId, name, data)
         self.cr.doDataCache.setCachedData(self.doId, name, data)
 
 
     def hasCachedData(self, name):
     def hasCachedData(self, name):
-        assert type(name) == type('')
+        assert isinstance(name, str)
         if not hasattr(self, '_cachedData'):
         if not hasattr(self, '_cachedData'):
             return False
             return False
         return name in self._cachedData
         return name in self._cachedData
 
 
     def getCachedData(self, name):
     def getCachedData(self, name):
-        assert type(name) == type('')
+        assert isinstance(name, str)
         # ownership of the data passes to the caller of this method
         # ownership of the data passes to the caller of this method
         data = self._cachedData[name]
         data = self._cachedData[name]
         del self._cachedData[name]
         del self._cachedData[name]
         return data
         return data
 
 
     def flushCachedData(self, name):
     def flushCachedData(self, name):
-        assert type(name) == type('')
+        assert isinstance(name, str)
         # call this to throw out cached data from a previous instantiation
         # call this to throw out cached data from a previous instantiation
         self._cachedData[name].flush()
         self._cachedData[name].flush()
 
 
@@ -278,14 +277,13 @@ class DistributedObject(DistributedObjectBase):
         Inheritors should redefine this to take appropriate action on disable
         Inheritors should redefine this to take appropriate action on disable
         """
         """
         assert self.notify.debug('disable(): %s' % (self.doId))
         assert self.notify.debug('disable(): %s' % (self.doId))
-        pass
 
 
     def isDisabled(self):
     def isDisabled(self):
         """
         """
         Returns true if the object has been disabled and/or deleted,
         Returns true if the object has been disabled and/or deleted,
         or if it is brand new and hasn't yet been generated.
         or if it is brand new and hasn't yet been generated.
         """
         """
-        return (self.activeState < ESGenerating)
+        return self.activeState < ESGenerating
 
 
     def isGenerated(self):
     def isGenerated(self):
         """
         """
@@ -293,17 +291,14 @@ class DistributedObject(DistributedObjectBase):
         and not yet disabled.
         and not yet disabled.
         """
         """
         assert self.notify.debugStateCall(self)
         assert self.notify.debugStateCall(self)
-        return (self.activeState == ESGenerated)
+        return self.activeState == ESGenerated
 
 
     def delete(self):
     def delete(self):
         """
         """
         Inheritors should redefine this to take appropriate action on delete
         Inheritors should redefine this to take appropriate action on delete
         """
         """
         assert self.notify.debug('delete(): %s' % (self.doId))
         assert self.notify.debug('delete(): %s' % (self.doId))
-        try:
-            self.DistributedObject_deleted
-        except:
-            self.DistributedObject_deleted = 1
+        self.DistributedObject_deleted = 1
 
 
     def generate(self):
     def generate(self):
         """
         """
@@ -374,10 +369,10 @@ class DistributedObject(DistributedObjectBase):
         self.cr.sendDeleteMsg(self.doId)
         self.cr.sendDeleteMsg(self.doId)
 
 
     def taskName(self, taskString):
     def taskName(self, taskString):
-        return ("%s-%s" % (taskString, self.doId))
+        return "%s-%s" % (taskString, self.doId)
 
 
     def uniqueName(self, idString):
     def uniqueName(self, idString):
-        return ("%s-%s" % (idString, self.doId))
+        return "%s-%s" % (idString, self.doId)
 
 
     def getCallbackContext(self, callback, extraArgs = []):
     def getCallbackContext(self, callback, extraArgs = []):
         # Some objects implement a back-and-forth handshake operation
         # Some objects implement a back-and-forth handshake operation
@@ -429,7 +424,7 @@ class DistributedObject(DistributedObjectBase):
         if tuple:
         if tuple:
             callback, extraArgs = tuple
             callback, extraArgs = tuple
             completeArgs = args + extraArgs
             completeArgs = args + extraArgs
-            if callback != None:
+            if callback is not None:
                 callback(*completeArgs)
                 callback(*completeArgs)
             del self.__callbacks[context]
             del self.__callbacks[context]
         else:
         else:
@@ -470,9 +465,9 @@ class DistributedObject(DistributedObjectBase):
         # doneBarrier() twice, or we have not received a barrier
         # doneBarrier() twice, or we have not received a barrier
         # context from the AI.  I think in either case it's ok to
         # context from the AI.  I think in either case it's ok to
         # silently ignore the error.
         # silently ignore the error.
-        if self.__barrierContext != None:
+        if self.__barrierContext is not None:
             context, aiName = self.__barrierContext
             context, aiName = self.__barrierContext
-            if name == None or name == aiName:
+            if name is None or name == aiName:
                 assert self.notify.debug('doneBarrier(%s, %s)' % (context, aiName))
                 assert self.notify.debug('doneBarrier(%s, %s)' % (context, aiName))
                 self.sendUpdate("setBarrierReady", [context])
                 self.sendUpdate("setBarrierReady", [context])
                 self.__barrierContext = None
                 self.__barrierContext = None

+ 27 - 32
direct/src/distributed/DistributedObjectAI.py

@@ -2,6 +2,7 @@
 
 
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.distributed.DistributedObjectBase import DistributedObjectBase
 from direct.distributed.DistributedObjectBase import DistributedObjectBase
+from direct.showbase.MessengerGlobal import messenger
 from direct.showbase import PythonUtil
 from direct.showbase import PythonUtil
 from panda3d.core import *
 from panda3d.core import *
 from panda3d.direct import *
 from panda3d.direct import *
@@ -13,9 +14,7 @@ class DistributedObjectAI(DistributedObjectBase):
     QuietZone = 1
     QuietZone = 1
 
 
     def __init__(self, air):
     def __init__(self, air):
-        try:
-            self.DistributedObjectAI_initialized
-        except:
+        if not hasattr(self, 'DistributedObjectAI_initialized'):
             self.DistributedObjectAI_initialized = 1
             self.DistributedObjectAI_initialized = 1
             DistributedObjectBase.__init__(self, air)
             DistributedObjectBase.__init__(self, air)
 
 
@@ -66,11 +65,11 @@ class DistributedObjectAI(DistributedObjectBase):
                 flags = []
                 flags = []
                 if self.__generated:
                 if self.__generated:
                     flags.append("generated")
                     flags.append("generated")
-                if self.air == None:
+                if self.air is None:
                     flags.append("deleted")
                     flags.append("deleted")
 
 
                 flagStr = ""
                 flagStr = ""
-                if len(flags):
+                if len(flags) > 0:
                     flagStr = " (%s)" % (" ".join(flags))
                     flagStr = " (%s)" % (" ".join(flags))
 
 
                 print("%sfrom DistributedObject doId:%s, parent:%s, zone:%s%s" % (
                 print("%sfrom DistributedObject doId:%s, parent:%s, zone:%s%s" % (
@@ -119,24 +118,23 @@ class DistributedObjectAI(DistributedObjectBase):
                 # self.doId may not exist.  The __dict__ syntax works around that.
                 # self.doId may not exist.  The __dict__ syntax works around that.
                 assert self.notify.debug('delete(): %s' % (self.__dict__.get("doId")))
                 assert self.notify.debug('delete(): %s' % (self.__dict__.get("doId")))
 
 
-                if not self._DOAI_requestedDelete:
-                    # this logs every delete that was not requested by us.
-                    # TODO: this currently prints warnings for deletes of objects
-                    # that we did not create. We need to add a 'locally created'
-                    # flag to every object to filter these out.
-                    """
-                    DistributedObjectAI.notify.warning(
-                        'delete() called but requestDelete never called for %s: %s'
-                        % (self.__dict__.get('doId'), self.__class__.__name__))
-                        """
-                    """
-                    # print a stack trace so we can detect whether this is the
-                    # result of a network msg.
-                    # this is slow.
-                    from direct.showbase.PythonUtil import StackTrace
-                    DistributedObjectAI.notify.warning(
-                        'stack trace: %s' % StackTrace())
-                        """
+                #if not self._DOAI_requestedDelete:
+                #    # this logs every delete that was not requested by us.
+                #    # TODO: this currently prints warnings for deletes of objects
+                #    # that we did not create. We need to add a 'locally created'
+                #    # flag to every object to filter these out.
+                #
+                #    DistributedObjectAI.notify.warning(
+                #        'delete() called but requestDelete never called for %s: %s'
+                #        % (self.__dict__.get('doId'), self.__class__.__name__))
+                #
+                #    # print a stack trace so we can detect whether this is the
+                #    # result of a network msg.
+                #    # this is slow.
+                #    from direct.showbase.PythonUtil import StackTrace
+                #    DistributedObjectAI.notify.warning(
+                #        'stack trace: %s' % StackTrace())
+
                 self._DOAI_requestedDelete = False
                 self._DOAI_requestedDelete = False
 
 
                 self.releaseZoneData()
                 self.releaseZoneData()
@@ -167,7 +165,7 @@ class DistributedObjectAI(DistributedObjectBase):
         Returns true if the object has been deleted,
         Returns true if the object has been deleted,
         or if it is brand new and hasnt yet been generated.
         or if it is brand new and hasnt yet been generated.
         """
         """
-        return self.air == None
+        return self.air is None
 
 
     def isGenerated(self):
     def isGenerated(self):
         """
         """
@@ -195,7 +193,6 @@ class DistributedObjectAI(DistributedObjectBase):
         Called after the object has been generated and all
         Called after the object has been generated and all
         of its required fields filled in. Overwrite when needed.
         of its required fields filled in. Overwrite when needed.
         """
         """
-        pass
 
 
     def b_setLocation(self, parentId, zoneId):
     def b_setLocation(self, parentId, zoneId):
         self.d_setLocation(parentId, zoneId)
         self.d_setLocation(parentId, zoneId)
@@ -206,14 +203,13 @@ class DistributedObjectAI(DistributedObjectBase):
 
 
     def setLocation(self, parentId, zoneId):
     def setLocation(self, parentId, zoneId):
         # Prevent Duplicate SetLocations for being Called
         # Prevent Duplicate SetLocations for being Called
-        if (self.parentId == parentId) and (self.zoneId == zoneId):
+        if self.parentId == parentId and self.zoneId == zoneId:
             return
             return
 
 
         oldParentId = self.parentId
         oldParentId = self.parentId
         oldZoneId = self.zoneId
         oldZoneId = self.zoneId
         self.air.storeObjectLocation(self, parentId, zoneId)
         self.air.storeObjectLocation(self, parentId, zoneId)
-        if ((oldParentId != parentId) or
-            (oldZoneId != zoneId)):
+        if oldParentId != parentId or oldZoneId != zoneId:
             self.releaseZoneData()
             self.releaseZoneData()
             messenger.send(self.getZoneChangeEvent(), [zoneId, oldZoneId])
             messenger.send(self.getZoneChangeEvent(), [zoneId, oldZoneId])
             # if we are not going into the quiet zone, send a 'logical' zone
             # if we are not going into the quiet zone, send a 'logical' zone
@@ -476,10 +472,10 @@ class DistributedObjectAI(DistributedObjectBase):
         self._DOAI_requestedDelete = True
         self._DOAI_requestedDelete = True
 
 
     def taskName(self, taskString):
     def taskName(self, taskString):
-        return ("%s-%s" % (taskString, self.doId))
+        return "%s-%s" % (taskString, self.doId)
 
 
     def uniqueName(self, idString):
     def uniqueName(self, idString):
-        return ("%s-%s" % (idString, self.doId))
+        return "%s-%s" % (idString, self.doId)
 
 
     def validate(self, avId, bool, msg):
     def validate(self, avId, bool, msg):
         if not bool:
         if not bool:
@@ -542,7 +538,7 @@ class DistributedObjectAI(DistributedObjectBase):
         avId = self.air.getAvatarIdFromSender()
         avId = self.air.getAvatarIdFromSender()
         assert self.notify.debug('setBarrierReady(%s, %s)' % (context, avId))
         assert self.notify.debug('setBarrierReady(%s, %s)' % (context, avId))
         barrier = self.__barriers.get(context)
         barrier = self.__barriers.get(context)
-        if barrier == None:
+        if barrier is None:
             # This may be None if a client was slow and missed an
             # This may be None if a client was slow and missed an
             # earlier timeout.  Too bad.
             # earlier timeout.  Too bad.
             return
             return
@@ -569,7 +565,6 @@ class DistributedObjectAI(DistributedObjectBase):
 
 
     def _retrieveCachedData(self):
     def _retrieveCachedData(self):
         """ This is a no-op on the AI. """
         """ This is a no-op on the AI. """
-        pass
 
 
     def setAI(self, aiChannel):
     def setAI(self, aiChannel):
         self.air.setAI(self.doId, aiChannel)
         self.air.setAI(self.doId, aiChannel)

+ 1 - 8
direct/src/distributed/DistributedObjectBase.py

@@ -49,7 +49,6 @@ class DistributedObjectBase(DirectObject):
         """
         """
         assert self.notify.debugCall()
         assert self.notify.debugCall()
         # Inheritors should override
         # Inheritors should override
-        pass
 
 
     def handleChildArriveZone(self, childObj, zoneId):
     def handleChildArriveZone(self, childObj, zoneId):
         """
         """
@@ -60,7 +59,6 @@ class DistributedObjectBase(DirectObject):
         """
         """
         assert self.notify.debugCall()
         assert self.notify.debugCall()
         # Inheritors should override
         # Inheritors should override
-        pass
 
 
     def handleChildLeave(self, childObj, zoneId):
     def handleChildLeave(self, childObj, zoneId):
         """
         """
@@ -69,7 +67,6 @@ class DistributedObjectBase(DirectObject):
         """
         """
         assert self.notify.debugCall()
         assert self.notify.debugCall()
         # Inheritors should override
         # Inheritors should override
-        pass
 
 
     def handleChildLeaveZone(self, childObj, zoneId):
     def handleChildLeaveZone(self, childObj, zoneId):
         """
         """
@@ -79,12 +76,10 @@ class DistributedObjectBase(DirectObject):
         """
         """
         assert self.notify.debugCall()
         assert self.notify.debugCall()
         # Inheritors should override
         # Inheritors should override
-        pass
 
 
     def handleQueryObjectChildrenLocalDone(self, context):
     def handleQueryObjectChildrenLocalDone(self, context):
         assert self.notify.debugCall()
         assert self.notify.debugCall()
         # Inheritors should override
         # Inheritors should override
-        pass
 
 
     def getParentObj(self):
     def getParentObj(self):
         if self.parentId is None:
         if self.parentId is None:
@@ -92,12 +87,10 @@ class DistributedObjectBase(DirectObject):
         return self.cr.doId2do.get(self.parentId)
         return self.cr.doId2do.get(self.parentId)
 
 
     def hasParentingRules(self):
     def hasParentingRules(self):
-        return self.dclass.getFieldByName('setParentingRules') != None
+        return self.dclass.getFieldByName('setParentingRules') is not None
 
 
     def delete(self):
     def delete(self):
         """
         """
         Override this to handle cleanup right before this object
         Override this to handle cleanup right before this object
         gets deleted.
         gets deleted.
         """
         """
-
-        pass

+ 0 - 1
direct/src/distributed/DistributedObjectGlobal.py

@@ -21,4 +21,3 @@ class DistributedObjectGlobal(DistributedObject):
         DistributedObject.__init__(self, cr)
         DistributedObject.__init__(self, cr)
         self.parentId = 0
         self.parentId = 0
         self.zoneId = 0
         self.zoneId = 0
-

+ 6 - 7
direct/src/distributed/DistributedObjectGlobalAI.py

@@ -18,15 +18,14 @@ class DistributedObjectGlobalAI(DistributedObjectAI):
             if not self.doNotListenToChannel:
             if not self.doNotListenToChannel:
                 self.air.registerForChannel(self.doId)
                 self.air.registerForChannel(self.doId)
         except AttributeError:
         except AttributeError:
-                self.air.registerForChannel(self.doId)
+            self.air.registerForChannel(self.doId)
         return False
         return False
 
 
     def delete(self):
     def delete(self):
-       DistributedObjectAI.delete(self)
-       try:
+        DistributedObjectAI.delete(self)
+        try:
             if not self.doNotListenToChannel:
             if not self.doNotListenToChannel:
-               self.air.unregisterForChannel(self.doId)
-       except AttributeError:
-           self.air.unregisterForChannel(self.doId)
+                self.air.unregisterForChannel(self.doId)
+        except AttributeError:
+            self.air.unregisterForChannel(self.doId)
         ## self.air.removeDOFromTables(self)
         ## self.air.removeDOFromTables(self)
-

+ 3 - 3
direct/src/distributed/DistributedObjectGlobalUD.py

@@ -1,5 +1,4 @@
-
-
+from panda3d.core import ConfigVariableInt
 from .DistributedObjectUD import DistributedObjectUD
 from .DistributedObjectUD import DistributedObjectUD
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.directnotify.DirectNotifyGlobal import directNotify
 
 
@@ -25,7 +24,8 @@ class DistributedObjectGlobalUD(DistributedObjectUD):
         DistributedObjectUD.delete(self)
         DistributedObjectUD.delete(self)
 
 
     def execCommand(self, command, mwMgrId, avId, zoneId):
     def execCommand(self, command, mwMgrId, avId, zoneId):
-        text = str(self.__execMessage(command))[:config.GetInt("ai-debug-length",300)]
+        length = ConfigVariableInt("ai-debug-length", 300)
+        text = str(self.__execMessage(command))[:length.value]
         self.notify.info(text)
         self.notify.info(text)
 
 
     def __execMessage(self, message):
     def __execMessage(self, message):

+ 8 - 11
direct/src/distributed/DistributedObjectOV.py

@@ -1,6 +1,7 @@
 
 
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.distributed.DistributedObjectBase import DistributedObjectBase
 from direct.distributed.DistributedObjectBase import DistributedObjectBase
+from direct.showbase.MessengerGlobal import messenger
 
 
 #from PyDatagram import PyDatagram
 #from PyDatagram import PyDatagram
 #from PyDatagramIterator import PyDatagramIterator
 #from PyDatagramIterator import PyDatagramIterator
@@ -23,9 +24,7 @@ class DistributedObjectOV(DistributedObjectBase):
 
 
     def __init__(self, cr):
     def __init__(self, cr):
         assert self.notify.debugStateCall(self)
         assert self.notify.debugStateCall(self)
-        try:
-            self.DistributedObjectOV_initialized
-        except:
+        if not hasattr(self, 'DistributedObjectOV_initialized'):
             self.DistributedObjectOV_initialized = 1
             self.DistributedObjectOV_initialized = 1
             DistributedObjectBase.__init__(self, cr)
             DistributedObjectBase.__init__(self, cr)
 
 
@@ -51,7 +50,7 @@ class DistributedObjectOV(DistributedObjectBase):
                     flags.append("disabled")
                     flags.append("disabled")
 
 
                 flagStr = ""
                 flagStr = ""
-                if len(flags):
+                if len(flags) > 0:
                     flagStr = " (%s)" % (" ".join(flags))
                     flagStr = " (%s)" % (" ".join(flags))
 
 
                 print("%sfrom DistributedObjectOV doId:%s, parent:%s, zone:%s%s" % (
                 print("%sfrom DistributedObjectOV doId:%s, parent:%s, zone:%s%s" % (
@@ -103,7 +102,7 @@ class DistributedObjectOV(DistributedObjectBase):
         Returns true if the object has been disabled and/or deleted,
         Returns true if the object has been disabled and/or deleted,
         or if it is brand new and hasn't yet been generated.
         or if it is brand new and hasn't yet been generated.
         """
         """
-        return (self.activeState < ESGenerating)
+        return self.activeState < ESGenerating
 
 
     def isGenerated(self):
     def isGenerated(self):
         """
         """
@@ -111,16 +110,14 @@ class DistributedObjectOV(DistributedObjectBase):
         and not yet disabled.
         and not yet disabled.
         """
         """
         assert self.notify.debugStateCall(self)
         assert self.notify.debugStateCall(self)
-        return (self.activeState == ESGenerated)
+        return self.activeState == ESGenerated
 
 
     def delete(self):
     def delete(self):
         """
         """
         Inheritors should redefine this to take appropriate action on delete
         Inheritors should redefine this to take appropriate action on delete
         """
         """
         assert self.notify.debug('delete(): %s' % (self.doId))
         assert self.notify.debug('delete(): %s' % (self.doId))
-        try:
-            self.DistributedObjectOV_deleted
-        except:
+        if not hasattr(self, 'DistributedObjectOV_deleted'):
             self.DistributedObjectOV_deleted = 1
             self.DistributedObjectOV_deleted = 1
             self.cr = None
             self.cr = None
             self.dclass = None
             self.dclass = None
@@ -186,7 +183,7 @@ class DistributedObjectOV(DistributedObjectBase):
             self.notify.warning("sendUpdate failed, because self.cr is not set")
             self.notify.warning("sendUpdate failed, because self.cr is not set")
 
 
     def taskName(self, taskString):
     def taskName(self, taskString):
-        return ('%s-%s-OV' % (taskString, self.getDoId()))
+        return '%s-%s-OV' % (taskString, self.getDoId())
 
 
     def uniqueName(self, idString):
     def uniqueName(self, idString):
-        return ('%s-%s-OV' % (idString, self.getDoId()))
+        return '%s-%s-OV' % (idString, self.getDoId())

+ 25 - 27
direct/src/distributed/DistributedObjectUD.py

@@ -2,6 +2,7 @@
 
 
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.distributed.DistributedObjectBase import DistributedObjectBase
 from direct.distributed.DistributedObjectBase import DistributedObjectBase
+from direct.showbase.MessengerGlobal import messenger
 from direct.showbase import PythonUtil
 from direct.showbase import PythonUtil
 from panda3d.core import *
 from panda3d.core import *
 from panda3d.direct import *
 from panda3d.direct import *
@@ -13,9 +14,7 @@ class DistributedObjectUD(DistributedObjectBase):
     QuietZone = 1
     QuietZone = 1
 
 
     def __init__(self, air):
     def __init__(self, air):
-        try:
-            self.DistributedObjectUD_initialized
-        except:
+        if not hasattr(self, 'DistributedObjectUD_initialized'):
             self.DistributedObjectUD_initialized = 1
             self.DistributedObjectUD_initialized = 1
             DistributedObjectBase.__init__(self, air)
             DistributedObjectBase.__init__(self, air)
 
 
@@ -64,11 +63,11 @@ class DistributedObjectUD(DistributedObjectBase):
                 flags = []
                 flags = []
                 if self.__generated:
                 if self.__generated:
                     flags.append("generated")
                     flags.append("generated")
-                if self.air == None:
+                if self.air is None:
                     flags.append("deleted")
                     flags.append("deleted")
 
 
                 flagStr = ""
                 flagStr = ""
-                if len(flags):
+                if len(flags) > 0:
                     flagStr = " (%s)" % (" ".join(flags))
                     flagStr = " (%s)" % (" ".join(flags))
 
 
                 print("%sfrom DistributedObject doId:%s, parent:%s, zone:%s%s" % (
                 print("%sfrom DistributedObject doId:%s, parent:%s, zone:%s%s" % (
@@ -103,24 +102,23 @@ class DistributedObjectUD(DistributedObjectBase):
                 # self.doId may not exist.  The __dict__ syntax works around that.
                 # self.doId may not exist.  The __dict__ syntax works around that.
                 assert self.notify.debug('delete(): %s' % (self.__dict__.get("doId")))
                 assert self.notify.debug('delete(): %s' % (self.__dict__.get("doId")))
 
 
-                if not self._DOUD_requestedDelete:
-                    # this logs every delete that was not requested by us.
-                    # TODO: this currently prints warnings for deletes of objects
-                    # that we did not create. We need to add a 'locally created'
-                    # flag to every object to filter these out.
-                    """
-                    DistributedObjectUD.notify.warning(
-                        'delete() called but requestDelete never called for %s: %s'
-                        % (self.__dict__.get('doId'), self.__class__.__name__))
-                        """
-                    """
-                    # print a stack trace so we can detect whether this is the
-                    # result of a network msg.
-                    # this is slow.
-                    from direct.showbase.PythonUtil import StackTrace
-                    DistributedObjectUD.notify.warning(
-                        'stack trace: %s' % StackTrace())
-                        """
+                #if not self._DOUD_requestedDelete:
+                #    # this logs every delete that was not requested by us.
+                #    # TODO: this currently prints warnings for deletes of objects
+                #    # that we did not create. We need to add a 'locally created'
+                #    # flag to every object to filter these out.
+                #
+                #    DistributedObjectUD.notify.warning(
+                #        'delete() called but requestDelete never called for %s: %s'
+                #        % (self.__dict__.get('doId'), self.__class__.__name__))
+                #
+                #    # print a stack trace so we can detect whether this is the
+                #    # result of a network msg.
+                #    # this is slow.
+                #    from direct.showbase.PythonUtil import StackTrace
+                #    DistributedObjectUD.notify.warning(
+                #        'stack trace: %s' % StackTrace())
+
                 self._DOUD_requestedDelete = False
                 self._DOUD_requestedDelete = False
 
 
                 # Clean up all the pending barriers.
                 # Clean up all the pending barriers.
@@ -143,7 +141,7 @@ class DistributedObjectUD(DistributedObjectBase):
         Returns true if the object has been deleted,
         Returns true if the object has been deleted,
         or if it is brand new and hasnt yet been generated.
         or if it is brand new and hasnt yet been generated.
         """
         """
-        return self.air == None
+        return self.air is None
 
 
     def isGenerated(self):
     def isGenerated(self):
         """
         """
@@ -409,10 +407,10 @@ class DistributedObjectUD(DistributedObjectBase):
         self._DOUD_requestedDelete = True
         self._DOUD_requestedDelete = True
 
 
     def taskName(self, taskString):
     def taskName(self, taskString):
-        return ("%s-%s" % (taskString, self.doId))
+        return "%s-%s" % (taskString, self.doId)
 
 
     def uniqueName(self, idString):
     def uniqueName(self, idString):
-        return ("%s-%s" % (idString, self.doId))
+        return "%s-%s" % (idString, self.doId)
 
 
     def validate(self, avId, bool, msg):
     def validate(self, avId, bool, msg):
         if not bool:
         if not bool:
@@ -475,7 +473,7 @@ class DistributedObjectUD(DistributedObjectBase):
         avId = self.air.getAvatarIdFromSender()
         avId = self.air.getAvatarIdFromSender()
         assert self.notify.debug('setBarrierReady(%s, %s)' % (context, avId))
         assert self.notify.debug('setBarrierReady(%s, %s)' % (context, avId))
         barrier = self.__barriers.get(context)
         barrier = self.__barriers.get(context)
-        if barrier == None:
+        if barrier is None:
             # This may be None if a client was slow and missed an
             # This may be None if a client was slow and missed an
             # earlier timeout.  Too bad.
             # earlier timeout.  Too bad.
             return
             return

+ 12 - 12
direct/src/distributed/DistributedSmoothNode.py

@@ -6,7 +6,9 @@ from .ClockDelta import *
 from . import DistributedNode
 from . import DistributedNode
 from . import DistributedSmoothNodeBase
 from . import DistributedSmoothNodeBase
 from direct.task.Task import cont
 from direct.task.Task import cont
+from direct.task.TaskManagerGlobal import taskMgr
 from direct.showbase import DConfig as config
 from direct.showbase import DConfig as config
+from direct.showbase.PythonUtil import report
 
 
 # This number defines our tolerance for out-of-sync telemetry packets.
 # This number defines our tolerance for out-of-sync telemetry packets.
 # If a packet appears to have originated from more than MaxFuture
 # If a packet appears to have originated from more than MaxFuture
@@ -62,9 +64,7 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
     """
     """
 
 
     def __init__(self, cr):
     def __init__(self, cr):
-        try:
-            self.DistributedSmoothNode_initialized
-        except:
+        if not hasattr(self, 'DistributedSmoothNode_initialized'):
             self.DistributedSmoothNode_initialized = 1
             self.DistributedSmoothNode_initialized = 1
             DistributedNode.DistributedNode.__init__(self, cr)
             DistributedNode.DistributedNode.__init__(self, cr)
             DistributedSmoothNodeBase.DistributedSmoothNodeBase.__init__(self)
             DistributedSmoothNodeBase.DistributedSmoothNodeBase.__init__(self)
@@ -181,22 +181,22 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
         self.smoother.setPhonyTimestamp()
         self.smoother.setPhonyTimestamp()
         self.smoother.markPosition()
         self.smoother.markPosition()
 
 
-    def _checkResume(self,timestamp):
+    def _checkResume(self, timestamp):
         """
         """
         Determine if we were previously stopped and now need to
         Determine if we were previously stopped and now need to
         resume movement by making sure any old stored positions
         resume movement by making sure any old stored positions
         reflect the node's current position
         reflect the node's current position
         """
         """
-        if (self.stopped):
+        if self.stopped:
             currTime = globalClock.getFrameTime()
             currTime = globalClock.getFrameTime()
             now = currTime - self.smoother.getExpectedBroadcastPeriod()
             now = currTime - self.smoother.getExpectedBroadcastPeriod()
             last = self.smoother.getMostRecentTimestamp()
             last = self.smoother.getMostRecentTimestamp()
-            if (now > last):
+            if now > last:
                 # only set a new timestamp postion if we still have
                 # only set a new timestamp postion if we still have
                 # a position being smoothed to (so we don't interrupt
                 # a position being smoothed to (so we don't interrupt
                 # any current smoothing and only do this if the object
                 # any current smoothing and only do this if the object
                 # is actually locally stopped)
                 # is actually locally stopped)
-                if (timestamp == None):
+                if timestamp is None:
                     # no timestamp, use current time
                     # no timestamp, use current time
                     local = 0.0
                     local = 0.0
                 else:
                 else:
@@ -302,7 +302,7 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
         self.smoother.setR(r)
         self.smoother.setR(r)
     @report(types = ['args'], dConfigParam = 'smoothnode')
     @report(types = ['args'], dConfigParam = 'smoothnode')
     def setComponentL(self, l):
     def setComponentL(self, l):
-        if (l != self.zoneId):
+        if l != self.zoneId:
             # only perform set location if location is different
             # only perform set location if location is different
             self.setLocation(self.parentId,l)
             self.setLocation(self.parentId,l)
     @report(types = ['args'], dConfigParam = 'smoothnode')
     @report(types = ['args'], dConfigParam = 'smoothnode')
@@ -360,7 +360,7 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
             howFarFuture = local - now
             howFarFuture = local - now
             if howFarFuture - chug >= MaxFuture:
             if howFarFuture - chug >= MaxFuture:
                 # Too far off; advise the other client of our clock information.
                 # Too far off; advise the other client of our clock information.
-                if globalClockDelta.getUncertainty() != None and \
+                if globalClockDelta.getUncertainty() is not None and \
                    realTime - self.lastSuggestResync >= MinSuggestResync and \
                    realTime - self.lastSuggestResync >= MinSuggestResync and \
                    hasattr(self.cr, 'localAvatarDoId'):
                    hasattr(self.cr, 'localAvatarDoId'):
                     self.lastSuggestResync = realTime
                     self.lastSuggestResync = realTime
@@ -457,9 +457,9 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
         result = self.peerToPeerResync(
         result = self.peerToPeerResync(
             avId, timestampA, serverTime, uncertainty)
             avId, timestampA, serverTime, uncertainty)
         if result >= 0 and \
         if result >= 0 and \
-           globalClockDelta.getUncertainty() != None:
+           globalClockDelta.getUncertainty() is not None:
             other = self.cr.doId2do.get(avId)
             other = self.cr.doId2do.get(avId)
-            if (not other):
+            if not other:
                 assert self.notify.info(
                 assert self.notify.info(
                     "Warning: couldn't find the avatar %d" % (avId))
                     "Warning: couldn't find the avatar %d" % (avId))
             elif hasattr(other, "d_returnResync") and \
             elif hasattr(other, "d_returnResync") and \
@@ -498,7 +498,7 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
         # If we didn't get anything useful from the other client,
         # If we didn't get anything useful from the other client,
         # maybe our clock is just completely hosed.  Go ask the AI.
         # maybe our clock is just completely hosed.  Go ask the AI.
         if not gotSync:
         if not gotSync:
-            if self.cr.timeManager != None:
+            if self.cr.timeManager is not None:
                 self.cr.timeManager.synchronize("suggested by %d" % (avId))
                 self.cr.timeManager.synchronize("suggested by %d" % (avId))
 
 
         return gotSync
         return gotSync

+ 1 - 2
direct/src/distributed/DistributedSmoothNodeAI.py

@@ -98,11 +98,10 @@ class DistributedSmoothNodeAI(DistributedNodeAI.DistributedNodeAI,
     def getComponentR(self):
     def getComponentR(self):
         return self.getR()
         return self.getR()
     def getComponentL(self):
     def getComponentL(self):
-        if (self.zoneId):
+        if self.zoneId:
             return self.zoneId
             return self.zoneId
         else:
         else:
             # we can't send None over the wire which self.zoneId can sometimes be
             # we can't send None over the wire which self.zoneId can sometimes be
             return 0
             return 0
     def getComponentT(self):
     def getComponentT(self):
         return 0
         return 0
-

+ 3 - 3
direct/src/distributed/DistributedSmoothNodeBase.py

@@ -2,6 +2,7 @@
 
 
 from .ClockDelta import *
 from .ClockDelta import *
 from direct.task import Task
 from direct.task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 from direct.showbase.PythonUtil import randFloat, Enum
 from direct.showbase.PythonUtil import randFloat, Enum
 from panda3d.direct import CDistributedSmoothNodeBase
 from panda3d.direct import CDistributedSmoothNodeBase
 
 
@@ -58,13 +59,13 @@ class DistributedSmoothNodeBase:
         self.d_broadcastPosHpr = None
         self.d_broadcastPosHpr = None
 
 
     def posHprBroadcastStarted(self):
     def posHprBroadcastStarted(self):
-        return self.d_broadcastPosHpr != None
+        return self.d_broadcastPosHpr is not None
 
 
     def wantSmoothPosBroadcastTask(self):
     def wantSmoothPosBroadcastTask(self):
         return True
         return True
 
 
     def startPosHprBroadcast(self, period=.2, stagger=0, type=None):
     def startPosHprBroadcast(self, period=.2, stagger=0, type=None):
-        if self.cnode == None:
+        if self.cnode is None:
             self.initializeCnode()
             self.initializeCnode()
 
 
         BT = DistributedSmoothNodeBase.BroadcastTypes
         BT = DistributedSmoothNodeBase.BroadcastTypes
@@ -117,4 +118,3 @@ class DistributedSmoothNodeBase:
         if self.d_broadcastPosHpr is None:
         if self.d_broadcastPosHpr is None:
             self.cnode.initialize(self, self.dclass, self.doId)
             self.cnode.initialize(self, self.dclass, self.doId)
         self.cnode.sendEverything()
         self.cnode.sendEverything()
-

+ 9 - 10
direct/src/distributed/DoCollectionManager.py

@@ -113,7 +113,7 @@ class DoCollectionManager:
             return 1
             return 1
         if dist2 is None:
         if dist2 is None:
             return -1
             return -1
-        if (dist1 < dist2):
+        if dist1 < dist2:
             return -1
             return -1
         return 1
         return 1
 
 
@@ -270,7 +270,7 @@ class DoCollectionManager:
 
 
     def deleteDistributedObjects(self):
     def deleteDistributedObjects(self):
         # Get rid of all the distributed objects
         # Get rid of all the distributed objects
-        for doId, do in list(self.doId2do.items()):
+        for do in list(self.doId2do.values()):
             self.deleteDistObject(do)
             self.deleteDistObject(do)
 
 
         # Get rid of everything that manages distributed objects
         # Get rid of everything that manages distributed objects
@@ -314,14 +314,14 @@ class DoCollectionManager:
     def storeObjectLocation(self, object, parentId, zoneId):
     def storeObjectLocation(self, object, parentId, zoneId):
         oldParentId = object.parentId
         oldParentId = object.parentId
         oldZoneId = object.zoneId
         oldZoneId = object.zoneId
-        if (oldParentId != parentId):
+        if oldParentId != parentId:
             # notify any existing parent that we're moving away
             # notify any existing parent that we're moving away
             oldParentObj = self.doId2do.get(oldParentId)
             oldParentObj = self.doId2do.get(oldParentId)
             if oldParentObj is not None:
             if oldParentObj is not None:
                 oldParentObj.handleChildLeave(object, oldZoneId)
                 oldParentObj.handleChildLeave(object, oldZoneId)
             self.deleteObjectLocation(object, oldParentId, oldZoneId)
             self.deleteObjectLocation(object, oldParentId, oldZoneId)
 
 
-        elif (oldZoneId != zoneId):
+        elif oldZoneId != zoneId:
             # Remove old location
             # Remove old location
             oldParentObj = self.doId2do.get(oldParentId)
             oldParentObj = self.doId2do.get(oldParentId)
             if oldParentObj is not None:
             if oldParentObj is not None:
@@ -331,8 +331,7 @@ class DoCollectionManager:
             # object is already at that parent and zone
             # object is already at that parent and zone
             return
             return
 
 
-        if ((parentId is None) or (zoneId is None) or
-            (parentId == zoneId == 0)):
+        if parentId is None or zoneId is None or (parentId == zoneId == 0):
             # Do not store null values
             # Do not store null values
             object.parentId = None
             object.parentId = None
             object.zoneId = None
             object.zoneId = None
@@ -418,10 +417,10 @@ class DoCollectionManager:
         #assert do.doId in self.doId2do
         #assert do.doId in self.doId2do
         location = do.getLocation()
         location = do.getLocation()
         if location:
         if location:
-           oldParentId, oldZoneId = location
-           oldParentObj = self.doId2do.get(oldParentId)
-           if oldParentObj:
-               oldParentObj.handleChildLeave(do, oldZoneId)
+            oldParentId, oldZoneId = location
+            oldParentObj = self.doId2do.get(oldParentId)
+            if oldParentObj:
+                oldParentObj.handleChildLeave(do, oldZoneId)
         self.deleteObjectLocation(do, do.parentId, do.zoneId)
         self.deleteObjectLocation(do, do.parentId, do.zoneId)
         ## location = do.getLocation()
         ## location = do.getLocation()
         ## if location is not None:
         ## if location is not None:

+ 2 - 2
direct/src/distributed/DoHierarchy.py

@@ -13,7 +13,7 @@ class DoHierarchy:
         self._allDoIds = set()
         self._allDoIds = set()
 
 
     def isEmpty(self):
     def isEmpty(self):
-        assert ((len(self._table) == 0) == (len(self._allDoIds) == 0))
+        assert (len(self._table) == 0) == (len(self._allDoIds) == 0)
         return len(self._table) == 0 and len(self._allDoIds) == 0
         return len(self._table) == 0 and len(self._allDoIds) == 0
 
 
     def __len__(self):
     def __len__(self):
@@ -77,7 +77,7 @@ class DoHierarchy:
                 'deleteObjectLocation(%s %s) not in _allDoIds; duplicate delete()? or invalid previous location on a new object?' % (
                 'deleteObjectLocation(%s %s) not in _allDoIds; duplicate delete()? or invalid previous location on a new object?' % (
                 do.__class__.__name__, do.doId))
                 do.__class__.__name__, do.doId))
         # jbutler: temp hack to get by the assert, this will be fixed soon
         # jbutler: temp hack to get by the assert, this will be fixed soon
-        if (doId not in self._allDoIds):
+        if doId not in self._allDoIds:
             return
             return
         parentZoneDict = self._table.get(parentId)
         parentZoneDict = self._table.get(parentId)
         if parentZoneDict is not None:
         if parentZoneDict is not None:

+ 4 - 2
direct/src/distributed/DoInterestManager.py

@@ -12,6 +12,7 @@ from panda3d.direct import *
 from .MsgTypes import *
 from .MsgTypes import *
 from direct.showbase.PythonUtil import *
 from direct.showbase.PythonUtil import *
 from direct.showbase import DirectObject
 from direct.showbase import DirectObject
+from direct.showbase.MessengerGlobal import messenger
 from .PyDatagram import PyDatagram
 from .PyDatagram import PyDatagram
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.directnotify.DirectNotifyGlobal import directNotify
 import types
 import types
@@ -375,7 +376,7 @@ class DoInterestManager(DirectObject.DirectObject):
             return
             return
         autoInterests = obj.getAutoInterests()
         autoInterests = obj.getAutoInterests()
         obj._autoInterestHandle = None
         obj._autoInterestHandle = None
-        if not len(autoInterests):
+        if len(autoInterests) == 0:
             return
             return
         obj._autoInterestHandle = self.addAutoInterest(obj.doId, autoInterests, '%s-autoInterest' % obj.__class__.__name__)
         obj._autoInterestHandle = self.addAutoInterest(obj.doId, autoInterests, '%s-autoInterest' % obj.__class__.__name__)
     def closeAutoInterests(self, obj):
     def closeAutoInterests(self, obj):
@@ -658,7 +659,8 @@ if __debug__:
                 if failed:
                 if failed:
                     self.stream.write("failures=%d" % failed)
                     self.stream.write("failures=%d" % failed)
                 if errored:
                 if errored:
-                    if failed: self.stream.write(", ")
+                    if failed:
+                        self.stream.write(", ")
                     self.stream.write("errors=%d" % errored)
                     self.stream.write("errors=%d" % errored)
                 self.stream.writeln(")")
                 self.stream.writeln(")")
             else:
             else:

+ 2 - 1
direct/src/distributed/GridChild.py

@@ -1,5 +1,7 @@
 from direct.distributed.DistributedSmoothNodeBase import DistributedSmoothNodeBase
 from direct.distributed.DistributedSmoothNodeBase import DistributedSmoothNodeBase
 from direct.distributed.GridParent import GridParent
 from direct.distributed.GridParent import GridParent
+from direct.showbase.PythonUtil import report
+
 
 
 class GridChild:
 class GridChild:
     """
     """
@@ -56,7 +58,6 @@ class GridChild:
             for currGridId, interestInfo in self._gridInterests.items():
             for currGridId, interestInfo in self._gridInterests.items():
                 self.cr.removeTaggedInterest(interestInfo[0])
                 self.cr.removeTaggedInterest(interestInfo[0])
             #self.__clearGridInterest()
             #self.__clearGridInterest()
-            pass
 
 
     def isOnAGrid(self):
     def isOnAGrid(self):
         return self._gridParent is not None
         return self._gridParent is not None

+ 2 - 4
direct/src/distributed/GridParent.py

@@ -96,7 +96,5 @@ class GridParent:
         else:
         else:
             self.av.reparentTo(self.cellOrigin)
             self.av.reparentTo(self.cellOrigin)
 
 
-        #print "gridParent: reparent to %s" % self.av
-        #print "gridParent: pos = %s, %s" % (self.av.getPos(), self.av.getParent().getPos())
-
-
+        #print("gridParent: reparent to %s" % self.av)
+        #print("gridParent: pos = %s, %s" % (self.av.getPos(), self.av.getParent().getPos()))

+ 8 - 8
direct/src/distributed/InterestWatcher.py

@@ -1,6 +1,8 @@
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.showbase.DirectObject import DirectObject
 from direct.showbase.DirectObject import DirectObject
 from direct.showbase.EventGroup import EventGroup
 from direct.showbase.EventGroup import EventGroup
+from direct.showbase.MessengerGlobal import messenger
+
 
 
 class InterestWatcher(DirectObject):
 class InterestWatcher(DirectObject):
     """Object that observes all interests adds/removes over a period of time,
     """Object that observes all interests adds/removes over a period of time,
@@ -66,11 +68,9 @@ class InterestWatcher(DirectObject):
     def _handleInterestCloseEvent(self, event, parentId, zoneIdList):
     def _handleInterestCloseEvent(self, event, parentId, zoneIdList):
         self._gotEvent = True
         self._gotEvent = True
         self._eGroup.addEvent(event)
         self._eGroup.addEvent(event)
-        """
-        if self._recurse:
-            # this interest is in the process of closing. If an interest
-            # underneath any objects in that interest close, we need to know
-            # about it.
-            self.closingParent2zones.setdefault(parentId, set())
-            self.closingParent2zones[parentId].union(set(zoneIdList))
-            """
+        #if self._recurse:
+        #    # this interest is in the process of closing. If an interest
+        #    # underneath any objects in that interest close, we need to know
+        #    # about it.
+        #    self.closingParent2zones.setdefault(parentId, set())
+        #    self.closingParent2zones[parentId].union(set(zoneIdList))

+ 0 - 2
direct/src/distributed/NetMessenger.py

@@ -90,5 +90,3 @@ class NetMessenger(Messenger):
         else:
         else:
             (message, sentArgs) = loads(pickleData)
             (message, sentArgs) = loads(pickleData)
         Messenger.send(self, message, sentArgs=sentArgs)
         Messenger.send(self, message, sentArgs=sentArgs)
-
-

+ 1 - 1
direct/src/distributed/ParentMgr.py

@@ -90,7 +90,7 @@ class ParentMgr:
         if isDefaultValue(token):
         if isDefaultValue(token):
             self.notify.error('parent token (for %s) cannot be a default value (%s)' % (repr(parent), token))
             self.notify.error('parent token (for %s) cannot be a default value (%s)' % (repr(parent), token))
 
 
-        if type(token) is int:
+        if isinstance(token, int):
             if token > 0xFFFFFFFF:
             if token > 0xFFFFFFFF:
                 self.notify.error('parent token %s (for %s) is out of uint32 range' % (token, repr(parent)))
                 self.notify.error('parent token %s (for %s) is out of uint32 range' % (token, repr(parent)))
 
 

+ 1 - 1
direct/src/distributed/PyDatagram.py

@@ -50,7 +50,7 @@ class PyDatagram(Datagram):
         self.addUint16(code)
         self.addUint16(code)
 
 
     def putArg(self, arg, subatomicType, divisor=1):
     def putArg(self, arg, subatomicType, divisor=1):
-        if (divisor == 1):
+        if divisor == 1:
             funcSpecs = self.FuncDict.get(subatomicType)
             funcSpecs = self.FuncDict.get(subatomicType)
             if funcSpecs:
             if funcSpecs:
                 addFunc, argFunc = funcSpecs
                 addFunc, argFunc = funcSpecs

+ 5 - 5
direct/src/distributed/RelatedObjectMgr.py

@@ -2,8 +2,10 @@
 
 
 # from direct.showbase.ShowBaseGlobal import *
 # from direct.showbase.ShowBaseGlobal import *
 from direct.showbase import DirectObject
 from direct.showbase import DirectObject
+from direct.task.TaskManagerGlobal import taskMgr
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
 
 
+
 class RelatedObjectMgr(DirectObject.DirectObject):
 class RelatedObjectMgr(DirectObject.DirectObject):
     """
     """
     This class manages a relationship between DistributedObjects that
     This class manages a relationship between DistributedObjects that
@@ -104,7 +106,7 @@ class RelatedObjectMgr(DirectObject.DirectObject):
         doIdList = doIdList[:]
         doIdList = doIdList[:]
 
 
         doLaterName = None
         doLaterName = None
-        if timeout != None:
+        if timeout is not None:
             doLaterName = "RelatedObject-%s" % (RelatedObjectMgr.doLaterSequence)
             doLaterName = "RelatedObject-%s" % (RelatedObjectMgr.doLaterSequence)
             assert self.notify.debug("doLaterName = %s" % (doLaterName))
             assert self.notify.debug("doLaterName = %s" % (doLaterName))
 
 
@@ -115,7 +117,7 @@ class RelatedObjectMgr(DirectObject.DirectObject):
 
 
         for doId in doIdsPending:
         for doId in doIdsPending:
             pendingList = self.pendingObjects.get(doId)
             pendingList = self.pendingObjects.get(doId)
-            if pendingList == None:
+            if pendingList is None:
                 pendingList = []
                 pendingList = []
                 self.pendingObjects[doId] = pendingList
                 self.pendingObjects[doId] = pendingList
                 self.__listenFor(doId)
                 self.__listenFor(doId)
@@ -171,7 +173,6 @@ class RelatedObjectMgr(DirectObject.DirectObject):
         assert self.notify.debug("timeout expired for %s (remaining: %s)" % (doIdList, doIdsPending))
         assert self.notify.debug("timeout expired for %s (remaining: %s)" % (doIdList, doIdsPending))
 
 
         self.__removePending(tuple, doIdsPending)
         self.__removePending(tuple, doIdsPending)
-
         if timeoutCallback:
         if timeoutCallback:
             timeoutCallback(doIdList)
             timeoutCallback(doIdList)
         else:
         else:
@@ -248,10 +249,9 @@ class RelatedObjectMgr(DirectObject.DirectObject):
             if doId:
             if doId:
                 object = self.cr.doId2do.get(doId)
                 object = self.cr.doId2do.get(doId)
                 objects.append(object)
                 objects.append(object)
-                if object == None:
+                if object is None:
                     doIdsPending.append(doId)
                     doIdsPending.append(doId)
             else:
             else:
                 objects.append(None)
                 objects.append(None)
 
 
         return objects, doIdsPending
         return objects, doIdsPending
-

+ 6 - 5
direct/src/distributed/ServerRepository.py

@@ -4,6 +4,7 @@ from panda3d.core import *
 from panda3d.direct import *
 from panda3d.direct import *
 from direct.distributed.MsgTypesCMU import *
 from direct.distributed.MsgTypesCMU import *
 from direct.task import Task
 from direct.task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
 from direct.distributed.PyDatagram import PyDatagram
 from direct.distributed.PyDatagram import PyDatagram
 
 
@@ -84,7 +85,7 @@ class ServerRepository:
                  threadedNet = None):
                  threadedNet = None):
         if threadedNet is None:
         if threadedNet is None:
             # Default value.
             # Default value.
-            threadedNet = config.GetBool('threaded-net', False)
+            threadedNet = ConfigVariableBool('threaded-net', False).value
 
 
         # Set up networking interfaces.
         # Set up networking interfaces.
         numThreads = 0
         numThreads = 0
@@ -217,7 +218,7 @@ class ServerRepository:
         self.hashVal = 0
         self.hashVal = 0
 
 
         dcImports = {}
         dcImports = {}
-        if dcFileNames == None:
+        if dcFileNames is None:
             readResult = dcFile.readAll()
             readResult = dcFile.readAll()
             if not readResult:
             if not readResult:
                 self.notify.error("Could not read dc file.")
                 self.notify.error("Could not read dc file.")
@@ -269,11 +270,11 @@ class ServerRepository:
             classDef = dcImports.get(className)
             classDef = dcImports.get(className)
 
 
             # Also try it without the dcSuffix.
             # Also try it without the dcSuffix.
-            if classDef == None:
+            if classDef is None:
                 className = dclass.getName()
                 className = dclass.getName()
                 classDef = dcImports.get(className)
                 classDef = dcImports.get(className)
 
 
-            if classDef == None:
+            if classDef is None:
                 self.notify.debug("No class definition for %s." % (className))
                 self.notify.debug("No class definition for %s." % (className))
             else:
             else:
                 if inspect.ismodule(classDef):
                 if inspect.ismodule(classDef):
@@ -458,7 +459,7 @@ class ServerRepository:
             return
             return
 
 
         dcfield = object.dclass.getFieldByIndex(fieldId)
         dcfield = object.dclass.getFieldByIndex(fieldId)
-        if dcfield == None:
+        if dcfield is None:
             self.notify.warning(
             self.notify.warning(
                 "Ignoring update for field %s on object %s from client %s; no such field for class %s." % (
                 "Ignoring update for field %s on object %s from client %s; no such field for class %s." % (
                 fieldId, doId, client.doIdBase, object.dclass.getName()))
                 fieldId, doId, client.doIdBase, object.dclass.getName()))

+ 0 - 1
direct/src/distributed/StagedObject.py

@@ -61,4 +61,3 @@ class StagedObject:
 
 
     def isOffStage(self):
     def isOffStage(self):
         return self.__state == StagedObject.OFF
         return self.__state == StagedObject.OFF
-

+ 2 - 3
direct/src/distributed/TimeManager.py

@@ -1,6 +1,7 @@
-from direct.showbase.DirectObject import *
 from panda3d.core import *
 from panda3d.core import *
+from direct.showbase.DirectObject import *
 from direct.task import Task
 from direct.task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 from direct.distributed import DistributedObject
 from direct.distributed import DistributedObject
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
 from direct.distributed.ClockDelta import globalClockDelta
 from direct.distributed.ClockDelta import globalClockDelta
@@ -144,7 +145,6 @@ class TimeManager(DistributedObject.DistributedObject):
 
 
         return 1
         return 1
 
 
-
     def serverTime(self, context, timestamp):
     def serverTime(self, context, timestamp):
         """serverTime(self, int8 context, int32 timestamp)
         """serverTime(self, int8 context, int32 timestamp)
 
 
@@ -184,4 +184,3 @@ class TimeManager(DistributedObject.DistributedObject):
 
 
         messenger.send("gotTimeSync", taskChain = 'default')
         messenger.send("gotTimeSync", taskChain = 'default')
         messenger.send(self.cr.uniqueName("gotTimeSync"), taskChain = 'default')
         messenger.send(self.cr.uniqueName("gotTimeSync"), taskChain = 'default')
-

+ 1 - 1
direct/src/distributed/TimeManagerAI.py

@@ -1,5 +1,5 @@
-from direct.distributed.ClockDelta import *
 from panda3d.core import *
 from panda3d.core import *
+from direct.distributed.ClockDelta import *
 from direct.distributed import DistributedObjectAI
 from direct.distributed import DistributedObjectAI
 
 
 class TimeManagerAI(DistributedObjectAI.DistributedObjectAI):
 class TimeManagerAI(DistributedObjectAI.DistributedObjectAI):

+ 1 - 1
direct/src/extensions_native/CInterval_extensions.py

@@ -67,7 +67,7 @@ def popupControls(self, tl = None):
         EntryScale = importlib.import_module('direct.tkwidgets.EntryScale')
         EntryScale = importlib.import_module('direct.tkwidgets.EntryScale')
         tkinter = importlib.import_module('tkinter')
         tkinter = importlib.import_module('tkinter')
 
 
-        if tl == None:
+        if tl is None:
             tl = tkinter.Toplevel()
             tl = tkinter.Toplevel()
             tl.title('Interval Controls')
             tl.title('Interval Controls')
         outerFrame = tkinter.Frame(tl)
         outerFrame = tkinter.Frame(tl)

+ 1 - 4
direct/src/extensions_native/HTTPChannel_extensions.py

@@ -6,10 +6,6 @@
 from panda3d import core
 from panda3d import core
 from .extension_native_helpers import Dtool_funcToMethod
 from .extension_native_helpers import Dtool_funcToMethod
 
 
-"""
-HTTPChannel-extensions module: contains methods to extend functionality
-of the HTTPChannel class
-"""
 
 
 def spawnTask(self, name = None, callback = None, extraArgs = []):
 def spawnTask(self, name = None, callback = None, extraArgs = []):
         """Spawns a task to service the download recently requested
         """Spawns a task to service the download recently requested
@@ -23,6 +19,7 @@ def spawnTask(self, name = None, callback = None, extraArgs = []):
         if not name:
         if not name:
             name = str(self.getUrl())
             name = str(self.getUrl())
         from direct.task import Task
         from direct.task import Task
+        from direct.task.TaskManagerGlobal import taskMgr
         task = Task.Task(self.doTask)
         task = Task.Task(self.doTask)
         task.callback = callback
         task.callback = callback
         task.callbackArgs = extraArgs
         task.callbackArgs = extraArgs

+ 5 - 5
direct/src/extensions_native/Mat3_extensions.py

@@ -12,11 +12,11 @@ from panda3d.core import Mat3
 from .extension_native_helpers import Dtool_funcToMethod
 from .extension_native_helpers import Dtool_funcToMethod
 
 
 def pPrintValues(self):
 def pPrintValues(self):
-        """
-        Pretty print
-        """
-        return "\n%s\n%s\n%s" % (
-            self.getRow(0).pPrintValues(), self.getRow(1).pPrintValues(), self.getRow(2).pPrintValues())
+    """
+    Pretty print
+    """
+    return "\n%s\n%s\n%s" % (
+        self.getRow(0).pPrintValues(), self.getRow(1).pPrintValues(), self.getRow(2).pPrintValues())
 Dtool_funcToMethod(pPrintValues, Mat3)
 Dtool_funcToMethod(pPrintValues, Mat3)
 del pPrintValues
 del pPrintValues
 #####################################################################
 #####################################################################

+ 87 - 62
direct/src/extensions_native/NodePath_extensions.py

@@ -105,6 +105,7 @@ def remove(self):
         print("Warning: NodePath.remove() is deprecated.  Use remove_node() instead.")
         print("Warning: NodePath.remove() is deprecated.  Use remove_node() instead.")
         # Send message in case anyone needs to do something
         # Send message in case anyone needs to do something
         # before node is deleted
         # before node is deleted
+        from direct.showbase.MessengerGlobal import messenger
         messenger.send('preRemoveNodePath', [self])
         messenger.send('preRemoveNodePath', [self])
         # Remove nodePath
         # Remove nodePath
         self.removeNode()
         self.removeNode()
@@ -315,7 +316,7 @@ def printTransform(self, other = None, sd = 2, fRecursive = 0):
     from panda3d.core import Vec3
     from panda3d.core import Vec3
     fmtStr = '%%0.%df' % sd
     fmtStr = '%%0.%df' % sd
     name = self.getName()
     name = self.getName()
-    if other == None:
+    if other is None:
         transform = self.getTransform()
         transform = self.getTransform()
     else:
     else:
         transform = self.getTransform(other)
         transform = self.getTransform(other)
@@ -464,7 +465,7 @@ def showCS(self, mask = None):
         npc = self.findAllMatches('**/+CollisionNode')
         npc = self.findAllMatches('**/+CollisionNode')
         for p in range(0, npc.getNumPaths()):
         for p in range(0, npc.getNumPaths()):
             np = npc[p]
             np = npc[p]
-            if (mask == None or (np.node().getIntoCollideMask() & mask).getWord()):
+            if (mask is None or (np.node().getIntoCollideMask() & mask).getWord()):
                 np.show()
                 np.show()
 
 
 Dtool_funcToMethod(showCS, NodePath)
 Dtool_funcToMethod(showCS, NodePath)
@@ -482,7 +483,7 @@ def hideCS(self, mask = None):
         npc = self.findAllMatches('**/+CollisionNode')
         npc = self.findAllMatches('**/+CollisionNode')
         for p in range(0, npc.getNumPaths()):
         for p in range(0, npc.getNumPaths()):
             np = npc[p]
             np = npc[p]
-            if (mask == None or (np.node().getIntoCollideMask() & mask).getWord()):
+            if (mask is None or (np.node().getIntoCollideMask() & mask).getWord()):
                 np.hide()
                 np.hide()
 
 
 Dtool_funcToMethod(hideCS, NodePath)
 Dtool_funcToMethod(hideCS, NodePath)
@@ -639,15 +640,15 @@ def flattenMultitex(self, stateFrom = None, target = None,
                         useGeom = 0, allowTexMat = 0, win = None):
                         useGeom = 0, allowTexMat = 0, win = None):
         from panda3d.core import MultitexReducer
         from panda3d.core import MultitexReducer
         mr = MultitexReducer()
         mr = MultitexReducer()
-        if target != None:
+        if target is not None:
             mr.setTarget(target)
             mr.setTarget(target)
         mr.setUseGeom(useGeom)
         mr.setUseGeom(useGeom)
         mr.setAllowTexMat(allowTexMat)
         mr.setAllowTexMat(allowTexMat)
 
 
-        if win == None:
+        if win is None:
             win = base.win
             win = base.win
 
 
-        if stateFrom == None:
+        if stateFrom is None:
             mr.scan(self)
             mr.scan(self)
         else:
         else:
             mr.scan(self, stateFrom)
             mr.scan(self, stateFrom)
@@ -664,7 +665,7 @@ def removeNonCollisions(self):
         # remove anything that is not collision-related
         # remove anything that is not collision-related
         print("NodePath.removeNonCollisions() is deprecated")
         print("NodePath.removeNonCollisions() is deprecated")
         stack = [self]
         stack = [self]
-        while len(stack):
+        while len(stack) > 0:
                 np = stack.pop()
                 np = stack.pop()
                 # if there are no CollisionNodes under this node, remove it
                 # if there are no CollisionNodes under this node, remove it
                 if np.find('**/+CollisionNode').isEmpty():
                 if np.find('**/+CollisionNode').isEmpty():
@@ -706,22 +707,44 @@ def r_subdivideCollisions(self, solids, numSolidsInLeaves):
         if len(solids) <= numSolidsInLeaves:
         if len(solids) <= numSolidsInLeaves:
             return solids
             return solids
         origins = []
         origins = []
-        avgX = 0; avgY = 0; avgZ = 0
-        minX = None; minY = None; minZ = None
-        maxX = None; maxY = None; maxZ = None
+        avgX = 0
+        avgY = 0
+        avgZ = 0
+        minX = None
+        minY = None
+        minZ = None
+        maxX = None
+        maxY = None
+        maxZ = None
         for solid in solids:
         for solid in solids:
             origin = solid.getCollisionOrigin()
             origin = solid.getCollisionOrigin()
             origins.append(origin)
             origins.append(origin)
-            x = origin.getX(); y = origin.getY(); z = origin.getZ()
-            avgX += x; avgY += y; avgZ += z
+            x = origin.getX()
+            y = origin.getY()
+            z = origin.getZ()
+            avgX += x
+            avgY += y
+            avgZ += z
             if minX is None:
             if minX is None:
-                minX = x; minY = y; minZ = z
-                maxX = x; maxY = y; maxZ = z
+                minX = x
+                minY = y
+                minZ = z
+                maxX = x
+                maxY = y
+                maxZ = z
             else:
             else:
-                minX = min(x, minX); minY = min(y, minY); minZ = min(z, minZ)
-                maxX = max(x, maxX); maxY = max(y, maxY); maxZ = max(z, maxZ)
-        avgX /= len(solids); avgY /= len(solids); avgZ /= len(solids)
-        extentX = maxX - minX; extentY = maxY - minY; extentZ = maxZ - minZ
+                minX = min(x, minX)
+                minY = min(y, minY)
+                minZ = min(z, minZ)
+                maxX = max(x, maxX)
+                maxY = max(y, maxY)
+                maxZ = max(z, maxZ)
+        avgX /= len(solids)
+        avgY /= len(solids)
+        avgZ /= len(solids)
+        extentX = maxX - minX
+        extentY = maxY - minY
+        extentZ = maxZ - minZ
         maxExtent = max(max(extentX, extentY), extentZ)
         maxExtent = max(max(extentX, extentY), extentZ)
         # sparse octree
         # sparse octree
         xyzSolids = []
         xyzSolids = []
@@ -738,60 +761,62 @@ def r_subdivideCollisions(self, solids, numSolidsInLeaves):
         # throw out axes that are not close to the max axis extent; try and keep
         # throw out axes that are not close to the max axis extent; try and keep
         # the divisions square/spherical
         # the divisions square/spherical
         if extentX < (maxExtent * .75) or extentX > (maxExtent * 1.25):
         if extentX < (maxExtent * .75) or extentX > (maxExtent * 1.25):
-                midX += maxExtent
+            midX += maxExtent
         if extentY < (maxExtent * .75) or extentY > (maxExtent * 1.25):
         if extentY < (maxExtent * .75) or extentY > (maxExtent * 1.25):
-                midY += maxExtent
+            midY += maxExtent
         if extentZ < (maxExtent * .75) or extentZ > (maxExtent * 1.25):
         if extentZ < (maxExtent * .75) or extentZ > (maxExtent * 1.25):
-                midZ += maxExtent
-        for i in range(len(solids)):
-                origin = origins[i]
-                x = origin.getX(); y = origin.getY(); z = origin.getZ()
-                if x < midX:
-                        if y < midY:
-                                if z < midZ:
-                                        xyzSolids.append(solids[i])
-                                else:
-                                        xyZSolids.append(solids[i])
-                        else:
-                                if z < midZ:
-                                        xYzSolids.append(solids[i])
-                                else:
-                                        xYZSolids.append(solids[i])
+            midZ += maxExtent
+        for i, solid in enumerate(solids):
+            origin = origins[i]
+            x = origin.getX()
+            y = origin.getY()
+            z = origin.getZ()
+            if x < midX:
+                if y < midY:
+                    if z < midZ:
+                        xyzSolids.append(solids[i])
+                    else:
+                        xyZSolids.append(solids[i])
                 else:
                 else:
-                        if y < midY:
-                                if z < midZ:
-                                        XyzSolids.append(solids[i])
-                                else:
-                                        XyZSolids.append(solids[i])
-                        else:
-                                if z < midZ:
-                                        XYzSolids.append(solids[i])
-                                else:
-                                        XYZSolids.append(solids[i])
+                    if z < midZ:
+                        xYzSolids.append(solids[i])
+                    else:
+                        xYZSolids.append(solids[i])
+            else:
+                if y < midY:
+                    if z < midZ:
+                        XyzSolids.append(solids[i])
+                    else:
+                        XyZSolids.append(solids[i])
+                else:
+                    if z < midZ:
+                        XYzSolids.append(solids[i])
+                    else:
+                        XYZSolids.append(solids[i])
         newSolids = []
         newSolids = []
-        if len(xyzSolids):
-                newSolids.append(self.r_subdivideCollisions(xyzSolids, numSolidsInLeaves))
-        if len(XyzSolids):
-                newSolids.append(self.r_subdivideCollisions(XyzSolids, numSolidsInLeaves))
-        if len(xYzSolids):
-                newSolids.append(self.r_subdivideCollisions(xYzSolids, numSolidsInLeaves))
-        if len(XYzSolids):
-                newSolids.append(self.r_subdivideCollisions(XYzSolids, numSolidsInLeaves))
-        if len(xyZSolids):
-                newSolids.append(self.r_subdivideCollisions(xyZSolids, numSolidsInLeaves))
-        if len(XyZSolids):
-                newSolids.append(self.r_subdivideCollisions(XyZSolids, numSolidsInLeaves))
-        if len(xYZSolids):
-                newSolids.append(self.r_subdivideCollisions(xYZSolids, numSolidsInLeaves))
-        if len(XYZSolids):
-                newSolids.append(self.r_subdivideCollisions(XYZSolids, numSolidsInLeaves))
+        if len(xyzSolids) > 0:
+            newSolids.append(self.r_subdivideCollisions(xyzSolids, numSolidsInLeaves))
+        if len(XyzSolids) > 0:
+            newSolids.append(self.r_subdivideCollisions(XyzSolids, numSolidsInLeaves))
+        if len(xYzSolids) > 0:
+            newSolids.append(self.r_subdivideCollisions(xYzSolids, numSolidsInLeaves))
+        if len(XYzSolids) > 0:
+            newSolids.append(self.r_subdivideCollisions(XYzSolids, numSolidsInLeaves))
+        if len(xyZSolids) > 0:
+            newSolids.append(self.r_subdivideCollisions(xyZSolids, numSolidsInLeaves))
+        if len(XyZSolids) > 0:
+            newSolids.append(self.r_subdivideCollisions(XyZSolids, numSolidsInLeaves))
+        if len(xYZSolids) > 0:
+            newSolids.append(self.r_subdivideCollisions(xYZSolids, numSolidsInLeaves))
+        if len(XYZSolids) > 0:
+            newSolids.append(self.r_subdivideCollisions(XYZSolids, numSolidsInLeaves))
         #import pdb;pdb.set_trace()
         #import pdb;pdb.set_trace()
         return newSolids
         return newSolids
 
 
 def r_constructCollisionTree(self, solidTree, parentNode, colName):
 def r_constructCollisionTree(self, solidTree, parentNode, colName):
         from panda3d.core import CollisionNode
         from panda3d.core import CollisionNode
         for item in solidTree:
         for item in solidTree:
-            if type(item[0]) == type([]):
+            if isinstance(item[0], list):
                 newNode = parentNode.attachNewNode('%s-branch' % colName)
                 newNode = parentNode.attachNewNode('%s-branch' % colName)
                 self.r_constructCollisionTree(item, newNode, colName)
                 self.r_constructCollisionTree(item, newNode, colName)
             else:
             else:

+ 103 - 97
direct/src/filter/CommonFilters.py

@@ -16,6 +16,13 @@ clunky approach.  - Josh
 
 
 """
 """
 
 
+from panda3d.core import LVecBase4, LPoint2
+from panda3d.core import AuxBitplaneAttrib
+from panda3d.core import Texture, Shader, ATSNone
+from panda3d.core import FrameBufferProperties
+
+from direct.task.TaskManagerGlobal import taskMgr
+
 from .FilterManager import FilterManager
 from .FilterManager import FilterManager
 from .filterBloomI import BLOOM_I
 from .filterBloomI import BLOOM_I
 from .filterBloomX import BLOOM_X
 from .filterBloomX import BLOOM_X
@@ -24,14 +31,8 @@ from .filterBlurX import BLUR_X
 from .filterBlurY import BLUR_Y
 from .filterBlurY import BLUR_Y
 from .filterCopy import COPY
 from .filterCopy import COPY
 from .filterDown4 import DOWN_4
 from .filterDown4 import DOWN_4
-from panda3d.core import LVecBase4, LPoint2
-from panda3d.core import Filename
-from panda3d.core import AuxBitplaneAttrib
-from panda3d.core import Texture, Shader, ATSNone
-from panda3d.core import FrameBufferProperties
-import os
 
 
-CARTOON_BODY="""
+CARTOON_BODY = """
 float4 cartoondelta = k_cartoonseparation * texpix_txaux.xwyw;
 float4 cartoondelta = k_cartoonseparation * texpix_txaux.xwyw;
 float4 cartoon_c0 = tex2D(k_txaux, %(texcoord)s + cartoondelta.xy);
 float4 cartoon_c0 = tex2D(k_txaux, %(texcoord)s + cartoondelta.xy);
 float4 cartoon_c1 = tex2D(k_txaux, %(texcoord)s - cartoondelta.xy);
 float4 cartoon_c1 = tex2D(k_txaux, %(texcoord)s - cartoondelta.xy);
@@ -48,7 +49,7 @@ o_color = lerp(o_color, k_cartooncolor, cartoon_thresh);
 # We fill in the actual value of numsamples in the loop limit
 # We fill in the actual value of numsamples in the loop limit
 # when the shader is configured.
 # when the shader is configured.
 #
 #
-SSAO_BODY="""//Cg
+SSAO_BODY = """//Cg
 
 
 void vshader(float4 vtx_position : POSITION,
 void vshader(float4 vtx_position : POSITION,
              out float4 l_position : POSITION,
              out float4 l_position : POSITION,
@@ -100,8 +101,8 @@ void fshader(out float4 o_color : COLOR,
 class FilterConfig:
 class FilterConfig:
     pass
     pass
 
 
-class CommonFilters:
 
 
+class CommonFilters:
     """ Class CommonFilters implements certain common image postprocessing
     """ Class CommonFilters implements certain common image postprocessing
     filters.  The constructor requires a filter builder as a parameter. """
     filters.  The constructor requires a filter builder as a parameter. """
 
 
@@ -118,20 +119,19 @@ class CommonFilters:
         self.bloom = []
         self.bloom = []
         self.blur = []
         self.blur = []
         self.ssao = []
         self.ssao = []
-        if self.task != None:
-          taskMgr.remove(self.task)
-          self.task = None
+        if self.task is not None:
+            taskMgr.remove(self.task)
+            self.task = None
 
 
     def reconfigure(self, fullrebuild, changed):
     def reconfigure(self, fullrebuild, changed):
         """ Reconfigure is called whenever any configuration change is made. """
         """ Reconfigure is called whenever any configuration change is made. """
 
 
         configuration = self.configuration
         configuration = self.configuration
 
 
-        if (fullrebuild):
-
+        if fullrebuild:
             self.cleanup()
             self.cleanup()
 
 
-            if (len(configuration) == 0):
+            if len(configuration) == 0:
                 return
                 return
 
 
             if not self.manager.win.gsg.getSupportsBasicShaders():
             if not self.manager.win.gsg.getSupportsBasicShaders():
@@ -141,12 +141,12 @@ class CommonFilters:
             needtex = set(["color"])
             needtex = set(["color"])
             needtexcoord = set(["color"])
             needtexcoord = set(["color"])
 
 
-            if ("CartoonInk" in configuration):
+            if "CartoonInk" in configuration:
                 needtex.add("aux")
                 needtex.add("aux")
                 auxbits |= AuxBitplaneAttrib.ABOAuxNormal
                 auxbits |= AuxBitplaneAttrib.ABOAuxNormal
                 needtexcoord.add("aux")
                 needtexcoord.add("aux")
 
 
-            if ("AmbientOcclusion" in configuration):
+            if "AmbientOcclusion" in configuration:
                 needtex.add("depth")
                 needtex.add("depth")
                 needtex.add("ssao0")
                 needtex.add("ssao0")
                 needtex.add("ssao1")
                 needtex.add("ssao1")
@@ -155,12 +155,12 @@ class CommonFilters:
                 auxbits |= AuxBitplaneAttrib.ABOAuxNormal
                 auxbits |= AuxBitplaneAttrib.ABOAuxNormal
                 needtexcoord.add("ssao2")
                 needtexcoord.add("ssao2")
 
 
-            if ("BlurSharpen" in configuration):
+            if "BlurSharpen" in configuration:
                 needtex.add("blur0")
                 needtex.add("blur0")
                 needtex.add("blur1")
                 needtex.add("blur1")
                 needtexcoord.add("blur1")
                 needtexcoord.add("blur1")
 
 
-            if ("Bloom" in configuration):
+            if "Bloom" in configuration:
                 needtex.add("bloom0")
                 needtex.add("bloom0")
                 needtex.add("bloom1")
                 needtex.add("bloom1")
                 needtex.add("bloom2")
                 needtex.add("bloom2")
@@ -168,10 +168,10 @@ class CommonFilters:
                 auxbits |= AuxBitplaneAttrib.ABOGlow
                 auxbits |= AuxBitplaneAttrib.ABOGlow
                 needtexcoord.add("bloom3")
                 needtexcoord.add("bloom3")
 
 
-            if ("ViewGlow" in configuration):
+            if "ViewGlow" in configuration:
                 auxbits |= AuxBitplaneAttrib.ABOGlow
                 auxbits |= AuxBitplaneAttrib.ABOGlow
 
 
-            if ("VolumetricLighting" in configuration):
+            if "VolumetricLighting" in configuration:
                 needtex.add(configuration["VolumetricLighting"].source)
                 needtex.add(configuration["VolumetricLighting"].source)
 
 
             for tex in needtex:
             for tex in needtex:
@@ -188,47 +188,47 @@ class CommonFilters:
                 clamping = False
                 clamping = False
 
 
             self.finalQuad = self.manager.renderSceneInto(textures = self.textures, auxbits=auxbits, fbprops=fbprops, clamping=clamping)
             self.finalQuad = self.manager.renderSceneInto(textures = self.textures, auxbits=auxbits, fbprops=fbprops, clamping=clamping)
-            if (self.finalQuad == None):
+            if self.finalQuad is None:
                 self.cleanup()
                 self.cleanup()
                 return False
                 return False
 
 
-            if ("BlurSharpen" in configuration):
-                blur0=self.textures["blur0"]
-                blur1=self.textures["blur1"]
-                self.blur.append(self.manager.renderQuadInto("filter-blur0", colortex=blur0,div=2))
+            if "BlurSharpen" in configuration:
+                blur0 = self.textures["blur0"]
+                blur1 = self.textures["blur1"]
+                self.blur.append(self.manager.renderQuadInto("filter-blur0", colortex=blur0, div=2))
                 self.blur.append(self.manager.renderQuadInto("filter-blur1", colortex=blur1))
                 self.blur.append(self.manager.renderQuadInto("filter-blur1", colortex=blur1))
                 self.blur[0].setShaderInput("src", self.textures["color"])
                 self.blur[0].setShaderInput("src", self.textures["color"])
                 self.blur[0].setShader(Shader.make(BLUR_X, Shader.SL_Cg))
                 self.blur[0].setShader(Shader.make(BLUR_X, Shader.SL_Cg))
                 self.blur[1].setShaderInput("src", blur0)
                 self.blur[1].setShaderInput("src", blur0)
                 self.blur[1].setShader(Shader.make(BLUR_Y, Shader.SL_Cg))
                 self.blur[1].setShader(Shader.make(BLUR_Y, Shader.SL_Cg))
 
 
-            if ("AmbientOcclusion" in configuration):
-                ssao0=self.textures["ssao0"]
-                ssao1=self.textures["ssao1"]
-                ssao2=self.textures["ssao2"]
+            if "AmbientOcclusion" in configuration:
+                ssao0 = self.textures["ssao0"]
+                ssao1 = self.textures["ssao1"]
+                ssao2 = self.textures["ssao2"]
                 self.ssao.append(self.manager.renderQuadInto("filter-ssao0", colortex=ssao0))
                 self.ssao.append(self.manager.renderQuadInto("filter-ssao0", colortex=ssao0))
-                self.ssao.append(self.manager.renderQuadInto("filter-ssao1", colortex=ssao1,div=2))
+                self.ssao.append(self.manager.renderQuadInto("filter-ssao1", colortex=ssao1, div=2))
                 self.ssao.append(self.manager.renderQuadInto("filter-ssao2", colortex=ssao2))
                 self.ssao.append(self.manager.renderQuadInto("filter-ssao2", colortex=ssao2))
                 self.ssao[0].setShaderInput("depth", self.textures["depth"])
                 self.ssao[0].setShaderInput("depth", self.textures["depth"])
                 self.ssao[0].setShaderInput("normal", self.textures["aux"])
                 self.ssao[0].setShaderInput("normal", self.textures["aux"])
-                self.ssao[0].setShaderInput("random", loader.loadTexture("maps/random.rgb"))
+                self.ssao[0].setShaderInput("random", base.loader.loadTexture("maps/random.rgb"))
                 self.ssao[0].setShader(Shader.make(SSAO_BODY % configuration["AmbientOcclusion"].numsamples, Shader.SL_Cg))
                 self.ssao[0].setShader(Shader.make(SSAO_BODY % configuration["AmbientOcclusion"].numsamples, Shader.SL_Cg))
                 self.ssao[1].setShaderInput("src", ssao0)
                 self.ssao[1].setShaderInput("src", ssao0)
                 self.ssao[1].setShader(Shader.make(BLUR_X, Shader.SL_Cg))
                 self.ssao[1].setShader(Shader.make(BLUR_X, Shader.SL_Cg))
                 self.ssao[2].setShaderInput("src", ssao1)
                 self.ssao[2].setShaderInput("src", ssao1)
                 self.ssao[2].setShader(Shader.make(BLUR_Y, Shader.SL_Cg))
                 self.ssao[2].setShader(Shader.make(BLUR_Y, Shader.SL_Cg))
 
 
-            if ("Bloom" in configuration):
+            if "Bloom" in configuration:
                 bloomconf = configuration["Bloom"]
                 bloomconf = configuration["Bloom"]
-                bloom0=self.textures["bloom0"]
-                bloom1=self.textures["bloom1"]
-                bloom2=self.textures["bloom2"]
-                bloom3=self.textures["bloom3"]
-                if (bloomconf.size == "large"):
+                bloom0 = self.textures["bloom0"]
+                bloom1 = self.textures["bloom1"]
+                bloom2 = self.textures["bloom2"]
+                bloom3 = self.textures["bloom3"]
+                if bloomconf.size == "large":
                     scale=8
                     scale=8
                     downsamplerName="filter-down4"
                     downsamplerName="filter-down4"
                     downsampler=DOWN_4
                     downsampler=DOWN_4
-                elif (bloomconf.size == "medium"):
+                elif bloomconf.size == "medium":
                     scale=4
                     scale=4
                     downsamplerName="filter-copy"
                     downsamplerName="filter-copy"
                     downsampler=COPY
                     downsampler=COPY
@@ -282,7 +282,7 @@ class CommonFilters:
             for texcoord, padTex in texcoordPadding.items():
             for texcoord, padTex in texcoordPadding.items():
                 if padTex is not None:
                 if padTex is not None:
                     text += "  uniform float4 texpad_tx%s,\n" % (padTex)
                     text += "  uniform float4 texpad_tx%s,\n" % (padTex)
-                    if ("HalfPixelShift" in configuration):
+                    if "HalfPixelShift" in configuration:
                         text += "  uniform float4 texpix_tx%s,\n" % (padTex)
                         text += "  uniform float4 texpix_tx%s,\n" % (padTex)
 
 
             for i, name in texcoordSets:
             for i, name in texcoordSets:
@@ -298,7 +298,7 @@ class CommonFilters:
                 else:
                 else:
                     text += "  %s = (vtx_position.xz * texpad_tx%s.xy) + texpad_tx%s.xy;\n" % (texcoord, padTex, padTex)
                     text += "  %s = (vtx_position.xz * texpad_tx%s.xy) + texpad_tx%s.xy;\n" % (texcoord, padTex, padTex)
 
 
-                    if ("HalfPixelShift" in configuration):
+                    if "HalfPixelShift" in configuration:
                         text += "  %s += texpix_tx%s.xy * 0.5;\n" % (texcoord, padTex)
                         text += "  %s += texpix_tx%s.xy * 0.5;\n" % (texcoord, padTex)
 
 
             text += "}\n"
             text += "}\n"
@@ -311,37 +311,37 @@ class CommonFilters:
             for key in self.textures:
             for key in self.textures:
                 text += "  uniform sampler2D k_tx" + key + ",\n"
                 text += "  uniform sampler2D k_tx" + key + ",\n"
 
 
-            if ("CartoonInk" in configuration):
+            if "CartoonInk" in configuration:
                 text += "  uniform float4 k_cartoonseparation,\n"
                 text += "  uniform float4 k_cartoonseparation,\n"
                 text += "  uniform float4 k_cartooncolor,\n"
                 text += "  uniform float4 k_cartooncolor,\n"
                 text += "  uniform float4 texpix_txaux,\n"
                 text += "  uniform float4 texpix_txaux,\n"
 
 
-            if ("BlurSharpen" in configuration):
+            if "BlurSharpen" in configuration:
                 text += "  uniform float4 k_blurval,\n"
                 text += "  uniform float4 k_blurval,\n"
 
 
-            if ("VolumetricLighting" in configuration):
+            if "VolumetricLighting" in configuration:
                 text += "  uniform float4 k_casterpos,\n"
                 text += "  uniform float4 k_casterpos,\n"
                 text += "  uniform float4 k_vlparams,\n"
                 text += "  uniform float4 k_vlparams,\n"
 
 
-            if ("ExposureAdjust" in configuration):
+            if "ExposureAdjust" in configuration:
                 text += "  uniform float k_exposure,\n"
                 text += "  uniform float k_exposure,\n"
 
 
             text += "  out float4 o_color : COLOR)\n"
             text += "  out float4 o_color : COLOR)\n"
             text += "{\n"
             text += "{\n"
             text += "  o_color = tex2D(k_txcolor, %s);\n" % (texcoords["color"])
             text += "  o_color = tex2D(k_txcolor, %s);\n" % (texcoords["color"])
-            if ("CartoonInk" in configuration):
+            if "CartoonInk" in configuration:
                 text += CARTOON_BODY % {"texcoord" : texcoords["aux"]}
                 text += CARTOON_BODY % {"texcoord" : texcoords["aux"]}
-            if ("AmbientOcclusion" in configuration):
+            if "AmbientOcclusion" in configuration:
                 text += "  o_color *= tex2D(k_txssao2, %s).r;\n" % (texcoords["ssao2"])
                 text += "  o_color *= tex2D(k_txssao2, %s).r;\n" % (texcoords["ssao2"])
-            if ("BlurSharpen" in configuration):
+            if "BlurSharpen" in configuration:
                 text += "  o_color = lerp(tex2D(k_txblur1, %s), o_color, k_blurval.x);\n" % (texcoords["blur1"])
                 text += "  o_color = lerp(tex2D(k_txblur1, %s), o_color, k_blurval.x);\n" % (texcoords["blur1"])
-            if ("Bloom" in configuration):
-                text += "  o_color = saturate(o_color);\n";
+            if "Bloom" in configuration:
+                text += "  o_color = saturate(o_color);\n"
                 text += "  float4 bloom = 0.5 * tex2D(k_txbloom3, %s);\n" % (texcoords["bloom3"])
                 text += "  float4 bloom = 0.5 * tex2D(k_txbloom3, %s);\n" % (texcoords["bloom3"])
                 text += "  o_color = 1-((1-bloom)*(1-o_color));\n"
                 text += "  o_color = 1-((1-bloom)*(1-o_color));\n"
-            if ("ViewGlow" in configuration):
+            if "ViewGlow" in configuration:
                 text += "  o_color.r = o_color.a;\n"
                 text += "  o_color.r = o_color.a;\n"
-            if ("VolumetricLighting" in configuration):
+            if "VolumetricLighting" in configuration:
                 text += "  float decay = 1.0f;\n"
                 text += "  float decay = 1.0f;\n"
                 text += "  float2 curcoord = %s;\n" % (texcoords["color"])
                 text += "  float2 curcoord = %s;\n" % (texcoords["color"])
                 text += "  float2 lightdir = curcoord - k_casterpos.xy;\n"
                 text += "  float2 lightdir = curcoord - k_casterpos.xy;\n"
@@ -357,15 +357,15 @@ class CommonFilters:
                 text += "  }\n"
                 text += "  }\n"
                 text += "  o_color += float4(vlcolor * k_vlparams.z, 1);\n"
                 text += "  o_color += float4(vlcolor * k_vlparams.z, 1);\n"
 
 
-            if ("ExposureAdjust" in configuration):
+            if "ExposureAdjust" in configuration:
                 text += "  o_color.rgb *= k_exposure;\n"
                 text += "  o_color.rgb *= k_exposure;\n"
 
 
             # With thanks to Stephen Hill!
             # With thanks to Stephen Hill!
-            if ("HighDynamicRange" in configuration):
+            if "HighDynamicRange" in configuration:
                 text += "  float3 aces_color = mul(aces_input_mat, o_color.rgb);\n"
                 text += "  float3 aces_color = mul(aces_input_mat, o_color.rgb);\n"
                 text += "  o_color.rgb = saturate(mul(aces_output_mat, (aces_color * (aces_color + 0.0245786f) - 0.000090537f) / (aces_color * (0.983729f * aces_color + 0.4329510f) + 0.238081f)));\n"
                 text += "  o_color.rgb = saturate(mul(aces_output_mat, (aces_color * (aces_color + 0.0245786f) - 0.000090537f) / (aces_color * (0.983729f * aces_color + 0.4329510f) + 0.238081f)));\n"
 
 
-            if ("GammaAdjust" in configuration):
+            if "GammaAdjust" in configuration:
                 gamma = configuration["GammaAdjust"]
                 gamma = configuration["GammaAdjust"]
                 if gamma == 0.5:
                 if gamma == 0.5:
                     text += "  o_color.rgb = sqrt(o_color.rgb);\n"
                     text += "  o_color.rgb = sqrt(o_color.rgb);\n"
@@ -374,12 +374,12 @@ class CommonFilters:
                 elif gamma != 1.0:
                 elif gamma != 1.0:
                     text += "  o_color.rgb = pow(o_color.rgb, %ff);\n" % (gamma)
                     text += "  o_color.rgb = pow(o_color.rgb, %ff);\n" % (gamma)
 
 
-            if ("SrgbEncode" in configuration):
+            if "SrgbEncode" in configuration:
                 text += "  o_color.r = (o_color.r < 0.0031308) ? (o_color.r * 12.92) : (1.055 * pow(o_color.r, 0.41666) - 0.055);\n"
                 text += "  o_color.r = (o_color.r < 0.0031308) ? (o_color.r * 12.92) : (1.055 * pow(o_color.r, 0.41666) - 0.055);\n"
                 text += "  o_color.g = (o_color.g < 0.0031308) ? (o_color.g * 12.92) : (1.055 * pow(o_color.g, 0.41666) - 0.055);\n"
                 text += "  o_color.g = (o_color.g < 0.0031308) ? (o_color.g * 12.92) : (1.055 * pow(o_color.g, 0.41666) - 0.055);\n"
                 text += "  o_color.b = (o_color.b < 0.0031308) ? (o_color.b * 12.92) : (1.055 * pow(o_color.b, 0.41666) - 0.055);\n"
                 text += "  o_color.b = (o_color.b < 0.0031308) ? (o_color.b * 12.92) : (1.055 * pow(o_color.b, 0.41666) - 0.055);\n"
 
 
-            if ("Inverted" in configuration):
+            if "Inverted" in configuration:
                 text += "  o_color = float4(1, 1, 1, 1) - o_color;\n"
                 text += "  o_color = float4(1, 1, 1, 1) - o_color;\n"
             text += "}\n"
             text += "}\n"
 
 
@@ -392,19 +392,19 @@ class CommonFilters:
 
 
             self.task = taskMgr.add(self.update, "common-filters-update")
             self.task = taskMgr.add(self.update, "common-filters-update")
 
 
-        if (changed == "CartoonInk") or fullrebuild:
-            if ("CartoonInk" in configuration):
+        if changed == "CartoonInk" or fullrebuild:
+            if "CartoonInk" in configuration:
                 c = configuration["CartoonInk"]
                 c = configuration["CartoonInk"]
                 self.finalQuad.setShaderInput("cartoonseparation", LVecBase4(c.separation, 0, c.separation, 0))
                 self.finalQuad.setShaderInput("cartoonseparation", LVecBase4(c.separation, 0, c.separation, 0))
                 self.finalQuad.setShaderInput("cartooncolor", c.color)
                 self.finalQuad.setShaderInput("cartooncolor", c.color)
 
 
-        if (changed == "BlurSharpen") or fullrebuild:
-            if ("BlurSharpen" in configuration):
+        if changed == "BlurSharpen" or fullrebuild:
+            if "BlurSharpen" in configuration:
                 blurval = configuration["BlurSharpen"]
                 blurval = configuration["BlurSharpen"]
                 self.finalQuad.setShaderInput("blurval", LVecBase4(blurval, blurval, blurval, blurval))
                 self.finalQuad.setShaderInput("blurval", LVecBase4(blurval, blurval, blurval, blurval))
 
 
-        if (changed == "Bloom") or fullrebuild:
-            if ("Bloom" in configuration):
+        if changed == "Bloom" or fullrebuild:
+            if "Bloom" in configuration:
                 bloomconf = configuration["Bloom"]
                 bloomconf = configuration["Bloom"]
                 intensity = bloomconf.intensity * 3.0
                 intensity = bloomconf.intensity * 3.0
                 self.bloom[0].setShaderInput("blend", bloomconf.blendx, bloomconf.blendy, bloomconf.blendz, bloomconf.blendw * 2.0)
                 self.bloom[0].setShaderInput("blend", bloomconf.blendx, bloomconf.blendy, bloomconf.blendz, bloomconf.blendw * 2.0)
@@ -412,20 +412,20 @@ class CommonFilters:
                 self.bloom[0].setShaderInput("desat", bloomconf.desat)
                 self.bloom[0].setShaderInput("desat", bloomconf.desat)
                 self.bloom[3].setShaderInput("intensity", intensity, intensity, intensity, intensity)
                 self.bloom[3].setShaderInput("intensity", intensity, intensity, intensity, intensity)
 
 
-        if (changed == "VolumetricLighting") or fullrebuild:
-            if ("VolumetricLighting" in configuration):
+        if changed == "VolumetricLighting" or fullrebuild:
+            if "VolumetricLighting" in configuration:
                 config = configuration["VolumetricLighting"]
                 config = configuration["VolumetricLighting"]
                 tcparam = config.density / float(config.numsamples)
                 tcparam = config.density / float(config.numsamples)
                 self.finalQuad.setShaderInput("vlparams", tcparam, config.decay, config.exposure, 0.0)
                 self.finalQuad.setShaderInput("vlparams", tcparam, config.decay, config.exposure, 0.0)
 
 
-        if (changed == "AmbientOcclusion") or fullrebuild:
-            if ("AmbientOcclusion" in configuration):
+        if changed == "AmbientOcclusion" or fullrebuild:
+            if "AmbientOcclusion" in configuration:
                 config = configuration["AmbientOcclusion"]
                 config = configuration["AmbientOcclusion"]
                 self.ssao[0].setShaderInput("params1", config.numsamples, -float(config.amount) / config.numsamples, config.radius, 0)
                 self.ssao[0].setShaderInput("params1", config.numsamples, -float(config.amount) / config.numsamples, config.radius, 0)
                 self.ssao[0].setShaderInput("params2", config.strength, config.falloff, 0, 0)
                 self.ssao[0].setShaderInput("params2", config.strength, config.falloff, 0, 0)
 
 
-        if (changed == "ExposureAdjust") or fullrebuild:
-            if ("ExposureAdjust" in configuration):
+        if changed == "ExposureAdjust" or fullrebuild:
+            if "ExposureAdjust" in configuration:
                 stops = configuration["ExposureAdjust"]
                 stops = configuration["ExposureAdjust"]
                 self.finalQuad.setShaderInput("exposure", 2 ** stops)
                 self.finalQuad.setShaderInput("exposure", 2 ** stops)
 
 
@@ -441,11 +441,11 @@ class CommonFilters:
             casterpos = LPoint2()
             casterpos = LPoint2()
             self.manager.camera.node().getLens().project(caster.getPos(self.manager.camera), casterpos)
             self.manager.camera.node().getLens().project(caster.getPos(self.manager.camera), casterpos)
             self.finalQuad.setShaderInput("casterpos", LVecBase4(casterpos.getX() * 0.5 + 0.5, (casterpos.getY() * 0.5 + 0.5), 0, 0))
             self.finalQuad.setShaderInput("casterpos", LVecBase4(casterpos.getX() * 0.5 + 0.5, (casterpos.getY() * 0.5 + 0.5), 0, 0))
-        if task != None:
+        if task is not None:
             return task.cont
             return task.cont
 
 
     def setCartoonInk(self, separation=1, color=(0, 0, 0, 1)):
     def setCartoonInk(self, separation=1, color=(0, 0, 0, 1)):
-        fullrebuild = (("CartoonInk" in self.configuration) == False)
+        fullrebuild = ("CartoonInk" not in self.configuration)
         newconfig = FilterConfig()
         newconfig = FilterConfig()
         newconfig.separation = separation
         newconfig.separation = separation
         newconfig.color = color
         newconfig.color = color
@@ -453,24 +453,30 @@ class CommonFilters:
         return self.reconfigure(fullrebuild, "CartoonInk")
         return self.reconfigure(fullrebuild, "CartoonInk")
 
 
     def delCartoonInk(self):
     def delCartoonInk(self):
-        if ("CartoonInk" in self.configuration):
+        if "CartoonInk" in self.configuration:
             del self.configuration["CartoonInk"]
             del self.configuration["CartoonInk"]
             return self.reconfigure(True, "CartoonInk")
             return self.reconfigure(True, "CartoonInk")
         return True
         return True
 
 
     def setBloom(self, blend=(0.3,0.4,0.3,0.0), mintrigger=0.6, maxtrigger=1.0, desat=0.6, intensity=1.0, size="medium"):
     def setBloom(self, blend=(0.3,0.4,0.3,0.0), mintrigger=0.6, maxtrigger=1.0, desat=0.6, intensity=1.0, size="medium"):
-        if   (size==0): size="off"
-        elif (size==1): size="small"
-        elif (size==2): size="medium"
-        elif (size==3): size="large"
-        if (size=="off"):
+        if size == 0 or size == "off":
             self.delBloom()
             self.delBloom()
             return
             return
-        if (maxtrigger==None): maxtrigger=mintrigger+0.8
+        elif size == 1:
+            size = "small"
+        elif size == 2:
+            size = "medium"
+        elif size == 3:
+            size = "large"
+
+        if maxtrigger is None:
+            maxtrigger = mintrigger + 0.8
+
         oldconfig = self.configuration.get("Bloom", None)
         oldconfig = self.configuration.get("Bloom", None)
         fullrebuild = True
         fullrebuild = True
-        if (oldconfig) and (oldconfig.size == size):
+        if oldconfig and oldconfig.size == size:
             fullrebuild = False
             fullrebuild = False
+
         newconfig = FilterConfig()
         newconfig = FilterConfig()
         (newconfig.blendx, newconfig.blendy, newconfig.blendz, newconfig.blendw) = blend
         (newconfig.blendx, newconfig.blendy, newconfig.blendz, newconfig.blendw) = blend
         newconfig.maxtrigger = maxtrigger
         newconfig.maxtrigger = maxtrigger
@@ -482,40 +488,40 @@ class CommonFilters:
         return self.reconfigure(fullrebuild, "Bloom")
         return self.reconfigure(fullrebuild, "Bloom")
 
 
     def delBloom(self):
     def delBloom(self):
-        if ("Bloom" in self.configuration):
+        if "Bloom" in self.configuration:
             del self.configuration["Bloom"]
             del self.configuration["Bloom"]
             return self.reconfigure(True, "Bloom")
             return self.reconfigure(True, "Bloom")
         return True
         return True
 
 
     def setHalfPixelShift(self):
     def setHalfPixelShift(self):
-        fullrebuild = (("HalfPixelShift" in self.configuration) == False)
+        fullrebuild = ("HalfPixelShift" not in self.configuration)
         self.configuration["HalfPixelShift"] = 1
         self.configuration["HalfPixelShift"] = 1
         return self.reconfigure(fullrebuild, "HalfPixelShift")
         return self.reconfigure(fullrebuild, "HalfPixelShift")
 
 
     def delHalfPixelShift(self):
     def delHalfPixelShift(self):
-        if ("HalfPixelShift" in self.configuration):
+        if "HalfPixelShift" in self.configuration:
             del self.configuration["HalfPixelShift"]
             del self.configuration["HalfPixelShift"]
             return self.reconfigure(True, "HalfPixelShift")
             return self.reconfigure(True, "HalfPixelShift")
         return True
         return True
 
 
     def setViewGlow(self):
     def setViewGlow(self):
-        fullrebuild = (("ViewGlow" in self.configuration) == False)
+        fullrebuild = ("ViewGlow" not in self.configuration)
         self.configuration["ViewGlow"] = 1
         self.configuration["ViewGlow"] = 1
         return self.reconfigure(fullrebuild, "ViewGlow")
         return self.reconfigure(fullrebuild, "ViewGlow")
 
 
     def delViewGlow(self):
     def delViewGlow(self):
-        if ("ViewGlow" in self.configuration):
+        if "ViewGlow" in self.configuration:
             del self.configuration["ViewGlow"]
             del self.configuration["ViewGlow"]
             return self.reconfigure(True, "ViewGlow")
             return self.reconfigure(True, "ViewGlow")
         return True
         return True
 
 
     def setInverted(self):
     def setInverted(self):
-        fullrebuild = (("Inverted" in self.configuration) == False)
+        fullrebuild = ("Inverted" not in self.configuration)
         self.configuration["Inverted"] = 1
         self.configuration["Inverted"] = 1
         return self.reconfigure(fullrebuild, "Inverted")
         return self.reconfigure(fullrebuild, "Inverted")
 
 
     def delInverted(self):
     def delInverted(self):
-        if ("Inverted" in self.configuration):
+        if "Inverted" in self.configuration:
             del self.configuration["Inverted"]
             del self.configuration["Inverted"]
             return self.reconfigure(True, "Inverted")
             return self.reconfigure(True, "Inverted")
         return True
         return True
@@ -523,7 +529,7 @@ class CommonFilters:
     def setVolumetricLighting(self, caster, numsamples = 32, density = 5.0, decay = 0.1, exposure = 0.1, source = "color"):
     def setVolumetricLighting(self, caster, numsamples = 32, density = 5.0, decay = 0.1, exposure = 0.1, source = "color"):
         oldconfig = self.configuration.get("VolumetricLighting", None)
         oldconfig = self.configuration.get("VolumetricLighting", None)
         fullrebuild = True
         fullrebuild = True
-        if (oldconfig) and (oldconfig.source == source) and (oldconfig.numsamples == int(numsamples)):
+        if oldconfig and oldconfig.source == source and oldconfig.numsamples == int(numsamples):
             fullrebuild = False
             fullrebuild = False
         newconfig = FilterConfig()
         newconfig = FilterConfig()
         newconfig.caster = caster
         newconfig.caster = caster
@@ -536,7 +542,7 @@ class CommonFilters:
         return self.reconfigure(fullrebuild, "VolumetricLighting")
         return self.reconfigure(fullrebuild, "VolumetricLighting")
 
 
     def delVolumetricLighting(self):
     def delVolumetricLighting(self):
-        if ("VolumetricLighting" in self.configuration):
+        if "VolumetricLighting" in self.configuration:
             del self.configuration["VolumetricLighting"]
             del self.configuration["VolumetricLighting"]
             return self.reconfigure(True, "VolumetricLighting")
             return self.reconfigure(True, "VolumetricLighting")
         return True
         return True
@@ -544,20 +550,20 @@ class CommonFilters:
     def setBlurSharpen(self, amount=0.0):
     def setBlurSharpen(self, amount=0.0):
         """Enables the blur/sharpen filter. If the 'amount' parameter is 1.0, it will not have effect.
         """Enables the blur/sharpen filter. If the 'amount' parameter is 1.0, it will not have effect.
         A value of 0.0 means fully blurred, and a value higher than 1.0 sharpens the image."""
         A value of 0.0 means fully blurred, and a value higher than 1.0 sharpens the image."""
-        fullrebuild = (("BlurSharpen" in self.configuration) == False)
+        fullrebuild = ("BlurSharpen" not in self.configuration)
         self.configuration["BlurSharpen"] = amount
         self.configuration["BlurSharpen"] = amount
         return self.reconfigure(fullrebuild, "BlurSharpen")
         return self.reconfigure(fullrebuild, "BlurSharpen")
 
 
     def delBlurSharpen(self):
     def delBlurSharpen(self):
-        if ("BlurSharpen" in self.configuration):
+        if "BlurSharpen" in self.configuration:
             del self.configuration["BlurSharpen"]
             del self.configuration["BlurSharpen"]
             return self.reconfigure(True, "BlurSharpen")
             return self.reconfigure(True, "BlurSharpen")
         return True
         return True
 
 
     def setAmbientOcclusion(self, numsamples = 16, radius = 0.05, amount = 2.0, strength = 0.01, falloff = 0.000002):
     def setAmbientOcclusion(self, numsamples = 16, radius = 0.05, amount = 2.0, strength = 0.01, falloff = 0.000002):
-        fullrebuild = (("AmbientOcclusion" in self.configuration) == False)
+        fullrebuild = ("AmbientOcclusion" not in self.configuration)
 
 
-        if (not fullrebuild):
+        if not fullrebuild:
             fullrebuild = (numsamples != self.configuration["AmbientOcclusion"].numsamples)
             fullrebuild = (numsamples != self.configuration["AmbientOcclusion"].numsamples)
 
 
         newconfig = FilterConfig()
         newconfig = FilterConfig()
@@ -570,7 +576,7 @@ class CommonFilters:
         return self.reconfigure(fullrebuild, "AmbientOcclusion")
         return self.reconfigure(fullrebuild, "AmbientOcclusion")
 
 
     def delAmbientOcclusion(self):
     def delAmbientOcclusion(self):
-        if ("AmbientOcclusion" in self.configuration):
+        if "AmbientOcclusion" in self.configuration:
             del self.configuration["AmbientOcclusion"]
             del self.configuration["AmbientOcclusion"]
             return self.reconfigure(True, "AmbientOcclusion")
             return self.reconfigure(True, "AmbientOcclusion")
         return True
         return True
@@ -584,7 +590,7 @@ class CommonFilters:
         return True
         return True
 
 
     def delGammaAdjust(self):
     def delGammaAdjust(self):
-        if ("GammaAdjust" in self.configuration):
+        if "GammaAdjust" in self.configuration:
             old_gamma = self.configuration["GammaAdjust"]
             old_gamma = self.configuration["GammaAdjust"]
             del self.configuration["GammaAdjust"]
             del self.configuration["GammaAdjust"]
             return self.reconfigure((old_gamma != 1.0), "GammaAdjust")
             return self.reconfigure((old_gamma != 1.0), "GammaAdjust")
@@ -610,7 +616,7 @@ class CommonFilters:
 
 
     def delSrgbEncode(self):
     def delSrgbEncode(self):
         """ Reverses the effects of setSrgbEncode. """
         """ Reverses the effects of setSrgbEncode. """
-        if ("SrgbEncode" in self.configuration):
+        if "SrgbEncode" in self.configuration:
             old_enable = self.configuration["SrgbEncode"]
             old_enable = self.configuration["SrgbEncode"]
             del self.configuration["SrgbEncode"]
             del self.configuration["SrgbEncode"]
             return self.reconfigure(old_enable, "SrgbEncode")
             return self.reconfigure(old_enable, "SrgbEncode")
@@ -632,7 +638,7 @@ class CommonFilters:
         return self.reconfigure(fullrebuild, "HighDynamicRange")
         return self.reconfigure(fullrebuild, "HighDynamicRange")
 
 
     def delHighDynamicRange(self):
     def delHighDynamicRange(self):
-        if ("HighDynamicRange" in self.configuration):
+        if "HighDynamicRange" in self.configuration:
             del self.configuration["HighDynamicRange"]
             del self.configuration["HighDynamicRange"]
             return self.reconfigure(True, "HighDynamicRange")
             return self.reconfigure(True, "HighDynamicRange")
         return True
         return True
@@ -652,7 +658,7 @@ class CommonFilters:
         return True
         return True
 
 
     def delExposureAdjust(self):
     def delExposureAdjust(self):
-        if ("ExposureAdjust" in self.configuration):
+        if "ExposureAdjust" in self.configuration:
             del self.configuration["ExposureAdjust"]
             del self.configuration["ExposureAdjust"]
             return self.reconfigure(True, "ExposureAdjust")
             return self.reconfigure(True, "ExposureAdjust")
         return True
         return True

+ 24 - 23
direct/src/filter/FilterManager.py

@@ -56,7 +56,7 @@ class FilterManager(DirectObject):
 
 
         if region is None:
         if region is None:
             self.notify.error('Could not find appropriate DisplayRegion to filter')
             self.notify.error('Could not find appropriate DisplayRegion to filter')
-            return False
+            return
 
 
         # Instance Variables.
         # Instance Variables.
 
 
@@ -78,13 +78,13 @@ class FilterManager(DirectObject):
         self.accept("window-event", self.windowEvent)
         self.accept("window-event", self.windowEvent)
 
 
 
 
-    def getClears(self,region):
+    def getClears(self, region):
         clears = []
         clears = []
         for i in range(GraphicsOutput.RTPCOUNT):
         for i in range(GraphicsOutput.RTPCOUNT):
             clears.append((region.getClearActive(i), region.getClearValue(i)))
             clears.append((region.getClearActive(i), region.getClearValue(i)))
         return clears
         return clears
 
 
-    def setClears(self,region,clears):
+    def setClears(self, region, clears):
         for i in range(GraphicsOutput.RTPCOUNT):
         for i in range(GraphicsOutput.RTPCOUNT):
             (active, value) = clears[i]
             (active, value) = clears[i]
             region.setClearActive(i, active)
             region.setClearActive(i, active)
@@ -94,7 +94,7 @@ class FilterManager(DirectObject):
         clears = []
         clears = []
         for i in range(GraphicsOutput.RTPCOUNT):
         for i in range(GraphicsOutput.RTPCOUNT):
             (active, value) = clears0[i]
             (active, value) = clears0[i]
-            if (active == 0):
+            if not active:
                 (active, value) = clears1[i]
                 (active, value) = clears1[i]
             region.setClearActive(i, active)
             region.setClearActive(i, active)
             region.setClearValue(i, value)
             region.setClearValue(i, value)
@@ -107,13 +107,14 @@ class FilterManager(DirectObject):
                 (self.region.getTop()    == 1.0))
                 (self.region.getTop()    == 1.0))
 
 
     def getScaledSize(self, mul, div, align):
     def getScaledSize(self, mul, div, align):
-
         """ Calculate the size of the desired window. Not public. """
         """ Calculate the size of the desired window. Not public. """
 
 
         winx = self.forcex
         winx = self.forcex
         winy = self.forcey
         winy = self.forcey
-        if winx == 0: winx = self.win.getXSize()
-        if winy == 0: winy = self.win.getYSize()
+        if winx == 0:
+            winx = self.win.getXSize()
+        if winy == 0:
+            winy = self.win.getYSize()
 
 
         if div != 1:
         if div != 1:
             winx = ((winx+align-1) // align) * align
             winx = ((winx+align-1) // align) * align
@@ -168,7 +169,7 @@ class FilterManager(DirectObject):
         scene.  It is assumed that the user will replace the shader
         scene.  It is assumed that the user will replace the shader
         on the quad with a more interesting filter. """
         on the quad with a more interesting filter. """
 
 
-        if (textures):
+        if textures:
             colortex = textures.get("color", None)
             colortex = textures.get("color", None)
             depthtex = textures.get("depth", None)
             depthtex = textures.get("depth", None)
             auxtex = textures.get("aux", None)
             auxtex = textures.get("aux", None)
@@ -178,7 +179,7 @@ class FilterManager(DirectObject):
             auxtex0 = auxtex
             auxtex0 = auxtex
             auxtex1 = None
             auxtex1 = None
 
 
-        if (colortex == None):
+        if colortex is None:
             colortex = Texture("filter-base-color")
             colortex = Texture("filter-base-color")
             colortex.setWrapU(Texture.WMClamp)
             colortex.setWrapU(Texture.WMClamp)
             colortex.setWrapV(Texture.WMClamp)
             colortex.setWrapV(Texture.WMClamp)
@@ -193,7 +194,7 @@ class FilterManager(DirectObject):
         else:
         else:
             buffer = self.createBuffer("filter-base", winx, winy, texgroup)
             buffer = self.createBuffer("filter-base", winx, winy, texgroup)
 
 
-        if (buffer == None):
+        if buffer is None:
             return None
             return None
 
 
         cm = CardMaker("filter-base-quad")
         cm = CardMaker("filter-base-quad")
@@ -208,7 +209,7 @@ class FilterManager(DirectObject):
         cs.setState(self.camstate)
         cs.setState(self.camstate)
         # Do we really need to turn on the Shader Generator?
         # Do we really need to turn on the Shader Generator?
         #cs.setShaderAuto()
         #cs.setShaderAuto()
-        if (auxbits):
+        if auxbits:
             cs.setAttrib(AuxBitplaneAttrib.make(auxbits))
             cs.setAttrib(AuxBitplaneAttrib.make(auxbits))
         if clamping is False:
         if clamping is False:
             # Disables clamping in the shader generator.
             # Disables clamping in the shader generator.
@@ -226,13 +227,13 @@ class FilterManager(DirectObject):
         self.region.setCamera(quadcam)
         self.region.setCamera(quadcam)
 
 
         self.setStackedClears(buffer, self.rclears, self.wclears)
         self.setStackedClears(buffer, self.rclears, self.wclears)
-        if (auxtex0):
+        if auxtex0:
             buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1)
             buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1)
             buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0))
             buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0))
-        if (auxtex1):
+        if auxtex1:
             buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1)
             buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1)
         self.region.disableClears()
         self.region.disableClears()
-        if (self.isFullscreen()):
+        if self.isFullscreen():
             self.win.disableClears()
             self.win.disableClears()
 
 
         dr = buffer.makeDisplayRegion()
         dr = buffer.makeDisplayRegion()
@@ -257,14 +258,14 @@ class FilterManager(DirectObject):
 
 
         winx, winy = self.getScaledSize(mul, div, align)
         winx, winy = self.getScaledSize(mul, div, align)
 
 
-        depthbits = bool(depthtex != None)
+        depthbits = int(depthtex is not None)
 
 
         if fbprops is not None:
         if fbprops is not None:
             buffer = self.createBuffer(name, winx, winy, texgroup, depthbits, fbprops=fbprops)
             buffer = self.createBuffer(name, winx, winy, texgroup, depthbits, fbprops=fbprops)
         else:
         else:
             buffer = self.createBuffer(name, winx, winy, texgroup, depthbits)
             buffer = self.createBuffer(name, winx, winy, texgroup, depthbits)
 
 
-        if (buffer == None):
+        if buffer is None:
             return None
             return None
 
 
         cm = CardMaker("filter-stage-quad")
         cm = CardMaker("filter-stage-quad")
@@ -313,23 +314,23 @@ class FilterManager(DirectObject):
             props.addProperties(fbprops)
             props.addProperties(fbprops)
 
 
         depthtex, colortex, auxtex0, auxtex1 = texgroup
         depthtex, colortex, auxtex0, auxtex1 = texgroup
-        if (auxtex0 != None):
+        if auxtex0 is not None:
             props.setAuxRgba(1)
             props.setAuxRgba(1)
-        if (auxtex1 != None):
+        if auxtex1 is not None:
             props.setAuxRgba(2)
             props.setAuxRgba(2)
         buffer=base.graphicsEngine.makeOutput(
         buffer=base.graphicsEngine.makeOutput(
             self.win.getPipe(), name, -1,
             self.win.getPipe(), name, -1,
             props, winprops, GraphicsPipe.BFRefuseWindow | GraphicsPipe.BFResizeable,
             props, winprops, GraphicsPipe.BFRefuseWindow | GraphicsPipe.BFResizeable,
             self.win.getGsg(), self.win)
             self.win.getGsg(), self.win)
-        if (buffer == None):
+        if buffer is None:
             return buffer
             return buffer
-        if (depthtex):
+        if depthtex:
             buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth)
             buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth)
-        if (colortex):
+        if colortex:
             buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor)
             buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor)
-        if (auxtex0):
+        if auxtex0:
             buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0)
             buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0)
-        if (auxtex1):
+        if auxtex1:
             buffer.addRenderTexture(auxtex1, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba1)
             buffer.addRenderTexture(auxtex1, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba1)
         buffer.setSort(self.nextsort)
         buffer.setSort(self.nextsort)
         buffer.disableClears()
         buffer.disableClears()

+ 13 - 20
direct/src/fsm/ClassicFSM.py

@@ -9,6 +9,7 @@ __all__ = ['ClassicFSM']
 
 
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.showbase.DirectObject import DirectObject
 from direct.showbase.DirectObject import DirectObject
+from direct.showbase.MessengerGlobal import messenger
 import weakref
 import weakref
 
 
 if __debug__:
 if __debug__:
@@ -83,7 +84,7 @@ class ClassicFSM(DirectObject):
         self.__internalStateInFlux = 0
         self.__internalStateInFlux = 0
         if __debug__:
         if __debug__:
             global _debugFsms
             global _debugFsms
-            _debugFsms[name]=weakref.ref(self)
+            _debugFsms[name] = weakref.ref(self)
 
 
     # I know this isn't how __repr__ is supposed to be used, but it
     # I know this isn't how __repr__ is supposed to be used, but it
     # is nice and convenient.
     # is nice and convenient.
@@ -107,7 +108,7 @@ class ClassicFSM(DirectObject):
         if self.__currentState == self.__initialState:
         if self.__currentState == self.__initialState:
             return
             return
 
 
-        assert self.__currentState == None
+        assert self.__currentState is None
         self.__internalStateInFlux = 1
         self.__internalStateInFlux = 1
         self.__enter(self.__initialState, argList)
         self.__enter(self.__initialState, argList)
         assert not self.__internalStateInFlux
         assert not self.__internalStateInFlux
@@ -115,7 +116,7 @@ class ClassicFSM(DirectObject):
     # setters and getters
     # setters and getters
 
 
     def getName(self):
     def getName(self):
-        return(self.__name)
+        return self.__name
 
 
     def setName(self, name):
     def setName(self, name):
         self.__name = name
         self.__name = name
@@ -134,13 +135,13 @@ class ClassicFSM(DirectObject):
         self.__states[state.getName()] = state
         self.__states[state.getName()] = state
 
 
     def getInitialState(self):
     def getInitialState(self):
-        return(self.__initialState)
+        return self.__initialState
 
 
     def setInitialState(self, initialStateName):
     def setInitialState(self, initialStateName):
         self.__initialState = self.getStateNamed(initialStateName)
         self.__initialState = self.getStateNamed(initialStateName)
 
 
     def getFinalState(self):
     def getFinalState(self):
-        return(self.__finalState)
+        return self.__finalState
 
 
     def setFinalState(self, finalStateName):
     def setFinalState(self, finalStateName):
         self.__finalState = self.getStateNamed(finalStateName)
         self.__finalState = self.getStateNamed(finalStateName)
@@ -149,7 +150,7 @@ class ClassicFSM(DirectObject):
         self.request(self.getFinalState().getName())
         self.request(self.getFinalState().getName())
 
 
     def getCurrentState(self):
     def getCurrentState(self):
-        return(self.__currentState)
+        return self.__currentState
 
 
 
 
     # lookup funcs
     # lookup funcs
@@ -198,7 +199,7 @@ class ClassicFSM(DirectObject):
         """
         """
         assert self.__internalStateInFlux
         assert self.__internalStateInFlux
         stateName = aState.getName()
         stateName = aState.getName()
-        if (stateName in self.__states):
+        if stateName in self.__states:
             assert ClassicFSM.notify.debug("[%s]: entering %s" % (self.__name, stateName))
             assert ClassicFSM.notify.debug("[%s]: entering %s" % (self.__name, stateName))
             self.__currentState = aState
             self.__currentState = aState
             # Only send the state change event if we are inspecting it
             # Only send the state change event if we are inspecting it
@@ -257,7 +258,7 @@ class ClassicFSM(DirectObject):
             aState = aStateName
             aState = aStateName
             aStateName = aState.getName()
             aStateName = aState.getName()
 
 
-        if aState == None:
+        if aState is None:
             ClassicFSM.notify.error("[%s]: request: %s, no such state" %
             ClassicFSM.notify.error("[%s]: request: %s, no such state" %
                              (self.__name, aStateName))
                              (self.__name, aStateName))
 
 
@@ -282,8 +283,8 @@ class ClassicFSM(DirectObject):
                               exitArgList)
                               exitArgList)
             return 1
             return 1
         # We can implicitly always transition to our final state.
         # We can implicitly always transition to our final state.
-        elif (aStateName == self.__finalState.getName()):
-            if (self.__currentState == self.__finalState):
+        elif aStateName == self.__finalState.getName():
+            if self.__currentState == self.__finalState:
                 # Do not do the transition if we are already in the
                 # Do not do the transition if we are already in the
                 # final state
                 # final state
                 assert ClassicFSM.notify.debug(
                 assert ClassicFSM.notify.debug(
@@ -300,7 +301,7 @@ class ClassicFSM(DirectObject):
                                   exitArgList)
                                   exitArgList)
                 return 1
                 return 1
         # are we already in this state?
         # are we already in this state?
-        elif (aStateName == self.__currentState.getName()):
+        elif aStateName == self.__currentState.getName():
             assert ClassicFSM.notify.debug(
             assert ClassicFSM.notify.debug(
                 "[%s]: already in state %s and no self transition" %
                 "[%s]: already in state %s and no self transition" %
                 (self.__name, aStateName))
                 (self.__name, aStateName))
@@ -348,7 +349,7 @@ class ClassicFSM(DirectObject):
             aState = aStateName
             aState = aStateName
             aStateName = aState.getName()
             aStateName = aState.getName()
 
 
-        if aState == None:
+        if aState is None:
             ClassicFSM.notify.error("[%s]: request: %s, no such state" %
             ClassicFSM.notify.error("[%s]: request: %s, no such state" %
                                 (self.__name, aStateName))
                                 (self.__name, aStateName))
 
 
@@ -375,11 +376,3 @@ class ClassicFSM(DirectObject):
 
 
     def isInternalStateInFlux(self):
     def isInternalStateInFlux(self):
         return self.__internalStateInFlux
         return self.__internalStateInFlux
-
-
-
-
-
-
-
-

+ 6 - 9
direct/src/fsm/FSM.py

@@ -9,8 +9,9 @@ __all__ = ['FSMException', 'FSM']
 
 
 
 
 from direct.showbase.DirectObject import DirectObject
 from direct.showbase.DirectObject import DirectObject
-from direct.directnotify import DirectNotifyGlobal
+from direct.showbase.MessengerGlobal import messenger
 from direct.showbase import PythonUtil
 from direct.showbase import PythonUtil
+from direct.directnotify import DirectNotifyGlobal
 from direct.stdpy.threading import RLock
 from direct.stdpy.threading import RLock
 
 
 
 
@@ -239,7 +240,7 @@ class FSM(DirectObject):
     def isInTransition(self):
     def isInTransition(self):
         self.fsmLock.acquire()
         self.fsmLock.acquire()
         try:
         try:
-            return self.state == None
+            return self.state is None
         finally:
         finally:
             self.fsmLock.release()
             self.fsmLock.release()
 
 
@@ -339,12 +340,10 @@ class FSM(DirectObject):
     def defaultEnter(self, *args):
     def defaultEnter(self, *args):
         """ This is the default function that is called if there is no
         """ This is the default function that is called if there is no
         enterState() method for a particular state name. """
         enterState() method for a particular state name. """
-        pass
 
 
     def defaultExit(self):
     def defaultExit(self):
         """ This is the default function that is called if there is no
         """ This is the default function that is called if there is no
         exitState() method for a particular state name. """
         exitState() method for a particular state name. """
-        pass
 
 
     def defaultFilter(self, request, args):
     def defaultFilter(self, request, args):
         """This is the function that is called if there is no
         """This is the function that is called if there is no
@@ -485,8 +484,6 @@ class FSM(DirectObject):
             if not self.__callFromToFunc(self.oldState, self.newState, *args):
             if not self.__callFromToFunc(self.oldState, self.newState, *args):
                 self.__callExitFunc(self.oldState)
                 self.__callExitFunc(self.oldState)
                 self.__callEnterFunc(self.newState, *args)
                 self.__callEnterFunc(self.newState, *args)
-                pass
-            pass
         except:
         except:
             # If we got an exception during the enter or exit methods,
             # If we got an exception during the enter or exit methods,
             # go directly to state "InternalError" and raise up the
             # go directly to state "InternalError" and raise up the
@@ -513,7 +510,7 @@ class FSM(DirectObject):
     def __callEnterFunc(self, name, *args):
     def __callEnterFunc(self, name, *args):
         # Calls the appropriate enter function when transitioning into
         # Calls the appropriate enter function when transitioning into
         # a new state, if it exists.
         # a new state, if it exists.
-        assert self.state == None and self.newState == name
+        assert self.state is None and self.newState == name
 
 
         func = getattr(self, "enter" + name, None)
         func = getattr(self, "enter" + name, None)
         if not func:
         if not func:
@@ -525,7 +522,7 @@ class FSM(DirectObject):
     def __callFromToFunc(self, oldState, newState, *args):
     def __callFromToFunc(self, oldState, newState, *args):
         # Calls the appropriate fromTo function when transitioning into
         # Calls the appropriate fromTo function when transitioning into
         # a new state, if it exists.
         # a new state, if it exists.
-        assert self.state == None and self.oldState == oldState and self.newState == newState
+        assert self.state is None and self.oldState == oldState and self.newState == newState
 
 
         func = getattr(self, "from%sTo%s" % (oldState,newState), None)
         func = getattr(self, "from%sTo%s" % (oldState,newState), None)
         if func:
         if func:
@@ -536,7 +533,7 @@ class FSM(DirectObject):
     def __callExitFunc(self, name):
     def __callExitFunc(self, name):
         # Calls the appropriate exit function when leaving a
         # Calls the appropriate exit function when leaving a
         # state, if it exists.
         # state, if it exists.
-        assert self.state == None and self.oldState == name
+        assert self.state is None and self.oldState == name
 
 
         func = getattr(self, "exit" + name, None)
         func = getattr(self, "exit" + name, None)
         if not func:
         if not func:

+ 0 - 1
direct/src/fsm/FourState.py

@@ -212,4 +212,3 @@ class FourState:
             """for debugging"""
             """for debugging"""
             return self.notify.debug("%d (%d) %s"%(
             return self.notify.debug("%d (%d) %s"%(
                     id(self), self.stateIndex==4, message))
                     id(self), self.stateIndex==4, message))
-

+ 1 - 1
direct/src/fsm/FourStateAI.py

@@ -7,6 +7,7 @@ from direct.directnotify import DirectNotifyGlobal
 from . import ClassicFSM
 from . import ClassicFSM
 from . import State
 from . import State
 from direct.task import Task
 from direct.task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 
 
 
 
 class FourStateAI:
 class FourStateAI:
@@ -268,4 +269,3 @@ class FourStateAI:
             """for debugging"""
             """for debugging"""
             return self.notify.debug("%d (%d) %s"%(
             return self.notify.debug("%d (%d) %s"%(
                     id(self), self.stateIndex==4, message))
                     id(self), self.stateIndex==4, message))
-

+ 1 - 0
direct/src/fsm/SampleFSM.py

@@ -4,6 +4,7 @@ __all__ = ['ClassicStyle', 'NewStyle', 'ToonEyes']
 
 
 from . import FSM
 from . import FSM
 from direct.task import Task
 from direct.task import Task
+from direct.task.TaskManagerGlobal import taskMgr
 
 
 
 
 class ClassicStyle(FSM.FSM):
 class ClassicStyle(FSM.FSM):

+ 13 - 13
direct/src/fsm/State.py

@@ -21,21 +21,21 @@ class State(DirectObject):
         States = weakref.WeakKeyDictionary()
         States = weakref.WeakKeyDictionary()
 
 
         @classmethod
         @classmethod
-        def replaceMethod(self, oldFunction, newFunction):
+        def replaceMethod(cls, oldFunction, newFunction):
             import types
             import types
             count = 0
             count = 0
-            for state in self.States:
+            for state in cls.States:
                 # Note: you can only replace methods currently
                 # Note: you can only replace methods currently
                 enterFunc = state.getEnterFunc()
                 enterFunc = state.getEnterFunc()
                 exitFunc = state.getExitFunc()
                 exitFunc = state.getExitFunc()
                 # print 'testing: ', state, enterFunc, exitFunc, oldFunction
                 # print 'testing: ', state, enterFunc, exitFunc, oldFunction
-                if type(enterFunc) == types.MethodType:
+                if isinstance(enterFunc, types.MethodType):
                     if enterFunc.__func__ == oldFunction:
                     if enterFunc.__func__ == oldFunction:
                         # print 'found: ', enterFunc, oldFunction
                         # print 'found: ', enterFunc, oldFunction
                         state.setEnterFunc(types.MethodType(newFunction,
                         state.setEnterFunc(types.MethodType(newFunction,
                                                             enterFunc.__self__))
                                                             enterFunc.__self__))
                         count += 1
                         count += 1
-                if type(exitFunc) == types.MethodType:
+                if isinstance(exitFunc, types.MethodType):
                     if exitFunc.__func__ == oldFunction:
                     if exitFunc.__func__ == oldFunction:
                         # print 'found: ', exitFunc, oldFunction
                         # print 'found: ', exitFunc, oldFunction
                         state.setExitFunc(types.MethodType(newFunction,
                         state.setExitFunc(types.MethodType(newFunction,
@@ -62,19 +62,19 @@ class State(DirectObject):
     # setters and getters
     # setters and getters
 
 
     def getName(self):
     def getName(self):
-        return(self.__name)
+        return self.__name
 
 
     def setName(self, stateName):
     def setName(self, stateName):
         self.__name = stateName
         self.__name = stateName
 
 
     def getEnterFunc(self):
     def getEnterFunc(self):
-        return(self.__enterFunc)
+        return self.__enterFunc
 
 
     def setEnterFunc(self, stateEnterFunc):
     def setEnterFunc(self, stateEnterFunc):
         self.__enterFunc = stateEnterFunc
         self.__enterFunc = stateEnterFunc
 
 
     def getExitFunc(self):
     def getExitFunc(self):
-        return(self.__exitFunc)
+        return self.__exitFunc
 
 
     def setExitFunc(self, stateExitFunc):
     def setExitFunc(self, stateExitFunc):
         self.__exitFunc = stateExitFunc
         self.__exitFunc = stateExitFunc
@@ -99,9 +99,9 @@ class State(DirectObject):
             return 1
             return 1
 
 
         # if we're given a state object, get its name instead
         # if we're given a state object, get its name instead
-        if type(otherState) != type(''):
+        if not isinstance(otherState, str):
             otherState = otherState.getName()
             otherState = otherState.getName()
-        return (otherState in self.__transitions)
+        return otherState in self.__transitions
 
 
     def setTransitions(self, stateTransitions):
     def setTransitions(self, stateTransitions):
         """setTransitions(self, string[])"""
         """setTransitions(self, string[])"""
@@ -119,7 +119,7 @@ class State(DirectObject):
     if __debug__:
     if __debug__:
         def getInspectorPos(self):
         def getInspectorPos(self):
             """getInspectorPos(self)"""
             """getInspectorPos(self)"""
-            return(self.__inspectorPos)
+            return self.__inspectorPos
 
 
         def setInspectorPos(self, inspectorPos):
         def setInspectorPos(self, inspectorPos):
             """setInspectorPos(self, [x, y])"""
             """setInspectorPos(self, [x, y])"""
@@ -131,7 +131,7 @@ class State(DirectObject):
         """
         """
         Return the list of child FSMs
         Return the list of child FSMs
         """
         """
-        return(self.__FSMList)
+        return self.__FSMList
 
 
     def setChildren(self, FSMList):
     def setChildren(self, FSMList):
         """setChildren(self, ClassicFSM[])
         """setChildren(self, ClassicFSM[])
@@ -196,7 +196,7 @@ class State(DirectObject):
         # state that is safe to enter
         # state that is safe to enter
         self.__enterChildren(argList)
         self.__enterChildren(argList)
 
 
-        if (self.__enterFunc != None):
+        if self.__enterFunc is not None:
             self.__enterFunc(*argList)
             self.__enterFunc(*argList)
 
 
     def exit(self, argList=[]):
     def exit(self, argList=[]):
@@ -207,7 +207,7 @@ class State(DirectObject):
         self.__exitChildren(argList)
         self.__exitChildren(argList)
 
 
         # call exit function if it exists
         # call exit function if it exists
-        if (self.__exitFunc != None):
+        if self.__exitFunc is not None:
             self.__exitFunc(*argList)
             self.__exitFunc(*argList)
 
 
     def __str__(self):
     def __str__(self):

+ 1 - 0
direct/src/fsm/StatePush.py

@@ -408,6 +408,7 @@ class AttrSetter(StateChangeNode):
         StateChangeNode._handleStateChange(self)
         StateChangeNode._handleStateChange(self)
 
 
 if __debug__:
 if __debug__:
+    from direct.showbase.PythonUtil import ScratchPad
     o = ScratchPad()
     o = ScratchPad()
     svar = StateVar(0)
     svar = StateVar(0)
     aset = AttrSetter(svar, o, 'testAttr')
     aset = AttrSetter(svar, o, 'testAttr')

+ 0 - 2
direct/src/gui/DirectButton.py

@@ -126,5 +126,3 @@ class DirectButton(DirectFrame):
             self.guiItem.setSound(DGG.ENTER + self.guiId, rolloverSound)
             self.guiItem.setSound(DGG.ENTER + self.guiId, rolloverSound)
         else:
         else:
             self.guiItem.clearSound(DGG.ENTER + self.guiId)
             self.guiItem.clearSound(DGG.ENTER + self.guiId)
-
-

+ 0 - 1
direct/src/gui/DirectCheckBox.py

@@ -56,4 +56,3 @@ class DirectCheckBox(DirectButton):
         if self['command']:
         if self['command']:
             # Pass any extra args to command
             # Pass any extra args to command
             self['command'](*[self['isChecked']] + self['extraArgs'])
             self['command'](*[self['isChecked']] + self['extraArgs'])
-

+ 6 - 13
direct/src/gui/DirectCheckButton.py

@@ -61,12 +61,12 @@ class DirectCheckButton(DirectButton):
         # Call option initialization functions
         # Call option initialization functions
         self.initialiseoptions(DirectCheckButton)
         self.initialiseoptions(DirectCheckButton)
         # After initialization with X giving it the correct size, put back space
         # After initialization with X giving it the correct size, put back space
-        if self['boxImage'] ==  None:
+        if self['boxImage'] is None:
             self.indicator['text'] = (' ', '*')
             self.indicator['text'] = (' ', '*')
             self.indicator['text_pos'] = (0, -.2)
             self.indicator['text_pos'] = (0, -.2)
         else:
         else:
             self.indicator['text'] = (' ', ' ')
             self.indicator['text'] = (' ', ' ')
-        if self['boxImageColor'] != None and self['boxImage'] !=  None:
+        if self['boxImageColor'] is not None and self['boxImage'] is not None:
             self.colors = [VBase4(0, 0, 0, 0), self['boxImageColor']]
             self.colors = [VBase4(0, 0, 0, 0), self['boxImageColor']]
             self.component('indicator')['image_color'] = VBase4(0, 0, 0, 0)
             self.component('indicator')['image_color'] = VBase4(0, 0, 0, 0)
 
 
@@ -84,7 +84,7 @@ class DirectCheckButton(DirectButton):
         else:
         else:
             # Use ready state to compute bounds
             # Use ready state to compute bounds
             frameType = self.frameStyle[0].getType()
             frameType = self.frameStyle[0].getType()
-            if fClearFrame and (frameType != PGFrameStyle.TNone):
+            if fClearFrame and frameType != PGFrameStyle.TNone:
                 self.frameStyle[0].setType(PGFrameStyle.TNone)
                 self.frameStyle[0].setType(PGFrameStyle.TNone)
                 self.guiItem.setFrameStyle(0, self.frameStyle[0])
                 self.guiItem.setFrameStyle(0, self.frameStyle[0])
                 # To force an update of the button
                 # To force an update of the button
@@ -92,7 +92,7 @@ class DirectCheckButton(DirectButton):
             # Clear out frame before computing bounds
             # Clear out frame before computing bounds
             self.getBounds()
             self.getBounds()
             # Restore frame style if necessary
             # Restore frame style if necessary
-            if (frameType != PGFrameStyle.TNone):
+            if frameType != PGFrameStyle.TNone:
                 self.frameStyle[0].setType(frameType)
                 self.frameStyle[0].setType(frameType)
                 self.guiItem.setFrameStyle(0, self.frameStyle[0])
                 self.guiItem.setFrameStyle(0, self.frameStyle[0])
 
 
@@ -170,7 +170,7 @@ class DirectCheckButton(DirectButton):
 
 
     def commandFunc(self, event):
     def commandFunc(self, event):
         self['indicatorValue'] = 1 - self['indicatorValue']
         self['indicatorValue'] = 1 - self['indicatorValue']
-        if self.colors != None:
+        if self.colors is not None:
             self.component('indicator')['image_color'] = self.colors[self['indicatorValue']]
             self.component('indicator')['image_color'] = self.colors[self['indicatorValue']]
 
 
         if self['command']:
         if self['command']:
@@ -179,12 +179,5 @@ class DirectCheckButton(DirectButton):
 
 
     def setIndicatorValue(self):
     def setIndicatorValue(self):
         self.component('indicator').guiItem.setState(self['indicatorValue'])
         self.component('indicator').guiItem.setState(self['indicatorValue'])
-        if self.colors != None:
+        if self.colors is not None:
             self.component('indicator')['image_color'] = self.colors[self['indicatorValue']]
             self.component('indicator')['image_color'] = self.colors[self['indicatorValue']]
-
-
-
-
-
-
-

Some files were not shown because too many files changed in this diff