コード例 #1
0
ファイル: BlockPool.cs プロジェクト: bluecri/uniProj
    private Dictionary <int, Queue <GameObject> > blockPoolDictionary = null;  //pool


    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(instance);
        }
        else if (instance != this)
        {
            Destroy(this.gameObject);
        }

        //make block info dictionary from editor
        MakeBlockInfoDictionary();


        GameObject instantGameObj = null;

        geoPrefabCount      = blockPrefabInfo_dictionary.Count; //set block total count
        blockPoolDictionary = new Dictionary <int, Queue <GameObject> >();

        foreach (KeyValuePair <int, GameObject> entry in blockPrefabInfo_dictionary)
        {
            blockPoolDictionary.Add(entry.Key, new Queue <GameObject>());

            for (int loop = 0; loop < defaultPoolCount; loop++)
            {
                instantGameObj = Instantiate(entry.Value);
                instantGameObj.SetActive(false);
                blockPoolDictionary[entry.Key].Enqueue(instantGameObj);
            }
        }
    }
コード例 #2
0
    public static void RemoveBlock(int x, int y, int z)
    {
        if (x < 0 || y < 0 || z < 0 || x > width * chunkSize - 1 || y > height * chunkSize - 1 || z > depth * chunkSize - 1)
        {
            return;
        }
        if ((blocks [x, y, z] >> 8) == 0)
        {
            return;
        }

        Chunk chunk = GetChunk(x, y, z);

        if (chunk != null)
        {
            if (!chunk.dirty)
            {
                chunk.dirty = true;
                rebuildList.Add(chunk);
            }
        }
        if (Random.value > 0.75)
        {
            BlockPool.AddBlock(x, y, z, blocks [x, y, z], 1);
        }
        blocks[x, y, z] = 0;
    }
コード例 #3
0
        private void GenerateShape(bool[,] shape, ShapeView shapeView, Color shapeColor)
        {
            var height = shape.GetLength(0);
            var width  = shape.GetLength(1);

            var blockViews = new IBlockView[height, width];

            shapeView.Shape = shape;

            for (var i = 0; i < height; i++)
            {
                for (var j = 0; j < width; j++)
                {
                    if (shape[i, j])
                    {
                        var blockView = BlockPool.Pop();
                        blockView.SetParent(shapeView.BlockContainer);
                        blockView.SetLocalPosition(new Vector3(j - width / 2f + 0.5f, height / 2f - i - 0.5f));
                        blockViews[i, j] = blockView;
                        blockView.SetColor(shapeColor);
                    }
                }
            }
            shapeView.BlockViews = blockViews;
            shapeView.MininimazeScale();
        }
コード例 #4
0
ファイル: Tetrino.cs プロジェクト: Negawisp/action_words
    protected virtual void TakeBlocks(int nLetters, char[] letters, Thaum.Type[] types)
    {
        if (letters.Length < nLetters)
        {
            Debug.LogError("Not enough letters!");
        }

        if (types.Length < nLetters)
        {
            Debug.LogError("Not enough thaums!!");
        }

        _blockPool = FindObjectOfType <BlockPool>();
        if (_blockPool == null)
        {
            Debug.LogError("Scene didn't have a BlockPool object.");
        }

        _blocks = new LetterBlock[nLetters];

        for (int i = 0; i < nLetters; i++)
        {
            _blocks[i] = _blockPool.Get();
            _blocks[i].transform.SetParent(_transform);
            _blocks[i].Construct(letters[i], types[i]);
        }
    }
コード例 #5
0
ファイル: ObstacleTree.cs プロジェクト: studentutu/dotsnav
 public Control(Allocator allocator)
 {
     Allocator    = allocator;
     Tree         = new Tree <IntPtr>(allocator);
     ObstaclePool = new BlockPool <Obstacle>(128, 1, allocator);
     Map          = new UnsafeHashMap <Entity, IntPtr>(128, allocator);
 }
コード例 #6
0
ファイル: BoardMatch3.cs プロジェクト: Kozhevka/Match3-Core
    private void Start()
    {
        movePhaseEnum      = MoveStageEnum.PlayerMakeMove;
        scoreCounterScript = ScoreCounter.instance;

        blockPoolScript = BlockPool.instance;
        blockTypes      = BlockPool.instance.blockWhatNeedToPool.Count;
    }
