public ApplyToPrefabAction(GameObject obj, ContentRef<Prefab> target) : base(new[] { obj }) { this.targetPrefab = new ContentRef<Prefab>[this.targetObj.Length]; for (int i = 0; i < this.targetPrefab.Length; i++) this.targetPrefab[i] = target; }
public ApplyToPrefabAction(IEnumerable<GameObject> obj) : base(obj.Where( o => o != null && o.PrefabLink != null && o.PrefabLink.Prefab.IsAvailable)) { this.targetPrefab = this.targetObj.Select(o => o.PrefabLink.Prefab).ToArray(); }
public void ReImportFile(ContentRef<Resource> r, string srcFile) { Font font = r.Res as Font; font.SourcePath = srcFile; font.EmbeddedTrueTypeFont = File.ReadAllBytes(srcFile); font.RenderGlyphs(); }
public void ReImportFile(ContentRef<Resource> r, string srcFile) { PixelData pixelData = LoadPixelData(srcFile); Pixmap res = r.Res as Pixmap; res.MainLayer = pixelData; res.SourcePath = srcFile; }
internal static void InitDefaultContent() { const string VirtualContentPath = ContentProvider.VirtualContentPath + "Texture:"; const string ContentPath_DualityIcon = VirtualContentPath + "DualityIcon"; const string ContentPath_DualityIconB = VirtualContentPath + "DualityIconB"; const string ContentPath_DualityLogoBig = VirtualContentPath + "DualityLogoBig"; const string ContentPath_DualityLogoMedium = VirtualContentPath + "DualityLogoMedium"; const string ContentPath_DualityLogoSmall = VirtualContentPath + "DualityLogoSmall"; const string ContentPath_White = VirtualContentPath + "White"; const string ContentPath_Checkerboard = VirtualContentPath + "Checkerboard"; ContentProvider.AddContent(ContentPath_DualityIcon, new Texture(Pixmap.DualityIcon)); ContentProvider.AddContent(ContentPath_DualityIconB, new Texture(Pixmap.DualityIconB)); ContentProvider.AddContent(ContentPath_DualityLogoBig, new Texture(Pixmap.DualityLogoBig)); ContentProvider.AddContent(ContentPath_DualityLogoMedium, new Texture(Pixmap.DualityLogoMedium)); ContentProvider.AddContent(ContentPath_DualityLogoSmall, new Texture(Pixmap.DualityLogoSmall)); ContentProvider.AddContent(ContentPath_White, new Texture(Pixmap.White)); ContentProvider.AddContent(ContentPath_Checkerboard, new Texture(Pixmap.Checkerboard, wrapX: TextureWrapMode.Repeat, wrapY: TextureWrapMode.Repeat)); DualityIcon = ContentProvider.RequestContent<Texture>(ContentPath_DualityIcon); DualityIconB = ContentProvider.RequestContent<Texture>(ContentPath_DualityIconB); DualityLogoBig = ContentProvider.RequestContent<Texture>(ContentPath_DualityLogoBig); DualityLogoMedium = ContentProvider.RequestContent<Texture>(ContentPath_DualityLogoMedium); DualityLogoSmall = ContentProvider.RequestContent<Texture>(ContentPath_DualityLogoSmall); White = ContentProvider.RequestContent<Texture>(ContentPath_White); Checkerboard = ContentProvider.RequestContent<Texture>(ContentPath_Checkerboard); }
/// <summary> /// Creates a new Sound Resource based on the specified AudioData, saves it and returns a reference to it. /// </summary> /// <param name="baseRes"></param> /// <returns></returns> public static ContentRef<Sound> CreateFromAudioData(ContentRef<AudioData> baseRes) { string resPath = PathHelper.GetFreePath(baseRes.FullName, FileExt); Sound res = new Sound(baseRes); res.Save(resPath); return res; }
/// <summary> /// Creates a new DrawTechnique using the specified <see cref="BlendMode"/> and <see cref="Duality.Resources.ShaderProgram"/>. /// </summary> /// <param name="blendType"></param> /// <param name="shader"></param> /// <param name="formatPref"></param> public DrawTechnique(BlendMode blendType, ContentRef<ShaderProgram> shader, VertexDeclaration formatPref = null) { this.blendType = blendType; this.shader = shader; this.prefFormat = formatPref; this.prefType = formatPref != null ? formatPref.DataType : null; }
internal SoundInstance(ContentRef<Sound> sound, Vector3 pos) { this.pos = pos; this.is3D = true; this.sound = sound; this.audioData = this.sound.IsAvailable ? this.sound.Res.FetchData() : null; }
public CreatureContainer(CreatureType type, bool forwardOnSpecial, ContentRef<Material> combatSprite, params NameOfAbility[] abilities) { this.CombatSprite = combatSprite; this.forwardOnSpecial = forwardOnSpecial; this.CreatureType = type; this.AbilityNameStorage = new List<NameOfAbility>(abilities); }
public TilesetSelectionChangedEventArgs(ContentRef<Tileset> prev, ContentRef<Tileset> next, SelectionChangeReason reason) : base() { this.prev = prev; this.next = next; this.reason = reason; }
internal SoundInstance(ContentRef<Sound> sound, GameObject attachObj) { this.attachedTo = attachObj; this.is3D = true; this.sound = sound; this.audioData = this.sound.IsAvailable ? this.sound.Res.FetchData() : null; }
// We are going to use ContentRefs instead of using Scene Resources directly /// <summary> /// Function to switch to another scene. /// </summary> /// <param name="scene">The ContentRef of the scene to switch to.</param> public static void Switch(ContentRef<Scene> scene) { // Note that we are not doing any scene disposal here. This means that // the current scene will not be removed from memory, and that it will // retain changes made to it. Scene.SwitchTo(scene); }
/// <summary> /// Function to save a copy of the specified scene. /// </summary> /// <param name="scene">The scene to be saved.</param> public static void SaveSceneCopy(ContentRef<Scene> scene) { // This is the path to which the file will be saved. It is constructed by // combining the Duality Data directory path with the sample name, which // results in the actual directory the file will be saved to. // This result is concatenated with the actual file name. // The file name is constructed by concatenating the specified scene's name, // along with "_Copy" and the Scene Resource file extension. string filePath = Duality.IO.PathOp.Combine(DualityApp.DataDirectory, "SceneTransitions") + (scene.Name + "_Copy" + Resource.GetFileExtByType<Scene>()); // Here we save the scene. scene.Res.Save(filePath); // The "Press to save" object's TextRenderer. TextRenderer textRenderer = scene.Res.FindGameObject("Text5").GetComponent<TextRenderer>(); // Set the "Press to save" object's TextRenderer's source text and color tint, // if the TextRenderer was found. if (textRenderer != null) { textRenderer.Text.ApplySource("The saved scene can be found in the Duality Data directory."); textRenderer.ColorTint = ColorRgba.Green; } }
public void ReImportFile(ContentRef<Resource> r, string srcFile) { AbstractShader s = r.Res as AbstractShader; string sourceCode = File.ReadAllText(srcFile); s.Source = sourceCode; s.SourcePath = srcFile; s.Compile(); }
internal static void InitDefaultContent() { const string VirtualContentPath = ContentProvider.VirtualContentPath + "Sound:"; const string ContentPath_Beep = VirtualContentPath + "Beep"; ContentProvider.AddContent(ContentPath_Beep, new Sound(AudioData.Beep)); Beep = ContentProvider.RequestContent<Sound>(ContentPath_Beep); }
internal static void InitDefaultContent() { const string VirtualContentPath = ContentProvider.VirtualContentPath + "AudioData:"; const string ContentPath_Beep = VirtualContentPath + "Beep"; ContentProvider.AddContent(ContentPath_Beep, new AudioData(DefaultContent.Beep)); Beep = ContentProvider.RequestContent<AudioData>(ContentPath_Beep); }
internal static void InitDefaultContent() { ContentProvider.RegisterContent(ContentPath_Beep, new Sound(AudioData.Beep)); ContentProvider.RegisterContent(ContentPath_DroneLoop, new Sound(AudioData.DroneLoop)); ContentProvider.RegisterContent(ContentPath_LogoJingle, new Sound(AudioData.LogoJingle)); Beep = ContentProvider.RequestContent<Sound>(ContentPath_Beep); DroneLoop = ContentProvider.RequestContent<Sound>(ContentPath_DroneLoop); LogoJingle = ContentProvider.RequestContent<Sound>(ContentPath_LogoJingle); }
public bool CanReImportFile(ContentRef<Resource> r, string srcFile) { string ext = Path.GetExtension(srcFile); if (r.Is<VertexShader>() && string.Equals(ext, SourceFileExtVertex, StringComparison.InvariantCultureIgnoreCase)) return true; else if (r.Is<FragmentShader>() && string.Equals(ext, SourceFileExtFragment, StringComparison.InvariantCultureIgnoreCase)) return true; else return false; }
internal static void InitDefaultContent() { ContentProvider.RegisterContent(ContentPath_Minimal, new ShaderProgram(VertexShader.Minimal, FragmentShader.Minimal)); ContentProvider.RegisterContent(ContentPath_Picking, new ShaderProgram(VertexShader.Minimal, FragmentShader.Picking)); ContentProvider.RegisterContent(ContentPath_SmoothAnim, new ShaderProgram(VertexShader.SmoothAnim, FragmentShader.SmoothAnim)); Minimal = ContentProvider.RequestContent<ShaderProgram>(ContentPath_Minimal); Picking = ContentProvider.RequestContent<ShaderProgram>(ContentPath_Picking); SmoothAnim = ContentProvider.RequestContent<ShaderProgram>(ContentPath_SmoothAnim); }
public static bool SceneContainsTileset(Scene scene, ContentRef<Tileset> tileset) { foreach (Tilemap tilemap in scene.FindComponents<Tilemap>()) { if (tilemap.Tileset == tileset) return true; } return false; }
public ScreenCaptureStream(BlockingCollection<CapturedFrame> frames, string streamName, ContentRef<RenderTarget> output, int numberOfCachedFrames) { _frames = frames; _output = output; StreamName = streamName; _numberOfCachedFrames = numberOfCachedFrames; _pboIds[0] = GL.GenBuffer(); _pboIds[1] = GL.GenBuffer(); }
/// <summary> /// Function to switch to another scene after disposing the specified scene. /// </summary> /// <param name="nextScene">The ContentRef of the scene to dispose.</param> /// <param name="nextScene">The ContentRef of the scene to switch to.</param> public static void DisposeAndSwitch(ContentRef<Scene> disposeScene, ContentRef<Scene> nextScene) { // In this function, the current scene will be disposed, or removed // from memory, before the switch to the next scene commences. // We are using DisposeLater() for safety, it will only dispose the // scene after the current update cycle is over. disposeScene.Res.DisposeLater(); Scene.SwitchTo(nextScene); }
public static string GenerateSourceFilePath(ContentRef<Resource> r, string srcFileExt) { string filePath = PathHelper.MakeFilePathRelative(r.Path, DualityApp.DataDirectory); string fileDir = Path.GetDirectoryName(filePath); if (filePath.Contains("..")) { filePath = Path.GetFileName(filePath); fileDir = "."; } return PathHelper.GetFreePath(Path.Combine(Path.Combine(EditorHelper.SourceMediaDirectory, fileDir), r.Name), srcFileExt); }
internal static void InitDefaultContent() { const string VirtualContentPath = ContentProvider.VirtualContentPath + "VertexShader:"; const string ContentPath_Minimal = VirtualContentPath + "Minimal"; const string ContentPath_SmoothAnim = VirtualContentPath + "SmoothAnim"; ContentProvider.AddContent(ContentPath_Minimal, new VertexShader(DefaultContent.MinimalVert)); ContentProvider.AddContent(ContentPath_SmoothAnim, new VertexShader(DefaultContent.SmoothAnimVert)); Minimal = ContentProvider.RequestContent<VertexShader>(ContentPath_Minimal); SmoothAnim = ContentProvider.RequestContent<VertexShader>(ContentPath_SmoothAnim); }
internal static void InitDefaultContent() { ContentProvider.RegisterContent(ContentPath_DualityLogo256, new Texture(Pixmap.DualityLogo256)); ContentProvider.RegisterContent(ContentPath_DualityLogoB256, new Texture(Pixmap.DualityLogoB256)); ContentProvider.RegisterContent(ContentPath_White, new Texture(Pixmap.White)); ContentProvider.RegisterContent(ContentPath_Checkerboard256, new Texture(Pixmap.Checkerboard256, wrapX: TextureWrapMode.Repeat, wrapY: TextureWrapMode.Repeat)); DualityLogo256 = ContentProvider.RequestContent<Texture>(ContentPath_DualityLogo256); DualityLogoB256 = ContentProvider.RequestContent<Texture>(ContentPath_DualityLogoB256); White = ContentProvider.RequestContent<Texture>(ContentPath_White); Checkerboard256 = ContentProvider.RequestContent<Texture>(ContentPath_Checkerboard256); }
internal static void InitDefaultContent() { VertexShader tmp; tmp = new VertexShader(); tmp.SetSource(DefaultRes.MinimalVert); ContentProvider.RegisterContent(ContentPath_Minimal, tmp); tmp = new VertexShader(); tmp.SetSource(DefaultRes.SmoothAnimVert); ContentProvider.RegisterContent(ContentPath_SmoothAnim, tmp); Minimal = ContentProvider.RequestContent<VertexShader>(ContentPath_Minimal); SmoothAnim = ContentProvider.RequestContent<VertexShader>(ContentPath_SmoothAnim); }
internal static void InitDefaultContent() { const string VirtualContentPath = ContentProvider.VirtualContentPath + "AudioData:"; const string ContentPath_Beep = VirtualContentPath + "Beep"; const string ContentPath_DroneLoop = VirtualContentPath + "DroneLoop"; const string ContentPath_LogoJingle = VirtualContentPath + "LogoJingle"; ContentProvider.AddContent(ContentPath_Beep, new AudioData(DefaultRes.Beep)); ContentProvider.AddContent(ContentPath_DroneLoop, new AudioData(DefaultRes.DroneLoop)); ContentProvider.AddContent(ContentPath_LogoJingle, new AudioData(DefaultRes.LogoJingle)); Beep = ContentProvider.RequestContent<AudioData>(ContentPath_Beep); DroneLoop = ContentProvider.RequestContent<AudioData>(ContentPath_DroneLoop); LogoJingle = ContentProvider.RequestContent<AudioData>(ContentPath_LogoJingle); }
internal static void InitDefaultContent() { const string VirtualContentPath = ContentProvider.VirtualContentPath + "FragmentShader:"; const string ContentPath_Minimal = VirtualContentPath + "Minimal"; const string ContentPath_Picking = VirtualContentPath + "Picking"; const string ContentPath_SmoothAnim = VirtualContentPath + "SmoothAnim"; const string ContentPath_SharpMask = VirtualContentPath + "SharpAlpha"; ContentProvider.AddContent(ContentPath_Minimal, new FragmentShader(DefaultContent.MinimalFrag)); ContentProvider.AddContent(ContentPath_Picking, new FragmentShader(DefaultContent.PickingFrag)); ContentProvider.AddContent(ContentPath_SmoothAnim, new FragmentShader(DefaultContent.SmoothAnimFrag)); ContentProvider.AddContent(ContentPath_SharpMask, new FragmentShader(DefaultContent.SharpAlphaFrag)); Minimal = ContentProvider.RequestContent<FragmentShader>(ContentPath_Minimal); Picking = ContentProvider.RequestContent<FragmentShader>(ContentPath_Picking); SmoothAnim = ContentProvider.RequestContent<FragmentShader>(ContentPath_SmoothAnim); SharpAlpha = ContentProvider.RequestContent<FragmentShader>(ContentPath_SharpMask); }
/// <summary> /// Prepares the specified <see cref="Tilemap"/> for user editing using the specified size. /// </summary> /// <param name="tilemap"></param> /// <param name="tilesetRef"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="isUpperLayer"></param> public static void SetupTilemap(Tilemap tilemap, ContentRef<Tileset> tilesetRef, int width, int height, bool isUpperLayer) { Tileset tileset = tilesetRef.Res; // Determine the first tile index that matches the layer type. int fillTileIndex = GetDefaultTileIndex(tileset, isUpperLayer); // Resize the Tilemap and fill it with the first visually non-empty tile. tilemap.Tileset = tileset; tilemap.Resize(width, height); tilemap.BeginUpdateTiles().Fill( new Tile(fillTileIndex), 0, 0, tilemap.Size.X, tilemap.Size.Y); tilemap.EndUpdateTiles(); }
internal static void InitDefaultContent() { const string VirtualContentPath = ContentProvider.VirtualContentPath + "ShaderProgram:"; const string ContentPath_Minimal = VirtualContentPath + "Minimal"; const string ContentPath_Picking = VirtualContentPath + "Picking"; const string ContentPath_SmoothAnim = VirtualContentPath + "SmoothAnim"; const string ContentPath_SharpMask = VirtualContentPath + "SharpAlpha"; ContentProvider.AddContent(ContentPath_Minimal, new ShaderProgram(VertexShader.Minimal, FragmentShader.Minimal)); ContentProvider.AddContent(ContentPath_Picking, new ShaderProgram(VertexShader.Minimal, FragmentShader.Picking)); ContentProvider.AddContent(ContentPath_SmoothAnim, new ShaderProgram(VertexShader.SmoothAnim, FragmentShader.SmoothAnim)); ContentProvider.AddContent(ContentPath_SharpMask, new ShaderProgram(VertexShader.Minimal, FragmentShader.SharpAlpha)); Minimal = ContentProvider.RequestContent<ShaderProgram>(ContentPath_Minimal); Picking = ContentProvider.RequestContent<ShaderProgram>(ContentPath_Picking); SmoothAnim = ContentProvider.RequestContent<ShaderProgram>(ContentPath_SmoothAnim); SharpAlpha = ContentProvider.RequestContent<ShaderProgram>(ContentPath_SharpMask); }
public void InitPostWindow() { defaultNormalMap = new Texture(new Pixmap(new PixelData(2, 2, new ColorRgba(0.5f, 0.5f, 1f))), TextureSizeMode.Default, TextureMagFilter.Nearest, TextureMinFilter.Nearest); defaultNormalMap.Res.DetachSource(); cachedMetadata = new ConcurrentDictionary <string, Metadata>(2, 31); cachedGraphics = new Dictionary <string, GenericGraphicResource>(); cachedShaders = new Dictionary <string, ContentRef <DrawTechnique> >(); //cachedSounds = new Dictionary<string, ContentRef<Sound>>(); basicNormal = RequestShader("BasicNormal"); paletteNormal = RequestShader("PaletteNormal"); AllowAsyncLoading(); #if DEBUG && UNCOMPRESSED_CONTENT InitWatchForFileChanges(); #endif }
public void OnActivate() { if (DualityApp.ExecEnvironment == DualityApp.ExecutionEnvironment.Editor) { return; } //load up the music and SFX and fade music in this.bumpSFX = ContentProvider.RequestContent <Sound>(@"Data\Audio\SFX\bump.Sound.Res"); this.bumpSFX.EnsureLoaded(); this.coinsSFX = ContentProvider.RequestContent <Sound>(@"Data\Audio\SFX\GetCoins.Sound.Res"); this.coinsSFX.EnsureLoaded(); this.noCoinsSFX = ContentProvider.RequestContent <Sound>(@"Data\Audio\SFX\NoCoins.Sound.Res"); this.noCoinsSFX.EnsureLoaded(); StartBackgroundMusic(); }
protected override void OnSaved(string saveAsPath) { if (this.serializeObj != null) { this.serializeObj = null; } base.OnSaved(saveAsPath); foreach (GameObject obj in this.objectManager.AllObjects) { obj.OnSaved(); } // If this Scene is the current one, but it wasn't saved before, update the current Scenes internal ContentRef if (this.IsCurrent && current.IsRuntimeResource) { current = new ContentRef <Scene>(this, saveAsPath); } }
private static bool IsUsingSourceFile(IFileImporter importer, ContentRef <Resource> resourceRef, string srcFilePath, string srcFileExt) { // Does the Resource or Importer recall to use this file? if (importer.IsUsingSrcFile(resourceRef, srcFilePath)) { return(true); } // Does the system suggest that the Resource would use that file if it was opened for editing? string resourceSourcePath = SelectSourceFilePath(resourceRef, srcFileExt); if (PathHelper.ArePathsEqual(resourceSourcePath, srcFilePath)) { return(true); } // Nope. return(false); }
public static void OpenSourceFile(ContentRef <Resource> resourceRef, string srcFileExt, Action <string> saveSrcToAction) { // Default content: Use temporary location if (resourceRef.IsDefaultContent) { string tmpLoc = Path.Combine(Path.GetTempPath(), resourceRef.Path.Replace(':', '_')) + srcFileExt; Directory.CreateDirectory(Path.GetDirectoryName(tmpLoc)); saveSrcToAction(tmpLoc); System.Diagnostics.Process.Start(tmpLoc); } // Other content: Use permanent src file location else { Resource resource = resourceRef.Res; string srcFilePath = resource.SourcePath; // If the Resource to open doesn't know where its source file is, search or create it if (String.IsNullOrEmpty(srcFilePath) || !File.Exists(srcFilePath)) { // Determine the desired source file path srcFilePath = SelectSourceFilePath(resourceRef, srcFileExt); // If there already is a matching file in the desired path, it's probably been relocated there if (File.Exists(srcFilePath)) { // Do nothing and simply use the existing file. } // Otherwise, export the Resource to the desired path else { Directory.CreateDirectory(Path.GetDirectoryName(srcFilePath)); saveSrcToAction(srcFilePath); } // Keep in mind where we left the source file resource.SourcePath = srcFilePath; DualityEditorApp.FlagResourceUnsaved(resource); } // Open the source file System.Diagnostics.Process.Start(srcFilePath); } }
protected override void OnDragDrop(DragEventArgs e) { base.OnDragDrop(e); DataObject data = e.Data as DataObject; var dragObjQuery = new ConvertOperation(data, ConvertOperation.Operation.All).Perform <Pixmap>(); if (dragObjQuery != null) { Pixmap pixmap = dragObjQuery.FirstOrDefault(); if (_pixmap != pixmap && pixmap.Atlas != null && pixmap.Atlas.Count > 0 && pixmap.MainLayer != null && pixmap.Width > 0 && pixmap.Height > 0) { _pixmap = pixmap; virtScroll.Value = 0; RefreshScrollBar(); RefreshDisplay(pixmap); } e.Effect = e.AllowedEffect; } }
private void StartRecordTilesetChanges() { // Copy the selected tileset's original settings to our local backup Tileset tileset = this.SelectedTileset.Res; if (tileset != null) { if (this.tilesetBackup == null) { this.tilesetBackup = new Tileset(); } tileset.CopyTo(this.tilesetBackup); this.backupTarget = this.SelectedTileset; } else { this.backupTarget = null; } }
/// <summary> /// Creates a new Texture based on a <see cref="Duality.Resources.Pixmap"/>. /// </summary> /// <param name="basePixmap">The <see cref="Duality.Resources.Pixmap"/> to use as source for pixel data.</param> /// <param name="sizeMode">Specifies behaviour in case the source data has non-power-of-two dimensions.</param> /// <param name="filterMag">The OpenGL filter mode for drawing the Texture bigger than it is.</param> /// <param name="filterMin">The OpenGL fitler mode for drawing the Texture smaller than it is.</param> /// <param name="wrapX">The OpenGL wrap mode on the texel x axis.</param> /// <param name="wrapY">The OpenGL wrap mode on the texel y axis.</param> /// <param name="format">The format in which OpenGL stores the pixel data.</param> public Texture(ContentRef <Pixmap> basePixmap, SizeMode sizeMode = SizeMode.Default, TextureMagFilter filterMag = TextureMagFilter.Linear, TextureMinFilter filterMin = TextureMinFilter.LinearMipmapLinear, TextureWrapMode wrapX = TextureWrapMode.ClampToEdge, TextureWrapMode wrapY = TextureWrapMode.ClampToEdge, PixelInternalFormat format = PixelInternalFormat.Rgba, PixelType pixelType = PixelType.UnsignedByte, bool keepPixmapDataResident = false) { this.filterMag = filterMag; this.filterMin = filterMin; this.wrapX = wrapX; this.wrapY = wrapY; this.pixelformat = format; this.pixelType = pixelType; this.keepPixmapDataResident = keepPixmapDataResident; this.LoadData(basePixmap, sizeMode); }
[Test] public void CloneContentRef() { TestResource resource = new TestResource { TestProperty = "TestString" }; ContentRef <TestResource> reference = new ContentRef <TestResource>(resource, "SomeTestPath"); // Expect the Resource to be cloned TestResource resourceClone = resource.DeepClone(); Assert.AreNotSame(resource, resourceClone); Assert.AreEqual(resource.TestProperty, resourceClone.TestProperty); // Expect only the reference to be cloned ContentRef <TestResource> referenceClone = reference.DeepClone(); Assert.AreEqual(reference.Path, referenceClone.Path); Assert.AreEqual(reference.ResWeak, referenceClone.ResWeak); }
/// <summary> /// Replaces the material that will be used for rendering with the specified one. /// </summary> /// <param name="material"></param> public void SetMaterial(ContentRef <Material> material) { BatchInfo info; if (material.IsExplicitNull) { info = DefaultMaterial; } else if (material.IsAvailable) { info = material.Res.Info; } else { info = Resources.Material.SolidWhite.Res.Info; } this.SetMaterial(info); }
public static void Stop() { if (state == SandboxState.Inactive) { return; } stateChange = true; ContentRef <Scene> activeScene = Scene.Current; // Leave the current Scene Scene.SwitchTo(null, true); // Force later Scene reload by disposing it if (!activeScene.IsRuntimeResource) { activeScene.Res.Dispose(); } // Stopp all audio that might not have been taken care of manually by the user DualityApp.Sound.StopAll(); Time.TimeScale = 1.0f; // Reset time scale Time.Resume(true); // Reset any previously (user-)generated time freeze events state = SandboxState.Inactive; DualityApp.ExecContext = DualityApp.ExecutionContext.Editor; // Check if the Scene we started the sandbox with is still valid, and switch back to it. if (startScene.IsAvailable) { Scene.SwitchTo(startScene); } // Otherwise, just switch back to the previously active Scene. This can happen if the // start scene was a runtime-only Scene that was active while a plugin reload occurred. else if (activeScene.IsAvailable) { Scene.SwitchTo(activeScene); } OnLeaveSandbox(); OnSandboxStateChanged(); stateChange = false; }
internal static void InitDefaultContent() { const string VirtualContentPath = ContentProvider.VirtualContentPath + "FragmentShader:"; const string ContentPath_Minimal = VirtualContentPath + "Minimal"; const string ContentPath_Picking = VirtualContentPath + "Picking"; const string ContentPath_SmoothAnim = VirtualContentPath + "SmoothAnim"; const string ContentPath_SharpMask = VirtualContentPath + "SharpAlpha"; #if !__ANDROID__ ContentProvider.AddContent(ContentPath_Minimal, new FragmentShader(DefaultContent.MinimalFrag)); ContentProvider.AddContent(ContentPath_Picking, new FragmentShader(DefaultContent.PickingFrag)); ContentProvider.AddContent(ContentPath_SmoothAnim, new FragmentShader(DefaultContent.SmoothAnimFrag)); ContentProvider.AddContent(ContentPath_SharpMask, new FragmentShader(DefaultContent.SharpAlphaFrag)); #endif Minimal = ContentProvider.RequestContent <FragmentShader>(ContentPath_Minimal); Picking = ContentProvider.RequestContent <FragmentShader>(ContentPath_Picking); SmoothAnim = ContentProvider.RequestContent <FragmentShader>(ContentPath_SmoothAnim); SharpAlpha = ContentProvider.RequestContent <FragmentShader>(ContentPath_SharpMask); }
///// <summary> ///// Determines the number of playing instances of a specific <see cref="Duality.Resources.Sound"/>. ///// </summary> ///// <param name="snd">The Sound of which to determine the number of playing instances.</param> ///// <returns>The number of the specified Sounds playing instances.</returns> //public int GetNumPlaying(ContentRef<Sound> snd) //{ // int curNumSoundRes; // if (!snd.IsAvailable || snd.IsRuntimeResource || !this.resPlaying.TryGetValue(snd.Path, out curNumSoundRes)) // return 0; // else // return curNumSoundRes; //} /// <summary> /// Registers a <see cref="Duality.Resources.Sound">Sounds</see> playing instance. /// </summary> /// <param name="snd">The Sound that is playing.</param> /// <param name="is3D">Whether the instance is 3d or not.</param> internal void RegisterPlaying(ContentRef <Sound> snd, bool is3D) { if (is3D) { this.numPlaying3D++; } else { this.numPlaying2D++; } //if (snd.IsAvailable && !snd.IsRuntimeResource) //{ // if (!this.resPlaying.ContainsKey(snd.Path)) // this.resPlaying.Add(snd.Path, 1); // else // this.resPlaying[snd.Path]++; //} }
private void btnCreateInstallerandDt_Click(object sender, EventArgs e) { ////Setup the installer and it's contents Content content = new Content(); MsiInstaller msiInstaller = new MsiInstaller(); FileInfo file = new FileInfo(txtMSILocation.Text); content.Location = file.Directory.FullName; ////use the msi folders location as the content source for the application package content = ContentImporter.CreateContentFromFolder(file.Directory.FullName); ////set the command that will run to install on a clients desktop msiInstaller.InstallCommandLine = txtInstallCommandLine.Text; msiInstaller.UninstallCommandLine = txtUninstallCommandLine.Text; ContentRef contentReferenece = new ContentRef(content); content.OnFastNetwork = ContentHandlingMode.Download; content.OnSlowNetwork = ContentHandlingMode.DoNothing; content.FallbackToUnprotectedDP = false; ////configure other properties - for instance the produce code which by default is used to detect whether the application is already installed msiInstaller.Contents.Add(content); msiInstaller.InstallContent = contentReferenece; msiInstaller.DetectionMethod = DetectionMethod.ProductCode; msiInstaller.ProductCode = txtProductCode.Text; msiInstaller.SourceUpdateProductCode = txtProductCode.Text; msiInstaller.ExecutionContext = sccm.ExecutionContext.System; msiInstaller.Contents[0].PinOnClient = false; msiInstaller.Contents[0].PeerCache = false; msiInstaller.UserInteractionMode = UserInteractionMode.Normal; msiInstaller.MaxExecuteTime = 120; msiInstaller.ExecuteTime = 0; ////Add a deployment type to the application using the installer details created above sccm.DeploymentType dt = new sccm.DeploymentType(msiInstaller, "MSI", NativeHostingTechnology.TechnologyId); dt.Title = txtSCCMApplicationName.Text; dt.Version = 1; ////retrieve tha application here to then add the deployment type to ot sccm.Application application = GetApplicationFromName(txtSCCMApplicationName.Text); application.DeploymentTypes.Add(dt); ////resave the application SaveApplication(application); }
public void DeleteContent(ContentRef cref, bool deleteThumb) { var fileName = GetFullPath(cref); if (File.Exists(fileName)) { File.Delete(fileName); } if (deleteThumb) { switch (cref.ContentType) { case ContentType.BikeImage: DeleteContent(new ContentRef(ContentType.BikeImageThumb, GetThumbFileName(cref)), false); break; } } }
public override void HandleError(SerializeError error) { AssignFieldError assignFieldError = error as AssignFieldError; ResolveTypeError resolveTypeError = error as ResolveTypeError; // BatchInfo uniforms and textures were moved to a nested ShaderParameters if (assignFieldError != null) { BatchInfo batchInfo = assignFieldError.TargetObject as BatchInfo; if (batchInfo != null) { if (assignFieldError.FieldName == "uniforms") { Dictionary <string, float[]> uniforms = assignFieldError.FieldValue as Dictionary <string, float[]>; if (uniforms != null) { foreach (var pair in uniforms) { batchInfo.SetArray(pair.Key, pair.Value); } assignFieldError.AssignSuccess = true; } } else if (assignFieldError.FieldName == "textures") { Dictionary <string, ContentRef <Texture> > textures = assignFieldError.FieldValue as Dictionary <string, ContentRef <Texture> >; if (textures != null) { foreach (var pair in textures) { ContentRef <Texture> texRef = pair.Value; texRef.EnsureLoaded(); batchInfo.SetTexture(pair.Key, texRef); } assignFieldError.AssignSuccess = true; } } } } return; }
public void Import(IAssetImportEnvironment env) { foreach (AssetImportInput input in env.Input) { // Request a target Resource with a name matching the input ContentRef <Duality.Resources.Font> targetRef = env.GetOutput <Duality.Resources.Font>(input.AssetName); // If we successfully acquired one, proceed with the import if (targetRef.IsAvailable) { Duality.Resources.Font target = targetRef.Res; var fileFormat = FigureOutFontFileFormat(input.Path); switch (fileFormat) { case FontFileFormat.BMFont: { var fontData = LoadBMFontData(input.Path); var textureData = LoadPixelData(fontData, Path.GetFullPath(Path.GetDirectoryName(input.Path))); target.SetGlyphData(textureData, fontData.Atlas.ToArray(), fontData.Glyps.ToArray(), fontData.Height, fontData.Ascent, fontData.BodyAscent, fontData.Descent, fontData.Baseline); target.Size = fontData.Size; //target.Kerning = true; env.AddOutput(targetRef, input.Path); break; } } } } }
public async Task <IContent> GetContent(ContentRef cref, bool mustExist) { var fileName = GetFullPath(cref); if (mustExist || File.Exists(fileName)) { var bytes = await File.ReadAllBytesAsync(fileName); switch (cref.ContentType.Format()) { case ContentFormat.ImageRgba32: return(new Content <Image <Rgba32> >(cref, GetHtmlContentType(cref), Image.Load(bytes))); default: throw new NotSupportedException($"Not supported format: {cref.ContentType.Format()}"); } } return(null); }
internal static void InitDefaultContent() { const string VirtualContentPath = ContentProvider.VirtualContentPath + "Texture:"; const string ContentPath_White = VirtualContentPath + "White"; const string ContentPath_Checkerboard = VirtualContentPath + "Checkerboard"; ContentProvider.AddContent(ContentPath_White, new Texture(Pixmap.White, keepPixmapDataResident: true)); ContentProvider.AddContent(ContentPath_Checkerboard, new Texture( Pixmap.Checkerboard, SizeMode.Default, TextureMagFilter.Nearest, TextureMinFilter.Nearest, TextureWrapMode.Repeat, TextureWrapMode.Repeat, keepPixmapDataResident: true)); White = ContentProvider.RequestContent <Texture>(ContentPath_White); Checkerboard = ContentProvider.RequestContent <Texture>(ContentPath_Checkerboard); }
void IAssetImporter.Import(IAssetImportEnvironment env) { // Handle all available input. No need to filter or ask for this anymore, as // the preparation step already made a selection with AcceptsInput. We won't // get any input here that didn't match. foreach (AssetImportInput input in env.Input) { // Request a target Resource with a name matching the input ContentRef <T> targetRef = env.GetOutput <T>(this.GetResourceNameFromInput(input)); // If we successfully acquired one, proceed with the import if (targetRef.IsAvailable) { this.ImportResource(targetRef, input, env); // Add the requested output to signal that we've done something with it env.AddOutput(targetRef, input.Path); } } }
private void ApplySelectedTileset() { // Query the selected tileset... ContentRef <Tileset> lastTileset = this.SelectedTileset; ContentRef <Tileset> tileset = TilemapsEditorSelectionParser.QuerySelectedTileset(); // ...or just use the last one (for editing continuity reasons) if none is selected. if (tileset == null && TilemapsEditorSelectionParser.SceneContainsTileset(Scene.Current, lastTileset)) { tileset = lastTileset; } // If the selected tileset is no longer available, deselect it. if (!tileset.IsAvailable) { tileset = null; } this.SelectedTileset = tileset; }
/// <summary> /// Binds the given Texture to a texture unit in order to use it for rendering. /// </summary> /// <param name="tex">The Texture to bind.</param> /// <param name="texUnit">The texture unit where the Texture will be bound to.</param> public static void Bind(ContentRef <Texture> tex, int texUnit = 0) { if (!initialized) { Init(); } Texture texRes = tex.IsExplicitNull ? null : (tex.Res ?? Checkerboard.Res); if (curBound[texUnit] == texRes) { return; } if (activeTexUnit != texUnit) { GL.ActiveTexture(texUnits[texUnit]); } activeTexUnit = texUnit; if (texRes == null) { GL.BindTexture(TextureTarget.Texture2D, 0); GL.Disable(EnableCap.Texture2D); curBound[texUnit] = null; } else { if (texRes.glTexId == 0) { throw new ArgumentException(string.Format("Specified texture '{0}' has no valid OpenGL texture Id! Maybe it hasn't been loaded / initialized properly?", texRes.Path), "tex"); } if (texRes.Disposed) { throw new ArgumentException(string.Format("Specified texture '{0}' has already been deleted!", texRes.Path), "tex"); } GL.Enable(EnableCap.Texture2D); GL.BindTexture(TextureTarget.Texture2D, texRes.glTexId); curBound[texUnit] = texRes; } }
SoundInstance PlaySoundInst(SoundEnum soundEnum) { var dict = new Dictionary <SoundEnum, ContentRef <Sound> > () { { SoundEnum.Pickup, Sound_Pickup }, { SoundEnum.PlayerDeath, Sound_PlayerDeath }, { SoundEnum.Drill, Sound_Drill }, { SoundEnum.ExitReached, Sound_ExitReached }, { SoundEnum.Jump, Sound_Jump } }; ContentRef <Sound> soundRef = dict[soundEnum]; if (soundRef == null) { Log.Game.WriteError($"Sound {soundEnum.ToString ()} not found"); return(null); } return(DualityApp.Sound.PlaySound(soundRef)); }
/// <summary> /// Reloads the <see cref="Current">current Scene</see> or schedules it for reload at the end of the /// frame, depending on whether it is considered safe to do so immediately. Similar to <see cref="SwitchTo"/> with /// regard to execution planning. /// </summary> public static void Reload() { ContentRef <Scene> target = Scene.Current; // Check whether there is anything that would prevent us from doing the // reload right now, instead of at the end of the current frame bool reloadIsBlocked = switchLock != 0 || Scene.Current.IsRenderingOrUpdating; if (reloadIsBlocked) { Scene.Current.DisposeLater(); } else { Scene.Current.Dispose(); } Scene.SwitchTo(target); }
[Test] public void GetContentRefs() { DataObject dataIn = new DataObject(); TestResource res = new TestResource(); ContentRef <TestResource> contentRef = new ContentRef <TestResource>(res); dataIn.SetContentRefs(new IContentRef[] { contentRef }); Assert.IsTrue(dataIn.ContainsContentRefs()); Assert.IsTrue(dataIn.ContainsContentRefs(typeof(TestResource))); Assert.AreEqual(contentRef, dataIn.GetContentRefs()[0]); Assert.AreEqual(contentRef, dataIn.GetContentRefs(typeof(TestResource))[0]); DataObject dataOut = this.SimulateClipboardSerialize(dataIn); Assert.IsTrue(dataOut.ContainsContentRefs()); // This is false due to the fact that the reference to the locally created // TestResource will not survive serialization. Assert.IsFalse(dataOut.ContainsContentRefs(typeof(TestResource))); }
/// <summary> /// Returns whether a change was made on a <see cref="Resource"/> of the specified type. /// </summary> /// <param name="type"></param> /// <param name="content"></param> /// <returns></returns> /// <seealso cref="FileSystemChangedEventArgs.Contains(FileEventType, string)"/> public bool Contains(FileEventType type, Type contentType) { // Early-out to avoid iterating if we don't have anything of that type if (!this.Any(type)) { return(false); } if (contentType == null) { return(false); } foreach (FileEvent item in this.FileEvents) { if ((item.Type & type) == FileEventType.None) { continue; } if (item.IsDirectory) { continue; } ContentRef <Resource> content = new ContentRef <Resource>(item.Path); if (contentType.IsAssignableFrom(content.ResType)) { return(true); } if (item.Type == FileEventType.Renamed) { ContentRef <Resource> oldContent = new ContentRef <Resource>(item.OldPath); if (contentType.IsAssignableFrom(oldContent.ResType)) { return(true); } } } return(false); }
/// <summary> /// Given the specified <see cref="Pixmap"/> reference, this method enumerates all /// loaded <see cref="Tileset"/> instances that are candidates for a runtime recompile /// to account for potential changes. /// </summary> /// <param name="pixmapRef"></param> /// <returns></returns> private List <Tileset> GetRecompileTilesets(ContentRef <Pixmap> pixmapRef) { List <Tileset> recompileTilesets = new List <Tileset>(); foreach (ContentRef <Tileset> tilesetRef in ContentProvider.GetLoadedContent <Tileset>()) { Tileset tileset = tilesetRef.Res; // Early-out, if the tileset is unavailable, or we didn't compile it yet anyway if (tileset == null) { continue; } if (!tileset.Compiled) { continue; } // Determine whether this tileset uses the modified pixmap bool usesModifiedPixmap = false; foreach (TilesetRenderInput input in tileset.RenderConfig) { if (input.SourceData == pixmapRef) { usesModifiedPixmap = true; break; } } if (!usesModifiedPixmap) { continue; } // This tileset is a candidate for recompiling due to pixmap changes recompileTilesets.Add(tileset); } return(recompileTilesets); }
/// <summary> /// Sets a texture. /// </summary> /// <param name="name"></param> /// <param name="tex"></param> public void SetTexture(string name, ContentRef <Texture> tex) { if (this.textures == null) { this.textures = new Dictionary <string, ContentRef <Texture> >(); } else { this.CleanDirty(DirtyFlag.Textures); } if (tex.IsExplicitNull) { this.textures.Remove(name); } else { this.textures[name] = tex; } this.InvalidateHashCode(); }
/// <summary> /// Called to render the specified <see cref="Scene"/>, including the viewports of /// all <see cref="Camera"/> objects contained within. /// </summary> /// <param name="scene">The <see cref="Scene"/> that should be rendered.</param> /// <param name="target"> /// The <see cref="RenderTarget"/> which will be used for all rendering output. /// "null" means rendering directly to the output buffer of the game window / screen. /// </param> /// <param name="viewportRect">The viewport to render to, in pixel coordinates.</param> /// <param name="imageSize">Target size of the rendered image before adjusting it to fit the specified viewport.</param> protected virtual void OnRenderScene(Scene scene, ContentRef <RenderTarget> target, Rect viewportRect, Vector2 imageSize) { Camera[] activeSceneCameras = scene.FindComponents <Camera>() .Where(c => c.Active) .OrderByDescending(c => c.Priority) .ToArray(); foreach (Camera camera in activeSceneCameras) { Vector2 cameraImageSize = imageSize; Rect cameraViewport = viewportRect; bool isOutputCamera = false; // Cameras with a custom render target will use its size to override image and viewport size if (camera.Target.IsAvailable) { cameraImageSize = camera.Target.Res.Size; cameraViewport = new Rect(camera.Target.Res.Size); } // Cameras without a custom render target will use the provided parameters else { camera.Target = target; isOutputCamera = true; } try { camera.Render(cameraViewport, cameraImageSize); } finally { if (isOutputCamera) { camera.Target = null; } } } }
/// <summary> /// Applies auto-resizing rules to all <see cref="RenderTarget"/> resources that are in the resize list /// of this <see cref="RenderSetup"/>. /// </summary> /// <param name="outputSize"></param> protected void ApplyOutputAutoResize(Point2 outputSize) { foreach (RenderSetupTargetResize autoResize in this.autoResizeTargets) { ContentRef <RenderTarget> targetRef = autoResize.Target; RenderTarget target = targetRef.Res; if (target == null) { continue; } // Determine the target's original size Point2 originalTargetSize; if (!this.originalTargetSizes.TryGetValue(targetRef, out originalTargetSize)) { originalTargetSize = target.Size; } // Determine the target's desired size based on output size and resize mode. Point2 desiredTargetSize = (Point2)(autoResize.ResizeMode.Apply(originalTargetSize, outputSize) * autoResize.Scale); desiredTargetSize = Point2.Max(desiredTargetSize, new Point2(1, 1)); if (target.Size != desiredTargetSize) { // If there's no record of the target's original size yet, create one if (!this.originalTargetSizes.ContainsKey(targetRef)) { this.originalTargetSizes.Add(targetRef, target.Size); } this.ResizeRenderTarget(target, desiredTargetSize); } // If the render target has been reset to its original size, remove the record for resetting it if (target.Size == originalTargetSize) { this.originalTargetSizes.Remove(targetRef); } } }