예제 #1
0
파일: FileChunk.cpp 프로젝트: RCB35/synergy
void
FileChunk::send(synergy::IStream* stream, UInt8 mark, char* data, size_t dataSize)
{
	String chunk(data, dataSize);

	switch (mark) {
	case kDataStart:
		LOG((CLOG_DEBUG2 "sending file chunk start: size=%s", data));
		break;

	case kDataChunk:
		LOG((CLOG_DEBUG2 "sending file chunk: size=%i", chunk.size()));
		break;

	case kDataEnd:
		LOG((CLOG_DEBUG2 "sending file finished"));
		break;
	}

	ProtocolUtil::writef(stream, kMsgDFileTransfer, mark, &chunk);
}
예제 #2
0
void
CClientProxy1_5::fileChunkSending(UInt8 mark, char* data, size_t dataSize)
{
    CString chunk(data, dataSize);

    switch (mark) {
    case kFileStart:
        LOG((CLOG_DEBUG2 "file sending start: size=%s", data));
        break;

    case kFileChunk:
        LOG((CLOG_DEBUG2 "file chunk sending: size=%i", chunk.size()));
        break;

    case kFileEnd:
        LOG((CLOG_DEBUG2 "file sending finished"));
        break;
    }

    CProtocolUtil::writef(getStream(), kMsgDFileTransfer, mark, &chunk);
}
예제 #3
0
 void setSingleChunkForShards( const vector<BSONObj> &splitPoints ) {
     ChunkMap &chunkMap = const_cast<ChunkMap&>( _chunkMap );
     ChunkRangeManager &chunkRanges = const_cast<ChunkRangeManager&>( _chunkRanges );
     set<Shard> &shards = const_cast<set<Shard>&>( _shards );
     
     vector<BSONObj> mySplitPoints( splitPoints );
     mySplitPoints.insert( mySplitPoints.begin(), _key.globalMin() );
     mySplitPoints.push_back( _key.globalMax() );
     
     for( unsigned i = 1; i < mySplitPoints.size(); ++i ) {
         string name = str::stream() << (i-1);
         Shard shard( name, name );
         shards.insert( shard );
         
         ChunkPtr chunk( new Chunk( this, mySplitPoints[ i-1 ], mySplitPoints[ i ],
                                   shard ) );
         chunkMap[ mySplitPoints[ i ] ] = chunk;
     }
     
     chunkRanges.reloadAll( chunkMap );
 }
예제 #4
0
static void body (LexState *ls, expdesc *e, int needself, int line) {
  /* body ->  `(' parlist `)' chunk END */
  FuncState new_fs;
  open_func(ls, &new_fs);
#if LUA_REFCOUNT
  luarc_addrefproto(new_fs.f);
#endif /* LUA_REFCOUNT */
  new_fs.f->linedefined = line;
  checknext(ls, '(');
  if (needself) {
    new_localvarliteral(ls, "self", 0);
    adjustlocalvars(ls, 1);
  }
  parlist(ls);
  checknext(ls, ')');
  chunk(ls);
  new_fs.f->lastlinedefined = ls->linenumber;
  check_match(ls, TK_END, TK_FUNCTION, line);
  close_func(ls);
  pushclosure(ls, &new_fs, e);
}
void chunk(int **data) {
	int *p0 = data[0];
	int *p1 = data[1];
	int *p2 = data[2];
	int *p3 = data[3];
	
	if(*p0 >= *p3) 
		return;
	
	(*p0)++;
	
	*p2 = *p3;
	
	data[1] = malloc(sizeof(int*));
	data[2] = data[1];
	data[3] = data[2];
	
	chunk(data);
	
	free(p3);
}
예제 #6
0
/** 현재 Energy Level 값 
 *
 * @param pId EUI64 ID
 *
 * @return 
 *      IF4ERR_NOERROR 성공
 *      IF4ERR_INVALID_ID 잘못된 ID
 *      IF4ERR_INVALID_PARAM 잘못된 pEnergyLevel pointer
 *      IF4ERR_DO_NOT_SUPPORT 지원하지 않음
 *      IF4ERR_CANNOT_CONNECT 장비에 연결되지 않음
 */
int COsakiParser::GetEnergyLevel(EUI64 *pId, BYTE *pEnergyLevel)
{
    CMDPARAM cmdParam;
    METER_STAT stat;
    int nError;
    BYTE nEnergyLevel=0;
	CChunk chunk(128);

    if(pId == NULL) return IF4ERR_INVALID_ID;
    if(pEnergyLevel == NULL) return IF4ERR_INVALID_PARAM;

    memset(&cmdParam, 0, sizeof(CMDPARAM));
    memset(&stat, 0, sizeof(METER_STAT));

    memcpy(&cmdParam.id, pId, sizeof(EUI64));
    cmdParam.codi      = GetCoordinator();
    cmdParam.nMeteringType = METERING_TYPE_BYPASS;
    cmdParam.nOption = ONDEMAND_OPTION_GET_RELAY_STATUS;
	cmdParam.pChunk	= &chunk;

    nError = METERING(&cmdParam, &stat);
    switch(nError) {
        case ONDEMAND_ERROR_OK:
            m_pEndDeviceList->GetEnergyLevel(pId, &nEnergyLevel, NULL);
            *pEnergyLevel = nEnergyLevel;
/** 제주실증단지 DR Level 적용 Patch */
#if     defined(__PATCH_11_65__)
            if(*m_pbPatch_11_65) {
                *pEnergyLevel = Patch_11_65_Nuri2Jeju(nEnergyLevel);
            }
#endif
            return IF4ERR_NOERROR;
        case ONDEMAND_ERROR_NOT_CONNECT:
        case ONDEMAND_ERROR_INIT:
        case ONDEMAND_ERROR_BUSY:
            return IF4ERR_CANNOT_CONNECT;
        default:
            return IF4ERR_UNKNOWN_ERROR;
    }
}
void ExplodingSprite::makeChunks(unsigned int n) { 
  // Break the SDL_Surface into n*n squares; where each square
  // has width and height of frameWidth/n and frameHeight/n
  unsigned int chunk_width = frame->getWidth()/n;
  unsigned int chunk_height = frame->getHeight()/n;
  Sint16 source_x = frame->getSourceX();
  Sint16 source_y = frame->getSourceY();
  int speedx = static_cast<int>(velocityX()); // Wanna test for zero...
  int speedy = static_cast<int>(velocityY()); // Make sure it's an int.
  if (speedx == 0) speedx = 1; // Make sure it's not 0;
  if (speedy == 0) speedy = 1; // Make sure it's not 0;

  // Get the SDL_Surface so we can chunk it:
  SDL_Surface* spriteSurface(frame->getSurface()); 
  // i tracks the width, j tracks the height:
  for (unsigned int i = 0; i < n; ++i) {
    for (unsigned int j = 0; j < n; ++j) {
      // Give each chunk it's own speed/direction:
      float sx = (rand() % speedx + 40) * (rand()%2?-1:1); // 'cause %0 is 
      float sy = (rand() % speedy + 40) * (rand()%2?-1:1); // float except
      Frame* frame = 
            new Frame(spriteSurface, chunk_width, chunk_height,
                  source_x+i*chunk_width,  // x coord of surface
                  source_y+j*chunk_height // y coord of surface
                );
      Chunk chunk(
                Vector2f(X()+i*chunk_width,   // x coord of destination 
                         Y()+j*chunk_height), // y coord of destination
                Vector2f(sx, sy),
                getName()+"Chunk",
                frame);
      // chunks uses value semantics, as does frames, but there's
      // a big difference:
      chunks.push_back(chunk);
      frames.push_back(frame);
    }
  }


}
예제 #8
0
void SmallGraphicsObject::applyTransform() {
  TerrainChunk::PolishView& vx = chunk();

  updateTransform();

  Tempest::Matrix4x4 mat = localTransform(vx);

  MVertex *v = &vx.geometry.vertex[glocation];
  float x, y, z, w = 1;

  for( size_t i=0; i<model->vertex.size(); ++i, ++v ){
    const MVertex & s = model->vertex[i];
    *v = s;
    mat.project( s.x,
                 s.y,
                 s.z - vx.zView/sizeZ(),
                 1, x, y, z, w );

    v->x = x;
    v->y = y;
    v->z = z;

    mat.project( s.nx, s.ny, s.nz, 0, x, y, z, w );
    v->nx = x;
    v->ny = y;
    v->nz = z;

    mat.project( s.bx, s.by, s.bz, 0, x, y, z, w );
    v->bx = x;
    v->by = y;
    v->bz = z;
    }

  uint16_t * id = &vx.geometry.index[ ilocation ];
  for( size_t i=0; i<model->index.size(); ++i, ++id ){
    *id = glocation+model->index[i];
    }

  needToUpdate = false;
  }