コード例 #7
0
ファイル: LetterBlock.cs プロジェクト: AleKuv55/ActionWords
    // Called by Animator!
    public void StoreToPool()
    {
        BlockPool pool = FindObjectOfType <BlockPool>();

        pool.Store(this);

        this.transform.SetParent(pool.transform);
        this.transform.localPosition = Vector3.zero;
    }
コード例 #8
0
        public void Initialize(IBlockMaterialProvider blockMaterialProvider, BlockPool pool, ITetrisGame game)
        {
            _blockMaterialProvider = blockMaterialProvider;
            _pool     = pool;
            _game     = game;
            _renderer = GetComponent <Renderer>();

            _game.LineClear += OnLineClear;
        }
コード例 #9
0
ファイル: PreviewController.cs プロジェクト: atesbalci/Tetris
        public PreviewController(BlockPool pool, Transform parent, ITetrisGame game)
        {
            _pool          = pool;
            _parent        = parent;
            _game          = game;
            _spawnedBlocks = new LinkedList <BlockView>();

            _game.RoundStart += OnRoundStart;
            _game.GameStart  += OnGameStart;
        }
コード例 #10
0
        public BlockViewsController(BlockPool pool, ITetrisGame game, Transform blocksParent)
        {
            _pool         = pool;
            _game         = game;
            _blocksParent = blocksParent;
            _blockViews   = new LinkedList <BlockView>();

            _game.RoundStart += OnRoundStart;
            _game.GameStart  += OnGameStart;
        }
コード例 #11
0
    public void InitializeGame()
    {
        if (!gameInitialized)
        {
            BlockPool.Initialize(this);

            players[0].NewBlock();
            players[1].NewBlock();

            UI = GameObject.FindObjectOfType <UI>();//TODO: improve
            gameInitialized = true;
        }
    }
コード例 #12
0
 public static Block GetBlockFromPool(BlockPool pool, Block sample)
 {
     if (pool != null)
     {
         Block newBlock = pool.GetDebrisBlock(sample);
         newBlock.OnGroundListener.AddListener(pool.ReturnBlock);
         return(newBlock);
     }
     else
     {
         Block newBlock = GameObject.Instantiate(sample);
         newBlock.OnGroundListener.AddListener(DestroyBlock);
         return(newBlock);
     }
 }
コード例 #13
0
    public void Init()
    {
        this.config    = GameConfig.CreateDefaultGameConfig();
        this.blockPool = new BlockPool(this.sampleBlock, 100);

        this.gameState     = GameState.Play;
        this.playState     = GamePlayState.Prepare;
        this.blockStack    = new List <Block>();
        this.blockStopped  = new List <Block>();
        this.currentHeight = 0;
        this.topBlock      = null;


        StartPlayGame();
    }
コード例 #14
0
ファイル: Block.cs プロジェクト: StijnOnline/Tetris-Shooter
    //TODO: Check and Fix multiple collisions
    private void OnTriggerStay2D(Collider2D _other)
    {
        if (_other.tag == "Wall")
        {
            return;
        }

        if (Time.time < _firstTouch)
        {
            //TODO: sometimes called when block spawns and then no new blocks spawn
            owner.NewBlock();
            _firstTouch          = Time.time;
            gameManager.Attract += Attract;
        }
        Block _otherBlock = _other.transform.parent?.parent?.GetComponent <Block>();

        if (_otherBlock != null)
        {
            //Adding connected blocks of same type to hashset
            //DISCUSS: Does this leave gaps? is this efficient?
            if (_otherBlock.type == type)
            {
                connected.UnionWith(_otherBlock.connected);
                connected.Add(_otherBlock);
                _otherBlock.connected.UnionWith(connected);
            }

            //If 3 blocks are connected remove them and award points
            if (connected.Contains(_otherBlock) && connected.Count >= 3)
            {
                Debug.Log("Instance " + gameObject.GetInstanceID() + " hit " + _other.GetInstanceID() + " - Time: " + Time.time);
                if (gameObject.GetInstanceID() > _other.GetInstanceID())//only 1 object will execute, hopefully
                {
                    gameManager.AddScore(transform.position.x, connected.Count);

                    connected.Remove(this);
                    foreach (Block b in new HashSet <Block>(connected))
                    {
                        BlockPool.Return(b.gameObject);
                    }
                    BlockPool.Return(this.gameObject);
                    AudioPlayer.Instance.PlaySound("ConnectedBlock", 1);
                }
            }
        }
    }
