Beispiel #1
0
        static string GetXamarinStudioXcodeSdkRoot()
        {
            var settingsPlistPath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.Personal),
                "Library",
                "Preferences",
                "Xamarin",
                "Settings.plist");

            if (!File.Exists(settingsPlistPath))
            {
                return(null);
            }

            try {
                var pDict = PlistDictionary.Load(settingsPlistPath);
                var path  = (string)pDict ["AppleSdkRoot"];

                if (Directory.Exists(path))
                {
                    return(path);
                }
            } catch (Exception e) {
                Log.Error(TAG, e);
            }

            return(null);
        }
        BuildResult MergeInfoPlist(IProgressMonitor monitor, MonoMacProject proj, MonoMacProjectConfiguration conf,
                                   ProjectFile template, FilePath plistOut)
        {
            return(MacBuildUtilities.CreateMergedPlist(monitor, template, plistOut, (PlistDocument doc) => {
                var result = new BuildResult();
                var dict = doc.Root as PlistDictionary;
                if (dict == null)
                {
                    doc.Root = dict = new PlistDictionary();
                }

                //required keys that the user is likely to want to modify
                SetIfNotPresent(dict, "CFBundleName", proj.Name);
                SetIfNotPresent(dict, "CFBundleIdentifier", "com.yourcompany." + proj.Name);
                SetIfNotPresent(dict, "CFBundleShortVersionString", proj.Version);
                SetIfNotPresent(dict, "CFBundleVersion", "1");
                SetIfNotPresent(dict, "LSMinimumSystemVersion", "10.6");
                SetIfNotPresent(dict, "CFBundleDevelopmentRegion", "English");

                //required keys that the user probably should not modify
                dict["CFBundleExecutable"] = conf.LaunchScript.FileName;
                SetIfNotPresent(dict, "CFBundleInfoDictionaryVersion", "6.0");
                SetIfNotPresent(dict, "CFBundlePackageType", "APPL");
                SetIfNotPresent(dict, "CFBundleSignature", "????");

                return result;
            }));
        }
 static void SetIfNotPresent(PlistDictionary dict, string key, PlistObjectBase value)
 {
     if (!dict.ContainsKey(key))
     {
         dict[key] = value;
     }
 }
        public void load(String path)
        {
            System.IO.StreamReader file = new System.IO.StreamReader(path);

            // Create an XmlReaderSettings object.
            XmlReaderSettings settings = new XmlReaderSettings();

            // Set XmlResolver to null, and ProhibitDtd to false.
            settings.XmlResolver   = null;
            settings.DtdProcessing = DtdProcessing.Ignore;

            // Now, create an XmlReader.  This is a forward-only text-reader based
            // reader of Xml.  Passing in the settings will ensure that validation
            // is not performed.
            XmlReader reader = XmlTextReader.Create(file, settings);

            // Create your document, and load the reader.
            XmlDocument doc = new XmlDocument();

            doc.Load(reader);

            XmlNode root = doc.DocumentElement.FirstChild;

            PlistDictionary dict = new PlistDictionary(root);

            plistFile = dict_to_plist(dict);

            file.Close();
        }
Beispiel #5
0
 public bool InitWithSpriteFrame(CCSpriteFrame spriteFrame, float delayUnits, PlistDictionary userInfo)
 {
     m_pSpriteFrame = spriteFrame;
     m_fDelayUnits  = delayUnits;
     m_pUserInfo    = userInfo;
     return(true);
 }
Beispiel #6
0
		private PlistType GetPlistType(PlistDictionary dict)
		{
			var isSpriteKit = dict.ContainsKey ("format") ? dict ["format"].AsString == "APPL" : false;

			return isSpriteKit ? PlistType.SpriteKit : PlistType.Cocos2D;

		}
Beispiel #7
0
        public LHSprite(CCSpriteFrame spriteFrame, PlistDictionary dict, CCNode prnt, String spriteFrameName, String imageDevPath) : base(spriteFrame)
        {
            Debug.WriteLine("DID INIT SPRITE WITH FRAME " + spriteFrame);

            this._spriteFrameName = spriteFrameName;
            this._imageFilePath   = imageDevPath;


            prnt.AddChild(this);

//				[self setColor:[dict colorForKey:@"colorOverlay"]];
//
            _nodeProtocolImp.loadGenericInfoFromDictionary(dict, this);

            Debug.WriteLine("LOADING PHYSICS...................");
            Debug.WriteLine("SPR NAME " + this.getSpriteFrameName());
            Debug.WriteLine("IMG NAME " + this.getImageFilePath());
            Debug.WriteLine(dict);

            _physicsProtocolImp.loadPhysicsInfoFromDictionary(dict["nodePhysics"].AsDictionary, this);


            LHNodeProtocolImp.loadChildrenForNode(this, dict);
//
//
//				_animationProtocolImp = [[LHNodeAnimationProtocolImp alloc] initAnimationProtocolImpWithDictionary:dict
//					node:self];
//			}
//
        }
 public bool InitWithSpriteFrame(CCSpriteFrame spriteFrame, float delayUnits, PlistDictionary userInfo)
 {
     m_pSpriteFrame = spriteFrame;
     m_fDelayUnits = delayUnits;
     m_pUserInfo = userInfo;
     return true;
 }
Beispiel #9
0
        static void ReadPlist()
        {
            PlistDictionary infoDict = (PlistDictionary)PlistStructure.FromFile(@"C:\Users\Admin\Desktop\iphonebak\00008030-000A6C562E92802E\Info.plist");

            BackupInfo backupInfo = new BackupInfo
            {
                Applications          = (PlistDictionary)infoDict["Applications"],
                BuildVersion          = ((PlistString)infoDict["Build Version"]).Value,
                DeviceName            = ((PlistString)infoDict["Device Name"]).Value,
                DisplayName           = ((PlistString)infoDict["Display Name"]).Value,
                GUID                  = ((PlistString)infoDict["GUID"]).Value,
                ICCID                 = ((PlistString)infoDict["ICCID"]).Value,
                IMEI                  = ((PlistString)infoDict["IMEI"]).Value,
                InstalledApplications = (PlistArray)infoDict["Installed Applications"],
                LastBackupDate        = ((PlistDate)infoDict["Last Backup Date"]).Value,
                MEID                  = ((PlistString)infoDict["MEID"]).Value,
                PhoneNumber           = ((PlistString)infoDict["Phone Number"]).Value,
                ProductType           = ((PlistString)infoDict["Product Type"]).Value,
                ProductVersion        = ((PlistString)infoDict["Product Version"]).Value,
                SerialNumber          = ((PlistString)infoDict["Serial Number"]).Value,
                TargetIdentifier      = ((PlistString)infoDict["Target Identifier"]).Value,
                TargetType            = ((PlistString)infoDict["Target Type"]).Value,
                UniqueIdentifier      = ((PlistString)infoDict["Unique Identifier"]).Value,
                iTunesFiles           = (PlistDictionary)infoDict["iTunes Files"],
                iTunesSettings        = (PlistDictionary)infoDict["iTunes Settings"],
                iTunesVersion         = ((PlistString)infoDict["iTunes Version"]).Value,
            };


            List <string> installedApplications = new List <string>();

            foreach (PlistString item in backupInfo.InstalledApplications)
            {
                installedApplications.Add(item.Value);
            }


            List <Application> applications = new List <Application>();

            foreach (var item in backupInfo.Applications)
            {
                string          key   = item.Key;
                PlistDictionary value = (PlistDictionary)item.Value;

                Application application = new Application
                {
                    ApplicationSINF = (PlistData)value["ApplicationSINF"],
                    PlaceholderIcon = (PlistData)value["PlaceholderIcon"],
                    iTunesMetadata  = (PlistData)value["iTunesMetadata"]
                };
                applications.Add(application);

                string path = Path.Combine(@"C:\Users\Admin\Desktop\iphonebak", $"{key}.png");
                using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    byte[] buffer = application.PlaceholderIcon.Value;
                    fileStream.Write(buffer, 0, buffer.Length);
                }
            }
        }
Beispiel #10
0
 private CCLabelAtlas(string label, PlistDictionary fontPlistDict) 
     : this(label, fontPlistDict["textureFilename"].AsString, 
         (int)Math.Ceiling((double)fontPlistDict["itemWidth"].AsInt), 
         (int)Math.Ceiling((double)fontPlistDict["itemHeight"].AsInt),
         (char)fontPlistDict["firstChar"].AsInt)
 {
     Debug.Assert(fontPlistDict["version"].AsInt == 1, "Unsupported version. Upgrade cocos2d version");
 }
Beispiel #11
0
        public void Store(IPhoneProject proj)
        {
            proj.BundleDevelopmentRegion = NullIfEmpty(devRegionEntry.Text);
            proj.BundleIdentifier        = NullIfEmpty(bundleIdEntry.Text);
            proj.BundleVersion           = NullIfEmpty(bundleVersionEntry.Text);
            proj.BundleDisplayName       = NullIfEmpty(displayNameEntry.Text);
            proj.MainNibFile             = NullIfEmpty(mainNibPicker.SelectedFile);
            proj.MainNibFileIPad         = NullIfEmpty(iPadNibPicker.SelectedFile);

            proj.BundleIcon              = NullIfEmpty(iphoneIconPicker.SelectedFile);
            proj.BundleIconHigh          = NullIfEmpty(iphoneIconHighPicker.SelectedFile);
            proj.BundleIconIPad          = NullIfEmpty(ipadIconPicker.SelectedFile);
            proj.BundleIconSpotlight     = NullIfEmpty(settingsIconPicker.SelectedFile);
            proj.BundleIconSpotlightHigh = NullIfEmpty(settingsIconHighPicker.SelectedFile);
            proj.BundleIconIPadSpotlight = NullIfEmpty(ipadSpotlightIconPicker.SelectedFile);

            proj.SupportedDevices = SupportedDevices;

            if (badPlist)
            {
                return;
            }
            try {
                var pf  = proj.GetInfoPlist();
                var doc = new PlistDocument();
                doc.LoadFromXmlFile(pf.FilePath);
                var dict = doc.Root as PlistDictionary;
                if (dict == null)
                {
                    doc.Root = dict = new PlistDictionary();
                }

                var orientations = SaveOrientationsCombo(supportedOrientationsCombo);
                if (orientations != null)
                {
                    dict [OrientationUtil.KEY] = orientations;
                }
                else
                {
                    dict.Remove(OrientationUtil.KEY);
                }

                var iPadOrientations = SaveOrientationsCombo(iPadOrientationsCombo);
                if (proj.SupportedDevices == TargetDevice.IPhoneAndIPad && iPadOrientations != null)
                {
                    dict [OrientationUtil.KEY_IPAD] = iPadOrientations;
                }
                else
                {
                    dict.Remove(OrientationUtil.KEY_IPAD);
                }

                doc.WriteToFile(pf.FilePath);
            } catch (Exception ex) {
                badPlist = true;
                MonoDevelop.Ide.MessageService.ShowException(ex, "Error saving Info.plist.");
            }
        }
        static void LHSetupb2FixtureWithInfo(b2FixtureDef fixture, PlistDictionary dict)
        {
            fixture.density     = dict ["density"].AsFloat;
            fixture.friction    = dict ["friction"].AsFloat;
            fixture.restitution = dict ["restitution"].AsFloat;
            fixture.isSensor    = dict["sensor"].AsBool;

            fixture.filter.maskBits     = (ushort)dict ["mask"].AsInt;
            fixture.filter.categoryBits = (ushort)dict ["category"].AsInt;
        }
        public static String devicePosition(PlistDictionary availablePositions, CCSize curScr)
        {
            string w   = Convert.ToInt32(curScr.Width).ToString();
            string h   = Convert.ToInt32(curScr.Height).ToString();
            string key = w + "x" + h;

            Debug.WriteLine("devicePosition key is " + key);

            return(availablePositions.TryGetValue(key).AsString);
        }
 public CCSpriteSheet AddSpriteSheet(PlistDictionary dictionary, CCTexture2D texture, string name)
 {
     CCSpriteSheet result;
     if (!_spriteSheets.TryGetValue(name, out result))
     {
         result = new CCSpriteSheet(name, texture);
         _spriteSheets.Add(name, result);
     }
     return result;
 }
        public CCSpriteSheet AddSpriteSheet(PlistDictionary dictionary, CCTexture2D texture, string name)
        {
            CCSpriteSheet result;

            if (!_spriteSheets.TryGetValue(name, out result))
            {
                result = new CCSpriteSheet(name, texture);
                _spriteSheets.Add(name, result);
            }
            return(result);
        }
        public static void loadChildrenForNode(CCNode prntNode, PlistDictionary dict)
        {
            PlistArray childrenInfo = dict["children"].AsArray;

            if (null != childrenInfo)
            {
                foreach (PlistDictionary childInfo in childrenInfo)
                {
                    /*CCNode node =*/ LHNodeProtocolImp.createLHNodeWithDictionary(childInfo, prntNode);
                }
            }
        }
        public void createShapeWithDictionary(PlistDictionary dict, PlistArray shapePoints, b2Body body, CCNode node, LHScene scene, CCPoint scale)
        {
            _shapeID   = dict ["shapeID"].AsInt;
            _shapeName = dict ["name"].AsString;

            int flipx = scale.X < 0 ? -1 : 1;
            int flipy = scale.Y < 0 ? -1 : 1;


            for (int f = 0; f < shapePoints.Count; ++f)
            {
                PlistArray fixPoints = shapePoints [f].AsArray;
                int        count     = fixPoints.Count;
                if (count > 2)
                {
                    b2Vec2[]       verts    = new b2Vec2[count];
                    b2PolygonShape shapeDef = new b2PolygonShape();

                    int i = 0;
                    for (int j = count - 1; j >= 0; --j)
                    {
                        int idx = (flipx < 0 && flipy >= 0) || (flipx >= 0 && flipy < 0) ? count - i - 1 : i;

                        String  pointStr = fixPoints [j].AsString;
                        CCPoint point    = CCPoint.Parse(pointStr);

                        point.X *= scale.X;
                        point.Y *= scale.Y;

                        point.Y = -point.Y;

                        b2Vec2 vec = new b2Vec2(point.X, point.Y);

                        verts[idx] = vec;
                        ++i;
                    }

                    if (LHValidateCentroid(verts, count))
                    {
                        shapeDef.Set(verts, count);

                        b2FixtureDef fixture = new b2FixtureDef();

                        LHSetupb2FixtureWithInfo(fixture, dict);

                        fixture.userData = this;
                        fixture.shape    = shapeDef;
                        body.CreateFixture(fixture);
                    }
                }
            }
        }
