bool Average::ComputeLuminance (RenderTreeBase& renderTree, iView* view,
	                                float& averageLuminance, float& maxLuminance,
	                                float& usedColorScale)
	{
	  int W, H;
	  csRef<iDataBuffer> computeData = GetResultData (renderTree, view, W, H,
	    usedColorScale);
	  if (computeData.IsValid ())
	  {
	    const uint8* bgra = computeData->GetUint8();
	    int numPixels = W * H;
	    float totalLum = 0;
	    float maxLum = 0;
	    for (int i = 0; i < numPixels; i++)
	    {
	      int b = *bgra++;
	      int g = *bgra++;
	      int r = *bgra++;
	      int a = *bgra++;
	      totalLum += (g+a)/510.0f;
	      if (b > r)
	        maxLum = csMax (maxLum, b/255.0f);
	      else
	        maxLum = csMax (maxLum, r/255.0f);
	    }
	    
	    averageLuminance = (totalLum / numPixels) * colorScale;
	    maxLuminance = maxLum;
	    return true;
	  }
	  return false;
	}
	bool LogAverage::ComputeLuminance (RenderTreeBase& renderTree, iView* view,
	                                   float& averageLuminance, float& maxLuminance,
	                                   float& maxComponent, float& usedColorScale)
	{
	  int W, H;
	  csRef<iDataBuffer> computeData = GetResultData (renderTree, view, W, H,
	    usedColorScale);
	  if (computeData.IsValid ())
	  {
	    const float* rgba = (float*)computeData->GetData();
	    int numPixels = W * H;
	    float lumSum = 0;
	    float maxLum = 0;
	    float maxComp = 0;
	    for (int i = 0; i < numPixels; i++)
	    {
	      float r = *rgba++;
	      float g = *rgba++;
	      float b = *rgba++;
	      rgba++;
	      lumSum += g;
	      maxLum = csMax (maxLum, r);
	      maxComp = csMax (maxComp, b);
	    }
	    
	    int numOrgPixels = view->GetContext ()->GetWidth ()
	      * view->GetContext ()->GetHeight ();
	    averageLuminance = expf (1.0f/numOrgPixels * lumSum);
	    maxLuminance = maxLum;
	    maxComponent = maxComp;
	    return true;
	  }
	  return false;
	}