예제 #9
0
	//---------------------------------------------------------------------------------
	void MeshAndBspLoadContext::load(const DataStreamExPtr& _dataStream)
	{
		clear();
		mDataStream = _dataStream;

		Progress& progress = Progress::getSingleton();
		progress.setRange(0, 100);

		// Read version and size of entire MeshAndBsp.
		readMeshAndBspHeader();

		// Read mesh
		MshFileLoadContext::load(_dataStream);
		progress.setPosition(5);

		// Read BSP
		bool finish = false;
		while(!finish)
		{
			Chunk chunk(mDataStream);
			switch(chunk.getID())
			{
				case 0xC000: readBspInfo(chunk); break;
				case 0xC010: readPolygonIndices(chunk); break;
				case 0xC040: readBspNodes(chunk); break;
				case 0xC045: readLights(chunk); break;
				case 0xC050: readSectors(chunk); break;
				case 0xC0FF: finish = true; break;
			}
		}
		progress.setPosition(10);

		// Remove excess polygons
		countPolygonUsesInLod0();
		removePolygonsNotUsedInLod0();

		// Log statistics
		logStatistics();
	}
예제 #10
0
void CompareOnTheFlyLight(comparer_context& comp)	{
	scoped_chunk chunk(comp,"aiLight");

	comp.cmp<aiString>("mName");
	const aiLightSourceType type = static_cast<aiLightSourceType>( 
		comp.cmp<uint32_t>("mType"));

	if(type==aiLightSource_DIRECTIONAL) {
		comp.cmp<float>("mAttenuationConstant");
		comp.cmp<float>("mAttenuationLinear");
		comp.cmp<float>("mAttenuationQuadratic");
	}

	comp.cmp<aiVector3D>("mColorDiffuse");
	comp.cmp<aiVector3D>("mColorSpecular");
	comp.cmp<aiVector3D>("mColorAmbient");

	if(type==aiLightSource_SPOT) {
		comp.cmp<float>("mAngleInnerCone");
		comp.cmp<float>("mAngleOuterCone");
	}
}
예제 #11
0
void CacheBase::Write(std::string path, const char* buf, size_t size, off_t off)
{
	FileContent& file = content_list.GetFile(path);
	FileChunk chunk(buf, off, size);
	file.SetChunk(chunk);

	/* No need to lock cache, we don't touch its members */
	pf_stat stat = GetAttr(path);
	time_t now = time(NULL);
	stat.meta_mtime = now;
	stat.mtime = now;
	stat.ctime = now;
	IDList idlist;
	idlist.insert(environment.my_id.Get());
	if(off + (off_t)size > (off_t)stat.size)
	{
		stat.size = (size_t)off + size;
		SetAttr(path, stat, idlist);
	}

	//content_list.RefreshPeersRef(path);
}
예제 #12
0
bool
WaveReader::ScanForwardUntil(uint32_t aWantedChunk, uint32_t* aChunkSize)
{
  NS_ABORT_IF_FALSE(aChunkSize, "Require aChunkSize argument");
  *aChunkSize = 0;

  for (;;) {
    static const unsigned int CHUNK_HEADER_SIZE = 8;
    char chunkHeader[CHUNK_HEADER_SIZE];
    const char* p = chunkHeader;

    if (!ReadAll(chunkHeader, sizeof(chunkHeader))) {
      return false;
    }

    PR_STATIC_ASSERT(sizeof(uint32_t) * 2 <= CHUNK_HEADER_SIZE);
    uint32_t magic = ReadUint32BE(&p);
    uint32_t chunkSize = ReadUint32LE(&p);

    if (magic == aWantedChunk) {
      *aChunkSize = chunkSize;
      return true;
    }

    // RIFF chunks are two-byte aligned, so round up if necessary.
    chunkSize += chunkSize % 2;

    static const unsigned int MAX_CHUNK_SIZE = 1 << 16;
    PR_STATIC_ASSERT(MAX_CHUNK_SIZE < UINT_MAX / sizeof(char));
    nsAutoArrayPtr<char> chunk(new char[MAX_CHUNK_SIZE]);
    while (chunkSize > 0) {
      uint32_t size = NS_MIN(chunkSize, MAX_CHUNK_SIZE);
      if (!ReadAll(chunk.get(), size)) {
        return false;
      }
      chunkSize -= size;
    }
  }
}
예제 #13
0
/** Energy Level 설정
 *
 * @param pId EUI64 ID
 * @param nEnergyLevel 유요한 level 값
 *
 * @return 
 *      IF4ERR_NOERROR 성공
 *      IF4ERR_INVALID_ID 잘못된 ID
 *      IF4ERR_INVALID_PARAM 잘못된 Level 값
 *      IF4ERR_DO_NOT_SUPPORT 지원하지 않음
 *      IF4ERR_CANNOT_CONNECT 장비에 연결되지 않음
 *
 * @see CACDParser#IsDRAsset();
 */
