text:
using namespace Torque;

extern bool gEditingMission;
#ifdef TORQUE_AFX_ENABLED
#include "afx/ce/afxZodiacMgr.h"
#endif

IMPLEMENT_CO_NETOBJECT_V1(TSStatic);

ConsoleDocClass( TSStatic,
   "@brief A static object derived from a 3D model file and placed within the game world.\n\n"

   "TSStatic is the most basic 3D shape in Torque.  Unlike StaticShape it doesn't make use of "
   "a datablock.  It derrives directly from SceneObject.  This makes TSStatic extremely light "
   "weight, which is why the Tools use this class when you want to drop in a DTS or DAE object.\n\n"

   "While a TSStatic doesn't provide any motion -- it stays were you initally put it -- it does allow for "
   "a single ambient animation sequence to play when the object is first added to the scene.\n\n"

   "@tsexample\n"
         "new TSStatic(Team1Base) {\n"
         "   shapeName = \"art/shapes/desertStructures/station01.dts\";\n"
         "   playAmbient = \"1\";\n"
         "   receiveSunLight = \"1\";\n"
         "   receiveLMLighting = \"1\";\n"
         "   useCustomAmbientLighting = \"0\";\n"
         "   customAmbientLighting = \"0 0 0 1\";\n"
         "   collisionType = \"Visible Mesh\";\n"
         "   decalType = \"Collision Mesh\";\n"
         "   allowPlayerStep = \"1\";\n"
         "   renderNormals = \"0\";\n"
         "   forceDetail = \"-1\";\n"
         "   position = \"315.18 -180.418 244.313\";\n"
         "   rotation = \"0 0 1 195.952\";\n"
         "   scale = \"1 1 1\";\n"
         "   isRenderEnabled = \"true\";\n"
         "   canSaveDynamicFields = \"1\";\n"
         "};\n"
   "@endtsexample\n"

   "@ingroup gameObjects\n"
);

TSStatic::TSStatic()
:
   cubeDescId( 0 ),
   reflectorDesc( NULL )
{
   mNetFlags.set(Ghostable | ScopeAlways);

   mTypeMask |= StaticObjectType | StaticShapeObjectType;

   mShapeName        = "";
   mShapeInstance    = NULL;

   mPlayAmbient      = true;
   mAmbientThread    = NULL;

   mAllowPlayerStep = false;

   mConvexList = new Convex;

   mRenderNormalScalar = 0;
   mForceDetail = -1;

   mMeshCulling = false;
   mUseOriginSort = false;

   mUseAlphaFade     = false;
   mAlphaFadeStart   = 100.0f;
   mAlphaFadeEnd     = 150.0f;
   mInvertAlphaFade  = false;
   mAlphaFade = 1.0f;
   mPhysicsRep = NULL;

   mCollisionType = CollisionMesh;
   mDecalType = CollisionMesh;

   mIgnoreZodiacs = false;
   mHasGradients = false;
   mInvertGradientRange = false;
   mGradientRangeUser.set(0.0f, 180.0f);
#ifdef TORQUE_AFX_ENABLED
   afxZodiacData::convertGradientRangeFromDegrees(mGradientRange, mGradientRangeUser);
#endif
}

TSStatic::~TSStatic()
{
   delete mConvexList;
   mConvexList = NULL;
}

ImplementEnumType( TSMeshType,
   "Type of mesh data available in a shape.\n"
   "@ingroup gameObjects" )
   { TSStatic::None,          "None",           "No mesh data." },
   { TSStatic::Bounds,        "Bounds",         "Bounding box of the shape." },
   { TSStatic::CollisionMesh, "Collision Mesh", "Specifically desingated \"collision\" meshes." },
   { TSStatic::VisibleMesh,   "Visible Mesh",   "Rendered mesh polygons." },
EndImplementEnumType;

void TSStatic::initPersistFields()
{
   addGroup("Media");

      addField("shapeName",   TypeShapeFilename,  Offset( mShapeName, TSStatic ),
         "%Path and filename of the model file (.DTS, .DAE) to use for this TSStatic." );

      addProtectedField( "skin", TypeRealString, Offset( mAppliedSkinName, TSStatic ), &_setFieldSkin, &_getFieldSkin,
      "@brief The skin applied to the shape.\n\n"

      "'Skinning' the shape effectively renames the material targets, allowing "
      "different materials to be used on different instances of the same model.\n\n"

      "Any material targets that start with the old skin name have that part "
      "of the name replaced with the new skin name. The initial old skin name is "
      "\"base\". For example, if a new skin of \"blue\" was applied to a model "
      "that had material targets base_body and face, the new targets "
      "would be blue_body and face. Note that face was not "
      "renamed since it did not start with the old skin name of \"base\".\n\n"

      "To support models that do not use the default \"base\" naming convention, "
      "you can also specify the part of the name to replace in the skin field "
      "itself. For example, if a model had a material target called shapemat, "
      "we could apply a new skin \"shape=blue\", and the material target would be "
      "renamed to bluemat (note \"shape\" has been replaced with \"blue\").\n\n"

      "Multiple skin updates can also be applied at the same time by separating "
      "them with a semicolon. For example: \"base=blue;face=happy_face\".\n\n"

      "Material targets are only renamed if an existing Material maps to that "
      "name, or if there is a diffuse texture in the model folder with the same "
      "name as the new target.\n\n" );

   endGroup("Media");

   addGroup("Rendering");

      addField( "playAmbient",   TypeBool,   Offset( mPlayAmbient, TSStatic ),
         "Enables automatic playing of the animation sequence named \"ambient\" (if it exists) when the TSStatic is loaded.");
      addField( "meshCulling",   TypeBool,   Offset( mMeshCulling, TSStatic ),
         "Enables detailed culling of meshes within the TSStatic. Should only be used "
         "with large complex shapes like buildings which contain many submeshes." );
      addField( "originSort",    TypeBool,   Offset( mUseOriginSort, TSStatic ),
         "Enables translucent sorting of the TSStatic by its origin instead of the bounds." );

   endGroup("Rendering");

   addGroup( "Reflection" );
      addField( "cubeReflectorDesc", TypeRealString, Offset( cubeDescName, TSStatic ),
         "References a ReflectorDesc datablock that defines performance and quality properties for dynamic reflections.\n");
   endGroup( "Reflection" );

   addGroup("Collision");

      addField( "collisionType",    TypeTSMeshType,   Offset( mCollisionType,   TSStatic ),
         "The type of mesh data to use for collision queries." );
      addField( "decalType",        TypeTSMeshType,   Offset( mDecalType,   TSStatic ),
         "The type of mesh data used to clip decal polygons against." );
      addField( "allowPlayerStep",  TypeBool,         Offset( mAllowPlayerStep, TSStatic ),
         "@brief Allow a Player to walk up sloping polygons in the TSStatic (based on the collisionType).\n\n"
         "When set to false, the slightest bump will stop the player from walking on top of the object.\n");

   endGroup("Collision");

   addGroup( "AlphaFade" );
      addField( "alphaFadeEnable",   TypeBool,   Offset(mUseAlphaFade,    TSStatic), "Turn on/off Alpha Fade" );
      addField( "alphaFadeStart",    TypeF32,    Offset(mAlphaFadeStart,  TSStatic), "Distance of start Alpha Fade" );
      addField( "alphaFadeEnd",      TypeF32,    Offset(mAlphaFadeEnd,    TSStatic), "Distance of end Alpha Fade" );
      addField( "alphaFadeInverse", TypeBool,    Offset(mInvertAlphaFade, TSStatic), "Invert Alpha Fade's Start & End Distance" );
   endGroup( "AlphaFade" );

   addGroup("Debug");

      addField( "renderNormals", TypeF32, Offset( mRenderNormalScalar, TSStatic ),
         "Debug rendering mode shows the normals for each point in the TSStatic's mesh." );
      addField( "forceDetail",   TypeS32, Offset( mForceDetail, TSStatic ),
         "Forces rendering to a particular detail level." );

   endGroup("Debug");

   addGroup("AFX");
   addField("ignoreZodiacs",         TypeBool,       Offset(mIgnoreZodiacs,       TSStatic));
   addField("useGradientRange",      TypeBool,       Offset(mHasGradients,        TSStatic));
   addField("gradientRange",         TypePoint2F,    Offset(mGradientRangeUser,   TSStatic));
   addField("invertGradientRange",   TypeBool,       Offset(mInvertGradientRange, TSStatic));
   endGroup("AFX");
   Parent::initPersistFields();
}

bool TSStatic::_setFieldSkin( void *object, const char *index, const char *data )
{
   TSStatic *ts = static_cast<TSStatic*>( object );
   if ( ts )
      ts->setSkinName( data );
   return false;
}

const char *TSStatic::_getFieldSkin( void *object, const char *data )
{
   TSStatic *ts = static_cast<TSStatic*>( object );
   return ts ? ts->mSkinNameHandle.getString() : "";
}

void TSStatic::inspectPostApply()
{
   // Apply any transformations set in the editor
   Parent::inspectPostApply();

   if(isServerObject())
   {
      setMaskBits(AdvancedStaticOptionsMask);
      prepCollision();
   }

   _updateShouldTick();
}

bool TSStatic::onAdd()
{
   PROFILE_SCOPE(TSStatic_onAdd);

   if ( isServerObject() )
   {
      // Handle the old "usePolysoup" field
      SimFieldDictionary* fieldDict = getFieldDictionary();

      if ( fieldDict )
      {
         StringTableEntry slotName = StringTable->insert( "usePolysoup" );

         SimFieldDictionary::Entry * entry = fieldDict->findDynamicField( slotName );

         if ( entry )
         {
            // Was "usePolysoup" set?
            bool usePolysoup = dAtob( entry->value );

            // "usePolysoup" maps to the new VisibleMesh type
            if ( usePolysoup )
               mCollisionType = VisibleMesh;

            // Remove the field in favor on the new "collisionType" field
            fieldDict->setFieldValue( slotName, "" );
         }
      }
   }

   if ( !Parent::onAdd() )
      return false;

   // Setup the shape.
   if ( !_createShape() )
   {
      Con::errorf( "TSStatic::onAdd() - Shape creation failed!" );
      return false;
   }

   setRenderTransform(mObjToWorld);

   // Register for the resource change signal.
   ResourceManager::get().getChangedSignal().notify( this, &TSStatic::_onResourceChanged );

   addToScene();

   if ( isClientObject() )
   {
      mCubeReflector.unregisterReflector();

      if ( reflectorDesc )
         mCubeReflector.registerReflector( this, reflectorDesc );
   }

   _updateShouldTick();

   // Accumulation and environment mapping
   if (isClientObject() && mShapeInstance)
   {
      AccumulationVolume::addObject(this);
   }

   return true;
}

bool TSStatic::_createShape()
{
   // Cleanup before we create.
   mCollisionDetails.clear();
   mDecalDetails.clear();
   mDecalDetailsPtr = 0;
   mLOSDetails.clear();
   SAFE_DELETE( mPhysicsRep );
   SAFE_DELETE( mShapeInstance );
   mAmbientThread = NULL;
   mShape = NULL;

   if (!mShapeName || mShapeName[0] == '\0')
   {
      Con::errorf( "TSStatic::_createShape() - No shape name!" );
      return false;
   }

   mShapeHash = _StringTable::hashString(mShapeName);

   mShape = ResourceManager::get().load(mShapeName);
   if ( bool(mShape) == false )
   {
      Con::errorf( "TSStatic::_createShape() - Unable to load shape: %s", mShapeName );
      return false;
   }

   if (  isClientObject() &&
         !mShape->preloadMaterialList(mShape.getPath()) &&
         NetConnection::filesWereDownloaded() )
      return false;

   mObjBox = mShape->mBounds;
   resetWorldBox();

   mShapeInstance = new TSShapeInstance( mShape, isClientObject() );

   if (isClientObject())
      mShapeInstance->cloneMaterialList();
   if( isGhost() )
   {
      // Reapply the current skin
      mAppliedSkinName = "";
      reSkin();
   }

   prepCollision();

   // Find the "ambient" animation if it exists
   S32 ambientSeq = mShape->findSequence("ambient");

   if ( ambientSeq > -1 && !mAmbientThread )
      mAmbientThread = mShapeInstance->addThread();

   if ( mAmbientThread )
      mShapeInstance->setSequence( mAmbientThread, ambientSeq, 0);

   // Resolve CubeReflectorDesc.
   if ( cubeDescName.isNotEmpty() )
   {
      Sim::findObject( cubeDescName, reflectorDesc );
   }
   else if( cubeDescId > 0 )
   {
      Sim::findObject( cubeDescId, reflectorDesc );
   }

   return true;
}