Пример #3
0
void csConsoleOutput::ScrollTo(int top, bool snap)
{
  CS::Threading::RecursiveMutexScopedLock lock (mutex);
  switch (top)
  {
    case csConPageUp:
      buffer->SetTopLine(csMax (0, buffer->GetTopLine() - buffer->GetPageSize()));
      break;
    case csConPageDown:
      buffer->SetTopLine(buffer->GetTopLine () + buffer->GetPageSize ());
      break;
    case csConVeryTop:
      buffer->SetTopLine(0);
      break;
    case csConVeryBottom:
      buffer->SetTopLine(buffer->GetCurLine () - buffer->GetPageSize () + 1);
      break;
    default:
      buffer->SetTopLine(top);
      break;
  }

  if ((buffer->GetCurLine () >= buffer->GetTopLine()) &&
      (buffer->GetCurLine () <= buffer->GetTopLine() + buffer->GetPageSize()))
    cy = csMax (buffer->GetCurLine () - buffer->GetTopLine (), 0);
  else
    cy = -1;
  do_snap = snap;
}
Пример #4
0
void csConditionEvaluator::SetupEvalCacheInternal (const csShaderVariableStack* stack)
{
  if (stack != 0)
  {
    if (evalCache.lastShaderVars.GetSize() != svAffectedConditions.GetSize())
    {
      evalCache.lastShaderVars.DeleteAll();
      evalCache.lastShaderVars.SetSize (svAffectedConditions.GetSize(),
	&definitelyUniqueSV);
    }
	
    for (size_t i = 0; i < svAffectedConditions.GetSize(); i++)
    {
      SVAffection& affection = svAffectedConditions[i];
      csShaderVariable* sv = (affection.svName < stack->GetSize()) ?
	(*stack)[affection.svName] : 0;
      if (evalCache.lastShaderVars[i] != sv)
      {
	if (affection.affectedConditions.GetSize() != evalCache.condChecked.GetSize())
	{
	  /* Sometimes the affected conditions mask is bigger,
	   * sometimes the condition checked mask - the former can happen
	   * when a fallback shader or new tech is loaded that uses hitherto
	   * unknown conditions */
	  size_t newCondSize = csMax (affection.affectedConditions.GetSize(),
	    evalCache.condChecked.GetSize());
	  SetSizeFill1 (affection.affectedConditions, newCondSize);
	  evalCache.condChecked.SetSize (newCondSize);
	  evalCache.condResult.SetSize (newCondSize);
	}
	evalCache.condChecked &= affection.affectedConditions;
	evalCache.lastShaderVars[i] = sv;
      }
    }
    /* Checking against last buffer value is expensive, so just mask all
       conditions depending on buffer values */
    MyBitArrayMalloc& bitarray = bufferAffectConditions;
    if (bitarray.GetSize() != evalCache.condChecked.GetSize())
    {
      size_t newCondSize = csMax (bitarray.GetSize(),
	evalCache.condChecked.GetSize());
      SetSizeFill1 (bitarray, newCondSize);
      evalCache.condChecked.SetSize (newCondSize);
      evalCache.condResult.SetSize (newCondSize);
    }
    evalCache.condChecked &= bitarray;
  }
}
static uint query_proc_cpuinfo()
{
  uint n = 0;
  FILE* f = fopen("/proc/cpuinfo", "r");
  if (f != 0)
  {
    csString line, key, val;
    char buff[ 1024 ];
    while (fgets(buff, sizeof(buff) - 1, f) != 0)
    {
      line = buff;
      size_t pos = line.Find(":");
      if (pos > 0)
      {
	key = line.Slice(0, pos);
	key.Trim();
	if (key.CompareNoCase("processor") || key.CompareNoCase("hw.ncpu"))
	{
	  val = line.Slice(pos + 1);
	  val.Trim();
	  n = csMax (static_cast<uint>(atol(val.GetData())), n+1);
	}
      }
    }
    fclose(f);
  }
  return n;
}
Пример #6
0
  void Configuration::Initialize (iConfigFile* _cfgFile)
  {
    csRef<iConfigFile> cfgFile = _cfgFile;
    if (!cfgFile.IsValid())
      cfgFile = scfQueryInterface<iConfigFile> (globalLighter->configMgr);
    
    lighterProperties.doDirectLight = cfgFile->GetBool ("lighter2.DirectLight", 
      lighterProperties.doDirectLight);
    lighterProperties.directionalLMs = cfgFile->GetBool ("lighter2.BumpLMs", 
      lighterProperties.directionalLMs);
    lighterProperties.specularDirectionMaps = cfgFile->GetBool ("lighter2.SpecMaps", 
      true) && lighterProperties.directionalLMs;
    lighterProperties.numThreads = cfgFile->GetInt ("lighter2.NumThreads", 
      lighterProperties.numThreads);
    lighterProperties.checkDupes = cfgFile->GetBool ("lighter2.CheckDupes",
      lighterProperties.checkDupes);

    lmProperties.lmDensity = cfgFile->GetFloat ("lighter2.lmDensity", 
      lmProperties.lmDensity);
    lmProperties.maxLightmapU = cfgFile->GetInt ("lighter2.maxLightmapU", 
      lmProperties.maxLightmapU);
    lmProperties.maxLightmapV = cfgFile->GetInt ("lighter2.maxLightmapV", 
      lmProperties.maxLightmapV);
    lighterProperties.saveBinaryBuffers = cfgFile->GetBool ("lighter2.binary",
      lighterProperties.saveBinaryBuffers);
   
    lmProperties.blackThreshold = cfgFile->GetFloat ("lighter2.blackThreshold", 
      lmProperties.blackThreshold);
    lmProperties.blackThreshold = csMax (lmProperties.blackThreshold,
      lightValueEpsilon); // Values lower than the LM precision don't make sense
      
    terrainProperties.maxLightmapU = cfgFile->GetInt ("lighter2.maxTerrainLightmapU", 
      lmProperties.maxLightmapU);
    terrainProperties.maxLightmapV = cfgFile->GetInt ("lighter2.maxTerrainLightmapV", 
      lmProperties.maxLightmapV);

    float normalsToleranceAngle = cfgFile->GetFloat ("lighter2.normalsTolerance", 
      1.0f);
    lmProperties.normalsTolerance = csMax (EPSILON, normalsToleranceAngle * 
      (PI / 180.0f));

    lmProperties.grayPDMaps = cfgFile->GetBool ("lighter2.grayPDMaps", 
      lmProperties.grayPDMaps);

    debugProperties.rayDebugRE =
      cfgFile->GetStr ("lighter2.debugOcclusionRays");
  }
Пример #7
0
bool psLinearMovement::InitCD (const csVector3& body, const csVector3& legs,
	const csVector3& shift, iMeshWrapper* meshWrap)
{
    mesh = meshWrap;
  
    topSize = body;
    bottomSize = legs;
    
    if (bottomSize.x * bottomSize.y > (0.8f * 1.4f + 0.1f))
        hugGround = true;
    
    intervalSize.x = csMin(topSize.x, bottomSize.x);
    intervalSize.y = csMin(topSize.y, bottomSize.y);
    intervalSize.z = csMin(topSize.z, bottomSize.z);
    
    float maxX = csMax(body.x, legs.x)+shift.x;
    float maxZ = csMax(body.z, legs.z)+shift.z;
    

    float bX2 = body.x / 2.0f;
    float bZ2 = body.z / 2.0f;
    float bYbottom = legs.y;
    float bYtop = legs.y + body.y;
    
    csBox3 top (csVector3 (-bX2, bYbottom, -bZ2) + shift,
                csVector3 (bX2, bYtop, bZ2) + shift);
    
    float lX2 = legs.x / 2.0f;
    float lZ2 = legs.z / 2.0f;
    
    csBox3 bot (csVector3 (-lX2, 0, -lZ2) + shift,
                csVector3 (lX2, 0 + legs.y, lZ2) + shift);
    
    boundingBox.Set(csVector3(-maxX / 2.0f, 0, -maxZ / 2.0f) + shift,
                    csVector3(maxX / 2.0f, bYtop, maxZ / 2.0f) + shift);

    psLinearMovement::shift = shift;
    
    cdsys = csQueryRegistry<iCollideSystem> (object_reg);
    
    if (colldet)
        delete colldet;
    
    colldet = new psCollisionDetection(object_reg);
    return colldet->Init (topSize, bottomSize, shift, mesh);
}
Пример #8
0
 static float cmax (bool u1, float v1, bool u2, float v2)
 {
     if (u1 && u2)
         return csMax (v1, v2);
     else if (u1)
         return v1;
     return v2;
 }
