void TileController::didRevalidateTiles()
{
    m_boundsAtLastRevalidate = bounds();

    updateTileCoverageMap();
}
示例#2
0
IntSize TiledLayerChromium::contentBounds() const
{
    return IntSize(lroundf(bounds().width() * contentsScale()), lroundf(bounds().height() * contentsScale()));
}
示例#3
0
文件: FLTKcode.cpp 项目: JenningsF/AI
    // CONSTRUCTOR
    MyTimer(int X,int Y,int W,int H,const char*L=0) : Fl_Chart(X,Y,W,H,L) {
        type(FL_LINE_CHART); 
		bounds(0,110); 
        Fl::add_timeout(0.25, Timer_CB, (void*)this);
    }
示例#4
0
void Boid3d:: update(const float amount) {
	
	// float vec[] = flock(amount);// flockfull(amount);
	//float * vec = flockfull(amount);
	
	// reset acc on begin 2 draw
	ax = 0;
	ay = 0;
	az = 0;
	
	
	
	float *vec = new float[3];	
	vec[0] = 0.0f;
	vec[1] = 0.0f;
	vec[2] = 0.0f;
	
	//	flock(amount, vec);
	flockfull(amount, vec);
	
	ax += vec[0];// *amount;
	ay += vec[1];// *amount;
	az += vec[2];
	
	delete [] vec;
	
	// change this to allow flock flock interaction
	// accX = vec[0];
	// accY = vec[1];
	
	// limit force
	float distMaxForce = ABS(ax) + ABS(ay) + ABS(az);
	if (distMaxForce > flockPtr->maxForce) {
		distMaxForce = flockPtr->maxForce / distMaxForce;
		ax *= distMaxForce;
		ay *= distMaxForce;
		az *= distMaxForce;
	}
	
	vx += ax;
	vy += ay;
	vz += az;
	
	// limit speed
	float distMaxSpeed = ABS(vx) + ABS(vy) + ABS(vz);
	if (distMaxSpeed > flockPtr->maxSpeed) {
		distMaxSpeed = flockPtr->maxSpeed / distMaxSpeed;
		vx *= distMaxSpeed;
		vy *= distMaxSpeed;
		vz *= distMaxSpeed;
	}
	
	x += vx * amount;
	y += vy * amount;
	z += vz * amount;
	
	bounds();
	
//	// reset acc on end
//	ax = 0;
//	ay = 0;
//	az = 0;
}
/*
============
idFrustum::ProjectionBounds
============
*/
bool idFrustum::ProjectionBounds( const idBox &box, idBounds &projectionBounds ) const {
	int i, p1, p2, pointCull[8], culled, outside;
	float scale1, scale2;
	idFrustum localFrustum;
	idVec3 points[8], localOrigin;
	idMat3 localAxis, localScaled;
	idBounds bounds( -box.GetExtents(), box.GetExtents() );

	// if the frustum origin is inside the bounds
	if ( bounds.ContainsPoint( ( origin - box.GetCenter() ) * box.GetAxis().Transpose() ) ) {
		// bounds that cover the whole frustum
		float boxMin, boxMax, base;

		base = origin * axis[0];
		box.AxisProjection( axis[0], boxMin, boxMax );

		projectionBounds[0].x = boxMin - base;
		projectionBounds[1].x = boxMax - base;
		projectionBounds[0].y = projectionBounds[0].z = -1.0f;
		projectionBounds[1].y = projectionBounds[1].z = 1.0f;

		return true;
	}

	projectionBounds.Clear();

	// transform the bounds into the space of this frustum
	localOrigin = ( box.GetCenter() - origin ) * axis.Transpose();
	localAxis = box.GetAxis() * axis.Transpose();
	BoxToPoints( localOrigin, box.GetExtents(), localAxis, points );

	// test outer four edges of the bounds
	culled = -1;
	outside = 0;
	for ( i = 0; i < 4; i++ ) {
		p1 = i;
		p2 = 4 + i;
		AddLocalLineToProjectionBoundsSetCull( points[p1], points[p2], pointCull[p1], pointCull[p2], projectionBounds );
		culled &= pointCull[p1] & pointCull[p2];
		outside |= pointCull[p1] | pointCull[p2];
	}

	// if the bounds are completely outside this frustum
	if ( culled ) {
		return false;
	}

	// if the bounds are completely inside this frustum
	if ( !outside ) {
		return true;
	}

	// test the remaining edges of the bounds
	for ( i = 0; i < 4; i++ ) {
		p1 = i;
		p2 = (i+1)&3;
		AddLocalLineToProjectionBoundsUseCull( points[p1], points[p2], pointCull[p1], pointCull[p2], projectionBounds );
	}

	for ( i = 0; i < 4; i++ ) {
		p1 = 4 + i;
		p2 = 4 + ((i+1)&3);
		AddLocalLineToProjectionBoundsUseCull( points[p1], points[p2], pointCull[p1], pointCull[p2], projectionBounds );
	}

	// if the bounds extend beyond two or more boundaries of this frustum
	if ( outside != 1 && outside != 2 && outside != 4 && outside != 8 ) {

		localOrigin = ( origin - box.GetCenter() ) * box.GetAxis().Transpose();
		localScaled = axis * box.GetAxis().Transpose();
		localScaled[0] *= dFar;
		localScaled[1] *= dLeft;
		localScaled[2] *= dUp;

		// test the outer edges of this frustum for intersection with the bounds
		if ( (outside & 2) && (outside & 8) ) {
			BoundsRayIntersection( bounds, localOrigin, localScaled[0] - localScaled[1] - localScaled[2], scale1, scale2 );
			if ( scale1 <= scale2 && scale1 >= 0.0f ) {
				projectionBounds.AddPoint( idVec3( scale1 * dFar, -1.0f, -1.0f ) );
				projectionBounds.AddPoint( idVec3( scale2 * dFar, -1.0f, -1.0f ) );
			}
		}
		if ( (outside & 2) && (outside & 4) ) {
			BoundsRayIntersection( bounds, localOrigin, localScaled[0] - localScaled[1] + localScaled[2], scale1, scale2 );
			if ( scale1 <= scale2 && scale1 >= 0.0f  ) {
				projectionBounds.AddPoint( idVec3( scale1 * dFar, -1.0f, 1.0f ) );
				projectionBounds.AddPoint( idVec3( scale2 * dFar, -1.0f, 1.0f ) );
			}
		}
		if ( (outside & 1) && (outside & 8) ) {
			BoundsRayIntersection( bounds, localOrigin, localScaled[0] + localScaled[1] - localScaled[2], scale1, scale2 );
			if ( scale1 <= scale2 && scale1 >= 0.0f  ) {
				projectionBounds.AddPoint( idVec3( scale1 * dFar, 1.0f, -1.0f ) );
				projectionBounds.AddPoint( idVec3( scale2 * dFar, 1.0f, -1.0f ) );
			}
		}
		if ( (outside & 1) && (outside & 2) ) {
			BoundsRayIntersection( bounds, localOrigin, localScaled[0] + localScaled[1] + localScaled[2], scale1, scale2 );
			if ( scale1 <= scale2 && scale1 >= 0.0f  ) {
				projectionBounds.AddPoint( idVec3( scale1 * dFar, 1.0f, 1.0f ) );
				projectionBounds.AddPoint( idVec3( scale2 * dFar, 1.0f, 1.0f ) );
			}
		}
	}

	return true;
}
示例#6
0
char num_to_digit_equiv(int ost) {
	if (bounds(ost, 0, 9))
		return ost + '0';
	else if (bounds(ost, 10, 15))
		return ost - 10 + 'a';
}
示例#7
0
void EditorToolbar::HandleSFEvents(std::list<sf::Event>& sfEvents) {
	bool mouseOverPressed = false;

	std::list<sf::Event>::iterator itSfEvent = sfEvents.begin();
	while (itSfEvent != sfEvents.end()) {
		switch (itSfEvent->Type) {
			case sf::Event::MouseMoved: {
				sf::Vector2f screenSize(background->GetScreenSize());
				sf::Vector2f fakePos(background->CalcFakePos());
				sf::Rect<float> bounds(fakePos.x - (screenSize.x / 2),
										fakePos.y - (screenSize.y / 2),
										fakePos.x + (screenSize.x / 2),
										fakePos.y + (screenSize.y / 2 ));

				hover = bounds.Contains(itSfEvent->MouseMove.X, itSfEvent->MouseMove.Y) ? true : false;

				if (dragging) {
					float before = toolViewOffsetY;

					toolViewOffsetY += (itSfEvent->MouseMove.Y - lastMousePressedY);

					CalcViewOffsetY();

					lastMousePressedY += toolViewOffsetY - before;

					/* mouse leaving window messes up values on _WINDOWS_
					 * 	so this still does not solve anything :/
					 * */
//					if (!Game->GetRenderWindow()->GetInput().IsMouseButtonDown(sf::Mouse::Left))
//						dragging = false;
				}
			} break;
			case sf::Event::MouseWheelMoved:
				if (hover && !tools.empty()) {
					toolViewOffsetY += Game->GetDeltaTime() * WHEELSCROLLSPD * itSfEvent->MouseWheel.Delta;

					CalcViewOffsetY();
				}
			break;
			case sf::Event::MouseButtonPressed:
				if (hover) {
					if (!tools.empty()) {
						if (itSfEvent->MouseButton.Button == sf::Mouse::Left) {
							lastMousePressedY = itSfEvent->MouseButton.Y;

							dragging = true;
						}
					}

					mouseOverPressed = true;
				}
			break;
			case sf::Event::MouseButtonReleased:
				dragging = false;
			break;
			case sf::Event::Resized:
				CalcViewOffsetY();
			break;
			default:
			break;
		}

		itSfEvent++;
	}

	toolEventID = -2;

	for (std::vector<EditorToolButton*>::iterator itTool = tools.begin();
			itTool != tools.end(); itTool++) {
		(*itTool)->HandleSFEvents(sfEvents);
	}

	if (toolEventID != -2) {
		for (std::vector<EditorToolButton*>::iterator itTool = tools.begin();
				itTool != tools.end(); itTool++) {
			if ((*itTool)->GetID() != toolEventID) {
				(*itTool)->SetActive(false);
			}
		}

		toolSelected(toolEventID);
		activeID = toolEventID;

		if (toolEventID == -1 && mouseOverPressed) {
			// if no tool was activated - the event wasn't eaten
			// but the mouse pressed over the toolbar
			// then eat it still

			itSfEvent = sfEvents.begin();
			while (itSfEvent != sfEvents.end()) {
				switch (itSfEvent->Type) {
					case sf::Event::MouseButtonPressed:
						itSfEvent =	--sfEvents.erase(itSfEvent);
					break;
					default:
					break;
				}

				itSfEvent++;
			}
		}
	}
}
示例#8
0
ProjectWindow::ProjectWindow(BRect frame, Project *project)
	:	DWindow(frame, "Paladin", B_DOCUMENT_WINDOW, B_NOT_ZOOMABLE |
													B_WILL_ACCEPT_FIRST_CLICK),
		fErrorWindow(NULL),
		fFilePanel(NULL),
		fProject(project),
		fSourceControl(NULL),
		fShowingLibs(false),
		fMenusLocked(false),
		fBuilder(BMessenger(this))
{
	AddCommonFilter(new AltTabFilter());
	SetSizeLimits(200,30000,200,30000);
	RegisterWindow();
	
	// This is for our in-program debug menu which comes in handy now and then.
	// Paladin -d doesn't always get the job done
	AddShortcut('9', B_COMMAND_KEY | B_SHIFT_KEY | B_CONTROL_KEY,
				new BMessage(M_TOGGLE_DEBUG_MENU));
	
	if (fProject)
	{
		fSourceControl = GetSCM(fProject->SourceControl());
		if (fSourceControl)
		{
			if (gPrintDebugMode > 0)
				fSourceControl->SetDebugMode(true);
			
			fSourceControl->SetUpdateCallback(SCMOutputCallback);
			fSourceControl->SetWorkingDirectory(fProject->GetPath().GetFolder());
			
			if (fSourceControl->NeedsInit(fProject->GetPath().GetFolder()))
				fSourceControl->CreateRepository(fProject->GetPath().GetFolder());
		}
	}
	
	BView *top = GetBackgroundView();
	
	BRect bounds(Bounds());
	BRect r(bounds);
	
	r.bottom = 16;
	fMenuBar = new BMenuBar(r,"documentbar");
	top->AddChild(fMenuBar);
	
	r = bounds;
	r.top = fMenuBar->Frame().bottom + 1;
	r.right -= B_V_SCROLL_BAR_WIDTH;
	r.bottom -= B_H_SCROLL_BAR_HEIGHT;
	
	fProjectList = new ProjectList(fProject, r,"filelist",B_FOLLOW_ALL);
	fProjectList->SetInvocationMessage(new BMessage(M_EDIT_FILE));
	
	BScrollView *scrollView = new BScrollView("scrollView",fProjectList,
											B_FOLLOW_ALL,0,false,true);
	top->AddChild(scrollView);
	fProjectList->SetTarget(this);
	
	r.top = r.bottom + 1;
	r.bottom = Bounds().bottom;
	fStatusBar = new BStringView(r,"statusbar", NULL, B_FOLLOW_LEFT_RIGHT |
														B_FOLLOW_BOTTOM);
	top->AddChild(fStatusBar);
	
	fStatusBar->SetViewColor(235,235,235);
	fStatusBar->SetFontSize(10.0);
	
	SetupMenus();
	
	if (project)
	{
		BString title("Paladin: ");
		title << project->GetName();
		SetTitle(title.String());
		
		for (int32 i = 0; i < project->CountGroups(); i++)
		{
			SourceGroup *group = project->GroupAt(i);
			SourceGroupItem *groupitem = new SourceGroupItem(group);
			fProjectList->AddItem(groupitem);
			groupitem->SetExpanded(group->expanded);
			
			for (int32 j = 0; j < group->filelist.CountItems(); j++)
			{
				SourceFile *file = group->filelist.ItemAt(j);
				SourceFileItem *fileitem = new SourceFileItem(file,1);
				
//				fProjectList->AddUnder(fileitem,groupitem);
				fProjectList->AddItem(fileitem);
				
				BString abspath = file->GetPath().GetFullPath();
				if (abspath[0] != '/')
				{
					abspath.Prepend("/");
					abspath.Prepend(project->GetPath().GetFolder());
				}
				BEntry entry(abspath.String());
				if (entry.Exists())
				{
					if (project->CheckNeedsBuild(file,false))
					{
						fileitem->SetDisplayState(SFITEM_NEEDS_BUILD);
						fProjectList->InvalidateItem(fProjectList->IndexOf(fileitem));
					}
					else
						file->SetBuildFlag(BUILD_NO);
				}
				else
				{
					fileitem->SetDisplayState(SFITEM_MISSING);
					fProjectList->InvalidateItem(fProjectList->IndexOf(fileitem));
				}
			}
		}
	}
	
	BNode node(fProject->GetPath().GetFullPath());
	if (node.ReadAttr("project_frame",B_RECT_TYPE,0,&r,sizeof(BRect)) == sizeof(BRect))
	{
		if (r.Width() < 200)
			r.right = r.left + 200;
		if (r.Height() < 200)
			r.top = r.bottom + 200;
		MoveTo(r.left,r.top);
		ResizeTo(r.Width(),r.Height());
	}
	
	fProjectList->MakeFocus(true);
	
	if (gShowFolderOnOpen)
	{
		// Duplicated code from MessageReceived::M_SHOW_PROJECT_FOLDER. Doing
		// it here in combo with snooze() makes it much more likely that the
		// opened project window is frontmost instead of the project folder's window
		entry_ref ref;
		BEntry(fProject->GetPath().GetFolder()).GetRef(&ref);
		BMessenger msgr("application/x-vnd.Be-TRAK");
		
		BMessage reply;
		BMessage openmsg(B_REFS_RECEIVED);
		openmsg.AddRef("refs",&ref);
		msgr.SendMessage(&openmsg);
		snooze(50000);
	}
	
	if (gAutoSyncModules)
		PostMessage(M_SYNC_MODULES);
}
示例#9
0
void TextField::ContentView::setBackgroundColor(KDColor backgroundColor) {
  m_backgroundColor = backgroundColor;
  markRectAsDirty(bounds());
}
示例#10
0
void PageOverlay::setNeedsDisplay()
{
    setNeedsDisplay(bounds());
}
示例#11
0
void PopUpController::ContentView::drawRect(KDContext * ctx, KDRect rect) const {
  ctx->fillRect(bounds(), KDColorBlack);
}
示例#12
0
Bounds line_bounds(const Vector2D& origin, const Matrix2D& m, const Vector2D& p1, const Vector2D& p2) {
	Bounds bounds(origin + p1 * m);
	bounds.update(origin + p2 * m);
	return bounds;
}
/**
 * Try the direct path.
 * @return True if we took the direct path
 */