int COsakiParser::SetEnergyLevel(EUI64 *pId, BYTE nEnergyLevel, BYTE *pszCallback, int nCallbakLen)
{
    CMDPARAM cmdParam;
    METER_STAT stat;
    int nError;
	CChunk chunk(128);

    if(pId == NULL) return IF4ERR_INVALID_ID;
    if(nEnergyLevel <= 0 || nEnergyLevel > ENERGY_LEVEL_MAX) return IF4ERR_INVALID_ID;

    memset(&cmdParam, 0, sizeof(CMDPARAM));
    memset(&stat, 0, sizeof(METER_STAT));

    memcpy(&cmdParam.id, pId, sizeof(EUI64));
    cmdParam.codi      = GetCoordinator();
    cmdParam.nMeteringType = METERING_TYPE_BYPASS;
	cmdParam.pChunk	= &chunk;
    switch(nEnergyLevel) {
        case  ENERGY_LEVEL_MIN:
            cmdParam.nOption = ONDEMAND_OPTION_DO_RELAY_ON;
            break;
        default:
            cmdParam.nOption = ONDEMAND_OPTION_DO_RELAY_OFF;
            break;
    }

    nError = METERING(&cmdParam, &stat);
    switch(nError) {
        case ONDEMAND_ERROR_OK:
            return IF4ERR_NOERROR;
        case ONDEMAND_ERROR_NOT_CONNECT:
        case ONDEMAND_ERROR_INIT:
        case ONDEMAND_ERROR_BUSY:
            return IF4ERR_CANNOT_CONNECT;
        default:
            return IF4ERR_UNKNOWN_ERROR;
    }
}
void Chunker::makeChunks(unsigned int n) { 
  // Break the SDL_Surface into n*n squares; where each square
  // has width and height of frameWidth/n and frameHeight/n
  unsigned int chunk_width = std::max(1u, sprite.getFrame()->getWidth()/n);
  unsigned int chunk_height = std::max(1u, sprite.getFrame()->getHeight()/n);
  int speedx = static_cast<int>(sprite.velocityX()); // Wanna test for zero...
  int speedy = static_cast<int>(sprite.velocityY()); // Make sure it's an int.
  if (speedx == 0) speedx = 1; // Make sure it's not 0;
  if (speedy == 0) speedy = 1; // Make sure it's not 0;

  // Get the SDL_Surface so we can chunk it:
  SDL_Surface* spriteSurface(sprite.getFrame()->getSurface()); 
  Sint16 source_y =sprite.getFrame()->getSourceY();
  while  (source_y < sprite.getFrame()->getHeight() ) {
    Sint16 source_x = sprite.getFrame()->getSourceX();
    while ( source_x < sprite.getFrame()->getWidth() ) {
      // Give each chunk it's own speed/direction:
      float sx = (rand() % speedx + 40) * (rand()%2?-1:1); // 'cause %0 is 
      float sy = (rand() % speedy + 40) * (rand()%2?-1:1); // float except
      Frame* frame = 
            new Frame(spriteSurface, chunk_width, chunk_height,
                  source_x, source_y
                );
      Chunk chunk(
                Vector2f(sprite.X()+source_x,   // x coord of destination 
                         sprite.Y()+source_y), // y coord of destination
                Vector2f(sx, sy),
                sprite.getName()+"/chunk",
                frame);
      // chunks uses value semantics, as does frames, but there's
      // a big difference:
      chunks.push_back(chunk);
      frames.push_back(frame);
      source_x += chunk_width;
    }
    source_y += chunk_height;
  }
}
예제 #15
0
static void repeatstat (LexState *ls, int line) {
  /* repeatstat -> REPEAT block UNTIL cond */
  int condexit;
  FuncState *fs = ls->fs;
  int repeat_init = luaK_getlabel(fs);
  BlockCnt bl1, bl2;
  enterblock(fs, &bl1, 1);  /* loop block */
  enterblock(fs, &bl2, 0);  /* scope block */
  luaX_next(ls);  /* skip REPEAT */
  chunk(ls);
  check_match(ls, TK_UNTIL, TK_REPEAT, line);
#if LUA_EXT_CONTINUE
  if (bl2.continuelist != NO_JUMP) {
    int oldprohibition = fs->prohibitedloc;
    luaK_patchtohere(fs, bl2.continuelist);
    fs->prohibitedloc = bl2.continuepos;
    condexit = cond(ls);  /* read condition (inside scope block) */
    fs->prohibitedloc = oldprohibition;
    bl2.continuelist = NO_JUMP;
  }
  else {
    condexit = cond(ls);  /* read condition (inside scope block) */
  }
#else
  condexit = cond(ls);  /* read condition (inside scope block) */
#endif /* LUA_EXT_CONTINUE */
  if (!bl2.upval) {  /* no upvalues? */
    leaveblock(fs);  /* finish scope */
    luaK_patchlist(ls->fs, condexit, repeat_init);  /* close the loop */
  }
  else {  /* complete semantics when there are upvalues */
    breakstat(ls);  /* if condition then break */
    luaK_patchtohere(ls->fs, condexit);  /* else... */
    leaveblock(fs);  /* finish scope... */
    luaK_patchlist(ls->fs, luaK_jump(fs), repeat_init);  /* and repeat */
  }
  leaveblock(fs);  /* finish loop */
}
void CMTPTypeDeviceInfo::ConstructL()
    {
    for (TUint i(0); (i < ENumElements); i++)
        {
        const TElementInfo& info(iElementInfo[i]);
        if (ChunkCount() <= info.iChunkId)
            {
            MMTPType* chunk(NULL);
            
            switch (info.iType)
                {
            case EMTPTypeArray:
                chunk = NewArrayChunkL(info);
                break;
                
            case EMTPTypeFlat:
                chunk = NewFlatChunkL(info);
                break;
                
            case EMTPTypeString:
                chunk = NewStringChunkL(info);
                break;
                
            case EMTPTypeUINT16:
                chunk = NewUInt16Chunk(info);
                break;
                
            default:
                break;
                }
                
            __ASSERT_DEBUG(chunk, User::Invariant());
            CleanupStack::PushL(chunk);
            ChunkAppendL(*chunk);
            CleanupStack::Pop(chunk);
            }
        }
    }
int main() {
	int **data  = malloc(4*sizeof(int*));
	
	
	int *p0 = malloc(sizeof(int));
	int *p1 = malloc(sizeof(int));
	int *p2 = malloc(sizeof(int));
	int *p3 = malloc(sizeof(int));
	
	
	int i = __VERIFIER_nondet_int();
	int upper = __VERIFIER_nondet_int();
	
	if(i >= upper)
		return 0;
	
	*p0 = i;
	*p3 = upper;
	
	

	data[0] = p0;
	data[1] = p1;
	data[2] = p2;
	data[3] = p3;
	

	
	chunk(data);
	
	
	int *p1_new = (int*) data[1];
	int *p2_new = (int*) data[2];
	
	free(p1_new);
	free(p2_new);
	
}
예제 #18
0
Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) {
  struct LexState lexstate;
  struct FuncState *pfuncstate = (struct FuncState*)malloc(sizeof(struct FuncState));
  Proto *res;
  TString *tname = luaS_new(L, name);
  setsvalue2s(L, L->top, tname);  /* protect name */
  incr_top(L);
  lexstate.buff = buff;
  luaX_setinput(L, &lexstate, z, tname);
  open_func(&lexstate, pfuncstate);
  pfuncstate->f->is_vararg = VARARG_ISVARARG;  /* main func. is always vararg */
  luaX_next(&lexstate);  /* read first token */
  chunk(&lexstate);
  check(&lexstate, TK_EOS);
  close_func(&lexstate);
  L->top--; /* remove 'name' from stack */
  lua_assert(pfuncstate->prev == NULL);
  lua_assert(pfuncstate->f->nups == 0);
  lua_assert(lexstate.fs == NULL);
  res = pfuncstate->f;
  free(pfuncstate);
  return res;
}
예제 #19
0
파일: cafs.cpp 프로젝트: Zhang-Yi/tornet
/**
 *  Imports the file chunks into the database, but does not
 *  import the file_header itself as a chunk, as it may be
 *  imbedded within another chunk.
 *
 *  @pre is_regular_file(p) 
 */