Пример #9
0
bool Location::CheckWithinBounds(iEngine* engine,const csVector3 &p,const iSector* sector)
{
    if(!IsRegion())
        return false;

    if(GetSector(engine) != sector)
        return false;

    // Thanks to http://astronomy.swin.edu.au/~pbourke/geometry/insidepoly/
    // for this example code.
    int counter = 0;
    size_t i,N=locs.GetSize();
    float xinters;
    csVector3 p1,p2;

    p1 = locs[0]->pos;
    for(i=1; i<=N; i++)
    {
        p2 = locs[i % N]->pos;
        if(p.z > csMin(p1.z,p2.z))
        {
            if(p.z <= csMax(p1.z,p2.z))
            {
                if(p.x <= csMax(p1.x,p2.x))
                {
                    if(p1.z != p2.z)
                    {
                        xinters = (p.z-p1.z)*(p2.x-p1.x)/(p2.z-p1.z)+p1.x;
                        if(p1.x == p2.x || p.x <= xinters)
                            counter++;
                    }
                }
            }
        }
        p1 = p2;
    }

    return (counter % 2 != 0);
}
Пример #10
0
void pawsTree::SetScrollBarMax()
{
    int width, height;

    if(layout != NULL)
    {
        layout->GetTreeSize(width, height);
        if(horizScrollBar != NULL)
        {
            if(width > screenFrame.Width())
            {
                horizScrollBar  -> SetMaxValue(csMax(0, width  - screenFrame.Width()));
                if(!horizScrollBar->IsVisible()) //as this function is called continually we have to check if
                    horizScrollBar->Show(); //the widget is already shown to avoid flickering
            }
            else
            {
                if(horizScrollBar->IsVisible())
                    horizScrollBar->Hide();
                horizScrollBar->SetMaxValue(0);
            }
        }
        if(vertScrollBar != NULL)
        {
            if(height > screenFrame.Height())
            {
                vertScrollBar   -> SetMaxValue(csMax(0, height - screenFrame.Height()));
                if(!vertScrollBar->IsVisible())
                    vertScrollBar->Show();
            }
            else
            {
                if(vertScrollBar->IsVisible())
                    vertScrollBar->Hide();
                vertScrollBar->SetMaxValue(0);
            }
        }
    }
}
Пример #11
0
void ProctexPDLight::PDMap::UpdateTiles (const TileHelper& helper)
{
  for (size_t t = 0; t < tiles.GetSize(); t++)
  {
    Tile& tile = tiles[t];
    
    csRect tileRect;
    helper.GetTileRect (t, tileRect);

    const csRect& lightInTile (nonNullAreas[t]);

    tile.tilePartX = (lightInTile.xmin - tileRect.xmin);
    tile.tilePartY = (lightInTile.ymin - tileRect.ymin);

    tile.tilePartW = csMin (lightInTile.xmax, imageX + imageW)
      - csMax (lightInTile.xmin, imageX);
    tile.tilePartH = csMin (lightInTile.ymax, imageY + imageH)
      - csMax (lightInTile.ymin, imageY);
    tile.tilePartPitch = imageW - tile.tilePartW;

    if (imageData->IsGray())
    {
      tile.tilePartData = static_cast<LumelBufferGray*> (
	  (LumelBufferBase*)imageData)->GetData()
        + (lightInTile.ymin - imageY) * imageW
        + (lightInTile.xmin - imageX);
    }
    else
    {
      tile.tilePartData = static_cast<LumelBufferRGB*> (
	  (LumelBufferBase*)imageData)->GetData()
        + (lightInTile.ymin - imageY) * imageW
        + (lightInTile.xmin - imageX);
    }
  }
  tiles.ShrinkBestFit ();
  nonNullAreas.DeleteAll ();
}
Пример #12
0
  size_t csFurData::GetControlPointsCount(float controlPointsLOD) const
  {
    if (controlPointsCount == 0)
      return 0;

    if (0.0f <= controlPointsLOD && controlPointsLOD <= 0.33f)
      return 2;
    else if (controlPointsLOD < 0.67f)
      return csMax ( (size_t)(controlPointsCount / 2), (size_t)2);
    else if (controlPointsLOD <= 1.0f)
      return controlPointsCount;

    return 0;
  }
