public string CreateJSON(GameObject target)
    {
        Transform[] blocks = target.GetComponentsInChildren<Transform>();
        Debug.Log(blocks.Length);
        List<BlockData> datas = new List<BlockData>();

        for (int i = 0; i < blocks.Length; i++)
        {
            if (blocks[i].transform.parent == target.transform)
            {
                BlockData data = new BlockData();

                data.iPos = Mathf.RoundToInt(blocks[i].transform.localPosition.x / Chunck.TILESIZE);
                data.jPos = Mathf.RoundToInt(blocks[i].transform.localPosition.z / Chunck.TILESIZE);
                data.kPos = Mathf.RoundToInt(blocks[i].transform.localPosition.y / Chunck.TILEHEIGHT);
                data.dir = Mathf.RoundToInt(blocks[i].transform.localRotation.eulerAngles.y / 90f);
                data.reference = blocks[i].GetComponent<MeshFilter>().sharedMesh.name.Split(' ')[0];
                data.texture = blocks[i].GetComponent<MeshRenderer>().sharedMaterial.name.Split(' ')[0];

                datas.Add(data);
            }
        }

        string jsonString = "{\"reference\" : \"" + reference + "\", \"blocks\" : [";
        foreach (BlockData data in datas)
        {
            jsonString += JsonUtility.ToJson(data);
            jsonString += ", ";
        }
        jsonString = jsonString.Remove(jsonString.Length - 2, 2);
        jsonString += "]}";

        return jsonString;
    }
Beispiel #2
0
        public Object getValue( BlockData blockdata, String varName )
        {
            Object dicValue;
            blockdata.getDic().TryGetValue( varName, out dicValue );

            if (dicValue != null) {
                return dicValue;
            }

            if (this.isObject()) {

                Dictionary<String, Object> dicValues = blockdata.getDic();
                Object obj;
                dicValues.TryGetValue( this.getObjName(), out obj );

                if (obj != null) {

                    Object pval = getPropertyValue( obj, _objAccessor, this.getObjName() );
                    return pval;
                }

            }

            return this.getRawLabelAndVar();
        }
		public void Generate (Chunk chunk)
        {
            int index = 0;
			for (int y = 0; y < EngineSettings.ChunkConfig.SizeYTotal; y++)
			{
	            for (int z = 0; z < EngineSettings.ChunkConfig.SizeZ; z++)
	            {
					int wz = z + (chunk.Pos.Z << EngineSettings.ChunkConfig.LogSizeZ);

	                for (int x = 0; x < EngineSettings.ChunkConfig.SizeX; x++, index++)
	                {
						int wx = x + (chunk.Pos.X << EngineSettings.ChunkConfig.LogSizeX);

	                    if (m_noise.GetValue(new Vector3(wx, y, wz) * 0.1f) > 0f)
	                    {
							chunk[index] = new BlockData (BlockType.Dirt);
                        }
						else
						{
							chunk[index] = BlockData.Air;
	                    }
                    }
                }
            }
        }
Beispiel #4
0
 public GameServer(int port)
 {
     ServerNetworkManager = new ServerNetworkManager();
     if (ServerNetworkManager.Host(port))
     {
         for (int x = 0; x < WorldSizeX; x++)
         {
             for (int y = 0; y < WorldSizeY; y++)
                 WorldBlocks[x, y] = new BlockData();
         }
         GenerateWorld();
         ServerGameMode.GenerateGameModes();
         GameMode = (ServerGameMode)ReflectionManager.CallConstructor(ServerGameMode.GetGameMode("Control Points"));
         GameMode.OnGameModeChosen();
         ServerItem.MakeItems();
         Block.GenerateBlocks();
         ServerCommands.Initialize();
         ServerConsole.Log("Hosted successfully on port " + port);
     }
     else
     {
         ServerNetworkManager = null;
         throw new Exception("Could not host on port " + port);
     }
 }