cafs::file_header cafs::import_file( const fc::path& p ) {
  file_header head;  
  head.file_size = fc::file_size(p);

  fc::vector<char> chunk( MAX_CHUNK_SIZE );

  // divide file up into chunks and slices
  fc::ifstream in( p.string(), fc::ifstream::binary );
  uint32_t r = 0;
  while( r < head.file_size ) {
    size_t some = fc::min( size_t(chunk.size()), size_t(head.file_size-r) );
    in.read( chunk.data(), some );
    size_t seed = randomize(chunk, *((uint64_t*)fc::sha1::hash(chunk.data(),chunk.size()).data()) );

    chunk.resize(some);
    auto chunk_head = slice_chunk(chunk);
    auto chunk_id   = store_chunk( chunk_head, chunk );

    head.add_chunk( chunk_id, seed, chunk_head );
    r += some;
  }
  return head;
}
예제 #20
0
Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) {
  struct LexState lexstate;
  struct FuncState funcstate;
  TString *tname = luaS_new(L, name);
  setsvalue2s(L, L->top, tname);  /* protect name */
  incr_top(L);
  lexstate.buff = buff;
  luaX_setinput(L, &lexstate, z, tname);
  open_func(&lexstate, &funcstate);
  funcstate.f->is_vararg = VARARG_ISVARARG;  /* main func. is always vararg */
  luaX_next(&lexstate);  /* read first token */
  chunk(&lexstate);
  check(&lexstate, TK_EOS);
  close_func(&lexstate);
#ifdef LUA_OPTIMIZE_DEBUG
  compile_stripdebug(L, funcstate.f);
#endif
  L->top--; /* remove 'name' from stack */
  lua_assert(funcstate.prev == NULL);
  lua_assert(funcstate.f->nups == 0);
  lua_assert(lexstate.fs == NULL);
  return funcstate.f;
}
예제 #21
0
SocketSync<Dtype>::SocketSync(shared_ptr<Solver<Dtype> > root_solver,
                              const vector<shared_ptr<SocketChannel> > &
                              peers, int rank)
  : P2PSync<Dtype>(root_solver, NULL, root_solver->param()),
    peers_(peers),
    rank_(rank),
    data_send_(peers.size()),
    data_recv_(peers.size()),
    diff_send_(peers.size()),
    diff_recv_(peers.size()),
    ctrl_send_(peers.size()),
    ctrl_recv_(peers.size()) {
#ifndef CPU_ONLY
  int initial_device;
  CUDA_CHECK(cudaGetDevice(&initial_device));
  CUDA_CHECK(cudaSetDevice(root_solver->param().device_id()));
  chunk(rank_, &own_offs_, &own_size_);
  for (int peer = 0; peer < peers_.size(); ++peer) {
    if (peer == rank_) {
      // Chunk for which we are master, connected to all peers.
      // Loops must be imbricated to have buffers created in
      // the same order on all boxes.
      for (int i = 0; i < peers_.size(); ++i) {
        if (i != rank_) {
          CreateMasterBuffers(i);
        }
      }
    } else {
      // Other chunks are connected to their respective masters
      CreateWorkerBuffers(peer);
    }
  }
  CUDA_CHECK(cudaSetDevice(initial_device));
#else
  NO_GPU;
#endif
}
예제 #22
0
파일: lparser.c 프로젝트: xiaofeng/Arcemu
static void repeatstat (LexState *ls, int line) {
  /* repeatstat -> REPEAT block UNTIL cond */
  int condexit;
  FuncState *fs = ls->fs;
  int repeat_init = luaK_getlabel(fs);
  BlockCnt bl1, bl2;
  enterblock(fs, &bl1, 1);  /* loop block */
  enterblock(fs, &bl2, 0);  /* scope block */
  luaX_next(ls);  /* skip REPEAT */
  chunk(ls);
  check_match(ls, TK_UNTIL, TK_REPEAT, line);
  condexit = cond(ls);  /* read condition (inside scope block) */
  if (!bl2.upval) {  /* no upvalues? */
    leaveblock(fs);  /* finish scope */
    luaK_patchlist(ls->fs, condexit, repeat_init);  /* close the loop */
  }
  else {  /* complete semantics when there are upvalues */
    breakstat(ls);  /* if condition then break */
    luaK_patchtohere(ls->fs, condexit);  /* else... */
    leaveblock(fs);  /* finish scope... */
    luaK_patchlist(ls->fs, luaK_jump(fs), repeat_init);  /* and repeat */
  }
  leaveblock(fs);  /* finish loop */
}
예제 #23
0
void Client::receiveChunk(const std::string& packetContents)
{
    PacketBuf::Chunk message;
    Packet::deserialize(packetContents, &message);

    std::vector<Block> blocks;

    uint32_t index = 0;
    for (uint32_t row = message.starty(); row < message.endy(); ++row) {
        for (uint32_t column = message.startx(); column < message.endx(); ++column) {
            Block block;
            block.meshType = message.meshtype(index);
            block.primitiveType = message.primitivetype(index);
            block.wallType = message.walltype(index);
            blocks.push_back(block);

            ++index;
        }
    }

    Chunk chunk(message.startx(), message.starty(), message.endx(), message.endy(), &blocks);

    m_world->loadChunk(&chunk);
}
예제 #24
0
void CompareOnTheFlyScene(comparer_context& comp)	{
	scoped_chunk chunk(comp,"aiScene");

	comp.cmp<uint32_t>("mFlags");
	comp.cmp<uint32_t>("mNumMeshes");
	comp.cmp<uint32_t>("mNumMaterials");
	comp.cmp<uint32_t>("mNumAnimations");
	comp.cmp<uint32_t>("mNumTextures");
	comp.cmp<uint32_t>("mNumLights");
	comp.cmp<uint32_t>("mNumCameras");

	sliced_chunk_reader reader(comp);
	for(sliced_chunk_iterator it = reader.begin(); !it.is_end(); ++it) {
		if ((*it).first == ASSBIN_CHUNK_AIMATERIAL) {
			CompareOnTheFlyMaterial(comp);
		}
		else if ((*it).first == ASSBIN_CHUNK_AITEXTURE) {
			CompareOnTheFlyTexture(comp);
		}
		else if ((*it).first == ASSBIN_CHUNK_AIMESH) {
			CompareOnTheFlyMesh(comp);
		}
		else if ((*it).first == ASSBIN_CHUNK_AIANIMATION) {
			CompareOnTheFlyAnimation(comp);
		}
		else if ((*it).first == ASSBIN_CHUNK_AICAMERA) {
			CompareOnTheFlyCamera(comp);
		}
		else if ((*it).first == ASSBIN_CHUNK_AILIGHT) {
			CompareOnTheFlyLight(comp);
		}
		else if ((*it).first == ASSBIN_CHUNK_AINODE) {
			CompareOnTheFlyNode(comp);
		}
	}
}
예제 #25
0
파일: Iax2Session.cpp 프로젝트: HiPiH/Oreka
/*
 * Returns false if packet is received out-of-sync (when we are in the wrong state)
 */