Пример #13
0
void pawsSeqTreeNode::AddSeqWidget(pawsWidget* w, int width)
{
    csRect widgetFrame;

    widgets.PushBack(pawsSeqTreeNode_widget(w, width));

    AddChild(w);
    w->MoveTo(screenFrame.xmax+1, screenFrame.ymin);
    w->Show();

    int newWidth = width + defaultFrame.Width();
    int newHeight = csMax(w->GetDefaultFrame().Height(), defaultFrame.Height());

    SetRelativeFrameSize(newWidth, newHeight);
}
Пример #14
0
 LayerSampler (int basemap_w, int basemap_h, MaterialLayer* layer)
  : textureScale (layer->texture_scale)
 {
   float layer_needed_x = float (basemap_w) / textureScale.x;
   float layer_needed_y = float (basemap_h) / textureScale.y;
   iImage* layerImage = layer->GetImage();
   int mip_x = csFindNearestPowerOf2 (
     int (ceil (layerImage->GetWidth() / layer_needed_x)));
   int mip_y = csFindNearestPowerOf2 (
     int (ceil (layerImage->GetHeight() / layer_needed_y)));
   int mip = csMax (
     csClamp (csLog2 (mip_x), csLog2 (layerImage->GetWidth()), 0),
     csClamp (csLog2 (mip_y), csLog2 (layerImage->GetHeight()), 0));
   img = GetImageMip (layerImage, mip);
   img_w = img->GetWidth();
   img_h = img->GetHeight();
 }
