示例#1
0
void Stage::l_initialize(PointTableRef table)
{
    m_metadata = table.metadata().add(getName());
}
void RenderNode::issueOperations(OpenGLRenderer& renderer, T& handler) {
    if (mDisplayList->isEmpty()) {
        DISPLAY_LIST_LOGD("%*sEmpty display list (%p, %s)", handler.level() * 2, "",
                this, getName());
        return;
    }

#if HWUI_NEW_OPS
    const bool drawLayer = false;
#else
    const bool drawLayer = (mLayer && (&renderer != mLayer->renderer.get()));
#endif
    // If we are updating the contents of mLayer, we don't want to apply any of
    // the RenderNode's properties to this issueOperations pass. Those will all
    // be applied when the layer is drawn, aka when this is true.
    const bool useViewProperties = (!mLayer || drawLayer);
    if (useViewProperties) {
        const Outline& outline = properties().getOutline();
        if (properties().getAlpha() <= 0
                || (outline.getShouldClip() && outline.isEmpty())
                || properties().getScaleX() == 0
                || properties().getScaleY() == 0) {
            DISPLAY_LIST_LOGD("%*sRejected display list (%p, %s)", handler.level() * 2, "",
                    this, getName());
            return;
        }
    }

    handler.startMark(getName());

#if DEBUG_DISPLAY_LIST
    const Rect& clipRect = renderer.getLocalClipBounds();
    DISPLAY_LIST_LOGD("%*sStart display list (%p, %s), localClipBounds: %.0f, %.0f, %.0f, %.0f",
            handler.level() * 2, "", this, getName(),
            clipRect.left, clipRect.top, clipRect.right, clipRect.bottom);
#endif

    LinearAllocator& alloc = handler.allocator();
    int restoreTo = renderer.getSaveCount();
    handler(new (alloc) SaveOp(SaveFlags::MatrixClip),
            PROPERTY_SAVECOUNT, properties().getClipToBounds());

    DISPLAY_LIST_LOGD("%*sSave %d %d", (handler.level() + 1) * 2, "",
            SaveFlags::MatrixClip, restoreTo);

    if (useViewProperties) {
        setViewProperties<T>(renderer, handler);
    }

#if HWUI_NEW_OPS
    LOG_ALWAYS_FATAL("legacy op traversal not supported");
#else
    bool quickRejected = properties().getClipToBounds()
            && renderer.quickRejectConservative(0, 0, properties().getWidth(), properties().getHeight());
    if (!quickRejected) {
        Matrix4 initialTransform(*(renderer.currentTransform()));
        renderer.setBaseTransform(initialTransform);

        if (drawLayer) {
            handler(new (alloc) DrawLayerOp(mLayer),
                    renderer.getSaveCount() - 1, properties().getClipToBounds());
        } else {
            const int saveCountOffset = renderer.getSaveCount() - 1;
            const int projectionReceiveIndex = mDisplayList->projectionReceiveIndex;
            for (size_t chunkIndex = 0; chunkIndex < mDisplayList->getChunks().size(); chunkIndex++) {
                const DisplayList::Chunk& chunk = mDisplayList->getChunks()[chunkIndex];

                std::vector<ZDrawRenderNodeOpPair> zTranslatedNodes;
                buildZSortedChildList(chunk, zTranslatedNodes);

                issueOperationsOf3dChildren(ChildrenSelectMode::NegativeZChildren,
                        initialTransform, zTranslatedNodes, renderer, handler);

                for (size_t opIndex = chunk.beginOpIndex; opIndex < chunk.endOpIndex; opIndex++) {
                    DisplayListOp *op = mDisplayList->getOps()[opIndex];
#if DEBUG_DISPLAY_LIST
                    op->output(handler.level() + 1);
#endif
                    handler(op, saveCountOffset, properties().getClipToBounds());

                    if (CC_UNLIKELY(!mProjectedNodes.empty() && projectionReceiveIndex >= 0 &&
                        opIndex == static_cast<size_t>(projectionReceiveIndex))) {
                        issueOperationsOfProjectedChildren(renderer, handler);
                    }
                }

                issueOperationsOf3dChildren(ChildrenSelectMode::PositiveZChildren,
                        initialTransform, zTranslatedNodes, renderer, handler);
            }
        }
    }
#endif

    DISPLAY_LIST_LOGD("%*sRestoreToCount %d", (handler.level() + 1) * 2, "", restoreTo);
    handler(new (alloc) RestoreToCountOp(restoreTo),
            PROPERTY_SAVECOUNT, properties().getClipToBounds());

    DISPLAY_LIST_LOGD("%*sDone (%p, %s)", handler.level() * 2, "", this, getName());
    handler.endMark();
}
void RenderNode::setViewProperties(OpenGLRenderer& renderer, T& handler) {
#if DEBUG_DISPLAY_LIST
    properties().debugOutputProperties(handler.level() + 1);
#endif
    if (properties().getLeft() != 0 || properties().getTop() != 0) {
        renderer.translate(properties().getLeft(), properties().getTop());
    }
    if (properties().getStaticMatrix()) {
        renderer.concatMatrix(*properties().getStaticMatrix());
    } else if (properties().getAnimationMatrix()) {
        renderer.concatMatrix(*properties().getAnimationMatrix());
    }
    if (properties().hasTransformMatrix()) {
        if (properties().isTransformTranslateOnly()) {
            renderer.translate(properties().getTranslationX(), properties().getTranslationY());
        } else {
            renderer.concatMatrix(*properties().getTransformMatrix());
        }
    }
    const bool isLayer = properties().effectiveLayerType() != LayerType::None;
    int clipFlags = properties().getClippingFlags();
    if (properties().getAlpha() < 1) {
        if (isLayer) {
            clipFlags &= ~CLIP_TO_BOUNDS; // bounds clipping done by layer
        }
        if (CC_LIKELY(isLayer || !properties().getHasOverlappingRendering())) {
            // simply scale rendering content's alpha
            renderer.scaleAlpha(properties().getAlpha());
        } else {
            // savelayer needed to create an offscreen buffer
            Rect layerBounds(0, 0, getWidth(), getHeight());
            if (clipFlags) {
                properties().getClippingRectForFlags(clipFlags, &layerBounds);
                clipFlags = 0; // all clipping done by savelayer
            }
            SaveLayerOp* op = new (handler.allocator()) SaveLayerOp(
                    layerBounds.left, layerBounds.top,
                    layerBounds.right, layerBounds.bottom,
                    (int) (properties().getAlpha() * 255),
                    SaveFlags::HasAlphaLayer | SaveFlags::ClipToLayer);
            handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds());
        }

        if (CC_UNLIKELY(ATRACE_ENABLED() && properties().promotedToLayer())) {
            // pretend alpha always causes savelayer to warn about
            // performance problem affecting old versions
            ATRACE_FORMAT("%s alpha caused saveLayer %dx%d", getName(),
                    static_cast<int>(getWidth()),
                    static_cast<int>(getHeight()));
        }
    }
    if (clipFlags) {
        Rect clipRect;
        properties().getClippingRectForFlags(clipFlags, &clipRect);
        ClipRectOp* op = new (handler.allocator()) ClipRectOp(
                clipRect.left, clipRect.top, clipRect.right, clipRect.bottom,
                SkRegion::kIntersect_Op);
        handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds());
    }

    // TODO: support nesting round rect clips
    if (mProperties.getRevealClip().willClip()) {
        Rect bounds;
        mProperties.getRevealClip().getBounds(&bounds);
        renderer.setClippingRoundRect(handler.allocator(), bounds, mProperties.getRevealClip().getRadius());
    } else if (mProperties.getOutline().willClip()) {
        renderer.setClippingOutline(handler.allocator(), &(mProperties.getOutline()));
    }
}
String SambaService::getCaption() const
{
	return getName();
}
示例#5
0
String
ManagedObject::id() const
{
	return CoreUtil::instanceId(getName(), getVersion());
	 
}
示例#6
0
void Window::swapBuffers()
{
    _systemWindow->swapBuffers();
    LBLOG( co::LOG_BARRIER ) << "Swap buffers done" << getName() << std::endl;
}
 void NodeTypeDescriptorSelect::printPostfix(File * fp)
 {
   fp->write(getName());
 }