bool Iax2Session::AddIax2Packet(Iax2PacketInfoRef& iax2Packet)
{
	CStdString logMsg;
	unsigned char channel = 0;

	/* What is our state?  We need to be in the IAX2_STATE_LINKED state
	 * or the IAX2_STATE_UP state to receive any voice frames */
	if((m_iax2_state != IAX2_STATE_LINKED) && (m_iax2_state != IAX2_STATE_UP)) {
		logMsg.Format("[%s] receiving voice packets while in %s state? "
				"Destroying session...", m_trackingId,
				iax2_state_to_str(m_iax2_state));
		LOG4CXX_INFO(m_log, logMsg);
		return false;
	}

	/* We do not have a voice packet yet */
	if(m_lastIax2Packet.get() == NULL) {
		/* The first IAX2 voice frame is expected to be a full frame,
		 * complete with the payload type information.  If this is not
		 * the case, we will continue dropping any mini frames */

		if(iax2Packet->m_frame_type != IAX2_FRAME_FULL) {
			logMsg.Format("[%s] 1st packet is not a full frame! Dropping...", m_trackingId);
			LOG4CXX_ERROR(m_log, logMsg);
			return true;
		}

		ProcessMetadataIax2(iax2Packet);
		m_iax2_state = IAX2_STATE_UP;
	}

	/* If we get another full voice packet, we need to update our codec 
	 * information */
	if(iax2Packet->m_frame_type == IAX2_FRAME_FULL)
	{
		m_codec = iax2Packet->m_payloadType;
	}

	m_lastIax2Packet = iax2Packet;
	if(m_lastIax2PacketSide1.get() == NULL) {
		// First IAX2 packet for side 1
		m_lastIax2PacketSide1 = iax2Packet;
		channel = 1;
		if(m_log->isInfoEnabled())
		{
			iax2Packet->ToString(logMsg);
			logMsg =  "[" + m_trackingId + "] 1st packet s1: " + logMsg;
			LOG4CXX_INFO(m_log, logMsg);
		}
	} else {
		// Comparing destination IP address to find out if side1, see (1)
		if((unsigned int)iax2Packet->m_destIp.s_addr == (unsigned int)m_lastIax2PacketSide1->m_destIp.s_addr)
		{
			if(DLLCONFIG.m_Iax2RewriteTimestamps == true)
			{
				iax2Packet->m_timestamp =+ m_lastIax2PacketSide1->m_timestamp + 20;
			}
			else if(iax2Packet->m_timestamp == m_lastIax2PacketSide1->m_timestamp)
			{
				m_hasDuplicateIax2 = true;
				return true;	// dismiss duplicate IAX2 packet
			}
			/* XXX Detect discontinuity using timestamps? */
			/*
			else
			{
				double seqNumDelta = (double)iax2Packet->m_seqNum - (double)m_lastIax2PacketSide1->m_seqNum;
				if(DLLCONFIG.m_iax2DiscontinuityDetect)
				{
					double timestampDelta = (double)iax2Packet->m_timestamp - (double)m_lastIax2PacketSide1->m_timestamp;
					if(	abs(seqNumDelta) > m_minIax2SeqDelta  &&
						abs(timestampDelta) > m_minIax2TimestampDelta)	
					{
						logMsg.Format("[%s] IAX2 discontinuity s1: before: seq:%u ts:%u after: seq:%u ts:%u", 
							m_trackingId, m_lastIax2PacketSide1->m_seqNum, m_lastIax2PacketSide1->m_timestamp, 
							iax2Packet->m_seqNum, iax2Packet->m_timestamp);
						LOG4CXX_INFO(m_log, logMsg);
						return false;
					}
				}
				if(seqNumDelta > (double)m_highestIax2SeqNumDelta)
				{
					m_highestIax2SeqNumDelta = (unsigned int)seqNumDelta;
				}
			} */
			m_lastIax2PacketSide1 = iax2Packet;
			channel = 1;
		}
		else
		{
			if(m_lastIax2PacketSide2.get() == NULL)
			{
				// First IAX2 packet for side 2
				if(m_log->isInfoEnabled())
				{
					iax2Packet->ToString(logMsg);
					logMsg =  "[" + m_trackingId + "] 1st packet s2: " + logMsg;
					LOG4CXX_INFO(m_log, logMsg);
				}
			}
			else
			{
				if(DLLCONFIG.m_Iax2RewriteTimestamps == true)
				{
					iax2Packet->m_timestamp += m_lastIax2PacketSide2->m_timestamp + 20;
				}
				else if(iax2Packet->m_timestamp == m_lastIax2PacketSide2->m_timestamp)
				{
					m_hasDuplicateIax2 = true;
					return true;	// dismiss duplicate IAX2 packet
				}
				/* XXX Detect discontinuity using timestamps? */
                                /*
				else
				{
					double seqNumDelta = (double)iax2Packet->m_seqNum - (double)m_lastIax2PacketSide2->m_seqNum;
					if(DLLCONFIG.m_iax2DiscontinuityDetect)
					{
						double timestampDelta = (double)iax2Packet->m_timestamp - (double)m_lastIax2PacketSide2->m_timestamp;
						if(	abs(seqNumDelta) > m_minIax2SeqDelta  &&
							abs(timestampDelta) > m_minIax2TimestampDelta)	
						{
							logMsg.Format("[%s] IAX2 discontinuity s2: before: seq:%u ts:%u after: seq:%u ts:%u", 
								m_trackingId, m_lastIax2PacketSide2->m_seqNum, m_lastIax2PacketSide2->m_timestamp, 
								iax2Packet->m_seqNum, iax2Packet->m_timestamp);
							LOG4CXX_INFO(m_log, logMsg);
							return false;
						}
					}
					if(seqNumDelta > (double)m_highestIax2SeqNumDelta)
					{
						m_highestIax2SeqNumDelta = (unsigned int)seqNumDelta;
					}
				}*/
			}
			m_lastIax2PacketSide2 = iax2Packet;
			channel = 2;
		}
	}

	m_numIax2Packets++;

	/* Can stream change happen with IAX2??
	bool hasSourceAddress = m_iax2AddressList.HasAddressOrAdd(iax2Packet->m_sourceIp, iax2Packet->m_sourcePort);
	bool hasDestAddress = m_iax2AddressList.HasAddressOrAdd(iax2Packet->m_destIp, iax2Packet->m_destPort);
	if(	hasSourceAddress == false || hasDestAddress == false )
	{
		iax2Packet->ToString(logMsg);
		logMsg.Format("[%s] new IAX2 stream s%d: %s", 
							m_trackingId, channel, logMsg);
		LOG4CXX_INFO(m_log, logMsg);

		if(m_protocol == ProtIax2 && m_started)	// make sure this only happens if ReportMetadata() already been called for the session
		{
			UpdateMetadataIax2(iax2Packet, hasDestAddress);
		}
	}
	*/

	if(m_numIax2Packets == 1) {
		Start();
		ReportMetadata();
	}

	unsigned short seq = 0;

	if(channel == 1)
	{
		m_channel1SeqNo += 1;
		if(m_channel1SeqNo >= 65535)
		{
			m_channel1SeqNo = 1;
		}

		seq = m_channel1SeqNo;
	}
	else
	{
		m_channel2SeqNo += 1;
		if(m_channel2SeqNo >= 65535)
		{
			m_channel2SeqNo = 1;
		}

		seq = m_channel2SeqNo;
	}

	if(m_started) {
		AudioChunkDetails details;
		AudioChunkRef chunk(new AudioChunk());

		details.m_arrivalTimestamp = iax2Packet->m_arrivalTimestamp;
		details.m_numBytes = iax2Packet->m_payloadSize;
		details.m_timestamp = (channel == 1 ? m_channel1SeqNo : m_channel2SeqNo) * RtpTimestamp();
		details.m_rtpPayloadType = m_codec;
		details.m_channel = channel;
		details.m_sequenceNumber = seq;
		details.m_encoding = AlawAudio;

		chunk->SetBuffer(iax2Packet->m_payload, details);
		g_audioChunkCallBack(chunk, m_capturePort);

		m_lastUpdated = iax2Packet->m_arrivalTimestamp;
	}

	return true;
}
예제 #26
0
void Irony::complete(const std::string &file,
                     unsigned line,
                     unsigned col,
                     const std::vector<std::string> &flags,
                     const std::vector<CXUnsavedFile> &unsavedFiles) {
  CXTranslationUnit tu = tuManager_.getOrCreateTU(file, flags, unsavedFiles);

  if (tu == nullptr) {
    std::cout << "nil\n";
    return;
  }

  if (CXCodeCompleteResults *completions =
          clang_codeCompleteAt(tu,
                               file.c_str(),
                               line,
                               col,
                               const_cast<CXUnsavedFile *>(unsavedFiles.data()),
                               unsavedFiles.size(),
                               (clang_defaultCodeCompleteOptions() &
                                ~CXCodeComplete_IncludeCodePatterns)
#if HAS_BRIEF_COMMENTS_IN_COMPLETION
                                   |
                                   CXCodeComplete_IncludeBriefComments
#endif
                               )) {

    if (debug_) {
      unsigned numDiags = clang_codeCompleteGetNumDiagnostics(completions);
      std::clog << "debug: complete: " << numDiags << " diagnostic(s)\n";
      for (unsigned i = 0; i < numDiags; ++i) {
        CXDiagnostic diagnostic =
            clang_codeCompleteGetDiagnostic(completions, i);
        CXString s = clang_formatDiagnostic(
            diagnostic, clang_defaultDiagnosticDisplayOptions());

        std::clog << clang_getCString(s) << std::endl;
        clang_disposeString(s);
        clang_disposeDiagnostic(diagnostic);
      }
    }

    clang_sortCodeCompletionResults(completions->Results,
                                    completions->NumResults);

    std::cout << "(\n";

    // re-use the same buffers to avoid unnecessary allocations
    std::string typedtext, brief, resultType, prototype, postCompCar;
    std::vector<unsigned> postCompCdr;

    for (unsigned i = 0; i < completions->NumResults; ++i) {
      CXCompletionResult candidate = completions->Results[i];
      CXAvailabilityKind availability =
          clang_getCompletionAvailability(candidate.CompletionString);

      unsigned priority =
          clang_getCompletionPriority(candidate.CompletionString);
      unsigned annotationStart = 0;
      bool typedTextSet = false;

      if (availability == CXAvailability_NotAccessible ||
          availability == CXAvailability_NotAvailable) {
        continue;
      }

      typedtext.clear();
      brief.clear();
      resultType.clear();
      prototype.clear();
      postCompCar.clear();
      postCompCdr.clear();

      for (CompletionChunk chunk(candidate.CompletionString); chunk.hasNext();
           chunk.next()) {
        char ch = 0;

        auto chunkKind = chunk.kind();

        switch (chunkKind) {
        case CXCompletionChunk_ResultType:
          resultType = chunk.text();
          break;

        case CXCompletionChunk_TypedText:
        case CXCompletionChunk_Text:
        case CXCompletionChunk_Placeholder:
        case CXCompletionChunk_Informative:
        case CXCompletionChunk_CurrentParameter:
          prototype += chunk.text();
          break;

        case CXCompletionChunk_LeftParen:       ch = '(';  break;
        case CXCompletionChunk_RightParen:      ch = ')';  break;
        case CXCompletionChunk_LeftBracket:     ch = '[';  break;
        case CXCompletionChunk_RightBracket:    ch = ']';  break;
        case CXCompletionChunk_LeftBrace:       ch = '{';  break;
        case CXCompletionChunk_RightBrace:      ch = '}';  break;
        case CXCompletionChunk_LeftAngle:       ch = '<';  break;
        case CXCompletionChunk_RightAngle:      ch = '>';  break;
        case CXCompletionChunk_Comma:           ch = ',';  break;
        case CXCompletionChunk_Colon:           ch = ':';  break;
        case CXCompletionChunk_SemiColon:       ch = ';';  break;
        case CXCompletionChunk_Equal:           ch = '=';  break;
        case CXCompletionChunk_HorizontalSpace: ch = ' ';  break;
        case CXCompletionChunk_VerticalSpace:   ch = '\n'; break;

        case CXCompletionChunk_Optional:
          // ignored for now
          break;
        }

        if (ch != 0) {
          prototype += ch;
          // commas look better followed by a space
          if (ch == ',') {
            prototype += ' ';
          }
        }

        if (typedTextSet) {
          if (ch != 0) {
            postCompCar += ch;
            if (ch == ',') {
              postCompCar += ' ';
            }
          } else if (chunkKind == CXCompletionChunk_Text ||
                     chunkKind == CXCompletionChunk_TypedText) {
            postCompCar += chunk.text();
          } else if (chunkKind == CXCompletionChunk_Placeholder ||
                     chunkKind == CXCompletionChunk_CurrentParameter) {
            postCompCdr.push_back(postCompCar.size());
            postCompCar += chunk.text();
            postCompCdr.push_back(postCompCar.size());
          }
        }

        // Consider only the first typed text. The CXCompletionChunk_TypedText
        // doc suggests that exactly one typed text will be given but at least
        // in Objective-C it seems that more than one can appear, see:
        // https://github.com/Sarcasm/irony-mode/pull/78#issuecomment-37115538
        if (chunkKind == CXCompletionChunk_TypedText && !typedTextSet) {
          typedtext = chunk.text();
          // annotation is what comes after the typedtext
          annotationStart = prototype.size();
          typedTextSet = true;
        }
      }

#if HAS_BRIEF_COMMENTS_IN_COMPLETION
      brief = cxStringToStd(
          clang_getCompletionBriefComment(candidate.CompletionString));
#endif

      // see irony-completion.el#irony-completion-candidates
      std::cout << '(' << support::quoted(typedtext)  //
                << ' ' << priority                    //
                << ' ' << support::quoted(resultType) //
                << ' ' << support::quoted(brief)      //
                << ' ' << support::quoted(prototype)  //
                << ' ' << annotationStart             //
                << " (" << support::quoted(postCompCar);
      for (unsigned index : postCompCdr)
        std::cout << ' ' << index;
      std::cout << ")"
                << ")\n";
    }

    clang_disposeCodeCompleteResults(completions);
    std::cout << ")\n";
  }
}
예제 #27
0
void SVGTextChunkBuilder::addTextChunk(Vector<SVGInlineTextBox*>& lineLayoutBoxes, unsigned boxStart, unsigned boxCount)
{
    SVGInlineTextBox* textBox = lineLayoutBoxes[boxStart];
    ASSERT(textBox);

    RenderSVGInlineText* textRenderer = toRenderSVGInlineText(textBox->textRenderer());
    ASSERT(textRenderer);

    const RenderStyle* style = textRenderer->style();
    ASSERT(style);

    const SVGRenderStyle* svgStyle = style->svgStyle();
    ASSERT(svgStyle);

    // Build chunk style flags.
    unsigned chunkStyle = SVGTextChunk::DefaultStyle;

    // Handle 'direction' property.
    if (!style->isLeftToRightDirection())
        chunkStyle |= SVGTextChunk::RightToLeftText;

    // Handle 'writing-mode' property.
    if (svgStyle->isVerticalWritingMode())
        chunkStyle |= SVGTextChunk::VerticalText;

    // Handle 'text-anchor' property.
    switch (svgStyle->textAnchor()) {
    case TA_START:
        break;
    case TA_MIDDLE:
        chunkStyle |= SVGTextChunk::MiddleAnchor;
        break;
    case TA_END:
        chunkStyle |= SVGTextChunk::EndAnchor;
        break;
    };

    // Handle 'lengthAdjust' property.
    float desiredTextLength = 0;
    if (SVGTextContentElement* textContentElement = SVGTextContentElement::elementFromRenderer(textRenderer->parent())) {
        desiredTextLength = textContentElement->specifiedTextLength().value(textContentElement);

        switch (textContentElement->lengthAdjust()) {
        case SVGTextContentElement::LENGTHADJUST_UNKNOWN:
            break;
        case SVGTextContentElement::LENGTHADJUST_SPACING:
            chunkStyle |= SVGTextChunk::LengthAdjustSpacing;
            break;
        case SVGTextContentElement::LENGTHADJUST_SPACINGANDGLYPHS:
            chunkStyle |= SVGTextChunk::LengthAdjustSpacingAndGlyphs;
            break;
        };
    }

    SVGTextChunk chunk(chunkStyle, desiredTextLength);

    Vector<SVGInlineTextBox*>& boxes = chunk.boxes();
    for (unsigned i = boxStart; i < boxStart + boxCount; ++i)
        boxes.append(lineLayoutBoxes[i]);

    m_textChunks.append(chunk);
}
예제 #28
0
파일: decalobject.cpp 프로젝트: Try/game
DecalObject::~DecalObject() {
  chunk().needToUpdate = true;
  }