Beispiel #5
0
 public void fillValues() {
     float[,] valueArray;
     if (dimensions % 2 == 0) {
         valueArray = new float[dimensions + 1, dimensions + 1];
         fillArray(valueArray);
         //Now we need to actually calculate the block heights
         for (int j = 0; j < valueArray.GetLength(0) - 1; j++) {
             for (int k = 0; k < valueArray.GetLength(1) - 1; k++) {
                 BlockData bd = new BlockData((valueArray[j, k] + valueArray[j + 1, k] + valueArray[j, k + 1] + valueArray[j + 1, k + 1]) / 4f);
                 blockData[j, k] = bd;
             }
         }
     } else {
         valueArray = new float[dimensions, dimensions];
         fillArray(valueArray);
         //Now we have the block heights, and can simply transfer them
         for (int j = 0; j < valueArray.GetLength(0); j++) {
             for (int k = 0; k < valueArray.GetLength(1); k++) {
                 BlockData bd = new BlockData(valueArray[j, k]);
                 blockData[j, k] = bd;
             }
         }
     }
     //Debug.Log("Section Finished!");
 }
        bool IGeometryGeneratorSource.CanBuildSide(BlockData me, BlockData side, Point3 mePos, Point3 sidePos)
        {
            if (IsFence(side))
                return false;

            return !side.IsSolid;
        }
        public override List<CustomBlockData> GenerateModel(byte metadata, BlockData me, BlockData Xpos, BlockData Xneg, BlockData Ypos, BlockData Yneg, BlockData Zpos, BlockData Zneg, BlockSource source, Point3 blockPosition)
        {
            List<CustomBlockData> dat = new List<CustomBlockData>();

            float s = 0.707f;
            Vector3 d = new Vector3(-0.02f, 0, -0.02f);

            dat.Add(new CustomBlockData()
            {
                Vertex1 = new Vector3(0, s, 0) - d,
                Vertex2 = new Vector3(s, s, s) - d,
                Vertex3 = new Vector3(s, 0, s) - d,
                Vertex4 = new Vector3(0, 0, 0) - d,

                Normal = new Vector3(1, 0, 1),
                Texture = Textures.GetTexturesForMetadata(metadata)[0]
            }.CreateUVsYFlipped());

            dat.Add(new CustomBlockData()
            {
                Vertex1 = new Vector3(0, s, 0) - d,
                Vertex2 = new Vector3(s, s, s) - d,
                Vertex3 = new Vector3(s, 0, s) - d,
                Vertex4 = new Vector3(0, 0, 0) - d,

                TriFlip = true,

                Normal = new Vector3(-1, 0, -1),
                Texture = Textures.GetTexturesForMetadata(metadata)[0]
            }.CreateUVsYFlipped());

            dat.Add(new CustomBlockData()
            {
                Vertex1 = new Vector3(s, s, 0),
                Vertex2 = new Vector3(0, s, s),
                Vertex3 = new Vector3(0, 0, s),
                Vertex4 = new Vector3(s, 0, 0),

                TriFlip = true,

                Normal = new Vector3(-1, 0, 1),
                Texture = Textures.GetTexturesForMetadata(metadata)[0]
            }.CreateUVsYFlipped());

            dat.Add(new CustomBlockData()
            {
                Vertex1 = new Vector3(s, s, 0),
                Vertex2 = new Vector3(0, s, s),
                Vertex3 = new Vector3(0, 0, s),
                Vertex4 = new Vector3(s, 0, 0),

                TriFlip = true,

                Normal = new Vector3(1, 0, -1),
                Texture = Textures.GetTexturesForMetadata(metadata)[0]
            }.CreateUVsYFlipped());

            return dat;
        }
        public void Cast_CalledWithNonPageType_ReturnsNull()
        {
            var block = new BlockData();

            var pageData = block.Cast(typeof(PageData));

            pageData.Should().BeNull();
        }
        public static void RenderBlockBreadcrumbs(this HtmlHelper htmlHelper, BlockData currentBlock)
        {
            var currentBlockAsIContent = currentBlock as IContent;
            if (currentBlockAsIContent == null)
                return;

            htmlHelper.RenderBlockBreadcrumbs(currentBlockAsIContent);
        }
Beispiel #10
0
 public void SetData(BlockData data)
 {
     iPos = data.iPos;
     jPos = data.jPos;
     kPos = data.kPos;
     dir = data.dir;
     reference = data.reference;
     texture = data.texture;
 }
Beispiel #11
0
        //public Token getByName( String tokenName ) {
        //    Token x;
        //    this.tokenMap.TryGetValue( tokenName, out x );
        //    return x;
        //}
        //private void addMap( List<Token> tokens ) {
        //    if (tokens == null) return;
        //    foreach (Token x in tokens) {
        //        if (x.getName() == null) continue;
        //        // 允许变量存在多次
        //        if (tokenMap.ContainsKey( x.getName() )) continue;
        //        tokenMap.Add( x.getName(), x );
        //    }
        //}
        public override void appendData( StringBuilder sb, ContentBlock block, BlockData blockdata )
        {
            ContentBlock subBlock = blockdata.getBlock( this.getName() );
            if (subBlock == null) return;

            List<BlockData> datalist = subBlock.getDataList();
            foreach (BlockData oneData in datalist) {
                subBlock.addResultOne( sb, oneData );
            }
        }
        public static DisplayOption GetDisplayOption(this HtmlHelper htmlHelper, BlockData block)
        {
            if(htmlHelper == null)
                throw new ArgumentNullException(nameof(htmlHelper));

            if(block == null)
                throw new ArgumentNullException(nameof(block));

            return htmlHelper.ViewContext.ViewData.ContainsKey(Constants.CurrentDisplayOptionKey)
                       ? htmlHelper.ViewContext.ViewData[Constants.CurrentDisplayOptionKey] as DisplayOption
                       : null;
        }
Beispiel #13
0
    private static void setBlockDatas()
    {
        blockDatas=new Hashtable();

        int blockCode = 0;
        //optimization: this resource load really only needs the paths of the texture
        foreach (Texture2D texture in Resources.LoadAll(ResourcePaths.blockTextures,typeof(Texture2D)))
        {
            BlockData blockData=new BlockData(texture.name,blockCode,IntVector3.zero);
            blockDatas.Add(blockCode, blockData);
            blockCode++;
        }
    }
        public BlockDataManager()
        {
            Bitmap drawBitmap = new Bitmap(128, 64);
            Graphics drawbuffer = Graphics.FromImage(drawBitmap);

            //now, we need to create the images...
            foreach (Type loopvalue in BlockTypeManager.ManagedTypes)
            {

                // if (((!(BCBlockGameState.HasAttribute(loopvalue, typeof(BBEditorInvisibleAttribute))) || BCBlockGameState.HasAttribute(loopvalue,typeof(BBEditorVisibleAttribute)))|| KeyboardInfo.GetAsyncKeyState((int)Keys.ShiftKey) < 0))
                //if (((!invisattrib) || vistrib) || shiftpressed)
                //{
                drawbuffer.Clear(Color.White);
                Block createdblock = null;
                try
                {

                    createdblock =
                        (Block)Activator.CreateInstance(loopvalue, (Object)new RectangleF(0, 0, 128, 64));
                }
                catch (Exception except)
                {
                    Debug.Print("Exception " + except.Message + " instantiating " + loopvalue.Name);
                    continue;
                }
                try
                {
                    createdblock.Draw(drawbuffer);
                    BlockData newdata = new BlockData();
                    newdata.BlockType = loopvalue;
                    newdata.useBlockImage = (Image)drawBitmap.Clone();
                    newdata.Usename = loopvalue.Name;
                    BlockInfo.Add(newdata);
                }
                catch (Exception anyexception)
                {
                    // Exception when we tried to draw, probably. (issue first encountered with replacerblock).
                    //Fix: when an error occurs, set the useBlockImage to null. Also, made a change to the BlockData so that
                    //it will redraw the image itself if it is null.
                    BlockData adddata = new BlockData();
                    adddata.BlockType = loopvalue;
                    adddata.useBlockImage = null;
                    adddata.Usename = loopvalue.Name;
                    BlockInfo.Add(adddata);

                }
                //  }
            }
        }
        public void Generate (Chunk chunk)
        {
            int index = 0;
			for (int y = 0; y < EngineSettings.ChunkConfig.SizeYTotal; y++)
			{
	            for (int z = 0; z < EngineSettings.ChunkConfig.SizeZ; z++)
	            {
					int wz = z + (chunk.Pos.Z << EngineSettings.ChunkConfig.LogSizeZ);

                    for (int x = 0; x < EngineSettings.ChunkConfig.SizeX; x++, index++)
                    {
						int wx = x + (chunk.Pos.X << EngineSettings.ChunkConfig.LogSizeX);

                        bool currentPoint = Eval(wx, y, wz);
                        bool up = Eval(wx, y + 1, wz);
					
                        if (currentPoint)
						{
                            if (!up)
							{
								chunk[index] = new BlockData(BlockType.Grass);
                                // Grass block was placed, lets place a tree blueprint here
                                if (y < EngineSettings.ChunkConfig.SizeYTotal)
                                {
                                    //int height =
                                }
                            }
							else
							{
                                if (y > 50)
									chunk[index] = new BlockData(BlockType.Dirt);
                                else
									chunk[index] = new BlockData(BlockType.Stone);
                            }
                        }
						else
						{
							chunk[index] = BlockData.Air;
                        }
                    }
                }
            }
        }
