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; } return 1.f; }
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 ); } } }
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; }
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()); compositable->RemoveTextureHost(tex); if (!IsAsync() && GetChildProcessId()) { // send FenceHandle if present via ImageBridge. ImageBridgeParent::SendFenceHandleToTrackerIfPresent( GetChildProcessId(), op.holderId(), op.transactionId(), op.textureParent()); // If the message is recievied via PLayerTransaction, // Send message back via PImageBridge. ImageBridgeParent::ReplyRemoveTexture( GetChildProcessId(), OpReplyRemoveTexture(true, // isMain op.holderId(), op.transactionId())); } else { // send FenceHandle if present. TextureHost::SendFenceHandleIfPresent(op.textureParent()); ReplyRemoveTexture(OpReplyRemoveTexture(false, // isMain op.holderId(), op.transactionId())); } break; } case CompositableOperation::TOpUseTexture: { const OpUseTexture& op = aEdit.get_OpUseTexture(); CompositableHost* compositable = AsCompositable(op); RefPtr<TextureHost> tex = TextureHost::AsTextureHost(op.textureParent()); MOZ_ASSERT(tex.get()); compositable->UseTextureHost(tex); if (IsAsync()) { ScheduleComposition(op); // Async layer updates don't trigger invalidation, manually tell the layer // that its content have changed. if (compositable->GetLayer()) { compositable->GetLayer()->SetInvalidRectToVisibleRegion(); } } break; } case CompositableOperation::TOpUseComponentAlphaTextures: { const OpUseComponentAlphaTextures& op = aEdit.get_OpUseComponentAlphaTextures(); CompositableHost* compositable = AsCompositable(op); RefPtr<TextureHost> texOnBlack = TextureHost::AsTextureHost(op.textureOnBlackParent()); RefPtr<TextureHost> texOnWhite = TextureHost::AsTextureHost(op.textureOnWhiteParent()); MOZ_ASSERT(texOnBlack && texOnWhite); compositable->UseComponentAlphaTextures(texOnBlack, texOnWhite); if (IsAsync()) { ScheduleComposition(op); } break; } #ifdef MOZ_WIDGET_GONK case CompositableOperation::TOpUseOverlaySource: { const OpUseOverlaySource& op = aEdit.get_OpUseOverlaySource(); CompositableHost* compositable = AsCompositable(op); MOZ_ASSERT(compositable->GetType() == CompositableType::IMAGE_OVERLAY, "Invalid operation!"); compositable->UseOverlaySource(op.overlay()); break; } #endif case CompositableOperation::TOpUpdateTexture: { const OpUpdateTexture& op = aEdit.get_OpUpdateTexture(); RefPtr<TextureHost> texture = TextureHost::AsTextureHost(op.textureParent()); MOZ_ASSERT(texture); texture->Updated(op.region().type() == MaybeRegion::TnsIntRegion ? &op.region().get_nsIntRegion() : nullptr); // no region means invalidate the entire surface break; } default: { MOZ_ASSERT(false, "bad type"); } } return true; }
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 currentLayer->toggleFrameSelected(frameNumber, true); } else if ( event->modifiers() == Qt::ShiftModifier ) { // Select a range from the last selected currentLayer->extendSelectionTo(frameNumber); } else { currentLayer->toggleFrameSelected(frameNumber, false); } } else { // We clicked on a selected frame, we can move it // canMoveFrame = true; } currentLayer->mousePress( event, frameNumber ); timeLine->updateContent(); } else { if ( frameNumber > 0 ) { if (mEditor->playback()->isPlaying()) { mEditor->playback()->stop(); } mEditor->scrubTo( frameNumber ); timeLine->scrubbing = true; qDebug( "Scrub to %d frame", frameNumber ); } } } } break; } }
// 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); } }
vector<Mat<T>> parameters() const { auto params = LSTM<T>::parameters(); auto decoder_params = decoder.parameters(); params.insert(params.end(), decoder_params.begin(), decoder_params.end()); return params; }
// 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; }
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(); } } } }
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; }
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); } }
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; }
/** * 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(); }
/* 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); } } }
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); } layer->SetAnimations(common.animations()); typedef SpecificLayerAttributes Specific; const SpecificLayerAttributes& specific = attrs.specific(); switch (specific.type()) { case Specific::Tnull_t: break; case Specific::TThebesLayerAttributes: { MOZ_LAYERS_LOG(("[ParentSide] thebes layer")); ShadowThebesLayer* thebesLayer = static_cast<ShadowThebesLayer*>(layer); const ThebesLayerAttributes& attrs = specific.get_ThebesLayerAttributes(); thebesLayer->SetValidRegion(attrs.validRegion()); break; } case Specific::TContainerLayerAttributes: { MOZ_LAYERS_LOG(("[ParentSide] container layer")); ContainerLayer* containerLayer = static_cast<ContainerLayer*>(layer); const ContainerLayerAttributes& attrs = specific.get_ContainerLayerAttributes(); containerLayer->SetFrameMetrics(attrs.metrics()); containerLayer->SetPreScale(attrs.preXScale(), attrs.preYScale()); break; } case Specific::TColorLayerAttributes: MOZ_LAYERS_LOG(("[ParentSide] color layer")); static_cast<ColorLayer*>(layer)->SetColor( specific.get_ColorLayerAttributes().color().value()); break; case Specific::TCanvasLayerAttributes: MOZ_LAYERS_LOG(("[ParentSide] canvas layer")); static_cast<CanvasLayer*>(layer)->SetFilter( specific.get_CanvasLayerAttributes().filter()); break; case Specific::TRefLayerAttributes: MOZ_LAYERS_LOG(("[ParentSide] ref layer")); static_cast<RefLayer*>(layer)->SetReferentId( specific.get_RefLayerAttributes().id()); break; case Specific::TImageLayerAttributes: { MOZ_LAYERS_LOG(("[ParentSide] image layer")); ImageLayer* imageLayer = static_cast<ImageLayer*>(layer); const ImageLayerAttributes& attrs = specific.get_ImageLayerAttributes(); imageLayer->SetFilter(attrs.filter()); imageLayer->SetForceSingleTile(attrs.forceSingleTile()); break; } default: NS_RUNTIMEABORT("not reached"); } break; } // Tree ops case Edit::TOpSetRoot: { MOZ_LAYERS_LOG(("[ParentSide] SetRoot")); mRoot = AsShadowLayer(edit.get_OpSetRoot())->AsContainer(); break; } case Edit::TOpInsertAfter: { MOZ_LAYERS_LOG(("[ParentSide] InsertAfter")); const OpInsertAfter& oia = edit.get_OpInsertAfter(); ShadowContainer(oia)->AsContainer()->InsertAfter( ShadowChild(oia)->AsLayer(), ShadowAfter(oia)->AsLayer()); break; } case Edit::TOpAppendChild: { MOZ_LAYERS_LOG(("[ParentSide] AppendChild")); const OpAppendChild& oac = edit.get_OpAppendChild(); ShadowContainer(oac)->AsContainer()->InsertAfter( ShadowChild(oac)->AsLayer(), NULL); break; } case Edit::TOpRemoveChild: { MOZ_LAYERS_LOG(("[ParentSide] RemoveChild")); const OpRemoveChild& orc = edit.get_OpRemoveChild(); Layer* childLayer = ShadowChild(orc)->AsLayer(); ShadowContainer(orc)->AsContainer()->RemoveChild(childLayer); break; } case Edit::TOpRepositionChild: { MOZ_LAYERS_LOG(("[ParentSide] RepositionChild")); const OpRepositionChild& orc = edit.get_OpRepositionChild(); ShadowContainer(orc)->AsContainer()->RepositionChild( ShadowChild(orc)->AsLayer(), ShadowAfter(orc)->AsLayer()); break; } case Edit::TOpRaiseToTopChild: { MOZ_LAYERS_LOG(("[ParentSide] RaiseToTopChild")); const OpRaiseToTopChild& rtc = edit.get_OpRaiseToTopChild(); ShadowContainer(rtc)->AsContainer()->RepositionChild( ShadowChild(rtc)->AsLayer(), NULL); break; } case Edit::TOpPaintTiledLayerBuffer: { MOZ_LAYERS_LOG(("[ParentSide] Paint TiledLayerBuffer")); const OpPaintTiledLayerBuffer& op = edit.get_OpPaintTiledLayerBuffer(); ShadowLayerParent* shadow = AsShadowLayer(op); ShadowThebesLayer* shadowLayer = static_cast<ShadowThebesLayer*>(shadow->AsLayer()); TiledLayerComposer* tileComposer = shadowLayer->AsTiledLayerComposer(); NS_ASSERTION(tileComposer, "shadowLayer is not a tile composer"); BasicTiledLayerBuffer* p = (BasicTiledLayerBuffer*)op.tiledLayerBuffer(); tileComposer->PaintedTiledLayerBuffer(p); break; } case Edit::TOpPaintThebesBuffer: { MOZ_LAYERS_LOG(("[ParentSide] Paint ThebesLayer")); const OpPaintThebesBuffer& op = edit.get_OpPaintThebesBuffer(); ShadowLayerParent* shadow = AsShadowLayer(op); ShadowThebesLayer* thebes = static_cast<ShadowThebesLayer*>(shadow->AsLayer()); const ThebesBuffer& newFront = op.newFrontBuffer(); RenderTraceInvalidateStart(thebes, "FF00FF", op.updatedRegion().GetBounds()); OptionalThebesBuffer newBack; nsIntRegion newValidRegion; OptionalThebesBuffer readonlyFront; nsIntRegion frontUpdatedRegion; thebes->Swap(newFront, op.updatedRegion(), &newBack, &newValidRegion, &readonlyFront, &frontUpdatedRegion); replyv.push_back( OpThebesBufferSwap( shadow, NULL, newBack, newValidRegion, readonlyFront, frontUpdatedRegion)); RenderTraceInvalidateEnd(thebes, "FF00FF"); break; } case Edit::TOpPaintCanvas: { MOZ_LAYERS_LOG(("[ParentSide] Paint CanvasLayer")); const OpPaintCanvas& op = edit.get_OpPaintCanvas(); ShadowLayerParent* shadow = AsShadowLayer(op); ShadowCanvasLayer* canvas = static_cast<ShadowCanvasLayer*>(shadow->AsLayer()); RenderTraceInvalidateStart(canvas, "FF00FF", canvas->GetVisibleRegion().GetBounds()); canvas->SetAllocator(this); CanvasSurface newBack; canvas->Swap(op.newFrontBuffer(), op.needYFlip(), &newBack); canvas->Updated(); replyv.push_back(OpBufferSwap(shadow, NULL, newBack)); RenderTraceInvalidateEnd(canvas, "FF00FF"); break; } case Edit::TOpPaintImage: { MOZ_LAYERS_LOG(("[ParentSide] Paint ImageLayer")); const OpPaintImage& op = edit.get_OpPaintImage(); ShadowLayerParent* shadow = AsShadowLayer(op); ShadowImageLayer* image = static_cast<ShadowImageLayer*>(shadow->AsLayer()); RenderTraceInvalidateStart(image, "FF00FF", image->GetVisibleRegion().GetBounds()); image->SetAllocator(this); SharedImage newBack; image->Swap(op.newFrontBuffer(), &newBack); replyv.push_back(OpImageSwap(shadow, NULL, newBack)); RenderTraceInvalidateEnd(image, "FF00FF"); break; } default: NS_RUNTIMEABORT("not reached"); } } layer_manager()->EndTransaction(NULL, NULL, LayerManager::END_NO_IMMEDIATE_REDRAW); reply->SetCapacity(replyv.size()); if (replyv.size() > 0) { reply->AppendElements(&replyv.front(), replyv.size()); } // Ensure that any pending operations involving back and front // buffers have completed, so that neither process stomps on the // other's buffer contents. ShadowLayerManager::PlatformSyncBeforeReplyUpdate(); mShadowLayersManager->ShadowLayersUpdated(this, targetConfig, isFirstPaint); #ifdef COMPOSITOR_PERFORMANCE_WARNING int compositeTime = (int)(mozilla::TimeStamp::Now() - updateStart).ToMilliseconds(); if (compositeTime > 15) { printf_stderr("Compositor: Layers update took %i ms (blocking gecko).\n", compositeTime); } #endif return true; }
void Net<Dtype>::Init(const NetParameter& in_param){ CHECK(Dragon::get_root_solver() || root_net) << "Root net need to be set for all non-root solvers."; phase = in_param.state().phase(); NetParameter filtered_param, param; // filter for unqualified LayerParameters(e.g Test DataLayer) filterNet(in_param, &filtered_param); insertSplits(filtered_param, ¶m); name = param.name(); LOG_IF(INFO, Dragon::get_root_solver()) << "Initialize net from parameters: ";/*<< endl << param.DebugString();*/ map<string, int> blob_name_to_idx; set<string> available_blobs; CHECK_EQ(param.input_size(), param.input_shape_size())<< "input blob_shape must specify a blob."; memory_used = 0; // check and stuff virtual input blobs firstly [Viewing Mode Only] for (int input_id=0; input_id < param.input_size(); input_id++){ const int layer_id = -1; // net_input.push_back(.....virtual blob.....) appendTop(param, layer_id, input_id, &available_blobs, &blob_name_to_idx); } // stuff real blobs for each layer then [Traning/Testing/Viewing Mode] bottom_vecs.resize(param.layer_size()); bottom_id_vecs.resize(param.layer_size()); bottoms_need_backward.resize(param.layer_size()); top_vecs.resize(param.layer_size()); top_id_vecs.resize(param.layer_size()); param_id_vecs.resize(param.layer_size()); for (int layer_id = 0; layer_id < param.layer_size(); layer_id++){ bool share_from_root = !Dragon::get_root_solver() && root_net->layers[layer_id]->shareInParallel(); // copy net phase to layer if not set if (!param.layer(layer_id).has_phase()) param.mutable_layer(layer_id)->set_phase(phase); const LayerParameter& layer_param = param.layer(layer_id); if (share_from_root){ LOG(INFO) << "Share Layer: " << layer_param.name() << " from the root net."; // share layer by pointer layers.push_back(root_net->layers[layer_id]); layers[layer_id]->setShared(true); } else{ // use layer factory to create a pointer // layer type is referred by layer_param->type() // see more in layer_factory.hpp layers.push_back(LayerFactory<Dtype>::createLayer(layer_param)); } layer_names.push_back(layer_param.name()); LOG_IF(INFO, Dragon::get_root_solver()) << "Create Layer: " << layer_param.name(); bool need_bp = false; // stuff bottom blobs for (int bottom_id = 0; bottom_id < layer_param.bottom_size(); bottom_id++){ const int blob_id = appendBottom(param, layer_id, bottom_id, &available_blobs, &blob_name_to_idx); // check whether a bottom need back propogation need_bp |= blobs_need_backward[blob_id]; } // stuff top blobs for (int top_id = 0; top_id < layer_param.top_size(); top_id++) appendTop(param, layer_id, top_id, &available_blobs, &blob_name_to_idx); // auto top blobs // NOT_IMPLEMENTED; Layer<Dtype>* layer = layers[layer_id].get(); // setup for layer if (share_from_root){ const vector<Blob<Dtype>*> base_top = root_net->top_vecs[layer_id]; const vector<Blob<Dtype>*> this_top = this->top_vecs[layer_id]; // reshape solely after root_net finishing for (int top_id = 0; top_id < base_top.size(); top_id++){ this_top[top_id]->reshapeLike(*base_top[top_id]); } } else layer->setup(bottom_vecs[layer_id], top_vecs[layer_id]); LOG_IF(INFO, Dragon::get_root_solver()) << "Setup Layer: " << layer_param.name(); for (int top_id = 0; top_id < top_vecs[layer_id].size(); top_id++){ // extend size to max number of blobs if necessary if (blobs_loss_weight.size() <= top_id_vecs[layer_id][top_id]) blobs_loss_weight.resize(top_id_vecs[layer_id][top_id] + 1, Dtype(0)); // store global loss weights from each layer each blob blobs_loss_weight[top_id_vecs[layer_id][top_id]] = layer->getLoss(top_id); LOG_IF(INFO, Dragon::get_root_solver()) << "Top shape: " << top_vecs[layer_id][top_id]->shape_string(); if (layer->getLoss(top_id)) LOG_IF(INFO, Dragon::get_root_solver()) << " with loss weight " << layer->getLoss(top_id); // sum up for training parameter statistic memory_used += top_vecs[layer_id][top_id]->count(); } LOG_IF(INFO, Dragon::get_root_solver()) << "Memory required for Data: " << memory_used*sizeof(Dtype); const int param_size = layer_param.param_size(); // blobs_size will be set after layer->setup() const int param_blobs_size = layer->getBlobs().size(); CHECK_LE(param_size, param_blobs_size)<< "Too many params specify for layer."; // use if do not specify hyperparameter // lr_mult=decay_mult=1.0 ParamSpec default_hyperparameter; for (int param_id = 0; param_id < param_blobs_size; param_id++){ const ParamSpec* hyperparameter = param_id < param_size ? &layer_param.param(param_id) : &default_hyperparameter; const bool param_need_bp = hyperparameter->lr_mult() != 0; // check whether a param blob need back propogation [default=true] need_bp |= param_need_bp; layer->setParamNeedBp(param_id, param_need_bp); } // stuff param blobs for (int param_id = 0; param_id < param_blobs_size; param_id++) appendParam(param, layer_id, param_id); // update param blobs if share others shareWeights(); layer_need_backward.push_back(need_bp); // after checking all bottom blobs and param blobs if (need_bp) for (int top_id = 0; top_id < top_id_vecs[layer_id].size(); top_id++) blobs_need_backward[top_id_vecs[layer_id][top_id]] = true; } // end layer_id set<string> blobs_under_loss, blobs_skip_bp; for (int layer_id = layers.size()-1; layer_id >= 0; layer_id--){ bool layer_contributes_loss = false; bool layer_skip_bp = true; Layer<Dtype>* layer = layers[layer_id].get(); for (int top_id = 0; top_id < top_vecs[layer_id].size(); top_id++){ const string& blob_name = blobs_name[top_id_vecs[layer_id][top_id]]; if (layer->getLoss(top_id) || blobs_under_loss.count(blob_name)) layer_contributes_loss = true; if (!blobs_skip_bp.count(blob_name)) layer_skip_bp = false; // find any top blobs if affected by loss and do not force to skip bp if (layer_contributes_loss&&!layer_skip_bp) break; } // optimization trick: set lr_mult but is not affected by loss if (layer_need_backward[layer_id] && layer_skip_bp){ // cancel layer layer_need_backward[layer_id] = false; // cancel bottom for (int bottom_id = 0; bottom_id < bottom_vecs[layer_id].size(); bottom_id++){ bottoms_need_backward[layer_id][bottom_id] = false; } } // cancel directly if layer is not affected by loss if (!layer_contributes_loss) layer_need_backward[layer_id] = false; // debug info if (Dragon::get_root_solver()){ if (layer_need_backward[layer_id]) LOG(INFO) << "Layer: " << layer_names[layer_id] << " need back-propogation."; else LOG(INFO) << "Layer: " << layer_names[layer_id] << " does not need back-propogation."; } // if one top blob affected by loss // all bottom blobs will be affected // regard it as "loss back-affected" for (int bottom_id = 0; bottom_id < bottom_vecs[layer_id].size(); bottom_id++){ const string& blob_name = blobs_name[bottom_id_vecs[layer_id][bottom_id]]; if (layer_contributes_loss) blobs_under_loss.insert(blob_name); else bottoms_need_backward[layer_id][bottom_id] = false; // use for optimization trick : skip all bottom blobs if (!bottoms_need_backward[layer_id][bottom_id]) blobs_skip_bp.insert(blob_name); } } // end layer id if (param.force_backward()){ for (int layer_id = 0; layer_id < layers.size(); layer_id++){ layer_need_backward[layer_id] = true; for (int bottom_id = 0; bottom_id < bottom_vecs[layer_id].size(); bottom_id++){ // set for bottoms bottoms_need_backward[layer_id][bottom_id] = bottoms_need_backward[layer_id][bottom_id]||layers[layer_id]->allowForceBackward(bottom_id); // set for blobs blobs_need_backward[bottom_id_vecs[layer_id][bottom_id]] = blobs_need_backward[bottom_id_vecs[layer_id][bottom_id]]||bottoms_need_backward[layer_id][bottom_id]; } // set for params for (int param_id = 0; param_id < layers[layer_id]->getBlobs().size(); param_id++){ layers[layer_id]->setParamNeedBp(param_id, true); } } } // move un-used(declare top but not use as bottom) blobs into output blobs // usually contain loss blobs for (set<string>::iterator i = available_blobs.begin(); i != available_blobs.end(); i++){ LOG_IF(INFO, Dragon::get_root_solver()) << "Network produces output: " << *i; net_output_blobs.push_back(blobs[blob_name_to_idx[*i]].get()); net_output_blob_indices.push_back(blob_name_to_idx[*i]); } // store blob_name -> blob_ids blobs_name_idx = blob_name_to_idx; // store layer_name -> layer_id for (size_t layer_id = 0; layer_id < layer_names.size(); layer_id++) layers_name_idx[layer_names[layer_id]] = layer_id; debug_info = param.debug_info(); LOG_IF(INFO, Dragon::get_root_solver()) << "Network Initializion done."; }
// 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); } }
int main(int argc, char *argv[]) { lua_State* cfgState = luaL_newstate(); luaL_dofile( cfgState, "cfg.lua" ); luaL_openlibs( cfgState ); lua_pcall( cfgState, 0, 0, 0 ); LuaRef t = getGlobal( cfgState, "cfg" ); screenWidth = t["SCREEN_WIDTH"]; screenHeight = t["SCREEN_HEIGHT"]; if ( SDL_Init( SDL_INIT_VIDEO ) != 0 ){ std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } window = SDL_CreateWindow( "Open Deathmatch", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screenWidth, screenHeight, SDL_WINDOW_SHOWN ); if ( window == nullptr ) { std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); if (renderer == nullptr) { SDL_DestroyWindow( window ); std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } Tileset ts = Tileset("Maps/first.lua", 1); Layer l = Layer("Maps/first.lua", 1); std::map<int, SDL_Surface*> tiles = ts.getTiles(); std::map<std::pair<int, int>, SDL_Texture*> renderingArea = std::map<std::pair<int, int>, SDL_Texture*>(); int indexCounter = 0; for (int i = 0; i < 512; i += 32) { for (int j = 0; j < 512; j += 32) { std::pair<int, int> p = std::pair<int, int>(j, i); renderingArea.insert(std::pair<std::pair<int, int>, SDL_Texture*>(p, SDL_CreateTextureFromSurface(renderer, tiles[l.getData().at(indexCounter)]))); std::cout << l.getData().at(indexCounter) << '\n'; indexCounter++; } } ts.freeTiles(tiles); while (!done) { SDL_RenderClear(renderer); for ( std::map<std::pair<int, int>, SDL_Texture*>::iterator iter = renderingArea.begin(); iter != renderingArea.end(); ++iter ) { SDL_Rect tempRect = { iter->first.first, iter->first.second, 32, 32 }; SDL_RenderCopy(renderer, iter->second, NULL, &tempRect); } SDL_RenderPresent(renderer); SDL_Delay(1000); while ( SDL_PollEvent( &e ) != 0 ) { if ( e.type == SDL_QUIT ) { done = true; } } } return 0; }
bool ElevationQuery::getElevationImpl(const GeoPoint& point, float& out_elevation, double desiredResolution, double* out_actualResolution) { // assertion. if ( !point.isAbsolute() ) { OE_WARN << LC << "Assertion failure; input must be absolute" << std::endl; return false; } osg::Timer_t begin = osg::Timer::instance()->tick(); // first try the terrain patches. if ( _terrainModelLayers.size() > 0 ) { osgUtil::IntersectionVisitor iv; if ( _ivrc.valid() ) iv.setReadCallback(_ivrc.get()); for(LayerVector::iterator i = _terrainModelLayers.begin(); i != _terrainModelLayers.end(); ++i) { // find the scene graph for this layer: Layer* layer = i->get(); osg::Node* node = layer->getNode(); if ( node ) { // configure for intersection: osg::Vec3d surface; point.toWorld( surface ); // trivial bounds check: if ( node->getBound().contains(surface) ) { osg::Vec3d nvector; point.createWorldUpVector(nvector); osg::Vec3d start( surface + nvector*5e5 ); osg::Vec3d end ( surface - nvector*5e5 ); // first time through, set up the intersector on demand if ( !_lsi.valid() ) { _lsi = new osgUtil::LineSegmentIntersector(start, end); _lsi->setIntersectionLimit( _lsi->LIMIT_NEAREST ); } else { _lsi->reset(); _lsi->setStart( start ); _lsi->setEnd ( end ); } // try it. iv.setIntersector( _lsi.get() ); node->accept( iv ); // check for a result!! if ( _lsi->containsIntersections() ) { osg::Vec3d isect = _lsi->getIntersections().begin()->getWorldIntersectPoint(); // transform back to input SRS: GeoPoint output; output.fromWorld( point.getSRS(), isect ); out_elevation = (float)output.z(); if ( out_actualResolution ) *out_actualResolution = 0.0; return true; } } else { //OE_INFO << LC << "Trivial rejection (bounds check)" << std::endl; } } } } if (_elevationLayers.empty()) { // this means there are no heightfields. out_elevation = NO_DATA_VALUE; return true; } // secure map pointer: osg::ref_ptr<const Map> map; if (!_map.lock(map)) { return false; } // tile size (resolution of elevation tiles) unsigned tileSize = 257; // yes? // default LOD: unsigned lod = 23u; // attempt to map the requested resolution to an LOD: if (desiredResolution > 0.0) { int level = map->getProfile()->getLevelOfDetailForHorizResolution(desiredResolution, tileSize); if ( level > 0 ) lod = level; } // do we need a new ElevationEnvelope? if (!_envelope.valid() || !point.getSRS()->isHorizEquivalentTo(_envelope->getSRS()) || lod != _envelope->getLOD()) { _envelope = map->getElevationPool()->createEnvelope(point.getSRS(), lod); } // sample the elevation, and if requested, the resolution as well: if (out_actualResolution) { std::pair<float, float> result = _envelope->getElevationAndResolution(point.x(), point.y()); out_elevation = result.first; *out_actualResolution = result.second; } else { out_elevation = _envelope->getElevation(point.x(), point.y()); } return out_elevation != NO_DATA_VALUE; }
bool ConnectedComponents::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList) { if (pInArgList == NULL) { return false; } mProgress = ProgressTracker(pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()), "Labeling connected components", "app", "{aa2169d0-9c0a-4d41-9f1d-9a9e83ecf32b}"); mpView = pInArgList->getPlugInArgValue<SpatialDataView>(Executable::ViewArg()); AoiElement* pAoi = pInArgList->getPlugInArgValue<AoiElement>("AOI"); if (pAoi == NULL && mpView != NULL) { Layer* pLayer = mpView->getActiveLayer(); if (pLayer == NULL) { std::vector<Layer*> layers; mpView->getLayerList()->getLayers(AOI_LAYER, layers); if (!layers.empty()) { pLayer = layers.front(); } } pAoi = pLayer == NULL ? NULL : dynamic_cast<AoiElement*>(pLayer->getDataElement()); } const BitMask* mpBitmask = (pAoi == NULL) ? NULL : pAoi->getSelectedPoints(); if (mpBitmask == NULL) { mProgress.report("Must specify an AOI.", 0, ERRORS, true); return false; } if (mpBitmask->isOutsideSelected()) { mProgress.report("Infinite AOIs can not be processed.", 0, ERRORS, true); return false; } // Get the extents and create the output element int x1 = 0; int x2 = 0; int y1 = 0; int y2 = 0; mpBitmask->getMinimalBoundingBox(x1, y1, x2, y2); if (x1 > x2) { std::swap(x1, x2); } if (y1 > y2) { std::swap(y1, y2); } if (x1 < 0 || y1 < 0) { mProgress.report("Negative pixel locations are not supported and will be ignored.", 1, WARNING, true); x1 = std::max(x1, 0); y1 = std::max(y1, 0); x2 = std::max(x2, 0); y2 = std::max(y2, 0); } // Include a 1 pixel border so we include the edge pixels x1--; x2++; y1--; y2++; unsigned int width = x2 - x1 + 1; unsigned int height = y2 - y1 + 1; mXOffset = x1; mYOffset = y1; mpLabels = static_cast<RasterElement*>( Service<ModelServices>()->getElement("Blobs", TypeConverter::toString<RasterElement>(), pAoi)); if (mpLabels != NULL) { if (!isBatch()) { Service<DesktopServices>()->showSuppressibleMsgDlg( getName(), "The \"Blobs\" element exists and will be deleted.", MESSAGE_INFO, "ConnectedComponents::DeleteExisting"); } Service<ModelServices>()->destroyElement(mpLabels); mpLabels = NULL; } mpLabels = RasterUtilities::createRasterElement("Blobs", height, width, INT2UBYTES, true, pAoi); if (mpLabels == NULL) { mProgress.report("Unable to create label element.", 0, ERRORS, true); return false; } ModelResource<RasterElement> pLabels(mpLabels); try { cv::Mat data(height, width, CV_8UC1, cv::Scalar(0)); for (unsigned int y = 0; y < height; ++y) { mProgress.report("Reading AOI data", 10 * y / height, NORMAL); for (unsigned int x = 0; x < width; ++x) { if (mpBitmask->getPixel(x + mXOffset, y + mYOffset)) { data.at<unsigned char>(y, x) = 255; } } } mProgress.report("Finding contours", 15, NORMAL); std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::findContours(data, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); cv::Mat labels(height, width, CV_16UC1, mpLabels->getRawData()); mProgress.report("Filling blobs", 50, NORMAL); unsigned short lastLabel = 0; fillContours(labels, contours, hierarchy, lastLabel, 0, 0); // create a pseudocolor layer for display mProgress.report("Displaying results", 90, NORMAL); mpLabels->updateData(); if (!createPseudocolor(lastLabel)) { mProgress.report("Unable to create blob layer", 0, ERRORS, true); return false; } // add blob count to the metadata DynamicObject* pMeta = pLabels->getMetadata(); VERIFY(pMeta); unsigned int numBlobs = static_cast<unsigned int>(lastLabel); pMeta->setAttribute("BlobCount", numBlobs); if (numBlobs == 0 && !isBatch()) { // Inform the user that there were no blobs so they don't think there was an // error running the algorithm. No need to do this in batch since this is // represented in the metadata already. mProgress.report("No blobs were found.", 95, WARNING); } // update the output arg list if (pOutArgList != NULL) { pOutArgList->setPlugInArgValue("Blobs", pLabels.get()); pOutArgList->setPlugInArgValue("Number of Blobs", &numBlobs); } } catch(const cv::Exception& exc) { mProgress.report(exc.what(), 0, ERRORS, true); return false; } pLabels.release(); mProgress.report("Labeling connected components", 100, NORMAL); mProgress.upALevel(); return true; }
lstm_state_t activate(Mat<T> embedding) const { auto c = c_layer.activate(embedding); auto o = o_layer.activate(embedding).sigmoid(); auto h = c.tanh() * o; return lstm_state_t(c,h); }
/** * Get the data element name of a specified layer. * * @param[in] [1] @opt * The name of the layer. Defaults to the top most layer. * @param[in] WINDOW @opt * The name of the window. Defaults to the active window. * @param[in] DATASET @opt * If \p [1] is not specified and this flag it set, get the * data set name of the top most raster layer. * @return The name of the data element. * @usage print,get_data_name(/DATASET) * @endusage */ IDL_VPTR get_data_name(int argc, IDL_VPTR pArgv[], char* pArgk) { typedef struct { IDL_KW_RESULT_FIRST_FIELD; int windowExists; IDL_STRING windowName; int datasetExists; IDL_LONG dataset; } KW_RESULT; //IDL_KW_FAST_SCAN is the type of scan we are using, following it is the //name of the keyword, followed by the type, the mask(which should be 1), //flags, a boolean whether the value was populated and finally the value itself static IDL_KW_PAR kw_pars[] = { IDL_KW_FAST_SCAN, {"DATASET", IDL_TYP_INT, 1, 0, reinterpret_cast<int*>(IDL_KW_OFFSETOF(datasetExists)), reinterpret_cast<char*>(IDL_KW_OFFSETOF(dataset))}, {"WINDOW", IDL_TYP_STRING, 1, 0, reinterpret_cast<int*>(IDL_KW_OFFSETOF(windowExists)), reinterpret_cast<char*>(IDL_KW_OFFSETOF(windowName))}, {NULL} }; IdlFunctions::IdlKwResource<KW_RESULT> kw(argc, pArgv, pArgk, kw_pars, 0, 1); std::string windowName; std::string layerName; std::string name; if (kw->windowExists) { windowName = IDL_STRING_STR(&kw->windowName); } //retrieve the layer name passed in as a parameter if (argc >= 1) { layerName = IDL_VarGetString(pArgv[0]); } //get the layer bool datasets = false; if (kw->datasetExists) { if (kw->dataset != 0) { datasets = true; } } Layer* pLayer = IdlFunctions::getLayerByName(windowName, layerName, datasets); if (pLayer != NULL) { //get the spectral element of the layer and return its name DataElement* pElement = pLayer->getDataElement(); if (pElement != NULL) { name = pElement->getName(); } } else { IDL_Message(IDL_M_GENERIC, IDL_MSG_RET, "the layer name passed into get_data_name " "was invalid."); return IDL_StrToSTRING(""); } return IDL_StrToSTRING(const_cast<char*>(name.c_str())); }
void TimeLineCells::drawContent() { if ( m_pCache == NULL ) { m_pCache = new QPixmap( size() ); if ( m_pCache->isNull() ) { // fail to create cache return; } } QPainter painter( m_pCache ); Object* object = mEditor->object(); Q_ASSERT_X( object != nullptr, "", "" ); Layer* layer = object->getLayer( mEditor->layers()->currentLayerIndex() ); if ( layer == NULL ) return; // grey background of the view painter.setPen( Qt::NoPen ); painter.setBrush( Qt::lightGray ); painter.drawRect( QRect( 0, 0, width(), height() ) ); // --- draw layers of the current object for ( int i = 0; i < object->getLayerCount(); i++ ) { if ( i != mEditor->layers()->currentLayerIndex() ) { Layer* layeri = object->getLayer( i ); if ( layeri != NULL ) { switch ( m_eType ) { case TIMELINE_CELL_TYPE::Tracks: layeri->paintTrack( painter, this, m_offsetX, getLayerY( i ), width() - m_offsetX, getLayerHeight(), false, frameSize ); break; case TIMELINE_CELL_TYPE::Layers: layeri->paintLabel( painter, this, 0, getLayerY( i ), width() - 1, getLayerHeight(), false, mEditor->allLayers() ); break; } } } } if ( abs( getMouseMoveY() ) > 5 ) { if ( m_eType == TIMELINE_CELL_TYPE::Tracks ) { layer->paintTrack( painter, this, m_offsetX, getLayerY( mEditor->layers()->currentLayerIndex() ) + getMouseMoveY(), width() - m_offsetX, getLayerHeight(), true, frameSize ); } if ( m_eType == TIMELINE_CELL_TYPE::Layers ) { layer->paintLabel( painter, this, 0, getLayerY( mEditor->layers()->currentLayerIndex() ) + getMouseMoveY(), width() - 1, getLayerHeight(), true, mEditor->allLayers() ); } painter.setPen( Qt::black ); painter.drawRect( 0, getLayerY( getLayerNumber( endY ) ) - 1, width(), 2 ); } else { if ( m_eType == TIMELINE_CELL_TYPE::Tracks ) { layer->paintTrack( painter, this, m_offsetX, getLayerY( mEditor->layers()->currentLayerIndex() ), width() - m_offsetX, getLayerHeight(), true, frameSize ); } if ( m_eType == TIMELINE_CELL_TYPE::Layers ) { layer->paintLabel( painter, this, 0, getLayerY( mEditor->layers()->currentLayerIndex() ), width() - 1, getLayerHeight(), true, mEditor->allLayers() ); } } // --- draw top painter.setPen( Qt::NoPen ); painter.setBrush( QColor( 220, 220, 220 ) ); painter.drawRect( QRect( 0, 0, width() - 1, m_offsetY - 1 ) ); painter.setPen( Qt::gray ); painter.drawLine( 0, 0, width() - 1, 0 ); painter.drawLine( 0, m_offsetY - 2, width() - 1, m_offsetY - 2 ); painter.setPen( Qt::lightGray ); painter.drawLine( 0, m_offsetY - 3, width() - 1, m_offsetY - 3 ); painter.drawLine( 0, 0, 0, m_offsetY - 3 ); if ( m_eType == TIMELINE_CELL_TYPE::Layers ) { // --- draw circle painter.setPen( Qt::black ); if ( mEditor->allLayers() == 0 ) { painter.setBrush( Qt::NoBrush ); } if ( mEditor->allLayers() == 1 ) { painter.setBrush( Qt::darkGray ); } if ( mEditor->allLayers() == 2 ) { painter.setBrush( Qt::black ); } painter.setRenderHint( QPainter::Antialiasing, true ); painter.drawEllipse( 6, 4, 9, 9 ); painter.setRenderHint( QPainter::Antialiasing, false ); } else if ( m_eType == TIMELINE_CELL_TYPE::Tracks ) { // --- draw ticks painter.setPen( QColor( 70, 70, 70, 255 ) ); painter.setBrush( Qt::darkGray ); painter.setFont( QFont( "helvetica", 10 ) ); int incr = 0; int fps = mEditor->playback()->fps(); for ( int i = frameOffset; i < frameOffset + ( width() - m_offsetX ) / frameSize; i++ ) { incr = ( i < 9 ) ? 4 : 0; if(i + 1 >= timeLine->getRangeLower() && i < timeLine->getRangeUpper()) { painter.setPen( Qt::NoPen ); painter.setBrush( Qt::yellow ); painter.drawRect( getFrameX( i ), 1, frameSize + 1, 2 ); painter.setPen( QColor( 70, 70, 70, 255 ) ); painter.setBrush( Qt::darkGray ); } if ( i%fps == 0 ) { painter.drawLine( getFrameX( i ), 1, getFrameX( i ), 5 ); } else if ( i%fps == fps / 2 ) { painter.drawLine( getFrameX( i ), 1, getFrameX( i ), 5 ); } else { painter.drawLine( getFrameX( i ), 1, getFrameX( i ), 3 ); } if ( i == 0 || i%fps == fps - 1 ) { painter.drawText( QPoint( getFrameX( i ) + incr, 15 ), QString::number( i + 1 ) ); } } // --- draw left border line painter.setPen( Qt::darkGray ); painter.drawLine( 0, 0, 0, height() ); } }
bool ShadowLayersParent::RecvUpdate(const InfallibleTArray<Edit>& cset, InfallibleTArray<EditReply>* reply) { 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(); layer->SetAllocator(this); 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::TOpCreateThebesBuffer: { MOZ_LAYERS_LOG(("[ParentSide] CreateThebesBuffer")); const OpCreateThebesBuffer& otb = edit.get_OpCreateThebesBuffer(); ShadowThebesLayer* thebes = static_cast<ShadowThebesLayer*>( AsShadowLayer(otb)->AsLayer()); thebes->SetFrontBuffer(otb.initialFront(), otb.frontValidRegion()); break; } case Edit::TOpCreateCanvasBuffer: { MOZ_LAYERS_LOG(("[ParentSide] CreateCanvasBuffer")); const OpCreateCanvasBuffer& ocb = edit.get_OpCreateCanvasBuffer(); ShadowCanvasLayer* canvas = static_cast<ShadowCanvasLayer*>( AsShadowLayer(ocb)->AsLayer()); canvas->Init(ocb.initialFront(), ocb.size(), ocb.needYFlip()); break; } case Edit::TOpCreateImageBuffer: { MOZ_LAYERS_LOG(("[ParentSide] CreateImageBuffer")); const OpCreateImageBuffer ocb = edit.get_OpCreateImageBuffer(); ShadowImageLayer* image = static_cast<ShadowImageLayer*>( AsShadowLayer(ocb)->AsLayer()); image->Init(ocb.initialFront(), ocb.size()); break; } case Edit::TOpDestroyThebesFrontBuffer: { MOZ_LAYERS_LOG(("[ParentSide] DestroyThebesFrontBuffer")); const OpDestroyThebesFrontBuffer& odfb = edit.get_OpDestroyThebesFrontBuffer(); ShadowThebesLayer* thebes = static_cast<ShadowThebesLayer*>( AsShadowLayer(odfb)->AsLayer()); thebes->DestroyFrontBuffer(); break; } case Edit::TOpDestroyCanvasFrontBuffer: { MOZ_LAYERS_LOG(("[ParentSide] DestroyCanvasFrontBuffer")); const OpDestroyCanvasFrontBuffer& odfb = edit.get_OpDestroyCanvasFrontBuffer(); ShadowCanvasLayer* canvas = static_cast<ShadowCanvasLayer*>( AsShadowLayer(odfb)->AsLayer()); canvas->DestroyFrontBuffer(); break; } case Edit::TOpDestroyImageFrontBuffer: { MOZ_LAYERS_LOG(("[ParentSide] DestroyImageFrontBuffer")); const OpDestroyImageFrontBuffer& odfb = edit.get_OpDestroyImageFrontBuffer(); ShadowImageLayer* image = static_cast<ShadowImageLayer*>( AsShadowLayer(odfb)->AsLayer()); image->DestroyFrontBuffer(); 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->SetTransform(common.transform()); layer->SetTileSourceRect(common.useTileSourceRect() ? &common.tileSourceRect() : NULL); static bool fixedPositionLayersEnabled = getenv("MOZ_ENABLE_FIXED_POSITION_LAYERS") != 0; if (fixedPositionLayersEnabled) { layer->SetIsFixedPosition(common.isFixedPosition()); } typedef SpecificLayerAttributes Specific; const SpecificLayerAttributes& specific = attrs.specific(); switch (specific.type()) { case Specific::Tnull_t: break; case Specific::TThebesLayerAttributes: { MOZ_LAYERS_LOG(("[ParentSide] thebes layer")); ShadowThebesLayer* thebesLayer = static_cast<ShadowThebesLayer*>(layer); const ThebesLayerAttributes& attrs = specific.get_ThebesLayerAttributes(); thebesLayer->SetValidRegion(attrs.validRegion()); break; } case Specific::TContainerLayerAttributes: MOZ_LAYERS_LOG(("[ParentSide] container layer")); static_cast<ContainerLayer*>(layer)->SetFrameMetrics( specific.get_ContainerLayerAttributes().metrics()); break; case Specific::TColorLayerAttributes: MOZ_LAYERS_LOG(("[ParentSide] color layer")); static_cast<ColorLayer*>(layer)->SetColor( specific.get_ColorLayerAttributes().color()); break; case Specific::TCanvasLayerAttributes: MOZ_LAYERS_LOG(("[ParentSide] canvas layer")); static_cast<CanvasLayer*>(layer)->SetFilter( specific.get_CanvasLayerAttributes().filter()); break; case Specific::TImageLayerAttributes: MOZ_LAYERS_LOG(("[ParentSide] image layer")); static_cast<ImageLayer*>(layer)->SetFilter( specific.get_ImageLayerAttributes().filter()); break; default: NS_RUNTIMEABORT("not reached"); } break; } // Tree ops case Edit::TOpSetRoot: { MOZ_LAYERS_LOG(("[ParentSide] SetRoot")); mRoot = AsShadowLayer(edit.get_OpSetRoot())->AsContainer(); break; } case Edit::TOpInsertAfter: { MOZ_LAYERS_LOG(("[ParentSide] InsertAfter")); const OpInsertAfter& oia = edit.get_OpInsertAfter(); ShadowContainer(oia)->AsContainer()->InsertAfter( ShadowChild(oia)->AsLayer(), ShadowAfter(oia)->AsLayer()); break; } case Edit::TOpAppendChild: { MOZ_LAYERS_LOG(("[ParentSide] AppendChild")); const OpAppendChild& oac = edit.get_OpAppendChild(); ShadowContainer(oac)->AsContainer()->InsertAfter( ShadowChild(oac)->AsLayer(), NULL); break; } case Edit::TOpRemoveChild: { MOZ_LAYERS_LOG(("[ParentSide] RemoveChild")); const OpRemoveChild& orc = edit.get_OpRemoveChild(); Layer* childLayer = ShadowChild(orc)->AsLayer(); ShadowContainer(orc)->AsContainer()->RemoveChild(childLayer); break; } case Edit::TOpPaintThebesBuffer: { MOZ_LAYERS_LOG(("[ParentSide] Paint ThebesLayer")); const OpPaintThebesBuffer& op = edit.get_OpPaintThebesBuffer(); ShadowLayerParent* shadow = AsShadowLayer(op); ShadowThebesLayer* thebes = static_cast<ShadowThebesLayer*>(shadow->AsLayer()); const ThebesBuffer& newFront = op.newFrontBuffer(); ThebesBuffer newBack; nsIntRegion newValidRegion; OptionalThebesBuffer readonlyFront; nsIntRegion frontUpdatedRegion; thebes->Swap(newFront, op.updatedRegion(), &newBack, &newValidRegion, &readonlyFront, &frontUpdatedRegion); replyv.push_back( OpThebesBufferSwap( shadow, NULL, newBack, newValidRegion, readonlyFront, frontUpdatedRegion)); break; } case Edit::TOpPaintCanvas: { MOZ_LAYERS_LOG(("[ParentSide] Paint CanvasLayer")); const OpPaintCanvas& op = edit.get_OpPaintCanvas(); ShadowLayerParent* shadow = AsShadowLayer(op); ShadowCanvasLayer* canvas = static_cast<ShadowCanvasLayer*>(shadow->AsLayer()); SurfaceDescriptor newFront = op.newFrontBuffer(); SurfaceDescriptor newBack; canvas->Swap(op.newFrontBuffer(), &newBack); if (newFront == newBack) { newFront = SurfaceDescriptor(); } canvas->Updated(); replyv.push_back(OpBufferSwap(shadow, NULL, newBack)); break; } case Edit::TOpPaintImage: { MOZ_LAYERS_LOG(("[ParentSide] Paint ImageLayer")); const OpPaintImage& op = edit.get_OpPaintImage(); ShadowLayerParent* shadow = AsShadowLayer(op); ShadowImageLayer* image = static_cast<ShadowImageLayer*>(shadow->AsLayer()); SharedImage newFront = op.newFrontBuffer(); SharedImage newBack; image->Swap(op.newFrontBuffer(), &newBack); if (newFront == newBack) { newFront = SharedImage(); } replyv.push_back(OpImageSwap(shadow, NULL, newBack)); break; } default: NS_RUNTIMEABORT("not reached"); } } layer_manager()->EndTransaction(NULL, NULL); reply->SetCapacity(replyv.size()); if (replyv.size() > 0) { reply->AppendElements(&replyv.front(), replyv.size()); } // Ensure that any pending operations involving back and front // buffers have completed, so that neither process stomps on the // other's buffer contents. ShadowLayerManager::PlatformSyncBeforeReplyUpdate(); Frame()->ShadowLayersUpdated(); return true; }
void TimeLineCells::mouseMoveEvent( QMouseEvent* event ) { if ( m_eType == TIMELINE_CELL_TYPE::Layers ) { endY = event->pos().y(); emit mouseMovedY( endY - startY ); } int frameNumber = getFrameNumber( event->pos().x() ); //int layerNumber = getLayerNumber( event->pos().y() ); if ( m_eType == TIMELINE_CELL_TYPE::Tracks ) { if ( primaryButton == Qt::MidButton ) { // qMin( max_frame_offset, qMax ( min_frame_offset, draw_frame_offset ) ) frameOffset = qMin( qMax( 0, frameLength - width() / getFrameSize() ), qMax( 0, frameOffset + lastFrameNumber - frameNumber ) ); update(); emit offsetChanged( frameOffset ); } else { if ( timeLine->scrubbing ) { mEditor->scrubTo( frameNumber ); } else { if ( startLayerNumber != -1 && startLayerNumber < mEditor->object()->getLayerCount() ) { Layer *currentLayer = mEditor->object()->getLayer(startLayerNumber); // Did we move to another frame ? // if ( frameNumber != lastFrameNumber ) { // Check if the frame we clicked was selected // if ( canMoveFrame ) { // If it is the case, we move the selected frames in the layer // movingFrames = true; int offset = frameNumber - lastFrameNumber; currentLayer->moveSelectedFrames(offset); mEditor->updateCurrentFrame(); } else if ( canBoxSelect ){ // Otherwise, we do a box select // boxSelecting = true; currentLayer->deselectAll(); currentLayer->setFrameSelected(startFrameNumber, true); currentLayer->extendSelectionTo(frameNumber); } lastFrameNumber = frameNumber; } currentLayer->mouseMove( event, frameNumber ); } } } } timeLine->update(); }
// Usage: caffe_('layer_get_type', hLayer) static void layer_get_type(MEX_ARGS) { mxCHECK(nrhs == 1 && mxIsStruct(prhs[0]), "Usage: caffe_('layer_get_type', hLayer)"); Layer<float>* layer = handle_to_ptr<Layer<float> >(prhs[0]); plhs[0] = mxCreateString(layer->type()); }
void AsyncCompositionManager::AlignFixedLayersForAnchorPoint(Layer* aLayer, Layer* aTransformedSubtreeRoot, const gfx3DMatrix& aPreviousTransformForRoot, const LayerMargin& aFixedLayerMargins) { if (aLayer != aTransformedSubtreeRoot && aLayer->GetIsFixedPosition() && !aLayer->GetParent()->GetIsFixedPosition()) { // Insert a translation so that the position of the anchor point is the same // before and after the change to the transform of aTransformedSubtreeRoot. // This currently only works for fixed layers with 2D transforms. // Accumulate the transforms between this layer and the subtree root layer. gfxMatrix ancestorTransform; if (!AccumulateLayerTransforms2D(aLayer->GetParent(), aTransformedSubtreeRoot, ancestorTransform)) { return; } gfxMatrix oldRootTransform; gfxMatrix newRootTransform; if (!aPreviousTransformForRoot.Is2D(&oldRootTransform) || !aTransformedSubtreeRoot->GetLocalTransform().Is2D(&newRootTransform)) { return; } // Calculate the cumulative transforms between the subtree root with the // old transform and the current transform. gfxMatrix oldCumulativeTransform = ancestorTransform * oldRootTransform; gfxMatrix newCumulativeTransform = ancestorTransform * newRootTransform; if (newCumulativeTransform.IsSingular()) { return; } gfxMatrix newCumulativeTransformInverse = newCumulativeTransform; newCumulativeTransformInverse.Invert(); // Now work out the translation necessary to make sure the layer doesn't // move given the new sub-tree root transform. gfxMatrix layerTransform; if (!GetBaseTransform2D(aLayer, &layerTransform)) { return; } // Calculate any offset necessary, in previous transform sub-tree root // space. This is used to make sure fixed position content respects // content document fixed position margins. LayerPoint offsetInOldSubtreeLayerSpace = GetLayerFixedMarginsOffset(aLayer, aFixedLayerMargins); // Add the above offset to the anchor point so we can offset the layer by // and amount that's specified in old subtree layer space. const LayerPoint& anchorInOldSubtreeLayerSpace = aLayer->GetFixedPositionAnchor(); LayerPoint offsetAnchorInOldSubtreeLayerSpace = anchorInOldSubtreeLayerSpace + offsetInOldSubtreeLayerSpace; // Add the local layer transform to the two points to make the equation // below this section more convenient. gfxPoint anchor(anchorInOldSubtreeLayerSpace.x, anchorInOldSubtreeLayerSpace.y); gfxPoint offsetAnchor(offsetAnchorInOldSubtreeLayerSpace.x, offsetAnchorInOldSubtreeLayerSpace.y); gfxPoint locallyTransformedAnchor = layerTransform.Transform(anchor); gfxPoint locallyTransformedOffsetAnchor = layerTransform.Transform(offsetAnchor); // Transforming the locallyTransformedAnchor by oldCumulativeTransform // returns the layer's anchor point relative to the parent of // aTransformedSubtreeRoot, before the new transform was applied. // Then, applying newCumulativeTransformInverse maps that point relative // to the layer's parent, which is the same coordinate space as // locallyTransformedAnchor again, allowing us to subtract them and find // out the offset necessary to make sure the layer stays stationary. gfxPoint oldAnchorPositionInNewSpace = newCumulativeTransformInverse.Transform( oldCumulativeTransform.Transform(locallyTransformedOffsetAnchor)); gfxPoint translation = oldAnchorPositionInNewSpace - locallyTransformedAnchor; // Finally, apply the 2D translation to the layer transform. TranslateShadowLayer2D(aLayer, translation); // The transform has now been applied, so there's no need to iterate over // child layers. return; } for (Layer* child = aLayer->GetFirstChild(); child; child = child->GetNextSibling()) { AlignFixedLayersForAnchorPoint(child, aTransformedSubtreeRoot, aPreviousTransformForRoot, aFixedLayerMargins); } }
void LayerModel::setLayerOpacity(int layerIndex, float opacity) { Layer *layer = mMap->layerAt(layerIndex); layer->setOpacity(opacity); emit layerChanged(layerIndex); }
bool AsyncCompositionManager::ApplyAsyncContentTransformToTree(TimeStamp aCurrentFrame, Layer *aLayer, bool* aWantNextFrame) { bool appliedTransform = false; for (Layer* child = aLayer->GetFirstChild(); child; child = child->GetNextSibling()) { appliedTransform |= ApplyAsyncContentTransformToTree(aCurrentFrame, child, aWantNextFrame); } ContainerLayer* container = aLayer->AsContainerLayer(); if (!container) { return appliedTransform; } if (AsyncPanZoomController* controller = container->GetAsyncPanZoomController()) { LayerComposite* layerComposite = aLayer->AsLayerComposite(); gfx3DMatrix oldTransform = aLayer->GetTransform(); ViewTransform treeTransform; ScreenPoint scrollOffset; *aWantNextFrame |= controller->SampleContentTransformForFrame(aCurrentFrame, &treeTransform, scrollOffset); const gfx3DMatrix& rootTransform = mLayerManager->GetRoot()->GetTransform(); const FrameMetrics& metrics = container->GetFrameMetrics(); // XXX We use rootTransform instead of metrics.mResolution here because on // Fennec the resolution is set on the root layer rather than the scrollable layer. // The SyncFrameMetrics call and the paintScale variable are used on Fennec only // so it doesn't affect any other platforms. See bug 732971. CSSToLayerScale paintScale = metrics.mDevPixelsPerCSSPixel / LayerToLayoutDeviceScale(rootTransform.GetXScale(), rootTransform.GetYScale()); CSSRect displayPort(metrics.mCriticalDisplayPort.IsEmpty() ? metrics.mDisplayPort : metrics.mCriticalDisplayPort); LayerMargin fixedLayerMargins(0, 0, 0, 0); ScreenPoint offset(0, 0); SyncFrameMetrics(scrollOffset, treeTransform.mScale.scale, metrics.mScrollableRect, mLayersUpdated, displayPort, paintScale, mIsFirstPaint, fixedLayerMargins, offset); mIsFirstPaint = false; mLayersUpdated = false; // Apply the render offset mLayerManager->GetCompositor()->SetScreenRenderOffset(offset); gfx3DMatrix transform(gfx3DMatrix(treeTransform) * aLayer->GetTransform()); // 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. transform.Scale(1.0f/container->GetPreXScale(), 1.0f/container->GetPreYScale(), 1); transform.ScalePost(1.0f/aLayer->GetPostXScale(), 1.0f/aLayer->GetPostYScale(), 1); layerComposite->SetShadowTransform(transform); NS_ASSERTION(!layerComposite->GetShadowTransformSetByAnimation(), "overwriting animated transform!"); // Apply resolution scaling to the old transform - the layer tree as it is // doesn't have the necessary transform to display correctly. #ifdef MOZ_WIDGET_ANDROID // XXX We use rootTransform instead of the resolution on the individual layer's // FrameMetrics on Fennec because the resolution is set on the root layer rather // than the scrollable layer. See bug 732971. On non-Fennec we do the right thing. LayoutDeviceToLayerScale resolution(1.0 / rootTransform.GetXScale(), 1.0 / rootTransform.GetYScale()); #else LayoutDeviceToLayerScale resolution = metrics.mResolution; #endif oldTransform.Scale(resolution.scale, resolution.scale, 1); AlignFixedLayersForAnchorPoint(aLayer, aLayer, oldTransform, fixedLayerMargins); appliedTransform = true; } return appliedTransform; }
tools::ToolLoop* create_tool_loop(Editor* editor, Context* context) { tools::Tool* current_tool = editor->getCurrentEditorTool(); tools::Ink* current_ink = editor->getCurrentEditorInk(); if (!current_tool || !current_ink) return NULL; Layer* layer = editor->layer(); if (!layer) { StatusBar::instance()->showTip(1000, "There is no active layer"); return NULL; } // If the active layer is not visible. if (!layer->isVisible()) { StatusBar::instance()->showTip(1000, "Layer '%s' is hidden", layer->name().c_str()); return NULL; } // If the active layer is read-only. else if (!layer->isEditable()) { StatusBar::instance()->showTip(1000, "Layer '%s' is locked", layer->name().c_str()); return NULL; } // Get fg/bg colors ColorBar* colorbar = ColorBar::instance(); app::Color fg = colorbar->getFgColor(); app::Color bg = colorbar->getBgColor(); ASSERT(fg.isValid()); ASSERT(bg.isValid()); if (!fg.isValid() || !bg.isValid()) { Alert::show(PACKAGE "<<The current selected foreground and/or background color" "<<is out of range. Select a valid color in the color-bar." "||&Close"); return NULL; } // Create the new tool loop try { return new ToolLoopImpl( editor, context, current_tool, current_ink, editor->document(), !editor->isSecondaryButton() ? tools::ToolLoop::Left: tools::ToolLoop::Right, fg, bg); } catch (const std::exception& ex) { Alert::show(PACKAGE "<<Error drawing ink:" "<<%s" "||&Close", ex.what()); return NULL; } }