Пример #1
0
void drawSprite(struct SPRITE *s, float x, float y)
{

    /* draw sprite, animate if it's got more than one frame */
    if (!s)
        return;

    // don't bother if we're not even visible
    if (!s->__internal__visible)
        return;

    // figure out if we know our graphic index
    if (s->__internal__anim.graphicIndex == -1)
        s->__internal__anim.graphicIndex = searchForBmp(s->__internal__anim.name);

    // check for basic sprite, non-animated
    if (s->__internal__anim.index == -1) {

        /* this is a basic sprite with no animation, so just display it */
        float w = al_get_bitmap_width(bmpLib[s->__internal__anim.graphicIndex].data) * s->GetScaleX(s);
        float h = al_get_bitmap_height(bmpLib[s->__internal__anim.graphicIndex].data) * s->GetScaleY(s);
        al_draw_tinted_scaled_rotated_bitmap(bmpLib[s->__internal__anim.graphicIndex].data,
           s->__internal_tint, 0, 0, x - (w / 2) - floorf(camera.x), y - h - floorf(camera.y),
                s->GetScaleX(s), s->GetScaleY(s), s->GetAngle(s), s->flipped);

    }
    else {

        /* otherwise, this is a fancier sprite - animate it */
        struct FRAME f = s->__internal__anim.frame[s->GetAnim(s)][s->__internal__anim.index];
        if (f.sound == -255) {

            // we've run out of frames, go back to zero
            if (s->__internal__looping) {
                f = s->__internal__anim.frame[s->GetAnim(s)][0];
                s->__internal__anim.index = 0;
            }
            else {
                --s->__internal__anim.index;
                s->__internal__frameDelay = 0;
                f = s->__internal__anim.frame[s->GetAnim(s)][s->__internal__anim.index];
            }

        }
        else {

            /* otherwise increment frame, if we've waited out the delay */
            ++s->__internal__frameDelay;
            if (s->__internal__frameDelay > (f.delay * s->__internal_slowAnim)) {
                ++s->__internal__anim.index;
                s->__internal__frameDelay = 0;

                // play frame sound if we're allow by the playFrameSounds variable
                if (playFrameSounds) {
                    if (f.sound > -1) {
                        playSound(f.sound);
                    }
                }

            }

        }

        /* finally, display retrieved frame */
        al_draw_tinted_scaled_rotated_bitmap_region(bmpLib[s->__internal__anim.graphicIndex].data,
           f.x, f.y, f.w, f.h,
           s->__internal_tint,
           0, 0, (x - (f.w / 2)) - floorf(camera.x),
                (y - f.h) - floorf(camera.y), s->GetScaleX(s), s->GetScaleY(s),
           s->GetAngle(s), s->flipped);
        //al_draw_rectangle(s->box.x - floorf(camera.x), s->box.y - floorf(camera.y), s->box.right - floorf(camera.x), s->box.bottom - floorf(camera.y), al_map_rgb(0, 255, 0), 1);

    }

}
Пример #2
0
void rescale_image_to_fit(Buffer* input, Buffer* output, bool doFlip) {

  const Dimensions inputDims = input->_dims;
  const int inputWidth = inputDims[1];
  const int inputHeight = inputDims[0];
  const int inputChannels = inputDims[2];

  const Dimensions outputDims = output->_dims;
  const int outputWidth = outputDims[1];
  const int outputHeight = outputDims[0];
  const int outputChannels = outputDims[2];

  if ((inputDims == outputDims) && !doFlip) {
    const int elementCount = inputDims.elementCount();
    const size_t bytesInBuffer = (elementCount * sizeof(jpfloat_t));
    memcpy(output->_data, input->_data, bytesInBuffer);
    return;
  }

  const float flipBias = (doFlip) ? inputHeight : 0.0f;
  const float flipScale = (doFlip) ? -1.0f : 1.0f;

  const float scaleX = (inputWidth / (jpfloat_t)(outputWidth));
  const float scaleY = (flipScale * (inputHeight / (jpfloat_t)(outputHeight)));
  const int channelsToWrite = MIN(outputChannels, inputChannels);

  const Dimensions inputRowDims = inputDims.removeDimensions(1);
  const Dimensions outputRowDims = outputDims.removeDimensions(1);

  const jpfloat_t* inputDataStart = input->_data;
  jpfloat_t* const outputDataStart = output->_data;

  for (int outputY = 0; outputY < outputHeight; outputY += 1) {
    const jpfloat_t inputY = (flipBias + (outputY * scaleY));
    const int indexY0 = fmaxf(0.0f, fminf((inputHeight - 1.0f), floorf(inputY)));
    const int indexY1 = fmaxf(0.0f, fminf((inputHeight - 1.0f), ceilf(inputY)));
    const jpfloat_t lerpY = (indexY1 - inputY);
    const jpfloat_t oneMinusLerpY = (1.0f - lerpY);

    const int inputRowY0Offset = inputDims.offset(indexY0, 0, 0);
    const jpfloat_t* const inputRowY0 = (inputDataStart + inputRowY0Offset);
    const int inputRowY1Offset = inputDims.offset(indexY1, 0, 0);
    const jpfloat_t* const inputRowY1 = (inputDataStart + inputRowY1Offset);
    const int outputRowOffset = outputDims.offset(outputY, 0, 0);
    jpfloat_t* const outputRow = (outputDataStart + outputRowOffset);

    for (int outputX = 0; outputX < outputWidth; outputX += 1) {
      const jpfloat_t inputX = (outputX * scaleX);
      const int indexX0 = fmaxf(0.0f, floorf(inputX));
      const int indexX1 = fminf((inputWidth - 1.0f), ceilf(inputX));
      const jpfloat_t lerpX = (indexX1 - inputX);
      const jpfloat_t oneMinusLerpX = (1.0f - lerpX);

      const int indexX0Offset = inputRowDims.offset(indexX0, 0);
      const int indexX1Offset = inputRowDims.offset(indexX1, 0);

      const jpfloat_t* const input00Base = (inputRowY0 + indexX0Offset);
      const jpfloat_t* const input01Base = (inputRowY0 + indexX1Offset);
      const jpfloat_t* const input10Base = (inputRowY1 + indexX0Offset);
      const jpfloat_t* const input11Base = (inputRowY1 + indexX1Offset);

      const int outputOffset = outputRowDims.offset(outputX, 0);
      jpfloat_t* const outputBase = (outputRow + outputOffset);

      for (int channel = 0; channel < outputChannels; channel += 1) {
        jpfloat_t* const outputLocation = (outputBase + channel);
        if (channel >= channelsToWrite) {
          *outputLocation = 0.0f;
        } else {
          const jpfloat_t* input00Location = (input00Base + channel);
          const jpfloat_t* input01Location = (input01Base + channel);
          const jpfloat_t* input10Location = (input10Base + channel);
          const jpfloat_t* input11Location = (input11Base + channel);

          const jpfloat_t input00 = (*input00Location);
          const jpfloat_t input01 = (*input01Location);
          const jpfloat_t input10 = (*input10Location);
          const jpfloat_t input11 = (*input11Location);

          const jpfloat_t yInterp0 = ((input00 * lerpY) + (input10 * oneMinusLerpY));
          const jpfloat_t yInterp1 = ((input01 * lerpY) + (input11 * oneMinusLerpY));
          const jpfloat_t interp = ((yInterp0 * lerpX) + (yInterp1 * oneMinusLerpX));
          *outputLocation = interp;
        }
      }

    }
  }
}
Пример #3
0
memcached_return update_continuum(memcached_st *ptr)
{
  uint32_t index;
  uint32_t host_index;
  uint32_t continuum_index= 0;
  uint32_t value;
  memcached_server_st *list;
  uint32_t pointer_counter= 0;
  uint32_t pointer_per_server= MEMCACHED_POINTS_PER_SERVER;
  uint32_t pointer_per_hash= 1;
  uint64_t total_weight= 0;
  uint32_t is_ketama_weighted= 0;
  uint32_t points_per_server= 0;

  is_ketama_weighted= memcached_behavior_get(ptr, MEMCACHED_BEHAVIOR_KETAMA_WEIGHTED);
  points_per_server= is_ketama_weighted ? MEMCACHED_POINTS_PER_SERVER_KETAMA : MEMCACHED_POINTS_PER_SERVER;

  if (ptr->number_of_hosts > ptr->continuum_count)
  {
    memcached_continuum_item_st *new_ptr;

    if (ptr->call_realloc)
      new_ptr= (memcached_continuum_item_st *)ptr->call_realloc(ptr, ptr->continuum, sizeof(memcached_continuum_item_st) * (ptr->number_of_hosts + MEMCACHED_CONTINUUM_ADDITION) * points_per_server);
    else
      new_ptr= (memcached_continuum_item_st *)realloc(ptr->continuum, sizeof(memcached_continuum_item_st) * (ptr->number_of_hosts + MEMCACHED_CONTINUUM_ADDITION) * points_per_server);

    if (new_ptr == 0)
      return MEMCACHED_MEMORY_ALLOCATION_FAILURE;

    ptr->continuum= new_ptr;
    ptr->continuum_count= ptr->number_of_hosts + MEMCACHED_CONTINUUM_ADDITION;
  }

  list = ptr->hosts;

  if (is_ketama_weighted) 
  {
    for (host_index = 0; host_index < ptr->number_of_hosts; ++host_index) 
    {
      if (list[host_index].weight == 0)
      {
        list[host_index].weight = 1;
      }
      total_weight += list[host_index].weight;
    }
  }

  for (host_index = 0; host_index < ptr->number_of_hosts; ++host_index) 
  {
    if (is_ketama_weighted) 
    {
        float pct = (float)list[host_index].weight / (float)total_weight;
        pointer_per_server= floorf(pct * MEMCACHED_POINTS_PER_SERVER_KETAMA / 4 * (float)(ptr->number_of_hosts) + 0.0000000001) * 4;
        pointer_per_hash= 4;
#ifdef HAVE_DEBUG
        printf("ketama_weighted:%s|%d|%llu|%u\n", 
               list[host_index].hostname, 
               list[host_index].port,  
               (unsigned long long)list[host_index].weight, 
               pointer_per_server);
#endif
    }
    for (index= 1; index <= pointer_per_server / pointer_per_hash; ++index) 
    {
      char sort_host[MEMCACHED_MAX_HOST_SORT_LENGTH]= "";
      size_t sort_host_length;

      if (list[host_index].port == MEMCACHED_DEFAULT_PORT)
      {
        sort_host_length= snprintf(sort_host, MEMCACHED_MAX_HOST_SORT_LENGTH, "%s-%d", 
                                   list[host_index].hostname, index - 1);

      }
      else
      {
        sort_host_length= snprintf(sort_host, MEMCACHED_MAX_HOST_SORT_LENGTH, "%s:%d-%d", 
                                   list[host_index].hostname, list[host_index].port, index - 1);
      }
      WATCHPOINT_ASSERT(sort_host_length);

      if (is_ketama_weighted)
      {
        int i;
        for (i = 0; i < pointer_per_hash; i++)
        {
          value= ketama_server_hash(sort_host, sort_host_length, i);
          ptr->continuum[continuum_index].index= host_index;
          ptr->continuum[continuum_index++].value= value;
        }
      }
      else
      {
        value= generate_hash_value(sort_host, sort_host_length, ptr->hash_continuum);
        ptr->continuum[continuum_index].index= host_index;
        ptr->continuum[continuum_index++].value= value;
      }
    }
    pointer_counter+= pointer_per_server;
  }

  WATCHPOINT_ASSERT(ptr);
  WATCHPOINT_ASSERT(ptr->continuum);
  WATCHPOINT_ASSERT(ptr->number_of_hosts * MEMCACHED_POINTS_PER_SERVER <= MEMCACHED_CONTINUUM_SIZE);
  ptr->continuum_points_counter= pointer_counter;
  qsort(ptr->continuum, ptr->continuum_points_counter, sizeof(memcached_continuum_item_st), continuum_item_cmp);

#ifdef HAVE_DEBUG
  for (index= 0; ptr->number_of_hosts && index < ((ptr->number_of_hosts * MEMCACHED_POINTS_PER_SERVER) - 1); index++) 
  {
    WATCHPOINT_ASSERT(ptr->continuum[index].value <= ptr->continuum[index + 1].value);
  }
#endif

  return MEMCACHED_SUCCESS;
}
Пример #4
0
/*
const float* SoloMesh::getBoundsMin()
{
	if (!m_geom) return 0;
	return m_geom->getMeshBoundsMin();
}

const float* SoloMesh::getBoundsMax()
{
	if (!m_geom) return 0;
	return m_geom->getMeshBoundsMax();
}

dtNavMesh* SoloMesh::getNavMesh()
{
	return m_navMesh;
}

dtCrowd* SoloMesh::getCrowd()
{
	return m_crowd;
}

dtNavMeshQuery* SoloMesh::getNavMeshQuery()
{
	return m_navQuery;
}

void SoloMesh::resetCommonSettings()
{
	m_cellSize = 0.3f;
	m_cellHeight = 0.2f;
	m_agentHeight = 2.0f;
	m_agentRadius = 0.6f;
	m_agentMaxClimb = 0.9f;
	m_agentMaxSlope = 45.0f;
	m_regionMinSize = 8;
	m_regionMergeSize = 20;
	m_monotonePartitioning = false;
	m_edgeMaxLen = 12.0f;
	m_edgeMaxError = 1.3f;
	m_vertsPerPoly = 6.0f;
	m_detailSampleDist = 6.0f;
	m_detailSampleMaxError = 1.0f;
}
*/
bool SoloMesh::handleBuild()
{
    if (!m_geom || !m_geom->getMesh())
    {
        m_ctx->log(RC_LOG_ERROR, "buildNavigation: Input mesh is not specified.");
        return false;
    }

    cleanup();

    const float* bmin = m_geom->getMeshBoundsMin();
    const float* bmax = m_geom->getMeshBoundsMax();
    const float* verts = m_geom->getMesh()->getVerts();
    const int nverts = m_geom->getMesh()->getVertCount();
    const int* tris = m_geom->getMesh()->getTris();
    const int ntris = m_geom->getMesh()->getTriCount();

    //
    // Step 1. Initialize build config.
    //

    // Init build configuration from GUI
    memset(&m_cfg, 0, sizeof(m_cfg));
    m_cfg.cs = m_cellSize;
    m_cfg.ch = m_cellHeight;
    m_cfg.walkableSlopeAngle = m_agentMaxSlope;
    m_cfg.walkableHeight = (int)ceilf(m_agentHeight / m_cfg.ch);
    m_cfg.walkableClimb = (int)floorf(m_agentMaxClimb / m_cfg.ch);
    m_cfg.walkableRadius = (int)ceilf(m_agentRadius / m_cfg.cs);
    m_cfg.maxEdgeLen = (int)(m_edgeMaxLen / m_cellSize);
    m_cfg.maxSimplificationError = m_edgeMaxError;
    m_cfg.minRegionArea = (int)rcSqr(m_regionMinSize);		// Note: area = size*size
    m_cfg.mergeRegionArea = (int)rcSqr(m_regionMergeSize);	// Note: area = size*size
    m_cfg.maxVertsPerPoly = (int)m_vertsPerPoly;
    m_cfg.detailSampleDist = m_detailSampleDist < 0.9f ? 0 : m_cellSize * m_detailSampleDist;
    m_cfg.detailSampleMaxError = m_cellHeight * m_detailSampleMaxError;

    // Set the area where the navigation will be build.
    // Here the bounds of the input mesh are used, but the
    // area could be specified by an user defined box, etc.
    rcVcopy(m_cfg.bmin, bmin);
    rcVcopy(m_cfg.bmax, bmax);
    rcCalcGridSize(m_cfg.bmin, m_cfg.bmax, m_cfg.cs, &m_cfg.width, &m_cfg.height);

    // Reset build times gathering.
    m_ctx->resetTimers();

    // Start the build process.
    m_ctx->startTimer(RC_TIMER_TOTAL);

    m_ctx->log(RC_LOG_PROGRESS, "Building navigation:");
    m_ctx->log(RC_LOG_PROGRESS, " - %d x %d cells", m_cfg.width, m_cfg.height);
    m_ctx->log(RC_LOG_PROGRESS, " - %.1fK verts, %.1fK tris", nverts/1000.0f, ntris/1000.0f);

    //
    // Step 2. Rasterize input polygon soup.
    //

    // Allocate voxel heightfield where we rasterize our input data to.
    m_solid = rcAllocHeightfield();
    if (!m_solid)
    {
        m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'solid'.");
        return false;
    }
    if (!rcCreateHeightfield(m_ctx, *m_solid, m_cfg.width, m_cfg.height, m_cfg.bmin, m_cfg.bmax, m_cfg.cs, m_cfg.ch))
    {
        m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create solid heightfield.");
        return false;
    }

    // Allocate array that can hold triangle area types.
    // If you have multiple meshes you need to process, allocate
    // and array which can hold the max number of triangles you need to process.
    m_triareas = new unsigned char[ntris];
    if (!m_triareas)
    {
        m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'm_triareas' (%d).", ntris);
        return false;
    }

    // Find triangles which are walkable based on their slope and rasterize them.
    // If your input data is multiple meshes, you can transform them here, calculate
    // the are type for each of the meshes and rasterize them.
    memset(m_triareas, 0, ntris*sizeof(unsigned char));
    rcMarkWalkableTriangles(m_ctx, m_cfg.walkableSlopeAngle, verts, nverts, tris, ntris, m_triareas);
    rcRasterizeTriangles(m_ctx, verts, nverts, tris, m_triareas, ntris, *m_solid, m_cfg.walkableClimb);

    if (!m_keepInterResults)
    {
        delete [] m_triareas;
        m_triareas = 0;
    }

    //
    // Step 3. Filter walkables surfaces.
    //

    // Once all geoemtry is rasterized, we do initial pass of filtering to
    // remove unwanted overhangs caused by the conservative rasterization
    // as well as filter spans where the character cannot possibly stand.
    rcFilterLowHangingWalkableObstacles(m_ctx, m_cfg.walkableClimb, *m_solid);
    rcFilterLedgeSpans(m_ctx, m_cfg.walkableHeight, m_cfg.walkableClimb, *m_solid);
    rcFilterWalkableLowHeightSpans(m_ctx, m_cfg.walkableHeight, *m_solid);


    //
    // Step 4. Partition walkable surface to simple regions.
    //

    // Compact the heightfield so that it is faster to handle from now on.
    // This will result more cache coherent data as well as the neighbours
    // between walkable cells will be calculated.
    m_chf = rcAllocCompactHeightfield();
    if (!m_chf)
    {
        m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'chf'.");
        return false;
    }
    if (!rcBuildCompactHeightfield(m_ctx, m_cfg.walkableHeight, m_cfg.walkableClimb, *m_solid, *m_chf))
    {
        m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build compact data.");
        return false;
    }

    if (!m_keepInterResults)
    {
        rcFreeHeightField(m_solid);
        m_solid = 0;
    }

    // Erode the walkable area by agent radius.
    if (!rcErodeWalkableArea(m_ctx, m_cfg.walkableRadius, *m_chf))
    {
        m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not erode.");
        return false;
    }

    // (Optional) Mark areas.
    const ConvexVolume* vols = m_geom->getConvexVolumes();
    for (int i  = 0; i < m_geom->getConvexVolumeCount(); ++i)
        rcMarkConvexPolyArea(m_ctx, vols[i].verts, vols[i].nverts, vols[i].hmin, vols[i].hmax, (unsigned char)vols[i].area, *m_chf);

    if (m_monotonePartitioning)
    {
        // Partition the walkable surface into simple regions without holes.
        // Monotone partitioning does not need distancefield.
        if (!rcBuildRegionsMonotone(m_ctx, *m_chf, 0, m_cfg.minRegionArea, m_cfg.mergeRegionArea))
        {
            m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build regions.");
            return false;
        }
    }
    else
    {
        // Prepare for region partitioning, by calculating distance field along the walkable surface.
        if (!rcBuildDistanceField(m_ctx, *m_chf))
        {
            m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build distance field.");
            return false;
        }

        // Partition the walkable surface into simple regions without holes.
        if (!rcBuildRegions(m_ctx, *m_chf, 0, m_cfg.minRegionArea, m_cfg.mergeRegionArea))
        {
            m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build regions.");
            return false;
        }
    }

    //
    // Step 5. Trace and simplify region contours.
    //

    // Create contours.
    m_cset = rcAllocContourSet();
    if (!m_cset)
    {
        m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'cset'.");
        return false;
    }
    if (!rcBuildContours(m_ctx, *m_chf, m_cfg.maxSimplificationError, m_cfg.maxEdgeLen, *m_cset))
    {
        m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create contours.");
        return false;
    }

    //
    // Step 6. Build polygons mesh from contours.
    //

    // Build polygon navmesh from the contours.
    m_pmesh = rcAllocPolyMesh();
    if (!m_pmesh)
    {
        m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'pmesh'.");
        return false;
    }
    if (!rcBuildPolyMesh(m_ctx, *m_cset, m_cfg.maxVertsPerPoly, *m_pmesh))
    {
        m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not triangulate contours.");
        return false;
    }

    //
    // Step 7. Create detail mesh which allows to access approximate height on each polygon.
    //

    m_dmesh = rcAllocPolyMeshDetail();
    if (!m_dmesh)
    {
        m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'pmdtl'.");
        return false;
    }

    if (!rcBuildPolyMeshDetail(m_ctx, *m_pmesh, *m_chf, m_cfg.detailSampleDist, m_cfg.detailSampleMaxError, *m_dmesh))
    {
        m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build detail mesh.");
        return false;
    }

    if (!m_keepInterResults)
    {
        rcFreeCompactHeightfield(m_chf);
        m_chf = 0;
        rcFreeContourSet(m_cset);
        m_cset = 0;
    }

    // At this point the navigation mesh data is ready, you can access it from m_pmesh.
    // See duDebugDrawPolyMesh or dtCreateNavMeshData as examples how to access the data.

    //
    // (Optional) Step 8. Create Detour data from Recast poly mesh.
    //

    // The GUI may allow more max points per polygon than Detour can handle.
    // Only build the detour navmesh if we do not exceed the limit.
    if (m_cfg.maxVertsPerPoly <= DT_VERTS_PER_POLYGON)
    {
        unsigned char* navData = 0;
        int navDataSize = 0;

        // Update poly flags from areas.
        for (int i = 0; i < m_pmesh->npolys; ++i)
        {
            if (m_pmesh->areas[i] == RC_WALKABLE_AREA)
                m_pmesh->areas[i] = SAMPLE_POLYAREA_GROUND;

            if (m_pmesh->areas[i] == SAMPLE_POLYAREA_GROUND ||
                    m_pmesh->areas[i] == SAMPLE_POLYAREA_GRASS ||
                    m_pmesh->areas[i] == SAMPLE_POLYAREA_ROAD)
            {
                m_pmesh->flags[i] = SAMPLE_POLYFLAGS_WALK;
            }
            else if (m_pmesh->areas[i] == SAMPLE_POLYAREA_WATER)
            {
                m_pmesh->flags[i] = SAMPLE_POLYFLAGS_SWIM;
            }
            else if (m_pmesh->areas[i] == SAMPLE_POLYAREA_DOOR)
            {
                m_pmesh->flags[i] = SAMPLE_POLYFLAGS_WALK | SAMPLE_POLYFLAGS_DOOR;
            }
        }


        dtNavMeshCreateParams params;
        memset(&params, 0, sizeof(params));
        params.verts = m_pmesh->verts;
        params.vertCount = m_pmesh->nverts;
        params.polys = m_pmesh->polys;
        params.polyAreas = m_pmesh->areas;
        params.polyFlags = m_pmesh->flags;
        params.polyCount = m_pmesh->npolys;
        params.nvp = m_pmesh->nvp;
        params.detailMeshes = m_dmesh->meshes;
        params.detailVerts = m_dmesh->verts;
        params.detailVertsCount = m_dmesh->nverts;
        params.detailTris = m_dmesh->tris;
        params.detailTriCount = m_dmesh->ntris;
        params.offMeshConVerts = m_geom->getOffMeshConnectionVerts();
        params.offMeshConRad = m_geom->getOffMeshConnectionRads();
        params.offMeshConDir = m_geom->getOffMeshConnectionDirs();
        params.offMeshConAreas = m_geom->getOffMeshConnectionAreas();
        params.offMeshConFlags = m_geom->getOffMeshConnectionFlags();
        params.offMeshConUserID = m_geom->getOffMeshConnectionId();
        params.offMeshConCount = m_geom->getOffMeshConnectionCount();
        params.walkableHeight = m_agentHeight;
        params.walkableRadius = m_agentRadius;
        params.walkableClimb = m_agentMaxClimb;
        rcVcopy(params.bmin, m_pmesh->bmin);
        rcVcopy(params.bmax, m_pmesh->bmax);
        params.cs = m_cfg.cs;
        params.ch = m_cfg.ch;
        params.buildBvTree = true;

        if (!dtCreateNavMeshData(&params, &navData, &navDataSize))
        {
            m_ctx->log(RC_LOG_ERROR, "Could not build Detour navmesh.");
            return false;
        }

        m_navMesh = dtAllocNavMesh();
        if (!m_navMesh)
        {
            dtFree(navData);
            m_ctx->log(RC_LOG_ERROR, "Could not create Detour navmesh");
            return false;
        }

        dtStatus status;

        status = m_navMesh->init(navData, navDataSize, DT_TILE_FREE_DATA);
        if (dtStatusFailed(status))
        {
            dtFree(navData);
            m_ctx->log(RC_LOG_ERROR, "Could not init Detour navmesh");
            return false;
        }

        status = m_navQuery->init(m_navMesh, 2048);
        if (dtStatusFailed(status))
        {
            m_ctx->log(RC_LOG_ERROR, "Could not init Detour navmesh query");
            return false;
        }
    }

    m_ctx->stopTimer(RC_TIMER_TOTAL);

    // Show performance stats.
    duLogBuildTimes(*m_ctx, m_ctx->getAccumulatedTime(RC_TIMER_TOTAL));
    m_ctx->log(RC_LOG_PROGRESS, ">> Polymesh: %d vertices  %d polygons", m_pmesh->nverts, m_pmesh->npolys);

    m_totalBuildTimeMs = m_ctx->getAccumulatedTime(RC_TIMER_TOTAL)/1000.0f;

    return true;
}
Пример #5
0
float poly_saw(float amplitude, float freq, float phase)
{
	// (signal amplitude) * (peak amplitude) * 2 * ((time + phase)/period - floor(1/2 + (time + phase)/period))
	// where period = 1/freq
	return amplitude * POLY_MAX_AMP * 2 * (freq * (((float)poly_time)/(poly_format->rate) + phase*(1.0/freq)) - floorf(0.5 + (((float)poly_time)/(poly_format->rate) + phase*(1.0/freq)) * freq));
}
Пример #6
0
void Fl_Osc_Dial::OSC_value(char v)
{
    value(v + value() - floorf(value()) +
          minimum());
}
Пример #7
0
void
SeekSlider::Draw(BRect updateRect)
{
    BRect r(Bounds());

    // draw both sides (the original from Be doesn't seem
    // to make a difference for enabled/disabled state)
//	DrawBitmapAsync(fLeftSideBits, r.LeftTop());
//	DrawBitmapAsync(fRightSideBits, BPoint(sliderEnd + 1.0, r.top));
    // colors for the slider area between the two bitmaps
    rgb_color background = ui_color(B_PANEL_BACKGROUND_COLOR);
    rgb_color shadow = tint_color(background, B_DARKEN_2_TINT);
    rgb_color softShadow = tint_color(background, B_DARKEN_1_TINT);
    rgb_color darkShadow = tint_color(background, B_DARKEN_4_TINT);
    rgb_color midShadow = tint_color(background, B_DARKEN_3_TINT);
    rgb_color light = tint_color(background, B_LIGHTEN_MAX_TINT);
    rgb_color softLight = tint_color(background, B_LIGHTEN_1_TINT);
    rgb_color green = kSeekGreen;
    rgb_color greenShadow = kSeekGreenShadow;
    rgb_color black = kBlack;
    rgb_color dotGrey = midShadow;
    rgb_color dotGreen = greenShadow;
    // draw frame
    _StrokeFrame(r, softShadow, softShadow, light, light);
    r.InsetBy(1.0, 1.0);
    _StrokeFrame(r, black, black, softShadow, softShadow);
    if (IsEnabled()) {
        // *** enabled look ***
        r.InsetBy(1.0, 1.0);
        // inner shadow
        _StrokeFrame(r, greenShadow, greenShadow, green, green);
        r.top++;
        r.left++;
        _StrokeFrame(r, greenShadow, greenShadow, green, green);
        // inside area
        r.InsetBy(1.0, 1.0);
        SetHighColor(green);
        FillRect(r);
        // dots
        int32 dotCount = (int32)(r.Width() / 6.0);
        BPoint dotPos;
        dotPos.y = r.top + 2.0;
        SetHighColor(dotGreen);

        float knobWidth2 = SEEK_SLIDER_KNOB_WIDTH / 2.0;
        float sliderStart = (r.left + knobWidth2);

        for (int32 i = 0; i < dotCount; i++) {
            dotPos.x = sliderStart + i * 6.0;
            StrokeLine(dotPos, BPoint(dotPos.x, dotPos.y + 6.0));
        }
        // slider handle
        r.top -= 4.0;
        r.bottom += 3.0;
        r.left = fKnobPos - knobWidth2;
        r.right = fKnobPos + knobWidth2;
        // black outline
        float handleBottomSize = 2.0;
        float handleArrowSize = 6.0;
        BeginLineArray(10);
        // upper handle
        AddLine(BPoint(r.left, r.top + handleBottomSize),
                BPoint(r.left, r.top), black);
        AddLine(BPoint(r.left + 1.0, r.top),
                BPoint(r.right, r.top), black);
        AddLine(BPoint(r.right, r.top + 1.0),
                BPoint(r.right, r.top + handleBottomSize), black);
        AddLine(BPoint(r.right - 1.0, r.top + handleBottomSize + 1.0),
                BPoint(fKnobPos, r.top + handleArrowSize), black);
        AddLine(BPoint(fKnobPos - 1.0, r.top + handleArrowSize - 1.0),
                BPoint(r.left + 1.0, r.top + handleBottomSize + 1.0), black);
        // lower handle
        AddLine(BPoint(r.left, r.bottom),
                BPoint(r.left, r.bottom - handleBottomSize), black);
        AddLine(BPoint(r.left + 1.0, r.bottom - handleBottomSize - 1.0),
                BPoint(fKnobPos, r.bottom - handleArrowSize), black);
        AddLine(BPoint(fKnobPos + 1.0, r.bottom - handleArrowSize + 1.0),
                BPoint(r.right, r.bottom - handleBottomSize), black);
        AddLine(BPoint(r.right, r.bottom - handleBottomSize + 1.0),
                BPoint(r.right, r.bottom), black);
        AddLine(BPoint(r.right - 1.0, r.bottom),
                BPoint(r.left + 1.0, r.bottom), black);
        EndLineArray();
        // inner red light and shadow lines
        r.InsetBy(1.0, 1.0);
        handleBottomSize--;
        handleArrowSize -= 2.0;
        BeginLineArray(10);
        // upper handle
        AddLine(BPoint(r.left, r.top + handleBottomSize),
                BPoint(r.left, r.top), kSeekRedLight);
        AddLine(BPoint(r.left + 1.0, r.top),
                BPoint(r.right, r.top), kSeekRedLight);
        AddLine(BPoint(r.right, r.top + 1.0),
                BPoint(r.right, r.top + handleBottomSize), kSeekRedShadow);
        AddLine(BPoint(r.right - 1.0, r.top + handleBottomSize + 1.0),
                BPoint(fKnobPos, r.top + handleArrowSize), kSeekRedShadow);
        AddLine(BPoint(fKnobPos - 1.0, r.top + handleArrowSize - 1.0),
                BPoint(r.left + 1.0, r.top + handleBottomSize + 1.0), kSeekRedLight);
        // lower handle
        AddLine(BPoint(r.left, r.bottom),
                BPoint(r.left, r.bottom - handleBottomSize), kSeekRedLight);
        AddLine(BPoint(r.left + 1.0, r.bottom - handleBottomSize - 1.0),
                BPoint(fKnobPos, r.bottom - handleArrowSize), kSeekRedLight);
        AddLine(BPoint(fKnobPos + 1.0, r.bottom - handleArrowSize + 1.0),
                BPoint(r.right, r.bottom - handleBottomSize), kSeekRedShadow);
        AddLine(BPoint(r.right, r.bottom - handleBottomSize + 1.0),
                BPoint(r.right, r.bottom), kSeekRedShadow);
        AddLine(BPoint(r.right - 1.0, r.bottom),
                BPoint(r.left + 1.0, r.bottom), kSeekRedShadow);
        EndLineArray();
        // fill rest of handles with red
        SetHighColor(kSeekRed);
        r.InsetBy(1.0, 1.0);
        handleArrowSize -= 2.0;
        BPoint arrow[3];
        // upper handle arrow
        arrow[0].x = r.left;
        arrow[0].y = r.top;
        arrow[1].x = r.right;
        arrow[1].y = r.top;
        arrow[2].x = fKnobPos;
        arrow[2].y = r.top + handleArrowSize;
        FillPolygon(arrow, 3);
        // lower handle arrow
        arrow[0].x = r.left;
        arrow[0].y = r.bottom;
        arrow[1].x = r.right;
        arrow[1].y = r.bottom;
        arrow[2].x = fKnobPos;
        arrow[2].y = r.bottom - handleArrowSize;
        FillPolygon(arrow, 3);
    } else {
        // *** disabled look ***
        r.InsetBy(1.0, 1.0);
        _StrokeFrame(r, darkShadow, darkShadow, darkShadow, darkShadow);
        r.InsetBy(1.0, 1.0);
        _StrokeFrame(r, darkShadow, darkShadow, darkShadow, darkShadow);
        r.InsetBy(1.0, 1.0);
        SetHighColor(darkShadow);
        SetLowColor(shadow);
        // stripes
        float width = floorf(StringWidth(fDisabledString.String()));
        float textPos = r.left + r.Width() / 2.0 - width / 2.0;
        pattern stripes = { { 0xc7, 0x8f, 0x1f, 0x3e, 0x7c, 0xf8, 0xf1, 0xe3 } };
        BRect stripesRect(r);
        stripesRect.right = textPos - 5.0;
        FillRect(stripesRect, stripes);
        stripesRect.left = textPos + width + 3.0;
        stripesRect.right = r.right;
        FillRect(stripesRect, stripes);
        // info text
        r.left = textPos - 4.0;
        r.right = textPos + width + 2.0;
        FillRect(r);
        SetHighColor(shadow);
        SetLowColor(darkShadow);
        font_height fh;
        GetFontHeight(&fh);
        DrawString(fDisabledString.String(),
                   BPoint(textPos, r.top + ceilf(fh.ascent) - 1.0));
    }
}
Пример #8
0
void hud_render_text(const LLWString &wstr, const LLVector3 &pos_agent,
					const LLFontGL &font,
					const U8 style,
					const F32 x_offset, const F32 y_offset,
					const LLColor4& color,
					const BOOL orthographic)
{
	// Do cheap plane culling
	LLVector3 dir_vec = pos_agent - gCamera->getOrigin();
	dir_vec /= dir_vec.magVec();

	if (wstr.empty() || (!orthographic && dir_vec * gCamera->getAtAxis() <= 0.f))
	{
		return;
	}

	LLVector3 right_axis;
	LLVector3 up_axis;
	if (orthographic)
	{
		right_axis.setVec(0.f, -1.f / gViewerWindow->getWindowHeight(), 0.f);
		up_axis.setVec(0.f, 0.f, 1.f / gViewerWindow->getWindowHeight());
	}
	else
	{
		gCamera->getPixelVectors(pos_agent, up_axis, right_axis);
	}
	LLCoordFrame render_frame = *gCamera;
	LLQuaternion rot;
	if (!orthographic)
	{
		rot = render_frame.getQuaternion();
		rot = rot * LLQuaternion(-F_PI_BY_TWO, gCamera->getYAxis());
		rot = rot * LLQuaternion(F_PI_BY_TWO, gCamera->getXAxis());
	}
	else
	{
		rot = LLQuaternion(-F_PI_BY_TWO, LLVector3(0.f, 0.f, 1.f));
		rot = rot * LLQuaternion(-F_PI_BY_TWO, LLVector3(0.f, 1.f, 0.f));
	}
	F32 angle;
	LLVector3 axis;
	rot.getAngleAxis(&angle, axis);

	LLVector3 render_pos = pos_agent + (floorf(x_offset) * right_axis) + (floorf(y_offset) * up_axis);

	//get the render_pos in screen space
	F64 modelview[16];
	F64 projection[16];
	GLint viewport[4];
	glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
	glGetDoublev(GL_PROJECTION_MATRIX, projection);
	glGetIntegerv(GL_VIEWPORT, viewport);

	F64 winX, winY, winZ;
	gluProject(render_pos.mV[0], render_pos.mV[1], render_pos.mV[2],
				modelview, projection, viewport,
				&winX, &winY, &winZ);
		
	//fonts all render orthographically, set up projection
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glMatrixMode(GL_MODELVIEW);
	
	LLUI::pushMatrix();
		
	gViewerWindow->setup2DRender();

	LLUI::loadIdentity();
	LLUI::translate((F32) winX*1.0f/LLFontGL::sScaleX, (F32) winY*1.0f/(LLFontGL::sScaleY), -(((F32) winZ*2.f)-1.f));
	//glRotatef(angle * RAD_TO_DEG, axis.mV[VX], axis.mV[VY], axis.mV[VZ]);
	//glScalef(right_scale, up_scale, 1.f);
	F32 right_x;
	
	font.render(wstr, 0, 0, 0, color, LLFontGL::LEFT, LLFontGL::BASELINE, style, wstr.length(), 1000, &right_x);
	LLUI::popMatrix();
	
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
}
Пример #9
0
int main(int argc, char*argv[]) {
    srand(time(NULL));

    // options
    unsigned int k=2;               // samples/symbol (input)
    unsigned int k_out=2;           // samples/symbol (output)
    unsigned int m=4;               // filter delay (symbols)
    float beta=0.3f;                // filter excess bandwidth factor
    unsigned int num_filters=64;    // number of filters in the bank
    unsigned int num_symbols=500;   // number of data symbols
    float SNRdB = 30.0f;            // signal-to-noise ratio
    liquid_rnyquist_type ftype_tx = LIQUID_RNYQUIST_RRC;
    liquid_rnyquist_type ftype_rx = LIQUID_RNYQUIST_RRC;

    float bt=0.01f;     // loop filter bandwidth
    float tau=-0.4f;    // fractional symbol offset
    float r = 1.00f;    // resampled rate
    
    char filename_base[256] = "figures.gen/filter_symsync_crcf";
    
    int dopt;
    while ((dopt = getopt(argc,argv,"hf:k:K:m:b:B:s:w:n:t:r:")) != EOF) {
        switch (dopt) {
        case 'h':   usage();                            return 0;
        case 'f':   strncpy(filename_base,optarg,256);  break;
        case 'k':   k           = atoi(optarg);     break;
        case 'K':   k_out       = atoi(optarg);     break;
        case 'm':   m           = atoi(optarg);     break;
        case 'b':   beta        = atof(optarg);     break;
        case 'B':   num_filters = atoi(optarg);     break;
        case 's':   SNRdB       = atof(optarg);     break;
        case 'w':   bt          = atof(optarg);     break;
        case 'n':   num_symbols = atoi(optarg);     break;
        case 't':   tau         = atof(optarg);     break;
        case 'r':   r           = atof(optarg);     break;
        default:
            exit(1);
        }
    }

    // validate input
    if (k < 2) {
        fprintf(stderr,"error: k (samples/symbol) must be at least 2\n");
        exit(1);
    } else if (m < 1) {
        fprintf(stderr,"error: m (filter delay) must be greater than 0\n");
        exit(1);
    } else if (beta <= 0.0f || beta > 1.0f) {
        fprintf(stderr,"error: beta (excess bandwidth factor) must be in (0,1]\n");
        exit(1);
    } else if (num_filters == 0) {
        fprintf(stderr,"error: number of polyphase filters must be greater than 0\n");
        exit(1);
    } else if (bt <= 0.0f) {
        fprintf(stderr,"error: timing PLL bandwidth must be greater than 0\n");
        exit(1);
    } else if (num_symbols == 0) {
        fprintf(stderr,"error: number of symbols must be greater than 0\n");
        exit(1);
    } else if (tau < -1.0f || tau > 1.0f) {
        fprintf(stderr,"error: timing phase offset must be in [-1,1]\n");
        exit(1);
    } else if (r < 0.5f || r > 2.0f) {
        fprintf(stderr,"error: timing frequency offset must be in [0.5,2]\n");
        exit(1);
    }

    // compute delay
    while (tau < 0) tau += 1.0f;    // ensure positive tau
    float g = k*tau;                // number of samples offset
    int ds=floorf(g);               // additional symbol delay
    float dt = (g - (float)ds);     // fractional sample offset
    if (dt > 0.5f) {                // force dt to be in [0.5,0.5]
        dt -= 1.0f;
        ds++;
    }

    unsigned int i, n=0;

    // derived values
    unsigned int num_samples = k*num_symbols;
    unsigned int num_samples_resamp = (unsigned int) ceilf(num_samples*r*1.1f) + 4;

    // arrays
    float complex s[num_symbols];           // data symbols
    float complex x[num_samples];           // interpolated samples
    float complex y[num_samples_resamp];    // resampled data (resamp_crcf)
    float complex z[k_out*num_symbols + 64];// synchronized samples
    float complex sym_out[num_symbols + 64];// synchronized symbols

    // random signal (QPSK)
    for (i=0; i<num_symbols; i++) {
        s[i] = ( rand() % 2 ? M_SQRT1_2 : -M_SQRT1_2 ) +
               ( rand() % 2 ? M_SQRT1_2 : -M_SQRT1_2 ) * _Complex_I;
    }

    // 
    // create and run interpolator
    //

    // design interpolating filter
    unsigned int h_len = 2*k*m+1;
    float h[h_len];
    liquid_firdes_rnyquist(ftype_tx,k,m,beta,dt,h);
    interp_crcf q = interp_crcf_create(k,h,h_len);
    for (i=0; i<num_symbols; i++) {
        interp_crcf_execute(q, s[i], &x[n]);
        n+=k;
    }
    assert(n == num_samples);
    interp_crcf_destroy(q);

    // 
    // run resampler
    //
    unsigned int resamp_len = 10*k; // resampling filter semi-length (filter delay)
    float resamp_bw = 0.45f;        // resampling filter bandwidth
    float resamp_As = 60.0f;        // resampling filter stop-band attenuation
    unsigned int resamp_npfb = 64;  // number of filters in bank
    resamp_crcf f = resamp_crcf_create(r, resamp_len, resamp_bw, resamp_As, resamp_npfb);
    unsigned int num_samples_resampled = 0;
    unsigned int num_written;
    for (i=0; i<num_samples; i++) {
#if 0
        // bypass arbitrary resampler
        y[i] = x[i];
        num_samples_resampled = num_samples;
#else
        // TODO : compensate for resampler filter delay
        resamp_crcf_execute(f, x[i], &y[num_samples_resampled], &num_written);
        num_samples_resampled += num_written;
#endif
    }
    resamp_crcf_destroy(f);

    // 
    // add noise
    //
    float nstd = powf(10.0f, -SNRdB/20.0f);
    for (i=0; i<num_samples_resampled; i++)
        y[i] += nstd*(randnf() + _Complex_I*randnf());


    // 
    // create and run symbol synchronizer
    //

    symsync_crcf d = symsync_crcf_create_rnyquist(ftype_rx, k, m, beta, num_filters);
    symsync_crcf_set_lf_bw(d,bt);
    symsync_crcf_set_output_rate(d,k_out);

    unsigned int num_samples_sync=0;
    unsigned int nn;
    unsigned int num_symbols_sync = 0;
    float tau_hat[num_samples];
    for (i=ds; i<num_samples_resampled; i++) {
        tau_hat[num_samples_sync] = symsync_crcf_get_tau(d);
        symsync_crcf_execute(d, &y[i], 1, &z[num_samples_sync], &nn);

        // decimate
        unsigned int j;
        for (j=0; j<nn; j++) {
            if ( (num_samples_sync%k_out)==0 )
                sym_out[num_symbols_sync++] = z[num_samples_sync];
            num_samples_sync++;
        }
    }
    symsync_crcf_destroy(d);

    // print last several symbols to screen
    printf("output symbols:\n");
    for (i=num_symbols_sync-10; i<num_symbols_sync; i++)
        printf("  sym_out(%2u) = %8.4f + j*%8.4f;\n", i+1, crealf(sym_out[i]), cimagf(sym_out[i]));

    // 
    // export output
    //
    FILE * fid = NULL;
    char filename[300];

    // 
    // const: constellation
    //
    strncpy(filename, filename_base, 256);
    strcat(filename, "_const.gnu");
    fid = fopen(filename,"w");
    if (!fid) {
        fprintf(stderr,"error: %s, could not open file '%s' for writing\n", argv[0], filename);
        return 1;
    }
    fprintf(fid,"# %s: auto-generated file\n\n", filename);
    fprintf(fid,"reset\n");
    fprintf(fid,"set terminal postscript eps enhanced color solid rounded\n");
    fprintf(fid,"set size ratio 1\n");
    fprintf(fid,"set xrange [-1.5:1.5];\n");
    fprintf(fid,"set yrange [-1.5:1.5];\n");
    fprintf(fid,"set xlabel 'In-phase'\n");
    fprintf(fid,"set ylabel 'Quadrature phase'\n");
    fprintf(fid,"set grid xtics ytics\n");
    fprintf(fid,"set grid linetype 1 linecolor rgb '%s' linewidth 1\n",LIQUID_DOC_COLOR_GRID);
    fprintf(fid,"plot '-' using 1:2 with points pointtype 7 pointsize 0.5 linecolor rgb '%s' title 'first %u symbols',\\\n", LIQUID_DOC_COLOR_GRAY, num_symbols/2);
    fprintf(fid,"     '-' using 1:2 with points pointtype 7 pointsize 0.7 linecolor rgb '%s' title 'last %u symbols'\n",     LIQUID_DOC_COLOR_RED,  num_symbols/2);

    // first half of symbols
    for (i=2*m; i<num_symbols_sync/2; i++)
        fprintf(fid,"  %12.4e %12.4e\n", crealf(sym_out[i]), cimagf(sym_out[i]));
    fprintf(fid,"e\n");

    // second half of symbols
    for ( ; i<num_symbols_sync; i++)
        fprintf(fid,"  %12.4e %12.4e\n", crealf(sym_out[i]), cimagf(sym_out[i]));
    fprintf(fid,"e\n");

    fclose(fid);
    printf("results written to '%s'\n", filename);


    //
    // time series
    //
    strncpy(filename, filename_base, 256);
    strcat(filename, "_time.gnu");
    fid = fopen(filename,"w");
    if (!fid) {
        fprintf(stderr,"error: %s, could not open file '%s' for writing\n", argv[0], filename);
        return 1;
    }
    fprintf(fid,"# %s: auto-generated file\n\n", filename);
    fprintf(fid,"reset\n");
    fprintf(fid,"set terminal postscript eps enhanced color solid rounded\n");
    fprintf(fid,"set xrange [0:%u];\n",num_symbols);
    fprintf(fid,"set yrange [-1.5:1.5]\n");
    fprintf(fid,"set size ratio 0.3\n");
    fprintf(fid,"set xlabel 'Symbol Index'\n");
    fprintf(fid,"set key top right nobox\n");
    //fprintf(fid,"set ytics -5,1,5\n");
    fprintf(fid,"set grid xtics ytics\n");
    fprintf(fid,"set pointsize 0.6\n");
    fprintf(fid,"set grid linetype 1 linecolor rgb '%s' lw 1\n", LIQUID_DOC_COLOR_GRID);
    fprintf(fid,"set multiplot layout 2,1 scale 1.0,1.0\n");

    // real
    fprintf(fid,"# real\n");
    fprintf(fid,"set ylabel 'Real'\n");
    fprintf(fid,"plot '-' using 1:2 with lines linetype 1 linewidth 1 linecolor rgb '#999999' notitle,\\\n");
    fprintf(fid,"     '-' using 1:2 with points pointtype 7 linecolor rgb '%s' notitle'\n", LIQUID_DOC_COLOR_BLUE);
    // 
    for (i=0; i<num_samples_sync; i++)
        fprintf(fid,"%12.8f %12.4e\n", (float)i/(float)k_out, crealf(z[i]));
    fprintf(fid,"e\n");
    // 
    for (i=0; i<num_samples_sync; i+=k)
        fprintf(fid,"%12.8f %12.4e\n", (float)i/(float)k_out, crealf(z[i]));
    fprintf(fid,"e\n");

    // imag
    fprintf(fid,"# imag\n");
    fprintf(fid,"set ylabel 'Imag'\n");
    fprintf(fid,"plot '-' using 1:2 with lines linetype 1 linewidth 1 linecolor rgb '#999999' notitle,\\\n");
    fprintf(fid,"     '-' using 1:2 with points pointtype 7 linecolor rgb '%s' notitle'\n", LIQUID_DOC_COLOR_GREEN);
    // 
    for (i=0; i<num_samples_sync; i++)
        fprintf(fid,"%12.8f %12.4e\n", (float)i/(float)k_out, cimagf(z[i]));
    fprintf(fid,"e\n");
    // 
    for (i=0; i<num_samples_sync; i+=k)
        fprintf(fid,"%12.8f %12.4e\n", (float)i/(float)k_out, cimagf(z[i]));
    fprintf(fid,"e\n");

    fprintf(fid,"unset multiplot\n");

    // close output file
    fclose(fid);
    printf("results written to '%s'\n", filename);

    // clean it up
    return 0;
}
Пример #10
0
int main(int argc, char **argv) {
    srand(time(NULL));
    rand();
    if (!glfwInit()) {
        return -1;
    }
    #ifdef __APPLE__
        glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
        glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
        glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
        glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    #endif
    if (!glfwOpenWindow(800, 600, 8, 8, 8, 0, 24, 0, GLFW_WINDOW)) {
        return -1;
    }
    glfwSwapInterval(VSYNC);
    glfwDisable(GLFW_MOUSE_CURSOR);
    glfwSetWindowTitle("Modern GL");
    glfwSetKeyCallback(on_key);
    glfwSetMouseButtonCallback(on_mouse_button);

    #ifndef __APPLE__
        if (glewInit() != GLEW_OK) {
            return -1;
        }
    #endif

    if (db_init()) {
        return -1;
    }

    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LINE_SMOOTH);
    glLogicOp(GL_INVERT);
    glClearColor(0.53, 0.81, 0.92, 1.00);

    GLuint vertex_array;
    glGenVertexArrays(1, &vertex_array);
    glBindVertexArray(vertex_array);

    GLuint texture;
    glGenTextures(1, &texture);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glfwLoadTexture2D("texture.tga", 0);

    GLuint block_program = load_program(
        "shaders/block_vertex.glsl", "shaders/block_fragment.glsl");
    GLuint matrix_loc = glGetUniformLocation(block_program, "matrix");
    GLuint camera_loc = glGetUniformLocation(block_program, "camera");
    GLuint sampler_loc = glGetUniformLocation(block_program, "sampler");
    GLuint timer_loc = glGetUniformLocation(block_program, "timer");
    GLuint position_loc = glGetAttribLocation(block_program, "position");
    GLuint normal_loc = glGetAttribLocation(block_program, "normal");
    GLuint uv_loc = glGetAttribLocation(block_program, "uv");

    GLuint line_program = load_program(
        "shaders/line_vertex.glsl", "shaders/line_fragment.glsl");
    GLuint line_matrix_loc = glGetUniformLocation(line_program, "matrix");
    GLuint line_position_loc = glGetAttribLocation(line_program, "position");

    Chunk chunks[MAX_CHUNKS];
    int chunk_count = 0;

    FPS fps = {0, 0};
    float matrix[16];
    float x = (rand_double() - 0.5) * 10000;
    float z = (rand_double() - 0.5) * 10000;
    float y = 0;
    float dy = 0;
    float rx = 0;
    float ry = 0;
    int px = 0;
    int py = 0;

    int loaded = db_load_state(&x, &y, &z, &rx, &ry);
    ensure_chunks(chunks, &chunk_count,
        floorf(roundf(x) / CHUNK_SIZE),
        floorf(roundf(z) / CHUNK_SIZE), 1);
    if (!loaded) {
        y = highest_block(chunks, chunk_count, x, z) + 2;
    }

    glfwGetMousePos(&px, &py);
    double previous = glfwGetTime();
    while (glfwGetWindowParam(GLFW_OPENED)) {
        update_fps(&fps, SHOW_FPS);
        double now = glfwGetTime();
        double dt = MIN(now - previous, 0.2);
        previous = now;

        if (exclusive) {
            int mx, my;
            glfwGetMousePos(&mx, &my);
            float m = 0.0025;
            rx += (mx - px) * m;
            ry -= (my - py) * m;
            if (rx < 0) {
                rx += RADIANS(360);
            }
            if (rx >= RADIANS(360)){
                rx -= RADIANS(360);
            }
            ry = MAX(ry, -RADIANS(90));
            ry = MIN(ry, RADIANS(90));
            px = mx;
            py = my;
        }
        else {
            glfwGetMousePos(&px, &py);
        }

        if (left_click) {
            left_click = 0;
            int hx, hy, hz;
            if (hit_test(chunks, chunk_count, 0, x, y, z, rx, ry,
                &hx, &hy, &hz))
            {
                if (hy > 0) {
                    set_block(chunks, chunk_count, hx, hy, hz, 0);
                }
            }
        }

        if (right_click) {
            right_click = 0;
            int hx, hy, hz;
            if (hit_test(chunks, chunk_count, 1, x, y, z, rx, ry,
                &hx, &hy, &hz))
            {
                if (!player_intersects_block(2, x, y, z, hx, hy, hz)) {
                    set_block(chunks, chunk_count, hx, hy, hz, block_type);
                }
            }
        }

        int sz = 0;
        int sx = 0;
        ortho = glfwGetKey(GLFW_KEY_LSHIFT);
        if (glfwGetKey('Q')) break;
        if (glfwGetKey('W')) sz--;
        if (glfwGetKey('S')) sz++;
        if (glfwGetKey('A')) sx--;
        if (glfwGetKey('D')) sx++;
        if (dy == 0 && glfwGetKey(GLFW_KEY_SPACE)) {
            dy = 8;
        }
        float vx, vy, vz;
        get_motion_vector(flying, sz, sx, rx, ry, &vx, &vy, &vz);
        float speed = flying ? 20 : 5;
        int step = 8;
        float ut = dt / step;
        vx = vx * ut * speed;
        vy = vy * ut * speed;
        vz = vz * ut * speed;
        for (int i = 0; i < step; i++) {
            if (flying) {
                dy = 0;
            }
            else {
                dy -= ut * 25;
                dy = MAX(dy, -250);
            }
            x += vx;
            y += vy + dy * ut;
            z += vz;
            if (collide(chunks, chunk_count, 2, &x, &y, &z)) {
                dy = 0;
            }
        }

        int p = floorf(roundf(x) / CHUNK_SIZE);
        int q = floorf(roundf(z) / CHUNK_SIZE);
        ensure_chunks(chunks, &chunk_count, p, q, 0);

        update_matrix_3d(matrix, x, y, z, rx, ry);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // render chunks
        glUseProgram(block_program);
        glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix);
        glUniform3f(camera_loc, x, y, z);
        glUniform1i(sampler_loc, 0);
        glUniform1f(timer_loc, glfwGetTime());
        for (int i = 0; i < chunk_count; i++) {
            Chunk *chunk = chunks + i;
            if (chunk_distance(chunk, p, q) > RENDER_CHUNK_RADIUS) {
                continue;
            }
            if (!chunk_visible(chunk, matrix)) {
                continue;
            }
            draw_chunk(chunk, position_loc, normal_loc, uv_loc);
        }

        // render focused block wireframe
        int hx, hy, hz;
        if (hit_test(chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz)) {
            glUseProgram(line_program);
            glLineWidth(1);
            glEnable(GL_COLOR_LOGIC_OP);
            glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix);
            GLuint buffer = make_cube_buffer(hx, hy, hz, 0.51);
            draw_lines(buffer, line_position_loc, 3, 48);
            glDeleteBuffers(1, &buffer);
            glDisable(GL_COLOR_LOGIC_OP);
        }

        update_matrix_2d(matrix);

        // render crosshairs
        glUseProgram(line_program);
        glLineWidth(4);
        glEnable(GL_COLOR_LOGIC_OP);
        glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix);
        GLuint buffer = make_line_buffer();
        draw_lines(buffer, line_position_loc, 2, 4);
        glDeleteBuffers(1, &buffer);
        glDisable(GL_COLOR_LOGIC_OP);

        glfwSwapBuffers();
    }
    db_save_state(x, y, z, rx, ry);
    db_close();
    glfwTerminate();
    return 0;
}
Пример #11
0
GLUSboolean init(GLUSvoid)
{
    GLfloat textureToWorldNormalMatrix[16];

    // The maximum detail level which is 2^s = sMapExtend.
    GLuint sMaxDetailLevel;

    // The maximum detail level which is 2^t = tMapExtend.
    GLuint tMaxDetailLevel;

    // The overall maximum detail level from s and t.
    GLuint overallMaxDetailLevel;

    // Step for s and t direction.
    GLfloat detailStep;

    GLuint s, t;

    GLUStgaimage image;

    GLfloat* map = 0;

    GLuint* indices = 0;

    GLUStextfile vertexSource;
    GLUStextfile controlSource;
    GLUStextfile evaluationSource;
    GLUStextfile geometrySource;
    GLUStextfile fragmentSource;

    GLfloat lightDirection[3] = { 1.0f, 1.0f, 1.0f };

    glusVector3Normalizef(lightDirection);

    g_topView.cameraPosition[0] = 0.0f;
    g_topView.cameraPosition[1] = 30000.0f * METERS_TO_VIRTUAL_WORLD_SCALE;
    g_topView.cameraPosition[2] = 0.0f;
    g_topView.cameraPosition[3] = 1.0;
    g_topView.cameraDirection[0] = 0.0f;
    g_topView.cameraDirection[1] = -1.0f;
    g_topView.cameraDirection[2] = 0.0f;
    g_topView.cameraUp[0] = 0.0f;
    g_topView.cameraUp[1] = 0.0f;
    g_topView.cameraUp[2] = -1.0f;
    g_topView.fov = 40.0f;

    g_personView.cameraPosition[0] = 0.0f;
    g_personView.cameraPosition[1] = 4700.0f * METERS_TO_VIRTUAL_WORLD_SCALE;
    g_personView.cameraPosition[2] = 0.0f;
    g_personView.cameraPosition[3] = 1.0;
    g_personView.cameraDirection[0] = 0.0f;
    g_personView.cameraDirection[1] = 0.0f;
    g_personView.cameraDirection[2] = -1.0f;
    g_personView.cameraUp[0] = 0.0f;
    g_personView.cameraUp[1] = 1.0f;
    g_personView.cameraUp[2] = 0.0f;
    g_personView.fov = 60.0f;

    g_activeView = &g_personView;

    if (!glusLoadTgaImage(NORMAL_MAP, &image))
    {
        printf("Could not load normal picture '%s'!\n", NORMAL_MAP);

        return GLUS_FALSE;
    }

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    glGenTextures(1, &g_normalMapTexture);

    glBindTexture(GL_TEXTURE_RECTANGLE, g_normalMapTexture);

    glTexImage2D(GL_TEXTURE_RECTANGLE, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);

    glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glusDestroyTgaImage(&image);

    if (!glusLoadTgaImage(HEIGHT_MAP, &image))
    {
        printf("Could not load height picture '%s'!\n", HEIGHT_MAP);

        return GLUS_FALSE;
    }

    glGenTextures(1, &g_heightMapTexture);

    glBindTexture(GL_TEXTURE_RECTANGLE, g_heightMapTexture);

    glTexImage2D(GL_TEXTURE_RECTANGLE, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);

    glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    g_sMapExtend = (GLfloat) image.width;

    g_tMapExtend = (GLfloat) image.height;

    glusDestroyTgaImage(&image);

    // Calculate the detail level for the s and ...
    sMaxDetailLevel = (GLuint) floorf(logf(g_sMapExtend) / logf(2.0f));

    // ... t extend
    tMaxDetailLevel = (GLuint) floorf(logf(g_tMapExtend) / logf(2.0f));

    overallMaxDetailLevel = glusMinf(sMaxDetailLevel, tMaxDetailLevel);

    // Do checking of calculated parameters
    if (MINIMUM_DETAIL_LEVEL > overallMaxDetailLevel)
    {
        printf("Detail level to high %d > %d\n", MINIMUM_DETAIL_LEVEL, overallMaxDetailLevel);

        return GLUS_FALSE;
    }

    if (MINIMUM_DETAIL_LEVEL + DETAIL_LEVEL_FIRST_PASS > overallMaxDetailLevel)
    {
        printf("First pass detail level to high %d > %d\n", MINIMUM_DETAIL_LEVEL + DETAIL_LEVEL_FIRST_PASS, overallMaxDetailLevel);

        return GLUS_FALSE;
    }

    if (powf(2.0f, overallMaxDetailLevel - (MINIMUM_DETAIL_LEVEL + DETAIL_LEVEL_FIRST_PASS)) > 32.0f)
    {
        printf("Tessellation level to high %d > 32\n", (GLint) powf(2.0f, overallMaxDetailLevel - (MINIMUM_DETAIL_LEVEL + DETAIL_LEVEL_FIRST_PASS)));

        return GLUS_FALSE;
    }

    detailStep = powf(2.0f, overallMaxDetailLevel - MINIMUM_DETAIL_LEVEL);

    g_sNumPoints = (GLuint) ceilf(g_sMapExtend / detailStep) - 1;

    g_tNumPoints = (GLuint) ceilf(g_tMapExtend / detailStep) - 1;

    //
    // Generate the flat terrain mesh.
    //

    map = (GLUSfloat*) malloc(g_sNumPoints * g_tNumPoints * 2 * sizeof(GLfloat));

    indices = (GLuint*) malloc(g_sNumPoints * g_tNumPoints * sizeof(GLuint));

    for (t = 0; t < g_tNumPoints; t++)
    {
        for (s = 0; s < g_sNumPoints; s++)
        {
            map[t * g_sNumPoints * 2 + s * 2 + 0] = 0.5f + detailStep / 2.0f + (GLfloat) s * detailStep;
            map[t * g_sNumPoints * 2 + s * 2 + 1] = 0.5f + detailStep / 2.0f + (GLfloat) t * detailStep;

            indices[t * g_sNumPoints + s + 0] = (t + 0) * g_sNumPoints + s + 0;
        }
    }

    //
    // Transferring vertices and indices into GPU
    //

    // Pass one

    glGenBuffers(1, &g_verticesPassOneVBO);
    glBindBuffer(GL_ARRAY_BUFFER, g_verticesPassOneVBO);
    glBufferData(GL_ARRAY_BUFFER, g_sNumPoints * g_tNumPoints * 2 * sizeof(GLfloat), map, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glGenBuffers(1, &g_indicesPassOneVBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesPassOneVBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, g_sNumPoints * g_tNumPoints * sizeof(GLuint), indices, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    // Pass two.

    glGenBuffers(1, &g_verticesPassTwoVBO);
    glBindBuffer(GL_ARRAY_BUFFER, g_verticesPassTwoVBO);
    // Calculate enough space!
    glBufferData(GL_ARRAY_BUFFER, g_sNumPoints * g_tNumPoints * (GLuint) pow(4, DETAIL_LEVEL_FIRST_PASS + 1) * 2 * sizeof(GLfloat), 0, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    //

    free(map);
    map = 0;

    free(indices);
    indices = 0;

    //

    if (!glusLoadTgaImage(COLOR_MAP, &image))
    {
        printf("Could not load color picture '%s'!\n", COLOR_MAP);

        return GLUS_FALSE;
    }

    glGenTextures(1, &g_colorMapTexture);

    glBindTexture(GL_TEXTURE_2D, g_colorMapTexture);

    glTexImage2D(GL_TEXTURE_2D, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    glusDestroyTgaImage(&image);

    //

    glGenQueries(1, &g_transformFeedbackQuery);

    //
    // Creating the shader program.
    //

    // Pass one.

    glusLoadTextFile("../Example14/shader/PassOne.vert.glsl", &vertexSource);
    glusLoadTextFile("../Example14/shader/PassOne.geom.glsl", &geometrySource);
    glusLoadTextFile("../Example14/shader/PassOne.frag.glsl", &fragmentSource);

    // Compile and ...
    glusCreateProgramFromSource(&g_programPassOne, (const GLUSchar**) &vertexSource.text, 0, 0, (const GLUSchar**) &geometrySource.text, (const GLUSchar**) &fragmentSource.text);

    // ... add the transform variable ...
    glTransformFeedbackVaryings(g_programPassOne.program, 1, (const GLchar**) &TRANSFORM_VARYING, GL_SEPARATE_ATTRIBS);

    // ... and link the program
    if (!glusLinkProgram(&g_programPassOne))
    {
        printf("Could not build program one\n");

        return GLUS_FALSE;
    }

    // Destroy the text resource
    glusDestroyTextFile(&vertexSource);
    glusDestroyTextFile(&geometrySource);
    glusDestroyTextFile(&fragmentSource);

    g_halfDetailStepPassOneLocation = glGetUniformLocation(g_programPassOne.program, "u_halfDetailStep");

    g_detailLevelPassOneLocation = glGetUniformLocation(g_programPassOne.program, "u_detailLevel");

    g_fovRadiusPassOneLocation = glGetUniformLocation(g_programPassOne.program, "u_fovRadius");

    g_positionTextureSpacePassOneLocation = glGetUniformLocation(g_programPassOne.program, "u_positionTextureSpace");
    g_leftNormalTextureSpacePassOneLocation = glGetUniformLocation(g_programPassOne.program, "u_leftNormalTextureSpace");
    g_rightNormalTextureSpacePassOneLocation = glGetUniformLocation(g_programPassOne.program, "u_rightNormalTextureSpace");
    g_backNormalTextureSpacePassOneLocation = glGetUniformLocation(g_programPassOne.program, "u_backNormalTextureSpace");

    // Pass two.

    glusLoadTextFile("../Example14/shader/PassTwo.vert.glsl", &vertexSource);
    glusLoadTextFile("../Example14/shader/PassTwo.cont.glsl", &controlSource);
    glusLoadTextFile("../Example14/shader/PassTwo.eval.glsl", &evaluationSource);
    glusLoadTextFile("../Example14/shader/PassTwo.geom.glsl", &geometrySource);
    glusLoadTextFile("../Example14/shader/PassTwo.frag.glsl", &fragmentSource);

    if (!glusBuildProgramFromSource(&g_shaderProgramPassTwo, (const GLUSchar**) &vertexSource.text, (const GLUSchar**) &controlSource.text, (const GLUSchar**) &evaluationSource.text, (const GLUSchar**) &geometrySource.text, (const GLUSchar**) &fragmentSource.text))
    {
        printf("Could not build program two\n");

        return GLUS_FALSE;
    }

    glusDestroyTextFile(&vertexSource);
    glusDestroyTextFile(&controlSource);
    glusDestroyTextFile(&evaluationSource);
    glusDestroyTextFile(&geometrySource);
    glusDestroyTextFile(&fragmentSource);

    g_maxTessellationLevelPassTwoLocation = glGetUniformLocation(g_shaderProgramPassTwo.program, "u_maxTessellationLevel");

    g_quadrantStepPassTwoLocation = glGetUniformLocation(g_shaderProgramPassTwo.program, "u_quadrantStep");

    g_positionTextureSpacePassTwoLocation = glGetUniformLocation(g_shaderProgramPassTwo.program, "u_positionTextureSpace");

    g_heightMapTexturePassTwoLocation = glGetUniformLocation(g_shaderProgramPassTwo.program, "u_heightMapTexture");
    g_normalMapTexturePassTwoLocation = glGetUniformLocation(g_shaderProgramPassTwo.program, "u_normalMapTexture");

    g_tmvpPassTwoLocation = glGetUniformLocation(g_shaderProgramPassTwo.program, "u_tmvpMatrix");

    g_lightDirectionPassTwoLocation = glGetUniformLocation(g_shaderProgramPassTwo.program, "u_lightDirection");

    g_colorMapTexturePassTwoLocation = glGetUniformLocation(g_shaderProgramPassTwo.program, "u_colorMapTexture");

    //

    // One time matrix calculations to convert between texture and world space

    glusMatrix4x4Identityf(g_textureToWorldMatrix);
    glusMatrix4x4Identityf(textureToWorldNormalMatrix);

    glusMatrix4x4Scalef(g_textureToWorldMatrix, HORIZONTAL_PIXEL_SPACING * METERS_TO_VIRTUAL_WORLD_SCALE, VERTICAL_PIXEL_RANGE * METERS_TO_VIRTUAL_WORLD_SCALE, HORIZONTAL_PIXEL_SPACING * METERS_TO_VIRTUAL_WORLD_SCALE);
    // Skip this scale for the normal matrix

    glusMatrix4x4Scalef(g_textureToWorldMatrix, 1.0f, 1.0f, -1.0f);
    glusMatrix4x4Scalef(textureToWorldNormalMatrix, 1.0f, 1.0f, -1.0f);

    glusMatrix4x4Translatef(g_textureToWorldMatrix, -g_sMapExtend / 2.0f, 0.0f, -g_tMapExtend / 2.0f);
    // No need for the translation matrix in the normal matrix

    glusMatrix4x4Copyf(g_worldToTextureMatrix, g_textureToWorldMatrix, GLUS_FALSE);
    glusMatrix4x4Inversef(g_worldToTextureMatrix);

    glusMatrix4x4Copyf(g_worldToTextureNormalMatrix, textureToWorldNormalMatrix, GLUS_FALSE);
    glusMatrix4x4Inversef(g_worldToTextureNormalMatrix);

    // Pass one

    glUseProgram(g_programPassOne.program);

    glUniform1f(g_halfDetailStepPassOneLocation, detailStep / 2.0f);
    glUniform1ui(g_detailLevelPassOneLocation, DETAIL_LEVEL_FIRST_PASS);
    glUniform1f(g_fovRadiusPassOneLocation, FOV_RADIUS / HORIZONTAL_PIXEL_SPACING * METERS_TO_VIRTUAL_WORLD_SCALE);

    glGenVertexArrays(1, &g_vaoPassOne);
    glBindVertexArray(g_vaoPassOne);

    glBindBuffer(GL_ARRAY_BUFFER, g_verticesPassOneVBO);
    // First 0 is the location = 0. See shader source
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
    // Enable location = 0
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesPassOneVBO);

   // Pass two

    glUseProgram(g_shaderProgramPassTwo.program);

    glUniform3fv(g_lightDirectionPassTwoLocation, 1, lightDirection);
    glUniform1ui(g_maxTessellationLevelPassTwoLocation, overallMaxDetailLevel - (MINIMUM_DETAIL_LEVEL + DETAIL_LEVEL_FIRST_PASS));
    glUniform1i(g_quadrantStepPassTwoLocation, QUADRANT_STEP);

    glGenVertexArrays(1, &g_vaoPassTwo);
    glBindVertexArray(g_vaoPassTwo);

    glBindBuffer(GL_ARRAY_BUFFER, g_verticesPassTwoVBO);
    // First 0 is the location = 0. See shader source
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
    // Enable location = 0
    glEnableVertexAttribArray(0);

    //

    glActiveTexture(GL_TEXTURE0);
    glUniform1i(g_heightMapTexturePassTwoLocation, 0);
    glBindTexture(GL_TEXTURE_RECTANGLE, g_heightMapTexture);

    glActiveTexture(GL_TEXTURE1);
    glUniform1i(g_colorMapTexturePassTwoLocation, 1);
    glBindTexture(GL_TEXTURE_2D, g_colorMapTexture);

    glActiveTexture(GL_TEXTURE2);
    glUniform1i(g_normalMapTexturePassTwoLocation, 2);
    glBindTexture(GL_TEXTURE_RECTANGLE, g_normalMapTexture);

    //

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    glClearDepth(1.0f);

    glEnable(GL_DEPTH_TEST);

    glEnable(GL_CULL_FACE);

    glPatchParameteri(GL_PATCH_VERTICES, 4);

    return GLUS_TRUE;
}
Пример #12
0
void BKE_image_buf_fill_checker(unsigned char *rect, float *rect_float, int width, int height)
{
	/* these two passes could be combined into one, but it's more readable and 
	* easy to tweak like this, speed isn't really that much of an issue in this situation... */
 
	int checkerwidth= 32, dark= 1;
	int x, y;

	unsigned char *rect_orig= rect;
	float *rect_float_orig= rect_float;

	
	float h=0.0, hoffs=0.0, hue=0.0, s=0.9, v=0.9, r, g, b;

	/* checkers */
	for(y= 0; y<height; y++) {
		dark= powf(-1.0f, floorf(y / checkerwidth));
		
		for(x= 0; x<width; x++) {
			if (x % checkerwidth == 0) dark= -dark;
			
			if (rect_float) {
				if (dark > 0) {
					rect_float[0]= rect_float[1]= rect_float[2]= 0.25f;
					rect_float[3]= 1.0f;
				} else {
					rect_float[0]= rect_float[1]= rect_float[2]= 0.58f;
					rect_float[3]= 1.0f;
				}
				rect_float+= 4;
			}
			else {
				if (dark > 0) {
					rect[0]= rect[1]= rect[2]= 64;
					rect[3]= 255;
				} else {
					rect[0]= rect[1]= rect[2]= 150;
					rect[3]= 255;
				}
				rect+= 4;
			}
		}
	}

	rect= rect_orig;
	rect_float= rect_float_orig;

	/* 2nd pass, colored + */
	for(y= 0; y<height; y++) {
		hoffs= 0.125f * floorf(y / checkerwidth);
		
		for(x= 0; x<width; x++) {
			h= 0.125f * floorf(x / checkerwidth);
			
			if ((fabs((x % checkerwidth) - (checkerwidth / 2)) < 4) &&
				(fabs((y % checkerwidth) - (checkerwidth / 2)) < 4)) {
				
				if ((fabs((x % checkerwidth) - (checkerwidth / 2)) < 1) ||
					(fabs((y % checkerwidth) - (checkerwidth / 2)) < 1)) {
					
					hue= fmodf(fabs(h-hoffs), 1.0f);
					hsv_to_rgb(hue, s, v, &r, &g, &b);
					
					if (rect) {
						rect[0]= (char)(r * 255.0f);
						rect[1]= (char)(g * 255.0f);
						rect[2]= (char)(b * 255.0f);
						rect[3]= 255;
					}
					
					if (rect_float) {
						rect_float[0]= r;
						rect_float[1]= g;
						rect_float[2]= b;
						rect_float[3]= 1.0f;
					}
				}
			}

			if (rect_float) rect_float+= 4;
			if (rect) rect+= 4;
		}
	}
}
Пример #13
0
void FlipY3D::update(float time)
{
    float angle = (float)M_PI * time; // 180 degrees
    float mz = sinf( angle );
    angle = angle / 2.0f;     // x calculates degrees from 0 to 90
    float my = cosf(angle);
    
    Vec3    v0, v1, v, diff;
    
    v0 = getOriginalVertex(Vec2(1.0f, 1.0f));
    v1 = getOriginalVertex(Vec2());
    
    float    y0 = v0.y;
    float    y1 = v1.y;
    float y;
    Vec2    a, b, c, d;
    
    if (y0 > y1)
    {
        // Normal Grid
        a.setZero();
        b.set(0.0f, 1.0f);
        c.set(1.0f, 0.0f);
        d.set(1.0f, 1.0f);
        y = y0;
    }
    else
    {
        // Reversed Grid
        b.setZero();
        a.set(0.0f, 1.0f);
        d.set(1.0f, 0.0f);
        c.set(1.0f, 1.0f);
        y = y1;
    }
    
    diff.y = y - y * my;
    diff.z = fabsf(floorf((y * mz) / 4.0f));
    
    // bottom-left
    v = getOriginalVertex(a);
    v.y = diff.y;
    v.z += diff.z;
    setVertex(a, v);
    
    // upper-left
    v = getOriginalVertex(b);
    v.y -= diff.y;
    v.z -= diff.z;
    setVertex(b, v);
    
    // bottom-right
    v = getOriginalVertex(c);
    v.y = diff.y;
    v.z += diff.z;
    setVertex(c, v);
    
    // upper-right
    v = getOriginalVertex(d);
    v.y -= diff.y;
    v.z -= diff.z;
    setVertex(d, v);
}
Пример #14
0
void FlipX3D::update(float time)
{
    float angle = (float)M_PI * time; // 180 degrees
    float mz = sinf(angle);
    angle = angle / 2.0f; // x calculates degrees from 0 to 90
    float mx = cosf(angle);

    Vec3 v0, v1, v, diff;

    v0 = getOriginalVertex(Vec2(1.0f, 1.0f));
    v1 = getOriginalVertex(Vec2());

    float    x0 = v0.x;
    float    x1 = v1.x;
    float    x;
    Vec2    a, b, c, d;

    if ( x0 > x1 )
    {
        // Normal Grid
        a.setZero();
        b.set(0.0f, 1.0f);
        c.set(1.0f, 0.0f);
        d.set(1.0f, 1.0f);
        x = x0;
    }
    else
    {
        // Reversed Grid
        c.setZero();
        d.set(0.0f, 1.0f);
        a.set(1.0f, 0.0f);
        b.set(1.0f, 1.0f);
        x = x1;
    }
    
    diff.x = ( x - x * mx );
    diff.z = fabsf( floorf( (x * mz) / 4.0f ) );

    // bottom-left
    v = getOriginalVertex(a);
    v.x = diff.x;
    v.z += diff.z;
    setVertex(a, v);
    
    // upper-left
    v = getOriginalVertex(b);
    v.x = diff.x;
    v.z += diff.z;
    setVertex(b, v);
    
    // bottom-right
    v = getOriginalVertex(c);
    v.x -= diff.x;
    v.z -= diff.z;
    setVertex(c, v);
    
    // upper-right
    v = getOriginalVertex(d);
    v.x -= diff.x;
    v.z -= diff.z;
    setVertex(d, v);
}
Пример #15
0
/* snaps the keyframe to the nearest frame */
static short snap_bezier_nearest(KeyframeEditData *UNUSED(ked), BezTriple *bezt)
{
	if (bezt->f2 & SELECT)
		bezt->vec[1][0] = (float)(floorf(bezt->vec[1][0] + 0.5f));
	return 0;
}
Пример #16
0
inline int Floor2Int(float val) {
    return (int)floorf(val);
}
Пример #17
0
void Fl_Osc_Dial::OSC_value(int v)
{
    value(v + value() - floorf(value()) +
          (minimum() == 64 ? 0 : minimum()));
}
Пример #18
0
S32 LLFontGL::render(const LLWString &wstr, S32 begin_offset, F32 x, F32 y, const LLColor4 &color, HAlign halign, VAlign valign, U8 style, 
					 ShadowType shadow, S32 max_chars, S32 max_pixels, F32* right_x, BOOL use_ellipses) const
{
	LLFastTimer _(FTM_RENDER_FONTS);

	if(!sDisplayFont) //do not display texts
	{
		return wstr.length() ;
	}

	if (wstr.empty())
	{
		return 0;
	} 

	gGL.getTexUnit(0)->enable(LLTexUnit::TT_TEXTURE);

	S32 scaled_max_pixels = max_pixels == S32_MAX ? S32_MAX : llceil((F32)max_pixels * sScaleX);

	// determine which style flags need to be added programmatically by stripping off the
	// style bits that are drawn by the underlying Freetype font
	U8 style_to_add = (style | mFontDescriptor.getStyle()) & ~mFontFreetype->getStyle();

	F32 drop_shadow_strength = 0.f;
	if (shadow != NO_SHADOW)
	{
		F32 luminance;
		color.calcHSL(NULL, NULL, &luminance);
		drop_shadow_strength = clamp_rescale(luminance, 0.35f, 0.6f, 0.f, 1.f);
		if (luminance < 0.35f)
		{
			shadow = NO_SHADOW;
		}
	}

	gGL.pushUIMatrix();

	gGL.loadUIIdentity();
	
	LLVector2 origin(floorf(sCurOrigin.mX*sScaleX), floorf(sCurOrigin.mY*sScaleY));
	// snap the text origin to a pixel grid to start with
	origin.mV[VX] -= ll_round((F32)sCurOrigin.mX) - (sCurOrigin.mX);
	origin.mV[VY] -= ll_round((F32)sCurOrigin.mY) - (sCurOrigin.mY);

	// Depth translation, so that floating text appears 'inworld'
	// and is correclty occluded.
	gGL.translatef(0.f,0.f,sCurOrigin.mZ);

	S32 chars_drawn = 0;
	S32 i;
	S32 length;

	if (-1 == max_chars)
	{
		length = (S32)wstr.length() - begin_offset;
	}
	else
	{
		length = llmin((S32)wstr.length() - begin_offset, max_chars );
	}

	F32 cur_x, cur_y, cur_render_x, cur_render_y;

 	// Not guaranteed to be set correctly
	gGL.setSceneBlendType(LLRender::BT_ALPHA);
	
	cur_x = ((F32)x * sScaleX) + origin.mV[VX];
	cur_y = ((F32)y * sScaleY) + origin.mV[VY];

	// Offset y by vertical alignment.
	// use unscaled font metrics here
	switch (valign)
	{
	case TOP:
		cur_y -= mFontFreetype->getAscenderHeight();
		break;
	case BOTTOM:
		cur_y += mFontFreetype->getDescenderHeight();
		break;
	case VCENTER:
		cur_y -= (mFontFreetype->getAscenderHeight() - mFontFreetype->getDescenderHeight()) / 2.f;
		break;
	case BASELINE:
		// Baseline, do nothing.
		break;
	default:
		break;
	}

	switch (halign)
	{
	case LEFT:
		break;
	case RIGHT:
	  	cur_x -= llmin(scaled_max_pixels, ll_round(getWidthF32(wstr.c_str(), begin_offset, length) * sScaleX));
		break;
	case HCENTER:
	    cur_x -= llmin(scaled_max_pixels, ll_round(getWidthF32(wstr.c_str(), begin_offset, length) * sScaleX)) / 2;
		break;
	default:
		break;
	}

	cur_render_y = cur_y;
	cur_render_x = cur_x;

	F32 start_x = (F32)ll_round(cur_x);

	const LLFontBitmapCache* font_bitmap_cache = mFontFreetype->getFontBitmapCache();

	F32 inv_width = 1.f / font_bitmap_cache->getBitmapWidth();
	F32 inv_height = 1.f / font_bitmap_cache->getBitmapHeight();

	const S32 LAST_CHARACTER = LLFontFreetype::LAST_CHAR_FULL;


	BOOL draw_ellipses = FALSE;
	if (use_ellipses)
	{
		// check for too long of a string
		S32 string_width = ll_round(getWidthF32(wstr.c_str(), begin_offset, max_chars) * sScaleX);
		if (string_width > scaled_max_pixels)
		{
			// use four dots for ellipsis width to generate padding
			const LLWString dots(utf8str_to_wstring(std::string("....")));
			scaled_max_pixels = llmax(0, scaled_max_pixels - ll_round(getWidthF32(dots.c_str())));
			draw_ellipses = TRUE;
		}
	}

	const LLFontGlyphInfo* next_glyph = NULL;

	const S32 GLYPH_BATCH_SIZE = 30;
	LLVector4a vertices[GLYPH_BATCH_SIZE * 4];
	LLVector2 uvs[GLYPH_BATCH_SIZE * 4];
	LLColor4U colors[GLYPH_BATCH_SIZE * 4];

	LLColor4U text_color(color);

	S32 bitmap_num = -1;
	S32 glyph_count = 0;
	for (i = begin_offset; i < begin_offset + length; i++)
	{
		llwchar wch = wstr[i];

		const LLFontGlyphInfo* fgi = next_glyph;
		next_glyph = NULL;
		if(!fgi)
		{
			fgi = mFontFreetype->getGlyphInfo(wch);
		}
		if (!fgi)
		{
			LL_ERRS() << "Missing Glyph Info" << LL_ENDL;
			break;
		}
		// Per-glyph bitmap texture.
		S32 next_bitmap_num = fgi->mBitmapNum;
		if (next_bitmap_num != bitmap_num)
		{
			// Actually draw the queued glyphs before switching their texture;
			// otherwise the queued glyphs will be taken from wrong textures.
			if (glyph_count > 0)
			{
				gGL.begin(LLRender::QUADS);
				{
					gGL.vertexBatchPreTransformed(vertices, uvs, colors, glyph_count * 4);
				}
				gGL.end();
				glyph_count = 0;
			}

			bitmap_num = next_bitmap_num;
			LLImageGL *font_image = font_bitmap_cache->getImageGL(bitmap_num);
			gGL.getTexUnit(0)->bind(font_image);
		}
	
		if ((start_x + scaled_max_pixels) < (cur_x + fgi->mXBearing + fgi->mWidth))
		{
			// Not enough room for this character.
			break;
		}

		// Draw the text at the appropriate location
		//Specify vertices and texture coordinates
		LLRectf uv_rect((fgi->mXBitmapOffset) * inv_width,
				(fgi->mYBitmapOffset + fgi->mHeight + PAD_UVY) * inv_height,
				(fgi->mXBitmapOffset + fgi->mWidth) * inv_width,
				(fgi->mYBitmapOffset - PAD_UVY) * inv_height);
		// snap glyph origin to whole screen pixel
		LLRectf screen_rect((F32)ll_round(cur_render_x + (F32)fgi->mXBearing),
				    (F32)ll_round(cur_render_y + (F32)fgi->mYBearing),
				    (F32)ll_round(cur_render_x + (F32)fgi->mXBearing) + (F32)fgi->mWidth,
				    (F32)ll_round(cur_render_y + (F32)fgi->mYBearing) - (F32)fgi->mHeight);
		
		if (glyph_count >= GLYPH_BATCH_SIZE)
		{
			gGL.begin(LLRender::QUADS);
			{
				gGL.vertexBatchPreTransformed(vertices, uvs, colors, glyph_count * 4);
			}
			gGL.end();

			glyph_count = 0;
		}

		drawGlyph(glyph_count, vertices, uvs, colors, screen_rect, uv_rect, text_color, style_to_add, shadow, drop_shadow_strength);

		chars_drawn++;
		cur_x += fgi->mXAdvance;
		cur_y += fgi->mYAdvance;

		llwchar next_char = wstr[i+1];
		if (next_char && (next_char < LAST_CHARACTER))
		{
			// Kern this puppy.
			next_glyph = mFontFreetype->getGlyphInfo(next_char);
			cur_x += mFontFreetype->getXKerning(fgi, next_glyph);
		}

		// Round after kerning.
		// Must do this to cur_x, not just to cur_render_x, otherwise you
		// will squish sub-pixel kerned characters too close together.
		// For example, "CCCCC" looks bad.
		cur_x = (F32)ll_round(cur_x);
		//cur_y = (F32)ll_round(cur_y);

		cur_render_x = cur_x;
		cur_render_y = cur_y;
	}

	if (glyph_count > 0)
	{
		gGL.begin(LLRender::QUADS);
		{
			gGL.vertexBatchPreTransformed(vertices, uvs, colors, glyph_count * 4);
		}
		gGL.end();
	}


	if (right_x)
	{
		*right_x = (cur_x - origin.mV[VX]) / sScaleX;
	}

	//FIXME: add underline as glyph?
	if (style_to_add & UNDERLINE)
	{
		F32 descender = mFontFreetype->getDescenderHeight();

		gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
		gGL.begin(LLRender::LINES);
		gGL.vertex2f(start_x, cur_y - descender);
		gGL.vertex2f(cur_x, cur_y - descender);
		gGL.end();
	}

	if (draw_ellipses)
	{
		
		// recursively render ellipses at end of string
		// we've already reserved enough room
		gGL.pushUIMatrix();
		renderUTF8(std::string("..."), 
				0,
				(cur_x - origin.mV[VX]) / sScaleX, (F32)y,
				color,
				LEFT, valign,
				style_to_add,
				shadow,
				S32_MAX, max_pixels,
				right_x,
				FALSE); 
		gGL.popUIMatrix();
	}

	gGL.popUIMatrix();

	return chars_drawn;
}
Пример #19
0
    void draw() {
        // Attempting to draw before we're visible and have a valid size will
        // produce GL errors.
        if (!isVisible() || _size.width() <= 0 || _size.height() <= 0) {
            return;
        }
        makeCurrent();
        
        gpu::Batch batch;
        batch.clearColorFramebuffer(gpu::Framebuffer::BUFFER_COLORS, { 0.0f, 0.0f, 0.0f, 1.0f });
        batch.clearDepthFramebuffer(1e4);
        batch.setViewportTransform({ 0, 0, _size.width() * devicePixelRatio(), _size.height() * devicePixelRatio() });
        batch.setProjectionTransform(_projectionMatrix);
        
        float t = _time.elapsed() * 1e-3f;
        glm::vec3 unitscale { 1.0f };
        glm::vec3 up { 0.0f, 1.0f, 0.0f };

        float distance = 3.0f;
        glm::vec3 camera_position{ distance * sinf(t), 0.0f, distance * cosf(t) };

        static const vec3 camera_focus(0);
        static const vec3 camera_up(0, 1, 0);
        glm::mat4 camera = glm::inverse(glm::lookAt(camera_position, camera_focus, up));
        batch.setViewTransform(camera);
        batch.setPipeline(_pipeline);
        batch.setModelTransform(Transform());

        auto geometryCache = DependencyManager::get<GeometryCache>();

        // Render grid on xz plane (not the optimal way to do things, but w/e)
        // Note: GeometryCache::renderGrid will *not* work, as it is apparenly unaffected by batch rotations and renders xy only
        {
            static const std::string GRID_INSTANCE = "Grid";
            static auto compactColor1 = toCompactColor(vec4{ 0.35f, 0.25f, 0.15f, 1.0f });
            static auto compactColor2 = toCompactColor(vec4{ 0.15f, 0.25f, 0.35f, 1.0f });
            static std::vector<glm::mat4> transforms;
            static gpu::BufferPointer colorBuffer;
            if (!transforms.empty()) {
                transforms.reserve(200);
                colorBuffer = std::make_shared<gpu::Buffer>();
                for (int i = 0; i < 100; ++i) {
                    {
                        glm::mat4 transform = glm::translate(mat4(), vec3(0, -1, -50 + i));
                        transform = glm::scale(transform, vec3(100, 1, 1));
                        transforms.push_back(transform);
                        colorBuffer->append(compactColor1);
                    }

                    {
                        glm::mat4 transform = glm::mat4_cast(quat(vec3(0, PI / 2.0f, 0)));
                        transform = glm::translate(transform, vec3(0, -1, -50 + i));
                        transform = glm::scale(transform, vec3(100, 1, 1));
                        transforms.push_back(transform);
                        colorBuffer->append(compactColor2);
                    }
                }
            }

            auto pipeline = geometryCache->getSimplePipeline();
            for (auto& transform : transforms) {
                batch.setModelTransform(transform);
                batch.setupNamedCalls(GRID_INSTANCE, [=](gpu::Batch& batch, gpu::Batch::NamedBatchData& data) {
                    batch.setViewTransform(camera);
                    batch.setPipeline(_pipeline);
                    geometryCache->renderWireShapeInstances(batch, GeometryCache::Line, data.count(), colorBuffer);
                });
            }
        }

        {
            static const size_t ITEM_COUNT = 1000;
            static const float SHAPE_INTERVAL = (PI * 2.0f) / ITEM_COUNT;
            static const float ITEM_INTERVAL = SHAPE_INTERVAL / TYPE_COUNT;

            static const gpu::Element POSITION_ELEMENT{ gpu::VEC3, gpu::FLOAT, gpu::XYZ };
            static const gpu::Element NORMAL_ELEMENT{ gpu::VEC3, gpu::FLOAT, gpu::XYZ };
            static const gpu::Element COLOR_ELEMENT{ gpu::VEC4, gpu::NUINT8, gpu::RGBA };
            static const gpu::Element TRANSFORM_ELEMENT{ gpu::MAT4, gpu::FLOAT, gpu::XYZW };


            static std::vector<Transform> transforms;
            static std::vector<vec4> colors;
            static gpu::BufferPointer indirectBuffer;
            static gpu::BufferPointer transformBuffer;
            static gpu::BufferPointer colorBuffer;
            static gpu::BufferView colorView; 
            static gpu::BufferView instanceXfmView; 

            if (!transformBuffer) {
                transformBuffer = std::make_shared<gpu::Buffer>();
                colorBuffer = std::make_shared<gpu::Buffer>();
                indirectBuffer = std::make_shared<gpu::Buffer>();

                static const float ITEM_RADIUS = 20;
                static const vec3 ITEM_TRANSLATION{ 0, 0, -ITEM_RADIUS };
                for (size_t i = 0; i < TYPE_COUNT; ++i) {
                    GeometryCache::Shape shape = SHAPE[i];
                    GeometryCache::ShapeData shapeData = geometryCache->_shapes[shape];
                    {
                        gpu::Batch::DrawIndexedIndirectCommand indirectCommand;
                        indirectCommand._count = (uint)shapeData._indexCount;
                        indirectCommand._instanceCount = ITEM_COUNT;
                        indirectCommand._baseInstance = (uint)(i * ITEM_COUNT);
                        indirectCommand._firstIndex = (uint)shapeData._indexOffset / 2;
                        indirectCommand._baseVertex = 0;
                        indirectBuffer->append(indirectCommand);
                    }

                    //indirectCommand._count
                    float startingInterval = ITEM_INTERVAL * i;
                    for (size_t j = 0; j < ITEM_COUNT; ++j) {
                        float theta = j * SHAPE_INTERVAL + startingInterval;
                        auto transform = glm::rotate(mat4(), theta, Vectors::UP);
                        transform = glm::rotate(transform, (randFloat() - 0.5f) * PI / 4.0f, Vectors::UNIT_X);
                        transform = glm::translate(transform, ITEM_TRANSLATION);
                        transform = glm::scale(transform, vec3(randFloat() / 2.0f + 0.5f));
                        transformBuffer->append(transform);
                        transforms.push_back(transform);
                        auto color = vec4{ randomColorValue(64), randomColorValue(64), randomColorValue(64), 255 };
                        color /= 255.0f;
                        colors.push_back(color);
                        colorBuffer->append(toCompactColor(color));
                    }
                }
                colorView = gpu::BufferView(colorBuffer, COLOR_ELEMENT);
                instanceXfmView = gpu::BufferView(transformBuffer, TRANSFORM_ELEMENT);
            }

#if 1
            GeometryCache::ShapeData shapeData = geometryCache->_shapes[GeometryCache::Icosahedron];
            {
                batch.setViewTransform(camera);
                batch.setModelTransform(Transform());
                batch.setPipeline(_pipeline);
                batch.setInputFormat(getInstancedSolidStreamFormat());
                batch.setInputBuffer(gpu::Stream::COLOR, colorView);
                batch.setIndirectBuffer(indirectBuffer);
                shapeData.setupBatch(batch);
                batch.multiDrawIndexedIndirect(TYPE_COUNT, gpu::TRIANGLES);
            }
#else
            batch.setViewTransform(camera);
            batch.setPipeline(_pipeline);
            for (size_t i = 0; i < TYPE_COUNT; ++i) {
                GeometryCache::Shape shape = SHAPE[i];
                for (size_t j = 0; j < ITEM_COUNT; ++j) {
                    int index = i * ITEM_COUNT + j;
                    batch.setModelTransform(transforms[index]);
                    const vec4& color = colors[index];
                    batch._glColor4f(color.r, color.g, color.b, 1.0);
                    geometryCache->renderShape(batch, shape);
                }
            }
#endif
        }

        // Render unlit cube + sphere
        static auto startUsecs = usecTimestampNow(); 
        float seconds = getSeconds(startUsecs);

        seconds /= 4.0f;
        int shapeIndex = ((int)seconds) % TYPE_COUNT;
        bool wire = (seconds - floorf(seconds) > 0.5f);
        batch.setModelTransform(Transform());
        batch._glColor4f(0.8f, 0.25f, 0.25f, 1.0f);

        if (wire) {
            geometryCache->renderWireShape(batch, SHAPE[shapeIndex]);
        } else {
            geometryCache->renderShape(batch, SHAPE[shapeIndex]);
        }
        
        batch.setModelTransform(Transform().setScale(2.05f));
        batch._glColor4f(1, 1, 1, 1);
        geometryCache->renderWireCube(batch);

        _context->render(batch);
        _qGlContext.swapBuffers(this);
        
        fps.increment();
        if (fps.elapsed() >= 0.5f) {
            qDebug() << "FPS: " << fps.rate();
            fps.reset();
        }
    }
Пример #20
0
// Vectorized 2d simplex noise.
float noise2d(float v1, float v2) {

    const float C[] = {
        0.211324865405187f,
        0.366025403784439f,
        -0.577350269189626f,
        0.024390243902439f };

    // First corner
    float i[2];
    i[0] = floorf(v1 + v1*C[1] + v2*C[1]);
    i[1] = floorf(v2 + v1*C[1] + v2*C[1]);

    float x0[2];
    x0[0] = v1 - i[0] + i[0]*C[0] + i[1]*C[0];
    x0[1] = v2 - i[1] + i[0]*C[0] + i[1]*C[0];

    // Other corners
    float i1[2];
    if (x0[0] > x0[1]) {
        i1[0] = 1;
        i1[1] = 0;
    } else {
        i1[0] = 0;
        i1[1] = 1;
    }

    float x12[4];
    x12[0] = x0[0] + C[0] - i1[0];
    x12[1] = x0[1] + C[0] - i1[1];
    x12[2] = x0[0] + C[2];
    x12[3] = x0[1] + C[2];

    // Permutations
    i[0] = mod289(i[0]);
    i[1] = mod289(i[1]);

    float p[3];
    p[0] = permute(permute(i[1]) + i[0]);
    p[1] = permute(permute(i[1] + i1[1]) + i[0] + i1[0]);
    p[2] = permute(permute(i[1] + 1) + i[0] + 1);

    float m[3];
    m[0] = std::max<float>(0.5f - x0[0]*x0[0] - x0[1]*x0[1], 0);
    m[1] = std::max<float>(0.5f - x12[0]*x12[0] - x12[1]*x12[1], 0);
    m[2] = std::max<float>(0.5f - x12[2]*x12[2] - x12[3]*x12[3], 0);

    m[0] = m[0] * m[0] * m[0] * m[0];
    m[1] = m[1] * m[1] * m[1] * m[1];
    m[2] = m[2] * m[2] * m[2] * m[2];

    // Gradients
    float tmp;

    float x[3];
    x[0] = 2 * modff(p[0] * C[3], &tmp) - 1;
    x[1] = 2 * modff(p[1] * C[3], &tmp) - 1;
    x[2] = 2 * modff(p[2] * C[3], &tmp) - 1;

    float h[3];
    h[0] = fabsf(x[0]) - 0.5f;
    h[1] = fabsf(x[1]) - 0.5f;
    h[2] = fabsf(x[2]) - 0.5f;

    float ox[3];
    ox[0] = floorf(x[0] + 0.5f);
    ox[1] = floorf(x[1] + 0.5f);
    ox[2] = floorf(x[2] + 0.5f);

    float a0[3];
    a0[0] = x[0] - ox[0];
    a0[1] = x[1] - ox[1];
    a0[2] = x[2] - ox[2];

    // Normalize
    m[0] *= 1.79284291400159f - 0.85373472095314f * (a0[0]*a0[0] + h[0]*h[0]);
    m[1] *= 1.79284291400159f - 0.85373472095314f * (a0[1]*a0[1] + h[1]*h[1]);
    m[2] *= 1.79284291400159f - 0.85373472095314f * (a0[2]*a0[2] + h[2]*h[2]);

    // Compute final value
    float g[3];
    g[0] = a0[0] * x0[0] + h[0] * x0[1];
    g[1] = a0[1] * x12[0] + h[1] * x12[1];
    g[2] = a0[2] * x12[2] + h[2] * x12[3];

    return 130 * (m[0] * g[0] + m[1] * g[1] + m[2] * g[2]);
}
Пример #21
0
float Math::Floor(float x)
{
    return floorf(x);
}
Пример #22
0
FileTypesWindow::FileTypesWindow(const BMessage& settings)
    :
    BWindow(_Frame(settings), B_TRANSLATE_SYSTEM_NAME("FileTypes"),
           B_TITLED_WINDOW, B_NOT_ZOOMABLE | B_ASYNCHRONOUS_CONTROLS
           | B_AUTO_UPDATE_SIZE_LIMITS),
    fNewTypeWindow(NULL)
{
    bool showIcons;
    bool showRule;
    if (settings.FindBool("show_icons", &showIcons) != B_OK)
        showIcons = true;
    if (settings.FindBool("show_rule", &showRule) != B_OK)
        showRule = false;

    float padding = be_control_look->DefaultItemSpacing();
    BAlignment labelAlignment = be_control_look->DefaultLabelAlignment();
    BAlignment fullAlignment(B_ALIGN_USE_FULL_WIDTH, B_ALIGN_USE_FULL_HEIGHT);

    // add the menu
    BMenuBar* menuBar = new BMenuBar("");

    BMenu* menu = new BMenu(B_TRANSLATE("File"));
    BMenuItem* item = new BMenuItem(
        B_TRANSLATE("New resource file" B_UTF8_ELLIPSIS), NULL, 'N',
        B_COMMAND_KEY);
    item->SetEnabled(false);
    menu->AddItem(item);

    BMenu* recentsMenu = BRecentFilesList::NewFileListMenu(
                             B_TRANSLATE("Open" B_UTF8_ELLIPSIS), NULL, NULL,
                             be_app, 10, false, NULL, kSignature);
    item = new BMenuItem(recentsMenu, new BMessage(kMsgOpenFilePanel));
    item->SetShortcut('O', B_COMMAND_KEY);
    menu->AddItem(item);

    menu->AddItem(new BMenuItem(
                      B_TRANSLATE("Application types" B_UTF8_ELLIPSIS),
                      new BMessage(kMsgOpenApplicationTypesWindow)));
    menu->AddSeparatorItem();

    menu->AddItem(new BMenuItem(B_TRANSLATE("Quit"),
                                new BMessage(B_QUIT_REQUESTED), 'Q', B_COMMAND_KEY));
    menu->SetTargetForItems(be_app);
    menuBar->AddItem(menu);

    menu = new BMenu(B_TRANSLATE("Settings"));
    item = new BMenuItem(B_TRANSLATE("Show icons in list"),
                         new BMessage(kMsgToggleIcons));
    item->SetMarked(showIcons);
    item->SetTarget(this);
    menu->AddItem(item);

    item = new BMenuItem(B_TRANSLATE("Show recognition rule"),
                         new BMessage(kMsgToggleRule));
    item->SetMarked(showRule);
    item->SetTarget(this);
    menu->AddItem(item);
    menuBar->AddItem(menu);
    menuBar->SetExplicitAlignment(BAlignment(B_ALIGN_LEFT, B_ALIGN_TOP));

    // MIME Types list
    BButton* addTypeButton = new BButton("add",
                                         B_TRANSLATE("Add" B_UTF8_ELLIPSIS), new BMessage(kMsgAddType));

    fRemoveTypeButton = new BButton("remove", B_TRANSLATE("Remove"),
                                    new BMessage(kMsgRemoveType) );

    fTypeListView = new MimeTypeListView("typeview", NULL, showIcons, false);
    fTypeListView->SetSelectionMessage(new BMessage(kMsgTypeSelected));
    fTypeListView->SetExplicitMinSize(BSize(200, B_SIZE_UNSET));

    BScrollView* typeListScrollView = new BScrollView("scrollview",
            fTypeListView, B_FRAME_EVENTS | B_WILL_DRAW, false, true);

    // "Icon" group

    fIconView = new TypeIconView("icon");
    fIconBox = new BBox("Icon BBox");
    fIconBox->SetLabel(B_TRANSLATE("Icon"));
    BLayoutBuilder::Group<>(fIconBox, B_VERTICAL, padding)
    .SetInsets(padding)
    .AddGlue(1)
    .Add(fIconView, 3)
    .AddGlue(1);

    // "File Recognition" group

    fRecognitionBox = new BBox("Recognition Box");
    fRecognitionBox->SetLabel(B_TRANSLATE("File recognition"));
    fRecognitionBox->SetExplicitAlignment(fullAlignment);

    fExtensionLabel = new StringView(B_TRANSLATE("Extensions:"), NULL);
    fExtensionLabel->LabelView()->SetExplicitAlignment(labelAlignment);

    fAddExtensionButton = new BButton("add ext",
                                      B_TRANSLATE("Add" B_UTF8_ELLIPSIS), new BMessage(kMsgAddExtension));
    fAddExtensionButton->SetExplicitMaxSize(
        BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));

    fRemoveExtensionButton = new BButton("remove ext", B_TRANSLATE("Remove"),
                                         new BMessage(kMsgRemoveExtension));

    fExtensionListView = new ExtensionListView("listview ext",
            B_SINGLE_SELECTION_LIST);
    fExtensionListView->SetSelectionMessage(
        new BMessage(kMsgExtensionSelected));
    fExtensionListView->SetInvocationMessage(
        new BMessage(kMsgExtensionInvoked));

    BScrollView* scrollView = new BScrollView("scrollview ext",
            fExtensionListView, B_FRAME_EVENTS | B_WILL_DRAW, false, true);

    fRuleControl = new BTextControl("rule", B_TRANSLATE("Rule:"), "",
                                    new BMessage(kMsgRuleEntered));
    fRuleControl->SetAlignment(B_ALIGN_RIGHT, B_ALIGN_LEFT);
    fRuleControl->Hide();

    BLayoutBuilder::Grid<>(fRecognitionBox, padding, padding / 2)
    .SetInsets(padding, padding * 2, padding, padding)
    .Add(fExtensionLabel->LabelView(), 0, 0)
    .Add(scrollView, 0, 1, 2, 2)
    .Add(fAddExtensionButton, 2, 1)
    .Add(fRemoveExtensionButton, 2, 2)
    .Add(fRuleControl, 0, 3, 3, 1);

    // "Description" group

    fDescriptionBox = new BBox("description BBox");
    fDescriptionBox->SetLabel(B_TRANSLATE("Description"));
    fDescriptionBox->SetExplicitAlignment(fullAlignment);

    fInternalNameView = new StringView(B_TRANSLATE("Internal name:"), NULL);
    fInternalNameView->SetEnabled(false);
    fTypeNameControl = new BTextControl("type", B_TRANSLATE("Type name:"), "",
                                        new BMessage(kMsgTypeEntered));
    fDescriptionControl = new BTextControl("description",
                                           B_TRANSLATE("Description:"), "", new BMessage(kMsgDescriptionEntered));

    BLayoutBuilder::Grid<>(fDescriptionBox, padding / 2, padding / 2)
    .SetInsets(padding, padding * 2, padding, padding)
    .Add(fInternalNameView->LabelView(), 0, 0)
    .Add(fInternalNameView->TextView(), 1, 0)
    .Add(fTypeNameControl->CreateLabelLayoutItem(), 0, 1)
    .Add(fTypeNameControl->CreateTextViewLayoutItem(), 1, 1, 2)
    .Add(fDescriptionControl->CreateLabelLayoutItem(), 0, 2)
    .Add(fDescriptionControl->CreateTextViewLayoutItem(), 1, 2, 2);

    // "Preferred Application" group

    fPreferredBox = new BBox("preferred BBox");
    fPreferredBox->SetLabel(B_TRANSLATE("Preferred application"));

    menu = new BPopUpMenu("preferred");
    menu->AddItem(item = new BMenuItem(B_TRANSLATE("None"),
                                       new BMessage(kMsgPreferredAppChosen)));
    item->SetMarked(true);
    fPreferredField = new BMenuField("preferred", (char*)NULL, menu);

    fSelectButton = new BButton("select",
                                B_TRANSLATE("Select" B_UTF8_ELLIPSIS),
                                new BMessage(kMsgSelectPreferredApp));

    fSameAsButton = new BButton("same as",
                                B_TRANSLATE("Same as" B_UTF8_ELLIPSIS),
                                new BMessage(kMsgSamePreferredAppAs));

    BLayoutBuilder::Group<>(fPreferredBox, B_HORIZONTAL, padding)
    .SetInsets(padding, padding * 2, padding, padding)
    .Add(fPreferredField)
    .Add(fSelectButton)
    .Add(fSameAsButton);

    // "Extra Attributes" group

    fAttributeBox = new BBox("Attribute Box");
    fAttributeBox->SetLabel(B_TRANSLATE("Extra attributes"));

    fAddAttributeButton = new BButton("add attr",
                                      B_TRANSLATE("Add" B_UTF8_ELLIPSIS), new BMessage(kMsgAddAttribute));
    fAddAttributeButton->SetExplicitMaxSize(
        BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));

    fRemoveAttributeButton = new BButton("remove attr", B_TRANSLATE("Remove"),
                                         new BMessage(kMsgRemoveAttribute));
    fRemoveAttributeButton->SetExplicitMaxSize(
        BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));

    fMoveUpAttributeButton = new BButton("move up attr", B_TRANSLATE("Move up"),
                                         new BMessage(kMsgMoveUpAttribute));
    fMoveUpAttributeButton->SetExplicitMaxSize(
        BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));
    fMoveDownAttributeButton = new BButton("move down attr",
                                           B_TRANSLATE("Move down"), new BMessage(kMsgMoveDownAttribute));
    fMoveDownAttributeButton->SetExplicitMaxSize(
        BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));

    fAttributeListView = new AttributeListView("listview attr");
    fAttributeListView->SetSelectionMessage(
        new BMessage(kMsgAttributeSelected));
    fAttributeListView->SetInvocationMessage(
        new BMessage(kMsgAttributeInvoked));

    BScrollView* attributesScroller = new BScrollView("scrollview attr",
            fAttributeListView, B_FRAME_EVENTS | B_WILL_DRAW, false, true);

    BLayoutBuilder::Group<>(fAttributeBox, B_HORIZONTAL, padding)
    .SetInsets(padding, padding * 2, padding, padding)
    .Add(attributesScroller, 1.0f)
    .AddGroup(B_VERTICAL, padding / 2, 0.0f)
    .SetInsets(0)
    .Add(fAddAttributeButton)
    .Add(fRemoveAttributeButton)
    .AddStrut(padding)
    .Add(fMoveUpAttributeButton)
    .Add(fMoveDownAttributeButton)
    .AddGlue();

    fMainSplitView = new BSplitView(B_HORIZONTAL, floorf(padding / 2));

    BLayoutBuilder::Group<>(this, B_VERTICAL, 0)
    .SetInsets(0)
    .Add(menuBar)
    .AddGroup(B_HORIZONTAL, 0)
    .SetInsets(padding, padding, padding, padding)
    .AddSplit(fMainSplitView)
    .AddGroup(B_VERTICAL, padding)
    .Add(typeListScrollView)
    .AddGroup(B_HORIZONTAL, padding)
    .Add(addTypeButton)
    .Add(fRemoveTypeButton)
    .AddGlue()
    .End()
    .End()
    // Right side
    .AddGroup(B_VERTICAL, padding)
    .AddGroup(B_HORIZONTAL, padding)
    .Add(fIconBox, 1)
    .Add(fRecognitionBox, 3)
    .End()
    .Add(fDescriptionBox)
    .Add(fPreferredBox)
    .Add(fAttributeBox, 5);

    _SetType(NULL);
    _ShowSnifferRule(showRule);

    float leftWeight;
    float rightWeight;
    if (settings.FindFloat("left_split_weight", &leftWeight) != B_OK
            || settings.FindFloat("right_split_weight", &rightWeight) != B_OK) {
        leftWeight = 0.2;
        rightWeight = 1.0 - leftWeight;
    }
    fMainSplitView->SetItemWeight(0, leftWeight, false);
    fMainSplitView->SetItemWeight(1, rightWeight, true);

    BMimeType::StartWatching(this);
}
Пример #23
0
int CtrlDisAsmView::yToAddress(int y)
{
	int ydiff=y-rect.bottom/2-rowHeight/2;
	ydiff=(int)(floorf((float)ydiff / (float)rowHeight))+1;
	return curAddress + ydiff * align;
}
Пример #24
0
void Pipewave::genwave (Addsynth *D, int n, float fsamp, float fpipe)
{
    int    h, i, k, nc;
    float  f0, f1, f, m, t, v, v0;

    m = D->_n_att.vi (n);
    for (h = 0; h < N_HARM; h++)
    {
	t = D->_h_att.vi (h, n);
        if (t > m) m = t;
    }
    _l0 = (int)(fsamp * m + 0.5);
    _l0 = (_l0 + PERIOD - 1) & ~(PERIOD - 1);

    f1 = (fpipe + D->_n_off.vi (n) + D->_n_ran.vi (n) * (2 * _rgen.urand () - 1)) / fsamp;
    f0 = f1 * exp2ap (D->_n_atd.vi (n) / 1200.0f);

    for (h = N_HARM - 1; h >= 0; h--)
    {
        f = (h + 1) * f1;
	if ((f < 0.45f) && (D->_h_lev.vi (h, n) >= -40.0f)) break;
    }
    if      (f > 0.250f) _k_s = 3;
    else if (f > 0.125f) _k_s = 2;
    else                 _k_s = 1;

    looplen (f1 * fsamp, _k_s * fsamp, (int)(fsamp / 6.0f), &_l1, &nc);
    if (_l1 < _k_s * PERIOD)
    {
        k = (_k_s * PERIOD - 1) / _l1 + 1;
        _l1 *= k;
        nc *= k;
    }

    k = _l0 + _l1 + _k_s * (PERIOD + 4);

    delete[] _p0;
    _p0 = new float [k];
    _p1 = _p0 + _l0;
    _p2 = _p1 + _l1;
    memset (_p0, 0, k * sizeof (float));

    _k_r = (int)(ceilf (D->_n_dct.vi (n) * fsamp / PERIOD) + 1);
    _m_r = 1.0f - powf (0.1, 1.0 / _k_r);
    _d_r = _k_s * (exp2ap (D->_n_dcd.vi (n) / 1200.0f) - 1.0f);
    _d_p = D->_n_ins.vi (n);

    t = 0.0f;
    k = (int)(fsamp * D->_n_att.vi (n) + 0.5);
    for (i = 0; i <= _l0; i++)
    {
        _arg [i] = t - floorf (t + 0.5);
	t += (i < k) ? (((k - i) * f0 + i * f1) / k) : f1;
    }

    for (i = 1; i < _l1; i++)
    {
	t = _arg [_l0]+ (float) i * nc / _l1;
        _arg [i + _l0] = t - floorf (t + 0.5);
    }

    v0 = exp2ap (0.1661 * D->_n_vol.vi (n));
    for (h = 0; h < N_HARM; h++)
    {
        if ((h + 1) * f1 > 0.45) break;
        v = D->_h_lev.vi (h, n);
        if (v < -80.0) continue;

        v = v0 * exp2ap (0.1661 * (v + D->_h_ran.vi (h, n) * (2 * _rgen.urand () - 1)));
        k = (int)(fsamp * D->_h_att.vi (h, n) + 0.5);
        attgain (k, D->_h_atp.vi (h, n));

        for (i = 0; i < _l0 + _l1; i++)
        {
	    t = _arg [i] * (h + 1);
            t -= floorf (t);
            m = v * sinf (2 * M_PI * t);
            if (i < k) m *= _att [i];
            _p0 [i] += m;
        }
    }
    for (i = 0; i < _k_s * (PERIOD + 4); i++) _p0 [i + _l0 + _l1] = _p0 [i + _l0];
}
Пример #25
0
float poly_triangle(float amplitude, float freq, float phase)
{
	// Triangle wave implemented as absolute value of sawtooth wave:
	// (signal amplitude) * (peak amplitude) * (2 * abs(sawtooth(t, phase)) - 1)
	return amplitude * POLY_MAX_AMP * (2 * fabsf(2 * (freq * (((float)poly_time)/(poly_format->rate) + phase*(1.0/freq)) - floorf(0.5 + (((float)poly_time)/(poly_format->rate) + phase*(1.0/freq)) * freq))) - 1);
}
Пример #26
0
void vm_floor_float_to_int(const ScriptArguments& args)
{
	/// @todo Not sure if this might round to zero
	*args[0].globalInteger = floorf(*args[1].globalReal);
}
Пример #27
0
static SkFixed fixlen(SkFixed x, SkFixed y) {
    float fx = (float)x;
    float fy = (float)y;

    return (int)floorf(sqrtf(fx*fx + fy*fy) + 0.5f);
}
Пример #28
0
void
xps_parse_tiling_brush(xps_document *doc, const fz_matrix *ctm, const fz_rect *area,
	char *base_uri, xps_resource *dict, fz_xml *root,
	void (*func)(xps_document*, const fz_matrix*, const fz_rect*, char*, xps_resource*, fz_xml*, void*), void *user)
{
	fz_xml *node;
	struct closure c;

	char *opacity_att;
	char *transform_att;
	char *viewbox_att;
	char *viewport_att;
	char *tile_mode_att;

	fz_xml *transform_tag = NULL;

	fz_matrix transform;
	fz_rect viewbox;
	fz_rect viewport;
	float xstep, ystep;
	float xscale, yscale;
	int tile_mode;

	opacity_att = fz_xml_att(root, "Opacity");
	transform_att = fz_xml_att(root, "Transform");
	viewbox_att = fz_xml_att(root, "Viewbox");
	viewport_att = fz_xml_att(root, "Viewport");
	tile_mode_att = fz_xml_att(root, "TileMode");

	c.base_uri = base_uri;
	c.dict = dict;
	c.root = root;
	c.user = user;
	c.func = func;

	for (node = fz_xml_down(root); node; node = fz_xml_next(node))
	{
		if (!strcmp(fz_xml_tag(node), "ImageBrush.Transform"))
			transform_tag = fz_xml_down(node);
		if (!strcmp(fz_xml_tag(node), "VisualBrush.Transform"))
			transform_tag = fz_xml_down(node);
	}

	xps_resolve_resource_reference(doc, dict, &transform_att, &transform_tag, NULL);

	transform = fz_identity;
	if (transform_att)
		xps_parse_render_transform(doc, transform_att, &transform);
	if (transform_tag)
		xps_parse_matrix_transform(doc, transform_tag, &transform);
	fz_concat(&transform, &transform, ctm);

	viewbox = fz_unit_rect;
	if (viewbox_att)
		xps_parse_rectangle(doc, viewbox_att, &viewbox);

	viewport = fz_unit_rect;
	if (viewport_att)
		xps_parse_rectangle(doc, viewport_att, &viewport);

	if (fabsf(viewport.x1 - viewport.x0) < 0.01f || fabsf(viewport.y1 - viewport.y0) < 0.01f)
		fz_warn(doc->ctx, "not drawing tile for viewport size %.4f x %.4f", viewport.x1 - viewport.x0, viewport.y1 - viewport.y0);
	else if (fabsf(viewbox.x1 - viewbox.x0) < 0.01f || fabsf(viewbox.y1 - viewbox.y0) < 0.01f)
		fz_warn(doc->ctx, "not drawing tile for viewbox size %.4f x %.4f", viewbox.x1 - viewbox.x0, viewbox.y1 - viewbox.y0);

	/* some sanity checks on the viewport/viewbox size */
	if (fabsf(viewport.x1 - viewport.x0) < 0.01f) return;
	if (fabsf(viewport.y1 - viewport.y0) < 0.01f) return;
	if (fabsf(viewbox.x1 - viewbox.x0) < 0.01f) return;
	if (fabsf(viewbox.y1 - viewbox.y0) < 0.01f) return;

	xstep = viewbox.x1 - viewbox.x0;
	ystep = viewbox.y1 - viewbox.y0;

	xscale = (viewport.x1 - viewport.x0) / xstep;
	yscale = (viewport.y1 - viewport.y0) / ystep;

	tile_mode = TILE_NONE;
	if (tile_mode_att)
	{
		if (!strcmp(tile_mode_att, "None"))
			tile_mode = TILE_NONE;
		if (!strcmp(tile_mode_att, "Tile"))
			tile_mode = TILE_TILE;
		if (!strcmp(tile_mode_att, "FlipX"))
			tile_mode = TILE_FLIP_X;
		if (!strcmp(tile_mode_att, "FlipY"))
			tile_mode = TILE_FLIP_Y;
		if (!strcmp(tile_mode_att, "FlipXY"))
			tile_mode = TILE_FLIP_X_Y;
	}

	if (tile_mode == TILE_FLIP_X || tile_mode == TILE_FLIP_X_Y)
		xstep *= 2;
	if (tile_mode == TILE_FLIP_Y || tile_mode == TILE_FLIP_X_Y)
		ystep *= 2;

	xps_begin_opacity(doc, &transform, area, base_uri, dict, opacity_att, NULL);

	fz_pre_translate(&transform, viewport.x0, viewport.y0);
	fz_pre_scale(&transform, xscale, yscale);
	fz_pre_translate(&transform, -viewbox.x0, -viewbox.y0);

	if (tile_mode != TILE_NONE)
	{
		int x0, y0, x1, y1;
		fz_matrix invctm;
		fz_rect local_area = *area;
		fz_transform_rect(&local_area, fz_invert_matrix(&invctm, &transform));
		/* SumatraPDF: make sure that the intended area is covered */
		{
			fz_point tl;
			fz_irect bbox;
			fz_rect bigview = viewbox;
			bigview.x1 = bigview.x0 + xstep;
			bigview.y1 = bigview.y0 + ystep;
			fz_irect_from_rect(&bbox, fz_transform_rect(&bigview, &transform));
			tl.x = bbox.x0;
			tl.y = bbox.y0;
			fz_transform_point(&tl, &invctm);
			local_area.x0 -= fz_max(tl.x, 0); local_area.x1 += xstep - fz_max(tl.x, 0);
			local_area.y0 -= fz_max(tl.y, 0); local_area.y1 += ystep - fz_max(tl.y, 0);
		}
		x0 = floorf(local_area.x0 / xstep);
		y0 = floorf(local_area.y0 / ystep);
		x1 = ceilf(local_area.x1 / xstep);
		y1 = ceilf(local_area.y1 / ystep);

#ifdef TILE
		/* cf. http://code.google.com/p/sumatrapdf/issues/detail?id=2248 */
		if ((local_area.x1 - local_area.x0) / xstep > 1 || (local_area.y1 - local_area.y0) / ystep > 1)
#else
		if (0)
#endif
		{
			fz_rect bigview = viewbox;
			bigview.x1 = bigview.x0 + xstep;
			bigview.y1 = bigview.y0 + ystep;
			fz_begin_tile(doc->dev, &local_area, &bigview, xstep, ystep, &transform);
			xps_paint_tiling_brush(doc, &transform, &viewbox, tile_mode, &c);
			fz_end_tile(doc->dev);
		}
		else
		{
			int x, y;
			for (y = y0; y < y1; y++)
			{
				for (x = x0; x < x1; x++)
				{
					fz_matrix ttm = transform;
					fz_pre_translate(&ttm, xstep * x, ystep * y);
					xps_paint_tiling_brush(doc, &ttm, &viewbox, tile_mode, &c);
				}
			}
		}
	}
	else
	{
		xps_paint_tiling_brush(doc, &transform, &viewbox, tile_mode, &c);
	}

	xps_end_opacity(doc, base_uri, dict, opacity_att, NULL);
}
Пример #29
0
void Ghost::movementChooser(tmx::TileMap *map, const sf::Vector2f& pacman_pos, const Pacman::Direction& pacman_dir) {
    sf::Vector2f target;

    if (state_ == State::InHouse) {
        this->houseMovement();
        return;
    } else if (state_ == State::ToHouse) {
        this->toHouseMovement(map, {(house_bounds_.left + 28), (house_bounds_.top - 8)});
        return;
    }

    // Check if the ghost is not on a Tile
    if ((static_cast<int>(this->getCollisionBox().left) % 8) != 0 ||
        (static_cast<int>(this->getCollisionBox().top) % 8) != 0) {
        return;
    }

    sf::Vector2f pacman_facing;  // Pacman's facing unitary vector

    sf::Vector2f distance_to_pacman;

    switch(pacman_dir) {
        case Left:
            pacman_facing = {-1, 0};
            break;
        case Right:
            pacman_facing = {1, 0};
            break;
        case Up:
            pacman_facing = {0, -1};
            break;
        case Down:
            pacman_facing = {0, 1};
            break;
        default:
            break;
    }

    switch (state_) {
        case Ghost::Chase:
            switch (name_) {
                case Blinky:
                    target = pacman_pos;
                    break;
                case Inky:
                    // Target the pacman position but four tiles ahead.
                    distance_to_pacman = pacman_pos + pacman_facing * (2.f * 8.f) - this->getPosition();
                    target = pacman_pos + distance_to_pacman;
                    break;
                case Pinky:
                    // Target the pacman position but four tiles ahead.
                    distance_to_pacman = pacman_pos + pacman_facing * (2.f * 8.f) - this->getPosition();
                    target = pacman_pos + pacman_facing * (4.f * 8.f);
                    break;
                case Clyde:
                    distance_to_pacman = pacman_pos - this->getPosition();
                    if ((abs(distance_to_pacman.x) + abs(distance_to_pacman.y)) / 8 <= 8)
                        target = {0*8, 35*8};
                    else
                        target = pacman_pos;
                    break;
            }
            this->focusMovement(map, target);
            break;
        case Ghost::Scatter:
            switch (name_) {
                case Blinky:
                    target = {25*8, 0*8};
                    break;
                case Inky:
                    target = {27*8, 35*8};
                    break;
                case Pinky:
                    target = {2*8, 0*8};
                    break;
                case Clyde:
                    target = {0*8, 35*8};
                    break;
            }
            if (state_timer.getElapsedTime().asSeconds() >= 7) this->setState(Chase);
            this->focusMovement(map, target);
            break;
        case Ghost::Frightened:
            this->randomMovement(map);
            if (state_timer.getElapsedTime().asSeconds() >= 5) {
                this->setState(Chase);
                const sf::Vector2f& pos = this->getPosition();
                this->setPosition(floorf(pos.x), floorf(pos.y));
            }
            break;
        default:
            break;
    }
}
Пример #30
0
static void SetSpriteTimer(struct SPRITE *s, float secs, void (*f)(struct SPRITE *))
{
    /* set timer for this sprite */
    s->timeLeft = floorf(secs * 60);
    s->timerFunc = f;
}