コード例 #15
0
    private void Awake()
    {
        if (BlockPool.instance == null)
        {
            instance = this;
        }
        else
        {
            Debug.LogError("BlockPool.instance already exist");
            Destroy(this.gameObject);
        }

        blockWhatNeedToPool = new List <GameObject>();
        blockWhatNeedToPool.Add(blockZero);
        blockWhatNeedToPool.Add(blockOne);
        blockWhatNeedToPool.Add(blockTwo);
        blockWhatNeedToPool.Add(blockThree);
    }
コード例 #16
0
ファイル: QuadTree.cs プロジェクト: studentutu/dotsnav
        public QuadTree(float size, int initialCapacity, int bucketSize, Allocator allocator) : this()
        {
            _bucketSize = bucketSize;
            _allocator  = allocator;
            var buckets = (int)math.ceil((float)initialCapacity / bucketSize);

            _chunks = new Stack <IntPtr>(buckets, allocator);
            for (int i = 0; i < buckets; i++)
            {
                _chunks.Push((IntPtr)Malloc());
            }

            const int blockSize     = 128;
            var       capacity      = 1.3334f * buckets;
            var       initialBlocks = (int)math.ceil(capacity / blockSize);

            _nodes = new BlockPool <QuadTreeNode>(blockSize, initialBlocks, allocator);
            _root  = _nodes.GetElementPointer(new QuadTreeNode(0, size / 2, GetChunk(), null));
        }
コード例 #17
0
    public void CollisionExplode()
    {
        this.noOfCollisions++;
        Vector3 pos = this.obj.GetComponent <MeshCollider> ().transform.position;

        //if (this.noOfCollisions > 10 && this.blocks.Length < 300) {
        // TBD:  foreach block in chunk
        for (int x = 0; x < this.toX; x++)
        {
            for (int y = 0; y < this.toY; y++)
            {
                for (int z = 0; z < this.toZ; z++)
                {
                    if (this.blocks [x, y, z] != 0)
                    {
                        if (Random.value > 0.5)
                        {
                            // TBD: Apply rotation.
                            BlockPool.AddBlock((int)pos.x + x, (int)pos.y + y, (int)pos.z + z, this.blocks[x, y, z], 1, 0.001f);
                        }
                    }
                }
            }
        }
        GameObject.Destroy(this.obj);
        //} else if(this.noOfCollisions > 10 ){
        //			// Remove random blocks
        //			int noOfBlocks = (int)Random.Range(1,this.blocks.Length/2);
        //			for(int i = 0; i < noOfBlocks; i++) {
        //				int x = (int)Random.Range (0, toX);
        //				int y = (int)Random.Range (0, toY);
        //				int z = (int)Random.Range (0, toZ);
        //				if (this.blocks [x, y, z] != 0) {
        //					this.blocks [x, y, z] = 0;
        //					BlockPool.AddBlock ((int)pos.x + x, (int)pos.y + y, (int)pos.z + z, this.blocks[x,y,z], 1, 0.001f);
        //				}
        //			}
        //			position = pos;
        //			World.RebuildChunks (this);
        //		}
        //}
    }
コード例 #18
0
ファイル: TxPool.cs プロジェクト: mx2s/csharp-blockchain
        public void ProcessNewBlock()
        {
            var TxsSize = 0;
            var block   = new Block();

            block.Index = BlockPool.Get().GetBlocks().Keys.Max() + 1;

            while (pool.Count > 0 && TxsSize < BlockTxLimit)
            {
                var next = GetNext();
                block.AddTx(next);
            }

            if (!BlockValidator.IsValid(block))
            {
                Console.WriteLine("Block is not valid");
                return;
            }

            BlockPool.Get().AddBlock(block);
        }