Beispiel #16
0
    public Block createBlock(BlockData blockData, IntVector3 position)
    {
        GameObject blockGO = Instantiate(ResourceLookup.getBlockPrefab(), position.getVector3(), Quaternion.identity) as GameObject;
        blockGO.transform.parent = blockContainer.transform;
        Block block = blockGO.GetComponent<Block>();
        blockData.position = position;
        block.initialize(blockData);

        if (blockData.isRotationRandom)
        {
            blockGO.transform.eulerAngles = Angles.getRandom();
        }
        else
        {
            blockGO.transform.eulerAngles = Angles.getFlat();
        }
        //blockGO.transform.parent = transform;
        blockGameObjects[position.x, position.y, position.z] = blockGO;

        return block;
    }
    public Dictionary<Vector3, List<BlockData>> Read()
    {
        Dictionary<Vector3, List<BlockData>> result = new Dictionary<Vector3, List<BlockData>>();

        byte[] buffer;

        while (_decompressor.Position < _decompressor.Length)
        {
            List<BlockData> bucket = new List<BlockData>();

            // Read the chunk position
            buffer = new byte[7];
            _decompressor.Read(buffer, 0, 7);
            Vector3 key = new Vector3(buffer[0], buffer[1], buffer[2]);

            // Read how many blocks are stored for this chunk
            int count = BitConverter.ToInt32(new byte[4] { buffer[3], buffer[4], buffer[5], buffer[6] }, 0);

            buffer = new byte[4 * count];
            _decompressor.Read(buffer, 0, buffer.Length);

            // Read the actual block data
            int i = 0;
            while (i < buffer.Length)
            {
                BlockData block = new BlockData();

                block.position = new Vector3(buffer[i], buffer[i+1], buffer[i+2]);
                block.type = (BlockType)buffer[i+3];

                bucket.Add(block);

                i+=4;
            }

            result[key] = bucket;
        }

        return result;
    }
Beispiel #18
0
        public void PickupFlag(NetworkPlayer pickerupper, BlockData block)
        {
            if (block.ID != 9001 || pickerupper.PlayerTeam == block.MetaData || block.MetaData > 1) return;
            //1 = red
            //0 = blue
            byte metaData = block.MetaData;
            if (metaData == 0 )
            {
                BlueFlagCarrier = pickerupper;
                GameServer.SetBlock((int)BlueFlagLocation.X, (int)BlueFlagLocation.Y, 0);
                GameServer.SendMessageToAll(pickerupper.PlayerName + " has picked up the blue flag.");
            }
            if (metaData == 1)
            {
                RedFlagCarrier = pickerupper;
                GameServer.SetBlock((int)RedFlagLocation.X, (int)RedFlagLocation.Y, 0);
                GameServer.SendMessageToAll(pickerupper.PlayerName + " has picked up the red flag.");
            }

            Packet p = new Packet((byte)metaData, pickerupper.PlayerID);
            SendGameModeEvent("pickup", p);
        }
        public override List<CustomBlockData> GenerateModel(byte metadata, BlockData me, BlockData Xpos, BlockData Xneg, BlockData Ypos, BlockData Yneg, BlockData Zpos, BlockData Zneg, BlockSource source, Point3 blockPosition)
        {
            float onepix = 1f / 16f;
            float partStart = onepix * 7;
            float partEnd = onepix * 9;

            float tstart = 0.375f;
            float tend = 1f - tstart;

            List<BoundingBox> boxes = new List<BoundingBox>();

            //Pole
            boxes.Add(new BoundingBox(new Vector3(tstart, 0, tstart), new Vector3(tend, 1f, tend)));

            if (IsFence(Xpos))
            {
                boxes.Add(new BoundingBox(new Vector3(tend, 1f - onepix, partStart), new Vector3(1f, 1f - (onepix * 4), partEnd)));
                boxes.Add(new BoundingBox(new Vector3(tend, 1f - (onepix * 8), partStart), new Vector3(1f, 1f - (onepix * 11), partEnd)));
            }
            if (IsFence(Xneg))
            {
                boxes.Add(new BoundingBox(new Vector3(0, 1f - onepix, partStart), new Vector3(tstart, 1f - (onepix * 4), partEnd)));
                boxes.Add(new BoundingBox(new Vector3(0, 1f - (onepix * 8), partStart), new Vector3(tstart, 1f - (onepix * 11), partEnd)));
            }

            if (IsFence(Zpos))
            {
                boxes.Add(new BoundingBox(new Vector3(partStart, 1f - onepix, tend), new Vector3(partEnd, 1f - (onepix * 4), 1f)));
                boxes.Add(new BoundingBox(new Vector3(partStart, 1f - (onepix * 8), tend), new Vector3(partEnd, 1f - (onepix * 11), 1f)));
            }
            if (IsFence(Zneg))
            {
                boxes.Add(new BoundingBox(new Vector3(partStart, 1f - onepix, 0), new Vector3(partEnd, 1f - (onepix * 4), tstart)));
                boxes.Add(new BoundingBox(new Vector3(partStart, 1f - (onepix * 8), 0), new Vector3(partEnd, 1f - (onepix * 11), tstart)));
            }

            return GeometryGenerator.GenerateModel(boxes, source, blockPosition, false, this);
        }
