Exemplo n.º 1
0
void RWsTextCursor::SetL(const TWsWinCmdSetTextCursor &aSet, TBool aClipped)
	{
	if (aSet.cursor.iType < TTextCursor::ETypeFirst ||
        (aSet.cursor.iType > TTextCursor::ETypeLast &&        
         aSet.cursor.iType <= TTextCursor::ETypeLastBasic) ||
		(aSet.cursor.iFlags&static_cast<TUint>(ETextCursorPrivateFlags)))
		{
		Cancel();
		iGroupWin->OwnerPanic(EWservPanicInvalidTextCursor);
		}
	else
		{
		CWsClientWindow* win = NULL;
		iGroupWin->WsOwner()->HandleToClientWindow(aSet.window, &win);

		// Check window is a child of the group window
		CWsWindowBase* searchWin = NULL;
		for(searchWin=win; searchWin->WinType()!=EWinTypeGroup; searchWin=searchWin->BaseParent())
			{}
		if (iGroupWin != searchWin)
			{
			Cancel();
			iGroupWin->OwnerPanic(EWservPanicWindow);
			}

		TPoint pos(aSet.pos.iX, aSet.pos.iY-aSet.cursor.iAscent);
		TSize size(aSet.cursor.iWidth, aSet.cursor.iHeight);
		TUint flags = aSet.cursor.iFlags;
		TInt type = aSet.cursor.iType;
		TRect clipRect = iClipRect;
		TRgb color = aSet.cursor.iColor;
		CWsCustomTextCursor* customTextCursor = iCustomTextCursor;
		TBool changed = EFalse;

		TPoint clipOrigo;
		TSize clipSize;

		if (type > TTextCursor::ETypeLastBasic)
			{
			changed = ETrue;

			customTextCursor = CWsClient::FindCustomTextCursor(type);
			if (!customTextCursor)
				{
				Cancel();
				iGroupWin->OwnerPanic(EWservPanicNoCustomTextCursor);
				return;
				}
			
			if( !customTextCursor->HasSpriteMember() )
				{
				iGroupWin->OwnerPanic(EWservPanicNoSpriteMember);
				return;
				}
			
			TInt yAdjust=0;
			switch (customTextCursor->Alignment())
				{
				case RWsSession::ECustomTextCursorAlignTop:
					break;
				case RWsSession::ECustomTextCursorAlignBaseline:
					yAdjust = aSet.cursor.iAscent-1;
					break;
				case RWsSession::ECustomTextCursorAlignBottom:
					yAdjust = aSet.cursor.iHeight-1;
					break;
				default:
					Cancel();
					iGroupWin->OwnerPanic(EWservPanicCustomTextCursorAlign);
					return;
				}
			pos.iY += yAdjust;
			// Start with a clipping rect to be the whole window
			// relative cursor pos and shrink down to what we want
			clipOrigo = -pos;
			clipSize = win->Size();
			if (flags & TTextCursor::EFlagClipHorizontal)
				{
				clipOrigo.iX = 0;
				clipSize.iWidth = size.iWidth;
				}
			if (flags & TTextCursor::EFlagClipVertical)
				{
				clipOrigo.iY = -yAdjust;
				clipSize.iHeight = aSet.cursor.iHeight;
				}
			}
		else
			{
			customTextCursor = NULL;
			}

		if (aClipped)
			{
			flags|=ETextCursorFlagClipped;
			clipRect=aSet.rect;
			}

		if (pos != iPos || size != iSize || iType != type ||
			flags != iFlags || clipRect != iClipRect || color != iColor ||
			customTextCursor != iCustomTextCursor || win != iWin)
			{
			// There is a change in the cursor.
			changed = ETrue;
			}

		if (iInternalFlags&EHasFocus && changed)
			{
			TCursorSprite::Hide();
			}

		iPos = pos;
		iSize = size;
		iType = type;
		iFlags= flags;
		iClipRect = clipRect;
		iColor = color;
		iCustomTextCursor = customTextCursor;
		iWin = win;
		if (customTextCursor && iInternalFlags&EHasFocus)
			{
			customTextCursor->CompleteL(win, !(flags&TTextCursor::EFlagNoFlash), flags & (TTextCursor::EFlagClipHorizontal | TTextCursor::EFlagClipVertical), clipOrigo, clipSize);
			customTextCursor->SetPositionNoRedraw(pos);
			}

		if (iInternalFlags&EHasFocus && changed)
			{
			TCursorSprite::SetCurrentCursor(this, win);
			}
		}
	}