PRBool
gfxXlibNativeRenderer::DrawDirect(gfxContext *ctx, nsIntSize size,
                                  PRUint32 flags,
                                  Screen *screen, Visual *visual)
{
    cairo_t *cr = ctx->GetCairo();

    /* Check that the target surface is an xlib surface. */
    cairo_surface_t *target = cairo_get_group_target (cr);
    if (cairo_surface_get_type (target) != CAIRO_SURFACE_TYPE_XLIB) {
        NATIVE_DRAWING_NOTE("FALLBACK: non-X surface");
        return PR_FALSE;
    }
    
    cairo_matrix_t matrix;
    cairo_get_matrix (cr, &matrix);
    double device_offset_x, device_offset_y;
    cairo_surface_get_device_offset (target, &device_offset_x, &device_offset_y);

    /* Draw() checked that the matrix contained only a very-close-to-integer
       translation.  Here (and in several other places and thebes) device
       offsets are assumed to be integer. */
    NS_ASSERTION(PRInt32(device_offset_x) == device_offset_x &&
                 PRInt32(device_offset_y) == device_offset_y,
                 "Expected integer device offsets");
    nsIntPoint offset(NS_lroundf(matrix.x0 + device_offset_x),
                      NS_lroundf(matrix.y0 + device_offset_y));
    
    int max_rectangles = 0;
    if (flags & DRAW_SUPPORTS_CLIP_RECT) {
      max_rectangles = 1;
    }
    if (flags & DRAW_SUPPORTS_CLIP_LIST) {
      max_rectangles = MAX_STATIC_CLIP_RECTANGLES;
    }

    /* The client won't draw outside the surface so consider this when
       analysing clip rectangles. */
    nsIntRect bounds(offset, size);
    bounds.IntersectRect(bounds,
                         nsIntRect(0, 0,
                                   cairo_xlib_surface_get_width(target),
                                   cairo_xlib_surface_get_height(target)));

    PRBool needs_clip = PR_TRUE;
    nsIntRect rectangles[MAX_STATIC_CLIP_RECTANGLES];
    int rect_count = 0;

    /* Check that the clip is rectangular and aligned on unit boundaries. */
    /* Temporarily set the matrix for _get_rectangular_clip. It's basically
       the identity matrix, but we must adjust for the fact that our
       offset-rect is in device coordinates. */
    cairo_identity_matrix (cr);
    cairo_translate (cr, -device_offset_x, -device_offset_y);
    PRBool have_rectangular_clip =
        _get_rectangular_clip (cr, bounds, &needs_clip,
                               rectangles, max_rectangles, &rect_count);
    cairo_set_matrix (cr, &matrix);
    if (!have_rectangular_clip)
        return PR_FALSE;

    /* Stop now if everything is clipped out */
    if (needs_clip && rect_count == 0)
        return PR_TRUE;
      
    /* Check that the screen is supported.
       Visuals belong to screens, so, if alternate visuals are not supported,
       then alternate screens cannot be supported. */  
    PRBool supports_alternate_visual =
        (flags & DRAW_SUPPORTS_ALTERNATE_VISUAL) != 0;
    PRBool supports_alternate_screen = supports_alternate_visual &&
        (flags & DRAW_SUPPORTS_ALTERNATE_SCREEN);
    if (!supports_alternate_screen &&
        cairo_xlib_surface_get_screen (target) != screen) {
        NATIVE_DRAWING_NOTE("FALLBACK: non-default screen");
        return PR_FALSE;
    }
        
    /* Check that there is a visual */
    Visual *target_visual = cairo_xlib_surface_get_visual (target);
    if (!target_visual) {
        NATIVE_DRAWING_NOTE("FALLBACK: no Visual for surface");
        return PR_FALSE;
    }        
    /* Check that the visual is supported */
    if (!supports_alternate_visual && target_visual != visual) {
        // Only the format of the visual is important (not the GLX properties)
        // for Xlib or XRender drawing.
        XRenderPictFormat *target_format =
            cairo_xlib_surface_get_xrender_format (target);
        if (!target_format ||
            (target_format !=
             XRenderFindVisualFormat (DisplayOfScreen(screen), visual))) {
            NATIVE_DRAWING_NOTE("FALLBACK: unsupported Visual");
            return PR_FALSE;
        }
    }
  
    /* we're good to go! */
    NATIVE_DRAWING_NOTE("TAKING FAST PATH\n");
    cairo_surface_flush (target);
    nsRefPtr<gfxASurface> surface = gfxASurface::Wrap(target);
    nsresult rv = DrawWithXlib(static_cast<gfxXlibSurface*>(surface.get()),
                               offset, rectangles,
                               needs_clip ? rect_count : 0);
    if (NS_SUCCEEDED(rv)) {
        cairo_surface_mark_dirty (target);
        return PR_TRUE;
    }
    return PR_FALSE;
}
示例#14
0
bool WKCACFLayerRenderer::createRenderer()
{
    if (m_d3dDevice || !m_mightBeAbleToCreateDeviceLater)
        return m_d3dDevice;

    m_mightBeAbleToCreateDeviceLater = false;
    D3DPRESENT_PARAMETERS parameters = initialPresentationParameters();

    if (!d3d() || !::IsWindow(m_hostWindow))
        return false;

    // D3D doesn't like to make back buffers for 0 size windows. We skirt this problem if we make the
    // passed backbuffer width and height non-zero. The window will necessarily get set to a non-zero
    // size eventually, and then the backbuffer size will get reset.
    RECT rect;
    GetClientRect(m_hostWindow, &rect);

    if (rect.left-rect.right == 0 || rect.bottom-rect.top == 0) {
        parameters.BackBufferWidth = 1;
        parameters.BackBufferHeight = 1;
    }

    D3DCAPS9 d3dCaps;
    if (FAILED(d3d()->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &d3dCaps)))
        return false;

    DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE;
    if ((d3dCaps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) && d3dCaps.VertexProcessingCaps)
        behaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
    else
        behaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;

    COMPtr<IDirect3DDevice9> device;
    if (FAILED(d3d()->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_hostWindow, behaviorFlags, &parameters, &device))) {
        // In certain situations (e.g., shortly after waking from sleep), Direct3DCreate9() will
        // return an IDirect3D9 for which IDirect3D9::CreateDevice will always fail. In case we
        // have one of these bad IDirect3D9s, get rid of it so we'll fetch a new one the next time
        // we want to call CreateDevice.
        s_d3d->Release();
        s_d3d = 0;

        // Even if we don't have a bad IDirect3D9, in certain situations (e.g., shortly after
        // waking from sleep), CreateDevice will fail, but will later succeed if called again.
        m_mightBeAbleToCreateDeviceLater = true;

        return false;
    }

    // Now that we've created the IDirect3DDevice9 based on the capabilities we
    // got from the IDirect3D9 global object, we requery the device for its
    // actual capabilities. The capabilities returned by the device can
    // sometimes be more complete, for example when using software vertex
    // processing.
    D3DCAPS9 deviceCaps;
    if (FAILED(device->GetDeviceCaps(&deviceCaps)))
        return false;

    if (!hardwareCapabilitiesIndicateCoreAnimationSupport(deviceCaps))
        return false;

    m_d3dDevice = device;

    D3DXMATRIXA16 projection;
    D3DXMatrixOrthoOffCenterRH(&projection, rect.left, rect.right, rect.top, rect.bottom, -1.0f, 1.0f);

    m_d3dDevice->SetTransform(D3DTS_PROJECTION, &projection);

    m_renderer = CARenderOGLNew(&kCARenderDX9Callbacks, m_d3dDevice.get(), 0);

    if (IsWindow(m_hostWindow))
        m_rootLayer->setBounds(bounds());

    return true;
}
示例#15
0
void
ShowImageWindow::_Print(BMessage* msg)
{
	status_t st;
	if (msg->FindInt32("status", &st) != B_OK || st != B_OK)
		return;

	_SavePrintOptions();

	BPrintJob printJob(fImageView->Image()->name);
	if (fPrintSettings)
		printJob.SetSettings(new BMessage(*fPrintSettings));

	if (printJob.ConfigJob() == B_OK) {
		delete fPrintSettings;
		fPrintSettings = printJob.Settings();

		// first/lastPage is unused for now
		int32 firstPage = printJob.FirstPage();
		int32 lastPage = printJob.LastPage();
		BRect printableRect = printJob.PrintableRect();

		if (firstPage < 1)
			firstPage = 1;
		if (lastPage < firstPage)
			lastPage = firstPage;

		BBitmap* bitmap = fImageView->Bitmap();
		float imageWidth = bitmap->Bounds().Width() + 1.0;
		float imageHeight = bitmap->Bounds().Height() + 1.0;

		float width;
		switch (fPrintOptions.Option()) {
			case PrintOptions::kFitToPage: {
				float w1 = printableRect.Width() + 1;
				float w2 = imageWidth * (printableRect.Height() + 1)
					/ imageHeight;
				if (w2 < w1)
					width = w2;
				else
					width = w1;
			}	break;
			case PrintOptions::kZoomFactor:
				width = imageWidth * fPrintOptions.ZoomFactor();
				break;
			case PrintOptions::kDPI:
				width = imageWidth * 72.0 / fPrintOptions.DPI();
				break;
			case PrintOptions::kWidth:
			case PrintOptions::kHeight:
				width = fPrintOptions.Width();
				break;

			default:
				// keep compiler silent; should not reach here
				width = imageWidth;
		}

		// TODO: eventually print large images on several pages
		printJob.BeginJob();
		fImageView->SetScale(width / imageWidth);
		// coordinates are relative to printable rectangle
		BRect bounds(bitmap->Bounds());
		printJob.DrawView(fImageView, bounds, BPoint(0, 0));
		fImageView->SetScale(1.0);
		printJob.SpoolPage();
		printJob.CommitJob();
	}
}
示例#16
0
void TextField::ContentView::setTextColor(KDColor textColor) {
  m_textColor = textColor;
  markRectAsDirty(bounds());
}
示例#17
0
int main(int argc, char* argv[]) {

  Teuchos::GlobalMPISession mpiSession(&argc, &argv);

  // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided.
  int iprint     = argc - 1;
  Teuchos::RCP<std::ostream> outStream;
  Teuchos::oblackholestream bhs; // outputs nothing
  if (iprint > 0)
    outStream = Teuchos::rcp(&std::cout, false);
  else
    outStream = Teuchos::rcp(&bhs, false);

  int errorFlag  = 0;

  try {
    /**********************************************************************************************/
    /************************* CONSTRUCT ROL ALGORITHM ********************************************/
    /**********************************************************************************************/
    // Get ROL parameterlist
    std::string filename = "input_01.xml";
    Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() );
    Teuchos::updateParametersFromXmlFile( filename, parlist.ptr() );
    Teuchos::ParameterList list = *parlist;
    /**********************************************************************************************/
    /************************* CONSTRUCT SOL COMPONENTS *******************************************/
    /**********************************************************************************************/
    // Build vectors
    unsigned dim = 4;
    Teuchos::RCP<std::vector<RealT> > x_rcp = Teuchos::rcp( new std::vector<RealT>(dim,0.0) );
    Teuchos::RCP<ROL::Vector<RealT> > x = Teuchos::rcp(new ROL::StdVector<RealT>(x_rcp));
    Teuchos::RCP<std::vector<RealT> > d_rcp = Teuchos::rcp( new std::vector<RealT>(dim,0.0) );
    Teuchos::RCP<ROL::Vector<RealT> > d = Teuchos::rcp(new ROL::StdVector<RealT>(d_rcp));
    setRandomVector(*d_rcp);
    // Build samplers
    int nSamp = 1000;  
    unsigned sdim = dim + 2;
    std::vector<RealT> tmp(2,0.); tmp[0] = -1.; tmp[1] = 1.;
    std::vector<std::vector<RealT> > bounds(sdim,tmp);
    Teuchos::RCP<ROL::BatchManager<RealT> > bman =
      Teuchos::rcp(new ROL::BatchManager<RealT>());
    Teuchos::RCP<ROL::SampleGenerator<RealT> > sampler =
      Teuchos::rcp(new ROL::MonteCarloGenerator<RealT>(nSamp,bounds,bman,false,false,100));
    // Build risk-averse objective function
    Teuchos::RCP<ROL::ParametrizedObjective<RealT> > pObj =
      Teuchos::rcp(new ParametrizedObjectiveEx1<RealT>);
    // Build bound constraints
    std::vector<RealT> l(dim,0.0);
    std::vector<RealT> u(dim,1.0);
    Teuchos::RCP<ROL::BoundConstraint<RealT> > bnd = 
      Teuchos::rcp( new ROL::StdBoundConstraint<RealT>(l,u) );
    bnd->deactivate();
    // Test parametrized objective functions
    *outStream << "Check Derivatives of Parametrized Objective Function\n";
    pObj->setParameter(sampler->getMyPoint(0));
    pObj->checkGradient(*x,*d,true,*outStream);
    pObj->checkHessVec(*x,*d,true,*outStream);
    /**********************************************************************************************/
    /************************* MEAN VALUE *********************************************************/
    /**********************************************************************************************/
    *outStream << "\nMEAN VALUE\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Mean Value"); 
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* RISK NEUTRAL *******************************************************/
    /**********************************************************************************************/
    *outStream << "\nRISK NEUTRAL\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Neutral"); 
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* MEAN PLUS DEVIATION ************************************************/
    /**********************************************************************************************/
    *outStream << "\nMEAN PLUS DEVIATION\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Mean Plus Deviation");
    list.sublist("SOL").sublist("Risk Measure").sublist("Mean Plus Deviation").set("Deviation Type","Absolute");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* MEAN PLUS VARIANCE *************************************************/
    /**********************************************************************************************/
    *outStream << "\nMEAN PLUS VARIANCE\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Mean Plus Variance");
    list.sublist("SOL").sublist("Risk Measure").sublist("Mean Plus Variance").set("Deviation Type","Absolute");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* MEAN PLUS DEVIATION FROM TARGET ************************************/
    /**********************************************************************************************/
    *outStream << "\nMEAN PLUS DEVIATION FROM TARGET\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Mean Plus Deviation From Target");
    list.sublist("SOL").sublist("Risk Measure").sublist("Mean Plus Deviation From Target").set("Deviation Type","Absolute");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* MEAN PLUS VARIANCE FROM TARGET *************************************/
    /**********************************************************************************************/
    *outStream << "\nMEAN PLUS VARIANCE FROM TARGET\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Mean Plus Variance From Target");
    list.sublist("SOL").sublist("Risk Measure").sublist("Mean Plus Variance From Target").set("Deviation Type","Absolute");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* MEAN PLUS SEMIDEVIATION ********************************************/
    /**********************************************************************************************/
    *outStream << "\nMEAN PLUS SEMIDEVIATION\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Mean Plus Deviation");
    list.sublist("SOL").sublist("Risk Measure").sublist("Mean Plus Deviation").set("Deviation Type","Upper");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* MEAN PLUS SEMIVARIANCE *********************************************/
    /**********************************************************************************************/
    *outStream << "\nMEAN PLUS SEMIVARIANCE\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Mean Plus Variance");
    list.sublist("SOL").sublist("Risk Measure").sublist("Mean Plus Variance").set("Deviation Type","Upper");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* MEAN PLUS SEMIDEVIATION FROM TARGET ********************************/
    /**********************************************************************************************/
    *outStream << "\nMEAN PLUS SEMIDEVIATION FROM TARGET\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Mean Plus Deviation From Target");
    list.sublist("SOL").sublist("Risk Measure").sublist("Mean Plus Deviation From Target").set("Deviation Type","Upper");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* MEAN PLUS SEMIVARIANCE FROM TARGET *********************************/
    /**********************************************************************************************/
    *outStream << "\nMEAN PLUS SEMIVARIANCE FROM TARGET\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Mean Plus Variance From Target");
    list.sublist("SOL").sublist("Risk Measure").sublist("Mean Plus Variance From Target").set("Deviation Type","Upper");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* MEAN PLUS CVAR *****************************************************/
    /**********************************************************************************************/
    *outStream << "\nMEAN PLUS CONDITIONAL VALUE AT RISK\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","CVaR");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* MEAN PLUS HMCR *****************************************************/
    /**********************************************************************************************/
    *outStream << "\nMEAN PLUS HIGHER MOMENT COHERENT RISK\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","HMCR");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* SMOOTHED CVAR QUADRANGLE *******************************************/
    /**********************************************************************************************/
    *outStream << "\nQUANTILE-BASED QUADRANGLE RISK MEASURE\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Quantile-Based Quadrangle");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* MIXED-QUANTILE QUADRANGLE ******************************************/
    /**********************************************************************************************/
    *outStream << "\nMIXED-QUANTILE QUADRANGLE RISK MEASURE\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Mixed-Quantile Quadrangle");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* SUPER QUANTILE QUADRANGLE ******************************************/
    /**********************************************************************************************/
    *outStream << "\nSUPER QUANTILE QUADRANGLE RISK MEASURE\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Super Quantile Quadrangle");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* CHEBYSHEV 1 KUSUOKA ************************************************/
    /**********************************************************************************************/
    *outStream << "\nCHEBYSHEV 1 KUSUOKA RISK MEASURE\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Chebyshev-Kusuoka");
    list.sublist("SOL").sublist("Risk Measure").sublist("Chebyshev-Kusuoka").set("Weight Type",1);
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* CHEBYSHEV 2 KUSUOKA ************************************************/
    /**********************************************************************************************/
    *outStream << "\nCHEBYSHEV 2 KUSUOKA RISK MEASURE\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Chebyshev-Kusuoka");
    list.sublist("SOL").sublist("Risk Measure").sublist("Chebyshev-Kusuoka").set("Weight Type",2);
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* CHEBYSHEV 3 KUSUOKA ************************************************/
    /**********************************************************************************************/
    *outStream << "\nCHEBYSHEV 3 KUSUOKA RISK MEASURE\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Chebyshev-Kusuoka");
    list.sublist("SOL").sublist("Risk Measure").sublist("Chebyshev-Kusuoka").set("Weight Type",3);
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* CHEBYSHEV 3 KUSUOKA ************************************************/
    /**********************************************************************************************/
    *outStream << "\nSINGLETON KUSUOKA RISK MEASURE\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Singleton Kusuoka");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* MEAN-VARIANCE QUADRANGLE *******************************************/
    /**********************************************************************************************/
    *outStream << "\nMEAN-VARIANCE QUADRANGLE RISK MEASURE\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Mean-Variance Quadrangle");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* QUANTILE-RANGE QUADRANGLE ******************************************/
    /**********************************************************************************************/
    *outStream << "\nQUANTILE-RADIUS QUADRANGLE RISK MEASURE\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Quantile-Radius Quadrangle");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* CHI-SQUARED DIVERGENCE *********************************************/
    /**********************************************************************************************/
    *outStream << "\nCHI-SQUARED DIVERGENCE DISTRIBUTIONALLY ROBUST\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Chi-Squared Divergence");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* KL DIVERGENCE ******************************************************/
    /**********************************************************************************************/
    *outStream << "\nKL DIVERGENCE DISTRIBUTIONALLY ROBUST\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","KL Divergence");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* COHERENT EXPONENTIAL UTILITY FUNCTION ******************************/
    /**********************************************************************************************/
    *outStream << "\nCOHERENT EXPONENTIAL UTILITY FUNCTION\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Coherent Exponential Utility");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* EXPONENTIAL UTILITY FUNCTION ***************************************/
    /**********************************************************************************************/
    *outStream << "\nEXPONENTIAL UTILITY FUNCTION\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Exponential Utility");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
    /**********************************************************************************************/
    /************************* CONVEX COMBINATION OF RISK MEASURES ********************************/
    /**********************************************************************************************/
    *outStream << "\nCONVEX COMBINATION OF RISK MEASURES\n";
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Averse"); 
    list.sublist("SOL").sublist("Risk Measure").set("Name","Convex Combination Risk Measure");
    setRandomVector(*x_rcp);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
  }
  catch (std::logic_error err) {
    *outStream << err.what() << "\n";
    errorFlag = -1000;
  }; // end try

  if (errorFlag != 0)
    std::cout << "End Result: TEST FAILED\n";
  else
    std::cout << "End Result: TEST PASSED\n";

  return 0;
}
示例#18
0
void TextField::ContentView::setAlignment(float horizontalAlignment, float verticalAlignment) {
  m_horizontalAlignment = horizontalAlignment;
  m_verticalAlignment = verticalAlignment;
  markRectAsDirty(bounds());
}
/*
 * Allocate I/O arrays for a problem.
 *
 * This is the default routine that can be overridden by the user in
 * complicated cases.
 */
