private void UpdateUVs() { int numVertices = (m_width) * (m_height) * 4; Vector2[] uvs = new Vector2[numVertices]; if (SourceChunk != null) { for (int j = 0; j < m_height; ++j) { for (int i = 0; i < m_width; ++i) { TileInfo tileInfo = m_sourceChunk.ReadSlotValue(i, j); int vertexIndex = (j * m_width + i) * 4; TileMapping.GetUVFromTile(tileInfo, out uvs[vertexIndex], out uvs[vertexIndex + 1], out uvs[vertexIndex + 2], out uvs[vertexIndex + 3]); } } } MeshFilter mf = GetComponent <MeshFilter>(); mf.mesh.uv = uvs; m_dirty = false; }
public static Tileset FromAlbion(TilesetData tileset, Tilemap2DProperties properties) { if (tileset == null) { throw new ArgumentNullException(nameof(tileset)); } if (properties == null) { throw new ArgumentNullException(nameof(properties)); } List <Tile> tiles = tileset.Tiles .Where(x => !x.IsBlank) .Select(x => TileMapping.BuildTile( tileset.Id.Id, x.Index, x.FrameCount > 0 ? x.ImageNumber : null, TileMapping.BuildTileProperties(x), properties)) .ToList(); // Add tiles for the extra frames of animated tiles int nextId = tileset.Tiles[^ 1].Index + 1;
protected override void Awake() { base.Awake(); m_worldMap = GetComponent <WorldMap>(); TileMapping.BuildFromJSON("tilesInfo"); }
public void Initialize(Texture2D baseImage, TileMapping mapping) { this.Width = baseImage.Width; this.Height = baseImage.Height; Color[] colors = new Color[Width * Height]; baseImage.GetData <Color>(colors); for (int i = 0; i < Width; i++) { for (int j = 0; j < Height; j++) { Color c = colors[GetIndex(i, j)]; int r = c.R; int g = c.G; int b = c.B; int col = r << 16 | g << 8 | b; IMappingAction action = mapping.Default; if (action != null) { action.Execute(this, i, j); } if (mapping.Get(col) != null) { action = mapping.Get(col); } if (action != null) { action.Execute(this, i, j); } } } }
public void RefreshTileMap(List <Vector3Int> changedCellsPositions) { foreach (Vector3Int cellPos in changedCellsPositions) { int x = cellPos.x; int y = cellPos.y; Cell foregroundCell = Data.GetForegroundCellAt(x, y); if (foregroundCell != null) { if (!foregroundCell.IsHidden) { TileMapping tileMapping = tileMappings.FirstOrDefault((t) => t.cellType == foregroundCell.Type); if (tileMapping != null) { foregroundTilemap.SetTile(new Vector3Int(x, y, 0), tileMapping.tile); } } else { foregroundTilemap.SetTile(new Vector3Int(x, y, 0), null); } } Cell backgroundCell = Data.GetBackgroundCellAt(x, y); if (backgroundCell != null) { TileMapping tileMapping = tileMappings.FirstOrDefault((t) => t.cellType == backgroundCell.Type); if (tileMapping != null) { backgroundTilemap.SetTile(new Vector3Int(x, y, 0), tileMapping.tile); } } } }
public Texture2D GenerateEnemies(Texture2D _levelMap) { LevelGenerator LG = GetComponent <LevelGenerator>(); levelMap = LG.CopyTexture(_levelMap); //make sure not to edit original texture for (int x = 0; x < levelMap.width; x++) { for (int y = 0; y < levelMap.height; y++) { Color pixelColor = levelMap.GetPixel(x, y); if (pixelColor.a == 0.0f) { allValid.Add(new Vector2Int(x, y)); //find all empty points in level } TileMapping tile = Array.Find(LG.mappingsHolder.mappings, TileMapping => TileMapping.color == pixelColor); if (tile != null && tile.tileType == TileMapping.SpecialTileType.door) { doorLocations.Add(new Vector2Int(x, y)); } } } //remove positions near enterance List <Vector2Int> positionsToRemove = new List <Vector2Int>(); float minDistFromDoor = 8; Vector2Int doorPos = (doorLocations[0].y > doorLocations[1].y) ? doorLocations[0] : doorLocations[1]; foreach (Vector2Int pos in allValid) { if (Vector2Int.Distance(pos, doorPos) < minDistFromDoor) { positionsToRemove.Add(pos); } } foreach (Vector2Int posToRemove in positionsToRemove) { allValid.Remove(posToRemove); } foreach (Vector2Int pos in allValid) //test for valid spawn types { if (CanSpawnGround(pos)) { groundSpawns.Add(pos); } if (CanSpawnAir(pos)) { airSpawns.Add(pos); } if (CanSpawnTreasure(pos)) { treasureSpawns.Add(pos); } } AssignTreasureWeights(); return(CreateEnemyTexture()); }
public static void saveTileMappings(Dictionary <int, int[, ]> tileMapping) { BinaryFormatter bf = new BinaryFormatter(); FileStream stream = new FileStream(Application.persistentDataPath + "/tileMappings.sav", FileMode.Create); TileMapping mapping = new TileMapping(tileMapping); bf.Serialize(stream, mapping); stream.Close(); }
private void Build() { Vector3 clickPoint = CastRay(); Tile clickedTile = world.GetTileAt(V3ToWorldSpace(clickPoint)); TileMapping mapping = TileMappings.Find(m => m.type == SelectedTileType); //Debug.Log(mapping.ToString()); BuildController.Build(mapping, clickedTile, world); }
public override void Update() { m_player.BeforeInputPos = m_player.transform.position; m_player.AfterInputPos = m_player.BeforeInputPos; if (m_player.HealthComponent.Health <= 0) { SwitchState <PlayerState_Dead>(); GameManager.Instance.OnMainPlayerDead(); return; } m_timeRemainingForNextAttack -= TimeManager.Dt; // Compute actual Player speed float speed = m_player.PlayerSpeed; TileInfo tileInfo = GameManager.Instance.GetTileFromWorldPos(m_player.transform.position); TileProperties tileProperties = TileMapping.GetTileProperties(tileInfo.Tile); if (tileProperties != null) { speed *= tileProperties.SpeedFactor; } Vector3 direction = Vector3.zero; if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W)) { direction.y = speed; } else if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S)) { direction.y = -speed; } if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A)) { direction.x = -speed; } else if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D)) { direction.x = speed; } direction *= TimeManager.Dt; m_player.transform.position = m_player.BeforeInputPos + (Vector2)direction; HandleAutoAttack(); base.Update(); m_player.AfterInputPos = m_player.transform.position; }
private void UpdateText() { if (!GameManager.Instance) { return; } // Update all texts for now for (int i = 0; i < NumInventorySlots; ++i) { ItemCount ic = GameManager.Instance.MainPlayer.Inventory.GetSlotInformation(i); InventorySlotUI isu = m_inventorySlot[i]; if (ic.Count == 0) { isu.m_count.text = ""; } else { isu.m_count.text = ic.Count.ToString(); } isu.m_title.color = (i == m_selectSlotIndex) ? new Color(48 / 255f, 255 / 255f, 42 / 255f) : new Color(1f, 1f, 1f); // set what is owned by this inventory slot if (ic.Item == EItem.None) { isu.m_icon.sprite = null; isu.m_icon.color = new Color(1f, 1f, 1f, 0f); } else { if (isu.m_icon.sprite == null) { TileResourceDef tileResourceDef = TileMapping.GetTileResourceDef((ETile)ic.Item); Texture2D tex = tileResourceDef != null ? Resources.Load(tileResourceDef.Filename) as Texture2D : null; if (tex) { Sprite sprite = Sprite.Create(tex, tileResourceDef.Rect, Vector2.zero); isu.m_icon.sprite = sprite; isu.m_icon.color = ItemInstance.GetColorForItem(ic.Item); isu.m_icon.rectTransform.SetWidth(Mathf.Min(tileResourceDef.Rect.width, 32)); isu.m_icon.rectTransform.SetHeight(Mathf.Min(tileResourceDef.Rect.height, 32)); } } } } }
public static bool BuildFromJSON(string filename) { JSONNode rootNode = JSONUtils.ParseJSON(filename); if (rootNode != null) { return(TileMapping.BuildFromJSON(rootNode)); } return(false); }
public void Build(TileMapping mapping, Tile selected, World world) { if (mapping.type == Tile.TileType.Empty) { return; } // TODO: can we optimize this? // Do a check for (int x = 0; x < mapping.width; x++) { for (int y = 0; y < mapping.height; y++) { Tile tile = world.GetTileAt(new Vector2(selected.X + x, selected.Y + y)); if (tile.Type != Tile.TileType.Empty) { return; } } } // Actually do stuff for (int x = 0; x < mapping.width; x++) { for (int y = 0; y < mapping.height; y++) { Tile tile = world.GetTileAt(new Vector2(selected.X + x, selected.Y + y)); tile.SetType(mapping.type); tile.SetParentTile(selected); } } if (selected.Type != Tile.TileType.Road) { WorldController.Instance.SpawnInstance(new Vector3(selected.X, 0, selected.Y), mapping.prefab.transform, selected); } else { UpdateRoad(selected, world); } if (mapping.type == Tile.TileType.Road) { List <Neighbor> neighbors = GetNeighborRoads(selected, world); List <int> neighborPos = GetNeighborRoadsInts(selected, world); for (int i = 0; i < neighbors.Count; i++) { UpdateRoad(neighbors[i].tile, world); } } }
/// <summary> /// Each tile set is made of a 8x6 grid and between each frame /// </summary> /// <param name="frame">The particular frame to select (e.g. a corner or a border)</param> /// <returns>The <see cref="Rectangle"/> coordinates on the tileSet</returns> public static Rectangle GetFrame(TileMapping frame) { int column = ((int)frame % COLUMNS); int row = (int)frame / COLUMNS; return(new Rectangle( (column * TILE_SIZE), (row * TILE_SIZE), TILE_SIZE, TILE_SIZE )); }
bool TileIsGround(Vector2Int checkPos) { TileMapping[] mappings = GetComponent <LevelGenerator>().mappingsHolder.mappings; bool ret = false; Color tileColor = levelMap.GetPixel(checkPos.x, checkPos.y); TileMapping tile = Array.Find(mappings, TileMapping => TileMapping.color == tileColor); if (tile != null && tile.tileType == TileMapping.SpecialTileType.ground) { ret = true; } return(ret); }
void SpawnMap() { mappings = mappingsHolder.mappings; for (int x = 0; x < fullMap.width; x++) { for (int y = 0; y < fullMap.height; y++) { Color pixelColor = fullMap.GetPixel(x, y); if (pixelColor.a == 0) { continue; } TileMapping tile = Array.Find(mappings, TileMapping => TileMapping.color == pixelColor); Vector3 thisOffset = new Vector3(tileSize * (float)x, tileSize * (float)y, 0); Vector3 spawnPos = transform.position + thisOffset; if (tile != null && tile.prefab != null) //avoid errors during testing { Instantiate(tile.prefab, spawnPos, Quaternion.identity).transform.parent = this.transform; } else { print("no prefab for this mapping"); } } } SpawnableMapping[] spawnablesMappings = mappingsHolder.spawnableMappings; for (int x = 0; x < spawnablesMap.width; x++) { for (int y = 0; y < spawnablesMap.height; y++) { Color pixelColor = spawnablesMap.GetPixel(x, y); if (pixelColor.a == 0) { continue; } SpawnableMapping tile = Array.Find(spawnablesMappings, SpawnableMapping => SpawnableMapping.color == pixelColor); Vector3 thisOffset = new Vector3(tileSize * (float)x, tileSize * (float)y, 0); Vector3 spawnPos = transform.position + thisOffset; if (tile != null && tile.prefab != null) //avoid errors during testing { Instantiate(tile.prefab, spawnPos, Quaternion.identity).transform.parent = this.transform; } else { print("Could not instanciate spawnable with pixel color: " + pixelColor); } } } }
Color ProcessColor(Color startColor, ref TileMapping mappingHolder) { Color retColor = new Color(1, 1, 1, 0); if (startColor.a != 0.0f) //skip blanks { TileMapping lookingAt = Array.Find(mappings, TileMapping => TileMapping.color == startColor); if (lookingAt == null) { print("Mapping not found for color: " + startColor); } else if (UnityEngine.Random.value < lookingAt.weight) { retColor = startColor; //roll for probabilistic tiles mappingHolder = lookingAt; } } return(retColor); }
private ItemInstance SpawnItem(EItem item) { if (!m_itemInstancePrefab) { return(null); } TileResourceDef tileResourceDef = TileMapping.GetTileResourceDef((ETile)item); if (tileResourceDef == null) { return(null); } GameObject obj = Instantiate(m_itemInstancePrefab); if (obj == null) { return(null); } Transform tr = obj.GetComponent <Transform>(); ItemInstance ii = obj.GetComponent <ItemInstance>(); MeshRenderer mr = obj.GetComponent <MeshRenderer>(); if (mr) { Texture tex = Resources.Load(tileResourceDef.Filename) as Texture; if (tex) { mr.material.mainTexture = tex; mr.material.color = ItemInstance.GetColor32ForItem(item); //float scale = (float) (Screen.height / 2.0) / Camera.main.orthographicSize; //tr.localScale = new Vector3((float)tex.width / scale, (float)tex.height / scale, tr.localScale.z); tr.localScale = new Vector3(1.0f, 1.0f, tr.localScale.z); } ii.SetType(item); } return(ii); }
private void SetTileset(string tilesetName) { // Get tileset index int tilesetIndex = GetTilesetIndex(tilesetName); if (tilesetIndex == UserData.current.map.tilesetSources.Count) { Debug.LogError("Could not find tileset: " + tilesetName); return; } int numTiles = (int)UserData.current.map.tilesetSources[tilesetIndex].numTiles; // Get tileset texture Texture2D tileset = TextureManager.GetTileset(tilesetName); if (tileset == null) { Debug.LogError("Tileset not loaded: " + tilesetName); return; } // Get all mappings for tileset int mappingCount = UserData.current.map.tileMappings.Count; for (int i = 0; i < mappingCount; ++i) { TileMapping mapping = UserData.current.map.tileMappings[i]; if (mapping.tilesetIndex != tilesetIndex) { continue; } Sprite tileSprite = TextureManager.GetTileSprite(tileset, numTiles, mapping.tileGraphicIndex); // Create button for tile GameObject goTile = Instantiate(m_TileButtonPrefab); PaintButton button = goTile.GetComponent <PaintButton>(); button.Initialize(m_TileButtonContainer, tileSprite, OnClick_Button, i); } }
private void RefreshOverlay() { if (!gameObject.activeSelf) { return; } if (m_SelectedMappingIndex < 0 || m_SelectedMappingIndex >= UserData.current.map.tileMappings.Count) { return; } // Get mapping and tileset data from mapping index TileMapping mapping = UserData.current.map.tileMappings[m_SelectedMappingIndex]; string tilesetName = UserData.current.map.tilesetSources[mapping.tilesetIndex].tilesetFilename; Texture2D tileset = TextureManager.GetTileset(tilesetName); int numTiles = (int)UserData.current.map.tilesetSources[mapping.tilesetIndex].numTiles; // Set overlay sprite to mapping m_OverlayRenderer.SetOverlay(TextureManager.GetTileSprite(tileset, numTiles, mapping.tileGraphicIndex)); }
void ProcessTileMap() //process all probability tiles and add blocks { LevelGenerator LG = GetComponent <LevelGenerator>(); tileMapProcessing = LG.CopyTexture(tileMap); //make a copy to edit tileMapProcessed = LG.BlankTex(tileMap.width, tileMap.height); //new map to write to for (int x = 0; x < tileMapProcessing.width; x++) { for (int y = tileMapProcessing.height; y >= 0; y--) { Color lookingAtColor = tileMapProcessing.GetPixel(x, y); TileMapping thisMapping = null; Color processedColor = ProcessColor(lookingAtColor, ref thisMapping); if (thisMapping != null) { if (thisMapping.tileType == TileMapping.SpecialTileType.groundBlock) { InsertBlock(x, y, true); continue; } if (thisMapping.tileType == TileMapping.SpecialTileType.airBlock) { InsertBlock(x, y, false); continue; } } tileMapProcessed.SetPixel(x, y, processedColor); } } float chanceToFlip = 0.5f; if (UnityEngine.Random.value > chanceToFlip) //flip entire map half the time { tileMapProcessed = FlipTexture(tileMapProcessed); } }
public void RefreshTileMap() { // TODO: Implement for (int x = 0; x < Data.Width; ++x) { for (int y = 0; y < Data.Height; ++y) { Cell foregroundCell = Data.GetForegroundCellAt(x, y); if (foregroundCell != null) { if (!foregroundCell.IsHidden) { TileMapping tileMapping = tileMappings.FirstOrDefault((t) => t.cellType == foregroundCell.Type); if (tileMapping != null) { foregroundTilemap.SetTile(new Vector3Int(x, y, 0), tileMapping.tile); } } else { foregroundTilemap.SetTile(new Vector3Int(x, y, 0), null); } } Cell backgroundCell = Data.GetBackgroundCellAt(x, y); if (backgroundCell != null) { TileMapping tileMapping = tileMappings.FirstOrDefault((t) => t.cellType == backgroundCell.Type); if (tileMapping != null) { backgroundTilemap.SetTile(new Vector3Int(x, y, 0), tileMapping.tile); } } } } }
Bitmap ConvertIgnoreTSA(Bitmap src, int maxColor, int yohaku, bool isReserve1StPalette, bool isUseTransparent) { int width = src.Width; int height = src.Height; width = U.Padding8(width); height = U.Padding8(height); Bitmap DestBitmap = ImageUtil.Blank(width + yohaku, height); List <ColorRanking> totalRank = new List <ColorRanking>(); List <TileMapping> tileMapping = new List <TileMapping>(); for (int y = 0; y < height; y += 8) { if (y + 8 > height) { continue; } for (int x = 0; x < width; x += 8) { if (x + 8 > width) { continue; } TileMapping tm = new TileMapping(); tm.Rank = new List <ColorRanking>(); tm.Palette = -1; tm.X = x; tm.Y = y; for (int yy = 0; yy < 8; yy++) { for (int xx = 0; xx < 8; xx++) { try { Color c = src.GetPixel(x + xx, y + yy); if (c.A == 0 && isUseTransparent) { continue; } VoteColor(tm.Rank, c); } catch (System.AccessViolationException) {//なんで例外が飛んでくるんだ? break; } } } SortColor(tm.Rank); tileMapping.Add(tm); for (int i = 0; i < tm.Rank.Count; i++) { VoteColor(totalRank, tm.Rank[i]); } } } SortColor(totalRank); //パレットの色数を16色 or 256色にします. List <ColorRanking> paletteList = new List <ColorRanking>(); paletteList.AddRange(Convert16Color(totalRank, isReserve1StPalette, maxColor)); //パレットの適応 ColorPalette cp = DestBitmap.Palette; for (int i = 0; i < maxColor; i++) { cp.Entries[i] = Color.FromArgb( paletteList[i].R , paletteList[i].G , paletteList[i].B ); } //利用しないところはゼロクリア for (int i = maxColor; i < 16 * 16; i++) { cp.Entries[i] = Color.FromArgb(0, 0, 0); } DestBitmap.Palette = cp; int startColor = 0; if (isReserve1StPalette && isUseTransparent == false) {//最初の色が背景なのに、背景色を使わないということは、color index==0は予約されている startColor = 1; } //ピクセルの変換 Rectangle destrect = new Rectangle(new Point(), DestBitmap.Size); BitmapData destbmpData = DestBitmap.LockBits(destrect, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed); IntPtr dest = destbmpData.Scan0; for (int i = 0; i < tileMapping.Count; i++) { int x = tileMapping[i].X; int y = tileMapping[i].Y; for (int yy = 0; yy < 8; yy++) { for (int xx = 0; xx < 8; xx++) { int index; try { Color c = src.GetPixel(x + xx, y + yy); if (c.A == 0 && isUseTransparent) { index = 0; } else { index = getPaletteIndex(c, paletteList, startColor); } } catch (System.AccessViolationException) {//なんで例外が飛んでくるんだ? break; } int pos = (x + xx) + ((y + yy) * destrect.Width); byte cc = (byte)(index); Marshal.WriteByte(dest, pos, cc); } } } DestBitmap.UnlockBits(destbmpData); return(DestBitmap); }
/// <summary> /// Generates a minimap texture and assigns it as an image. /// </summary> /// <param name="map">The map to to generate a minimap from.</param> /// <param name="missionVariant">The mission variant to generate a minimap from. (optional)</param> public void SetMap(Map map, MissionVariant missionVariant = null) { uint mapWidth = map.GetWidthInTiles(); uint mapHeight = map.GetHeightInTiles(); // Create minimap texture Texture2D minimapTexture = new Texture2D((int)mapWidth * TextureManager.minimapScale, (int)mapHeight * TextureManager.minimapScale, TextureFormat.ARGB32, false); CellTypeMap cellTypeMap = new CellTypeMap(map, missionVariant); for (uint x = 0; x < mapWidth; ++x) { for (uint y = 0; y < mapHeight; ++y) { ulong tileMappingIndex = GetTileMappingIndex(map, cellTypeMap, new Vector2Int((int)x, (int)y)); TileMapping mapping = map.GetTileMapping(tileMappingIndex); ulong tileSetIndex = mapping.tilesetIndex; int tileImageIndex = mapping.tileGraphicIndex; string tileSetPath = map.GetTilesetSourceFilename(tileSetIndex); int tileSetNumTiles = (int)map.GetTilesetSourceNumTiles(tileSetIndex); // Get image offset int inverseTileIndex = tileSetNumTiles - tileImageIndex - 1; Vector3Int cellPosition = new Vector3Int((int)x, (int)(mapHeight - y - 1), 0); ++cellPosition.y; // Set minimap pixel Texture2D mTexture = TextureManager.LoadMinimapTileset(tileSetPath, tileSetNumTiles); for (int my = 0; my < TextureManager.minimapScale; ++my) { for (int mx = 0; mx < TextureManager.minimapScale; ++mx) { Color color = mTexture.GetPixel(mx, inverseTileIndex * TextureManager.minimapScale + my); minimapTexture.SetPixel(cellPosition.x * TextureManager.minimapScale + mx, cellPosition.y * TextureManager.minimapScale + my - 1, color); } } } } // Apply mission units to minimap if (missionVariant != null) { foreach (GameData.Beacon beacon in missionVariant.tethysGame.beacons) { SetMinimapTile(minimapTexture, new Vector2Int(beacon.position.x, beacon.position.y) - Vector2Int.one, Color.white); } foreach (GameData.Marker marker in missionVariant.tethysGame.markers) { SetMinimapTile(minimapTexture, new Vector2Int(marker.position.x, marker.position.y) - Vector2Int.one, Color.white); } foreach (GameData.Wreckage wreckage in missionVariant.tethysGame.wreckage) { SetMinimapTile(minimapTexture, new Vector2Int(wreckage.position.x, wreckage.position.y) - Vector2Int.one, Color.white); } foreach (PlayerData player in missionVariant.players) { foreach (UnitData unit in player.resources.units) { RectInt unitArea = StructureData.GetStructureArea(new Vector2Int(unit.position.x, unit.position.y) - Vector2Int.one, unit.typeID); for (int x = unitArea.xMin; x < unitArea.xMax; ++x) { for (int y = unitArea.yMin; y < unitArea.yMax; ++y) { SetMinimapTile(minimapTexture, new Vector2Int(x, y), GetPlayerColor(player)); } } } } } // Apply minimap texture minimapTexture.Apply(); // Update image RefreshImage(map, minimapTexture); }
Color ProcessColor(Color startColor) { TileMapping reference = null; return(ProcessColor(startColor, ref reference)); }
public Bitmap Convert(Bitmap src, int maxPalette, int yohaku, bool isReserve1StPalette, bool ignoreTSA) { if (maxPalette == 1 || ignoreTSA) {//1パレット16色 または、 TSA無効の場合 return(ConvertIgnoreTSA(src, maxPalette * 16, yohaku, isReserve1StPalette, maxPalette < 16)); } int width = src.Width; int height = src.Height; width = U.Padding8(width); height = U.Padding8(height); Bitmap DestBitmap = ImageUtil.Blank(width + yohaku, height); List <ColorRanking> totalRank = new List <ColorRanking>(); List <TileMapping> tileMapping = new List <TileMapping>(); for (int y = 0; y < height; y += 8) { if (y + 8 > height) { continue; } for (int x = 0; x < width; x += 8) { if (x + 8 > width) { continue; } TileMapping tm = new TileMapping(); tm.Rank = new List <ColorRanking>(); tm.Palette = -1; tm.X = x; tm.Y = y; for (int yy = 0; yy < 8; yy++) { for (int xx = 0; xx < 8; xx++) { try { Color c = src.GetPixel(x + xx, y + yy); if (c.A == 0) { continue; } VoteColor(tm.Rank, c); } catch (System.AccessViolationException) {//なんで例外が飛んでくるんだ? break; } } } SortColor(tm.Rank); tileMapping.Add(tm); //複数パレットの場合、そのタイルの中で最も人気の色 if (tm.Rank.Count > 0) { VoteColor(totalRank, tm.Rank[0]); } } } SortColor(totalRank); //上位の色たちをパレットに割り当てていきます. List <List <ColorRanking> > countList = new List <List <ColorRanking> >(); for (int i = 0; i < maxPalette; i++) { List <ColorRanking> pal = AssingPalette(i, totalRank, tileMapping); countList.Add(pal); } //まだ割り当てていないタイルがあれば、一番近い色セットを持つどれかのパレットに割り当てます. AssingaPaletteByUnassignedTile(countList, tileMapping, totalRank); //パレットの色数を16色にします. List <ColorRanking[]> paletteList = new List <ColorRanking[]>(); for (int i = 0; i < maxPalette; i++) { paletteList.Add(Convert16Color(countList[i], isReserve1StPalette)); } //パレットの適応 ColorPalette cp = DestBitmap.Palette; for (int i = 0; i < maxPalette; i++) { for (int n = 0; n < 16; n++) { cp.Entries[i * 16 + n] = Color.FromArgb(paletteList[i][n].R , paletteList[i][n].G , paletteList[i][n].B ); } } //利用しないところはゼロクリア for (int i = maxPalette; i < 16; i++) { for (int n = 0; n < 16; n++) { cp.Entries[i * 16 + n] = Color.FromArgb(0, 0, 0); } } DestBitmap.Palette = cp; //ピクセルの変換 Rectangle destrect = new Rectangle(new Point(), DestBitmap.Size); BitmapData destbmpData = DestBitmap.LockBits(destrect, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed); IntPtr dest = destbmpData.Scan0; for (int i = 0; i < tileMapping.Count; i++) { int paletteno = tileMapping[i].Palette; if (paletteno < 0) { Debug.Assert(false); continue; } int x = tileMapping[i].X; int y = tileMapping[i].Y; for (int yy = 0; yy < 8; yy++) { for (int xx = 0; xx < 8; xx++) { int index; try { Color c = src.GetPixel(x + xx, y + yy); if (c.A == 0) { index = 0; } else { index = getPaletteIndex(c, countList[paletteno]); } } catch (System.AccessViolationException) {//なんで例外が飛んでくるんだ? break; } int pos = (x + xx) + ((y + yy) * destrect.Width); byte cc = (byte)(paletteno * 16 + index); Marshal.WriteByte(dest, pos, cc); } } } DestBitmap.UnlockBits(destbmpData); return(DestBitmap); }