Exemplo n.º 2
0
static int countdown( const char * msg, int row, int timeout )
{
    unsigned long time;
    int ch  = 0;
    int col = strlen(msg) + 1;
	
    flushKeyboardBuffer();

	if( bootArgs->Video.v_display == VGA_TEXT_MODE )
	{
		moveCursor( 0, row );
		printf(msg);

	} else {

		position_t p = pos( gui.screen.width / 2 + 1 , ( gui.devicelist.pos.y + 3 ) + ( ( gui.devicelist.height - gui.devicelist.iconspacing ) / 2 ) );
	
		char dummy[80];
		getBootVolumeDescription( gBootVolume, dummy, sizeof(dummy) - 1, true );
		drawDeviceIcon( gBootVolume, gui.screen.pixmap, p, true );
		drawStrCenteredAt( (char *) msg, &font_small, gui.screen.pixmap, gui.countdown.pos );
		
		// make this screen the new background
		memcpy( gui.backbuffer->pixels, gui.screen.pixmap->pixels, gui.backbuffer->width * gui.backbuffer->height * 4 );
		
	}

	int multi_buff = 18 * (timeout);
    int multi = ++multi_buff;

    int lasttime=0;

    for ( time = time18(), timeout++; timeout > 0; )
    {
		if( time18() > lasttime)
		{
			multi--; 
			lasttime=time18();
		}		
  
        if (ch = readKeyboardStatus())
            break;

        // Count can be interrupted by holding down shift,
        // control or alt key
        if ( ( readKeyboardShiftFlags() & 0x0F ) != 0 )
		{
            ch = 1;
            break;
        }

        if ( time18() >= time )
        {
            time += 18;
            timeout--;

			if( bootArgs->Video.v_display == VGA_TEXT_MODE )
			{
				moveCursor( col, row );
				printf("(%d) ", timeout);
			}
        }
	
		if( bootArgs->Video.v_display == GRAPHICS_MODE )
		{
			drawProgressBar( gui.screen.pixmap, 100, gui.progressbar.pos , ( multi * 100 / multi_buff ) );
			gui.redraw = true;
			updateVRAM();
		}

    }

    flushKeyboardBuffer();

    return ch;
}
Exemplo n.º 3
0
void ParallaxLCD::at ( int row, int col, const char v[] )	{ pos(row,col); print(v); }
Exemplo n.º 4
0
sk_sp<SkShader> Gradient::shader() {
  if (m_gradient)
    return m_gradient;

  sortStopsIfNecessary();
  ASSERT(m_stopsSorted);

  size_t countUsed = totalStopsNeeded(m_stops.data(), m_stops.size());
  ASSERT(countUsed >= 2);
  ASSERT(countUsed >= m_stops.size());

  ColorStopOffsetVector pos(countUsed);
  ColorStopColorVector colors(countUsed);
  fillStops(m_stops.data(), m_stops.size(), pos, colors);

  SkShader::TileMode tile = SkShader::kClamp_TileMode;
  switch (m_spreadMethod) {
    case SpreadMethodReflect:
      tile = SkShader::kMirror_TileMode;
      break;
    case SpreadMethodRepeat:
      tile = SkShader::kRepeat_TileMode;
      break;
    case SpreadMethodPad:
      tile = SkShader::kClamp_TileMode;
      break;
  }

  uint32_t shouldDrawInPMColorSpace =
      m_drawInPMColorSpace ? SkGradientShader::kInterpolateColorsInPremul_Flag
                           : 0;
  if (m_radial) {
    if (aspectRatio() != 1) {
      // CSS3 elliptical gradients: apply the elliptical scaling at the
      // gradient center point.
      m_gradientSpaceTransformation.translate(m_p0.x(), m_p0.y());
      m_gradientSpaceTransformation.scale(1, 1 / aspectRatio());
      m_gradientSpaceTransformation.translate(-m_p0.x(), -m_p0.y());
      ASSERT(m_p0 == m_p1);
    }
    SkMatrix localMatrix =
        affineTransformToSkMatrix(m_gradientSpaceTransformation);

    // Since the two-point radial gradient is slower than the plain radial,
    // only use it if we have to.
    if (m_p0 == m_p1 && m_r0 <= 0.0f) {
      m_gradient = SkGradientShader::MakeRadial(
          m_p1.data(), m_r1, colors.data(), pos.data(),
          static_cast<int>(countUsed), tile, shouldDrawInPMColorSpace,
          &localMatrix);
    } else {
      // The radii we give to Skia must be positive. If we're given a
      // negative radius, ask for zero instead.
      SkScalar radius0 = m_r0 >= 0.0f ? WebCoreFloatToSkScalar(m_r0) : 0;
      SkScalar radius1 = m_r1 >= 0.0f ? WebCoreFloatToSkScalar(m_r1) : 0;
      m_gradient = SkGradientShader::MakeTwoPointConical(
          m_p0.data(), radius0, m_p1.data(), radius1, colors.data(), pos.data(),
          static_cast<int>(countUsed), tile, shouldDrawInPMColorSpace,
          &localMatrix);
    }
  } else {
    SkPoint pts[2] = {m_p0.data(), m_p1.data()};
    SkMatrix localMatrix =
        affineTransformToSkMatrix(m_gradientSpaceTransformation);
    m_gradient = SkGradientShader::MakeLinear(
        pts, colors.data(), pos.data(), static_cast<int>(countUsed), tile,
        shouldDrawInPMColorSpace, &localMatrix);
  }

  if (!m_gradient) {
    // use last color, since our "geometry" was degenerate (e.g. radius==0)
    m_gradient = SkShader::MakeColorShader(colors[countUsed - 1]);
  }
  return m_gradient;
}
Exemplo n.º 5
0
VolumeFlow3D* FlowReader::readConvert(const tgt::ivec3& dimensions, const BYTE orientation,
                                      std::fstream& ifs)
{
    tgt::ivec3 permutation = Flow3D::getAxisPermutation(orientation);
    switch (orientation) {
        case Flow3D::XZY:
            LINFO("voxel order: XZY (code = " << static_cast<int>(orientation) << ")");
            LINFO("changing voxel order from XZY to XYZ...");
            break;
        case Flow3D::YXZ:
            LINFO("voxel order: YXZ (code = " << static_cast<int>(orientation) << ")");
            LINFO("changing voxel order from YXZ to XYZ...");
            break;
        case Flow3D::YZX:
            LINFO("voxel order: YZX (code = " << static_cast<int>(orientation) << ")");
            LINFO("changing voxel order from YZX to XYZ...");
            break;
        case Flow3D::ZXY:
            LINFO("voxel order: ZXY (code = " << static_cast<int>(orientation) << ")");
            LINFO("changing voxel order from ZXY to XYZ...");
            break;
        case Flow3D::ZYX:
            LINFO("voxel order: ZYX (code = " << static_cast<int>(orientation) << ")");
            LINFO("changing voxel order from ZYX to XYZ...");
            break;
        case Flow3D::XYZ:
            LINFO("voxel order: XYZ (code = " << static_cast<int>(orientation) << ")");
            LINFO("no conversion of voxel order required.");
            break;
        default:
            LINFO("voxel order: unknown (code = " << static_cast<int>(orientation) << ")");
            LINFO("further processing not possible! canceling");
            return 0;
    }

    const size_t numVoxels = dimensions.x * dimensions.y * dimensions.z;
    const size_t byteSize = numVoxels * sizeof(tgt::vec3);

    tgt::vec3* voxels = 0;
    try {
        voxels = new tgt::vec3[numVoxels];
    } catch (std::bad_alloc) {
        throw;
    }

    const tgt::ivec3 xyz(0, 1, 2);  // target voxel order is XYZ
    const int max = tgt::max(dimensions);

    // no remainder possible because getNumBytes is a multiple of max
    //
    const size_t bufferByteSize = byteSize / static_cast<size_t>(max);
    const size_t numBufferElements = bufferByteSize / sizeof(tgt::vec3);
    tgt::vec3* buffer = new tgt::vec3[numBufferElements];
    memset(buffer, 0, bufferByteSize);

    ProgressBar* progress = getProgressBar();

    tgt::ivec3 pos(0, 0, 0);
    float maxValue = std::numeric_limits<float>::min();
    float minValue = std::numeric_limits<float>::max();
    float maxMagnitude = 0.0f;

    for (size_t i = 0; i < size_t(max); ++i) {
        ifs.read(reinterpret_cast<char*>(buffer), bufferByteSize);
        if (progress)
            progress->setProgress(static_cast<float>(i) / static_cast<float>(max));

        for (size_t j = 0; j < numBufferElements; ++j) {
            // get the number of the voxel in current data orientation
            //
            size_t voxelNumber = j + (i * numBufferElements);

            if (orientation != Flow3D::XYZ) {
                // convert the number into the position within the voxel
                // ((x, y, z)-coordinates in volume's bounding box)
                //
                pos = Flow3D::voxelNumberToPos(voxelNumber, permutation, dimensions);

                // re-calculate the number of the voxel for the desired
                // data orientation
                //
                size_t newNumber = Flow3D::posToVoxelNumber(pos, xyz, dimensions);
                voxels[newNumber] = buffer[j];
            } else
                voxels[voxelNumber] = buffer[j];

            // calculate max and min of current voxel and dataset's min and max.
            //
            float voxelMax = tgt::max(buffer[j]);
            float voxelMin = tgt::min(buffer[j]);
            float magnitude = tgt::length(buffer[j]);

            if (voxelMax > maxValue)
                maxValue = voxelMax;
            if (voxelMin < minValue)
                minValue = voxelMin;
            if (magnitude > maxMagnitude)
                maxMagnitude = magnitude;
        }
    }

    delete [] buffer;

    LINFO("min. among all components of all voxels: " << minValue);
    LINFO("max. among all components of all voxels: " << maxValue);
    LINFO("max. magnitude among all  voxels: " << maxMagnitude);

    return new VolumeFlow3D(voxels, dimensions, minValue, maxValue, maxMagnitude);
}
Exemplo n.º 6
0
/*! Initializes the main menu state
 *
 *  @param          pContentLoader      Pointer to the content loader
 *  @returns        ICRESULT            Success/failure of initialization
**/
ICRESULT NetMenu::Init(icContentLoader* pContentLoader)
{
    if (!pContentLoader)
        return IC_FAIL_GEN;

    m_pContent = pContentLoader;

    icTexture *tex1 = NULL;
    icTexture *tex2 = NULL;

    icSoundParam param;
    param.bLoop = false;
    param.fPitch = 1.0f;
    param.fVol = gApp.GetSettings().fSfx_vol;

    // load the textures
    if (ICEFAIL(m_pContent->Load("Resource/textures/UI_net_menu.tga", &tex1)))
        return IC_FAIL_GEN;

    if (ICEFAIL(m_pContent->Load("Resource/textures/UI_net_menu_sel.tga", &tex2)))
        return IC_FAIL_GEN;

    // load the sounds
    if (ICEFAIL(m_pContent->Load("Resource/audio/whip_01.wav", &m_pHover)))
        return IC_FAIL_GEN;

    if (ICEFAIL(m_pContent->Load("Resource/audio/weirdbreath.wav", &m_pClick)))
        return IC_FAIL_GEN;

    m_pHover->SetParams(param);
    m_pClick->SetParams(param);

    icReal sx = (icReal)gApp.GetSettings().iScreen_x;
    icReal sy = (icReal)gApp.GetSettings().iScreen_y;

    icReal rat = sy/1024.0f;
    icReal mx = sx/2.0f;

    // set up UI Frame
    m_uiFrame = new icFrame(m_pContent);

    //m_uiFrame->SetTextures(tex1,tex2);

    icVector2 bl(0.0f,0.0f);
    icVector2 tl(0.0f,1.0f);
    icVector2 tr(1.0f,1.0f);
    icVector2 br(1.0f,0.0f);
    m_uiFrame->SetUVs( tl, tr, bl, br );

    icVector2 size(1280.0f,720.0f);
    icVector2 pos(640.0f,360.0f);
    icColor col(0,0,0,255);
    m_uiFrame->SetSize(size);
    m_uiFrame->SetPos(pos);
    m_uiFrame->SetColor(col);

    // network play widget
    m_wgtNetPlay = new icWidget(m_pContent);
    m_wgtNetPlay->SetTextures(tex1,tex2);
    size.Set(650.0f*rat,135.0f*rat);
    pos.Set(mx,sy*0.839f);
    //col.Set(0,0,0,255);
    m_wgtNetPlay->SetSize(size);
    m_wgtNetPlay->SetPos(pos);
    m_wgtNetPlay->SetColor(col);
    bl.Set(0.0f,0.861f);
    tl.Set(0.0f,1.0f);
    tr.Set(1.0f,1.0f);
    br.Set(1.0f,0.861f);
    m_wgtNetPlay->SetUVs(tl,tr,bl,br);
    m_wgtNetPlay->SetHighUVs(tl,tr,bl,br);
    m_wgtNetPlay->EnableHighlight(false);
    m_uiFrame->AddChild(m_wgtNetPlay);

    // host game button
    m_btnHost = new icButton(m_pContent);
    m_btnHost->SetTextures(tex1,tex2);
    size.Set(512.0f*rat,115.0f*rat);
    pos.Set(mx,sy*0.661f);
    //col.Set(0,0,0,255);
    m_btnHost->SetSize(size);
    m_btnHost->SetPos(pos);
    m_btnHost->SetColor(col);
    bl.Set(0.0f,0.646f);
    tl.Set(0.0f,0.811f);
    tr.Set(1.0f,0.811f);
    br.Set(1.0f,0.646f);
    m_btnHost->SetUVs(tl,tr,bl,br);
    m_btnHost->SetHighUVs(tl,tr,bl,br);
    m_btnHost->SetSounds(m_pClick,m_pHover);
    m_uiFrame->AddChild(m_btnHost);

    // join ip button
    m_btnJoinIP = new icButton(m_pContent);
    m_btnJoinIP->SetTextures(tex1,tex2);
    size.Set(512.0f*rat,120.0f*rat);
    pos.Set(mx,sy*0.504f);
    //col.Set(0,0,0,255);
    m_btnJoinIP->SetSize(size);
    m_btnJoinIP->SetPos(pos);
    m_btnJoinIP->SetColor(col);
    bl.Set(0.0f,0.436f);
    tl.Set(0.0f,0.611f);
    tr.Set(1.0f,0.611f);
    br.Set(1.0f,0.436f);
    m_btnJoinIP->SetUVs(tl,tr,bl,br);
    m_btnJoinIP->SetHighUVs(tl,tr,bl,br);
    m_btnJoinIP->SetSounds(m_pClick,m_pHover);
    m_uiFrame->AddChild(m_btnJoinIP);

    // find local button
    m_btnFind = new icButton(m_pContent);
    m_btnFind->SetTextures(tex1,tex2);
    size.Set(512.0f*rat,115.0f*rat);
    pos.Set(mx,sy*0.33f);
    //col.Set(0,0,0,255);
    m_btnFind->SetSize(size);
    m_btnFind->SetPos(pos);
    m_btnFind->SetColor(col);
    bl.Set(0.0f,0.238f);
    tl.Set(0.0f,0.406f);
    tr.Set(1.0f,0.406f);
    br.Set(1.0f,0.238f);
    m_btnFind->SetUVs(tl,tr,bl,br);
    m_btnFind->SetHighUVs(tl,tr,bl,br);
    m_btnFind->SetSounds(m_pClick,m_pHover);
    m_uiFrame->AddChild(m_btnFind);

    // main menu button
    m_btnMainMenu = new icButton(m_pContent);
    m_btnMainMenu->SetTextures(tex1,tex2);
    size.Set(512.0f*rat,100.0f*rat);
    pos.Set(mx,sy*0.135f);
    //col.Set(0,0,0,255);
    m_btnMainMenu->SetSize(size);
    m_btnMainMenu->SetPos(pos);
    m_btnFind->SetColor(col);
    bl.Set(0.0f,0.039f);
    tl.Set(0.0f,0.189f);
    tr.Set(1.0f,0.189f);
    br.Set(1.0f,0.039f);
    m_btnMainMenu->SetUVs(tl,tr,bl,br);
    m_btnMainMenu->SetHighUVs(tl,tr,bl,br);
    m_btnMainMenu->SetSounds(m_pClick,m_pHover);
    m_uiFrame->AddChild(m_btnMainMenu);
    return IC_OK;
}// END FUNCTION Init(icContentLoader* pContentLoader)
Exemplo n.º 7
0
int OSDPretty::current_display() const {
  QDesktopWidget* desktop = QApplication::desktop();
  return desktop->screenNumber(pos());
}
Exemplo n.º 8
0
void FluidMask::addObstacle(float x, float y, float rad)
{
    ofVec2f pos(x, y);
    pos /= fluid->scaleFactor;
    fluid->addObstacle(new ofxMPMObstacle(pos.x, pos.y, rad));
}
edge_image_type IonDetector::canny_edge( const image_type& img ) {
	image_type::extents_type three( 3, 3 );
	Kernel gaussian( image_type( three, boost::assign::list_of
		( 1./16 )( 2./16 )( 1./16 )
		( 2./16 )( 4./16 )( 2./16 )
		( 1./16 )( 2./16 )( 1./16 ) ) );
	Kernel sobelx( image_type( three, boost::assign::list_of
		(1)(0)(-1)(2)(0)(-2)(1)(0)(-1) ) );
	Kernel sobely( image_type( three, boost::assign::list_of
		(1)(2)(1)(0)(0)(0)(-1)(-2)(-1) ) );

	image_type img_gauss( img.extents ), img_sobelx( img.extents ),
		img_sobely( img.extents );

	//gaussian.apply_kernel( img, img_gauss );
	sobelx.apply_kernel( img, img_sobelx );
	sobely.apply_kernel( img, img_sobely );

	save_file( "orig.fits", img );
	//save_file( "gauss.fits", img_gauss );
	//save_file( "sobelx.fits", img_sobelx );
	//save_file( "sobely.fits", img_sobely );

	image_type img_sobel( img_sobelx.extents );
	edge_image_type edges( img_sobelx.extents );

	image_type::element mean = 0, std_dev = 0;
	for( image_type::index i = 2; i < img_sobelx.extents.first-2; ++i ) 
	for( image_type::index j = 2; j < img_sobelx.extents.second-2; ++j ) {
		image_type::element val = img_sobelx( i, j )*img_sobelx( i, j ) +
			img_sobely( i, j )*img_sobely( i, j );
		img_sobel( i, j ) = val;
		mean += val;
	}

	save_file( "sobel.fits", img_sobel );
	
	mean /= img_sobel.num_elements();	
	for( image_type::index i = 2; i<img_sobelx.extents.first-2; ++i ) 
	for( image_type::index j = 2; j<img_sobelx.extents.second-2; ++j ) {
		std_dev += ( img_sobel( i, j ) - mean )*
			( img_sobel( i, j ) - mean );
	}
			
	std_dev = sqrt(std_dev / img_sobel.num_elements());
	image_type::element thresh = mean + canny_threshold * std_dev;
	image_type::element continue_thresh = mean + 
		canny_continue_threshold * std_dev;

	// First mark off edges with a high threshold
	for( image_type::index i = 2; i<img_sobelx.extents.first-2; ++i ) 
	for( image_type::index j = 2; j<img_sobelx.extents.second-2; ++j ) {
		edge_image_type::position pos( i, j );
		if( edges( pos ) ) continue;
		if(	canny_check( img_sobel, img_sobelx, img_sobely, 
				pos, thresh ) ) {
			std::stack< image_type::position > checks;
			checks.push( pos );

			while( !checks.empty() ) {
				pos = checks.top();
				checks.pop();

				if( edges( pos ) ) continue;
				if( !canny_check( img_sobel, img_sobelx, img_sobely, 
						pos, continue_thresh ) ) 
					continue;

				edges( pos ) = 1.0f;
				pos.first++;	checks.push( pos );
				pos.second++;	checks.push( pos );
				pos.second-=2;	checks.push( pos );
				pos.first--;	checks.push( pos );
				pos.second+=2;	checks.push( pos );
				pos.first--;	checks.push( pos );
				pos.second--;	checks.push( pos );
				pos.second--;	checks.push( pos );
			}
		}
	}

		
	save_file( "edges.fits", edges );
	return edges;
}
Exemplo n.º 10
0
//  Sim Update
//-------------------------------------------------------------------------------------------------------------------------------
void COLLISION_WORLD::Update(double dt, bool profiling)
{
	///  Simulate
	world->stepSimulation(dt, maxSubsteps, fixedTimestep);
	
	//  use collision hit results, once a frame
	int n = world->vHits.size();
	if (n > 0)
	{
		//LogO(toStr(n));
		//  pick the one with biggest force
		DynamicsWorld::Hit& hit = world->vHits[0];
		float force = 0.f;//, vel = 0.f;
		for (int i=0; i < n; ++i)
			if (world->vHits[i].force > force)
			{
				force = world->vHits[i].force;
				hit = world->vHits[i];
			}

		CARDYNAMICS* cd = hit.sdCar->pCarDyn;
		cdOld = cd;
		btVector3 vcar = hit.vel;
		Ogre::Vector3 vel(vcar[0], vcar[2], -vcar[1]);
		Ogre::Vector3 norm(hit.norm.getX(), hit.norm.getZ(), -hit.norm.getY());
		float vlen = vel.length(), normvel = abs(vel.dotProduct(norm));

		//  Sparks emit params
		cd->vHitPos = Ogre::Vector3(hit.pos.getX(), hit.pos.getZ(), -hit.pos.getY());
		cd->vHitNorm = norm + vel * 0.1f;
		cd->fParVel = 3.0f + 0.4f * vlen;
		cd->fParIntens = 10.f + 30.f * vlen;
		
		///----  damage normal
		MATHVECTOR<Dbl,3> pos(hit.pos.getX(), hit.pos.getY(), hit.pos.getZ()),
			cN = pos - cd->GetPosition(),
			f = cN * force;
			f[0] *= gPar.camBncFHit;  f[1] *= gPar.camBncFHit;  f[2] *= gPar.camBncFHitY;
			cd->cam_force = cd->cam_force + f;  // cam bounce hit ++

		(-cd->GetOrientation()).RotateVector(cN);
		cd->vHitCarN = Ogre::Vector3(cN[0],cN[1],cN[2]);  cd->vHitCarN.normalise();
		//----  factors
		float sx = cd->vHitCarN.x, sy = cd->vHitCarN.y, sz = cd->vHitCarN.z;
		float nx = fabs(sx), ny = fabs(sy), nz = fabs(sz);
		cd->vHitDmgN.x = nx * (1.f-ny) * (1.f-nz) * (sx > 0 ? 1.0f : 0.3f);  // front x+
		cd->vHitDmgN.y = (1.f-nx) * ny * (1.f-nz) * 0.3f;  // side y
		cd->vHitDmgN.z = (1.f-nx) * (1.f-ny) * nz * (sz > 0 ? 1.0f : 0.1f);  // top z+
		cd->fHitDmgA = cd->vHitDmgN.x + cd->vHitDmgN.y + cd->vHitDmgN.z;
		//--------

		//  hit force for sound
		cd->fHitForce = normvel*0.02f /*+ 0.02f*vlen*/;  //+
		cd->fHitForce2 = force*0.1f;

		//  dyn obj hit  ***
		if (hit.dyn)
		{	cd->fHitForce *= 0.3f;  //par
			cd->fHitDmgA *= 0.4f;
		}
		
		//float a = (vlen*0.1f*powf(force, 0.2f) - 0*cd->fHitForce4);
		float a = std::min(1.f, std::min(vlen, 2.2f)*0.1f*powf(force, 0.4f) );
		if (a > cd->fCarScrap)  cd->fCarScrap = a;

		float b = std::min(1.f, 0.2f*force);
		if (b > cd->fCarScreech)  cd->fCarScreech = b;
			
		//if (cd->fHitForce4 > 0.f)
		//	cd->fHitForce4 -= 0.04f * dt;
		//if (force > 0.5f)
			cd->fHitTime = 1.f;
		///LogO("upd sf " + toStr(cd->fHitForce) + " force " + toStr(hit.force) + " vel " + toStr(vlen) + " Nvel " + toStr(normvel));
	}
	else if (cdOld)
	{
		cdOld->fHitForce  = 0.f;
		cdOld->fHitForce2 = 0.f;
		//cdOld->fHitForce4 = 0.f;
		//cdOld->fHitForce3 = cdOld->fHitTime;
		//cdOld = 0;
	}

	world->vHits.clear();//+
}
Exemplo n.º 11
0
/*
========================
idDebugGraph::Render
========================
*/
void idDebugGraph::Render( idRenderSystem* gui )
{
	if( !enable )
	{
		return;
	}
	
	gui->DrawFilled( bgColor, position.x, position.y, position.z, position.w );
	
	if( bars.Num() == 0 )
	{
		return;
	}
	
	if( sideways )
	{
		float barWidth = position.z - border * 2.0f;
		float barHeight = ( ( position.w - border ) / ( float )bars.Num() );
		float barLeft = position.x + border;
		float barTop = position.y + border;
		
		for( int i = 0; i < bars.Num(); i++ )
		{
			idVec4 rect( vec4_zero );
			if( mode == GRAPH_LINE )
			{
				rect.Set( barLeft + barWidth * bars[i].value, barTop + i * barHeight, 1.0f, barHeight - border );
			}
			else if( mode == GRAPH_FILL )
			{
				rect.Set( barLeft, barTop + i * barHeight, barWidth * bars[i].value, barHeight - border );
			}
			else if( mode == GRAPH_FILL_REVERSE )
			{
				rect.Set( barLeft + barWidth, barTop + i * barHeight, barWidth - barWidth * bars[i].value, barHeight - border );
			}
			gui->DrawFilled( bars[i].color, rect.x, rect.y, rect.z, rect.w );
		}
		if( labels.Num() > 0 )
		{
			int maxLen = 0;
			for( int i = 0; i < labels.Num(); i++ )
			{
				maxLen = Max( maxLen, labels[i].Length() );
			}
			idVec4 rect( position );
			rect.x -= SMALLCHAR_WIDTH * maxLen;
			rect.z = SMALLCHAR_WIDTH * maxLen;
			gui->DrawFilled( bgColor, rect.x, rect.y, rect.z, rect.w );
			for( int i = 0; i < labels.Num(); i++ )
			{
				idVec2 pos( barLeft - SMALLCHAR_WIDTH * maxLen, barTop + i * barHeight );
				gui->DrawSmallStringExt( idMath::Ftoi( pos.x ), idMath::Ftoi( pos.y ), labels[i], fontColor, true );
			}
		}
	}
	else
	{
		float barWidth = ( ( position.z - border ) / ( float )bars.Num() );
		float barHeight = position.w - border * 2.0f;
		float barLeft = position.x + border;
		float barTop = position.y + border;
		float barBottom = barTop + barHeight;
		
		for( int i = 0; i < grid.Num(); i++ )
		{
			idVec4 rect( position.x, barBottom - barHeight * grid[i].value, position.z, 1.0f );
			gui->DrawFilled( grid[i].color, rect.x, rect.y, rect.z, rect.w );
		}
		for( int i = 0; i < bars.Num(); i++ )
		{
			idVec4 rect;
			if( mode == GRAPH_LINE )
			{
				rect.Set( barLeft + i * barWidth, barBottom - barHeight * bars[i].value, barWidth - border, 1.0f );
			}
			else if( mode == GRAPH_FILL )
			{
				rect.Set( barLeft + i * barWidth, barBottom - barHeight * bars[i].value, barWidth - border, barHeight * bars[i].value );
			}
			else if( mode == GRAPH_FILL_REVERSE )
			{
				rect.Set( barLeft + i * barWidth, barTop, barWidth - border, barHeight * bars[i].value );
			}
			gui->DrawFilled( bars[i].color, rect.x, rect.y, rect.z, rect.w );
		}
		if( labels.Num() > 0 )
		{
			idVec4 rect( position );
			rect.y += barHeight;
			rect.w = SMALLCHAR_HEIGHT;
			gui->DrawFilled( bgColor, rect.x, rect.y, rect.z, rect.w );
			for( int i = 0; i < labels.Num(); i++ )
			{
				idVec2 pos( barLeft + i * barWidth, barBottom + border );
				gui->DrawSmallStringExt( idMath::Ftoi( pos.x ), idMath::Ftoi( pos.y ), labels[i], fontColor, true );
			}
		}
	}
}
Exemplo n.º 12
0
void Sokoban::deadlocks(std::vector< std::vector<char> > &map_out){
    // go through map to mark deadlocks
    // find all corners
    std::vector< std::vector<char> > deadlocks = map_out;
    for(int i = 0; i < map_out.size(); i++){
        for(int j = 0; j < (map_out.at(i)).size(); j++){
            pos_t pos(j,i);
            if(!isNotCorner(pos,map_out)){
                deadlocks[i][j] = MAP_WALL;
            }
        }
    }
    // find the deadlocks which are next to a wall with no goal
    // that is the block can not leave the wall again
    // find wall parts that have no indnent to push the diamond out
    //
    // first look at vertical walls
    for(int j = 0; j < (map_out.at(0)).size(); j++){ // go through x (row by row)
        bool unblocked_l = false, unblocked_r = false; // assume each row is blocked
        for(int i = 0; i < map_out.size(); i++){ // go vertical down and see it there is a wall next to it that is blocking
            char element = map_out[i][j];
            // check if the wall part ends
            if(MAP_IS_WALL(element)){
                if(!(unblocked_l && unblocked_r)){ // if any of the sides were blocked, go back and mark the deadlocks
//                    std::cout << "A piece of deadlockwall was found at ";
//                    std::cout << "(" << j << ", " << i << ")\n";
                    int b = i-1;
                    while( b >= 0  && !MAP_IS_WALL(map_out[b][j])){
                        deadlocks[b][j] = MAP_WALL;
                        b--;
                    }
                }
                unblocked_l = false;
                unblocked_r = false;


            } else if(MAP_IS_GOAL(element)){ // checkif the wall path is valid - that is there is a goal at the wall
                unblocked_l = true;
                unblocked_r = true;
            }
            // check if there is a continous wall on one of the sides (set false if there is a hole in the wall)
            if(j > 0){
                if(!MAP_IS_WALL(map_out[i][j-1])){
                    unblocked_l = true;
                }
            }
            if(j < (map_out.at(i)).size() - 1 ){
                if(!MAP_IS_WALL(map_out[i][j+1])){
                    unblocked_r = true;
                }
            }
        }
    }


    // now look at horizontal walls
    for(int i = 0; i < map_out.size(); i++){ // go vertical down and see it there is a wall next to it that is blocking
        bool unblocked_l = false, unblocked_r = false; // assume each row is blocked
        for(int j = 0; j < (map_out.at(i)).size(); j++){ // go through x (row by row)
            char element = map_out[i][j];
            // check if the wall part ends
            if(MAP_IS_WALL(element)){
                if(!(unblocked_l && unblocked_r)){ // if any of the sides were blocked, go back and mark the deadlocks
//                    std::cout << "A piece of deadlockwall was found at ";
//                    std::cout << "(" << j << ", " << i << ")\n";
                    int b = j-1;
                    while( b >= 0  && !MAP_IS_WALL(map_out[i][b])){
                        deadlocks[i][b] = MAP_WALL;
                        b--;
                    }
                }
                unblocked_l = false;
                unblocked_r = false;


            } else if(MAP_IS_GOAL(element)){ // checkif the wall path is valid - that is there is a goal at the wall
                unblocked_l = true;
                unblocked_r = true;
            }
            // check if there is a continous wall on one of the sides (set false if there is a hole in the wall)
            if(i > 0){
                if(!MAP_IS_WALL(map_out[i-1][j])){
                    unblocked_l = true;
                }
            }
            if(i < map_out.size() - 1 ){
                if(!MAP_IS_WALL(map_out[i+1][j])){
                    unblocked_r = true;
                }
            }
        }
    }

    // return the image
    map_out = deadlocks;
}
Exemplo n.º 13
0
// static public
// Insert an item in the relevant region map
// returns true if item inserted, false otherwise
bool LLWorldMap::insertItem(U32 x_world, U32 y_world, std::string& name, LLUUID& uuid, U32 type, S32 extra, S32 extra2)
{
    // Create an item record for the received object
    LLItemInfo new_item((F32)x_world, (F32)y_world, name, uuid);

    // Compute a region handle based on the objects coordinates
    LLVector3d	pos((F32)x_world, (F32)y_world, 40.0);
    U64 handle = to_region_handle(pos);

    // Get the region record for that handle or NULL if we haven't browsed it yet
    LLSimInfo* siminfo = LLWorldMap::getInstance()->simInfoFromHandle(handle);
    if (siminfo == NULL)
    {
        siminfo = LLWorldMap::getInstance()->createSimInfoFromHandle(handle);
    }

    //LL_INFOS("World Map") << "Process item : type = " << type << LL_ENDL;
    switch (type)
    {
    case MAP_ITEM_TELEHUB: // telehubs
    {
        /* Merov: we are not using the hub color anymore for display so commenting that out
        // Telehub color
        U32 X = x_world / REGION_WIDTH_UNITS;
        U32 Y = y_world / REGION_WIDTH_UNITS;
        F32 red = fmod((F32)X * 0.11f, 1.f) * 0.8f;
        F32 green = fmod((F32)Y * 0.11f, 1.f) * 0.8f;
        F32 blue = fmod(1.5f * (F32)(X + Y) * 0.11f, 1.f) * 0.8f;
        F32 add_amt = (X % 2) ? 0.15f : -0.15f;
        add_amt += (Y % 2) ? -0.15f : 0.15f;
        LLColor4 color(red + add_amt, green + add_amt, blue + add_amt);
        new_item.setColor(color);
        */

        // extra2 specifies whether this is an infohub or a telehub.
        if (extra2)
        {
            siminfo->insertInfoHub(new_item);
        }
        else
        {
            siminfo->insertTeleHub(new_item);
        }
        break;
    }
    case MAP_ITEM_PG_EVENT: // events
    case MAP_ITEM_MATURE_EVENT:
    case MAP_ITEM_ADULT_EVENT:
    {
        struct tm* timep;
        // Convert to Pacific, based on server's opinion of whether
        // it's daylight savings time there.
        timep = utc_to_pacific_time(extra, gPacificDaylightTime);

        S32 display_hour = timep->tm_hour % 12;
        if (display_hour == 0) display_hour = 12;

        new_item.setTooltip( llformat( "%d:%02d %s",
                                       display_hour,
                                       timep->tm_min,
                                       (timep->tm_hour < 12 ? "AM" : "PM") ) );

        // HACK: store Z in extra2
        new_item.setElevation((F64)extra2);
        if (type == MAP_ITEM_PG_EVENT)
        {
            siminfo->insertPGEvent(new_item);
        }
        else if (type == MAP_ITEM_MATURE_EVENT)
        {
            siminfo->insertMatureEvent(new_item);
        }
        else if (type == MAP_ITEM_ADULT_EVENT)
        {
            siminfo->insertAdultEvent(new_item);
        }
        break;
    }
    case MAP_ITEM_LAND_FOR_SALE:		// land for sale
    case MAP_ITEM_LAND_FOR_SALE_ADULT:	// adult land for sale
    {
        new_item.setTooltip(llformat("%d sq. m. %s%d", extra,
                                     gHippoGridManager->getConnectedGrid()->getCurrencySymbol().c_str(),
                                     extra2));
        if (type == MAP_ITEM_LAND_FOR_SALE)
        {
            siminfo->insertLandForSale(new_item);
        }
        else if (type == MAP_ITEM_LAND_FOR_SALE_ADULT)
        {
            siminfo->insertLandForSaleAdult(new_item);
        }
        break;
    }
    case MAP_ITEM_CLASSIFIED: // classifieds
    {
        //DEPRECATED: no longer used
        break;
    }
    case MAP_ITEM_AGENT_LOCATIONS: // agent locations
    {
// 				LL_INFOS("World Map") << "New Location " << new_item.mName << LL_ENDL;
        if (extra > 0)
        {
            new_item.setCount(extra);
            siminfo->insertAgentLocation(new_item);
        }
        break;
    }
    default:
        break;
    }
    return true;
}
Exemplo n.º 14
0
bool BoundingBox::IntersectP(const Ray & ray)
{
	//shadow ray and reflected ray returns false mistakenly
	//probably because they are in the box


	Vector3f pos(ray.getStartPosition());
	Vector3f inv_dir(ray.getInvDirection());


	float tx1 = (min_pos.x() - pos.x())*inv_dir.x();
	float tx2 = (max_pos.x() - pos.x())*inv_dir.x();

	float tmin = min(tx1, tx2);
	float tmax = max(tx1, tx2);

	float ty1 = (min_pos.y() - pos.y())*inv_dir.y();
	float ty2 = (max_pos.y() - pos.y())*inv_dir.y();

	tmin = max(tmin, min(ty1, ty2));
	tmax = min(tmax, max(ty1, ty2));


	//TODO, t should >0

	if (tmax >= tmin)
	{
		float tz1 = (min_pos.z() - pos.z())*inv_dir.z();
		float tz2 = (max_pos.z() - pos.z())*inv_dir.z();

		tmin = max(tmin, min(tz1, tz2));
		tmax = min(tmax, max(tz1, tz2));


		//To confirm?? tmax>0
		if(tmax >= tmin && tmax > 0)
		{
			//the line of ray will intersect
			//but maybe the t < 0

			

			return true;
		}
	}



	return false;






	
	//Vector3f dir(ray.getDirection());
	//Vector3f inv_dir(ray.getInvDirection());


	//float tx1 = (min_pos.x() - dir.x())*inv_dir.x();
	//float tx2 = (max_pos.x() - dir.x())*inv_dir.x();

	//float tmin = min(tx1, tx2);
	//float tmax = max(tx1, tx2);

	//float ty1 = (min_pos.y() - dir.y())*inv_dir.y();
	//float ty2 = (max_pos.y() - dir.y())*inv_dir.y();

	//tmin = max(tmin, min(ty1, ty2));
	//tmax = min(tmax, max(ty1, ty2));


	////TODO, t should >0

	//if (tmax >= tmin)
	//{
	//	float tz1 = (min_pos.z() - dir.z())*inv_dir.z();
	//	float tz2 = (max_pos.z() - dir.z())*inv_dir.z();

	//	tmin = max(tmin, min(tz1, tz2));
	//	tmax = min(tmax, max(tz1, tz2));


	//	if(tmax >= tmin)
	//	{
	//		//the line of ray will intersect
	//		//but maybe the t < 0

	//		//TODO
	//		return true;
	//	}
	//}



	//return false;



}
Exemplo n.º 15
0
void QgsComposerArrow::drawSVGMarker( QPainter* p, MarkerType type, const QString &markerPath )
{
  Q_UNUSED( markerPath );
  double ang = QgsComposerUtils::angle( mStartPoint, mStopPoint );

  double arrowHeadHeight;
  if ( type == StartMarker )
  {
    arrowHeadHeight = mStartArrowHeadHeight;
  }
  else
  {
    arrowHeadHeight = mStopArrowHeadHeight;
  }
  if ( mArrowHeadWidth <= 0 || arrowHeadHeight <= 0 )
  {
    //bad image size
    return;
  }

  QPointF imageFixPoint;
  imageFixPoint.setX( mArrowHeadWidth / 2.0 );
  QPointF canvasPoint;
  if ( type == StartMarker )
  {
    canvasPoint = QPointF( mStartPoint.x() - pos().x(), mStartPoint.y() - pos().y() );
    imageFixPoint.setY( mStartArrowHeadHeight );
  }
  else //end marker
  {
    canvasPoint = QPointF( mStopPoint.x() - pos().x(), mStopPoint.y() - pos().y() );
    imageFixPoint.setY( 0 );
  }

  //rasterize svg
  QSvgRenderer r;
  if ( type == StartMarker )
  {
    if ( mStartMarkerFile.isEmpty() || !r.load( mStartMarkerFile ) )
    {
      return;
    }
  }
  else //end marker
  {
    if ( mEndMarkerFile.isEmpty() || !r.load( mEndMarkerFile ) )
    {
      return;
    }
  }

  p->save();
  p->setRenderHint( QPainter::Antialiasing );
  if ( mBoundsBehaviour == 22 )
  {
    //if arrow was created in versions prior to 2.4, use the old rendering style
    //rotate image fix point for backtransform
    QPointF fixPoint;
    if ( type == StartMarker )
    {
      fixPoint.setX( 0 ); fixPoint.setY( arrowHeadHeight / 2.0 );
    }
    else
    {
      fixPoint.setX( 0 ); fixPoint.setY( -arrowHeadHeight / 2.0 );
    }
    QPointF rotatedFixPoint;
    double angleRad = ang / 180 * M_PI;
    rotatedFixPoint.setX( fixPoint.x() * cos( angleRad ) + fixPoint.y() * -sin( angleRad ) );
    rotatedFixPoint.setY( fixPoint.x() * sin( angleRad ) + fixPoint.y() * cos( angleRad ) );
    p->translate( canvasPoint.x() - rotatedFixPoint.x(), canvasPoint.y() - rotatedFixPoint.y() );
  }
  else
  {
    p->translate( canvasPoint.x(), canvasPoint.y() );
  }

  p->rotate( ang );
  p->translate( -mArrowHeadWidth / 2.0, -arrowHeadHeight / 2.0 );
  r.render( p, QRectF( 0, 0, mArrowHeadWidth, arrowHeadHeight ) );
  p->restore();

  return;
}
Exemplo n.º 16
0
/*
	Propagates sunlight down through the block.
	Doesn't modify nodes that are not affected by sunlight.
	
	Returns false if sunlight at bottom block is invalid.
	Returns true if sunlight at bottom block is valid.
	Returns true if bottom block doesn't exist.

	If there is a block above, continues from it.
	If there is no block above, assumes there is sunlight, unless
	is_underground is set or highest node is water.

	All sunlighted nodes are added to light_sources.

	if remove_light==true, sets non-sunlighted nodes black.

	if black_air_left!=NULL, it is set to true if non-sunlighted
	air is left in block.
*/
bool MapBlock::propagateSunlight(std::set<v3s16> & light_sources,
		bool remove_light, bool *black_air_left)
{
	INodeDefManager *nodemgr = m_gamedef->ndef();

	// Whether the sunlight at the top of the bottom block is valid
	bool block_below_is_valid = true;
	
	v3s16 pos_relative = getPosRelative();
	
	for(s16 x=0; x<MAP_BLOCKSIZE; x++)
	{
		for(s16 z=0; z<MAP_BLOCKSIZE; z++)
		{
#if 1
			bool no_sunlight = false;
			bool no_top_block = false;
			// Check if node above block has sunlight
			try{
				MapNode n = getNodeParent(v3s16(x, MAP_BLOCKSIZE, z));
				if(n.getContent() == CONTENT_IGNORE)
				{
					// Trust heuristics
					no_sunlight = is_underground;
				}
				else if(n.getLight(LIGHTBANK_DAY, m_gamedef->ndef()) != LIGHT_SUN)
				{
					no_sunlight = true;
				}
			}
			catch(InvalidPositionException &e)
			{
				no_top_block = true;
				
				// NOTE: This makes over-ground roofed places sunlighted
				// Assume sunlight, unless is_underground==true
				if(is_underground)
				{
					no_sunlight = true;
				}
				else
				{
					MapNode n = getNode(v3s16(x, MAP_BLOCKSIZE-1, z));
					if(m_gamedef->ndef()->get(n).sunlight_propagates == false)
					{
						no_sunlight = true;
					}
				}
				// NOTE: As of now, this just would make everything dark.
				// No sunlight here
				//no_sunlight = true;
			}
#endif
#if 0 // Doesn't work; nothing gets light.
			bool no_sunlight = true;
			bool no_top_block = false;
			// Check if node above block has sunlight
			try{
				MapNode n = getNodeParent(v3s16(x, MAP_BLOCKSIZE, z));
				if(n.getLight(LIGHTBANK_DAY) == LIGHT_SUN)
				{
					no_sunlight = false;
				}
			}
			catch(InvalidPositionException &e)
			{
				no_top_block = true;
			}
#endif

			/*std::cout<<"("<<x<<","<<z<<"): "
					<<"no_top_block="<<no_top_block
					<<", is_underground="<<is_underground
					<<", no_sunlight="<<no_sunlight
					<<std::endl;*/
		
			s16 y = MAP_BLOCKSIZE-1;
			
			// This makes difference to diminishing in water.
			bool stopped_to_solid_object = false;
			
			u8 current_light = no_sunlight ? 0 : LIGHT_SUN;

			for(; y >= 0; y--)
			{
				v3s16 pos(x, y, z);
				MapNode &n = getNodeRef(pos);
				
				if(current_light == 0)
				{
					// Do nothing
				}
				else if(current_light == LIGHT_SUN && nodemgr->get(n).sunlight_propagates)
				{
					// Do nothing: Sunlight is continued
				}
				else if(nodemgr->get(n).light_propagates == false)
				{
					// A solid object is on the way.
					stopped_to_solid_object = true;
					
					// Light stops.
					current_light = 0;
				}
				else
				{
					// Diminish light
					current_light = diminish_light(current_light);
				}

				u8 old_light = n.getLight(LIGHTBANK_DAY, nodemgr);

				if(current_light > old_light || remove_light)
				{
					n.setLight(LIGHTBANK_DAY, current_light, nodemgr);
				}
				
				if(diminish_light(current_light) != 0)
				{
					light_sources.insert(pos_relative + pos);
				}

				if(current_light == 0 && stopped_to_solid_object)
				{
					if(black_air_left)
					{
						*black_air_left = true;
					}
				}
			}

			// Whether or not the block below should see LIGHT_SUN
			bool sunlight_should_go_down = (current_light == LIGHT_SUN);

			/*
				If the block below hasn't already been marked invalid:

				Check if the node below the block has proper sunlight at top.
				If not, the block below is invalid.
				
				Ignore non-transparent nodes as they always have no light
			*/
			try
			{
			if(block_below_is_valid)
			{
				MapNode n = getNodeParent(v3s16(x, -1, z));
				if(nodemgr->get(n).light_propagates)
				{
					if(n.getLight(LIGHTBANK_DAY, nodemgr) == LIGHT_SUN
							&& sunlight_should_go_down == false)
						block_below_is_valid = false;
					else if(n.getLight(LIGHTBANK_DAY, nodemgr) != LIGHT_SUN
							&& sunlight_should_go_down == true)
						block_below_is_valid = false;
				}
			}//if
			}//try
			catch(InvalidPositionException &e)
			{
				/*std::cout<<"InvalidBlockException for bottom block node"
						<<std::endl;*/
				// Just no block below, no need to panic.
			}
		}
	}

	return block_below_is_valid;
}
Exemplo n.º 17
0
void Hud::drawLuaElements() {
	for (size_t i = 0; i != player->hud.size(); i++) {
		HudElement *e = player->hud[i];
		if (!e)
			continue;
		
		v2s32 pos(e->pos.X * screensize.X, e->pos.Y * screensize.Y);
		switch (e->type) {
			case HUD_ELEM_IMAGE: {
				video::ITexture *texture = tsrc->getTexture(e->text);
				if (!texture)
					continue;

				const video::SColor color(255, 255, 255, 255);
				const video::SColor colors[] = {color, color, color, color};
				core::dimension2di imgsize(texture->getOriginalSize());
				v2s32 dstsize(imgsize.Width * e->scale.X,
				              imgsize.Height * e->scale.Y);
				if (e->scale.X < 0)
					dstsize.X = screensize.X * (e->scale.X * -0.01);
				if (e->scale.Y < 0)
					dstsize.Y = screensize.Y * (e->scale.Y * -0.01);
				v2s32 offset((e->align.X - 1.0) * dstsize.X / 2,
				             (e->align.Y - 1.0) * dstsize.Y / 2);
				core::rect<s32> rect(0, 0, dstsize.X, dstsize.Y);
				rect += pos + offset + v2s32(e->offset.X, e->offset.Y);
				driver->draw2DImage(texture, rect,
					core::rect<s32>(core::position2d<s32>(0,0), imgsize),
					NULL, colors, true);
				break; }
			case HUD_ELEM_TEXT: {
				video::SColor color(255, (e->number >> 16) & 0xFF,
										 (e->number >> 8)  & 0xFF,
										 (e->number >> 0)  & 0xFF);
				core::rect<s32> size(0, 0, e->scale.X, text_height * e->scale.Y);
				std::wstring text = narrow_to_wide(e->text);
				core::dimension2d<u32> textsize = font->getDimension(text.c_str());
				v2s32 offset((e->align.X - 1.0) * (textsize.Width / 2),
				             (e->align.Y - 1.0) * (textsize.Height / 2));
				v2s32 offs(e->offset.X, e->offset.Y);
				font->draw(text.c_str(), size + pos + offset + offs, color);
				break; }
			case HUD_ELEM_STATBAR: {
				v2s32 offs(e->offset.X, e->offset.Y);
				drawStatbar(pos, HUD_CORNER_UPPER, e->dir, e->text, e->number, offs);
				break; }
			case HUD_ELEM_INVENTORY: {
				InventoryList *inv = inventory->getList(e->text);
				drawItem(pos, hotbar_imagesize, e->number, inv, e->item, e->dir);
				break; }
			case HUD_ELEM_WAYPOINT: {
				v3f p_pos = player->getPosition() / BS;
				v3f w_pos = e->world_pos * BS;
				float distance = floor(10 * p_pos.getDistanceFrom(e->world_pos)) / 10;
				scene::ICameraSceneNode* camera = smgr->getActiveCamera();
				core::matrix4 trans = camera->getProjectionMatrix();
				trans *= camera->getViewMatrix();
				f32 transformed_pos[4] = { w_pos.X, w_pos.Y, w_pos.Z, 1.0f };
				trans.multiplyWith1x4Matrix(transformed_pos);
				if (transformed_pos[3] < 0)
					break;
				f32 zDiv = transformed_pos[3] == 0.0f ? 1.0f :
					core::reciprocal(transformed_pos[3]);
				pos.X = screensize.X * (0.5 * transformed_pos[0] * zDiv + 0.5);
				pos.Y = screensize.Y * (0.5 - transformed_pos[1] * zDiv * 0.5);
				video::SColor color(255, (e->number >> 16) & 0xFF,
										 (e->number >> 8)  & 0xFF,
										 (e->number >> 0)  & 0xFF);
				core::rect<s32> size(0, 0, 200, 2 * text_height);
				std::wstring text = narrow_to_wide(e->name);
				font->draw(text.c_str(), size + pos, color);
				std::ostringstream os;
				os<<distance<<e->text;
				text = narrow_to_wide(os.str());
				pos.Y += text_height;
				font->draw(text.c_str(), size + pos, color);
				break; }
			default:
				infostream << "Hud::drawLuaElements: ignoring drawform " << e->type <<
					" of hud element ID " << i << " due to unrecognized type" << std::endl;
		}
	}
}
Exemplo n.º 18
0
void CcdChapter::CreateBullet()
{

	m_pkCollisionConfiguration = new btDefaultCollisionConfiguration();
	m_pkDispatcher = new btCollisionDispatcher(m_pkCollisionConfiguration);

	m_pkBroadphase = new btDbvtBroadphase();
	m_pkSolver = new btSequentialImpulseConstraintSolver();

	m_pkDynamicsWorld = new btDiscreteDynamicsWorld(m_pkDispatcher, m_pkBroadphase, m_pkSolver, m_pkCollisionConfiguration);
	m_pkDynamicsWorld->getSolverInfo().m_solverMode |= SOLVER_RANDMIZE_ORDER;

	m_pkDynamicsWorld->getDispatchInfo().m_enableSPU = true;
	m_pkDynamicsWorld->setGravity(btVector3(0, -10, 0));


	gContactAddedCallback = contactAddedCallback;


	//	DebugDraw
	m_pkDebugDraw = new BulletDebugDraw();
	m_pkDebugDraw->setVisible(false);
	m_pkDynamicsWorld->setDebugDrawer(m_pkDebugDraw);
	m_pkDebugDraw->setDebugMode(BulletDebugDraw::DBG_DrawText | BulletDebugDraw::DBG_DrawContactPoints);

	m_pkDebugNode = m_pkRootNode->createChildSceneNode();
	m_pkDebugNode->attachObject(m_pkDebugDraw);






	int i;
	btTransform tr;
	tr.setIdentity();

	for(i=0; i<120; ++i)
	{
		if(i>0)
		{
			m_nShapeIndex[i] = 1;
		}
		else
			m_nShapeIndex[i] = 0;
	}

	for(i=0; i<32760; ++i)
	{
		btCollisionShape *shape = m_CollisionShapes[m_nShapeIndex[i]];
		shape->setMargin(0.05f);

		bool isDyna = 1>0;

		btTransform trans;
		trans.setIdentity();

		if(i>0)
		{
			int colsize = 10;
			int row = (i*0.5f*2)/(colsize*2*0.5f);
			int row2 = row;
			int col = (i)%(colsize)-colsize/2;

			if(col>3)
			{
				col = 11;
				row2 |= 1;
			}

			btVector3 pos(col*2*0.5f + (row2%2)*0.5f, row*2*0.5f+0.5f+ -10.f, 0);

			trans.setOrigin(pos);
		}
		else
		{
			trans.setOrigin(btVector3(0, -10.0f-0.5f, 0));
		}

		float mass = 1.0f;

		if( !isDyna )
			mass = 0.0f;

		btRigidBody *body = CreateRigidBody(shape, isDyna, trans, mass);

		body->setCcdMotionThreshold( 0.5f );

		body->setCcdSweptSphereRadius( 0.2f * 0.5f );
	}
}
Exemplo n.º 19
0
void FlappyCatGame::initialize() {

  using Constant = FlappyCatGameConstants::Constants;
  using ColorConstant = FlappyCatColorScheme::Colors;

  // background
  mBackground.moveTo(-(mGameConstants[Constant::CameraSize] / 2.f));
  mBackground.resize(mGameConstants[Constant::CameraSize]);
  mBackground.setResetModifier(
    [this](FlappyCatBackground& background) {

      const FlappyCatColorScheme& colorScheme = mGameConstants.colorScheme();

      background.setColor(colorScheme[ColorConstant::BackgroundColor]);
    }
  );

  // limit
  mLimit.moveTo(-(mGameConstants[Constant::CameraSize] / 2.f));
  mLimit.resize(mGameConstants[Constant::CameraSize]);

  // floor
  mFloor.moveTo(mGameConstants[Constant::FloorPosition]);
  mFloor.resize(mGameConstants[Constant::FloorSize]);
  mFloor.setDecorationSizes(mGameConstants[Constant::FloorOrganicSurfaceSize],
                            mGameConstants[Constant::FloorSpikesSize]);

  mFloor.setResetModifier(
    [this](FlappyCatFloor& floor) {

      const FlappyCatColorScheme& colorScheme = mGameConstants.colorScheme();

      floor.setMovementDisplacement(mGameConstants[Constant::PhysicsForegroundDisplacement]);
      floor.setColor(colorScheme[ColorConstant::BlockColor], colorScheme[ColorConstant::DirtColor]);
    }
  );

  mFloor.setUpdateModifier(
    [this](FlappyCatFloor& floor, const FrameDuration& frameDuration) {

      Position::value_type radius = mHero.radius();
      // TODO: implement proper origin in 'transformation' and remove this line
      // circle origin in bottom left so we shift by radius
      Position center = mHero.position() + Position(radius, radius);

      if (mGameState == PlayState || mGameState == LoseState) {

        if (Collide::circleRect(center, radius, mFloor.boundingBox())) {
          mGameState = OnTheFloorState;
          mHero.moveTo(Position(mHero.position().x(), mFloor.position().y()));
        }
      }

      UNUSED(floor); // this update function process 'mHere' as a real target, not floor
      UNUSED(frameDuration); // not need for time processing here
    }
  );

  // moving walls
  mBarricade.moveTo(mGameConstants[Constant::BarricadePosition]);
  mBarricade.resize(mGameConstants[Constant::BarricadeSize]);
  mBarricade.setStartOffset(mGameConstants[Constant::BarricadeStartOffset]);
  mBarricade.setLinkSize(mGameConstants[Constant::BarricadeWallSize]);
  mBarricade.setOffsetBetweenLinks(mGameConstants[Constant::BarricadeBetweenWallOffset]);
  mBarricade.setMovementDisplacement(mGameConstants[Constant::PhysicsForegroundDisplacement]);

  mBarricade.setResetModifier(
    [this](FlappyCatWall& wall) {

      const FlappyCatColorScheme& colorScheme = mGameConstants.colorScheme();

      wall.setGapInterval(mHero.radius() * 2.f * 4.f);

      Position offset = mGameConstants[Constant::BarricadeWallGapDisplacement];
      wall.setGapDisplacement(mGameConstants.clampedRandomOffsetFrom(offset.x(), offset.y()));

      wall.setColor(colorScheme[ColorConstant::BlockColor]);
    }
  );

  mBarricade.setUpdateModifier(
    [this](FlappyCatWall& wall) {

      Position::value_type radius = mHero.radius();
      // TODO: implement proper origin in 'transformation' and remove this code
      // circle origin in bottom left so we shift by radius
      Position center = mHero.position() + Position(radius, radius);

      if (mGameState == PlayState) {

        if (wall.collideWithCircle(center, radius)) {

          mGameState = LoseState;
          mFloor.setMovementDisplacement(Position(0.f, 0.f));
        }
      }
    }
  );

  mBarricade.setWrapAroundModifier(
    [this](FlappyCatWall& wall) {

      Position offset = mGameConstants[Constant::BarricadeWallGapDisplacement];
      wall.setGapDisplacement(mGameConstants.clampedRandomOffsetFrom(offset.x(), offset.y()));
    }
  );

  // city buildings
  mBackgroundCity.moveTo(mGameConstants[Constant::CityPosition]);
  mBackgroundCity.resize(mGameConstants[Constant::CitySize]);
  mBackgroundCity.setLinkSize(mGameConstants[Constant::CityHouseSize]);
  mBackgroundCity.setMovementDisplacement(mGameConstants[Constant::PhysicsBackgroundDisplacement]);

  mBackgroundCity.setResetModifier(
    [this](FlappyCatSpike& house) {

      const FlappyCatColorScheme& colorScheme = mGameConstants.colorScheme();

      Position offset = mGameConstants[Constant::CityHouseOffset];
      Position varyingSize(mGameConstants[Constant::CityHouseSize]
                           + Position(0.f, std::abs(mGameConstants.randomOffsetFrom(offset.x(),
                                                                                    offset.y()))));
      house.resize(varyingSize);
      house.setColor(colorScheme[ColorConstant::HouseColor]);
    }
  );

  mBackgroundCity.setWrapAroundModifier(
    [this](FlappyCatSpike& house) {

      Position offset = mGameConstants[Constant::CityHouseOffset];
      Position varyingSize(mGameConstants[Constant::CityHouseSize]
                           + Position(0.f, std::abs(mGameConstants.randomOffsetFrom(offset.x(),
                                                                                    offset.y()))));
      house.resize(varyingSize);
    }
  );

  // sky with clouds
  mBackgroundSky.setParts(mGameConstants[Constant::SkyCloudParts].x());
  mBackgroundSky.setResetModifier(
    [this](FlappyCatCloud::entity_type& cloud) {

      const FlappyCatColorScheme& colorScheme = mGameConstants.colorScheme();

      Position cloudOffset = mGameConstants[Constant::SkyCloudOffset];
      Position skyOffset = mGameConstants[Constant::SkyOffset];

      cloud.geometry().setRadius(mGameConstants[Constant::SkyCloudSize].x()
                               + std::abs(mGameConstants.randomOffsetFrom(cloudOffset.x(),
                                                                          cloudOffset.y())));

      Position pos(mGameConstants.randomOffsetFrom(skyOffset.x(), skyOffset.y()),
                   mGameConstants.randomOffsetFrom(skyOffset.x(), skyOffset.y()));

      cloud.transformation().setPosition(pos);
      cloud.setColor(colorScheme[ColorConstant::CloudColor]);
    }
  );

  // cat hero!
  mHero.setJumpConstants(mGameConstants[Constant::PhysicsJumpAcceleration],
                         mGameConstants[Constant::PhysicsJumpVelocity]);
  mHero.setGravity(mGameConstants[Constant::PhysicsGravity]);

  mHero.setUpdateModifier(
    [this](FlappyCatHero& hero, const FrameDuration& frameDuration) {

      hero.moveBy(hero.distance());

      // tilt the hero
      Position::value_type angle = hero.rotation();

      if (hero.distance().y() > 0.f) {
        if (angle < 35.f) {
          angle += 2.5f;
        }
      }
      else {
        if (angle > -90.f) {
          angle -= 2.5f;
        }
      }

      hero.rotateTo(angle);

      UNUSED(frameDuration); // not need for time processing here
    }
  );

  mHero.setResetModifier(
    [this](FlappyCatHero& hero) {

      const FlappyCatColorScheme& colorScheme = mGameConstants.colorScheme();

      hero.setRadius(mGameConstants[Constant::HeroSize].x());
      hero.moveTo(mGameConstants[Constant::HeroPosition]);
      hero.rotateTo(0.f);

      hero.setColor(colorScheme[ColorConstant::HeroColor],
                    colorScheme[ColorConstant::MascotBodyColor],
                    colorScheme[ColorConstant::MascotScarfColor],
                    colorScheme[ColorConstant::MascotMouthColor]);
    }
  );

  // initialize all stuff
  mBackground.initialize();
  mFloor.initialize();
  mBarricade.initialize();
  mBackgroundCity.initialize();
  mBackgroundSky.initialize();
  mHero.initialize();
  mLimit.initialize();
}
Exemplo n.º 20
0
//
// Framework functions
//
bool Setup()
{
	HRESULT hr = 0;

	//
	// Load the XFile data.
	//

	ID3DXBuffer* adjBuffer  = 0;
	ID3DXBuffer* mtrlBuffer = 0;
	DWORD        numMtrls   = 0;

	hr = D3DXLoadMeshFromX(  
		"bigship1.x",
		D3DXMESH_MANAGED,
		Device,
		&adjBuffer,
		&mtrlBuffer,
		0,
		&numMtrls,
		&Mesh);

	if(FAILED(hr))
	{
		::MessageBox(0, "D3DXLoadMeshFromX() - FAILED", 0, 0);
		return false;
	}

	//
	// Extract the materials, and load textures.
	//

	printf("numMtrls:%i",numMtrls);

	if( mtrlBuffer != 0 && numMtrls != 0 )
	{
		D3DXMATERIAL* mtrls = (D3DXMATERIAL*)mtrlBuffer->GetBufferPointer();

		for(int i = 0; i < numMtrls; i++)
		{
			// the MatD3D property doesn't have an ambient value set
			// when its loaded, so set it now:
			mtrls[i].MatD3D.Ambient = mtrls[i].MatD3D.Diffuse;

			// save the ith material
			Mtrls.push_back( mtrls[i].MatD3D );

			// check if the ith material has an associative texture
			if( mtrls[i].pTextureFilename != 0 )
			{
				// yes, load the texture for the ith subset
				IDirect3DTexture9* tex = 0;
				D3DXCreateTextureFromFile(
					Device,
					mtrls[i].pTextureFilename,
					&tex);

				// save the loaded texture
				Textures.push_back( tex );
			}
			else
			{
				// no texture for the ith subset
				Textures.push_back( 0 );
			}
		}
	}
	d3d::Release<ID3DXBuffer*>(mtrlBuffer); // done w/ buffer

	//
	// Optimize the mesh.
	//

	hr = Mesh->OptimizeInplace(		
		D3DXMESHOPT_ATTRSORT |
		D3DXMESHOPT_COMPACT  |
		D3DXMESHOPT_VERTEXCACHE,
		(DWORD*)adjBuffer->GetBufferPointer(),
		0, 0, 0);

	d3d::Release<ID3DXBuffer*>(adjBuffer); // done w/ buffer

	if(FAILED(hr))
	{
		::MessageBox(0, "OptimizeInplace() - FAILED", 0, 0);
		return false;
	}

	//
	// Set texture filters.
	//

	Device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
	Device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
	Device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT);

	// 
	// Set Lights.
	//

	D3DXVECTOR3 dir(1.0f, -1.0f, 1.0f);
	D3DXCOLOR col(1.0f, 1.0f, 1.0f, 1.0f);
	D3DLIGHT9 light = d3d::InitDirectionalLight(&dir, &col);

	Device->SetLight(0, &light);
	Device->LightEnable(0, true);
	Device->SetRenderState(D3DRS_NORMALIZENORMALS, true);
	Device->SetRenderState(D3DRS_SPECULARENABLE, true);

	//
	// Set camera.
	//

	D3DXVECTOR3 pos(4.0f, 4.0f, -13.0f);
	D3DXVECTOR3 target(0.0f, 0.0f, 0.0f);
	D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);

	D3DXMATRIX V;
	D3DXMatrixLookAtLH(
		&V,
		&pos,
		&target,
		&up);

	Device->SetTransform(D3DTS_VIEW, &V);

	//
	// Set projection matrix.
	//

	D3DXMATRIX proj;
	D3DXMatrixPerspectiveFovLH(
			&proj,
			D3DX_PI * 0.5f, // 90 - degree
			(float)Width / (float)Height,
			1.0f,
			1000.0f);
	Device->SetTransform(D3DTS_PROJECTION, &proj);

	return true;
}
Exemplo n.º 21
0
int    KX_VertexProxy::py_setattro(PyObject *attr, PyObject *pyvalue)
{
  char *attr_str= _PyUnicode_AsString(attr);
  if (PySequence_Check(pyvalue))
  {
	if (!strcmp(attr_str, "XYZ"))
	{
		MT_Point3 vec;
		if (PyVecTo(pyvalue, vec))
		{
			m_vertex->SetXYZ(vec);
			m_mesh->SetMeshModified(true);
			return PY_SET_ATTR_SUCCESS;
		}
		return PY_SET_ATTR_FAIL;
	}

	if (!strcmp(attr_str, "UV"))
	{
		MT_Point2 vec;
		if (PyVecTo(pyvalue, vec))
		{
			m_vertex->SetUV(vec);
			m_mesh->SetMeshModified(true);
			return PY_SET_ATTR_SUCCESS;
		}
		return PY_SET_ATTR_FAIL;
	}

	if (!strcmp(attr_str, "color") || !strcmp(attr_str, "colour"))
	{
		MT_Vector4 vec;
		if (PyVecTo(pyvalue, vec))
		{
			m_vertex->SetRGBA(vec);
			m_mesh->SetMeshModified(true);
			return PY_SET_ATTR_SUCCESS;
		}
		return PY_SET_ATTR_FAIL;
	}

	if (!strcmp(attr_str, "normal"))
	{
		MT_Vector3 vec;
		if (PyVecTo(pyvalue, vec))
		{
			m_vertex->SetNormal(vec);
			m_mesh->SetMeshModified(true);
			return PY_SET_ATTR_SUCCESS;
		}
		return PY_SET_ATTR_FAIL;
	}
  }

  if (PyFloat_Check(pyvalue))
  {
  	float val = PyFloat_AsDouble(pyvalue);
  	// pos
	MT_Point3 pos(m_vertex->getXYZ());
  	if (!strcmp(attr_str, "x"))
	{
		pos.x() = val;
		m_vertex->SetXYZ(pos);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}

  	if (!strcmp(attr_str, "y"))
	{
		pos.y() = val;
		m_vertex->SetXYZ(pos);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}

	if (!strcmp(attr_str, "z"))
	{
		pos.z() = val;
		m_vertex->SetXYZ(pos);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}

	// uv
	MT_Point2 uv = m_vertex->getUV1();
	if (!strcmp(attr_str, "u"))
	{
		uv[0] = val;
		m_vertex->SetUV(uv);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}

	if (!strcmp(attr_str, "v"))
	{
		uv[1] = val;
		m_vertex->SetUV(uv);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}

	// uv
	MT_Point2 uv2 = m_vertex->getUV2();
	if (!strcmp(attr_str, "u2"))
	{
		uv[0] = val;
		m_vertex->SetUV2(uv);
		m_mesh->SetMeshModified(true);
		return 0;
	}

	if (!strcmp(attr_str, "v2"))
	{
		uv[1] = val;
		m_vertex->SetUV2(uv);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}

	// col
	unsigned int icol = *((const unsigned int *)m_vertex->getRGBA());
	unsigned char *cp = (unsigned char*) &icol;
	val *= 255.0;
	if (!strcmp(attr_str, "r"))
	{
		cp[0] = (unsigned char) val;
		m_vertex->SetRGBA(icol);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}
	if (!strcmp(attr_str, "g"))
	{
		cp[1] = (unsigned char) val;
		m_vertex->SetRGBA(icol);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}
	if (!strcmp(attr_str, "b"))
	{
		cp[2] = (unsigned char) val;
		m_vertex->SetRGBA(icol);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}
	if (!strcmp(attr_str, "a"))
	{
		cp[3] = (unsigned char) val;
		m_vertex->SetRGBA(icol);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}
  }

  return CValue::py_setattro(attr, pyvalue);
}
Exemplo n.º 22
0
//////////////////////////////////////////////////////////////////////////
// initialize seeds with possibly different start times 
//////////////////////////////////////////////////////////////////////////
void vtCFieldLine::setSeedPoints(VECTOR4* points, int numPoints, 
		int64_t *seedIds)
{
	int i, res;
	VECTOR3 nodeData;

	if(points == NULL)
		return;

	// if the rake size has changed, forget the previous seed points
	if( m_nNumSeeds != numPoints )
		releaseSeedMemory();

	if ( seedIds != NULL )
	{
		for (i = 0 ; i < numPoints ; i++ )
		{
			m_lSeedIds.push_back( seedIds[i] );
		}
	}

	if( m_nNumSeeds == 0 )
	{
		for(i = 0 ; i < numPoints ; i++ )
		{
			vtParticleInfo* newParticle = new vtParticleInfo;

			VECTOR3 pos(points[i][0], points[i][1], points[i][2]); 
			newParticle->m_pointInfo.phyCoord = pos;
			newParticle->m_fStartTime = points[i][3]; 
			newParticle->ptId = i;

			// query the field in order to get the starting
			// cell interpolant for the seed point
			// which was passed to us without any prior information

			res = m_pField->at_phys(-1, pos, newParticle->m_pointInfo, points[i][3], nodeData);
// 			newParticle->itsValidFlag =  (res == 1) ? 1 : 0 ;
			newParticle->itsValidFlag =  1;
			m_lSeeds.push_back( newParticle );
		}
	} 
	else
	{
		vtListParticleIter sIter = m_lSeeds.begin();

		for(i = 0 ; sIter != m_lSeeds.end() ; ++sIter, ++i )
		{
			vtParticleInfo* thisSeed = *sIter;

			VECTOR3 pos(points[i][0], points[i][1], points[i][2]); 
			// set the new location for this seed point
			thisSeed->m_pointInfo.phyCoord = pos;
			thisSeed->m_fStartTime = points[i][3];
			res = m_pField->at_phys(-1, pos, thisSeed->m_pointInfo, points[i][3], nodeData);
			thisSeed->itsValidFlag =  (res == 1) ? 1 : 0 ;
		}    
	}

	m_nNumSeeds = numPoints;
}
void CCBManager::Update()
{
	//チョコボールを生成していく。
	const float deltaTime = 1.0f / 60.0f;
	m_timer += deltaTime;
	if (m_interval < m_timer){
		int createCount = 0;
		while ( m_numCreate < CHOCO_NUM ){
			if (createCount == 10){
				break;
			}
			float rate = 100.0f / (rand() % 100 + 1);
			rate /= 50.0f;
			if (rand() % 2){
				rate *= -1.0f;
			}
			D3DXVECTOR3 pos(GetStartPosition());
			pos.x += rate;
			pos.z += fabsf(rate);
			pos.y += rate;
			D3DXVECTOR3 Epos(GetEndPosition());
			Epos.x += rate;
			Epos.z += fabsf(rate);
			Epos.y += rate;
			m_Choco[m_numCreate].Initialize(pos, Epos);
			//if (m_IsFirst){
			//	D3DXMESHCONTAINER_DERIVED* pMeshContainer = static_cast<D3DXMESHCONTAINER_DERIVED*>(m_Choco[m_numCreate].GetImage()->pModel->GetFrameRoot()->pMeshContainer);
			//	LPDIRECT3DVERTEXBUFFER9 buffer;
			//	pMeshContainer->MeshData.pMesh->GetVertexBuffer(&buffer)/*->GetBufferPointer()*/;
			//	VOID* pVertices;
			//	buffer->Lock(0, sizeof(buffer), (void**)&pVertices, 0);
			//	D3DVERTEXBUFFER_DESC desc;
			//	buffer->GetDesc(&desc);
			//	int stride = D3DXGetFVFVertexSize(desc.FVF);
			//	char* p = (char*)pVertices;
			//	int offset = -1;
			//	D3DVERTEXELEMENT9 pDecl[MAX_FVF_DECL_SIZE];
			//	memset(pDecl, -1, sizeof(pDecl));
			//	pMeshContainer->MeshData.pMesh->GetDeclaration(pDecl);
			//	for (int idx = 0; idx < MAX_FVF_DECL_SIZE; idx++){
			//		if (pDecl[idx].Stream == 255){
			//			//終わり
			//			break;
			//		}
			//		if (pDecl[idx].Usage == D3DDECLUSAGE_BINORMAL){
			//			offset = pDecl[idx].Offset;
			//		}
			//	}
			//	for (int vertNo = 0; vertNo < pMeshContainer->MeshData.pMesh->GetNumVertices(); vertNo++){
			//		D3DXVECTOR3* pBinomal = (D3DXVECTOR3*)&p[offset];
			//		pBinomal->x = 
			//		p += stride;
			//	}
			//	
			//	
			//	//buffer
			//	//m_pVertexBuffer->
			//	//memcpy(pVertices, buffer, sizeof(buffer));
			//	//pVertices
			//	buffer->Unlock();

			//	(*graphicsDevice()).CreateVertexBuffer(sizeof(buffer), 0, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &m_pVertexBuffer, nullptr);
			//	m_IsFirst = false;
			//}
			SINSTANCE(CShadowRender)->Entry(&m_Choco[m_numCreate]);
			createCount++;
			m_numCreate++;
		}
	}
	for (int i = 0; i < m_numCreate; i++)
	{
		m_Choco[i].Update();
	}
}
Exemplo n.º 24
0
void AbstractContent::toXml(QDomElement & pe) const
{
    // Save general item properties
    pe.setTagName("abstract");
    QDomDocument doc = pe.ownerDocument();
    QDomElement domElement;
    QDomText text;
    QString valueStr;

    // Save item position and size
    QDomElement rectParent = doc.createElement("rect");
    QDomElement xElement = doc.createElement("x");
    rectParent.appendChild(xElement);
    QDomElement yElement = doc.createElement("y");
    rectParent.appendChild(yElement);
    QDomElement wElement = doc.createElement("w");
    rectParent.appendChild(wElement);
    QDomElement hElement = doc.createElement("h");
    rectParent.appendChild(hElement);

    QRectF rect = m_contentsRect;
    xElement.appendChild(doc.createTextNode(QString::number(rect.left())));
    yElement.appendChild(doc.createTextNode(QString::number(rect.top())));
    wElement.appendChild(doc.createTextNode(QString::number(rect.width())));
    hElement.appendChild(doc.createTextNode(QString::number(rect.height())));
    pe.appendChild(rectParent);

    // Save the position
    domElement= doc.createElement("pos");
    xElement = doc.createElement("x");
    yElement = doc.createElement("y");
    valueStr.setNum(pos().x());
    xElement.appendChild(doc.createTextNode(valueStr));
    valueStr.setNum(pos().y());
    yElement.appendChild(doc.createTextNode(valueStr));
    domElement.appendChild(xElement);
    domElement.appendChild(yElement);
    pe.appendChild(domElement);

    // Save the stacking position
    domElement= doc.createElement("zvalue");
    pe.appendChild(domElement);
    valueStr.setNum(zValue());
    text = doc.createTextNode(valueStr);
    domElement.appendChild(text);

    // Save the visible state
    domElement= doc.createElement("visible");
    pe.appendChild(domElement);
    valueStr.setNum(isVisible());
    text = doc.createTextNode(valueStr);
    domElement.appendChild(text);

    // Save the frame class
    valueStr.setNum(frameClass());
    domElement= doc.createElement("frame-class");
    pe.appendChild(domElement);
    text = doc.createTextNode(valueStr);
    domElement.appendChild(text);

    domElement= doc.createElement("frame-text-enabled");
    pe.appendChild(domElement);
    valueStr.setNum(frameTextEnabled());
    text = doc.createTextNode(valueStr);
    domElement.appendChild(text);

    if(frameTextEnabled()) {
        domElement= doc.createElement("frame-text");
        pe.appendChild(domElement);
        text = doc.createTextNode(frameText());
        domElement.appendChild(text);
    }

    // save transformation
    const QTransform t = transform();
    if (!t.isIdentity()) {
        domElement = doc.createElement("transformation");
        domElement.setAttribute("xRot", m_xRotationAngle);
        domElement.setAttribute("yRot", m_yRotationAngle);
        domElement.setAttribute("zRot", m_zRotationAngle);
        pe.appendChild(domElement);
    }
    domElement = doc.createElement("mirror");
    domElement.setAttribute("state", mirrorEnabled());
    pe.appendChild(domElement);

}
Exemplo n.º 25
0
int getBootOptions(bool firstRun)
{
	int     i;
	int     key;
	int     nextRow;
	int     timeout;
	int     bvCount;
	BVRef   bvr;
	BVRef   menuBVR;
	bool    showPrompt, newShowPrompt, isCDROM;

	// Initialize default menu selection entry.
	gBootVolume = menuBVR = selectBootVolume(bvChain);

	if (biosDevIsCDROM(gBIOSDev)) {
		isCDROM = true;
	} else {
		isCDROM = false;
	}

	// ensure we're in graphics mode if gui is setup
	if (gui.initialised && bootArgs->Video.v_display == VGA_TEXT_MODE)
	{
		setVideoMode(GRAPHICS_MODE, 0);
	}

	// Clear command line boot arguments
	clearBootArgs();

	// Allow user to override default timeout.
	if (multiboot_timeout_set) {
		timeout = multiboot_timeout;
	} else if (!getIntForKey(kTimeoutKey, &timeout, &bootInfo->bootConfig)) {
		/*  If there is no timeout key in the file use the default timeout
		    which is different for CDs vs. hard disks.  However, if not booting
		    a CD and no config file could be loaded set the timeout
		    to zero which causes the menu to display immediately.
		    This way, if no partitions can be found, that is the disk is unpartitioned
		    or simply cannot be read) then an empty menu is displayed.
		    If some partitions are found, for example a Windows partition, then
		    these will be displayed in the menu as foreign partitions.
		 */
		if (isCDROM) {
			timeout = kCDBootTimeout;
		} else {
			timeout = sysConfigValid ? kBootTimeout : 0;
		}
	}

	if (timeout < 0) {
		gBootMode |= kBootModeQuiet;
	}

	// If the user is holding down a modifier key, enter safe mode.
	if ((readKeyboardShiftFlags() & 0x0F) != 0) {
		gBootMode |= kBootModeSafe;
	}

	// Checking user pressed keys
	bool f8press = false, spress = false, vpress = false;
	while (readKeyboardStatus()) {
		key = bgetc ();
		if (key == 0x4200) f8press = true;
		if ((key & 0xff) == 's' || (key & 0xff) == 'S') spress = true;
		if ((key & 0xff) == 'v' || (key & 0xff) == 'V') vpress = true;
	}
	// If user typed F8, abort quiet mode, and display the menu.
	if (f8press) {
		gBootMode &= ~kBootModeQuiet;
		timeout = 0;
	}
	// If user typed 'v' or 'V', boot in verbose mode.
	if ((gBootMode & kBootModeQuiet) && firstRun && vpress) {
		addBootArg(kVerboseModeFlag);
	}
	// If user typed 's' or 'S', boot in single user mode.
	if ((gBootMode & kBootModeQuiet) && firstRun && spress) {
		addBootArg(kSingleUserModeFlag);
	}

	if (bootArgs->Video.v_display == VGA_TEXT_MODE) {
		setCursorPosition(0, 0, 0);
		clearScreenRows(0, kScreenLastRow);
		if (!(gBootMode & kBootModeQuiet)) {
			// Display banner and show hardware info.
			printf(bootBanner, (bootInfo->convmem + bootInfo->extmem) / 1024);
			printf(getVBEInfoString());
		}
		changeCursor(0, kMenuTopRow, kCursorTypeUnderline, 0);
		verbose("Scanning device %x...", gBIOSDev);
	}

	// When booting from CD, default to hard drive boot when possible. 
	if (isCDROM && firstRun) {
		const char *val;
		char *prompt = NULL;
		char *name = NULL;
		int cnt;
		int optionKey;

		if (getValueForKey(kCDROMPromptKey, &val, &cnt, &bootInfo->bootConfig)) {
			prompt = malloc(cnt + 1);
			strncat(prompt, val, cnt);
		} else {
			name = malloc(80);
			getBootVolumeDescription(gBootVolume, name, 79, false);
			prompt = malloc(256);
			sprintf(prompt, "Press any key to start up from %s, or press F8 to enter startup options.", name);
			free(name);
		}

		if (getIntForKey( kCDROMOptionKey, &optionKey, &bootInfo->bootConfig )) {
			// The key specified is a special key.
		} else {
			// Default to F8.
			optionKey = 0x4200;
		}

		// If the timeout is zero then it must have been set above due to the
		// early catch of F8 which means the user wants to set boot options
		// which we ought to interpret as meaning he wants to boot the CD.
		if (timeout != 0) {
			key = countdown(prompt, kMenuTopRow, timeout);
		} else {
			key = optionKey;
		}

		if (prompt != NULL) {
			free(prompt);
		}

		clearScreenRows( kMenuTopRow, kMenuTopRow + 2 );

		// Hit the option key ?
		if (key == optionKey) {
			gBootMode &= ~kBootModeQuiet;
			timeout = 0;
		} else {
			key = key & 0xFF;

			// Try booting hard disk if user pressed 'h'
			if (biosDevIsCDROM(gBIOSDev) && key == 'h') {
				BVRef bvr;

				// Look at partitions hosting OS X other than the CD-ROM
				for (bvr = bvChain; bvr; bvr=bvr->next) {
					if ((bvr->flags & kBVFlagSystemVolume) && bvr->biosdev != gBIOSDev) {
						gBootVolume = bvr;
					}
				}
			}
			goto done;
		}
	}

	if (gBootMode & kBootModeQuiet) {
		// No input allowed from user.
		goto done;
	}

	if (firstRun && timeout > 0 && countdown("Press any key to enter startup options.", kMenuTopRow, timeout) == 0) {
		// If the user is holding down a modifier key,
		// enter safe mode.
		if ((readKeyboardShiftFlags() & 0x0F) != 0) {
			gBootMode |= kBootModeSafe;
		}
		goto done;
	}

	if (gDeviceCount) {
		// Allocate memory for an array of menu items.
		menuItems = malloc(sizeof(MenuItem) * gDeviceCount);
		if (menuItems == NULL) {
			goto done;
		}

		// Associate a menu item for each BVRef.
		for (bvr=bvChain, i=gDeviceCount-1, selectIndex=0; bvr; bvr=bvr->next) {
			if (bvr->visible) {
				getBootVolumeDescription(bvr, menuItems[i].name, sizeof(menuItems[i].name) - 1, true);
				menuItems[i].param = (void *) bvr;
				if (bvr == menuBVR) {
					selectIndex = i;
				}
				i--;
			}
		}
	}

	if (bootArgs->Video.v_display == GRAPHICS_MODE) {
		// redraw the background buffer
		gui.logo.draw = true;
		drawBackground();
		gui.devicelist.draw = true;
		gui.redraw = true;
		if (!(gBootMode & kBootModeQuiet)) {
			bool showBootBanner = true;
 
			// Check if "Boot Banner"=N switch is present in config file.
			getBoolForKey(kBootBannerKey, &showBootBanner, &bootInfo->bootConfig); 
			if (showBootBanner) {
				// Display banner and show hardware info.
				gprintf(&gui.screen, bootBanner + 1, (bootInfo->convmem + bootInfo->extmem) / 1024);
			}

			// redraw background
			memcpy(gui.backbuffer->pixels, gui.screen.pixmap->pixels, gui.backbuffer->width * gui.backbuffer->height * 4);
		}
	} else {
		// Clear screen and hide the blinking cursor.
		clearScreenRows(kMenuTopRow, kMenuTopRow + 2);
		changeCursor(0, kMenuTopRow, kCursorTypeHidden, 0);
	}

	nextRow = kMenuTopRow;
	showPrompt = true;

	if (gDeviceCount) {
		if( bootArgs->Video.v_display == VGA_TEXT_MODE ) {
			printf("Use \30\31 keys to select the startup volume.");
		}
		showMenu( menuItems, gDeviceCount, selectIndex, kMenuTopRow + 2, kMenuMaxItems );
		nextRow += min( gDeviceCount, kMenuMaxItems ) + 3;
	}

	// Show the boot prompt.
	showPrompt = (gDeviceCount == 0) || (menuBVR->flags & kBVFlagNativeBoot);
	showBootPrompt( nextRow, showPrompt );
	
	do {
		if (bootArgs->Video.v_display == GRAPHICS_MODE) {
			// redraw background
			memcpy( gui.backbuffer->pixels, gui.screen.pixmap->pixels, gui.backbuffer->width * gui.backbuffer->height * 4 );
			// reset cursor co-ords
			gui.debug.cursor = pos( gui.screen.width - 160 , 10 );
		}
		key = getc();
		updateMenu( key, (void **) &menuBVR );
		newShowPrompt = (gDeviceCount == 0) || (menuBVR->flags & kBVFlagNativeBoot);

		if (newShowPrompt != showPrompt) {
			showPrompt = newShowPrompt;
			showBootPrompt( nextRow, showPrompt );
		}

		if (showPrompt) {
			updateBootArgs(key);
		}

		switch (key) {
		case kReturnKey:
			if (gui.menu.draw) { 
				key=0;
				break;
			}
			if (*gBootArgs == '?') {
				char * argPtr = gBootArgs;

				// Skip the leading "?" character.
				argPtr++;
				getNextArg(&argPtr, booterCommand);
				getNextArg(&argPtr, booterParam);

				/*
				* TODO: this needs to be refactored.
				*/
				if (strcmp( booterCommand, "video" ) == 0) {
					if (bootArgs->Video.v_display == GRAPHICS_MODE) {
						showInfoBox(getVBEInfoString(), getVBEModeInfoString());
					} else {
						printVBEModeInfo();
					}
				} else if ( strcmp( booterCommand, "memory" ) == 0) {
					if (bootArgs->Video.v_display == GRAPHICS_MODE ) {
						showInfoBox("Memory Map", getMemoryInfoString());
					} else {
						printMemoryInfo();
					}
				} else if (strcmp(booterCommand, "lspci") == 0) {
					lspci();
				} else if (strcmp(booterCommand, "more") == 0) {
					showTextFile(booterParam);
				} else if (strcmp(booterCommand, "rd") == 0) {
					processRAMDiskCommand(&argPtr, booterParam);
				} else if (strcmp(booterCommand, "norescan") == 0) {
					if (gEnableCDROMRescan) {
						gEnableCDROMRescan = false;
						break;
					}
				} else {
					showHelp();
				}
				key = 0;
				showBootPrompt(nextRow, showPrompt);
				break;
			}
			gBootVolume = menuBVR;
			setRootVolume(menuBVR);
			gBIOSDev = menuBVR->biosdev;
			break;

		case kEscapeKey:
			clearBootArgs();
			break;

		case kF5Key:
			// New behavior:
			// Clear gBootVolume to restart the loop
			// if the user enabled rescanning the optical drive.
			// Otherwise boot the default boot volume.
			if (gEnableCDROMRescan) {
				gBootVolume = NULL;
				clearBootArgs();
			}
			break;

		case kF10Key:
			gScanSingleDrive = false;
			scanDisks(gBIOSDev, &bvCount);
			gBootVolume = NULL;
			clearBootArgs();
			break;

		case kTabKey:
			// New behavior:
			// Switch between text & graphic interfaces
			// Only Permitted if started in graphics interface
			if (useGUI) {
				if (bootArgs->Video.v_display == GRAPHICS_MODE) {
					setVideoMode(VGA_TEXT_MODE, 0);

					setCursorPosition(0, 0, 0);
					clearScreenRows(0, kScreenLastRow);

					// Display banner and show hardware info.
					printf(bootBanner, (bootInfo->convmem + bootInfo->extmem) / 1024);
					printf(getVBEInfoString());

					clearScreenRows(kMenuTopRow, kMenuTopRow + 2);
					changeCursor(0, kMenuTopRow, kCursorTypeHidden, 0);

					nextRow = kMenuTopRow;
					showPrompt = true;

					if (gDeviceCount) {
						printf("Use \30\31 keys to select the startup volume.");
						showMenu(menuItems, gDeviceCount, selectIndex, kMenuTopRow + 2, kMenuMaxItems);
						nextRow += min(gDeviceCount, kMenuMaxItems) + 3;
					}

					showPrompt = (gDeviceCount == 0) || (menuBVR->flags & kBVFlagNativeBoot);
					showBootPrompt(nextRow, showPrompt);
					//changeCursor( 0, kMenuTopRow, kCursorTypeUnderline, 0 );
				} else {
					gui.redraw = true;
					setVideoMode(GRAPHICS_MODE, 0);
					updateVRAM();
				}
			}
			key = 0;
			break;

		default:
			key = 0;
			break;
		}
	} while (0 == key);

done:
	if (bootArgs->Video.v_display == VGA_TEXT_MODE) {
		clearScreenRows(kMenuTopRow, kScreenLastRow);
		changeCursor(0, kMenuTopRow, kCursorTypeUnderline, 0);
	}
	shouldboot = false;
	gui.menu.draw = false;
	if (menuItems) {
		free(menuItems);
		menuItems = NULL;
	}
	return 0;
}
Exemplo n.º 26
0
bool Transport::GenerateWaypoints(uint32 pathid, std::set<uint32> &mapids)
{
    if (pathid >= sTaxiPathNodesByPath.size())
        return false;

    TaxiPathNodeList const& path = sTaxiPathNodesByPath[pathid];

    std::vector<keyFrame> keyFrames;
    int mapChange = 0;
    mapids.clear();
    for (size_t i = 1; i < path.size() - 1; ++i)
    {
        if (mapChange == 0)
        {
            TaxiPathNodeEntry const& node_i = path[i];
            if (node_i.mapid == path[i+1].mapid)
            {
                keyFrame k(node_i);
                keyFrames.push_back(k);
                mapids.insert(k.node->mapid);
            }
            else
            {
                mapChange = 1;
            }
        }
        else
        {
            --mapChange;
        }
    }

    int lastStop = -1;
    int firstStop = -1;

    // first cell is arrived at by teleportation :S
    keyFrames[0].distFromPrev = 0;
    if (keyFrames[0].node->actionFlag == 2)
    {
        lastStop = 0;
    }

    // find the rest of the distances between key points
    for (size_t i = 1; i < keyFrames.size(); ++i)
    {
        if ((keyFrames[i].node->actionFlag == 1) || (keyFrames[i].node->mapid != keyFrames[i-1].node->mapid))
        {
            keyFrames[i].distFromPrev = 0;
        }
        else
        {
            keyFrames[i].distFromPrev =
                sqrt(pow(keyFrames[i].node->x - keyFrames[i - 1].node->x, 2) +
                     pow(keyFrames[i].node->y - keyFrames[i - 1].node->y, 2) +
                     pow(keyFrames[i].node->z - keyFrames[i - 1].node->z, 2));
        }
        if (keyFrames[i].node->actionFlag == 2)
        {
            // remember first stop frame
            if (firstStop == -1)
                firstStop = i;
            lastStop = i;
        }
    }

    float tmpDist = 0;
    for (size_t i = 0; i < keyFrames.size(); ++i)
    {
        int j = (i + lastStop) % keyFrames.size();
        if (keyFrames[j].node->actionFlag == 2)
            tmpDist = 0;
        else
            tmpDist += keyFrames[j].distFromPrev;
        keyFrames[j].distSinceStop = tmpDist;
    }

    for (int i = int(keyFrames.size()) - 1; i >= 0; --i)
    {
        int j = (i + (firstStop + 1)) % keyFrames.size();
        tmpDist += keyFrames[(j + 1) % keyFrames.size()].distFromPrev;
        keyFrames[j].distUntilStop = tmpDist;
        if (keyFrames[j].node->actionFlag == 2)
            tmpDist = 0;
    }

    for (size_t i = 0; i < keyFrames.size(); ++i)
    {
        if (keyFrames[i].distSinceStop < (30 * 30 * 0.5f))
            keyFrames[i].tFrom = sqrt(2 * keyFrames[i].distSinceStop);
        else
            keyFrames[i].tFrom = ((keyFrames[i].distSinceStop - (30 * 30 * 0.5f)) / 30) + 30;

        if (keyFrames[i].distUntilStop < (30 * 30 * 0.5f))
            keyFrames[i].tTo = sqrt(2 * keyFrames[i].distUntilStop);
        else
            keyFrames[i].tTo = ((keyFrames[i].distUntilStop - (30 * 30 * 0.5f)) / 30) + 30;

        keyFrames[i].tFrom *= 1000;
        keyFrames[i].tTo *= 1000;
    }

    //    for (int i = 0; i < keyFrames.size(); ++i) {
    //        sLog.outString("%f, %f, %f, %f, %f, %f, %f", keyFrames[i].x, keyFrames[i].y, keyFrames[i].distUntilStop, keyFrames[i].distSinceStop, keyFrames[i].distFromPrev, keyFrames[i].tFrom, keyFrames[i].tTo);
    //    }

    // Now we're completely set up; we can move along the length of each waypoint at 100 ms intervals
    // speed = max(30, t) (remember x = 0.5s^2, and when accelerating, a = 1 unit/s^2
    int t = 0;
    bool teleport = false;
    if (keyFrames[keyFrames.size() - 1].node->mapid != keyFrames[0].node->mapid)
        teleport = true;

    WayPoint pos(keyFrames[0].node->mapid, keyFrames[0].node->x, keyFrames[0].node->y, keyFrames[0].node->z, teleport,
                 keyFrames[0].node->arrivalEventID, keyFrames[0].node->departureEventID);
    m_WayPoints[0] = pos;
    t += keyFrames[0].node->delay * 1000;

    uint32 cM = keyFrames[0].node->mapid;
    for (size_t i = 0; i < keyFrames.size() - 1; ++i)
    {
        float d = 0;
        float tFrom = keyFrames[i].tFrom;
        float tTo = keyFrames[i].tTo;

        // keep the generation of all these points; we use only a few now, but may need the others later
        if (((d < keyFrames[i + 1].distFromPrev) && (tTo > 0)))
        {
            while ((d < keyFrames[i + 1].distFromPrev) && (tTo > 0))
            {
                tFrom += 100;
                tTo -= 100;

                if (d > 0)
                {
                    float newX, newY, newZ;
                    newX = keyFrames[i].node->x + (keyFrames[i + 1].node->x - keyFrames[i].node->x) * d / keyFrames[i + 1].distFromPrev;
                    newY = keyFrames[i].node->y + (keyFrames[i + 1].node->y - keyFrames[i].node->y) * d / keyFrames[i + 1].distFromPrev;
                    newZ = keyFrames[i].node->z + (keyFrames[i + 1].node->z - keyFrames[i].node->z) * d / keyFrames[i + 1].distFromPrev;

                    bool teleport = false;
                    if (keyFrames[i].node->mapid != cM)
                    {
                        teleport = true;
                        cM = keyFrames[i].node->mapid;
                    }

                    //                    sLog.outString("T: %d, D: %f, x: %f, y: %f, z: %f", t, d, newX, newY, newZ);
                    WayPoint pos(keyFrames[i].node->mapid, newX, newY, newZ, teleport);
                    if (teleport)
                        m_WayPoints[t] = pos;
                }

                if (tFrom < tTo)                            // caught in tFrom dock's "gravitational pull"
                {
                    if (tFrom <= 30000)
                    {
                        d = 0.5f * (tFrom / 1000) * (tFrom / 1000);
                    }
                    else
                    {
                        d = 0.5f * 30 * 30 + 30 * ((tFrom - 30000) / 1000);
                    }
                    d = d - keyFrames[i].distSinceStop;
                }
                else
                {
                    if (tTo <= 30000)
                    {
                        d = 0.5f * (tTo / 1000) * (tTo / 1000);
                    }
                    else
                    {
                        d = 0.5f * 30 * 30 + 30 * ((tTo - 30000) / 1000);
                    }
                    d = keyFrames[i].distUntilStop - d;
                }
                t += 100;
            }
            t -= 100;
        }

        if (keyFrames[i + 1].tFrom > keyFrames[i + 1].tTo)
            t += 100 - ((long)keyFrames[i + 1].tTo % 100);
        else
            t += (long)keyFrames[i + 1].tTo % 100;

        bool teleport = false;
        if ((keyFrames[i + 1].node->actionFlag == 1) || (keyFrames[i + 1].node->mapid != keyFrames[i].node->mapid))
        {
            teleport = true;
            cM = keyFrames[i + 1].node->mapid;
        }

        WayPoint pos(keyFrames[i + 1].node->mapid, keyFrames[i + 1].node->x, keyFrames[i + 1].node->y, keyFrames[i + 1].node->z, teleport,
                     keyFrames[i + 1].node->arrivalEventID, keyFrames[i + 1].node->departureEventID);

        //        sLog.outString("T: %d, x: %f, y: %f, z: %f, t:%d", t, pos.x, pos.y, pos.z, teleport);

        // if (teleport)
        m_WayPoints[t] = pos;

        t += keyFrames[i + 1].node->delay * 1000;
        //        sLog.outString("------");
    }

    uint32 timer = t;

    //    sLog.outDetail("    Generated %lu waypoints, total time %u.", (unsigned long)m_WayPoints.size(), timer);

    m_next = m_WayPoints.begin();                           // will used in MoveToNextWayPoint for init m_curr
    MoveToNextWayPoint();                                   // m_curr -> first point
    MoveToNextWayPoint();                                   // skip first point

    m_pathTime = timer;

    m_nextNodeTime = m_curr->first;

    return true;
}
Exemplo n.º 27
0
void BitcoinGUI::saveWindowGeometry()
{
    QSettings settings;
    settings.setValue("nWindowPos", pos());
    settings.setValue("nWindowSize", size());
}
void SimpleShadowMapEngine::setupLightChunk(Light         *pLight,
                                            LightTypeE     eType,
                                            RenderAction  *pAction,
                                            EngineDataPtr  pEngineData)
{
    if(eType == Directional)
    {
        DirectionalLight *pDLight = 
            dynamic_cast<DirectionalLight *>(pLight);

        LightChunkUnrecPtr  pChunk  = pEngineData->getLightChunk();

        if(pChunk == NULL)
        {
            pChunk = LightChunk::createLocal();
            
            pEngineData->setLightChunk(pChunk);
        }
        
        Color4f tmpVal(0.0, 0.0, 0.0, 1.0);
        
        pChunk->setSpecular(tmpVal);
        
        tmpVal.setValuesRGBA(0.2f, 0.2f, 0.2f, 1.0f);
        
        pChunk->setDiffuse (tmpVal);
        
        tmpVal.setValuesRGBA(0.0, 0.0, 0.0, 1.0);
        
        pChunk->setAmbient (tmpVal);
        
        Vec4f dir(pDLight->getDirection());
        
        dir[3] = 0;
        
        pChunk->setPosition(dir);
        
        pChunk->setBeacon(pLight->getBeacon());
    }
    else if(eType == Point)
    {
        PointLight         *pPLight = dynamic_cast<PointLight *>(pLight);

        LightChunkUnrecPtr  pChunk  = pEngineData->getLightChunk();
        
        if(pChunk == NULL)
        {
            pChunk = LightChunk::createLocal();
            
            pEngineData->setLightChunk(pChunk);
        }
        
        Color4f tmpVal(0.0, 0.0, 0.0, 1.0);
        
        pChunk->setSpecular(tmpVal);
        
        tmpVal.setValuesRGBA(this->getShadowColor()[0], 
                             this->getShadowColor()[1],
                             this->getShadowColor()[2],
                             this->getShadowColor()[3]);
        
        pChunk->setDiffuse (tmpVal);
        
        tmpVal.setValuesRGBA(0.0, 0.0, 0.0, 1.0);
        
        pChunk->setAmbient (tmpVal);
        
        Vec4f pos(pPLight->getPosition());
        
        pos[3] = 1;
        
        pChunk->setPosition(pos);
        
        pChunk->setBeacon(pLight->getBeacon());
    }
}
Exemplo n.º 29
0
void ParallaxLCD::at ( int row, int col, int v )				{ pos(row,col); print(v); }
Exemplo n.º 30
0
void GLCanvas::drawUserInterface(wxDC &dc) const
{
    wxSize size = GetSize();
    wxPoint pos(0, 0);
    pos.x = size.x - _buttonSize;

    wxSize buttonSize(_buttonSize, _buttonSize);

    wxPen whitePen(wxColour(255, 255, 255));
    whitePen.SetWidth(1);
    wxPen blackPen(wxColour(0, 0, 0));
    blackPen.SetWidth(1);
    wxPen greenPen(wxColour(0, 255, 0));
    wxBrush brush;

	dc.SetPen(blackPen);

    brush.SetColour(wxColour(0, 0, 0));
	dc.SetBrush(brush);

	// draw black background behind all buttons
	dc.DrawRectangle(pos.x - 1, pos.y, _buttonSize + 1, _numButtons * _buttonSize + 1);

	// draw grit
	if (_style & DRAW_GRID)
    {
        dc.SetPen(greenPen);
    }
    else
    {
        dc.SetPen(whitePen);
    }

	dc.DrawRectangle(pos.x + 1, pos.y + 1, _buttonSize - 2, _buttonSize - 2);

	dc.DrawLine(pos.x + _buttonSizeHalf, pos.y + 1, pos.x + _buttonSizeHalf, pos.y + _buttonSize - 1);
	dc.DrawLine(pos.x + 1, pos.y + _buttonSizeHalf, size.x - 1, pos.y + _buttonSizeHalf);

	pos.y += _buttonSize;

	// draw a cube for showing AABB
	if (_style & DRAW_AABB)
    {
        dc.SetPen(greenPen);
    }
    else
    {
        dc.SetPen(whitePen);
    }

	dc.DrawRectangle(pos.x + _buttonSizeHalf - 3, pos.y + 3, _buttonSizeHalf, _buttonSizeHalf);
	dc.DrawRectangle(pos.x + 2, pos.y + _buttonSizeHalf - 2, _buttonSizeHalf, _buttonSizeHalf);

	dc.DrawLine(pos.x + 2, pos.y + _buttonSizeHalf - 2, pos.x + _buttonSizeHalf - 3, pos.y + 3);
	dc.DrawLine(pos.x + 2 + _buttonSizeHalf, pos.y + _buttonSizeHalf - 2, pos.x + _buttonSize - 3, pos.y + 3);
	dc.DrawLine(pos.x + 2 + _buttonSizeHalf, pos.y + _buttonSize - 3, pos.x + _buttonSize - 3, pos.y + _buttonSizeHalf + 2);

	pos.y += _buttonSize;

	// draw coordinate system
	if (_style & DRAW_LOCAL_COORDINATE_SYSTEM)
    {
        dc.SetPen(greenPen);
    }
    else
    {
        dc.SetPen(whitePen);
    }

	dc.DrawLine(pos.x + 2, pos.y + 3, pos.x + 2, pos.y + _buttonSize - 2);
	dc.DrawLine(pos.x + 2, pos.y + _buttonSize - 2, size.x - 3, pos.y + _buttonSize - 2);

	dc.DrawLine(pos.x + 2, pos.y + _buttonSize - 2, pos.x + _buttonSize - 6, pos.y + _buttonSizeHalf + 2);

	pos.y += _buttonSize;

	// draw joint constraints
	if (_style & DRAW_JOINT_CONSTRAINTS)
    {
        dc.SetPen(greenPen);
    }
    else
    {
        dc.SetPen(whitePen);
    }
	//dc.DrawCircle(pos.x + _buttonSizeHalf, pos.y + _buttonSizeHalf, _buttonSizeHalf - 3);
    //dc.DrawArc(pos.x + 4, pos.y + 5, pos.x + 4, pos.y + _buttonSize - 5, pos.x + _buttonSizeHalf + 2, pos.y + _buttonSizeHalf);
	//dc.DrawCircle(pos.x + 6, pos.y + _buttonSizeHalf, 3);
	dc.DrawEllipse(pos.x + 4, pos.y + 3, _buttonSizeHalf - 5, _buttonSizeHalf + 4);
	dc.DrawLine(pos.x + 8, pos.y + 3, pos.x + _buttonSizeHalf + 5, pos.y + _buttonSizeHalf);
	dc.DrawLine(pos.x + 8, pos.y + _buttonSizeHalf + 7, pos.x + _buttonSizeHalf + 5, pos.y + _buttonSizeHalf);

	pos.y += _buttonSize;

	// draw rotation axis
	if (_style & DRAW_ROTATION_AXIS)
    {
        dc.SetPen(greenPen);
    }
    else
    {
        dc.SetPen(whitePen);
    }

    dc.DrawArc(pos.x + _buttonSizeHalf + 2, pos.y + _buttonSize - 2, pos.x + _buttonSizeHalf, pos.y + _buttonSizeHalf + 1, pos.x + 2, pos.y + _buttonSize - 2);
    //dc.DrawEllipse(pos.x + 6, pos.y + 5, _buttonSize - 12, _buttonSize - 10);
    //dc.DrawCircle(pos.x + _buttonSizeHalf + 2, pos.y + _buttonSizeHalf - 2, 3);
	dc.DrawLine(pos.x + 2, pos.y + _buttonSize - 2, pos.x + _buttonSize - 2, pos.y + 2);
	dc.DrawLine(pos.x + 2, pos.y + _buttonSize - 2, pos.x + _buttonSize - 2, pos.y + _buttonSize - 2);

	pos.y += _buttonSize;

	// draw label
	if (_style & DRAW_LABEL)
    {
        dc.SetPen(greenPen);
    }
    else
    {
        dc.SetPen(whitePen);
    }

	dc.DrawRoundedRectangle(pos.x + 4, pos.y + 3, _buttonSize - 5, _buttonSizeHalf, 3.0);
	dc.DrawSpline(pos.x + 4, pos.y + _buttonSizeHalf - 3, pos.x + 1, pos.y + _buttonSizeHalf + 4, pos.x + _buttonSizeHalf + 4, pos.y + _buttonSizeHalf + 6);

	pos.y += _buttonSize;

	// draw locate skeleton button
    dc.SetPen(whitePen);

	dc.DrawLine(pos.x + _buttonSizeHalf, pos.y + 2, pos.x + _buttonSizeHalf, pos.y + _buttonSize - 1);
	dc.DrawLine(pos.x + 2, pos.y + _buttonSizeHalf, size.x - 1, pos.y + _buttonSizeHalf);

	dc.DrawCircle(pos.x + _buttonSizeHalf, pos.y + _buttonSizeHalf, _buttonSizeHalf - 4);
	brush.SetColour(wxColour(255, 255, 255));
	dc.SetBrush(brush);
	dc.DrawCircle(pos.x + _buttonSizeHalf, pos.y + _buttonSizeHalf, _buttonSizeHalf - 8);


	pos.y += _buttonSize;

	// draw settings button
	dc.DrawCircle(pos.x + _buttonSizeHalf, pos.y + _buttonSizeHalf, _buttonSizeHalf - 3);

	dc.SetPen(blackPen);

	brush.SetColour(wxColour(0, 0, 0));
	dc.SetBrush(brush);

	dc.DrawCircle(pos.x + _buttonSizeHalf + 6, pos.y + _buttonSizeHalf, 2);
	dc.DrawCircle(pos.x + _buttonSizeHalf - 6, pos.y + _buttonSizeHalf, 2);

	dc.DrawCircle(pos.x + _buttonSizeHalf, pos.y + _buttonSizeHalf + 6, 2);
	dc.DrawCircle(pos.x + _buttonSizeHalf, pos.y + _buttonSizeHalf - 6, 2);

	dc.SetPen(whitePen);

	dc.DrawCircle(pos.x + _buttonSizeHalf, pos.y + _buttonSizeHalf, _buttonSizeHalf - 7);
}