Beispiel #20
0
    void OnGUI()
    {
        int i;

        if(placeObjectScript.DragObject == null)
        {
            selected = null;
        }

        for (i = 0; i < blockDatas.Count; i++)
        {
            if (GUI.Toggle(new Rect(10, 10 + 25 * i, 100, 20), (selected != null && selected.ID == blockDatas[i].ID), blockDatas[i].File))
            {
                if (selected != blockDatas[i])
                {
                    if (placeObjectScript.DragObject)
                    {
                        placeObjectScript.StopDrag(true);
                    }

                    block = (GameObject)Instantiate(Resources.Load(blockDatas[i].File), new Vector3(0, 0, 0), new Quaternion(0, 0, 0, 0));
                    block.transform.Rotate(new Vector3(-90, 0, 0));

                    Attachable attachable = block.AddComponent<Attachable>();

                    attachable.CreateGrid(blockDatas[i].AvailableWidth, blockDatas[i].AvailableHeight);

                    placeObjectScript.DragGameObject(block);
                }
                selected = blockDatas[i];
            }
        }
        if (GUI.Button(new Rect(10, 10 + 25 * i, 100, 20), "unselect"))
        {
            selected = null;
            placeObjectScript.StopDrag(true);
        }
    }
        public NetworkPlayer(byte playerID, NetConnection connection, Vector2 playerPos, string name)
        {
            NetConnection = connection;

            UpdateMask |= 1;
            UpdateMask |= (int)PlayerUpdateFlags.Player_Position;

            this.PlayerID = playerID;
            this.EntityPosition = playerPos;
            this.PlayerName = name;
            EntityVelocity.X = 3;

            PlayerBlockCache = new BlockData[GameServer.WorldSizeX, GameServer.WorldSizeY];

            Inventory = new PlayerInventory(this);
            PClass = new PlayerClassDestroyer(this);

            for (int x = 0; x < GameServer.WorldSizeX; x++)
                for (int y = 0; y < GameServer.WorldSizeY; y++)
                    PlayerBlockCache[x, y] = new BlockData();

            Respawn();
        }
Beispiel #22
0
        public override void appendData( StringBuilder sb, ContentBlock block, BlockData blockdata )
        {
            Object dicValue;
            blockdata.getDic().TryGetValue( this.getName(), out dicValue );

            if (dicValue != null) {
                sb.Append( dicValue );
                return;
            }

            if (this.isObject() && blockdata.getDic().ContainsKey( this.getObjName() )) {

                Object obj = blockdata.getDic()[this.getObjName()];
                if (obj == null) throw new NullReferenceException( "view's data " + this.getObjName() + " is null" );

                Object pval = getPropertyValue( obj, _objAccessor );
                sb.Append( pval );

                return;
            }

            sb.Append( this.getRawLabelAndVar() );
        }
Beispiel #23
0
 public void SetCell(Vector3Int pos, BlockData value)
 {
     SetCell(pos.x, pos.y, pos.z, value);
 }
Beispiel #24
0
    public void Initialize(BlockData data, Color color)
    {
        Initialize();

        this._data = data;

        CreateTile(color);

        this._position = GameObjectManager.Instance.GetStartPosition();
        this._direction = DIRECTION.UP;

        Move(this._position, this._direction);
    }
Beispiel #25
0
        public void SetType(int blockX, int blockY, int blockZ, BlockData.Blocks value, bool needsUpdate = true)
        {
            Section section = _Sections[blockY >> 4];

            if (section == null)
            {
                if (value != BlockData.Blocks.Air)
                    section = AddNewSection(blockY >> 4);
                else
                    return;
            }

            section[(blockY & 0xF) << 8 | blockZ << 4 | blockX] = (byte)value;

            OnSetType(blockX, blockY, blockZ, value);

            if (needsUpdate)
                BlockNeedsUpdate(blockX, blockY, blockZ);
        }
Beispiel #26
0
        /// <summary>
        ///     Set the block at the world position
        /// </summary>
        public void SetBlock(BlockData block, int wx, int wy, int wz)
        {
            if (wy<0 || wy>=EngineSettings.ChunkConfig.SizeYTotal)
                return;

            int cx = wx>>EngineSettings.ChunkConfig.LogSizeX;
            int cz = wz>>EngineSettings.ChunkConfig.LogSizeZ;

            Chunk chunk = GetChunk(cx, cz);
            if (chunk==null)
                return;

            int lx = wx&EngineSettings.ChunkConfig.MaskX;
            int lz = wz&EngineSettings.ChunkConfig.MaskZ;

			chunk.ModifyBlock(lx, wy, lz, block);
        }