Beispiel #18
0
    public PlistDocument(string plistText)
    {
        XmlDocument xmlDocument = new XmlDocument();

        xmlDocument.LoadXml(plistText);

        if (IsAvailable(xmlDocument) == false)
        {
            return;
        }

        this.rootDictionary = new PlistDictionary(xmlDocument.DocumentElement.FirstChild);
    }
Beispiel #19
0
        public LHBackUINode(PlistDictionary dict, CCNode prnt) : base()
        {
            Debug.WriteLine("DID LOAD BACK UI NODE");

            prnt.AddChild(this);

            _nodeProtocolImp.loadGenericInfoFromDictionary(dict, this);

            this.ZOrder   = -1;
            this.Position = new CCPoint();

            LHNodeProtocolImp.loadChildrenForNode(this, dict);
        }
Beispiel #20
0
        public static Version GetXcodeVersion(string sdkRoot)
        {
            try {
                var pDict = PlistDictionary.Load(Path.Combine(
                                                     sdkRoot,
                                                     "Contents",
                                                     "Info.plist"));
                var shortVersion = (string)pDict ["CFBundleShortVersionString"];

                return(Version.Parse(shortVersion));
            } catch (Exception e) {
                Log.Error(TAG, e);
                return(null);
            }
        }
        //--------------------------------------------------------------------------------------------------------------
        public static LHScene createWithContentOfFile(string plistLevelFile, CCWindow mainWindow, CCApplication application)
        {
            PlistDictionary dict = CCContentManager.SharedContentManager.Load <PlistDocument> (plistLevelFile).Root.AsDictionary;

            if (null == dict)
            {
                Debug.WriteLine("\nERROR: Could not load level file %s. The file does not appear to exist.\n", plistLevelFile);
                return(null);
            }

            var aspect = dict ["aspect"].AsInt;

            if (aspect == 0)           //exact fit
            {
                CCSize winSize = CCSize.Parse(dict ["designResolution"].AsString);
                CCScene.SetDefaultDesignResolution(winSize.Width, winSize.Height, CCSceneResolutionPolicy.ExactFit);
            }
            else if (aspect == 1)           //no borders
            {
                CCSize winSize = CCSize.Parse(dict ["designResolution"].AsString);
                CCScene.SetDefaultDesignResolution(winSize.Width, winSize.Height, CCSceneResolutionPolicy.NoBorder);
            }
            else if (aspect == 2)           //show all
            {
                CCSize winSize = mainWindow.WindowSizeInPixels;
                CCScene.SetDefaultDesignResolution(winSize.Width, winSize.Height, CCSceneResolutionPolicy.ShowAll);
            }

            PlistArray devsInfo = dict["devices"].AsArray;

            if (null == devsInfo)
            {
                Debug.WriteLine("\nERROR: Level doesn't contain valid devices.\n");
                return(null);
            }

            foreach (PlistDictionary devInf in devsInfo)
            {
                string suffix = dict ["suffix"].AsString;
                application.ContentSearchPaths.Add(suffix);
            }

            application.ContentSearchPaths.Add("hd");
            application.ContentSearchPaths.Add("568");

            return(new LHScene(dict, plistLevelFile, mainWindow));
        }
        public void createCircleWithDictionary(PlistDictionary dict, b2Body body, CCNode node, LHScene scene, CCSize size)
        {
            _shapeID   = dict ["shapeID"].AsInt;
            _shapeName = dict ["name"].AsString;

            b2CircleShape shape = new b2CircleShape();

            shape.Radius = size.Width * 0.5f;

            b2FixtureDef fixture = new b2FixtureDef();

            LHSetupb2FixtureWithInfo(fixture, dict);

            fixture.userData = this;
            fixture.shape    = shape;

            body.CreateFixture(fixture);
        }
        public void createRectangleWithDictionary(PlistDictionary dict, b2Body body, CCNode node, LHScene scene, CCSize size)
        {
            _shapeID   = dict ["shapeID"].AsInt;
            _shapeName = dict ["name"].AsString;

            b2PolygonShape shape = new b2PolygonShape();

            shape.SetAsBox(size.Width * 0.5f, size.Height * 0.5f);

            b2FixtureDef fixture = new b2FixtureDef();

            LHSetupb2FixtureWithInfo(fixture, dict);

            fixture.userData = this;
            fixture.shape    = shape;

            body.CreateFixture(fixture);
        }
        public void AddAnimationsWithDictionary(PlistDictionary dictionary)
        {
            PlistDictionary animations = dictionary["animations"].AsDictionary;

            if (animations == null)
            {
                CCLog.Log("cocos2d: CCAnimationCache: No animations were found in provided dictionary.");
                return;
            }

            PlistDictionary properties = dictionary["properties"].AsDictionary;
            if (properties != null)
            {
                int version = properties["format"].AsInt;
                PlistArray spritesheets = properties["spritesheets"].AsArray;

                foreach (PlistObjectBase pObj in spritesheets)
                {
                    string name = pObj.AsString;
                    CCSpriteFrameCache.SharedSpriteFrameCache.AddSpriteFramesWithFile(name);
                }

                switch (version)
                {
                    case 1:
                        ParseVersion1(animations);
                        break;

                    case 2:
                        ParseVersion2(animations);
                        break;

                    default:
                        Debug.Assert(false, "Invalid animation format");
                        break;
                }
            }
        }