void problem_alloc(bench_problem *p)
{
     int ilb, iub, olb, oub;
     int isz, osz;

     bounds(p, &ilb, &iub, &olb, &oub);
     isz = iub - ilb;
     osz = oub - olb;

     if (p->kind == PROBLEM_COMPLEX) {
	  bench_complex *in, *out;

	  p->iphyssz = isz;
	  p->inphys = in = (bench_complex *) bench_malloc(isz * sizeof(bench_complex));
	  p->in = in - ilb;
	  
	  if (p->in_place) {
	       p->out = p->in;
	       p->outphys = p->inphys;
	       p->ophyssz = p->iphyssz;
	  } else {
	       p->ophyssz = osz;
	       p->outphys = out = (bench_complex *) bench_malloc(osz * sizeof(bench_complex));
	       p->out = out - olb;
	  }
     } else if (p->kind == PROBLEM_R2R) {
	  bench_real *in, *out;

	  p->iphyssz = isz;
	  p->inphys = in = (bench_real *) bench_malloc(isz * sizeof(bench_real));
	  p->in = in - ilb;
	  
	  if (p->in_place) {
	       p->out = p->in;
	       p->outphys = p->inphys;
	       p->ophyssz = p->iphyssz;
	  } else {
	       p->ophyssz = osz;
	       p->outphys = out = (bench_real *) bench_malloc(osz * sizeof(bench_real));
	       p->out = out - olb;
	  }
     } else if (p->kind == PROBLEM_REAL && p->sign < 0) { /* R2HC */
	  bench_real *in;
	  bench_complex *out;

	  p->iphyssz = p->in_place ? (isz > osz*2 ? isz : osz*2) : isz;
	  p->inphys = in = (bench_real *) bench_malloc(p->iphyssz * sizeof(bench_real));
	  p->in = in - ilb;
	  
	  if (p->in_place) {
	       p->out = p->in;
	       p->outphys = p->inphys;
	       p->ophyssz = p->iphyssz / 2;
	  } else {
	       p->ophyssz = osz;
	       p->outphys = out = (bench_complex *) bench_malloc(osz * sizeof(bench_complex));
	       p->out = out - olb;
	  }
     } else if (p->kind == PROBLEM_REAL && p->sign > 0) { /* HC2R */
	  bench_real *out;
	  bench_complex *in;

	  p->ophyssz = p->in_place ? (osz > isz*2 ? osz : isz*2) : osz;
	  p->outphys = out = (bench_real *) bench_malloc(p->ophyssz * sizeof(bench_real));
	  p->out = out - olb;
	  
	  if (p->in_place) {
	       p->in = p->out;
	       p->inphys = p->outphys;
	       p->iphyssz = p->ophyssz / 2;
	  } else {
	       p->iphyssz = isz;
	       p->inphys = in = (bench_complex *) bench_malloc(isz * sizeof(bench_complex));
	       p->in = in - ilb;
	  }
     } else {
	  BENCH_ASSERT(0); /* TODO */
     }
}
示例#20
0
int main(int argc, char* argv[]) {

  Teuchos::GlobalMPISession mpiSession(&argc, &argv);
  Teuchos::RCP<const Teuchos::Comm<int> > commptr =
    Teuchos::DefaultComm<int>::getComm();

  // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided.
  int iprint     = argc - 1;
  Teuchos::RCP<std::ostream> outStream;
  Teuchos::oblackholestream bhs; // outputs nothing
  if (iprint > 0 && commptr->getRank()==0)
    outStream = Teuchos::rcp(&std::cout, false);
  else
    outStream = Teuchos::rcp(&bhs, false);

  int errorFlag  = 0;

  try {
    /**********************************************************************************************/
    /************************* CONSTRUCT ROL ALGORITHM ********************************************/
    /**********************************************************************************************/
    // Get ROL parameterlist
    std::string filename = "input_07.xml";
    Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() );
    Teuchos::updateParametersFromXmlFile( filename, parlist.ptr() );
    Teuchos::ParameterList list = *parlist;
    // Build ROL algorithm
    Teuchos::RCP<ROL::Algorithm<RealT> > algo;
    /**********************************************************************************************/
    /************************* CONSTRUCT SOL COMPONENTS *******************************************/
    /**********************************************************************************************/
    // Build vectors
    const unsigned dim = 4;
    Teuchos::RCP<std::vector<RealT> > x_rcp = Teuchos::rcp(new std::vector<RealT>(dim));
    Teuchos::RCP<std::vector<RealT> > d_rcp = Teuchos::rcp(new std::vector<RealT>(dim));
    Teuchos::RCP<ROL::Vector<RealT> > x = Teuchos::rcp(new ROL::StdVector<RealT>(x_rcp));
    Teuchos::RCP<ROL::Vector<RealT> > d = Teuchos::rcp(new ROL::StdVector<RealT>(d_rcp));
    setRandomVector(*x_rcp,commptr);
    setRandomVector(*d_rcp,commptr);
    // Build samplers
    const RealT zero(0), one(1);
    const int nSamp = 1000;
    const unsigned sdim = dim + 2;
    std::vector<RealT> tmp = {-one, one};
    std::vector<std::vector<RealT> > bounds(sdim,tmp);
    Teuchos::RCP<ROL::BatchManager<RealT> > bman =
      Teuchos::rcp(new ROL::StdTeuchosBatchManager<RealT,int>(commptr));
    Teuchos::RCP<ROL::SampleGenerator<RealT> > sampler =
      Teuchos::rcp(new ROL::MonteCarloGenerator<RealT>(nSamp,bounds,bman,false,false,100));
    // Build risk-averse objective function
    Teuchos::RCP<ROL::ParametrizedObjective<RealT> > pObj =
      Teuchos::rcp(new ParametrizedObjectiveEx7<RealT>);
    // Build bound constraints
    std::vector<RealT> l(dim,zero);
    std::vector<RealT> u(dim,one);
    Teuchos::RCP<ROL::BoundConstraint<RealT> > bnd = 
      Teuchos::rcp( new ROL::StdBoundConstraint<RealT>(l,u) );
    bnd->deactivate();
    // Test parametrized objective functions
    *outStream << "Check Derivatives of Parametrized Objective Function\n";
    pObj->setParameter(sampler->getMyPoint(0));
    pObj->checkGradient(*x,*d,true,*outStream);
    pObj->checkHessVec(*x,*d,true,*outStream);
    /**********************************************************************************************/
    /************************* MEAN PLUS HMCR *****************************************************/
    /**********************************************************************************************/
    *outStream << "\nMEAN PLUS HIGHER MOMENT COHERENT RISK MEASURE\n";
    setRandomVector(*x_rcp,commptr);
    setUpAndSolve(list,pObj,sampler,x,d,bnd,*outStream);
    printSolution(*x_rcp,*outStream);
  }
  catch (std::logic_error err) {
    *outStream << err.what() << "\n";
    errorFlag = -1000;
  }; // end try

  if (errorFlag != 0)
    std::cout << "End Result: TEST FAILED\n";
  else
    std::cout << "End Result: TEST PASSED\n";

  return 0;
}
示例#21
0
 // Return the convex hull of two points; the smallest bounds that contains both.
 static LatLngBounds hull(const LatLng& a, const LatLng& b) {
     LatLngBounds bounds(a, a);
     bounds.extend(b);
     return bounds;
 }