Beispiel #27
0
        internal void OnSetType(int blockX, int blockY, int blockZ, BlockData.Blocks value)
        {
            byte blockId = (byte)value;
            short blockPackedCoords = (short)(blockX << 11 | blockZ << 7 | blockY);


            if (GrowableBlocks.ContainsKey(blockPackedCoords))
            {
                short unused;

                if (!BlockHelper.Instance.IsGrowable(blockId))
                {
                    GrowableBlocks.TryRemove(blockPackedCoords, out unused);
                }
                else
                {
                    byte metaData = GetData(blockX, blockY, blockZ);
                    StructBlock block = new StructBlock(UniversalCoords.FromBlock(Coords.ChunkX, Coords.ChunkZ, blockX, blockY, blockZ), blockId, metaData, World);
                    if (!(BlockHelper.Instance.CreateBlockInstance(blockId) as IBlockGrowable).CanGrow(block, this))
                    {
                        GrowableBlocks.TryRemove(blockPackedCoords, out unused);
                    }
                }
            }
            else
            {
                if (BlockHelper.Instance.IsGrowable(blockId))
                {
                    byte metaData = GetData(blockX, blockY, blockZ);
                    UniversalCoords blockCoords = UniversalCoords.FromBlock(Coords.ChunkX, Coords.ChunkZ, blockX, blockY,
                                                                            blockZ);
                    StructBlock block = new StructBlock(blockCoords, blockId, metaData, World);
                    if ((BlockHelper.Instance.CreateBlockInstance(blockId) as IBlockGrowable).CanGrow(block, this))
                        GrowableBlocks.TryAdd(blockPackedCoords, blockPackedCoords);
                }
            }
        }
Beispiel #28
0
        public void SetType(UniversalCoords coords, BlockData.Blocks value, bool needsUpdate = true)
        {
            int sectionId = coords.BlockY >> 4;
            Section section = _Sections[sectionId];

            if (section == null)
            {
                if (value != BlockData.Blocks.Air)
                    section = AddNewSection(sectionId);
                else
                    return;
            }
            section[coords.SectionPackedCoords] = (byte)value;
            OnSetType(coords, value);

            if (needsUpdate)
                BlockNeedsUpdate(coords.BlockX, coords.BlockY, coords.BlockZ);
        }
        /// <summary>
        ///     Raises the page event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="contentEventArgs">Event information to send to registered event handlers.</param>
        public void OnPublishingContent(object sender, ContentEventArgs contentEventArgs)
        {
            if (contentEventArgs == null)
            {
                return;
            }

            PageData page = contentEventArgs.Content as PageData;

            if (page == null)
            {
                return;
            }

            PropertyInfo addtionalSearchContentProperty = GetAddtionalSearchContentProperty(page);

            if (addtionalSearchContentProperty == null)
            {
                return;
            }

            if (addtionalSearchContentProperty.PropertyType != typeof(string))
            {
                return;
            }

            StringBuilder stringBuilder = new StringBuilder();

            ContentType contentType = this.ContentTypeRepository.Service.Load(page.ContentTypeID);

            foreach (PropertyDefinition current in
                     from d in contentType.PropertyDefinitions
                     where typeof(PropertyContentArea).IsAssignableFrom(d.Type.DefinitionType)
                     select d)
            {
                PropertyData propertyData = page.Property[current.Name];

                ContentArea contentArea = propertyData.Value as ContentArea;

                if (contentArea == null)
                {
                    continue;
                }

                foreach (ContentAreaItem contentAreaItem in contentArea.Items)
                {
                    IContent content;
                    if (!this.ContentRepository.Service.TryGet(contentAreaItem.ContentLink, out content))
                    {
                        continue;
                    }

                    // content area item can be null when duplicating a page
                    if (content == null)
                    {
                        continue;
                    }

                    // Check if the content is indeed a block, and not a page used in a content area
                    BlockData blockData = content as BlockData;

                    // Content area is not a block, but probably a page used as a teaser.
                    if (blockData == null)
                    {
                        Logger.Information(
                            "[Blocksearch] Contentarea item is not block data. Skipping update.",
                            content.Name);
                        continue;
                    }

                    IEnumerable <string> props = this.GetSearchablePropertyValues(content, content.ContentTypeID);
                    stringBuilder.AppendFormat(" {0}", string.Join(" ", props));
                }
            }

            if (addtionalSearchContentProperty.PropertyType != typeof(string))
            {
                return;
            }

            try
            {
                string additionalSearchContent = TextIndexer.StripHtml(stringBuilder.ToString(), 0);

                // When being "delayed published" the pagedata is readonly. Create a writable clone to be safe.
                PageData editablePage = page.CreateWritableClone();
                editablePage[addtionalSearchContentProperty.Name] = additionalSearchContent;

                // Save the writable pagedata, do not create a new version
                this.ContentRepository.Service.Save(
                    editablePage,
                    SaveAction.Save | SaveAction.ForceCurrentVersion,
                    AccessLevel.NoAccess);
            }
            catch (EPiServerException ePiServerException)
            {
                Logger.Error(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "[Blocksearch] Property {0} dose not exist on {1} .",
                        addtionalSearchContentProperty.Name,
                        page.Name),
                    ePiServerException);
            }
        }
Beispiel #30
0
 public int GetIdFromBlock(BlockData block)
 {
     Guard.ValidateObject(block);
     return(((IContent)block).ContentLink.ID);
 }