示例#8
0
void
pcl_ros::FeatureFromNormals::input_normals_surface_indices_callback (
   const PointCloudInConstPtr &cloud, const PointCloudNConstPtr &cloud_normals,
   const PointCloudInConstPtr &cloud_surface, const PointIndicesConstPtr &indices)
{
  // No subscribers, no work
  if (pub_output_.getNumSubscribers () <= 0)
    return;

  // If cloud+normals is given, check if it's valid
  if (!isValid (cloud))// || !isValid (cloud_normals, "normals"))
  {
    NODELET_ERROR ("[%s::input_normals_surface_indices_callback] Invalid input!", getName ().c_str ());
    emptyPublish (cloud);
    return;
  }

  // If surface is given, check if it's valid
  if (cloud_surface && !isValid (cloud_surface, "surface"))
  {
    NODELET_ERROR ("[%s::input_normals_surface_indices_callback] Invalid input surface!", getName ().c_str ());
    emptyPublish (cloud);
    return;
  }
    
  // If indices are given, check if they are valid
  if (indices && !isValid (indices))
  {
    NODELET_ERROR ("[%s::input_normals_surface_indices_callback] Invalid input indices!", getName ().c_str ());
    emptyPublish (cloud);
    return;
  }

  /// DEBUG
  if (cloud_surface)
    if (indices)
      NODELET_DEBUG ("[%s::input_normals_surface_indices_callback]\n"
                     "                                                 - PointCloud with %d data points (%s), stamp %f, and frame %s on topic %s received.\n"
                     "                                                 - PointCloud with %d data points (%s), stamp %f, and frame %s on topic %s received.\n"
                     "                                                 - PointCloud with %d data points (%s), stamp %f, and frame %s on topic %s received.\n"
                     "                                                 - PointIndices with %zu values, stamp %f, and frame %s on topic %s received.",
                     getName ().c_str (),
                     cloud->width * cloud->height, pcl::getFieldsList (*cloud).c_str (), cloud->header.stamp.toSec (), cloud->header.frame_id.c_str (), pnh_->resolveName ("input").c_str (),
                     cloud_surface->width * cloud_surface->height, pcl::getFieldsList (*cloud_surface).c_str (), cloud_surface->header.stamp.toSec (), cloud_surface->header.frame_id.c_str (), pnh_->resolveName ("surface").c_str (),
                     cloud_normals->width * cloud_normals->height, pcl::getFieldsList (*cloud_normals).c_str (), cloud_normals->header.stamp.toSec (), cloud_normals->header.frame_id.c_str (), pnh_->resolveName ("normals").c_str (),
                     indices->indices.size (), indices->header.stamp.toSec (), indices->header.frame_id.c_str (), pnh_->resolveName ("indices").c_str ());
    else
      NODELET_DEBUG ("[%s::input_normals_surface_indices_callback]\n"
                     "                                         - PointCloud with %d data points (%s), stamp %f, and frame %s on topic %s received.\n"
                     "                                         - PointCloud with %d data points (%s), stamp %f, and frame %s on topic %s received.\n"
                     "                                         - PointCloud with %d data points (%s), stamp %f, and frame %s on topic %s received.",
                     getName ().c_str (), 
                     cloud->width * cloud->height, pcl::getFieldsList (*cloud).c_str (), cloud->header.stamp.toSec (), cloud->header.frame_id.c_str (), pnh_->resolveName ("input").c_str (),
                     cloud_surface->width * cloud_surface->height, pcl::getFieldsList (*cloud_surface).c_str (), cloud_surface->header.stamp.toSec (), cloud_surface->header.frame_id.c_str (), pnh_->resolveName ("surface").c_str (),
                     cloud_normals->width * cloud_normals->height, pcl::getFieldsList (*cloud_normals).c_str (), cloud_normals->header.stamp.toSec (), cloud_normals->header.frame_id.c_str (), pnh_->resolveName ("normals").c_str ());
  else
    if (indices)
      NODELET_DEBUG ("[%s::input_normals_surface_indices_callback]\n"
                     "                                         - PointCloud with %d data points (%s), stamp %f, and frame %s on topic %s received.\n"
                     "                                         - PointCloud with %d data points (%s), stamp %f, and frame %s on topic %s received.\n"
                     "                                         - PointIndices with %zu values, stamp %f, and frame %s on topic %s received.",
                     getName ().c_str (),
                     cloud->width * cloud->height, pcl::getFieldsList (*cloud).c_str (), cloud->header.stamp.toSec (), cloud->header.frame_id.c_str (), pnh_->resolveName ("input").c_str (),
                     cloud_normals->width * cloud_normals->height, pcl::getFieldsList (*cloud_normals).c_str (), cloud_normals->header.stamp.toSec (), cloud_normals->header.frame_id.c_str (), pnh_->resolveName ("normals").c_str (),
                     indices->indices.size (), indices->header.stamp.toSec (), indices->header.frame_id.c_str (), pnh_->resolveName ("indices").c_str ());
    else
      NODELET_DEBUG ("[%s::input_normals_surface_indices_callback]\n"
                     "                                 - PointCloud with %d data points (%s), stamp %f, and frame %s on topic %s received.\n"
                     "                                 - PointCloud with %d data points (%s), stamp %f, and frame %s on topic %s received.",
                     getName ().c_str (), 
                     cloud->width * cloud->height, pcl::getFieldsList (*cloud).c_str (), cloud->header.stamp.toSec (), cloud->header.frame_id.c_str (), pnh_->resolveName ("input").c_str (),
                     cloud_normals->width * cloud_normals->height, pcl::getFieldsList (*cloud_normals).c_str (), cloud_normals->header.stamp.toSec (), cloud_normals->header.frame_id.c_str (), pnh_->resolveName ("normals").c_str ());
  ///

  if ((int)(cloud->width * cloud->height) < k_)
  {
    NODELET_ERROR ("[%s::input_normals_surface_indices_callback] Requested number of k-nearest neighbors (%d) is larger than the PointCloud size (%d)!", getName ().c_str (), k_, (int)(cloud->width * cloud->height));
    emptyPublish (cloud);
    return;
  }

  // If indices given...
  IndicesPtr vindices;
  if (indices && !indices->header.frame_id.empty ())
    vindices.reset (new std::vector<int> (indices->indices));

  computePublish (cloud, cloud_normals, cloud_surface, vindices);
}
示例#9
0
void
pcl_ros::Feature::onInit ()
{
  // Call the super onInit ()
  PCLNodelet::onInit ();

  // Call the child init
  childInit (*pnh_);

  // Allow each individual class that inherits from us to declare their own Publisher
  // This is useful for Publisher<pcl::PointCloud<T> >, as NormalEstimation can publish PointCloud<Normal>, etc
  //pub_output_ = pnh_->template advertise<PointCloud2> ("output", max_queue_size_);

  // ---[ Mandatory parameters
  if (!pnh_->getParam ("k_search", k_) && !pnh_->getParam ("radius_search", search_radius_))
  {
    NODELET_ERROR ("[%s::onInit] Neither 'k_search' nor 'radius_search' set! Need to set at least one of these parameters before continuing.", getName ().c_str ());
    return;
  }
  if (!pnh_->getParam ("spatial_locator", spatial_locator_type_))
  {
    NODELET_ERROR ("[%s::onInit] Need a 'spatial_locator' parameter to be set before continuing!", getName ().c_str ());
    return;
  }

  // ---[ Optional parameters
  pnh_->getParam ("use_surface", use_surface_);

  // Enable the dynamic reconfigure service
  srv_ = boost::make_shared<dynamic_reconfigure::Server<FeatureConfig> > (*pnh_);
  dynamic_reconfigure::Server<FeatureConfig>::CallbackType f = boost::bind (&Feature::config_callback, this, _1, _2);
  srv_->setCallback (f);

  // If we're supposed to look for PointIndices (indices) or PointCloud (surface) messages
  if (use_indices_ || use_surface_)
  {
    // Create the objects here
    if (approximate_sync_)
      sync_input_surface_indices_a_ = boost::make_shared<message_filters::Synchronizer<sync_policies::ApproximateTime<PointCloudIn, PointCloudIn, PointIndices> > >(max_queue_size_);
    else
      sync_input_surface_indices_e_ = boost::make_shared<message_filters::Synchronizer<sync_policies::ExactTime<PointCloudIn, PointCloudIn, PointIndices> > >(max_queue_size_);

    // Subscribe to the input using a filter
    sub_input_filter_.subscribe (*pnh_, "input", max_queue_size_);
    if (use_indices_)
    {
      // If indices are enabled, subscribe to the indices
      sub_indices_filter_.subscribe (*pnh_, "indices", max_queue_size_);
      if (use_surface_)     // Use both indices and surface
      {
        // If surface is enabled, subscribe to the surface, connect the input-indices-surface trio and register
        sub_surface_filter_.subscribe (*pnh_, "surface", max_queue_size_);
        if (approximate_sync_)
          sync_input_surface_indices_a_->connectInput (sub_input_filter_, sub_surface_filter_, sub_indices_filter_);
        else
          sync_input_surface_indices_e_->connectInput (sub_input_filter_, sub_surface_filter_, sub_indices_filter_);
      }
      else                  // Use only indices
      {
        sub_input_filter_.registerCallback (bind (&Feature::input_callback, this, _1));
        // surface not enabled, connect the input-indices duo and register
        if (approximate_sync_)
          sync_input_surface_indices_a_->connectInput (sub_input_filter_, nf_pc_, sub_indices_filter_);
        else
          sync_input_surface_indices_e_->connectInput (sub_input_filter_, nf_pc_, sub_indices_filter_);
      }
    }
    else                    // Use only surface
    {
      sub_input_filter_.registerCallback (bind (&Feature::input_callback, this, _1));
      // indices not enabled, connect the input-surface duo and register
      sub_surface_filter_.subscribe (*pnh_, "surface", max_queue_size_);
      if (approximate_sync_)
        sync_input_surface_indices_a_->connectInput (sub_input_filter_, sub_surface_filter_, nf_pi_);
      else
        sync_input_surface_indices_e_->connectInput (sub_input_filter_, sub_surface_filter_, nf_pi_);
    }
    // Register callbacks
    if (approximate_sync_)
      sync_input_surface_indices_a_->registerCallback (bind (&Feature::input_surface_indices_callback, this, _1, _2, _3));
    else
      sync_input_surface_indices_e_->registerCallback (bind (&Feature::input_surface_indices_callback, this, _1, _2, _3));
  }
  else
    // Subscribe in an old fashion to input only (no filters)
    sub_input_ = pnh_->subscribe<PointCloudIn> ("input", max_queue_size_,  bind (&Feature::input_surface_indices_callback, this, _1, PointCloudInConstPtr (), PointIndicesConstPtr ()));

  NODELET_DEBUG ("[%s::onInit] Nodelet successfully created with the following parameters:\n"
                 " - use_surface    : %s\n"
                 " - k_search       : %d\n"
                 " - radius_search  : %f\n"
                 " - spatial_locator: %d",
                getName ().c_str (),
                (use_surface_) ? "true" : "false", k_, search_radius_, spatial_locator_type_);
}
示例#10
0
void PointProbe::ioParam_batchLoc(enum ParamsIOFlag ioFlag) {
   getParent()->ioParamValueRequired(ioFlag, getName(), "batchLoc", &batchLoc);
}
示例#11
0
    //----------------------------------------------------------------------
    void Demonizer::startWithMonitoring(int(*startFunc)(void),
                                        int(*stopFunc)(void), int(*rereadCfgFun)(void)) {

        this->ms_startFunc = startFunc;
        this->ms_stopFunc = stopFunc;
        this->ms_rereadCfgFun = rereadCfgFun;

        int pid = 0;
        int status = 0;
        int need_start = 1;
        sigset_t sigset;
        siginfo_t siginfo;
        sigemptyset(&sigset);
        sigaddset(&sigset, SIGQUIT);
        sigaddset(&sigset, SIGINT);
        //sigaddset(&sigset, SIGTERM);
        //sigaddset(&sigset, SIGCHLD);
        sigaddset(&sigset, SIGCHLD);
        sigprocmask(SIG_BLOCK, &sigset, NULL);

        for (; ;) {
            if (need_start) {
                pid = fork();
                if (pid != 0) {
                    sysLogger.log("Fork with pid=" + Logger::itos(pid));

                    if (SystemTools::checkRunningAndSavePID(getName() + "_worker", pid)) {
                        sysLogger.log("worker daemon is already running");
                        exit(CHILD_NEED_TERMINATE);
                    }
                }
            }
            need_start = 1;
            if (pid == -1) {
                sysLogger.log("Monitor: fork failed with " + std::string(strerror(errno)));
            } else if (!pid) {
                //we are child
                status = this->workProc();
                exit(status);
            } else {// parent

                sigwaitinfo(&sigset, &siginfo);
                sysLogger.log("Monitor: wait status...");
                if (siginfo.si_signo == SIGCHLD) {

                    sysLogger.log("Monitor: got child status...");
                    wait(&status);

                    sysLogger.log("Monitor: got exit status");

                    status = WEXITSTATUS(status);
                    if (status == CHILD_NEED_TERMINATE) {
                        sysLogger.log("Monitor: children stopped");
                        break;
                    } else if (status == CHILD_NEED_RESTART) {// restart
                        sysLogger.log("Monitor: children restart");
                    }
                } else if (siginfo.si_signo == SIGUSR1) {//reread config
                    sysLogger.log("Monitor: resend signal to pid=" + Logger::itos(pid));
                    kill(pid, SIGUSR1); //resend signal
                    need_start = 0; //don't restart
                } else {
                    sysLogger.log("Monitor: signal " + std::string(strsignal(siginfo.si_signo)));
                    //kill child
                    kill(pid, SIGTERM);
                    status = 0;
                    break;
                }
            }
        }
        sysLogger.log("Monitor: stopped");
        //delete pid file
        //unlink(calculateFilenameToStorePID(this->getName()));
    }