Beispiel #25
0
        public static LHSprite nodeWithDictionary(PlistDictionary dict, CCNode prnt)
        {
            LHScene scene = ((LHNodeProtocol)prnt).getScene();

            string imageFileName     = dict ["imageFileName"].AsString;
            string relativeImagePath = dict ["relativeImagePath"].AsString;


//			string imagePath = LHUtils.imagePathWithFilename (imageFileName, relativeImagePath, scene.currentDeviceSuffix (false));
//			string imageDevPath = LHUtils.imagePathWithFilename (imageFileName, relativeImagePath, scene.currentDeviceSuffix (true));

            string imagePath    = LHUtils.imagePathWithFilename(imageFileName, "", scene.currentDeviceSuffix(false));
            string imageDevPath = LHUtils.imagePathWithFilename(imageFileName, "", scene.currentDeviceSuffix(true));


            CCTexture2D texture = scene.textureWithImagePath(imagePath);

            CCSpriteFrame spriteFrame = null;

            string imageFilePath   = imageDevPath;
            string spriteFrameName = dict["spriteName"].AsString;

            if (spriteFrameName != null)
            {
                LHSprite.cacheSpriteFramesInfo(imageDevPath, scene);
                spriteFrame = CCSpriteFrameCache.SharedSpriteFrameCache [spriteFrameName];
            }
            else
            {
                //spriteFrame = [texture createSpriteFrame];
            }

            LHSprite spr = new LHSprite(spriteFrame, dict, prnt, spriteFrameName, imageDevPath);


            return(spr);
        }
		public void Load (IPhoneProject proj)
		{
			devRegionEntry.Text = proj.BundleDevelopmentRegion ?? "";
			bundleIdEntry.Text = proj.BundleIdentifier ?? "";
			bundleVersionEntry.Text = proj.BundleVersion ?? "";
			displayNameEntry.Text = proj.BundleDisplayName ?? "";
			
			mainNibPicker.Project         = iPadNibPicker.Project         = proj;
			mainNibPicker.EntryIsEditable = iPadNibPicker.EntryIsEditable = true;
			mainNibPicker.DefaultFilter   = iPadNibPicker.DefaultFilter   = "*.xib";
			
			mainNibPicker.DialogTitle = GettextCatalog.GetString ("Select main interface file...");
			mainNibPicker.SelectedFile = proj.MainNibFile.ToString () ?? "";
			
			iPadNibPicker.DialogTitle = GettextCatalog.GetString ("Select iPad interface file...");
			iPadNibPicker.SelectedFile = proj.MainNibFileIPad.ToString () ?? "";
			
			targetDevicesCombo.AppendText (GettextCatalog.GetString ("iPhone and iPad"));
			targetDevicesCombo.AppendText (GettextCatalog.GetString ("iPhone only"));
			targetDevicesCombo.AppendText (GettextCatalog.GetString ("iPad only"));
			
			SupportedDevices = proj.SupportedDevices;
			
			ProjectFileEntry [] pickers = {
				iphoneIconPicker,
				iphoneIconHighPicker,
				ipadIconPicker,
				settingsIconPicker,
				settingsIconHighPicker,
				ipadSpotlightIconPicker,
			};
			
			foreach (var p in pickers) {
				p.Project = proj;
				p.DefaultFilter = "*.png";
				p.EntryIsEditable = true;
				p.DialogTitle = GettextCatalog.GetString ("Select icon...");
			}
			
			iphoneIconPicker.SelectedFile = proj.BundleIcon.ToString () ?? "";
			iphoneIconHighPicker.SelectedFile = proj.BundleIconHigh.ToString () ?? "";
			ipadIconPicker.SelectedFile = proj.BundleIconIPad.ToString () ?? "";
			settingsIconPicker.SelectedFile = proj.BundleIconSpotlight.ToString () ?? "";
			settingsIconHighPicker.SelectedFile = proj.BundleIconSpotlightHigh.ToString () ?? "";
			ipadSpotlightIconPicker.SelectedFile = proj.BundleIconIPadSpotlight.ToString () ?? "";
			
			badPlist = false;
			try {
				var pf = proj.GetInfoPlist ();
				var doc = new PlistDocument ();
				doc.LoadFromXmlFile (pf.FilePath);
				var dict = doc.Root as PlistDictionary;
				if (dict == null)
					doc.Root = dict = new PlistDictionary ();
				
				var orientationArr = dict.TryGetValue (OrientationUtil.KEY) as PlistArray;
				var ipadOrientationArr = dict.TryGetValue (OrientationUtil.KEY_IPAD) as PlistArray;
				
				LoadOrientationsCombo (supportedOrientationsCombo, orientationArr);
				LoadOrientationsCombo (iPadOrientationsCombo, ipadOrientationArr);
			} catch (Exception ex) {
				badPlist = true;
				MonoDevelop.Ide.MessageService.ShowException (ex, "Error reading Info.plist. Some settings may not be saved.");
			}
			
			HandleTargetDevicesComboChanged (null, null);
		}
        public void loadPhysicsInfoFromDictionary(PlistDictionary dict, CCNode nd)
        {
            _node = nd;

            if (null != dict)
            {
                int shapeType = dict ["shape"].AsInt;
                int type      = dict ["type"].AsInt;

                LHScene scene = ((LHNodeProtocol)_node).getScene();

                b2World world = scene.getBox2dWorld();

                var bodyDef = new b2BodyDef();
                bodyDef.type = (b2BodyType)type;

                CCPoint position = _node.Parent.ConvertToWorldspace(_node.Position);
//				bodyDef.position = scene.metersFromPoint (position);
                bodyDef.position = new b2Vec2(position.X, position.Y);

                float angle = CCNodeTransforms.GlobalXAngleFromLocalAngle(_node, _node.RotationX);
                bodyDef.angle = LHUtils.LH_DEGREES_TO_RADIANS(angle);

                bodyDef.userData = _node;

                _body          = world.CreateBody(bodyDef);
                _body.UserData = _node;


                Debug.WriteLine("BODY:" + _body);


                _body.SetFixedRotation(dict ["fixedRotation"].AsBool);
                //_body->SetGravityScale

                _body.SetSleepingAllowed(dict ["allowSleep"].AsBool);
                _body.SetBullet(dict ["bullet"].AsBool);

                _body.AngularDamping  = dict ["angularDamping"].AsFloat;
                _body.AngularVelocity = -360.0f * dict ["angularVelocity"].AsFloat;
                _body.LinearDamping   = dict ["linearDamping"].AsFloat;

                CCPoint linearVel = CCPoint.Parse(dict ["linearVelocity"].AsString);
                _body.LinearVelocity = new b2Vec2(linearVel.X, linearVel.Y);


                CCSize size = _node.ContentSize;
//				size.Width = scene.metersFromValue (size.Width);
//				size.Height = scene.metersFromValue (size.Height);

                CCPoint scale = new CCPoint(_node.ScaleX, _node.ScaleY);
                scale = CCNodeTransforms.ConvertToWorldScale(_node, scale);

                previousScale = scale;


                size.Width  *= scale.X;
                size.Height *= scale.Y;


                PlistDictionary fixInfo = dict ["genericFixture"].AsDictionary;

                Debug.WriteLine("FIX INFO " + fixInfo);

                Debug.WriteLine("SHAPE TYPE " + shapeType);

                if (shapeType == 0)               //RECTANGLE
                {
                    LHBodyShape shape = new LHBodyShape();
                    shape.createRectangleWithDictionary(fixInfo, _body, _node, scene, size);

                    _subShapes.Add(shape);
                }
                else if (shapeType == 1)               //CIRCLE
                {
                    LHBodyShape shape = new LHBodyShape();
                    shape.createCircleWithDictionary(fixInfo, _body, _node, scene, size);

                    _subShapes.Add(shape);
                }
                else if (shapeType == 4)               //oval
                {
                    PlistArray shapePoints = dict ["ovalShape"].AsArray;
                    if (shapePoints != null)
                    {
                        LHBodyShape shape = new LHBodyShape();
                        shape.createShapeWithDictionary(fixInfo, shapePoints, _body, _node, scene, scale);
                        _subShapes.Add(shape);
                    }
                }
                else if (shapeType == 5)               //traced
                {
                    String fixUUID = dict ["fixtureUUID"].AsString;

                    Debug.WriteLine("TRACED " + fixUUID);

                    PlistArray shapePoints = scene.tracedFixturesWithUUID(fixUUID);

                    Debug.WriteLine("RETURNS " + shapePoints);

                    if (shapePoints == null)
                    {
                        //CHECK IN ASSET
                        //LHAsset asset = _node.assetParent;
                        ///
                    }

                    if (shapePoints != null)
                    {
                        LHBodyShape shape = new LHBodyShape();

                        Debug.WriteLine("WE HAVE A TRACED SHAPE");

                        shape.createShapeWithDictionary(fixInfo, shapePoints, _body, _node, scene, scale);

                        _subShapes.Add(shape);
                    }
                }
                else if (shapeType == 6)               //editor
                {
                    LHSprite sprite = (LHSprite)_node;


                    if (sprite != null && sprite.GetType() == typeof(LHSprite))
                    {
                        String imageFile = sprite.getImageFilePath();

                        imageFile = LHUtils.stripExtension(imageFile);

                        Debug.WriteLine("WE HAVE AN EDITOR SHAPE for sprite " + sprite + " node " + _node + " tst " + imageFile);


                        PlistDictionary bodyInfo = scene.getEditorBodyInfoForSpriteName(sprite.getSpriteFrameName(), imageFile);

                        Debug.WriteLine("WE HAVE BODY INFO " + bodyInfo);

                        if (bodyInfo != null)
                        {
                            PlistArray fixturesInfo = bodyInfo ["shapes"].AsArray;

                            for (int i = 0; i < fixturesInfo.Count; ++i)
                            {
                                PlistDictionary shapeInfo = fixturesInfo [i].AsDictionary;

                                Debug.WriteLine("SHAPE INFO " + shapeInfo);

                                LHBodyShape shape = new LHBodyShape();

                                shape.createEditorWithDictionary(shapeInfo, _body, _node, scene, scale);

                                _subShapes.Add(shape);
                            }
                        }
                    }
                }

//				if (dict.ContainsKey ("alpha")) {
//					_node.Opacity = (byte)dict ["alpha"].AsFloat;
//				}
            }
        }
        private void ProcessPlist(XmlReader reader)
        {   
            // create null plist object
            PlistObjectBase rootDict = null;
            
            // loop through reader
            while (reader.Read())
            {
                // node type is not an Element ignore and loop again.
                if (reader.NodeType != XmlNodeType.Element) continue;
                // node type is element, loop through xml data recursively.
                rootDict = LoadFromNode(reader); 
             }
             
            // assign loaded plist as sheet.
             _sheet = (PlistDictionary)rootDict;
            

        }
        private void ParseVersion2(PlistDictionary animations)
        {
            CCSpriteFrameCache frameCache = CCSpriteFrameCache.SharedSpriteFrameCache;

            foreach (var pElement in animations)
            {
                string name = pElement.Key;
                PlistDictionary animationDict = pElement.Value.AsDictionary;

                int loops = animationDict["loops"].AsInt;
                bool restoreOriginalFrame = animationDict["restoreOriginalFrame"].AsBool;

                PlistArray frameArray = animationDict["frames"].AsArray;

                if (frameArray == null)
                {
                    CCLog.Log(
                        "cocos2d: CCAnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.",
                        name);
                    continue;
                }

                // Array of AnimationFrames
                var array = new List<CCAnimationFrame>(frameArray.Count);

                foreach (PlistObjectBase pObj in frameArray)
                {
                    PlistDictionary entry = pObj.AsDictionary;

                    string spriteFrameName = entry["spriteframe"].AsString;
                    CCSpriteFrame spriteFrame = frameCache.SpriteFrameByName(spriteFrameName);

                    if (spriteFrame == null)
                    {
                        CCLog.Log(
                            "cocos2d: CCAnimationCache: Animation '%s' refers to frame '%s' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.",
                            name, spriteFrameName);

                        continue;
                    }

                    float delayUnits = entry["delayUnits"].AsFloat;
                    PlistDictionary userInfo = entry["notification"].AsDictionary;

                    var animFrame = new CCAnimationFrame();
                    animFrame.InitWithSpriteFrame(spriteFrame, delayUnits, userInfo);

                    array.Add(animFrame);
                }

                float delayPerUnit = animationDict["delayPerUnit"].AsFloat;
                var animation = new CCAnimation();
                animation.InitWithAnimationFrames(array, delayPerUnit, (uint) loops);

                animation.RestoreOriginalFrame = restoreOriginalFrame;

                SharedAnimationCache.AddAnimation(animation, name);
            }
        }
        protected override BuildResult Build(IProgressMonitor monitor, SolutionEntityItem item, ConfigurationSelector configuration)
        {
            MonobjcProject proj = item as MonobjcProject;
            if (proj == null || proj.CompileTarget != CompileTarget.Exe)
                return base.Build(monitor, item, configuration);

            BuildResult result = base.Build(monitor, item, configuration);
            if (result.ErrorCount > 0)
                return result;

            var conf = (MonobjcProjectConfiguration) proj.GetConfiguration(configuration);

            // Create directories
            monitor.BeginTask("Creating application bundle", 0);
            foreach (var path in new [] { conf.ResourcesDirectory, conf.MacOSDirectory }) {
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
            }
            monitor.EndTask();

            string exeName = Path.GetFileNameWithoutExtension(conf.CompiledOutputName);

            // Write Info.plist into 'Contents' directory

            monitor.BeginTask("Updating application manifest", 0);
            var doc = new PlistDocument();
            var docRoot = new PlistDictionary();
              			docRoot["CFBundleExecutable"]            = exeName;
            docRoot["CFBundleInfoDictionaryVersion"] = "6.0";
            docRoot["CFBundlePackageType"]           = "APPL";
            docRoot["CFBundleName"]                  = proj.BundleDisplayName ?? proj.Name;
            docRoot["CFBundleDisplayName"]           = proj.BundleDisplayName ?? proj.Name;
            docRoot["CFBundleIdentifier"]            = proj.BundleIdentifier ?? String.Format("com.yourcompany.{0}", proj.Name);
            docRoot["CFBundleVersion"]               = proj.BundleVersion ?? "1.0";
            docRoot["CFBundleDevelopmentRegion"]     = proj.BundleDevelopmentRegion ?? "English";

            FilePath icon = proj.BundleIcon.ToRelative (proj.BaseDirectory);
            if (!(icon.IsNullOrEmpty || icon.ToString () == "."))
                docRoot["CFBundleIconFile"] = icon.FileName;

            if (!String.IsNullOrEmpty (proj.MainNibFile.ToString ()))
                docRoot["NSMainNibFile"] = Path.GetFileNameWithoutExtension(proj.MainNibFile.ToString ());

            doc.Root = docRoot;

            var plistOut = conf.ContentsDirectory.Combine("Info.plist");
            using (XmlTextWriter writer = new XmlTextWriter(plistOut, Encoding.UTF8)) {
                doc.Write(writer);
            }
            monitor.EndTask();

            // Copy project binary into 'Resources' directory
            monitor.BeginTask("Copying application binary", 0);
            File.Copy(conf.CompiledOutputName, conf.ResourcesDirectory.Combine(conf.CompiledOutputName.FileName), true);
            if (File.Exists(conf.CompiledOutputName + ".mdb"))
                File.Copy(conf.CompiledOutputName + ".mdb", conf.ResourcesDirectory.Combine(conf.CompiledOutputName.FileName + ".mdb"), true);
            monitor.EndTask();

            // Copy references into 'Resources' directory
            var references = BuildUtils.GetReferencesFilePairs(proj, configuration);
            foreach (var pair in references) {
                pair.EnsureOutputDirectory();
                monitor.Log.WriteLine("Copying '{0}' to '{1}'", pair.Input, pair.Output);
                File.Copy(pair.Input, pair.Output, true);
                monitor.Step(1);
            }
            monitor.EndTask();

            // Write launcher script into 'MacOS' directory
            monitor.BeginTask("Writing launcher script", 0);
            string scriptPath = conf.MacOSDirectory.Combine(exeName);
            var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("LaunchScript.sh");
            using (StreamReader reader = new StreamReader(stream)) {
                using (StreamWriter writer = new StreamWriter(scriptPath)) {
                    writer.Write(reader.ReadToEnd());
                }
            }

            // Make executable (755)
            new UnixFileInfo(scriptPath).FileAccessPermissions = FileAccessPermissions.UserReadWriteExecute |
                FileAccessPermissions.GroupRead | FileAccessPermissions.GroupExecute |
                FileAccessPermissions.OtherRead | FileAccessPermissions.OtherExecute;

            monitor.EndTask();

            return result;
        }
Beispiel #31
0
        public static bool EqualObject(object x, object y, double deltaReal, double deltaDateSeconds)
        {
            if (x.GetType() != y.GetType())
            {
                return(false);
            }

            if (x is bool || x is int || x is string)
            {
                bool eq = x.Equals(y);
                return(eq);
            }

            if (x is byte[])
            {
                byte[] xbyte = x as byte[];
                byte[] ybyte = y as byte[];
                if (xbyte.Length != ybyte.Length)
                {
                    return(false);
                }
                for (int i = 0; i < xbyte.Length; ++i)
                {
                    if (xbyte[i] != ybyte[i])
                    {
                        return(false);
                    }
                }
                return(true);
                // bool eq = (x as byte[]).SequenceEqual(y as byte[]);
                // return eq;
            }
            if (x is double)
            {
                bool eq = Math.Abs((double)x - (double)y) < deltaReal;
                return(eq);
            }
            if (x is DateTime)
            {
                var  deltaTime = (DateTime)x - (DateTime)y;
                bool eq        = Math.Abs(deltaTime.TotalSeconds) < deltaDateSeconds;
                return(eq);
            }

            if (x is PlistList)
            {
                PlistList xList = x as PlistList;
                PlistList yList = y as PlistList;
                if (xList.Count != yList.Count)
                {
                    return(false);
                }
                for (int i = 0; i < xList.Count; ++i)
                {
                    if (EqualObject(xList[i], yList[i], deltaReal, deltaDateSeconds) == false)
                    {
                        return(false);
                    }
                }
                return(true);
            }
            if (x is PlistDictionary)
            {
                PlistDictionary xDict = x as PlistDictionary;
                PlistDictionary yDict = y as PlistDictionary;
                if (xDict.Count != yDict.Count)
                {
                    return(false);
                }

                foreach (var kv in xDict)
                {
                    if (yDict.ContainsKey(kv.Key) == false)
                    {
                        return(false);
                    }
                    var yValue = yDict[kv.Key];
                    if (EqualObject(kv.Value, yValue, deltaReal, deltaDateSeconds) == false)
                    {
                        return(false);
                    }
                }
                return(true);
            }
            throw new PlistException("undefined data type");
        }
		public void Store (IPhoneProject proj)
		{
			proj.BundleDevelopmentRegion = NullIfEmpty (devRegionEntry.Text);
			proj.BundleIdentifier = NullIfEmpty (bundleIdEntry.Text);
			proj.BundleVersion = NullIfEmpty (bundleVersionEntry.Text);
			proj.BundleDisplayName = NullIfEmpty (displayNameEntry.Text);
			proj.MainNibFile = NullIfEmpty (mainNibPicker.SelectedFile);
			proj.MainNibFileIPad = NullIfEmpty (iPadNibPicker.SelectedFile);
			
			proj.BundleIcon = NullIfEmpty (iphoneIconPicker.SelectedFile);
			proj.BundleIconHigh = NullIfEmpty (iphoneIconHighPicker.SelectedFile);
			proj.BundleIconIPad = NullIfEmpty (ipadIconPicker.SelectedFile);
			proj.BundleIconSpotlight = NullIfEmpty (settingsIconPicker.SelectedFile);
			proj.BundleIconSpotlightHigh = NullIfEmpty (settingsIconHighPicker.SelectedFile);
			proj.BundleIconIPadSpotlight = NullIfEmpty (ipadSpotlightIconPicker.SelectedFile);
			
			proj.SupportedDevices = SupportedDevices;
			
			if (badPlist)
				return;
			try {
				var pf = proj.GetInfoPlist ();
				var doc = new PlistDocument ();
				doc.LoadFromXmlFile (pf.FilePath);
				var dict = doc.Root as PlistDictionary;
				if (dict == null)
					doc.Root = dict = new PlistDictionary ();
				
				var orientations = SaveOrientationsCombo (supportedOrientationsCombo);
				if (orientations != null)
					dict [OrientationUtil.KEY] = orientations;
				else
					dict.Remove (OrientationUtil.KEY);
				
				var iPadOrientations = SaveOrientationsCombo (iPadOrientationsCombo);
				if (proj.SupportedDevices == TargetDevice.IPhoneAndIPad && iPadOrientations != null)
					dict [OrientationUtil.KEY_IPAD] = iPadOrientations;
				else
					dict.Remove (OrientationUtil.KEY_IPAD);
				
				doc.WriteToFile (pf.FilePath);
			} catch (Exception ex) {
				badPlist = true;
				MonoDevelop.Ide.MessageService.ShowException (ex, "Error saving Info.plist.");
			}
		}
        public override bool Execute()
        {
            string displayName = DisplayName ?? Name;
            string identifier  = Identifier ?? String.Format("com.yourcompany.{0}", Name);
            string version     = Version ?? "1.0";
            string region      = DevelopmentRegion ?? "English";

            var doc = new PlistDocument();
            var docRoot = new PlistDictionary();
              			docRoot["CFBundleExecutable"]            = ExeName;
            docRoot["CFBundleInfoDictionaryVersion"] = "6.0";
            docRoot["CFBundlePackageType"]           = "APPL";
            docRoot["CFBundleName"]                  = displayName;
            docRoot["CFBundleDisplayName"]           = displayName;
            docRoot["CFBundleIdentifier"]            = identifier;
            docRoot["CFBundleVersion"]               = version;
            docRoot["CFBundleDevelopmentRegion"]     = region;

            if (!String.IsNullOrEmpty(Icon))
                docRoot["CFBundleIconFile"] = Icon;

            if (!String.IsNullOrEmpty(MainNibFile))
                docRoot["NSMainNibFile"] = Path.GetFileNameWithoutExtension(MainNibFile);

            doc.Root = docRoot;

            using (XmlTextWriter writer = new XmlTextWriter(FileName, Encoding.UTF8)) {
                doc.Write(writer);
            }

            Log.LogMessage("Wrote {0}", FileName);

            return true;
        }