Пример #15
0
void pawsScrollBar::MoveThumbToMouse()
{
    psPoint mousePos;
    int relMouseCoord,     // coordinate of mouse cursor relative to the rectangle that constraints thumb movement
        rectBegin,         // coordinate of the constraint rectangle
        rectSize,          // size of the constraint rectangle
        thumbPos;          // coordinate of thumb relative to the constraint rectangle

    int scrollBarSize = GetScrollBarSize();

    mousePos = PawsManager::GetSingleton().GetMouse()->GetPosition();
    if(horizontal)
    {
        rectBegin = screenFrame.xmin + scrollBarSize;
        relMouseCoord = mousePos.x - rectBegin;
    }
    else
    {
        rectBegin = screenFrame.ymin + scrollBarSize;
        relMouseCoord = mousePos.y - rectBegin;
    }

    rectSize = GetThumbScaleLength();

    if(mouseIsDraggingThumb)
        thumbPos = relMouseCoord - thumbDragPoint;
    else
        thumbPos = relMouseCoord - (scrollBarSize - 2*THUMB_MARGIN) / 2;
    thumbPos = csMax(thumbPos, 0);
    thumbPos = csMin(thumbPos, rectSize);

    if(horizontal)
        thumb->MoveTo(rectBegin+thumbPos, thumb->GetScreenFrame().ymin);
    else
        thumb->MoveTo(thumb->GetScreenFrame().xmin, rectBegin+thumbPos);

    currentValue = minValue + (float(thumbPos) / rectSize * (maxValue-minValue));
    if(limited)
        LimitCurrentValue();

    if(parent != NULL)
        parent->OnScroll(SCROLL_THUMB, this);
}
Пример #16
0
void csTerrainCell::UnlockHeightData ()
{
  Touch();

  minHeight = FLT_MAX;
  maxHeight = -FLT_MAX;

  for (size_t i = 0; i < heightmap.GetSize (); ++i)
  {
    minHeight = csMin (minHeight, heightmap[i]);
    maxHeight = csMax (maxHeight, heightmap[i]);
  }

  const csVector3 size01 = size * 0.1f;
  boundingBox.Set (position.x - size01.x, minHeight - size01.y, position.y - size01.z,
    position.x + size.x + size01.x, maxHeight + size01.y, position.y + size.z + size01.z);

  terrain->CellSizeUpdate (this);

  terrain->FireHeightUpdateCallbacks (this, lockedHeightRect);
}
Пример #17
0
bool psRaceInfo::Load(iResultRow &row)
{
    uid  = row.GetUInt32("id");
    name = row["name"];
    psserver->GetCacheManager()->AddCommonStringID(name);
    initialCP = row.GetUInt32("initial_cp");
    race = row.GetUInt32("race");
    helmGroup = row["helm"];
    BracerGroup = row["bracer"];
    BeltGroup = row["belt"];
    CloakGroup = row["cloak"];
    MounterAnim = row["cstr_mounter_animation"];
    psserver->GetCacheManager()->AddCommonStringID(MounterAnim);
    sex = row["sex"];
    scale = row.GetFloat("scale");
    speedModifier = row.GetFloat("speed_modifier");

    gender = psserver->GetCacheManager()->ConvertGenderString(row["sex"]);

    iResultSet* rs = db->Select("SELECT * FROM race_spawns WHERE raceid = %lu", race);

    if(!rs || rs->Count() == 0)
    {
        Error2("Race spawn points for race %d not found.", race);
        return false;
    }

    for(unsigned int i = 0 ; i < rs->Count() ; i++)
    {
        psRaceStartingLocation startingLoc;
        //prepare x,y,z and rotation of the spawn point
        startingLoc.x = (*rs)[i].GetFloat("x");
        startingLoc.y = (*rs)[i].GetFloat("y");
        startingLoc.z = (*rs)[i].GetFloat("z");
        startingLoc.yrot = (*rs)[i].GetFloat("yrot");
        //set a range used to select a random point within it from the x and z
        startingLoc.range = (*rs)[i].GetFloat("range");

        psSectorInfo* secinfo=psserver->GetCacheManager()->GetSectorInfoByID((*rs)[i].GetUInt32("sector_id"));
        if(secinfo==NULL)
        {
            Error3("Unresolvable sector id %lu in start_sector_id field of race info for race %u.  Failing!",
                   (*rs)[i].GetUInt32("sector_id"),race);
            return false;
        }

        startingLoc.sector_name = secinfo->name;

        startingLocations.Push(startingLoc);
    }

    rs->Release();

    size.x = row.GetFloat("size_x");
    size.y = row.GetFloat("size_y");
    size.z = row.GetFloat("size_z");

    // Z size and X size (width and length) need to be equal because the collision reaction system
    // does not know how to cope with rotations. An ellipsoid would be more ideal.
    size.z = size.x = csMax(size.x, size.z);

    baseRegen[PSRACEINFO_STAMINA_PHYSICAL_STILL] = row.GetFloat("base_physical_regen_still");
    baseRegen[PSRACEINFO_STAMINA_PHYSICAL_WALK]  = row.GetFloat("base_physical_regen_walk");
    baseRegen[PSRACEINFO_STAMINA_MENTAL_STILL]   = row.GetFloat("base_mental_regen_still");
    baseRegen[PSRACEINFO_STAMINA_MENTAL_WALK]    = row.GetFloat("base_mental_regen_walk");

    mesh_name = row["cstr_mesh"];
    if(!mesh_name)
    {
        Error2("Invalid 'cstr_mesh' for race '%s'\n", name.GetData());
    }
    psserver->GetCacheManager()->AddCommonStringID(mesh_name);

    base_texture_name = row["cstr_base_texture"];
    psserver->GetCacheManager()->AddCommonStringID(base_texture_name);

    // Load starting stats
    SetBaseAttribute(PSITEMSTATS_STAT_STRENGTH      ,row.GetUInt32("start_str"));
    SetBaseAttribute(PSITEMSTATS_STAT_ENDURANCE     ,row.GetUInt32("start_end"));
    SetBaseAttribute(PSITEMSTATS_STAT_AGILITY       ,row.GetUInt32("start_agi"));
    SetBaseAttribute(PSITEMSTATS_STAT_INTELLIGENCE  ,row.GetUInt32("start_int"));
    SetBaseAttribute(PSITEMSTATS_STAT_WILL          ,row.GetUInt32("start_will"));
    SetBaseAttribute(PSITEMSTATS_STAT_CHARISMA      ,row.GetUInt32("start_cha"));

    // Load natural armor
    natural_armor_id = row.GetUInt32("armor_id");

    // Load natural claws/weapons
    natural_weapon_id = row.GetUInt32("weapon_id");

    return true;
}
Пример #18
0
static float LightAttnLinear (float squaredDistance, const csVector4& c)
{
  /// linear attenuation:  * (1 - distance * inverse_radius)
  return csMax (0.0f, 1.0f - (sqrtf (squaredDistance) * c.w));
}
	bool BaseHierarchical::SetupStage (LuminanceComputeStage& stage,
					    int inputW, int inputH, int minSize,
					    iTextureHandle* inputTex,
					    iShader* computeShader)
	{
	  stage.svInput.AttachNew (new csShaderVariable (
	    svNameStringSet->Request ("tex diffuse")));
	    
	  size_t pticket;
	  CS::Graphics::RenderMeshModes modes; // Just keep defaults
	  csShaderVariableStack svstack;
    
	  {
	    PostEffectManager::Layer* tempLayer;
	    PostEffectManager::LayerInputMap inputMap;
	    inputMap.manualInput = stage.svInput;
	    tempLayer = computeFX.AddLayer (computeShader, 1, &inputMap);
	    
	    // Determine 'priority ticket' for stage
	    svstack.Setup (shaderManager->GetSVNameStringset ()->GetSize ());
	    computeFX.GetLayerRenderSVs (tempLayer, svstack);
	    pticket = computeShader->GetPrioritiesTicket (modes, svstack);
	    computeFX.RemoveLayer (tempLayer);
	  }
	  
	  int maxBlockSizeX = 16;
	  int maxBlockSizeY = 16;
	  
	  csRef<iShader> shader;
	  FindBlockSize (computeShader, pticket, modes, svstack,
	    inputW, inputH,
	    maxBlockSizeX, maxBlockSizeY, 0);
	      
	  csArray<ProcessingPartFinal> finalParts;
	  csFIFO<ProcessingPart> remainingParts;
	  {
	    ProcessingPart firstPart;
	    firstPart.sourceRect.Set (0, 0, inputW, inputH);
	    firstPart.destOffsX = 0;
	    firstPart.destOffsY = 0;
	    remainingParts.Push (firstPart);
	  }
	  while (remainingParts.GetSize() > 0)
	  {
	    ProcessingPart part = remainingParts.PopTop();
	    int blockSizeX = 16;
	    int blockSizeY = 16;
	    
	    csRef<iShader> shader;
	    FindBlockSize (computeShader, pticket, modes, svstack,
	      part.sourceRect.Width(), part.sourceRect.Height(),
	      blockSizeX, blockSizeY, &shader);
	    // @@@ Handle failure
	    
	    int destW = part.sourceRect.Width()/blockSizeX;
	    int destH = part.sourceRect.Height()/blockSizeY;
	    int coveredW = destW*blockSizeX;
	    int coveredH = destH*blockSizeY;
	    int remainderX = part.sourceRect.Width()-coveredW;
	    int remainderY = part.sourceRect.Height()-coveredH;
	    if (remainderX > 0)
	    {
	      ProcessingPart newPart;
	      newPart.sourceRect.Set (
		part.sourceRect.xmin+coveredW, 
		part.sourceRect.ymin,
		part.sourceRect.xmin+coveredW+remainderX,
		part.sourceRect.ymin+coveredH);
	      newPart.destOffsX = part.destOffsX+destW;
	      newPart.destOffsY = part.destOffsY;
	      remainingParts.Push (newPart);
	    }
	    if (remainderY > 0)
	    {
	      ProcessingPart newPart;
	      newPart.sourceRect.Set (
		part.sourceRect.xmin, 
		part.sourceRect.ymin+coveredH,
		part.sourceRect.xmin+coveredW, 
		part.sourceRect.ymin+coveredH+remainderY);
	      newPart.destOffsX = part.destOffsX;
	      newPart.destOffsY = part.destOffsY+destH;
	      remainingParts.Push (newPart);
	    }
	    if ((remainderX > 0) && (remainderY > 0))
	    {
	      ProcessingPart newPart;
	      newPart.sourceRect.Set (
		part.sourceRect.xmin+coveredW, 
		part.sourceRect.ymin+coveredH,
		part.sourceRect.xmin+coveredW+remainderX, 
		part.sourceRect.ymin+coveredH+remainderY);
	      newPart.destOffsX = part.destOffsX+destW;
	      newPart.destOffsY = part.destOffsY+destH;
	      remainingParts.Push (newPart);
	    }
	    
	    ProcessingPartFinal finalPart;
	    finalPart.sourceRect.Set (
	      part.sourceRect.xmin, part.sourceRect.ymin,
	      part.sourceRect.xmin+coveredW,
	      part.sourceRect.ymin+coveredH);
	    finalPart.destRect.Set (
	      part.destOffsX, part.destOffsY,
	      part.destOffsX+destW, part.destOffsY+destH);
	    finalPart.shader = shader;
	    
	    finalParts.Push (finalPart);
	  }
	  
	  stage.targetW = finalParts[0].destRect.xmax;
	  stage.targetH = finalParts[0].destRect.ymax;
	  for (size_t l = 1; l < finalParts.GetSize(); l++)
	  {
	    stage.targetW = csMax (stage.targetW, finalParts[l].destRect.xmax);
	    stage.targetH = csMax (stage.targetH, finalParts[l].destRect.ymax);
	  }
	  bool lastStage = (stage.targetW <= minSize) && (stage.targetH <= minSize);
	  uint texFlags =
	    CS_TEXTURE_3D | CS_TEXTURE_NPOTS | CS_TEXTURE_CLAMP | CS_TEXTURE_SCALE_UP | CS_TEXTURE_NOMIPMAPS;
	  csString stageFormat;
	  if (lastStage)
	    stageFormat = readbackFmt.GetCanonical();
	  else
	    stageFormat = computeFX.GetIntermediateTargetFormat();
	  stage.target = graphics3D->GetTextureManager ()->CreateTexture (stage.targetW,
	    stage.targetH, csimg2D, stageFormat, texFlags);
	  
	  
	  int targetPixels = stage.targetW * maxBlockSizeX 
	    * stage.targetH * maxBlockSizeY;
	  int sourcePixels = inputW * inputH;
	  stage.svWeightCoeff.AttachNew (new csShaderVariable (
	    svNameStringSet->Request ("weight coeff")));
	  stage.svWeightCoeff->SetValue (float(targetPixels)/float(sourcePixels));
	  
	  // Set measureTex as input to first layer of computeFX
	  stage.svInput->SetValue (inputTex);
	  
	  PostEffectManager::Layer* outputLayer = 0;
	  for (size_t l = 0; l < finalParts.GetSize(); l++)
	  {
	    PostEffectManager::Layer* layer;
	    PostEffectManager::LayerInputMap inputMap;
	    inputMap.manualInput = stage.svInput;
	    inputMap.sourceRect = finalParts[l].sourceRect;
	    inputMap.inputPixelSizeName = "input pixel size";
	    PostEffectManager::LayerOptions options;
	    options.targetRect = finalParts[l].destRect;
	    if (outputLayer == 0)
	    {
	      options.manualTarget = stage.target;
	      options.readback = lastStage;
	    }
	    else
	      options.renderOn = outputLayer;
	    //inputMap.manualTexcoords = computeTexcoordBuf;
	    layer = computeFX.AddLayer (finalParts[l].shader, options, 1, &inputMap);
	    
	    layer->GetSVContext()->AddVariable (stage.svInput);
	    layer->GetSVContext()->AddVariable (stage.svWeightCoeff);
	    stage.layers.Push (layer);
	    if (outputLayer == 0) outputLayer = layer;
	  }
	  return !lastStage;
	}