示例#12
0
//-----------------------------------------------------------------------------
// onAdd
//-----------------------------------------------------------------------------
bool ParticleData::onAdd()
{
   if (Parent::onAdd() == false)
      return false;

   if (dragCoefficient < 0.0) {
      Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) drag coeff less than 0", getName());
      dragCoefficient = 0.0f;
   }
   if (lifetimeMS < 1) {
      Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) lifetime < 1 ms", getName());
      lifetimeMS = 1;
   }
   if (lifetimeVarianceMS >= lifetimeMS) {
      Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) lifetimeVariance >= lifetime", getName());
      lifetimeVarianceMS = lifetimeMS - 1;
   }
   if (spinSpeed > 1000.f || spinSpeed < -1000.f) {
      Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) spinSpeed invalid", getName());
      return false;
   }
   if (spinRandomMin > 1000.f || spinRandomMin < -1000.f) {
      Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) spinRandomMin invalid", getName());
      spinRandomMin = -360.0;
      return false;
   }
   if (spinRandomMin > spinRandomMax) {
      Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) spinRandomMin greater than spinRandomMax", getName());
      spinRandomMin = spinRandomMax - (spinRandomMin - spinRandomMax );
      return false;
   }
   if (spinRandomMax > 1000.f || spinRandomMax < -1000.f) {
      Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) spinRandomMax invalid", getName());
      spinRandomMax = 360.0;
      return false;
   }
   if (framesPerSec > 255)
   {
      Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) framesPerSec > 255, too high", getName());
      framesPerSec = 255;
      return false;
   }

   times[0] = 0.0f;
   for (U32 i = 1; i < 4; i++) {
      if (times[i] < times[i-1]) {
         Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) times[%d] < times[%d]", getName(), i, i-1);
         times[i] = times[i-1];
      }
   }

   // Here we validate parameters
   if (animateTexture) 
   {
     // Tiling dimensions must be positive and non-zero
     if (animTexTiling.x <= 0 || animTexTiling.y <= 0)
     {
       Con::warnf(ConsoleLogEntry::General, 
                  "ParticleData(%s) bad value(s) for animTexTiling [%d or %d <= 0], invalid datablock", 
                  animTexTiling.x, animTexTiling.y, getName());
       return false;
     }

     // Indices must fit into a byte so these are also bad
     if (animTexTiling.x * animTexTiling.y > 256)
     {
       Con::warnf(ConsoleLogEntry::General, 
                  "ParticleData(%s) bad values for animTexTiling [%d*%d > %d], invalid datablock", 
                  animTexTiling.x, animTexTiling.y, 256, getName());
       return false;
     }

     // A list of frames is required
     if (!animTexFramesString || !animTexFramesString[0]) 
     {
       Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) no animTexFrames, invalid datablock", getName());
       return false;
     }

     // The frame list cannot be too long.
     if (animTexFramesString && dStrlen(animTexFramesString) > 255) 
     {
       Con::errorf(ConsoleLogEntry::General, "ParticleData(%s) animTexFrames string too long [> 255 chars]", getName());
       return false;
     }
   }

   return true;
}
示例#13
0
bool Settings::write()
{
   // Fetch Dynamic-Field Dictionary.
   SimFieldDictionary* pFieldDictionary = getFieldDictionary();

   // Any Field Dictionary?
   if ( pFieldDictionary == NULL )
   {
      // No, so we're done.
      return false;
   }

/*
   // Iterate fields.
   for ( SimFieldDictionaryIterator itr(pFieldDictionary); *itr; ++itr )
   {
      // Fetch Field Entry.
      SimFieldDictionary::Entry* fieldEntry = *itr;

	  String check(fieldEntry->slotName);
	  String::SizeType pos = check.find("_default");
	  if(pos != String::NPos)
		 continue;

      // let's build our XML doc
      document->pushNewElement("dynamicField");
	  document->setAttribute("name", fieldEntry->slotName);
	  document->addText(fieldEntry->value);
      document->popElement();
   }
*/
   SimXMLDocument *document = new SimXMLDocument();
   document->registerObject();
   document->addHeader();

   document->pushNewElement(getName());

   SettingSaveNode *node = new SettingSaveNode();
   // Iterate fields.
   for ( SimFieldDictionaryIterator itr(pFieldDictionary); *itr; ++itr )
   {
      // Fetch Field Entry.
      SimFieldDictionary::Entry* fieldEntry = *itr;

      String check(fieldEntry->slotName);
	  if(check.find("_default") != String::NPos || check.find("_type") != String::NPos)
		 continue;

	  node->addValue(fieldEntry->slotName, fieldEntry->value);
   }

   node->buildDocument(document, true);
   node->clear();
   delete node;

   bool saved = document->saveFile(mFile.c_str());
   document->deleteObject();

   if(saved)
      return true;
   else
	   return false;   
}
示例#14
0
/*------------------------------------------------------------------------------
 *  Log in to the ShoutCast server using the icy login scheme
 *----------------------------------------------------------------------------*/
