Beispiel #1
0
// image calculation
// load frame from video
void VideoFFmpeg::calcImage (unsigned int texId, double ts)
{
	if (m_status == SourcePlaying)
	{
		// get actual time
		double startTime = PIL_check_seconds_timer();
		double actTime;
		// timestamp passed from audio actuators can sometimes be slightly negative
		if (m_isFile && ts >= -0.5)
		{
			// allow setting timestamp only when not streaming
			actTime = ts;
			if (actTime * actFrameRate() < m_lastFrame) 
			{
				// user is asking to rewind, force a cache clear to make sure we will do a seek
				// note that this does not decrement m_repeat if ts didn't reach m_range[1]
				stopCache();
			}
		}
		else
		{
			if (m_lastFrame == -1 && !m_isFile)
				m_startTime = startTime;
			actTime = startTime - m_startTime;
		}
		// if video has ended
		if (m_isFile && actTime * m_frameRate >= m_range[1])
		{
			// in any case, this resets the cache
			stopCache();
			// if repeats are set, decrease them
			if (m_repeat > 0) 
				--m_repeat;
			// if video has to be replayed
			if (m_repeat != 0)
			{
				// reset its position
				actTime -= (m_range[1] - m_range[0]) / m_frameRate;
				m_startTime += (m_range[1] - m_range[0]) / m_frameRate;
			}
			// if video has to be stopped, stop it
			else 
			{
				m_status = SourceStopped;
				return;
			}
		}
		// actual frame
		long actFrame = (m_isImage) ? m_lastFrame+1 : long(actTime * actFrameRate());
		// if actual frame differs from last frame
		if (actFrame != m_lastFrame)
		{
			AVFrame* frame;
			// get image
			if ((frame = grabFrame(actFrame)) != NULL)
			{
				if (!m_isFile && !m_cacheStarted) 
				{
					// streaming without cache: detect synchronization problem
					double execTime = PIL_check_seconds_timer() - startTime;
					if (execTime > 0.005) 
					{
						// exec time is too long, it means that the function was blocking
						// resynchronize the stream from this time
						m_startTime += execTime;
					}
				}
				// save actual frame
				m_lastFrame = actFrame;
				// init image, if needed
				init(short(m_codecCtx->width), short(m_codecCtx->height));
				// process image
				process((BYTE*)(frame->data[0]));
				// finished with the frame, release it so that cache can reuse it
				releaseFrame(frame);
				// in case it is an image, automatically stop reading it
				if (m_isImage)
				{
					m_status = SourceStopped;
					// close the file as we don't need it anymore
					release();
				}
			} else if (m_isStreaming)
			{
				// we didn't get a frame and we are streaming, this may be due to
				// a delay in the network or because we are getting the frame too fast.
				// In the later case, shift time by a small amount to compensate for a drift
				m_startTime += 0.001;
			}
		}
	}
}
Beispiel #2
0
void CMyDatabase::GetStationCustomPL(_TagStation &Station, CDatabase &m_Database, int dbms)
{

	CRecordset       m_RS( &m_Database );
	short nFields     = 0;
	CString mSQL;
	CString Message;

	try
	{

		mSQL.Format( "SELECT * FROM DOCUGATE_GENERAL_CTLUNIT_CUSTOM_PL WHERE CTLUNIT_GUID = '%s'",Station.UnitGUID );
		Message.Format("CMyDatabase::GetStationCustomPL(%s)",mSQL);
		WriteLog(Message,"");
	
		m_RS.Open( CRecordset::forwardOnly, mSQL);
		if( !m_RS.IsEOF() )
		{
	
			
			   CString		  varData;
			   CODBCFieldInfo varInfo;
			   nFields = m_RS.GetODBCFieldCount( );
			   for( short index = 0; index < nFields; index++ )
			   {
						m_RS.GetFieldValue    ( short(index), varData );
						m_RS.GetODBCFieldInfo ( short(index), varInfo );
					
						if( varInfo.m_strName.CompareNoCase("ENABLED") == 0 )
					         Station.plCustomCostEnabled = atoi(varData);
						else if( varInfo.m_strName.CompareNoCase("PL1") == 0 )
					         Station.pl1CustomCost=(float)atof(varData);
						else if( varInfo.m_strName.CompareNoCase("PL2") == 0 )
					         Station.pl2CustomCost=(float)atof(varData);
						else if( varInfo.m_strName.CompareNoCase("PL3") == 0 )
					         Station.pl3CustomCost=(float)atof(varData);
						else if( varInfo.m_strName.CompareNoCase("PL4") == 0 )
					         Station.pl4CustomCost=(float)atof(varData);
			   }

			  Message.Format("CMyDatabase::GetStationCustomPL(%s) was located ,Enabled = %d",Station.UnitGUID,Station.plCustomCostEnabled);
			  WriteLog(Message,"");


		} else {

				Message.Format("CMyDatabase::GetStationCustomPL(%s) not located",Station.UnitGUID);
				WriteLog(Message,"");

		}
 
	
		if ( m_RS.IsOpen() )
			 m_RS.Close();
	}
	catch( CDBException *e)
	{

		CString Message;
		Message.Format("CMyDatabase::GetStationCustomPL(%s)",e->m_strError);
		WriteLog(Message,"");
		e->Delete();
	}

}
Beispiel #3
0
LRESULT CALLBACK Win32Assistant::WindowProc (HWND hWnd, UINT message,
  WPARAM wParam, LPARAM lParam)
{
  Win32Assistant* assistant;
  if (IsWindowUnicode (hWnd))
    assistant = (Win32Assistant*)GetWindowLongPtrW (hWnd, 0);
  else
    assistant = (Win32Assistant*)GetWindowLongPtrA (hWnd, 0);
  switch (message)
  {
    case WM_ACTIVATEAPP:
      if ((assistant != 0))
      {
        if (wParam) 
	{ 
	  assistant->ApplicationActive = true; 
	} 
	else 
	{ 
	  assistant->ApplicationActive = false; 
	}
      }
      break;
    case WM_ACTIVATE:
      if ((assistant != 0))
      {
	iEventOutlet* outlet = assistant->GetEventOutlet();
        if (LOWORD(wParam) != WA_INACTIVE)
          outlet->Broadcast (assistant->FocusGained, 1);
        else
          outlet->Broadcast (assistant->FocusLost, 0);
      }
      break;
    case WM_CREATE:
      {
	CreateInfo* ci;
	if (IsWindowUnicode (hWnd))
	{
	  ci = (CreateInfo*)((LPCREATESTRUCTW)lParam)->lpCreateParams;
	  SetWindowLongPtrW (hWnd, 0, (LONG_PTR)ci->assistant);
	  SetWindowLongPtrW (hWnd, sizeof (LONG_PTR), (LONG_PTR)ci->canvas);
	}
	else
	{
	  ci = (CreateInfo*)((LPCREATESTRUCTA)lParam)->lpCreateParams;
	  SetWindowLongPtrA (hWnd, 0, (LONG_PTR)ci->assistant);
	  SetWindowLongPtrA (hWnd, sizeof (LONG_PTR), (LONG_PTR)ci->canvas);
	}
	// a window is created. Hide the console window, if requested.
	if (ci->assistant->is_console_app && 
	  !ci->assistant->console_window)
	{
	  ci->assistant->DisableConsole ();
	}
      }
      break;
    case WM_SYSCOMMAND:
      if (wParam == SC_CLOSE)
      {
	PostQuitMessage (0);
	return TRUE;
      }
      break;
    case WM_SYSCHAR:
    case WM_CHAR:
    case WM_UNICHAR:
    case WM_DEADCHAR:
    case WM_SYSDEADCHAR:
    case WM_IME_COMPOSITION:
    case WM_KEYDOWN:
    case WM_SYSKEYDOWN:
    case WM_KEYUP:
    case WM_SYSKEYUP:
    {
      if (assistant != 0)
      {	  
	if (assistant->HandleKeyMessage (hWnd, message, wParam, lParam))
	{
	  return 0;
	}
      }
      break;
    }
    case WM_LBUTTONDOWN:
    case WM_RBUTTONDOWN:
    case WM_MBUTTONDOWN:
    {
      if (assistant != 0)
      {
	const int buttonNum = (message == WM_LBUTTONDOWN) ? csmbLeft :
          (message == WM_RBUTTONDOWN) ? csmbRight : csmbMiddle;
        if (assistant->mouseButtons == 0) SetCapture (hWnd);
	assistant->mouseButtons |= 1 << (buttonNum - csmbLeft);

        iEventOutlet* outlet = assistant->GetEventOutlet();
        outlet->Mouse (buttonNum, true,
          short (LOWORD (lParam)), short (HIWORD (lParam)));
      }
      return TRUE;
    }
    case WM_LBUTTONUP:
    case WM_RBUTTONUP:
    case WM_MBUTTONUP:
    {
      if (assistant != 0)
      {
	const int buttonNum = (message == WM_LBUTTONUP) ? csmbLeft :
          (message == WM_RBUTTONUP) ? csmbRight : csmbMiddle;
	assistant->mouseButtons &= ~(1 << (buttonNum - csmbLeft));
        if (assistant->mouseButtons == 0) ReleaseCapture ();

        iEventOutlet* outlet = assistant->GetEventOutlet();
        outlet->Mouse (buttonNum, false,
          short (LOWORD (lParam)), short (HIWORD (lParam)));
      }
      return TRUE;
    }
    case WM_MOUSEWHEEL:
    {
      if (assistant != 0)
      {
        iEventOutlet* outlet = assistant->GetEventOutlet();
	int wheelDelta = (short)HIWORD (wParam);
	// @@@ Only emit events when WHEEL_DELTA wheel ticks accumulated?
	POINT coords;
	coords.x = short (LOWORD (lParam));
	coords.y = short (HIWORD (lParam));
	ScreenToClient(hWnd, &coords);
	outlet->Mouse (wheelDelta > 0 ? csmbWheelUp : csmbWheelDown, true,
	  coords.x, coords.y);
	//outlet->Mouse (wheelDelta > 0 ? csmbWheelUp : csmbWheelDown, false,
	  //coords.x, coords.y); 
      }
      return 0;
    }
    case WM_XBUTTONUP:
    case WM_XBUTTONDOWN:
    {
      if (assistant != 0)
      {
	bool down = (message == WM_XBUTTONDOWN);
	const int maxXButtons = 16; 
	  // XButton flags are stored in high word of lparam
	const int mbFlagsOffs = csmbMiddle; 
	  // Offset of bit num of mouseButtons

	int XButtons = HIWORD(wParam);

	if (down && (assistant->mouseButtons == 0)) SetCapture (hWnd);

        iEventOutlet* outlet = assistant->GetEventOutlet();
	for (int x = 0; x < maxXButtons; x++)
	{
	  if (XButtons & (1 << x))
	  {
	    int mbFlag = 1 << (x + mbFlagsOffs);
	    if (down && !(assistant->mouseButtons & mbFlag))
	    {
	      assistant->mouseButtons |= mbFlag;
	      outlet->Mouse (csmbExtra1 + x, true,
		short (LOWORD (lParam)), short (HIWORD (lParam)));
	    }
	    else if (!down && (assistant->mouseButtons & mbFlag))
	    {
	      assistant->mouseButtons &= ~mbFlag;
	      outlet->Mouse (csmbExtra1 + x, false,
		short (LOWORD (lParam)), short (HIWORD (lParam)));
	    }
	  }
	}
        if (!down && (assistant->mouseButtons == 0)) ReleaseCapture ();
      }
      return TRUE;
    }
    case WM_MOUSEMOVE:
    {
      if (assistant != 0)
      {
        iEventOutlet* outlet = assistant->GetEventOutlet();
        outlet->Mouse (csmbNone, false, short(LOWORD(lParam)), 
	  short(HIWORD(lParam)));
      }
      return TRUE;
    }
    case WM_SETCURSOR:
    {
      if ((assistant != 0) && (LOWORD (lParam) == HTCLIENT))
      {
        ::SetCursor (assistant->m_hCursor);
        return TRUE;
      }
      break;
    }
    case WM_SIZE:
    {
      if (assistant != 0)
      {
	iGraphics2D* canvas;
	if (IsWindowUnicode (hWnd))
	  canvas = (iGraphics2D*)GetWindowLongPtrW (hWnd, sizeof (LONG_PTR));
	else
	  canvas = (iGraphics2D*)GetWindowLongPtrA (hWnd, sizeof (LONG_PTR));

	if ( (wParam == SIZE_MAXIMIZED) || (wParam == SIZE_RESTORED) )
	{
          iEventOutlet* outlet = assistant->GetEventOutlet();
	  outlet->Broadcast (csevCanvasExposed (assistant->registry, canvas));
	} 
	else if (wParam == SIZE_MINIMIZED) 
	{
          iEventOutlet* outlet = assistant->GetEventOutlet();
	  outlet->Broadcast (csevCanvasHidden (assistant->registry, canvas));
	}
      }
      return TRUE;
    }
    case WM_SHOWWINDOW:
    {
      if (assistant != 0)
      {
	iGraphics2D* canvas;
	if (IsWindowUnicode (hWnd))
	  canvas = (iGraphics2D*)GetWindowLongPtrW (hWnd, sizeof (LONG_PTR));
	else
	  canvas = (iGraphics2D*)GetWindowLongPtrA (hWnd, sizeof (LONG_PTR));

	if (wParam)
	{
          iEventOutlet* outlet = assistant->GetEventOutlet();
	  outlet->Broadcast (csevCanvasExposed (assistant->registry, canvas));
	} 
	else
	{
          iEventOutlet* outlet = assistant->GetEventOutlet();
	  outlet->Broadcast (csevCanvasHidden (assistant->registry, canvas));
	}
      }
      break;
    }
  }
  if (IsWindowUnicode (hWnd))
  {
    return DefWindowProcW (hWnd, message, wParam, lParam);
  }
  else
  {
    return DefWindowProcA (hWnd, message, wParam, lParam);
  }
}
Beispiel #4
0
//--------- Begin of function UnitArray::move_to_now ---------//
//
// Order the unit to move to a specific location following the
// shortest path.
//
// <int> 	destXLoc, destYLoc - the location of the destination.
// <short*> selectedUnitArray  - an array of recno of selected units.
// <int>    selectedCount 		 - no. of selected units.
//
void UnitArray::move_to_now(int destXLoc, int destYLoc, short* selectedUnitArray, int selectedCount)
{
    err_when(destXLoc<0 || destYLoc<0 || destXLoc>=MAX_WORLD_X_LOC || destYLoc>=MAX_WORLD_Y_LOC);
    err_when( selectedCount > 10000 );

    //------------ define vars -----------------------//
    int		unprocessCount;// = selectedCount;		// num. of unprocessed sprite
    int		k;													// for counting
    short		vecX, vecY;										// used to reset x, y
    short		oddCount, evenCount;
    int		j;
    Unit*		unitPtr = unit_array[selectedUnitArray[0]];
    DWORD		curGroupId = unitPtr->unit_group_id;
    int		mobileType = unitPtr->mobile_type;
    Location	*worldLocMatrix=world.loc_matrix, *locPtr;
    //int		sizeOneSelectedCount=0, sizeTwoSelectedCount=0;
    int		sizeOneSelectedCount = selectedCount;

    //---------- set Unit::unit_group_id and count the unit by size ----------//
    int i;
    for( i=0 ; i<selectedCount ; i++ )
    {
        unitPtr = operator[](selectedUnitArray[i]);
        err_when(unitPtr->cur_action==SPRITE_IDLE && (unitPtr->cur_x!=unitPtr->next_x || unitPtr->cur_y!=unitPtr->next_y));
        err_when(unitPtr->action_para); // action_para should be set to zero in move_to()

        if(unitPtr->cur_action==SPRITE_ATTACK)
            unitPtr->stop();

        err_when(unitPtr->cur_action==SPRITE_ATTACK && unitPtr->action_para==0);
        if(unitPtr->cur_action==SPRITE_IDLE)
            unitPtr->set_ready();

        /*switch(unitPtr->sprite_info->loc_width)
        {
        	case 1:	sizeOneSelectedCount++;
        				break;

        	case 2:	sizeTwoSelectedCount++;
        				break;

        	default:	err_here();
        				break;
        }*/
    }
    unprocessCount = sizeOneSelectedCount;

    //---- construct array to store size one selected unit ----//
    short* selectedSizeOneUnitArray;
    if(sizeOneSelectedCount)
    {
        selectedSizeOneUnitArray = (short*)mem_add(sizeof(short)*sizeOneSelectedCount);
        memset(selectedSizeOneUnitArray, 0, sizeof(short)*sizeOneSelectedCount);
        for(i=0, k=0; i<selectedCount && unprocessCount; i++)
        {
            unitPtr = operator[](selectedUnitArray[i]);
            if(unitPtr->sprite_info->loc_width==1)
            {
                selectedSizeOneUnitArray[k++] = selectedUnitArray[i];
                unprocessCount--;
            }
        }
    }
    unprocessCount = sizeOneSelectedCount;

    //----------- variables initialization ---------------//
    int destX, destY;
    if(mobileType==UNIT_LAND)
    {
        x = destX = destXLoc;
        y = destY = destYLoc;
        move_scale = 1;
    }
    else // UNIT_AIR, UNIT_SEA
    {
        x = destX = (destXLoc/2)*2;
        y = destY = (destYLoc/2)*2;
        move_scale = 2;
    }

    //if(sizeOneSelectedCount)
    //{
    //----- initialize parameters and construct data structure -----//
    oddCount =1;
    evenCount = 3;
    square_size = not_tested_loc = lower_right_case = upper_left_case = 0;

    distance = (int*)mem_add(sizeof(int)*sizeOneSelectedCount);		// used in the function construct_sorted_array and this function,
    memset(distance, 0, sizeof(int)*sizeOneSelectedCount);				// and allocate/free the memory in this function

    sorted_distance = (int*)mem_add(sizeof(int)*sizeOneSelectedCount);
    memset(sorted_distance, 0, sizeof(int)*sizeOneSelectedCount);

    sorted_member = (int*)mem_add(sizeof(int)*sizeOneSelectedCount);
    memset(sorted_member, 0, sizeof(int)*sizeOneSelectedCount);

    done_flag = (char*)mem_add(sizeof(char)*sizeOneSelectedCount);
    memset(done_flag, 0, sizeof(char)*sizeOneSelectedCount);

    //--- calculate the rectangle size used to allocate space for the sprites----//
    unprocessCount = sizeOneSelectedCount;
    while(unprocessCount)
    {
        //=============================
        // process odd size square
        //=============================
        vecX = short(oddCount/4)*move_scale;
        vecY = vecX;
        k = 0;

        for(j=0; j<oddCount && unprocessCount; j++)
        {
            x = destX+vecX;
            y = destY+vecY;

            if(x>=0 && y>=0 && x<MAX_WORLD_X_LOC && y<MAX_WORLD_Y_LOC)
            {
                if( worldLocMatrix[y*MAX_WORLD_X_LOC+x].is_unit_group_accessible(mobileType, curGroupId) )
                    unprocessCount--;
            }

            if(k++ < int(oddCount/2))	// reset vecX, vecY
                vecX -= move_scale;
            else
                vecY -= move_scale;
        }
        square_size+=move_scale;
        if(j<oddCount)
            not_tested_loc = oddCount-j;
        oddCount+=4;

        if(unprocessCount)
        {
            //=============================
            // process even size square
            //=============================
            vecY = (-short(evenCount/4)-1)*move_scale;
            vecX = vecY+move_scale;
            k = 0;

            for(j=0; j<evenCount && unprocessCount; j++)
            {
                x = destX+vecX;
                y = destY+vecY;

                if(x>=0 && y>=0 && x<MAX_WORLD_X_LOC && y<MAX_WORLD_Y_LOC)
                {
                    if(worldLocMatrix[y*MAX_WORLD_X_LOC+x].is_unit_group_accessible(mobileType, curGroupId) )
                        unprocessCount--;
                }

                if(k++ < int(evenCount/2))	// reset vecX, vecY
                    vecX += move_scale;
                else
                    vecY += move_scale;
            }
            square_size+=move_scale;
            if(j<evenCount)
                not_tested_loc = evenCount-j;
            evenCount+=4;
        }
    }

    rec_height = rec_width = square_size;	// get the height and width of the rectangle
    if(not_tested_loc >= (square_size/move_scale))
        rec_width -= move_scale;

    //--- decide to use upper_left_case or lower_right_case, however, it maybe changed for boundary improvement----//
    x = cal_rectangle_lower_right_x(destX);
    y = cal_rectangle_lower_right_y(destY);

    for(i=0; i<sizeOneSelectedCount; i++)
    {
        unitPtr = (Unit*) get_ptr(selectedSizeOneUnitArray[i]);

        if(unitPtr->next_y_loc()<y)		// lower_right_case or upper_left_case
            lower_right_case++;
        else if(unitPtr->next_y_loc()>y)
            upper_left_case++;
    }

    if(lower_right_case==upper_left_case) // in case both values are equal, check by upper_left_case
    {
        x = cal_rectangle_upper_left_x(destX);
        y = cal_rectangle_upper_left_y(destY);

        lower_right_case = upper_left_case = 0;
        for(i=0; i<sizeOneSelectedCount; i++)
        {
            unitPtr = (Unit*) get_ptr(selectedSizeOneUnitArray[i]);

            if(unitPtr->next_y_loc()<y)		// lower_right_case or upper_left_case
                lower_right_case++;
            else if(unitPtr->next_y_loc()>y)
                upper_left_case++;
        }
    }

    //------------ determine x, y and lower_right_case/upper_left_case-----------//
    determine_position_to_construct_table(selectedCount, destX, destY, mobileType);
    err_when(x<0 || y<0 || x>=MAX_WORLD_X_LOC || y>=MAX_WORLD_Y_LOC);

    //------------ construct a table to store distance -------//
    construct_sorted_array(selectedSizeOneUnitArray, sizeOneSelectedCount);	// distance and sorted_member should be initialized first
    err_when(x<0 || y<0 || x>=MAX_WORLD_X_LOC || y>=MAX_WORLD_Y_LOC);

    //------------ process the movement -----------//
    unprocessCount = sizeOneSelectedCount;//selectedCount;
    k=0;

    //-******************* auto correct ***********************-//
    int autoCorrectStartX = x;
    int autoCorrectStartY = y;
    //-******************* auto correct ***********************-//

    if(lower_right_case >= upper_left_case)
    {
        while(unprocessCount)
        {
            locPtr = worldLocMatrix+y*MAX_WORLD_X_LOC+x;
            for(i=x; i>x-rec_width && unprocessCount; i-=move_scale, locPtr-=move_scale)
            {
                if(locPtr->is_unit_group_accessible(mobileType, curGroupId))
                {
                    do
                    {
                        unitPtr = (Unit*) get_ptr(selectedSizeOneUnitArray[sorted_member[k++]]);
                    } while(unitPtr->sprite_info->loc_width>1);

                    err_when(k>sizeOneSelectedCount);
                    if(sizeOneSelectedCount>1)
                    {
                        if(unprocessCount==sizeOneSelectedCount) // the first unit to move
                        {
                            unitPtr->move_to(i, y, 1, 4, 0, sizeOneSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_INITIAL);
                            if(unitPtr->mobile_type==UNIT_LAND && unitPtr->nation_recno)
                                unitPtr->select_search_sub_mode(unitPtr->next_x_loc(), unitPtr->next_y_loc(), i, y, unitPtr->nation_recno, SEARCH_MODE_REUSE);
                            unitPtr->move_to(i, y, 1, 4, 0, sizeOneSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_FIRST_SEEK);
                        }
                        else
                        {
                            err_when(unprocessCount==sizeOneSelectedCount);
                            if(unitPtr->mobile_type==UNIT_LAND && unitPtr->nation_recno)
                                unitPtr->select_search_sub_mode(unitPtr->next_x_loc(), unitPtr->next_y_loc(), i, y, unitPtr->nation_recno, SEARCH_MODE_REUSE);
                            unitPtr->move_to(i, y, 1, 4, 0, sizeOneSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_SEARCH);
                        }
                    }
                    else
                        unitPtr->move_to(i, y, 1);
                    unprocessCount--;
                }
            }
            y-=move_scale;
            //-******************* auto correct ***********************-//
#ifdef DEBUG
            err_when(unprocessCount && y<0);
#else
            if(unprocessCount && y<0)
                y = autoCorrectStartY;
#endif
            //-******************* auto correct ***********************-//
        }
    }
    else // upper_left_case
    {
        while(unprocessCount)
        {
            locPtr = worldLocMatrix+y*MAX_WORLD_X_LOC+x;
            for(i=x; i<x+rec_width && unprocessCount; i+=move_scale, locPtr+=move_scale)
            {
                if(locPtr->is_unit_group_accessible(mobileType, curGroupId))
                {
                    do
                    {
                        unitPtr = (Unit*) get_ptr(selectedSizeOneUnitArray[sorted_member[k++]]);
                    } while(unitPtr->sprite_info->loc_width>1);
                    err_when(k>sizeOneSelectedCount);

                    if(sizeOneSelectedCount>1)
                    {
                        if(unprocessCount==sizeOneSelectedCount) // the first unit to move
                        {
                            unitPtr->move_to(i, y, 1, 4, 0, sizeOneSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_INITIAL);
                            if(unitPtr->mobile_type==UNIT_LAND && unitPtr->nation_recno)
                                unitPtr->select_search_sub_mode(unitPtr->next_x_loc(), unitPtr->next_y_loc(), i, y, unitPtr->nation_recno, SEARCH_MODE_REUSE);
                            unitPtr->move_to(i, y, 1, 4, 0, sizeOneSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_FIRST_SEEK);
                        }
                        else
                        {
                            err_when(unprocessCount==sizeOneSelectedCount);
                            if(unitPtr->mobile_type==UNIT_LAND && unitPtr->nation_recno)
                                unitPtr->select_search_sub_mode(unitPtr->next_x_loc(), unitPtr->next_y_loc(), i, y, unitPtr->nation_recno, SEARCH_MODE_REUSE);
                            unitPtr->move_to(i, y, 1, 4, 0, sizeOneSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_SEARCH);
                        }
                    }
                    else
                        unitPtr->move_to(i, y, 1);
                    unprocessCount--;
                }
            }
            y+=move_scale;
            //-******************* auto correct ***********************-//
#ifdef DEBUG
            err_when(unprocessCount && y>=MAX_WORLD_Y_LOC);
#else
            if(unprocessCount && y>=MAX_WORLD_Y_LOC)
                y = autoCorrectStartY;
#endif
            //-******************* auto correct ***********************-//
        }
    }
    //---------------- destruct data structure --------------//
    mem_del(done_flag);
    mem_del(sorted_distance);
    mem_del(sorted_member);
    mem_del(distance);
    mem_del(selectedSizeOneUnitArray);
    //}// end if (sizeOneSelectedCount)
    /*
    //=============================================================================//
    //----- order sprite with size two to move to a specified position ------------//
    //=============================================================================//

    int sizeTwoUnprocessCount = sizeTwoSelectedCount;
    int surX, surY, suaCount=0;
    char w, h, blocked=0;

    if(sizeOneSelectedCount)	// mix, size one units have processed
    {
    	if(rec_width>square_size)
    		square_size = rec_width;
    	if(rec_height>square_size)
    		square_size = rec_height;
    	square_size = ((square_size+1)/2)<<1;	// change to multiply of two
    	rec_width = rec_height = square_size;

    	x = destX-rec_width/2+1;
    	y = destY-rec_height/2;
    }
    else	// all are size 2 units
    {
    	//-***************** testing ********************-//
    	err_here();
    	//-***************** testing ********************-//

    	square_size = rec_width = rec_height = 2;
    	x = destX;
    	y = destY;

    	if(x<0)
    		x = 0;
    	else if(x>=MAX_WORLD_X_LOC-1)
    		x = MAX_WORLD_X_LOC-2;

    	if(y<0)
    		y = 0;
    	else if(y>=MAX_WORLD_Y_LOC-1)
    		y = MAX_WORLD_Y_LOC-2;

    	blocked = 0;
    	for(h=0, surY=y; h<2 && !blocked; h++, surY++)
    	{
    		for(w=0, surX=x; w<2 && !blocked; w++, surX++)
    		{
    			locPtr = worldLocMatrix+surY*MAX_WORLD_X_LOC+surX;
    			blocked = !locPtr->is_unit_group_accessible(mobileType, curGroupId);
    		}
    	}

    	if(!blocked)
    	{
    		do
    		{
    			unitPtr = (Unit*) get_ptr(selectedUnitArray[suaCount++]);
    		}while(unitPtr->sprite_info->loc_width<2);

    		if(sizeTwoSelectedCount>1)
    		{
    			unitPtr->move_to(x, y, 1, 4, 0, sizeTwoSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_INITIAL);
    			unitPtr->move_to(x, y, 1, 4, 0, sizeTwoSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_FIRST_SEEK);
    		}
    		else
    			unitPtr->move_to(x, y, 1);
    		sizeTwoUnprocessCount--;
    	}
    }

    while(sizeTwoUnprocessCount)
    {
    	//-***************** testing ********************-//
    	err_here();
    	//-***************** testing ********************-//

    	int moveToX, moveToY;
    	int boundedX, boundedY;

    	//------------- upper edge --------------//
    	moveToY = y-2;
    	moveToX = x;
    	if(moveToY>=0)
    	{
    		if(x+rec_width+2 > MAX_WORLD_X_LOC-2)
    			boundedX = MAX_WORLD_X_LOC-1;
    		else
    			boundedX = x+rec_width+2;

    		while(moveToX<boundedX && sizeTwoUnprocessCount)
    		{
    			//--------------- is the position blocked? ----------//
    			if(moveToX>=MAX_WORLD_X_LOC-1 || moveToY>=MAX_WORLD_Y_LOC-1)
    				blocked = 1;
    			else
    			{
    				blocked = 0;
    				for(h=0, surY=moveToY; h<2 && !blocked; h++, surY++)
    				{
    					for(w=0, surX=moveToX; w<2 && !blocked; w++, surX++)
    					{
    						locPtr = worldLocMatrix+surY*MAX_WORLD_X_LOC+surX;
    						blocked = !locPtr->is_unit_group_accessible(mobileType, curGroupId);
    					}
    				}
    			}

    			if(!blocked)
    			{
    				do
    				{
    					unitPtr = (Unit*) get_ptr(selectedUnitArray[suaCount++]);
    				}while(unitPtr->sprite_info->loc_width<2);

    				if(sizeTwoSelectedCount>1)
    				{
    					if(sizeTwoUnprocessCount==sizeTwoSelectedCount) // the first unit to move
    					{
    						unitPtr->move_to(moveToX, moveToY, 1, 4, 0, sizeTwoSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_INITIAL);
    						unitPtr->move_to(moveToX, moveToY, 1, 4, 0, sizeTwoSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_FIRST_SEEK);
    					}
    					else
    					{
    						err_if(sizeTwoUnprocessCount==sizeTwoSelectedCount)
    							err_here();

    						unitPtr->move_to(moveToX, moveToY, 1, 4, 0, sizeTwoSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_SEARCH);
    					}
    				}
    				else
    					unitPtr->move_to(moveToX, moveToY, 1);
    				sizeTwoUnprocessCount--;
    			}
    			moveToX+=2;
    		}
    	}

    	//------------- right edge --------------//
    	moveToX = x+rec_width;
    	moveToY = y;
    	if(moveToX<MAX_WORLD_X_LOC-1)
    	{
    		if(y+rec_height+2 > MAX_WORLD_Y_LOC-2)
    			boundedY = MAX_WORLD_Y_LOC-1;
    		else
    			boundedY = y+rec_height+2;

    		while(moveToY<boundedY && sizeTwoUnprocessCount)
    		{
    			//--------------- is the position blocked? ----------//
    			if(moveToX>=MAX_WORLD_X_LOC-1 || moveToY>=MAX_WORLD_Y_LOC-1)
    				blocked = 1;
    			else
    			{
    				blocked = 0;
    				for(h=0, surY=moveToY; h<2 && !blocked; h++, surY++)
    				{
    					for(w=0, surX=moveToX; w<2 && !blocked; w++, surX++)
    					{
    						locPtr = worldLocMatrix+surY*MAX_WORLD_X_LOC+surX;
    						blocked = !locPtr->is_unit_group_accessible(mobileType, curGroupId);
    					}
    				}
    			}

    			if(!blocked)
    			{
    				do
    				{
    					unitPtr = (Unit*) get_ptr(selectedUnitArray[suaCount++]);
    				}while(unitPtr->sprite_info->loc_width<2);

    				if(sizeTwoSelectedCount>1)
    				{
    					if(sizeTwoUnprocessCount==sizeTwoSelectedCount) // the first unit to move
    					{
    						unitPtr->move_to(moveToX, moveToY, 1, 4, 0, sizeTwoSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_INITIAL);
    						unitPtr->move_to(moveToX, moveToY, 1, 4, 0, sizeTwoSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_FIRST_SEEK);
    					}
    					else
    					{
    						err_if(sizeTwoUnprocessCount==sizeTwoSelectedCount)
    							err_here();

    						unitPtr->move_to(moveToX, moveToY, 1, 4, 0, sizeTwoSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_SEARCH);
    					}
    				}
    				else
    					unitPtr->move_to(moveToX, moveToY, 1);
    				sizeTwoUnprocessCount--;
    			}
    			moveToY+=2;
    		}
    	}

    	//------------- lower edge ----------------//
    	moveToX = x+rec_width-2;
    	moveToY = y+rec_height;
    	if(moveToY<MAX_WORLD_Y_LOC-1)
    	{
    		if(x-3 < 0)
    			boundedX = -1;
    		else
    			boundedX = x-3;

    		while(moveToX>boundedX && sizeTwoUnprocessCount)
    		{
    			//--------------- is the position blocked? ----------//
    			if(moveToX>=MAX_WORLD_X_LOC-1 || moveToY>=MAX_WORLD_Y_LOC-1)
    				blocked = 1;
    			else
    			{
    				blocked = 0;
    				for(h=0, surY=moveToY; h<2 && !blocked; h++, surY++)
    				{
    					for(w=0, surX=moveToX; w<2 && !blocked; w++, surX++)
    					{
    						locPtr = worldLocMatrix+surY*MAX_WORLD_X_LOC+surX;
    						blocked = !locPtr->is_unit_group_accessible(mobileType, curGroupId);
    					}
    				}
    			}

    			if(!blocked)
    			{
    				do
    				{
    					unitPtr = (Unit*) get_ptr(selectedUnitArray[suaCount++]);
    				}while(unitPtr->sprite_info->loc_width<2);
    				if(sizeTwoSelectedCount>1)
    				{
    					if(sizeTwoUnprocessCount==sizeTwoSelectedCount) // the first unit to move
    					{
    						unitPtr->move_to(moveToX, moveToY, 1, 4, 0, sizeTwoSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_INITIAL);
    						unitPtr->move_to(moveToX, moveToY, 1, 4, 0, sizeTwoSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_FIRST_SEEK);
    					}
    					else
    					{
    						err_if(sizeTwoUnprocessCount==sizeTwoSelectedCount)
    							err_here();

    						unitPtr->move_to(moveToX, moveToY, 1, 4, 0, sizeTwoSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_SEARCH);
    					}
    				}
    				else
    					unitPtr->move_to(moveToX, moveToY, 1);
    				sizeTwoUnprocessCount--;
    			}
    			moveToX-=2;
    		}
    	}

    	//------------- left edge ---------------//
    	moveToX = x-2;
    	moveToY = y+rec_height-2;
    	if(moveToX>=0)
    	{
    		if(y-3 < 0)
    			boundedY = -1;
    		else
    			boundedY = y-3;

    		while(moveToY>boundedY && sizeTwoUnprocessCount)
    		{
    			//--------------- is the position blocked? ----------//
    			if(moveToX>=MAX_WORLD_X_LOC-1 || moveToY>=MAX_WORLD_Y_LOC-1)
    				blocked = 1;
    			else
    			{
    				blocked = 0;
    				for(h=0, surY=moveToY; h<2 && !blocked; h++, surY++)
    				{
    					for(w=0, surX=moveToX; w<2 && !blocked; w++, surX++)
    					{
    						locPtr = worldLocMatrix+surY*MAX_WORLD_X_LOC+surX;
    						blocked = !locPtr->is_unit_group_accessible(mobileType, curGroupId);
    					}
    				}
    			}

    			if(!blocked)
    			{
    				do
    				{
    					unitPtr = (Unit*) get_ptr(selectedUnitArray[suaCount++]);
    				}while(unitPtr->sprite_info->loc_width<2);

    				if(sizeTwoSelectedCount>1)
    				{
    					if(sizeTwoUnprocessCount==sizeTwoSelectedCount) // the first unit to move
    					{
    						unitPtr->move_to(moveToX, moveToY, 1, 4, 0, sizeTwoSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_INITIAL);
    						unitPtr->move_to(moveToX, moveToY, 1, 4, 0, sizeTwoSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_FIRST_SEEK);
    					}
    					else
    					{
    						err_if(sizeTwoUnprocessCount==sizeTwoSelectedCount)
    							err_here();

    						unitPtr->move_to(moveToX, moveToY, 1, 4, 0, sizeTwoSelectedCount, GENERAL_GROUP_MOVEMENT, REUSE_PATH_SEARCH);
    					}
    				}
    				else
    					unitPtr->move_to(moveToX, moveToY, 1);
    				sizeTwoUnprocessCount--;
    			}
    			moveToY-=2;
    		}
    	}

    	//------- reset square_size, rec_width, rec_height -----------//
    	rec_width+=4;
    	rec_height+=4;
    	x-=2;
    	y-=2;
    }*/
}
Beispiel #5
0
inline void Scene::PhongColor (float px, float py, float pz, 
			       float nx, float ny, float nz,
			       Material* m,
			       short& rr, short& gg, short& bb)
{
  const float Eps = 1e-5f;

  // check for NULL material pointer - take scenes default material
  if ( ! m ) m = &mat;
    
  // check for image texture mapping
  if (m->use_image_texture) {
    Matpack.Error("Scene::PhongColor: image textures not yet available");
    rr = gg = bb = 0; 
    return;
  }

  // check for normal texturing function  - apply to normal vector
  if (m->use_normal_texture) {
    Vector3D tmp(nx,ny,nz);
    (*m).normal_texture(tmp);
    nx = tmp.x; ny = tmp.y; nz = tmp.z;
  }

  // normalization of normal vector
  float sn = hypot(nx,ny,nz);
  if (sn) { nx /= sn; ny /= sn; nz /= sn; }

  // normalization of coordinate vector of surface point
  float sp = hypot(px,py,pz), pxn = 0, pyn = 0, pzn = 0;
  if (sp) { pxn = px/sp; pyn = py/sp; pzn = pz/sp; }
    
  float r = 0,
        g = 0,
        b = 0,
        spec = 0,
        amb = m->ambient,    // ambient light contribution
        spc = m->specular;   // specular light contribution

  // loop through list of lights
  for (Light *l = FirstLight(); l; NextLight(l) ) {
	
    // distance of light to point on surface: sl = |light-point|
    float sxp = l->x - px, 
          syp = l->y - py, 
          szp = l->z - pz,
          sl = hypot(sxp,syp,szp),
          cs = (sl == 0.0) ? 0.0 : (nx*sxp+ny*syp+nz*szp)/sl;
	
    // If cs is negative then we look at the back side, if it is positive
    // then the front side is visible. The side is determined by the orientation
    // of the vertices in the facet (counter clockwise = front side).

    if (cs < 0.0) cs = 0;

    // ambient light plus diffuse reflection according to Lambert's law
    float light = (1.0 - amb) * cs + amb;
	
    // add specular reflection according to Bui-Tuong Phong's model
    if (spc > Eps) {
      if (sl && sp && sn) { 
	float qx = sxp/sl - pxn,
	      qy = syp/sl - pyn,
	      qz = szp/sl - pzn,
	      sq = hypot(qx,qy,qz);
	if (sq != 0.0) { 
	  float csa2 = (qx*nx+qy*ny+qz*nz) / sq,
	        csa  = 2.0 * csa2*csa2 - 1.0;
	  spec = (csa > Eps) ? spc * pow(csa,m->exponent) : 0.0;
	} else
	  spec = 0.0;
      } else 
	spec = 0.0;
    }

    // intensity factor of light
    light *= l->intensity;

    // now multiply light with surface color 
    // evaluate a texturing function if neccessary
    if (m->use_color_texture) {
      Vector3D tmp = Qinv * Vector3D(px,py,pz); // backtrafo to user coord.
      (*m).color_texture(tmp);
      r += light * l->red   * tmp.x + spec;
      g += light * l->green * tmp.y + spec;
      b += light * l->blue  * tmp.z + spec;
    } else {
      r += light * l->red   * m->color.red   + spec;
      g += light * l->green * m->color.green + spec;
      b += light * l->blue  * m->color.blue  + spec;
    }
  }
    
  // Fog can be simulated by mixing the background color to the surface color.
  // With increasing distance of the camera from the surface point (p) an 
  // exponentially increasing contribution of the background color 
  // should be mixed to the surface color. 
  //
  // But this model is not flexible enough. A much better fog is a 
  // parametrization using the hyperbolic tangent as blending function. 
  // The mixing is controlled by three parameters:
  //
  //  1. fog_color     (RGB color)
  //  2. fog_opacity   (fog_opacity >= 0)
  //  3. fog_distance  (distance from camera)
  //
  // A depth cueing effect can easily achieved with the approach.
  
  if (fog_opacity) {
    // the distance from the camera is given by "sp"
    float k1 = 0.5 * ( 1 - tanh( (6/fog_opacity) * (sp - fog_distance - 1) ) ),
          k2 = 1.0 - k1;
    r = k1 * r + k2 * fog_color.red;
    g = k1 * g + k2 * fog_color.green;
    b = k1 * b + k2 * fog_color.blue;
  }

  // scale and truncate to range 0..255
  rr = short(255*r); if (rr > 255) rr = 255; else if (rr < 0) rr = 0; 
  gg = short(255*g); if (gg > 255) gg = 255; else if (gg < 0) gg = 0; 
  bb = short(255*b); if (bb > 255) bb = 255; else if (bb < 0) bb = 0; 
}    
Beispiel #6
0
static DerivedMesh *normalEditModifier_do(NormalEditModifierData *enmd, Object *ob, DerivedMesh *dm)
{
	Mesh *me = ob->data;

	const int num_verts = dm->getNumVerts(dm);
	const int num_edges = dm->getNumEdges(dm);
	const int num_loops = dm->getNumLoops(dm);
	const int num_polys = dm->getNumPolys(dm);
	MVert *mvert;
	MEdge *medge;
	MLoop *mloop;
	MPoly *mpoly;

	const bool use_invert_vgroup = ((enmd->flag & MOD_NORMALEDIT_INVERT_VGROUP) != 0);
	const bool use_current_clnors = !((enmd->mix_mode == MOD_NORMALEDIT_MIX_COPY) &&
	                                  (enmd->mix_factor == 1.0f) &&
	                                  (enmd->defgrp_name[0] == '\0') &&
	                                  (enmd->mix_limit == (float)M_PI));

	int defgrp_index;
	MDeformVert *dvert;

	float (*loopnors)[3] = NULL;
	short (*clnors)[2];

	float (*polynors)[3];
	bool free_polynors = false;

	/* Do not run that modifier at all if autosmooth is disabled! */
	if (!is_valid_target(enmd) || !num_loops) {
		return dm;
	}

	if (!(me->flag & ME_AUTOSMOOTH)) {
		modifier_setError((ModifierData *)enmd, "Enable 'Auto Smooth' option in mesh settings");
		return dm;
	}

	medge = dm->getEdgeArray(dm);
	if (me->medge == medge) {
		/* We need to duplicate data here, otherwise setting custom normals (which may also affect sharp edges) could
		 * modify org mesh, see T43671. */
		dm = CDDM_copy(dm);
		medge = dm->getEdgeArray(dm);
	}
	mvert = dm->getVertArray(dm);
	mloop = dm->getLoopArray(dm);
	mpoly = dm->getPolyArray(dm);

	if (use_current_clnors) {
		dm->calcLoopNormals(dm, true, me->smoothresh);
		loopnors = dm->getLoopDataArray(dm, CD_NORMAL);
	}

	clnors = CustomData_duplicate_referenced_layer(&dm->loopData, CD_CUSTOMLOOPNORMAL, num_loops);
	if (!clnors) {
		DM_add_loop_layer(dm, CD_CUSTOMLOOPNORMAL, CD_CALLOC, NULL);
		clnors = dm->getLoopDataArray(dm, CD_CUSTOMLOOPNORMAL);
	}

	polynors = dm->getPolyDataArray(dm, CD_NORMAL);
	if (!polynors) {
		polynors = MEM_malloc_arrayN((size_t)num_polys, sizeof(*polynors), __func__);
		BKE_mesh_calc_normals_poly(mvert, NULL, num_verts, mloop, mpoly, num_loops, num_polys, polynors, false);
		free_polynors = true;
	}

	modifier_get_vgroup(ob, dm, enmd->defgrp_name, &dvert, &defgrp_index);

	if (enmd->mode == MOD_NORMALEDIT_MODE_RADIAL) {
		normalEditModifier_do_radial(
		            enmd, ob, dm, clnors, loopnors, polynors,
		            enmd->mix_mode, enmd->mix_factor, enmd->mix_limit, dvert, defgrp_index, use_invert_vgroup,
		            mvert, num_verts, medge, num_edges, mloop, num_loops, mpoly, num_polys);
	}
	else if (enmd->mode == MOD_NORMALEDIT_MODE_DIRECTIONAL) {
		normalEditModifier_do_directional(
		            enmd, ob, dm, clnors, loopnors, polynors,
		            enmd->mix_mode, enmd->mix_factor, enmd->mix_limit, dvert, defgrp_index, use_invert_vgroup,
		            mvert, num_verts, medge, num_edges, mloop, num_loops, mpoly, num_polys);
	}

	if (free_polynors) {
		MEM_freeN(polynors);
	}

	return dm;
}
Beispiel #7
0
std::vector<bool> Halite::processNextFrame(std::vector<bool> alive) {

	//Update alive frame counts
	for(unsigned char a = 0; a < number_of_players; a++) if(alive[a]) alive_frame_count[a]++;

	//Create threads to send/receive data to/from players. The threads should return a float of how much time passed between the end of their message being sent and the end of the AI's message being sent.
	std::vector< std::future<unsigned int> > frameThreads(std::count(alive.begin(), alive.end(), true));
	unsigned char threadLocation = 0; //Represents place in frameThreads.

	//Figure out how long each AI is permitted to respond without penalty in milliseconds.
	std::vector<int> allowableTimesToRespond(number_of_players);
	const int BOT_FRAME_TIMEOUT_MILLIS = 50 + ((game_map.map_width * game_map.map_height) / 2);
	for(unsigned char a = 0; a < number_of_players; a++) allowableTimesToRespond[a] = BOT_FRAME_TIMEOUT_MILLIS;

	//Stores the messages sent by bots this frame
	for(unsigned char a = 0; a < number_of_players; a++) {
		if(alive[a]) {
			frameThreads[threadLocation] = std::async(&Networking::handleFrameNetworking, &networking, allowableTimesToRespond[a], a + 1, game_map, &player_moves[a]);
			threadLocation++;
		}
	}

	std::vector< std::vector<unsigned char> > moveDirections(game_map.map_height, std::vector<unsigned char>(game_map.map_width, 0));

	//Join threads. Figure out if the player responded in an allowable amount of time or if the player has timed out.
	std::vector<unsigned short> permissibleTime(number_of_players, false);
	threadLocation = 0; //Represents place in frameThreads.
	for(unsigned char a = 0; a < number_of_players; a++) {
		if(alive[a]) {
			unsigned short millis = frameThreads[threadLocation].get();
			if(millis < BOT_FRAME_TIMEOUT_MILLIS) {
				permissibleTime[a] = true;
			}
			//	There was an exception in the networking thread or the player timed out. Either way, kill their thread
			else {
				if(!program_output_style) std::cout << player_names[a] << " timed out\n";
				permissibleTime[a] = false;
				networking.killPlayer(a + 1);
			}
			threadLocation++;
			total_response_time[a] += millis;
		}
	}

	std::vector< std::map<hlt::Location, unsigned char> > pieces(number_of_players);

	//For each player, use their moves to create the pieces map.
	for(unsigned char a = 0; a < number_of_players; a++) if(alive[a]) {
		//Add in pieces according to their moves. Also add in a second piece corresponding to the piece left behind.
		for(auto b = player_moves[a].begin(); b != player_moves[a].end(); b++) if(game_map.inBounds(b->loc) && game_map.getSite(b->loc, STILL).owner == a + 1) {
			if(b->dir == STILL) {
				if(game_map.getSite(b->loc, STILL).strength + game_map.getSite(b->loc, STILL).production <= 255) game_map.getSite(b->loc, STILL).strength += game_map.getSite(b->loc, STILL).production;
				else game_map.getSite(b->loc, STILL).strength = 255;
				//Update full still count
				full_still_count[a]++;
				//Add to full production
				full_production_count[a] += game_map.getSite(b->loc, STILL).production;
			}
			//Update full caridnal count.
			else full_cardinal_count[a]++;

			//Update moves
			moveDirections[b->loc.y][b->loc.x] = b->dir;

			hlt::Location newLoc = game_map.getLocation(b->loc, b->dir);
			if(pieces[a].count(newLoc)) {
				if(short(pieces[a][newLoc]) + game_map.getSite(b->loc, STILL).strength <= 255) pieces[a][newLoc] += game_map.getSite(b->loc, STILL).strength;
				else pieces[a][newLoc] = 255;
			}
			else {
				pieces[a].insert(std::pair<hlt::Location, unsigned char>(newLoc, game_map.getSite(b->loc, STILL).strength));
			}

			//Add in a new piece with a strength of 0 if necessary.
			if(!pieces[a].count(b->loc)) {
				pieces[a].insert(std::pair<hlt::Location, unsigned char>(b->loc, 0));
			}

			//Erase from the game map so that the player can't make another move with the same piece.
			game_map.getSite(b->loc, STILL).owner = 0;
			game_map.getSite(b->loc, STILL).strength = 0;
		}
	}

	//Add in all of the remaining pieces whose moves weren't specified.
	for(unsigned short a = 0; a < game_map.map_height; a++) for(unsigned short b = 0; b < game_map.map_width; b++) {
		hlt::Location l = { b, a };
		hlt::Site & s = game_map.getSite(l, STILL);
		if(s.owner != 0) {
			if(short(s.strength) + s.production <= 255) {
				s.strength += s.production;
			}
			else s.strength = 255;
			if(pieces[s.owner - 1].count(l)) {
				if(short(pieces[s.owner - 1][l]) + s.strength <= 255) pieces[s.owner - 1][l] += s.strength;
				else pieces[s.owner - 1][l] = 255;
			}
			else {
				pieces[s.owner - 1].insert(std::pair<hlt::Location, unsigned char>(l, s.strength));
			}
			//Add to full production
			full_production_count[s.owner - 1] += s.production;
			//Update full still count
			full_still_count[s.owner - 1]++;
			//Erase from game map.
			s.owner = 0;
			s.strength = 0;
		}
	}

	std::vector< std::map<hlt::Location, unsigned short> > toInjure(number_of_players);
	std::vector< std::vector<unsigned short> > injureMap(game_map.map_height, std::vector<unsigned short>(game_map.map_width, 0));

	//Sweep through locations and find the correct damage for each piece. Start by applying damage within only the active strengths.
	for(unsigned char a = 0; a != game_map.map_height; a++) for(unsigned short b = 0; b < game_map.map_width; b++) {
		hlt::Location l = { b, a };
		for(unsigned short c = 0; c < number_of_players; c++) if(alive[c] && pieces[c].count(l)) {
			for(unsigned short d = 0; d < number_of_players; d++) if(d != c && alive[d]) {
				hlt::Location tempLoc = l;
				//Check 'STILL' square. We also need to deal with the threshold here:
				if(pieces[d].count(tempLoc)) {
					//Apply damage, but not more than they have strength:
					if(toInjure[d].count(tempLoc)) toInjure[d][tempLoc] += pieces[c][l];
					else toInjure[d].insert(std::pair<hlt::Location, unsigned short>(tempLoc, pieces[c][l]));
				}
				//Check 'NORTH' square:
				tempLoc = game_map.getLocation(l, NORTH);
				if(pieces[d].count(tempLoc)) {
					//Apply damage, but not more than they have strength:
					if(toInjure[d].count(tempLoc)) toInjure[d][tempLoc] += pieces[c][l];
					else toInjure[d].insert(std::pair<hlt::Location, unsigned short>(tempLoc, pieces[c][l]));
				}
				//Check 'EAST' square:
				tempLoc = game_map.getLocation(l, EAST);
				if(pieces[d].count(tempLoc)) {
					//Apply damage, but not more than they have strength:
					if(toInjure[d].count(tempLoc)) toInjure[d][tempLoc] += pieces[c][l];
					else toInjure[d].insert(std::pair<hlt::Location, unsigned short>(tempLoc, pieces[c][l]));
				}
				//Check 'SOUTH' square:
				tempLoc = game_map.getLocation(l, SOUTH);
				if(pieces[d].count(tempLoc)) {
					//Apply damage, but not more than they have strength:
					if(toInjure[d].count(tempLoc)) toInjure[d][tempLoc] += pieces[c][l];
					else toInjure[d].insert(std::pair<hlt::Location, unsigned short>(tempLoc, pieces[c][l]));
				}
				//Check 'WEST' square:
				tempLoc = game_map.getLocation(l, WEST);
				if(pieces[d].count(tempLoc)) {
					//Apply damage, but not more than they have strength:
					if(toInjure[d].count(tempLoc)) toInjure[d][tempLoc] += pieces[c][l];
					else toInjure[d].insert(std::pair<hlt::Location, unsigned short>(tempLoc, pieces[c][l]));
				}
			}
			if(game_map.getSite(l, STILL).strength > 0) {
				if(toInjure[c].count(l)) toInjure[c][l] += game_map.getSite(l, STILL).strength;
				else toInjure[c].insert(std::pair<hlt::Location, unsigned short>(l, game_map.getSite(l, STILL).strength));
				injureMap[l.y][l.x] += pieces[c][l];
			}
		}
	}

	//Injure and/or delete pieces. Note >= rather than > indicates that pieces with a strength of 0 are killed.
	for(unsigned char a = 0; a < number_of_players; a++) if(alive[a]) {
		for(auto b = toInjure[a].begin(); b != toInjure[a].end(); b++) {
			//Apply damage.
			if(b->second >= pieces[a][b->first]) pieces[a].erase(b->first);
			else pieces[a][b->first] -= b->second;
		}
	}

	//Apply damage to map pieces.
	for(int a = 0; a < game_map.map_height; a++) for(int b = 0; b < game_map.map_width; b++) {
		if(game_map.contents[a][b].strength < injureMap[a][b]) game_map.contents[a][b].strength = 0;
		else game_map.contents[a][b].strength -= injureMap[a][b];
		game_map.contents[a][b].owner = 0;
	}


	//Add pieces back into the map.
	for(unsigned char a = 0; a < number_of_players; a++) {
		for(auto b = pieces[a].begin(); b != pieces[a].end(); b++) {
			game_map.getSite(b->first, STILL).owner = a + 1;
			game_map.getSite(b->first, STILL).strength = b->second;
		}
	}

	std::vector<unsigned char> * turn = new std::vector<unsigned char>; turn->reserve(game_map.map_height * game_map.map_width * 2.25);
	for(auto a = moveDirections.begin(); a != moveDirections.end(); a++) for(auto b = a->begin(); b != a->end(); b++) {
		turn->push_back(*b);
	}
	unsigned char presentOwner = game_map.contents.begin()->begin()->owner;
	std::list<unsigned char> strengths;
	short numPieces = 0;
	for(auto a = game_map.contents.begin(); a != game_map.contents.end(); a++) for(auto b = a->begin(); b != a->end(); b++) {
		if(numPieces == 255 || b->owner != presentOwner) {
			turn->push_back(numPieces);
			turn->push_back(presentOwner);
			for(auto b = strengths.begin(); b != strengths.end(); b++) turn->push_back(*b);
			strengths.clear();
			numPieces = 0;
			presentOwner = b->owner;
		}
		numPieces++;
		strengths.push_back(b->strength);
	}

	//Final output set:
	turn->push_back(numPieces);
	turn->push_back(presentOwner);
	for(auto b = strengths.begin(); b != strengths.end(); b++) turn->push_back(*b);
	turn->shrink_to_fit();
	//Add to full game:
	full_game.push_back(turn);

	//Check if the game is over:
	std::vector<bool> stillAlive(number_of_players, false);

	for(unsigned short a = 0; a < game_map.map_height; a++) for(unsigned short b = 0; b < game_map.map_width; b++) if(game_map.contents[a][b].owner != 0) {
		full_territory_count[game_map.contents[a][b].owner - 1]++;
		full_strength_count[game_map.contents[a][b].owner - 1] += game_map.contents[a][b].strength;
		full_production_count[game_map.contents[a][b].owner - 1] += game_map.contents[a][b].strength;

		stillAlive[game_map.contents[a][b].owner - 1] = true;
	}

	//Check for bots which have timed out.
	for(unsigned char a = 0; a < permissibleTime.size(); a++) if(alive[a] && !permissibleTime[a]) {
		stillAlive[a] = false;
		timeout_tags.insert(a + 1);
	}

	return stillAlive;
}
Beispiel #8
0
PintObjectHandle Bullet::CreateObject(const PINT_OBJECT_CREATE& desc)
{
	udword NbShapes = desc.GetNbShapes();
	if(!NbShapes)
		return null;

	ASSERT(mDynamicsWorld);

	const PINT_SHAPE_CREATE* CurrentShape = desc.mShapes;

	float FrictionCoeff = 0.5f;
	float RestitutionCoeff = 0.0f;
	btCollisionShape* colShape = null;
	if(NbShapes>1)
	{
		btCompoundShape* CompoundShape = new btCompoundShape();
		colShape = CompoundShape;
		mCollisionShapes.push_back(colShape);

		while(CurrentShape)
		{
			if(CurrentShape->mMaterial)
			{
				FrictionCoeff		= CurrentShape->mMaterial->mDynamicFriction;
				RestitutionCoeff	= CurrentShape->mMaterial->mRestitution;
			}

			const btTransform LocalPose(ToBtQuaternion(CurrentShape->mLocalRot), ToBtVector3(CurrentShape->mLocalPos));

			// ### TODO: where is this deleted?
			btCollisionShape* subShape = CreateBulletShape(*CurrentShape);
			if(subShape)
			{
				CompoundShape->addChildShape(LocalPose, subShape);
			}

			CurrentShape = CurrentShape->mNext;
		}
	}
	else
	{
		colShape = CreateBulletShape(*CurrentShape);

		if(CurrentShape->mMaterial)
		{
			FrictionCoeff		= CurrentShape->mMaterial->mDynamicFriction;
			RestitutionCoeff	= CurrentShape->mMaterial->mRestitution;
		}
	}

	const bool isDynamic = (desc.mMass != 0.0f);

	btVector3 localInertia(0,0,0);
	if(isDynamic)
		colShape->calculateLocalInertia(desc.mMass, localInertia);

	const btTransform startTransform(ToBtQuaternion(desc.mRotation), ToBtVector3(desc.mPosition));

	//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
	btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);

	btRigidBody::btRigidBodyConstructionInfo rbInfo(desc.mMass, myMotionState, colShape, localInertia);
	{
		rbInfo.m_friction		= FrictionCoeff;
		rbInfo.m_restitution	= RestitutionCoeff;

	//	rbInfo.m_startWorldTransform;
		rbInfo.m_linearDamping				= gLinearDamping;
		rbInfo.m_angularDamping				= gAngularDamping;
		if(!gEnableSleeping)
		{
//			rbInfo.m_linearSleepingThreshold	= 99999999.0f;
//			rbInfo.m_angularSleepingThreshold	= 99999999.0f;
//			rbInfo.m_linearSleepingThreshold	= 0.0f;
//			rbInfo.m_angularSleepingThreshold	= 0.0f;
		}
	//	rbInfo.m_additionalDamping;
	//	rbInfo.m_additionalDampingFactor;
	//	rbInfo.m_additionalLinearDampingThresholdSqr;
	//	rbInfo.m_additionalAngularDampingThresholdSqr;
	//	rbInfo.m_additionalAngularDampingFactor;
	}
	btRigidBody* body = new btRigidBody(rbInfo);
	ASSERT(body);
	if(!gEnableSleeping)
		body->setActivationState(DISABLE_DEACTIVATION);

	sword collisionFilterGroup, collisionFilterMask;

	if(isDynamic)
	{
		body->setLinearVelocity(ToBtVector3(desc.mLinearVelocity));
		body->setAngularVelocity(ToBtVector3(desc.mAngularVelocity));

		collisionFilterGroup = short(btBroadphaseProxy::DefaultFilter);
		collisionFilterMask = short(btBroadphaseProxy::AllFilter);

		if(desc.mCollisionGroup)
		{
			const udword btGroup = RemapCollisionGroup(desc.mCollisionGroup);
			ASSERT(btGroup<32);
			collisionFilterGroup = short(1<<btGroup);
			collisionFilterMask = short(mGroupMasks[btGroup]);
		}
	}
	else
	{
//		body->setCollisionFlags(btCollisionObject::CF_STATIC_OBJECT);
		body->setCollisionFlags(btCollisionObject::CF_STATIC_OBJECT|btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);

		collisionFilterGroup = short(btBroadphaseProxy::StaticFilter);
		collisionFilterMask = short(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
	}

	if(desc.mAddToWorld)
//		mDynamicsWorld->addRigidBody(body);
		mDynamicsWorld->addRigidBody(body, collisionFilterGroup, collisionFilterMask);

	if(gUseCCD)
	{
//		body->setCcdMotionThreshold(1e-7);
//		body->setCcdSweptSphereRadius(0.9*CUBE_HALF_EXTENTS);

		body->setCcdMotionThreshold(0.0001f);
		body->setCcdSweptSphereRadius(0.4f);
	}
	return body;
}
Beispiel #9
0
string a_short() {
    return short();
}
Beispiel #10
0
//---------------------------------------------------------------------------
void CXMMTCtrl::OnReceive(CCSocket *pSocket, int nErrorCode)
{
	if( nErrorCode == SOCKET_ERROR ) return;
	ASSERT(pSocket);
	BYTE    bf[8192];
	UINT    n;

	n = pSocket->Receive(bf, sizeof(bf));
	int nIndex = 0;
	for( ; (nIndex < USERMAX) && (pSocket != m_pConnection[nIndex]); nIndex++ );
	if( nIndex >= USERMAX ) return;
	if( n != SOCKET_ERROR ){
		LPBYTE p = bf;
		for( UINT i = 0; i < n; i++, p++ ){
			if( !m_CustomSession[nIndex].IsOpen() ){
				switch(*p){
					case NOTIFY_PTTON:
						FireOnPttEvent(nIndex, TRUE);
						break;
					case NOTIFY_PTTOFF:
						FireOnPttEvent(nIndex, FALSE);
						break;
					case NOTIFY_BUSYON:
						m_bBusy[nIndex] = TRUE;
						FireOnBusyEvent(nIndex, TRUE);
						break;
					case NOTIFY_BUSYOFF:
						m_bBusy[nIndex] = FALSE;
						FireOnBusyEvent(nIndex, FALSE);
						break;
					case CODE_CUSTOMSESSION:
						// サーバーとクライアント間で定義された特別なデータの伝送が
						// 開始されます。
						m_CustomSession[nIndex].OpenSession();
						break;
					default:
						FireOnCharRcvd(nIndex, *p);
						break;
				}
			}
			else if( m_CustomSession[nIndex].PutData(*p) ){
				// サーバーとクライアント間で定義された特別なデータの伝送が終了
				// しました。ここでそのデータの処理を行います。
				CUSTOMSESSION *pCom = m_CustomSession[nIndex].GetData();
				switch(pCom->m_command){
					case COM_NOTIFY:
						// MMTTYからのmmtNotifyがここに通知されます。
						if( m_bNotify[nIndex] & ntNOTIFY ){
							FireOnNotifyNMMT(nIndex, (LONG *)pCom->m_pData);
						}
						break;
					case COM_NOTIFYFFT:
						// MMTTYからのmmtNotifyFFTがここに通知されます。
						if( m_bNotify[nIndex] & ntNOTIFYFFT ){
							COMFFT *pFFT = (COMFFT *)pCom->m_pData;
							if( m_bFftConversion ){
								DoFftConversion(nIndex, pFFT);
							}
							else {
								FireOnNotifyFFT(nIndex, pFFT->m_wdata, pFFT->m_wsize, pFFT->m_wsampfreq);
							}
						}
						break;
					case COM_NOTIFYXY:
						// MMTTYからのmmtNotifyXYがここに通知されます。
						if( m_bNotify[nIndex] & ntNOTIFYXY ){
							FireOnNotifyXY(nIndex, (LONG *)pCom->m_pData);
						}
						break;
					case COM_MESSAGERESULT:
						// COM_MESSAGERESULTでMMTTYに送信したメッセージの返答が
						// ここに通知されます。
						{
							COMMSG *pc = (COMMSG *)pCom->m_pData;
							if( pc->m_wParam == MMTMSG_GETPROFILENAME ){
								LPCSTR pStr = LPCSTR(pCom->m_pData + sizeof(COMMSG));
								if( pCom->m_len <= sizeof(COMMSG) ) pStr = "";
								FireOnGetProfileName(nIndex, short(pc->m_lParam), pStr);
							}
							else {
								FireOnMessageResult(nIndex, pc->m_wParam, pc->m_lParam, pc->m_lResult);
							}
						}
						break;
				}
				m_CustomSession[nIndex].Delete();
			}
		}
	}
}
Beispiel #11
0
void h_Player::UpdateBuildPos( const p_WorldPhysMesh& phys_mesh )
{
	m_Vec3 eye_dir(
		-std::sin( view_angle_.z ) * std::cos( view_angle_.x ),
		+std::cos( view_angle_.z ) * std::cos( view_angle_.x ),
		+std::sin( view_angle_.x ) );

	m_Vec3 eye_pos= pos_;
	eye_pos.z+= eyes_level_;
	float square_dist= std::numeric_limits<float>::max();
	h_Direction block_dir= h_Direction::Unknown;

	m_Vec3 intersect_pos;
	m_Vec3 candidate_pos;
	m_Vec3 n;

	for( const p_UpperBlockFace& face : phys_mesh.upper_block_faces )
	{
		n= g_block_normals[ static_cast<size_t>(face.dir) ];

		// Triangulate polygon and check intersection with triangles.
		m_Vec3 triangle[3];
		triangle[0]= m_Vec3( face.vertices[0], face.z );
		for( unsigned int i= 0; i < face.vertex_count - 2; i++ )
		{
			triangle[1]= m_Vec3( face.vertices[ i + 1 ], face.z );
			triangle[2]= m_Vec3( face.vertices[ i + 2 ], face.z );
			if( pRayHasIniersectWithTriangle( triangle, n, eye_pos, eye_dir, &candidate_pos ) )
			{
				float candidate_square_dist= ( candidate_pos - eye_pos ).SquareLength();
				if( candidate_square_dist < square_dist )
				{
					square_dist= candidate_square_dist;
					intersect_pos= candidate_pos;
					block_dir= face.dir;
				}
			}
		}
	}

	for( const p_BlockSide& side : phys_mesh.block_sides )
	{
		n= g_block_normals[ static_cast<size_t>(side.dir) ];

		m_Vec3 triangles[6];
		triangles[0]= m_Vec3( side.edge[0], side.z0 );
		triangles[1]= m_Vec3( side.edge[1], side.z0 );
		triangles[2]= m_Vec3( side.edge[1], side.z1 );
		triangles[3]= m_Vec3( side.edge[0], side.z1 );
		triangles[4]= m_Vec3( side.edge[0], side.z0 );
		triangles[5]= m_Vec3( side.edge[1], side.z1 );
		for( unsigned int i= 0; i < 2; i++ )
		{
			if( pRayHasIniersectWithTriangle( triangles + i * 3, n, eye_pos, eye_dir, &candidate_pos ) )
			{
				float candidate_square_dist= ( candidate_pos - eye_pos ).SquareLength();
				if( candidate_square_dist < square_dist )
				{
					square_dist= candidate_square_dist;
					intersect_pos= candidate_pos;
					block_dir= side.dir;
				}
			}
		}
	}

	if( block_dir == h_Direction::Unknown ||
		square_dist > g_max_build_distance * g_max_build_distance )
	{
		build_direction_= h_Direction::Unknown;
		return;
	}

	// Fix accuracy. Move intersection point inside target block.
	intersect_pos-= g_block_normals[ static_cast<size_t>(block_dir) ] * 0.1f;

	pGetHexogonCoord( intersect_pos.xy(), &destroy_pos_[0], &destroy_pos_[1] );
	destroy_pos_[2]= short( intersect_pos.z );

	discret_build_pos_[0]= destroy_pos_[0];
	discret_build_pos_[1]= destroy_pos_[1];
	discret_build_pos_[2]= destroy_pos_[2];

	switch( block_dir )
	{
	case h_Direction::Up: discret_build_pos_[2]++; break;
	case h_Direction::Down: discret_build_pos_[2]--; break;

	case h_Direction::Forward: discret_build_pos_[1]++; break;
	case h_Direction::Back: discret_build_pos_[1]--; break;

	case h_Direction::ForwardRight:
		discret_build_pos_[1]+= ( (discret_build_pos_[0]^1) & 1 );
		discret_build_pos_[0]++;
		break;
	case h_Direction::BackRight:
		discret_build_pos_[1]-= discret_build_pos_[0] & 1;
		discret_build_pos_[0]++;
		break;

	case h_Direction::ForwardLeft:
		discret_build_pos_[1]+= ( (discret_build_pos_[0]^1) & 1 );
		discret_build_pos_[0]--;
		break;
	case h_Direction::BackLeft:
		discret_build_pos_[1]-= discret_build_pos_[0] & 1;
		discret_build_pos_[0]--;
		break;

	case h_Direction::Unknown: H_ASSERT(false); break;
	}

	build_pos_.x= float( discret_build_pos_[0] + 1.0f / 3.0f ) * H_SPACE_SCALE_VECTOR_X;
	build_pos_.y= float( discret_build_pos_[1] ) - 0.5f * float(discret_build_pos_[0]&1) + 0.5f;
	build_pos_.z= float( discret_build_pos_[2] );

	build_direction_= block_dir;
}
Beispiel #12
0
// Post-render callback
//
void refreshCompute::postRenderCB(const MString& panelName, void * data)
{	
	refreshCompute *thisCompute = (refreshCompute *) data;
	if (!thisCompute)
		return;

	// Get the view if any for the panel
	M3dView view;
	MStatus status = M3dView::getM3dViewFromModelPanel(panelName, view);
	if (status != MS::kSuccess)
		return;

	view.popViewport();

	if (thisCompute->mBufferOperation == kDrawDepthBuffer)
	{
		int width = 0, height = 0;
		width = view.portWidth( &status ) / 2 ;
		if (status != MS::kSuccess || (width < 2))
			return;
		height = view.portHeight( &status ) / 2 ;
		if (status != MS::kSuccess || (height < 2))
			return;

		unsigned int numPixels = width * height;

		float *depthPixels = new float[numPixels];
		if (!depthPixels)
			return;

		unsigned char *colorPixels = new unsigned char[numPixels * 4];
		if (!colorPixels)
		{
			delete depthPixels;
			delete colorPixels;
		}

		// Read into a float buffer
		status = view.readDepthMap( 0,0, width, height, (unsigned char *)depthPixels, M3dView::kDepth_Float );

		if (status != MS::kSuccess)
		{
			delete depthPixels;
			delete colorPixels;
			return;
		}

		// Find depth range and remap normalized depth range (-1 to 1) into 0...255
		// for color.
		float *dPtr = depthPixels;
		unsigned int i = 0;

		float zmin = 100.0f; // *dPtr;
		float zmax = -100.0f; // *dPtr;
		for(i=0; i<numPixels; i++)
		{
			float val = *dPtr; // * 2.0f - 1.0f;
			if(val < zmin) {
				zmin = *dPtr;
			}
			if(val > zmax) {
				zmax = *dPtr;
			}
			dPtr++;
		}
		float zrange = zmax - zmin;
		//printf("depth values = (%g, %g). Range = %g\n", zmin, zmax, zrange);

		unsigned char *cPtr = colorPixels;

		dPtr = depthPixels;
		for(i=0; i < numPixels; i++)
		{
			float val = *dPtr; // * 2.0f - 1.0f;
			//unsigned char depth = (unsigned char)(255.0f * (( (*dPtr)-zmin) / zrange) + zmin );
			unsigned char depth = (unsigned char)(255.0f * (( (val)-zmin) / zrange) );
			//unsigned char depth = (unsigned char)(255.0f * val);
			*cPtr = depth; cPtr++;
			*cPtr = depth; cPtr++;
			*cPtr = depth; cPtr++;
			*cPtr = 0xff;   
			cPtr++;
			dPtr++;
		}

		MImage image;
		image.setPixels( colorPixels, width, height );

		// Uncomment next line to test writing buffer to file.
		//image.writeToFile( "C:\\temp\\dumpDepth.iff" );

		// Write all pixels back. The origin of the image (lower left)
		// is used 
		status = view.writeColorBuffer( image, 5, 5 );

		if (depthPixels)
			delete depthPixels;
		if (colorPixels)
			delete colorPixels;
	}

	// Do a simple color invert operation on all pixels
	//
	else if (thisCompute->mBufferOperation == kInvertColorBuffer)
	{
		// Optional to read as RGBA. Note that this will be slower
		// since we must swizzle the bytes around from the default
		// BGRA format.
		bool readAsRGBA = true;

		// Read the RGB values from the color buffer
		MImage image;
		status = view.readColorBuffer( image, readAsRGBA );
		if (status != MS::kSuccess)
			return;

		status = view.writeColorBuffer( image, 5, 5 );

		unsigned char *pixelPtr = (unsigned char*)image.pixels();
		if (pixelPtr)
		{
			unsigned int width, height;
			image.getSize( width, height );

			MImage image2;
			image2.create( width, height );
			unsigned char *pixelPtr2 = (unsigned char*)image2.pixels();

			unsigned int numPixels = width * height;
			for (unsigned int i=0; i < numPixels; i++)
			{
				*pixelPtr2 = (255 - *pixelPtr);	
				pixelPtr2++; pixelPtr++;
				*pixelPtr2 = (255 - *pixelPtr);	
				pixelPtr2++; pixelPtr++;
				*pixelPtr2 = (255 - *pixelPtr);	
				pixelPtr2++; pixelPtr++;
				*pixelPtr2 = 255;	
				pixelPtr2++; pixelPtr++;
			}

			// Write all pixels back. The origin of the image (lower left)
			// is used 
			status = view.writeColorBuffer( image2, 5, short(5+height/2) );
		}
	}
}
// This function should prepare system functions so that it will be faster to call them
int PrepareSystemFunctionGeneric(asCScriptFunction *func, asSSystemFunctionInterface *internal, asCScriptEngine *engine)
{
	asASSERT(internal->callConv == ICC_GENERIC_METHOD || internal->callConv == ICC_GENERIC_FUNC);

	// Calculate the size needed for the parameters
	internal->paramSize = func->GetSpaceNeededForArguments();

	// Prepare the clean up instructions for the function arguments
	internal->cleanArgs.SetLength(0);
	int offset = 0;
	for( asUINT n = 0; n < func->parameterTypes.GetLength(); n++ )
	{
		asCDataType &dt = func->parameterTypes[n];

		if( (dt.IsObject() || dt.IsFuncdef()) && !dt.IsReference() )
		{
			if (dt.IsFuncdef())
			{
				asSSystemFunctionInterface::SClean clean;
				clean.op = 0; // call release
				clean.ot = &engine->functionBehaviours;
				clean.off = short(offset);
				internal->cleanArgs.PushLast(clean);
			}
			else if( dt.GetTypeInfo()->flags & asOBJ_REF )
			{
				asSTypeBehaviour *beh = &dt.GetTypeInfo()->CastToObjectType()->beh;
				asASSERT( (dt.GetTypeInfo()->flags & asOBJ_NOCOUNT) || beh->release );
				if( beh->release )
				{
					asSSystemFunctionInterface::SClean clean;
					clean.op  = 0; // call release
					clean.ot  = dt.GetTypeInfo()->CastToObjectType();
					clean.off = short(offset);
					internal->cleanArgs.PushLast(clean);
				}
			}
			else
			{
				asSSystemFunctionInterface::SClean clean;
				clean.op  = 1; // call free
				clean.ot  = dt.GetTypeInfo()->CastToObjectType();
				clean.off = short(offset);

				// Call the destructor then free the memory
				asSTypeBehaviour *beh = &dt.GetTypeInfo()->CastToObjectType()->beh;
				if( beh->destruct )
					clean.op = 2; // call destruct, then free

				internal->cleanArgs.PushLast(clean);
			}
		}

		if( dt.IsObject() && !dt.IsObjectHandle() && !dt.IsReference() )
			offset += AS_PTR_SIZE;
		else
			offset += dt.GetSizeOnStackDWords();
	}

	return 0;
}
bool AuxPlayerIndex::BuildPacket(unsigned char *buffer, long &index)
{
    if (!(Flags[0] & 0x02))
    {
        return false;
    }

    index = 0;

    AddData(buffer, u32(0), index);
    AddData(buffer, short(0), index);
    AddData(buffer, char(1), index);

    AddFlags(Flags, sizeof(Flags), buffer, index);

    if (Flags[0] & 0x10)	//ExtendedFlags[2] & 0x40
    {
        AddData(buffer, Data.Credits, index);
    }

    if (Flags[0] & 0x20)	//ExtendedFlags[2] & 0x80
    {
        AddData(buffer, Data.XPDebt, index);
    }

    if (Flags[0] & 0x40)	//ExtendedFlags[3] & 0x01
    {
        SecureInv.BuildPacket(buffer, index);
    }

    if (Flags[0] & 0x80)	//ExtendedFlags[3] & 0x02
    {
        VendorInv.BuildPacket(buffer, index);
    }

    if (Flags[1] & 0x01)	//ExtendedFlags[3] & 0x04
    {
        RewardInv.BuildPacket(buffer, index);
    }

    if (Flags[1] & 0x02)	//ExtendedFlags[3] & 0x08
    {
        OverflowInv.BuildPacket(buffer, index);
    }

    if (Flags[1] & 0x04)	//ExtendedFlags[3] & 0x10
    {
        RPGInfo.BuildPacket(buffer, index);
    }

    if (Flags[1] & 0x08)	//ExtendedFlags[3] & 0x20
    {
        AddString(buffer, Data.CommunityEventFlags, index);
    }

    if (Flags[1] & 0x10)	//ExtendedFlags[3] & 0x40
    {
        AddData(buffer,Data.MusicID,index);
    }

    if (Flags[1] & 0x20)	//ExtendedFlags[3] & 0x80
    {
        Missions.BuildPacket(buffer, index);
    }

    if (Flags[1] & 0x40)	//ExtendedFlags[4] & 0x01
    {
        Reputation.BuildPacket(buffer, index);
    }

    if (Flags[1] & 0x80)	//ExtendedFlags[4] & 0x02
    {
        AddData(buffer, Data.PIPAvatarID, index);
    }

    if (Flags[2] & 0x01)	//ExtendedFlags[4] & 0x04
    {
        AddString(buffer, Data.RegistrationStarbase, index);
    }

    if (Flags[2] & 0x02)	//ExtendedFlags[4] & 0x08
    {
        AddString(buffer, Data.RegistrationStarbaseSector, index);
    }

    if (Flags[2] & 0x04)	//ExtendedFlags[4] & 0x10
    {
        AddString(buffer, Data.SectorName, index);
    }

    if (Flags[2] & 0x08)	//ExtendedFlags[4] & 0x20
    {
        AddData(buffer, Data.SectorNum, index);
    }

    if (Flags[2] & 0x10)	//ExtendedFlags[4] & 0x40
    {
        AddData(buffer, Data.ClientSendUITriggers ,index);
    }

    if (Flags[2] & 0x20)	//ExtendedFlags[4] & 0x80
    {
        GroupInfo.BuildPacket(buffer, index);
    }

    *((short *) &buffer[4]) = short(index - 6);

    memset(Flags,0,sizeof(Flags));

    return true;
}
Beispiel #15
0
LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
	bool bActivating;

	switch(msg)
	{	
		case WM_CREATE: 
			return FALSE;
		
		case WM_PAINT:
			if(pHGE->pD3D && pHGE->procRenderFunc && pHGE->bWindowed) pHGE->procRenderFunc();
			break;

		case WM_DESTROY:
			PostQuitMessage(0);
			return FALSE;

/*
		case WM_ACTIVATEAPP:
			bActivating = (wparam == TRUE);
			if(pHGE->pD3D && pHGE->bActive != bActivating) pHGE->_FocusChange(bActivating);
			return FALSE;
*/
		case WM_ACTIVATE:
			// tricky: we should catch WA_ACTIVE and WA_CLICKACTIVE,
			// but only if HIWORD(wParam) (fMinimized) == FALSE (0)
			bActivating = (LOWORD(wparam) != WA_INACTIVE) && (HIWORD(wparam) == 0);
			if(pHGE->pD3D && pHGE->bActive != bActivating) pHGE->_FocusChange(bActivating);
			return FALSE;


		case WM_SETCURSOR:
			if(pHGE->bActive && LOWORD(lparam)==HTCLIENT && pHGE->bHideMouse) SetCursor(NULL);
			else SetCursor(LoadCursor(NULL, IDC_ARROW));
			return FALSE;

		case WM_SYSKEYDOWN:
			if(wparam == VK_F4)
			{
				if(pHGE->procExitFunc && !pHGE->procExitFunc()) return FALSE;
				return DefWindowProc(hwnd, msg, wparam, lparam);
			}
			else if(wparam == VK_RETURN)
			{
				pHGE->System_SetState(HGE_WINDOWED, !pHGE->System_GetState(HGE_WINDOWED));
				return FALSE;
			}
			else
			{
				pHGE->_BuildEvent(INPUT_KEYDOWN, wparam, HIWORD(lparam) & 0xFF, (lparam & 0x40000000) ? HGEINP_REPEAT:0, -1, -1);
				return FALSE;
			}

		case WM_KEYDOWN:
			pHGE->_BuildEvent(INPUT_KEYDOWN, wparam, HIWORD(lparam) & 0xFF, (lparam & 0x40000000) ? HGEINP_REPEAT:0, -1, -1);
			return FALSE;
		case WM_SYSKEYUP:
			pHGE->_BuildEvent(INPUT_KEYUP, wparam, HIWORD(lparam) & 0xFF, 0, -1, -1);
			return FALSE;
		case WM_KEYUP:
			pHGE->_BuildEvent(INPUT_KEYUP, wparam, HIWORD(lparam) & 0xFF, 0, -1, -1);
			return FALSE;

		case WM_LBUTTONDOWN:
			SetFocus(hwnd);
			pHGE->_BuildEvent(INPUT_MBUTTONDOWN, HGEK_LBUTTON, 0, 0, LOWORDINT(lparam), HIWORDINT(lparam));
			return FALSE;
		case WM_MBUTTONDOWN:
			SetFocus(hwnd);
			pHGE->_BuildEvent(INPUT_MBUTTONDOWN, HGEK_MBUTTON, 0, 0, LOWORDINT(lparam), HIWORDINT(lparam));
			return FALSE;
		case WM_RBUTTONDOWN:
			SetFocus(hwnd);
			pHGE->_BuildEvent(INPUT_MBUTTONDOWN, HGEK_RBUTTON, 0, 0, LOWORDINT(lparam), HIWORDINT(lparam));
			return FALSE;

		case WM_LBUTTONDBLCLK:
			pHGE->_BuildEvent(INPUT_MBUTTONDOWN, HGEK_LBUTTON, 0, HGEINP_REPEAT, LOWORDINT(lparam), HIWORDINT(lparam));
			return FALSE;
		case WM_MBUTTONDBLCLK:
			pHGE->_BuildEvent(INPUT_MBUTTONDOWN, HGEK_MBUTTON, 0, HGEINP_REPEAT, LOWORDINT(lparam), HIWORDINT(lparam));
			return FALSE;
		case WM_RBUTTONDBLCLK:
			pHGE->_BuildEvent(INPUT_MBUTTONDOWN, HGEK_RBUTTON, 0, HGEINP_REPEAT, LOWORDINT(lparam), HIWORDINT(lparam));
			return FALSE;

		case WM_LBUTTONUP:
			pHGE->_BuildEvent(INPUT_MBUTTONUP, HGEK_LBUTTON, 0, 0, LOWORDINT(lparam), HIWORDINT(lparam));
			return FALSE;
		case WM_MBUTTONUP:
			pHGE->_BuildEvent(INPUT_MBUTTONUP, HGEK_MBUTTON, 0, 0, LOWORDINT(lparam), HIWORDINT(lparam));
			return FALSE;
		case WM_RBUTTONUP:
			pHGE->_BuildEvent(INPUT_MBUTTONUP, HGEK_RBUTTON, 0, 0, LOWORDINT(lparam), HIWORDINT(lparam));
			return FALSE;

		case WM_MOUSEMOVE:
			pHGE->_BuildEvent(INPUT_MOUSEMOVE, 0, 0, 0, LOWORDINT(lparam), HIWORDINT(lparam));
			return FALSE;
		case 0x020A: // WM_MOUSEWHEEL, GET_WHEEL_DELTA_WPARAM(wparam);
			pHGE->_BuildEvent(INPUT_MOUSEWHEEL, short(HIWORD(wparam))/120, 0, 0, LOWORDINT(lparam), HIWORDINT(lparam));
			return FALSE;

		case WM_SIZE:
			if(pHGE->pD3D && wparam==SIZE_RESTORED) pHGE->_Resize(LOWORD(lparam), HIWORD(lparam));
			//return FALSE;
			break;

		case WM_SYSCOMMAND:
			if(wparam==SC_CLOSE)
			{
				if(pHGE->procExitFunc && !pHGE->procExitFunc()) return FALSE;
				pHGE->bActive=false;
				return DefWindowProc(hwnd, msg, wparam, lparam);
			}
			break;
	}

	return DefWindowProc(hwnd, msg, wparam, lparam);
}
Beispiel #16
0
string the_short() {
    return short();
}
 short a2(int i) {return short(i+1);}