Beispiel #34
0
        static void cacheSpriteFramesInfo(string imageDevPath, LHScene scene)
        {
            string sceneRelative = scene.relativePath;
            string curDevSuffix  = scene.currentDeviceSuffix(true);

            string atlasName = LHUtils.stripExtension(imageDevPath);
//			string atlasName = Path.GetFileNameWithoutExtension(imageDevPath);

            string atlasPlist = atlasName + ".plist";
//			string atlasPlist = Path.ChangeExtension (atlasName, "plist");

            string sceneSuf = sceneRelative + curDevSuffix;


//			atlasPlist = sceneSuf + atlasPlist;

//			Debug.WriteLine ("atlasPlist");
//			Debug.WriteLine (atlasPlist);


//			string sceneSuf = Path.Combine (sceneRelative, curDevSuffix);
//			atlasPlist = Path.Combine (sceneSuf, atlasPlist);



            CCSpriteFrameCache cache = CCSpriteFrameCache.SharedSpriteFrameCache;

            cache.AddSpriteFrames(atlasPlist);


            atlasName = sceneRelative + atlasName;
//			atlasName = Path.Combine (sceneRelative, atlasName);

            if (false == scene.hasEditorBodyInfoForImageFilePath(atlasName))
            {
                string path = CCFileUtils.FullPathFromRelativePath(atlasPlist);

                PlistDocument   document = CCContentManager.SharedContentManager.Load <PlistDocument>(path);
                PlistDictionary dict     = document.Root.AsDictionary;

                PlistDictionary framesDict = dict ["frames"].AsDictionary;

                foreach (var pair in framesDict)
                {
                    string          sprName = pair.Key;
                    PlistDictionary frmInfo = pair.Value.AsDictionary;

                    if (null != frmInfo)
                    {
                        PlistDictionary bodyInfo = frmInfo ["body"].AsDictionary;

                        if (null != bodyInfo)
                        {
                            Debug.WriteLine("CACHING BODY " + sprName + " atlas " + atlasName + " body " + bodyInfo);

                            scene.setEditorBodyInfoForSpriteName(sprName, atlasName, bodyInfo);
                        }
                    }
                }
            }
        }
 private PlistDictionary LoadDictionaryContents(XmlReader reader, PlistDictionary dict)
 {
     Debug.Assert(reader.NodeType == XmlNodeType.Element && reader.LocalName == "key");
     while (!reader.EOF && reader.NodeType == XmlNodeType.Element)
     {
         string key = reader.ReadElementString();
         while (reader.NodeType != XmlNodeType.Element && reader.Read())
             if (reader.NodeType == XmlNodeType.EndElement)
                 throw new Exception(String.Format("No value found for key {0}", key));
         PlistObjectBase result = LoadFromNode(reader);
         if (result != null)
             dict.Add(key, result);
         reader.ReadToNextSibling("key");
     }
     return dict;
 }
        public void AddSpriteFramesWithDictionary(PlistDictionary pobDictionary, CCTexture2D pobTexture, string framePrefix)
        {
            /*
            Supported Zwoptex Formats:

            ZWTCoordinatesFormatOptionXMLLegacy = 0, // Flash Version
            ZWTCoordinatesFormatOptionXML1_0 = 1, // Desktop Version 0.0 - 0.4b
            ZWTCoordinatesFormatOptionXML1_1 = 2, // Desktop Version 1.0.0 - 1.0.1
            ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+
            */

            PlistDictionary metadataDict = null;
            if (pobDictionary.ContainsKey("metadata"))
            {
                metadataDict = pobDictionary["metadata"].AsDictionary;
            }

            PlistDictionary framesDict = null;
            if (pobDictionary.ContainsKey("frames"))
            {
                framesDict = pobDictionary["frames"].AsDictionary;
            }

            int format = 0;

            // get the format
            if (metadataDict != null)
            {
                format = metadataDict["format"].AsInt;
            }

            // check the format
            if (format < 0 || format > 3)
            {
                throw (new NotSupportedException("PList format " + format + " is not supported."));
            }

            foreach (var pair in framesDict)
            {
                PlistDictionary frameDict = pair.Value.AsDictionary;
                CCSpriteFrame spriteFrame = null;

                if (format == 0)
                {
                    float x=0f, y=0f, w=0f, h=0f;
                    x = frameDict["x"].AsFloat;
                    y = frameDict["y"].AsFloat;
                    w = frameDict["width"].AsFloat;
                    h = frameDict["height"].AsFloat;
                    float ox = 0f, oy = 0f;
                    ox = frameDict["offsetX"].AsFloat;
                    oy = frameDict["offsetY"].AsFloat;
                    int ow = 0, oh = 0;
                    ow = frameDict["originalWidth"].AsInt;
                    oh = frameDict["originalHeight"].AsInt;
                    // check ow/oh
                    if (ow == 0 || oh == 0)
                    {
                        CCLog.Log(
                            "cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist or check the 'format' metatag");
                    }
                    // abs ow/oh
                    ow = Math.Abs(ow);
                    oh = Math.Abs(oh);
                    // create frame
                    spriteFrame = new CCSpriteFrame(pobTexture,
                                                new CCRect(x, y, w, h),
                                                false,
                                                new CCPoint(ox, oy),
                                                new CCSize(ow, oh)
                        );
                }
                else if (format == 1 || format == 2)
                {
					CCRect frame = CCRect.Parse(frameDict["frame"].AsString);
                    bool rotated = false;

                    // rotation
                    if (format == 2)
                    {
                        if (frameDict.ContainsKey("rotated"))
                        {
                            rotated = frameDict["rotated"].AsBool;
                        }
                    }

                    CCPoint offset = CCPoint.Parse(frameDict["offset"].AsString);
					CCSize sourceSize = CCSize.Parse (frameDict["sourceSize"].AsString);

                    // create frame
                    spriteFrame = new CCSpriteFrame(pobTexture,
                                                frame,
                                                rotated,
                                                offset,
                                                sourceSize
                        );
                }
                else if (format == 3)
                {
                    // get values
                    CCSize spriteSize = CCSize.Parse (frameDict["spriteSize"].AsString);
                    CCPoint spriteOffset = CCPoint.Parse(frameDict["spriteOffset"].AsString);
					CCSize spriteSourceSize = CCSize.Parse (frameDict["spriteSourceSize"].AsString);
                    CCRect textureRect = CCRect.Parse(frameDict["textureRect"].AsString);
                    bool textureRotated = false;
                    if (frameDict.ContainsKey("textureRotated"))
                    {
                        textureRotated = frameDict["textureRotated"].AsBool;
                    }

                    // get aliases
                    PlistArray aliases = frameDict["aliases"].AsArray;
                    string frameKey = pair.Key;

                    foreach (PlistObjectBase item2 in aliases)
                    {
                        string oneAlias = item2.AsString;
                        if (m_pSpriteFramesAliases.Keys.Contains(oneAlias))
                        {
                            if (m_pSpriteFramesAliases[oneAlias] != null)
                            {
                                CCLog.Log("cocos2d: WARNING: an alias with name {0} already exists", oneAlias);
                            }
                        }
                        if (!m_pSpriteFramesAliases.Keys.Contains(oneAlias))
                        {
                            m_pSpriteFramesAliases.Add(oneAlias, frameKey);
                        }
                    }

                    // create frame
                    spriteFrame = new CCSpriteFrame(pobTexture,
                                                new CCRect(textureRect.Origin.X, textureRect.Origin.Y, spriteSize.Width, spriteSize.Height),
                                                textureRotated,
                                                spriteOffset,
                                                spriteSourceSize);
                }

                // add sprite frame
                string key = framePrefix + pair.Key;
                if (!_AllowFrameOverwrite && m_pSpriteFrames.ContainsKey(key))
                {
                    CCLog.Log("Frame named " + key + " already exists in the animation cache. Not overwriting existing record.");
                }
                else if (_AllowFrameOverwrite || !m_pSpriteFrames.ContainsKey(key))
                {
                    m_pSpriteFrames[key] = spriteFrame;
                }
            }
        }
		static bool SetNibProperty (PlistDictionary dict, IPhoneProject proj, FilePath mainNibProp, string propName)
		{
			if (!dict.ContainsKey (propName)) {
				if (mainNibProp.IsNullOrEmpty) {
					return false;
				} else {
					string mainNib = mainNibProp.ToRelative (proj.BaseDirectory);
					if (mainNib.EndsWith (".nib") || mainNib.EndsWith (".xib"))
					    mainNib = mainNib.Substring (0, mainNib.Length - 4).Replace ('\\', '/');
					dict[propName] = mainNib;
				}
			}
			return true;
		}
        public bool InitWithDictionary(PlistDictionary dictionary)
        {
            bool bRet = false;

            do
            {
                int maxParticles = dictionary["maxParticles"].AsInt;
                // self, not super
                if (InitWithTotalParticles(maxParticles))
                {
                    // angle
                    m_fAngle = dictionary["angle"].AsFloat;
                    m_fAngleVar = dictionary["angleVariance"].AsFloat;

                    // duration
                    m_fDuration = dictionary["duration"].AsFloat;

                    // blend function
                    m_tBlendFunc.Source = dictionary["blendFuncSource"].AsInt;
                    m_tBlendFunc.Destination = dictionary["blendFuncDestination"].AsInt;

                    // color
                    m_tStartColor.R = dictionary["startColorRed"].AsFloat;
                    m_tStartColor.G = dictionary["startColorGreen"].AsFloat;
                    m_tStartColor.B = dictionary["startColorBlue"].AsFloat;
                    m_tStartColor.A = dictionary["startColorAlpha"].AsFloat;

                    m_tStartColorVar.R = dictionary["startColorVarianceRed"].AsFloat;
                    m_tStartColorVar.G = dictionary["startColorVarianceGreen"].AsFloat;
                    m_tStartColorVar.B = dictionary["startColorVarianceBlue"].AsFloat;
                    m_tStartColorVar.A = dictionary["startColorVarianceAlpha"].AsFloat;

                    m_tEndColor.R = dictionary["finishColorRed"].AsFloat;
                    m_tEndColor.G = dictionary["finishColorGreen"].AsFloat;
                    m_tEndColor.B = dictionary["finishColorBlue"].AsFloat;
                    m_tEndColor.A = dictionary["finishColorAlpha"].AsFloat;

                    m_tEndColorVar.R = dictionary["finishColorVarianceRed"].AsFloat;
                    m_tEndColorVar.G = dictionary["finishColorVarianceGreen"].AsFloat;
                    m_tEndColorVar.B = dictionary["finishColorVarianceBlue"].AsFloat;
                    m_tEndColorVar.A = dictionary["finishColorVarianceAlpha"].AsFloat;

                    // particle size
                    m_fStartSize = dictionary["startParticleSize"].AsFloat;
                    m_fStartSizeVar = dictionary["startParticleSizeVariance"].AsFloat;
                    m_fEndSize = dictionary["finishParticleSize"].AsFloat;
                    m_fEndSizeVar = dictionary["finishParticleSizeVariance"].AsFloat;

                    // position
                    float x = dictionary["sourcePositionx"].AsFloat;
                    float y = dictionary["sourcePositiony"].AsFloat;
                    Position = new CCPoint(x, y);
                    m_tPosVar.X = dictionary["sourcePositionVariancex"].AsFloat;
                    m_tPosVar.Y = dictionary["sourcePositionVariancey"].AsFloat;

                    // Spinning
                    m_fStartSpin = dictionary["rotationStart"].AsFloat;
                    m_fStartSpinVar = dictionary["rotationStartVariance"].AsFloat;
                    m_fEndSpin = dictionary["rotationEnd"].AsFloat;
                    m_fEndSpinVar = dictionary["rotationEndVariance"].AsFloat;

                    m_nEmitterMode = (CCEmitterMode) dictionary["emitterType"].AsInt;

                    // Mode A: Gravity + tangential accel + radial accel
                    if (m_nEmitterMode == CCEmitterMode.kCCParticleModeGravity)
                    {
                        // gravity
                        modeA.gravity.X = dictionary["gravityx"].AsFloat;
                        modeA.gravity.Y = dictionary["gravityy"].AsFloat;

                        // speed
                        modeA.speed = dictionary["speed"].AsFloat;
                        modeA.speedVar = dictionary["speedVariance"].AsFloat;

                        // radial acceleration
                        modeA.radialAccel = dictionary["radialAcceleration"].AsFloat;
                        modeA.radialAccelVar = dictionary["radialAccelVariance"].AsFloat;

                        // tangential acceleration
                        modeA.tangentialAccel = dictionary["tangentialAcceleration"].AsFloat;
                        modeA.tangentialAccelVar = dictionary["tangentialAccelVariance"].AsFloat;
                    }

                        // or Mode B: radius movement
                    else if (m_nEmitterMode == CCEmitterMode.kCCParticleModeRadius)
                    {
                        modeB.startRadius = dictionary["maxRadius"].AsFloat;
                        modeB.startRadiusVar = dictionary["maxRadiusVariance"].AsFloat;
                        modeB.endRadius = dictionary["minRadius"].AsFloat;
                        modeB.endRadiusVar = 0.0f;
                        modeB.rotatePerSecond = dictionary["rotatePerSecond"].AsFloat;
                        modeB.rotatePerSecondVar = dictionary["rotatePerSecondVariance"].AsFloat;
                    }
                    else
                    {
                        Debug.Assert(false, "Invalid emitterType in config file");
                        break;
                    }

                    // life span
                    m_fLife = dictionary["particleLifespan"].AsFloat;
                    m_fLifeVar = dictionary["particleLifespanVariance"].AsFloat;

                    // emission Rate
                    m_fEmissionRate = m_uTotalParticles / m_fLife;

                    //don't get the internal texture if a batchNode is used
                    if (m_pBatchNode == null)
                    {
                        // Set a compatible default for the alpha transfer
                        m_bOpacityModifyRGB = false;

                        // texture
                        // Try to get the texture from the cache
                        string textureName = dictionary["textureFileName"].AsString;
                        string fullpath = CCFileUtils.FullPathFromRelativeFile(textureName, m_sPlistFile);

                        CCTexture2D tex = null;

                        if (!string.IsNullOrEmpty(textureName))
                        {
                            // set not pop-up message box when load image failed
                            bool bNotify = CCFileUtils.IsPopupNotify;
                            CCFileUtils.IsPopupNotify = false;
                            try
                            {
                                tex = CCTextureCache.SharedTextureCache.AddImage(fullpath);
                            }
                            catch (Exception)
                            {
                                tex = null;
                            }

                            // reset the value of UIImage notify
                            CCFileUtils.IsPopupNotify = bNotify;
                        }

                        if (tex != null)
                        {
                            Texture = tex;
                        }
                        else
                        {
                            string textureData = dictionary["textureImageData"].AsString;
                            Debug.Assert(textureData != null && textureData.Length > 0, string.Format("CCParticleSystem: textureData does not exist : {0}",textureName));

                            int dataLen = textureData.Length;
                            if (dataLen != 0)
                            {

                                var dataBytes = Convert.FromBase64String(textureData);
                                Debug.Assert(dataBytes != null, string.Format("CCParticleSystem: error decoding textureImageData : {0}",textureName));

                                var imageBytes = Inflate(dataBytes);
                                Debug.Assert(imageBytes != null, string.Format("CCParticleSystem: error init image with Data for texture : {0}",textureName));

                                using (var imageStream = new MemoryStream(imageBytes))
                                {
                                    try
                                    {
                                        Texture = CCTextureCache.SharedTextureCache.AddImage(imageStream, textureName);
                                    }
                                    catch (Exception ex)
                                    {
                                        CCLog.Log(ex.ToString());
                                        throw (new NotSupportedException("Embedded textureImageData is a format that this platform does not understand. Use PNG, GIF, or JPEG for your particle systems."));
                                    }
                                }
                            }
                        }
                        Debug.Assert(Texture != null, string.Format("CCParticleSystem: error loading the texture : {0}", textureName));
                    }
                    bRet = true;
                }
            } while (false);

            return bRet;
        }
		static BuildResult GenXcent (IProgressMonitor monitor, IPhoneSdkVersion sdkVersion, IPhoneProject proj, 
			IPhoneProjectConfiguration conf, IPhoneAppIdentity identity, out string xcentName)
		{
			xcentName = conf.CompiledOutputName.ChangeExtension (".xcent");
			
			monitor.BeginTask (GettextCatalog.GetString ("Processing entitlements file"), 0);
			
			string srcFile;
			
			if (!string.IsNullOrEmpty (conf.CodesignEntitlements)) {
				if (!File.Exists (conf.CodesignEntitlements))
					return BuildError ("Entitlements file \"" + conf.CodesignEntitlements + "\" not found.");
				srcFile = conf.CodesignEntitlements;
			} else {
				srcFile = "/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS" + sdkVersion.ToString ()
					+ ".sdk/Entitlements.plist";
			}
			
			var doc = new PlistDocument ();
			try {
				doc.LoadFromXmlFile (srcFile);
			} catch (Exception ex) {
				monitor.Log.WriteLine (ex.ToString ());
				return BuildError ("Error loading entitlements source file '" + srcFile +"'.");
			}
			
			//insert the app ID into the plist at the beginning
			var oldDict = doc.Root as PlistDictionary;
			var newDict = new PlistDictionary ();
			doc.Root = newDict;
			newDict["application-identifier"] = identity.AppID;
			var keychainGroups = new PlistArray (new [] { identity.AppID } );
			newDict["keychain-access-groups"] = keychainGroups;
			
			//merge in the user's values
			foreach (var item in oldDict) {
				//FIXME: we currently ignore these items, and write our own, but maybe we should do substitutes
				//i.e. $(AppIdentifierPrefix)$(CFBundleIdentifier)
				if (item.Key == "application-identifier") {
					var str = item.Value as PlistString;
					if (str == null || string.IsNullOrEmpty (str.Value) || str.Value.Contains ('$'))
						continue;
				} else if (item.Key == "keychain-access-groups") {
					//special handling, merge into the array
					var keyArr = item.Value as PlistArray;
					foreach (var key in keyArr) {
						var str = key as PlistString;
						if (str != null && !string.IsNullOrEmpty (str.Value) && !str.Value.Contains ('$')) {
							keychainGroups.Add (str.Value);
						}
					}
					continue;
				}
				newDict[item.Key] = item.Value;
			}
			
			//merge in the settings from the provisioning profile, skipping some
			foreach (var item in identity.Profile.Entitlements)
				if (item.Key != "application-identifier" && item.Key != "keychain-access-groups")
					newDict[item.Key] = item.Value;
			
			try {
				WriteXcent (doc, xcentName);
			} catch (Exception ex) {
				monitor.Log.WriteLine (ex.ToString ());
				return BuildError ("Error writing entitlements file '" + xcentName +"'.");
			}
			
			monitor.EndTask ();
			return null;
		}
		BuildResult MergeInfoPlist (IProgressMonitor monitor, MonoMacProject proj, MonoMacProjectConfiguration conf, 
		                            ProjectFile template, FilePath plistOut)
		{
			return MacBuildUtilities.CreateMergedPlist (monitor, template, plistOut, (PlistDocument doc) => {
				var result = new BuildResult ();
				var dict = doc.Root as PlistDictionary;
				if (dict == null)
					doc.Root = dict = new PlistDictionary ();
				
				//required keys that the user is likely to want to modify
				SetIfNotPresent (dict, "CFBundleName", proj.Name);
				SetIfNotPresent (dict, "CFBundleIdentifier", "com.yourcompany." + proj.Name);
				SetIfNotPresent (dict, "CFBundleShortVersionString", proj.Version);
				SetIfNotPresent (dict, "CFBundleVersion", "1");
				SetIfNotPresent (dict, "LSMinimumSystemVersion", "10.6");
				SetIfNotPresent (dict, "CFBundleDevelopmentRegion", "English");
				
				//required keys that the user probably should not modify
				dict["CFBundleExecutable"] = conf.LaunchScript.FileName;
				SetIfNotPresent (dict, "CFBundleInfoDictionaryVersion", "6.0");
				SetIfNotPresent (dict, "CFBundlePackageType", "APPL");
				SetIfNotPresent (dict, "CFBundleSignature", "????");
				
				return result;
			});
		}
        private PlistFile dict_to_plist(Dictionary <string, XmlNode> dict)
        {
            PlistFile plistFile = new PlistFile();

            //metadata
            plistFile.metadata.format = 0;
            if (dict.ContainsKey("metadata"))
            {
                PlistDictionary metadata = new PlistDictionary(dict["metadata"]);
                plistFile.metadata.format = metadata.GetInt("format");
                plistFile.metadata.realTextureFileName = metadata.GetString("realTextureFileName");
                plistFile.metadata.smartupdate         = metadata.GetString("smartupdate");
                plistFile.metadata.textureFileName     = metadata.GetString("textureFileName");

                plistFile.metadata.size = metadata.GetSize("size");
            }

            //frames
            PlistDictionary frames = new PlistDictionary(dict["frames"]);
            int             format = plistFile.metadata.format;

            foreach (KeyValuePair <string, XmlNode> node in frames)
            {
                PlistDictionary d     = new PlistDictionary(node.Value);
                PlistFrame      frame = new PlistFrame
                {
                    name = node.Key
                };

                if (format == 0)
                {
                    frame.frame  = d.ToRectangle();
                    frame.offset = d.ToPoint("offsetX", "offsetY");

                    frame.sourceSize        = d.ToSize("originalWidth", "originalWidth");
                    frame.sourceSize.Width  = Math.Abs(frame.sourceSize.Width);
                    frame.sourceSize.Height = Math.Abs(frame.sourceSize.Height);

                    frame.rotated = false;
                }
                else if (format == 1 || format == 2)
                {
                    frame.rotated = format == 2 ? d.GetBool("rotated") : false;

                    frame.frame = d.GetRectangle("frame");

                    frame.offset = d.GetPoint("offset");

                    frame.sourceSize = d.GetSize("sourceSize");
                }
                else if (format == 3)
                {
                    frame.rotated = d.GetBool("textureRotated");

                    frame.sourceSize = d.GetSize("spriteSourceSize");

                    frame.offset = d.GetPoint("spriteOffset");

                    Size      s = d.GetSize("spriteSize");
                    Rectangle b = d.GetRectangle("textureRect");
                    frame.frame = new Rectangle(b.X, b.Y, s.Width, s.Height);
                }
                plistFile.frames.Add(frame);
            }
            return(plistFile);
        }