bool
ShoutCast :: sendLogin ( void )                           throw ( Exception )
{
    Sink          * sink   = getSink();
    Source        * source = getSocket();
    const char    * str;
    char            resp[STRBUF_SIZE];
    unsigned int    len;
    bool            needsMountPoint = false;
    const char    * mountPoint      = getMountPoint();


    if ( !source->isOpen() ) {
        return false;
    }
    if ( !sink->isOpen() ) {
        return false;
    }

    // We will add SOURCE only if really needed: if the mountPoint is not null
    // and is different of "/". This is to keep maximum compatibility with
    // NullSoft Shoutcast server.
    if (mountPoint != 0L
     && strlen(mountPoint) > 0 && 0 != strcmp("/", mountPoint)) {
        needsMountPoint = true;
    }

    std::ostringstream os;

    if (needsMountPoint) {
        os << "SOURCE ";
    }

    /* first line is the password in itself */
    os << getPassword();
    os << "\n";
 
    // send the mount point 
    if (needsMountPoint) {
        os << " ";
        if (strncmp("/", mountPoint, 1) != 0) {
            os << "/";
        }
        os << mountPoint;
        os << "\n";
    }

    str = os.str().c_str();

    // Ok, now we send login which will be different of classical Shoutcast
    // if mountPoint is not null and is different from "/" ...
    sink->write( str, strlen( str));
    sink->flush();

    /* read the anticipated response: "OK" */
    len = source->read( resp, STRBUF_SIZE);
    reportEvent(8, "server response length: ", len);
    reportEvent(8, "server response: ", resp);
    if ( len < 2 || resp[0] != 'O' || resp[1] != 'K' ) {
        return false;
    }

    /* suck anything that the other side has to say */
    while ( source->canRead( 0, 0) && 
           (len = source->read( resp, STRBUF_SIZE)) ) {
        ;
    }

    /* send the icy headers */
    if ( getName() ) {
        str = "icy-name:";
        sink->write( str, strlen( str));
        str = getName();
        sink->write( str, strlen( str));
    }

    if ( getUrl() ) {
        str = "\nicy-url:";
        sink->write( str, strlen( str));
        str = getUrl();
        sink->write( str, strlen( str));
    }

    if ( getGenre() ) {
        str = "\nicy-genre:";
        sink->write( str, strlen( str));
        str = getGenre();
        sink->write( str, strlen( str));
    }

    if ( getIrc() ) {
        str = "\nicy-irc:";
        sink->write( str, strlen( str));
        str = getIrc();
        sink->write( str, strlen( str));
    }

    if ( getAim() ) {
        str = "\nicy-aim:";
        sink->write( str, strlen( str));
        str = getAim();
        sink->write( str, strlen( str));
    }

    if ( getIcq() ) {
        str = "\nicy-icq:";
        sink->write( str, strlen( str));
        str = getIcq();
        sink->write( str, strlen( str));
    }

    str = "\nicy-br:";
    sink->write( str, strlen( str));
    if ( log10(getBitRate()) >= (STRBUF_SIZE-2) ) {
        throw Exception( __FILE__, __LINE__,
                         "bitrate does not fit string buffer", getBitRate());
    }
    sprintf( resp, "%d", getBitRate());
    sink->write( resp, strlen( resp));

    str = "\nicy-pub:";
    sink->write( str, strlen( str));
    str = getIsPublic() ? "1" : "0";
    sink->write( str, strlen( str));

    str = "\n\n";
    sink->write( str, strlen( str));
    sink->flush();

    return true;
}
示例#15
0
bool ewol::widget::Button::onEventInput(const ewol::event::Input& _event) {
	EWOL_VERBOSE("Event on BT : " << _event);
	// disable event in the lock access mode :
	if(ewol::widget::Button::lockAccess == m_lock) {
		return false;
	}
	if(    ewol::key::statusLeave == _event.getStatus()
	    || ewol::key::statusAbort == _event.getStatus()) {
		m_mouseHover = false;
		m_buttonPressed = false;
	} else {
		vec2 relativePos = relativePosition(_event.getPos());
		// prevent error from ouside the button
		if(    relativePos.x() < m_selectableAreaPos.x()
		    || relativePos.y() < m_selectableAreaPos.y()
		    || relativePos.x() > m_selectableAreaPos.x() + m_selectableAreaSize.x()
		    || relativePos.y() > m_selectableAreaPos.y() + m_selectableAreaSize.y() ) {
			m_mouseHover = false;
			m_buttonPressed = false;
		} else {
			m_mouseHover = true;
		}
	}
	EWOL_VERBOSE("Event on BT ... mouse hover : " << m_mouseHover);
	if (true == m_mouseHover) {
		if (1 == _event.getId()) {
			if(ewol::key::statusDown == _event.getStatus()) {
				EWOL_VERBOSE(getName() << " : Generate event : " << signalDown);
				signalDown.emit();
				m_buttonPressed = true;
				markToRedraw();
			}
			if(ewol::key::statusUp == _event.getStatus()) {
				EWOL_VERBOSE(getName() << " : Generate event : " << signalUp);
				signalUp.emit();
				m_buttonPressed = false;
				markToRedraw();
			}
			if(ewol::key::statusSingle == _event.getStatus()) {
				if(    (    m_value.get() == true
				         && ewol::widget::Button::lockWhenPressed == m_lock)
				    || (    m_value.get() == false
				         && ewol::widget::Button::lockWhenReleased == m_lock) ) {
					// nothing to do : Lock mode ...
					// user might set himself the new correct value with @ref setValue(xxx)
				} else {
					// inverse value :
					setValue((m_value.get())?false:true);
					EWOL_VERBOSE(getName() << " : Generate event : " << signalPressed);
					signalPressed.emit();
					EWOL_VERBOSE(getName() << " : Generate event : " << signalValue << " val=" << m_value );
					signalValue.emit(m_value.get());
					if(    m_toggleMode.get() == false
					    && m_value.get() == true) {
						setValue(false);
						EWOL_VERBOSE(getName() << " : Generate event : " << signalValue << " val=" << m_value);
						signalValue.emit(m_value.get());
					}
				}
				markToRedraw();
			}
		}
	}
	CheckStatus();
	return m_mouseHover;
}
示例#16
0
 void Link::setStateTrace(tmgr_trace_t trace) {
   xbt_assert(m_stateEvent==NULL,"Cannot set a second state trace to Link %s", getName());
   m_stateEvent = future_evt_set->add_trace(trace, 0.0, this);
 }