Пример #20
0
void psLinearMovement::HugGround (const csVector3& pos, iSector* sector)
{
  csVector3 start, end;
  csIntersectingTriangle closest_tri;
  csVector3 isect[4];
  csPlane3 plane;
  bool hit[4];

  // Set minimum base dimensions of 0.5x0.5 for good aesthetics
  float legsXlimit = csMax(bottomSize.x / 2, 0.5f);
  float legsZlimit = csMax(bottomSize.z / 2, 0.5f);

  start.y = pos.y + shift.y + 0.01;

  // Assuming the bounding box is axis-aligned: (Lower-left point)
  start.x = pos.x - legsXlimit;
  start.z = pos.z - legsZlimit;

  end = start;
  end.y -= 5;

  hit[0] = csColliderHelper::TraceBeam (cdsys, sector, start, end,
  	false, closest_tri, isect[0]) != -1;

  // Assuming the bounding box is axis-aligned: (Upper-left point)
  start.x = pos.x - legsXlimit;
  start.z = pos.z + legsZlimit;

  end = start;
  end.y -= 5;

  hit[1] = csColliderHelper::TraceBeam (cdsys, sector, start, end,
  	false, closest_tri, isect[1]) != -1;

  // Assuming the bounding box is axis-aligned: (Upper-right point)
  start.x = pos.x + legsXlimit;
  start.z = pos.z + legsZlimit;

  end = start;
  end.y -= 5;

  hit[2] = csColliderHelper::TraceBeam (cdsys, sector, start, end,
  	false, closest_tri, isect[2]) != -1;

  // Assuming the bounding box is axis-aligned: (Lower-right point)
  start.x = pos.x + legsXlimit;
  start.z = pos.z - legsZlimit;

  end = start;
  end.y -= 5;

  hit[3] = csColliderHelper::TraceBeam (cdsys, sector, start, end,
  	false, closest_tri, isect[3]) != -1;

  //printf("Isect (%f %f %f %f)\n",hit[0] ? isect[0].y : -999, hit[1] ? isect[1].y : -999, hit[2] ? isect[2].y: -999, hit[3] ? isect[3].y: -999);

  int notHit = 0;
  int lowest = -1;
  for (int i = 0; i < 4 && notHit <= 1; i++)
  {
    if (!hit[i])
    {
      notHit++;
      lowest = i;
      continue;
    }
    if(notHit == 0)
    {
      if(lowest == -1)
        lowest = i;
      else if (isect[lowest].y > isect[i].y)
        lowest = i;
    }
  }
  if (notHit <= 1)
  {
    switch (lowest)
    {
      case 0:
        plane.Set (isect[1], isect[2], isect[3]);
        break;
      case 1:
        plane.Set (isect[0], isect[2], isect[3]);
        break;
      case 2:
        plane.Set (isect[0], isect[1], isect[3]);
        break;
      case 3:
        plane.Set (isect[0], isect[1], isect[2]);
        break;
    }
    csVector3 normal = plane.GetNormal ().Unit ();

    float newxRot = atan2 (normal.z, normal.y );
    float newzRot = -atan2 (normal.x, normal.y );
    csMatrix3 rotMat = csZRotMatrix3 (newzRot) * csXRotMatrix3 (newxRot - xRot)
    	* csZRotMatrix3 (-zRot);
    mesh->GetMovable ()->Transform (rotMat);
    xRot = newxRot;
    zRot = newzRot;
  }
}
Пример #21
0
void NetBase::CheckResendPkts()
{
    // NOTE: Globaliterators on csHash do not retrieve keys contiguously.
    csHash<csRef<psNetPacketEntry> , PacketKey>::GlobalIterator it(awaitingack.GetIterator());
    csRef<psNetPacketEntry> pkt;
    csArray<csRef<psNetPacketEntry> > pkts;
    csArray<Connection*> resentConnections;

    csTicks currenttime = csGetTicks();
    unsigned int resentCount = 0;

    while(it.HasNext())
    {
        pkt = it.Next();
        // Check the connection packet timeout
        if (pkt->timestamp + csMin((csTicks)PKTMAXRTO, pkt->RTO) < currenttime)
            pkts.Push(pkt);
    }
    for (size_t i = 0; i < pkts.GetSize(); i++)
    {
        pkt = pkts.Get(i);
#ifdef PACKETDEBUG
        Debug2(LOG_NET,0,"Resending nonacked HIGH packet (ID %d).\n", pkt->packet->pktid);
#endif
        Connection* connection = GetConnByNum(pkt->clientnum);
        if (connection)
        {
            if (resentConnections.Find(connection) == csArrayItemNotFound)
                resentConnections.Push(connection);

            // This indicates a bug in the netcode.
            if (pkt->RTO == 0)
            {
                Error1("Unexpected 0 packet RTO.");
                abort();
            }

            pkt->RTO *= 2;
            connection->resends++;
        }
        resentCount++;
        
        pkt->timestamp = currenttime;   // update stamp on packet
        pkt->retransmitted = true;
        
        // re-add to send queue
        if(NetworkQueue->Add(pkt))
        {
            //printf("pkt=%p, pkt->packet=%p\n",pkt,pkt->packet);
            // take out of awaiting ack pool.
            // This does NOT delete the pkt mem block itself.
            if (!awaitingack.Delete(PacketKey(pkt->clientnum, pkt->packet->pktid), pkt))
            {
#ifdef PACKETDEBUG
                Debug2(LOG_NET,0,"No packet in ack queue :%d\n", pkt->packet->pktid);
#endif
            }
            else if(connection)
            {
                connection->RemoveFromWindow(pkt->packet->GetPacketSize());
            }
        }
    }

    if(resentCount > 0)
    {
        resends[resendIndex] = resentCount;
        resendIndex = (resendIndex + 1) % RESENDAVGCOUNT;
        
        csTicks timeTaken = csGetTicks() - currenttime;
        if(resentCount > 300 || resendIndex == 1 || timeTaken > 50)
        {
            size_t peakResend = 0;
            float resendAvg = 0.0f;
            // Calculate averages data here
            for(int i = 0; i < RESENDAVGCOUNT; i++)
            {
                resendAvg += resends[i];
                peakResend = csMax(peakResend, resends[i]);
            }
            resendAvg /= RESENDAVGCOUNT;
            csString status;
            if(timeTaken > 50)
            {
                status.Format("Resending high priority packets has taken %u time to process, for %u packets.", timeTaken, resentCount);
                CPrintf(CON_WARNING, "%s\n", (const char *) status.GetData());
            }
            status.AppendFmt("Resending non-acked packet statistics: %g average resends, peak of %zu resent packets", resendAvg, peakResend);
 
            if(LogCSV::GetSingletonPtr())
                LogCSV::GetSingleton().Write(CSV_STATUS, status);
        }
        
    }
}
Пример #22
0
  bool Compute()
  {
    int lwidth = loResImage.width;
    int lheight = loResImage.height;
    int hwidth = hiResImage.width;
    int hheight = hiResImage.height;
    if ((lwidth > hwidth) && (lheight > hheight))
      return false;
    float scaleXToHiRes = (float)hwidth/(float)lwidth;
    float scaleYToHiRes = (float)hheight/(float)lheight;
    /* Radius around a pixel to search for closest pixel of the opposite state
     * ("spread factor" in the paper) */
    int searchRadius = (int)ceilf (csMax (scaleXToHiRes, scaleYToHiRes) * 0.707106781);

    const csRGBpixel* hiData = hiResImage.data;
    csRGBpixel* loData = loResImage.data;

    for (int y = y1; y < y2; y++)
    {
      for (int x = 0; x < lwidth; x++)
      {
	int hiResX = (int)((x + 0.5f) * scaleXToHiRes);
	int hiResY = (int)((y + 0.5f) * scaleYToHiRes);
	bool state = hiData[hiResY * hwidth + hiResX].alpha > 0.5f;
	float minRadius = searchRadius;
	int search_x1 = hiResX-searchRadius;
	int search_x2 = hiResX+searchRadius;
	int search_y1 = hiResY-searchRadius;
	int search_y2 = hiResY+searchRadius;

	for (int sy = search_y1; sy <= search_y2; sy++)
	{
	  int real_y = sy;
	  if (real_y < 0) real_y += hheight;
	  else if (real_y >= hheight) real_y -= hheight;
	  for (int sx = search_x1; sx <= search_x2; sx++)
	  {
	    int real_x = sx;
	    if (real_x < 0) real_x += hwidth;
	    else if (real_x >= hwidth) real_x -= hwidth;
	    bool search_state = hiData[real_y * hwidth + real_x].alpha > 0.5f;
	    if (search_state != state)
	    {
	      int dx = sx - hiResX;
	      int dy = sy - hiResY;
	      minRadius = csMin (minRadius, sqrtf (dx*dx + dy*dy));
	    }
	  }
	}

	uint8 distNorm;
	if (state)
	  distNorm = int (127.5f + 127.5f*(minRadius/(float)searchRadius));
	else
	  distNorm = int (127.5f - 127.5f*(minRadius/(float)searchRadius));
	loData[y * lwidth + x].alpha = distNorm;
      }
      progress.Step ();
    }
    return true;
  }