Beispiel #18
0
 static short rateFromMode(const DisplayMode* mode)
 {
     return short(qRound(mode->refreshRate));
 }
inline void __TBB_get_cpu_ctl_env ( __TBB_cpu_ctl_env_t* fe ) {
    fe->x87cw = short(_control87(0, 0) & _MCW_RC) << 2;
    fe->mxcsr = _mm_getcsr();
}
Beispiel #20
0
TEST(VariantTest, toShort)
{
  Avogadro::Core::Variant variant(short(4));
  EXPECT_EQ(variant.toShort(), short(4));
}
Beispiel #21
0
static short ExecDLL(FARPROC fp, BYTE ret_type, ATOMID arg_types,
                     ARGLIST args, BOOL bCCall)
{
    struct StackStruct stack;
    char strbuf[MAXSTRBUF];
    int strptr = 0;
    ATOMID fname = CAR(args);
    int i, len, count;
    int stackptr = 0;
    short (*ret)();
    char argstr[MAXARGNUM];
    
#ifdef MAC
    return TRUE;
#else

    if (!arg_types) 
        len = 0;
    else 
    {
        KppGetAtomName(arg_types, argstr, MAXARGNUM);
        len = strlen(argstr);
    }
        
    count = KppArgCount(args);
    
    if (len != count)
    {
        error(len < count ? IDE_TOOMANYARGS : IDE_MISSINGARGS,
              fname, NULL, NULL);
        return NULL;
    }
        
    ret = converters[ret_type].Return;
    args += CDR(args);
        
    for (i = 0; i < len; i++)
        stackptr += converters[argstr[i] - 1].Size;
    
    if (stackptr > MAXSTACKSIZE)
    {
        error(IDE_BUFSPACE, fname, NULL, NULL);
        return NULL;
    }
        
    if (bCCall)
        stackptr = 0;
    for (i = 0; i < len; i++) {
        if (!bCCall)
            stackptr -= converters[argstr[i] - 1].Size;

        if (converters[argstr[i] - 1].Convert && 
            !((*converters[argstr[i] - 1].Convert)(args, &stack.buf[stackptr],
                                                   &strbuf[strptr], &strptr)))
            return NULL;

        args += CDR(args);
        
        if (bCCall)
            stackptr += converters[argstr[i] - 1].Size;
    }

    if (ret_type > SHORTINDEX)
    {
        DWORD (W_EXPORT *fpstack)(struct StackStruct);
        DWORD dword;
        
        fpstack = (DWORD (W_EXPORT *)(struct StackStruct)) fp;
        dword = DwordDLLCall(fpstack, stack, bCCall);
        
        return (*(short (*)(DWORD)) ret)(dword);
    }
    else if (ret_type > DOUBLEINDEX)
    {
        WORD (W_EXPORT *fpstack)(struct StackStruct);
        WORD word;
        
        fpstack = (WORD (W_EXPORT *)(struct StackStruct)) fp;
        word = WordDLLCall(fpstack, stack, bCCall);
        
        return (*(short (*)(WORD)) ret)(word);
    }
#ifdef __BORLANDC__
    else if (ret_type == MSCDBLINDEX)
    {
        double _ss * (FAR PASCAL *dfpstack)(struct StackStruct,
                                            double _ss *dd);
        double value;
        
        dfpstack = fp;
        value = MSCDblDLLCall(dfpstack, stack, bCCall);
        
        return (*(short (*)(double)) ret)(value);
    }
Beispiel #22
0
void PoleZeroChart::paintContents (Graphics& g)
{
  Colour cPole (0xd0ff0000);
  Colour cZero (0xd02020ff);
	
  Rectangle<int> bounds = getLocalBounds();

  short size = short ((jmin (getWidth(), getHeight()) + 2) / 3);

  // scale the graph down if the pole/zeroes lie outside the unit disc
  AffineTransform t = AffineTransform::identity;

  {
    float margin = 0.2f;
    if (m_max > 1 + margin)
    {
      t = t.scaled (float(1/(m_max-margin)), float(1/(m_max-margin)));
    }
  }

  t = t.scaled (float(size), -float(size));
  t = t.translated (float(bounds.getCentreX()), float(bounds.getCentreY()));

	g.setColour (m_cAxis);
  {
    Point<float> p = Point<float>(100000, 0).transformedBy (t);
    g.drawLine (-p.getX(), p.getY(), p.getX(), p.getY(), 1);
  }
  {
    Point<float> p = Point<float>(0, 100000).transformedBy (t);
    g.drawLine (p.getX(), -p.getY(), p.getX(), p.getY(), 1);
  }
  {
    Point<float> p0 = Point<float>(-1, -1).transformedBy (t);
    Point<float> p1 = Point<float>( 1,  1).transformedBy (t);
    g.drawEllipse (p0.getX(), p0.getY(),
                   p1.getX()-p0.getX(), p1.getY()-p0.getY(), 1);
  }

  const float r = 3.5f;

  for (size_t i = 0; i < m_vpz.size(); ++i)
  {
    const Dsp::PoleZeroPair& pzp = m_vpz[i];

    if (!pzp.is_nan())
    {
      {
        Point<float> p (float(pzp.poles.first.real()),
                        float(pzp.poles.first.imag()));
        p = p.transformedBy (t);
        g.setColour (cPole);
        g.drawLine (p.getX()-r, p.getY()-r, p.getX()+r, p.getY()+r);
        g.drawLine (p.getX()+r, p.getY()-r, p.getX()-r, p.getY()+r);
      }

      {
        Point<float> p (float(pzp.zeros.first.real()),
                        float(pzp.zeros.first.imag()));
        p = p.transformedBy (t);
        g.setColour (cZero);
    	  g.drawEllipse (p.getX()-r, p.getY()-r, 2*r, 2*r, 1);
      }

      if (!pzp.isSinglePole())
      {
        {
          Point<float> p (float(pzp.poles.second.real()),
                          float(pzp.poles.second.imag()));
          p = p.transformedBy (t);
          g.setColour (cPole);
          g.drawLine (p.getX()-r, p.getY()-r, p.getX()+r, p.getY()+r);
          g.drawLine (p.getX()+r, p.getY()-r, p.getX()-r, p.getY()+r);
        }

        {
          Point<float> p (float(pzp.zeros.second.real()),
                          float(pzp.zeros.second.imag()));
          p = p.transformedBy (t);
          g.setColour (cZero);
    	    g.drawEllipse (p.getX()-r, p.getY()-r, 2*r, 2*r, 1);
        }
      }
    }
  }
}
Beispiel #23
0
inline short SHORT(float x)
{
	if(x < -32767.0f) return -32767;
	if(x > 32767.0f) return 32767;
	return short(x);
}
Beispiel #24
0
static bool Configure(SoundTemplate &self, const tinyxml2::XMLElement *element, unsigned int id)
{
	const char *name = element->Attribute("name");
	if (name == NULL)
		return false;

#if defined(USE_BASS)

	// load sound file
	HSAMPLE handle = BASS_SampleLoad(false, name, 0, 0, 1, BASS_SAMPLE_MONO);
	if (!handle)
	{
		DebugPrint("error loading sound file \"%s\": %s\n", name, BASS_ErrorGetString());
		return false;
	}

	// get sample info
	BASS_SAMPLE info;
	BASS_SampleGetInfo(handle, &info);

	// allocate space for data
	self.Reserve(info.length / info.chans);

	// set frequency
	self.mFrequency = info.freq;

	// if converting format...
	if ((info.chans > 1) || (info.flags & BASS_SAMPLE_8BITS))
	{
		// get sample data
		void *buf = _alloca(info.length);
		BASS_SampleGetData(handle, buf);

		// if converting from 8-bit...
		int accum = 0;
		if (info.flags & BASS_SAMPLE_8BITS)
		{
			for (unsigned int in = 0, samp = 0; in < info.length; ++in)
			{
				accum += static_cast<unsigned char *>(buf)[in];
				if (++samp >= info.chans)
				{
					self.Append(short(accum * 257 / samp - 32768));
					accum = 0;
					samp = 0;
				}
			}
		}
		else
		{
			for (unsigned int in = 0, samp = 0; in < info.length / sizeof(short); ++in)
			{
				accum += static_cast<short *>(buf)[in];
				if (++samp >= info.chans)
				{
					self.Append(short(accum / samp));
					accum = 0;
					samp = 0;
				}
			}
		}
	}
	else
	{
		// copy sound data
		BASS_SampleGetData(handle, static_cast<short *>(self.mData) + self.mLength);
	}

	// free loaded data
	BASS_SampleFree(handle);

#elif defined(USE_SDL_MIXER)

	// load sound file
	Mix_Chunk *loadchunk = Mix_LoadWAV(name);
	if (!loadchunk)
	{
		DebugPrint("error loading sound file \"%s\": %s\n", name, Mix_GetError());
		return false;
	}

	// copy sound data
	self.mSize = self.mLength * sizeof(short) + loadchunk->alen;
	self.mData = realloc(self.mData, self.mSize);
	memcpy(static_cast<short *>(self.mData) + self.mLength, loadchunk->abuf, loadchunk->alen);
	self.mLength = self.mSize / sizeof(short);

	// free loaded data
	Mix_FreeChunk(loadchunk);

#elif defined(USE_SDL)

	// load wave file data
	SDL_AudioSpec wave;
	Uint8 *data;
	Uint32 dlen;
	if ( !SDL_LoadWAV(name, &wave, &data, &dlen) )
	{
		DebugPrint("error loading sound file \"%s\": %s\n", name, SDL_GetError());
		return false;
	}

	// build audio conversion
	SDL_AudioCVT cvt;
	SDL_BuildAudioCVT(&cvt, wave.format, wave.channels, wave.freq,
							AUDIO_S16,   1,             AUDIO_FREQUENCY);

	// append sound data
	self.mSize = self.mLength * sizeof(short) + dlen * cvt.len_mult;
	self.mData = realloc(self.mData, self.mSize);
	memcpy(static_cast<short *>(self.mData) + self.mLength, data, dlen);
	cvt.buf = reinterpret_cast<unsigned char *>(static_cast<short *>(mData) + mLength);
	cvt.len = dlen;

	// convert to final format
	SDL_ConvertAudio(&cvt);
	self.mLength += cvt.len_cvt / sizeof(short);
	self.mSize = self.mLength * sizeof(short);
	self.mData = realloc(self.mData, self.mSize);

	// release wave file data
	SDL_FreeWAV(data);

#endif

	return true;
}
Beispiel #25
0
// This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
void wxApp::MacCreateKeyEvent( wxKeyEvent& event, wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey , wxChar uniChar )
{
#if wxOSX_USE_CARBON
    short keycode, keychar ;

    keychar = short(keymessage & charCodeMask);
    keycode = short(keymessage & keyCodeMask) >> 8 ;
    if ( !(event.GetEventType() == wxEVT_CHAR) && (modifiers & (controlKey | shiftKey | optionKey) ) )
    {
        // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
        // and look at the character after
#ifdef __LP64__
        // TODO new implementation using TextInputSources
#else
        UInt32 state = 0;
        UInt32 keyInfo = KeyTranslate((Ptr)GetScriptManagerVariable(smKCHRCache), ( modifiers & (~(controlKey | shiftKey | optionKey))) | keycode, &state);
        keychar = short(keyInfo & charCodeMask);
#endif
    }

    long keyval = wxMacTranslateKey(keychar, keycode) ;
    if ( keyval == keychar && ( event.GetEventType() == wxEVT_KEY_UP || event.GetEventType() == wxEVT_KEY_DOWN ) )
        keyval = wxToupper( keyval ) ;

    // Check for NUMPAD keys.  For KEY_UP/DOWN events we need to use the
    // WXK_NUMPAD constants, but for the CHAR event we want to use the
    // standard ascii values
    if ( event.GetEventType() != wxEVT_CHAR )
    {
        if (keyval >= '0' && keyval <= '9' && keycode >= 82 && keycode <= 92)
        {
            keyval = (keyval - '0') + WXK_NUMPAD0;
        }
        else if (keycode >= 65 && keycode <= 81)
        {
            switch (keycode)
            {
            case 76 :
                keyval = WXK_NUMPAD_ENTER;
                break;

            case 81:
                keyval = WXK_NUMPAD_EQUAL;
                break;

            case 67:
                keyval = WXK_NUMPAD_MULTIPLY;
                break;

            case 75:
                keyval = WXK_NUMPAD_DIVIDE;
                break;

            case 78:
                keyval = WXK_NUMPAD_SUBTRACT;
                break;

            case 69:
                keyval = WXK_NUMPAD_ADD;
                break;

            case 65:
                keyval = WXK_NUMPAD_DECIMAL;
                break;
            default:
                break;
            }
        }
    }

    event.m_shiftDown = modifiers & shiftKey;
    event.m_controlDown = modifiers & controlKey;
    event.m_altDown = modifiers & optionKey;
    event.m_metaDown = modifiers & cmdKey;
    event.m_keyCode = keyval ;
#if wxUSE_UNICODE
    event.m_uniChar = uniChar ;
#endif

    event.m_rawCode = keymessage;
    event.m_rawFlags = modifiers;
    event.m_x = wherex;
    event.m_y = wherey;
    event.SetTimestamp(when);
    event.SetEventObject(focus);
#else
    wxUnusedVar(event);
    wxUnusedVar(focus);
    wxUnusedVar(keymessage);
    wxUnusedVar(modifiers);
    wxUnusedVar(when);
    wxUnusedVar(wherex);
    wxUnusedVar(wherey);
    wxUnusedVar(uniChar);
#endif
}
OSStatus			AUCarbonViewBase::CreateCarbonView(AudioUnit inAudioUnit, WindowRef inWindow, ControlRef inParentControl, const Float32Point &inLocation, const Float32Point &inSize, ControlRef &outParentControl)
{
#if !__LP64__
	mEditAudioUnit = inAudioUnit;
	mCarbonWindow = inWindow;

	WindowAttributes attributes;
	verify_noerr(GetWindowAttributes(mCarbonWindow, &attributes));
	mCompositWindow = (attributes & kWindowCompositingAttribute) != 0;

	Rect area;
	area.left = short(inLocation.x); area.top = short(inLocation.y);
	area.right = short(area.left + inSize.x); area.bottom = short(area.top + inSize.y);
	OSStatus err = ::CreateUserPaneControl(inWindow, &area, 
						kControlSupportsEmbedding,
						&mCarbonPane);	// subclass can resize mCarbonPane to taste
	verify_noerr(err);
	if (err) return err;
	outParentControl = mCarbonPane;
	
	// register for mouse-down in our pane -- we want to clear focus
	EventTypeSpec paneEvents[] = {
		{ kEventClassControl, kEventControlClick }
	};
	WantEventTypes(GetControlEventTarget(mCarbonPane), GetEventTypeCount(paneEvents), paneEvents);
	
	if (IsCompositWindow()) {
		verify_noerr(::HIViewAddSubview(inParentControl, mCarbonPane));
		mXOffset = 0;
		mYOffset = 0;
	}
	else {
		verify_noerr(::EmbedControl(mCarbonPane, inParentControl));
		mXOffset = inLocation.x;
		mYOffset = inLocation.y;
	}
	mBottomRight.h = mBottomRight.v = 0;
	
	SizeControl(mCarbonPane, 0, 0);
	if (err = CreateUI(mXOffset, mYOffset))
		return err;

	// we should only resize the control if a subclass has embedded
	// controls in this AND this is done with the EmbedControl call below
	// if mBottomRight is STILL equal to zero, then that wasn't done
	// so don't size the control
	Rect paneBounds;
	GetControlBounds(mCarbonPane, &paneBounds);
	// only resize mCarbonPane if it has not already been resized during CreateUI
	if ((paneBounds.top == paneBounds.bottom) && (paneBounds.left == paneBounds.right)) {
		if (mBottomRight.h != 0 && mBottomRight.v != 0)
			SizeControl(mCarbonPane, (short) (mBottomRight.h - mXOffset), (short) (mBottomRight.v - mYOffset));
	}

	if (IsCompositWindow()) {
		// prepare for handling scroll-events
		EventTypeSpec scrollEvents[] = {
			{ kEventClassScrollable, kEventScrollableGetInfo },
			{ kEventClassScrollable, kEventScrollableScrollTo }
		};
		
		WantEventTypes(GetControlEventTarget(mCarbonPane), GetEventTypeCount(scrollEvents), scrollEvents);
	
		mCurrentScrollPoint.x = mCurrentScrollPoint.y = 0.0f;
	}
	
	return err;
#else
	return noErr;
#endif
}
Beispiel #27
0
int CMyDatabase::ReadStationsFromTable( CDatabase &m_Database)
{


	CRecordset       m_RS( &m_Database );
	short nFields     = 0;
	int StationCount  = 0;
	CString mSQL;

	
	try
	{

		if ( m_LocationFilter.IsEmpty() )
			mSQL.Format( "SELECT * FROM DOCUGATE_GENERAL_CTLUNIT" );
		else
			mSQL.Format( "SELECT * FROM DOCUGATE_GENERAL_CTLUNIT WHERE CTLUNIT_LOCATION = '%s'",m_LocationFilter );
	
		m_RS.Open( CRecordset::forwardOnly, mSQL); //_T( "SELECT * FROM DOCUGATE_GENERAL_CTLUNIT" ) );
		nFields = m_RS.GetODBCFieldCount( );

		while( !m_RS.IsEOF() )
		{

			   CString		  varData;
			   CODBCFieldInfo varInfo;

			   for( short index = 0; index < nFields; index++ )
			   {
						m_RS.GetFieldValue    ( short(index), varData );
						m_RS.GetODBCFieldInfo ( short(index), varInfo );

						if( varInfo.m_strName.CompareNoCase("CTLUNIT_GUID") == 0 )
					         strncpy(Stations[StationCount].UnitGUID,varData,51);

						if( varInfo.m_strName.CompareNoCase("CTLUNIT_IP") == 0 )
					         strncpy(Stations[StationCount].UnitAddress,varData,50);
	
						else if( varInfo.m_strName.CompareNoCase("CTLUNIT_PORT_NO") == 0 )
					         strncpy(Stations[StationCount].UnitPort,varData,10);
					
						else if( varInfo.m_strName.CompareNoCase("CTLUNIT_REQ_CLIENT") == 0 )
					         strncpy(Stations[StationCount].ReqCopyClient,varData,5);
	
						else if( varInfo.m_strName.CompareNoCase("CTLUNIT_REQ_MATTER") == 0 )
					         strncpy(Stations[StationCount].ReqCopyMatter,varData,5);
					
						else if( varInfo.m_strName.CompareNoCase("CTLUNIT_CONN_RESET") == 0 )
					         strncpy(Stations[StationCount].IdleReset,varData,10);

						else if( varInfo.m_strName.CompareNoCase("CTLUNIT_COPYPIN_ENABLED") == 0 )
					         strncpy(Stations[StationCount].ReqPin,varData,5);

						else if( varInfo.m_strName.CompareNoCase("CTLUNIT_KEYBRD_MODE") == 0 )
					         strncpy(Stations[StationCount].Keyboard,varData,10);

						else if( varInfo.m_strName.CompareNoCase("CTLUNIT_PULSE_IDLE_MIN") == 0 )
					         strncpy(Stations[StationCount].PulseIdle,varData,10);
			   }

			Stations[StationCount].UnitActive = 1;
			Stations[StationCount].UnitConnected = 0;
	
			StationCount++;
		    m_RS.MoveNext( );
		}
	
		if ( m_RS.IsOpen() )
			 m_RS.Close();
	}
	catch( CDBException *e)
	{

		CString Message;
		Message.Format("CMyDatabase::GetAccount(%s)",e->m_strError);
		WriteLog(Message,"");
		e->Delete();
	}

	return StationCount;
}
Beispiel #28
0
unsigned short CMath::GetAngle(int x, int y)
{
   short result = -1;

   if (x == 0) {
      if (y < 0) {
         result = 270;
      } else if (0 < y) {
         result = 90;
      } else {
         result = 0;
      }
   } else if (y == 0) {
      if (x < 0) {
         result = 180;
      } else {
         result = 0;
      }
   } else {
      int correction;

      if (x < 0) {
         if (y < 0) {
            x = -x;
            y = -y;
            correction = 180;
         } else {
            const int old_x = x;
            x = y;
            y = -old_x;
            correction = 90;
         }
      } else {
         if (y < 0) {
            const int old_x = x;
            x = -y;
            y = old_x;
            correction = 270;
         } else {
            correction = 0;
         }
      }

      //assert(0 < x);
      //assert(0 < y);
      if (x == y) {
         result = 45;
      } else {
         /*
            For y < x, this table takes quotient y * 128 / x
            (which will be 0..127)
            and tells corresponding angle 0..45
         */
         static const unsigned char quotient_to_angle[128] = {
             0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7,
             7, 8, 8, 8, 9, 9,10,10,11,11,11,12,12,13,13,14,
            14,14,15,15,16,16,16,17,17,18,18,18,19,19,20,20,
            20,21,21,22,22,22,23,23,24,24,24,25,25,25,26,26,
            26,27,27,27,28,28,29,29,29,30,30,30,31,31,31,32,
            32,32,32,33,33,33,34,34,34,35,35,35,36,36,36,36,
            37,37,37,38,38,38,38,39,39,39,39,40,40,40,40,41,
            41,41,41,42,42,42,42,43,43,43,43,44,44,44,44,45,
         };

         if (x < y) {
            const unsigned int quotient = ((unsigned int)x * 128) / (unsigned int)y;
            result = 90 - quotient_to_angle[quotient];
         } else {
            const unsigned int quotient = ((unsigned int)y * 128) / (unsigned int)x;
            result = quotient_to_angle[quotient];
         }
      }
	  result = short(result + correction);
      if (result == 360) {
         result = 0;
      }
   }
   return result;
}
Beispiel #29
0
void CEdRptDoc::GetStaticData(CRecordset &rc)
{
	if (!rc.IsOpen())
		return;

	CString csTmp;

	GV_ITEM Item;
	Item.mask = GVIF_TEXT|GVIF_FORMAT;
	Item.nFormat = DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX;	
	Item.row = m_Grid.GetRowCount() - 1;	
	Item.col = 0;
	Item.szText = "总计";
	m_Grid.SetItem(&Item);

	CString csFormat;
	CODBCFieldInfo fi;
	for (Item.col = 1; Item.col < m_ColFmt.GetSize(); Item.col++)
	{
		if (m_ColFmt[Item.col].format.IsEmpty())
		{
			rc.GetODBCFieldInfo(short(Item.col), fi);
			if (fi.m_nSQLType == SQL_NUMERIC || fi.m_nSQLType == SQL_DECIMAL)
			{
				if (fi.m_nScale == 0)
				{
					fi.m_nSQLType = SQL_INTEGER;
					csFormat.Format("%%%dd", fi.m_nPrecision);				
				}
				else
				{
					fi.m_nSQLType = SQL_FLOAT;
					csFormat.Format("%%%d.%df", fi.m_nPrecision, fi.m_nScale);				
				}
			}
		}
		else
		{
			csFormat = m_ColFmt[Item.col].format;
			if (csFormat.FindOneOf("dioux") > 0)
				fi.m_nSQLType = SQL_INTEGER;
			else if (csFormat.FindOneOf("eEfgG") > 0)
				fi.m_nSQLType = SQL_FLOAT;
			else
				fi.m_nSQLType = SQL_DATETIME;
		}

		switch(fi.m_nSQLType)
		{
		case SQL_INTEGER:
		case SQL_SMALLINT:
		case SQL_TINYINT:
		case SQL_BIGINT:
			fi.m_nSQLType = SQL_INTEGER;
			if (csFormat.IsEmpty())
				csFormat = _T("%d");
			break;

		case SQL_FLOAT:
		case SQL_REAL:
		case SQL_DOUBLE:
			fi.m_nSQLType = SQL_FLOAT;
			if (csFormat.IsEmpty())
				csFormat = _T("%f");
			break;
		default:
			break;
		}
		
		double fSum = 0.0;
		if (fi.m_nSQLType == SQL_INTEGER || fi.m_nSQLType == SQL_FLOAT)
		{
			CString csTmp;
			for (int j = 1; j < m_Grid.GetRowCount() - 1; j++)
			{
				csTmp = m_Grid.GetItemText(j, Item.col);
				fSum += atof(csTmp);
			}
		}
		
		if (fi.m_nSQLType == SQL_INTEGER)
			Item.szText.Format(csFormat, (int)fSum);
		else if (fi.m_nSQLType == SQL_FLOAT)
			Item.szText.Format(csFormat, fSum);
		else
			Item.szText = "--:--";

		Item.szText.TrimLeft();
		Item.szText.TrimRight();
		m_Grid.SetItem(&Item);	
	}
	
}
void MultiBodyConstraintFeedbackSetup::initPhysics()
{
    int upAxis = 2;
	gJointFeedbackInWorldSpace = true;
	gJointFeedbackInJointFrame = true;
	m_guiHelper->setUpAxis(upAxis);

    btVector4 colors[4] =
    {
        btVector4(1,0,0,1),
        btVector4(0,1,0,1),
        btVector4(0,1,1,1),
        btVector4(1,1,0,1),
    };
    int curColor = 0;



    

	this->createEmptyDynamicsWorld();
    m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
    m_dynamicsWorld->getDebugDrawer()->setDebugMode(
        //btIDebugDraw::DBG_DrawConstraints
        +btIDebugDraw::DBG_DrawWireframe
        +btIDebugDraw::DBG_DrawContactPoints
        +btIDebugDraw::DBG_DrawAabb
        );//+btIDebugDraw::DBG_DrawConstraintLimits);

	

    //create a static ground object
    if (1)
        {
            btVector3 groundHalfExtents(10,10,0.2);
            btBoxShape* box = new btBoxShape(groundHalfExtents);
            box->initializePolyhedralFeatures();

            m_guiHelper->createCollisionShapeGraphicsObject(box);
            btTransform start; start.setIdentity();
            btVector3 groundOrigin(-0.4f, 3.f, 0.f);
			btVector3 basePosition = btVector3(-0.4f, 3.f, 0.f);
            groundOrigin[upAxis] -=.5;
			groundOrigin[2]-=0.6;
            start.setOrigin(groundOrigin);
			btQuaternion groundOrn(btVector3(0,1,0),0.25*SIMD_PI);
		
		//	start.setRotation(groundOrn);
            btRigidBody* body =  createRigidBody(0,start,box);
			body->setFriction(0);
            btVector4 color = colors[curColor];
			curColor++;
			curColor&=3;
            m_guiHelper->createRigidBodyGraphicsObject(body,color);
        }

    {
        bool floating = false;
        bool damping = false;
        bool gyro = false;
        int numLinks = 2;
        bool spherical = false;					//set it ot false -to use 1DoF hinges instead of 3DoF sphericals
        bool canSleep = false;
        bool selfCollide = false;
          btVector3 linkHalfExtents(0.05, 0.5, 0.1);
        btVector3 baseHalfExtents(0.05, 0.5, 0.1);

        btVector3 basePosition = btVector3(-0.4f, 3.f, 0.f);
        //mbC->forceMultiDof();							//if !spherical, you can comment this line to check the 1DoF algorithm
        //init the base
        btVector3 baseInertiaDiag(0.f, 0.f, 0.f);
        float baseMass = 0.01f;

        if(baseMass)
        {
            //btCollisionShape *shape = new btSphereShape(baseHalfExtents[0]);// btBoxShape(btVector3(baseHalfExtents[0], baseHalfExtents[1], baseHalfExtents[2]));
			btCollisionShape *shape = new btBoxShape(btVector3(baseHalfExtents[0], baseHalfExtents[1], baseHalfExtents[2]));
            shape->calculateLocalInertia(baseMass, baseInertiaDiag);
            delete shape;
        }

        bool isMultiDof = true;
        btMultiBody *pMultiBody = new btMultiBody(numLinks, baseMass, baseInertiaDiag, !floating, canSleep, isMultiDof);
		
        m_multiBody = pMultiBody;
        btQuaternion baseOriQuat(0.f, 0.f, 0.f, 1.f);
	//	baseOriQuat.setEulerZYX(-.25*SIMD_PI,0,-1.75*SIMD_PI);
        pMultiBody->setBasePos(basePosition);
        pMultiBody->setWorldToBaseRot(baseOriQuat);
        btVector3 vel(0, 0, 0);
    //	pMultiBody->setBaseVel(vel);

        //init the links
        btVector3 hingeJointAxis(1, 0, 0);
        
        //y-axis assumed up
        btVector3 parentComToCurrentCom(0, -linkHalfExtents[1] * 2.f, 0);						//par body's COM to cur body's COM offset
        btVector3 currentPivotToCurrentCom(0, -linkHalfExtents[1], 0);							//cur body's COM to cur body's PIV offset
        btVector3 parentComToCurrentPivot = parentComToCurrentCom - currentPivotToCurrentCom;	//par body's COM to cur body's PIV offset

        //////
        btScalar q0 = 0.f * SIMD_PI/ 180.f;
        btQuaternion quat0(btVector3(0, 1, 0).normalized(), q0);
        quat0.normalize();
        /////

        for(int i = 0; i < numLinks; ++i)
        {
			float linkMass = i==0? 0.0001 : 1.f;
			//if (i==3 || i==2)
			//	linkMass= 1000;
			btVector3 linkInertiaDiag(0.f, 0.f, 0.f);

			btCollisionShape* shape = 0;
			if (i==0)
			{
				shape = new btBoxShape(btVector3(linkHalfExtents[0], linkHalfExtents[1], linkHalfExtents[2]));//
			} else
			{
				shape = new btSphereShape(radius);
			}
			shape->calculateLocalInertia(linkMass, linkInertiaDiag);
			delete shape;


            if(!spherical)
			{
                //pMultiBody->setupRevolute(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f), hingeJointAxis, parentComToCurrentPivot, currentPivotToCurrentCom, false);
		
				if (i==0)
				{
				pMultiBody->setupRevolute(i, linkMass, linkInertiaDiag, i - 1, 
					btQuaternion(0.f, 0.f, 0.f, 1.f), 
					hingeJointAxis, 
					parentComToCurrentPivot, 
					currentPivotToCurrentCom, false);
				} else
				{
					btVector3 parentComToCurrentCom(0, -linkHalfExtents[1], 0);						//par body's COM to cur body's COM offset
					btVector3 currentPivotToCurrentCom(0, 0, 0);							//cur body's COM to cur body's PIV offset
					//btVector3 parentComToCurrentPivot = parentComToCurrentCom - currentPivotToCurrentCom;	//par body's COM to cur body's PIV offset


					pMultiBody->setupFixed(i, linkMass, linkInertiaDiag, i - 1, 
					btQuaternion(0.f, 0.f, 0.f, 1.f), 
					parentComToCurrentPivot, 
					currentPivotToCurrentCom, false);
				}
					
				//pMultiBody->setupFixed(i,linkMass,linkInertiaDiag,i-1,btQuaternion(0,0,0,1),parentComToCurrentPivot,currentPivotToCurrentCom,false);
		
			}
            else
			{
                //pMultiBody->setupPlanar(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f)/*quat0*/, btVector3(1, 0, 0), parentComToCurrentPivot*2, false);
                pMultiBody->setupSpherical(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f), parentComToCurrentPivot, currentPivotToCurrentCom, false);
			}
        }

        pMultiBody->finalizeMultiDof();

		//for (int i=pMultiBody->getNumLinks()-1;i>=0;i--)//
			for (int i=0;i<pMultiBody->getNumLinks();i++)
		{
			btMultiBodyJointFeedback* fb = new btMultiBodyJointFeedback();
			pMultiBody->getLink(i).m_jointFeedback = fb;
			m_jointFeedbacks.push_back(fb);
			//break;
		}
        btMultiBodyDynamicsWorld* world = m_dynamicsWorld;

        ///
        world->addMultiBody(pMultiBody);
        btMultiBody* mbC = pMultiBody;
        mbC->setCanSleep(canSleep);
        mbC->setHasSelfCollision(selfCollide);
        mbC->setUseGyroTerm(gyro);
        //
        if(!damping)
        {
            mbC->setLinearDamping(0.f);
            mbC->setAngularDamping(0.f);
        }else
        {	mbC->setLinearDamping(0.1f);
            mbC->setAngularDamping(0.9f);
        }
        //
    	m_dynamicsWorld->setGravity(btVector3(0,0,-10));

        //////////////////////////////////////////////
        if(0)//numLinks > 0)
        {
            btScalar q0 = 45.f * SIMD_PI/ 180.f;
            if(!spherical)
                if(mbC->isMultiDof())
                    mbC->setJointPosMultiDof(0, &q0);
                else
                    mbC->setJointPos(0, q0);
            else
            {
                btQuaternion quat0(btVector3(1, 1, 0).normalized(), q0);
                quat0.normalize();
                mbC->setJointPosMultiDof(0, quat0);
            }
        }
        ///

        btAlignedObjectArray<btQuaternion> world_to_local;
        world_to_local.resize(pMultiBody->getNumLinks() + 1);

        btAlignedObjectArray<btVector3> local_origin;
        local_origin.resize(pMultiBody->getNumLinks() + 1);
        world_to_local[0] = pMultiBody->getWorldToBaseRot();
        local_origin[0] = pMultiBody->getBasePos();
        double friction = 1;
        {

        //	float pos[4]={local_origin[0].x(),local_origin[0].y(),local_origin[0].z(),1};
            float quat[4]={-world_to_local[0].x(),-world_to_local[0].y(),-world_to_local[0].z(),world_to_local[0].w()};


            if (1)
            {
                btCollisionShape* shape = new btBoxShape(btVector3(baseHalfExtents[0],baseHalfExtents[1],baseHalfExtents[2]));//new btSphereShape(baseHalfExtents[0]);
                m_guiHelper->createCollisionShapeGraphicsObject(shape);

                btMultiBodyLinkCollider* col= new btMultiBodyLinkCollider(pMultiBody, -1);
                col->setCollisionShape(shape);

                btTransform tr;
                tr.setIdentity();
//if we don't set the initial pose of the btCollisionObject, the simulator will do this 
				//when syncing the btMultiBody link transforms to the btMultiBodyLinkCollider
               
                tr.setOrigin(local_origin[0]);
				btQuaternion orn(btVector3(0,0,1),0.25*3.1415926538);
				
                tr.setRotation(orn);
                col->setWorldTransform(tr);

				bool isDynamic = (baseMass > 0 && floating);
				short collisionFilterGroup = isDynamic? short(btBroadphaseProxy::DefaultFilter) : short(btBroadphaseProxy::StaticFilter);
				short collisionFilterMask = isDynamic? 	short(btBroadphaseProxy::AllFilter) : 	short(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);


                world->addCollisionObject(col,collisionFilterGroup,collisionFilterMask);//, 2,1+2);

                btVector3 color(0.0,0.0,0.5);
                m_guiHelper->createCollisionObjectGraphicsObject(col,color);

//                col->setFriction(friction);
                pMultiBody->setBaseCollider(col);

            }
        }


        for (int i=0; i < pMultiBody->getNumLinks(); ++i)
        {
            const int parent = pMultiBody->getParent(i);
            world_to_local[i+1] = pMultiBody->getParentToLocalRot(i) * world_to_local[parent+1];
            local_origin[i+1] = local_origin[parent+1] + (quatRotate(world_to_local[i+1].inverse() , pMultiBody->getRVector(i)));
        }


        for (int i=0; i < pMultiBody->getNumLinks(); ++i)
        {

            btVector3 posr = local_origin[i+1];
        //	float pos[4]={posr.x(),posr.y(),posr.z(),1};

            float quat[4]={-world_to_local[i+1].x(),-world_to_local[i+1].y(),-world_to_local[i+1].z(),world_to_local[i+1].w()};
			btCollisionShape* shape =0;

			if (i==0)
			{
				shape = new btBoxShape(btVector3(linkHalfExtents[0],linkHalfExtents[1],linkHalfExtents[2]));//btSphereShape(linkHalfExtents[0]);
			} else
			{
				
				shape = new btSphereShape(radius);
			}

            m_guiHelper->createCollisionShapeGraphicsObject(shape);
            btMultiBodyLinkCollider* col = new btMultiBodyLinkCollider(pMultiBody, i);

            col->setCollisionShape(shape);
            btTransform tr;
            tr.setIdentity();
            tr.setOrigin(posr);
            tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3]));
            col->setWorldTransform(tr);
     //       col->setFriction(friction);
			bool isDynamic = 1;//(linkMass > 0);
			short collisionFilterGroup = isDynamic? short(btBroadphaseProxy::DefaultFilter) : short(btBroadphaseProxy::StaticFilter);
			short collisionFilterMask = isDynamic? 	short(btBroadphaseProxy::AllFilter) : 	short(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);

			//if (i==0||i>numLinks-2)
			{
				world->addCollisionObject(col,collisionFilterGroup,collisionFilterMask);//,2,1+2);
				   btVector4 color = colors[curColor];
			curColor++;
			curColor&=3;
            m_guiHelper->createCollisionObjectGraphicsObject(col,color);


            pMultiBody->getLink(i).m_collider=col;
			}
         
        }
	int link=0;
	int targetVelocity=0.f;
	btScalar maxForce = 100000;
	 m_motor = new btMultiBodyJointMotor(pMultiBody,link,targetVelocity,maxForce);
	m_dynamicsWorld->addMultiBodyConstraint(m_motor);
    }
}