示例#17
0
void
CacheStrategyUtility::_onConfig(
    const Metadata& m)
{
    const char *param;
    const Metadata *dm;

    if (m.getName() != getName()) {
        HAGGLE_ERR("Wrong config.\n");
        return;
    }

    // load knapsack optimizer

    param = m.getParameter("knapsack_optimizer");

    if (!param) {
        HAGGLE_DBG("No knapsack optimizer specified, using default.\n");
        ksOptimizer = CacheKnapsackOptimizerFactory::getNewKnapsackOptimizer(getManager()->getKernel());
    } 
    else {
        ksOptimizer = CacheKnapsackOptimizerFactory::getNewKnapsackOptimizer(getManager()->getKernel(), param);
    }

    if (!ksOptimizer) {
        HAGGLE_ERR("Could not initialize knapsack optimizer.\n");
        return;
    }

    dm = m.getMetadata(param);
    if (dm) {
        ksOptimizer->onConfig(*dm);
    }

    // load global optimizer 

    param = m.getParameter("global_optimizer");
    if (!param) {
        HAGGLE_DBG("No  specified, using default.\n");
        globalOptimizer = CacheGlobalOptimizerFactory::getNewGlobalOptimizer(getManager()->getKernel());
    } 
    else {
        globalOptimizer = CacheGlobalOptimizerFactory::getNewGlobalOptimizer(getManager()->getKernel(), param);
    }

    if (!globalOptimizer) {
        HAGGLE_ERR("Could not initialize global optimizer.\n");
        return;
    }

    dm = m.getMetadata(param);
    if (dm) {
        globalOptimizer->onConfig(*dm);
    }

    // load utility function

    param = m.getParameter("utility_function");
    if (!param) {
        HAGGLE_DBG("No utility function specified, using default.\n");
        utilFunction = CacheUtilityFunctionFactory::getNewUtilityFunction(getManager(), globalOptimizer);
    } 
    else {
        utilFunction = CacheUtilityFunctionFactory::getNewUtilityFunction(getManager(), globalOptimizer, param);
    }

    if (!utilFunction) {
        HAGGLE_ERR("Could not initialize utility function.\n");
        return;
    }

    dm = m.getMetadata(param);
    if (dm) {
        utilFunction->onConfig(*dm);
    }

    param = m.getParameter("max_capacity_kb");
    if (!param) {
        HAGGLE_ERR("No maximum capacity specified\n");
        return;
    }

    max_capacity_kb = atoi(param);

    if (max_capacity_kb < 0) {
        HAGGLE_ERR("Invalid max capacity.\n");
        return;
    }

    param = m.getParameter("watermark_capacity_kb");
    if (!param) {
        HAGGLE_ERR("No watermark capacity specified\n");
        return;
    }

    watermark_capacity_kb = atoi(param);

    if ((watermark_capacity_kb < 0) || (watermark_capacity_kb > max_capacity_kb)) {
        HAGGLE_ERR("Invalid watermark capacity.\n");
        return;
    }

    param = m.getParameter("compute_period_ms");
    if (param) {
        computePeriodMs = atoi(param);
    }

    if (computePeriodMs  < 0) {
        HAGGLE_ERR("Invalid compute period.\n");
        return;
    }

    param = m.getParameter("purge_poll_period_ms");
    if (param) {
        pollPeriodMs = atoi(param);
    }

    if (pollPeriodMs < 0) {
        HAGGLE_ERR("Invalid poll period.\n");
        return;
    }

    param = m.getParameter("purge_on_insert");
    if (param) {
        purgeOnInsert = (0 == strcmp("true", param));
    }

    param = m.getParameter("manage_only_remote_files");
    if (param) {
        manage_only_remote_files = (0 == strcmp("true", param));
    }

    param = m.getParameter("manage_locally_sent_files");
    if (param) {
        manage_locally_sent_files = (0 == strcmp("true", param));
    }

    param = m.getParameter("publish_stats_dataobject");
    if (param) {
        publish_stats_dataobject = (0 == strcmp("true", param));
    }

    param = m.getParameter("keep_in_bloomfilter");
    if (param) {
        keep_in_bloomfilter = (0 == strcmp("true", param));
    }

    param = m.getParameter("handle_zero_size");
    if (param) {
        handle_zero_size = (0 == strcmp("true", param));
    }

//JM: START DB 
    param = m.getParameter("manage_db_purging");
    if (param) {
        allow_db_purging = (0 == strcmp("true", param));
    }

    param = m.getParameter("db_size_threshold");
    if (param) {
        db_size_threshold = atoll(param);
    }

    param = m.getParameter("self_benchmark_test");
    if (param) {
        self_test = (0 == strcmp("true", param));
    }
//JM: END
    param = m.getParameter("bloomfilter_remove_delay_ms");
    if (param) {
        bloomfilter_remove_delay_ms = atoi(param);
    }

// SW: START: remove from local bloomfilter.
    if (bloomfilter_remove_delay_ms >= 0) {
        bloomfilterRemoveDelayEventType = registerEventType("BFRemoveDelay", onBloomfilterRemoveDelay);
        if (bloomfilterRemoveDelayEventType <= 0) {
            HAGGLE_ERR("Could not register bloomfilter remove delay event.\n");
        }
    }
//SW: END: remove from local bloomfilter.

    if (publish_stats_dataobject) {
        CacheReplacementTotalOrder *replacement = 
            new CacheReplacementTotalOrder(
                getManager(),
                "Timestamp",
                "PublisherID",
                "CacheStrategyUtility",
                "stats");
        // only keep the most up to date stats in the data base
        stats_replacement_strat =
            new CacheStrategyReplacementPurger(
                getManager(),
                replacement,
                NULL,
                false);

        if (!stats_replacement_strat) {
            HAGGLE_ERR("Could not allocate replacement strat\n");
        }
        else {
            stats_replacement_strat->start();
        }
    }

    periodicPurgeEventType = registerEventType("periodic purge event", onPeriodicEvent);
    periodicPurgeEvent = new Event(periodicPurgeEventType);
    // we re-use the event
	periodicPurgeEvent->setAutoDelete(false);

    firePeriodic();

    if (!purgeOnInsert && (pollPeriodMs <= 0)) {
        HAGGLE_DBG("WARNING: All purging is disabled, was this intended?\n");
    }

    // add debug printing 

    HAGGLE_DBG("Successfully initialized utiltiy cache strategy, knapsack optimizer: %s, global optimizer: %s, utiltiy function: %s,  max capacity kb: %lld, watermark capacity kb: %lld, compute period ms: %d, purge poll period ms: %d, purge on insert; %s, manage only remote files: %s, publish stats dataobject: %s, db_purge: %s (%lld), self test:%s \n", getKnapsackOptimizer()->getName().c_str(), getGlobalOptimizer()->getName().c_str(), getUtilityFunction()->getName().c_str(),  max_capacity_kb, watermark_capacity_kb, computePeriodMs, pollPeriodMs, purgeOnInsert ? "yes" : "no", manage_only_remote_files ? "yes" : "no", publish_stats_dataobject ? "yes (CacheStrategyUtility=stats)" : "no", allow_db_purging ? "yes" : "no", db_size_threshold, self_test ? "yes" : "no");
}
示例#18
0
 void Link::setBandwidthTrace(tmgr_trace_t trace)
 {
   xbt_assert(m_bandwidth.event==NULL,"Cannot set a second bandwidth trace to Link %s", getName());
   m_bandwidth.event = future_evt_set->add_trace(trace, 0.0, this);
 }