コード例 #19
0
    public static void TrimMinX(Block target, float minX, BlockPool blockPool = null)
    {
        if (NeedTrimMinX(target, minX))
        {
            MeshFilter meshFilterTarget = target.gameObject.GetComponent <MeshFilter>();
            Vector3[]  targetVertices   = meshFilterTarget.mesh.vertices;
            Block      cutOff           = GetBlockFromPool(blockPool, target);
            //cutOff.transform.position = target.transform.position;
            //Vector3[] cutOffVertices = targetVertices;
            ///GameObject cutOff = GameObject.CreatePrimitive(PrimitiveType.Cube);
            Vector3 pos = target.transform.position;
            cutOff.transform.position   = pos;
            cutOff.transform.localScale = target.transform.localScale;

            ///Create vertices for cutoff block
            Vector3[] cutOffVertices = meshFilterTarget.mesh.vertices;
            for (int i = 0; i < targetVertices.Length; i++)
            {
                Vector3 worldPos = target.transform.TransformPoint(targetVertices[i]);
                if (worldPos.x < minX)
                {
                    cutOffVertices[i] = cutOff.transform.InverseTransformPoint(worldPos);
                    targetVertices[i] = target.transform.InverseTransformPoint(new Vector3(minX, worldPos.y, worldPos.z));
                    Debug.Log("- Trim vertex by maxX: " + i);
                }
                else
                {
                    cutOffVertices[i] = cutOff.transform.InverseTransformPoint(new Vector3(minX, worldPos.y, worldPos.z));
                }
            }

            ///Recalculate target block
            ApplyNewVerticesToMesh(meshFilterTarget, targetVertices);

            ///Recalculate cutoff
            ApplyNewVerticesToMesh(cutOff.GetComponent <MeshFilter>(), cutOffVertices);

            MakeBlockFallStatic(cutOff);
        }
    }
コード例 #20
0
ファイル: Navmesh.cs プロジェクト: studentutu/dotsnav
        internal Navmesh(NavmeshComponent component)
        {
            Assert.IsTrue(math.all(component.Size > 0));
            Assert.IsTrue(component.ExpectedVerts > 0);

            Extent           = component.Size / 2;
            _e               = component.MergePointsDistance;
            _collinearMargin = component.CollinearMargin;

            const int blockSize     = 128;
            var       initialBlocks = (int)math.ceil((float)component.ExpectedVerts / blockSize);

            _vertices       = new BlockPool <Vertex>(blockSize, initialBlocks, Allocator.Persistent);
            _verticesSeq    = new UnsafeList <IntPtr>(component.ExpectedVerts, Allocator.Persistent);
            _quadEdges      = new BlockPool <QuadEdge>(3 * blockSize, initialBlocks, Allocator.Persistent);
            _constraints    = new UnsafeHashMap <Entity, IntPtr>(component.ExpectedVerts, Allocator.Persistent);
            V               = new HashSet <IntPtr>(16, Allocator.Persistent);
            C               = new HashSet <IntPtr>(16, Allocator.Persistent);
            _edgeSearch     = new EdgeSearch(100, 100, Allocator.Persistent);
            _qt             = new QuadTree(math.max(component.Size.x, component.Size.y), 100, 10, Allocator.Persistent);
            _flipStack      = new PtrStack <Edge>(32, Allocator.Persistent);
            _insertedPoints = new UnsafeList <Point>(64, Allocator.Persistent);
            _open           = new PtrStack <Vertex>(64, Allocator.Persistent);
            _vlist          = new UnsafeList <IntPtr>(64, Allocator.Persistent);
            _elist          = new UnsafeList <IntPtr>(64, Allocator.Persistent);
            _creps          = new Stack <UnsafeList <Entity> >(2 * component.ExpectedVerts, Allocator.Persistent);
            for (int i = 0; i < 2 * component.ExpectedVerts; i++)
            {
                _creps.Push(new UnsafeList <Entity>(CrepMinCapacity, Allocator.Persistent));
            }
            DestroyedTriangles = new HashSet <int>(64, Allocator.Persistent);
            _refinementQueue   = new Deque <IntPtr>(24, Allocator.Persistent);

            _mark       = default;
            _edgeId     = default;
            _triangleId = default;

            BuildBoundingBoxes();
        }
