# 1. it tells python that yade (this directory) is package of python modules
#	see http://http://www.python.org/doc/2.1.3/tut/node8.html#SECTION008400000000000000000
#
# 2. import the runtime namespace (will be populated from within c++)
#

"""Common initialization core for yade.

This file is executed when anything is imported from yade for the first time.
It loads yade plugins and injects c++ class constructors to the __builtins__
(that might change in the future, though) namespace, making them available
everywhere.
"""
import ctypes,sys,os

if os.getenv('OMPI_COMM_WORLD_RANK')==None: #else decrease verbosity
	print("Using python version:",sys.version)

sys.setdlopenflags(os.RTLD_NOW | os.RTLD_GLOBAL)

# important: initialize c++ by importing libstdc++ directly
# see http://www.abclinuxu.cz/poradna/programovani/show/286322
# (old site, fixed bug) https://bugs.launchpad.net/bugs/490744
# 
# This is already fixed in systems, newer, than Ubuntu 10.04. anyway for 
# back-compatibility we will keep it.

libstdcxx='${libstdcxx}' # substituted by scons
try:
  ctypes.cdll.LoadLibrary(libstdcxx)
except: pass

#

# now ready for c++ imports

# find plugin directory
import os,os.path
from yade import config
# find plugins recursively
plugins=[]
# might add followlinks=True to os.walk, for python>=2.6
for root,dirs,files in os.walk(config.libDir):
	# skip any directory named 'dbg' in the non-debug build
	if 'dbg' in dirs: dirs.remove('dbg')
	for f in files:
		# ouch, ugly!
		#if not config.debug and '/dbg/' in root: continue
		if not (f.startswith('lib') and f.endswith('.so')): continue
		plugin=os.path.join(config.libDir,root,f)
		plugins.append(plugin)
if 'YADE_DEBUG' in os.environ:
     print('The following plugins will be loaded:')
     for p in plugins: print('\t'+p)

# c++ initialization code
from yade import boot
boot.initialize(plugins,config.confDir)
from yade import system
## ENABLE_LOGGER ## this was in git revision 014b11496 YADE_LOG4CXX -> YADE_BOOST_LOG ##
## ENABLE_LOGGER #? system.setExitHandlers() # avoid backtrace if crash at finalization (log4cxx)

# create proxies for deprecated classes
deprecatedTypes=system.cxxCtorsDict()
# insert those in the module namespace
globals().update(deprecatedTypes)
# declare what should be imported for "from yade import *"
__all__=list(deprecatedTypes.keys())+['O']

from yade.minieigenHP import *

from yade.wrapper import *
# import to separate namespace to be able to call dir(miniEigen) and dir(wrapper) below
from yade import wrapper 

# bindings for python2 retro-compatibility:
wrapper.BodyIterator.next=wrapper.BodyIterator.__next__
wrapper.InteractionIterator.next=wrapper.InteractionIterator.__next__
from yade import pack
pack.SpherePackIterator.next=pack.SpherePackIterator.__next__

# out-of-class docstrings for some classes
from yade import _extraDocs
# import a few "important" modules along with *
from yade import utils # some others?
__all__+=['utils',]+dir(wrapper)


# make O and wrapper.Omega part of __builtin__ (equvialent to global)
import builtins
builtins.__dict__['O'] = O
builtins.__dict__['Omega'] = wrapper.Omega

#this will allow in python3 direct use of yade modules with import module_name (normally forbidden)
sys.path.insert(2,os.path.realpath(__file__).rsplit("/",1)[0])

# FIXME: this should go somewhere else, but where? userSession() might be too late since there is possible script execution before it.

# define a default list of engine
yade.utils.defaultEngines=[
		ForceResetter(),
		InsertionSortCollider([Bo1_Sphere_Aabb(),Bo1_Facet_Aabb(),Bo1_Box_Aabb()],label="collider"),
		InteractionLoop(
			[Ig2_Sphere_Sphere_ScGeom(),Ig2_Facet_Sphere_ScGeom(),Ig2_Box_Sphere_ScGeom()],
			[Ip2_FrictMat_FrictMat_FrictPhys()],	#for linear model only
			[Law2_ScGeom_FrictPhys_CundallStrack(label="law")],	#for linear model only
			label="interactionLoop"
		),
		GlobalStiffnessTimeStepper(timeStepUpdateInterval=10,label="timeStepper"),
		NewtonIntegrator(label="newton")
	]
O.engines=yade.utils.defaultEngines