示例#19
0
  //----------------------------------------------------------------
  // IElement::load
  //
  uint64
  IElement::load(IStorage & storage,
                 uint64 bytesToRead,
                 IDelegateLoad * loader)
  {
    if (!bytesToRead)
    {
      return 0;
    }

    // save a storage receipt so that element position references
    // can be resolved later:
    IStorage::IReceiptPtr storageReceipt = storage.receipt();

    // save current seek position, so it can be restored if necessary:
    IStorage::TSeek storageStart(storage);

    uint64 eltId = loadEbmlId(storage);
    if (eltId != getId())
    {
      // element id wrong for my type:
      return 0;
    }

#if 0 // !defined(NDEBUG) && (defined(DEBUG) || defined(_DEBUG))
    Indent::More indentMore(Indent::depth_);
    {
      IStorage::TSeek restore(storage);
      uint64 vsizeSize = 0;
      uint64 vsize = vsizeDecode(storage, vsizeSize);
      std::cout << indent()
                << std::setw(8) << uintEncode(getId()) << " @ "
                << std::hex
                << "0x" << storageStart.absolutePosition()
                << std::dec
                << " -- " << getName()
                << ", payload " << vsize << " bytes" << std::endl;
    }
#endif

    // this appears to be a good payload:
    storageStart.doNotRestore();

    // store the storage receipt:
    receipt_ = storageReceipt;

    // read payload size:
    uint64 vsizeSize = 0;
    uint64 payloadSize = vsizeDecode(storage, vsizeSize);
    const bool payloadSizeUnknown = (payloadSize == uintMax[8]);

    // keep track of the number of bytes read successfully:
    receipt_->add(uintNumBytes(eltId));
    receipt_->add(vsizeSize);

    // clear the payload checksum:
    setCrc32(false);
    storedCrc32_ = 0;
    computedCrc32_ = 0;

    // save the payload storage receipt so that element position references
    // can be resolved later:
    IStorage::IReceiptPtr receiptPayload = storage.receipt();
    offsetToPayload_ = receiptPayload->position() - receipt_->position();
    offsetToCrc32_ = kUndefinedOffset;

    // shortcut:
    IPayload & payload = getPayload();

    // container elements may be present in any order, therefore
    // not every load will succeed -- keep trying until all
    // load attempts fail:
    uint64 payloadBytesToRead = payloadSize;
    uint64 payloadBytesReadTotal = 0;
    while (payloadBytesToRead)
    {
      uint64 prevPayloadBytesToRead = payloadBytesToRead;

      // try to load some part of the payload:
      uint64 partialPayloadSize = 0;
      if (loader)
      {
        uint64 bytesRead = loader->load(storage,
                                        payloadBytesToRead,
                                        eltId,
                                        payload);
        if (bytesRead == uintMax[8])
        {
          // special case, indicating that the loader doesn't
          // want to read any more data:
          storageStart.doRestore();
          loader->loaded(*this);
          return 0;
        }

        partialPayloadSize += bytesRead;
        payloadBytesToRead -= bytesRead;
      }

      if (!partialPayloadSize)
      {
        uint64 bytesRead = payload.load(storage,
                                        payloadBytesToRead,
                                        loader);
        partialPayloadSize += bytesRead;
        payloadBytesToRead -= bytesRead;
      }

      // consume any void elements that may exist:
      IPayload::TVoid eltVoid;
      uint64 voidPayloadSize = eltVoid.load(storage,
                                            payloadBytesToRead,
                                            loader);
      if (voidPayloadSize)
      {
        payloadBytesToRead -= voidPayloadSize;

        // find an element to store the Void element, so that
        // the relative element order would be preserved:
        IStorage::IReceiptPtr voidReceipt = eltVoid.storageReceipt();
        FindElement crawler(voidReceipt->position() - 2);

        if (partialPayloadSize)
        {
          crawler.evalPayload(payload);
          assert(crawler.eltFound_);
        }

        if (crawler.eltFound_)
        {
          IPayload & dstPayload = crawler.eltFound_->getPayload();
          dstPayload.voids_.push_back(eltVoid);
        }
        else
        {
          payload.voids_.push_back(eltVoid);
        }
      }

      // consume the CRC-32 element if it exists:
      payloadBytesToRead -= loadCrc32(storage,
                                      payloadBytesToRead);

      uint64 payloadBytesRead = prevPayloadBytesToRead - payloadBytesToRead;
      payloadBytesReadTotal += payloadBytesRead;

      if (payloadBytesRead == 0)
      {
        break;
      }
    }

    if (payloadBytesReadTotal < payloadSize && !payloadSizeUnknown)
    {
      // skip unrecognized alien data:
      uint64 alienDataSize = payloadSize - payloadBytesReadTotal;

#if !defined(NDEBUG) && (defined(DEBUG) || defined(_DEBUG))
      std::cerr << indent() << "WARNING: " << getName()
                << " 0x" << uintEncode(getId())
                << " -- skipping " << alienDataSize
                << " bytes of unrecognized alien data @ 0x"
                << std::hex
                << storage.receipt()->position()
                << std::dec
                << std::endl;
#endif

      storage.skip(alienDataSize);
      payloadBytesReadTotal = payloadSize;
    }

    receiptPayload->add(payloadBytesReadTotal);
    *receipt_ += receiptPayload;

    // verify stored payload CRC-32 checksum:
    if (shouldComputeCrc32())
    {
      IStorage::IReceiptPtr receiptCrc32 = crc32Receipt();

      Crc32 crc32;
      receiptPayload->calcCrc32(crc32, receiptCrc32);
      computedCrc32_ = crc32.checksum();

      if (computedCrc32_ != storedCrc32_)
      {
#if 1 // !defined(NDEBUG) && (defined(DEBUG) || defined(_DEBUG))
        std::cerr << indent() << "WARNING: " << getName()
                  << " 0x" << uintEncode(getId())
                  << " -- checksum mismatch, loaded "
                  << std::hex << storedCrc32_
                  << ", computed " << computedCrc32_
                  << ", CRC-32 @ 0x" << receiptCrc32->position()
                  << ", payload @ 0x" << receiptPayload->position()
                  << ":" << receiptPayload->numBytes()
                  << std::dec
                  << std::endl;

        Crc32 doOverCrc32;
        receiptPayload->calcCrc32(doOverCrc32, receiptCrc32);
#endif
      }
    }

    if (loader && receipt_->numBytes())
    {
      // allow the delegate to perform post-processing on the loaded element:
      loader->loaded(*this);
    }

    return receipt_->numBytes();
  }
示例#20
0
 void Link::setLatencyTrace(tmgr_trace_t trace)
 {
   xbt_assert(m_latency.event==NULL,"Cannot set a second latency trace to Link %s", getName());
   m_latency.event = future_evt_set->add_trace(trace, 0.0, this);
 }
示例#21
0
  {
    const double lengthRescale = 1 / Sim->primaryCellSize.maxElement();

    if (!_renderObj)
      {
	std::vector<float> verts;
	verts.reserve(3 * _vertices.size());
	BOOST_FOREACH(const Vector& v, _vertices)
	  {
	    verts.push_back(v[0] * lengthRescale);
	    verts.push_back(v[1] * lengthRescale);
	    verts.push_back(v[2] * lengthRescale);
	  }

	std::vector<GLuint> elems;
	elems.reserve(3 * _elements.size());
	BOOST_FOREACH(const TriangleElements& e, _elements)
	  {
	    elems.push_back(e.get<0>());
	    elems.push_back(e.get<1>());
	    elems.push_back(e.get<2>());
	  }
      
	_renderObj.reset(new coil::RTriangleMesh(getName(), verts, elems));
      }
  
    return std::tr1::static_pointer_cast<coil::RenderObj>(_renderObj);
  }