void TSStatic::prepCollision()
{
   // Let the client know that the collision was updated
   setMaskBits( UpdateCollisionMask );

   // Allow the ShapeInstance to prep its collision if it hasn't already
   if ( mShapeInstance )
      mShapeInstance->prepCollision();

   // Cleanup any old collision data
   mCollisionDetails.clear();
   mDecalDetails.clear();
   mDecalDetailsPtr = 0;
   mLOSDetails.clear();
   mConvexList->nukeList();

   if ( mCollisionType == CollisionMesh || mCollisionType == VisibleMesh )
   {
      mShape->findColDetails( mCollisionType == VisibleMesh, &mCollisionDetails, &mLOSDetails );
      if ( mDecalType == mCollisionType )
      {
         mDecalDetailsPtr = &mCollisionDetails;
      }
      else if ( mDecalType == CollisionMesh || mDecalType == VisibleMesh )
      {
         mShape->findColDetails( mDecalType == VisibleMesh, &mDecalDetails, 0 );
         mDecalDetailsPtr = &mDecalDetails;
      }
   }
   else if ( mDecalType == CollisionMesh || mDecalType == VisibleMesh )
   {
      mShape->findColDetails( mDecalType == VisibleMesh, &mDecalDetails, 0 );
      mDecalDetailsPtr = &mDecalDetails;
   }

   _updatePhysics();
}

void TSStatic::_updatePhysics()
{
   SAFE_DELETE( mPhysicsRep );

   if ( !PHYSICSMGR || mCollisionType == None )
      return;

   PhysicsCollision *colShape = NULL;
   if ( mCollisionType == Bounds )
   {
      MatrixF offset( true );
      offset.setPosition( mShape->center );
      colShape = PHYSICSMGR->createCollision();
      colShape->addBox( getObjBox().getExtents() * 0.5f * mObjScale, offset );
   }
   else
      colShape = mShape->buildColShape( mCollisionType == VisibleMesh, getScale() );

   if ( colShape )
   {
      PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
      mPhysicsRep = PHYSICSMGR->createBody();
      mPhysicsRep->init( colShape, 0, 0, this, world );
      mPhysicsRep->setTransform( getTransform() );
   }
}

void TSStatic::onRemove()
{
   SAFE_DELETE( mPhysicsRep );

   // Accumulation
   if ( isClientObject() && mShapeInstance )
   {
      if ( mShapeInstance->hasAccumulation() )
         AccumulationVolume::removeObject(this);
   }

   mConvexList->nukeList();

   removeFromScene();

   // Remove the resource change signal.
   ResourceManager::get().getChangedSignal().remove( this, &TSStatic::_onResourceChanged );

   delete mShapeInstance;
   mShapeInstance = NULL;

   mAmbientThread = NULL;
   if ( isClientObject() )
       mCubeReflector.unregisterReflector();

   Parent::onRemove();
}

void TSStatic::_onResourceChanged( const Torque::Path &path )
{
   if ( path != Path( mShapeName ) )
      return;

   _createShape();
   _updateShouldTick();
}

void TSStatic::setSkinName( const char *name )
{
   if ( !isGhost() )
   {
      if ( name[0] != '\0' )
      {
         // Use tags for better network performance
         // Should be a tag, but we'll convert to one if it isn't.
         if ( name[0] == StringTagPrefixByte )
            mSkinNameHandle = NetStringHandle( U32(dAtoi(name + 1)) );
         else
            mSkinNameHandle = NetStringHandle( name );
      }
      else
         mSkinNameHandle = NetStringHandle();

      setMaskBits( SkinMask );
   }
}

void TSStatic::reSkin()
{
   if ( isGhost() && mShapeInstance && mSkinNameHandle.isValidString() )
   {
	  mShapeInstance->resetMaterialList();
      Vector<String> skins;
      String(mSkinNameHandle.getString()).split( ";", skins );

      for (S32 i = 0; i < skins.size(); i++)
      {
         String oldSkin( mAppliedSkinName.c_str() );
         String newSkin( skins[i] );

         // Check if the skin handle contains an explicit "old" base string. This
         // allows all models to support skinning, even if they don't follow the
         // "base_xxx" material naming convention.
         S32 split = newSkin.find( '=' );    // "old=new" format skin?
         if ( split != String::NPos )
         {
            oldSkin = newSkin.substr( 0, split );
            newSkin = newSkin.erase( 0, split+1 );
         }

         mShapeInstance->reSkin( newSkin, oldSkin );
         mAppliedSkinName = newSkin;
      }
   }
}

void TSStatic::processTick( const Move *move )
{
   if ( isServerObject() && mPlayAmbient && mAmbientThread )
      mShapeInstance->advanceTime( TickSec, mAmbientThread );

   if ( isMounted() )
   {
      MatrixF mat( true );
      mMount.object->getMountTransform(mMount.node, mMount.xfm, &mat );
      setTransform( mat );
   }
}

void TSStatic::interpolateTick( F32 delta )
{
}

void TSStatic::advanceTime( F32 dt )
{
   if ( mPlayAmbient && mAmbientThread )
      mShapeInstance->advanceTime( dt, mAmbientThread );

   if ( isMounted() )
   {
      MatrixF mat( true );
      mMount.object->getRenderMountTransform( dt, mMount.node, mMount.xfm, &mat );
      setRenderTransform( mat );
   }
}

void TSStatic::_updateShouldTick()
{
   bool shouldTick = (mPlayAmbient && mAmbientThread) || isMounted();

   if ( isTicking() != shouldTick )
      setProcessTick( shouldTick );
}

void TSStatic::prepRenderImage( SceneRenderState* state )
{
   if( !mShapeInstance )
      return;

   Point3F cameraOffset;
   getRenderTransform().getColumn(3,&cameraOffset);
   cameraOffset -= state->getDiffuseCameraPosition();
   F32 dist = cameraOffset.len();
   if (dist < 0.01f)
      dist = 0.01f;

   if (mUseAlphaFade)
   {
      mAlphaFade = 1.0f;
      if ((mAlphaFadeStart < mAlphaFadeEnd) && mAlphaFadeStart > 0.1f)
      {
         if (mInvertAlphaFade)
         {
            if (dist <= mAlphaFadeStart)
            {
               return;
            }
            if (dist < mAlphaFadeEnd)
            {
               mAlphaFade = ((dist - mAlphaFadeStart) / (mAlphaFadeEnd - mAlphaFadeStart));
            }
         }
         else
         {
            if (dist >= mAlphaFadeEnd)
            {
               return;
            }
            if (dist > mAlphaFadeStart)
            {
               mAlphaFade -= ((dist - mAlphaFadeStart) / (mAlphaFadeEnd - mAlphaFadeStart));
            }
         }
      }
   }

   F32 invScale = (1.0f/getMax(getMax(mObjScale.x,mObjScale.y),mObjScale.z));

   // If we're currently rendering our own reflection we
   // don't want to render ourselves into it.
   if ( mCubeReflector.isRendering() )
      return;

   if ( mForceDetail == -1 )
      mShapeInstance->setDetailFromDistance( state, dist * invScale );
   else
      mShapeInstance->setCurrentDetail( mForceDetail );

   if ( mShapeInstance->getCurrentDetail() < 0 )
      return;

   GFXTransformSaver saver;

   // Set up our TS render state.
   TSRenderState rdata;
   rdata.setSceneState( state );
   rdata.setFadeOverride( 1.0f );
   rdata.setOriginSort( mUseOriginSort );

   if ( mCubeReflector.isEnabled() )
      rdata.setCubemap( mCubeReflector.getCubemap() );

   // Acculumation
   rdata.setAccuTex(mAccuTex);

   // If we have submesh culling enabled then prepare
   // the object space frustum to pass to the shape.
   Frustum culler;
   if ( mMeshCulling )
   {
      culler = state->getCullingFrustum();
      MatrixF xfm( true );
      xfm.scale( Point3F::One / getScale() );
      xfm.mul( getRenderWorldTransform() );
      xfm.mul( culler.getTransform() );
      culler.setTransform( xfm );
      rdata.setCuller( &culler );
   }

   // We might have some forward lit materials
   // so pass down a query to gather lights.
   LightQuery query;
   query.init( getWorldSphere() );
   rdata.setLightQuery( &query );

   MatrixF mat = getRenderTransform();
   mat.scale( mObjScale );
   GFX->setWorldMatrix( mat );

   if ( state->isDiffusePass() && mCubeReflector.isEnabled() && mCubeReflector.getOcclusionQuery() )
   {
       RenderPassManager *pass = state->getRenderPass();
       OccluderRenderInst *ri = pass->allocInst<OccluderRenderInst>();

       ri->type = RenderPassManager::RIT_Occluder;
       ri->query = mCubeReflector.getOcclusionQuery();
       mObjToWorld.mulP( mObjBox.getCenter(), &ri->position );
       ri->scale.set( mObjBox.getExtents() );
       ri->orientation = pass->allocUniqueXform( mObjToWorld );
       ri->isSphere = false;
       state->getRenderPass()->addInst( ri );
   }

   mShapeInstance->animate();
   if(mShapeInstance)
   {
      if (mUseAlphaFade)
      {
         mShapeInstance->setAlphaAlways(mAlphaFade);
         S32 s = mShapeInstance->mMeshObjects.size();

         for(S32 x = 0; x < s; x++)
         {
            mShapeInstance->mMeshObjects[x].visible = mAlphaFade;
         }
      }
   }
   mShapeInstance->render( rdata );
#ifdef TORQUE_AFX_ENABLED
   if (!mIgnoreZodiacs && mDecalDetailsPtr != 0)
      afxZodiacMgr::renderPolysoupZodiacs(state, this);
#endif
   if ( mRenderNormalScalar > 0 )
   {
      ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
      ri->renderDelegate.bind( this, &TSStatic::_renderNormals );
      ri->type = RenderPassManager::RIT_Editor;
      state->getRenderPass()->addInst( ri );
   }
}