Beispiel #42
0
        private static object ReadObjectBinary(byte[] bytes, ref Trailer trailer, ulong objectRef)
        {
            ulong objectAt = ReadOffset(bytes, trailer, objectRef);
            byte  headbyte = bytes[objectAt];

            int type = headbyte & 0xF0;
            int nnnn = headbyte & 0x0F;

            switch (type)
            {
            case TypeBitsBoolOrNil:      /* 0000 null, false, true*/
                switch (nnnn)
                {
                case 0x0:
                    throw new PlistException("unsupported null");

                case FalseBit:
                    return(false);

                case TrueBit:
                    return(true);

                default:
                    throw new PlistException("undefined value");
                }

            case TypeBitsInteger:      /* 0001 integer */
            {
                ulong nextAt;
                long  integer = ReadInteger(bytes, objectAt, out nextAt);
                if (integer < int.MinValue || int.MaxValue < integer)
                {
                    throw new PlistException("int overflow, we use int for simplity.");
                }
                return((int)integer);
            }

            case TypeBitsReal:      /* 0010 real */
            {
                int nnnn_bytes = TwoPowNNNN(nnnn);
                var real       = BigEndianReader.ReadNBytesReal(bytes, nnnn_bytes, objectAt + 1);
                return(real);
            }

            case TypeBitsDate:      /* 0011 date */
            {
                double   elapsed = BigEndianReader.ReadNBytesReal(bytes, 8, objectAt + 1);
                var      span    = TimeSpan.FromSeconds(elapsed);
                DateTime date    = BaseTime.Add(span).ToLocalTime();
                return(date);
            }

            case TypeBitsBinaryData:      /* 0100 data */
            {
                ulong dataLength;
                ulong dataAt;
                IntNNNNorNextInt(bytes, objectAt, nnnn, out dataLength, out dataAt);

                byte[] data = new byte[dataLength];
                Array.Copy(bytes, (long)dataAt, data, 0, (long)dataLength);
                return(data);
            }

            case TypeBitsASCIIString:      /* 0101 ascii string */
            {
                ulong asciiCount;
                ulong asciiAt;
                IntNNNNorNextInt(bytes, objectAt, nnnn, out asciiCount, out asciiAt);
                string ascii;
                if (asciiAt + asciiCount < int.MaxValue)
                {
                    ascii = System.Text.Encoding.ASCII.GetString(bytes, (int)asciiAt, (int)asciiCount);
                }
                else
                {
                    byte[] asciiBytes = new byte[asciiCount];
                    Array.Copy(bytes, (long)asciiAt, asciiBytes, 0, (long)asciiCount);
                    ascii = System.Text.Encoding.ASCII.GetString(asciiBytes, 0, (int)asciiBytes.Length);
                }
                return(ascii);
            }

            case TypeBitsUTF16String:      /* 0110 utf16 string */
            {
                ulong utf16Count;
                ulong utf16At;
                IntNNNNorNextInt(bytes, objectAt, nnnn, out utf16Count, out utf16At);
                ulong utf16byteLength = utf16Count * 2;

                string utf16;
                if (utf16At + utf16byteLength < int.MaxValue)
                {
                    utf16 = UTF16BE.GetString(bytes, (int)utf16At, (int)utf16byteLength);
                }
                else
                {
                    byte[] utf16Bytes = new byte[utf16byteLength];
                    Array.Copy(bytes, (long)utf16At, utf16Bytes, 0, (long)utf16byteLength);
                    utf16 = UTF16BE.GetString(utf16Bytes, 0, utf16Bytes.Length);
                }
                return(utf16);
            }

            case TypeBitsArray:      /* 1010 array */
            {
                ulong count;
                ulong arrayAt;
                IntNNNNorNextInt(bytes, objectAt, nnnn, out count, out arrayAt);

                int       capacity    = (int)(Math.Min(count, int.MaxValue));
                PlistList objectArray = new PlistList(capacity);
                for (ulong i = 0; i < count; ++i)
                {
                    ulong arrayObjectRef = BigEndianReader.ReadNBytesUnsignedInteger(bytes, trailer.ObjectRefSize, arrayAt + trailer.ObjectRefSize * i);
                    objectArray.Add(ReadObjectBinary(bytes, ref trailer, arrayObjectRef));
                }
                return(objectArray);
            }

            case TypeBitsDictionary:     /* 1101 dictionary */
            {
                ulong count;
                ulong dictionaryAt;
                IntNNNNorNextInt(bytes, objectAt, nnnn, out count, out dictionaryAt);
                int             capacity         = (int)(Math.Min(count, int.MaxValue));
                PlistDictionary objectDictionary = new PlistDictionary(capacity);

                /* key, key, key, value, value, value... */
                ulong keyBytes = trailer.ObjectRefSize * count;
                for (ulong i = 0; i < count; ++i)
                {
                    ulong  keyObjectRef   = BigEndianReader.ReadNBytesUnsignedInteger(bytes, trailer.ObjectRefSize, dictionaryAt + trailer.ObjectRefSize * i);
                    ulong  valueObjectRef = BigEndianReader.ReadNBytesUnsignedInteger(bytes, trailer.ObjectRefSize, dictionaryAt + keyBytes + trailer.ObjectRefSize * i);
                    string keyObject      = ReadObjectBinary(bytes, ref trailer, keyObjectRef) as string;
                    object valueObject    = ReadObjectBinary(bytes, ref trailer, valueObjectRef);
                    objectDictionary.Add(keyObject, valueObject);
                }
                return(objectDictionary);
            }

            default:
                throw new PlistException("undefined data type");
            }
        }
		BuildResult UpdateInfoPlist (IProgressMonitor monitor, IPhoneProject proj, IPhoneProjectConfiguration conf,
		                             IPhoneAppIdentity identity, ProjectFile template, string plistOut)
		{
			return MacBuildUtilities.CreateMergedPlist (monitor, template, plistOut, (PlistDocument doc) => {
				var result = new BuildResult ();
				var dict = doc.Root as PlistDictionary;
				if (dict == null)
					doc.Root = dict = new PlistDictionary ();
				
				bool sim = conf.Platform != IPhoneProject.PLAT_IPHONE;
				var sdkversion = IPhoneSdkVersion.Parse (conf.MtouchSdkVersion);
				bool v3_2_orNewer = sdkversion.CompareTo (IPhoneSdkVersion.V3_2) >= 0;
				bool v4_0_orNewer = sdkversion.CompareTo (IPhoneSdkVersion.V4_0) >= 0;
				bool supportsIPhone = (proj.SupportedDevices & TargetDevice.IPhone) != 0;
				bool supportsIPad = (proj.SupportedDevices & TargetDevice.IPad) != 0;
				
				SetIfNotPresent (dict, "CFBundleDevelopmentRegion",
					String.IsNullOrEmpty (proj.BundleDevelopmentRegion)? "English" : proj.BundleDevelopmentRegion);
				
				SetIfNotPresent (dict, "CFBundleDisplayName", proj.BundleDisplayName ?? proj.Name);
				SetIfNotPresent (dict, "CFBundleExecutable", conf.NativeExe.FileName);
				
				// < 3.2 icon
				if (supportsIPhone) {
					if (!dict.ContainsKey ("CFBundleIconFile")) {
						var icon = proj.BundleIcon.ToRelative (proj.BaseDirectory);
						if (icon.IsNullOrEmpty || icon.ToString () == ".")
							result.AddWarning ("Application bundle icon has not been set (iPhone Application options panel)");
						else
							dict ["CFBundleIconFile"] = icon.FileName;
					}
				}
				
				//newer icons
				if (v3_2_orNewer && !dict.ContainsKey ("CFBundleIconFiles")) {
					var arr = new PlistArray ();
					dict["CFBundleIconFiles"] = arr;
					
					if (supportsIPhone)
						AddIconRelativeIfNotEmpty (proj, arr, proj.BundleIcon);
					
					AddIconRelativeIfNotEmpty (proj, arr, proj.BundleIconSpotlight, "Icon-Small.png");
					if (supportsIPad) {
						AddIconRelativeIfNotEmpty (proj, arr, proj.BundleIconIPadSpotlight, "Icon-Small-50.png");
						if (!AddIconRelativeIfNotEmpty (proj, arr, proj.BundleIconIPad))
							result.AddWarning ("iPad bundle icon has not been set (iPhone Application options panel)");
					}
					
					if (v4_0_orNewer) {
						if (supportsIPhone) {
							if (!AddIconRelativeIfNotEmpty (proj, arr, proj.BundleIconHigh))
								result.AddWarning ("iPhone high res bundle icon has not been set (iPhone Application options panel)");
							AddIconRelativeIfNotEmpty (proj, arr, proj.BundleIconSpotlightHigh, "*****@*****.**");
						}
					}
				}
				
				SetIfNotPresent (dict, "CFBundleIdentifier", identity.BundleID);
				SetIfNotPresent (dict, "CFBundleInfoDictionaryVersion", "6.0");
				SetIfNotPresent (dict, "CFBundleName", proj.Name);
				SetIfNotPresent (dict, "CFBundlePackageType", "APPL");
				if (!sim)
					dict["CFBundleResourceSpecification"] = "ResourceRules.plist";
				SetIfNotPresent (dict, "CFBundleSignature", "????");
				SetIfNotPresent (dict,  "CFBundleSupportedPlatforms",
					new PlistArray () { sim? "iPhoneSimulator" : "iPhoneOS" });
				SetIfNotPresent (dict, "CFBundleVersion", proj.BundleVersion ?? "1.0");
				SetIfNotPresent (dict, "DTPlatformName", sim? "iphonesimulator" : "iphoneos");
				SetIfNotPresent (dict, "DTSDKName", IPhoneFramework.GetDTSdkName (sdkversion, sim));
				SetIfNotPresent (dict,  "LSRequiresIPhoneOS", true);
				if (v3_2_orNewer)
					SetIfNotPresent (dict,  "UIDeviceFamily", GetSupportedDevices (proj.SupportedDevices));
				SetIfNotPresent (dict, "DTPlatformVersion", IPhoneFramework.DTPlatformVersion);
				
				SetIfNotPresent (dict, "MinimumOSVersion", conf.MtouchMinimumOSVersion);
				
				SetNibProperty (dict, proj, proj.MainNibFile, "NSMainNibFile");
				if (proj.SupportedDevices == TargetDevice.IPhoneAndIPad)
					SetNibProperty (dict, proj, proj.MainNibFileIPad, "NSMainNibFile~ipad");
				
				
				if (v3_2_orNewer) {
					if (!dict.ContainsKey (OrientationUtil.KEY)) {
						result.AddWarning ("Supported orientations have not been set (iPhone Application options panel)");
					} else {
						var val = OrientationUtil.Parse ((PlistArray)dict[OrientationUtil.KEY]);
						if (!OrientationUtil.IsValidPair (val))
							result.AddWarning ("Supported orientations are not matched pairs (Info.plist)");
						if (dict.ContainsKey (OrientationUtil.KEY_IPAD)) {
							var pad = OrientationUtil.Parse ((PlistArray)dict[OrientationUtil.KEY_IPAD]);
							if (pad != Orientation.None && !OrientationUtil.IsValidPair (pad))
								result.AddWarning ("iPad orientations are not matched pairs (Info.plist)");
						}
					}
				}   
				
				return result;
			});
		}