#endif
}
示例#22
0
void TextStreamProbe::ioParam_displayPeriod(enum ParamsIOFlag ioFlag) {
   getParent()->ioParamValue(ioFlag, getName(), "displayPeriod", &displayPeriod, 1.0);
}
Boolean SambaService::getName(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_NAME, getName());
	return true;
}
/// Insert a message into the buffer.
void SipClientWriteBuffer::insertMessage(SipMessage* message)
{
   UtlBoolean wasEmpty = mWriteBuffer.isEmpty();

    //
    // Let all outbound processors know about this message
    //
    if (message && mpSipUserAgent && mClientSocket && mClientSocket->isOk())
    {
      UtlString remoteHostAddress;
      int remotePort;
      mClientSocket->getRemoteHostIp(&remoteHostAddress, &remotePort);
      // We are about to post a message that will cause the
      // SIP message to be sent.  Notify the user agent so
      // that it can offer the message to all its registered
      // output processors.


      ssize_t msgLength = 0;
      UtlString msgText;
      message->getBytes(&msgText, &msgLength, true);
      if (msgLength)
      {
        system_tap_sip_tx(
             mLocalHostAddress.data(), portIsValid(mLocalHostPort) ? mLocalHostPort : defaultPort(),
             remoteHostAddress.data(), remotePort == PORT_NONE ? defaultPort() : remotePort,
             msgText.data(), msgLength);

        mpSipUserAgent->executeAllBufferedSipOutputProcessors(*message, remoteHostAddress.data(),
               remotePort == PORT_NONE ? defaultPort() : remotePort);
      }
    }

   // Add the message to the queue.
   mWriteBuffer.insert(message);

   // If the buffer was empty, we need to set mWriteString and
   // mWritePointer.
   if (wasEmpty)
   {
      ssize_t length;
      message->getBytes(&mWriteString, &length);
      mWritePointer = 0;
   }

   mWriteQueued = TRUE;

   // Check to see if our internal queue is getting too big, which means
   // that the socket has been blocked for writing for a long time.
   // We use the message queue length of this task as the limit, since
   // both queues are affected by the same traffic load factors.
   if (mWriteBuffer.entries() > (size_t) (getMessageQueue()->maxMsgs()))
   {
      // If so, abort all unsent messages and terminate this client (so
      // as to clear any state of the socket).
      Os::Logger::instance().log(FAC_SIP, PRI_ERR,
                    "SipClientWriteBuffer[%s]::insertMessage "
                    "mWriteBuffer has '%d' entries, exceeding the limit of maxMsgs '%d'",
                    getName().data(), (int) mWriteBuffer.entries(),
                    getMessageQueue()->maxMsgs());
      emptyBuffer(TRUE);
      clientStopSelf();
   }
}
示例#25
0
 void Solver::setValue(std::string key, const Variant& value)
 {
     if (settings.find(key) ==  settings.end())
         throw std::invalid_argument(getName() + " invalid key: " + key);
     settings[key] = value;
 }