Beispiel #31
0
        public void PlayerScore(NetworkPlayer scorer, BlockData touched)
        {
            if (touched.ID != 9001) return;
            if (scorer != RedFlagCarrier && scorer != BlueFlagCarrier) return;
            if(scorer == RedFlagCarrier)
            {
                RedFlagCarrier = null;
                BlueScore += 1;
                GameServer.SetBlock((int)RedFlagLocation.X, (int)RedFlagLocation.Y, 9001, true, 1);
                GameServer.SendMessageToAll(scorer.PlayerName + " has scored a point for blue. Blue's score: " + BlueScore);

                Packet p = new Packet(scorer.PlayerID);
                SendGameModeEvent("drop", p);
            }
            if (scorer == BlueFlagCarrier)
            {
                BlueFlagCarrier = null;
                RedScore += 1;
                GameServer.SetBlock((int)BlueFlagLocation.X, (int)BlueFlagLocation.Y, 9001);
                GameServer.SendMessageToAll(scorer.PlayerName + " has scored a point for red. Red's score: " + RedScore);

                Packet p = new Packet(scorer.PlayerID);
                SendGameModeEvent("drop", p);
            }
        }
Beispiel #32
0
        private int AllocBlock(int length)
        {
            if (length <= 0)
            {
                return(GetEmptyBlockIndex());
            }

            length = (int)GetUpBoundClusterOffset(length);

            int lengthFound = -1;
            GameFrameworkLinkedListRange <int> lengthRange = default(GameFrameworkLinkedListRange <int>);

            foreach (KeyValuePair <int, GameFrameworkLinkedListRange <int> > i in m_FreeBlockIndexes)
            {
                if (i.Key < length)
                {
                    continue;
                }

                if (lengthFound >= 0 && lengthFound < i.Key)
                {
                    continue;
                }

                lengthFound = i.Key;
                lengthRange = i.Value;
            }

            if (lengthFound >= 0)
            {
                if (lengthFound > length && m_BlockDatas.Count >= m_HeaderData.MaxBlockCount)
                {
                    return(-1);
                }

                int blockIndex = lengthRange.First.Value;
                m_FreeBlockIndexes.Remove(lengthFound, blockIndex);
                if (lengthFound > length)
                {
                    BlockData blockData = m_BlockDatas[blockIndex];
                    m_BlockDatas[blockIndex] = new BlockData(blockData.ClusterIndex, length);
                    WriteBlockData(blockIndex);

                    int deltaLength       = lengthFound - length;
                    int anotherBlockIndex = GetEmptyBlockIndex();
                    m_BlockDatas[anotherBlockIndex] = new BlockData(blockData.ClusterIndex + GetUpBoundClusterCount(length), deltaLength);
                    m_FreeBlockIndexes.Add(deltaLength, anotherBlockIndex);
                    WriteBlockData(anotherBlockIndex);
                }

                return(blockIndex);
            }
            else
            {
                int blockIndex = GetEmptyBlockIndex();
                if (blockIndex < 0)
                {
                    return(-1);
                }

                long fileLength = m_Stream.Length;
                try
                {
                    m_Stream.SetLength(fileLength + length);
                }
                catch
                {
                    return(-1);
                }

                m_BlockDatas[blockIndex] = new BlockData(GetUpBoundClusterCount(fileLength), length);
                WriteBlockData(blockIndex);
                return(blockIndex);
            }
        }
Beispiel #33
0
 public Block CreateBlockAsDefault(BlockData blockData)
 {
     return(CreateBlockAsDefault(blockData.location, blockData.shapeData, blockData.blockType));
 }
Beispiel #34
0
        private static int LoadModels(IRegistryManager registryManager, ResourceManager resources,
                                      McResourcePack resourcePack, bool replace,
                                      bool reportMissing, IProgressReceiver progressReceiver)
        {
            long idCounter          = 0;
            var  blockRegistry      = registryManager.GetRegistry <Block>();
            var  blockModelRegistry = registryManager.GetRegistry <BlockModel>();

            var data           = BlockData.FromJson(ResourceManager.ReadStringResource("Alex.Resources.NewBlocks.json"));
            int total          = data.Count;
            int done           = 0;
            int importCounter  = 0;
            int multipartBased = 0;

            uint c = 0;

            foreach (var entry in data)
            {
                double percentage = 100D * ((double)done / (double)total);
                progressReceiver.UpdateProgress((int)percentage, $"Importing block models...", entry.Key);

                var variantMap   = new BlockStateVariantMapper();
                var defaultState = new BlockState
                {
                    Name          = entry.Key,
                    VariantMapper = variantMap
                };

                if (entry.Value.Properties != null)
                {
                    foreach (var property in entry.Value.Properties)
                    {
                        //	if (property.Key.Equals("waterlogged"))
                        //		continue;

                        defaultState = (BlockState)defaultState.WithPropertyNoResolve(property.Key,
                                                                                      property.Value.FirstOrDefault(), false);
                    }
                }

                foreach (var s in entry.Value.States)
                {
                    var id = s.ID;

                    BlockState variantState = (BlockState)(defaultState).CloneSilent();
                    variantState.ID   = id;
                    variantState.Name = entry.Key;

                    if (s.Properties != null)
                    {
                        foreach (var property in s.Properties)
                        {
                            //if (property.Key.Equals("waterlogged"))
                            //		continue;

                            variantState =
                                (Blocks.State.BlockState)variantState.WithPropertyNoResolve(property.Key,
                                                                                            property.Value, false);
                        }
                    }

                    if (!replace && RegisteredBlockStates.TryGetValue(id, out BlockState st))
                    {
                        Log.Warn(
                            $"Duplicate blockstate id (Existing: {st.Name}[{st.ToString()}] | New: {entry.Key}[{variantState.ToString()}]) ");
                        continue;
                    }


                    var cachedBlockModel = GetOrCacheModel(resources, resourcePack, variantState, id, replace);
                    if (cachedBlockModel == null)
                    {
                        if (reportMissing)
                        {
                            Log.Warn($"Missing blockmodel for blockstate {entry.Key}[{variantState.ToString()}]");
                        }

                        cachedBlockModel = UnknownBlockModel;
                    }

                    if (variantState.IsMultiPart)
                    {
                        multipartBased++;
                    }

                    string displayName = entry.Key;
                    IRegistryEntry <Block> registryEntry;

                    if (!blockRegistry.TryGet(entry.Key, out registryEntry))
                    {
                        registryEntry = new UnknownBlock(id);
                        displayName   = $"(MISSING) {displayName}";

                        registryEntry = registryEntry.WithLocation(entry.Key);                         // = entry.Key;
                    }
                    else
                    {
                        registryEntry = registryEntry.WithLocation(entry.Key);
                    }

                    var block = registryEntry.Value;

                    variantState.Model   = cachedBlockModel;
                    variantState.Default = s.Default;

                    if (string.IsNullOrWhiteSpace(block.DisplayName) ||
                        !block.DisplayName.Contains("minet", StringComparison.InvariantCultureIgnoreCase))
                    {
                        block.DisplayName = displayName;
                    }

                    variantState.Block = block;
                    block.BlockState   = variantState;

                    if (variantMap.TryAdd(variantState))
                    {
                        if (!RegisteredBlockStates.TryAdd(variantState.ID, variantState))
                        {
                            if (replace)
                            {
                                RegisteredBlockStates[variantState.ID] = variantState;
                                importCounter++;
                            }
                            else
                            {
                                Log.Warn(
                                    $"Failed to add blockstate (variant), key already exists! ({variantState.ID} - {variantState.Name})");
                            }
                        }
                        else
                        {
                            importCounter++;
                        }
                    }
                    else
                    {
                        Log.Warn(
                            $"Could not add variant to variant map: {variantState.Name}[{variantState.ToString()}]");
                    }
                }

                if (!BlockStateByName.TryAdd(defaultState.Name, variantMap))
                {
                    if (replace)
                    {
                        BlockStateByName[defaultState.Name] = variantMap;
                    }
                    else
                    {
                        Log.Warn($"Failed to add blockstate, key already exists! ({defaultState.Name})");
                    }
                }

                done++;
            }

            Log.Info($"Got {multipartBased} multi-part blockstate variants!");
            return(importCounter);
        }
