From 40cc37e3da265592b2d8ef440a6d0aa55e643e39 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 11:56:02 +0000 Subject: [PATCH 01/37] fix terminal colouring when using Python 3 --- makepanda/makepandacore.py | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/makepanda/makepandacore.py b/makepanda/makepandacore.py index 82cd50122e..bb261e00ed 100644 --- a/makepanda/makepandacore.py +++ b/makepanda/makepandacore.py @@ -159,22 +159,30 @@ def DisableColors(): HAVE_COLORS = False def GetColor(color = None): - if not HAVE_COLORS: return "" - if color != None: color = color.lower() + if not HAVE_COLORS: + return "" + if color != None: + color = color.lower() + if (color == "blue"): - return curses.tparm(SETF, 1) + token = curses.tparm(SETF, 1) elif (color == "green"): - return curses.tparm(SETF, 2) + token = curses.tparm(SETF, 2) elif (color == "cyan"): - return curses.tparm(SETF, 3) + token = curses.tparm(SETF, 3) elif (color == "red"): - return curses.tparm(SETF, 4) + token = curses.tparm(SETF, 4) elif (color == "magenta"): - return curses.tparm(SETF, 5) + token = curses.tparm(SETF, 5) elif (color == "yellow"): - return curses.tparm(SETF, 6) + token = curses.tparm(SETF, 6) else: - return curses.tparm(curses.tigetstr("sgr0")) + token = curses.tparm(curses.tigetstr("sgr0")) + + if sys.version_info >= (3, 0): + return token.decode('ascii') + else: + return token def ColorText(color, text, reset=True): if reset is True: From 0046d259dcc7234c6faa2ca789f701c20a86a9cd Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 13:28:51 +0000 Subject: [PATCH 02/37] Eliminate unused HAVE_GETTIMEOFDAY which conflicts with Python's definition anyway. --- makepanda/makepanda.py | 1 - 1 file changed, 1 deletion(-) diff --git a/makepanda/makepanda.py b/makepanda/makepanda.py index 878584a1d0..a4ce357d8f 100755 --- a/makepanda/makepanda.py +++ b/makepanda/makepanda.py @@ -1883,7 +1883,6 @@ DTOOL_CONFIG=[ ("SIMPLE_STRUCT_POINTERS", '1', 'UNDEF'), ("HAVE_DINKUM", 'UNDEF', 'UNDEF'), ("HAVE_STL_HASH", 'UNDEF', 'UNDEF'), - ("HAVE_GETTIMEOFDAY", 'UNDEF', '1'), ("GETTIMEOFDAY_ONE_PARAM", 'UNDEF', 'UNDEF'), ("HAVE_GETOPT", 'UNDEF', '1'), ("HAVE_GETOPT_LONG_ONLY", 'UNDEF', '1'), From b686d371ca771347d021bdf6c891d5478f2c55ae Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 13:33:39 +0000 Subject: [PATCH 03/37] fix maya location on linux, fix dependency cache problems with Python 3 that forced a full rebuild every time --- makepanda/makepanda.py | 12 +++---- makepanda/makepandacore.py | 67 ++++++++++++++++++++------------------ 2 files changed, 42 insertions(+), 37 deletions(-) diff --git a/makepanda/makepanda.py b/makepanda/makepanda.py index a4ce357d8f..4622e48c02 100755 --- a/makepanda/makepanda.py +++ b/makepanda/makepanda.py @@ -2149,7 +2149,7 @@ def WriteConfigSettings(): speedtree_parameters["SPEEDTREE_BIN_DIR"] = (SDK["SPEEDTREE"] + "/Bin") conf = "/* prc_parameters.h. Generated automatically by makepanda.py */\n" - for key in prc_parameters.keys(): + for key in sorted(prc_parameters.keys()): if ((key == "DEFAULT_PRC_DIR") or (key[:4]=="PRC_")): val = OverrideValue(key, prc_parameters[key]) if (val == 'UNDEF'): conf = conf + "#undef " + key + "\n" @@ -2157,7 +2157,7 @@ def WriteConfigSettings(): ConditionalWriteFile(GetOutputDir() + '/include/prc_parameters.h', conf) conf = "/* dtool_config.h. Generated automatically by makepanda.py */\n" - for key in dtool_config.keys(): + for key in sorted(dtool_config.keys()): val = OverrideValue(key, dtool_config[key]) if (val == 'UNDEF'): conf = conf + "#undef " + key + "\n" else: conf = conf + "#define " + key + " " + val + "\n" @@ -2165,7 +2165,7 @@ def WriteConfigSettings(): if (RTDIST or RUNTIME): conf = "/* p3d_plugin_config.h. Generated automatically by makepanda.py */\n" - for key in plugin_config.keys(): + for key in sorted(plugin_config.keys()): val = plugin_config[key] if (val == 'UNDEF'): conf = conf + "#undef " + key + "\n" else: conf = conf + "#define " + key + " \"" + val.replace("\\", "\\\\") + "\"\n" @@ -2173,15 +2173,15 @@ def WriteConfigSettings(): if (PkgSkip("SPEEDTREE")==0): conf = "/* speedtree_parameters.h. Generated automatically by makepanda.py */\n" - for key in speedtree_parameters.keys(): + for key in sorted(speedtree_parameters.keys()): val = OverrideValue(key, speedtree_parameters[key]) if (val == 'UNDEF'): conf = conf + "#undef " + key + "\n" else: conf = conf + "#define " + key + " \"" + val.replace("\\", "\\\\") + "\"\n" ConditionalWriteFile(GetOutputDir() + '/include/speedtree_parameters.h', conf) for x in PkgListGet(): - if (PkgSkip(x)): ConditionalWriteFile(GetOutputDir() + '/tmp/dtool_have_'+x.lower()+'.dat',"0\n") - else: ConditionalWriteFile(GetOutputDir() + '/tmp/dtool_have_'+x.lower()+'.dat',"1\n") + if (PkgSkip(x)): ConditionalWriteFile(GetOutputDir() + '/tmp/dtool_have_'+x.lower()+'.dat', "0\n") + else: ConditionalWriteFile(GetOutputDir() + '/tmp/dtool_have_'+x.lower()+'.dat', "1\n") WriteConfigSettings() diff --git a/makepanda/makepandacore.py b/makepanda/makepandacore.py index bb261e00ed..7d11816d54 100644 --- a/makepanda/makepandacore.py +++ b/makepanda/makepandacore.py @@ -627,32 +627,34 @@ def ClearTimestamp(path): BUILTFROMCACHE = {} -def JustBuilt(files,others): - dates = [] +def JustBuilt(files, others): + dates = {} for file in files: del TIMESTAMPCACHE[file] - dates.append(GetTimestamp(file)) + dates[file] = GetTimestamp(file) for file in others: - dates.append(GetTimestamp(file)) - key = tuple(files) - BUILTFROMCACHE[key] = [others,dates] + dates[file] = GetTimestamp(file) -def NeedsBuild(files,others): - dates = [] - for file in files: - dates.append(GetTimestamp(file)) - if (not os.path.exists(file)): return 1 - for file in others: - dates.append(GetTimestamp(file)) key = tuple(files) - if (key in BUILTFROMCACHE): - if (BUILTFROMCACHE[key] == [others,dates]): - return 0 - else: - oldothers = BUILTFROMCACHE[key][0] - if (oldothers != others and VERBOSE): - print("%sWARNING:%s file dependencies changed: %s%s%s" % (GetColor("red"), GetColor(), GetColor("green"), files, GetColor())) - return 1 + BUILTFROMCACHE[key] = dates + +def NeedsBuild(files, others): + dates = {} + for file in files: + dates[file] = GetTimestamp(file) + if not os.path.exists(file): + return True + for file in others: + dates[file] = GetTimestamp(file) + + key = tuple(files) + if key in BUILTFROMCACHE: + if BUILTFROMCACHE[key] == dates: + return False + if VERBOSE and frozenset(oldothers) != frozenset(others): + print("%sWARNING:%s file dependencies changed: %s%s%s" % (GetColor("red"), GetColor(), GetColor("green"), files, GetColor())) + + return True ######################################################################## ## @@ -721,8 +723,8 @@ def SaveDependencyCache(): except: icache = 0 if (icache!=0): print("Storing dependency cache.") - pickle.dump(CXXINCLUDECACHE, icache, 1) - pickle.dump(BUILTFROMCACHE, icache, 1) + pickle.dump(CXXINCLUDECACHE, icache, 2) + pickle.dump(BUILTFROMCACHE, icache, 2) icache.close() def LoadDependencyCache(): @@ -971,8 +973,10 @@ def ConditionalWriteFile(dest, desiredcontents): contents = rfile.read(-1) rfile.close() except: - contents=0 + contents = 0 if contents != desiredcontents: + if VERBOSE: + print("Writing %s" % (dest)) sys.stdout.flush() WriteFile(dest, desiredcontents) @@ -1744,7 +1748,7 @@ def SdkLocateDirectX( strMode = 'default' ): SDK["DIRECTCAM"] = SDK["DX9"] def SdkLocateMaya(): - for (ver,key) in MAYAVERSIONINFO: + for (ver, key) in MAYAVERSIONINFO: if (PkgSkip(ver)==0 and ver not in SDK): GetSdkDir(ver.lower().replace("x",""), ver) if (not ver in SDK): @@ -1759,7 +1763,7 @@ def SdkLocateMaya(): ddir = "/Applications/Autodesk/maya"+key if (os.path.isdir(ddir)): SDK[ver] = ddir else: - if (GetTargetArch() == 'x64'): + if (GetTargetArch() in ("x86_64", "amd64")): ddir1 = "/usr/autodesk/maya"+key+"-x64" ddir2 = "/usr/aw/maya"+key+"-x64" else: @@ -2544,9 +2548,9 @@ def CalcLocation(fn, ipath): def FindLocation(fn, ipath): if (GetLinkAllStatic() and fn.endswith(".dll")): - fn = fn[:-4]+".lib" + fn = fn[:-4] + ".lib" loc = CalcLocation(fn, ipath) - (base,ext) = os.path.splitext(fn) + base, ext = os.path.splitext(fn) ORIG_EXT[loc] = ext return loc @@ -2597,8 +2601,8 @@ def FindLocation(fn, ipath): class Target: pass -TARGET_LIST=[] -TARGET_TABLE={} +TARGET_LIST = [] +TARGET_TABLE = {} def TargetAdd(target, dummy=0, opts=0, input=0, dep=0, ipath=0, winrc=0): if (dummy != 0): @@ -2607,7 +2611,7 @@ def TargetAdd(target, dummy=0, opts=0, input=0, dep=0, ipath=0, winrc=0): if (ipath == 0): ipath = [] if (type(input) == str): input = [input] if (type(dep) == str): dep = [dep] - full = FindLocation(target,[OUTPUTDIR+"/include"]) + full = FindLocation(target, [OUTPUTDIR + "/include"]) if (full not in TARGET_TABLE): t = Target() @@ -2642,6 +2646,7 @@ def TargetAdd(target, dummy=0, opts=0, input=0, dep=0, ipath=0, winrc=0): for x in dep: fulldep = FindLocation(x, ipath) t.deps[fulldep] = 1 + if winrc != 0 and GetTarget() == 'windows': TargetAdd(target, input=WriteResourceFile(target.split("/")[-1].split(".")[0], **winrc)) From 708dca046830ffb3279d7a629d2f253e499ef547 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 13:39:30 +0000 Subject: [PATCH 04/37] oops, fix for verbose builds --- makepanda/makepandacore.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/makepanda/makepandacore.py b/makepanda/makepandacore.py index 7d11816d54..55fa889816 100644 --- a/makepanda/makepandacore.py +++ b/makepanda/makepandacore.py @@ -649,9 +649,10 @@ def NeedsBuild(files, others): key = tuple(files) if key in BUILTFROMCACHE: - if BUILTFROMCACHE[key] == dates: + cached = BUILTFROMCACHE[key] + if cached == dates: return False - if VERBOSE and frozenset(oldothers) != frozenset(others): + if VERBOSE and frozenset(cached.keys()) != frozenset(dates.keys()): print("%sWARNING:%s file dependencies changed: %s%s%s" % (GetColor("red"), GetColor(), GetColor("green"), files, GetColor())) return True From 634c3c5a0afa5062bc7ee7bbafc7900139dfa340 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 15:03:30 +0000 Subject: [PATCH 05/37] Stubs for Python 3 functions --- dtool/src/pystub/pystub.cxx | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/dtool/src/pystub/pystub.cxx b/dtool/src/pystub/pystub.cxx index cdf23b1e45..1a63ac5b2f 100644 --- a/dtool/src/pystub/pystub.cxx +++ b/dtool/src/pystub/pystub.cxx @@ -20,6 +20,10 @@ extern "C" { EXPCL_PYSTUB int PyArg_ParseTupleAndKeywords(...); EXPCL_PYSTUB int PyBool_FromLong(...); EXPCL_PYSTUB int PyBuffer_Release(...); + EXPCL_PYSTUB int PyBytes_AsString(...); + EXPCL_PYSTUB int PyBytes_AsStringAndSize(...); + EXPCL_PYSTUB int PyBytes_FromStringAndSize(...); + EXPCL_PYSTUB int PyBytes_Size(...); EXPCL_PYSTUB int PyCFunction_New(...); EXPCL_PYSTUB int PyCFunction_NewEx(...); EXPCL_PYSTUB int PyCallable_Check(...); @@ -79,8 +83,10 @@ extern "C" { EXPCL_PYSTUB int PyModule_AddIntConstant(...); EXPCL_PYSTUB int PyModule_AddObject(...); EXPCL_PYSTUB int PyModule_AddStringConstant(...); + EXPCL_PYSTUB int PyModule_Create2(...); EXPCL_PYSTUB int PyNumber_Float(...); EXPCL_PYSTUB int PyNumber_Long(...); + EXPCL_PYSTUB int PyObject_ASCII(...); EXPCL_PYSTUB int PyObject_Call(...); EXPCL_PYSTUB int PyObject_CallFunction(...); EXPCL_PYSTUB int PyObject_CallMethod(...); @@ -134,6 +140,12 @@ extern "C" { EXPCL_PYSTUB int PyUnicodeUCS4_FromWideChar(...); EXPCL_PYSTUB int PyUnicodeUCS4_AsWideChar(...); EXPCL_PYSTUB int PyUnicodeUCS4_GetSize(...); + EXPCL_PYSTUB int PyUnicode_AsUTF8(...); + EXPCL_PYSTUB int PyUnicode_AsWideChar(...); + EXPCL_PYSTUB int PyUnicode_FromString(...); + EXPCL_PYSTUB int PyUnicode_FromStringAndSize(...); + EXPCL_PYSTUB int PyUnicode_FromWideChar(...); + EXPCL_PYSTUB int PyUnicode_GetSize(...); EXPCL_PYSTUB int PyUnicode_Type(...); EXPCL_PYSTUB int Py_BuildValue(...); EXPCL_PYSTUB int Py_InitModule4(...); @@ -145,11 +157,13 @@ extern "C" { EXPCL_PYSTUB int _Py_NegativeRefcount(...); EXPCL_PYSTUB int _Py_RefTotal(...); + EXPCL_PYSTUB void Py_Initialize(); EXPCL_PYSTUB int Py_IsInitialized(); EXPCL_PYSTUB extern void *PyExc_AssertionError; EXPCL_PYSTUB extern void *PyExc_AttributeError; EXPCL_PYSTUB extern void *PyExc_BufferError; + EXPCL_PYSTUB extern void *PyExc_ConnectionError; EXPCL_PYSTUB extern void *PyExc_Exception; EXPCL_PYSTUB extern void *PyExc_FutureWarning; EXPCL_PYSTUB extern void *PyExc_IndexError; @@ -169,6 +183,10 @@ int PyArg_ParseTuple(...) { return 0; } int PyArg_ParseTupleAndKeywords(...) { return 0; } int PyBool_FromLong(...) { return 0; } int PyBuffer_Release(...) { return 0; } +int PyBytes_AsString(...) { return 0; } +int PyBytes_AsStringAndSize(...) { return 0; } +int PyBytes_FromStringAndSize(...) { return 0; } +int PyBytes_Size(...) { return 0; } int PyCFunction_New(...) { return 0; }; int PyCFunction_NewEx(...) { return 0; }; int PyCallable_Check(...) { return 0; } @@ -228,8 +246,10 @@ int PyMemoryView_FromObject(...) { return 0; } int PyModule_AddIntConstant(...) { return 0; }; int PyModule_AddObject(...) { return 0; }; int PyModule_AddStringConstant(...) { return 0; }; +int PyModule_Create2(...) { return 0; }; int PyNumber_Float(...) { return 0; } int PyNumber_Long(...) { return 0; } +int PyObject_ASCII(...) { return 0; } int PyObject_Call(...) { return 0; } int PyObject_CallFunction(...) { return 0; } int PyObject_CallMethod(...) { return 0; } @@ -283,6 +303,12 @@ int PyUnicodeUCS4_FromStringAndSize(...) { return 0; } int PyUnicodeUCS4_FromWideChar(...) { return 0; } int PyUnicodeUCS4_AsWideChar(...) { return 0; } int PyUnicodeUCS4_GetSize(...) { return 0; } +int PyUnicode_AsUTF8(...) { return 0; } +int PyUnicode_AsWideChar(...) { return 0; } +int PyUnicode_FromString(...) { return 0; } +int PyUnicode_FromStringAndSize(...) { return 0; } +int PyUnicode_FromWideChar(...) { return 0; } +int PyUnicode_GetSize(...) { return 0; } int PyUnicode_Type(...) { return 0; } int Py_BuildValue(...) { return 0; } int Py_InitModule4(...) { return 0; } @@ -295,6 +321,8 @@ int _Py_NegativeRefcount(...) { return 0; }; int _Py_RefTotal(...) { return 0; }; // We actually might call this one. +void Py_Initialize() { +} int Py_IsInitialized() { return 0; } @@ -303,6 +331,7 @@ int Py_IsInitialized() { void *PyExc_AssertionError = (void *)NULL; void *PyExc_AttributeError = (void *)NULL; void *PyExc_BufferError = (void *)NULL; +void *PyExc_ConnectionError = (void *)NULL; void *PyExc_Exception = (void *)NULL; void *PyExc_FutureWarning = (void *)NULL; void *PyExc_IndexError = (void *)NULL; @@ -319,4 +348,3 @@ void *_Py_NotImplementedStruct = (void *)NULL; void pystub() { } - From 01ebd5e66a6cbf46c8eebc020210db607fdc897b Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 15:18:37 +0000 Subject: [PATCH 06/37] very error, such compile, wow --- makepanda/makepandacore.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/makepanda/makepandacore.py b/makepanda/makepandacore.py index 55fa889816..ebe70730a5 100644 --- a/makepanda/makepandacore.py +++ b/makepanda/makepandacore.py @@ -652,7 +652,7 @@ def NeedsBuild(files, others): cached = BUILTFROMCACHE[key] if cached == dates: return False - if VERBOSE and frozenset(cached.keys()) != frozenset(dates.keys()): + if VERBOSE and frozenset(cached) != frozenset(dates): print("%sWARNING:%s file dependencies changed: %s%s%s" % (GetColor("red"), GetColor(), GetColor("green"), files, GetColor())) return True From f29c4681e1fe57c555c99ae6b2cd52b331371850 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 17:42:16 +0000 Subject: [PATCH 07/37] Fix broken Python 3 support. --- .../interfaceMakerPythonNative.cxx | 42 ++++++--- dtool/src/interrogate/interrogate_module.cxx | 91 ++++++++++++------- dtool/src/interrogatedb/py_panda.cxx | 31 +++---- dtool/src/interrogatedb/py_panda.h | 6 +- 4 files changed, 106 insertions(+), 64 deletions(-) diff --git a/dtool/src/interrogate/interfaceMakerPythonNative.cxx b/dtool/src/interrogate/interfaceMakerPythonNative.cxx index 0a457f4058..01ec64a781 100755 --- a/dtool/src/interrogate/interfaceMakerPythonNative.cxx +++ b/dtool/src/interrogate/interfaceMakerPythonNative.cxx @@ -1167,25 +1167,41 @@ write_module(ostream &out, ostream *out_h, InterrogateModuleDef *def) { out << "//********************************************************************\n"; out << "#if PY_MAJOR_VERSION >= 3\n" - << "#define INIT_FUNC PyObject *PyInit_" << def->module_name << "\n" - << "#else\n" - << "#define INIT_FUNC void init" << def->module_name << "\n" - << "#endif\n\n" - + << "static struct PyModuleDef python_native_module = {\n" + << " PyModuleDef_HEAD_INIT,\n" + << " \"" << def->module_name << "\",\n" + << " NULL,\n" + << " -1,\n" + << " NULL,\n" + << " NULL, NULL, NULL, NULL\n" + << "};\n" + << "\n" << "#ifdef _WIN32\n" - << "extern \"C\" __declspec(dllexport) INIT_FUNC();\n" + << "extern \"C\" __declspec(dllexport) PyObject *PyInit_" << def->module_name << "();\n" << "#else\n" - << "extern \"C\" INIT_FUNC();\n" - << "#endif\n\n" - - << "INIT_FUNC() {\n" + << "extern \"C\" PyObject *PyInit_" << def->module_name << "();\n" + << "#endif\n" + << "\n" << "PyObject *PyInit_" << def->module_name << "() {\n" << " LibraryDef *refs[] = {&" << def->library_name << "_moddef, NULL};\n" - << "#if PY_MAJOR_VERSION >= 3\n" - << " return\n" + << " return Dtool_PyModuleInitHelper(refs, &python_native_module);\n" + << "}\n" + << "\n" + << "#else // Python 2 case\n" + << "\n" + << "#ifdef _WIN32\n" + << "extern \"C\" __declspec(dllexport) void init" << def->module_name << "();\n" + << "#else\n" + << "extern \"C\" void init" << def->module_name << "();\n" << "#endif\n" + << "\n" + << "void init" << def->module_name << "() {\n" + << " LibraryDef *refs[] = {&" << def->library_name << "_moddef, NULL};\n" << " Dtool_PyModuleInitHelper(refs, \"" << def->module_name << "\");\n" - << "}\n\n"; + << "}\n" + << "\n" + << "#endif\n" + << "\n"; } ///////////////////////////////////////////////////////////////////////////////////////////// // Function :write_module_class diff --git a/dtool/src/interrogate/interrogate_module.cxx b/dtool/src/interrogate/interrogate_module.cxx index 724904b891..9292f04b02 100644 --- a/dtool/src/interrogate/interrogate_module.cxx +++ b/dtool/src/interrogate/interrogate_module.cxx @@ -80,7 +80,7 @@ int write_python_table_native(ostream &out) { int count = 0; - pset Libraries; + pset libraries; // out << "extern \"C\" {\n"; @@ -92,59 +92,88 @@ int write_python_table_native(ostream &out) { // Consider only those that belong in the module we asked for. if (interrogate_function_has_module_name(function_index) && - module_name == interrogate_function_module_name(function_index)) { - // if it has a library name add it to set of libraries - if(interrogate_function_has_library_name(function_index)) - Libraries.insert(interrogate_function_library_name(function_index)); + module_name == interrogate_function_module_name(function_index)) { + // if it has a library name add it to set of libraries + if (interrogate_function_has_library_name(function_index)) { + libraries.insert(interrogate_function_library_name(function_index)); + } } } - for(int ti = 0; ti < interrogate_number_of_types(); ti++) { + for (int ti = 0; ti < interrogate_number_of_types(); ti++) { TypeIndex thetype = interrogate_get_type(ti); - if(interrogate_type_has_module_name(thetype) && module_name == interrogate_type_module_name(thetype)) { - if(interrogate_type_has_library_name(thetype)) - Libraries.insert(interrogate_type_library_name(thetype)); + if (interrogate_type_has_module_name(thetype) && module_name == interrogate_type_module_name(thetype)) { + if (interrogate_type_has_library_name(thetype)) { + libraries.insert(interrogate_type_library_name(thetype)); + } } } pset::iterator ii; - for(ii = Libraries.begin(); ii != Libraries.end(); ii++) { - printf("Referencing Library %s\n",(*ii).c_str()); - out << "extern LibraryDef "<< *ii << "_moddef;\n"; + for(ii = libraries.begin(); ii != libraries.end(); ii++) { + printf("Referencing Library %s\n", (*ii).c_str()); + out << "extern LibraryDef " << *ii << "_moddef;\n"; } out << "\n" << "#if PY_MAJOR_VERSION >= 3\n" - << "#define INIT_FUNC PyObject *PyInit_" << library_name << "\n" - << "#else\n" - << "#define INIT_FUNC void init" << library_name << "\n" - << "#endif\n\n" - + << "static struct PyModuleDef py_" << library_name << "_module = {\n" + << " PyModuleDef_HEAD_INIT,\n" + << " \"" << library_name << "\",\n" + << " NULL,\n" + << " -1,\n" + << " NULL,\n" + << " NULL, NULL, NULL, NULL\n" + << "};\n" + << "\n" << "#ifdef _WIN32\n" - << "extern \"C\" __declspec(dllexport) INIT_FUNC();\n" + << "extern \"C\" __declspec(dllexport) PyObject *PyInit_" << library_name << "();\n" << "#else\n" - << "extern \"C\" INIT_FUNC();\n" - << "#endif\n\n" - - << "INIT_FUNC() {\n"; + << "extern \"C\" PyObject *PyInit_" << library_name << "();\n" + << "#endif\n" + << "\n" + << "PyObject *PyInit_" << library_name << "() {\n"; if (track_interpreter) { out << " in_interpreter = 1;\n"; } out << " LibraryDef *defs[] = {"; - for(ii = Libraries.begin(); ii != Libraries.end(); ii++) { - out << "&"<< *ii << "_moddef, "; + for(ii = libraries.begin(); ii != libraries.end(); ii++) { + out << "&" << *ii << "_moddef, "; } - out << "NULL};\n\n"; + out << "NULL};\n" + << "\n" + << " return Dtool_PyModuleInitHelper(defs, &py_" << library_name << "_module);\n" + << "}\n" + << "\n" + << "#else // Python 2 case\n" + << "\n" + << "#ifdef _WIN32\n" + << "extern \"C\" __declspec(dllexport) void init" << library_name << "();\n" + << "#else\n" + << "extern \"C\" void init" << library_name << "();\n" + << "#endif\n" + << "\n" + << "void init" << library_name << "() {\n"; + + if (track_interpreter) { + out << " in_interpreter = 1;\n"; + } + + out << " LibraryDef *defs[] = {"; + for(ii = libraries.begin(); ii != libraries.end(); ii++) { + out << "&" << *ii << "_moddef, "; + } + + out << "NULL};\n" + << "\n" + << " Dtool_PyModuleInitHelper(defs, \"" << library_name << "\");\n" + << "}\n" + << "#endif\n" + << "\n"; - out << "#if PY_MAJOR_VERSION >= 3\n"; - out << " return Dtool_PyModuleInitHelper(defs, \"" << library_name << "\");\n"; - out << "#else\n"; - out << " Dtool_PyModuleInitHelper(defs, \"" << library_name << "\");\n"; - out << "#endif\n"; - out << "}\n"; return count; } diff --git a/dtool/src/interrogatedb/py_panda.cxx b/dtool/src/interrogatedb/py_panda.cxx index 55b4904b8a..afb33e8ea2 100644 --- a/dtool/src/interrogatedb/py_panda.cxx +++ b/dtool/src/interrogatedb/py_panda.cxx @@ -203,8 +203,7 @@ DTOOL_Call_GetPointerThisClass(PyObject *self, Dtool_PyTypedObject *classdef, if (report_errors) { ostringstream str; str << function_name << "() argument " << param << " must be "; - - + PyObject *fname = PyObject_GetAttrString((PyObject *)classdef, "__name__"); if (fname != (PyObject *)NULL) { #if PY_MAJOR_VERSION >= 3 @@ -216,7 +215,7 @@ DTOOL_Call_GetPointerThisClass(PyObject *self, Dtool_PyTypedObject *classdef, } else { str << classdef->_name; } - + PyObject *tname = PyObject_GetAttrString((PyObject *)Py_TYPE(self), "__name__"); if (tname != (PyObject *)NULL) { #if PY_MAJOR_VERSION >= 3 @@ -228,7 +227,7 @@ DTOOL_Call_GetPointerThisClass(PyObject *self, Dtool_PyTypedObject *classdef, } else { str << ", not " << my_type->_name; } - + string msg = str.str(); PyErr_SetString(PyExc_TypeError, msg.c_str()); } @@ -445,11 +444,15 @@ Dtool_PyTypedObject *Dtool_RuntimeTypeDtoolType(int type) { return di->second; } } - return NULL; + return NULL; } /////////////////////////////////////////////////////////////////////////////// +#if PY_MAJOR_VERSION >= 3 +PyObject *Dtool_PyModuleInitHelper(LibraryDef *defs[], PyModuleDef *module_def) { +#else PyObject *Dtool_PyModuleInitHelper(LibraryDef *defs[], const char *modulename) { +#endif // the module level function inits.... MethodDefmap functions; for (int xx = 0; defs[xx] != NULL; xx++) { @@ -468,20 +471,11 @@ PyObject *Dtool_PyModuleInitHelper(LibraryDef *defs[], const char *modulename) { newdef[offset].ml_flags = 0; #if PY_MAJOR_VERSION >= 3 - cerr << "About to create module " << modulename << "\n"; - struct PyModuleDef moduledef = { - PyModuleDef_HEAD_INIT, - modulename, - NULL, - -1, - newdef, - NULL, NULL, NULL, NULL - }; - PyObject *module = PyModule_Create(&moduledef); - cerr << "Module created!\n"; + module_def->m_methods = newdef; + PyObject *module = PyModule_Create(module_def); #else - PyObject *module = Py_InitModule((char *)modulename, newdef); -#endif + PyObject *module = Py_InitModule((char *)modulename, newdef); +#endif if (module == NULL) { #if PY_MAJOR_VERSION >= 3 @@ -492,7 +486,6 @@ PyObject *Dtool_PyModuleInitHelper(LibraryDef *defs[], const char *modulename) { return NULL; } - // the constant inits... enums, classes ... for (int y = 0; defs[y] != NULL; y++) { defs[y]->_constants(module); diff --git a/dtool/src/interrogatedb/py_panda.h b/dtool/src/interrogatedb/py_panda.h index 1f8d35594d..a9779300f4 100755 --- a/dtool/src/interrogatedb/py_panda.h +++ b/dtool/src/interrogatedb/py_panda.h @@ -204,7 +204,7 @@ struct Dtool_PyTypedObject { { \ { \ PyVarObject_HEAD_INIT(NULL, 0) \ - "lib" #MODULE_NAME "." #PUBLIC_NAME, /*type name with module */ \ + #MODULE_NAME "." #PUBLIC_NAME, /*type name with module */ \ sizeof(Dtool_PyInstDef), /* tp_basicsize */ \ 0, /* tp_itemsize */ \ &Dtool_Deallocate_General, /* tp_dealloc */ \ @@ -444,7 +444,11 @@ struct LibraryDef { }; /////////////////////////////////////////////////////////////////////////////// +#if PY_MAJOR_VERSION >= 3 +EXPCL_DTOOLCONFIG PyObject *Dtool_PyModuleInitHelper(LibraryDef *defs[], PyModuleDef *module_def); +#else EXPCL_DTOOLCONFIG PyObject *Dtool_PyModuleInitHelper(LibraryDef *defs[], const char *modulename); +#endif /////////////////////////////////////////////////////////////////////////////// /// HACK.... Be carefull From 708e8dc5130de20685ccf13ce732a4024eb155a2 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 18:01:54 +0000 Subject: [PATCH 08/37] Remove HAVE_GETTIMEOFDAY which we aren't using --- dtool/Config.Android.pp | 3 --- dtool/Config.FreeBSD.pp | 3 --- dtool/Config.Irix.pp | 3 --- dtool/Config.Linux.pp | 3 --- dtool/Config.OSX.pp | 3 --- dtool/Config.Win32.pp | 3 --- dtool/Config.Win64.pp | 3 --- 7 files changed, 21 deletions(-) diff --git a/dtool/Config.Android.pp b/dtool/Config.Android.pp index a8bc758d2e..d5fe1f9eef 100644 --- a/dtool/Config.Android.pp +++ b/dtool/Config.Android.pp @@ -245,9 +245,6 @@ // assertion failures on execution. #define SIMPLE_STRUCT_POINTERS -// Do we have a gettimeofday() function? -#define HAVE_GETTIMEOFDAY 1 - // Does gettimeofday() take only one parameter? #define GETTIMEOFDAY_ONE_PARAM diff --git a/dtool/Config.FreeBSD.pp b/dtool/Config.FreeBSD.pp index 61e8e7fcd0..b7a2fde268 100644 --- a/dtool/Config.FreeBSD.pp +++ b/dtool/Config.FreeBSD.pp @@ -168,9 +168,6 @@ // assertion failures on execution. #define SIMPLE_STRUCT_POINTERS -// Do we have a gettimeofday() function? -#define HAVE_GETTIMEOFDAY 1 - // Does gettimeofday() take only one parameter? #define GETTIMEOFDAY_ONE_PARAM diff --git a/dtool/Config.Irix.pp b/dtool/Config.Irix.pp index 7939568c7f..3912a8b4ae 100644 --- a/dtool/Config.Irix.pp +++ b/dtool/Config.Irix.pp @@ -41,9 +41,6 @@ // assertion failures on execution. #define SIMPLE_STRUCT_POINTERS -// Do we have a gettimeofday() function? -#define HAVE_GETTIMEOFDAY 1 - // Does gettimeofday() take only one parameter? #define GETTIMEOFDAY_ONE_PARAM diff --git a/dtool/Config.Linux.pp b/dtool/Config.Linux.pp index 96ecc27a73..36156b07d0 100644 --- a/dtool/Config.Linux.pp +++ b/dtool/Config.Linux.pp @@ -210,9 +210,6 @@ // assertion failures on execution. #define SIMPLE_STRUCT_POINTERS -// Do we have a gettimeofday() function? -#define HAVE_GETTIMEOFDAY 1 - // Does gettimeofday() take only one parameter? #define GETTIMEOFDAY_ONE_PARAM diff --git a/dtool/Config.OSX.pp b/dtool/Config.OSX.pp index 24c422cc2d..be2dd75c84 100644 --- a/dtool/Config.OSX.pp +++ b/dtool/Config.OSX.pp @@ -169,9 +169,6 @@ // assertion failures on execution. #define SIMPLE_STRUCT_POINTERS -// Do we have a gettimeofday() function? -#define HAVE_GETTIMEOFDAY 1 - // Does gettimeofday() take only one parameter? #define GETTIMEOFDAY_ONE_PARAM diff --git a/dtool/Config.Win32.pp b/dtool/Config.Win32.pp index 84ad72749c..8c56d25a29 100644 --- a/dtool/Config.Win32.pp +++ b/dtool/Config.Win32.pp @@ -47,9 +47,6 @@ // assertion failures on execution. #define SIMPLE_STRUCT_POINTERS 1 -// Do we have a gettimeofday() function? -#define HAVE_GETTIMEOFDAY - // Does gettimeofday() take only one parameter? #define GETTIMEOFDAY_ONE_PARAM diff --git a/dtool/Config.Win64.pp b/dtool/Config.Win64.pp index 1df2384869..40936b0bdc 100755 --- a/dtool/Config.Win64.pp +++ b/dtool/Config.Win64.pp @@ -47,9 +47,6 @@ // assertion failures on execution. #define SIMPLE_STRUCT_POINTERS 1 -// Do we have a gettimeofday() function? -#define HAVE_GETTIMEOFDAY - // Does gettimeofday() take only one parameter? #define GETTIMEOFDAY_ONE_PARAM From 3403c8748e5ba9f9b46df3abf1552f82ee5d4da0 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 18:05:45 +0000 Subject: [PATCH 09/37] Fix use of outdated exec and repr syntax --- .../distributed/DistributedObjectGlobalUD.py | 4 +- direct/src/distributed/MsgTypes.py | 2 +- direct/src/distributed/MsgTypesCMU.py | 2 +- direct/src/particles/ParticleEffect.py | 2 +- direct/src/particles/Particles.py | 52 +++++++++---------- direct/src/pyinst/imputil.py | 2 +- direct/src/showutil/FreezeTool.py | 2 +- direct/src/tkpanels/FSMInspector.py | 2 +- 8 files changed, 34 insertions(+), 34 deletions(-) diff --git a/direct/src/distributed/DistributedObjectGlobalUD.py b/direct/src/distributed/DistributedObjectGlobalUD.py index 8af8a0ecb8..c53f1cdde9 100755 --- a/direct/src/distributed/DistributedObjectGlobalUD.py +++ b/direct/src/distributed/DistributedObjectGlobalUD.py @@ -35,7 +35,7 @@ class DistributedObjectGlobalUD(DistributedObjectUD): def __execMessage(self, message): if not self.ExecNamespace: # Import some useful variables into the ExecNamespace initially. - exec 'from pandac.PandaModules import *' in globals(), self.ExecNamespace + exec('from pandac.PandaModules import *', globals(), self.ExecNamespace) #self.importExecNamespace() # Now try to evaluate the expression using ChatInputNormal.ExecNamespace as @@ -48,7 +48,7 @@ class DistributedObjectGlobalUD(DistributedObjectUD): # "import math". These aren't expressions, so eval() # fails, but they can be exec'ed. try: - exec message in globals(), self.ExecNamespace + exec(message, globals(), self.ExecNamespace) return 'ok' except: exception = sys.exc_info()[0] diff --git a/direct/src/distributed/MsgTypes.py b/direct/src/distributed/MsgTypes.py index 4f6340aae2..283701e3b4 100644 --- a/direct/src/distributed/MsgTypes.py +++ b/direct/src/distributed/MsgTypes.py @@ -108,7 +108,7 @@ MsgId2Names = invertDictLossless(MsgName2Id) # put msg names in module scope, assigned to msg value for name, value in MsgName2Id.items(): - exec '%s = %s' % (name, value) + exec('%s = %s' % (name, value)) del name, value # These messages are ignored when the client is headed to the quiet zone diff --git a/direct/src/distributed/MsgTypesCMU.py b/direct/src/distributed/MsgTypesCMU.py index 32e70d68fd..8501866a5b 100644 --- a/direct/src/distributed/MsgTypesCMU.py +++ b/direct/src/distributed/MsgTypesCMU.py @@ -27,5 +27,5 @@ MsgId2Names = invertDictLossless(MsgName2Id) # put msg names in module scope, assigned to msg value for name, value in MsgName2Id.items(): - exec '%s = %s' % (name, value) + exec('%s = %s' % (name, value)) del name, value diff --git a/direct/src/particles/ParticleEffect.py b/direct/src/particles/ParticleEffect.py index 25e0343ddb..914630f19c 100644 --- a/direct/src/particles/ParticleEffect.py +++ b/direct/src/particles/ParticleEffect.py @@ -202,7 +202,7 @@ class ParticleEffect(NodePath): data = vfs.readFile(filename, 1) data = data.replace('\r', '') try: - exec data + exec(data) except: self.notify.warning('loadConfig: failed to load particle file: '+ repr(filename)) raise diff --git a/direct/src/particles/Particles.py b/direct/src/particles/Particles.py index 4a065fe709..974ff4af9e 100644 --- a/direct/src/particles/Particles.py +++ b/direct/src/particles/Particles.py @@ -365,31 +365,31 @@ class Particles(ParticleSystem): typ = type(fun).__name__ if typ == 'ColorInterpolationFunctionConstant': c_a = fun.getColorA() - file.write(targ+'.renderer.getColorInterpolationManager().addConstant('+repr(t_b)+','+`t_e`+','+ \ - 'Vec4('+repr(c_a[0])+','+`c_a[1]`+','+`c_a[2]`+','+`c_a[3]`+'),'+`mod`+')\n') + file.write(targ+'.renderer.getColorInterpolationManager().addConstant('+repr(t_b)+','+repr(t_e)+','+ \ + 'Vec4('+repr(c_a[0])+','+repr(c_a[1])+','+repr(c_a[2])+','+repr(c_a[3])+'),'+repr(mod)+')\n') elif typ == 'ColorInterpolationFunctionLinear': c_a = fun.getColorA() c_b = fun.getColorB() - file.write(targ+'.renderer.getColorInterpolationManager().addLinear('+repr(t_b)+','+`t_e`+','+ \ - 'Vec4('+repr(c_a[0])+','+`c_a[1]`+','+`c_a[2]`+','+`c_a[3]`+'),' + \ - 'Vec4('+repr(c_b[0])+','+`c_b[1]`+','+`c_b[2]`+','+`c_b[3]`+'),'+`mod`+')\n') + file.write(targ+'.renderer.getColorInterpolationManager().addLinear('+repr(t_b)+','+repr(t_e)+','+ \ + 'Vec4('+repr(c_a[0])+','+repr(c_a[1])+','+repr(c_a[2])+','+repr(c_a[3])+'),' + \ + 'Vec4('+repr(c_b[0])+','+repr(c_b[1])+','+repr(c_b[2])+','+repr(c_b[3])+'),'+repr(mod)+')\n') elif typ == 'ColorInterpolationFunctionStepwave': c_a = fun.getColorA() c_b = fun.getColorB() w_a = fun.getWidthA() w_b = fun.getWidthB() - file.write(targ+'.renderer.getColorInterpolationManager().addStepwave('+repr(t_b)+','+`t_e`+','+ \ - 'Vec4('+repr(c_a[0])+','+`c_a[1]`+','+`c_a[2]`+','+`c_a[3]`+'),' + \ - 'Vec4('+repr(c_b[0])+','+`c_b[1]`+','+`c_b[2]`+','+`c_b[3]`+'),' + \ - repr(w_a)+','+`w_b`+','+`mod`+')\n') + file.write(targ+'.renderer.getColorInterpolationManager().addStepwave('+repr(t_b)+','+repr(t_e)+','+ \ + 'Vec4('+repr(c_a[0])+','+repr(c_a[1])+','+repr(c_a[2])+','+repr(c_a[3])+'),' + \ + 'Vec4('+repr(c_b[0])+','+repr(c_b[1])+','+repr(c_b[2])+','+repr(c_b[3])+'),' + \ + repr(w_a)+','+repr(w_b)+','+repr(mod)+')\n') elif typ == 'ColorInterpolationFunctionSinusoid': c_a = fun.getColorA() c_b = fun.getColorB() per = fun.getPeriod() - file.write(targ+'.renderer.getColorInterpolationManager().addSinusoid('+repr(t_b)+','+`t_e`+','+ \ - 'Vec4('+repr(c_a[0])+','+`c_a[1]`+','+`c_a[2]`+','+`c_a[3]`+'),' + \ - 'Vec4('+repr(c_b[0])+','+`c_b[1]`+','+`c_b[2]`+','+`c_b[3]`+'),' + \ - repr(per)+','+`mod`+')\n') + file.write(targ+'.renderer.getColorInterpolationManager().addSinusoid('+repr(t_b)+','+repr(t_e)+','+ \ + 'Vec4('+repr(c_a[0])+','+repr(c_a[1])+','+repr(c_a[2])+','+repr(c_a[3])+'),' + \ + 'Vec4('+repr(c_b[0])+','+repr(c_b[1])+','+repr(c_b[2])+','+repr(c_b[3])+'),' + \ + repr(per)+','+repr(mod)+')\n') elif (self.rendererType == "SparkleParticleRenderer"): file.write('# Sparkle parameters\n') @@ -468,31 +468,31 @@ class Particles(ParticleSystem): typ = type(fun).__name__ if typ == 'ColorInterpolationFunctionConstant': c_a = fun.getColorA() - file.write(targ+'.renderer.getColorInterpolationManager().addConstant('+repr(t_b)+','+`t_e`+','+ \ - 'Vec4('+repr(c_a[0])+','+`c_a[1]`+','+`c_a[2]`+','+`c_a[3]`+'),'+`mod`+')\n') + file.write(targ+'.renderer.getColorInterpolationManager().addConstant('+repr(t_b)+','+repr(t_e)+','+ \ + 'Vec4('+repr(c_a[0])+','+repr(c_a[1])+','+repr(c_a[2])+','+repr(c_a[3])+'),'+repr(mod)+')\n') elif typ == 'ColorInterpolationFunctionLinear': c_a = fun.getColorA() c_b = fun.getColorB() - file.write(targ+'.renderer.getColorInterpolationManager().addLinear('+repr(t_b)+','+`t_e`+','+ \ - 'Vec4('+repr(c_a[0])+','+`c_a[1]`+','+`c_a[2]`+','+`c_a[3]`+'),' + \ - 'Vec4('+repr(c_b[0])+','+`c_b[1]`+','+`c_b[2]`+','+`c_b[3]`+'),'+`mod`+')\n') + file.write(targ+'.renderer.getColorInterpolationManager().addLinear('+repr(t_b)+','+repr(t_e)+','+ \ + 'Vec4('+repr(c_a[0])+','+repr(c_a[1])+','+repr(c_a[2])+','+repr(c_a[3])+'),' + \ + 'Vec4('+repr(c_b[0])+','+repr(c_b[1])+','+repr(c_b[2])+','+repr(c_b[3])+'),'+repr(mod)+')\n') elif typ == 'ColorInterpolationFunctionStepwave': c_a = fun.getColorA() c_b = fun.getColorB() w_a = fun.getWidthA() w_b = fun.getWidthB() - file.write(targ+'.renderer.getColorInterpolationManager().addStepwave('+repr(t_b)+','+`t_e`+','+ \ - 'Vec4('+repr(c_a[0])+','+`c_a[1]`+','+`c_a[2]`+','+`c_a[3]`+'),' + \ - 'Vec4('+repr(c_b[0])+','+`c_b[1]`+','+`c_b[2]`+','+`c_b[3]`+'),' + \ - repr(w_a)+','+`w_b`+','+`mod`+')\n') + file.write(targ+'.renderer.getColorInterpolationManager().addStepwave('+repr(t_b)+','+repr(t_e)+','+ \ + 'Vec4('+repr(c_a[0])+','+repr(c_a[1])+','+repr(c_a[2])+','+repr(c_a[3])+'),' + \ + 'Vec4('+repr(c_b[0])+','+repr(c_b[1])+','+repr(c_b[2])+','+repr(c_b[3])+'),' + \ + repr(w_a)+','+repr(w_b)+','+repr(mod)+')\n') elif typ == 'ColorInterpolationFunctionSinusoid': c_a = fun.getColorA() c_b = fun.getColorB() per = fun.getPeriod() - file.write(targ+'.renderer.getColorInterpolationManager().addSinusoid('+repr(t_b)+','+`t_e`+','+ \ - 'Vec4('+repr(c_a[0])+','+`c_a[1]`+','+`c_a[2]`+','+`c_a[3]`+'),' + \ - 'Vec4('+repr(c_b[0])+','+`c_b[1]`+','+`c_b[2]`+','+`c_b[3]`+'),' + \ - repr(per)+','+`mod`+')\n') + file.write(targ+'.renderer.getColorInterpolationManager().addSinusoid('+repr(t_b)+','+repr(t_e)+','+ \ + 'Vec4('+repr(c_a[0])+','+repr(c_a[1])+','+repr(c_a[2])+','+repr(c_a[3])+'),' + \ + 'Vec4('+repr(c_b[0])+','+repr(c_b[1])+','+repr(c_b[2])+','+repr(c_b[3])+'),' + \ + repr(per)+','+repr(mod)+')\n') file.write('# Emitter parameters\n') emissionType = self.emitter.getEmissionType() diff --git a/direct/src/pyinst/imputil.py b/direct/src/pyinst/imputil.py index 5c49f69b09..dadfe03900 100644 --- a/direct/src/pyinst/imputil.py +++ b/direct/src/pyinst/imputil.py @@ -223,7 +223,7 @@ class Importer: # execute the code within the module's namespace if not is_module: - exec result[1] in module.__dict__ + exec(result[1], module.__dict__) # insert the module into its parent if parent: diff --git a/direct/src/showutil/FreezeTool.py b/direct/src/showutil/FreezeTool.py index 089b91c2a9..4f0ac57ca4 100644 --- a/direct/src/showutil/FreezeTool.py +++ b/direct/src/showutil/FreezeTool.py @@ -657,7 +657,7 @@ class Freezer: __path__. """ str = 'import %s' % (moduleName) - exec str + exec(str) module = sys.modules[moduleName] for path in module.__path__: diff --git a/direct/src/tkpanels/FSMInspector.py b/direct/src/tkpanels/FSMInspector.py index 3ec7cafaaa..398cd1583f 100644 --- a/direct/src/tkpanels/FSMInspector.py +++ b/direct/src/tkpanels/FSMInspector.py @@ -71,7 +71,7 @@ class FSMInspector(AppShell): 'Set state label size', tearoff = 1) for size in (8, 10, 12, 14, 18, 24): menuBar.addmenuitem('Font Size', 'command', - 'Set font to: ' + repr(size) + ' Pts', label = `size` + ' Pts', + 'Set font to: ' + repr(size) + ' Pts', label = repr(size) + ' Pts', command = lambda s = self, sz = size: s.setFontSize(sz)) menuBar.addcascademenu('States', 'Marker Size', 'Set state marker size', tearoff = 1) From c1273d5684262de045785bf42a0b1243a89444c3 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 18:42:11 +0000 Subject: [PATCH 10/37] PyEval_InitThreads should go after Py_Initialize in Python 3 --- direct/src/plugin/p3dPythonRun.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/direct/src/plugin/p3dPythonRun.cxx b/direct/src/plugin/p3dPythonRun.cxx index a72ebdfcad..d6b2e9df1d 100755 --- a/direct/src/plugin/p3dPythonRun.cxx +++ b/direct/src/plugin/p3dPythonRun.cxx @@ -20,7 +20,7 @@ #include "nativeWindowHandle.h" #ifndef CPPPARSER -#include "py_panda.h" +#include "py_panda.h" IMPORT_THIS struct Dtool_PyTypedObject Dtool_WindowHandle; #endif @@ -81,9 +81,9 @@ P3DPythonRun(const char *program_name, const char *archive_file, // Initialize Python. It appears to be important to do this before // we open the pipe streams and spawn the thread, below. - PyEval_InitThreads(); Py_SetProgramName((char *)_program_name.c_str()); Py_Initialize(); + PyEval_InitThreads(); PySys_SetArgv(_py_argc, _py_argv); // Open the error output before we do too much more. From 88048bf3dac3714615de8a17a6b6ae9eab824db2 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 19:49:09 +0000 Subject: [PATCH 11/37] Fix use of has_key and map() --- direct/src/actor/Actor.py | 6 +- direct/src/cluster/ClusterClient.py | 22 ++-- direct/src/cluster/ClusterServer.py | 14 +-- direct/src/directscripts/packpanda.py | 2 +- direct/src/directtools/DirectLights.py | 4 +- direct/src/directtools/DirectSession.py | 14 +-- direct/src/directtools/DirectUtil.py | 2 +- direct/src/distributed/CRCache.py | 8 +- direct/src/distributed/ClientRepository.py | 2 +- .../src/distributed/ClientRepositoryBase.py | 10 +- .../distributed/DistributedCartesianGridAI.py | 2 +- direct/src/distributed/DoInterestManager.py | 12 +- direct/src/distributed/OldClientRepository.py | 2 +- direct/src/distributed/ParentMgr.py | 6 +- direct/src/distributed/ServerRepository.py | 4 +- direct/src/ffi/FFIEnvironment.py | 2 +- direct/src/ffi/FFIInterrogateDatabase.py | 2 +- direct/src/ffi/FFIOverload.py | 2 +- direct/src/ffi/FFIRename.py | 2 +- direct/src/filter/CommonFilters.py | 104 +++++++++--------- direct/src/gui/DirectDialog.py | 6 +- direct/src/gui/DirectGuiBase.py | 10 +- direct/src/gui/DirectGuiTest.py | 2 +- direct/src/gui/DirectScrolledList.py | 6 +- direct/src/gui/DirectWaitBar.py | 2 +- direct/src/http/WebRequest.py | 2 +- direct/src/http/webAIInspector.py | 6 +- direct/src/interval/MetaInterval.py | 8 +- direct/src/leveleditor/ObjectPropertyUI.py | 6 +- direct/src/p3d/DeploymentTools.py | 14 +-- direct/src/p3d/FileSpec.py | 4 +- direct/src/p3d/PackageInfo.py | 12 +- direct/src/p3d/Packager.py | 10 +- direct/src/p3d/packp3d.py | 2 +- direct/src/plugin_installer/make_installer.py | 2 +- .../src/plugin_standalone/make_osx_bundle.py | 2 +- direct/src/pyinst/finder.py | 2 +- direct/src/pyinst/modulefinder.py | 12 +- direct/src/pyinst/resource.py | 2 +- direct/src/showbase/Audio3DManager.py | 6 +- direct/src/showbase/Factory.py | 2 +- direct/src/showbase/PythonUtil.py | 5 +- direct/src/showbase/VFSImporter.py | 2 +- direct/src/showbase/VerboseImport.py | 2 +- direct/src/showutil/TexMemWatcher.py | 2 +- direct/src/tkpanels/DirectSessionPanel.py | 5 +- direct/src/tkpanels/Inspector.py | 6 +- direct/src/tkpanels/MopathRecorder.py | 2 +- direct/src/tkpanels/ParticlePanel.py | 4 +- direct/src/tkpanels/Placer.py | 2 +- direct/src/tkwidgets/EntryScale.py | 3 +- direct/src/tkwidgets/Floater.py | 3 +- direct/src/tkwidgets/Slider.py | 2 +- direct/src/tkwidgets/Tree.py | 6 +- direct/src/tkwidgets/Valuator.py | 8 +- direct/src/tkwidgets/VectorWidgets.py | 3 +- direct/src/wxwidgets/WxPandaShell.py | 24 ++-- 57 files changed, 205 insertions(+), 214 deletions(-) diff --git a/direct/src/actor/Actor.py b/direct/src/actor/Actor.py index a5ecbaf1cb..53eaf3808d 100644 --- a/direct/src/actor/Actor.py +++ b/direct/src/actor/Actor.py @@ -1006,7 +1006,7 @@ class Actor(DirectObject, NodePath): return # remove the part - if (partBundleDict.has_key(partName)): + if (partName in partBundleDict): partBundleDict[partName].partBundleNP.removeNode() del(partBundleDict[partName]) @@ -1019,7 +1019,7 @@ class Actor(DirectObject, NodePath): return # remove the animations - if (partDict.has_key(partName)): + if (partName in partDict): del(partDict[partName]) # remove the bundle handle, in case this part is ever @@ -1802,7 +1802,7 @@ class Actor(DirectObject, NodePath): # Get all main parts, but not sub-parts. animDictItems = [] for thisPart, animDict in partDict.items(): - if not self.__subpartDict.has_key(thisPart): + if thisPart not in self.__subpartDict: animDictItems.append((thisPart, animDict)) else: diff --git a/direct/src/cluster/ClusterClient.py b/direct/src/cluster/ClusterClient.py index 1fe8d9569d..adb7f8744e 100644 --- a/direct/src/cluster/ClusterClient.py +++ b/direct/src/cluster/ClusterClient.py @@ -137,7 +137,7 @@ class ClusterClient(DirectObject.DirectObject): object = pair[1] name = self.controlMappings[object][0] serverList = self.controlMappings[object][1] - if (self.objectMappings.has_key(object)): + if (object in self.objectMappings): self.moveObject(self.objectMappings[object],name,serverList, self.controlOffsets[object], self.objectHasColor[object]) self.sendNamedMovementDone() @@ -204,20 +204,20 @@ class ClusterClient(DirectObject.DirectObject): def addNamedObjectMapping(self,object,name,hasColor = True): - if (not self.objectMappings.has_key(name)): + if (name not in self.objectMappings): self.objectMappings[name] = object self.objectHasColor[name] = hasColor else: self.notify.debug('attempt to add duplicate named object: '+name) def removeObjectMapping(self,name): - if (self.objectMappings.has_key(name)): + if (name in self.objectMappings): self.objectMappings.pop(name) def addControlMapping(self,objectName,controlledName, serverList = None, offset = None, priority = 0): - if (not self.controlMappings.has_key(objectName)): + if (objectName not in self.controlMappings): if (serverList == None): serverList = range(len(self.serverList)) if (offset == None): @@ -239,11 +239,11 @@ class ClusterClient(DirectObject.DirectObject): #self.notify.debug('attempt to add duplicate controlled object: '+name) def setControlMappingOffset(self,objectName,offset): - if (self.controlMappings.has_key(objectName)): + if (objectName in self.controlMappings): self.controlOffsets[objectName] = offset def removeControlMapping(self,name, serverList = None): - if (self.controlMappings.has_key(name)): + if (name in self.controlMappings): if (serverList == None): self.controlMappings.pop(name) @@ -299,7 +299,7 @@ class ClusterClient(DirectObject.DirectObject): def selectNodePath(self, nodePath): name = self.getNodePathName(nodePath) - if self.taggedObjects.has_key(name): + if name in self.taggedObjects: taskMgr.remove("moveSelectedTask") tag = self.taggedObjects[name] function = tag["selectFunction"] @@ -312,7 +312,7 @@ class ClusterClient(DirectObject.DirectObject): def deselectNodePath(self, nodePath): name = self.getNodePathName(nodePath) - if self.taggedObjects.has_key(name): + if name in self.taggedObjects: tag = self.taggedObjects[name] function = tag["deselectFunction"] args = tag["deselectArgs"] @@ -323,7 +323,7 @@ class ClusterClient(DirectObject.DirectObject): def sendCamFrustum(self, focalLength, filmSize, filmOffset, indexList=[]): if indexList: - serverList = map(lambda i: self.serverList[i], indexList) + serverList = [self.serverList[i] for i in indexList] else: serverList = self.serverList for server in serverList: @@ -381,7 +381,7 @@ class ClusterClient(DirectObject.DirectObject): #print "name" #if (name == "camNode"): # print x,y,z,h,p,r, sx, sy, sz,red,g,b,a, hidden - if (self.objectMappings.has_key(name)): + if (name in self.objectMappings): self.objectMappings[name].setPosHpr(render, x, y, z, h, p, r) self.objectMappings[name].setScale(render,sx,sy,sz) if (self.objectHasColor[name]): @@ -598,7 +598,7 @@ def createClusterClient(): # setup camera offsets based on cluster-config clusterConfig = base.config.GetString('cluster-config', 'single-server') # No cluster config specified! - if not ClientConfigs.has_key(clusterConfig): + if clusterConfig not in ClientConfigs: base.notify.warning( 'createClusterClient: %s cluster-config is undefined.' % clusterConfig) diff --git a/direct/src/cluster/ClusterServer.py b/direct/src/cluster/ClusterServer.py index b2bd835926..a4a8177a9d 100644 --- a/direct/src/cluster/ClusterServer.py +++ b/direct/src/cluster/ClusterServer.py @@ -102,14 +102,14 @@ class ClusterServer(DirectObject.DirectObject): def addNamedObjectMapping(self,object,name,hasColor = True, priority = 0): - if (not self.objectMappings.has_key(name)): + if (name not in self.objectMappings): self.objectMappings[name] = object self.objectHasColor[name] = hasColor else: self.notify.debug('attempt to add duplicate named object: '+name) def removeObjectMapping(self,name): - if (self.objectMappings.has_key(name)): + if (name in self.objectMappings): self.objectMappings.pop(name) @@ -125,7 +125,7 @@ class ClusterServer(DirectObject.DirectObject): def addControlMapping(self,objectName,controlledName, offset = None, priority = 0): - if (not self.controlMappings.has_key(objectName)): + if (objectName not in self.controlMappings): self.controlMappings[objectName] = controlledName if (offset == None): offset = Vec3(0,0,0) @@ -136,12 +136,12 @@ class ClusterServer(DirectObject.DirectObject): self.notify.debug('attempt to add duplicate controlled object: '+name) def setControlMappingOffset(self,objectName,offset): - if (self.controlMappings.has_key(objectName)): + if (objectName in self.controlMappings): self.controlOffsets[objectName] = offset def removeControlMapping(self,name): - if (self.controlMappings.has_key(name)): + if (name in self.controlMappings): self.controlMappings.pop(name) self.controlPriorities.pop(name) self.redoSortedPriorities() @@ -156,7 +156,7 @@ class ClusterServer(DirectObject.DirectObject): for pair in self.sortedControlPriorities: object = pair[1] name = self.controlMappings[object] - if (self.objectMappings.has_key(object)): + if (object in self.objectMappings): self.moveObject(self.objectMappings[object],name,self.controlOffsets[object], self.objectHasColor[object]) @@ -297,7 +297,7 @@ class ClusterServer(DirectObject.DirectObject): def handleNamedMovement(self, data): """ Update cameraJig position to reflect latest position """ (name,x, y, z, h, p, r,sx,sy,sz, red, g, b, a, hidden) = data - if (self.objectMappings.has_key(name)): + if (name in self.objectMappings): self.objectMappings[name].setPosHpr(render, x, y, z, h, p, r) self.objectMappings[name].setScale(render,sx,sy,sz) self.objectMappings[name].setColor(red,g,b,a) diff --git a/direct/src/directscripts/packpanda.py b/direct/src/directscripts/packpanda.py index a8d9b90386..72e33c3e9b 100755 --- a/direct/src/directscripts/packpanda.py +++ b/direct/src/directscripts/packpanda.py @@ -165,7 +165,7 @@ if (sys.platform == "win32"): def limitedCopyTree(src, dst, rmdir): if (os.path.isdir(src)): - if (rmdir.has_key(os.path.basename(src))): + if (os.path.basename(src) in rmdir): return if (not os.path.isdir(dst)): os.mkdir(dst) for x in os.listdir(src): diff --git a/direct/src/directtools/DirectLights.py b/direct/src/directtools/DirectLights.py index 59eba21947..5e5a5eb5e2 100644 --- a/direct/src/directtools/DirectLights.py +++ b/direct/src/directtools/DirectLights.py @@ -48,11 +48,11 @@ class DirectLights(NodePath): self.delete(light) def asList(self): - return map(lambda n, s=self: s[n], self.getNameList()) + return [self[n] for n in self.getNameList()] def getNameList(self): # Return a sorted list of all lights in the light dict - nameList = map(lambda x: x.getName(), self.lightDict.values()) + nameList = [x.getName() for x in self.lightDict.values()] nameList.sort() return nameList diff --git a/direct/src/directtools/DirectSession.py b/direct/src/directtools/DirectSession.py index e4508c89df..a68012c2d8 100644 --- a/direct/src/directtools/DirectSession.py +++ b/direct/src/directtools/DirectSession.py @@ -42,7 +42,7 @@ class DirectSession(DirectObject): self.fIgnoreDirectOnlyKeyMap = 0 # [gjeon] to skip old direct controls in new LE self.drList = DisplayRegionList() - self.iRayList = map(lambda x: x.iRay, self.drList) + self.iRayList = [x.iRay for x in self.drList] self.dr = self.drList[0] self.win = base.win self.camera = base.camera @@ -196,8 +196,8 @@ class DirectSession(DirectObject): 'alt', 'alt-up', 'alt-repeat', ] - keyList = map(chr, range(97, 123)) - keyList.extend(map(chr, range(48, 58))) + keyList = [chr(i) for i in range(97, 123)] + keyList.extend([chr(i) for i in range(48, 58)]) keyList.extend(["`", "-", "=", "[", "]", ";", "'", ",", ".", "/", "\\"]) self.specialKeys = ['escape', 'delete', 'page_up', 'page_down', 'enter'] @@ -209,8 +209,8 @@ class DirectSession(DirectObject): return "shift-%s"%a self.keyEvents = keyList[:] - self.keyEvents.extend(map(addCtrl, keyList)) - self.keyEvents.extend(map(addShift, keyList)) + self.keyEvents.extend(list(map(addCtrl, keyList))) + self.keyEvents.extend(list(map(addShift, keyList))) self.keyEvents.extend(self.specialKeys) self.mouseEvents = ['mouse1', 'mouse1-up', @@ -996,7 +996,7 @@ class DirectSession(DirectObject): # Get last item off of redo list undoGroup = self.popUndoGroup() # Record redo information - nodePathList = map(lambda x: x[0], undoGroup) + nodePathList = [x[0] for x in undoGroup] self.pushRedo(nodePathList) # Now undo xform for group for pose in undoGroup: @@ -1010,7 +1010,7 @@ class DirectSession(DirectObject): # Get last item off of redo list redoGroup = self.popRedoGroup() # Record undo information - nodePathList = map(lambda x: x[0], redoGroup) + nodePathList = [x[0] for x in redoGroup] self.pushUndo(nodePathList, fResetRedo = 0) # Redo xform for pose in redoGroup: diff --git a/direct/src/directtools/DirectUtil.py b/direct/src/directtools/DirectUtil.py index ac7c886c5b..224b069b9d 100644 --- a/direct/src/directtools/DirectUtil.py +++ b/direct/src/directtools/DirectUtil.py @@ -79,7 +79,7 @@ def getFileData(filename, separator = ','): if l: # If its a valid line, split on separator and # strip leading/trailing whitespace from each element - data = map(lambda s: s.strip(), l.split(separator)) + data = [s.strip() for s in l.split(separator)] fileData.append(data) return fileData diff --git a/direct/src/distributed/CRCache.py b/direct/src/distributed/CRCache.py index 9117d5586d..947609decf 100644 --- a/direct/src/distributed/CRCache.py +++ b/direct/src/distributed/CRCache.py @@ -59,7 +59,7 @@ class CRCache: doId = distObj.getDoId() # Error check success = False - if self.dict.has_key(doId): + if doId in self.dict: CRCache.notify.warning("Double cache attempted for distObj " + str(doId)) else: @@ -89,7 +89,7 @@ class CRCache: def retrieve(self, doId): assert self.checkCache() - if self.dict.has_key(doId): + if doId in self.dict: # Find the object distObj = self.dict[doId] # Remove it from the dictionary @@ -103,11 +103,11 @@ class CRCache: return None def contains(self, doId): - return self.dict.has_key(doId) + return doId in self.dict def delete(self, doId): assert self.checkCache() - assert self.dict.has_key(doId) + assert doId in self.dict # Look it up distObj = self.dict[doId] # Remove it from the dict and fifo diff --git a/direct/src/distributed/ClientRepository.py b/direct/src/distributed/ClientRepository.py index 761def7c91..fef18fea80 100644 --- a/direct/src/distributed/ClientRepository.py +++ b/direct/src/distributed/ClientRepository.py @@ -372,7 +372,7 @@ class ClientRepository(ClientRepositoryBase): This is not a distributed message and does not delete the object on the server or on any other client. """ - if self.doId2do.has_key(doId): + if doId in self.doId2do: # If it is in the dictionary, remove it. obj = self.doId2do[doId] # Remove it from the dictionary diff --git a/direct/src/distributed/ClientRepositoryBase.py b/direct/src/distributed/ClientRepositoryBase.py index 406133f68b..2b0ebaa632 100644 --- a/direct/src/distributed/ClientRepositoryBase.py +++ b/direct/src/distributed/ClientRepositoryBase.py @@ -221,7 +221,7 @@ class ClientRepositoryBase(ConnectionRepository): return Task.done def generateWithRequiredFields(self, dclass, doId, di, parentId, zoneId): - if self.doId2do.has_key(doId): + if doId in self.doId2do: # ...it is in our dictionary. # Just update it. distObj = self.doId2do[doId] @@ -269,7 +269,7 @@ class ClientRepositoryBase(ConnectionRepository): def generateWithRequiredOtherFields(self, dclass, doId, di, parentId = None, zoneId = None): - if self.doId2do.has_key(doId): + if doId in self.doId2do: # ...it is in our dictionary. # Just update it. distObj = self.doId2do[doId] @@ -315,7 +315,7 @@ class ClientRepositoryBase(ConnectionRepository): return distObj def generateWithRequiredOtherFieldsOwner(self, dclass, doId, di): - if self.doId2ownerView.has_key(doId): + if doId in self.doId2ownerView: # ...it is in our dictionary. # Just update it. self.notify.error('duplicate owner generate for %s (%s)' % ( @@ -359,7 +359,7 @@ class ClientRepositoryBase(ConnectionRepository): def disableDoId(self, doId, ownerView=False): table, cache = self.getTables(ownerView) # Make sure the object exists - if table.has_key(doId): + if doId in table: # Look up the object distObj = table[doId] # remove the object from the dictionary @@ -378,7 +378,7 @@ class ClientRepositoryBase(ConnectionRepository): # make sure we're not leaking distObj.detectLeaks() - elif self.deferredDoIds.has_key(doId): + elif doId in self.deferredDoIds: # The object had been deferred. Great; we don't even have # to generate it now. del self.deferredDoIds[doId] diff --git a/direct/src/distributed/DistributedCartesianGridAI.py b/direct/src/distributed/DistributedCartesianGridAI.py index 3cdeef45b2..647d8153fd 100755 --- a/direct/src/distributed/DistributedCartesianGridAI.py +++ b/direct/src/distributed/DistributedCartesianGridAI.py @@ -65,7 +65,7 @@ class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase): # Remove grid parent for this av avId = av.doId - if self.gridObjects.has_key(avId): + if avId in self.gridObjects: del self.gridObjects[avId] # Stop task if there are no more av's being managed diff --git a/direct/src/distributed/DoInterestManager.py b/direct/src/distributed/DoInterestManager.py index d3d6e4c4cb..6bf73494fd 100755 --- a/direct/src/distributed/DoInterestManager.py +++ b/direct/src/distributed/DoInterestManager.py @@ -147,7 +147,7 @@ class DoInterestManager(DirectObject.DirectObject): # still a valid interest handle if not isinstance(handle, InterestHandle): return False - return DoInterestManager._interests.has_key(handle.asInt()) + return handle.asInt() in DoInterestManager._interests def updateInterestDescription(self, handle, desc): iState = DoInterestManager._interests.get(handle.asInt()) @@ -240,7 +240,7 @@ class DoInterestManager(DirectObject.DirectObject): if not event: event = self._getAnonymousEvent('removeInterest') handle = handle.asInt() - if DoInterestManager._interests.has_key(handle): + if handle in DoInterestManager._interests: existed = True intState = DoInterestManager._interests[handle] if event: @@ -287,7 +287,7 @@ class DoInterestManager(DirectObject.DirectObject): assert isinstance(handle, InterestHandle) existed = False handle = handle.asInt() - if DoInterestManager._interests.has_key(handle): + if handle in DoInterestManager._interests: existed = True intState = DoInterestManager._interests[handle] if intState.isPendingDelete(): @@ -345,7 +345,7 @@ class DoInterestManager(DirectObject.DirectObject): exists = False if event is None: event = self._getAnonymousEvent('alterInterest') - if DoInterestManager._interests.has_key(handle): + if handle in DoInterestManager._interests: if description is not None: DoInterestManager._interests[handle].desc = description else: @@ -427,7 +427,7 @@ class DoInterestManager(DirectObject.DirectObject): """ assert DoInterestManager.notify.debugCall() - if DoInterestManager._interests.has_key(handle): + if handle in DoInterestManager._interests: if DoInterestManager._interests[handle].isPendingDelete(): # make sure there is no pending event for this interest if DoInterestManager._interests[handle].context == NO_CONTEXT: @@ -594,7 +594,7 @@ class DoInterestManager(DirectObject.DirectObject): DoInterestManager.notify.debug( "handleInterestDoneMessage--> Received handle %s, context %s" % ( handle, contextId)) - if DoInterestManager._interests.has_key(handle): + if handle in DoInterestManager._interests: eventsToSend = [] # if the context matches, send out the event if contextId == DoInterestManager._interests[handle].context: diff --git a/direct/src/distributed/OldClientRepository.py b/direct/src/distributed/OldClientRepository.py index 65c3e47e86..2e996cc5df 100644 --- a/direct/src/distributed/OldClientRepository.py +++ b/direct/src/distributed/OldClientRepository.py @@ -168,7 +168,7 @@ class OldClientRepository(ClientRepositoryBase): dclass.stopGenerate() def generateWithRequiredFields(self, dclass, doId, di): - if self.doId2do.has_key(doId): + if doId in self.doId2do: # ...it is in our dictionary. # Just update it. distObj = self.doId2do[doId] diff --git a/direct/src/distributed/ParentMgr.py b/direct/src/distributed/ParentMgr.py index a979c415ba..eea9d5438f 100644 --- a/direct/src/distributed/ParentMgr.py +++ b/direct/src/distributed/ParentMgr.py @@ -57,7 +57,7 @@ class ParentMgr: self.pendingParentToken2children[parentToken].remove(child) def requestReparent(self, child, parentToken): - if self.token2nodepath.has_key(parentToken): + if parentToken in self.token2nodepath: # this parent has registered # this child may already be waiting on a different parent; # make sure they aren't any more @@ -82,7 +82,7 @@ class ParentMgr: child.reparentTo(hidden) def registerParent(self, token, parent): - if self.token2nodepath.has_key(token): + if token in self.token2nodepath: self.notify.error( "registerParent: token '%s' already registered, referencing %s" % (token, repr(self.token2nodepath[token]))) @@ -141,7 +141,7 @@ class ParentMgr: del self.pendingChild2parentToken[child] def unregisterParent(self, token): - if not self.token2nodepath.has_key(token): + if token not in self.token2nodepath: self.notify.warning("unregisterParent: unknown parent token '%s'" % token) return diff --git a/direct/src/distributed/ServerRepository.py b/direct/src/distributed/ServerRepository.py index f155364704..5a24f81299 100644 --- a/direct/src/distributed/ServerRepository.py +++ b/direct/src/distributed/ServerRepository.py @@ -699,7 +699,7 @@ class ServerRepository: if self.notify.getDebug(): self.notify.debug( - "ServerRepository sending to all in zone %s except %s:" % (zoneId, map(lambda c: c.doIdBase, exceptionList))) + "ServerRepository sending to all in zone %s except %s:" % (zoneId, [c.doIdBase for c in exceptionList])) #datagram.dumpHex(ostream) for client in self.zonesToClients.get(zoneId, []): @@ -716,7 +716,7 @@ class ServerRepository: if self.notify.getDebug(): self.notify.debug( - "ServerRepository sending to all except %s:" % (map(lambda c: c.doIdBase, exceptionList),)) + "ServerRepository sending to all except %s:" % ([c.doIdBase for c in exceptionList],)) #datagram.dumpHex(ostream) for client in self.clientsByConnection.values(): diff --git a/direct/src/ffi/FFIEnvironment.py b/direct/src/ffi/FFIEnvironment.py index 443a2cbb81..f857c69d34 100644 --- a/direct/src/ffi/FFIEnvironment.py +++ b/direct/src/ffi/FFIEnvironment.py @@ -12,7 +12,7 @@ class FFIEnvironment: self.manifests = [] def addType(self, typeDescriptor, name): - if self.types.has_key(name): + if name in self.types: FFIConstants.notify.info('Redefining type named: ' + name) self.types[name] = typeDescriptor diff --git a/direct/src/ffi/FFIInterrogateDatabase.py b/direct/src/ffi/FFIInterrogateDatabase.py index a82d852060..f203addc82 100644 --- a/direct/src/ffi/FFIInterrogateDatabase.py +++ b/direct/src/ffi/FFIInterrogateDatabase.py @@ -238,7 +238,7 @@ class FFIInterrogateDatabase: self.environment = FFIEnvironment.FFIEnvironment() def isDefinedType(self, typeIndex): - return self.typeIndexMap.has_key(typeIndex) + return typeIndex in self.typeIndexMap def constructDescriptor(self, typeIndex): if interrogate_type_is_atomic(typeIndex): diff --git a/direct/src/ffi/FFIOverload.py b/direct/src/ffi/FFIOverload.py index 87e7041e13..51b85e8787 100644 --- a/direct/src/ffi/FFIOverload.py +++ b/direct/src/ffi/FFIOverload.py @@ -337,7 +337,7 @@ class FFIMethodArgumentTree: # methodSpec in this dictionary self.tree[typeDesc] = [None, methodSpec] else: - if self.tree.has_key(typeDesc): + if typeDesc in self.tree: # If there already is a tree here, jump into and pass the # cdr of the arg list subTree = self.tree[typeDesc][0] diff --git a/direct/src/ffi/FFIRename.py b/direct/src/ffi/FFIRename.py index 69c985ffbe..7a637cd930 100644 --- a/direct/src/ffi/FFIRename.py +++ b/direct/src/ffi/FFIRename.py @@ -108,7 +108,7 @@ def classNameFromCppName(cppName): firstChar = 0 else: className = className + char - if classRenameDictionary.has_key(className): + if className in classRenameDictionary: className = classRenameDictionary[className] if (className == ''): diff --git a/direct/src/filter/CommonFilters.py b/direct/src/filter/CommonFilters.py index c548e871fb..a9836fdca4 100644 --- a/direct/src/filter/CommonFilters.py +++ b/direct/src/filter/CommonFilters.py @@ -86,28 +86,28 @@ class CommonFilters: auxbits = 0 needtex = {} needtex["color"] = True - if (configuration.has_key("CartoonInk")): + if ("CartoonInk" in configuration): needtex["aux"] = True auxbits |= AuxBitplaneAttrib.ABOAuxNormal - if (configuration.has_key("AmbientOcclusion")): + if ("AmbientOcclusion" in configuration): needtex["depth"] = True needtex["ssao0"] = True needtex["ssao1"] = True needtex["ssao2"] = True needtex["aux"] = True auxbits |= AuxBitplaneAttrib.ABOAuxNormal - if (configuration.has_key("BlurSharpen")): + if ("BlurSharpen" in configuration): needtex["blur0"] = True needtex["blur1"] = True - if (configuration.has_key("Bloom")): + if ("Bloom" in configuration): needtex["bloom0"] = True needtex["bloom1"] = True needtex["bloom2"] = True needtex["bloom3"] = True auxbits |= AuxBitplaneAttrib.ABOGlow - if (configuration.has_key("ViewGlow")): + if ("ViewGlow" in configuration): auxbits |= AuxBitplaneAttrib.ABOGlow - if (configuration.has_key("VolumetricLighting")): + if ("VolumetricLighting" in configuration): needtex[configuration["VolumetricLighting"].source] = True for tex in needtex: self.textures[tex] = Texture("scene-"+tex) @@ -120,7 +120,7 @@ class CommonFilters: self.cleanup() return False - if (configuration.has_key("BlurSharpen")): + if ("BlurSharpen" in configuration): blur0=self.textures["blur0"] blur1=self.textures["blur1"] self.blur.append(self.manager.renderQuadInto(colortex=blur0,div=2)) @@ -130,7 +130,7 @@ class CommonFilters: self.blur[1].setShaderInput("src", blur0) self.blur[1].setShader(self.loadShader("filter-blury.sha")) - if (configuration.has_key("AmbientOcclusion")): + if ("AmbientOcclusion" in configuration): ssao0=self.textures["ssao0"] ssao1=self.textures["ssao1"] ssao2=self.textures["ssao2"] @@ -146,7 +146,7 @@ class CommonFilters: self.ssao[2].setShaderInput("src", ssao1) self.ssao[2].setShader(self.loadShader("filter-blury.sha")) - if (configuration.has_key("Bloom")): + if ("Bloom" in configuration): bloomconf = configuration["Bloom"] bloom0=self.textures["bloom0"] bloom1=self.textures["bloom1"] @@ -180,74 +180,74 @@ class CommonFilters: text += " uniform float4 texpad_txcolor,\n" text += " uniform float4 texpix_txcolor,\n" text += " out float4 l_texcoordC : TEXCOORD0,\n" - if (configuration.has_key("CartoonInk")): + if ("CartoonInk" in configuration): text += " uniform float4 texpad_txaux,\n" text += " uniform float4 texpix_txaux,\n" text += " out float4 l_texcoordN : TEXCOORD1,\n" - if (configuration.has_key("Bloom")): + if ("Bloom" in configuration): text += " uniform float4 texpad_txbloom3,\n" text += " out float4 l_texcoordB : TEXCOORD2,\n" - if (configuration.has_key("BlurSharpen")): + if ("BlurSharpen" in configuration): text += " uniform float4 texpad_txblur1,\n" text += " out float4 l_texcoordBS : TEXCOORD3,\n" - if (configuration.has_key("AmbientOcclusion")): + if ("AmbientOcclusion" in configuration): text += " uniform float4 texpad_txssao2,\n" text += " out float4 l_texcoordAO : TEXCOORD4,\n" text += " uniform float4x4 mat_modelproj)\n" text += "{\n" text += " l_position=mul(mat_modelproj, vtx_position);\n" text += " l_texcoordC=(vtx_position.xzxz * texpad_txcolor) + texpad_txcolor;\n" - if (configuration.has_key("CartoonInk")): + if ("CartoonInk" in configuration): text += " l_texcoordN=(vtx_position.xzxz * texpad_txaux) + texpad_txaux;\n" - if (configuration.has_key("Bloom")): + if ("Bloom" in configuration): text += " l_texcoordB=(vtx_position.xzxz * texpad_txbloom3) + texpad_txbloom3;\n" - if (configuration.has_key("BlurSharpen")): + if ("BlurSharpen" in configuration): text += " l_texcoordBS=(vtx_position.xzxz * texpad_txblur1) + texpad_txblur1;\n" - if (configuration.has_key("AmbientOcclusion")): + if ("AmbientOcclusion" in configuration): text += " l_texcoordAO=(vtx_position.xzxz * texpad_txssao2) + texpad_txssao2;\n" - if (configuration.has_key("HalfPixelShift")): + if ("HalfPixelShift" in configuration): text += " l_texcoordC+=texpix_txcolor*0.5;\n" - if (configuration.has_key("CartoonInk")): + if ("CartoonInk" in configuration): text += " l_texcoordN+=texpix_txaux*0.5;\n" text += "}\n" text += "void fshader(\n" text += "float4 l_texcoordC : TEXCOORD0,\n" text += "uniform float4 texpix_txcolor,\n" - if (configuration.has_key("CartoonInk")): + if ("CartoonInk" in configuration): text += "float4 l_texcoordN : TEXCOORD1,\n" text += "uniform float4 texpix_txaux,\n" - if (configuration.has_key("Bloom")): + if ("Bloom" in configuration): text += "float4 l_texcoordB : TEXCOORD2,\n" - if (configuration.has_key("BlurSharpen")): + if ("BlurSharpen" in configuration): text += "float4 l_texcoordBS : TEXCOORD3,\n" text += "uniform float4 k_blurval,\n" - if (configuration.has_key("AmbientOcclusion")): + if ("AmbientOcclusion" in configuration): text += "float4 l_texcoordAO : TEXCOORD4,\n" for key in self.textures: text += "uniform sampler2D k_tx" + key + ",\n" - if (configuration.has_key("CartoonInk")): + if ("CartoonInk" in configuration): text += "uniform float4 k_cartoonseparation,\n" text += "uniform float4 k_cartooncolor,\n" - if (configuration.has_key("VolumetricLighting")): + if ("VolumetricLighting" in configuration): text += "uniform float4 k_casterpos,\n" text += "uniform float4 k_vlparams,\n" text += "out float4 o_color : COLOR)\n" text += "{\n" text += " o_color = tex2D(k_txcolor, l_texcoordC.xy);\n" - if (configuration.has_key("CartoonInk")): + if ("CartoonInk" in configuration): text += CARTOON_BODY - if (configuration.has_key("AmbientOcclusion")): + if ("AmbientOcclusion" in configuration): text += "o_color *= tex2D(k_txssao2, l_texcoordAO.xy).r;\n" - if (configuration.has_key("BlurSharpen")): + if ("BlurSharpen" in configuration): text += " o_color = lerp(tex2D(k_txblur1, l_texcoordBS.xy), o_color, k_blurval.x);\n" - if (configuration.has_key("Bloom")): + if ("Bloom" in configuration): text += "o_color = saturate(o_color);\n"; text += "float4 bloom = 0.5*tex2D(k_txbloom3, l_texcoordB.xy);\n" text += "o_color = 1-((1-bloom)*(1-o_color));\n" - if (configuration.has_key("ViewGlow")): + if ("ViewGlow" in configuration): text += "o_color.r = o_color.a;\n" - if (configuration.has_key("VolumetricLighting")): + if ("VolumetricLighting" in configuration): text += "float decay = 1.0f;\n" text += "float2 curcoord = l_texcoordC.xy;\n" text += "float2 lightdir = curcoord - k_casterpos.xy;\n" @@ -262,7 +262,7 @@ class CommonFilters: text += " decay *= k_vlparams.y;\n" text += "}\n" text += "o_color += float4(vlcolor * k_vlparams.z, 1);\n" - if (configuration.has_key("Inverted")): + if ("Inverted" in configuration): text += "o_color = float4(1, 1, 1, 1) - o_color;\n" text += "}\n" @@ -273,18 +273,18 @@ class CommonFilters: self.task = taskMgr.add(self.update, "common-filters-update") if (changed == "CartoonInk") or fullrebuild: - if (configuration.has_key("CartoonInk")): + if ("CartoonInk" in configuration): c = configuration["CartoonInk"] self.finalQuad.setShaderInput("cartoonseparation", Vec4(c.separation, 0, c.separation, 0)) self.finalQuad.setShaderInput("cartooncolor", c.color) if (changed == "BlurSharpen") or fullrebuild: - if (configuration.has_key("BlurSharpen")): + if ("BlurSharpen" in configuration): blurval = configuration["BlurSharpen"] self.finalQuad.setShaderInput("blurval", Vec4(blurval, blurval, blurval, blurval)) if (changed == "Bloom") or fullrebuild: - if (configuration.has_key("Bloom")): + if ("Bloom" in configuration): bloomconf = configuration["Bloom"] intensity = bloomconf.intensity * 3.0 self.bloom[0].setShaderInput("blend", bloomconf.blendx, bloomconf.blendy, bloomconf.blendz, bloomconf.blendw * 2.0) @@ -293,13 +293,13 @@ class CommonFilters: self.bloom[3].setShaderInput("intensity", intensity, intensity, intensity, intensity) if (changed == "VolumetricLighting") or fullrebuild: - if (configuration.has_key("VolumetricLighting")): + if ("VolumetricLighting" in configuration): config = configuration["VolumetricLighting"] tcparam = config.density / float(config.numsamples) self.finalQuad.setShaderInput("vlparams", tcparam, config.decay, config.exposure, 0.0) if (changed == "AmbientOcclusion") or fullrebuild: - if (configuration.has_key("AmbientOcclusion")): + if ("AmbientOcclusion" in configuration): config = configuration["AmbientOcclusion"] 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) @@ -311,7 +311,7 @@ class CommonFilters: """Updates the shader inputs that need to be updated every frame. Normally, you shouldn't call this, it's being called in a task.""" - if self.configuration.has_key("VolumetricLighting"): + if "VolumetricLighting" in self.configuration: caster = self.configuration["VolumetricLighting"].caster casterpos = Point2() self.manager.camera.node().getLens().project(caster.getPos(self.manager.camera), casterpos) @@ -320,7 +320,7 @@ class CommonFilters: return task.cont def setCartoonInk(self, separation=1, color=(0, 0, 0, 1)): - fullrebuild = (self.configuration.has_key("CartoonInk") == False) + fullrebuild = (("CartoonInk" in self.configuration) == False) newconfig = FilterConfig() newconfig.separation = separation newconfig.color = color @@ -328,7 +328,7 @@ class CommonFilters: return self.reconfigure(fullrebuild, "CartoonInk") def delCartoonInk(self): - if (self.configuration.has_key("CartoonInk")): + if ("CartoonInk" in self.configuration): del self.configuration["CartoonInk"] return self.reconfigure(True, "CartoonInk") return True @@ -357,40 +357,40 @@ class CommonFilters: return self.reconfigure(fullrebuild, "Bloom") def delBloom(self): - if (self.configuration.has_key("Bloom")): + if ("Bloom" in self.configuration): del self.configuration["Bloom"] return self.reconfigure(True, "Bloom") return True def setHalfPixelShift(self): - fullrebuild = (self.configuration.has_key("HalfPixelShift") == False) + fullrebuild = (("HalfPixelShift" in self.configuration) == False) self.configuration["HalfPixelShift"] = 1 return self.reconfigure(fullrebuild, "HalfPixelShift") def delHalfPixelShift(self): - if (self.configuration.has_key("HalfPixelShift")): + if ("HalfPixelShift" in self.configuration): del self.configuration["HalfPixelShift"] return self.reconfigure(True, "HalfPixelShift") return True def setViewGlow(self): - fullrebuild = (self.configuration.has_key("ViewGlow") == False) + fullrebuild = (("ViewGlow" in self.configuration) == False) self.configuration["ViewGlow"] = 1 return self.reconfigure(fullrebuild, "ViewGlow") def delViewGlow(self): - if (self.configuration.has_key("ViewGlow")): + if ("ViewGlow" in self.configuration): del self.configuration["ViewGlow"] return self.reconfigure(True, "ViewGlow") return True def setInverted(self): - fullrebuild = (self.configuration.has_key("Inverted") == False) + fullrebuild = (("Inverted" in self.configuration) == False) self.configuration["Inverted"] = 1 return self.reconfigure(fullrebuild, "Inverted") def delInverted(self): - if (self.configuration.has_key("Inverted")): + if ("Inverted" in self.configuration): del self.configuration["Inverted"] return self.reconfigure(True, "Inverted") return True @@ -411,7 +411,7 @@ class CommonFilters: return self.reconfigure(fullrebuild, "VolumetricLighting") def delVolumetricLighting(self): - if (self.configuration.has_key("VolumetricLighting")): + if ("VolumetricLighting" in self.configuration): del self.configuration["VolumetricLighting"] return self.reconfigure(True, "VolumetricLighting") return True @@ -419,18 +419,18 @@ class CommonFilters: def setBlurSharpen(self, amount=0.0): """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.""" - fullrebuild = (self.configuration.has_key("BlurSharpen") == False) + fullrebuild = (("BlurSharpen" in self.configuration) == False) self.configuration["BlurSharpen"] = amount return self.reconfigure(fullrebuild, "BlurSharpen") def delBlurSharpen(self): - if (self.configuration.has_key("BlurSharpen")): + if ("BlurSharpen" in self.configuration): del self.configuration["BlurSharpen"] return self.reconfigure(True, "BlurSharpen") return True def setAmbientOcclusion(self, numsamples = 16, radius = 0.05, amount = 2.0, strength = 0.01, falloff = 0.000002): - fullrebuild = (self.configuration.has_key("AmbientOcclusion") == False) + fullrebuild = (("AmbientOcclusion" in self.configuration) == False) newconfig = FilterConfig() newconfig.numsamples = numsamples newconfig.radius = radius @@ -441,7 +441,7 @@ class CommonFilters: return self.reconfigure(fullrebuild, "AmbientOcclusion") def delAmbientOcclusion(self): - if (self.configuration.has_key("AmbientOcclusion")): + if ("AmbientOcclusion" in self.configuration): del self.configuration["AmbientOcclusion"] return self.reconfigure(True, "AmbientOcclusion") return True diff --git a/direct/src/gui/DirectDialog.py b/direct/src/gui/DirectDialog.py index a785b0a586..803cce5467 100644 --- a/direct/src/gui/DirectDialog.py +++ b/direct/src/gui/DirectDialog.py @@ -15,7 +15,7 @@ def findDialog(uniqueName): useful for debugging, to get a pointer to the current onscreen panel of a particular type. """ - if DirectDialog.AllDialogs.has_key(uniqueName): + if uniqueName in DirectDialog.AllDialogs: return DirectDialog.AllDialogs[uniqueName] return None @@ -27,7 +27,7 @@ def cleanupDialog(uniqueName): that opening panel A should automatically close panel B, for instance. """ - if DirectDialog.AllDialogs.has_key(uniqueName): + if uniqueName in DirectDialog.AllDialogs: # calling cleanup() will remove it out of the AllDialogs dict # This way it will get removed from the dict even it we did # not clean it up using this interface (ie somebody called @@ -330,7 +330,7 @@ class DirectDialog(DirectFrame): def cleanup(self): # Remove this panel out of the AllDialogs list uniqueName = self['dialogName'] - if DirectDialog.AllDialogs.has_key(uniqueName): + if uniqueName in DirectDialog.AllDialogs: del DirectDialog.AllDialogs[uniqueName] self.destroy() diff --git a/direct/src/gui/DirectGuiBase.py b/direct/src/gui/DirectGuiBase.py index 36edd099b6..3d9d66292d 100644 --- a/direct/src/gui/DirectGuiBase.py +++ b/direct/src/gui/DirectGuiBase.py @@ -439,7 +439,7 @@ class DirectGuiBase(DirectObject.DirectObject): Get current configuration setting for this option """ # Return the value of an option, for example myWidget['font']. - if self._optionInfo.has_key(option): + if option in self._optionInfo: return self._optionInfo[option][DGG._OPT_VALUE] else: index = string.find(option, '_') @@ -448,7 +448,7 @@ class DirectGuiBase(DirectObject.DirectObject): componentOption = option[(index + 1):] # Expand component alias - if self.__componentAliases.has_key(component): + if component in self.__componentAliases: component, subComponent = self.__componentAliases[ component] if subComponent is not None: @@ -457,7 +457,7 @@ class DirectGuiBase(DirectObject.DirectObject): # Expand option string to write on error option = component + '_' + componentOption - if self.__componentInfo.has_key(component): + if component in self.__componentInfo: # Call cget on the component. componentCget = self.__componentInfo[component][3] return componentCget(componentOption) @@ -582,7 +582,7 @@ class DirectGuiBase(DirectObject.DirectObject): # Expand component alias # Example entry which is an alias for entryField_entry - if self.__componentAliases.has_key(component): + if component in self.__componentAliases: # component = entryField, subComponent = entry component, subComponent = self.__componentAliases[component] if subComponent is not None: @@ -608,7 +608,7 @@ class DirectGuiBase(DirectObject.DirectObject): return names def hascomponent(self, component): - return self.__componentInfo.has_key(component) + return component in self.__componentInfo def destroycomponent(self, name): # Remove a megawidget component. diff --git a/direct/src/gui/DirectGuiTest.py b/direct/src/gui/DirectGuiTest.py index 4bbc97affe..2b076eed00 100644 --- a/direct/src/gui/DirectGuiTest.py +++ b/direct/src/gui/DirectGuiTest.py @@ -124,7 +124,7 @@ if __name__ == "__main__": command = printDialogValue) customDialog = DirectDialog(text = 'Pick a number', - buttonTextList = map(str, range(10)), + buttonTextList = [str(i) for i in range(10)], buttonValueList = range(10), command = printDialogValue) diff --git a/direct/src/gui/DirectScrolledList.py b/direct/src/gui/DirectScrolledList.py index cac7874007..aa0293ae5e 100644 --- a/direct/src/gui/DirectScrolledList.py +++ b/direct/src/gui/DirectScrolledList.py @@ -22,10 +22,10 @@ class DirectScrolledListItem(DirectButton): def __init__(self, parent=None, **kw): assert self.notify.debugStateCall(self) self.parent = parent - if kw.has_key("command"): + if "command" in kw: self.nextCommand = kw.get("command") del kw["command"] - if kw.has_key("extraArgs"): + if "extraArgs" in kw: self.nextCommandExtraArgs = kw.get("extraArgs") del kw["extraArgs"] optiondefs = ( @@ -59,7 +59,7 @@ class DirectScrolledList(DirectFrame): # if 'items' is a list of strings, make a copy for our use # so we can modify it without mangling the user's list - if kw.has_key('items'): + if 'items' in kw: for item in kw['items']: if type(item) != type(''): break diff --git a/direct/src/gui/DirectWaitBar.py b/direct/src/gui/DirectWaitBar.py index b84df687a0..c1e7bee0c9 100644 --- a/direct/src/gui/DirectWaitBar.py +++ b/direct/src/gui/DirectWaitBar.py @@ -35,7 +35,7 @@ class DirectWaitBar(DirectFrame): ('barRelief', DGG.FLAT, self.setBarRelief), ('sortOrder', NO_FADE_SORT_INDEX, None), ) - if kw.has_key('text'): + if 'text' in kw: textoptiondefs = ( ('text_pos', (0, -0.025), None), ('text_scale', 0.1, None) diff --git a/direct/src/http/WebRequest.py b/direct/src/http/WebRequest.py index 3dc1b7c161..95b058ef5e 100755 --- a/direct/src/http/WebRequest.py +++ b/direct/src/http/WebRequest.py @@ -262,7 +262,7 @@ class WebRequestDispatcher(object): def enableLandingPage(self, enable): if enable: - if not self.__dict__.has_key("landingPage"): + if "landingPage" not in self.__dict__: self.landingPage = LandingPage() self.registerGETHandler("/", self._main, returnsResponse = True, autoSkin = True) self.registerGETHandler("/services", self._services, returnsResponse = True, autoSkin = True) diff --git a/direct/src/http/webAIInspector.py b/direct/src/http/webAIInspector.py index 9e4d3f8ac3..8c3da6ae2f 100755 --- a/direct/src/http/webAIInspector.py +++ b/direct/src/http/webAIInspector.py @@ -292,7 +292,7 @@ def inspectObject(anObject): def inspectorFor(anObject): typeName = string.capitalize(type(anObject).__name__) + 'Type' - if _InspectorMap.has_key(typeName): + if typeName in _InspectorMap: inspectorName = _InspectorMap[typeName] else: print "Can't find an inspector for " + typeName @@ -355,7 +355,7 @@ class Inspector: # self._partsList.append(each) def initializePartNames(self): - self._partNames = ['up'] + map(lambda each: str(each), self._partsList) + self._partNames = ['up'] + [str(each) for each in self._partsList] def title(self): "Subclasses may override." @@ -458,7 +458,7 @@ class DictionaryInspector(Inspector): if partNumber == 0: return self.object key = self.privatePartNumber(partNumber) - if self.object.has_key(key): + if key in self.object: return self.object[key] else: return getattr(self.object, key) diff --git a/direct/src/interval/MetaInterval.py b/direct/src/interval/MetaInterval.py index 4900cbfbc4..f521414593 100644 --- a/direct/src/interval/MetaInterval.py +++ b/direct/src/interval/MetaInterval.py @@ -38,7 +38,7 @@ class MetaInterval(CMetaInterval): #else: # Look for the name in the keyword params. - if kw.has_key('name'): + if 'name' in kw: name = kw['name'] del kw['name'] @@ -52,10 +52,10 @@ class MetaInterval(CMetaInterval): autoPause = 0 autoFinish = 0 - if kw.has_key('autoPause'): + if 'autoPause' in kw: autoPause = kw['autoPause'] del kw['autoPause'] - if kw.has_key('autoFinish'): + if 'autoFinish' in kw: autoFinish = kw['autoFinish'] del kw['autoFinish'] @@ -63,7 +63,7 @@ class MetaInterval(CMetaInterval): # appear to have for the purposes of computing the start time # for subsequent intervals in a sequence or track. self.phonyDuration = -1 - if kw.has_key('duration'): + if 'duration' in kw: self.phonyDuration = kw['duration'] del kw['duration'] diff --git a/direct/src/leveleditor/ObjectPropertyUI.py b/direct/src/leveleditor/ObjectPropertyUI.py index f04b21d3ad..9e918f6048 100755 --- a/direct/src/leveleditor/ObjectPropertyUI.py +++ b/direct/src/leveleditor/ObjectPropertyUI.py @@ -91,7 +91,7 @@ class ObjectPropUI(wx.Panel): value = self.getValue() frame = self.parent.editor.ui.animUI.curFrame - if self.parent.editor.animMgr.keyFramesInfo.has_key((objUID,propertyName)): + if (objUID, propertyName) in self.parent.editor.animMgr.keyFramesInfo: for i in range(len(self.parent.editor.animMgr.keyFramesInfo[(objUID,propertyName)])): if self.parent.editor.animMgr.keyFramesInfo[(objUID,propertyName)][i][AG.FRAME] == frame: del self.parent.editor.animMgr.keyFramesInfo[(objUID,propertyName)][i] @@ -239,8 +239,8 @@ class ObjectPropUITime(wx.Panel): hSizer = wx.BoxSizer(wx.HORIZONTAL) self.uiAmPm = wx.Choice(self.uiPane, -1, choices=['AM', 'PM']) - self.uiHour = wx.Choice(self.uiPane, -1, choices=map(lambda x : str(x), range(1, 13))) - self.uiMin = wx.Choice(self.uiPane, -1, choices=map(lambda x : str(x), range(0, 60, 15))) + self.uiHour = wx.Choice(self.uiPane, -1, choices=[str(x) for x in range(1, 13)]) + self.uiMin = wx.Choice(self.uiPane, -1, choices=[str(x) for x in range(0, 60, 15)]) hSizer.Add(self.uiAmPm) hSizer.Add(self.uiHour) diff --git a/direct/src/p3d/DeploymentTools.py b/direct/src/p3d/DeploymentTools.py index 02012cd87f..fde6a741a1 100644 --- a/direct/src/p3d/DeploymentTools.py +++ b/direct/src/p3d/DeploymentTools.py @@ -39,9 +39,9 @@ def archiveFilter(info): # Somewhat hacky, but it's the only way # permissions can work on a Windows box. if info.type != tarfile.DIRTYPE and '.' in info.name.rsplit('/', 1)[-1]: - info.mode = 0644 + info.mode = 0o644 else: - info.mode = 0755 + info.mode = 0o755 return info @@ -53,8 +53,8 @@ class TarInfoRoot(tarfile.TarInfo): gid = property(lambda self: 0, lambda self, x: None) uname = property(lambda self: "root", lambda self, x: None) gname = property(lambda self: "root", lambda self, x: None) - mode = property(lambda self: 0644 if self.type != tarfile.DIRTYPE and \ - '.' in self.name.rsplit('/', 1)[-1] else 0755, + mode = property(lambda self: 0o644 if self.type != tarfile.DIRTYPE and \ + '.' in self.name.rsplit('/', 1)[-1] else 0o755, lambda self, x: None) # On OSX, the root group is named "wheel". @@ -186,7 +186,7 @@ class Standalone: ohandle.close() phandle.close() - os.chmod(output.toOsSpecific(), 0755) + os.chmod(output.toOsSpecific(), 0o755) def getExtraFiles(self, platform): """ Returns a list of extra files that will need to be included @@ -550,7 +550,7 @@ class Installer: mf = Multifile() # Make sure that it isn't mounted before altering it, just to be safe vfs.unmount(archive) - os.chmod(archive.toOsSpecific(), 0644) + os.chmod(archive.toOsSpecific(), 0o644) if not mf.openReadWrite(archive): Installer.notify.warning("Failed to open archive %s" % (archive)) continue @@ -575,7 +575,7 @@ class Installer: # archive.unlink() #else: mf.close() - try: os.chmod(archive.toOsSpecific(), 0444) + try: os.chmod(archive.toOsSpecific(), 0o444) except: pass # Write out our own contents.xml file. diff --git a/direct/src/p3d/FileSpec.py b/direct/src/p3d/FileSpec.py index d0c7ca8766..78dff88fe8 100644 --- a/direct/src/p3d/FileSpec.py +++ b/direct/src/p3d/FileSpec.py @@ -205,9 +205,9 @@ class FileSpec: # On Windows, we have to change the file to read-write before # we can successfully update its timestamp. try: - os.chmod(pathname.toOsSpecific(), 0755) + os.chmod(pathname.toOsSpecific(), 0o755) os.utime(pathname.toOsSpecific(), (st.st_atime, self.timestamp)) - os.chmod(pathname.toOsSpecific(), 0555) + os.chmod(pathname.toOsSpecific(), 0o555) except OSError: pass diff --git a/direct/src/p3d/PackageInfo.py b/direct/src/p3d/PackageInfo.py index 6a173b57aa..7dcd35c62e 100644 --- a/direct/src/p3d/PackageInfo.py +++ b/direct/src/p3d/PackageInfo.py @@ -175,7 +175,7 @@ class PackageInfo: # Return the size of plan A, assuming it will work. plan = self.installPlans[0] - size = sum(map(lambda step: step.getEffort(), plan)) + size = sum([step.getEffort() for step in plan]) return size @@ -313,7 +313,7 @@ class PackageInfo: filename = Filename(self.getPackageDir(), self.descFileBasename) # Now that we've written the desc file, make it read-only. - os.chmod(filename.toOsSpecific(), 0444) + os.chmod(filename.toOsSpecific(), 0o444) if not self.__readDescFile(): # Weird, it passed the hash check, but we still can't read @@ -688,7 +688,7 @@ class PackageInfo: installPlans = self.installPlans self.installPlans = None for plan in installPlans: - self.totalPlanSize = sum(map(lambda step: step.getEffort(), plan)) + self.totalPlanSize = sum([step.getEffort() for step in plan]) self.totalPlanCompleted = 0 self.downloadProgress = 0 @@ -832,7 +832,7 @@ class PackageInfo: if bytesStarted: self.notify.info("Resuming %s after %s bytes already downloaded" % (url, bytesStarted)) # Make sure the file is writable. - os.chmod(targetPathname.toOsSpecific(), 0644) + os.chmod(targetPathname.toOsSpecific(), 0o644) channel.beginGetSubdocument(request, bytesStarted, 0) else: # No partial download possible; get the whole file. @@ -980,7 +980,7 @@ class PackageInfo: yield self.stepFailed; return # Now that we've verified the archive, make it read-only. - os.chmod(targetPathname.toOsSpecific(), 0444) + os.chmod(targetPathname.toOsSpecific(), 0o444) # Now we can safely remove the compressed archive. sourcePathname.unlink() @@ -1032,7 +1032,7 @@ class PackageInfo: continue # Make sure it's executable, and not writable. - os.chmod(targetPathname.toOsSpecific(), 0555) + os.chmod(targetPathname.toOsSpecific(), 0o555) step.bytesDone += file.size self.__updateStepProgress(step) diff --git a/direct/src/p3d/Packager.py b/direct/src/p3d/Packager.py index cd62ffb180..1346d875cd 100644 --- a/direct/src/p3d/Packager.py +++ b/direct/src/p3d/Packager.py @@ -427,7 +427,7 @@ class Packager: self.compressionLevel = 6 # Every p3dapp requires panda3d. - if 'panda3d' not in map(lambda p: p.packageName, self.requires): + if 'panda3d' not in [p.packageName for p in self.requires]: assert not self.packager.currentPackage self.packager.currentPackage = self self.packager.do_require('panda3d') @@ -726,7 +726,7 @@ class Packager: if self.p3dApplication: # No patches for an application; just move it into place. # Make the application file executable. - os.chmod(self.packageFullpath.toOsSpecific(), 0755) + os.chmod(self.packageFullpath.toOsSpecific(), 0o755) else: self.readDescFile() self.packageSeq += 1 @@ -2206,7 +2206,7 @@ class Packager: # returned, so they will persist beyond the lifespan of the # config variable. cvar = ConfigVariableSearchPath('pdef-path') - self.installSearch = map(Filename, cvar.getDirectories()) + self.installSearch = list(map(Filename, cvar.getDirectories())) # The system PATH, for searching dll's and exe's. self.executablePath = DSearchPath() @@ -2938,7 +2938,7 @@ class Packager: tuples.append((version, file)) tuples.sort(reverse = True) - return map(lambda t: t[1], tuples) + return [t[1] for t in tuples] def __sortPackageInfos(self, packages): """ Given a list of PackageInfos retrieved from a Host, sorts @@ -2951,7 +2951,7 @@ class Packager: tuples.append((version, file)) tuples.sort(reverse = True) - return map(lambda t: t[1], tuples) + return [t[1] for t in tuples] def __makeVersionTuple(self, version): """ Converts a version string into a tuple for sorting, by diff --git a/direct/src/p3d/packp3d.py b/direct/src/p3d/packp3d.py index 4dbfd5d898..6331995448 100755 --- a/direct/src/p3d/packp3d.py +++ b/direct/src/p3d/packp3d.py @@ -204,7 +204,7 @@ def makePackedApp(args): # Pre-require panda3d, to give a less-confusing error message # if one of our requirements pulls in a wrong version of # panda3d. - if 'panda3d' not in map(lambda t: t[0], requires): + if 'panda3d' not in [t[0] for t in requires]: packager.do_require('panda3d') for name, version, host in requires: diff --git a/direct/src/plugin_installer/make_installer.py b/direct/src/plugin_installer/make_installer.py index db51c12f62..5846e05955 100755 --- a/direct/src/plugin_installer/make_installer.py +++ b/direct/src/plugin_installer/make_installer.py @@ -441,7 +441,7 @@ def makeInstaller(): if not os.path.exists(dst_panda3dapp): os.makedirs(os.path.dirname(dst_panda3dapp)) shutil.copytree(pluginFiles[npapi], dst_npapi) shutil.copyfile(pluginFiles[panda3d], dst_panda3d) - os.chmod(dst_panda3d, 0755) + os.chmod(dst_panda3d, 0o755) shutil.copytree(pluginFiles[panda3dapp], dst_panda3dapp) tmpresdir = tempfile.mktemp('', 'p3d-resources') diff --git a/direct/src/plugin_standalone/make_osx_bundle.py b/direct/src/plugin_standalone/make_osx_bundle.py index 6bbadab662..dbeede9d88 100755 --- a/direct/src/plugin_standalone/make_osx_bundle.py +++ b/direct/src/plugin_standalone/make_osx_bundle.py @@ -73,7 +73,7 @@ def makeBundle(startDir): shutil.copyfile(icons.toOsSpecific(), iconFilename.toOsSpecific()) print panda3d_mac, exeFilename shutil.copyfile(panda3d_mac.toOsSpecific(), exeFilename.toOsSpecific()) - os.chmod(exeFilename.toOsSpecific(), 0755) + os.chmod(exeFilename.toOsSpecific(), 0o755) # All done! bundleFilename.touch() diff --git a/direct/src/pyinst/finder.py b/direct/src/pyinst/finder.py index 830a5d3b00..1c6a34f240 100644 --- a/direct/src/pyinst/finder.py +++ b/direct/src/pyinst/finder.py @@ -96,7 +96,7 @@ def identify(name, xtrapath=None): else: if xtrapath is None: xtra = [] - elif _pcache.has_key(id(xtrapath)): + elif id(xtrapath) in _pcache: xtra = _pcache[id(xtrapath)] else: xtra = expand(xtrapath) diff --git a/direct/src/pyinst/modulefinder.py b/direct/src/pyinst/modulefinder.py index 87773602d7..5e1b4805aa 100644 --- a/direct/src/pyinst/modulefinder.py +++ b/direct/src/pyinst/modulefinder.py @@ -218,7 +218,7 @@ class ModuleFinder: else: self.msgout(3, "import_module ->", m) return m - if self.badmodules.has_key(fqname): + if fqname in self.badmodules: self.msgout(3, "import_module -> None") self.badmodules[fqname][parent.__name__] = None return None @@ -275,24 +275,24 @@ class ModuleFinder: i = i+2 if op == IMPORT_NAME: name = lastname = co.co_names[oparg] - if not self.badmodules.has_key(lastname): + if lastname not in self.badmodules: try: self.import_hook(name, m) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) - if not self.badmodules.has_key(name): + if name not in self.badmodules: self.badmodules[name] = {} self.badmodules[name][m.__name__] = None elif op == IMPORT_FROM: name = co.co_names[oparg] assert lastname is not None - if not self.badmodules.has_key(lastname): + if lastname not in self.badmodules: try: self.import_hook(lastname, m, [name]) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) fullname = lastname + "." + name - if not self.badmodules.has_key(fullname): + if fullname not in self.badmodules: self.badmodules[fullname] = {} self.badmodules[fullname][m.__name__] = None else: @@ -316,7 +316,7 @@ class ModuleFinder: return m def add_module(self, fqname): - if self.modules.has_key(fqname): + if fqname in self.modules: return self.modules[fqname] self.modules[fqname] = m = Module(fqname) return m diff --git a/direct/src/pyinst/resource.py b/direct/src/pyinst/resource.py index 07c0f2f700..29e13e7ccd 100644 --- a/direct/src/pyinst/resource.py +++ b/direct/src/pyinst/resource.py @@ -18,7 +18,7 @@ def makeresource(name, xtrapath=None): when the module archive.py was desired.""" typ, nm, fullname = finder.identify(name, xtrapath) fullname = os.path.normpath(fullname) - if _cache.has_key(fullname): + if fullname in _cache: return _cache[fullname] elif typ in (finder.SCRIPT, finder.GSCRIPT): rsrc = scriptresource(nm, fullname) diff --git a/direct/src/showbase/Audio3DManager.py b/direct/src/showbase/Audio3DManager.py index f52fedb76e..84c572d815 100644 --- a/direct/src/showbase/Audio3DManager.py +++ b/direct/src/showbase/Audio3DManager.py @@ -139,7 +139,7 @@ class Audio3DManager: """ Get the velocity of the sound. """ - if (self.vel_dict.has_key(sound)): + if (sound in self.vel_dict): vel = self.vel_dict[sound] if (vel!=None): return vel @@ -196,7 +196,7 @@ class Audio3DManager: # the object any more del self.sound_dict[known_object] - if not self.sound_dict.has_key(object): + if object not in self.sound_dict: self.sound_dict[object] = [] self.sound_dict[object].append(sound) @@ -222,7 +222,7 @@ class Audio3DManager: """ returns a list of sounds attached to an object """ - if not self.sound_dict.has_key(object): + if object not in self.sound_dict: return [] sound_list = [] sound_list.extend(self.sound_dict[object]) diff --git a/direct/src/showbase/Factory.py b/direct/src/showbase/Factory.py index e0b12e4c06..ff25dc75bd 100755 --- a/direct/src/showbase/Factory.py +++ b/direct/src/showbase/Factory.py @@ -20,7 +20,7 @@ class Factory: return self._type2ctor[type](*args, **kwArgs) def _registerType(self, type, ctor): - if self._type2ctor.has_key(type): + if type in self._type2ctor: self.notify.debug('replacing %s ctor %s with %s' % (type, self._type2ctor[type], ctor)) self._type2ctor[type] = ctor diff --git a/direct/src/showbase/PythonUtil.py b/direct/src/showbase/PythonUtil.py index 9b77d6537e..24cf72f99d 100644 --- a/direct/src/showbase/PythonUtil.py +++ b/direct/src/showbase/PythonUtil.py @@ -61,10 +61,7 @@ import bisect __report_indent = 3 from direct.directutil import Verify -# Don't import libpandaexpressModules, which doesn't get built until -# genPyCode. -import direct.extensions_native.extension_native_helpers -from libpandaexpress import ConfigVariableBool +from panda3d.core import ConfigVariableBool ScalarTypes = (types.FloatType, types.IntType, types.LongType) diff --git a/direct/src/showbase/VFSImporter.py b/direct/src/showbase/VFSImporter.py index b99762a3ae..6f036c4423 100644 --- a/direct/src/showbase/VFSImporter.py +++ b/direct/src/showbase/VFSImporter.py @@ -457,7 +457,7 @@ class VFSSharedLoader: # Also set this special symbol, which records that this is a # shared package, and also lists the paths we have already # loaded. - mod._vfs_shared_path = vfs_shared_path + map(lambda l: l.dir_path, self.loaders) + mod._vfs_shared_path = vfs_shared_path + [l.dir_path for l in self.loaders] return mod diff --git a/direct/src/showbase/VerboseImport.py b/direct/src/showbase/VerboseImport.py index 26c7db6d06..a8e2ef7317 100644 --- a/direct/src/showbase/VerboseImport.py +++ b/direct/src/showbase/VerboseImport.py @@ -18,7 +18,7 @@ def newimport(*args, **kw): fPrint = 0 name = args[0] # Only print the name if we have not imported this before - if not sys.modules.has_key(name): + if name not in sys.modules: print (" "*indentLevel + "import " + args[0]) fPrint = 1 indentLevel += 1 diff --git a/direct/src/showutil/TexMemWatcher.py b/direct/src/showutil/TexMemWatcher.py index f012d122a6..5368b49e2e 100644 --- a/direct/src/showutil/TexMemWatcher.py +++ b/direct/src/showutil/TexMemWatcher.py @@ -627,7 +627,7 @@ class TexMemWatcher(DirectObject): self.repack() else: - overflowCount = sum(map(lambda tp: tp.overflowed, self.texPlacements.keys())) + overflowCount = sum([tp.overflowed for tp in self.texPlacements.keys()]) if totalSize <= self.limit and overflowCount: # Shouldn't be overflowing any more. Better repack. self.repack() diff --git a/direct/src/tkpanels/DirectSessionPanel.py b/direct/src/tkpanels/DirectSessionPanel.py index 0cbd509a1c..e10c0d91bb 100644 --- a/direct/src/tkpanels/DirectSessionPanel.py +++ b/direct/src/tkpanels/DirectSessionPanel.py @@ -216,8 +216,7 @@ class DirectSessionPanel(AppShell): Label(drFrame, text = 'Display Region', font=('MSSansSerif', 14, 'bold')).pack(expand = 0) - nameList = map(lambda x: 'Display Region ' + repr(x), - range(len(base.direct.drList))) + nameList = ['Display Region ' + repr(x) for x in range(len(base.direct.drList))] self.drMenu = Pmw.ComboBox( drFrame, labelpos = W, label_text = 'Display Region:', entry_width = 20, @@ -726,7 +725,7 @@ class DirectSessionPanel(AppShell): else: # Generate a unique name for the dict dictName = name + '-' + repr(nodePath.id()) - if not dict.has_key(dictName): + if dictName not in dict: # Update combo box to include new item names.append(dictName) listbox = menu.component('scrolledlist') diff --git a/direct/src/tkpanels/Inspector.py b/direct/src/tkpanels/Inspector.py index 95a5decc2e..ed0e3989cd 100644 --- a/direct/src/tkpanels/Inspector.py +++ b/direct/src/tkpanels/Inspector.py @@ -24,7 +24,7 @@ def inspect(anObject): def inspectorFor(anObject): typeName = string.capitalize(type(anObject).__name__) + 'Type' - if _InspectorMap.has_key(typeName): + if typeName in _InspectorMap: inspectorName = _InspectorMap[typeName] else: print "Can't find an inspector for " + typeName @@ -92,7 +92,7 @@ class Inspector: # self._partsList.append(each) def initializePartNames(self): - self._partNames = ['up'] + map(lambda each: str(each), self._partsList) + self._partNames = ['up'] + [str(each) for each in self._partsList] def title(self): "Subclasses may override." @@ -195,7 +195,7 @@ class DictionaryInspector(Inspector): if partNumber == 0: return self.object key = self.privatePartNumber(partNumber) - if self.object.has_key(key): + if key in self.object: return self.object[key] else: return getattr(self.object, key) diff --git a/direct/src/tkpanels/MopathRecorder.py b/direct/src/tkpanels/MopathRecorder.py index 71f9dbd12e..929c166315 100644 --- a/direct/src/tkpanels/MopathRecorder.py +++ b/direct/src/tkpanels/MopathRecorder.py @@ -1248,7 +1248,7 @@ class MopathRecorder(AppShell, DirectObject): else: # Generate a unique name for the dict dictName = name + '-' + repr(nodePath.id()) - if not dict.has_key(dictName): + if dictName not in dict: # Update combo box to include new item names.append(dictName) listbox = menu.component('scrolledlist') diff --git a/direct/src/tkpanels/ParticlePanel.py b/direct/src/tkpanels/ParticlePanel.py index 588b07e561..2d89609903 100644 --- a/direct/src/tkpanels/ParticlePanel.py +++ b/direct/src/tkpanels/ParticlePanel.py @@ -1132,7 +1132,7 @@ class ParticlePanel(AppShell): self.particlesLabelMenu.add_separator() # Add in a checkbutton for each effect (to toggle on/off) particles = self.particleEffect.getParticlesList() - names = map(lambda x: x.getName(), particles) + names = [x.getName() for x in particles] names.sort() for name in names: particle = self.particleEffect.getParticlesNamed(name) @@ -1157,7 +1157,7 @@ class ParticlePanel(AppShell): self.forceGroupLabelMenu.add_separator() # Add in a checkbutton for each effect (to toggle on/off) forceGroupList = self.particleEffect.getForceGroupList() - names = map(lambda x: x.getName(), forceGroupList) + names = [x.getName() for x in forceGroupList] names.sort() for name in names: force = self.particleEffect.getForceGroupNamed(name) diff --git a/direct/src/tkpanels/Placer.py b/direct/src/tkpanels/Placer.py index 44d0d04728..e762725bd5 100644 --- a/direct/src/tkpanels/Placer.py +++ b/direct/src/tkpanels/Placer.py @@ -510,7 +510,7 @@ class Placer(AppShell): else: # Generate a unique name for the dict dictName = name + '-' + repr(nodePath.id()) - if not dict.has_key(dictName): + if dictName not in dict: # Update combo box to include new item names.append(dictName) listbox = menu.component('scrolledlist') diff --git a/direct/src/tkwidgets/EntryScale.py b/direct/src/tkwidgets/EntryScale.py index 59cbb3d928..f79afe00aa 100644 --- a/direct/src/tkwidgets/EntryScale.py +++ b/direct/src/tkwidgets/EntryScale.py @@ -293,8 +293,7 @@ class EntryScaleGroup(Pmw.MegaToplevel): DEFAULT_DIM = 1 # Default value depends on *actual* group size, test for user input DEFAULT_VALUE = [0.0] * kw.get('dim', DEFAULT_DIM) - DEFAULT_LABELS = map(lambda x: 'v[%d]' % x, - range(kw.get('dim', DEFAULT_DIM))) + DEFAULT_LABELS = ['v[%d]' % x for x in range(kw.get('dim', DEFAULT_DIM))] #define the megawidget options INITOPT = Pmw.INITOPT diff --git a/direct/src/tkwidgets/Floater.py b/direct/src/tkwidgets/Floater.py index b4056d6900..799d6c7b8e 100644 --- a/direct/src/tkwidgets/Floater.py +++ b/direct/src/tkwidgets/Floater.py @@ -218,8 +218,7 @@ class FloaterGroup(Pmw.MegaToplevel): DEFAULT_DIM = 1 # Default value depends on *actual* group size, test for user input DEFAULT_VALUE = [0.0] * kw.get('dim', DEFAULT_DIM) - DEFAULT_LABELS = map(lambda x: 'v[%d]' % x, - range(kw.get('dim', DEFAULT_DIM))) + DEFAULT_LABELS = ['v[%d]' % x for x in range(kw.get('dim', DEFAULT_DIM))] #define the megawidget options INITOPT = Pmw.INITOPT diff --git a/direct/src/tkwidgets/Slider.py b/direct/src/tkwidgets/Slider.py index f1ff964be7..2a28107d8d 100644 --- a/direct/src/tkwidgets/Slider.py +++ b/direct/src/tkwidgets/Slider.py @@ -262,7 +262,7 @@ class SliderWidget(Pmw.MegaWidget): self.initialiseoptions(SliderWidget) # Adjust relief - if not kw.has_key('relief'): + if 'relief' not in kw: if self['style'] == VALUATOR_FULL: self['relief'] = FLAT diff --git a/direct/src/tkwidgets/Tree.py b/direct/src/tkwidgets/Tree.py index 89979ae1b9..b8c8100940 100644 --- a/direct/src/tkwidgets/Tree.py +++ b/direct/src/tkwidgets/Tree.py @@ -227,7 +227,7 @@ class TreeNode: self.kidKeys = [] for item in sublist: key = item.GetKey() - if fUseCachedChildren and self.children.has_key(key): + if fUseCachedChildren and key in self.children: child = self.children[key] else: child = TreeNode(self.canvas, self, item, self.menuList) @@ -291,7 +291,7 @@ class TreeNode: sublist.sort(compareText) for item in sublist: key = item.GetKey() - if fUseCachedChildren and self.children.has_key(key): + if fUseCachedChildren and key in self.children: child = self.children[key] else: child = TreeNode(self.canvas, self, item, self.menuList) @@ -452,7 +452,7 @@ class TreeNode: key = item.GetKey() # Use existing child or create new TreeNode if none exists - if self.children.has_key(key): + if key in self.children: child = self.children[key] else: child = TreeNode(self.canvas, self, item, self.menuList) diff --git a/direct/src/tkwidgets/Valuator.py b/direct/src/tkwidgets/Valuator.py index b53c5e0821..652640a8cf 100644 --- a/direct/src/tkwidgets/Valuator.py +++ b/direct/src/tkwidgets/Valuator.py @@ -89,7 +89,7 @@ class Valuator(Pmw.MegaWidget): self.packValuator() # Set reset value if none specified - if not kw.has_key('resetValue'): + if 'resetValue' not in kw: self['resetValue'] = self['value'] if self['fAdjustable']: @@ -351,8 +351,7 @@ class ValuatorGroup(Pmw.MegaWidget): DEFAULT_DIM = 1 # Default value depends on *actual* group size, test for user input DEFAULT_VALUE = [0.0] * kw.get('dim', DEFAULT_DIM) - DEFAULT_LABELS = map(lambda x: 'v[%d]' % x, - range(kw.get('dim', DEFAULT_DIM))) + DEFAULT_LABELS = ['v[%d]' % x for x in range(kw.get('dim', DEFAULT_DIM))] #define the megawidget options INITOPT = Pmw.INITOPT @@ -486,8 +485,7 @@ class ValuatorGroupPanel(Pmw.MegaToplevel): DEFAULT_DIM = 1 # Default value depends on *actual* group size, test for user input DEFAULT_VALUE = [0.0] * kw.get('dim', DEFAULT_DIM) - DEFAULT_LABELS = map(lambda x: 'v[%d]' % x, - range(kw.get('dim', DEFAULT_DIM))) + DEFAULT_LABELS = ['v[%d]' % x for x in range(kw.get('dim', DEFAULT_DIM))] #define the megawidget options INITOPT = Pmw.INITOPT diff --git a/direct/src/tkwidgets/VectorWidgets.py b/direct/src/tkwidgets/VectorWidgets.py index d6c580e4d7..8fa64d31d9 100644 --- a/direct/src/tkwidgets/VectorWidgets.py +++ b/direct/src/tkwidgets/VectorWidgets.py @@ -19,8 +19,7 @@ class VectorEntry(Pmw.MegaWidget): DEFAULT_DIM = 3 # Default value depends on *actual* vector size, test for user input DEFAULT_VALUE = [0.0] * kw.get('dim', DEFAULT_DIM) - DEFAULT_LABELS = map(lambda x: 'v[%d]' % x, - range(kw.get('dim', DEFAULT_DIM))) + DEFAULT_LABELS = ['v[%d]' % x for x in range(kw.get('dim', DEFAULT_DIM))] # Process options INITOPT = Pmw.INITOPT diff --git a/direct/src/wxwidgets/WxPandaShell.py b/direct/src/wxwidgets/WxPandaShell.py index 4bffda319d..00b2483276 100755 --- a/direct/src/wxwidgets/WxPandaShell.py +++ b/direct/src/wxwidgets/WxPandaShell.py @@ -126,26 +126,26 @@ class WxPandaShell(WxAppShell): base.startDirect(fWantTk = 0, fWantWx = 0) base.direct.disableMouseEvents() - newMouseEvents = map(lambda x: "_le_per_%s"%x, base.direct.mouseEvents) +\ - map(lambda x: "_le_fro_%s"%x, base.direct.mouseEvents) +\ - map(lambda x: "_le_lef_%s"%x, base.direct.mouseEvents) +\ - map(lambda x: "_le_top_%s"%x, base.direct.mouseEvents) + newMouseEvents = ["_le_per_%s"%x for x in base.direct.mouseEvents] +\ + ["_le_fro_%s"%x for x in base.direct.mouseEvents] +\ + ["_le_lef_%s"%x for x in base.direct.mouseEvents] +\ + ["_le_top_%s"%x for x in base.direct.mouseEvents] base.direct.mouseEvents = newMouseEvents base.direct.enableMouseEvents() base.direct.disableKeyEvents() - keyEvents = map(lambda x: "_le_per_%s"%x, base.direct.keyEvents) +\ - map(lambda x: "_le_fro_%s"%x, base.direct.keyEvents) +\ - map(lambda x: "_le_lef_%s"%x, base.direct.keyEvents) +\ - map(lambda x: "_le_top_%s"%x, base.direct.keyEvents) + keyEvents = ["_le_per_%s"%x for x in base.direct.keyEvents] +\ + ["_le_fro_%s"%x for x in base.direct.keyEvents] +\ + ["_le_lef_%s"%x for x in base.direct.keyEvents] +\ + ["_le_top_%s"%x for x in base.direct.keyEvents] base.direct.keyEvents = keyEvents base.direct.enableKeyEvents() base.direct.disableModifierEvents() - modifierEvents = map(lambda x: "_le_per_%s"%x, base.direct.modifierEvents) +\ - map(lambda x: "_le_fro_%s"%x, base.direct.modifierEvents) +\ - map(lambda x: "_le_lef_%s"%x, base.direct.modifierEvents) +\ - map(lambda x: "_le_top_%s"%x, base.direct.modifierEvents) + modifierEvents = ["_le_per_%s"%x for x in base.direct.modifierEvents] +\ + ["_le_fro_%s"%x for x in base.direct.modifierEvents] +\ + ["_le_lef_%s"%x for x in base.direct.modifierEvents] +\ + ["_le_top_%s"%x for x in base.direct.modifierEvents] base.direct.modifierEvents = modifierEvents base.direct.enableModifierEvents() From 66f4964c8b85c5793c78b8fa2b674de7a76c33a0 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 20:04:59 +0000 Subject: [PATCH 12/37] Oops, checked in the wrong file --- direct/src/directutil/DirectMySQLdbConnection.py | 13 +++++-------- direct/src/showbase/PythonUtil.py | 5 ++++- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/direct/src/directutil/DirectMySQLdbConnection.py b/direct/src/directutil/DirectMySQLdbConnection.py index ee89d47414..6174e269a0 100755 --- a/direct/src/directutil/DirectMySQLdbConnection.py +++ b/direct/src/directutil/DirectMySQLdbConnection.py @@ -8,19 +8,16 @@ class DirectMySQLdbConnection(Connection): from MySQLdb.constants import CLIENT, FIELD_TYPE from MySQLdb.converters import conversions from weakref import proxy, WeakValueDictionary - + import types kwargs2 = kwargs.copy() - - if kwargs.has_key('conv'): - conv = kwargs['conv'] - else: - conv = conversions + + conv = kwargs.get('conv', conversions) kwargs2['conv'] = dict([ (k, v) for k, v in conv.items() if type(k) is int ]) - + self.cursorclass = kwargs2.pop('cursorclass', self.default_cursor) charset = kwargs2.pop('charset', '') @@ -28,7 +25,7 @@ class DirectMySQLdbConnection(Connection): use_unicode = True else: use_unicode = False - + use_unicode = kwargs2.pop('use_unicode', use_unicode) sql_mode = kwargs2.pop('sql_mode', '') diff --git a/direct/src/showbase/PythonUtil.py b/direct/src/showbase/PythonUtil.py index 24cf72f99d..9b77d6537e 100644 --- a/direct/src/showbase/PythonUtil.py +++ b/direct/src/showbase/PythonUtil.py @@ -61,7 +61,10 @@ import bisect __report_indent = 3 from direct.directutil import Verify -from panda3d.core import ConfigVariableBool +# Don't import libpandaexpressModules, which doesn't get built until +# genPyCode. +import direct.extensions_native.extension_native_helpers +from libpandaexpress import ConfigVariableBool ScalarTypes = (types.FloatType, types.IntType, types.LongType) From 3241443077be7436999ffb48cbbcc8666ba85d43 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 20:31:46 +0000 Subject: [PATCH 13/37] fix error parsing PandaVersion.pp with Python 3 --- makepanda/makepandacore.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/makepanda/makepandacore.py b/makepanda/makepandacore.py index ebe70730a5..8acb530039 100644 --- a/makepanda/makepandacore.py +++ b/makepanda/makepandacore.py @@ -2352,7 +2352,7 @@ def CopyTree(dstdir, srcdir, omitCVS=True): def ParsePandaVersion(fn): try: - f = file(fn, "r") + f = open(fn, "r") pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+PANDA_VERSION[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)') for line in f: match = pattern.match(line,0) @@ -2365,7 +2365,7 @@ def ParsePandaVersion(fn): def ParsePluginVersion(fn): try: - f = file(fn, "r") + f = open(fn, "r") pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+P3D_PLUGIN_VERSION[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)') for line in f: match = pattern.match(line,0) @@ -2378,7 +2378,7 @@ def ParsePluginVersion(fn): def ParseCoreapiVersion(fn): try: - f = file(fn, "r") + f = open(fn, "r") pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+P3D_COREAPI_VERSION.*([0-9]+)[ \t]*$') for line in f: match = pattern.match(line,0) From 5edb53b8e8ffb346dcd689f5b861a2295f760bf5 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 22:44:39 +0000 Subject: [PATCH 14/37] fix some 64-bit linux issues --- makepanda/makepanda.py | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/makepanda/makepanda.py b/makepanda/makepanda.py index 4622e48c02..223eadc9b0 100755 --- a/makepanda/makepanda.py +++ b/makepanda/makepanda.py @@ -665,10 +665,18 @@ if (COMPILER=="GCC"): LibDirectory("ALWAYS", "/usr/local/lib") # Workaround for an issue where pkg-config does not include this path - if (os.path.isdir("/usr/lib64/glib-2.0/include")): - IncDirectory("GTK2", "/usr/lib64/glib-2.0/include") - if (os.path.isdir("/usr/lib64/gtk-2.0/include")): - IncDirectory("GTK2", "/usr/lib64/gtk-2.0/include") + if GetTargetArch() in ("x86_64", "amd64"): + if (os.path.isdir("/usr/lib64/glib-2.0/include")): + IncDirectory("GTK2", "/usr/lib64/glib-2.0/include") + if (os.path.isdir("/usr/lib64/gtk-2.0/include")): + IncDirectory("GTK2", "/usr/lib64/gtk-2.0/include") + + if (os.path.isdir("/usr/X11R6/lib64")): + LibDirectory("ALWAYS", "/usr/X11R6/lib64") + else: + LibDirectory("ALWAYS", "/usr/X11R6/lib") + else: + LibDirectory("ALWAYS", "/usr/X11R6/lib") fcollada_libs = ("FColladaD", "FColladaSD", "FColladaS") # WARNING! The order of the ffmpeg libraries matters! @@ -707,20 +715,23 @@ if (COMPILER=="GCC"): # We use a statically linked libboost_python on OSX rocket_libs += ("boost_python",) SmartPkgEnable("ROCKET", "", rocket_libs, "Rocket/Core.h") + SmartPkgEnable("GTK2", "gtk+-2.0") - SmartPkgEnable("GTK2", "gtk+-2.0") SmartPkgEnable("JPEG", "", ("jpeg"), "jpeglib.h") SmartPkgEnable("OPENSSL", "openssl", ("ssl", "crypto"), ("openssl/ssl.h", "openssl/crypto.h")) SmartPkgEnable("PNG", "libpng", ("png"), "png.h", tool = "libpng-config") SmartPkgEnable("ZLIB", "zlib", ("z"), "zlib.h") + if (RTDIST and GetHost() == "darwin" and "PYTHONVERSION" in SDK): # Don't use the framework for the OSX rtdist build. I'm afraid it gives problems somewhere. SmartPkgEnable("PYTHON", "", SDK["PYTHONVERSION"], (SDK["PYTHONVERSION"], SDK["PYTHONVERSION"] + "/Python.h"), tool = SDK["PYTHONVERSION"] + "-config") elif("PYTHONVERSION" in SDK and not RUNTIME): SmartPkgEnable("PYTHON", "", SDK["PYTHONVERSION"], (SDK["PYTHONVERSION"], SDK["PYTHONVERSION"] + "/Python.h"), tool = SDK["PYTHONVERSION"] + "-config", framework = "Python") + if (RTDIST): SmartPkgEnable("WX", tool = "wx-config") SmartPkgEnable("FLTK", "", ("fltk"), ("Fl/Fl.H"), tool = "fltk-config") + if (RUNTIME): if (GetHost() == 'darwin'): SmartPkgEnable("NPAPI", "", (), ("npapi.h")) @@ -1416,7 +1427,7 @@ def CompileLink(dll, obj, opts): if COMPILER == "GCC": cxx = GetCXX() if GetOrigExt(dll) == ".exe" and GetTarget() != 'android': - cmd = cxx + ' -o ' + dll + ' -L' + GetOutputDir() + '/lib -L' + GetOutputDir() + '/tmp -L/usr/X11R6/lib' + cmd = cxx + ' -o ' + dll + ' -L' + GetOutputDir() + '/lib -L' + GetOutputDir() + '/tmp' else: if (GetTarget() == "darwin"): cmd = cxx + ' -undefined dynamic_lookup' @@ -1424,11 +1435,11 @@ def CompileLink(dll, obj, opts): else: cmd += ' -dynamiclib -install_name ' + os.path.basename(dll) cmd += ' -compatibility_version ' + MAJOR_VERSION + ' -current_version ' + VERSION - cmd += ' -o ' + dll + ' -L' + GetOutputDir() + '/lib -L' + GetOutputDir() + '/tmp -L/usr/X11R6/lib' + cmd += ' -o ' + dll + ' -L' + GetOutputDir() + '/lib -L' + GetOutputDir() + '/tmp' else: cmd = cxx + ' -shared' if ("MODULE" not in opts): cmd += " -Wl,-soname=" + os.path.basename(dll) - cmd += ' -o ' + dll + ' -L' + GetOutputDir() + '/lib -L' + GetOutputDir() + '/tmp -L/usr/X11R6/lib' + cmd += ' -o ' + dll + ' -L' + GetOutputDir() + '/lib -L' + GetOutputDir() + '/tmp' for x in obj: if GetOrigExt(x) != ".dat": From 4b9da436a01fe18a97fa9bfb7f0271ac035a3e62 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 22:48:19 +0000 Subject: [PATCH 15/37] Automatically invoke 2to3 on built/direct for a Python 3 build --- makepanda/makepanda.py | 10 ++++++---- makepanda/makepandacore.py | 41 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/makepanda/makepanda.py b/makepanda/makepanda.py index 223eadc9b0..2cf64380e6 100755 --- a/makepanda/makepanda.py +++ b/makepanda/makepanda.py @@ -1611,12 +1611,14 @@ def RunGenPyCode(target, inputs, opts): if (PkgSkip("PYTHON") != 0): return - cmdstr = sys.executable + " -B " + os.path.join("direct", "src", "ffi", "jGenPyCode.py") + cmdstr = sys.executable + " -B " + os.path.join(GetOutputDir(), "direct", "ffi", "jGenPyCode.py") if (GENMAN): cmdstr += " -d" cmdstr += " -r" for i in inputs: - if (GetOrigExt(i)==".dll"): - cmdstr += " " + os.path.basename(os.path.splitext(i)[0].replace("_d","").replace(GetOutputDir()+"/lib/","")) + if (GetOrigExt(i)==".pyd"): + cmdstr += " panda3d." + os.path.basename(os.path.splitext(i)[0]) + elif (GetOrigExt(i)==".dll"): + cmdstr += " " + os.path.basename(os.path.splitext(i)[0].replace("_d","")) oscmd(cmdstr) @@ -2379,7 +2381,7 @@ CreatePandaVersionFiles() ########################################################################################## if (PkgSkip("DIRECT")==0): - CopyTree(GetOutputDir()+'/direct', 'direct/src') + CopyPythonTree(GetOutputDir() + '/direct', 'direct/src', lib2to3_fixers=['all']) ConditionalWriteFile(GetOutputDir() + '/direct/__init__.py', "") if (GetTarget() == 'windows'): CopyFile(GetOutputDir()+'/bin/panda3d.py', 'direct/src/ffi/panda3d.py') diff --git a/makepanda/makepandacore.py b/makepanda/makepandacore.py index 8acb530039..911e3036d7 100644 --- a/makepanda/makepandacore.py +++ b/makepanda/makepandacore.py @@ -2343,6 +2343,47 @@ def CopyTree(dstdir, srcdir, omitCVS=True): else: cmd = 'cp -R -f ' + srcdir + ' ' + dstdir oscmd(cmd) + if omitCVS: + DeleteCVS(dstdir) + +def CopyPythonTree(dstdir, srcdir, lib2to3_fixers=[]): + if (not os.path.isdir(dstdir)): + os.mkdir(dstdir) + + lib2to3 = None + if len(lib2to3_fixers) > 0 and sys.version_info >= (3, 0): + from lib2to3.main import main as lib2to3 + lib2to3_args = ['-w', '-n', '--no-diffs', '-x', 'buffer', '-x', 'idioms', '-x', 'set_literal', '-x', 'ws_comma'] + if lib2to3_fixers != ['all']: + for fixer in lib2to3_fixers: + lib2to3_args += ['-f', fixer] + + refactor = [] + for entry in os.listdir(srcdir): + srcpth = os.path.join(srcdir, entry) + dstpth = os.path.join(dstdir, entry) + if (os.path.isfile(srcpth)): + base, ext = os.path.splitext(entry) + if (entry != ".cvsignore" and ext not in SUFFIX_INC): + if (NeedsBuild([dstpth], [srcpth])): + WriteBinaryFile(dstpth, ReadBinaryFile(srcpth)) + + if ext == '.py' and not entry.endswith('-extensions.py'): + refactor.append((dstpth, srcpth)) + else: + JustBuilt([dstpth], [srcpth]) + + elif (entry != "CVS"): + CopyPythonTree(dstpth, srcpth, lib2to3_fixers) + + for dstpth, srcpth in refactor: + if lib2to3 is not None: + ret = lib2to3("lib2to3.fixes", lib2to3_args + [dstpth]) + if ret != 0: + os.remove(dstpth) + exit("Error in lib2to3.") + JustBuilt([dstpth], [srcpth]) + ######################################################################## ## From 088df4a3d214d674f22bb3ade45a5823176d36d4 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 17 Dec 2013 22:51:28 +0000 Subject: [PATCH 16/37] A few modernisation fixes, mostly for Python 3 support --- direct/src/showbase/ElementTree.py | 20 ++++++++++---------- direct/src/showbase/PythonUtil.py | 18 ------------------ 2 files changed, 10 insertions(+), 28 deletions(-) diff --git a/direct/src/showbase/ElementTree.py b/direct/src/showbase/ElementTree.py index 8ea3c79796..3f368edd39 100755 --- a/direct/src/showbase/ElementTree.py +++ b/direct/src/showbase/ElementTree.py @@ -794,7 +794,7 @@ def _encode_entity(text, pattern=_escape): # the following functions assume an ascii-compatible encoding # (or "utf-16") -def _escape_cdata(text, encoding=None, replace=string.replace): +def _escape_cdata(text, encoding=None): # escape character data try: if encoding: @@ -802,14 +802,14 @@ def _escape_cdata(text, encoding=None, replace=string.replace): text = _encode(text, encoding) except UnicodeError: return _encode_entity(text) - text = replace(text, "&", "&") - text = replace(text, "<", "<") - text = replace(text, ">", ">") + text = text.replace("&", "&") + text = text.replace("<", "<") + text = text.replace( ">", ">") return text except (TypeError, AttributeError): _raise_serialization_error(text) -def _escape_attrib(text, encoding=None, replace=string.replace): +def _escape_attrib(text, encoding=None): # escape attribute value try: if encoding: @@ -817,11 +817,11 @@ def _escape_attrib(text, encoding=None, replace=string.replace): text = _encode(text, encoding) except UnicodeError: return _encode_entity(text) - text = replace(text, "&", "&") - text = replace(text, "'", "'") # FIXME: overkill - text = replace(text, "\"", """) - text = replace(text, "<", "<") - text = replace(text, ">", ">") + text = text.replace("&", "&") + text = text.replace("'", "'") # FIXME: overkill + text = text.replace("\"", """) + text = text.replace("<", "<") + text = text.replace(">", ">") return text except (TypeError, AttributeError): _raise_serialization_error(text) diff --git a/direct/src/showbase/PythonUtil.py b/direct/src/showbase/PythonUtil.py index 9b77d6537e..a56643789d 100644 --- a/direct/src/showbase/PythonUtil.py +++ b/direct/src/showbase/PythonUtil.py @@ -68,24 +68,6 @@ from libpandaexpress import ConfigVariableBool ScalarTypes = (types.FloatType, types.IntType, types.LongType) -import __builtin__ -if not hasattr(__builtin__, 'enumerate'): - def enumerate(L): - """Returns (0, L[0]), (1, L[1]), etc., allowing this syntax: - for i, item in enumerate(L): - ... - - enumerate is a built-in feature in Python 2.3, which implements it - using an iterator. For now, we can use this quick & dirty - implementation that returns a list of tuples that is completely - constructed every time enumerate() is called. - """ - return zip(xrange(len(L)), L) - - __builtin__.enumerate = enumerate -else: - enumerate = __builtin__.enumerate - """ # with one integer positional arg, this uses about 4/5 of the memory of the Functor class below def Functor(function, *args, **kArgs): From 4944d7cd7b37c8be08f20564561723075f9913de Mon Sep 17 00:00:00 2001 From: rdb Date: Wed, 18 Dec 2013 10:24:00 +0000 Subject: [PATCH 17/37] use compare_to and get_class_type instead of compareTo and getClassType --- dtool/src/dtoolbase/typeHandle.cxx | 10 ++-- dtool/src/interrogatedb/py_panda.cxx | 72 +++++++++++++++------------- 2 files changed, 43 insertions(+), 39 deletions(-) diff --git a/dtool/src/dtoolbase/typeHandle.cxx b/dtool/src/dtoolbase/typeHandle.cxx index 619109976b..c25ee886c7 100644 --- a/dtool/src/dtoolbase/typeHandle.cxx +++ b/dtool/src/dtoolbase/typeHandle.cxx @@ -25,9 +25,9 @@ TypeHandle TypeHandle::_none; // Access: Published // Description: This special method allows coercion to a TypeHandle // from a Python class object or instance. It simply -// attempts to call classobj.getClassType(), and returns -// that value (or raises an exception if that method -// doesn't work). +// attempts to call classobj.get_class_type(), and +// returns that value (or raises an exception if that +// method doesn't work). // // This method allows a Python class object to be used // anywhere a TypeHandle is expected by the C++ @@ -35,7 +35,7 @@ TypeHandle TypeHandle::_none; //////////////////////////////////////////////////////////////////// PyObject *TypeHandle:: make(PyObject *classobj) { - return PyObject_CallMethod(classobj, (char *)"getClassType", (char *)""); + return PyObject_CallMethod(classobj, (char *)"get_class_type", (char *)""); } #endif // HAVE_PYTHON @@ -119,7 +119,7 @@ operator << (ostream &out, TypeHandle::MemoryClass mem_class) { case TypeHandle::MC_limit: return out << "limit"; } - + return out << "**invalid TypeHandle::MemoryClass (" << (int)mem_class << ")**\n"; diff --git a/dtool/src/interrogatedb/py_panda.cxx b/dtool/src/interrogatedb/py_panda.cxx index afb33e8ea2..786b45d15e 100644 --- a/dtool/src/interrogatedb/py_panda.cxx +++ b/dtool/src/interrogatedb/py_panda.cxx @@ -43,7 +43,7 @@ bool DtoolCanThisBeAPandaInstance(PyObject *self) { //////////////////////////////////////////////////////////////////////// // Function : DTOOL_Call_ExtractThisPointerForType // -// These are the wrappers that allow for down and upcast from type .. +// These are the wrappers that allow for down and upcast from type .. // needed by the Dtool py interface.. Be very careful if you muck with these // as the generated code depends on how this is set up.. //////////////////////////////////////////////////////////////////////// @@ -119,7 +119,7 @@ attempt_coercion(PyObject *self, Dtool_PyTypedObject *classdef, // temporary object. Weird. Py_DECREF(obj); } - + // Clear the error returned by the coercion constructor. It's not // the error message we want to report. PyErr_Clear(); @@ -245,7 +245,7 @@ DTOOL_Call_GetPointerThisClass(PyObject *self, Dtool_PyTypedObject *classdef, if (report_errors) { ostringstream str; str << function_name << "() argument " << param << " must be "; - + PyObject *fname = PyObject_GetAttrString((PyObject *)classdef, "__name__"); if (fname != (PyObject *)NULL) { #if PY_MAJOR_VERSION >= 3 @@ -257,7 +257,7 @@ DTOOL_Call_GetPointerThisClass(PyObject *self, Dtool_PyTypedObject *classdef, } else { str << classdef->_name; } - + PyObject *tname = PyObject_GetAttrString((PyObject *)Py_TYPE(self), "__name__"); if (tname != (PyObject *)NULL) { #if PY_MAJOR_VERSION >= 3 @@ -267,14 +267,14 @@ DTOOL_Call_GetPointerThisClass(PyObject *self, Dtool_PyTypedObject *classdef, #endif Py_DECREF(tname); } - + string msg = str.str(); PyErr_SetString(PyExc_TypeError, msg.c_str()); } } } else { if (report_errors) { - PyErr_SetString(PyExc_TypeError, "self is NULL"); + PyErr_SetString(PyExc_TypeError, "self is NULL"); } } @@ -295,7 +295,7 @@ void *DTOOL_Call_GetPointerThis(PyObject *self) { //////////////////////////////////////////////////////////////////////// // Function : DTool_CreatePyInstanceTyped // -// this function relies on the behavior of typed objects in the panda system. +// this function relies on the behavior of typed objects in the panda system. // //////////////////////////////////////////////////////////////////////// PyObject *DTool_CreatePyInstanceTyped(void *local_this_in, Dtool_PyTypedObject & known_class_type, bool memory_rules, bool is_const, int RunTimeType) { @@ -330,7 +330,7 @@ PyObject *DTool_CreatePyInstanceTyped(void *local_this_in, Dtool_PyTypedObject & self->_signature = PY_PANDA_SIGNATURE; self->_My_Type = target_class; return (PyObject *)self; - } + } } } } @@ -345,13 +345,13 @@ PyObject *DTool_CreatePyInstanceTyped(void *local_this_in, Dtool_PyTypedObject & self->_memory_rules = memory_rules; self->_is_const = is_const; self->_signature = PY_PANDA_SIGNATURE; - self->_My_Type = &known_class_type; + self->_My_Type = &known_class_type; } return (PyObject *)self; } //////////////////////////////////////////////////////////////////////// -// DTool_CreatePyInstance .. wrapper function to finalize the existance of a general +// DTool_CreatePyInstance .. wrapper function to finalize the existance of a general // dtool py instance.. //////////////////////////////////////////////////////////////////////// PyObject *DTool_CreatePyInstance(void *local_this, Dtool_PyTypedObject &in_classdef, bool memory_rules, bool is_const) { @@ -366,8 +366,8 @@ PyObject *DTool_CreatePyInstance(void *local_this, Dtool_PyTypedObject &in_class self->_ptr_to_object = local_this; self->_memory_rules = memory_rules; self->_is_const = is_const; - self->_My_Type = classdef; - } + self->_My_Type = classdef; + } return (PyObject *)self; } @@ -390,13 +390,13 @@ int DTool_PyInit_Finalize(PyObject *self, void *local_this, Dtool_PyTypedObject // at code generation time because of multiple generation passes in interrogate.. // /////////////////////////////////////////////////////////////////////////////// -void Dtool_Accum_MethDefs(PyMethodDef in[], MethodDefmap &themap) { +void Dtool_Accum_MethDefs(PyMethodDef in[], MethodDefmap &themap) { for (; in->ml_name != NULL; in++) { if (themap.find(in->ml_name) == themap.end()) { themap[in->ml_name] = in; } } -} +} /////////////////////////////////////////////////////////////////////////////// // ** HACK ** alert.. @@ -406,10 +406,10 @@ void Dtool_Accum_MethDefs(PyMethodDef in[], MethodDefmap &themap) { // /////////////////////////////////////////////////////////////////////////////// void -RegisterRuntimeClass(Dtool_PyTypedObject * otype, int class_id) { +RegisterRuntimeClass(Dtool_PyTypedObject *otype, int class_id) { if (class_id == 0) { interrogatedb_cat.warning() - << "Class " << otype->_name + << "Class " << otype->_name << " has a zero TypeHandle value; check that init_type() is called.\n"; } else if (class_id > 0) { @@ -421,7 +421,7 @@ RegisterRuntimeClass(Dtool_PyTypedObject * otype, int class_id) { Dtool_PyTypedObject *other_type = (*result.first).second; interrogatedb_cat.warning() << "Classes " << otype->_name << " and " << other_type->_name - << " share the same TypeHandle value (" << class_id + << " share the same TypeHandle value (" << class_id << "); check class definitions.\n"; } else { @@ -540,19 +540,20 @@ PyObject *Dtool_AddToDictionary(PyObject *self1, PyObject *args) { } else { PyDict_SetItem(dict,key,subject); } - } + } if (PyErr_Occurred()) { return (PyObject *)NULL; } return Py_BuildValue(""); } + /////////////////////////////////////////////////////////////////////////////////// /* inline long DTool_HashKey(PyObject * inst) { long outcome = (long)inst; - PyObject * func = PyObject_GetAttrString(inst, "__hash__"); - if (func == NULL) + PyObject *func = PyObject_GetAttrString(inst, "__hash__"); + if (func == NULL) { if (DtoolCanThisBeAPandaInstance(inst)) if (((Dtool_PyInstDef *)inst)->_ptr_to_object != NULL) @@ -564,13 +565,13 @@ inline long DTool_HashKey(PyObject * inst) Py_DECREF(func); if (res == NULL) return -1; - if (PyInt_Check(res)) + if (PyInt_Check(res)) { outcome = PyInt_AsLong(res); if (outcome == -1) outcome = -2; } - else + else { PyErr_SetString(PyExc_TypeError, "__hash__() should return an int"); @@ -592,7 +593,7 @@ inline long DTool_HashKey(PyObject * inst) int DTOOL_PyObject_Compare(PyObject *v1, PyObject *v2) { // First try compareTo function.. - PyObject * func = PyObject_GetAttrString(v1, "compareTo"); + PyObject * func = PyObject_GetAttrString(v1, "compare_to"); if (func == NULL) { PyErr_Clear(); } else { @@ -636,26 +637,29 @@ int DTOOL_PyObject_Compare(PyObject *v1, PyObject *v2) { #endif Py_DECREF(res); } - }; + } // try this compare void *v1_this = DTOOL_Call_GetPointerThis(v1); void *v2_this = DTOOL_Call_GetPointerThis(v2); if (v1_this != NULL && v2_this != NULL) { // both are our types... - if (v1_this < v2_this) + if (v1_this < v2_this) { return -1; - - if (v1_this > v2_this) + } + if (v1_this > v2_this) { return 1; + } return 0; } // ok self compare... - if (v1 < v2) - return -1; - if (v1 > v2) - return 1; - return 0; + if (v1 < v2) { + return -1; + } + if (v1 > v2) { + return 1; + } + return 0; } PyObject *DTOOL_PyObject_RichCompare(PyObject *v1, PyObject *v2, int op) { @@ -697,7 +701,7 @@ PyObject *make_list_for_item(PyObject *self, const char *num_name, num_elements = PyInt_AsSsize_t(num_result); #endif Py_DECREF(num_result); - + PyObject *list = PyList_New(num_elements); for (int i = 0; i < num_elements; ++i) { PyObject *element = PyObject_CallMethod(self, (char *)element_name, (char *)"(i)", i); @@ -716,7 +720,7 @@ PyObject *make_list_for_item(PyObject *self, const char *num_name, // __copy__() method from a C++ make_copy() method. //////////////////////////////////////////////////////////////////// PyObject *copy_from_make_copy(PyObject *self) { - return PyObject_CallMethod(self, (char *)"makeCopy", (char *)"()"); + return PyObject_CallMethod(self, (char *)"make_copy", (char *)"()"); } //////////////////////////////////////////////////////////////////// From 5bd9eaf7fc9a7bac86643d66a6296c72cacb8d36 Mon Sep 17 00:00:00 2001 From: David Rose Date: Thu, 19 Dec 2013 18:56:45 +0000 Subject: [PATCH 18/37] fix import error --- direct/src/showbase/PythonUtil.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/direct/src/showbase/PythonUtil.py b/direct/src/showbase/PythonUtil.py index a56643789d..bf6b89cabb 100644 --- a/direct/src/showbase/PythonUtil.py +++ b/direct/src/showbase/PythonUtil.py @@ -1,7 +1,7 @@ """Undocumented Module""" -__all__ = ['enumerate', 'unique', 'indent', 'nonRepeatingRandomList', +__all__ = ['unique', 'indent', 'nonRepeatingRandomList', 'writeFsmTree', 'StackTrace', 'traceFunctionCall', 'traceParentCall', 'printThisCall', 'tron', 'trace', 'troff', 'getClassLineage', 'pdir', '_pdir', '_is_variadic', '_has_keywordargs', '_varnames', '_getcode', From adf9b0538108a562f3a7179f52dd7114a0c30711 Mon Sep 17 00:00:00 2001 From: rdb Date: Sun, 22 Dec 2013 10:12:19 +0000 Subject: [PATCH 19/37] include version number in dependency cache (sorry for forcing a full rebuild onto y'all) --- makepanda/makepandacore.py | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/makepanda/makepandacore.py b/makepanda/makepandacore.py index 911e3036d7..78d9b2250c 100644 --- a/makepanda/makepandacore.py +++ b/makepanda/makepandacore.py @@ -709,6 +709,7 @@ def CxxGetIncludes(path): ## ######################################################################## +DCACHE_VERSION = 2 DCACHE_BACKED_UP = False def SaveDependencyCache(): @@ -720,10 +721,15 @@ def SaveDependencyCache(): os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache-backup")) except: pass DCACHE_BACKED_UP = True - try: icache = open(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),'wb') - except: icache = 0 - if (icache!=0): + + try: + icache = open(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),'wb') + except: + icache = None + + if icache is not None: print("Storing dependency cache.") + pickle.dump(DCACHE_VERSION, icache, 0) pickle.dump(CXXINCLUDECACHE, icache, 2) pickle.dump(BUILTFROMCACHE, icache, 2) icache.close() @@ -731,12 +737,20 @@ def SaveDependencyCache(): def LoadDependencyCache(): global CXXINCLUDECACHE global BUILTFROMCACHE - try: icache = open(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),'rb') - except: icache = 0 - if (icache!=0): - CXXINCLUDECACHE = pickle.load(icache) - BUILTFROMCACHE = pickle.load(icache) - icache.close() + + try: + icache = open(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"), 'rb') + except: + icache = None + + if icache is not None: + ver = pickle.load(icache) + if ver == DCACHE_VERSION: + CXXINCLUDECACHE = pickle.load(icache) + BUILTFROMCACHE = pickle.load(icache) + icache.close() + else: + print("Cannot load dependency cache, version is too old!") ######################################################################## ## From c7297752659a1b5972e5f20e1e55618840118cb5 Mon Sep 17 00:00:00 2001 From: rdb Date: Mon, 23 Dec 2013 15:08:00 +0000 Subject: [PATCH 20/37] The 'new' module has been deprecated since 2.6 and removed in Python 3, let's not use it (use 'types' module instead) --- direct/src/fsm/State.py | 13 ++++++------- direct/src/interval/FunctionInterval.py | 7 +++---- direct/src/p3d/Packager.py | 1 - direct/src/showbase/Messenger.py | 3 +-- direct/src/showbase/PythonUtil.py | 26 ++++++++++++------------- direct/src/showbase/VFSImporter.py | 1 - direct/src/task/Task.py | 7 +++---- 7 files changed, 25 insertions(+), 33 deletions(-) diff --git a/direct/src/fsm/State.py b/direct/src/fsm/State.py index 23701c3b5d..0af9f45851 100644 --- a/direct/src/fsm/State.py +++ b/direct/src/fsm/State.py @@ -23,7 +23,6 @@ class State(DirectObject): @classmethod def replaceMethod(self, oldFunction, newFunction): - import new import types count = 0 for state in self.States: @@ -34,16 +33,16 @@ class State(DirectObject): if type(enterFunc) == types.MethodType: if (enterFunc.im_func == oldFunction): # print 'found: ', enterFunc, oldFunction - state.setEnterFunc(new.instancemethod(newFunction, - enterFunc.im_self, - enterFunc.im_class)) + state.setEnterFunc(types.MethodType(newFunction, + enterFunc.im_self, + enterFunc.im_class)) count += 1 if type(exitFunc) == types.MethodType: if (exitFunc.im_func == oldFunction): # print 'found: ', exitFunc, oldFunction - state.setExitFunc(new.instancemethod(newFunction, - exitFunc.im_self, - exitFunc.im_class)) + state.setExitFunc(types.MethodType(newFunction, + exitFunc.im_self, + exitFunc.im_class)) count += 1 return count diff --git a/direct/src/interval/FunctionInterval.py b/direct/src/interval/FunctionInterval.py index 272063d27f..450cb5d5de 100644 --- a/direct/src/interval/FunctionInterval.py +++ b/direct/src/interval/FunctionInterval.py @@ -28,7 +28,6 @@ class FunctionInterval(Interval.Interval): @classmethod def replaceMethod(self, oldFunction, newFunction): - import new import types count = 0 for ival in self.FunctionIntervals: @@ -37,9 +36,9 @@ class FunctionInterval(Interval.Interval): if type(ival.function) == types.MethodType: if (ival.function.im_func == oldFunction): # print 'found: ', ival.function, oldFunction - ival.function = new.instancemethod(newFunction, - ival.function.im_self, - ival.function.im_class) + ival.function = types.MethodType(newFunction, + ival.function.im_self, + ival.function.im_class) count += 1 return count diff --git a/direct/src/p3d/Packager.py b/direct/src/p3d/Packager.py index 1346d875cd..deb55f3a5e 100644 --- a/direct/src/p3d/Packager.py +++ b/direct/src/p3d/Packager.py @@ -10,7 +10,6 @@ import sys import os import glob import marshal -import new import string import types import getpass diff --git a/direct/src/showbase/Messenger.py b/direct/src/showbase/Messenger.py index 8c476f9b39..56ec2958de 100644 --- a/direct/src/showbase/Messenger.py +++ b/direct/src/showbase/Messenger.py @@ -506,7 +506,6 @@ class Messenger: This is only used by Finder.py - the module that lets you redefine functions with Control-c-Control-v """ - import new retFlag = 0 for entry in self.__callbacks.items(): event, objectDict = entry @@ -522,7 +521,7 @@ class Messenger: # 'oldMethod: ' + repr(oldMethod) + '\n' + # 'newFunction: ' + repr(newFunction) + '\n') if (function == oldMethod): - newMethod = new.instancemethod( + newMethod = types.MethodType( newFunction, method.im_self, method.im_class) params[0] = newMethod # Found it retrun true diff --git a/direct/src/showbase/PythonUtil.py b/direct/src/showbase/PythonUtil.py index bf6b89cabb..be61d06dc7 100644 --- a/direct/src/showbase/PythonUtil.py +++ b/direct/src/showbase/PythonUtil.py @@ -45,7 +45,6 @@ import os import sys import random import time -import new import gc #if __debug__: import traceback @@ -1203,16 +1202,15 @@ def getSetter(targetObj, valueName, prefix='set'): def mostDerivedLast(classList): """pass in list of classes. sorts list in-place, with derived classes appearing after their bases""" - def compare(a, b): - if issubclass(a, b): - result=1 - elif issubclass(b, a): - result=-1 - else: - result=0 - #print a, b, result - return result - classList.sort(compare) + + class ClassSortKey(object): + __slots__ = 'classobj', + def __init__(self, classobj): + self.classobj = classobj + def __lt__(self, other): + return issubclass(other.classobj, self.classobj) + + classList.sort(key=ClassSortKey) """ ParamObj/ParamSet @@ -1509,7 +1507,7 @@ class ParamObj: # then the applier, or b) call the setter and queue the # applier, depending on whether our params are locked """ - setattr(self, setterName, new.instancemethod( + setattr(self, setterName, types.MethodType( Functor(setterStub, param, setterFunc), self, self.__class__)) """ def setterStub(self, value, param=param, origSetterName=origSetterName): @@ -2734,7 +2732,7 @@ def tagRepr(obj, tag): return s oldRepr = Functor(stringer, repr(obj)) stringer = None - obj.__repr__ = new.instancemethod(Functor(reprWithTag, oldRepr, tag), obj, obj.__class__) + obj.__repr__ = types.MethodType(Functor(reprWithTag, oldRepr, tag), obj, obj.__class__) reprWithTag = None return obj @@ -2761,7 +2759,7 @@ def appendStr(obj, st): return s oldStr = Functor(stringer, str(obj)) stringer = None - obj.__str__ = new.instancemethod(Functor(appendedStr, oldStr, st), obj, obj.__class__) + obj.__str__ = types.MethodType(Functor(appendedStr, oldStr, st), obj, obj.__class__) appendedStr = None return obj diff --git a/direct/src/showbase/VFSImporter.py b/direct/src/showbase/VFSImporter.py index 6f036c4423..3bf8275cfc 100644 --- a/direct/src/showbase/VFSImporter.py +++ b/direct/src/showbase/VFSImporter.py @@ -1,6 +1,5 @@ from libpandaexpress import Filename, VirtualFileSystem, VirtualFileMountSystem, OFileStream, copyStream import sys -import new import os import marshal import imp diff --git a/direct/src/task/Task.py b/direct/src/task/Task.py index 281c634b80..bffe8fa82d 100644 --- a/direct/src/task/Task.py +++ b/direct/src/task/Task.py @@ -560,10 +560,9 @@ class TaskManager: else: function = method if (function == oldMethod): - import new - newMethod = new.instancemethod(newFunction, - method.im_self, - method.im_class) + newMethod = types.MethodType(newFunction, + method.im_self, + method.im_class) task.setFunction(newMethod) # Found a match return 1 From 2275784525acec26567a788301d8106bf4d8a383 Mon Sep 17 00:00:00 2001 From: rdb Date: Mon, 23 Dec 2013 18:57:48 +0000 Subject: [PATCH 21/37] More Python 3 support, and a bit of work toward being able to compile as panda3d/core.pyd, etc. --- .../extension_native_helpers.py | 61 +++++++++++++------ direct/src/ffi/DoGenPyCode.py | 35 +++++++++-- direct/src/fsm/StatePush.py | 2 +- direct/src/showbase/ExceptionVarDump.py | 1 - direct/src/showbase/Finder.py | 37 ++++++----- direct/src/showbase/PythonUtil.py | 36 +++++------ direct/src/showbase/ShowBase.py | 2 +- 7 files changed, 111 insertions(+), 63 deletions(-) diff --git a/direct/src/extensions_native/extension_native_helpers.py b/direct/src/extensions_native/extension_native_helpers.py index 525b416876..8cfbe1e53d 100644 --- a/direct/src/extensions_native/extension_native_helpers.py +++ b/direct/src/extensions_native/extension_native_helpers.py @@ -1,7 +1,7 @@ ### Tools __all__ = ["Dtool_ObjectToDict", "Dtool_funcToMethod", "Dtool_PreloadDLL"] -import imp,sys,os +import imp, sys, os # The following code exists to work around a problem that exists # with Python 2.5 or greater. @@ -15,6 +15,7 @@ dll_suffix = '' if sys.platform == "win32": # On Windows, dynamic libraries end in ".dll". dll_ext = '.dll' + module_ext = '.pyd' # We allow the caller to preload dll_suffix into the sys module. dll_suffix = getattr(sys, 'dll_suffix', None) @@ -33,9 +34,11 @@ elif sys.platform == "darwin": from direct.extensions_native.extensions_darwin import dll_ext except ImportError: dll_ext = '.dylib' + module_ext = '.so' else: # On most other UNIX systems (including linux), .so is used. dll_ext = '.so' + module_ext = '.so' if sys.platform == "win32": # On Windows, we must furthermore ensure that the PATH is modified @@ -51,47 +54,69 @@ if sys.platform == "win32": target = dir if target == None: message = "Cannot find %s" % (filename) - raise ImportError, message + raise ImportError(message) # And add that directory to the system path. path = os.environ["PATH"] if not path.startswith(target + ";"): os.environ["PATH"] = target + ";" + path +def Dtool_FindModule(module): + # Finds a .pyd module on the Python path. + filename = module.replace('.', os.path.sep) + module_ext + for dir in sys.path: + lib = os.path.join(dir, filename) + if (os.path.exists(lib)): + return lib + + return None + def Dtool_PreloadDLL(module): if module in sys.modules: return + # First find it as a .pyd module on the Python path. + if Dtool_FindModule(module): + # OK, we should have no problem importing it as is. + return + + # Nope, we'll need to search for a dynamic lib and preload it. # Search for the appropriate directory. target = None - filename = module + dll_suffix + dll_ext + filename = module.replace('.', os.path.sep) + dll_suffix + dll_ext for dir in sys.path + [sys.prefix]: lib = os.path.join(dir, filename) if (os.path.exists(lib)): target = dir break - if target == None: + + if target is None: message = "DLL loader cannot find %s." % (module) - raise ImportError, message + raise ImportError(message) # Now import the file explicitly. pathname = os.path.join(target, filename) - imp.load_dynamic(module, pathname) + imp.load_dynamic(module, pathname) -Dtool_PreloadDLL("libpandaexpress") -from libpandaexpress import * +# Nowadays, we can compile libpandaexpress with libpanda into a +# .pyd file called panda3d/core.pyd which can be imported without +# any difficulty. Let's see if this is the case. +if Dtool_FindModule("panda3d.core"): + from panda3d.core import * +else: + Dtool_PreloadDLL("libpandaexpress") + from libpandaexpress import * -def Dtool_ObjectToDict(clas, name, obj): - clas.DtoolClassDict[name] = obj; +def Dtool_ObjectToDict(cls, name, obj): + cls.DtoolClassDict[name] = obj; -def Dtool_funcToMethod(func, clas, method_name=None): +def Dtool_funcToMethod(func, cls, method_name=None): """Adds func to class so it is an accessible method; use method_name to specify the name to be used for calling the method. The new method is accessible to any instance immediately.""" - func.im_class=clas - func.im_func=func - func.im_self=None + if sys.version_info < (3, 0): + func.im_class = cls + func.im_func = func + func.im_self = None if not method_name: - method_name = func.__name__ - clas.DtoolClassDict[method_name] = func; - - + method_name = func.__name__ + cls.DtoolClassDict[method_name] = func; diff --git a/direct/src/ffi/DoGenPyCode.py b/direct/src/ffi/DoGenPyCode.py index f23725b1f7..62b15585a1 100644 --- a/direct/src/ffi/DoGenPyCode.py +++ b/direct/src/ffi/DoGenPyCode.py @@ -224,7 +224,7 @@ def doErrorCheck(): FFIConstants.CodeModuleNameList = codeLibs def generateNativeWrappers(): - from direct.extensions_native.extension_native_helpers import Dtool_PreloadDLL + from direct.extensions_native.extension_native_helpers import Dtool_FindModule, Dtool_PreloadDLL # Empty out the output directories of unnecessary crud from # previous runs before we begin. @@ -256,27 +256,50 @@ def generateNativeWrappers(): for moduleName in FFIConstants.CodeModuleNameList: print('Importing code library: ' + moduleName) Dtool_PreloadDLL(moduleName) - exec('import %s as module' % moduleName) + + __import__(moduleName) + module = sys.modules[moduleName] + + # Make a suitable meta module name + metaModuleName = "" + nextCap = False + for ch in moduleName: + if ch == '.': + nextCap = True + elif nextCap: + metaModuleName += ch.upper() + nextCap = False + else: + metaModuleName += ch + metaModuleName += "Modules" # Wrap the import in a try..except so that we can continue if # the library isn't present. This is particularly necessary # in the runtime (plugin) environment, where all libraries are # not necessarily downloaded. - pandaModules.write('try:\n from %sModules import *\nexcept ImportError, err:\n if "DLL loader cannot find" not in str(err):\n raise\n' % (moduleName)) + if sys.version_info >= (3, 0): + pandaModules.write('try:\n from .%s import *\nexcept ImportError as err:\n if "DLL loader cannot find" not in str(err):\n raise\n' % (metaModuleName)) + else: + pandaModules.write('try:\n from %s import *\nexcept ImportError, err:\n if "DLL loader cannot find" not in str(err):\n raise\n' % (metaModuleName)) + # Not sure if this message is helpful or annoying. #pandaModules.write(' print("Failed to import %s")\n' % (moduleName)) pandaModules.write('\n') - moduleModulesFilename = os.path.join(outputCodeDir, '%sModules.py' % (moduleName)) + moduleModulesFilename = os.path.join(outputCodeDir, '%s.py' % (metaModuleName)) moduleModules = open(moduleModulesFilename, 'w') - moduleModules.write('from extension_native_helpers import *\n') + if sys.version_info >= (3, 0): + moduleModules.write('from .extension_native_helpers import *\n') + else: + moduleModules.write('from extension_native_helpers import *\n') moduleModules.write('Dtool_PreloadDLL("%s")\n' % (moduleName)) + moduleModules.write('from %s import *\n\n' % (moduleName)) # Now look for extensions for className, classDef in module.__dict__.items(): - if type(classDef) == types.TypeType: + if isinstance(classDef, type): extensionFilename = os.path.join(extensionsDir, '%s_extensions.py' % (className)) if os.path.exists(extensionFilename): print(' Found extensions for class: %s' % (className)) diff --git a/direct/src/fsm/StatePush.py b/direct/src/fsm/StatePush.py index b26d93a5e0..49a6667fbb 100755 --- a/direct/src/fsm/StatePush.py +++ b/direct/src/fsm/StatePush.py @@ -238,7 +238,7 @@ class FunctionCall(ReceivesMultipleStateChanges, PushesStateChanges): def _recvMultiStatePush(self, key, source): # one of the arguments changed # pick up the new value - if isinstance(key, types.StringType): + if isinstance(key, str): self._bakedKargs[key] = source.getState() else: self._bakedArgs[key] = source.getState() diff --git a/direct/src/showbase/ExceptionVarDump.py b/direct/src/showbase/ExceptionVarDump.py index 8601fb0242..0c8bd56f6a 100755 --- a/direct/src/showbase/ExceptionVarDump.py +++ b/direct/src/showbase/ExceptionVarDump.py @@ -1,7 +1,6 @@ from pandac.PandaModules import getConfigShowbase from direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase.PythonUtil import fastRepr -from exceptions import Exception import sys import types import traceback diff --git a/direct/src/showbase/Finder.py b/direct/src/showbase/Finder.py index 556c9a4793..f209ef9b14 100644 --- a/direct/src/showbase/Finder.py +++ b/direct/src/showbase/Finder.py @@ -5,7 +5,6 @@ __all__ = ['findClass', 'rebindClass', 'copyFuncs', 'replaceMessengerFunc', 'rep import time import types import os -import new import sys def findClass(className): @@ -107,24 +106,24 @@ def copyFuncs(fromClass, toClass): # SystemError: cellobject.c:22: bad argument to internal function # Give the new function code the same filename as the old function # Perhaps there is a cleaner way to do this? This was my best idea. - newCode = new.code(newFunc.func_code.co_argcount, - newFunc.func_code.co_nlocals, - newFunc.func_code.co_stacksize, - newFunc.func_code.co_flags, - newFunc.func_code.co_code, - newFunc.func_code.co_consts, - newFunc.func_code.co_names, - newFunc.func_code.co_varnames, - # Use the oldFunc's filename here. Tricky! - oldFunc.func_code.co_filename, - newFunc.func_code.co_name, - newFunc.func_code.co_firstlineno, - newFunc.func_code.co_lnotab) - newFunc = new.function(newCode, - newFunc.func_globals, - newFunc.func_name, - newFunc.func_defaults, - newFunc.func_closure) + newCode = types.CodeType(newFunc.func_code.co_argcount, + newFunc.func_code.co_nlocals, + newFunc.func_code.co_stacksize, + newFunc.func_code.co_flags, + newFunc.func_code.co_code, + newFunc.func_code.co_consts, + newFunc.func_code.co_names, + newFunc.func_code.co_varnames, + # Use the oldFunc's filename here. Tricky! + oldFunc.func_code.co_filename, + newFunc.func_code.co_name, + newFunc.func_code.co_firstlineno, + newFunc.func_code.co_lnotab) + newFunc = types.FunctionType(newCode, + newFunc.func_globals, + newFunc.func_name, + newFunc.func_defaults, + newFunc.func_closure) """ replaceFuncList.append((oldFunc, funcName, newFunc)) else: diff --git a/direct/src/showbase/PythonUtil.py b/direct/src/showbase/PythonUtil.py index be61d06dc7..418bb86f6b 100644 --- a/direct/src/showbase/PythonUtil.py +++ b/direct/src/showbase/PythonUtil.py @@ -168,7 +168,7 @@ class Queue: def __len__(self): return len(self.__list) -if __debug__: +if __debug__ and __name__ == '__main__': q = Queue() assert q.isEmpty() q.clear() @@ -615,7 +615,7 @@ class Signature: l.append('*' + specials['positional']) if 'keyword' in specials: l.append('**' + specials['keyword']) - return "%s(%s)" % (self.name, string.join(l, ', ')) + return "%s(%s)" % (self.name, ', '.join(l)) else: return "%s(?)" % self.name @@ -908,7 +908,7 @@ def binaryRepr(number, max_length = 32): digits = map (operator.mod, shifts, max_length * [2]) if not digits.count (1): return 0 digits = digits [digits.index (1):] - return string.join (map (repr, digits), '') + return ''.join([repr(digit) for digit in digits]) class StdoutCapture: # redirects stdout to a string @@ -1194,7 +1194,7 @@ def extractProfile(*args, **kArgs): def getSetterName(valueName, prefix='set'): # getSetterName('color') -> 'setColor' # getSetterName('color', 'get') -> 'getColor' - return '%s%s%s' % (prefix, string.upper(valueName[0]), valueName[1:]) + return '%s%s%s' % (prefix, valueName[0].upper(), valueName[1:]) def getSetter(targetObj, valueName, prefix='set'): # getSetter(smiley, 'pos') -> smiley.setPos return getattr(targetObj, getSetterName(valueName, prefix)) @@ -1427,6 +1427,8 @@ class ParamObj: # we've already compiled the defaults for this class return bases = list(cls.__bases__) + if object in bases: + bases.remove(object) # bring less-derived classes to the front mostDerivedLast(bases) cls._Params = {} @@ -1612,7 +1614,7 @@ class ParamObj: argStr += '%s=%s,' % (param, repr(value)) return '%s(%s)' % (self.__class__.__name__, argStr) -if __debug__: +if __debug__ and __name__ == '__main__': class ParamObjTest(ParamObj): class ParamSet(ParamObj.ParamSet): Params = { @@ -1809,7 +1811,7 @@ class POD: argStr += '%s=%s,' % (name, repr(getSetter(self, name, 'get')())) return '%s(%s)' % (self.__class__.__name__, argStr) -if __debug__: +if __debug__ and __name__ == '__main__': class PODtest(POD): DataSet = { 'foo': dict, @@ -2139,7 +2141,7 @@ def pivotScalar(scalar, pivot): # reflect scalar about pivot; see tests below return pivot + (pivot - scalar) -if __debug__: +if __debug__ and __name__ == '__main__': assert pivotScalar(1, 0) == -1 assert pivotScalar(-1, 0) == 1 assert pivotScalar(3, 5) == 7 @@ -3596,9 +3598,9 @@ def recordCreationStackStr(cls): self._creationStackTraceStrLst = StackTrace(start=1).compact().split(',') return self.__moved_init__(*args, **kArgs) def getCreationStackTraceCompactStr(self): - return string.join(self._creationStackTraceStrLst, ',') + return ','.join(self._creationStackTraceStrLst) def printCreationStackTrace(self): - print string.join(self._creationStackTraceStrLst, ',') + print ','.join(self._creationStackTraceStrLst) cls.__init__ = __recordCreationStackStr_init__ cls.getCreationStackTraceCompactStr = getCreationStackTraceCompactStr cls.printCreationStackTrace = printCreationStackTrace @@ -3750,7 +3752,7 @@ def flywheel(*args, **kArgs): pass return flywheel -if __debug__: +if __debug__ and __name__ == '__main__': f = flywheel(['a','b','c','d'], countList=[11,20,3,4]) obj2count = {} for obj in f: @@ -3944,7 +3946,7 @@ def formatTimeCompact(seconds): result += '%ss' % seconds return result -if __debug__: +if __debug__ and __name__ == '__main__': ftc = formatTimeCompact assert ftc(0) == '0s' assert ftc(1) == '1s' @@ -3980,7 +3982,7 @@ def formatTimeExact(seconds): result += '%ss' % seconds return result -if __debug__: +if __debug__ and __name__ == '__main__': fte = formatTimeExact assert fte(0) == '0s' assert fte(1) == '1s' @@ -4019,7 +4021,7 @@ class AlphabetCounter: break return result -if __debug__: +if __debug__ and __name__ == '__main__': def testAlphabetCounter(): tempList = [] ac = AlphabetCounter() @@ -4195,7 +4197,7 @@ def unescapeHtmlString(s): result += char return result -if __debug__: +if __debug__ and __name__ == '__main__': assert unescapeHtmlString('asdf') == 'asdf' assert unescapeHtmlString('as+df') == 'as df' assert unescapeHtmlString('as%32df') == 'as2df' @@ -4252,7 +4254,7 @@ class HTMLStringToElements(HTMLParser): def str2elements(str): return HTMLStringToElements(str).getElements() -if __debug__: +if __debug__ and __name__ == '__main__': s = ScratchPad() assert len(str2elements('')) == 0 s.br = str2elements('
') @@ -4292,7 +4294,7 @@ def repeatableRepr(obj): return repeatableRepr(l) return repr(obj) -if __debug__: +if __debug__ and __name__ == '__main__': assert repeatableRepr({1: 'a', 2: 'b'}) == repeatableRepr({2: 'b', 1: 'a'}) assert repeatableRepr(set([1,2,3])) == repeatableRepr(set([3,2,1])) @@ -4349,7 +4351,7 @@ class PriorityCallbacks: for priority, callback in self._callbacks: callback() -if __debug__: +if __debug__ and __name__ == '__main__': l = [] def a(l=l): l.append('a') diff --git a/direct/src/showbase/ShowBase.py b/direct/src/showbase/ShowBase.py index fd2eb7cc43..a33b671dff 100644 --- a/direct/src/showbase/ShowBase.py +++ b/direct/src/showbase/ShowBase.py @@ -312,7 +312,7 @@ class ShowBase(DirectObject.DirectObject): TrueClock.getGlobalPtr().setCpuAffinity(1 << (affinity % 32)) # Make sure we're not making more than one ShowBase. - if hasattr(__builtin__, 'base'): + if 'base' in __builtin__.__dict__: raise StandardError, "Attempt to spawn multiple ShowBase instances!" __builtin__.base = self From 8365c5ce13c95c7c6973b41d4e15ae68d5fd62a1 Mon Sep 17 00:00:00 2001 From: rdb Date: Mon, 23 Dec 2013 19:39:22 +0000 Subject: [PATCH 22/37] Remove superfluous import lines (this is really genPyCode's task) --- .../extensions_native/CInterval_extensions.py | 40 +++++++------------ .../EggGroupNode_extensions.py | 4 -- .../EggPrimitive_extensions.py | 4 -- .../HTTPChannel_extensions.py | 4 -- .../src/extensions_native/Mat3_extensions.py | 4 -- .../NodePathCollection_extensions.py | 4 -- .../extensions_native/NodePath_extensions.py | 10 ++--- .../extensions_native/OdeBody_extensions.py | 4 -- .../extensions_native/OdeGeom_extensions.py | 4 -- .../extensions_native/OdeJoint_extensions.py | 4 -- .../extensions_native/OdeSpace_extensions.py | 4 -- .../extensions_native/Ramfile_extensions.py | 4 -- .../StreamReader_extensions.py | 4 -- .../extensions_native/VBase3_extensions.py | 5 --- .../extensions_native/VBase4_extensions.py | 5 --- 15 files changed, 19 insertions(+), 85 deletions(-) diff --git a/direct/src/extensions_native/CInterval_extensions.py b/direct/src/extensions_native/CInterval_extensions.py index 7b04f17f37..34c7a781cc 100644 --- a/direct/src/extensions_native/CInterval_extensions.py +++ b/direct/src/extensions_native/CInterval_extensions.py @@ -1,13 +1,3 @@ -from extension_native_helpers import * -try: - Dtool_PreloadDLL("libp3direct") - from libp3direct import * -except: - Dtool_PreloadDLL("libdirect") - from libdirect import * - -##################################################################### - from direct.directnotify.DirectNotifyGlobal import directNotify notify = directNotify.newCategory("Interval") Dtool_ObjectToDict(CInterval,"notify", notify) @@ -26,39 +16,39 @@ del setT ##################################################################### def play(self, t0 = 0.0, duration = None, scale = 1.0): - self.notify.error("using deprecated CInterval.play() interface") - if duration: # None or 0 implies full length - self.start(t0, t0 + duration, scale) - else: - self.start(t0, -1, scale) + self.notify.error("CInterval.play() is deprecated, use start() instead") + if duration: # None or 0 implies full length + self.start(t0, t0 + duration, scale) + else: + self.start(t0, -1, scale) Dtool_funcToMethod(play, CInterval) del play ##################################################################### def stop(self): - self.notify.error("using deprecated CInterval.stop() interface") - self.finish() + self.notify.error("CInterval.stop() is deprecated, use finish() instead") + self.finish() Dtool_funcToMethod(stop, CInterval) del stop ##################################################################### def setFinalT(self): - self.notify.error("using deprecated CInterval.setFinalT() interface") - self.finish() + self.notify.error("CInterval.setFinalT() is deprecated, use finish() instead") + self.finish() Dtool_funcToMethod(setFinalT, CInterval) del setFinalT ##################################################################### def privPostEvent(self): - # Call after calling any of the priv* methods to do any required - # Python finishing steps. - t = self.getT() - if hasattr(self, "setTHooks"): - for func in self.setTHooks: - func(t) + # Call after calling any of the priv* methods to do any required + # Python finishing steps. + t = self.getT() + if hasattr(self, "setTHooks"): + for func in self.setTHooks: + func(t) Dtool_funcToMethod(privPostEvent, CInterval) del privPostEvent diff --git a/direct/src/extensions_native/EggGroupNode_extensions.py b/direct/src/extensions_native/EggGroupNode_extensions.py index f852100854..6c6173e66f 100644 --- a/direct/src/extensions_native/EggGroupNode_extensions.py +++ b/direct/src/extensions_native/EggGroupNode_extensions.py @@ -1,7 +1,3 @@ -from extension_native_helpers import * -Dtool_PreloadDLL("libpandaegg") -from libpandaegg import * - #################################################################### #Dtool_funcToMethod(func, class) #del func diff --git a/direct/src/extensions_native/EggPrimitive_extensions.py b/direct/src/extensions_native/EggPrimitive_extensions.py index 9478ca9ea7..657f99a132 100644 --- a/direct/src/extensions_native/EggPrimitive_extensions.py +++ b/direct/src/extensions_native/EggPrimitive_extensions.py @@ -1,7 +1,3 @@ -from extension_native_helpers import * -Dtool_PreloadDLL("libpandaegg") -from libpandaegg import * - #################################################################### #Dtool_funcToMethod(func, class) #del func diff --git a/direct/src/extensions_native/HTTPChannel_extensions.py b/direct/src/extensions_native/HTTPChannel_extensions.py index 3a5769c636..fbbb4421dc 100644 --- a/direct/src/extensions_native/HTTPChannel_extensions.py +++ b/direct/src/extensions_native/HTTPChannel_extensions.py @@ -1,7 +1,3 @@ -from extension_native_helpers import * -Dtool_PreloadDLL("libpandaexpress") -from libpandaexpress import * - #################################################################### #Dtool_funcToMethod(func, class) #del func diff --git a/direct/src/extensions_native/Mat3_extensions.py b/direct/src/extensions_native/Mat3_extensions.py index 921d0dddf3..3895a4dd46 100755 --- a/direct/src/extensions_native/Mat3_extensions.py +++ b/direct/src/extensions_native/Mat3_extensions.py @@ -1,7 +1,3 @@ -from extension_native_helpers import * -Dtool_PreloadDLL("libpanda") -from libpanda import * - #################################################################### #Dtool_funcToMethod(func, class) #del func diff --git a/direct/src/extensions_native/NodePathCollection_extensions.py b/direct/src/extensions_native/NodePathCollection_extensions.py index 5a7503c082..f7f379ab32 100644 --- a/direct/src/extensions_native/NodePathCollection_extensions.py +++ b/direct/src/extensions_native/NodePathCollection_extensions.py @@ -1,7 +1,3 @@ -from extension_native_helpers import * -Dtool_PreloadDLL("libpanda") -from libpanda import * - ##################################################################### # For iterating over children diff --git a/direct/src/extensions_native/NodePath_extensions.py b/direct/src/extensions_native/NodePath_extensions.py index d4f6b4d472..c1a19f3784 100644 --- a/direct/src/extensions_native/NodePath_extensions.py +++ b/direct/src/extensions_native/NodePath_extensions.py @@ -1,7 +1,3 @@ -from extension_native_helpers import * -Dtool_PreloadDLL("libpanda") -from libpanda import * - #################################################################### #Dtool_funcToMethod(func, class) #del func @@ -15,6 +11,7 @@ of the NodePath class #################################################################### def id(self): """Returns a unique id identifying the NodePath instance""" + print "Warning: NodePath.id() is deprecated. Use hash(NodePath) or NodePath.get_key() instead." return self.getKey() Dtool_funcToMethod(id, NodePath) @@ -28,7 +25,7 @@ del id # For iterating over children def getChildrenAsList(self): """Converts a node path's child NodePathCollection into a list""" - print "Warning: NodePath.getChildrenAsList() is deprecated. Use getChildren() instead." + print "Warning: NodePath.getChildrenAsList() is deprecated. Use get_children() instead." return list(self.getChildren()) Dtool_funcToMethod(getChildrenAsList, NodePath) @@ -99,6 +96,7 @@ del isolate def remove(self): """Remove a node path from the scene graph""" + print "Warning: NodePath.remove() is deprecated. Use remove_node() instead." # Send message in case anyone needs to do something # before node is deleted messenger.send('preRemoveNodePath', [self]) @@ -148,7 +146,7 @@ del reverseLsNames ##################################################################### def getAncestry(self): """Get a list of a node path's ancestors""" - print "NodePath.getAncestry() is deprecated. Use getAncestors() instead.""" + print "NodePath.getAncestry() is deprecated. Use get_ancestors() instead.""" ancestors = list(self.getAncestors()) ancestors.reverse() return ancestors diff --git a/direct/src/extensions_native/OdeBody_extensions.py b/direct/src/extensions_native/OdeBody_extensions.py index 91d30521ae..78b71cb638 100755 --- a/direct/src/extensions_native/OdeBody_extensions.py +++ b/direct/src/extensions_native/OdeBody_extensions.py @@ -1,7 +1,3 @@ -from extension_native_helpers import * -Dtool_PreloadDLL("libpanda") -from libpanda import * - #################################################################### #Dtool_funcToMethod(func, class) #del func diff --git a/direct/src/extensions_native/OdeGeom_extensions.py b/direct/src/extensions_native/OdeGeom_extensions.py index 6075cbd858..e154e05e55 100755 --- a/direct/src/extensions_native/OdeGeom_extensions.py +++ b/direct/src/extensions_native/OdeGeom_extensions.py @@ -1,7 +1,3 @@ -from extension_native_helpers import * -Dtool_PreloadDLL("libpanda") -from libpanda import * - #################################################################### #Dtool_funcToMethod(func, class) #del func diff --git a/direct/src/extensions_native/OdeJoint_extensions.py b/direct/src/extensions_native/OdeJoint_extensions.py index f9bcd68f88..e113e6fdfa 100755 --- a/direct/src/extensions_native/OdeJoint_extensions.py +++ b/direct/src/extensions_native/OdeJoint_extensions.py @@ -1,7 +1,3 @@ -from extension_native_helpers import * -Dtool_PreloadDLL("libpanda") -from libpanda import * - #################################################################### #Dtool_funcToMethod(func, class) #del func diff --git a/direct/src/extensions_native/OdeSpace_extensions.py b/direct/src/extensions_native/OdeSpace_extensions.py index 5fed35c2f7..14b3c1e618 100755 --- a/direct/src/extensions_native/OdeSpace_extensions.py +++ b/direct/src/extensions_native/OdeSpace_extensions.py @@ -1,7 +1,3 @@ -from extension_native_helpers import * -Dtool_PreloadDLL("libpanda") -from libpanda import * - #################################################################### #Dtool_funcToMethod(func, class) #del func diff --git a/direct/src/extensions_native/Ramfile_extensions.py b/direct/src/extensions_native/Ramfile_extensions.py index e112a19b58..c05040c73e 100644 --- a/direct/src/extensions_native/Ramfile_extensions.py +++ b/direct/src/extensions_native/Ramfile_extensions.py @@ -1,7 +1,3 @@ -from extension_native_helpers import * -Dtool_PreloadDLL("libpandaexpress") -from libpandaexpress import * - """ Ramfile_extensions module: contains methods to extend functionality of the Ramfile class diff --git a/direct/src/extensions_native/StreamReader_extensions.py b/direct/src/extensions_native/StreamReader_extensions.py index 2cff97c311..b4111cc965 100755 --- a/direct/src/extensions_native/StreamReader_extensions.py +++ b/direct/src/extensions_native/StreamReader_extensions.py @@ -1,7 +1,3 @@ -from extension_native_helpers import * -Dtool_PreloadDLL("libpandaexpress") -from libpandaexpress import * - """ StreamReader_extensions module: contains methods to extend functionality of the StreamReader class diff --git a/direct/src/extensions_native/VBase3_extensions.py b/direct/src/extensions_native/VBase3_extensions.py index 4ea1ec2310..331bafdd4e 100755 --- a/direct/src/extensions_native/VBase3_extensions.py +++ b/direct/src/extensions_native/VBase3_extensions.py @@ -2,11 +2,6 @@ Methods to extend functionality of the VBase3 class """ -from extension_native_helpers import * -Dtool_PreloadDLL("libpanda") -from libpanda import * - - def pPrintValues(self): """ Pretty print diff --git a/direct/src/extensions_native/VBase4_extensions.py b/direct/src/extensions_native/VBase4_extensions.py index f5de0f5252..8b7c022593 100755 --- a/direct/src/extensions_native/VBase4_extensions.py +++ b/direct/src/extensions_native/VBase4_extensions.py @@ -2,11 +2,6 @@ Methods to extend functionality of the VBase4 class """ -from extension_native_helpers import * -Dtool_PreloadDLL("libpanda") -from libpanda import * - - def pPrintValues(self): """ Pretty print From 4e92e480e06a0a41cd640aaadaa651aafbee5b7c Mon Sep 17 00:00:00 2001 From: rdb Date: Mon, 23 Dec 2013 20:46:20 +0000 Subject: [PATCH 23/37] Make DatagramIterator typed (ask me if you want to know why) --- panda/src/express/config_express.cxx | 2 ++ panda/src/express/datagramIterator.cxx | 3 ++- panda/src/express/datagramIterator.h | 16 ++++++++++++++-- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/panda/src/express/config_express.cxx b/panda/src/express/config_express.cxx index d5a0abcf58..8a37739c32 100644 --- a/panda/src/express/config_express.cxx +++ b/panda/src/express/config_express.cxx @@ -14,6 +14,7 @@ #include "config_express.h" #include "datagram.h" +#include "datagramIterator.h" #include "nodeReferenceCount.h" #include "referenceCount.h" #include "textEncoder.h" @@ -99,6 +100,7 @@ init_libexpress() { initialized = true; Datagram::init_type(); + DatagramIterator::init_type(); Namable::init_type(); NodeReferenceCount::init_type(); ReferenceCount::init_type(); diff --git a/panda/src/express/datagramIterator.cxx b/panda/src/express/datagramIterator.cxx index 898d9dd7dd..c679536931 100644 --- a/panda/src/express/datagramIterator.cxx +++ b/panda/src/express/datagramIterator.cxx @@ -12,10 +12,11 @@ // //////////////////////////////////////////////////////////////////// - #include "datagramIterator.h" #include "pnotify.h" +TypeHandle DatagramIterator::_type_handle; + //////////////////////////////////////////////////////////////////// // Function: DatagramIterator::get_string // Access: Public diff --git a/panda/src/express/datagramIterator.h b/panda/src/express/datagramIterator.h index fbb6d0f867..c30a402453 100644 --- a/panda/src/express/datagramIterator.h +++ b/panda/src/express/datagramIterator.h @@ -28,8 +28,9 @@ // know the correct type and order of each element. //////////////////////////////////////////////////////////////////// class EXPCL_PANDAEXPRESS DatagramIterator { -public: - INLINE void assign(Datagram &datagram, size_t offset = 0); +public: + INLINE void assign(Datagram &datagram, size_t offset = 0); + PUBLISHED: INLINE DatagramIterator(); INLINE DatagramIterator(const Datagram &datagram, size_t offset = 0); @@ -82,6 +83,17 @@ PUBLISHED: private: const Datagram *_datagram; size_t _current_index; + +public: + static TypeHandle get_class_type() { + return _type_handle; + } + static void init_type() { + register_type(_type_handle, "DatagramIterator"); + } + +private: + static TypeHandle _type_handle; }; // These generic functions are primarily for reading a value from a From a10bbe9c9efeb24b544d769802be871252a9a321 Mon Sep 17 00:00:00 2001 From: rdb Date: Mon, 23 Dec 2013 21:06:20 +0000 Subject: [PATCH 24/37] One more pystub symbol for Python 3 that's used in direct --- dtool/src/pystub/pystub.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dtool/src/pystub/pystub.cxx b/dtool/src/pystub/pystub.cxx index 1a63ac5b2f..9118c15209 100644 --- a/dtool/src/pystub/pystub.cxx +++ b/dtool/src/pystub/pystub.cxx @@ -141,6 +141,7 @@ extern "C" { EXPCL_PYSTUB int PyUnicodeUCS4_AsWideChar(...); EXPCL_PYSTUB int PyUnicodeUCS4_GetSize(...); EXPCL_PYSTUB int PyUnicode_AsUTF8(...); + EXPCL_PYSTUB int PyUnicode_AsUTF8AndSize(...); EXPCL_PYSTUB int PyUnicode_AsWideChar(...); EXPCL_PYSTUB int PyUnicode_FromString(...); EXPCL_PYSTUB int PyUnicode_FromStringAndSize(...); @@ -304,6 +305,7 @@ int PyUnicodeUCS4_FromWideChar(...) { return 0; } int PyUnicodeUCS4_AsWideChar(...) { return 0; } int PyUnicodeUCS4_GetSize(...) { return 0; } int PyUnicode_AsUTF8(...) { return 0; } +int PyUnicode_AsUTF8AndSize(...) { return 0; } int PyUnicode_AsWideChar(...) { return 0; } int PyUnicode_FromString(...) { return 0; } int PyUnicode_FromStringAndSize(...) { return 0; } From ea22e87f7911a4888adc19aebde7d304454e3c17 Mon Sep 17 00:00:00 2001 From: rdb Date: Mon, 23 Dec 2013 22:08:33 +0000 Subject: [PATCH 25/37] remove GLX_EXT_import_context section entirely as we're not using it, and it uses GLXContextID which seems to give trouble related to conflicting definitions. --- panda/src/glxdisplay/panda_glxext.h | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/panda/src/glxdisplay/panda_glxext.h b/panda/src/glxdisplay/panda_glxext.h index 1f4952cf0c..71f208f34a 100644 --- a/panda/src/glxdisplay/panda_glxext.h +++ b/panda/src/glxdisplay/panda_glxext.h @@ -181,12 +181,6 @@ extern "C" { /* reuse GLX_NONE_EXT */ #endif -#ifndef GLX_EXT_import_context -#define GLX_SHARE_CONTEXT_EXT 0x800A -#define GLX_VISUAL_ID_EXT 0x800B -#define GLX_SCREEN_EXT 0x800C -#endif - #ifndef GLX_SGIX_fbconfig #define GLX_WINDOW_BIT_SGIX 0x00000001 #define GLX_PIXMAP_BIT_SGIX 0x00000002 @@ -458,22 +452,6 @@ typedef void (* PFNGLXDESTROYGLXVIDEOSOURCESGIXPROC) (X11_Display *dpy, GLXVideo #define GLX_EXT_visual_rating 1 #endif -#ifndef GLX_EXT_import_context -#define GLX_EXT_import_context 1 -#ifdef GLX_GLXEXT_PROTOTYPES -extern X11_Display * glXGetCurrentDisplayEXT (); -extern int glXQueryContextInfoEXT (X11_Display *, GLXContext, int, int *); -extern GLXContextID glXGetContextIDEXT (const GLXContext); -extern GLXContext glXImportContextEXT (X11_Display *, GLXContextID); -extern void glXFreeContextEXT (X11_Display *, GLXContext); -#endif /* GLX_GLXEXT_PROTOTYPES */ -typedef X11_Display * (* PFNGLXGETCURRENTDISPLAYEXTPROC) (); -typedef int (* PFNGLXQUERYCONTEXTINFOEXTPROC) (X11_Display *dpy, GLXContext context, int attribute, int *value); -typedef GLXContextID (* PFNGLXGETCONTEXTIDEXTPROC) (const GLXContext context); -typedef GLXContext (* PFNGLXIMPORTCONTEXTEXTPROC) (X11_Display *dpy, GLXContextID contextID); -typedef void (* PFNGLXFREECONTEXTEXTPROC) (X11_Display *dpy, GLXContext context); -#endif - #ifndef GLX_SGIX_fbconfig #define GLX_SGIX_fbconfig 1 #ifdef GLX_GLXEXT_PROTOTYPES From eeb2c4211fd7cd739e694c9e7ee0649e82e8ad5e Mon Sep 17 00:00:00 2001 From: rdb Date: Wed, 25 Dec 2013 13:59:08 +0000 Subject: [PATCH 26/37] Fix compilation of raw mouse support in Linux --- panda/src/x11display/x11GraphicsWindow.cxx | 25 +++++++++++----------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/panda/src/x11display/x11GraphicsWindow.cxx b/panda/src/x11display/x11GraphicsWindow.cxx index 53a7d7e1d4..27819dbf84 100644 --- a/panda/src/x11display/x11GraphicsWindow.cxx +++ b/panda/src/x11display/x11GraphicsWindow.cxx @@ -32,7 +32,7 @@ #include #include -#ifdef HAVE_LINUX_INPUT_H +#ifdef PHAVE_LINUX_INPUT_H #include #endif @@ -1202,7 +1202,7 @@ setup_colormap(XVisualInfo *visual) { //////////////////////////////////////////////////////////////////// void x11GraphicsWindow:: open_raw_mice() { -#ifdef HAVE_LINUX_INPUT_H +#ifdef PHAVE_LINUX_INPUT_H bool any_present = false; bool any_mice = false; @@ -1282,11 +1282,10 @@ open_raw_mice() { // Description: Reads events from the raw mouse device files. //////////////////////////////////////////////////////////////////// void x11GraphicsWindow:: -poll_raw_mice() -{ -#ifdef HAVE_LINUX_INPUT_H - for (int dev=0; dev<_mouse_device_info.size(); dev++) { - MouseDeviceInfo &inf = _mouse_device_info[dev]; +poll_raw_mice() { +#ifdef PHAVE_LINUX_INPUT_H + for (int di = 0; di < _mouse_device_info.size(); ++di) { + MouseDeviceInfo &inf = _mouse_device_info[di]; // Read all bytes into buffer. if (inf._fd >= 0) { @@ -1296,7 +1295,7 @@ poll_raw_mice() if (nread > 0) { inf._io_buffer += string(tbuf, nread); } else { - if ((nread < 0)&&((errno == EWOULDBLOCK) || (errno==EAGAIN))) { + if ((nread < 0) && ((errno == EWOULDBLOCK) || (errno==EAGAIN))) { break; } close(inf._fd); @@ -1315,7 +1314,7 @@ poll_raw_mice() GraphicsWindowInputDevice &dev = _input_devices[inf._input_device_index]; int x = dev.get_raw_pointer().get_x(); int y = dev.get_raw_pointer().get_y(); - for (int i=0; i= BTN_MOUSE)&&(events[i].code < BTN_MOUSE+8)) { + if ((events[i].code >= BTN_MOUSE) && (events[i].code < BTN_MOUSE + 8)) { int btn = events[i].code - BTN_MOUSE; - dev.set_pointer_in_window(x,y); + dev.set_pointer_in_window(x, y); if (events[i].value) { dev.button_down(MouseButton::button(btn)); } else { @@ -1334,8 +1333,8 @@ poll_raw_mice() } } } - inf._io_buffer.erase(0,nevents*sizeof(struct input_event)); - dev.set_pointer_in_window(x,y); + inf._io_buffer.erase(0, nevents * sizeof(struct input_event)); + dev.set_pointer_in_window(x, y); } #endif } From faa78c734ef71d8f889dd3ac1ec2d9e5f5153da2 Mon Sep 17 00:00:00 2001 From: rdb Date: Mon, 6 Jan 2014 21:11:23 +0000 Subject: [PATCH 27/37] Add HAVE_PYTHON guards --- panda/src/gobj/geomVertexArrayData_ext.cxx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/panda/src/gobj/geomVertexArrayData_ext.cxx b/panda/src/gobj/geomVertexArrayData_ext.cxx index c8310909af..04718f8770 100644 --- a/panda/src/gobj/geomVertexArrayData_ext.cxx +++ b/panda/src/gobj/geomVertexArrayData_ext.cxx @@ -14,6 +14,8 @@ #include "geomVertexArrayData_ext.h" +#ifdef HAVE_PYTHON + struct InternalBufferData { CPT(GeomVertexArrayDataHandle) _handle; Py_ssize_t _num_rows; @@ -273,3 +275,4 @@ copy_subdata_from(size_t to_start, size_t to_size, #endif } +#endif // HAVE_PYTHON From c47a98379817f09bbcb86e5962deb153d3618891 Mon Sep 17 00:00:00 2001 From: rdb Date: Sat, 11 Jan 2014 13:14:18 +0000 Subject: [PATCH 28/37] Exclude _mysql.pyd from main Panda3D package, to reduce file size --- direct/src/p3d/panda3d.pdef | 2 ++ 1 file changed, 2 insertions(+) diff --git a/direct/src/p3d/panda3d.pdef b/direct/src/p3d/panda3d.pdef index 98b44ffab9..6c93c4485d 100755 --- a/direct/src/p3d/panda3d.pdef +++ b/direct/src/p3d/panda3d.pdef @@ -87,6 +87,8 @@ class panda3d(package): 'direct.tkpanels', 'direct.tkwidgets', 'tkCommonDialog', 'tkMessageBox', 'tkSimpleDialog') + excludeModule('MySQLdb', '_mysql') + # Most of the core Panda3D DLL's will be included implicitly due to # being referenced by the above Python code. Here we name a few more # that are also needed, but aren't referenced by any code. Again, From 03b293244b9febc1bb291faa2de2c73001a4a746 Mon Sep 17 00:00:00 2001 From: rdb Date: Sat, 11 Jan 2014 13:57:37 +0000 Subject: [PATCH 29/37] Fix threaded build with Python 2.5, fix OS X build that doesn't specify sysroot --- makepanda/makepandacore.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/makepanda/makepandacore.py b/makepanda/makepandacore.py index 78d9b2250c..50b079bcde 100644 --- a/makepanda/makepandacore.py +++ b/makepanda/makepandacore.py @@ -9,7 +9,7 @@ ## ######################################################################## -import sys,os,time,stat,string,re,getopt,fnmatch,threading,signal,shutil,platform,glob,getpass,signal +import sys,os,time,stat,string,re,getopt,fnmatch,threading,signal,shutil,platform,glob,getpass,signal,thread from distutils import sysconfig if sys.version_info >= (3, 0): @@ -205,7 +205,8 @@ def PrettyTime(t): def ProgressOutput(progress, msg, target = None): prefix = "" - if (threading.currentThread() is MAINTHREAD): + thisthread = threading.currentThread() + if thisthread is MAINTHREAD: if progress is None: prefix = "" elif (progress >= 100.0): @@ -216,7 +217,8 @@ def ProgressOutput(progress, msg, target = None): prefix = "%s[%s %d%%%s] " % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow")) else: global THREADS - ident = threading.currentThread().ident + + ident = thread.get_ident() if (ident not in THREADS): THREADS[ident] = len(THREADS) + 1 prefix = "%s[%sT%d%s] " % (GetColor("yellow"), GetColor("cyan"), THREADS[ident], GetColor("yellow")) @@ -2208,10 +2210,10 @@ def SetupBuildEnvironment(compiler): cmd = GetCXX() + " -print-search-dirs" - if "MACOSX" in SDK: + if SDK.get("MACOSX"): # The default compiler in Leopard does not respect --sysroot correctly. cmd += " -isysroot " + SDK["MACOSX"] - if "SYSROOT" in SDK: + if SDK.get("SYSROOT"): cmd += ' --sysroot=%s -no-canonical-prefixes' % (SDK["SYSROOT"]) # Extract the dirs from the line that starts with 'libraries: ='. From 9c27cea4030106bf7688fc975e16c117f370ada0 Mon Sep 17 00:00:00 2001 From: rdb Date: Sat, 11 Jan 2014 13:58:22 +0000 Subject: [PATCH 30/37] try and remove unnecessary X11 dependency on OS X --- makepanda/makepanda.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/makepanda/makepanda.py b/makepanda/makepanda.py index 2cf64380e6..a98b0b755b 100755 --- a/makepanda/makepanda.py +++ b/makepanda/makepanda.py @@ -650,11 +650,10 @@ if (COMPILER=="GCC"): if (PkgSkip("PYTHON")==0): IncDirectory("ALWAYS", SDK["PYTHON"]) if (GetHost() == "darwin"): - if (PkgSkip("FREETYPE")==0): - IncDirectory("FREETYPE", "/usr/X11R6/include") + if (PkgSkip("FREETYPE")==0 and not os.path.isdir(GetThirdpartyDir() + 'freetype')): IncDirectory("FREETYPE", "/usr/X11/include") IncDirectory("FREETYPE", "/usr/X11/include/freetype2") - IncDirectory("GL", "/usr/X11R6/include") + LibDirectory("FREETYPE", "/usr/X11/lib") if (os.path.isdir("/usr/PCBSD")): IncDirectory("ALWAYS", "/usr/PCBSD/local/include") @@ -664,19 +663,20 @@ if (COMPILER=="GCC"): IncDirectory("ALWAYS", "/usr/local/include") LibDirectory("ALWAYS", "/usr/local/lib") - # Workaround for an issue where pkg-config does not include this path - if GetTargetArch() in ("x86_64", "amd64"): - if (os.path.isdir("/usr/lib64/glib-2.0/include")): - IncDirectory("GTK2", "/usr/lib64/glib-2.0/include") - if (os.path.isdir("/usr/lib64/gtk-2.0/include")): - IncDirectory("GTK2", "/usr/lib64/gtk-2.0/include") + if GetHost() != "darwin": + # Workaround for an issue where pkg-config does not include this path + if GetTargetArch() in ("x86_64", "amd64"): + if (os.path.isdir("/usr/lib64/glib-2.0/include")): + IncDirectory("GTK2", "/usr/lib64/glib-2.0/include") + if (os.path.isdir("/usr/lib64/gtk-2.0/include")): + IncDirectory("GTK2", "/usr/lib64/gtk-2.0/include") - if (os.path.isdir("/usr/X11R6/lib64")): - LibDirectory("ALWAYS", "/usr/X11R6/lib64") + if (os.path.isdir("/usr/X11R6/lib64")): + LibDirectory("ALWAYS", "/usr/X11R6/lib64") + else: + LibDirectory("ALWAYS", "/usr/X11R6/lib") else: LibDirectory("ALWAYS", "/usr/X11R6/lib") - else: - LibDirectory("ALWAYS", "/usr/X11R6/lib") fcollada_libs = ("FColladaD", "FColladaSD", "FColladaS") # WARNING! The order of the ffmpeg libraries matters! From b781547956f7a576ee4af896fb0728d4005f9b95 Mon Sep 17 00:00:00 2001 From: rdb Date: Sat, 11 Jan 2014 15:06:22 +0000 Subject: [PATCH 31/37] a tiny optimisation to use less registers --- panda/src/pgraphnodes/shaderGenerator.cxx | 142 ++++++++++------------ 1 file changed, 64 insertions(+), 78 deletions(-) diff --git a/panda/src/pgraphnodes/shaderGenerator.cxx b/panda/src/pgraphnodes/shaderGenerator.cxx index 9f9218ed46..2ff2b5e3ce 100644 --- a/panda/src/pgraphnodes/shaderGenerator.cxx +++ b/panda/src/pgraphnodes/shaderGenerator.cxx @@ -95,6 +95,14 @@ alloc_vreg() { case 5: _vtregs_used += 1; return (char*)"TEXCOORD5"; case 6: _vtregs_used += 1; return (char*)"TEXCOORD6"; case 7: _vtregs_used += 1; return (char*)"TEXCOORD7"; + } + switch (_vcregs_used) { + case 0: _vcregs_used += 1; return (char*)"COLOR0"; + case 1: _vcregs_used += 1; return (char*)"COLOR1"; + } + // These don't exist in arbvp1, though they're reportedly + // supported by other profiles. + switch (_vtregs_used) { case 8: _vtregs_used += 1; return (char*)"TEXCOORD8"; case 9: _vtregs_used += 1; return (char*)"TEXCOORD9"; case 10: _vtregs_used += 1; return (char*)"TEXCOORD10"; @@ -104,24 +112,6 @@ alloc_vreg() { case 14: _vtregs_used += 1; return (char*)"TEXCOORD14"; case 15: _vtregs_used += 1; return (char*)"TEXCOORD15"; } - switch (_vcregs_used) { - case 0: _vcregs_used += 1; return (char*)"COLOR0"; - case 1: _vcregs_used += 1; return (char*)"COLOR1"; - case 2: _vcregs_used += 1; return (char*)"COLOR2"; - case 3: _vcregs_used += 1; return (char*)"COLOR3"; - case 4: _vcregs_used += 1; return (char*)"COLOR4"; - case 5: _vcregs_used += 1; return (char*)"COLOR5"; - case 6: _vcregs_used += 1; return (char*)"COLOR6"; - case 7: _vcregs_used += 1; return (char*)"COLOR7"; - case 8: _vcregs_used += 1; return (char*)"COLOR8"; - case 9: _vcregs_used += 1; return (char*)"COLOR9"; - case 10: _vcregs_used += 1; return (char*)"COLOR10"; - case 11: _vcregs_used += 1; return (char*)"COLOR11"; - case 12: _vcregs_used += 1; return (char*)"COLOR12"; - case 13: _vcregs_used += 1; return (char*)"COLOR13"; - case 14: _vcregs_used += 1; return (char*)"COLOR14"; - case 15: _vcregs_used += 1; return (char*)"COLOR15"; - } return (char*)"UNKNOWN"; } @@ -141,6 +131,14 @@ alloc_freg() { case 5: _ftregs_used += 1; return (char*)"TEXCOORD5"; case 6: _ftregs_used += 1; return (char*)"TEXCOORD6"; case 7: _ftregs_used += 1; return (char*)"TEXCOORD7"; + } + switch (_fcregs_used) { + case 0: _fcregs_used += 1; return (char*)"COLOR0"; + case 1: _fcregs_used += 1; return (char*)"COLOR1"; + } + // These don't exist in arbvp1/arbfp1, though they're + // reportedly supported by other profiles. + switch (_ftregs_used) { case 8: _ftregs_used += 1; return (char*)"TEXCOORD8"; case 9: _ftregs_used += 1; return (char*)"TEXCOORD9"; case 10: _ftregs_used += 1; return (char*)"TEXCOORD10"; @@ -150,24 +148,6 @@ alloc_freg() { case 14: _ftregs_used += 1; return (char*)"TEXCOORD14"; case 15: _ftregs_used += 1; return (char*)"TEXCOORD15"; } - switch (_fcregs_used) { - case 0: _fcregs_used += 1; return (char*)"COLOR0"; - case 1: _fcregs_used += 1; return (char*)"COLOR1"; - case 2: _fcregs_used += 1; return (char*)"COLOR2"; - case 3: _fcregs_used += 1; return (char*)"COLOR3"; - case 4: _fcregs_used += 1; return (char*)"COLOR4"; - case 5: _fcregs_used += 1; return (char*)"COLOR5"; - case 6: _fcregs_used += 1; return (char*)"COLOR6"; - case 7: _fcregs_used += 1; return (char*)"COLOR7"; - case 8: _fcregs_used += 1; return (char*)"COLOR8"; - case 9: _fcregs_used += 1; return (char*)"COLOR9"; - case 10: _fcregs_used += 1; return (char*)"COLOR10"; - case 11: _fcregs_used += 1; return (char*)"COLOR11"; - case 12: _fcregs_used += 1; return (char*)"COLOR12"; - case 13: _fcregs_used += 1; return (char*)"COLOR13"; - case 14: _fcregs_used += 1; return (char*)"COLOR14"; - case 15: _fcregs_used += 1; return (char*)"COLOR15"; - } return (char*)"UNKNOWN"; } @@ -230,7 +210,7 @@ analyze_renderstate(const RenderState *rs) { _out_aux_normal = (outputs & AuxBitplaneAttrib::ABO_aux_normal) ? true:false; _out_aux_glow = (outputs & AuxBitplaneAttrib::ABO_aux_glow) ? true:false; _out_aux_any = (_out_aux_normal || _out_aux_glow); - + if (_out_aux_normal) { _need_eye_normal = true; } @@ -285,7 +265,7 @@ analyze_renderstate(const RenderState *rs) { // See if there is a normal map, height map, gloss map, or glow map. // Also check if anything has TexGen. - + const TexGenAttrib *tex_gen = DCAST(TexGenAttrib, rs->get_attrib_def(TexGenAttrib::get_class_slot())); for (int i=0; i<_num_textures; i++) { TextureStage *stage = texture->get_on_stage(i); @@ -336,7 +316,6 @@ analyze_renderstate(const RenderState *rs) { if (la->get_num_on_lights() > 0) { _lighting = true; - _need_eye_position = true; _need_eye_normal = true; } @@ -390,6 +369,13 @@ analyze_renderstate(const RenderState *rs) { } else if (_map_index_gloss >= 0) { _have_specular = true; } + + if (_plights.size() + _slights.size() > 0) { + _need_eye_position = true; + + } else if (_have_specular && _material->get_local()) { + _need_eye_position = true; + } } // Decide whether to separate ambient and diffuse calculations. @@ -521,34 +507,34 @@ CPT(RenderAttrib) ShaderGenerator:: create_shader_attrib(const string &txt) { PT(Shader) shader = Shader::make(txt); CPT(RenderAttrib) shattr = ShaderAttrib::make(); - shattr=DCAST(ShaderAttrib, shattr)->set_shader(shader); + shattr = DCAST(ShaderAttrib, shattr)->set_shader(shader); if (_lighting) { - for (int i=0; i<(int)_alights.size(); i++) { - shattr=DCAST(ShaderAttrib, shattr)->set_shader_input(InternalName::make("alight", i), _alights_np[i]); + for (int i=0; i < (int)_alights.size(); i++) { + shattr = DCAST(ShaderAttrib, shattr)->set_shader_input(InternalName::make("alight", i), _alights_np[i]); } - for (int i=0; i<(int)_dlights.size(); i++) { - shattr=DCAST(ShaderAttrib, shattr)->set_shader_input(InternalName::make("dlight", i), _dlights_np[i]); + for (int i=0; i < (int)_dlights.size(); i++) { + shattr = DCAST(ShaderAttrib, shattr)->set_shader_input(InternalName::make("dlight", i), _dlights_np[i]); if (_shadows && _dlights[i]->_shadow_caster) { PT(Texture) tex = update_shadow_buffer(_dlights_np[i]); if (tex == NULL) { pgraph_cat.error() << "Failed to create shadow buffer for DirectionalLight '" << _dlights[i]->get_name() << "'!\n"; } - shattr=DCAST(ShaderAttrib, shattr)->set_shader_input(InternalName::make("dlighttex", i), tex); + shattr = DCAST(ShaderAttrib, shattr)->set_shader_input(InternalName::make("dlighttex", i), tex); } else { _dlights[i]->clear_shadow_buffers(); } } - for (int i=0; i<(int)_plights.size(); i++) { - shattr=DCAST(ShaderAttrib, shattr)->set_shader_input(InternalName::make("plight", i), _plights_np[i]); + for (int i=0; i < (int)_plights.size(); i++) { + shattr = DCAST(ShaderAttrib, shattr)->set_shader_input(InternalName::make("plight", i), _plights_np[i]); } - for (int i=0; i<(int)_slights.size(); i++) { - shattr=DCAST(ShaderAttrib, shattr)->set_shader_input(InternalName::make("slight", i), _slights_np[i]); + for (int i=0; i < (int)_slights.size(); i++) { + shattr = DCAST(ShaderAttrib, shattr)->set_shader_input(InternalName::make("slight", i), _slights_np[i]); if (_shadows && _slights[i]->_shadow_caster) { PT(Texture) tex = update_shadow_buffer(_slights_np[i]); if (tex == NULL) { pgraph_cat.error() << "Failed to create shadow buffer for Spotlight '" << _slights[i]->get_name() << "'!\n"; } - shattr=DCAST(ShaderAttrib, shattr)->set_shader_input(InternalName::make("slighttex", i), tex); + shattr = DCAST(ShaderAttrib, shattr)->set_shader_input(InternalName::make("slighttex", i), tex); } else { _slights[i]->clear_shadow_buffers(); } @@ -574,7 +560,7 @@ update_shadow_buffer(NodePath light_np) { if (light == NULL || !light->_shadow_caster) { return NULL; } - + // See if we already have a buffer. If not, create one. PT(Texture) tex; if (light->_sbuffers.count(_gsg) == 0) { @@ -634,7 +620,6 @@ synthesize_shader(const RenderState *rs) { // These variables will hold the results of register allocation. - char *normal_vreg = 0; char *ntangent_vreg = 0; char *ntangent_freg = 0; char *nbinormal_vreg = 0; @@ -652,6 +637,7 @@ synthesize_shader(const RenderState *rs) { char *hpos_freg = 0; if (_vertex_colors) { + // Reserve COLOR0 _vcregs_used = 1; _fcregs_used = 1; } @@ -676,8 +662,8 @@ synthesize_shader(const RenderState *rs) { text << "\t out float4 l_texcoord" << i << " : " << texcoord_freg[i] << ",\n"; } if (_vertex_colors) { - text << "\t in float4 vtx_color : COLOR,\n"; - text << "\t out float4 l_color : COLOR,\n"; + text << "\t in float4 vtx_color : COLOR0,\n"; + text << "\t out float4 l_color : COLOR0,\n"; } if (_need_world_position || _need_world_normal) { text << "\t uniform float4x4 trans_model_to_world,\n"; @@ -701,8 +687,7 @@ synthesize_shader(const RenderState *rs) { text << "\t out float4 l_eye_normal : " << eye_normal_freg << ",\n"; } if (_map_index_height >= 0 || _need_world_normal || _need_eye_normal) { - normal_vreg = alloc_vreg(); - text << "\t in float4 vtx_normal : " << normal_vreg << ",\n"; + text << "\t in float4 vtx_normal : NORMAL,\n"; } if (_map_index_height >= 0) { htangent_vreg = alloc_vreg(); @@ -722,6 +707,7 @@ synthesize_shader(const RenderState *rs) { if (_map_index_normal != _map_index_height) { ntangent_vreg = alloc_vreg(); nbinormal_vreg = alloc_vreg(); + // NB. If we used TANGENT and BINORMAL, Cg would have them overlap with TEXCOORD6-7. text << "\t in float4 vtx_tangent" << _map_index_normal << " : " << ntangent_vreg << ",\n"; text << "\t in float4 vtx_binormal" << _map_index_normal << " : " << nbinormal_vreg << ",\n"; } @@ -731,7 +717,7 @@ synthesize_shader(const RenderState *rs) { text << "\t out float4 l_binormal : " << nbinormal_freg << ",\n"; } if (_shadows && _auto_shadow_on) { - for (int i=0; i<(int)_dlights.size(); i++) { + for (int i=0; i < (int)_dlights.size(); i++) { if (_dlights[i]->_shadow_caster) { dlightcoord_freg.push_back(alloc_freg()); text << "\t uniform float4x4 trans_model_to_clip_of_dlight" << i << ",\n"; @@ -740,7 +726,7 @@ synthesize_shader(const RenderState *rs) { dlightcoord_freg.push_back(NULL); } } - for (int i=0; i<(int)_slights.size(); i++) { + for (int i=0; i < (int)_slights.size(); i++) { if (_slights[i]->_shadow_caster) { slightcoord_freg.push_back(alloc_freg()); text << "\t uniform float4x4 trans_model_to_clip_of_slight" << i << ",\n"; @@ -793,12 +779,12 @@ synthesize_shader(const RenderState *rs) { } if (_shadows && _auto_shadow_on) { text << "\t float4x4 biasmat = {0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f};\n"; - for (int i=0; i<(int)_dlights.size(); i++) { + for (int i=0; i < (int)_dlights.size(); i++) { if (_dlights[i]->_shadow_caster) { text << "\t l_dlightcoord" << i << " = mul(biasmat, mul(trans_model_to_clip_of_dlight" << i << ", vtx_position));\n"; } } - for (int i=0; i<(int)_slights.size(); i++) { + for (int i=0; i < (int)_slights.size(); i++) { if (_slights[i]->_shadow_caster) { text << "\t l_slightcoord" << i << " = mul(biasmat, mul(trans_model_to_clip_of_slight" << i << ", vtx_position));\n"; } @@ -827,7 +813,7 @@ synthesize_shader(const RenderState *rs) { if (_need_world_normal) { text << "\t in float4 l_world_normal : " << world_normal_freg << ",\n"; } - if (_need_eye_position) { + if (_need_eye_position) { text << "\t in float4 l_eye_position : " << eye_position_freg << ",\n"; } if (_need_eye_normal) { @@ -851,10 +837,10 @@ synthesize_shader(const RenderState *rs) { text << "\t in float3 l_binormal : " << nbinormal_freg << ",\n"; } if (_lighting) { - for (int i=0; i<(int)_alights.size(); i++) { + for (int i=0; i < (int)_alights.size(); i++) { text << "\t uniform float4 alight_alight" << i << ",\n"; } - for (int i=0; i<(int)_dlights.size(); i++) { + for (int i=0; i < (int)_dlights.size(); i++) { text << "\t uniform float4x4 dlight_dlight" << i << "_rel_view,\n"; if (_shadows && _dlights[i]->_shadow_caster && _auto_shadow_on) { if (_use_shadow_filter) { @@ -865,10 +851,10 @@ synthesize_shader(const RenderState *rs) { text << "\t in float4 l_dlightcoord" << i << " : " << dlightcoord_freg[i] << ",\n"; } } - for (int i=0; i<(int)_plights.size(); i++) { + for (int i=0; i < (int)_plights.size(); i++) { text << "\t uniform float4x4 plight_plight" << i << "_rel_view,\n"; } - for (int i=0; i<(int)_slights.size(); i++) { + for (int i=0; i < (int)_slights.size(); i++) { text << "\t uniform float4x4 slight_slight" << i << "_rel_view,\n"; text << "\t uniform float4 satten_slight" << i << ",\n"; if (_shadows && _slights[i]->_shadow_caster && _auto_shadow_on) { @@ -899,7 +885,7 @@ synthesize_shader(const RenderState *rs) { } text << "\t out float4 o_color : COLOR0,\n"; if (_vertex_colors) { - text << "\t in float4 l_color : COLOR,\n"; + text << "\t in float4 l_color : COLOR0,\n"; } else { text << "\t uniform float4 attr_color,\n"; } @@ -917,7 +903,7 @@ synthesize_shader(const RenderState *rs) { } text << "\t float4 result;\n"; if (_out_aux_any) { - text << "\t o_aux = float4(0,0,0,0);\n"; + text << "\t o_aux = float4(0, 0, 0, 0);\n"; } // Now generate any texture coordinates according to TexGenAttrib. If it has a TexMatrixAttrib, also transform them. for (int i=0; i<_num_textures; i++) { @@ -959,11 +945,11 @@ synthesize_shader(const RenderState *rs) { case Texture::TT_2d_texture_array: text << "xyz"; break; - case Texture::TT_2d_texture: - text << "xy"; + case Texture::TT_2d_texture: + text << "xy"; break; case Texture::TT_1d_texture: - text << "x"; + text << "x"; break; default: break; @@ -1058,7 +1044,7 @@ synthesize_shader(const RenderState *rs) { text << "\t float shininess = 50; // no shininess specified, using default\n"; } } - for (int i=0; i<(int)_alights.size(); i++) { + for (int i=0; i < (int)_alights.size(); i++) { text << "\t // Ambient Light " << i << "\n"; text << "\t lcolor = alight_alight" << i << ";\n"; if (_separate_ambient_diffuse && _have_ambient) { @@ -1067,7 +1053,7 @@ synthesize_shader(const RenderState *rs) { text << "\t tot_diffuse += lcolor;\n"; } } - for (int i=0; i<(int)_dlights.size(); i++) { + for (int i=0; i < (int)_dlights.size(); i++) { text << "\t // Directional Light " << i << "\n"; text << "\t lcolor = dlight_dlight" << i << "_rel_view[0];\n"; text << "\t lspec = dlight_dlight" << i << "_rel_view[1];\n"; @@ -1095,7 +1081,7 @@ synthesize_shader(const RenderState *rs) { text << "\t tot_specular += lspec;\n"; } } - for (int i=0; i<(int)_plights.size(); i++) { + for (int i=0; i < (int)_plights.size(); i++) { text << "\t // Point Light " << i << "\n"; text << "\t lcolor = plight_plight" << i << "_rel_view[0];\n"; text << "\t lspec = plight_plight" << i << "_rel_view[1];\n"; @@ -1113,14 +1099,14 @@ synthesize_shader(const RenderState *rs) { if (_material->get_local()) { text << "\t lhalf = normalize(lvec - normalize(l_eye_position));\n"; } else { - text << "\t lhalf = normalize(lvec - float4(0,1,0,0));\n"; + text << "\t lhalf = normalize(lvec - float4(0, 1, 0, 0));\n"; } text << "\t lspec *= lattenv;\n"; text << "\t lspec *= pow(saturate(dot(l_eye_normal.xyz, lhalf.xyz)), shininess);\n"; text << "\t tot_specular += lspec;\n"; } } - for (int i=0; i<(int)_slights.size(); i++) { + for (int i=0; i < (int)_slights.size(); i++) { text << "\t // Spot Light " << i << "\n"; text << "\t lcolor = slight_slight" << i << "_rel_view[0];\n"; text << "\t lspec = slight_slight" << i << "_rel_view[1];\n"; @@ -1431,7 +1417,7 @@ synthesize_shader(const RenderState *rs) { case Fog::M_linear: text << "\t result.rgb = lerp(attr_fogcolor.rgb, result.rgb, saturate((attr_fog.z - l_hpos.z) * attr_fog.w));\n"; break; - case Fog::M_exponential: + case Fog::M_exponential: // 1.442695f = 1 / log(2) text << "\t result.rgb = lerp(attr_fogcolor.rgb, result.rgb, saturate(exp2(attr_fog.x * l_hpos.z * -1.442695f)));\n"; break; case Fog::M_exponential_squared: @@ -1454,10 +1440,10 @@ synthesize_shader(const RenderState *rs) { // Insert the shader into the shader attrib. CPT(RenderAttrib) shattr = create_shader_attrib(text.str()); if (_subsume_alpha_test) { - shattr=DCAST(ShaderAttrib, shattr)->set_flag(ShaderAttrib::F_subsume_alpha_test, true); + shattr = DCAST(ShaderAttrib, shattr)->set_flag(ShaderAttrib::F_subsume_alpha_test, true); } if (_disable_alpha_write) { - shattr=DCAST(ShaderAttrib, shattr)->set_flag(ShaderAttrib::F_disable_alpha_write, true); + shattr = DCAST(ShaderAttrib, shattr)->set_flag(ShaderAttrib::F_disable_alpha_write, true); } clear_analysis(); reset_register_allocator(); From 56577ec08a6c5cef34af6b66c5ad074ce7feb5cd Mon Sep 17 00:00:00 2001 From: rdb Date: Mon, 13 Jan 2014 21:31:42 +0000 Subject: [PATCH 32/37] Don't rely on color fregs, they have unintended side-effects. Also, don't use up unnecessary registers when texgen is enabled. --- panda/src/pgraphnodes/shaderGenerator.cxx | 25 ++++++++++++++--------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/panda/src/pgraphnodes/shaderGenerator.cxx b/panda/src/pgraphnodes/shaderGenerator.cxx index 2ff2b5e3ce..d250387b9e 100644 --- a/panda/src/pgraphnodes/shaderGenerator.cxx +++ b/panda/src/pgraphnodes/shaderGenerator.cxx @@ -132,10 +132,12 @@ alloc_freg() { case 6: _ftregs_used += 1; return (char*)"TEXCOORD6"; case 7: _ftregs_used += 1; return (char*)"TEXCOORD7"; } - switch (_fcregs_used) { - case 0: _fcregs_used += 1; return (char*)"COLOR0"; - case 1: _fcregs_used += 1; return (char*)"COLOR1"; - } + // We really shouldn't rely on COLOR fregs, + // since the clamping can have unexpected side-effects. + //switch (_fcregs_used) { + //case 0: _fcregs_used += 1; return (char*)"COLOR0"; + //case 1: _fcregs_used += 1; return (char*)"COLOR1"; + //} // These don't exist in arbvp1/arbfp1, though they're // reportedly supported by other profiles. switch (_ftregs_used) { @@ -655,11 +657,14 @@ synthesize_shader(const RenderState *rs) { text << "void vshader(\n"; const TextureAttrib *texture = DCAST(TextureAttrib, rs->get_attrib_def(TextureAttrib::get_class_slot())); const TexGenAttrib *tex_gen = DCAST(TexGenAttrib, rs->get_attrib_def(TexGenAttrib::get_class_slot())); - for (int i=0; i<_num_textures; i++) { - texcoord_vreg.push_back(alloc_vreg()); - texcoord_freg.push_back(alloc_freg()); - text << "\t in float4 vtx_texcoord" << i << " : " << texcoord_vreg[i] << ",\n"; - text << "\t out float4 l_texcoord" << i << " : " << texcoord_freg[i] << ",\n"; + for (int i = 0; i < _num_textures; ++i) { + TextureStage *stage = texture->get_on_stage(i); + if (!tex_gen->has_stage(stage)) { + texcoord_vreg.push_back(alloc_vreg()); + texcoord_freg.push_back(alloc_freg()); + text << "\t in float4 vtx_texcoord" << i << " : " << texcoord_vreg[i] << ",\n"; + text << "\t out float4 l_texcoord" << i << " : " << texcoord_freg[i] << ",\n"; + } } if (_vertex_colors) { text << "\t in float4 vtx_color : COLOR0,\n"; @@ -763,7 +768,7 @@ synthesize_shader(const RenderState *rs) { text << "\t l_eye_normal.xyz = mul((float3x3)tpose_view_to_model, vtx_normal.xyz);\n"; text << "\t l_eye_normal.w = 0;\n"; } - for (int i=0; i<_num_textures; i++) { + for (int i = 0; i < _num_textures; ++i) { if (!tex_gen->has_stage(texture->get_on_stage(i))) { text << "\t l_texcoord" << i << " = vtx_texcoord" << i << ";\n"; } From 849dc05a60bcbdd2ada5c1e63d9dc30d2a8b1e11 Mon Sep 17 00:00:00 2001 From: rdb Date: Mon, 13 Jan 2014 22:06:47 +0000 Subject: [PATCH 33/37] Fix blunder --- panda/src/pgraphnodes/shaderGenerator.cxx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/panda/src/pgraphnodes/shaderGenerator.cxx b/panda/src/pgraphnodes/shaderGenerator.cxx index d250387b9e..b77dddd5c4 100644 --- a/panda/src/pgraphnodes/shaderGenerator.cxx +++ b/panda/src/pgraphnodes/shaderGenerator.cxx @@ -628,7 +628,6 @@ synthesize_shader(const RenderState *rs) { char *nbinormal_freg = 0; char *htangent_vreg = 0; char *hbinormal_vreg = 0; - pvector texcoord_vreg; pvector texcoord_freg; pvector dlightcoord_freg; pvector slightcoord_freg; @@ -660,10 +659,11 @@ synthesize_shader(const RenderState *rs) { for (int i = 0; i < _num_textures; ++i) { TextureStage *stage = texture->get_on_stage(i); if (!tex_gen->has_stage(stage)) { - texcoord_vreg.push_back(alloc_vreg()); texcoord_freg.push_back(alloc_freg()); - text << "\t in float4 vtx_texcoord" << i << " : " << texcoord_vreg[i] << ",\n"; + text << "\t in float4 vtx_texcoord" << i << " : " << alloc_vreg() << ",\n"; text << "\t out float4 l_texcoord" << i << " : " << texcoord_freg[i] << ",\n"; + } else { + texcoord_freg.push_back(NULL); } } if (_vertex_colors) { From 07404ff69428a2aacf0c35ea3664cdef1b33489c Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 14 Jan 2014 10:12:50 +0000 Subject: [PATCH 34/37] Add SetRegView so we can correctly install 64-bit build to the 64-bit registry --- direct/src/directscripts/packpanda.nsi | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/direct/src/directscripts/packpanda.nsi b/direct/src/directscripts/packpanda.nsi index 04cb72279c..78e829b48d 100755 --- a/direct/src/directscripts/packpanda.nsi +++ b/direct/src/directscripts/packpanda.nsi @@ -22,6 +22,7 @@ ; PANDACONF - name of panda config directory - usually $PANDA\etc ; PSOURCE - location of the panda source-tree if available, OR location of panda install tree. ; PYEXTRAS - directory containing python extras, if any. +; REGVIEW - either 32 or 64, depending on the build architecture. ; ; PPGAME - directory containing prepagaged game, if any (ie, "C:\My Games\Airblade") ; PPMAIN - python program containing prepackaged game, if any (ie, "Airblade.py") @@ -37,6 +38,10 @@ OutFile "${OUTFILE}" SetCompress auto SetCompressor ${COMPRESSOR} +!ifdef REGVIEW +SetRegView ${REGVIEW} +!endif + !define MUI_WELCOMEFINISHPAGE_BITMAP "${IBITMAP}" !define MUI_UNWELCOMEFINISHPAGE_BITMAP "${UBITMAP}" From cd01f15c77e4d1e751714e9fd1b6398a9566c147 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 14 Jan 2014 10:42:03 +0000 Subject: [PATCH 35/37] Use 64-bit regview when making 64-bit builds to fix interaction between Python installations/libraries and Panda3D --- makepanda/makepanda.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/makepanda/makepanda.py b/makepanda/makepanda.py index a98b0b755b..9fbe316221 100755 --- a/makepanda/makepanda.py +++ b/makepanda/makepanda.py @@ -5908,6 +5908,11 @@ def MakeInstallerNSIS(file, fullname, smdirectory, installdir): psource = os.path.abspath(".") panda = os.path.abspath(GetOutputDir()) + if GetTargetArch() == 'x64': + regview = '64' + else: + regview = '32' + nsis_defs = { 'COMPRESSOR' : COMPRESSOR, 'NAME' : fullname, @@ -5924,6 +5929,7 @@ def MakeInstallerNSIS(file, fullname, smdirectory, installdir): 'PANDACONF' : os.path.join(panda, 'etc'), 'PSOURCE' : psource, 'PYEXTRAS' : os.path.join(os.path.abspath(GetThirdpartyBase()), 'win-extras'), + 'REGVIEW' : regview, } if GetHost() == 'windows': From 5f9545a914be20a3c13c7a5e9b8a2835efefecf3 Mon Sep 17 00:00:00 2001 From: rdb Date: Tue, 14 Jan 2014 11:02:58 +0000 Subject: [PATCH 36/37] Move SetRegView to appropriate sections --- direct/src/directscripts/packpanda.nsi | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/direct/src/directscripts/packpanda.nsi b/direct/src/directscripts/packpanda.nsi index 78e829b48d..dad5e4beb5 100755 --- a/direct/src/directscripts/packpanda.nsi +++ b/direct/src/directscripts/packpanda.nsi @@ -38,10 +38,6 @@ OutFile "${OUTFILE}" SetCompress auto SetCompressor ${COMPRESSOR} -!ifdef REGVIEW -SetRegView ${REGVIEW} -!endif - !define MUI_WELCOMEFINISHPAGE_BITMAP "${IBITMAP}" !define MUI_UNWELCOMEFINISHPAGE_BITMAP "${UBITMAP}" @@ -245,6 +241,10 @@ SectionEnd Section -post + !ifdef REGVIEW + SetRegView ${REGVIEW} + !endif + !ifndef PPGAME # Add the "bin" directory to the PATH. @@ -287,6 +287,10 @@ SectionEnd Section Uninstall + !ifdef REGVIEW + SetRegView ${REGVIEW} + !endif + !ifndef PPGAME Push "$INSTDIR\python" Call un.RemoveFromPath From 618781e7ccb8016d59251443b8177089ecc7ebc5 Mon Sep 17 00:00:00 2001 From: rdb Date: Fri, 17 Jan 2014 22:09:53 +0000 Subject: [PATCH 37/37] there's no reason to interrogate the ffmpeg code. --- panda/src/ffmpeg/Sources.pp | 2 -- 1 file changed, 2 deletions(-) diff --git a/panda/src/ffmpeg/Sources.pp b/panda/src/ffmpeg/Sources.pp index 47c7f4a048..c47164a611 100644 --- a/panda/src/ffmpeg/Sources.pp +++ b/panda/src/ffmpeg/Sources.pp @@ -39,6 +39,4 @@ ffmpegAudioCursor.h ffmpegAudioCursor.I \ ffmpegVirtualFile.h ffmpegVirtualFile.I - #define IGATESCAN all - #end lib_target