コード例 #21
0
    private void Start()
    {
        pool         = BlockPool.Instance;
        chunkManager = ChunkManager.Instance;

        List <Vector3Int> surfacePositions = GenerateHeightMap(size, (x, z) =>
        {
            float height = (Mathf.PerlinNoise(x * smoothness, z * smoothness * 2) * heightMult +
                            Mathf.PerlinNoise(x * smoothness, z * smoothness * 2) * heightMult) / 2f;

            return(Mathf.CeilToInt(height));
        });

        System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
        watch.Start();

        foreach (Vector3Int surfacePosition in surfacePositions)
        {
            Block block = new Block(surfacePosition);
            block.UVSetter.SetBlockUV(surface);
            chunkManager.AddBlock(block);
        }

        // Optimierungsbedarf
        // Entweder erst Blöcke alle in den Chunk einfügen, dann einmal, aber viel combinen
        // und / oder Multithreading!!!! MÖGLICH DURCH BLOCK

        List <Vector3Int> rofl  = GenerateBottomMap(surfacePositions);
        List <Block>      temp2 = new List <Block>();

        foreach (Vector3Int bottomPosition in rofl)
        {
            Block block = new Block(bottomPosition);
            block.UVSetter.SetBlockUV(bottom);
            chunkManager.AddBlock(block);
        }
        watch.Stop();
        Debug.Log(watch.ElapsedMilliseconds);
    }
コード例 #22
0
ファイル: UserUtil.cs プロジェクト: mx2s/csharp-blockchain
        public static double GetBalance(string wallet)
        {
            var    pool          = BlockPool.Get();
            double senderBalance = 0;

            foreach (var block in pool.GetBlocks())
            {
                foreach (var curTx in block.Value.Txs)
                {
                    if (curTx.To == wallet)
                    {
                        senderBalance += curTx.Amount;
                    }

                    if (curTx.From == wallet)
                    {
                        senderBalance -= curTx.Amount;
                    }
                }
            }

            return(senderBalance);
        }
コード例 #23
0
    public void NewBlock()
    {
        if (nextBlock != null)
        {
            currentBlock = nextBlock;
        }
        else
        {
            GameObject _newblock = BlockPool.GetNext();
            currentBlock = _newblock.GetComponent <Block>();
        }
        currentBlock.transform.position = spawnPos;
        currentBlock = currentBlock.GetComponent <Block>();
        currentBlock.SetFreeze(false);
        currentBlock.owner = this;

        GameObject _newblock2 = BlockPool.GetNext();

        nextBlock = _newblock2.GetComponent <Block>();
        nextBlock.transform.position = spawnPos * 1.5f + new Vector3(0, -5, 0);//Position part of UI
        nextBlock.SetFreeze(true);

        AudioPlayer.Instance.PlaySound("SpawnBlock", 0.5f);
    }