示例#22
0
void CComPropertySheet::OnActivated(CPropertyPage* pPage)
{
	if(!pPage) return;

	CRect bounds(30000,30000,-30000,-30000);

	CRect wr, cr;
	GetWindowRect(wr);
	GetClientRect(cr);
	CSize ws = wr.Size(), cs = cr.Size();

	CRect twr, tcr;
	CTabCtrl* pTC = (CTabCtrl*)GetDlgItem(AFX_IDC_TAB_CONTROL);
	pTC->GetWindowRect(twr);
	pTC->GetClientRect(tcr);
	CSize tws = twr.Size(), tcs = tcr.Size();

	if(CWnd* pChild = pPage->GetWindow(GW_CHILD))
	{
		pChild->ModifyStyle(WS_CAPTION|WS_THICKFRAME, 0);
		pChild->ModifyStyleEx(WS_EX_DLGMODALFRAME, WS_EX_CONTROLPARENT);

		for(CWnd* pGrandChild = pChild->GetWindow(GW_CHILD); pGrandChild; pGrandChild = pGrandChild->GetNextWindow())
		{
			if(!(pGrandChild->GetStyle()&WS_VISIBLE)) continue;

			CRect r;
			pGrandChild->GetWindowRect(&r);
			pChild->ScreenToClient(r);
			bounds |= r;
		}
	}

	bounds |= CRect(0,0,0,0);
	bounds.SetRect(0, 0, bounds.right + max(bounds.left, 4), bounds.bottom + max(bounds.top, 4));

	CRect r = CRect(CPoint(0,0), bounds.Size());
	pTC->AdjustRect(TRUE, r);
	r.SetRect(twr.TopLeft(), twr.TopLeft() + r.Size());
	ScreenToClient(r);
	pTC->MoveWindow(r);
	pTC->ModifyStyle(TCS_MULTILINE, TCS_SINGLELINE);

	CSize diff = r.Size() - tws;

	if(!bounds.IsRectEmpty())
	{
		if(CWnd* pChild = pPage->GetWindow(GW_CHILD))
			pChild->MoveWindow(bounds);
		CRect r = twr;
		pTC->AdjustRect(FALSE, r);
		ScreenToClient(r);
		pPage->MoveWindow(CRect(r.TopLeft(), bounds.Size()));
	}

	int _afxPropSheetButtons[] = { IDOK, IDCANCEL, ID_APPLY_NOW, IDHELP };
	for(int i = 0; i < countof(_afxPropSheetButtons); i++)
	{
		if(CWnd* pWnd = GetDlgItem(_afxPropSheetButtons[i]))
		{
			pWnd->GetWindowRect(r);
			ScreenToClient(r);
			pWnd->MoveWindow(CRect(r.TopLeft() + diff, r.Size()));
		}
	}

	MoveWindow(CRect(wr.TopLeft(), ws + diff));

	Invalidate();
}
    void ResAtlasGeneric::loadAtlas2(CreateResourceContext& context)
    {
        _current = 0;
        pugi::xml_node node = context.walker.getNode();

        int w = node.attribute("width").as_int(defaultAtlasWidth);
        int h = node.attribute("height").as_int(defaultAtlasHeight);

        const char* format = node.attribute("format").as_string("8888");

        loadBase(node);

        atlas_data ad;


        TextureFormat tf = string2TextureFormat(format);


        bool compressed = false;


        std::vector<ResAnim*> anims;


        while (true)
        {
            XmlWalker walker = context.walker.next();
            if (walker.empty())
                break;

            pugi::xml_node child_node = walker.getNode();

            const char* name = child_node.name();
            if (strcmp(name, "image"))
                continue;


            std::string id = child_node.attribute("id").value();
            std::string file = child_node.attribute("file").value();

            if (file.empty())
            {
                createEmpty(walker, context);
                continue;
            }


            bool trim = child_node.attribute("trim").as_bool(true);
            bool extend = child_node.attribute("extend").as_bool(true);

            Point offset = extend ? Point(2, 2) : Point(0, 0);

            MemoryTexture mt;
            ImageData im;

            int columns = 0;
            int rows = 0;
            int frame_width = 0;
            int frame_height = 0;
            float frame_scale = 1.0f;
            bool loaded = false;


            file::buffer bf;
            file::read(walker.getPath("file"), bf);

            mt.init(bf, true, tf);
            im = mt.lock();
            if (im.w)
            {
                rows = child_node.attribute("rows").as_int();
                frame_width = child_node.attribute("frame_width").as_int();
                columns = child_node.attribute("cols").as_int();
                frame_height = child_node.attribute("frame_height").as_int();

                if (!rows)
                    rows = 1;

                if (!columns)
                    columns = 1;

                if (frame_width)
                    columns = im.w / frame_width;
                else
                    frame_width = im.w / columns;


                if (frame_height)
                    rows = im.h / frame_height;
                else
                    frame_height = im.h / rows;
            }


            if (columns)
            {
                animationFrames frames;
                int frames_count = rows * columns;
                frames.reserve(frames_count);

                ResAnim* ra = new ResAnim(this);


                anims.push_back(ra);

                for (int y = 0; y < rows; ++y)
                {
                    for (int x = 0; x < columns; ++x)
                    {
                        Rect frameRect;
                        frameRect.pos = Point(x * frame_width, y * frame_height);
                        frameRect.size = Point(frame_width, frame_height);

                        ImageData srcImage_ = im.getRect(frameRect);


                        HitTestData adata;
                        ImageData src;
                        Rect bounds(0, 0, im.w, im.h);
                        if (trim)
                            makeAlpha(srcImage_, bounds, _hitTestBuffer, adata, walker.getAlphaHitTest());
                        src = srcImage_.getRect(bounds);

                        Rect dest(0, 0, 0, 0);

                        if (!ad.texture)
                        {
                            std::string atlas_id = getName();
                            nextAtlas(w, h, tf, ad, atlas_id.c_str());
                        }

                        bool s = ad.atlas.add(&ad.mt, src, dest, offset);
                        if (s == false)
                        {
                            applyAtlas(ad, _linearFilter, _clamp2edge);

                            nextAtlas(w, h, tf, ad, walker.getCurrentFolder().c_str());
                            s = ad.atlas.add(&ad.mt, src, dest, offset);
                            OX_ASSERT(s);
                        }

                        //extend = false;
                        if (extend)
                        {
                            //duplicate image edges
                            MemoryTexture& mt = ad.mt;
                            ImageData tmp;

                            if (bounds.getY() == 0 && dest.pos.y != 0)
                            {
                                tmp = mt.lock(Rect(dest.pos.x, dest.pos.y - 1, src.w, 1));
                                operations::copy(src.getRect(Rect(0, 0, src.w, 1)), tmp);
                            }

                            if (bounds.getHeight() == im.h && dest.getBottom() != mt.getHeight())
                            {
                                tmp = mt.lock(Rect(dest.pos.x, dest.pos.y + src.h, src.w, 1));
                                operations::copy(src.getRect(Rect(0, src.h - 1, src.w, 1)), tmp);
                            }

                            if (bounds.getX() == 0 && dest.pos.x != 0)
                            {
                                tmp = mt.lock(Rect(dest.pos.x - 1, dest.pos.y, 1, src.h));
                                operations::copy(src.getRect(Rect(0, 0, 1, src.h)), tmp);
                            }

                            if (bounds.getWidth() == im.w && dest.getRight() != mt.getWidth())
                            {
                                tmp = mt.lock(Rect(dest.pos.x + src.w, dest.pos.y, 1, src.h));
                                operations::copy(src.getRect(Rect(src.w - 1, 0, 1, src.h)), tmp);
                            }
                        }


                        //operations::copy(src.getRect(Rect(0, 0, 1, 1)), mt.lock(&Rect(dest.pos.x - 1, dest.pos.y - 1, 1, 1)));
                        //operations::copy(src.getRect(Rect(src.w - 1, 0, 1, 1)), mt.lock(&Rect(dest.pos.x + src.w, dest.pos.y - 1, 1, 1)));

                        //operations::copy(src.getRect(Rect(0, src.h - 1, 1, 1)), mt.lock(&Rect(dest.pos.x - 1, dest.pos.y + src.h, 1, 1)));
                        //operations::copy(src.getRect(Rect(src.w - 1, src.h - 1, 1, 1)), mt.lock(&Rect(dest.pos.x + src.w, dest.pos.y + src.h, 1, 1)));


                        float iw = 1.0f;
                        float ih = 1.0f;

                        RectF srcRect(dest.pos.x * iw, dest.pos.y * ih, dest.size.x * iw, dest.size.y * ih);

                        Vector2 sizeScaled = Vector2((float)dest.size.x, (float)dest.size.y) * walker.getScaleFactor();
                        RectF destRect(bounds.pos.cast<Vector2>(), sizeScaled);

                        AnimationFrame frame;
                        Diffuse df;
                        df.base = ad.texture;
                        df.premultiplied = true;//!Renderer::getPremultipliedAlphaRender();

                        Vector2 fsize = Vector2((float)frame_width, (float)frame_height) * walker.getScaleFactor();
                        frame.init2(ra, x, y, df,
                                    srcRect, destRect, fsize);

                        frame.setHitTestData(adata);

                        frames.push_back(frame);
                    }
                }

                init_resAnim(ra, file, child_node);

                ra->init(frames, columns, walker.getScaleFactor(), 1.0f / walker.getScaleFactor());
                ra->setParent(this);
                context.resources->add(ra, context.options->_shortenIDS);
            }

        }

        applyAtlas(ad, _linearFilter, _clamp2edge);

        for (std::vector<ResAnim*>::iterator i = anims.begin(); i != anims.end(); ++i)
        {
            ResAnim* rs = *i;
            int num = rs->getTotalFrames();

            for (int n = 0; n < num; ++n)
            {
                AnimationFrame& frame = const_cast<AnimationFrame&>(rs->getFrame(n));

                float iw = 1.0f / frame.getDiffuse().base->getWidth();
                float ih = 1.0f / frame.getDiffuse().base->getHeight();

                RectF rect = frame.getSrcRect();
                rect.pos.x *= iw;
                rect.pos.y *= ih;
                rect.size.x *= iw;
                rect.size.y *= ih;
                frame.setSrcRect(rect);

                HitTestData ad = frame.getHitTestData();
                if (ad.pitch)
                {
                    ad.data = &_hitTestBuffer[reinterpret_cast<size_t>(ad.data)];
                    frame.setHitTestData(ad);
                }
            }
        }
    }