Beispiel #35
0
 public static Block GetBlock(this BlockData data)
 {
     return(Block.GetBlock(data.GetBlockId()));
 }
Beispiel #36
0
        private bool TryCombineFreeBlocks(int freeBlockIndex)
        {
            BlockData freeBlockData = m_BlockDatas[freeBlockIndex];

            if (freeBlockData.Length <= 0)
            {
                return(false);
            }

            int previousFreeBlockIndex    = -1;
            int nextFreeBlockIndex        = -1;
            int nextBlockDataClusterIndex = freeBlockData.ClusterIndex + GetUpBoundClusterCount(freeBlockData.Length);

            foreach (KeyValuePair <int, GameFrameworkLinkedListRange <int> > blockIndexes in m_FreeBlockIndexes)
            {
                if (blockIndexes.Key <= 0)
                {
                    continue;
                }

                int blockDataClusterCount = GetUpBoundClusterCount(blockIndexes.Key);
                foreach (int blockIndex in blockIndexes.Value)
                {
                    BlockData blockData = m_BlockDatas[blockIndex];
                    if (blockData.ClusterIndex + blockDataClusterCount == freeBlockData.ClusterIndex)
                    {
                        previousFreeBlockIndex = blockIndex;
                    }
                    else if (blockData.ClusterIndex == nextBlockDataClusterIndex)
                    {
                        nextFreeBlockIndex = blockIndex;
                    }
                }
            }

            if (previousFreeBlockIndex < 0 && nextFreeBlockIndex < 0)
            {
                return(false);
            }

            m_FreeBlockIndexes.Remove(freeBlockData.Length, freeBlockIndex);
            if (previousFreeBlockIndex >= 0)
            {
                BlockData previousFreeBlockData = m_BlockDatas[previousFreeBlockIndex];
                m_FreeBlockIndexes.Remove(previousFreeBlockData.Length, previousFreeBlockIndex);
                freeBlockData = new BlockData(previousFreeBlockData.ClusterIndex, previousFreeBlockData.Length + freeBlockData.Length);
                m_BlockDatas[previousFreeBlockIndex] = BlockData.Empty;
                m_FreeBlockIndexes.Add(0, previousFreeBlockIndex);
                WriteBlockData(previousFreeBlockIndex);
            }

            if (nextFreeBlockIndex >= 0)
            {
                BlockData nextFreeBlockData = m_BlockDatas[nextFreeBlockIndex];
                m_FreeBlockIndexes.Remove(nextFreeBlockData.Length, nextFreeBlockIndex);
                freeBlockData = new BlockData(freeBlockData.ClusterIndex, freeBlockData.Length + nextFreeBlockData.Length);
                m_BlockDatas[nextFreeBlockIndex] = BlockData.Empty;
                m_FreeBlockIndexes.Add(0, nextFreeBlockIndex);
                WriteBlockData(nextFreeBlockIndex);
            }

            m_BlockDatas[freeBlockIndex] = freeBlockData;
            m_FreeBlockIndexes.Add(freeBlockData.Length, freeBlockIndex);
            WriteBlockData(freeBlockIndex);
            return(true);
        }
        public override List<CustomBlockData> GenerateModel(byte metadata, BlockData me, BlockData Xpos, BlockData Xneg, BlockData Ypos, BlockData Yneg, BlockData Zpos, BlockData Zneg, BlockSource source, Point3 blockPosition)
        {
            List<CustomBlockData> r = new List<CustomBlockData>();

            bool top = BitHelper.IsBitSet(metadata, 3);

            float h = .5f;
            float l = 0;

            if (top)
            {
                h = 1;
                l = .5f;
            }

            if (Block.CanBuild(Ypos, me))
            {
                r.Add(new CustomBlockData()
                {
                    Vertex1 = new Vector3(0, h, 0),
                    Vertex2 = new Vector3(1, h, 0),
                    Vertex3 = new Vector3(1, h, 1),
                    Vertex4 = new Vector3(0, h, 1),

                    Texture = GetTextureForSide(BlockSide.Ypos, metadata),
                    Normal = new Vector3(0, 1, 0)
                }.CreateUVs());
            }

            if (Block.CanBuild(Yneg, me))
            {
                r.Add(new CustomBlockData()
                {
                    Vertex1 = new Vector3(1, l, 1),
                    Vertex2 = new Vector3(0, l, 1),
                    Vertex3 = new Vector3(0, l, 0),
                    Vertex4 = new Vector3(1, l, 0),

                    Texture = GetTextureForSide(BlockSide.Yneg, metadata),
                    Normal = new Vector3(0, -1, 0)
                }.CreateUVs());
            }

            if (Block.CanBuild(Zneg, me))
            {
                r.Add(new CustomBlockData()
                {
                    Vertex1 = new Vector3(0, l, 0),
                    Vertex2 = new Vector3(1, l, 0),
                    Vertex3 = new Vector3(1, h, 0),
                    Vertex4 = new Vector3(0, h, 0),

                    UV1 = new Vector2(0, l),
                    UV2 = new Vector2(1, l),
                    UV3 = new Vector2(1, h),
                    UV4 = new Vector2(0, h),

                    Texture = GetTextureForSide(BlockSide.Zneg, metadata),
                    Normal = new Vector3(0, 0, -1)
                });
            }

            if (Block.CanBuild(Zpos, me))
            {
                r.Add(new CustomBlockData()
                {
                    Vertex1 = new Vector3(0, l, 1),
                    Vertex2 = new Vector3(1, l, 1),
                    Vertex3 = new Vector3(1, h, 1),
                    Vertex4 = new Vector3(0, h, 1),

                    UV1 = new Vector2(0, l),
                    UV2 = new Vector2(1, l),
                    UV3 = new Vector2(1, h),
                    UV4 = new Vector2(0, h),

                    Texture = GetTextureForSide(BlockSide.Zpos, metadata),
                    Normal = new Vector3(0, 0, 1)
                });
            }

            if (Block.CanBuild(Xneg, me))
            {
                r.Add(new CustomBlockData()
                {
                    Vertex1 = new Vector3(0, l, 0),
                    Vertex2 = new Vector3(0, l, 1),
                    Vertex3 = new Vector3(0, h, 1),
                    Vertex4 = new Vector3(0, h, 0),

                    UV1 = new Vector2(0, l),
                    UV2 = new Vector2(1, l),
                    UV3 = new Vector2(1, h),
                    UV4 = new Vector2(0, h),

                    Texture = GetTextureForSide(BlockSide.Xneg, metadata),
                    Normal = new Vector3(-1, 0, 0)
                });
            }

            if (Block.CanBuild(Xpos, me))
            {
                r.Add(new CustomBlockData()
                {
                    Vertex1 = new Vector3(1, l, 0),
                    Vertex2 = new Vector3(1, l, 1),
                    Vertex3 = new Vector3(1, h, 1),
                    Vertex4 = new Vector3(1, h, 0),

                    UV1 = new Vector2(0, l),
                    UV2 = new Vector2(1, l),
                    UV3 = new Vector2(1, h),
                    UV4 = new Vector2(0, h),

                    Texture = GetTextureForSide(BlockSide.Xpos, metadata),
                    Normal = new Vector3(1, 0, 0)
                });
            }

            return r;
        }