コード例 #24
0
    private void GenerateBlock(BlockData blockData, Vector3 position)
    {
        BlockPool blockPool;

        if (!isInitMap)  // 초기 맵 생성 시
        {
            string    path     = PhotonPrefabPathContainer.GetPrefabPath(blockData.block.name);
            Transform newBlock = PhotonNetwork.InstantiateSceneObject(path, position, Quaternion.identity, 0, null).transform;

            blockData.block     = newBlock;
            blockData.endHeight = newBlock.GetComponent <Block>().endHeight;

            if (blockData.type != -2) // startBlock이 아니면
            {
                // 블럭을 현재 파트 블럭리스트에 추가
                blockInEachPart[(int)curPart].Add(newBlock);

                // 블록 텍스쳐 변경을 위해 블록에 파트값 부여
                blockData.block.GetComponent <Block>().part = curPart;
                blockData.block.GetComponent <ChangeBlockTexture>().SetBlockTexture((int)curPart);

                // input into pool
                blockPool           = new BlockPool();
                blockPool.blockData = blockData;
                blockPool.part      = curPart;
                blockPool.isUse     = true;
                mapPool.blockPool.Add(blockPool);
            }
        }
        else
        {
            // 풀에서 있는 지 검사하고 있다면 꺼내고, 없다면 생성
            blockPool = mapPool.blockPool.Find(x => x.blockData.num == blockData.num && x.blockData.type == blockData.type && x.isUse == false);

            if (blockPool != null)
            {
                blockPool.part = curPart;
                blockPool.blockData.block.GetComponent <Block>().part = curPart;
                blockPool.blockData.block.GetComponent <ChangeBlockTexture>().SetBlockTexture((int)curPart);
                blockPool.Pull(createdBlockCount);
            }
            else
            {
                // Block 및 BlockPool 생성, 현재 blockData를 Add
                string    path     = PhotonPrefabPathContainer.GetPrefabPath(blockData.block.name);
                Transform newBlock = PhotonNetwork.InstantiateSceneObject(path, position, Quaternion.identity, 0, null).transform;
                blockData.block     = newBlock;
                blockData.endHeight = newBlock.GetComponent <Block>().endHeight;

                blockPool           = new BlockPool();
                blockPool.part      = curPart;
                blockPool.blockData = blockData;
                blockPool.blockData.block.GetComponent <Block>().part = curPart;
                blockPool.blockData.block.GetComponent <ChangeBlockTexture>().SetBlockTexture((int)curPart);
                mapPool.blockPool.Add(blockPool);

                blockPool.Pull(createdBlockCount);
            }
        }

        // listBlockData가 계속 쌓이는 것을 방지
        listBlockData.Add(blockData);
        if (listBlockData.Count > 5)
        {
            listBlockData.RemoveAt(0);
        }

        // subPartData에 추가. SubPartData의 blocks list 개수가 6개가 아니면 추가
        if (blockData.type != -2) // startBlock이 아니면
        {
            SubPartData spData = partData[(int)curPart].subPartData.Find(x => x.part == curPart && x.blocks.Count != 6);
            spData.blocks.Add(blockData);
            spData.blocksPos.Add(createdBlockCount);
        }
    }
コード例 #25
0
 private void Start()
 {
     _table     = FindObjectOfType <Table>();
     _blockPool = FindObjectOfType <BlockPool>();
 }
