// function to init tasks & read config file void init(struct TileQueue* tiles, int rank, int q, int N, int C) { FILE* fd = fopen("config","r"); int i, k; rank--; // no config file: regular tasks, calculate image if (fd == NULL) { fprintf(stderr, "Warning: No config file. Regular tasks & chines remainder.\n"); for (k = rank * q; k <= chinese_remainder_bound(rank, q, C); k++){ addTile(tiles,chinese_remainder_value(k, N, C)); } return; } char buffer[1024]; int nb_task = 0, sleep_time = 100, repartition = 0; fscanf(fd, "%d\n", &fake); // fake tasks ? fscanf(fd, "%d\n", &repartition); // chinese remainder ? fscanf(fd, "%d\n", &vol); // vol de travail ? if (fake == 0) { // Chosen method is: regular tasks for (k = rank * q; k <= chinese_remainder_bound(rank, q, C); k++){ addTile(tiles,(repartition==0)?k:chinese_remainder_value(k, N, C)); } fclose(fd); return; } // Chosen method is: fake tasks fscanf(fd, "%d\n", &C); q = (C+P-1)/P; int *sleep_values = malloc(C * sizeof(int)); k = 0; while (fgets(buffer,1024,fd) && k < C){ sscanf(buffer, "%d %d", &nb_task, &sleep_time); // printf("creating %d %d\n",nb_task,sleep_time ); for (i = 0; i < nb_task && k < C; i++){ sleep_values[k] = -sleep_time; k++; } } for (k = rank * q; k <= chinese_remainder_bound(rank, q, C); k++){ // printf("Adding %d to queue\n", sleep_values[(repartition == 0)?k:chinese_remainder_value(k, N, C)]); addTile(tiles,sleep_values[(repartition == 0)?k:chinese_remainder_value(k, N, C)]); } free(sleep_values); fclose(fd); }
BlueFramework::Engine::BlueMap::BlueMap( buw::ReferenceCounted<buw::IRenderSystem> renderSystem, buw::ReferenceCounted<buw::IRenderContext> renderContext_ ) : renderSystem_(renderSystem), renderContext_(renderContext_), stopThread_(false), mapSizeInPixels_(256) { textureRepository_ = std::make_shared<buw::TextureRepository>(); quadShader_ = renderSystem_->createShader("Shader/drawQuad.be"); quad_ = std::make_shared<buw::Quad2>(renderSystem_, quadShader_, buw::eFilter::None); loading_ = buw::loadTexture(renderSystem, "Data/textures/loading.png"); #ifdef USA start_ = buw::vector2i(5240, 12661); #else start_ = buw::vector2i(139495, 90962); start_ = buw::vector2i(34873-3, 22740); #endif for (int x = 0; x < 50; x++) for(int y = 0; y < 30; y++) { addTile( start_ + buw::vector2i(x, y) ); } t1 = std::thread(&BlueMap::loadTextures, this); }
void WorldTiles::initializeFromChunks(WorldChunks *chunks, TileManager *manager, PhysicsManager *physicsManager) { init(); for (int i=0; i<(m_nWidth/10); i++) { for (int j=0; j<(m_nHeight/10); j++) { Chunk *chunk = chunks->getChunk(i,j); for (int x=0; x<10; x++) { for (int y=0; y<10; y++) { m_worldTiles[i*10+x][j*10+y]->tileMode = (TileMode) chunk->getTileMode(x,y); } } } } for (int i=0; i<m_nWidth; i++) { for (int j=0; j<m_nHeight; j++) { Tile *blockTile = new Tree(); *blockTile = *(Tree*)manager->getTile("Tree"); blockTile->translate(i-5.0f, 0, j-5.0f); if (rand() % 50 == 1) { addTile(i,j,blockTile,physicsManager); } } } }
void UMPFile::parseTile (Tokeniser &tokeniser) throw (UMPException) { std::string name = tokeniser.getToken(); if (name.empty()) throw UMPException("Unexpected tile format, expected tile name"); std::string token = tokeniser.getToken(); if (token != "{") throw UMPException("Unexpected tile format, expected {, found " + token); std::string width = tokeniser.getToken(); if (width.empty()) throw UMPException("Unexpected tile format, expected tile width"); std::string height = tokeniser.getToken(); if (width.empty()) throw UMPException("Unexpected tile format, expected tile height"); UMPTile tile(name, string::toInt(width), string::toInt(height)); for (;;) { token = tokeniser.getToken(); if (token.empty() || token == "}") break; // TODO: fill the data } addTile(tile); }
// Called after our constructor is called void SceneSample1::setup() { // Set our virtual camera width to be 320 // This means that the width of the view will be 320 camera->setCameraWidth( 320.0f ); // Background { CCTile3DButton *tile = new CCTile3DButton( this ); // Pass in this scene tile->setupTextured( 640.0f, // Specify the width of the tile "Resources/background.png" ); // Texture to load // Add the tile to our list of touchable tiles, to allow for user interaction addTile( tile ); } // Create a tile CCTile3DButton *tileHelloWorld = NULL; { CCTile3DButton *tile = new CCTile3DButton( this ); tile->setupText( "Hello World", // Tell it to say 'Hello World' 64.0f, // Specify the height of the text true ); // Request the text to be centered // Set the colour of the text model to be black tile->setTextColour( CCColour( 1.0f ), true ); addTile( tile ); tileHelloWorld = tile; } // Create a tile with an image { CCTile3DButton *tile = new CCTile3DButton( this ); tile->setupTextured( 128.0f, "Resources/f7u12_derp.png" ); addTile( tile ); // Position it underneath our hello world tile tile->positionTileBelow( tileHelloWorld ); } // refresh the scene range refreshCameraView(); }
void TCOD_noteye_init() { if(scr) return; if(tnoteye.port == 0) tnoteye.port = 6678; if(tnoteye.quality == 0) tnoteye.quality = 256; if(tnoteye.minTicks == 0) tnoteye.minTicks = 50; if(tnoteye.name == NULL) tnoteye.name = "libtcod"; if(tnoteye.maxClients <= 0) tnoteye.maxClients = 1; if(tnoteye.maxClients > MAXCLIENT) tnoteye.maxClients = MAXCLIENT; objs.push_back(NULL); objs.push_back(&gfx); exsurface=SDL_CreateRGBSurface(SDL_SWSURFACE,16,16,32,0,0,0,0); img = new Image(8*32, 16*8); img->title = TCOD_ctx.font_file; registerObject(img); fontcount = TCOD_ctx.fontNbCharHoriz * TCOD_ctx.fontNbCharVertic; ourfont = new int[fontcount]; for(int ch=0; ch<fontcount; ch++) { int ascii= TCOD_ctx.ascii_to_tcod[ch]; int ti = addTile(img, (ascii%TCOD_ctx.fontNbCharHoriz)*TCOD_ctx.font_width, (ascii/TCOD_ctx.fontNbCharHoriz)*TCOD_ctx.font_height, TCOD_ctx.font_width, TCOD_ctx.font_height, 0); (byId<TileImage> (ti, LS_image))->chid = ch; ourfont[ch] = ti; } scr = new Screen; registerObject(scr); IPaddress ip; noteye_initnet(); if(SDLNet_ResolveHost(&ip, NULL, tnoteye.port) != 0) { printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError()); exit(1); } TCPsocket skt = SDLNet_TCP_Open(&ip); if(!skt) { printf("SDLNet_TCP_Open: %s\n", SDLNet_GetError()); exit(1); } server = new TCPServer(skt); }
//creates grid of size x * y void Window::makeGrid(int x, int y) { for (int a = 0;a < x*y; a++){ tiles.append(addTile(a%x, a/x)); connect(tiles.last(), SIGNAL(textChanged(const QString &)), mapper, SLOT(map())); mapper->setMapping(tiles.last(), a); tiles.last()->show(); } if (x < 4) x = 4; this->setFixedSize(40*x, 115+40*y); }
void TileList::raise(int x, int y){ //get the tile int index = indexOfTopTile(x,y); //there was no tile if (index == -1) return; Tile tile = tileArray[index]; //remove the tile from its current place and add it to the end of the list removeTile(index); addTile(tile); }
int addRoom(struct TileElement** tiles, struct Room rm, int curr) { int added = 0; int x = rm.pos.x; while (x < rm.pos.x+rm.dim.x) { int y = rm.pos.y; while (y < rm.pos.y+rm.dim.y) { added += addTile(tiles, x, y, curr+added); ++y; } ++x; } return added; };
int addCaveRoom(struct TileElement **tiles, struct CaveRoom* cr, int curr) { int box_len = ceil(cr->radius+pos_most(cr->trig_effect)); int box_size = box_len*box_len*4; int num_tries = 0;//-box_size; int added = 0; while (num_tries < box_size) { Pos2 tile_pos; tile_pos.x = floor(num_tries/(box_len*2))-box_len; tile_pos.y = num_tries%(box_len*2)-box_len; if (check_in_cave_room_rel(cr, &tile_pos) == 0) addTile(tiles, tile_pos.x+cr->origin.x, tile_pos.y+cr->origin.y, curr+added); ++num_tries; } return added; };
void renderer::worldToArray(world* gameSpace) { unsigned int pos[2]; double color[] = {1,1,1}; int location[2]; for(int i = 0; i < gameSpace -> getY(); i++) { pos[1] = i; for(int j = 0; j < gameSpace -> getX(); j++) { pos[0] = j; tileData -> addTile(gameSpace -> checkTileMap(pos)); location[0] = j*gameSpace -> getResolution(), location[1] = i*gameSpace -> getResolution(); addTile(location, color, gameSpace -> getResolution()); } } }
int FileWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: newScene(); break; case 1: addChunk(); break; case 2: addTile(); break; case 3: saveChunk(); break; case 4: saveTile(); break; default: ; } _id -= 5; } return _id; }
bool dtNavMesh::init(unsigned char* data, const int dataSize, const int flags) { // Make sure the data is in right format. dtMeshHeader* header = (dtMeshHeader*)data; if (header->magic != DT_NAVMESH_MAGIC) return false; if (header->version != DT_NAVMESH_VERSION) return false; dtNavMeshParams params; dtVcopy(params.orig, header->bmin); params.tileWidth = header->bmax[0] - header->bmin[0]; params.tileHeight = header->bmax[2] - header->bmin[2]; params.maxTiles = 1; params.maxPolys = header->polyCount; if (!init(¶ms)) return false; return addTile(data, dataSize, flags) != 0; }
int MapTileLayer::_tileRegion(const Coordinate& a, const Coordinate& b, int lod, bool async) { MapLoader* loader = MapViewLayer::Context.Loader; auto ai = loader->getTileIndex(a, lod); auto bi = loader->getTileIndex(b, lod); Coordinate size = loader->getTileSize(lod); cocos2d::log("Map rebuild (%d,%d) (%d,%d)", ai.first, ai.second, bi.first, bi.second); int tilesNotYetLoaded = 0; for(int i = ai.second; i <= bi.second; ++i) // y axis { for(int j = ai.first; j <= bi.first; ++j) // x axis { Coordinate position = Coordinate(j*size.x, i*size.y); const MapTileInfo& tileInfo = loader->getMapTileInfo({j, i}, lod); tilesNotYetLoaded += addTile(tileInfo, position, size, async); } } return tilesNotYetLoaded; }
void Building::generate() { clearTiles(); std::vector<std::pair<sf::Vector2i,sf::IntRect>> tiles = getTiles(mCoords); for (std::size_t i = 0; i < tiles.size(); i++) { sf::IntRect rect; if (mBuilt) { rect = tiles[i].second; } else { rect = sf::IntRect(1536,0,256,256); } std::cout << rect.left << " " << mType << std::endl; addTile(tiles[i].first,"building",rect); } }
bool TileCachedRecastMeshManager::addObject(const ObjectId id, const btCollisionShape& shape, const btTransform& transform, const AreaType areaType) { bool result = false; auto& tilesPositions = mObjectsTilesPositions[id]; const auto border = getBorderSize(mSettings); { auto tiles = mTiles.lock(); getTilesPositions(shape, transform, mSettings, [&] (const TilePosition& tilePosition) { if (addTile(id, shape, transform, areaType, tilePosition, border, tiles.get())) { tilesPositions.insert(tilePosition); result = true; } }); } if (result) ++mRevision; return result; }
// Called after our constructor is called void SceneSample::setup() { // Set our virtual camera width to be 320 // This means that the width of the view will be 320 camera->setCameraWidth( 320.0f ); { CCTile3DButton *tile = new CCTile3DButton( this, // Pass in this scene 100.0f, // Specify the width of the tile "Resources/f7u12_derp.png" ); // Texture to load // On tile pressed and released LAMBDA_1( MyCallback, CCTile3DButton, tile, tile->setBaseTexture( "Resources/f7u12_rage.png", Resource_Packaged ); ) tile->onRelease.add( new MyCallback( tile ) ); // Add the tile to our list of touchable tiles, to allow for user interaction addTile( tile ); }
FileWidget::FileWidget() : QWidget(0) { newSceneBtn = new QPushButton("New Scene"); chunkCmb = new QComboBox(); addChunkToSceneBtn = new QPushButton("Add Scene"); tileCmb = new QComboBox(); addTileToSceneBtn = new QPushButton("Add Tile"); saveAsChunkBtn = new QPushButton("Save as Scene"); saveAsTileBtn = new QPushButton("Save as Tile"); QVBoxLayout *mainLayout = new QVBoxLayout; QHBoxLayout *chunkLayout = new QHBoxLayout; QHBoxLayout *tileLayout = new QHBoxLayout; QHBoxLayout *saveLayout = new QHBoxLayout; chunkLayout->addWidget(chunkCmb); chunkLayout->addWidget(addChunkToSceneBtn); saveLayout->addWidget(saveAsChunkBtn); mainLayout->addWidget(newSceneBtn); mainLayout->addLayout(chunkLayout); mainLayout->addLayout(saveLayout); mainLayout->setContentsMargins(0,0,0,0); setLayout(mainLayout); connect(newSceneBtn, SIGNAL(clicked()),this, SLOT(newScene())); connect(addChunkToSceneBtn, SIGNAL(clicked()),this, SLOT(addChunk())); connect(addTileToSceneBtn, SIGNAL(clicked()),this, SLOT(addTile())); connect(saveAsChunkBtn, SIGNAL(clicked()),this, SLOT(saveChunk())); connect(saveAsTileBtn, SIGNAL(clicked()),this, SLOT(saveTile())); setFixedHeight(sizeHint().height()); setFixedWidth(400); }
dtStatus dtNavMesh::init(unsigned char* data, const int dataSize, const int flags) { // Make sure the data is in right format. dtMeshHeader* header = (dtMeshHeader*)data; if (header->magic != DT_NAVMESH_MAGIC) return DT_FAILURE | DT_WRONG_MAGIC; if (header->version != DT_NAVMESH_VERSION) return DT_FAILURE | DT_WRONG_VERSION; dtNavMeshParams params; dtVcopy(params.orig, header->bmin); params.tileWidth = header->bmax[0] - header->bmin[0]; params.tileHeight = header->bmax[2] - header->bmin[2]; params.maxTiles = 1; params.maxPolys = header->polyCount; dtStatus status = init(¶ms); if (dtStatusFailed(status)) return status; return addTile(data, dataSize, flags, 0, 0); }
void GraphicalBoardFrame::recreateWidgets() { Quackle::Board emptyBoard; emptyBoard.prepareEmptyBoard(); for (QSize currentTile(0, 0); currentTile.height() < m_boardSize.height(); currentTile.setHeight(currentTile.height() + 1)) { for (currentTile.setWidth(0); currentTile.width() < m_boardSize.width(); currentTile.setWidth(currentTile.width() + 1)) { TileWidget *newTile = new TileWidget; newTile->setLocation(currentTile); newTile->setAlwaysShowVerboseLabels(m_alwaysShowVerboseLabels); newTile->setOriginalInformation(emptyBoard.tileInformation(currentTile.height(), currentTile.width())); addTile(currentTile, newTile); } } for (int row = 0; row <= m_boardSize.height(); ++row) { MarkWidget *newMark = new MarkWidget; if (row == 0) newMark->setCapstone(); else newMark->setRow(row); addMark(QSize(0, row), newMark); } for (int col = 1; col <= m_boardSize.width(); ++col) { MarkWidget *newMark = new MarkWidget; newMark->setCol(col); addMark(QSize(col, 0), newMark); } }
Walls::Walls(Background &bg) { /* basic idea: process all the tiles from the Background map (not to be confused with TileMap, which is much cooler) */ TileMap &tilemap = bg.getTileMap(); int i, j; for (j = 0; j < 60; j++) for (i= 0; i < 80; i++) { Point p(i*8, j*8); TileMapEntry *tme = tilemap.index(i,j); assert(tme); tme->setTileType(bg.mapIndex(i, j)); tme->setULCorner(p); tme->setIndex(i,j); addTile(tilemap, *tme); } }
int CMainMap::initMap(ALLEGRO_DISPLAY *display, CData* gameData) { int iRet = RET_OKAY; int line=0, col=0; ALLEGRO_BITMAP* image = NULL; // check, if display is valid if (!display) { return RET_ERR; } image = gameData->getResources()->getGraphic(RESG_MAPTILE)->getImage(RESG_IMG_STYLE_STD); if (image) { m_tileWidth = al_get_bitmap_width(image); m_tileHeight = al_get_bitmap_height(image); } else { return RET_ERR; } m_activeGraphic = gameData->getResources()->getGraphic(RESG_MAPTILEACTIVE); // load tile graphic and build a tile map if (iRet == RET_OKAY){ for (line=0; line < m_mapLines; line++) { for (col=0; col < m_mapCols; col++) { addTile(gameData->getGraphic(RESG_MAPTILE), line, col); // hier müsste eigentlich eine MAP geladen werden, so sind alle MAP-Grafiken gleich } } } setActiveTile(0); return iRet; }
std::vector<TilePosition> TileCachedRecastMeshManager::updateObject(const ObjectId id, const btCollisionShape& shape, const btTransform& transform, const AreaType areaType) { const auto object = mObjectsTilesPositions.find(id); if (object == mObjectsTilesPositions.end()) return std::vector<TilePosition>(); auto& currentTiles = object->second; const auto border = getBorderSize(mSettings); std::vector<TilePosition> changedTiles; std::set<TilePosition> newTiles; { auto tiles = mTiles.lock(); const auto onTilePosition = [&] (const TilePosition& tilePosition) { if (currentTiles.count(tilePosition)) { newTiles.insert(tilePosition); if (updateTile(id, transform, areaType, tilePosition, tiles.get())) changedTiles.push_back(tilePosition); } else if (addTile(id, shape, transform, areaType, tilePosition, border, tiles.get())) { newTiles.insert(tilePosition); changedTiles.push_back(tilePosition); } }; getTilesPositions(shape, transform, mSettings, onTilePosition); for (const auto& tile : currentTiles) if (!newTiles.count(tile) && removeTile(id, tile, tiles.get())) changedTiles.push_back(tile); } std::swap(currentTiles, newTiles); if (!changedTiles.empty()) ++mRevision; return changedTiles; }
void img (const char *FileNameImg) { FILE *FileImg; COLOR *TabColor, *Color, *TileColor; STRING Name; INDEX i, j, rank; BYTE Byte; int N = 18988, err, provided; int next_proc; MPI_Request rs; MPI_Status status; MPI_Init_thread(NULL, NULL, MPI_THREAD_MULTIPLE, &provided); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &P); next_proc = (rank + 1) % P; if (next_proc == 0) next_proc++; P--; MPI_Type_vector(1, 3, 0, MPI_FLOAT, &MPI_COLOR); MPI_Type_commit(&MPI_COLOR); if (rank == 0) { strcpy (Name, FileNameImg); strcat (Name, ".ppm"); INIT_FILE (FileImg, Name, "w"); fprintf (FileImg, "P6\n%d %d\n255\n", Img.Pixel.i, Img.Pixel.j); } // number of tiles Ci = Img.Pixel.i / TILE_SIZE + (Img.Pixel.i % TILE_SIZE?1:0); // number of tiles in dimension i Cj = Img.Pixel.j / TILE_SIZE + (Img.Pixel.i % TILE_SIZE?1:0); // number of tiles in dimension j int C = Ci * Cj; int q = (C+P-1)/P; int size = Img.Pixel.i * Img.Pixel.j ; N = C/2+1; // buffer for each tile INIT_MEM (TileColor, TILE_SIZE * TILE_SIZE, COLOR); if (rank != 0) { struct TileQueue tiles = {NULL, NULL}; // Init tasks init(&tiles,rank,q,N,C); // Init mutex, semaphores & threads pthread_mutex_init(&mutex,NULL); pthread_mutex_init(&mutex_time,NULL); sem_init(&wait_work, 0, 0); sem_init(&ask_work, 0, 0); pthread_t tid[NB_THREADS]; for (i = 0; i < NB_THREADS; i++){ err = pthread_create(&(tid[i]), NULL, (void*)tile_fill, (void*)&tiles); if (err != 0) printf("\ncan't create thread :[%s]", strerror(err)); } // vol de travail ? if (vol){ // Main thread: Communicator while (!terminated) { int flag = 0, msg; MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status); if (flag) { // We DID receive a communication so we CAN do a blocking receive MPI_Recv(&msg, 1, MPI_INT, status.MPI_SOURCE, status.MPI_TAG, MPI_COMM_WORLD, &status); // TAG contains the information about what the message is switch (status.MPI_TAG){ case TERMINATE: // No more jobs; threads can finish their jobs and return MPI_Isend(&msg, 1, MPI_INT, next_proc, TERMINATE, MPI_COMM_WORLD, &rs); terminated = 1; break; case WORK_ASK: // msg-th process is seeking for job pthread_mutex_lock(&mutex); if(!isEmpty(&tiles)){ int tile = firstElement(&tiles); pop(&tiles); pthread_mutex_unlock(&mutex); MPI_Isend(&tile, 1, MPI_INT, msg, WORK_SEND, MPI_COMM_WORLD, &rs); } else { pthread_mutex_unlock(&mutex); if (msg == rank){ MPI_Isend(&msg, 1, MPI_INT, next_proc, TERMINATE, MPI_COMM_WORLD, &rs); terminated = 1; } else { MPI_Isend(&msg, 1, MPI_INT, next_proc, WORK_ASK, MPI_COMM_WORLD, &rs); } } break; case WORK_SEND: // Received a job pthread_mutex_lock(&mutex); addTile(&tiles, msg); pthread_mutex_unlock(&mutex); sem_post(&wait_work); break; default: fprintf(stderr, "Err: Unknown message: %d, with tag %d\n", msg,status.MPI_TAG); break; } } if (sem_trywait(&ask_work) == 0){ MPI_Isend(&rank, 1, MPI_INT, next_proc, WORK_ASK, MPI_COMM_WORLD, &rs); } } for (i = 0; i < NB_THREADS; i++){ sem_post(&wait_work); } } for (i = 0; i < NB_THREADS; i++){ pthread_join(tid[i],NULL); } pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&mutex_time); sem_destroy(&wait_work); sem_destroy(&ask_work); fprintf(stderr, "%d %ld\n", rank, local_time); } // process 0 gathers all the tiles if (rank == 0){ // If fake tasks: we don't receive anything and don't write the image FILE* fd = fopen("config","r"); if (fd != NULL){ int fake; fscanf(fd,"%d\n",&fake); if (fake){ EXIT_FILE(FileImg); EXIT_MEM(TileColor); MPI_Finalize(); return; } } // final image buffer that will receive the tiles INIT_MEM (TabColor, size, COLOR); // Receive tiles from other procs for (i = 0; i < C ; i++){ MPI_Recv(TileColor, TILE_SIZE * TILE_SIZE, MPI_COLOR, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); int current_tile = status.MPI_TAG - TILE_TAG_INDEX; int j_begin = rank_j(current_tile,Cj); int index_begin = rank_i(current_tile,Ci) + j_begin * Img.Pixel.i; for (j = 0; j < TILE_SIZE && j_begin + j < Img.Pixel.j; j++) { memcpy(&TabColor[index_begin + j * Img.Pixel.i],&TileColor[j * TILE_SIZE],MIN(Img.Pixel.i - rank_i(current_tile,Ci),TILE_SIZE) * sizeof(COLOR)); } } // writing in file for (j = 0, Color = TabColor; j < size; j++, Color++) { Byte = Color->r < 1.0 ? 255.0*Color->r : 255.0; putc (Byte, FileImg); Byte = Color->g < 1.0 ? 255.0*Color->g : 255.0; putc (Byte, FileImg); Byte = Color->b < 1.0 ? 255.0*Color->b : 255.0; putc (Byte, FileImg); } EXIT_FILE (FileImg); printf("Copied in file\n"); EXIT_MEM (TabColor); } EXIT_MEM (TileColor); MPI_Finalize(); }
frameSprite_* getFrameSprite(unsigned char *image8bpp, int wi, int x, int y, int w, int h) { int i, j; int p, pal; int index; unsigned int tile[8]; frameSprite_* result; tileset_* tileset; // get palette for this sprite pal = getTile(image8bpp, tile, 0, 0, wi * 8); // error retrieving tile --> return NULL if (pal == -1) return NULL; // allocate tileset tileset = createTileSet(malloc(w * h * 32), 0); for(i = 0; i < w; i++) { for(j = 0; j < h; j++) { p = getTile(image8bpp, tile, i + x, j + y, wi * 8); // error retrieving tile --> return NULL if (p == -1) { freeTileset(tileset); return NULL; } // different palette in VDP same sprite --> error if (p != pal) { printf("Error: Sprite at position (%d,%d) of size [%d,%d] reference different palette.", x, y, w, h); freeTileset(tileset); return NULL; } index = addTile(tile, tileset, FALSE); // error adding new tile --> return NULL if (index == -1) { freeTileset(tileset); return NULL; } } } // allocate result result = malloc(sizeof(frameSprite_)); // always first index as we result->ind = 0; result->attr = TILE_ATTR(pal, FALSE, FALSE, FALSE); // initialized afterward result->x = 0; result->y = 0; result->w = w; result->h = h; result->tileset = tileset; return result; }
void Layer::updateTiles() { if ((boundingRect().width() == 0) || (boundingRect().height() == 0)) return; // TODO create enums to define image aspect, auto tile, etc... QPixmap pix(source()); // TODO if (m_drawType == Quasi::PlaneDrawType) { m_tileWidth = width(); m_tileHeight = height(); if (pix.width() % (int)width() != 0) { // XXX create some log system? qCritical() << QString("Quasi>>Image \'%1\' doesn't contains a proper size... CROPPING!").arg(source()); int newWidth = pix.width() - (pix.width() % (int)width()); pix = pix.copy(0, 0, newWidth, height()); } } if (pix.width() < boundingRect().width()) { QPixmap temp(boundingRect().width(), boundingRect().height()); QPainter p(&temp); p.drawTiledPixmap(boundingRect(), pix, QPoint(0,0)); p.end(); pix = temp; } QPixmap mirrored; if (m_type == Quasi::MirroredType){ QImage image = pix.toImage(); mirrored = QPixmap::fromImage(image.mirrored(true, false)); } // visible tiles m_numColumns = boundingRect().width() / m_tileWidth; m_numRows = boundingRect().height() / m_tileHeight; // total of columns and rows m_totalColumns = pix.width() / m_tileWidth; m_totalRows = pix.height() / m_tileHeight; int i, j; for (i = 0; i < m_totalRows; i++) { for (j = 0; j < m_totalColumns; j++){ QPixmap temp(m_tileWidth, m_tileHeight); QPainter p(&temp); p.setCompositionMode(QPainter::CompositionMode_Source); p.drawPixmap(0, 0, m_tileWidth, m_tileHeight, pix, j * m_tileWidth, i * m_tileHeight, m_tileWidth, m_tileHeight); p.end(); addTile(temp); if (m_type == Quasi::MirroredType) { QPainter p(&temp); p.drawPixmap(0, 0, m_tileWidth, m_tileHeight, mirrored, j * m_tileWidth, i * m_tileHeight, m_tileWidth, m_tileHeight); p.end(); m_mirroredTiles.append(temp); } } } generateOffsets(); drawPixmap(); }
void Source::update(Map& map, uv::worker& worker, util::ptr<Style> style, GlyphAtlas& glyphAtlas, GlyphStore& glyphStore, SpriteAtlas& spriteAtlas, util::ptr<Sprite> sprite, Texturepool& texturepool, FileSource& fileSource, std::function<void ()> callback) { if (!loaded || map.getTime() <= updated) return; bool changed = false; int32_t zoom = std::floor(getZoom(map.getState())); std::forward_list<Tile::ID> required = coveringTiles(map.getState()); // Determine the overzooming/underzooming amounts. int32_t minCoveringZoom = util::clamp<int32_t>(zoom - 10, info.min_zoom, info.max_zoom); int32_t maxCoveringZoom = util::clamp<int32_t>(zoom + 1, info.min_zoom, info.max_zoom); // Retain is a list of tiles that we shouldn't delete, even if they are not // the most ideal tile for the current viewport. This may include tiles like // parent or child tiles that are *already* loaded. std::forward_list<Tile::ID> retain(required); // Add existing child/parent tiles if the actual tile is not yet loaded for (const Tile::ID& id : required) { const TileData::State state = addTile(map, worker, style, glyphAtlas, glyphStore, spriteAtlas, sprite, fileSource, texturepool, id, callback); if (state != TileData::State::parsed) { // The tile we require is not yet loaded. Try to find a parent or // child tile that we already have. // First, try to find existing child tiles that completely cover the // missing tile. bool complete = findLoadedChildren(id, maxCoveringZoom, retain); // Then, if there are no complete child tiles, try to find existing // parent tiles that completely cover the missing tile. if (!complete) { findLoadedParent(id, minCoveringZoom, retain); } } if (state == TileData::State::initial) { changed = true; } } // Remove tiles that we definitely don't need, i.e. tiles that are not on // the required list. std::set<Tile::ID> retain_data; util::erase_if(tiles, [&retain, &retain_data, &changed](std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair) { Tile &tile = *pair.second; bool obsolete = std::find(retain.begin(), retain.end(), tile.id) == retain.end(); if (obsolete) { changed = true; } else { retain_data.insert(tile.data->id); } return obsolete; }); // Remove all the expired pointers from the set. util::erase_if(tile_data, [&retain_data](std::pair<const Tile::ID, std::weak_ptr<TileData>> &pair) { const util::ptr<TileData> tile = pair.second.lock(); if (!tile) { return true; } bool obsolete = retain_data.find(tile->id) == retain_data.end(); if (obsolete) { tile->cancel(); return true; } else { return false; } }); updated = map.getTime(); }
void TileManager::updateTileSet() { m_tileSetChanged = false; // Check if any native worker needs to be dispatched i.e. queuedTiles is not empty { auto workersIter = m_workers.begin(); auto queuedTilesIter = m_queuedTiles.begin(); while (workersIter != m_workers.end() && queuedTilesIter != m_queuedTiles.end()) { auto& worker = *workersIter; if (worker->isFree()) { worker->processTileData(std::move(*queuedTilesIter), m_scene->getStyles(), *m_view); queuedTilesIter = m_queuedTiles.erase(queuedTilesIter); } ++workersIter; } } // Check if any incoming tiles are finished for (auto& worker : m_workers) { if (!worker->isFree() && worker->isFinished()) { // Get result from worker and move it into tile set auto tile = worker->getTileResult(); const TileID& id = tile->getID(); logMsg("Tile [%d, %d, %d] finished loading\n", id.z, id.x, id.y); std::swap(m_tileSet[id], tile); cleanProxyTiles(id); m_tileSetChanged = true; } } if (! (m_view->changedOnLastUpdate() || m_tileSetChanged) ) { // No new tiles have come into view and no tiles have finished loading, // so the tileset is unchanged return; } const std::set<TileID>& visibleTiles = m_view->getVisibleTiles(); // Loop over visibleTiles and add any needed tiles to tileSet { auto setTilesIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (visTilesIter != visibleTiles.end()) { if (setTilesIter == m_tileSet.end() || *visTilesIter < setTilesIter->first) { // tileSet is missing an element present in visibleTiles addTile(*visTilesIter); m_tileSetChanged = true; ++visTilesIter; } else if (setTilesIter->first < *visTilesIter) { // visibleTiles is missing an element present in tileSet (handled below) ++setTilesIter; } else { // tiles in both sets match, move on ++setTilesIter; ++visTilesIter; } } } // Loop over tileSet and remove any tiles that are neither visible nor proxies { auto setTilesIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (setTilesIter != m_tileSet.end()) { if (visTilesIter == visibleTiles.end() || setTilesIter->first < *visTilesIter) { // visibleTiles is missing an element present in tileSet if (setTilesIter->second->getProxyCounter() <= 0) { removeTile(setTilesIter); m_tileSetChanged = true; } else { ++setTilesIter; } } else if (*visTilesIter < setTilesIter->first) { // tileSet is missing an element present in visibleTiles (shouldn't occur) ++visTilesIter; } else { // tiles in both sets match, move on ++setTilesIter; ++visTilesIter; } } } }
Quarry::Quarry(sf::Vector2i const& coords) : Resource(coords) { mType = Buildings::Quarry; addTile(coords,"building",sf::IntRect(1024,0,256,256)); addResource(Resources::Rock,1000); }
// Loads the map into the memory bool CMapLoader::load( Uint8 episode, Uint8 level, const std::string& path, bool loadNewMusic, bool stategame ) { std::string levelname = "level"; if(level < 10) levelname += "0"; levelname += itoa(level) + ".ck" + itoa(episode); mp_map->resetScrolls(); mp_map->m_gamepath = path; mp_map->m_worldmap = (level == 80); // HQ Music. Load Music for a level if you have HQP if(loadNewMusic) { g_pMusicPlayer->stop(); // If no music from the songlist could be loaded try the normal table which // has another format. It is part of HQP if(!g_pMusicPlayer->LoadfromSonglist(path, level)) g_pMusicPlayer->LoadfromMusicTable(path, levelname); } // decompress map RLEW data std::ifstream MapFile; bool fileopen = OpenGameFileR(MapFile, getResourceFilename(levelname,path,true,false), std::ios::binary); if (!fileopen) { // only record this error message on build platforms that log errors // to a file and not to the screen. g_pLogFile->ftextOut("MapLoader: unable to open file %s<br>", levelname.c_str()); return 0; } g_pLogFile->ftextOut("MapLoader: file %s opened. Loading...<br>", levelname.c_str()); MapFile.seekg (0, std::ios::beg); // load the compressed data into the memory std::vector<Uint8> compdata; while( !MapFile.eof() ) { compdata.push_back(static_cast<Uint8>(MapFile.get())); } MapFile.close(); CRLE RLE; std::vector<Uint16> planeitems; RLE.expandSwapped(planeitems,compdata, 0xFEFE); // Here goes the memory allocation function mp_map->createEmptyDataPlane(1, planeitems.at(1), planeitems.at(2)); int t; unsigned int planesize = 0; unsigned int curmapx=0, curmapy=0; planesize = planeitems.at(8); planesize /= 2; // Size of two planes, but we only need one const char &fixlevel_error = g_pBehaviorEngine->m_option[OPT_FIXLEVELERRORS].value; Uint32 c; for( c=17 ; c<planesize+17 ; c++ ) // Check against Tilesize { t = planeitems.at(c); if( fixlevel_error ) fixLevelTiles(t, curmapx, curmapy, episode, level); addTile(t, curmapx, curmapy); curmapx++; if (curmapx >= mp_map->m_width) { curmapx = 0; curmapy++; if (curmapy >= mp_map->m_height) break; } if(t > 255) t=0; // If there are some invalid values in the file } // now do the sprites // get sprite data int resetcnt, resetpt; curmapx = curmapy = 0; resetcnt = resetpt = 0; if(mp_objvect && stategame == false) { std::vector<CObject*>::iterator obj = mp_objvect->begin(); for( ; obj != mp_objvect->end() ; obj++ ) { delete *obj; mp_objvect->pop_back(); } mp_objvect->reserve(2000); for( c=planesize+17 ; c<2*planesize+16 ; c++ ) { // in case the planesizes are bigger than the actual file content itself if(planeitems.size() <= c) break; t = planeitems.at(c); if (mp_map->m_worldmap) addWorldMapObject(t, curmapx, curmapy, episode ); else addEnemyObject(t, curmapx, curmapy, episode, level); curmapx++; if (curmapx >= mp_map->m_width) { curmapx = 0; curmapy++; if (curmapy >= mp_map->m_height) break; } if (++resetcnt==resetpt) curmapx = curmapy = 0; } } planeitems.clear(); // Do some post calculations // Limit the scroll screens so the blocking (blue in EP1) tiles are3 never seen SDL_Rect gamerect = g_pVideoDriver->getGameResolution(); mp_map->m_maxscrollx = (mp_map->m_width<<4) - gamerect.w - 32; mp_map->m_maxscrolly = (mp_map->m_height<<4) - gamerect.h - 32; // Set Scrollbuffer g_pVideoDriver->setScrollBuffer(&mp_map->m_scrollx_buf, &mp_map->m_scrolly_buf); return true; }