Beispiel #38
0
 public override void appendData( StringBuilder sb, ContentBlock block, BlockData blockdata )
 {
     sb.Append( this.getValue() );
 }
        /// <summary>
        ///     Handles the <see cref="E:PublishedContent" /> event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="contentEventArgs">The <see cref="ContentEventArgs" /> instance containing the event data.</param>
        public void OnPublishedContent(object sender, ContentEventArgs contentEventArgs)
        {
            if (contentEventArgs == null)
            {
                return;
            }

            // Check if the content that is published is indeed a block.
            BlockData blockData = contentEventArgs.Content as BlockData;

            // If it's not, don't do anything.
            if (blockData == null)
            {
                return;
            }

            // Get the references to this block
            List <ContentReference> referencingContentLinks =
                this.ContentSoftLinkRepository.Service.Load(contentEventArgs.ContentLink, true)
                .Where(
                    link =>
                    (link.SoftLinkType == ReferenceType.PageLinkReference) &&
                    !ContentReference.IsNullOrEmpty(link.OwnerContentLink))
                .Select(link => link.OwnerContentLink)
                .ToList();

            // Loop through each reference
            foreach (ContentReference referencingContentLink in referencingContentLinks)
            {
                PageData parent;
                this.ContentRepository.Service.TryGet(referencingContentLink, out parent);

                // If it is not pagedata, do nothing
                if (parent == null)
                {
                    Logger.Information("[Blocksearch] Referencing content is not a page. Skipping update.");
                    continue;
                }

                // Check if the containing page is published.
                if (!parent.CheckPublishedStatus(PagePublishedStatus.Published))
                {
                    Logger.Information("[Blocksearch] page named '{0}' is not published. Skipping update.", parent.Name);
                    continue;
                }

                // Republish the containing page.
                try
                {
                    this.ContentRepository.Service.Save(
                        parent.CreateWritableClone(),
                        SaveAction.Publish | SaveAction.ForceCurrentVersion,
                        AccessLevel.NoAccess);
                    Logger.Information("[Blocksearch] Updated containing page named '{0}'.", parent.Name);
                }
                catch (AccessDeniedException accessDeniedException)
                {
                    Logger.Error(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "[Blocksearch] Not enough accessrights to republish containing pagetype named '{0}'.",
                            parent.Name),
                        accessDeniedException);
                }
            }
        }