当前位置: 首页>>代码示例>>C++>>正文


C++ Layer类代码示例

本文整理汇总了C++中Layer的典型用法代码示例。如果您正苦于以下问题:C++ Layer类的具体用法?C++ Layer怎么用?C++ Layer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Layer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: GetRoot

float
LayerManagerComposite::ComputeRenderIntegrity()
{
  // We only ever have incomplete rendering when progressive tiles are enabled.
  Layer* root = GetRoot();
  if (!gfxPlatform::GetPlatform()->UseProgressivePaint() || !root) {
    return 1.f;
  }

  FrameMetrics rootMetrics = LayerMetricsWrapper::TopmostScrollableMetrics(root);
  if (!rootMetrics.IsScrollable()) {
    // The root may not have any scrollable metrics, in which case rootMetrics
    // will just be an empty FrameMetrics. Instead use the actual metrics from
    // the root layer.
    rootMetrics = LayerMetricsWrapper(root).Metrics();
  }
  ParentLayerIntRect bounds = RoundedToInt(rootMetrics.GetCompositionBounds());
  IntRect screenRect(bounds.x,
                       bounds.y,
                       bounds.width,
                       bounds.height);

  float lowPrecisionMultiplier = 1.0f;
  float highPrecisionMultiplier = 1.0f;

#ifdef MOZ_WIDGET_ANDROID
  // Use the transform on the primary scrollable layer and its FrameMetrics
  // to find out how much of the viewport the current displayport covers
  nsTArray<Layer*> rootScrollableLayers;
  GetRootScrollableLayers(rootScrollableLayers);
  if (rootScrollableLayers.Length() > 0) {
    // This is derived from the code in
    // AsyncCompositionManager::TransformScrollableLayer
    Layer* rootScrollable = rootScrollableLayers[0];
    const FrameMetrics& metrics = LayerMetricsWrapper::TopmostScrollableMetrics(rootScrollable);
    Matrix4x4 transform = rootScrollable->GetEffectiveTransform();
    transform.PostScale(metrics.GetPresShellResolution(), metrics.GetPresShellResolution(), 1);

    // Clip the screen rect to the document bounds
    Rect documentBounds =
      transform.TransformBounds(Rect(metrics.GetScrollableRect().x - metrics.GetScrollOffset().x,
                                     metrics.GetScrollableRect().y - metrics.GetScrollOffset().y,
                                     metrics.GetScrollableRect().width,
                                     metrics.GetScrollableRect().height));
    documentBounds.RoundOut();
    screenRect = screenRect.Intersect(IntRect(documentBounds.x, documentBounds.y,
                                                documentBounds.width, documentBounds.height));

    // If the screen rect is empty, the user has scrolled entirely into
    // over-scroll and so we can be considered to have full integrity.
    if (screenRect.IsEmpty()) {
      return 1.0f;
    }

    // Work out how much of the critical display-port covers the screen
    bool hasLowPrecision = false;
    if (!metrics.GetCriticalDisplayPort().IsEmpty()) {
      hasLowPrecision = true;
      highPrecisionMultiplier =
        GetDisplayportCoverage(metrics.GetCriticalDisplayPort(), transform, screenRect);
    }

    // Work out how much of the display-port covers the screen
    if (!metrics.GetDisplayPort().IsEmpty()) {
      if (hasLowPrecision) {
        lowPrecisionMultiplier =
          GetDisplayportCoverage(metrics.GetDisplayPort(), transform, screenRect);
      } else {
        lowPrecisionMultiplier = highPrecisionMultiplier =
          GetDisplayportCoverage(metrics.GetDisplayPort(), transform, screenRect);
      }
    }
  }

  // If none of the screen is covered, we have zero integrity.
  if (highPrecisionMultiplier <= 0.0f && lowPrecisionMultiplier <= 0.0f) {
    return 0.0f;
  }
#endif // MOZ_WIDGET_ANDROID

  nsIntRegion screenRegion(screenRect);
  nsIntRegion lowPrecisionScreenRegion(screenRect);
  Matrix4x4 transform;
  ComputeRenderIntegrityInternal(root, screenRegion,
                                 lowPrecisionScreenRegion, transform);

  if (!screenRegion.IsEqual(screenRect)) {
    // Calculate the area of the region. All rects in an nsRegion are
    // non-overlapping.
    float screenArea = screenRect.width * screenRect.height;
    float highPrecisionIntegrity = screenRegion.Area() / screenArea;
    float lowPrecisionIntegrity = 1.f;
    if (!lowPrecisionScreenRegion.IsEqual(screenRect)) {
      lowPrecisionIntegrity = lowPrecisionScreenRegion.Area() / screenArea;
    }

    return ((highPrecisionIntegrity * highPrecisionMultiplier) +
            (lowPrecisionIntegrity * lowPrecisionMultiplier)) / 2;
  }

//.........这里部分代码省略.........
开发者ID:rtrsparq,项目名称:gecko-dev,代码行数:101,代码来源:LayerManagerComposite.cpp

示例2: qMax

void PenTool::drawStroke()
{
    StrokeTool::drawStroke();
    QList<QPointF> p = m_pStrokeManager->interpolateStroke();

    Layer* layer = mEditor->layers()->currentLayer();

    if ( layer->type() == Layer::BITMAP )
    {
        for ( int i = 0; i < p.size(); i++ )
        {
            p[ i ] = mEditor->view()->mapScreenToCanvas( p[ i ] );
        }

        qreal opacity = 1.0;
        qreal brushWidth = mCurrentPressure * mCurrentWidth;
        qreal brushStep = (0.5 * brushWidth) - ((properties.feather/100.0) * brushWidth * 0.5);
        brushStep = qMax( 1.0, brushStep );

        BlitRect rect;

        QPointF a = lastBrushPoint;
        QPointF b = getCurrentPoint();

        qreal distance = 4 * QLineF( b, a ).length();
        int steps = qRound( distance ) / brushStep;

        for ( int i = 0; i < steps; i++ )
        {
            QPointF point = lastBrushPoint + ( i + 1 ) * ( brushStep )* ( b - lastBrushPoint ) / distance;
            rect.extend( point.toPoint() );
            mScribbleArea->drawPen( point,
                                    brushWidth,
                                    mEditor->color()->frontColor(),
                                    opacity );

            if ( i == ( steps - 1 ) )
            {
                lastBrushPoint = point;
            }
        }

        int rad = qRound( brushWidth ) / 2 + 2;
        mScribbleArea->refreshBitmap( rect, rad );
    }
    else if ( layer->type() == Layer::VECTOR )
    {
        qreal brushWidth = mCurrentPressure * mCurrentWidth;
        int rad = qRound( ( brushWidth / 2 + 2 ) * mEditor->view()->scaling() );

        QPen pen( mEditor->color()->frontColor(),
                  brushWidth * mEditor->view()->scaling(),
                  Qt::SolidLine,
                  Qt::RoundCap,
                  Qt::RoundJoin );

        if ( p.size() == 4 )
        {
            QPainterPath path( p[ 0 ] );
            path.cubicTo( p[ 1 ],
                          p[ 2 ],
                          p[ 3 ] );
            mScribbleArea->drawPath( path, pen, Qt::NoBrush, QPainter::CompositionMode_Source );
            mScribbleArea->refreshVector( path.boundingRect().toRect(), rad );
        }
    }
}
开发者ID:linganesan,项目名称:pencil,代码行数:67,代码来源:pentool.cpp

示例3: SampleAnimations

static bool
SampleAnimations(Layer* aLayer, TimeStamp aPoint)
{
  AnimationArray& animations = aLayer->GetAnimations();
  InfallibleTArray<AnimData>& animationData = aLayer->GetAnimationData();

  bool activeAnimations = false;

  for (uint32_t i = animations.Length(); i-- !=0; ) {
    Animation& animation = animations[i];
    AnimData& animData = animationData[i];

    double numIterations = animation.numIterations() != -1 ?
      animation.numIterations() : NS_IEEEPositiveInfinity();
    double positionInIteration =
      ElementAnimations::GetPositionInIteration(aPoint - animation.startTime(),
                                                animation.duration(),
                                                numIterations,
                                                animation.direction());

    NS_ABORT_IF_FALSE(0.0 <= positionInIteration &&
                      positionInIteration <= 1.0,
                      "position should be in [0-1]");

    int segmentIndex = 0;
    AnimationSegment* segment = animation.segments().Elements();
    while (segment->endPortion() < positionInIteration) {
      ++segment;
      ++segmentIndex;
    }

    double positionInSegment = (positionInIteration - segment->startPortion()) /
                                 (segment->endPortion() - segment->startPortion());

    double portion = animData.mFunctions[segmentIndex]->GetValue(positionInSegment);

    activeAnimations = true;

    // interpolate the property
    Animatable interpolatedValue;
    SampleValue(portion, animation, animData.mStartValues[segmentIndex],
                animData.mEndValues[segmentIndex], &interpolatedValue);
    LayerComposite* layerComposite = aLayer->AsLayerComposite();
    switch (animation.property()) {
    case eCSSProperty_opacity:
    {
      layerComposite->SetShadowOpacity(interpolatedValue.get_float());
      break;
    }
    case eCSSProperty_transform:
    {
      gfx3DMatrix matrix = interpolatedValue.get_ArrayOfTransformFunction()[0].get_TransformMatrix().value();
      if (ContainerLayer* c = aLayer->AsContainerLayer()) {
        matrix.ScalePost(c->GetInheritedXScale(),
                         c->GetInheritedYScale(),
                         1);
      }
      layerComposite->SetShadowTransform(matrix);
      layerComposite->SetShadowTransformSetByAnimation(true);
      break;
    }
    default:
      NS_WARNING("Unhandled animated property");
    }
  }

  for (Layer* child = aLayer->GetFirstChild(); child;
       child = child->GetNextSibling()) {
    activeAnimations |= SampleAnimations(child, aPoint);
  }

  return activeAnimations;
}
开发者ID:Jaxo,项目名称:releases-mozilla-central,代码行数:73,代码来源:AsyncCompositionManager.cpp

示例4: switch

bool
CompositableParentManager::ReceiveCompositableUpdate(const CompositableOperation& aEdit,
                                                     EditReplyVector& replyv)
{
  switch (aEdit.type()) {
    case CompositableOperation::TOpCreatedIncrementalTexture: {
      MOZ_LAYERS_LOG(("[ParentSide] Created texture"));
      const OpCreatedIncrementalTexture& op = aEdit.get_OpCreatedIncrementalTexture();
      CompositableHost* compositable = AsCompositable(op);

      bool success =
        compositable->CreatedIncrementalTexture(this,
                                                op.textureInfo(),
                                                op.bufferRect());
      if (!success) {
        return false;
      }
      break;
    }
    case CompositableOperation::TOpPaintTextureRegion: {
      MOZ_LAYERS_LOG(("[ParentSide] Paint ThebesLayer"));

      const OpPaintTextureRegion& op = aEdit.get_OpPaintTextureRegion();
      CompositableHost* compositable = AsCompositable(op);
      Layer* layer = compositable->GetLayer();
      if (!layer || layer->GetType() != Layer::TYPE_THEBES) {
        return false;
      }
      ThebesLayerComposite* thebes = static_cast<ThebesLayerComposite*>(layer);

      const ThebesBufferData& bufferData = op.bufferData();

      RenderTraceInvalidateStart(thebes, "FF00FF", op.updatedRegion().GetBounds());

      nsIntRegion frontUpdatedRegion;
      if (!compositable->UpdateThebes(bufferData,
                                      op.updatedRegion(),
                                      thebes->GetValidRegion(),
                                      &frontUpdatedRegion))
      {
        return false;
      }
      replyv.push_back(
        OpContentBufferSwap(op.compositableParent(), nullptr, frontUpdatedRegion));

      RenderTraceInvalidateEnd(thebes, "FF00FF");
      break;
    }
    case CompositableOperation::TOpPaintTextureIncremental: {
      MOZ_LAYERS_LOG(("[ParentSide] Paint ThebesLayer"));

      const OpPaintTextureIncremental& op = aEdit.get_OpPaintTextureIncremental();

      CompositableHost* compositable = AsCompositable(op);

      SurfaceDescriptor desc = op.image();

      compositable->UpdateIncremental(op.textureId(),
                                      desc,
                                      op.updatedRegion(),
                                      op.bufferRect(),
                                      op.bufferRotation());
      break;
    }
    case CompositableOperation::TOpUpdatePictureRect: {
      const OpUpdatePictureRect& op = aEdit.get_OpUpdatePictureRect();
      CompositableHost* compositable = AsCompositable(op);
      MOZ_ASSERT(compositable);
      compositable->SetPictureRect(op.picture());
      break;
    }
    case CompositableOperation::TOpUseTiledLayerBuffer: {
      MOZ_LAYERS_LOG(("[ParentSide] Paint TiledLayerBuffer"));
      const OpUseTiledLayerBuffer& op = aEdit.get_OpUseTiledLayerBuffer();
      CompositableHost* compositable = AsCompositable(op);

      TiledLayerComposer* tileComposer = compositable->AsTiledLayerComposer();
      NS_ASSERTION(tileComposer, "compositable is not a tile composer");

      const SurfaceDescriptorTiles& tileDesc = op.tileLayerDescriptor();
      tileComposer->UseTiledLayerBuffer(this, tileDesc);
      break;
    }
    case CompositableOperation::TOpRemoveTexture: {
      const OpRemoveTexture& op = aEdit.get_OpRemoveTexture();
      CompositableHost* compositable = AsCompositable(op);
      RefPtr<TextureHost> tex = TextureHost::AsTextureHost(op.textureParent());

      MOZ_ASSERT(tex.get());
      compositable->RemoveTextureHost(tex);
      // send FenceHandle if present.
      TextureHost::SendFenceHandleIfPresent(op.textureParent());
      break;
    }
    case CompositableOperation::TOpRemoveTextureAsync: {
      const OpRemoveTextureAsync& op = aEdit.get_OpRemoveTextureAsync();
      CompositableHost* compositable = AsCompositable(op);
      RefPtr<TextureHost> tex = TextureHost::AsTextureHost(op.textureParent());

      MOZ_ASSERT(tex.get());
//.........这里部分代码省略.........
开发者ID:bebef1987,项目名称:gecko-dev,代码行数:101,代码来源:CompositableTransactionParent.cpp

示例5: getFrameNumber

void TimeLineCells::mousePressEvent( QMouseEvent* event )
{
    if ( primaryButton != Qt::NoButton ) return;
    int frameNumber = getFrameNumber( event->pos().x() );
    int layerNumber = getLayerNumber( event->pos().y() );

    startY = event->pos().y();
    startLayerNumber = layerNumber;
    endY = event->pos().y();

    startFrameNumber = frameNumber;
    lastFrameNumber = startFrameNumber;

    canMoveFrame    = false;
    movingFrames    = false;

    canBoxSelect    = false;
    boxSelecting    = false;

    clickSelecting  = false;

    primaryButton = event->button();

    mEditor->tools()->currentTool()->switchingLayers();
    switch ( m_eType )
    {
    case TIMELINE_CELL_TYPE::Layers:
        if ( layerNumber != -1 && layerNumber < mEditor->object()->getLayerCount() )
        {
            if ( event->pos().x() < 15 )
            {
                mEditor->switchVisibilityOfLayer( layerNumber );
            }
            else
            {
                mEditor->layers()->setCurrentLayer( layerNumber );
            }
        }
        if ( layerNumber == -1 )
        {
            if ( event->pos().x() < 15 )
            {
                mEditor->toggleShowAllLayers();
            }
        }
        break;
    case TIMELINE_CELL_TYPE::Tracks:
        if ( event->button() == Qt::MidButton )
        {
            lastFrameNumber = getFrameNumber( event->pos().x() );
        }
        else
        {
            if ( frameNumber == mEditor->currentFrame() && ( !shortScrub || ( shortScrub && startY < 20 ) ) )
            {
                if (mEditor->playback()->isPlaying())
                {
                    mEditor->playback()->stop();
                }
                timeLine->scrubbing = true;
            }
            else
            {
                if ( ( layerNumber != -1 ) && layerNumber < mEditor->object()->getLayerCount() )
                {
                    int previousLayerNumber = mEditor->layers()->currentLayerIndex();

                    if (previousLayerNumber != layerNumber) {
                        Layer *previousLayer = mEditor->object()->getLayer(previousLayerNumber);
                        previousLayer->deselectAll();

                        mEditor->setCurrentLayer( layerNumber );
                    }

                    Layer *currentLayer = mEditor->object()->getLayer(layerNumber);


                    // Check if we are using the alt key
                    //
                    if (event->modifiers() == Qt::AltModifier) {

                        // If it is the case, we select everything that is after the selected frame
                        //
                        clickSelecting = true;
                        canMoveFrame = true;

                        currentLayer->selectAllFramesAfter(frameNumber);

                    }
                    // Check if we are clicking on a non selected frame
                    //
                    else if (!currentLayer->isFrameSelected(frameNumber)) {

                        // If it is the case, we select it
                        //
                        canBoxSelect = true;
                        clickSelecting = true;

                        if ( event->modifiers() == Qt::ControlModifier ) {
                            // Add/remove from already selected
//.........这里部分代码省略.........
开发者ID:linganesan,项目名称:pencil,代码行数:101,代码来源:timelinecells.cpp

示例6: BuildViewMap

// Recursively create a new array of scrollables, preserving any scrollables
// that are still in the layer tree.
//
// aXScale and aYScale are used to calculate any values that need to be in
// chrome-document CSS pixels and aren't part of the rendering loop, such as
// the initial scroll offset for a new view.
static void
BuildViewMap(ViewMap& oldContentViews, ViewMap& newContentViews,
             nsFrameLoader* aFrameLoader, Layer* aLayer,
             float aXScale = 1, float aYScale = 1,
             float aAccConfigXScale = 1, float aAccConfigYScale = 1)
{
  ContainerLayer* container = aLayer->AsContainerLayer();
  if (!container)
    return;
  const FrameMetrics metrics = container->GetFrameMetrics();
  const ViewID scrollId = metrics.mScrollId;
  const gfx3DMatrix transform = aLayer->GetTransform();
  aXScale *= GetXScale(transform);
  aYScale *= GetYScale(transform);

  if (metrics.IsScrollable()) {
    nscoord auPerDevPixel = aFrameLoader->GetPrimaryFrameOfOwningContent()
                                        ->PresContext()->AppUnitsPerDevPixel();
    nsContentView* view = FindViewForId(oldContentViews, scrollId);
    if (view) {
      // View already exists. Be sure to propagate scales for any values
      // that need to be calculated something in chrome-doc CSS pixels.
      ViewConfig config = view->GetViewConfig();
      aXScale *= config.mXScale;
      aYScale *= config.mYScale;
      view->mFrameLoader = aFrameLoader;
      // If scale has changed, then we should update
      // current scroll offset to new scaled value
      if (aAccConfigXScale != view->mParentScaleX ||
          aAccConfigYScale != view->mParentScaleY) {
        float xscroll = 0, yscroll = 0;
        view->GetScrollX(&xscroll);
        view->GetScrollY(&yscroll);
        xscroll = xscroll * (aAccConfigXScale / view->mParentScaleX);
        yscroll = yscroll * (aAccConfigYScale / view->mParentScaleY);
        view->ScrollTo(xscroll, yscroll);
        view->mParentScaleX = aAccConfigXScale;
        view->mParentScaleY = aAccConfigYScale;
      }
      // Collect only config scale values for scroll compensation
      aAccConfigXScale *= config.mXScale;
      aAccConfigYScale *= config.mYScale;
    } else {
      // View doesn't exist, so generate one. We start the view scroll offset at
      // the same position as the framemetric's scroll offset from the layer.
      // The default scale is 1, so no need to propagate scale down.
      ViewConfig config;
      config.mScrollOffset = nsPoint(
        NSIntPixelsToAppUnits(metrics.mViewportScrollOffset.x, auPerDevPixel) * aXScale,
        NSIntPixelsToAppUnits(metrics.mViewportScrollOffset.y, auPerDevPixel) * aYScale);
      view = new nsContentView(aFrameLoader, scrollId, config);
      view->mParentScaleX = aAccConfigXScale;
      view->mParentScaleY = aAccConfigYScale;
    }

    view->mViewportSize = nsSize(
      NSIntPixelsToAppUnits(metrics.mViewport.width, auPerDevPixel) * aXScale,
      NSIntPixelsToAppUnits(metrics.mViewport.height, auPerDevPixel) * aYScale);
    view->mContentSize = nsSize(
      NSIntPixelsToAppUnits(metrics.mContentRect.width, auPerDevPixel) * aXScale,
      NSIntPixelsToAppUnits(metrics.mContentRect.height, auPerDevPixel) * aYScale);

    newContentViews[scrollId] = view;
  }

  for (Layer* child = aLayer->GetFirstChild();
       child; child = child->GetNextSibling()) {
    BuildViewMap(oldContentViews, newContentViews, aFrameLoader, child,
                 aXScale, aYScale, aAccConfigXScale, aAccConfigYScale);
  }
}
开发者ID:,项目名称:,代码行数:77,代码来源:

示例7: snprintf

// on "init" you need to initialize your instance
bool NewScene5::init()
{



    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    //eventos de teclado



    auto mni = MenuItemImage::create("bk.png","bk.png",CC_CALLBACK_1(NewScene5::btntouch, this));
    mni->setPosition(Point(origin.x + visibleSize.width - mni->getContentSize().width / 2, origin.y + mni->getContentSize().height / 2));
    auto mn = Menu::create(mni,NULL);
    mn->setPosition(Point::ZERO);
    this->addChild(mn);


    Menu* menu = Menu::create();

    const int MAX_ITEMS = 20;
    const int BASE_TAG = 100;
    const int HEIGHT = 40;

    char menuName[20];
    for (int i = 0; i < MAX_ITEMS; i++)
    {
        snprintf(menuName, sizeof(menuName), "ITEM %d", i);
        Node* menuLabel = LabelTTF::create(menuName, "Arial", 24);
        Size menuSize = menuLabel->getContentSize();

        MenuItem* menuItem = MenuItemLabel::create(menuLabel, CC_CALLBACK_1(NewScene5::menuItemCallback, this));
        menuItem->setTag(BASE_TAG+i);
        menuItem->setPosition(Vec2(0, (MAX_ITEMS-i)*HEIGHT - visibleSize.height/2));

        menu->addChild(menuItem);
    }



    Rect rect(0, -HEIGHT, 100, MAX_ITEMS * HEIGHT);


    // Setup scroll container
    Layer* scrollContainer = Layer::create();
    scrollContainer->addChild(menu);

    Size contentSize(rect.size.width-rect.origin.x, rect.size.height-rect.origin.y);
    scrollContainer->setContentSize(contentSize);


    // Setup scroll view
    extension::ScrollView* scrollView = extension::ScrollView::create(visibleSize, scrollContainer);
    scrollView->setBounceable(true);
    scrollView->setDirection(extension::ScrollView::Direction::VERTICAL);

    // Scroll to bottom
    scrollView->setContentOffset( Point::ZERO, true );

    this->addChild(scrollView);




    this->setKeyboardEnabled(true);




    return true;
}
开发者ID:Johan08,项目名称:cocos2d-x-3.2-ui-,代码行数:80,代码来源:NewScene5.cpp

示例8: CHECK

void Net<Dtype>::appendParam(const NetParameter& param, const int layer_id, const int param_id){
	const LayerParameter& layer_param = param.layer(layer_id);
	Layer<Dtype>* layer = layers[layer_id].get();
	const int param_size = layer_param.param_size();
	//	default name="" (not set)
	string param_name = param_id<param_size? layer_param.param(param_id).name() : "";
	//	has name
	if (param_name.size()) param_display_names.push_back(param_name);
	//	set param_id as name
	else{
		ostringstream display_name;
		display_name << param_id;
		param_display_names.push_back(display_name.str());
	}
	//	each param blob has a net id(both weight and bias)
	const int net_param_id = param_blobs.size();
	//	add param blob which can be used by a net id
	param_blobs.push_back(layer->getBlobs()[param_id]);
	//	store a net id
	//	param_id_vecs[layer_id][param_id] can get the net_param_id
	param_id_vecs[layer_id].push_back(net_param_id);
	//	store orginal id ( x_th layer/ y_th param )
	//	param_layer_indices[net_param_id] can get layer_id/param_id
	param_layer_indices.push_back(make_pair(layer_id, param_id));
	ParamSpec default_hyperparameter;
	const ParamSpec* hyperparameter = param_id < param_size ?
		&layer_param.param(param_id) : &default_hyperparameter;
	//	do not have a name or
	if (!param_size || !param_name.size() ||
		(param_name.size() && !param_names_index.count(param_name))){
		param_owners.push_back(-1);
		//	has a name(non-empty) but has not logged before
		if (param_name.size()) param_names_index[param_name] = net_param_id;
		const int learnable_param_id = learnable_params.size();
		learnable_params.push_back(param_blobs[net_param_id].get());
		learnable_param_ids.push_back(learnable_param_id);
		has_params_lr.push_back(hyperparameter->has_lr_mult());
		has_params_decay.push_back(hyperparameter->has_decay_mult());
		params_lr.push_back(hyperparameter->lr_mult());
		params_decay.push_back(hyperparameter->decay_mult());
	}
	else{
		//	has a name(non-empty) and has logged before
		//	it means to share this param and we need get the owner id
		const int owner_net_param_id = param_names_index[param_name];
		param_owners.push_back(owner_net_param_id);
		const pair<int, int>& owner_index = param_layer_indices[owner_net_param_id];
		const int owner_layer_id = owner_index.first;
		const int owner_param_id = owner_index.second;
		LOG_IF(INFO, Dragon::get_root_solver())
			<< "Share parameter: " << param_name << " ownd by layer: "
			<< layer_names[owner_layer_id] << " param index: " << owner_layer_id;
		Blob<Dtype>* this_blob = param_blobs[net_param_id].get();
		Blob<Dtype>* owner_blob = param_blobs[owner_net_param_id].get();
		CHECK(this_blob);CHECK(owner_blob);
		//	check before sharing
		if (layer_param.param(param_id).share_mode() == ParamSpec_DimCheckMode_PERMISSIVE_MODE)
			CHECK_EQ(this_blob->count(), owner_blob->count());
		else CHECK(this_blob->shape() == owner_blob->shape());
		//	note that learnable_param_id = owner_net_param_id
		const int learnable_param_id = learnable_param_ids[owner_net_param_id];
		//	store parent id
		learnable_param_ids.push_back(learnable_param_id);
		//	check lr_mult
		if (hyperparameter->has_lr_mult()){
			if (has_params_lr[learnable_param_id])
				CHECK_EQ(hyperparameter->lr_mult(), params_lr[learnable_param_id])
				<< "Shared param: " << param_name << " has mismatched lr_mult.";
			else{
				has_params_lr[learnable_param_id] = true;
				params_lr[learnable_param_id] = hyperparameter->lr_mult();
			}
		}
		//	check decay_mult
		if (hyperparameter->has_decay_mult()){
			if (has_params_decay[learnable_param_id])
				CHECK_EQ(hyperparameter->decay_mult(), params_decay[learnable_param_id])
				<< "Shared param: " << param_name << " has mismatched decay_mult.";
			else{
				has_params_decay[learnable_param_id] = true;
				params_decay[learnable_param_id] = hyperparameter->decay_mult();
			}
		}
	}
}
开发者ID:qianxinchun,项目名称:Dragon,代码行数:85,代码来源:net.cpp

示例9: CCASSERT

bool WindowProtocol::init(){
    bool ret = false;
    
    //super init
    if(!Layer::init())
        return ret;
    
    //Put blocker
    Layer* blocker = LayerColor::create(Color4B(0, 0, 0, 255*0.5), VisibleRect::getVisibleRect().size.width, VisibleRect::getVisibleRect().size.height);
    blocker->setAnchorPoint(Vec2::ZERO);
    blocker->setPosition(Vec2(VisibleRect::getVisibleRect().origin.x, VisibleRect::getVisibleRect().origin.y));
    
    //Base window
    _baseWindow = Scale9Sprite::createWithSpriteFrameName("WindowBase.psd",BASE_WINDOW_INSET_RECT);
    _baseWindow->setContentSize(Size(850,490-10-10));
    _baseWindow->setAnchorPoint(Vec2(0.0, 1.0));
    _baseWindow->setPosition(Vec2(55, VisibleRect::getVisibleRect().size.height-60));
    
    //Put base window
    _baseLayout = Layout::create();
    CCASSERT(_baseLayout!=nullptr, "_baseLayout cannot be null.");
    _baseLayout->setLayoutType(Layout::Type::VERTICAL);
    _baseLayout->setContentSize(_baseWindow->getCapInsets().size);
    _baseLayout->setAnchorPoint(Vec2(0.0, 1.0));
    _baseLayout->setPosition(Vec2(2,_baseWindow->getContentSize().height-2));
    //PutLayout on sprite
    _baseWindow->addChild(_baseLayout,0);
    
    //---Title---
    //Layout
    _titleLayout = Layout::create();
    CCASSERT(_titleLayout!=nullptr, "_titleLayer cannot be null.");
    //_titleLayout->setAnchorPoint(Vec2(0.0, 1.0));
    _titleLayout->setLayoutType(Layout::Type::HORIZONTAL);
    _titleLayout->setContentSize(Size(850-2*2, 55));
    _titleLayout->setPosition(Vec2(_baseLayout->getContentSize().width/2, _baseLayout->getContentSize().height/2));
    //set baseTitle as titleLayout background
    //No longer need title base image...
    _titleLayout->setBackGroundColorType(Layout::BackGroundColorType::SOLID);
    _titleLayout->setBackGroundColor(Color3B(200, 200, 169));
    //Close Button
    LinearLayoutParameter* lpCloseButton = LinearLayoutParameter::create();
    _closeButton = Button::create("MainUI_Windows_Close_Normal.png","MainUI_Windows_Close_Pressed.png","",TextureResType::PLIST);
    CCASSERT(_closeButton!=nullptr, "_closeButton cannot be null.");
    _closeButton->setPosition(Vec2(_titleLayout->getContentSize().width/2, _titleLayout->getContentSize().height/2));
    lpCloseButton->setGravity(LinearLayoutParameter::LinearGravity::LEFT);
    lpCloseButton->setMargin(Margin(0, 0, 0, 0));
    _closeButton->setLayoutParameter(lpCloseButton);
    if(_closeCallback!=nullptr)
        _closeButton->addTouchEventListener(_closeCallback);
    
    //Title text
    LinearLayoutParameter* lpTitleText = LinearLayoutParameter::create();
    _titleText = Text::create(_titleString, "fonts/Apple_LiGothic_Medium.ttf", computeFontSize(42));
    CCASSERT(_titleText!=nullptr, "_titletext cannot be null.");
    _titleText->setColor(Color3B(59,134,134));
    _titleText->setPosition(Vec2(_titleLayout->getContentSize().width/2, _titleLayout->getContentSize().height/2));
    lpTitleText->setGravity(LinearLayoutParameter::LinearGravity::CENTER_VERTICAL);
    lpTitleText->setMargin(Margin(_titleLayout->getContentSize().width/2-_titleText->getContentSize().width/2-_closeButton->getContentSize().width, 0, 0, 0));
    _titleText->setLayoutParameter(lpTitleText);
    
    
    //Add component to title layout
    _titleLayout->addChild(_closeButton,1);
    _titleLayout->addChild(_titleText,2);
    
    //---add to base layout---
    _baseLayout->addChild(_titleLayout);
    
    //setBlockerTouchDispatcher
    auto touchBlocker = EventListenerTouchOneByOne::create();
    touchBlocker->setSwallowTouches(true);
    //lambda decide later
    touchBlocker->onTouchBegan= [](Touch* touch,Event* e){
        return true;
    };
    _eventDispatcher->addEventListenerWithSceneGraphPriority(touchBlocker, blocker);
    
    //addChild
    addChild(blocker,0);
    addChild(_baseWindow,1);
    
    ret = true;
    return ret;
}
开发者ID:visualcshape,项目名称:Parallelformosa,代码行数:85,代码来源:WindowProtocol.cpp

示例10: GetEffectiveTransform

void
ClientTiledThebesLayer::BeginPaint()
{
  if (ClientManager()->IsRepeatTransaction()) {
    return;
  }

  mPaintData.mLowPrecisionPaintCount = 0;
  mPaintData.mPaintFinished = false;

  // Calculate the transform required to convert screen space into layer space
  mPaintData.mTransformScreenToLayer = GetEffectiveTransform();
  // XXX Not sure if this code for intermediate surfaces is correct.
  //     It rarely gets hit though, and shouldn't have terrible consequences
  //     even if it is wrong.
  for (ContainerLayer* parent = GetParent(); parent; parent = parent->GetParent()) {
    if (parent->UseIntermediateSurface()) {
      mPaintData.mTransformScreenToLayer.PreMultiply(parent->GetEffectiveTransform());
    }
  }
  mPaintData.mTransformScreenToLayer.Invert();

  // Compute the critical display port in layer space.
  mPaintData.mLayerCriticalDisplayPort.SetEmpty();
  const gfx::Rect& criticalDisplayPort = GetParent()->GetFrameMetrics().mCriticalDisplayPort;
  if (!criticalDisplayPort.IsEmpty()) {
    gfxRect transformedCriticalDisplayPort =
      mPaintData.mTransformScreenToLayer.TransformBounds(
        gfxRect(criticalDisplayPort.x, criticalDisplayPort.y,
                criticalDisplayPort.width, criticalDisplayPort.height));
    transformedCriticalDisplayPort.RoundOut();
    mPaintData.mLayerCriticalDisplayPort = nsIntRect(transformedCriticalDisplayPort.x,
                                             transformedCriticalDisplayPort.y,
                                             transformedCriticalDisplayPort.width,
                                             transformedCriticalDisplayPort.height);
  }

  // Calculate the frame resolution.
  mPaintData.mResolution.SizeTo(1, 1);
  for (ContainerLayer* parent = GetParent(); parent; parent = parent->GetParent()) {
    const FrameMetrics& metrics = parent->GetFrameMetrics();
    mPaintData.mResolution.width *= metrics.mResolution.width;
    mPaintData.mResolution.height *= metrics.mResolution.height;
  }

  // Calculate the scroll offset since the last transaction, and the
  // composition bounds.
  mPaintData.mCompositionBounds.SetEmpty();
  mPaintData.mScrollOffset.MoveTo(0, 0);
  Layer* primaryScrollable = ClientManager()->GetPrimaryScrollableLayer();
  if (primaryScrollable) {
    const FrameMetrics& metrics = primaryScrollable->AsContainerLayer()->GetFrameMetrics();
    mPaintData.mScrollOffset = metrics.mScrollOffset;
    gfxRect transformedViewport = mPaintData.mTransformScreenToLayer.TransformBounds(
      gfxRect(metrics.mCompositionBounds.x, metrics.mCompositionBounds.y,
              metrics.mCompositionBounds.width, metrics.mCompositionBounds.height));
    transformedViewport.RoundOut();
    mPaintData.mCompositionBounds =
      nsIntRect(transformedViewport.x, transformedViewport.y,
                transformedViewport.width, transformedViewport.height);
  }
}
开发者ID:RickEyre,项目名称:mozilla-central,代码行数:62,代码来源:ClientTiledThebesLayer.cpp

示例11: ComputeChangeInternal

  virtual nsIntRegion ComputeChangeInternal(NotifySubDocInvalidationFunc aCallback,
                                            bool& aGeometryChanged)
  {
    ContainerLayer* container = mLayer->AsContainerLayer();
    nsIntRegion result;

    bool childrenChanged = false;

    if (mPreXScale != container->GetPreXScale() ||
        mPreYScale != container->GetPreYScale()) {
      aGeometryChanged = true;
      result = OldTransformedBounds();
      AddRegion(result, NewTransformedBounds());
      childrenChanged = true;

      // Can't bail out early, we need to update the child container layers
    }

    // A low frame rate is especially visible to users when scrolling, so we
    // particularly want to avoid unnecessary invalidation at that time. For us
    // here, that means avoiding unnecessary invalidation of child items when
    // other children are added to or removed from our container layer, since
    // that may be caused by children being scrolled in or out of view. We are
    // less concerned with children changing order.
    // TODO: Consider how we could avoid unnecessary invalidation when children
    // change order, and whether the overhead would be worth it.

    nsDataHashtable<nsPtrHashKey<Layer>, uint32_t> oldIndexMap(mChildren.Length());
    for (uint32_t i = 0; i < mChildren.Length(); ++i) {
      oldIndexMap.Put(mChildren[i]->mLayer, i);
    }

    uint32_t i = 0; // cursor into the old child list mChildren
    for (Layer* child = container->GetFirstChild(); child; child = child->GetNextSibling()) {
      bool invalidateChildsCurrentArea = false;
      if (i < mChildren.Length()) {
        uint32_t childsOldIndex;
        if (oldIndexMap.Get(child, &childsOldIndex)) {
          if (childsOldIndex >= i) {
            // Invalidate the old areas of layers that used to be between the
            // current |child| and the previous |child| that was also in the
            // old list mChildren (if any of those children have been reordered
            // rather than removed, we will invalidate their new area when we
            // encounter them in the new list):
            for (uint32_t j = i; j < childsOldIndex; ++j) {
              AddRegion(result, mChildren[j]->OldTransformedBounds());
              childrenChanged |= true;
            }
            // Invalidate any regions of the child that have changed:
            nsIntRegion region = mChildren[childsOldIndex]->ComputeChange(aCallback, aGeometryChanged);
            i = childsOldIndex + 1;
            if (!region.IsEmpty()) {
              AddRegion(result, region);
              childrenChanged |= true;
            }
          } else {
            // We've already seen this child in mChildren (which means it must
            // have been reordered) and invalidated its old area. We need to
            // invalidate its new area too:
            invalidateChildsCurrentArea = true;
          }
        } else {
          // |child| is new
          invalidateChildsCurrentArea = true;
        }
      } else {
        // |child| is new, or was reordered to a higher index
        invalidateChildsCurrentArea = true;
      }
      if (invalidateChildsCurrentArea) {
        aGeometryChanged = true;
        AddTransformedRegion(result, child->GetVisibleRegion(), child->GetLocalTransform());
        if (aCallback) {
          NotifySubdocumentInvalidationRecursive(child, aCallback);
        } else {
          ClearInvalidations(child);
        }
      }
      childrenChanged |= invalidateChildsCurrentArea;
    }

    // Process remaining removed children.
    while (i < mChildren.Length()) {
      childrenChanged |= true;
      AddRegion(result, mChildren[i]->OldTransformedBounds());
      i++;
    }

    if (aCallback) {
      aCallback(container, result);
    }

    if (childrenChanged) {
      container->SetChildrenChanged(true);
    }

    result.Transform(gfx::To3DMatrix(mLayer->GetLocalTransform()));

    return result;
  }
开发者ID:AtulKumar2,项目名称:gecko-dev,代码行数:100,代码来源:LayerTreeInvalidation.cpp

示例12: Create

  /**
   * Invoked upon creation of application
   * @param[in] application The application instance
   */
  void Create( Application& application )
  {
    Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleController::OnKeyEvent);

    mStageSize = Stage::GetCurrent().GetSize();

    // The Init signal is received once (only) during the Application lifetime

    // Hide the indicator bar
    application.GetWindow().ShowIndicator( Dali::Window::INVISIBLE );

    // Creates a default view with a default tool bar.
    // The view is added to the stage.
    Toolkit::ToolBar toolBar;
    mContent = DemoHelper::CreateView( application,
                                       mView,
                                       toolBar,
                                       BACKGROUND_IMAGE,
                                       TOOLBAR_IMAGE,
                                       APPLICATION_TITLE );

    mContent.SetLeaveRequired(true);
    mContent.TouchSignal().Connect( this, &ExampleController::OnTouched );

    // Create magnifier (controlled by human touch)
    Layer overlay = Layer::New();
    overlay.SetSensitive(false);
    overlay.SetParentOrigin( ParentOrigin::CENTER );
    overlay.SetSize(mStageSize);
    Stage::GetCurrent().Add(overlay);

    mMagnifier = Toolkit::Magnifier::New();
    mMagnifier.SetSourceActor( mView );
    mMagnifier.SetSize( MAGNIFIER_SIZE * mStageSize.width );  // Size of magnifier is in relation to stage width
    mMagnifier.SetProperty( Toolkit::Magnifier::Property::MAGNIFICATION_FACTOR, MAGNIFICATION_FACTOR );
    mMagnifier.SetScale(Vector3::ZERO);
    overlay.Add( mMagnifier );

    // Apply constraint to animate the position of the magnifier.
    Constraint constraint = Constraint::New<Vector3>( mMagnifier, Actor::Property::POSITION, ConfinementConstraint(Vector3( 0.5f, 0.5f, 0.0f ), Vector2::ONE * MAGNIFIER_INDENT, Vector2::ONE * MAGNIFIER_INDENT) );
    constraint.AddSource( LocalSource(Actor::Property::SIZE) );
    constraint.AddSource( LocalSource(Actor::Property::PARENT_ORIGIN) );
    constraint.AddSource( LocalSource(Actor::Property::ANCHOR_POINT) );
    constraint.AddSource( ParentSource(Actor::Property::SIZE) );
    constraint.SetRemoveAction(Constraint::Discard);
    constraint.Apply();

    // Create bouncing magnifier automatically bounces around screen.
    mBouncingMagnifier = Toolkit::Magnifier::New();
    mBouncingMagnifier.SetSourceActor( mView );
    mBouncingMagnifier.SetSize( MAGNIFIER_SIZE * mStageSize.width ); // Size of magnifier is in relation to stage width
    mBouncingMagnifier.SetProperty( Toolkit::Magnifier::Property::MAGNIFICATION_FACTOR, MAGNIFICATION_FACTOR );
    overlay.Add( mBouncingMagnifier );

    mAnimationTimeProperty = mBouncingMagnifier.RegisterProperty("animationTime",  0.0f);
    ContinueAnimation();

    // Apply constraint to animate the position of the magnifier.
    constraint = Constraint::New<Vector3>( mBouncingMagnifier, Actor::Property::POSITION, MagnifierPathConstraint(mStageSize, mStageSize * 0.5f) );
    constraint.AddSource( LocalSource(Actor::Property::SIZE) );
    constraint.AddSource( LocalSource(mAnimationTimeProperty) );
    constraint.Apply();

    // Apply constraint to animate the source of the magnifier.
    constraint = Constraint::New<Vector3>( mBouncingMagnifier, Toolkit::Magnifier::Property::SOURCE_POSITION, MagnifierPathConstraint(mStageSize) );
    constraint.AddSource( LocalSource(Actor::Property::SIZE) );
    constraint.AddSource( LocalSource(mAnimationTimeProperty) );
    constraint.Apply();
  }
开发者ID:tizenorg,项目名称:platform.core.uifw.dali-demo,代码行数:73,代码来源:magnifier-example.cpp

示例13: ComputeRenderIntegrityInternal

/* static */ void
LayerManagerComposite::ComputeRenderIntegrityInternal(Layer* aLayer,
                                                      nsIntRegion& aScreenRegion,
                                                      nsIntRegion& aLowPrecisionScreenRegion,
                                                      const Matrix4x4& aTransform)
{
  if (aLayer->GetOpacity() <= 0.f ||
      (aScreenRegion.IsEmpty() && aLowPrecisionScreenRegion.IsEmpty())) {
    return;
  }

  // If the layer's a container, recurse into all of its children
  ContainerLayer* container = aLayer->AsContainerLayer();
  if (container) {
    // Accumulate the transform of intermediate surfaces
    Matrix4x4 transform = aTransform;
    if (container->UseIntermediateSurface()) {
      transform = aLayer->GetEffectiveTransform();
      transform = aTransform * transform;
    }
    for (Layer* child = aLayer->GetFirstChild(); child;
         child = child->GetNextSibling()) {
      ComputeRenderIntegrityInternal(child, aScreenRegion, aLowPrecisionScreenRegion, transform);
    }
    return;
  }

  // Only painted layers can be incomplete
  PaintedLayer* paintedLayer = aLayer->AsPaintedLayer();
  if (!paintedLayer) {
    return;
  }

  // See if there's any incomplete rendering
  nsIntRegion incompleteRegion = aLayer->GetEffectiveVisibleRegion();
  incompleteRegion.Sub(incompleteRegion, paintedLayer->GetValidRegion());

  if (!incompleteRegion.IsEmpty()) {
    // Calculate the transform to get between screen and layer space
    Matrix4x4 transformToScreen = aLayer->GetEffectiveTransform();
    transformToScreen = aTransform * transformToScreen;

    SubtractTransformedRegion(aScreenRegion, incompleteRegion, transformToScreen);

    // See if there's any incomplete low-precision rendering
    TiledContentHost* composer = nullptr;
    LayerComposite* shadow = aLayer->AsLayerComposite();
    if (shadow) {
      composer = shadow->GetCompositableHost()->AsTiledContentHost();
      if (composer) {
        incompleteRegion.Sub(incompleteRegion, composer->GetValidLowPrecisionRegion());
        if (!incompleteRegion.IsEmpty()) {
          SubtractTransformedRegion(aLowPrecisionScreenRegion, incompleteRegion, transformToScreen);
        }
      }
    }

    // If we can't get a valid low precision region, assume it's the same as
    // the high precision region.
    if (!composer) {
      SubtractTransformedRegion(aLowPrecisionScreenRegion, incompleteRegion, transformToScreen);
    }
  }
}
开发者ID:rtrsparq,项目名称:gecko-dev,代码行数:64,代码来源:LayerManagerComposite.cpp

示例14: MOZ_LAYERS_LOG

bool
ShadowLayersParent::RecvUpdate(const InfallibleTArray<Edit>& cset,
                               const TargetConfig& targetConfig,
                               const bool& isFirstPaint,
                               InfallibleTArray<EditReply>* reply)
{
#ifdef COMPOSITOR_PERFORMANCE_WARNING
  TimeStamp updateStart = TimeStamp::Now();
#endif

  MOZ_LAYERS_LOG(("[ParentSide] received txn with %d edits", cset.Length()));

  if (mDestroyed || layer_manager()->IsDestroyed()) {
    return true;
  }

  EditReplyVector replyv;

  layer_manager()->BeginTransactionWithTarget(NULL);

  for (EditArray::index_type i = 0; i < cset.Length(); ++i) {
    const Edit& edit = cset[i];

    switch (edit.type()) {
      // Create* ops
    case Edit::TOpCreateThebesLayer: {
      MOZ_LAYERS_LOG(("[ParentSide] CreateThebesLayer"));

      nsRefPtr<ShadowThebesLayer> layer =
        layer_manager()->CreateShadowThebesLayer();
      layer->SetAllocator(this);
      AsShadowLayer(edit.get_OpCreateThebesLayer())->Bind(layer);
      break;
    }
    case Edit::TOpCreateContainerLayer: {
      MOZ_LAYERS_LOG(("[ParentSide] CreateContainerLayer"));

      nsRefPtr<ContainerLayer> layer = layer_manager()->CreateShadowContainerLayer();
      AsShadowLayer(edit.get_OpCreateContainerLayer())->Bind(layer);
      break;
    }
    case Edit::TOpCreateImageLayer: {
      MOZ_LAYERS_LOG(("[ParentSide] CreateImageLayer"));

      nsRefPtr<ShadowImageLayer> layer =
        layer_manager()->CreateShadowImageLayer();
      AsShadowLayer(edit.get_OpCreateImageLayer())->Bind(layer);
      break;
    }
    case Edit::TOpCreateColorLayer: {
      MOZ_LAYERS_LOG(("[ParentSide] CreateColorLayer"));

      nsRefPtr<ShadowColorLayer> layer = layer_manager()->CreateShadowColorLayer();
      AsShadowLayer(edit.get_OpCreateColorLayer())->Bind(layer);
      break;
    }
    case Edit::TOpCreateCanvasLayer: {
      MOZ_LAYERS_LOG(("[ParentSide] CreateCanvasLayer"));

      nsRefPtr<ShadowCanvasLayer> layer = 
        layer_manager()->CreateShadowCanvasLayer();
      layer->SetAllocator(this);
      AsShadowLayer(edit.get_OpCreateCanvasLayer())->Bind(layer);
      break;
    }
    case Edit::TOpCreateRefLayer: {
      MOZ_LAYERS_LOG(("[ParentSide] CreateRefLayer"));

      nsRefPtr<ShadowRefLayer> layer =
        layer_manager()->CreateShadowRefLayer();
      layer->SetAllocator(this);
      AsShadowLayer(edit.get_OpCreateRefLayer())->Bind(layer);
      break;
    }

      // Attributes
    case Edit::TOpSetLayerAttributes: {
      MOZ_LAYERS_LOG(("[ParentSide] SetLayerAttributes"));

      const OpSetLayerAttributes& osla = edit.get_OpSetLayerAttributes();
      Layer* layer = AsShadowLayer(osla)->AsLayer();
      const LayerAttributes& attrs = osla.attrs();

      const CommonLayerAttributes& common = attrs.common();
      layer->SetVisibleRegion(common.visibleRegion());
      layer->SetContentFlags(common.contentFlags());
      layer->SetOpacity(common.opacity());
      layer->SetClipRect(common.useClipRect() ? &common.clipRect() : NULL);
      layer->SetBaseTransform(common.transform().value());
      layer->SetPostScale(common.postXScale(), common.postYScale());
      static bool fixedPositionLayersEnabled = getenv("MOZ_ENABLE_FIXED_POSITION_LAYERS") != 0;
      if (fixedPositionLayersEnabled) {
        layer->SetIsFixedPosition(common.isFixedPosition());
        layer->SetFixedPositionAnchor(common.fixedPositionAnchor());
      }
      if (PLayerParent* maskLayer = common.maskLayerParent()) {
        layer->SetMaskLayer(cast(maskLayer)->AsLayer());
      } else {
        layer->SetMaskLayer(NULL);
      }
//.........这里部分代码省略.........
开发者ID:LyeSS,项目名称:mozilla-central,代码行数:101,代码来源:ShadowLayersParent.cpp

示例15: TransformShadowTree

// Go down shadow layer tree and apply transformations for scrollable layers.
static void
TransformShadowTree(nsDisplayListBuilder* aBuilder, nsFrameLoader* aFrameLoader,
                    nsIFrame* aFrame, Layer* aLayer,
                    const ViewTransform& aTransform,
                    float aTempScaleDiffX = 1.0,
                    float aTempScaleDiffY = 1.0)
{
  ShadowLayer* shadow = aLayer->AsShadowLayer();
  shadow->SetShadowClipRect(aLayer->GetClipRect());
  shadow->SetShadowVisibleRegion(aLayer->GetVisibleRegion());
  shadow->SetShadowOpacity(aLayer->GetOpacity());

  const FrameMetrics* metrics = GetFrameMetrics(aLayer);

  gfx3DMatrix shadowTransform = aLayer->GetTransform();
  ViewTransform layerTransform = aTransform;

  if (metrics && metrics->IsScrollable()) {
    const ViewID scrollId = metrics->mScrollId;
    const nsContentView* view =
      aFrameLoader->GetCurrentRemoteFrame()->GetContentView(scrollId);
    NS_ABORT_IF_FALSE(view, "Array of views should be consistent with layer tree");
    const gfx3DMatrix& currentTransform = aLayer->GetTransform();

    const ViewConfig& config = view->GetViewConfig();
    // With temporary scale we should compensate translation
    // using temporary scale value
    aTempScaleDiffX *= GetXScale(shadowTransform) * config.mXScale;
    aTempScaleDiffY *= GetYScale(shadowTransform) * config.mYScale;
    ViewTransform viewTransform = ComputeShadowTreeTransform(
      aFrame, aFrameLoader, metrics, view->GetViewConfig(),
      aTempScaleDiffX, aTempScaleDiffY
    );

    // Apply the layer's own transform *before* the view transform
    shadowTransform = gfx3DMatrix(viewTransform) * currentTransform;

    layerTransform = viewTransform;
    if (metrics->IsRootScrollable()) {
      // Apply the root frame translation *before* we do the rest of the transforms.
      nsIntPoint rootFrameOffset = GetRootFrameOffset(aFrame, aBuilder);
      shadowTransform = shadowTransform *
          gfx3DMatrix::Translation(float(rootFrameOffset.x), float(rootFrameOffset.y), 0.0);
    }
  }

  if (aLayer->GetIsFixedPosition() &&
      !aLayer->GetParent()->GetIsFixedPosition()) {
    // Alter the shadow transform of fixed position layers in the situation
    // that the view transform's scroll position doesn't match the actual
    // scroll position, due to asynchronous layer scrolling.
    float offsetX = layerTransform.mTranslation.x / layerTransform.mXScale;
    float offsetY = layerTransform.mTranslation.y / layerTransform.mYScale;
    ReverseTranslate(shadowTransform, gfxPoint(offsetX, offsetY));
    const nsIntRect* clipRect = shadow->GetShadowClipRect();
    if (clipRect) {
      nsIntRect transformedClipRect(*clipRect);
      transformedClipRect.MoveBy(-offsetX, -offsetY);
      shadow->SetShadowClipRect(&transformedClipRect);
    }
  }

  // The transform already takes the resolution scale into account.  Since we
  // will apply the resolution scale again when computing the effective
  // transform, we must apply the inverse resolution scale here.
  if (ContainerLayer* c = aLayer->AsContainerLayer()) {
    shadowTransform.Scale(1.0f/c->GetPreXScale(),
                          1.0f/c->GetPreYScale(),
                          1);
  }
  shadowTransform.ScalePost(1.0f/aLayer->GetPostXScale(),
                            1.0f/aLayer->GetPostYScale(),
                            1);

  shadow->SetShadowTransform(shadowTransform);
  for (Layer* child = aLayer->GetFirstChild();
       child; child = child->GetNextSibling()) {
    TransformShadowTree(aBuilder, aFrameLoader, aFrame, child, layerTransform,
                        aTempScaleDiffX, aTempScaleDiffY);
  }
}
开发者ID:,项目名称:,代码行数:82,代码来源:


注:本文中的Layer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。