예제 #29
0
파일: Quvi.cpp 프로젝트: alexmarsev/quvif
QuviMedia::QuviMedia(std::wstring&& url)
	: QuviMediaInfo(std::move(url))
	, m_curlsh(curl_share_init())
{
	assert(m_curlsh); // TODO: throw exception
	curl_share_setopt(m_curlsh, CURLSHOPT_LOCKFUNC, CurlShareLockFunction);
	curl_share_setopt(m_curlsh, CURLSHOPT_UNLOCKFUNC, CurlShareUnlockFunction);
	curl_share_setopt(m_curlsh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
	curl_share_setopt(m_curlsh, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
	curl_share_setopt(m_curlsh, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);
	curl_share_setopt(m_curlsh, CURLSHOPT_USERDATA, &m_curlshLock);

	curl_easy_setopt(m_curl, CURLOPT_SHARE, m_curlsh);
	// TODO: ensure that cookies are properly inherited

	if (GetContentType() == "video/vnd.mpeg.dash.mpd") {
		std::string murl = GetMultibyteUrl();
		if (murl.empty())
			throw 1; // TODO: replace with some sensible exception
		std::unique_ptr<dash::IDASHManager> manager(CreateDashManager());
		if (!manager)
			throw 1; // TODO: replace with some sensible exception
		std::unique_ptr<dash::mpd::IMPD> mpd(manager->Open(&murl[0]));
		if (!mpd)
			throw 1; // TODO: replace with some sensible exception

		const auto& period = mpd->GetPeriods().front();

		for (const auto& adaptationSet : period->GetAdaptationSets()) {
			const auto& representation = adaptationSet->GetRepresentation().back();

			enum class DashRepresentationType {
				Base,
				Template,
				List,
			};

			auto determineType = [](const dash::mpd::IPeriod* period,
				const dash::mpd::IAdaptationSet* adaptationSet,
				const dash::mpd::IRepresentation* representation) -> DashRepresentationType {
				assert(representation && adaptationSet && period);
				if (representation->GetSegmentList())
					return DashRepresentationType::List;
				if (representation->GetSegmentTemplate())
					return DashRepresentationType::Template;
				if (representation->GetSegmentBase() || !representation->GetBaseURLs().empty())
					return DashRepresentationType::Base;

				if (adaptationSet->GetSegmentList())
					return DashRepresentationType::List;
				if (adaptationSet->GetSegmentTemplate())
					return DashRepresentationType::Template;
				if (adaptationSet->GetSegmentBase())
					return DashRepresentationType::Base;

				if (period->GetSegmentList())
					return DashRepresentationType::List;
				if (period->GetSegmentTemplate())
					return DashRepresentationType::Template;
				if (period->GetSegmentBase())
					return DashRepresentationType::Base;

				throw 1; // TODO: replace with some sensible exception
			};

			const DashRepresentationType type = determineType(period, adaptationSet, representation);

			if (type != DashRepresentationType::Base) // TODO: support other stream types
				throw 1; // TODO: replace with some sensible exception

			// TODO: support compound urls
			std::unique_ptr<dash::network::IChunk> chunk(representation->GetBaseURLs()[0]->ToMediaSegment({}));
			if (!chunk)
				throw 1; // TODO: replace with some sensible exception

			auto& uri = chunk->AbsoluteURI();
			if (uri.empty())
				throw 1; // TODO: replace with some sensible exception

			curl_easy_setopt(m_curl, CURLOPT_URL, &uri[0]);
			curl_easy_setopt(m_curl, CURLOPT_NOBODY, 1L);

			CURLcode cc = curl_easy_perform(m_curl);
			if (cc != CURLE_OK)
				throw 1; // TODO: replace with some sensible exception

			// TODO: use return codes
			long code = 0, proxycode = 0;
			curl_easy_getinfo(m_curl, CURLINFO_RESPONSE_CODE, &code);
			curl_easy_getinfo(m_curl, CURLINFO_HTTP_CONNECTCODE, &proxycode);

			double size = 0;
			curl_easy_getinfo(m_curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &size);

			curl_easy_setopt(m_curl, CURLOPT_HTTPGET, 1L);
			m_backends.emplace_back(std::make_unique<QuviSimpleStreamBackend>((uint64_t)size, m_curl, m_curlsh));
		}
	} else {
		assert(m_backends.empty());
		m_backends.emplace_back(std::make_unique<QuviSimpleStreamBackend>(GetContentLength(), m_curl, m_curlsh));
	}
}
예제 #30
0
static FIBITMAP * DLL_CALLCONV
Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) {
    bool bUseRgbaInterface = false;
    FIBITMAP *dib = NULL;

    if(!handle) {
        return NULL;
    }

    try {
        BOOL header_only = (flags & FIF_LOAD_NOPIXELS) == FIF_LOAD_NOPIXELS;

        // save the stream starting point
        const long stream_start = io->tell_proc(handle);

        // wrap the FreeImage IO stream
        C_IStream istream(io, handle);

        // open the file
        Imf::InputFile file(istream);

        // get file info
        const Imath::Box2i &dataWindow = file.header().dataWindow();
        int width  = dataWindow.max.x - dataWindow.min.x + 1;
        int height = dataWindow.max.y - dataWindow.min.y + 1;

        //const Imf::Compression &compression = file.header().compression();

        const Imf::ChannelList &channels = file.header().channels();

        // check the number of components and check for a coherent format

        std::string exr_color_model;
        Imf::PixelType pixel_type = Imf::HALF;
        FREE_IMAGE_TYPE image_type = FIT_UNKNOWN;
        int components = 0;
        bool bMixedComponents = false;

        for (Imf::ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i) {
            components++;
            if(components == 1) {
                exr_color_model += i.name();
                pixel_type = i.channel().type;
            } else {
                exr_color_model += "/";
                exr_color_model += i.name();
                if (i.channel().type != pixel_type) {
                    bMixedComponents = true;
                }
            }
        }

        if(bMixedComponents) {
            bool bHandled = false;
            // we may have a RGBZ or RGBAZ image ...
            if(components > 4) {
                if(channels.findChannel("R") && channels.findChannel("G") && channels.findChannel("B") && channels.findChannel("A")) {
                    std::string msg = "Warning: converting color model " + exr_color_model + " to RGBA color model";
                    FreeImage_OutputMessageProc(s_format_id, msg.c_str());
                    bHandled = true;
                }
            }
            else if(components > 3) {
                if(channels.findChannel("R") && channels.findChannel("G") && channels.findChannel("B")) {
                    std::string msg = "Warning: converting color model " + exr_color_model + " to RGB color model";
                    FreeImage_OutputMessageProc(s_format_id, msg.c_str());
                    bHandled = true;
                }
            }
            if(!bHandled) {
                THROW (Iex::InputExc, "Unable to handle mixed component types (color model = " << exr_color_model << ")");
            }
        }

        switch(pixel_type) {
        case Imf::UINT:
            THROW (Iex::InputExc, "Unsupported format: UINT");
            break;
        case Imf::HALF:
        case Imf::FLOAT:
        default:
            break;
        }

        // check for supported image color models
        // --------------------------------------------------------------

        if((components == 1) || (components == 2)) {
            // if the image is gray-alpha (YA), ignore the alpha channel
            if((components == 1) && channels.findChannel("Y")) {
                image_type = FIT_FLOAT;
                components = 1;
            } else {
                std::string msg = "Warning: loading color model " + exr_color_model + " as Y color model";
                FreeImage_OutputMessageProc(s_format_id, msg.c_str());
                image_type = FIT_FLOAT;
                // ignore the other channel
                components = 1;
            }
        } else if(components == 3) {
            if(channels.findChannel("R") && channels.findChannel("G") && channels.findChannel("B")) {
                image_type = FIT_RGBF;
            }
            else if(channels.findChannel("BY") && channels.findChannel("RY") && channels.findChannel("Y")) {
                image_type = FIT_RGBF;
                bUseRgbaInterface = true;
            }
        } else if(components >= 4) {
            if(channels.findChannel("R") && channels.findChannel("G") && channels.findChannel("B")) {
                if(channels.findChannel("A")) {
                    if(components > 4) {
                        std::string msg = "Warning: converting color model " + exr_color_model + " to RGBA color model";
                        FreeImage_OutputMessageProc(s_format_id, msg.c_str());
                    }
                    image_type = FIT_RGBAF;
                    // ignore other layers if there is more than one alpha layer
                    components = 4;
                } else {
                    std::string msg = "Warning: converting color model " + exr_color_model + " to RGB color model";
                    FreeImage_OutputMessageProc(s_format_id, msg.c_str());

                    image_type = FIT_RGBF;
                    // ignore other channels
                    components = 3;
                }
            }
        }

        if(image_type == FIT_UNKNOWN) {
            THROW (Iex::InputExc, "Unsupported color model: " << exr_color_model);
        }

        // allocate a new dib
        dib = FreeImage_AllocateHeaderT(header_only, image_type, width, height, 0);
        if(!dib) THROW (Iex::NullExc, FI_MSG_ERROR_MEMORY);

        // try to load the preview image
        // --------------------------------------------------------------

        if(file.header().hasPreviewImage()) {
            const Imf::PreviewImage& preview = file.header().previewImage();
            const unsigned thWidth = preview.width();
            const unsigned thHeight = preview.height();

            FIBITMAP* thumbnail = FreeImage_Allocate(thWidth, thHeight, 32);
            if(thumbnail) {
                const Imf::PreviewRgba *src_line = preview.pixels();
                BYTE *dst_line = FreeImage_GetScanLine(thumbnail, thHeight - 1);
                const unsigned dstPitch = FreeImage_GetPitch(thumbnail);

                for (unsigned y = 0; y < thHeight; ++y) {
                    const Imf::PreviewRgba *src_pixel = src_line;
                    RGBQUAD* dst_pixel = (RGBQUAD*)dst_line;

                    for(unsigned x = 0; x < thWidth; ++x) {
                        dst_pixel->rgbRed = src_pixel->r;
                        dst_pixel->rgbGreen = src_pixel->g;
                        dst_pixel->rgbBlue = src_pixel->b;
                        dst_pixel->rgbReserved = src_pixel->a;
                        src_pixel++;
                        dst_pixel++;
                    }
                    src_line += thWidth;
                    dst_line -= dstPitch;
                }
                FreeImage_SetThumbnail(dib, thumbnail);
                FreeImage_Unload(thumbnail);
            }
        }

        if(header_only) {
            // header only mode
            return dib;
        }

        // load pixels
        // --------------------------------------------------------------

        const BYTE *bits = FreeImage_GetBits(dib);			// pointer to our pixel buffer
        const size_t bytespp = sizeof(float) * components;	// size of our pixel in bytes
        const unsigned pitch = FreeImage_GetPitch(dib);		// size of our yStride in bytes

        Imf::PixelType pixelType = Imf::FLOAT;	// load as float data type;

        if(bUseRgbaInterface) {
            // use the RGBA interface (used when loading RY BY Y images )

            const int chunk_size = 16;

            BYTE *scanline = (BYTE*)bits;

            // re-open using the RGBA interface
            io->seek_proc(handle, stream_start, SEEK_SET);
            Imf::RgbaInputFile rgbaFile(istream);

            // read the file in chunks
            Imath::Box2i dw = dataWindow;
            Imf::Array2D<Imf::Rgba> chunk(chunk_size, width);
            while (dw.min.y <= dw.max.y) {
                // read a chunk
                rgbaFile.setFrameBuffer (&chunk[0][0] - dw.min.x - dw.min.y * width, 1, width);
                rgbaFile.readPixels (dw.min.y, MIN(dw.min.y + chunk_size - 1, dw.max.y));
                // fill the dib
                const int y_max = ((dw.max.y - dw.min.y) <= chunk_size) ? (dw.max.y - dw.min.y) : chunk_size;
                for(int y = 0; y < y_max; y++) {
                    FIRGBF *pixel = (FIRGBF*)scanline;
                    const Imf::Rgba *half_rgba = chunk[y];
                    for(int x = 0; x < width; x++) {
                        // convert from half to float
                        pixel[x].red = half_rgba[x].r;
                        pixel[x].green = half_rgba[x].g;
                        pixel[x].blue = half_rgba[x].b;
                    }
                    // next line
                    scanline += pitch;
                }
                // next chunk
                dw.min.y += chunk_size;
            }

        } else {
            // use the low level interface

            // build a frame buffer (i.e. what we want on output)
            Imf::FrameBuffer frameBuffer;

            // allow dataWindow with minimal bounds different form zero
            size_t offset = - dataWindow.min.x * bytespp - dataWindow.min.y * pitch;

            if(components == 1) {
                frameBuffer.insert ("Y",	// name
                                    Imf::Slice (pixelType,	// type
                                                (char*)(bits + offset), // base
                                                bytespp,				// xStride
                                                pitch,					// yStride
                                                1, 1,					// x/y sampling
                                                0.0));					// fillValue
            } else if((components == 3) || (components == 4)) {
                const char *channel_name[4] = { "R", "G", "B", "A" };

                for(int c = 0; c < components; c++) {
                    frameBuffer.insert (
                        channel_name[c],					// name
                        Imf::Slice (pixelType,				// type
                                    (char*)(bits + c * sizeof(float) + offset), // base
                                    bytespp,							// xStride
                                    pitch,								// yStride
                                    1, 1,								// x/y sampling
                                    0.0));								// fillValue
                }
            }

            // read the file
            file.setFrameBuffer(frameBuffer);
            file.readPixels(dataWindow.min.y, dataWindow.max.y);
        }

        // lastly, flip dib lines
        FreeImage_FlipVertical(dib);

    }
    catch(Iex::BaseExc & e) {
        if(dib != NULL) {
            FreeImage_Unload(dib);
        }
        FreeImage_OutputMessageProc(s_format_id, e.what());
        return NULL;
    }

    return dib;
}