Beispiel #44
0
 public static LHGameWorldNode nodeWithDictionary(PlistDictionary dict, CCNode prnt)
 {
     return(new LHGameWorldNode(dict, prnt));
 }
Beispiel #45
0
		private void LoadCocos2DDictionary(PlistDictionary dict, CCTexture2D texture)
		{
			
			PlistDictionary metadataDict = null;

			if (dict.ContainsKey("metadata"))
			{
				metadataDict = dict["metadata"].AsDictionary;
			}

			PlistDictionary framesDict = null;
			if (dict.ContainsKey("frames"))
			{
				framesDict = dict["frames"].AsDictionary;
			}

			// get the format
			int format = 0;
			if (metadataDict != null)
			{
				format = metadataDict["format"].AsInt;
			}

			// check the format
			if (format < 0 || format > 3)
			{
				throw (new NotSupportedException("PList format " + format + " is not supported."));
			}

			foreach (var pair in framesDict)
			{
				PlistDictionary frameDict = pair.Value.AsDictionary;
				CCSpriteFrame spriteFrame = null;

				if (format == 0)
				{
					float x = 0f, y = 0f, w = 0f, h = 0f;
					x = frameDict["x"].AsFloat;
					y = frameDict["y"].AsFloat;
					w = frameDict["width"].AsFloat;
					h = frameDict["height"].AsFloat;
					float ox = 0f, oy = 0f;
					ox = frameDict["offsetX"].AsFloat;
					oy = frameDict["offsetY"].AsFloat;
					int ow = 0, oh = 0;
					ow = frameDict["originalWidth"].AsInt;
					oh = frameDict["originalHeight"].AsInt;
					// check ow/oh
					if (ow == 0 || oh == 0)
					{
						CCLog.Log(
							"cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist or check the 'format' metatag");
					}
					// abs ow/oh
					ow = Math.Abs(ow);
					oh = Math.Abs(oh);

					// create frame
					spriteFrame = new CCSpriteFrame(
						texture,
						new CCRect(x, y, w, h),
						false,
						new CCPoint(ox, oy),
						new CCSize(ow, oh)
						);
				}
				else if (format == 1 || format == 2)
				{
					var frame = CCRect.Parse(frameDict["frame"].AsString);
					bool rotated = false;

					// rotation
					if (format == 2)
					{
						if (frameDict.ContainsKey("rotated"))
						{
							rotated = frameDict["rotated"].AsBool;
						}
					}

					var offset = CCPoint.Parse(frameDict["offset"].AsString);
					var sourceSize = CCSize.Parse(frameDict["sourceSize"].AsString);

					// create frame
					spriteFrame = new CCSpriteFrame(texture, frame, rotated, offset, sourceSize);
				}
				else if (format == 3)
				{
					var spriteSize = CCSize.Parse(frameDict["spriteSize"].AsString);
					var spriteOffset = CCPoint.Parse(frameDict["spriteOffset"].AsString);
					var spriteSourceSize = CCSize.Parse(frameDict["spriteSourceSize"].AsString);
					var textureRect = CCRect.Parse(frameDict["textureRect"].AsString);

					bool textureRotated = false;

					if (frameDict.ContainsKey("textureRotated"))
					{
						textureRotated = frameDict["textureRotated"].AsBool;
					}

					// get aliases
					var aliases = frameDict["aliases"].AsArray;

					for (int i = 0; i < aliases.Count; i++ )
					{
						string oneAlias = aliases[i].AsString;

						if (_spriteFramesAliases.ContainsKey(oneAlias))
						{
							if (_spriteFramesAliases[oneAlias] != null)
							{
								CCLog.Log("cocos2d: WARNING: an alias with name {0} already exists", oneAlias);
							}
						}

						if (!_spriteFramesAliases.ContainsKey(oneAlias))
						{
							_spriteFramesAliases.Add(oneAlias, pair.Key);
						}
					}

					// create frame
					spriteFrame = new CCSpriteFrame(
						texture,
						new CCRect(textureRect.Origin.X, textureRect.Origin.Y, spriteSize.Width, spriteSize.Height),
						textureRotated,
						spriteOffset,
						spriteSourceSize
						);
				}

				_spriteFrames[pair.Key] = spriteFrame;
			}

		}