/// Write as much of the buffered messages as can be written.
// Executed by the thread.
void SipClientWriteBuffer::writeMore()
{
   // 'exit_loop' will be set to TRUE if an attempt to write does
   // not write any bytes, and we will then return.
   UtlBoolean exit_loop = FALSE;

   while (mWriteQueued && !exit_loop)
   {
      if (mWritePointer >= mWriteString.length())
      {
         // We have written all of the first message.
         // Pop it and set up to write the next message.
         delete mWriteBuffer.get();
         mWriteString.remove(0);
         mWritePointer = 0;
         mWriteQueued = ! mWriteBuffer.isEmpty();
         if (mWriteQueued)
         {
            // get the message on the head of the queue, and figure out which kind it is
            UtlContainable* nextMsg = mWriteBuffer.first();
            SipMessage* sipMsg;
            UtlString* keepAliveMsg;
            if ((sipMsg = dynamic_cast<SipMessage*>(nextMsg))) // a SIP message
            {
               ssize_t length;
               sipMsg->getBytes(&mWriteString, &length);
            }
            else if ((keepAliveMsg = dynamic_cast<UtlString*>(nextMsg))) // a keepalive CRLF
            {
               mWriteString.append(*keepAliveMsg);
            }
            else
            {
               Os::Logger::instance().log(FAC_SIP, PRI_CRIT,
                             "SipClientWriteBuffer[%s]::writeMore "
                             "unrecognized message type in queue",
                             mName.data());
               assert(false);
               delete mWriteBuffer.get();
               mWriteQueued = mWriteBuffer.isEmpty();
            }
         }
      }
      else
      {
         // Some portion of the first message remains to be written.

         // If the socket has failed, attempt to reconnect it.
         // :NOTE: OsConnectionSocket::reconnect isn't implemented.
         if (!mClientSocket->isOk())
         {
            mClientSocket->reconnect();
         }

         // Calculate the length to write.
         int length = mWriteString.length() - mWritePointer;

         // ret is the value returned from write attempt.
         // -1 means an error was seen.
         int ret;
         if (mClientSocket->isOk())
         {
            // Write what we can.
            ret = mClientSocket->write(mWriteString.data() + mWritePointer, length);
            // Theoretically, ret > 0, since the socket is ready for writing,
            // but it appears that that ret can be 0.
         }
         else
         {
            // Record the error.
            ret = -1;
            // Set a special errno value, which hopefully is not a real value.
            errno = 1000;
         }

         if (ret > 0)
         {
            // We successfully sent some data, perhaps all of the
            // remainder of the first message.
            // Update the last-activity time.
            touch();
            // Update the state variables.
            mWritePointer += ret;
         }
         else if (ret == 0)
         {
            // No data sent, even though (in our caller) poll()
            // reported the socket was ready to write.
            exit_loop = TRUE;
         }
         else
         {
            // Error while writing.
            Os::Logger::instance().log(FAC_SIP, PRI_ERR,
                          "SipClientWriteBuffer[%s]::writeMore "
                          "OsSocket::write() returned %d, errno = %d",
                          getName().data(), ret, errno);
            // Return all buffered messages with a transport error indication.
            emptyBuffer(TRUE);
            // Because TCP is a connection protocol, we know that we cannot
            // send successfully any more and so should shut down this client.
            clientStopSelf();
            // Exit the loop so handleMessage() can process the stop request.
            exit_loop = TRUE;
         }
      }
   }
}
void RenderNode::pushLayerUpdate(TreeInfo& info) {
    LayerType layerType = properties().effectiveLayerType();
    // If we are not a layer OR we cannot be rendered (eg, view was detached)
    // we need to destroy any Layers we may have had previously
    if (CC_LIKELY(layerType != LayerType::RenderLayer) || CC_UNLIKELY(!isRenderable())) {
        if (CC_UNLIKELY(mLayer)) {
            destroyLayer(mLayer);
            mLayer = nullptr;
        }
        return;
    }

    bool transformUpdateNeeded = false;
    if (!mLayer) {
        mLayer = createLayer(info.canvasContext.getRenderState(), getWidth(), getHeight());
#if !HWUI_NEW_OPS
        applyLayerPropertiesToLayer(info);
#endif
        damageSelf(info);
        transformUpdateNeeded = true;
    } else if (!layerMatchesWidthAndHeight(mLayer, getWidth(), getHeight())) {
#if HWUI_NEW_OPS
        // TODO: remove now irrelevant, currently enqueued damage (respecting damage ordering)
        // Or, ideally, maintain damage between frames on node/layer so ordering is always correct
        RenderState& renderState = mLayer->renderState;
        if (properties().fitsOnLayer()) {
            mLayer = renderState.layerPool().resize(mLayer, getWidth(), getHeight());
        } else {
#else
        if (!LayerRenderer::resizeLayer(mLayer, getWidth(), getHeight())) {
#endif
            destroyLayer(mLayer);
            mLayer = nullptr;
        }
        damageSelf(info);
        transformUpdateNeeded = true;
    }

    SkRect dirty;
    info.damageAccumulator->peekAtDirty(&dirty);

    if (!mLayer) {
        Caches::getInstance().dumpMemoryUsage();
        if (info.errorHandler) {
            std::ostringstream err;
            err << "Unable to create layer for " << getName();
            const int maxTextureSize = Caches::getInstance().maxTextureSize;
            if (getWidth() > maxTextureSize || getHeight() > maxTextureSize) {
                err << ", size " << getWidth() << "x" << getHeight()
                        << " exceeds max size " << maxTextureSize;
            } else {
                err << ", see logcat for more info";
            }
            info.errorHandler->onError(err.str());
        }
        return;
    }

    if (transformUpdateNeeded && mLayer) {
        // update the transform in window of the layer to reset its origin wrt light source position
        Matrix4 windowTransform;
        info.damageAccumulator->computeCurrentTransform(&windowTransform);
        mLayer->setWindowTransform(windowTransform);
    }

#if HWUI_NEW_OPS
    info.layerUpdateQueue->enqueueLayerWithDamage(this, dirty);
#else
    if (dirty.intersect(0, 0, getWidth(), getHeight())) {
        dirty.roundOut(&dirty);
        mLayer->updateDeferred(this, dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom);
    }
    // This is not inside the above if because we may have called
    // updateDeferred on a previous prepare pass that didn't have a renderer
    if (info.renderer && mLayer->deferredUpdateScheduled) {
        info.renderer->pushLayerUpdate(mLayer);
    }
#endif

    // There might be prefetched layers that need to be accounted for.
    // That might be us, so tell CanvasContext that this layer is in the
    // tree and should not be destroyed.
    info.canvasContext.markLayerInUse(this);
}

/**
 * Traverse down the the draw tree to prepare for a frame.
 *
 * MODE_FULL = UI Thread-driven (thus properties must be synced), otherwise RT driven
 *
 * While traversing down the tree, functorsNeedLayer flag is set to true if anything that uses the
 * stencil buffer may be needed. Views that use a functor to draw will be forced onto a layer.
 */
void RenderNode::prepareTreeImpl(TreeInfo& info, bool functorsNeedLayer) {
    info.damageAccumulator->pushTransform(this);

    if (info.mode == TreeInfo::MODE_FULL) {
        pushStagingPropertiesChanges(info);
    }
    uint32_t animatorDirtyMask = 0;
    if (CC_LIKELY(info.runAnimations)) {
        animatorDirtyMask = mAnimatorManager.animate(info);
    }

    bool willHaveFunctor = false;
    if (info.mode == TreeInfo::MODE_FULL && mStagingDisplayList) {
        willHaveFunctor = !mStagingDisplayList->getFunctors().empty();
    } else if (mDisplayList) {
        willHaveFunctor = !mDisplayList->getFunctors().empty();
    }
    bool childFunctorsNeedLayer = mProperties.prepareForFunctorPresence(
            willHaveFunctor, functorsNeedLayer);

    if (CC_UNLIKELY(mPositionListener.get())) {
        mPositionListener->onPositionUpdated(*this, info);
    }

    prepareLayer(info, animatorDirtyMask);
    if (info.mode == TreeInfo::MODE_FULL) {
        pushStagingDisplayListChanges(info);
    }
    prepareSubTree(info, childFunctorsNeedLayer, mDisplayList);
    pushLayerUpdate(info);

    info.damageAccumulator->popTransform();
}
示例#28
0
void ewol::widget::Button::onLostFocus() {
	m_buttonPressed = false;
	EWOL_VERBOSE(getName() << " : Remove Focus ...");
	CheckStatus();
}
示例#29
0
/* Create a feature on the map */
FEATURE *buildFeature(FEATURE_STATS *psStats, UDWORD x, UDWORD y, bool FromSave)
{
	//try and create the Feature
	FEATURE *psFeature = new FEATURE(generateSynchronisedObjectId(), psStats);

	if (psFeature == NULL)
	{
		debug(LOG_WARNING, "Feature couldn't be built.");
		return NULL;
	}
	// features are not in the cluster system
	// this will cause an assert when they still end up there
	psFeature->cluster = ~0;
	//add the feature to the list - this enables it to be drawn whilst being built
	addFeature(psFeature);

	// snap the coords to a tile
	if (!FromSave)
	{
		x = (x & ~TILE_MASK) + psStats->baseWidth  % 2 * TILE_UNITS / 2;
		y = (y & ~TILE_MASK) + psStats->baseBreadth % 2 * TILE_UNITS / 2;
	}
	else
	{
		if ((x & TILE_MASK) != psStats->baseWidth  % 2 * TILE_UNITS / 2 ||
		    (y & TILE_MASK) != psStats->baseBreadth % 2 * TILE_UNITS / 2)
		{
			debug(LOG_WARNING, "Feature not aligned. position (%d,%d), size (%d,%d)", x, y, psStats->baseWidth, psStats->baseBreadth);
		}
	}

	psFeature->pos.x = x;
	psFeature->pos.y = y;

	StructureBounds b = getStructureBounds(psFeature);

	// get the terrain average height
	int foundationMin = INT32_MAX;
	int foundationMax = INT32_MIN;
	for (int breadth = 0; breadth <= b.size.y; ++breadth)
	{
		for (int width = 0; width <= b.size.x; ++width)
		{
			int h = map_TileHeight(b.map.x + width, b.map.y + breadth);
			foundationMin = std::min(foundationMin, h);
			foundationMax = std::max(foundationMax, h);
		}
	}
	//return the average of max/min height
	int height = (foundationMin + foundationMax) / 2;

	if (psStats->subType == FEAT_TREE)
	{
		psFeature->rot.direction = gameRand(DEG_360);
	}
	else
	{
		psFeature->rot.direction = 0;
	}
	psFeature->body = psStats->body;
	psFeature->periodicalDamageStart = 0;
	psFeature->periodicalDamage = 0;

	// it has never been drawn
	psFeature->sDisplay.frameNumber = 0;

	memset(psFeature->seenThisTick, 0, sizeof(psFeature->seenThisTick));
	memset(psFeature->visible, 0, sizeof(psFeature->visible));

	// set up the imd for the feature
	psFeature->sDisplay.imd = psStats->psImd;

	ASSERT_OR_RETURN(NULL, psFeature->sDisplay.imd, "No IMD for feature");		// make sure we have an imd.

	for (int breadth = 0; breadth < b.size.y; ++breadth)
	{
		for (int width = 0; width < b.size.x; ++width)
		{
			MAPTILE *psTile = mapTile(b.map.x + width, b.map.y + breadth);

			//check not outside of map - for load save game
			ASSERT_OR_RETURN(NULL, b.map.x + width < mapWidth, "x coord bigger than map width - %s, id = %d", getName(psFeature->psStats), psFeature->id);
			ASSERT_OR_RETURN(NULL, b.map.y + breadth < mapHeight, "y coord bigger than map height - %s, id = %d", getName(psFeature->psStats), psFeature->id);

			if (width != psStats->baseWidth && breadth != psStats->baseBreadth)
			{
				if (TileHasFeature(psTile))
				{
					FEATURE *psBlock = (FEATURE *)psTile->psObject;

					debug(LOG_ERROR, "%s(%d) already placed at (%d+%d, %d+%d) when trying to place %s(%d) at (%d+%d, %d+%d) - removing it",
					      getName(psBlock->psStats), psBlock->id, map_coord(psBlock->pos.x), psBlock->psStats->baseWidth, map_coord(psBlock->pos.y),
					      psBlock->psStats->baseBreadth, getName(psFeature->psStats), psFeature->id, b.map.x, b.size.x, b.map.y, b.size.y);

					removeFeature(psBlock);
				}

				psTile->psObject = (BASE_OBJECT *)psFeature;

				// if it's a tall feature then flag it in the map.
				if (psFeature->sDisplay.imd->max.y > TALLOBJECT_YMAX)
				{
					auxSetBlocking(b.map.x + width, b.map.y + breadth, AIR_BLOCKED);
				}

				if (psStats->subType != FEAT_GEN_ARTE && psStats->subType != FEAT_OIL_DRUM)
				{
					auxSetBlocking(b.map.x + width, b.map.y + breadth, FEATURE_BLOCKED);
				}
			}

			if ((!psStats->tileDraw) && (FromSave == false))
			{
				psTile->height = height;
			}
		}
	}
	psFeature->pos.z = map_TileHeight(b.map.x, b.map.y);//jps 18july97

	return psFeature;
}
示例#30
0
文件: Widget.cpp 项目: biddyweb/ewol
void ewol::Widget::periodicCallDisable() {
	EWOL_VERBOSE("Perodic call disable " << getName());
	getObjectManager().periodicCall.release(shared_from_this());
}