void TSStatic::_renderNormals( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
{
   PROFILE_SCOPE( TSStatic_RenderNormals );

   GFXTransformSaver saver;

   MatrixF mat = getRenderTransform();
   mat.scale( mObjScale );
   GFX->multWorld( mat );

   S32 dl = mShapeInstance->getCurrentDetail();
   mShapeInstance->renderDebugNormals( mRenderNormalScalar, dl );
}

void TSStatic::onScaleChanged()
{
   Parent::onScaleChanged();

   if ( mPhysicsRep )
   {
      // If the editor is enabled delay the scale operation
      // by a few milliseconds so that we're not rebuilding
      // during an active scale drag operation.
      if ( gEditingMission )
         mPhysicsRep->queueCallback( 500, Delegate<void()>( this, &TSStatic::_updatePhysics ) );
      else
         _updatePhysics();
   }

   setMaskBits( ScaleMask );
}

void TSStatic::setTransform(const MatrixF & mat)
{
   Parent::setTransform(mat);
   if ( !isMounted() )
      setMaskBits( TransformMask );

   if ( mPhysicsRep )
      mPhysicsRep->setTransform( mat );

   // Accumulation
   if ( isClientObject() && mShapeInstance )
   {
      if ( mShapeInstance->hasAccumulation() )
         AccumulationVolume::updateObject(this);
   }

   // Since this is a static it's render transform changes 1
   // to 1 with it's collision transform... no interpolation.
   setRenderTransform(mat);
}

U32 TSStatic::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
{
   U32 retMask = Parent::packUpdate(con, mask, stream);

   if ( stream->writeFlag( mask & TransformMask ) )
      mathWrite( *stream, getTransform() );

   if ( stream->writeFlag( mask & ScaleMask ) )
   {
      // Only write one bit if the scale is one.
      if ( stream->writeFlag( mObjScale != Point3F::One ) )
         mathWrite( *stream, mObjScale );
   }

   if ( stream->writeFlag( mask & UpdateCollisionMask ) )
      stream->write( (U32)mCollisionType );

   if ( stream->writeFlag( mask & SkinMask ) )
      con->packNetStringHandleU( stream, mSkinNameHandle );

   if (stream->writeFlag(mask & AdvancedStaticOptionsMask))
   {
      stream->writeString(mShapeName);
      stream->write((U32)mDecalType);

      stream->writeFlag(mAllowPlayerStep);
      stream->writeFlag(mMeshCulling);
      stream->writeFlag(mUseOriginSort);

      stream->write(mRenderNormalScalar);

      stream->write(mForceDetail);

      stream->writeFlag(mPlayAmbient);
   }

   if ( stream->writeFlag(mUseAlphaFade) )
   {
      stream->write(mAlphaFadeStart);
      stream->write(mAlphaFadeEnd);
      stream->write(mInvertAlphaFade);
   }

   stream->writeFlag(mIgnoreZodiacs);
   if (stream->writeFlag(mHasGradients))
   {
      stream->writeFlag(mInvertGradientRange);
      stream->write(mGradientRange.x);
      stream->write(mGradientRange.y);
   }
   if ( mLightPlugin )
      retMask |= mLightPlugin->packUpdate(this, AdvancedStaticOptionsMask, con, mask, stream);

   if( stream->writeFlag( reflectorDesc != NULL ) )
   {
      stream->writeRangedU32( reflectorDesc->getId(), DataBlockObjectIdFirst,  DataBlockObjectIdLast );
   }
   return retMask;
}

void TSStatic::unpackUpdate(NetConnection *con, BitStream *stream)
{
   Parent::unpackUpdate(con, stream);

   if ( stream->readFlag() ) // TransformMask
   {
      MatrixF mat;
      mathRead( *stream, &mat );
      setTransform(mat);
      setRenderTransform(mat);
   }

   if ( stream->readFlag() ) // ScaleMask
   {
      if ( stream->readFlag() )
      {
         VectorF scale;
         mathRead( *stream, &scale );
         setScale( scale );
      }
      else
         setScale( Point3F::One );
   }

   if ( stream->readFlag() ) // UpdateCollisionMask
   {
      U32 collisionType = CollisionMesh;

      stream->read( &collisionType );

      // Handle it if we have changed CollisionType's
      if ( (MeshType)collisionType != mCollisionType )
      {
         mCollisionType = (MeshType)collisionType;

         if ( isProperlyAdded() && mShapeInstance )
            prepCollision();
      }
   }

   if (stream->readFlag())    // SkinMask
   {
      NetStringHandle skinDesiredNameHandle = con->unpackNetStringHandleU(stream);;
      if (mSkinNameHandle != skinDesiredNameHandle)
      {
         mSkinNameHandle = skinDesiredNameHandle;
         reSkin();
      }
   }

   if (stream->readFlag()) // AdvancedStaticOptionsMask
   {
      mShapeName = stream->readSTString();

      stream->read((U32*)&mDecalType);

      mAllowPlayerStep = stream->readFlag();
      mMeshCulling = stream->readFlag();
      mUseOriginSort = stream->readFlag();

      stream->read(&mRenderNormalScalar);

      stream->read(&mForceDetail);
      mPlayAmbient = stream->readFlag();
   }

   mUseAlphaFade = stream->readFlag();
   if (mUseAlphaFade)
   {
      stream->read(&mAlphaFadeStart);
      stream->read(&mAlphaFadeEnd);
      stream->read(&mInvertAlphaFade);
   }

   mIgnoreZodiacs = stream->readFlag();
   mHasGradients = stream->readFlag();
   if (mHasGradients)
   {
      mInvertGradientRange = stream->readFlag();
      stream->read(&mGradientRange.x);
      stream->read(&mGradientRange.y);
   }
   if ( mLightPlugin )
   {
      mLightPlugin->unpackUpdate(this, con, stream);
   }

   if( stream->readFlag() )
   {
      cubeDescId = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
   }

   if ( isProperlyAdded() )
      _updateShouldTick();
   set_special_typing();
}

//----------------------------------------------------------------------------
bool TSStatic::castRay(const Point3F &start, const Point3F &end, RayInfo* info)
{
   if ( mCollisionType == None )
      return false;

   if ( !mShapeInstance )
      return false;

   if ( mCollisionType == Bounds )
   {
      F32 fst;
      if (!mObjBox.collideLine(start, end, &fst, &info->normal))
         return false;

      info->t = fst;
      info->object = this;
      info->point.interpolate( start, end, fst );
      info->material = NULL;
      return true;
   }
   else
   {
      RayInfo shortest = *info;
      RayInfo localInfo;
      shortest.t = 1e8f;
      localInfo.generateTexCoord = info->generateTexCoord;

      for ( U32 i = 0; i < mLOSDetails.size(); i++ )
      {
         mShapeInstance->animate( mLOSDetails[i] );

         if ( mShapeInstance->castRayOpcode( mLOSDetails[i], start, end, &localInfo ) )
         {
            localInfo.object = this;

            if (localInfo.t < shortest.t)
               shortest = localInfo;
         }
      }

      if (shortest.object == this)
      {
         // Copy out the shortest time...
         *info = shortest;
         return true;
      }
   }

   return false;
}

bool TSStatic::castRayRendered(const Point3F &start, const Point3F &end, RayInfo *info)
{
   if ( !mShapeInstance )
      return false;

   // Cast the ray against the currently visible detail
   RayInfo localInfo;
   if (info && info->generateTexCoord)
      localInfo.generateTexCoord = true;
   bool res = mShapeInstance->castRayOpcode( mShapeInstance->getCurrentDetail(), start, end, &localInfo );

   if ( res )
   {
      *info = localInfo;
      info->object = this;
      return true;
   }

   return false;
}

bool TSStatic::buildPolyList(PolyListContext context, AbstractPolyList* polyList, const Box3F &box, const SphereF &)
{
   if ( !mShapeInstance )
      return false;

   // This is safe to set even if we're not outputing
   polyList->setTransform( &mObjToWorld, mObjScale );
   polyList->setObject( this );

   if ( context == PLC_Export )
   {
      // Use highest detail level
      S32 dl = 0;

      // Try to call on the client so we can export materials
      if ( isServerObject() && getClientObject() )
         dynamic_cast<TSStatic*>(getClientObject())->mShapeInstance->buildPolyList( polyList, dl );
      else
          mShapeInstance->buildPolyList( polyList, dl );
   }
   else if ( context == PLC_Selection )
   {
      // Use the last rendered detail level
      S32 dl = mShapeInstance->getCurrentDetail();
      mShapeInstance->buildPolyListOpcode( dl, polyList, box );
   }
   else
   {
      // Figure out the mesh type we're looking for.
      MeshType meshType = ( context == PLC_Decal ) ? mDecalType : mCollisionType;

      if ( meshType == None )
         return false;
      else if ( meshType == Bounds )
         polyList->addBox( mObjBox );
      else if ( meshType == VisibleMesh )
          mShapeInstance->buildPolyList( polyList, 0 );
      else if (context == PLC_Decal && mDecalDetailsPtr != 0)
      {
         for ( U32 i = 0; i < mDecalDetailsPtr->size(); i++ )
            mShapeInstance->buildPolyListOpcode( (*mDecalDetailsPtr)[i], polyList, box );
      }
      else
      {
         // Everything else is done from the collision meshes
         // which may be built from either the visual mesh or
         // special collision geometry.
         for ( U32 i = 0; i < mCollisionDetails.size(); i++ )
            mShapeInstance->buildPolyListOpcode( mCollisionDetails[i], polyList, box );
      }
   }

   return true;
}

bool TSStatic::buildExportPolyList(ColladaUtils::ExportData* exportData, const Box3F &box, const SphereF &)
{
   if (!mShapeInstance)
      return false;

   if (mCollisionType == Bounds)
   {
      ColladaUtils::ExportData::colMesh* colMesh;
      exportData->colMeshes.increment();
      colMesh = &exportData->colMeshes.last();

      colMesh->mesh.setTransform(&mObjToWorld, mObjScale);
      colMesh->mesh.setObject(this);

      colMesh->mesh.addBox(mObjBox);

      colMesh->colMeshName = String::ToString("ColBox%d-1", exportData->colMeshes.size());
   }
   else if (mCollisionType == VisibleMesh)
   {
      ColladaUtils::ExportData::colMesh* colMesh;
      exportData->colMeshes.increment();
      colMesh = &exportData->colMeshes.last();

      colMesh->mesh.setTransform(&mObjToWorld, mObjScale);
      colMesh->mesh.setObject(this);

      mShapeInstance->buildPolyList(&colMesh->mesh, 0);

      colMesh->colMeshName = String::ToString("ColMesh%d-1", exportData->colMeshes.size());
   }
   else if (mCollisionType == CollisionMesh)
   {
      // Everything else is done from the collision meshes
      // which may be built from either the visual mesh or
      // special collision geometry.
      for (U32 i = 0; i < mCollisionDetails.size(); i++)
      {
         ColladaUtils::ExportData::colMesh* colMesh;
         exportData->colMeshes.increment();
         colMesh = &exportData->colMeshes.last();

         colMesh->mesh.setTransform(&mObjToWorld, mObjScale);
         colMesh->mesh.setObject(this);

         mShapeInstance->buildPolyListOpcode(mCollisionDetails[i], &colMesh->mesh, box);

         colMesh->colMeshName = String::ToString("ColMesh%d-1", exportData->colMeshes.size());
      }
   }

   //Next, process the LOD levels and materials.
   if (isServerObject() && getClientObject())
   {
      TSStatic* clientShape = dynamic_cast<TSStatic*>(getClientObject());
      U32 numDetails = clientShape->mShapeInstance->getNumDetails() - 1;

      exportData->meshData.increment();

      //Prep a meshData for this shape in particular
      ColladaUtils::ExportData::meshLODData* meshData = &exportData->meshData.last();

      //Fill out the info we'll need later to actually append our mesh data for the detail levels during the processing phase
      meshData->shapeInst = clientShape->mShapeInstance;
      meshData->originatingObject = this;
      meshData->meshTransform = mObjToWorld;
      meshData->scale = mObjScale;

      //Iterate over all our detail levels
      for (U32 i = 0; i < clientShape->mShapeInstance->getNumDetails(); i++)
      {
         TSShape::Detail detail = clientShape->mShapeInstance->getShape()->details[i];

         String detailName = String::ToLower(clientShape->mShapeInstance->getShape()->getName(detail.nameIndex));

         //Skip it if it's a collision or line of sight element
         if (detailName.startsWith("col") || detailName.startsWith("los"))
            continue;

         meshData->meshDetailLevels.increment();

         ColladaUtils::ExportData::detailLevel* curDetail = &meshData->meshDetailLevels.last();

         //Make sure we denote the size this detail level has
         curDetail->size = detail.size;
      }
   }

   return true;
}

void TSStatic::buildConvex(const Box3F& box, Convex* convex)
{
   if ( mCollisionType == None )
      return;

   if ( mShapeInstance == NULL )
      return;

   // These should really come out of a pool
   mConvexList->collectGarbage();

   if ( mCollisionType == Bounds )
   {
      // Just return a box convex for the entire shape...
      Convex* cc = 0;
      CollisionWorkingList& wl = convex->getWorkingList();
      for (CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext)
      {
         if (itr->mConvex->getType() == BoxConvexType &&
             itr->mConvex->getObject() == this)
         {
            cc = itr->mConvex;
            break;
         }
      }
      if (cc)
         return;

      // Create a new convex.
      BoxConvex* cp = new BoxConvex;
      mConvexList->registerObject(cp);
      convex->addToWorkingList(cp);
      cp->init(this);

      mObjBox.getCenter(&cp->mCenter);
      cp->mSize.x = mObjBox.len_x() / 2.0f;
      cp->mSize.y = mObjBox.len_y() / 2.0f;
      cp->mSize.z = mObjBox.len_z() / 2.0f;
   }
   else  // CollisionMesh || VisibleMesh
   {
      TSStaticPolysoupConvex::smCurObject = this;

      for (U32 i = 0; i < mCollisionDetails.size(); i++)
         mShapeInstance->buildConvexOpcode( mObjToWorld, mObjScale, mCollisionDetails[i], box, convex, mConvexList );

      TSStaticPolysoupConvex::smCurObject = NULL;
   }
}

SceneObject* TSStaticPolysoupConvex::smCurObject = NULL;

TSStaticPolysoupConvex::TSStaticPolysoupConvex()
:  box( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f ),
   normal( 0.0f, 0.0f, 0.0f, 0.0f ),
   idx( 0 ),
   mesh( NULL )
{
   mType = TSPolysoupConvexType;

   for ( U32 i = 0; i < 4; ++i )
   {
      verts[i].set( 0.0f, 0.0f, 0.0f );
   }
}

Point3F TSStaticPolysoupConvex::support(const VectorF& vec) const
{
   F32 bestDot = mDot( verts[0], vec );

   const Point3F *bestP = &verts[0];
   for(S32 i=1; i<4; i++)
   {
      F32 newD = mDot(verts[i], vec);
      if(newD > bestDot)
      {
         bestDot = newD;
         bestP = &verts[i];
      }
   }

   return *bestP;
}

Box3F TSStaticPolysoupConvex::getBoundingBox() const
{
   Box3F wbox = box;
   wbox.minExtents.convolve( mObject->getScale() );
   wbox.maxExtents.convolve( mObject->getScale() );
   mObject->getTransform().mul(wbox);
   return wbox;
}

Box3F TSStaticPolysoupConvex::getBoundingBox(const MatrixF& mat, const Point3F& scale) const
{
   AssertISV(false, "TSStaticPolysoupConvex::getBoundingBox(m,p) - Not implemented. -- XEA");
   return box;
}

void TSStaticPolysoupConvex::getPolyList(AbstractPolyList *list)
{
   // Transform the list into object space and set the pointer to the object
   MatrixF i( mObject->getTransform() );
   Point3F iS( mObject->getScale() );
   list->setTransform(&i, iS);
   list->setObject(mObject);

   // Add only the original collision triangle
   S32 base =  list->addPoint(verts[0]);
               list->addPoint(verts[2]);
               list->addPoint(verts[1]);

   list->begin(0, (U32)idx ^ (uintptr_t)mesh);
   list->vertex(base + 2);
   list->vertex(base + 1);
   list->vertex(base + 0);
   list->plane(base + 0, base + 1, base + 2);
   list->end();
}

void TSStaticPolysoupConvex::getFeatures(const MatrixF& mat,const VectorF& n, ConvexFeature* cf)
{
   cf->material = 0;
   cf->object = mObject;

   // For a tetrahedron this is pretty easy... first
   // convert everything into world space.
   Point3F tverts[4];
   mat.mulP(verts[0], &tverts[0]);
   mat.mulP(verts[1], &tverts[1]);
   mat.mulP(verts[2], &tverts[2]);
   mat.mulP(verts[3], &tverts[3]);

   // points...
   S32 firstVert = cf->mVertexList.size();
   cf->mVertexList.increment(); cf->mVertexList.last() = tverts[0];
   cf->mVertexList.increment(); cf->mVertexList.last() = tverts[1];
   cf->mVertexList.increment(); cf->mVertexList.last() = tverts[2];
   cf->mVertexList.increment(); cf->mVertexList.last() = tverts[3];

   //    edges...
   cf->mEdgeList.increment();
   cf->mEdgeList.last().vertex[0] = firstVert+0;
   cf->mEdgeList.last().vertex[1] = firstVert+1;

   cf->mEdgeList.increment();
   cf->mEdgeList.last().vertex[0] = firstVert+1;
   cf->mEdgeList.last().vertex[1] = firstVert+2;

   cf->mEdgeList.increment();
   cf->mEdgeList.last().vertex[0] = firstVert+2;
   cf->mEdgeList.last().vertex[1] = firstVert+0;

   cf->mEdgeList.increment();
   cf->mEdgeList.last().vertex[0] = firstVert+3;
   cf->mEdgeList.last().vertex[1] = firstVert+0;

   cf->mEdgeList.increment();
   cf->mEdgeList.last().vertex[0] = firstVert+3;
   cf->mEdgeList.last().vertex[1] = firstVert+1;

   cf->mEdgeList.increment();
   cf->mEdgeList.last().vertex[0] = firstVert+3;
   cf->mEdgeList.last().vertex[1] = firstVert+2;

   //    triangles...
   cf->mFaceList.increment();
   cf->mFaceList.last().normal = PlaneF(tverts[2], tverts[1], tverts[0]);
   cf->mFaceList.last().vertex[0] = firstVert+2;
   cf->mFaceList.last().vertex[1] = firstVert+1;
   cf->mFaceList.last().vertex[2] = firstVert+0;

   cf->mFaceList.increment();
   cf->mFaceList.last().normal = PlaneF(tverts[1], tverts[0], tverts[3]);
   cf->mFaceList.last().vertex[0] = firstVert+1;
   cf->mFaceList.last().vertex[1] = firstVert+0;
   cf->mFaceList.last().vertex[2] = firstVert+3;

   cf->mFaceList.increment();
   cf->mFaceList.last().normal = PlaneF(tverts[2], tverts[1], tverts[3]);
   cf->mFaceList.last().vertex[0] = firstVert+2;
   cf->mFaceList.last().vertex[1] = firstVert+1;
   cf->mFaceList.last().vertex[2] = firstVert+3;

   cf->mFaceList.increment();
   cf->mFaceList.last().normal = PlaneF(tverts[0], tverts[2], tverts[3]);
   cf->mFaceList.last().vertex[0] = firstVert+0;
   cf->mFaceList.last().vertex[1] = firstVert+2;
   cf->mFaceList.last().vertex[2] = firstVert+3;

   // All done!
}

void TSStatic::onMount( SceneObject *obj, S32 node )
{
   Parent::onMount(obj, node);
   _updateShouldTick();
}

void TSStatic::onUnmount( SceneObject *obj, S32 node )
{
   Parent::onUnmount( obj, node );
   setMaskBits( TransformMask );
   _updateShouldTick();
}

U32 TSStatic::getNumDetails()
{
	if (isServerObject() && getClientObject())
	{
		TSStatic* clientShape = dynamic_cast<TSStatic*>(getClientObject());
		return clientShape->mShapeInstance->getNumDetails();
	}
	return 0;
};

//------------------------------------------------------------------------
//These functions are duplicated in tsStatic and shapeBase.
//They each function a little differently; but achieve the same purpose of gathering
//target names/counts without polluting simObject.

DefineEngineMethod( TSStatic, getTargetName, const char*, ( S32 index ),(0),
   "Get the name of the indexed shape material.\n"
   "@param index index of the material to get (valid range is 0 - getTargetCount()-1).\n"
   "@return the name of the indexed material.\n"
   "@see getTargetCount()\n")
{
   TSStatic *obj = dynamic_cast< TSStatic* > ( object );
   if(obj)
   {
      // Try to use the client object (so we get the reskinned targets in the Material Editor)
      if ((TSStatic*)obj->getClientObject())
         obj = (TSStatic*)obj->getClientObject();

      return obj->getShapeInstance()->getTargetName(index);
   }

   return "";
}

DefineEngineMethod( TSStatic, getTargetCount, S32,(),,
   "Get the number of materials in the shape.\n"
   "@return the number of materials in the shape.\n"
   "@see getTargetName()\n")
{
   TSStatic *obj = dynamic_cast< TSStatic* > ( object );
   if(obj)
   {
      // Try to use the client object (so we get the reskinned targets in the Material Editor)
      if ((TSStatic*)obj->getClientObject())
         obj = (TSStatic*)obj->getClientObject();

      return obj->getShapeInstance()->getTargetCount();
   }

   return -1;
}

// This method is able to change materials per map to with others. The material that is being replaced is being mapped to
// unmapped_mat as a part of this transition

DefineEngineMethod( TSStatic, changeMaterial, void, ( const char* mapTo, Material* oldMat, Material* newMat ),("",nullAsType<Material*>(),nullAsType<Material*>()),
   "@brief Change one of the materials on the shape.\n\n"

   "This method changes materials per mapTo with others. The material that "
   "is being replaced is mapped to unmapped_mat as a part of this transition.\n"

   "@note Warning, right now this only sort of works. It doesn't do a live "
   "update like it should.\n"

   "@param mapTo the name of the material target to remap (from getTargetName)\n"
   "@param oldMat the old Material that was mapped \n"
   "@param newMat the new Material to map\n\n"

   "@tsexample\n"
      "// remap the first material in the shape\n"
      "%mapTo = %obj.getTargetName( 0 );\n"
      "%obj.changeMaterial( %mapTo, 0, MyMaterial );\n"
   "@endtsexample\n" )
{
   // if no valid new material, theres no reason for doing this
   if( !newMat )
   {
      Con::errorf("TSShape::changeMaterial failed: New material does not exist!");
      return;
   }

   TSMaterialList* shapeMaterialList = object->getShape()->materialList;

   // Check the mapTo name exists for this shape
   S32 matIndex = shapeMaterialList->getMaterialNameList().find_next(String(mapTo));
   if (matIndex < 0)
   {
      Con::errorf("TSShape::changeMaterial failed: Invalid mapTo name '%s'", mapTo);
      return;
   }

   // Lets remap the old material off, so as to let room for our current material room to claim its spot
   if( oldMat )
      oldMat->mMapTo = String("unmapped_mat");

   newMat->mMapTo = mapTo;

   // Map the material by name in the matmgr
   MATMGR->mapMaterial( mapTo, newMat->getName() );

   // Replace instances with the new material being traded in. Lets make sure that we only
   // target the specific targets per inst, this is actually doing more than we thought
   delete shapeMaterialList->mMatInstList[matIndex];
   shapeMaterialList->mMatInstList[matIndex] = newMat->createMatInstance();

   // Finish up preparing the material instances for rendering
   const GFXVertexFormat *flags = getGFXVertexFormat<GFXVertexPNTTB>();
   FeatureSet features = MATMGR->getDefaultFeatures();
   shapeMaterialList->getMaterialInst(matIndex)->init(features, flags);
}

DefineEngineMethod( TSStatic, getModelFile, const char *, (),,
   "@brief Get the model filename used by this shape.\n\n"

   "@return the shape filename\n\n"
   "@tsexample\n"
      "// Acquire the model filename used on this shape.\n"
      "%modelFilename = %obj.getModelFile();\n"
   "@endtsexample\n"
   )
{
   return object->getShapeFileName();
}

void TSStatic::set_special_typing()
{
   if (mCollisionType == VisibleMesh || mCollisionType == CollisionMesh)
      mTypeMask |= InteriorLikeObjectType;
   else
      mTypeMask &= ~InteriorLikeObjectType;
}

void TSStatic::onStaticModified(const char* slotName, const char*newValue)
{
#ifdef TORQUE_AFX_ENABLED
   if (slotName == afxZodiacData::GradientRangeSlot)
   {
      afxZodiacData::convertGradientRangeFromDegrees(mGradientRange, mGradientRangeUser);
      return;
   }
#endif

   set_special_typing();
}

void TSStatic::setSelectionFlags(U8 flags)
{
   Parent::setSelectionFlags(flags);

   if (!mShapeInstance || !isClientObject())
      return;

   if (!mShapeInstance->ownMaterialList())
      return;

   TSMaterialList* pMatList = mShapeInstance->getMaterialList();
   for (S32 j = 0; j < pMatList->size(); j++)
   {
      BaseMatInstance * bmi = pMatList->getMaterialInst(j);
      bmi->setSelectionHighlighting(needsSelectionHighlighting());
   }
}


text:
<!DOCTYPE html>

       <meta http-equiv="content-type" content="text/html; charset=utf-8"></meta>
       <title>My Application</title>
       <link rel="stylesheet" href="css/style.css">

           trying to Connect 3rd ...

<button id='led_state'>Turn on</button>

LED Off

LED On

redpajama_set_name: RedPajamaGithub


text:
lm_shiny-app
============

shiny app for uploading CSV and applying linear regression on different variables


text:
<!doctype html>

        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link href='http://fonts.useso.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>
        <link href='http://fonts.useso.com/css?family=Niconne' rel='stylesheet' type='text/css'>
        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="css/_main.css">

                        <button type="button" data-toggle="collapse" data-target=".navbar-collapse" class="navbar-toggle">

                        </button>

ABOUT

GALLERY

NEWS

TYPO

CONTACT

Gardening

Main Heading

Content specific to this page goes here

Copyright © Company Name


text:
require 'optparse'

module Launchy
  class Cli

    attr_reader :options
    def initialize
      @options = {}
    end

    def parser
      @parser ||= OptionParser.new do |op|
        op.banner = "Usage: launchy [options] thing-to-launch"

        op.separator ""
        op.separator "Launch Options:"

        op.on( "-a", "--application APPLICATION",
               "Explicitly specify the application class to use in the launch") do |app|
          @options[:application] = app
        end

        op.on( "-d", "--debug",
               "Force debug. Output lots of information.") do |d|
          @options[:debug] = 'true'
        end

        op.on( "-e", "--engine RUBY_ENGINE",
               "Force launchy to behave as if it was on a particular ruby engine.") do |e|
          @options[:ruby_engine] = e
        end

        op.on( "-n", "--dry-run", "Don't launchy, print the command to be executed on stdout" ) do |x|
          @options[:dry_run] = true
        end

        op.on( "-o", "--host-os HOST_OS",
               "Force launchy to behave as if it was on a particular host os.") do |os|
          @options[:host_os] = os
        end

        op.separator ""
        op.separator "Standard Options:"

        op.on( "-h", "--help", "Print this message.") do |h|
          $stdout.puts op.to_s
          exit 0
        end

        op.on( "-v", "--version", "Output the version of Launchy") do |v|
          $stdout.puts "Launchy version #{Launchy::VERSION}"
          exit 0
        end

      end
    end

    def parse( argv, env )
      parser.parse!( argv )
      return true
    rescue ::OptionParser::ParseError => pe
      error_output( pe )
    end

    def good_run( argv, env )
      if parse( argv, env ) then
        Launchy.open( argv.shift, options ) { |e| error_output( e ) }
        return true
      else
        return false
      end
    end

    def error_output( error )
      $stderr.puts "ERROR: #{error}"
      Launchy.log "ERROR: #{error}"
      error.backtrace.each do |bt|
        Launchy.log bt
      end
      $stderr.puts "Try `#{parser.program_name} --help' for more information."
      return false
    end

    def run( argv = ARGV, env = ENV )
      exit 1 unless good_run( argv, env )
    end
  end
end


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>File: README</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href=".././rdoc-style.css" type="text/css" media="screen" />

README

      Path:
      README

      Last Update:
      Mon Jun 18 11:46:50 CEST 2007

CAPTCHA validation

This plugin adds the ability to require CAPTCHA validation in your
model. It depends on RMagick to
generate images.

Right now there are two different challenges in this plugin. There’s
the familiar, but inaccessible image with embedded text, and then
there’s another type of challenge which involves asking the user a
(simple) question to prove he is not a robot. The latter type is also
passable by people with vision impairments, and as a bonus it is also more
lightweight.

Usage

How to use in your Rails application.

Install

Put this plugin in your application’s <tt>vendor/plugins</tt>
directory. This can be done easily using the <tt>script/plugin</tt> script
in your application:

  script/plugin install http://nimrod.interinter.net/plugins/trunk/validates_captcha

If your app is in Subversion you may want to include an -x to associate the
plugin with its original repository so you can <tt>svn up</tt> it later.
Also, <strong>note the changed address for the
repository</strong> if you have previously used this plugin.

Prepare

This plugin assumes it has write access to a directory where a PStore file
with the generated CAPTCHA challenges is stored. This is by default
<tt>var/data</tt>. You can create this directory by running
<tt>script/generate captcha store_directory</tt> in your
application’s root folder. You should check that your web
server’s user has write access to this directory.

If you plan to use the image challenges, these will also need to be stored
in a server-writable directory. This is by default
<tt>public/images/captcha</tt>. You can create this directory by running
<tt>script/generate captcha image_directory</tt> in your
application’s root directory.

Both of these locations can be changed. See FleskPlugins::CaptchaConfig
for details.

Update Model

This step is not necessary if you want to validate the challenge in your
controller. Instructions on how to do that are further down on the page.

  class MySuperModel < ActiveRecord::Base
    validates_captcha
  end

Update View

In your view, put this inside the form for the model that requires CAPTCHA
validation:

  <% c = prepare_captcha :type => :image -%>
  <%= captcha_hidden_field c, 'my_super_model' %>
  <%= captcha_image_tag c %>
  <%= captcha_label 'my_super_model', 'Type in the text from the image above' %>
  <%= captcha_text_field 'my_super_model' %>

To use the question challenge instead, do this:

  <% c = prepare_captcha :type => :question -%>
  <%= captcha_hidden_field c, 'my_super_model' %>
  <%= captcha_question_as_label c, 'my_super_model' %>
  <%= captcha_text_field 'my_super_model' %>

See FleskPlugins::Captcha::Helpers
for how to customise your view.

Update Controller

If you want to validate the challenge in your controller, you can use the
+captcha_valid?+ method:

  def save
        supermodel = MySuperModel.find(params[:id])
        supermodel.attributes = params[:my_super_model]

        if captcha_valid?(params[:my_super_model][:captcha_id], params[:my_super_model][:captcha_validation])
                supermodel.save
        else
          flash[:error] = "Are you sure you're human?"
          redirect_or_something
        end
  end

If you want to let the model handle the validation, you need to assign the
values from your form to your model. If you’re using some form of
mass-assignment, this will happen automatically:

  def save
    @supermodel = MySuperModel.find(params[:id])
    @supermodel.attributes = params[:my_super_model]
    @supermodel.save
  end

The virtual attributes, <tt>captcha_id</tt> and
<tt>captcha_validation</tt>, are accessible to mass-assignment. If
you’re assigning each attribute seperately, you will also have to
assign these virtual attributes:

  def save
    @supermodel = MySuperModel.find(params[:id])
    @supermodel.name = params[:my_super_model][:name]
    @supermodel.description params[:my_super_model][:description]
    @supermodel.captcha_id = params[:my_super_model][:captcha_id]
    @supermodel.captcha_validation = params[:my_super_model][:captcha_validation]
  end

Restart server

For Rails to use the newly installed plugin, you have to restart the
server, even in development mode. You only have to do this once.

Contact

You can contact me at toredarell att gmail doot com

Contributors

Serge Sozonoff

Blake Watters

Manik Juneja

Joscha Diehl

Mark Lussier

Bradford Folkens

Licence

See MIT-LICENCE (same as Rails; use however you want; if your computer
explodes it’s not my fault)

[Validate]


text:
#ifndef THREADXX_H
#define	THREADXX_H

#include <thread>
#include <condition_variable>
#include <atomic>
#include "../logxx/logxx.h"

namespace threadxx {

	class Thread {
	public:
	        Thread(int id);
	        virtual ~Thread();

	        virtual bool Start();
	        virtual void Join();
	        virtual void Interrupt();

	        const int id;
	protected:
	        virtual void Run();
	        std::atomic_bool interrupted;
	        std::unique_ptr<std::thread> thread;
	        logxx::Log cLog;

	private:
	        void JoinWOCheck();
	        void MakeThread();
	        void WaitForStart();

	        std::mutex threadExecuteMutex;
	        std::condition_variable threadCV;
	        bool threadReadyToStart = false;
	        bool threadStarted = false;

	};
} // namespace threadxx
#endif	/* THREAD_H */


text:
package net.ivang.axonix.main.actors.game.level.enemies;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.google.common.eventbus.EventBus;

/**
 * @author Ivan Gadzhega
 * @since 0.4
 */
public class RedEnemy extends Enemy {

    public RedEnemy(float x, float y, Skin skin, EventBus eventBus) {
        super(x, y, 0.5f, Direction.getRandomDiagonal(), eventBus);
        this.bouncingOffBlocks = true;
        // appearance
        setColor(1, 0.2f, 0.1f, 1);
        this.region = skin.getRegion("circular_flare");
        particleEffect.load(Gdx.files.internal("data/particles/enemies/enemy_red.p"), skin.getAtlas());
    }

}


text:
#import "WXComponent.h"
#import "WXNavigationProtocol.h"

@interface WXComponent (Navigation)

- (void)setNavigationBarHidden:(BOOL)hidden;

- (void)setNavigationBackgroundColor:(UIColor *)backgroundColor;

- (void)setNavigationItemWithParam:(NSDictionary *)param position:(WXNavigationItemPosition)position;

- (void)setNavigationWithStyles:(NSDictionary *)styles;

@end


text:
DEFINE_STATICREGISTER(TestRenderPipe, RenderPipe)

void TestRenderPipe::ConstructRenderPasses()
{
	r_PassLists.push_back(std::make_shared<SuperSimplePass>());

	ConstructPassesRenderBuffer();
	ConstructPassesBlendState();
}

std::string TestRenderPipe::GetPipeName()
{
	return TXT("TestRenderPipe");
}

TestRenderPipe::TestRenderPipe()
{
}

RenderBufferDesc TestRenderPipe::GetPipeRenderBufferDesc()
{
	RenderBufferDesc RetVal;
	RetVal.c_Desc = TestRenderPipeRenderBuffer();
	return RetVal;
}

void TestRenderPipe::ConstructPipe()
{
	ConstructPipeRenderBuffer<TestRenderPipeRenderBuffer>();
	ConstructRenderPasses();
}

void TestRenderPipe::Render(std::weak_ptr<IRPICommandLine> inCommandline, std::shared_ptr<RendererContext> inRenderContext, std::shared_ptr<SceneInfo> inScene)
{
	auto sceneProxy = inScene->PullData();
	std::vector<SceneAtom> SceneAtoms;
	for (std::shared_ptr<RenderProxy> proxy : sceneProxy)
	{
		SceneAtoms.push_back(proxy->ConstructSceneAtom());
	}

	// update our pipe render buffer
	UpdatePipeRenderBuffer(inCommandline);

	// draw each pass
	std::vector<RenderResourceBase*> renderTargetList;
	std::vector<RenderResourceBase*> renderResourceList;
	PassDrawInfo DrawInfo;
	DrawInfo.c_DrawPipeName = GetPipeName();
	DrawInfo.c_StaticPipe = TestRenderPipe::GetStatic();
	for (std::shared_ptr<RenderPass> pass : r_PassLists)
	{
		FindPassRRT(inRenderContext, pass, renderTargetList, renderResourceList);

		// set our viewport and draw
		inCommandline.lock()->SetViewport(inRenderContext->c_Viewport);

		// set the pass blend state
		inCommandline.lock()->SetBlendState(pass->GetPassBlendState()->r_BlendState.r_ResourceRef.get());

		pass->Draw(DrawInfo, inRenderContext, inCommandline.lock().get(), renderResourceList, renderTargetList, SceneAtoms);
	}
}


text:
<?php

$container->setParameter('php.loaded', true);


text:
package us.nineworlds.serenity.ui.browser.music.tracks;

import java.io.IOException;

import us.nineworlds.serenity.R;
import us.nineworlds.serenity.core.model.impl.AudioTrackContentInfo;
import android.app.Activity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

/**
 * @author dcarver
 *
 */
public class AudioTrackItemClickListener implements OnItemClickListener {

	MediaPlayer mediaPlayer;

	AudioTrackItemClickListener(MediaPlayer mp) {
		mediaPlayer = mp;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget
	 * .AdapterView, android.view.View, int, long)
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		AudioTrackContentInfo mt = (AudioTrackContentInfo) parent
				.getItemAtPosition(position);
		Activity context = (Activity) parent.getContext();
		ListView lv = (ListView) context.findViewById(R.id.audioTracksListview);
		TextView ptv = (TextView) context.findViewById(R.id.track_playing);
		ptv.setText(mt.getTitle());
		lv.setSelection(position);
		MusicTracksActivity.currentPlayingItem = position;

		if (mediaPlayer == null) {
			mediaPlayer = MediaPlayer.create(view.getContext(), Uri.parse(mt.getDirectPlayUrl()));
		} else {
			try {
				mediaPlayer.reset();
				mediaPlayer.setDataSource(view.getContext(), Uri.parse(mt.getDirectPlayUrl()));
				mediaPlayer.prepare();
			} catch (IllegalArgumentException e) {
				Log.e(getClass().getName(), "Unable to play Track", e);
			} catch (SecurityException e) {
				Log.e(getClass().getName(), "Unable to play Track", e);
			} catch (IllegalStateException e) {
				Log.e(getClass().getName(), "Unable to play Track", e);
			} catch (IOException e) {
				Log.e(getClass().getName(), "Unable to play Track", e);
			}
		}

		try {
			showControlls(context);
			mediaPlayer.start();
		} catch (IllegalArgumentException e) {
			Log.e("TrackPlayButton", "Unable to play Track", e);
		} catch (IllegalStateException e) {
			Log.e("TrackPlayButton", "Unable to play Track", e);
		}

	}

	/**
	 * @param context
	 */
	protected void showControlls(Activity context) {
		ImageButton playBtn = (ImageButton) context.findViewById(R.id.audioPause);
		playBtn.setVisibility(View.VISIBLE);

		SeekBar seekBar = (SeekBar) context.findViewById(R.id.mediacontroller_seekbar);
		seekBar.setVisibility(View.VISIBLE);

		ImageButton nextBtn = (ImageButton) context.findViewById(R.id.audioSkipForward);
		nextBtn.setVisibility(View.VISIBLE);

		ImageButton prevBtn = (ImageButton) context.findViewById(R.id.audioSkipBack);
		prevBtn.setVisibility(View.VISIBLE);

		ImageButton nextTrack = (ImageButton) context.findViewById(R.id.audioNextTrack);
		nextTrack.setVisibility(View.VISIBLE);

		ImageButton prevTrack = (ImageButton) context.findViewById(R.id.audioPrevTrack);
		prevTrack.setVisibility(View.VISIBLE);

		TextView currentTime = (TextView) context.findViewById(R.id.mediacontroller_time_current);
		currentTime.setVisibility(View.VISIBLE);

		TextView durationTime = (TextView) context.findViewById(R.id.mediacontroller_time_total);
		durationTime.setVisibility(View.VISIBLE);

		TextView playingTrack = (TextView) context.findViewById(R.id.track_playing);
		playingTrack.setVisibility(View.VISIBLE);

		CheckBox randomPlay = (CheckBox) context.findViewById(R.id.audioRandomPlay);
		if (randomPlay != null) {
			randomPlay.setVisibility(View.VISIBLE);
		}

		LinearLayout mediaProgressControl = (LinearLayout) context.findViewById(R.id.mediacontroller_progress_layout);
		mediaProgressControl.setVisibility(View.VISIBLE);

	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <list default="true" id="247c9d19-9fdf-4a7e-b1bb-17616ad363f3" name="Default Changelist" comment="">
      <change afterPath="$PROJECT_DIR$/.idea/uiDesigner.xml" afterDir="false" />
      <change afterPath="$PROJECT_DIR$/LICENSE.txt" afterDir="false" />
      <change afterPath="$PROJECT_DIR$/README.md" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/out/production/tomcat-runner/META-INF/plugin.xml" beforeDir="false" afterPath="$PROJECT_DIR$/out/production/tomcat-runner/META-INF/plugin.xml" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/out/production/tomcat-runner/br/com/camtwo/intellij/tomcatrunner/conf/TomcatRunnerConfigurationFactory.class" beforeDir="false" afterPath="$PROJECT_DIR$/out/production/tomcat-runner/br/com/camtwo/intellij/tomcatrunner/conf/TomcatRunnerConfigurationFactory.class" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/out/production/tomcat-runner/br/com/camtwo/intellij/tomcatrunner/model/TomcatRunnerCommandLine.class" beforeDir="false" afterPath="$PROJECT_DIR$/out/production/tomcat-runner/br/com/camtwo/intellij/tomcatrunner/model/TomcatRunnerCommandLine.class" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/out/production/tomcat-runner/br/com/camtwo/intellij/tomcatrunner/ui/TomcatRunnerConfPanel$3.class" beforeDir="false" afterPath="$PROJECT_DIR$/out/production/tomcat-runner/br/com/camtwo/intellij/tomcatrunner/ui/TomcatRunnerConfPanel$3.class" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/out/production/tomcat-runner/br/com/camtwo/intellij/tomcatrunner/ui/TomcatRunnerConfPanel.class" beforeDir="false" afterPath="$PROJECT_DIR$/out/production/tomcat-runner/br/com/camtwo/intellij/tomcatrunner/ui/TomcatRunnerConfPanel.class" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/out/production/tomcat-runner/br/com/camtwo/intellij/tomcatrunner/ui/TomcatRunnerEditor$1.class" beforeDir="false" afterPath="$PROJECT_DIR$/out/production/tomcat-runner/br/com/camtwo/intellij/tomcatrunner/ui/TomcatRunnerEditor$1.class" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/out/production/tomcat-runner/br/com/camtwo/intellij/tomcatrunner/ui/TomcatRunnerEditor.class" beforeDir="false" afterPath="$PROJECT_DIR$/out/production/tomcat-runner/br/com/camtwo/intellij/tomcatrunner/ui/TomcatRunnerEditor.class" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/resources/META-INF/plugin.xml" beforeDir="false" afterPath="$PROJECT_DIR$/resources/META-INF/plugin.xml" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/src/br/com/camtwo/intellij/tomcatrunner/ui/TomcatRunnerConfPanel.form" beforeDir="false" afterPath="$PROJECT_DIR$/src/br/com/camtwo/intellij/tomcatrunner/ui/TomcatRunnerConfPanel.form" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/src/br/com/camtwo/intellij/tomcatrunner/ui/TomcatRunnerConfPanel.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/br/com/camtwo/intellij/tomcatrunner/ui/TomcatRunnerConfPanel.java" afterDir="false" />
    </list>
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="Git.Settings">
    <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
  </component>
  <component name="GitSEFilterConfiguration">
    <file-type-list>
      <filtered-out-file-type name="LOCAL_BRANCH" />
      <filtered-out-file-type name="REMOTE_BRANCH" />
      <filtered-out-file-type name="TAG" />
      <filtered-out-file-type name="COMMIT_BY_MESSAGE" />
    </file-type-list>
  </component>
  <component name="LogFilters">
    <option name="FILTER_ERRORS" value="false" />
    <option name="FILTER_WARNINGS" value="false" />
    <option name="FILTER_INFO" value="true" />
    <option name="FILTER_DEBUG" value="true" />
    <option name="CUSTOM_FILTER" />
  </component>
  <component name="ProjectId" id="1sfqXvYg5E2sDAyfaASDvXeiWti" />
  <component name="ProjectLevelVcsManager">
    <ConfirmationsSetting value="2" id="Add" />
  </component>
  <component name="ProjectViewState">
    <option name="hideEmptyMiddlePackages" value="true" />
    <option name="showLibraryContents" value="true" />
  </component>
  <component name="PropertiesComponent">
    <property name="ASKED_ADD_EXTERNAL_FILES" value="true" />
    <property name="RunOnceActivity.OpenProjectViewOnStart" value="true" />
    <property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
    <property name="SHARE_PROJECT_CONFIGURATION_FILES" value="true" />
  </component>
  <component name="RecentsManager">
    <key name="MoveFile.RECENT_KEYS">
      <recent name="$PROJECT_DIR$/src" />
      <recent name="$PROJECT_DIR$/resources" />
    </key>
  </component>
  <component name="RunManager">
    <configuration name="Plugin" type="#org.jetbrains.idea.devkit.run.PluginConfigurationType">
      <module name="tomcat-runner" />
      <option name="VM_PARAMETERS" value="-Xmx512m -Xms256m -ea" />
      <option name="PROGRAM_PARAMETERS" />
      <predefined_log_file enabled="true" id="idea.log" />
      <method v="2">
        <option name="Make" enabled="true" />
      </method>
    </configuration>
    <configuration default="true" type="#org.jetbrains.idea.devkit.run.PluginConfigurationType">
      <module name="tomcat-runner" />
      <option name="VM_PARAMETERS" value="-Xmx512m -Xms256m -ea" />
      <option name="PROGRAM_PARAMETERS" />
      <predefined_log_file enabled="true" id="idea.log" />
      <method v="2">
        <option name="Make" enabled="true" />
      </method>
    </configuration>
  </component>
  <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="247c9d19-9fdf-4a7e-b1bb-17616ad363f3" name="Default Changelist" comment="" />
      <created>1621274036409</created>
      <option name="number" value="Default" />
      <option name="presentableId" value="Default" />
      <updated>1621274036409</updated>
    </task>
    <servers />
  </component>
  <component name="VcsManagerConfiguration">
    <option name="ADD_EXTERNAL_FILES_SILENTLY" value="true" />
  </component>
</project>


text:
function attributes(paper, graph){

//	var ed;
//
//	paper.on('cell:pointerdblclick', function(cellView, evt) {
//
//
//		//var test = $.noConflict();
//
//		var text = joint.ui.TextEditor.getTextElement(evt.target);
//		//console.log(text);
//
//	    if (text) {
//	        if (ed){
//	        	ed.remove();   // Remove old editor if there was one.
//	        }
//	        ed = new joint.ui.TextEditor({ text: text });
//	        ed.render(paper.el);
//
//	        ed.on('text:change', function(newText) {
//	            // Set the new text to the property that you use to change text in your views.
//	            cellView.model.set('name', newText);
//	        });
//	    }
//
//
//	});
//
//	paper.on('blank:pointerclick', function(cellView, evt) {
//
//		//console.log($.noConflict(false));
//
//		if (ed){
//        	ed.remove();   // Remove old editor if there was one.
//        }
//	});
//
//	paper.on('cell:pointerclick', function(cellView, evt) {
//		if (ed){
//        	ed.remove();   // Remove old editor if there was one.
//        }
//	});
//
//	function autosize(element) {
//
//	    var view = paper.findViewByModel(element);
//	    if(view == undefined) return;
//
//	    console.log(view);
//	    var text = view.$('text')[0];
//
//	    // Use bounding box without transformations so that our autosizing works
//	    // even on e.g. rotated element.
//	    var bbox = V(text).bbox(true);
//	    // Give the element some padding on the right/bottom.
//	    element.resize(bbox.width + 50, bbox.height + 50);
//	}
//
//	graph.on('change:attrs', function(cell) {
//		autosize(cell)
//	});
//

//	paper.on('cell:pointerdblclick', function(cellView, evt, opt) {
//
//		if(cellView.model.get('type') === 'archimate.Relationships') return;
//		if(cellView.model.get('type') === 'archimate.Junction') return;
//
//		showAttributeDialog(cellView.model);
//	});
//
//	graph.on('add', function(cell) {
//
//		$('.inspector-paper-container').hide();
//		$('.inspector-container').show();
//
//		if(cell.get('type') === 'archimate.Relationships') return;
//		if(cell.get('type') === 'archimate.Junction') return;
//
//		showAttributeDialog(cell);
//	});

	function showAttributeDialog(cell){

		//console.log(JSON.stringify(cell));

		var name = cell.get('name');
		var documentation = cell.get('documentation');

		var content = '
'
		content = content + 'Name: <textarea rows="1" class="name" onclick="this.focus();this.select()">' + name + "</textarea>"
		content = content + '<button id="definition" alt="Get definition from Wikipedia">Wikipedia</button>
'
		content = content + 'Documentation: <textarea rows="4" class="documentation">' + documentation + "</textarea>"
		content = content + "
"

		var dialog = new joint.ui.Dialog({
			width: 300,
			type: 'neutral',
			title: 'General',
			content: content,
			buttons: [
				{ action: 'cancel', content: 'Cancel', position: 'left' },
				{ action: 'ok', content: 'OK', position: 'left' }
			]
		});
		dialog.on('action:ok', setName);
		dialog.on('action:cancel', dialog.close);
		dialog.open();

		$('.name').focus();
		$('.name').select();

		$(".attributes").keypress(function(e) {
		    if(e.which == 13) {
		    	setName();
		    }
		});

		$(".attributes").keyup(function(e) {
		    if(e.which == 27){
		    	dialog.close();
		    }
		});

		$('#definition').click(function(){
			getWikipediaDefinition();
		});

		function getWikipediaDefinition(){

			//alert(JSON.stringify(cell));

			$.ajax({
			   type: "POST",
			   async: false,
			   url: "getDefinition.htm",
			   data: {
				   'cellName' : $('.name').val(),
			   },
			   success: function(data){
				   $('.documentation').val(data)
			   },
			   error : function(e) {
				   //alert("error: " + e.status);
			   }
			});

		}

		function setName(){
			cell.set('name', $('.name').val());
			cell.set('documentation', $('.documentation').val());
			dialog.close();
		}
	}

}


text:
"""
This module provides convenient functions to transform sympy expressions to
lambda functions which can be used to calculate numerical values very fast.
"""

from __future__ import print_function, division

from sympy.external import import_module
from sympy.core.compatibility import exec_, is_sequence, iterable, string_types
from sympy.utilities.decorator import doctest_depends_on
import inspect
from sympy.utilities.exceptions import SymPyDeprecationWarning
import warnings

warnings.simplefilter("always", SymPyDeprecationWarning)

# These are the namespaces the lambda functions will use.
MATH = {}
MPMATH = {}
NUMPY = {}
SYMPY = {}
NUMEXPR = {}

# Default namespaces, letting us define translations that can't be defined
# by simple variable maps, like I => 1j
# These are separate from the names above because the above names are modified
# throughout this file, whereas these should remain unmodified.
MATH_DEFAULT = {}
MPMATH_DEFAULT = {}
NUMPY_DEFAULT = {"I": 1j}
SYMPY_DEFAULT = {}
NUMEXPR_DEFAULT = {}

# Mappings between sympy and other modules function names.
MATH_TRANSLATIONS = {
    "Abs": "fabs",
    "ceiling": "ceil",
    "E": "e",
    "ln": "log",
}

MPMATH_TRANSLATIONS = {
    "Abs": "fabs",
    "elliptic_k": "ellipk",
    "elliptic_f": "ellipf",
    "elliptic_e": "ellipe",
    "elliptic_pi": "ellippi",
    "ceiling": "ceil",
    "chebyshevt": "chebyt",
    "chebyshevu": "chebyu",
    "E": "e",
    "I": "j",
    "ln": "log",
    #"lowergamma":"lower_gamma",
    "oo": "inf",
    #"uppergamma":"upper_gamma",
    "LambertW": "lambertw",
    "Matrix": "matrix",
    "MutableDenseMatrix": "matrix",
    "ImmutableMatrix": "matrix",
    "conjugate": "conj",
    "dirichlet_eta": "altzeta",
    "Ei": "ei",
    "Shi": "shi",
    "Chi": "chi",
    "Si": "si",
    "Ci": "ci"
}

NUMPY_TRANSLATIONS = {
    "Abs": "abs",
    "acos": "arccos",
    "acosh": "arccosh",
    "arg": "angle",
    "asin": "arcsin",
    "asinh": "arcsinh",
    "atan": "arctan",
    "atan2": "arctan2",
    "atanh": "arctanh",
    "ceiling": "ceil",
    "E": "e",
    "im": "imag",
    "ln": "log",
    "Matrix": "array",
    "MutableDenseMatrix": "array",
    "ImmutableMatrix": "array",
    "Max": "amax",
    "Min": "amin",
    "oo": "inf",
    "re": "real",
}

NUMEXPR_TRANSLATIONS = {}

# Available modules:
MODULES = {
    "math": (MATH, MATH_DEFAULT, MATH_TRANSLATIONS, ("from math import *",)),
    "mpmath": (MPMATH, MPMATH_DEFAULT, MPMATH_TRANSLATIONS, ("from sympy.mpmath import *",)),
    "numpy": (NUMPY, NUMPY_DEFAULT, NUMPY_TRANSLATIONS, ("import_module('numpy')",)),
    "sympy": (SYMPY, SYMPY_DEFAULT, {}, (
        "from sympy.functions import *",
        "from sympy.matrices import *",
        "from sympy import Integral, pi, oo, nan, zoo, E, I",)),
    "numexpr" : (NUMEXPR, NUMEXPR_DEFAULT, NUMEXPR_TRANSLATIONS,
                 ("import_module('numexpr')", )),
}

def _import(module, reload="False"):
    """
    Creates a global translation dictionary for module.

    The argument module has to be one of the following strings: "math",
    "mpmath", "numpy", "sympy".
    These dictionaries map names of python functions to their equivalent in
    other modules.
    """
    try:
        namespace, namespace_default, translations, import_commands = MODULES[
            module]
    except KeyError:
        raise NameError(
            "'%s' module can't be used for lambdification" % module)

    # Clear namespace or exit
    if namespace != namespace_default:
        # The namespace was already generated, don't do it again if not forced.
        if reload:
            namespace.clear()
            namespace.update(namespace_default)
        else:
            return

    for import_command in import_commands:
        if import_command.startswith('import_module'):
            module = eval(import_command)

            if module is not None:
                namespace.update(module.__dict__)
                continue
        else:
            try:
                exec_(import_command, {}, namespace)
                continue
            except ImportError:
                pass

        raise ImportError(
            "can't import '%s' with '%s' command" % (module, import_command))

    # Add translated names to namespace
    for sympyname, translation in translations.items():
        namespace[sympyname] = namespace[translation]

@doctest_depends_on(modules=('numpy'))
def lambdify(args, expr, modules=None, printer=None, use_imps=True,
        dummify=True, default_array=False):
    """
    Returns a lambda function for fast calculation of numerical values.

    If not specified differently by the user, SymPy functions are replaced as
    far as possible by either python-math, numpy (if available) or mpmath
    functions - exactly in this order. To change this behavior, the "modules"
    argument can be used. It accepts:

     - the strings "math", "mpmath", "numpy", "numexpr", "sympy"
     - any modules (e.g. math)
     - dictionaries that map names of sympy functions to arbitrary functions
     - lists that contain a mix of the arguments above, with higher priority
       given to entries appearing first.

    The default behavior is to substitute all arguments in the provided
    expression with dummy symbols. This allows for applied functions (e.g.
    f(t)) to be supplied as arguments. Call the function with dummify=False if
    dummy substitution is unwanted (and `args` is not a string). If you want
    to view the lambdified function or provide "sympy" as the module, you
    should probably set dummify=False.

    Deprecation Warnings
    ====================

    In previous releases ``lambdify`` replaced ``Matrix`` with ``numpy.matrix``
    by default. As of release 0.7.6 ``numpy.array`` is being transitioned to
    the default. In release 0.7.7 this transition will be complete. For now,
    to use the new default behavior you must pass in ``default_array=True``. If
    you plan on using ``lambdify`` often in your code it may be to your benefit
    to apply ``functools.partial``:

        >>> from sympy import lambdify
        >>> from functools import partial
        >>> lambdify = partial(lambdify, default_array=True)

    For functions involving large array calculations, numexpr can provide a
    significant speedup over numpy.  Please note that the available functions
    for numexpr are more limited than numpy but can be expanded with
    implemented_function and user defined subclasses of Function.  If specified,
    numexpr may be the only option in modules. The official list of numexpr
    functions can be found at:
    https://github.com/pydata/numexpr#supported-functions

    Usage
    =====

    (1) Use one of the provided modules:

        >>> from sympy import sin, tan, gamma
        >>> from sympy.utilities.lambdify import lambdastr
        >>> from sympy.abc import x, y
        >>> f = lambdify(x, sin(x), "math")

        Attention: Functions that are not in the math module will throw a name
                   error when the lambda function is evaluated! So this would
                   be better:

        >>> f = lambdify(x, sin(x)*gamma(x), ("math", "mpmath", "sympy"))

    (2) Use some other module:

        >>> import numpy
        >>> f = lambdify((x,y), tan(x*y), numpy)

        Attention: There are naming differences between numpy and sympy. So if
                   you simply take the numpy module, e.g. sympy.atan will not be
                   translated to numpy.arctan. Use the modified module instead
                   by passing the string "numpy":

        >>> f = lambdify((x,y), tan(x*y), "numpy")
        >>> f(1, 2)
        -2.18503986326
        >>> from numpy import array
        >>> f(array([1, 2, 3]), array([2, 3, 5]))
        [-2.18503986 -0.29100619 -0.8559934 ]

    (3) Use a dictionary defining custom functions:

        >>> def my_cool_function(x): return 'sin(%s) is cool' % x
        >>> myfuncs = {"sin" : my_cool_function}
        >>> f = lambdify(x, sin(x), myfuncs); f(1)
        'sin(1) is cool'

    Examples
    ========

    >>> from sympy.utilities.lambdify import implemented_function
    >>> from sympy import sqrt, sin, Matrix
    >>> from sympy import Function
    >>> from sympy.abc import w, x, y, z

    >>> f = lambdify(x, x**2)
    >>> f(2)
    4
    >>> f = lambdify((x, y, z), [z, y, x])
    >>> f(1,2,3)
    [3, 2, 1]
    >>> f = lambdify(x, sqrt(x))
    >>> f(4)
    2.0
    >>> f = lambdify((x, y), sin(x*y)**2)
    >>> f(0, 5)
    0.0
    >>> row = lambdify((x, y), Matrix((x, x + y)).T, modules='sympy')
    >>> row(1, 2)
    Matrix([[1, 3]])

    Tuple arguments are handled and the lambdified function should
    be called with the same type of arguments as were used to create
    the function.:

    >>> f = lambdify((x, (y, z)), x + y)
    >>> f(1, (2, 4))
    3

    A more robust way of handling this is to always work with flattened
    arguments:

    >>> from sympy.utilities.iterables import flatten
    >>> args = w, (x, (y, z))
    >>> vals = 1, (2, (3, 4))
    >>> f = lambdify(flatten(args), w + x + y + z)
    >>> f(*flatten(vals))
    10

    Functions present in `expr` can also carry their own numerical
    implementations, in a callable attached to the ``_imp_``
    attribute.  Usually you attach this using the
    ``implemented_function`` factory:

    >>> f = implemented_function(Function('f'), lambda x: x+1)
    >>> func = lambdify(x, f(x))
    >>> func(4)
    5

    ``lambdify`` always prefers ``_imp_`` implementations to implementations
    in other namespaces, unless the ``use_imps`` input parameter is False.
    """
    from sympy.core.symbol import Symbol
    from sympy.utilities.iterables import flatten

    # If the user hasn't specified any modules, use what is available.
    module_provided = True
    if modules is None:
        module_provided = False
        # Use either numpy (if available) or python.math where possible.
        # XXX: This leads to different behaviour on different systems and
        #      might be the reason for irreproducible errors.
        modules = ["math", "mpmath", "sympy"]

        # If the new defaults should be used (part of the deprecation cycle)
        if not default_array:
            # Ensures that the translation dict is set back
            # to matrix if lambdify was already called
            NUMPY_TRANSLATIONS.update({"Matrix": "matrix",
                "MutableDenseMatrix": "matrix",
                "ImmutableMatrix": "matrix"})
            SymPyDeprecationWarning("Replacing sympy.Matrix with numpy.matrix "
                                    "by default is deprecated in favor of "
                                    "numpy.array. For now, to use the new "
                                    "behavior and remove the warning set "
                                    "the kwarg default_array=True. The old "
                                    "behavior can still be used by passing "
                                    "in a custom dictionary to the modules "
                                    "kwarg.", issue=7853).warn()
        else:
            NUMPY_TRANSLATIONS.update({"Matrix": "array",
                "MutableDenseMatrix": "array",
                "ImmutableMatrix": "array"})
        #Attempt to import numpy
        try:
            _import("numpy")
        except ImportError:
            pass
        else:
            modules.insert(1, "numpy")

    # Get the needed namespaces.
    namespaces = []
    # First find any function implementations
    if use_imps:
        namespaces.append(_imp_namespace(expr))
    # Check for dict before iterating
    if isinstance(modules, (dict, str)) or not hasattr(modules, '__iter__'):
        namespaces.append(modules)
    else:
        # consistency check
        if 'numexpr' in modules and len(modules) > 1:
            raise TypeError("numexpr must be the only item in 'modules'")
        namespaces += list(modules)
    # fill namespace with first having highest priority
    namespace = {}
    for m in namespaces[::-1]:
        buf = _get_namespace(m)
        namespace.update(buf)

    if hasattr(expr, "atoms"):
        #Try if you can extract symbols from the expression.
        #Move on if expr.atoms in not implemented.
        syms = expr.atoms(Symbol)
        for term in syms:
            namespace.update({str(term): term})

    if 'numexpr' in namespaces and printer is None:
        #XXX: This has to be done here because of circular imports
        from sympy.printing.lambdarepr import NumExprPrinter as printer

    # Create lambda function.
    lstr = lambdastr(args, expr, printer=printer, dummify=dummify)
    flat = '__flatten_args__'

    if flat in lstr:
        import itertools
        namespace.update({flat: flatten})
    return eval(lstr, namespace)

def _get_namespace(m):
    """
    This is used by _lambdify to parse its arguments.
    """
    if isinstance(m, str):
        _import(m)
        return MODULES[m][0]
    elif isinstance(m, dict):
        return m
    elif hasattr(m, "__dict__"):
        return m.__dict__
    else:
        raise TypeError("Argument must be either a string, dict or module but it is: %s" % m)

def lambdastr(args, expr, printer=None, dummify=False):
    """
    Returns a string that can be evaluated to a lambda function.

    Examples
    ========

    >>> from sympy.abc import x, y, z
    >>> from sympy.utilities.lambdify import lambdastr
    >>> lambdastr(x, x**2)
    'lambda x: (x**2)'
    >>> lambdastr((x,y,z), [z,y,x])
    'lambda x,y,z: ([z, y, x])'

    Although tuples may not appear as arguments to lambda in Python 3,
    lambdastr will create a lambda function that will unpack the original
    arguments so that nested arguments can be handled:

    >>> lambdastr((x, (y, z)), x + y)
    'lambda _0,_1: (lambda x,y,z: (x + y))(*list(__flatten_args__([_0,_1])))'
    """
    # Transforming everything to strings.
    from sympy.matrices import DeferredVector
    from sympy import Dummy, sympify, Symbol, Function, flatten

    if printer is not None:
        if inspect.isfunction(printer):
            lambdarepr = printer
        else:
            if inspect.isclass(printer):
                lambdarepr = lambda expr: printer().doprint(expr)
            else:
                lambdarepr = lambda expr: printer.doprint(expr)
    else:
        #XXX: This has to be done here because of circular imports
        from sympy.printing.lambdarepr import lambdarepr

    def sub_args(args, dummies_dict):
        if isinstance(args, str):
            return args
        elif isinstance(args, DeferredVector):
            return str(args)
        elif iterable(args):
            dummies = flatten([sub_args(a, dummies_dict) for a in args])
            return ",".join(str(a) for a in dummies)
        else:
            #Sub in dummy variables for functions or symbols
            if isinstance(args, (Function, Symbol)):
                dummies = Dummy()
                dummies_dict.update({args : dummies})
                return str(dummies)
            else:
                return str(args)

    def sub_expr(expr, dummies_dict):
        try:
            expr = sympify(expr).xreplace(dummies_dict)
        except Exception:
            if isinstance(expr, DeferredVector):
                pass
            elif isinstance(expr, dict):
                k = [sub_expr(sympify(a), dummies_dict) for a in expr.keys()]
                v = [sub_expr(sympify(a), dummies_dict) for a in expr.values()]
                expr = dict(zip(k, v))
            elif isinstance(expr, tuple):
                expr = tuple(sub_expr(sympify(a), dummies_dict) for a in expr)
            elif isinstance(expr, list):
                expr = [sub_expr(sympify(a), dummies_dict) for a in expr]
        return expr

    # Transform args
    def isiter(l):
        return iterable(l, exclude=(str, DeferredVector))

    if isiter(args) and any(isiter(i) for i in args):
        from sympy.utilities.iterables import flatten
        import re
        dum_args = [str(Dummy(str(i))) for i in range(len(args))]
        iter_args = ','.join([i if isiter(a) else i
            for i, a in zip(dum_args, args)])
        lstr = lambdastr(flatten(args), expr, printer=printer, dummify=dummify)
        flat = '__flatten_args__'
        rv = 'lambda %s: (%s)(*list(%s([%s])))' % (
            ','.join(dum_args), lstr, flat, iter_args)
        if len(re.findall(r'\b%s\b' % flat, rv)) > 1:
            raise ValueError('the name %s is reserved by lambdastr' % flat)
        return rv

    dummies_dict = {}
    if dummify:
        args = sub_args(args, dummies_dict)
    else:
        if isinstance(args, str):
            pass
        elif iterable(args, exclude=DeferredVector):
            args = ",".join(str(a) for a in args)

    # Transform expr
    if dummify:
        if isinstance(expr, str):
            pass
        else:
            expr = sub_expr(expr, dummies_dict)
    expr = lambdarepr(expr)

    return "lambda %s: (%s)" % (args, expr)

def _imp_namespace(expr, namespace=None):
    """ Return namespace dict with function implementations

    We need to search for functions in anything that can be thrown at
    us - that is - anything that could be passed as `expr`.  Examples
    include sympy expressions, as well as tuples, lists and dicts that may
    contain sympy expressions.

    Parameters
    ----------
    expr : object
       Something passed to lambdify, that will generate valid code from
       ``str(expr)``.
    namespace : None or mapping
       Namespace to fill.  None results in new empty dict

    Returns
    -------
    namespace : dict
       dict with keys of implemented function names within `expr` and
       corresponding values being the numerical implementation of
       function

    Examples
    --------
    >>> from sympy.abc import x
    >>> from sympy.utilities.lambdify import implemented_function, _imp_namespace
    >>> from sympy import Function
    >>> f = implemented_function(Function('f'), lambda x: x+1)
    >>> g = implemented_function(Function('g'), lambda x: x*10)
    >>> namespace = _imp_namespace(f(g(x)))
    >>> sorted(namespace.keys())
    ['f', 'g']
    """
    # Delayed import to avoid circular imports
    from sympy.core.function import FunctionClass
    if namespace is None:
        namespace = {}
    # tuples, lists, dicts are valid expressions
    if is_sequence(expr):
        for arg in expr:
            _imp_namespace(arg, namespace)
        return namespace
    elif isinstance(expr, dict):
        for key, val in expr.items():
            # functions can be in dictionary keys
            _imp_namespace(key, namespace)
            _imp_namespace(val, namespace)
        return namespace
    # sympy expressions may be Functions themselves
    func = getattr(expr, 'func', None)
    if isinstance(func, FunctionClass):
        imp = getattr(func, '_imp_', None)
        if imp is not None:
            name = expr.func.__name__
            if name in namespace and namespace[name] != imp:
                raise ValueError('We found more than one '
                                 'implementation with name '
                                 '"%s"' % name)
            namespace[name] = imp
    # and / or they may take Functions as arguments
    if hasattr(expr, 'args'):
        for arg in expr.args:
            _imp_namespace(arg, namespace)
    return namespace

def implemented_function(symfunc, implementation):
    """ Add numerical ``implementation`` to function ``symfunc``.

    ``symfunc`` can be an ``UndefinedFunction`` instance, or a name string.
    In the latter case we create an ``UndefinedFunction`` instance with that
    name.

    Be aware that this is a quick workaround, not a general method to create
    special symbolic functions. If you want to create a symbolic function to be
    used by all the machinery of SymPy you should subclass the ``Function``
    class.

    Parameters
    ----------
    symfunc : ``str`` or ``UndefinedFunction`` instance
       If ``str``, then create new ``UndefinedFunction`` with this as
       name.  If `symfunc` is a sympy function, attach implementation to it.
    implementation : callable
       numerical implementation to be called by ``evalf()`` or ``lambdify``

    Returns
    -------
    afunc : sympy.FunctionClass instance
       function with attached implementation

    Examples
    --------
    >>> from sympy.abc import x
    >>> from sympy.utilities.lambdify import lambdify, implemented_function
    >>> from sympy import Function
    >>> f = implemented_function(Function('f'), lambda x: x+1)
    >>> lam_f = lambdify(x, f(x), default_array=True)
    >>> lam_f(4)
    5
    """
    # Delayed import to avoid circular imports
    from sympy.core.function import UndefinedFunction
    # if name, create function to hold implementation
    if isinstance(symfunc, string_types):
        symfunc = UndefinedFunction(symfunc)
    elif not isinstance(symfunc, UndefinedFunction):
        raise ValueError('symfunc should be either a string or'
                         ' an UndefinedFunction instance.')
    # We need to attach as a method because symfunc will be a class
    symfunc._imp_ = staticmethod(implementation)
    return symfunc