bool ModelOBJ::import(const char *pszFilename, bool rebuildNormals)
{
    FILE *pFile = fopen(pszFilename, "r");

    if (!pFile)
        return false;

    // Extract the directory the OBJ file is in from the file name.
    // This directory path will be used to load the OBJ's associated MTL file.

    m_directoryPath.clear();

    std::string filename = pszFilename;
    std::string::size_type offset = filename.find_last_of('\\');

    if (offset != std::string::npos)
    {
        m_directoryPath = filename.substr(0, ++offset);
    }
    else
    {
        offset = filename.find_last_of('/');

        if (offset != std::string::npos)
            m_directoryPath = filename.substr(0, ++offset);
    }

    // Import the OBJ file.

    importGeometryFirstPass(pFile);
    rewind(pFile);
    importGeometrySecondPass(pFile);
    fclose(pFile);

    // Perform post import tasks.

    buildMeshes();
    bounds(m_center, m_width, m_height, m_length, m_radius);

    // Build vertex normals if required.

    if (rebuildNormals)
    {
        generateNormals();
    }
    else
    {
        if (!hasNormals())
            generateNormals();
    }

    // Build tangents is required.

    for (int i = 0; i < m_numberOfMaterials; ++i)
    {
        if (!m_materials[i].bumpMapFilename.empty())
        {
            generateTangents();
            break;
        }
    }

    return true;
}
示例#25
0
void
LayerManagerComposite::Render()
{
  PROFILER_LABEL("LayerManagerComposite", "Render",
    js::ProfileEntry::Category::GRAPHICS);

  if (mDestroyed) {
    NS_WARNING("Call on destroyed layer manager");
    return;
  }

  /** Our more efficient but less powerful alter ego, if one is available. */
  nsRefPtr<Composer2D> composer2D = mCompositor->GetWidget()->GetComposer2D();

  // Set LayerScope begin/end frame
  LayerScopeAutoFrame frame(PR_Now());

  // Dump to console
  if (gfxPrefs::LayersDump()) {
    this->Dump();
  }

  // Dump to LayerScope Viewer
  if (LayerScope::CheckSendable()) {
    // Create a LayersPacket, dump Layers into it and transfer the
    // packet('s ownership) to LayerScope.
    auto packet = MakeUnique<layerscope::Packet>();
    layerscope::LayersPacket* layersPacket = packet->mutable_layers();
    this->Dump(layersPacket);
    LayerScope::SendLayerDump(Move(packet));
  }

  if (!mTarget && composer2D && composer2D->TryRender(mRoot, mWorldMatrix, mGeometryChanged)) {
    if (mFPS) {
      double fps = mFPS->mCompositionFps.AddFrameAndGetFps(TimeStamp::Now());
      if (gfxPrefs::LayersDrawFPS()) {
        printf_stderr("HWComposer: FPS is %g\n", fps);
      }
    }
    mCompositor->EndFrameForExternalComposition(mWorldMatrix);
    // Reset the invalid region as compositing is done
    mInvalidRegion.SetEmpty();
    return;
  }

  {
    PROFILER_LABEL("LayerManagerComposite", "PreRender",
      js::ProfileEntry::Category::GRAPHICS);

    if (!mCompositor->GetWidget()->PreRender(this)) {
      return;
    }
  }

  nsIntRegion invalid;
  if (mTarget) {
    invalid = mTargetBounds;
  } else {
    invalid = mInvalidRegion;
    // Reset the invalid region now that we've begun compositing.
    mInvalidRegion.SetEmpty();
  }

  nsIntRect clipRect;
  Rect bounds(mRenderBounds.x, mRenderBounds.y, mRenderBounds.width, mRenderBounds.height);
  Rect actualBounds;

  CompositorBench(mCompositor, bounds);

  if (mRoot->GetClipRect()) {
    clipRect = *mRoot->GetClipRect();
    WorldTransformRect(clipRect);
    Rect rect(clipRect.x, clipRect.y, clipRect.width, clipRect.height);
    mCompositor->BeginFrame(invalid, &rect, mWorldMatrix, bounds, nullptr, &actualBounds);
  } else {
    gfx::Rect rect;
    mCompositor->BeginFrame(invalid, nullptr, mWorldMatrix, bounds, &rect, &actualBounds);
    clipRect = nsIntRect(rect.x, rect.y, rect.width, rect.height);
  }

  if (actualBounds.IsEmpty()) {
    mCompositor->GetWidget()->PostRender(this);
    return;
  }

  // Allow widget to render a custom background.
  mCompositor->GetWidget()->DrawWindowUnderlay(this, nsIntRect(actualBounds.x,
                                                               actualBounds.y,
                                                               actualBounds.width,
                                                               actualBounds.height));

  // Render our layers.
  RootLayer()->Prepare(clipRect);
  RootLayer()->RenderLayer(clipRect);

  if (!mRegionToClear.IsEmpty()) {
    nsIntRegionRectIterator iter(mRegionToClear);
    const nsIntRect *r;
    while ((r = iter.Next())) {
      mCompositor->ClearRect(Rect(r->x, r->y, r->width, r->height));
    }
  }

  // Allow widget to render a custom foreground.
  mCompositor->GetWidget()->DrawWindowOverlay(this, nsIntRect(actualBounds.x,
                                                              actualBounds.y,
                                                              actualBounds.width,
                                                              actualBounds.height));

  // Debugging
  RenderDebugOverlay(actualBounds);

  {
    PROFILER_LABEL("LayerManagerComposite", "EndFrame",
      js::ProfileEntry::Category::GRAPHICS);

    mCompositor->EndFrame();
    mCompositor->SetFBAcquireFence(mRoot);
  }

  mCompositor->GetWidget()->PostRender(this);

  RecordFrame();
}
示例#26
0
void
LayerManagerComposite::Render()
{
  PROFILER_LABEL("LayerManagerComposite", "Render",
    js::ProfileEntry::Category::GRAPHICS);

  if (mDestroyed) {
    NS_WARNING("Call on destroyed layer manager");
    return;
  }

  // At this time, it doesn't really matter if these preferences change
  // during the execution of the function; we should be safe in all
  // permutations. However, may as well just get the values onces and
  // then use them, just in case the consistency becomes important in
  // the future.
  bool invertVal = gfxPrefs::LayersEffectInvert();
  bool grayscaleVal = gfxPrefs::LayersEffectGrayscale();
  float contrastVal = gfxPrefs::LayersEffectContrast();
  bool haveLayerEffects = (invertVal || grayscaleVal || contrastVal != 0.0);

  // Set LayerScope begin/end frame
  LayerScopeAutoFrame frame(PR_Now());

  // Dump to console
  if (gfxPrefs::LayersDump()) {
    this->Dump();
  }

  // Dump to LayerScope Viewer
  if (LayerScope::CheckSendable()) {
    // Create a LayersPacket, dump Layers into it and transfer the
    // packet('s ownership) to LayerScope.
    auto packet = MakeUnique<layerscope::Packet>();
    layerscope::LayersPacket* layersPacket = packet->mutable_layers();
    this->Dump(layersPacket);
    LayerScope::SendLayerDump(Move(packet));
  }

  /** Our more efficient but less powerful alter ego, if one is available. */
  nsRefPtr<Composer2D> composer2D;

  // We can't use composert2D if we have layer effects, so only get it
  // when we don't have any effects.
  if (!haveLayerEffects) {
    composer2D = mCompositor->GetWidget()->GetComposer2D();
  }

  if (!mTarget && composer2D && composer2D->TryRender(mRoot, mWorldMatrix, mGeometryChanged)) {
    if (mFPS) {
      double fps = mFPS->mCompositionFps.AddFrameAndGetFps(TimeStamp::Now());
      if (gfxPrefs::LayersDrawFPS()) {
        printf_stderr("HWComposer: FPS is %g\n", fps);
      }
    }
    mCompositor->EndFrameForExternalComposition(mWorldMatrix);
    // Reset the invalid region as compositing is done
    mInvalidRegion.SetEmpty();
    return;
  }

  {
    PROFILER_LABEL("LayerManagerComposite", "PreRender",
      js::ProfileEntry::Category::GRAPHICS);

    if (!mCompositor->GetWidget()->PreRender(this)) {
      return;
    }
  }

  nsIntRegion invalid;
  if (mTarget) {
    invalid = mTargetBounds;
  } else {
    invalid = mInvalidRegion;
    // Reset the invalid region now that we've begun compositing.
    mInvalidRegion.SetEmpty();
  }

  nsIntRect clipRect;
  Rect bounds(mRenderBounds.x, mRenderBounds.y, mRenderBounds.width, mRenderBounds.height);
  Rect actualBounds;

  CompositorBench(mCompositor, bounds);

  if (mRoot->GetClipRect()) {
    clipRect = *mRoot->GetClipRect();
    WorldTransformRect(clipRect);
    Rect rect(clipRect.x, clipRect.y, clipRect.width, clipRect.height);
    mCompositor->BeginFrame(invalid, &rect, mWorldMatrix, bounds, nullptr, &actualBounds);
  } else {
    gfx::Rect rect;
    mCompositor->BeginFrame(invalid, nullptr, mWorldMatrix, bounds, &rect, &actualBounds);
    clipRect = nsIntRect(rect.x, rect.y, rect.width, rect.height);
  }

  if (actualBounds.IsEmpty()) {
    mCompositor->GetWidget()->PostRender(this);
    return;
  }

  // Allow widget to render a custom background.
  mCompositor->GetWidget()->DrawWindowUnderlay(this, nsIntRect(actualBounds.x,
                                                               actualBounds.y,
                                                               actualBounds.width,
                                                               actualBounds.height));

  RefPtr<CompositingRenderTarget> previousTarget;
  if (haveLayerEffects) {
    previousTarget = PushGroupForLayerEffects();
  } else {
    mTwoPassTmpTarget = nullptr;
  }

  // Render our layers.
  RootLayer()->Prepare(RenderTargetPixel::FromUntyped(clipRect));
  RootLayer()->RenderLayer(clipRect);

  if (!mRegionToClear.IsEmpty()) {
    nsIntRegionRectIterator iter(mRegionToClear);
    const nsIntRect *r;
    while ((r = iter.Next())) {
      mCompositor->ClearRect(Rect(r->x, r->y, r->width, r->height));
    }
  }

  if (mTwoPassTmpTarget) {
    MOZ_ASSERT(haveLayerEffects);
    PopGroupForLayerEffects(previousTarget, clipRect,
                            grayscaleVal, invertVal, contrastVal);
  }

  // Allow widget to render a custom foreground.
  mCompositor->GetWidget()->DrawWindowOverlay(this, nsIntRect(actualBounds.x,
                                                              actualBounds.y,
                                                              actualBounds.width,
                                                              actualBounds.height));

  // Debugging
  RenderDebugOverlay(actualBounds);

  {
    PROFILER_LABEL("LayerManagerComposite", "EndFrame",
      js::ProfileEntry::Category::GRAPHICS);

    mCompositor->EndFrame();
    mCompositor->SetFBAcquireFence(mRoot);
  }

  mCompositor->GetWidget()->PostRender(this);

  RecordFrame();
}
示例#27
0
void expand_node_t::do_calc_bounds( const render::context_t& context)
{
    Imath::Box2i bounds( ImathExt::intersect( input_as<image_node_t>()->bounds(), format()));
    set_bounds( bounds);
}
示例#28
0
void drawScene() {
  glPushMatrix();

  //Set the animation control variables.
  if (!paused) frame++;
  int ticks = frame % 1440;
  if (frame % 1440 == 0) {
    ticks = 0;

    //Reset animation object positions and rotations.
    planePriorX = 0, planePriorY = 0, planePriorZ = 0;
    planePostX = 0, planePostY = 0, planePostZ = 0;
    planeRotX = 0, planeRotY = 0, planeRotZ = 0;

    eaglePriorX = -0.5, eaglePriorY = 0.03, eaglePriorZ = -0.1;
    eaglePostX = 0, eaglePostY = 0, eaglePostZ = 0;
    eagleRotX = 0, eagleRotY = 0, eagleRotZ = 0;
  }

  //Apply scene transformations.
  glRotatef(30, 0, 1, 0);
  glTranslatef(0, 0, -1500 * frame * SCALE_FACTOR);

  //Make sure angles are in bounds.
  bounds(planeRotX); bounds(planeRotY); bounds(planeRotZ);
  bounds(eagleRotX); bounds(eagleRotY); bounds(eagleRotZ);

  if (!paused) {
    //Airplane transformation events.
    //Constant swaying.
    planeRotZ -= 0.5 * cos(ticks * 2 * PI / 180);
    planePostY -= 0.01 * cos(ticks * PI / 180);

    //Spin upside-down.
    if (ticks >= 180 && ticks < 360) planeRotZ -= PI * 0.5 * sin(ticks * PI / 180);

    //Spin back round.
    if (ticks >= 360 && ticks < 540) planeRotZ += PI * 0.5 * sin(ticks * PI / 180);

    //Dive.
    if (ticks >= 720 && ticks < 900) {
      planeRotX -= 0.25 * PI * sin(ticks * 2 * PI / 180);
      planePriorY -= 0.005 * PI * sin(ticks * PI / 180);
      planePriorZ -= 0.01 * PI * sin(ticks * 0.5 * PI / 180);
    }

    //Loop-the-loop
    if (ticks >= 900 && ticks < 1220) {
      planeRotX += 1;
      planePriorY += 0.015 * PI * sin((ticks - 180) * PI / 180);
      planePriorZ -= 0.015 * PI * cos((ticks - 180) * PI / 180);
    }

    //Reset position.
    if (ticks >= 1220 && ticks < 1440) {
      // These values were found by minimising errors using binary division.
      planeRotX -= 0.1262345 * PI * sin(ticks * PI / 180);
      planePriorY -= 0.002379563 * PI * sin(ticks * 0.5 * PI / 180);
      planePriorZ -= 0.003826425 * PI * sin(ticks * 0.5 * PI / 180);
    }

    //Eagle transformation events.
    //Set default position.
    eaglePriorX = -1;
    eaglePriorZ = 0.4;

    //Set start position over left wing.
    if (ticks >= 0 && ticks < 180) {
      eaglePriorX = -0.5;
      eaglePriorY = 0.03;
      eaglePriorZ = -0.1;
    }

    //Move a little with the wing.
    if (ticks >= 0 && ticks < 90) {
      eagleRotZ -= cos(ticks * 2 * PI / 180);
      eaglePostY -= 0.009 * sin(ticks * 2 * PI / 180);
    }

    //Move back, up and left.
    if (ticks >= 90 && ticks < 180) {
      eaglePriorX -= (float)0.5 / 90 * (ticks - 90);
      eaglePriorZ += (float)0.5 / 90 * (ticks - 90);
      eaglePostY += 0.009 * sin((ticks - 90) * 2 * PI / 180);
    }

    //Swaying.
    if (ticks >= 90 && ticks < 1350) {
      eagleRotZ -= 0.6 * cos((ticks + 90) * PI / 180);
      eaglePostY -= 0.01 * cos((ticks + 90) * 2 * PI / 180);
    }

    //Avoid plane collision.
    if (ticks >= 360 && ticks < 540) eagleRotZ += 0.25 * PI * sin(ticks * 2 * PI / 180);

    //Glide from side to side.
    if (ticks >= 720 && ticks < 1080) eaglePriorX += 0.4 * PI * sin(ticks * 0.5 * PI / 180);

    //Move back to start position.
    if (ticks >= 1350 && ticks < 1440) {
      eaglePriorX += (float)0.5 / 90 * (ticks - 1350);
      eaglePriorZ -= (float)0.5 / 90 * (ticks - 1350);
    }

    //Avoid plane collision.
    if (ticks >= 1400 && ticks < 1420) eaglePriorY += 0.01;
    if (ticks >= 1420 && ticks < 1440) eaglePriorY -= 0.01;
  }

  //Apply the transformations then draw the airplane.
  glPushMatrix();
  glTranslatef(planePriorX, planePriorY, planePriorZ);
  glRotatef(planeRotX, 1, 0, 0);
  glRotatef(planeRotY, 0, 1, 0);
  glRotatef(planeRotZ, 0, 0, 1);
  glTranslatef(planePostX, planePostY, planePostZ);
  drawAirplane();
  glPopMatrix();

  //Apply the transformations then draw the eagle.
  glPushMatrix();
  glTranslatef(eaglePriorX, eaglePriorY, eaglePriorZ);
  glRotatef(eagleRotX, 1, 0, 0);
  glRotatef(eagleRotY, 0, 1, 0);
  glRotatef(eagleRotZ, 0, 0, 1);
  glTranslatef(eaglePostX, eaglePostY, eaglePostZ);
  drawEagle();
  glPopMatrix();
  glPopMatrix();
}
int LbfgsbOptimizer::solve()
{
    // Solution vector
    ap::real_1d_array x0;
    x0.setbounds(1, x.dim);

    // copy current x into x0
    for(size_t i = 0; i < x.dim; i++)
    {
        x0(i+1) = x.val[i];
    }

    ap::integer_1d_array nbd;
    ap::real_1d_array l;
    ap::real_1d_array u;
    nbd.setbounds(1, x.dim);
    l.setbounds(1, x.dim);
    u.setbounds(1, x.dim);

    // Set bounds
    if(binary)
    {
        bounds_binary(nbd, l, u);
    }
    else
    {
        bounds(nbd, l, u);
    }

    // Lancelot: gamma_bar = 0.1
    double gamma_bar = 0.1; // < 1 :

    // Lancelot: tau = 0.1
    double tau = 0.1; // # < 1

    // Lancelot: alpha_eta = 0.1
    double alpha_eta = 0.01; // # min(1, self._alpha_omega)

    //Lancelot: beta_eta = 0.9
    double beta_eta = 0.9; // # min(1, self._beta_omega)

    //Lancelot: alpha_omega = 1.0
    double alpha_omega = 4.0;

    //Lancelot: beta_omega = 1.0
    double beta_omega = 4.0;

    // Lancelot: omega_bar = firtsg/pow(std::min(mu, gamma_bar), alpha_omega);
    double omega_bar = 0.5;

    // Lancelot: eta_bar = firtsc/pow(std::min(mu, gamma_bar), alpha_eta);
    double eta_bar = 1.0;

    double mu_bar = 0.9; // must be <= 1

    mu = mu_bar;

    // Lancelot: alpha  = min(mu, gamma_bar)
    double alpha = std::min(mu, gamma_bar);

    // Lancelot: eta = max(etamin, eta_bar*pow(alpha, alpha_eta))
    // svnvish: BUGBUG what is etamin?
    // etamin is the minimum norm of the constraint violation
    double eta = eta_bar*pow(alpha, alpha_eta);

    // Lancelot: omega = max(omemin, omega_bar*pow(alpha, alpha_omega))
    // svnvish: BUGBUG what is omemin?
    // omemin is the tolerance for kkt gap
    double omega = omega_bar*pow(alpha, alpha_omega);

    DenseVector W;
    W.val = x.val;
    W.dim = num_weak_learners;

    for(size_t iteration = 0; iteration < LBFGSB::max_iterations; iteration++)
    {
        double epsg = omega;
        double epsf = 0;
        double epsx = 0;
        int info;

        lbfgsbminimize(x.dim,
                       std::min(x.dim, LBFGSB::lbfgsb_m),
                       x0,
                       epsg,
                       epsf,
                       epsx,
                       LBFGSB::lbfgsb_max_iterations,
                       nbd,
                       l,
                       u,
                       (void*) this,
                       info);

        // copy current solution into x
        for(size_t i = 0; i < x.dim; i++)
        {
            x.val[i] = x0(i+1);
        }

        const double w_gap = sum(W) - 1.0;

        // std::cout << "info: " << info << std::endl;
        // assert(info > 0);
        assert(info == 4);

        if(std::abs(w_gap) < eta)
        {

            if(std::abs(w_gap) < Optimizer::wt_sum_tol)
            {

                if(duality_gap_met())
                {
                    // // svnvish: BUGBUG
                    // // Extra gradient computation happening here
                    // // Better to use norm gaps
                    // dvec gradk = grad();

                    // if(converged(grad())){
                    report_statistics();
                    break;
                }
            }

            lambda = lambda - (w_gap/mu);
            //mu = mu;
            alpha = mu;
            eta = eta*pow(alpha, beta_eta);
            omega = omega*pow(alpha, beta_omega);

        }
        else
        {
            //lambda = lambda;
            mu *= tau;
            alpha = mu*gamma_bar;
            eta = eta_bar*pow(alpha, beta_eta);
            omega = omega_bar*pow(alpha, beta_omega);
        }

    } // end of "for each iteration"

    // This is not a memory leak!
    W.val = NULL;
    W.dim = 0;

    return 0;
} // end of LbfgsbOptimizer::solve()
/*
 *	Q P r o b l e m B _ i n i t
 */