コード例 #26
0
        public static void Main(string[] args)
        {
            {
                #region Snippet_1
                IFileSystem filesystem = new MemoryFileSystem();
                #endregion Snippet_1
            }
            {
                #region Snippet_1b
                IFileSystem filesystem = new MemoryFileSystem(blockSize: 4096);
                #endregion Snippet_1b
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                #region Snippet_2
                foreach (var entry in filesystem.Browse(""))
                {
                    Console.WriteLine(entry.Path);
                }
                #endregion Snippet_2
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                filesystem.CreateFile("file.txt");
                #region Snippet_3a
                using (Stream s = filesystem.Open("file.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    Console.WriteLine(s.Length);
                }
                #endregion Snippet_3a
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                filesystem.CreateFile("file.txt");
                #region Snippet_3b
                using (Stream s = filesystem.Open("file.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    s.WriteByte(32);
                }
                #endregion Snippet_3b
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                #region Snippet_4
                IObserver <IEvent> observer = new Observer();
                using (IDisposable handle = filesystem.Observe("**", observer))
                {
                }
                #endregion Snippet_4
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                #region Snippet_5
                filesystem.CreateDirectory("dir/");
                #endregion Snippet_5
            }

            {
                IFileSystem filesystem = new MemoryFileSystem();
                #region Snippet_5a
                filesystem.CreateDirectory("dir1/dir2/dir3/");
                filesystem.PrintTo(Console.Out);
                #endregion Snippet_5a
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                #region Snippet_5b
                filesystem.CreateDirectory("/tmp/dir/");
                #endregion Snippet_5b
                filesystem.PrintTo(Console.Out);
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                #region Snippet_5c
                filesystem.CreateDirectory("/tmp/dir/");
                #endregion Snippet_5c
                filesystem.PrintTo(Console.Out);
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                #region Snippet_5d
                filesystem.CreateDirectory("file://");
                #endregion Snippet_5d
                filesystem.PrintTo(Console.Out);
            }

            {
                IFileSystem filesystem = new MemoryFileSystem();
                filesystem.CreateDirectory("dir/");
                #region Snippet_6
                filesystem.Delete("dir/", recurse: true);
                #endregion Snippet_6
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                filesystem.CreateDirectory("dir/");
                #region Snippet_7
                filesystem.CreateDirectory("dir/");
                filesystem.Move("dir/", "new-name/");
                #endregion Snippet_7
                filesystem.Delete("new-name/");
            }

            {
                #region Snippet_8a
                IFileSystem filesystem = new MemoryFileSystem();
                #endregion Snippet_8a
                foreach (var entry in filesystem.Browse(""))
                {
                    Console.WriteLine(entry.Path);
                }
            }
            {
                #region Snippet_8b
                #endregion Snippet_8b
            }
            {
                #region Snippet_10a
                // Init
                object obj = new ReaderWriterLockSlim();
                IFileSystemDisposable filesystem = new FileSystem("").AddDisposable(obj);

                // ... do work ...

                // Dispose both
                filesystem.Dispose();
                #endregion Snippet_10a
            }
            {
                #region Snippet_10b
                IFileSystemDisposable filesystem = new FileSystem("")
                                                   .AddDisposeAction(f => Console.WriteLine("Disposed"));
                #endregion Snippet_10b
            }
            {
                #region Snippet_10c
                MemoryFileSystem filesystem = new MemoryFileSystem();
                filesystem.CreateDirectory("/tmp/dir/");

                // Postpone dispose
                IDisposable belateDisposeHandle = filesystem.BelateDispose();
                // Start concurrent work
                Task.Run(() =>
                {
                    // Do work
                    Thread.Sleep(1000);
                    filesystem.GetEntry("");
                    // Release belate handle. Disposes here or below, depending which thread runs last.
                    belateDisposeHandle.Dispose();
                });

                // Start dispose, but postpone it until belatehandle is disposed in another thread.
                filesystem.Dispose();
                #endregion Snippet_10c
            }

            {
                // <Snippet_20a>
                IFileSystem ms = new MemoryFileSystem(blockSize: 1024, maxSpace: 1L << 34);
                // </Snippet_20a>
            }
            {
                // <Snippet_20b>
                IFileSystem ms = new MemoryFileSystem(blockSize: 1024, maxSpace: 1L << 34);
                ms.CreateFile("file", new byte[1 << 30]);
                ms.PrintTo(Console.Out, format: PrintTree.Format.AllWithName);
                // </Snippet_20b>
            }
            {
                try
                {
                    // <Snippet_20c>
                    IFileSystem ms = new MemoryFileSystem(blockSize: 1024, maxSpace: 2048);
                    ms.CreateFile("file1", new byte[1024]);
                    ms.CreateFile("file2", new byte[1024]);

                    // throws FileSystemExceptionOutOfDiskSpace
                    ms.CreateFile("file3", new byte[1024]);
                    // </Snippet_20c>
                }
                catch (FileSystemExceptionOutOfDiskSpace) { }
            }
            {
                try
                {
                    // <Snippet_20d>
                    IBlockPool  pool = new BlockPool(blockSize: 1024, maxBlockCount: 3, maxRecycleQueue: 3);
                    IFileSystem ms1  = new MemoryFileSystem(pool);
                    IFileSystem ms2  = new MemoryFileSystem(pool);

                    // Reserve 2048 from shared pool
                    ms1.CreateFile("file1", new byte[2048]);

                    // Not enough for another 3072, throws FileSystemExceptionOutOfDiskSpace
                    ms2.CreateFile("file2", new byte[2048]);
                    // </Snippet_20d>
                }
                catch (FileSystemExceptionOutOfDiskSpace) { }
            }
            {
                try
                {
                    // <Snippet_20e>
                    IBlockPool  pool = new BlockPool(blockSize: 1024, maxBlockCount: 3, maxRecycleQueue: 3);
                    IFileSystem ms   = new MemoryFileSystem(pool);
                    Stream      s    = ms.Open("file", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                    s.Write(new byte[3072], 0, 3072);
                    ms.Delete("file");

                    Console.WriteLine(pool.BytesAvailable); // Prints 0
                    s.Dispose();
                    Console.WriteLine(pool.BytesAvailable); // Prints 3072
                    // </Snippet_20e>
                }
                catch (FileSystemExceptionOutOfDiskSpace) { }
            }
        }
コード例 #27
0
        public void Quota()
        {
            BlockPool  pool = new BlockPool(1024, 3, 3, true);
            MemoryFile file = new MemoryFile(pool);

            using (var s = file.Open(FileAccess.ReadWrite, FileShare.None))
            {
                Assert.AreEqual(0L, pool.BytesAllocated);

                s.Write(new byte[1024]);
                Assert.AreEqual(1024L, pool.BytesAllocated);
                Assert.AreEqual(2048L, pool.BytesAvailable);
                Assert.AreEqual(1024L, s.Length);

                s.Write(new byte[1024]);
                Assert.AreEqual(2048L, pool.BytesAllocated);
                Assert.AreEqual(1024L, pool.BytesAvailable);
                Assert.AreEqual(2048L, s.Length);

                s.Write(new byte[1024]);
                Assert.AreEqual(3072L, s.Length);
                Assert.AreEqual(3072L, pool.BytesAllocated);
                Assert.AreEqual(0L, pool.BytesAvailable);

                try
                {
                    s.Write(new byte[1024]);
                    Assert.Fail();
                } catch (FileSystemExceptionOutOfDiskSpace)
                {
                }
                Assert.AreEqual(3072, s.Length);

                try
                {
                    s.WriteByte(3);
                    Assert.Fail();
                }
                catch (FileSystemExceptionOutOfDiskSpace)
                {
                }
                Assert.AreEqual(3072, s.Length);

                s.SetLength(3071);
                Assert.AreEqual(3071, s.Length);

                s.WriteByte(3);
                Assert.AreEqual(3072, s.Length);

                s.SetLength(0L);
                Assert.AreEqual(0, s.Length);
                Assert.AreEqual(0L, pool.BytesAllocated);
                Assert.AreEqual(3072L, pool.BytesAvailable);

                s.Write(new byte[1024]);
                s.Write(new byte[1024]);
                s.Write(new byte[1024]);
                Assert.AreEqual(3072L, s.Length);
                Assert.AreEqual(3072L, pool.BytesAllocated);
                Assert.AreEqual(0L, pool.BytesAvailable);
            }

            Assert.AreEqual(3072L, pool.BytesAllocated);
            Assert.AreEqual(0L, pool.BytesAvailable);
            Stream ss = file.Open(FileAccess.ReadWrite, FileShare.ReadWrite);

            file.Dispose();
            Assert.AreEqual(3072L, pool.BytesAllocated);
            Assert.AreEqual(0L, pool.BytesAvailable);
            ss.Dispose();
            Assert.AreEqual(0L, pool.BytesAllocated);
            Assert.AreEqual(3072L, pool.BytesAvailable);
        }
コード例 #28
0
    public static void TrimBlockToCollision(Block target, Block pattern, Collision collision, BlockPool blockPool = null)
    {
        Debug.Log(string.Format("TrimBlockToCollision: {0}, {1}, contact={2}", target.name, pattern.name, collision.contacts.Length));
        for (int i = 0; i < collision.contacts.Length; i++)
        {
            Debug.Log(string.Format("\t- CollisionContact: {0}", collision.contacts[i].point));
        }

        float maxX = GetMaxWorldX(pattern);
        float minX = GetMinWorldX(pattern);

        float maxZ = GetMaxWorldZ(pattern);
        float minZ = GetMinWorldZ(pattern);

        Debug.Log(string.Format("Pattern limitation: maxX={0}, maxZ={1}", maxX, maxZ));

        TrimMaxX(target, maxX, blockPool);
        TrimMinX(target, minX, blockPool);

        TrimMaxZ(target, maxZ, blockPool);
        TrimMinZ(target, minZ, blockPool);
    }
コード例 #29
0
 public void TrimBlockToCollision(Block target, Block pattern, Collision collision, BlockPool blockPool)
 {
     Debug.Log(string.Format("TrimBlockToCollision: {0}, {1}", target.name, pattern.name));
     UtilCube.TrimBlockToCollision(target, pattern, collision, blockPool);
 }