Beispiel #46
0
 public CCSpriteSheet(PlistDictionary dictionary, CCTexture2D texture)
 {
     InitWithDictionary(dictionary, texture);
 }
        private PlistObjectBase LoadFromNode(XmlReader reader)
        {
            //Debug.Assert(reader.NodeType == XmlNodeType.Element);
            bool isEmpty = reader.IsEmptyElement;
            switch (reader.LocalName)
            {
                case "dict":
                    var dict = new PlistDictionary(true);
                    if (!isEmpty)
                    {
                        if (reader.ReadToDescendant("key"))
                            dict = LoadDictionaryContents(reader, dict);
                        reader.ReadEndElement();
                    }
                    return dict;

                case "array":
                    if (isEmpty)
                        return new PlistArray();

                    //advance to first node
                    reader.ReadStartElement();
                    while (reader.Read() && reader.NodeType != XmlNodeType.Element) ;

                    // HACK: plist data in iPods is not even valid in some cases! Way to go Apple!
                    // This hack checks to see if they really meant for this array to be a dict.
                    if (reader.LocalName == "key")
                    {
                        var ret = LoadDictionaryContents(reader, new PlistDictionary(true));
                        reader.ReadEndElement();
                        return ret;
                    }

                    var arr = new PlistArray();
                    do
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            var val = LoadFromNode(reader);
                            if (val != null)
                                arr.Add(val);
                        }
                    } while (reader.Read() && reader.NodeType != XmlNodeType.EndElement);
                    reader.ReadEndElement();
                    return arr;

                case "key":
                    return new PlistString(reader.ReadElementContentAsString());
                case "string":
                    return new PlistString(reader.ReadElementContentAsString());
                case "integer":
                    return new PlistInteger(reader.ReadElementContentAsInt());
                case "real":
                    return new PlistReal(reader.ReadElementContentAsDouble());
                case "false":
                    reader.ReadStartElement();
                    if (!isEmpty)
                        reader.ReadEndElement();
                    return new PlistBoolean(false);
                case "true":
                    reader.ReadStartElement();
                    if (!isEmpty)
                        reader.ReadEndElement();
                    return new PlistBoolean(true);
                case "data":
                    return new PlistData(reader.ReadElementContentAsString());
                case "date":
                    return new PlistDate(reader.ReadElementContentAsDateTime());
                default:
                    throw new XmlException(String.Format("Plist Node `{0}' is not supported", reader.LocalName));
            }
        }
		BuildResult UpdateInfoPlist (IProgressMonitor monitor, IPhoneSdkVersion sdkVersion, IPhoneProject proj,
			IPhoneProjectConfiguration conf, IPhoneAppIdentity identity, ProjectFile template, string plistOut)
		{
			return MacBuildUtilities.CreateMergedPlist (monitor, template, plistOut, (PlistDocument doc) => {
				var result = new BuildResult ();
				var dict = doc.Root as PlistDictionary;
				if (dict == null)
					doc.Root = dict = new PlistDictionary ();
				
				bool sim = conf.Platform != IPhoneProject.PLAT_IPHONE;
				bool v3_2_orNewer = sdkVersion >= IPhoneSdkVersion.V3_2;
				bool v3_1_orNewer = sdkVersion >= IPhoneSdkVersion.V3_1;
				bool v4_0_orNewer = sdkVersion >= IPhoneSdkVersion.V4_0;
				bool supportsIPhone = (proj.SupportedDevices & TargetDevice.IPhone) != 0;
				bool supportsIPad = (proj.SupportedDevices & TargetDevice.IPad) != 0;
				
				var sdkSettings = IPhoneFramework.GetSdkSettings (sdkVersion);
				var dtSettings = IPhoneFramework.GetDTSettings ();
				
				SetIfNotPresent (dict, "BuildMachineOSBuild", dtSettings.BuildMachineOSBuild);
				
				SetIfNotPresent (dict, "CFBundleDevelopmentRegion",
					String.IsNullOrEmpty (proj.BundleDevelopmentRegion)? "en" : proj.BundleDevelopmentRegion);
				
				SetIfNotPresent (dict, "CFBundleDisplayName", proj.BundleDisplayName ?? proj.Name);
				SetIfNotPresent (dict, "CFBundleExecutable", conf.NativeExe.FileName);
				
				// < 3.2 icon
				if (supportsIPhone) {
					if (!dict.ContainsKey ("CFBundleIconFile")) {
						var icon = proj.BundleIcon.ToRelative (proj.BaseDirectory);
						if (icon.IsNullOrEmpty || icon.ToString () == ".")
							result.AddWarning ("Application bundle icon has not been set (iPhone Application options panel)");
						else
							dict ["CFBundleIconFile"] = icon.FileName;
					}
				}
				
				//newer icons - see http://developer.apple.com/library/ios/#qa/qa2010/qa1686.html
				if (v3_2_orNewer && !dict.ContainsKey ("CFBundleIconFiles")) {
					var arr = new PlistArray ();
					dict["CFBundleIconFiles"] = arr;
					
					if (supportsIPhone)
						AddIconRelativeIfNotEmpty (proj, arr, proj.BundleIcon, "Icon.png");
					
					if (v4_0_orNewer && supportsIPhone)
						if (!AddIconRelativeIfNotEmpty (proj, arr, proj.BundleIconHigh, "*****@*****.**"))
							result.AddWarning ("iPhone high res bundle icon has not been set (iPhone Application options panel)");
					
					if (supportsIPad)
						if (!AddIconRelativeIfNotEmpty (proj, arr, proj.BundleIconIPad, "Icon-72.png"))
							result.AddWarning ("iPad bundle icon has not been set (iPhone Application options panel)");
					
					AddIconRelativeIfNotEmpty (proj, arr, proj.BundleIconSpotlight, "Icon-Small.png");
					
					if (supportsIPad)
						AddIconRelativeIfNotEmpty (proj, arr, proj.BundleIconIPadSpotlight, "Icon-Small-50.png");
					
					if (v4_0_orNewer && supportsIPhone)
						AddIconRelativeIfNotEmpty (proj, arr, proj.BundleIconSpotlightHigh, "*****@*****.**");
				}
				
				SetIfNotPresent (dict, "CFBundleIdentifier", identity.BundleID);
				SetIfNotPresent (dict, "CFBundleInfoDictionaryVersion", "6.0");
				SetIfNotPresent (dict, "CFBundleName", proj.Name);
				SetIfNotPresent (dict, "CFBundlePackageType", "APPL");
				if (!sim)
					dict["CFBundleResourceSpecification"] = "ResourceRules.plist";
				SetIfNotPresent (dict, "CFBundleSignature", "????");
				SetIfNotPresent (dict,  "CFBundleSupportedPlatforms",
					new PlistArray () { sim? "iPhoneSimulator" : "iPhoneOS" });
				SetIfNotPresent (dict, "CFBundleVersion", proj.BundleVersion ?? "1.0");
				
				if (!sim) {
					SetIfNotPresent (dict, "DTCompiler", sdkSettings.DTCompiler);
					SetIfNotPresent (dict, "DTPlatformBuild", dtSettings.DTPlatformBuild);
					SetIfNotPresent (dict, "DTSDKBuild", sdkSettings.DTSDKBuild);
				}
				SetIfNotPresent (dict, "DTPlatformName", sim? "iphonesimulator" : "iphoneos");
				if (!sim) {
					SetIfNotPresent (dict, "DTPlatformVersion", dtSettings.DTPlatformVersion);
				}
				SetIfNotPresent (dict, "DTSDKName", sim? sdkSettings.AlternateSDK : sdkSettings.CanonicalName);
				if (!sim) {
					SetIfNotPresent (dict, "DTXcode", dtSettings.DTXcode);
					SetIfNotPresent (dict, "DTXcodeBuild", dtSettings.DTXcodeBuild);
				}
				
				SetIfNotPresent (dict,  "LSRequiresIPhoneOS", true);
				if (v3_2_orNewer)
					SetIfNotPresent (dict,  "UIDeviceFamily", GetSupportedDevices (proj.SupportedDevices));
				
				if (v3_1_orNewer) {
					if (conf.MtouchArch != MtouchArch.ARMv6_ARMv7) {
						var val = conf.MtouchArch == MtouchArch.ARMv6? "armv6" : "armv7";
						var key = "UIRequiredDeviceCapabilities";
						var caps = dict.TryGetValue (key) ?? (dict[key] = new PlistArray ());
						var a = caps as PlistArray;
						if (a != null) {
							a.Add (val);
						} else {
							var d = (PlistDictionary) caps;
							d[val] = new PlistBoolean (true);
						}
					}
				}
				
				SetIfNotPresent (dict, "MinimumOSVersion", conf.MtouchMinimumOSVersion);
				
				SetNibProperty (dict, proj, proj.MainNibFile, "NSMainNibFile");
				if (proj.SupportedDevices == TargetDevice.IPhoneAndIPad)
					SetNibProperty (dict, proj, proj.MainNibFileIPad, "NSMainNibFile~ipad");
				
				
				if (v3_2_orNewer) {
					if (!dict.ContainsKey (OrientationUtil.KEY)) {
						result.AddWarning ("Supported orientations have not been set (iPhone Application options panel)");
					} else {
						var val = OrientationUtil.Parse ((PlistArray)dict[OrientationUtil.KEY]);
						if (!OrientationUtil.IsValidPair (val))
							result.AddWarning ("Supported orientations are not matched pairs (Info.plist)");
						if (dict.ContainsKey (OrientationUtil.KEY_IPAD)) {
							var pad = OrientationUtil.Parse ((PlistArray)dict[OrientationUtil.KEY_IPAD]);
							if (pad != Orientation.None && !OrientationUtil.IsValidPair (pad))
								result.AddWarning ("iPad orientations are not matched pairs (Info.plist)");
						}
					}
				}   
				
				return result;
			});
		}
Beispiel #49
0
 public static LHBackUINode nodeWithDictionary(PlistDictionary dict, CCNode prnt)
 {
     return(new LHBackUINode(dict, prnt));
 }
Beispiel #50
0
        public void Load(IPhoneProject proj)
        {
            devRegionEntry.Text     = proj.BundleDevelopmentRegion ?? "";
            bundleIdEntry.Text      = proj.BundleIdentifier ?? "";
            bundleVersionEntry.Text = proj.BundleVersion ?? "";
            displayNameEntry.Text   = proj.BundleDisplayName ?? "";

            mainNibPicker.Project         = iPadNibPicker.Project = proj;
            mainNibPicker.EntryIsEditable = iPadNibPicker.EntryIsEditable = true;
            mainNibPicker.DefaultFilter   = iPadNibPicker.DefaultFilter = "*.xib";

            mainNibPicker.DialogTitle  = GettextCatalog.GetString("Select main interface file...");
            mainNibPicker.SelectedFile = proj.MainNibFile.ToString() ?? "";

            iPadNibPicker.DialogTitle  = GettextCatalog.GetString("Select iPad interface file...");
            iPadNibPicker.SelectedFile = proj.MainNibFileIPad.ToString() ?? "";

            targetDevicesCombo.AppendText(GettextCatalog.GetString("iPhone and iPad"));
            targetDevicesCombo.AppendText(GettextCatalog.GetString("iPhone only"));
            targetDevicesCombo.AppendText(GettextCatalog.GetString("iPad only"));

            SupportedDevices = proj.SupportedDevices;

            ProjectFileEntry [] pickers =
            {
                iphoneIconPicker,
                iphoneIconHighPicker,
                ipadIconPicker,
                settingsIconPicker,
                settingsIconHighPicker,
                ipadSpotlightIconPicker,
            };

            foreach (var p in pickers)
            {
                p.Project         = proj;
                p.DefaultFilter   = "*.png";
                p.EntryIsEditable = true;
                p.DialogTitle     = GettextCatalog.GetString("Select icon...");
            }

            iphoneIconPicker.SelectedFile        = proj.BundleIcon.ToString() ?? "";
            iphoneIconHighPicker.SelectedFile    = proj.BundleIconHigh.ToString() ?? "";
            ipadIconPicker.SelectedFile          = proj.BundleIconIPad.ToString() ?? "";
            settingsIconPicker.SelectedFile      = proj.BundleIconSpotlight.ToString() ?? "";
            settingsIconHighPicker.SelectedFile  = proj.BundleIconSpotlightHigh.ToString() ?? "";
            ipadSpotlightIconPicker.SelectedFile = proj.BundleIconIPadSpotlight.ToString() ?? "";

            badPlist = false;
            try {
                var pf  = proj.GetInfoPlist();
                var doc = new PlistDocument();
                doc.LoadFromXmlFile(pf.FilePath);
                var dict = doc.Root as PlistDictionary;
                if (dict == null)
                {
                    doc.Root = dict = new PlistDictionary();
                }

                var orientationArr     = dict.TryGetValue(OrientationUtil.KEY) as PlistArray;
                var ipadOrientationArr = dict.TryGetValue(OrientationUtil.KEY_IPAD) as PlistArray;

                LoadOrientationsCombo(supportedOrientationsCombo, orientationArr);
                LoadOrientationsCombo(iPadOrientationsCombo, ipadOrientationArr);
            } catch (Exception ex) {
                badPlist = true;
                MonoDevelop.Ide.MessageService.ShowException(ex, "Error reading Info.plist. Some settings may not be saved.");
            }

            HandleTargetDevicesComboChanged(null, null);
        }
		static void SetIfNotPresent (PlistDictionary dict, string key, PlistObjectBase value)
		{
			if (!dict.ContainsKey (key))
				dict[key] = value;
		}
		static BuildResult UpdateDebugSettingsPlist (IProgressMonitor monitor, IPhoneProjectConfiguration conf,
		                                             ProjectFile template, string target)
		{
			if (template != null && template.BuildAction != BuildAction.Content)
				template = null;
			
			//if not in debug mode, make sure that the settings file is either
			//copied cleanly or deleted
			if (!conf.DebugMode) {
				if (template != null) {
					MacBuildUtilities.EnsureDirectoryForFile (target);
					File.Copy (template.FilePath, target, true);
				} else if (File.Exists (target)) {
					File.Delete (target);
				}
				return null;
			}
			
			return MacBuildUtilities.CreateMergedPlist (monitor, template, target, (PlistDocument doc) => {
				var br = new BuildResult ();
				var debuggerIP = System.Net.IPAddress.Any;
				bool sim = conf.Platform == IPhoneProject.PLAT_SIM;
				
				try {
					debuggerIP = IPhoneSettings.GetDebuggerHostIP (sim);
				} catch {
					br.AddWarning (GettextCatalog.GetString ("Could not resolve host IP for debugger settings"));
				}
				
				var dict = doc.Root as PlistDictionary;
				if (dict == null)
					doc.Root = dict = new PlistDictionary ();
				
				SetIfNotPresent (dict, "Title", "AppSettings");
				SetIfNotPresent (dict, "StringsTable", "Root");
				
				var arr = dict.TryGetValue ("PreferenceSpecifiers") as PlistArray;
				if (arr == null)
					dict["PreferenceSpecifiers"] = arr = new PlistArray ();
				
				arr.Add (new PlistDictionary (true) {
					{ "Type", "PSGroupSpecifier" },
					{ "Title", "Debug Settings" }
				});
				
				arr.Add (new PlistDictionary (true) {
					{ "Type", "PSToggleSwitchSpecifier" },
					{ "Title", "Enabled" },
					{ "Key", "__monotouch_debug_enabled" },
					{ "DefaultValue", "1" },
					{ "TrueValue", "1" },
					{ "FalseValue", "0" }
				});
				
				arr.Add (new PlistDictionary (true) {
					{ "Type", "PSTextFieldSpecifier" },
					{ "Title", "Debugger Host" },
					{ "Key", "__monotouch_debug_host" },
					{ "AutocapitalizationType", "None" },
					{ "AutocorrectionType", "No" },
					{ "DefaultValue", debuggerIP.ToString () }
				});
					
				arr.Add (new PlistDictionary (true) {
					{ "Type", "PSTextFieldSpecifier" },
					{ "Title", "Debugger Port" },
					{ "Key", "__monotouch_debug_port" },
					{ "AutocapitalizationType", "None" },
					{ "AutocorrectionType", "No" },
					{ "DefaultValue", IPhoneSettings.DebuggerPort.ToString () }
				});
					
				arr.Add (new PlistDictionary (true) {
					{ "Type", "PSTextFieldSpecifier" },
					{ "Title", "Output Port" },
					{ "Key", "__monotouch_output_port" },
					{ "AutocapitalizationType", "None" },
					{ "AutocorrectionType", "No" },
					{ "DefaultValue", IPhoneSettings.DebuggerOutputPort.ToString () }
				});
				
				return br;
			});
		}