int_t QProblemB_init(	int_t handle, 
						SymmetricMatrix* H, real_t* g,
						const real_t* const lb, const real_t* const ub,
						int_t nWSRin, real_t maxCpuTimeIn,
						const double* const x0, Options* options,
						int_t nOutputs, mxArray* plhs[],
						const double* const guessedBounds,
						const double* const _R
						)
{
	int_t nWSRout = nWSRin;
	real_t maxCpuTimeOut = (maxCpuTimeIn >= 0.0) ? maxCpuTimeIn : INFTY;

	/* 1) setup initial QP. */
	QProblemB* globalQPB = getQPInstance(handle)->qpb;

	if ( globalQPB == 0 )
	{
		myMexErrMsgTxt( "ERROR (qpOASES): Invalid handle to QP instance!" );
		return -1;
	}

	globalQPB->setOptions( *options );
	
	/* 2) Solve initial QP. */
	returnValue returnvalue;
	int_t nV = globalQPB->getNV();
	
	/* 3) Fill the working set. */
	Bounds bounds(nV);
	if (guessedBounds != 0) {
		for (int_t i = 0; i < nV; i++) {
			if ( isEqual(guessedBounds[i],-1.0) == BT_TRUE ) {
				bounds.setupBound(i, ST_LOWER);
			} else if ( isEqual(guessedBounds[i],1.0) == BT_TRUE ) {
				bounds.setupBound(i, ST_UPPER);
			} else if ( isEqual(guessedBounds[i],0.0) == BT_TRUE ) {
				bounds.setupBound(i, ST_INACTIVE);
			} else {
				char msg[MAX_STRING_LENGTH];
				snprintf(msg, MAX_STRING_LENGTH,
						"ERROR (qpOASES): Only {-1, 0, 1} allowed for status of bounds!");
				myMexErrMsgTxt(msg);
				return -1;
			}
		}
	}

	returnvalue = globalQPB->init(	H,g,lb,ub,
									nWSRout,&maxCpuTimeOut,
									x0,0,
									(guessedBounds != 0) ? &bounds : 0,
									_R
									);

	/* 3) Assign lhs arguments. */
	obtainOutputs(	0,globalQPB,returnvalue,nWSRout,maxCpuTimeOut,
					nOutputs,plhs,nV,0,handle );

	return 0;
}