Beispiel #53
0
        private static ulong WriteObjectBinary(Stream stream, object root, byte objectRefSize, byte[] encodeBuffer, ref ulong objectIndex, List <ulong> offsetTable)
        {
            ulong objectRef = objectIndex++;
            ulong objectAt  = (ulong)stream.Position;

            offsetTable.Add(objectAt);

            if (root == null)
            {
                throw new PlistException("unsupported null");
            }
            else if (root is bool)
            {
                if ((bool)root)
                {
                    stream.WriteByte(TypeBitsBoolOrNil | TrueBit);
                }
                else
                {
                    stream.WriteByte(TypeBitsBoolOrNil | FalseBit);
                }
            }
            else if (root is int)
            {
                WriteInteger((int)root, stream);
            }
            else if (root is double)
            {
                // real, 2^3 = 8 byte
                // 0010 0011
                // force use double
                byte headbyte = TypeBitsReal | 0x03;
                stream.WriteByte(headbyte);
                var f64 = new Float64Bits((double)root);
                f64.Write(stream);
            }
            else if (root is DateTime)
            {
                DateTime date        = (DateTime)root;
                TimeSpan elapsedSpan = date.ToUniversalTime() - BaseTime;
                double   elapsed     = elapsedSpan.TotalSeconds;

                byte headbyte = TypeBitsDate | 0x03;
                stream.WriteByte(headbyte);
                var f64 = new Float64Bits(elapsed);
                f64.Write(stream);
            }
            else if (root is string)
            {
                string text = root as string;

                byte typebit;
                int  count;
                int  writeBytes;
                if (IsASCIIEncodable(text))
                {
                    typebit    = TypeBitsASCIIString;
                    writeBytes = ASCII.GetBytes(text, 0, text.Length, encodeBuffer, 0);
                    count      = writeBytes;
                }
                else
                {
                    typebit    = TypeBitsUTF16String;
                    writeBytes = UTF16BE.GetBytes(text, 0, text.Length, encodeBuffer, 0);
                    count      = writeBytes >> 1;
                }

                if (count < 15)
                {
                    byte headbyte = (byte)(typebit | count);
                    stream.WriteByte(headbyte);
                }
                else
                {
                    byte headbyte = (byte)(typebit | 0x0F);
                    stream.WriteByte(headbyte);
                    WriteInteger((long)count, stream);
                }
                stream.Write(encodeBuffer, 0, writeBytes);
            }
            else if (root is byte[])
            {
                byte[] data    = root as byte[];
                byte   typebit = TypeBitsBinaryData;
                if (data.Length < 15)
                {
                    byte headbyte = (byte)(typebit | data.Length);
                    stream.WriteByte(headbyte);
                }
                else
                {
                    byte headbyte = (byte)(typebit | 0x0F);
                    stream.WriteByte(headbyte);
                    WriteInteger(data.LongLength, stream);
                }
                stream.Write(data, 0, data.Length);
            }
            else if (root is PlistList)
            {
                PlistList objectArray = root as PlistList;
                byte      typebit     = TypeBitsArray;
                if (objectArray.Count < 15)
                {
                    byte headbyte = (byte)(typebit | objectArray.Count);
                    stream.WriteByte(headbyte);
                }
                else
                {
                    byte headbyte = (byte)(typebit | 0x0F);
                    stream.WriteByte(headbyte);
                    WriteInteger(objectArray.Count, stream);
                }

                ulong arrayAt = (ulong)stream.Position;

                // reserve data
                ulong reserveBytes = (ulong)objectArray.Count * objectRefSize;
                for (ulong i = 0; i < reserveBytes; ++i)
                {
                    stream.WriteByte(0);
                }
                for (int i = 0; i < objectArray.Count; ++i)
                {
                    ulong arrayObjectRef = WriteObjectBinary(stream, objectArray[i], objectRefSize, encodeBuffer, ref objectIndex, offsetTable);
                    stream.Seek((long)arrayAt + i * objectRefSize, SeekOrigin.Begin);
                    BigEndianWriter.WriteNBytesUnsignedInteger(stream, arrayObjectRef, objectRefSize);
                    stream.Seek(0, SeekOrigin.End);
                }
            }
            else if (root is PlistDictionary)
            {
                PlistDictionary objectDictionary = root as PlistDictionary;
                byte            typebit          = TypeBitsDictionary;
                if (objectDictionary.Count < 15)
                {
                    byte headbyte = (byte)(typebit | objectDictionary.Count);
                    stream.WriteByte(headbyte);
                }
                else
                {
                    byte headbyte = (byte)(typebit | 0x0F);
                    stream.WriteByte(headbyte);
                    WriteInteger(objectDictionary.Count, stream);
                }

                ulong dictionaryAt = (ulong)stream.Position;

                // reserve data
                ulong reserveBytes = (ulong)objectDictionary.Count * 2 * objectRefSize;
                for (ulong j = 0; j < reserveBytes; ++j)
                {
                    stream.WriteByte(0);
                }

                /* key, key, key, value, value, value... */
                long keyBytes = objectRefSize * (long)objectDictionary.Count;
                int  i        = 0;
                foreach (var objectKeyValue in objectDictionary)
                {
                    ulong arrayKeyRef   = WriteObjectBinary(stream, objectKeyValue.Key, objectRefSize, encodeBuffer, ref objectIndex, offsetTable);
                    ulong arrayValueRef = WriteObjectBinary(stream, objectKeyValue.Value, objectRefSize, encodeBuffer, ref objectIndex, offsetTable);

                    stream.Seek((long)dictionaryAt + i * objectRefSize, SeekOrigin.Begin);
                    BigEndianWriter.WriteNBytesUnsignedInteger(stream, arrayKeyRef, objectRefSize);

                    stream.Seek((long)dictionaryAt + keyBytes + i * objectRefSize, SeekOrigin.Begin);
                    BigEndianWriter.WriteNBytesUnsignedInteger(stream, arrayValueRef, objectRefSize);
                    stream.Seek(0, SeekOrigin.End);

                    i++;
                }
            }
            else
            {
                throw new PlistException();
            }
            return(objectRef);
        }
        private void ParseVersion1(PlistDictionary animations)
        {
            CCSpriteFrameCache frameCache = CCSpriteFrameCache.SharedSpriteFrameCache;

            foreach (var pElement in animations)
            {
                PlistDictionary animationDict = pElement.Value.AsDictionary;

                PlistArray frameNames = animationDict["frames"].AsArray;
                float delay = animationDict["delay"].AsFloat;
                //CCAnimation* animation = NULL;

                if (frameNames == null)
                {
                    CCLog.Log(
                        "cocos2d: CCAnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.",
                        pElement.Key);
                    continue;
                }

                var frames = new List<CCAnimationFrame>(frameNames.Count);

                foreach (PlistObjectBase pObj in frameNames)
                {
                    string frameName = pObj.AsString;
                    CCSpriteFrame spriteFrame = frameCache.SpriteFrameByName(frameName);

                    if (spriteFrame == null)
                    {
                        CCLog.Log(
                            "cocos2d: CCAnimationCache: Animation '%s' refers to frame '%s' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.",
                            pElement.Key, frameName);
                        continue;
                    }

                    var animFrame = new CCAnimationFrame();
                    animFrame.InitWithSpriteFrame(spriteFrame, 1, null);
                    frames.Add(animFrame);
                }

                if (frames.Count == 0)
                {
                    CCLog.Log(
                        "cocos2d: CCAnimationCache: None of the frames for animation '%s' were found in the CCSpriteFrameCache. Animation is not being added to the Animation Cache.",
                        pElement.Key);
                    continue;
                }
                else if (frames.Count != frameNames.Count)
                {
                    CCLog.Log(
                        "cocos2d: CCAnimationCache: An animation in your dictionary refers to a frame which is not in the CCSpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.",
                        pElement.Key);
                }

                CCAnimation animation = CCAnimation.Create(frames, delay, 1);

                SharedAnimationCache.AddAnimation(animation, pElement.Key);
            }
        }
Beispiel #55
0
 private static XElement BuildElementXML(object root)
 {
     if (root == null)
     {
         throw new PlistException("unsupported null");
     }
     else if (root is bool)
     {
         if ((bool)root)
         {
             return(new XElement("true"));
         }
         else
         {
             return(new XElement("false"));
         }
     }
     else if (root is int)
     {
         return(new XElement("integer", root.ToString()));
     }
     else if (root is double)
     {
         return(new XElement("real", root.ToString()));
     }
     else if (root is DateTime)
     {
         DateTime date = (DateTime)root;
         var      str  = date.ToUniversalTime().ToString(DateFormat, System.Globalization.CultureInfo.InvariantCulture);
         return(new XElement("date", str));
     }
     else if (root is string)
     {
         string text = root as string;
         return(new XElement("string", text));
     }
     else if (root is byte[])
     {
         byte[] data = root as byte[];
         var    str  = System.Convert.ToBase64String(data);
         return(new XElement("data", str));
     }
     else if (root is PlistList)
     {
         PlistList objectArray = root as PlistList;
         object[]  contents    = new object[objectArray.Count];
         for (int i = 0; i < objectArray.Count; ++i)
         {
             contents[i] = BuildElementXML(objectArray[i]);
         }
         return(new XElement("array", contents));
     }
     else if (root is PlistDictionary)
     {
         PlistDictionary objectDictionary = root as PlistDictionary;
         object[]        contents         = new object[objectDictionary.Count * 2];
         int             i = 0;
         foreach (var kv in objectDictionary)
         {
             contents[i++] = new XElement("key", kv.Key);
             contents[i++] = BuildElementXML(kv.Value);
         }
         return(new XElement("dict", contents));
     }
     else
     {
         throw new PlistException("undefined data type");
     }
 }
        /*
         *  Recursive method to load xml plist data into plist objects.
         * 
         */
        private PlistObjectBase LoadFromNode(XmlReader reader)
        {
            //Console.WriteLine("Loading data from node");
            //only processes XmlNodeType.Element
            bool isEmpty = reader.IsEmptyElement;
            switch (reader.LocalName)
            {
                case "dict":
                    var dict = new PlistDictionary(true);
                    if (!isEmpty)
                    {
                        if (reader.ReadToDescendant("key"))
                            dict = LoadDictionaryContents(reader, dict);
                        reader.ReadEndElement();
                        
                    }
                    return dict;

                case "array":
                    return new PlistArray();
                case "key":
                    return new PlistString(reader.ReadElementContentAsString());
                case "string":
                    return new PlistString(reader.ReadElementContentAsString());
                case "integer":
                    return new PlistInteger(reader.ReadElementContentAsInt());
                case "real":
                    return new PlistInteger(reader.ReadElementContentAsInt());
                case "false":
                    reader.ReadStartElement();
                    if (!isEmpty)
                        reader.ReadEndElement();
                    return new PlistBoolean(false);
                case "true":
                    reader.ReadStartElement();
                    if (!isEmpty)
                        reader.ReadEndElement();
                    return new PlistBoolean(true);
                case "data":
                    return new PlistData(reader.ReadElementContentAsString());
                case "date":
                    return new PlistDate(reader.ReadElementContentAsDateTime());
                default:
                    throw new XmlException(String.Format("Plist Node `{0}' is not supported", reader.LocalName));
            }
        }
 public void AddSpriteFramesWithDictionary(PlistDictionary pobDictionary, CCTexture2D pobTexture)
 {
     AddSpriteFramesWithDictionary(pobDictionary, pobTexture, string.Empty);
 }
Beispiel #58
0
        public void InitWithDictionary(PlistDictionary dict, CCTexture2D texture)
        {
            _spriteFrames.Clear();
            _spriteFramesAliases.Clear();

			if (plistType == PlistType.SpriteKit)
				LoadAppleDictionary (dict, texture);
			else
				LoadCocos2DDictionary(dict, texture);
        }
        public void RemoveSpriteFramesFromDictionary(PlistDictionary dictionary)
        {
            PlistDictionary framesDict = dictionary["frames"].AsDictionary;
            var keysToRemove = new List<string>();

            foreach (var pair in framesDict)
            {
                if (m_pSpriteFrames.ContainsKey(pair.Key))
                {
                    keysToRemove.Remove(pair.Key);
                }
            }

            foreach (string key in keysToRemove)
            {
                m_pSpriteFrames.Remove(key);
            }
        }
Beispiel #60
0
		private void LoadAppleDictionary(PlistDictionary dict, CCTexture2D texture)
		{

			var version = dict.ContainsKey ("version") ? dict ["version"].AsInt : 0; 

			if (version != 1)
				throw (new NotSupportedException("Binary PList version " + version + " is not supported."));


			var images = dict.ContainsKey ("images") ? dict ["images"].AsArray : null;

			foreach (var imageEntry in images) 
			{
				// we only support one image for now
				var imageDict = imageEntry.AsDictionary;

				var path = imageDict ["path"].AsString;

				path = Path.Combine(plistFilePath, CCFileUtils.RemoveExtension(path));

				if (!CCTextureCache.SharedTextureCache.Contains (path))
					texture = CCTextureCache.SharedTextureCache.AddImage (path);
				else
					texture = CCTextureCache.SharedTextureCache[path];



				// size not used right now
				//var size = CCSize.Parse(imageDict ["size"].AsString);

				var subImages = imageDict ["subimages"].AsArray;

				foreach (var subImage in subImages) {
					CCSpriteFrame spriteFrame = null;

					var subImageDict = subImage.AsDictionary;
					var name = subImageDict ["name"].AsString;
					var alias = subImageDict ["alias"].AsString;
					var isFullyOpaque = true;

					if (subImageDict.ContainsKey ("isFullyOpaque"))
						isFullyOpaque = subImageDict ["isFullyOpaque"].AsBool;

					var textureRect = CCRect.Parse (subImageDict ["textureRect"].AsString);
					var spriteOffset = CCPoint.Parse (subImageDict ["spriteOffset"].AsString);

					// We are going to override the sprite offset for now to be 0,0
					// It seems the offset is calculated off of the original size but if 
					// we pass this offset it throws our center position calculations off.
					spriteOffset = CCPoint.Zero;

					var textureRotated = false;
					if (subImageDict.ContainsKey ("textureRotated")) {
						textureRotated = subImageDict ["textureRotated"].AsBool;
					}
					var spriteSourceSize = CCSize.Parse (subImageDict ["spriteSourceSize"].AsString);
					var frameRect = textureRect;
					if (textureRotated)
						frameRect = new CCRect (textureRect.Origin.X, textureRect.Origin.Y, textureRect.Size.Height, textureRect.Size.Width);

#if DEBUG
					CCLog.Log ("texture {0} rect {1} rotated {2} offset {3}, sourcesize {4}", name, textureRect, textureRotated, spriteOffset, spriteSourceSize);
#endif

					// create frame
					spriteFrame = new CCSpriteFrame (
						texture,
						frameRect,
						textureRotated,
						spriteOffset,
						spriteSourceSize
					);


					_spriteFrames [name] = spriteFrame;
				}
			}
		}