protected ATMVolsRankGroup(FXGroup group_) { var currencies = Singleton<FXIDs>.Instance.Where(x => x.IsGroup(group_)).ToArray(); var oneWeek = new ConstructGen<double>(currencies.Select(x => x.Code).ToArray()); var oneMonth = new ConstructGen<double>(currencies.Select(x => x.Code).ToArray()); for (int i = 0; i < currencies.Length; ++i) { { var vols = BbgTalk.HistoryRequester.GetHistory(DataConstants.DATA_START, currencies[i].AtTheMoneyVolTicker_1W, "PX_LAST", false); oneWeek.SetColumnValues(i, vols); } { var vols = BbgTalk.HistoryRequester.GetHistory(DataConstants.DATA_START, currencies[i].AtTheMoneyVolTicker_1M, "PX_LAST", false); oneMonth.SetColumnValues(i, vols); } } { oneWeek.SortKeys(); var avg1W = oneWeek.AvgRows(); ATM_1W_Avg = avg1W; ATM_1W_o6M = avg1W.ToPercentileRanked(126); ATM_1W_o1Y = avg1W.ToPercentileRanked(252); } { oneMonth.SortKeys(); var avg1M = oneMonth.AvgRows(); ATM_1M_Avg = avg1M; ATM_1M_o6M = avg1M.ToPercentileRanked(126); ATM_1M_o1Y = avg1M.ToPercentileRanked(252); } }
private static void PlayClickSound(FXGroup audioOutput) { if (audioOutput != null) { audioOutput.audio.Play(); } }
/*public override void onPartDestroy() * { * this.VPI.scanVessel(); * }*/ public void init() { if (PowSys == null) { PowSys = new LCARS_PowerSystem(); PowSys.SetShip(this.CurrentMotherShip); PT1 = this.PowSys.setPowerTaker("TransporterSystem", "SubSystem", 1250, 2500, 500); } if (planetScanner == null) { planetScanner = new LCARS_PlanetScanner(); LCARS_Utilities.SetLoadDistance(100000, 100000); } /* */ if (TransporterSound == null) { TransporterSound = new FXGroup("TransporterSound"); GameObject audioObj = new GameObject(); audioObj.transform.position = FlightGlobals.ActiveVessel.transform.position; audioObj.transform.parent = FlightGlobals.ActiveVessel.transform; // add to parent TransporterSound.audio = audioObj.AddComponent <AudioSource>(); TransporterSound.audio.dopplerLevel = 0f; TransporterSound.audio.Stop(); TransporterSound.audio.clip = GameDatabase.Instance.GetAudioClip(TransporterSoundFile); TransporterSound.audio.loop = false; TransporterSound.audio.Play(); TransporterSound.audio.enabled = false; TransporterSound.audio.time = 0; } }
private FXGroup createAudio(GameObject obj, string audioPath) { if (obj == null) { return(null); } FXGroup fXGroup = new FXGroup("lockHasp"); fXGroup.audio = obj.AddComponent <AudioSource> (); fXGroup.audio.volume = GameSettings.SHIP_VOLUME; fXGroup.audio.rolloffMode = AudioRolloffMode.Logarithmic; fXGroup.audio.dopplerLevel = 0; fXGroup.audio.maxDistance = 30; fXGroup.audio.loop = false; fXGroup.audio.playOnAwake = false; if (GameDatabase.Instance.ExistsAudioClip(audioPath)) { fXGroup.audio.clip = GameDatabase.Instance.GetAudioClip(audioPath); } else { printDebug("No clip found with path " + audioPath); } return(fXGroup); }
public void Start() { if (string.IsNullOrEmpty(soundURL)) { JUtil.LogMessage(this, "JSIInternalBackgroundNoise called with no soundURL"); Destroy(this); return; } if (needsElectricCharge) { RPMVesselComputer comp = RPMVesselComputer.Instance(vessel); comp.UpdateDataRefreshRate(soundCheckRate); electricChargeReserve = comp.ProcessVariable(resourceName).MassageToFloat(); } audioOutput = new FXGroup("RPM" + internalModel.internalName + vessel.id); audioOutput.audio = internalModel.gameObject.AddComponent <AudioSource>(); audioOutput.audio.clip = GameDatabase.Instance.GetAudioClip(soundURL.EnforceSlashes()); audioOutput.audio.Stop(); audioOutput.audio.volume = GameSettings.SHIP_VOLUME * soundVolume; audioOutput.audio.rolloffMode = AudioRolloffMode.Logarithmic; audioOutput.audio.maxDistance = 10f; audioOutput.audio.minDistance = 8f; audioOutput.audio.dopplerLevel = 0f; audioOutput.audio.panStereo = 0f; audioOutput.audio.playOnAwake = false; audioOutput.audio.priority = 255; audioOutput.audio.loop = true; audioOutput.audio.pitch = 1f; }
public override void OnStart(PartModule.StartState state) { SoundManager.LoadSound("FTLDriveContinued/Sounds/drive_sound", "DriveSound"); driveSound = new FXGroup("DriveSound"); SoundManager.CreateFXSound(part, driveSound, "DriveSound", true, 50f); animStages = animationNames.Split(',').Select(a => a.Trim()).ToArray(); SetUpAnimation(animStages[0], this.part, WrapMode.Loop); UpdateEvents(); containerStates = states.ToArray(); if (driveActive) { availableFtlDrives.Add(this); } try { this.state = DriveState.IDLE; if (state != StartState.Editor) { navCom.Source = FlightGlobals.ActiveVessel; } } catch (Exception ex) { print(String.Format("[FTLDriveContinued] Error in OnStart - {0}", ex.ToString())); } base.OnStart(state); }
public static bool createGroup(Part part, FXGroup group, string name, float distance, float spread, bool isloop, bool isLinearRolloff, bool bypassEffects) { if (name != string.Empty) { if (!GameDatabase.Instance.ExistsAudioClip (name)) { Debug.LogError ("[DynamicSFX] AudioFile " + name + " not found"); return false; } if(part == null) { group.audio = Camera.main.gameObject.AddComponent<AudioSource>(); }else{ group.audio = part.gameObject.AddComponent<AudioSource> (); } group.audio.dopplerLevel = 0f; group.audio.panLevel = 1f; group.audio.clip = GameDatabase.Instance.GetAudioClip (name); group.audio.loop = isloop; group.audio.maxDistance = distance; group.audio.spread = spread; group.audio.playOnAwake = false; group.audio.bypassEffects = bypassEffects; if (isLinearRolloff == true) { group.audio.rolloffMode = AudioRolloffMode.Linear; } else { group.audio.rolloffMode = AudioRolloffMode.Logarithmic; } Debug.Log("[DynamicSFX] Added " + name + ".* in FXGroup " + group.name + " for Part = " + part.name); return true; } return false; }
//private AudioHighPassFilter highPassFilter; //private float highPassTest = 100.0f; /// <summary> /// Fills an FXGroup with sound values /// </summary> /// <param name="group">The group that will receive a new sound</param> /// <param name="name">The name of the sound in the game database. No file extensions. e.g. Firespitter\Sounds\sound_fspropidle</param> /// <param name="loop">Does the sound loop by default?</param> /// <returns></returns> public bool createGroup(FXGroup group, string name, bool loop) { if (name != string.Empty) { if (!GameDatabase.Instance.ExistsAudioClip(name)) { return(false); } group.audio = gameObject.AddComponent <AudioSource>(); group.audio.playOnAwake = false; group.audio.loop = loop; //group.audio.rolloffMode = AudioRolloffMode.Linear; // audio gradual cutoff is too sudden/choppy with Linear group.audio.rolloffMode = AudioRolloffMode.Logarithmic; group.audio.dopplerLevel = 0f; // makes audio sound too distorted, so I set to 0 (disabled) group.audio.volume = GameSettings.SHIP_VOLUME; //group.audio.panStereo = 0f; group.audio.spatialBlend = 1f; group.audio.clip = GameDatabase.Instance.GetAudioClip(name); //highPassFilter = group.audio.GetComponent<AudioHighPassFilter>(); return(true); } return(false); }
public static bool createFXSound(Part part, FXGroup group, string sndPath, bool loop, float maxDistance = 30f) { group.audio = part.gameObject.AddComponent <AudioSource>(); group.audio.volume = GameSettings.SHIP_VOLUME; group.audio.rolloffMode = AudioRolloffMode.Linear; group.audio.dopplerLevel = 0f; group.audio.spatialBlend = 1f; group.audio.maxDistance = maxDistance; group.audio.loop = loop; group.audio.playOnAwake = false; if (GameDatabase.Instance.ExistsAudioClip(sndPath)) { group.audio.clip = GameDatabase.Instance.GetAudioClip(sndPath); return(true); } else { Logger.logError("Sound not found in the game database !"); ScreenMessages.PostScreenMessage( string.Format("Sound file : {0} has not been found, please check your KIS installation !", sndPath), 10, ScreenMessageStyle.UPPER_CENTER); return(false); } }
private void ScrapeSound(FXGroup sound, float speed) { if (!_soundInstantiated) { SetupAudio(); } if (sound == null || sound.audio == null) { return; } if (speed > minScrapeSpeed) { if (!sound.audio.isPlaying) { sound.audio.Play(); } sound.audio.pitch = 1 + Mathf.Log(speed) / 5; if (speed < scrapeFadeSpeed) { // Fade out at low speeds. sound.audio.volume = speed / scrapeFadeSpeed * volume * GameSettings.SHIP_VOLUME; } else { sound.audio.volume = volume * GameSettings.SHIP_VOLUME; } } else { sound.audio.Stop(); } }
public void OnDestroy() { // Switch tourists back Log.dbg("entered OnDestroy"); try { if (null == FlightGlobals.VesselsLoaded) { return; } Log.dbg("VesselsLoaded: {0}", FlightGlobals.VesselsLoaded); foreach (Vessel v in FlightGlobals.VesselsLoaded) { if (null == v) { continue; // Weird behaviour on KSP 1.10? } Log.dbg("restoring vessel {0}", v.name); List <ProtoCrewMember> crewList = v.GetVesselCrew(); if (null == v.GetVesselCrew()) { continue; // Weird behaviour on KSP 1.10? } foreach (ProtoCrewMember crew in crewList) { if (null == crew) { continue; // Weird behaviour on KSP 1.10? } Log.dbg("restoring crew={0}", crew.name); if (Tourist.isTourist(crew)) { crew.type = ProtoCrewMember.KerbalType.Tourist; } } } } catch (Exception e) { Log.error(e, "Got Exception while attempting to access loaded vessels"); } GameEvents.onVesselRecovered.Remove(OnVesselRecoveredOffGame); GameEvents.onKerbalLevelUp.Remove(OnKerbalLevelUp); GameEvents.onCrewOnEva.Remove(OnEvaStart); GameEvents.onCrewBoardVessel.Remove(OnCrewBoardVessel); GameEvents.onVesselWillDestroy.Remove(OnVesselWillDestroy); GameEvents.onVesselLoaded.Add(OnVesselLoad); GameEvents.onVesselChange.Remove(OnVesselChange); GameEvents.onVesselCreate.Remove(OnVesselCreate); GameEvents.onNewVesselCreated.Remove(OnNewVesselCreated); GameEvents.onAttemptEva.Remove(OnAttemptEVA); GameEvents.onFlightReady.Remove(OnFlightReady); GameEvents.onVesselGoOffRails.Remove(OnVesselGoOffRails); tourists = null; factory = null; // do we really need this? smile = false; taken = false; fx = null; }
public void Start() { if (string.IsNullOrEmpty(soundURL)) { JUtil.LogMessage(this, "JSIInternalBackgroundNoise called with no soundURL"); Destroy(this); return; } if (needsElectricCharge) { RPMVesselComputer comp = RPMVesselComputer.Instance(vessel); comp.UpdateDataRefreshRate(soundCheckRate); electricChargeReserve = (float)comp.ProcessVariable("SYSR_ELECTRICCHARGE"); } audioOutput = new FXGroup("RPM" + internalModel.internalName + vessel.id); audioOutput.audio = internalModel.gameObject.AddComponent<AudioSource>(); audioOutput.audio.clip = GameDatabase.Instance.GetAudioClip(soundURL.EnforceSlashes()); audioOutput.audio.Stop(); audioOutput.audio.volume = GameSettings.SHIP_VOLUME * soundVolume; audioOutput.audio.rolloffMode = AudioRolloffMode.Logarithmic; audioOutput.audio.maxDistance = 10f; audioOutput.audio.minDistance = 8f; audioOutput.audio.dopplerLevel = 0f; audioOutput.audio.panLevel = 0f; audioOutput.audio.playOnAwake = false; audioOutput.audio.priority = 255; audioOutput.audio.loop = true; audioOutput.audio.pitch = 1f; }
protected override void OnInvokeEnd() { base.OnInvokeEnd(); vfx.Stop(); vfx = null; }
private void InitialiseSound(FXGroup soundGroup, string soundFile, float volume, bool loop) { if (!GameDatabase.Instance.ExistsAudioClip(soundFile)) { Debug.LogError("[WheelSounds] Audio file not found: " + soundFile); return; } if (soundGroup == null) { Debug.LogError("[WheelSounds] FXGroup is null"); return; } soundGroup.audio = gameObject.AddComponent <AudioSource>(); soundGroup.audio.clip = GameDatabase.Instance.GetAudioClip(soundFile); soundGroup.audio.dopplerLevel = 0f; soundGroup.audio.rolloffMode = AudioRolloffMode.Logarithmic; soundGroup.audio.Stop(); soundGroup.audio.loop = loop; soundGroup.audio.spatialBlend = 1; soundGroup.audio.volume = volume * GameSettings.SHIP_VOLUME; if (loop) { // Seek to a random position in the sound file so we don't have harmonic effects with other wheels. soundGroup.audio.time = UnityEngine.Random.Range(0, soundGroup.audio.clip.length); } }
public void Start() { try { comp = RasterPropMonitorComputer.Instantiate(internalProp); textObjTransform = internalProp.FindModelTransform(labelTransform); textObj = InternalComponents.Instance.CreateText(fontName, fontSize, textObjTransform, string.Empty); activeLabel = 0; SmarterButton.CreateButton(internalProp, switchTransform, Click); ConfigNode moduleConfig = null; foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP")) { if (node.GetValue("name") == internalProp.propName) { moduleConfig = node.GetNodes("MODULE")[moduleID]; ConfigNode[] variableNodes = moduleConfig.GetNodes("VARIABLESET"); for (int i = 0; i < variableNodes.Length; i++) { try { labelsEx.Add(new VariableLabelSet(variableNodes[i])); } catch (ArgumentException e) { JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID); } } break; } } // Fallback: If there are no VARIABLESET blocks, we treat the module configuration itself as a variableset block. if (labelsEx.Count < 1 && moduleConfig != null) { try { labelsEx.Add(new VariableLabelSet(moduleConfig)); } catch (ArgumentException e) { JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID); } } if (labelsEx.Count == 0) { JUtil.LogMessage(this, "No labels defined."); throw new ArgumentException("No labels defined"); } colorShiftRenderer = internalProp.FindModelComponent<Renderer>(coloredObject); if (labelsEx[activeLabel].hasColor) { colorShiftRenderer.material.SetColor(colorName, labelsEx[activeLabel].color); } if (labelsEx[activeLabel].hasText) { textObj.text.Text = StringProcessor.ProcessString(labelsEx[activeLabel].labelText, comp); } audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false); JUtil.LogMessage(this, "Configuration complete in prop {1}, supporting {0} variable indicators.", labelsEx.Count, internalProp.propID); } catch { JUtil.AnnoyUser(this); enabled = false; throw; } }
public void SpawnPhotonTorpedo(Vector3 location, Target t) { try { TorpedoSound = new FXGroup("TorpedoSound"); GameObject audioObj = new GameObject(); audioObj.transform.position = FlightGlobals.ActiveVessel.transform.position; audioObj.transform.parent = FlightGlobals.ActiveVessel.transform; // add to parent TorpedoSound.audio = audioObj.AddComponent <AudioSource>(); TorpedoSound.audio.dopplerLevel = 0f; TorpedoSound.audio.Stop(); TorpedoSound.audio.clip = GameDatabase.Instance.GetAudioClip(TorpedoSoundFile); TorpedoSound.audio.loop = false; TorpedoSound.audio.Play(); TorpedoSound.audio.enabled = false; if (TorpedoSound != null && TorpedoSound.audio != null) { float soundVolume = GameSettings.SHIP_VOLUME * TorpedoSoundVolume; TorpedoSound.audio.enabled = true; TorpedoSound.audio.volume = soundVolume; } } catch (Exception ex) { Debug.LogError("ExplosionSound Error Explode: " + ex.Message); } float TorpedoPower = t.TorpedoYield; TorpedoClone = null; Collider[] myColliders = FlightGlobals.ActiveVessel.GetComponentsInChildren <Collider>(); Bounds myBounds = new Bounds(FlightGlobals.ActiveVessel.transform.position, Vector3.zero); foreach (Collider nextCollider in myColliders) { myBounds.Encapsulate(nextCollider.bounds); } _PhotonTorpedo bar = new _PhotonTorpedo(); TorpedoClone = bar.get_PhotonTorpedo(myBounds, FlightGlobals.ActiveVessel, FlightGlobals.ActiveVessel.GetWorldPos3D()); Vector3 TargetVector = TorpedoClone.transform.position - t.ship.transform.position; TorpedoClone.transform.rotation = Quaternion.LookRotation(TargetVector.normalized); PhotonTorpedoType PTT = new PhotonTorpedoType(); PTT.ID = TorpedoCounter++; PTT.Target = t; PTT.TorpedoClone = TorpedoClone; PTT.TorpedoYield = PTT.Target.TorpedoYield; PTT.prevPos = TorpedoClone.transform.position; PTT.savedVel = new Vector3(0, 0, 0); TorpedoList.Add(TorpedoClone.name, PTT); }
private void reinitEvents(Vessel v) { Log.dbg("entered reinitEvents for vessel {0}", v); foreach (Part p in v.Parts) { if (!"kerbalEVA".Equals(p.name)) { continue; } this.reinitEvents(p); } KerbalEVA evaCtl = v.evaController; if (null == evaCtl) { return; } List <ProtoCrewMember> roster = v.GetVesselCrew(); if (0 == roster.Count) { Log.dbg("Vessel has no crew."); return; } ProtoCrewMember crew = roster[0]; String kerbalName = crew.name; Log.dbg("evCtl found; checking name: {0}", kerbalName); if (!tourists.TryGetValue(kerbalName, out Tourist t)) { return; } Log.dbg("among tourists: {0}", kerbalName); t.smile = false; t.taken = false; if (!Tourist.isTourist(crew)) { Log.dbg("...but is a crew, not a tourist!"); return; // not a real tourist } // Change crew type right away to avoid them being crew after recovery crew.type = ProtoCrewMember.KerbalType.Tourist; EVASupport.INSTANCE.disableEvaEvents(v, t.hasAbility("EVA")); this.addSelfie(evaCtl); Log.dbg("Initializing sound"); // Should we always invalidate cache??? fx = null; getOrCreateAudio(evaCtl.part.gameObject); }
public void Initialize(string soundPath) { //Initializing stuff; bigBenPlayer = new GameObject("BigBenPlayer"); //Makes the GameObject source = new FXGroup("BigBenPlayer"); source.audio = bigBenPlayer.AddComponent <AudioSource>(); loadedClip = GameDatabase.Instance.GetAudioClip(soundPath); source.audio.volume = 0.5f; source.audio.spatialBlend = 0; }
public void Initialize(string soundPath) { //Initializing stuff; // dangeralertplayer = new GameObject("dangeralertplayer"); source = new FXGroup("MSSRBsAlarmPlayer"); source.audio = dangeralertplayer.AddComponent <AudioSource>(); loadedClip = GameDatabase.Instance.GetAudioClip(soundPath); source.audio.volume = 0.5f; source.audio.spatialBlend = 0; }
protected override void early_setup(StartState state) { base.early_setup(state); NoGUI = true; LaunchWithPunch = true; PayloadFixedInFlight = true; update_crew_capacity(CrewCapacity); Events["EditName"].active = false; FX = part.findFxGroup(FxGroup); //setup fairings if (!find_fairings()) { return; } if (jettisoned) { fairings.ForEach(f => f.gameObject.SetActive(false)); part.DragCubes.SetCubeWeight("Fairing ", 0f); part.DragCubes.SetCubeWeight("Clean ", 1f); part.UpdateCoMOffset(BaseCoMOffset); part.stagingIcon = string.Empty; SetStaging(false); part.UpdateStageability(true, true); } else { fairings.ForEach(f => f.gameObject.SetActive(true)); part.DragCubes.SetCubeWeight("Fairing ", 1f); part.DragCubes.SetCubeWeight("Clean ", 0f); part.stagingIcon = "DECOUPLER_HOR"; part.UpdateStageability(true, true); } update_PAW(); //setup attach nodes decoupleNodes.Clear(); foreach (var nodeID in Utils.ParseLine(DecoupleNodes, Utils.Comma)) { var node = part.FindAttachNode(nodeID); if (node == null) { continue; } decoupleNodes.Add(node); if (jettisoned) { disable_decouplers(node.id); } } JettisonDirection.Normalize(); if (vessel != null) { vessel.SpawnCrew(); } }
public void FixedUpdate() { if (!HighLogic.LoadedSceneIsFlight) { return; } checkApproachingGeeLimit(); if (!smile) { return; } int sec = (DateTime.Now - selfieTime).Seconds; if (!taken && sec > 1) { printDebug("Getting snd"); FXGroup snd = getOrCreateAudio(FlightGlobals.ActiveVessel.evaController.gameObject); if (snd != null) { snd.audio.Play(); } else { printDebug("snd is null"); } String fname = "../Screenshots/" + generateSelfieFileName(); printDebug("wrting file " + fname); ScreenCapture.CaptureScreenshot(fname); taken = true; } if (sec > 5) { smile = false; taken = false; /*FlightCamera camera = FlightCamera.fetch; * camera.transform.position = savedCameraPosition; * camera.transform.rotation = savedCameraRotation; * camera.SetTarget (savedCameraTarget, FlightCamera.TargetMode.Transform);*/ //FlightGlobals.ActiveVessel.evaController.part.Events ["TakeSelfie"].active = true; GameEvents.onShowUI.Fire(); ScreenMessages.PostScreenMessage("Selfie taken!"); } else { Smile(); } }
public void LoadSound(string ID, string URL) { player = new GameObject(); player.name = "NodeAlertPlayer" + ID; audioSource = new FXGroup(ID); audioSource.audio = player.AddComponent <AudioSource>() as AudioSource; audioSource.audio.clip = GameDatabase.Instance.GetAudioClip(Pathfinder.dllFolderName() + URL); audioSource.audio.volume = GameSettings.SHIP_VOLUME * Settings.VolumeMulitplicator; Debug.Log("Loaded"); }
/// <summary> /// Tear everything down. /// </summary> public void OnDestroy() { for (int i = 0; i < action.Count; ++i) { action[i].TearDown(); } // TODO: Do any of these need explicitly released? switchAudio = null; loopingAudio = null; anim = null; }
public static void CreateFXSound(Part part, FXGroup group, string defaultSound, bool loop, float maxDistance = 30f) { group.audio = (part as UnityEngine.Component ?? Camera.main).gameObject.AddComponent <AudioSource>(); group.audio.volume = GameSettings.SHIP_VOLUME; group.audio.rolloffMode = AudioRolloffMode.Linear; group.audio.dopplerLevel = 0f; group.audio.spatialBlend = 1f; group.audio.maxDistance = maxDistance; group.audio.loop = loop; group.audio.playOnAwake = false; group.audio.clip = GetSound(defaultSound); }
public void Start() { comp = RasterPropMonitorComputer.Instantiate(internalProp); textObjTransform = internalProp.FindModelTransform(labelTransform); textObj = InternalComponents.Instance.CreateText(fontName, fontSize, textObjTransform, string.Empty); activeLabel = 0; SmarterButton.CreateButton(internalProp, switchTransform, Click); ConfigNode moduleConfig = null; foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP")) { if (node.GetValue("name") == internalProp.propName) { moduleConfig = node.GetNodes("MODULE")[moduleID]; ConfigNode[] variableNodes = moduleConfig.GetNodes("VARIABLESET"); for (int i = 0; i < variableNodes.Length; i++) { try { labelsEx.Add(new VariableLabelSet(variableNodes[i])); } catch (ArgumentException e) { JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID); } } break; } } // Fallback: If there are no VARIABLESET blocks, we treat the module configuration itself as a variableset block. if (labelsEx.Count < 1 && moduleConfig != null) { try { labelsEx.Add(new VariableLabelSet(moduleConfig)); } catch (ArgumentException e) { JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID); } } colorShiftRenderer = internalProp.FindModelComponent <Renderer>(coloredObject); if (labelsEx[activeLabel].hasColor) { colorShiftRenderer.material.SetColor(colorName, labelsEx[activeLabel].color); } textObj.text.Text = StringProcessor.ProcessString(labelsEx[activeLabel].labelText, comp); audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false); JUtil.LogMessage(this, "Configuration complete in prop {1}, supporting {0} variable indicators.", labelsEx.Count, internalProp.propID); }
public void OnDestroy() { //JUtil.LogMessage(this, "OnDestroy()"); if (colorShiftMaterial != null) { UnityEngine.Object.Destroy(colorShiftMaterial); colorShiftMaterial = null; } actionHandler = null; transferGetter = null; transferSetter = null; audioOutput = null; loopingOutput = null; }
public void lockHasp(Part latch) { printDebug($"part={latch.name}; id={latch.flightID}; fsm state={lockFSM.state}"); // If we're not restoring the state after timewarp/load, perform // what it takes to lock the latch if (lockFSM.state == LockFSM.State.Locking) { #if (KSP_151 || KSP_161 || KSP_171) float num = (float)part.RequestResource("ElectricCharge", (double)(new decimal(ecConsumption))); #else float num = part.RequestResource("ElectricCharge", ecConsumption); #endif if (num < ecConsumption) { ScreenMessages.PostScreenMessage("Not enough electric charge to lock the hasp!"); return; } isSlave = false; // If we use genderless locking, tell the other part that we are leading if (isLockablePart(latch) && latch.Modules.Contains("LockMechanism")) { // Both locks could be primed. In that case assign master status // to the part with lesser flightID otherLock = (LockMechanism)latch.Modules ["LockMechanism"]; printDebug($"our fsm state = {lockFSM.state}, other fsm state = {otherLock.lockFSM.state}"); if (otherLock.lockFSM.state != LockFSM.State.Locking || part.flightID < latch.flightID) { printDebug("acquiring master status"); otherLock.setSlaveLock(part.flightID); isMaster = true; } else { printDebug("submitting to slave status"); isSlave = true; } } if (!isSlave) { if (lockSound == null) { lockSound = createAudio(part.gameObject, lockSoundPath); } lockSound.audio.Play(); } } StartCoroutine(finalizeLock(latch)); }
private void FixEnginesFX(ModuleEngines engine) { // Why this is needed : // When engines OnStart is called, the module does this : // - It find the FX XXX on the part // - It duplicate the particule emitter of this FX into a new FX in the engine XXXGroups list, one for each thrusttransform // - It remove the particule emitter from the original FX on the part // - It copy back the new FX named prefix + XXX + index of transform to the part FX list // So when we call Onstart again, the init method can't find the emitters since they are removed from the base FX on the part // To fix this we need to manually re-link the engine XXXGroups with the FX that still are on the part, and call the setup method AutoPlaceFXGroup // Remove garbage FX on the part created by previous loads engine.part.fxGroups.FindAll(p => (p.name.Contains(engine.fxGroupPrefix + "Flameout") || p.name.Contains(engine.fxGroupPrefix + "Running") || p.name.Contains(engine.fxGroupPrefix + "Power")) && !p.isValid).Clear(); // Reset the module FX groups engine.flameoutGroups.Clear(); engine.powerGroups.Clear(); engine.runningGroups.Clear(); // Relink the part FX to the module FX list for (int i = 0; i < engine.thrustTransforms.Count; i++) { FXGroup flameoutFX = engine.part.fxGroups.Find(p => p.name == engine.fxGroupPrefix + "Flameout" + i && p.isValid); if (flameoutFX != null) { engine.AutoPlaceFXGroup(flameoutFX, engine.thrustTransforms[i]); engine.flameoutGroups.Add(flameoutFX); } FXGroup runningFX = engine.part.fxGroups.Find(p => p.name == engine.fxGroupPrefix + "Running" + i && p.isValid); if (runningFX != null) { engine.AutoPlaceFXGroup(runningFX, engine.thrustTransforms[i]); engine.runningGroups.Add(runningFX); } FXGroup powerFX = engine.part.fxGroups.Find(p => p.name == engine.fxGroupPrefix + "Power" + i && p.isValid); if (powerFX != null) { engine.AutoPlaceFXGroup(powerFX, engine.thrustTransforms[i]); engine.powerGroups.Add(powerFX); } } }
public void Start() { Log.Info("[DangIt] [AlarmManager] Starting..."); audioSource = new FXGroup("DangItAlarm"); Log.Info("[DangIt] [AlarmManager] Creating Dictionary"); if (loops == null) { loops = new Dictionary <FailureModule, int>(); //Reset counter, so on logic pass we play it failedParts = new Dictionary <FailedPart, int>(); } GameEvents.onShowUI.Add(showUI); GameEvents.onHideUI.Add(hideUI); //DontDestroyOnLoad(this); }
// Unlocking takes time as well public void unlockHasp() { setEmissiveColor(); setMenuEvents(); if (unlockSound == null) { unlockSound = createAudio(part.gameObject, unlockSoundPath); } if (!isSlave) { // Not playing two sounds at once unlockSound.audio.Play(); } StartCoroutine(finalizeUnlock(false)); }
private void SetupAudio() { HatchOpenSound = new FXGroup("HatchOpen"); HatchOpenSound.audio = IvaGameObject.AddComponent <AudioSource>(); HatchOpenSound.audio.dopplerLevel = 0f; HatchOpenSound.audio.Stop(); HatchOpenSound.audio.clip = GameDatabase.Instance.GetAudioClip(HatchOpenSoundFile); HatchOpenSound.audio.loop = false; HatchCloseSound = new FXGroup("HatchClose"); HatchCloseSound.audio = IvaGameObject.AddComponent <AudioSource>(); HatchCloseSound.audio.dopplerLevel = 0f; HatchCloseSound.audio.Stop(); HatchCloseSound.audio.clip = GameDatabase.Instance.GetAudioClip(HatchCloseSoundFile); HatchCloseSound.audio.loop = false; }
public void Start() { print("[DangIt] [AlarmManager] Starting..."); print("[DangIt] [AlarmManager] Setting Volume..."); audioSource = new FXGroup("DangItAlarm"); audioSource.audio = Camera.main.gameObject.AddComponent <AudioSource>(); // audio = new AudioSource(); audioSource.audio.spatialBlend = 0f; //This disable the game scaling volume with distance from source audioSource.audio.volume = 0f; Logger.Info("[DangIt] [AlarmManager] Creating Clip"); audioSource.audio.clip = GameDatabase.Instance.GetAudioClip("DangIt/Sounds/alarm"); //Load alarm sound Logger.Info("[DangIt] [AlarmManager] Creating Dictionary"); this.loops = new Dictionary <FailureModule, int>(); //Reset counter, so on logic pass we play it }
public void SetupAudio(GameObject gameObject) { ActivateSound = new FXGroup("HatchOpen"); ActivateSound.audio = gameObject.AddComponent <AudioSource>(); ActivateSound.audio.dopplerLevel = 0f; ActivateSound.audio.Stop(); ActivateSound.audio.clip = GameDatabase.Instance.GetAudioClip(ActivateSoundFile); ActivateSound.audio.loop = false; DeactivateSound = new FXGroup("HatchClose"); DeactivateSound.audio = gameObject.AddComponent <AudioSource>(); DeactivateSound.audio.dopplerLevel = 0f; DeactivateSound.audio.Stop(); DeactivateSound.audio.clip = GameDatabase.Instance.GetAudioClip(DeactivateSoundFile); DeactivateSound.audio.loop = false; }
// Called at beginning of flight scene after onPartStart() // also when part comes in range of focussed ship (<2.5km) after onPartStart() protected override void onFlightStart() { Debug.Log("test"); foreach (Part p in children) { if (p is ANPPPulseFuel && this.topNode.attachedPart == p) { fuelSupply = p as ANPPPulseFuel; } } if (fuelSupply == null && parent is ANPPPulseFuel && this.topNode.attachedPart == parent) { fuelSupply = parent as ANPPPulseFuel; } Debug.Log("test2"); this.explosionGroup = base.findFxGroup("explosionGroup"); }
//sound (from the KAS mod; KAS_Shared class) public static bool createFXSound(Part part, FXGroup group, string sndPath, bool loop, float maxDistance = 30f) { group.audio = part.gameObject.AddComponent <AudioSource>(); group.audio.volume = GameSettings.SHIP_VOLUME; group.audio.rolloffMode = AudioRolloffMode.Logarithmic; group.audio.dopplerLevel = 0f; group.audio.maxDistance = maxDistance; group.audio.loop = loop; group.audio.playOnAwake = false; if (GameDatabase.Instance.ExistsAudioClip(sndPath)) { group.audio.clip = GameDatabase.Instance.GetAudioClip(sndPath); return(true); } Message(10, "Sound file : {0} has not been found, please check your Hangar installation", sndPath); return(false); }
private void add(WtsSeriesAnalyzer analyzer_, SI.Controls.Panel panel_, FXGroup group_) { ZoneChart zc = new ZoneChart(); zc.Dock = DockStyle.Fill; panel_.ClientArea.Controls.Add(zc); double[] pnl = new double[analyzer_.Performance.Dates.Count]; double[] wts = new double[analyzer_.SourceWts.Dates.Count]; for (int i = 0; i < analyzer_.Performance.ArrayLength; ++i) { Currency ccy = Singleton<FXIDs>.Instance[i]; if (ccy.IsGroup(group_) == false) continue; for (int j = 0; j < pnl.Length; ++j) { pnl[j] += analyzer_.Performance.GetValue(analyzer_.Performance.Dates[j], i); } for (int j = 0; j < wts.Length; ++j) { wts[j] += analyzer_.SourceWts.GetValue(analyzer_.SourceWts.Dates[j], i); } DatedDataCollectionGen<double> perf = new DatedDataCollectionGen<double>(analyzer_.Performance.Dates.ToArray(), pnl); DatedDataCollectionGen<double> wwww = new DatedDataCollectionGen<double>(analyzer_.SourceWts.Dates.ToArray(), wts); if (m_startDate != null && m_endDate != null) { perf = perf.GetSubValues(m_startDate.Value, m_endDate.Value); wwww = wwww.GetSubValues(m_startDate.Value, m_endDate.Value); } zc.Create( new DatedDataCollectionGen<double>(perf.Dates, perf.Data.Cumulative()), wwww, new ZoneDefinition[] { new ZoneDefinition("Short",double.MinValue,0d,Color.IndianRed), new ZoneDefinition("Long",0d,double.MaxValue,Color.LightGreen) }); } }
protected override void OnInvokeStart() { base.OnInvokeStart(); controller = source.GetComponent<ActorController>(); controller.actor.physics.velocity += controller.actor.Forward * force; if (vfx != null) { vfx.Stop(); vfx = null; } GameObject vfxGO = GameObjectFactory.Instance.Spawn("p-DashVFX"); vfx = vfxGO.GetComponent<FXGroup>(); vfx.transform.parent = controller.transform.FindTransformInChildren("Body"); vfx.transform.localPosition = Vector3.zero; AudioManager.Instance.PlayOneShot(controller.actor.audioSource, AudioManager.Instance.dash); }
public void Start() { if (needsElectricCharge) { comp = RasterPropMonitorComputer.Instantiate(internalProp); comp.UpdateRefreshRates(soundCheckRate, soundCheckRate); electricChargeReserve = (double)comp.ProcessVariable("ELECTRIC"); } audioOutput = new FXGroup("RPM" + internalModel.internalName + vessel.id); audioOutput.audio = internalModel.gameObject.AddComponent<AudioSource>(); audioOutput.audio.clip = GameDatabase.Instance.GetAudioClip(soundURL.EnforceSlashes()); audioOutput.audio.Stop(); audioOutput.audio.volume = GameSettings.SHIP_VOLUME * soundVolume; audioOutput.audio.rolloffMode = AudioRolloffMode.Logarithmic; audioOutput.audio.maxDistance = 10f; audioOutput.audio.minDistance = 8f; audioOutput.audio.dopplerLevel = 0f; audioOutput.audio.panLevel = 0f; audioOutput.audio.playOnAwake = false; audioOutput.audio.priority = 255; audioOutput.audio.loop = true; audioOutput.audio.pitch = 1f; }
public static bool createFXSound(Part part, FXGroup group, string sndPath, bool loop, float maxDistance = 30f) { group.audio = part.gameObject.AddComponent<AudioSource>(); group.audio.volume = GameSettings.SHIP_VOLUME; group.audio.rolloffMode = AudioRolloffMode.Linear; group.audio.dopplerLevel = 0f; group.audio.panLevel = 1f; group.audio.maxDistance = maxDistance; group.audio.loop = loop; group.audio.playOnAwake = false; if (GameDatabase.Instance.ExistsAudioClip(sndPath)) { group.audio.clip = GameDatabase.Instance.GetAudioClip(sndPath); return true; } else { KAS_Shared.DebugError("Sound not found in the game database !"); ScreenMessages.PostScreenMessage("Sound file : " + sndPath + " as not been found, please check your KAS installation !", 10, ScreenMessageStyle.UPPER_CENTER); return false; } }
/// <summary> /// Start everything up and get it configured. /// </summary> public void Start() { try { rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true); Transform textObjTransform = internalProp.FindModelTransform(transformName); Vector3 localScale = internalProp.transform.localScale; Transform offsetTransform = new GameObject().transform; offsetTransform.gameObject.name = "JSILabel-" + this.internalProp.propID + "-" + this.GetHashCode().ToString(); offsetTransform.gameObject.layer = textObjTransform.gameObject.layer; offsetTransform.SetParent(textObjTransform, false); offsetTransform.Translate(transformOffset.x * localScale.x, transformOffset.y * localScale.y, 0.0f); textObj = offsetTransform.gameObject.AddComponent<JSITextMesh>(); font = JUtil.LoadFont(fontName, fontQuality); textObj.font = font; //textObj.fontSize = fontQuality; // This doesn't work with Unity-embedded fonts textObj.fontSize = font.fontSize; if (!string.IsNullOrEmpty(anchor)) { if (anchor == TextAnchor.LowerCenter.ToString()) { textObj.anchor = TextAnchor.LowerCenter; } else if (anchor == TextAnchor.LowerLeft.ToString()) { textObj.anchor = TextAnchor.LowerLeft; } else if (anchor == TextAnchor.LowerRight.ToString()) { textObj.anchor = TextAnchor.LowerRight; } else if (anchor == TextAnchor.MiddleCenter.ToString()) { textObj.anchor = TextAnchor.MiddleCenter; } else if (anchor == TextAnchor.MiddleLeft.ToString()) { textObj.anchor = TextAnchor.MiddleLeft; } else if (anchor == TextAnchor.MiddleRight.ToString()) { textObj.anchor = TextAnchor.MiddleRight; } else if (anchor == TextAnchor.UpperCenter.ToString()) { textObj.anchor = TextAnchor.UpperCenter; } else if (anchor == TextAnchor.UpperLeft.ToString()) { textObj.anchor = TextAnchor.UpperLeft; } else if (anchor == TextAnchor.UpperRight.ToString()) { textObj.anchor = TextAnchor.UpperRight; } else { JUtil.LogErrorMessage(this, "Unrecognized anchor '{0}' in config for {1} ({2})", anchor, internalProp.propID, internalProp.propName); } } if (!string.IsNullOrEmpty(alignment)) { if (alignment == TextAlignment.Center.ToString()) { textObj.alignment = TextAlignment.Center; } else if (alignment == TextAlignment.Left.ToString()) { textObj.alignment = TextAlignment.Left; } else if (alignment == TextAlignment.Right.ToString()) { textObj.alignment = TextAlignment.Right; } else { JUtil.LogErrorMessage(this, "Unrecognized alignment '{0}' in config for {1} ({2})", alignment, internalProp.propID, internalProp.propName); } } float sizeScalar = 32.0f / (float)font.fontSize; textObj.characterSize = fontSize * 0.00005f * sizeScalar; textObj.lineSpacing = textObj.lineSpacing * lineSpacing; // "Normal" mode if (string.IsNullOrEmpty(switchTransform)) { // Force oneshot if there's no variables: oneshot |= !labelText.Contains("$&$"); string sourceString = labelText.UnMangleConfigText(); if (!string.IsNullOrEmpty(sourceString) && sourceString.Length > 1) { // Alow a " character to escape leading whitespace if (sourceString[0] == '"') { sourceString = sourceString.Substring(1); } } labels.Add(new JSILabelSet(sourceString, rpmComp, oneshot)); if (!oneshot) { rpmComp.UpdateDataRefreshRate(refreshRate); } } else // Switchable mode { SmarterButton.CreateButton(internalProp, switchTransform, Click); audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false); foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP")) { if (node.GetValue("name") == internalProp.propName) { ConfigNode moduleConfig = node.GetNodes("MODULE")[moduleID]; ConfigNode[] variableNodes = moduleConfig.GetNodes("VARIABLESET"); for (int i = 0; i < variableNodes.Length; i++) { try { bool lOneshot = false; if (variableNodes[i].HasValue("oneshot")) { bool.TryParse(variableNodes[i].GetValue("oneshot"), out lOneshot); } if (variableNodes[i].HasValue("labelText")) { string lText = variableNodes[i].GetValue("labelText"); string sourceString = lText.UnMangleConfigText(); lOneshot |= !lText.Contains("$&$"); labels.Add(new JSILabelSet(sourceString, rpmComp, lOneshot)); if (!lOneshot) { rpmComp.UpdateDataRefreshRate(refreshRate); } } } catch (ArgumentException e) { JUtil.LogErrorMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID); } } break; } } } if (!string.IsNullOrEmpty(zeroColor)) { zeroColorValue = JUtil.ParseColor32(zeroColor, part, ref rpmComp); textObj.color = zeroColorValue; } bool usesMultiColor = false; if (!(string.IsNullOrEmpty(variableName) || string.IsNullOrEmpty(positiveColor) || string.IsNullOrEmpty(negativeColor) || string.IsNullOrEmpty(zeroColor))) { usesMultiColor = true; positiveColorValue = JUtil.ParseColor32(positiveColor, part, ref rpmComp); negativeColorValue = JUtil.ParseColor32(negativeColor, part, ref rpmComp); del = (Action<float>)Delegate.CreateDelegate(typeof(Action<float>), this, "OnCallback"); rpmComp.RegisterVariableCallback(variableName, del); registeredVessel = vessel.id; // Initialize the text color. Actually, callback registration takes care of that. } if (string.IsNullOrEmpty(emissive)) { if (usesMultiColor) { emissiveMode = EmissiveMode.active; } else { emissiveMode = EmissiveMode.always; } } else if (emissive.ToLower() == EmissiveMode.always.ToString()) { emissiveMode = EmissiveMode.always; } else if (emissive.ToLower() == EmissiveMode.never.ToString()) { emissiveMode = EmissiveMode.never; } else if (emissive.ToLower() == EmissiveMode.active.ToString()) { emissiveMode = EmissiveMode.active; } else if (emissive.ToLower() == EmissiveMode.passive.ToString()) { emissiveMode = EmissiveMode.passive; } else if (emissive.ToLower() == EmissiveMode.flash.ToString()) { if (flashRate > 0.0f) { emissiveMode = EmissiveMode.flash; fm = JUtil.InstallFlashModule(part, flashRate); if (fm != null) { fm.flashSubscribers += FlashToggle; } } else { emissiveMode = EmissiveMode.active; } } else { JUtil.LogErrorMessage(this, "Unrecognized emissive mode '{0}' in config for {1} ({2})", emissive, internalProp.propID, internalProp.propName); emissiveMode = EmissiveMode.always; } UpdateShader(); } catch (Exception e) { JUtil.LogErrorMessage(this, "Start failed in prop {1} ({2}) with exception {0}", e, internalProp.propID, internalProp.propName); labels.Add(new JSILabelSet("ERR", rpmComp, true)); } }
public SoundSource(Part part, string groupId) { this.part = part; isPlaying = false; motorSound = new FXGroup(groupId); }
/// <summary> /// Called when the part is started. /// </summary> /// <param name="state">The start state.</param> public override void OnStart(PartModule.StartState state) { base.OnStart(state); if (HighLogic.LoadedSceneIsFlight) { leakables = GetLeakables(); SoundManager.LoadSound(KMUtil.soundSource + "Tape", "Tape"); ductTapeSound = new FXGroup("ductTapeSound"); SoundManager.CreateFXSound(part, ductTapeSound, "Tape", false, 50f); if (failure != "" && leakables != null) { string leakName = failure.Substring(0, failure.Length - " leaking!".Length); foreach (PartResource r in leakables) { if (r.resourceName == leakName) { leak = r; Events["FixLeak"].active = true; Events["ApplyDuctTape"].active = true; break; } } if (!leak) { Logger.DebugError("Leak \"" + leakName + "\" not found!"); canLeak = false; failure = ""; } } } }
public void Start() { // If we're not in the correct location, there's no point doing anything. if (!InstallationPathWarning.Warn()) return; try { // Install the calculator module. comp = RasterPropMonitorComputer.Instantiate(internalProp); comp.UpdateRefreshRates(refreshTextRate, refreshDataRate); // Loading the font... fontTexture.Add(LoadFont(this, internalProp, fontTransform, false)); // Damn KSP's config parser!!! if (!string.IsNullOrEmpty(emptyColor)) emptyColorValue = ConfigNode.ParseColor32(emptyColor); if (!string.IsNullOrEmpty(defaultFontTint)) defaultFontTintValue = ConfigNode.ParseColor32(defaultFontTint); if (!string.IsNullOrEmpty(fontDefinition)) { JUtil.LogMessage(this, "Loading font definition from {0}", fontDefinition); fontDefinitionString = File.ReadAllLines(KSPUtil.ApplicationRootPath + "GameData/" + fontDefinition.EnforceSlashes(), Encoding.UTF8)[0]; } // We can pre-compute the rectangles the font characters will be copied from, this seems to make it slightly quicker... // although I'm not sure I'm not seeing things by this point. int fontLettersX = (fontTexture[0].width / fontLetterWidth); int fontLettersY = (fontTexture[0].height / fontLetterHeight); float letterSpanX = 1f / fontLettersX; float letterSpanY = 1f / fontLettersY; int lastCharacter = fontLettersX * fontLettersY; if (lastCharacter != fontDefinitionString.Length) { JUtil.LogMessage(this, "Warning, number of letters in the font definition does not match font bitmap size."); } for (int i = 0; i < lastCharacter && i < fontDefinitionString.Length; i++) { int xSource = i % fontLettersX; int ySource = (i - xSource) / fontLettersX; if (!fontCharacters.ContainsKey(fontDefinitionString[i])) fontCharacters[fontDefinitionString[i]] = new Rect(letterSpanX * xSource, letterSpanY * (fontLettersY - ySource - 1), letterSpanX, letterSpanY); } // And a little optimisation for superscript/subscript: fontLetterHalfHeight = fontLetterHeight / 2f; fontLetterHalfWidth = fontLetterWidth / 2f; fontLetterDoubleWidth = fontLetterWidth * 2f; // Now that is done, proceed to setting up the screen. screenTexture = new RenderTexture(screenPixelWidth, screenPixelHeight, 24, RenderTextureFormat.ARGB32); screenMat = internalProp.FindModelTransform(screenTransform).renderer.material; foreach (string layerID in textureLayerID.Split()) screenMat.SetTexture(layerID.Trim(), screenTexture); if (GameDatabase.Instance.ExistsTexture(noSignalTextureURL.EnforceSlashes())) { noSignalTexture = GameDatabase.Instance.GetTexture(noSignalTextureURL.EnforceSlashes(), false); } // Create camera instance... cameraStructure = new FlyingCamera(part, screenTexture, cameraAspect); // The neat trick. IConfigNode doesn't work. No amount of kicking got it to work. // Well, we don't need it. GameDatabase, gimme config nodes for all props! foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes ("PROP")) { // Now, we know our own prop name. if (node.GetValue("name") == internalProp.propName) { // So this is the configuration of our prop in memory. Nice place. // We know it contains at least one MODULE node, us. // And we know our moduleID, which is the number in order of being listed in the prop. // Therefore the module by that number is our module's own config node. ConfigNode moduleConfig = node.GetNodes("MODULE")[moduleID]; ConfigNode[] pageNodes = moduleConfig.GetNodes("PAGE"); // Which we can now parse for page definitions. for (int i = 0; i < pageNodes.Length; i++) { // Mwahahaha. try { var newPage = new MonitorPage(i, pageNodes[i], this); activePage = activePage ?? newPage; if (newPage.isDefault) activePage = newPage; pages.Add(newPage); } catch (ArgumentException e) { JUtil.LogMessage(this, "Warning - {0}", e); } } // Now that all pages are loaded, we can use the moment in the loop to suck in all the extra fonts. foreach (string value in moduleConfig.GetValues("extraFont")) { fontTexture.Add(LoadFont(this, internalProp, value, true)); } break; } } JUtil.LogMessage(this, "Done setting up pages, {0} pages ready.", pages.Count); // Load our state from storage... persistentVarName = "activePage" + internalProp.propID; persistence = new PersistenceAccessor(part); int? activePageID = persistence.GetVar(persistentVarName); if (activePageID != null && activePageID.Value < pages.Count) { activePage = pages[activePageID.Value]; } activePage.Active(true); // If we have global buttons, set them up. if (!string.IsNullOrEmpty(globalButtons)) { string[] tokens = globalButtons.Split(','); for (int i = 0; i < tokens.Length; i++) { string buttonName = tokens[i].Trim(); // Notice that holes in the global button list ARE legal. if (!string.IsNullOrEmpty(buttonName)) SmarterButton.CreateButton(internalProp, buttonName, i, GlobalButtonClick, GlobalButtonRelease); } } audioOutput = JUtil.SetupIVASound(internalProp, buttonClickSound, buttonClickVolume, false); // One last thing to make sure of: If our pod is transparent, we're always active. ourPodIsTransparent = JUtil.IsPodTransparent(part); // And if the try block never completed, startupComplete will never be true. startupComplete = true; } catch { JUtil.AnnoyUser(this); startupFailed = true; // We can also disable ourselves, that should help. enabled = false; // And now that we notified the user that config is borked, we rethrow the exception so that // it gets logged and we can debug. throw; } }
public static void PlaySound(FXGroup fx, float volume) { if(fx.audio.isPlaying) { if(fx.audio.volume < volume) fx.audio.volume = volume; } else { fx.audio.volume = volume; fx.audio.Play (); } if(ReentryPhysics.debugging) print (fx.audio.clip.name); }
private void SetupAudio() { if (scrapeSparks) { if (SparkSounds == null) { Debug.LogError("CollisionFX: SparkSounds was null"); return; } if (!String.IsNullOrEmpty(sparkSound)) { part.fxGroups.Add(SparkSounds); SparkSounds.name = "SparkSounds"; SparkSounds.audio = gameObject.AddComponent<AudioSource>(); SparkSounds.audio.clip = GameDatabase.Instance.GetAudioClip(sparkSound); if (SparkSounds.audio.clip == null) { Debug.LogError("CollisionFX: Unable to load sparkSound \"" + sparkSound + "\""); scrapeSparks = false; return; } SparkSounds.audio.dopplerLevel = 0f; SparkSounds.audio.rolloffMode = AudioRolloffMode.Logarithmic; SparkSounds.audio.Stop(); SparkSounds.audio.loop = true; SparkSounds.audio.volume = volume * GameSettings.SHIP_VOLUME; SparkSounds.audio.time = UnityEngine.Random.Range(0, SparkSounds.audio.clip.length); } } if (ScrapeSounds == null) { Debug.LogError("CollisionFX: ScrapeSounds was null"); return; } if (!String.IsNullOrEmpty(scrapeSound)) { part.fxGroups.Add(ScrapeSounds); ScrapeSounds.name = "ScrapeSounds"; ScrapeSounds.audio = gameObject.AddComponent<AudioSource>(); ScrapeSounds.audio.clip = GameDatabase.Instance.GetAudioClip(scrapeSound); if (ScrapeSounds.audio.clip == null) { Debug.LogError("CollisionFX: Unable to load scrapeSound \"" + scrapeSound + "\""); } else { ScrapeSounds.audio.dopplerLevel = 0f; ScrapeSounds.audio.rolloffMode = AudioRolloffMode.Logarithmic; ScrapeSounds.audio.Stop(); ScrapeSounds.audio.loop = true; ScrapeSounds.audio.volume = volume * GameSettings.SHIP_VOLUME; ScrapeSounds.audio.time = UnityEngine.Random.Range(0, ScrapeSounds.audio.clip.length); } } if (!String.IsNullOrEmpty(collisionSound)) { part.fxGroups.Add(BangSound); BangSound.name = "BangSound"; BangSound.audio = gameObject.AddComponent<AudioSource>(); BangSound.audio.clip = GameDatabase.Instance.GetAudioClip(collisionSound); BangSound.audio.dopplerLevel = 0f; BangSound.audio.rolloffMode = AudioRolloffMode.Logarithmic; BangSound.audio.Stop(); BangSound.audio.loop = false; BangSound.audio.volume = GameSettings.SHIP_VOLUME; } if (wheelCollider != null && !String.IsNullOrEmpty(wheelImpactSound)) { WheelImpactSound = new FXGroup("WheelImpactSound"); part.fxGroups.Add(WheelImpactSound); WheelImpactSound.name = "WheelImpactSound"; WheelImpactSound.audio = gameObject.AddComponent<AudioSource>(); WheelImpactSound.audio.clip = GameDatabase.Instance.GetAudioClip(wheelImpactSound); WheelImpactSound.audio.dopplerLevel = 0f; WheelImpactSound.audio.rolloffMode = AudioRolloffMode.Logarithmic; WheelImpactSound.audio.Stop(); WheelImpactSound.audio.loop = false; WheelImpactSound.audio.volume = GameSettings.SHIP_VOLUME; } }
private static void SetupFxGroup(FXGroup group, GameObject gameObject, string audioFileUrl) { group.audio = gameObject.AddComponent<AudioSource>(); group.audio.clip = GameDatabase.Instance.GetAudioClip(audioFileUrl); group.audio.dopplerLevel = 0f; group.audio.rolloffMode = AudioRolloffMode.Linear; group.audio.maxDistance = 30f; group.audio.loop = false; group.audio.playOnAwake = false; group.audio.volume = GameSettings.SHIP_VOLUME; }
public void Start() { // If we're not in the correct location, there's no point doing anything. if (!InstallationPathWarning.Warn()) { return; } if (HighLogic.LoadedSceneIsEditor) { return; } try { rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true); JUtil.LogMessage(this, "Attaching monitor {2}-{1} to {0}", rpmComp.RPMCid, internalProp.propID, internalProp.internalModel.internalName); // Install the calculator module. rpmComp.UpdateDataRefreshRate(refreshDataRate); // Loading the font... List<Texture2D> fontTexture = new List<Texture2D>(); fontTexture.Add(LoadFont(this, internalProp, fontTransform)); // Damn KSP's config parser!!! if (!string.IsNullOrEmpty(emptyColor)) { emptyColorValue = ConfigNode.ParseColor32(emptyColor); } if (!string.IsNullOrEmpty(defaultFontTint)) { defaultFontTintValue = ConfigNode.ParseColor32(defaultFontTint); } if (!string.IsNullOrEmpty(fontDefinition)) { JUtil.LogMessage(this, "Loading font definition from {0}", fontDefinition); fontDefinitionString = File.ReadAllLines(KSPUtil.ApplicationRootPath + "GameData/" + fontDefinition.EnforceSlashes(), Encoding.UTF8)[0]; } // Now that is done, proceed to setting up the screen. screenTexture = new RenderTexture(screenPixelWidth, screenPixelHeight, 24, RenderTextureFormat.ARGB32); screenMat = internalProp.FindModelTransform(screenTransform).GetComponent<Renderer>().material; foreach (string layerID in textureLayerID.Split()) { screenMat.SetTexture(layerID.Trim(), screenTexture); } if (GameDatabase.Instance.ExistsTexture(noSignalTextureURL.EnforceSlashes())) { noSignalTexture = GameDatabase.Instance.GetTexture(noSignalTextureURL.EnforceSlashes(), false); } // Create camera instance... cameraStructure = new FlyingCamera(part, cameraAspect); // The neat trick. IConfigNode doesn't work. No amount of kicking got it to work. // Well, we don't need it. GameDatabase, gimme config nodes for all props! foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP")) { // Now, we know our own prop name. if (node.GetValue("name") == internalProp.propName) { // So this is the configuration of our prop in memory. Nice place. // We know it contains at least one MODULE node, us. // And we know our moduleID, which is the number in order of being listed in the prop. // Therefore the module by that number is our module's own config node. ConfigNode moduleConfig = node.GetNodes("MODULE")[moduleID]; ConfigNode[] pageNodes = moduleConfig.GetNodes("PAGE"); // Which we can now parse for page definitions. for (int i = 0; i < pageNodes.Length; i++) { // Mwahahaha. try { var newPage = new MonitorPage(i, pageNodes[i], this); activePage = activePage ?? newPage; if (newPage.isDefault) activePage = newPage; pages.Add(newPage); } catch (ArgumentException e) { JUtil.LogMessage(this, "Warning - {0}", e); } } // Now that all pages are loaded, we can use the moment in the loop to suck in all the extra fonts. foreach (string value in moduleConfig.GetValues("extraFont")) { fontTexture.Add(LoadFont(this, internalProp, value)); } break; } } JUtil.LogMessage(this, "Done setting up pages, {0} pages ready.", pages.Count); textRenderer = new TextRenderer(fontTexture, new Vector2((float)fontLetterWidth, (float)fontLetterHeight), fontDefinitionString, 17, screenPixelWidth, screenPixelHeight); // Load our state from storage... persistentVarName = "activePage" + internalProp.propID; int activePageID = rpmComp.GetPersistentVariable(persistentVarName, pages.Count, false).MassageToInt(); if (activePageID < pages.Count) { activePage = pages[activePageID]; } activePage.Active(true); // If we have global buttons, set them up. if (!string.IsNullOrEmpty(globalButtons)) { string[] tokens = globalButtons.Split(','); for (int i = 0; i < tokens.Length; i++) { string buttonName = tokens[i].Trim(); // Notice that holes in the global button list ARE legal. if (!string.IsNullOrEmpty(buttonName)) SmarterButton.CreateButton(internalProp, buttonName, i, GlobalButtonClick, GlobalButtonRelease); } } audioOutput = JUtil.SetupIVASound(internalProp, buttonClickSound, buttonClickVolume, false); if (needsElectricCharge) { del = (Action<bool>)Delegate.CreateDelegate(typeof(Action<bool>), this, "ResourceDepletedCallback"); rpmComp.RegisterResourceCallback(resourceName, del); } // And if the try block never completed, startupComplete will never be true. startupComplete = true; } catch { JUtil.AnnoyUser(this); // We can also disable ourselves, that should help. enabled = false; // And now that we notified the user that config is borked, we rethrow the exception so that // it gets logged and we can debug. throw; } }
private void InitialiseSound(FXGroup soundGroup, string soundFile, float volume, bool loop) { if (!GameDatabase.Instance.ExistsAudioClip(soundFile)) { Debug.LogError("[WheelSounds] Audio file not found: " + soundFile); return; } if (soundGroup == null) { Debug.LogError("[WheelSounds] FXGroup is null"); return; } soundGroup.audio = gameObject.AddComponent<AudioSource>(); soundGroup.audio.clip = GameDatabase.Instance.GetAudioClip(soundFile); soundGroup.audio.dopplerLevel = 0f; soundGroup.audio.rolloffMode = AudioRolloffMode.Logarithmic; soundGroup.audio.Stop(); soundGroup.audio.loop = loop; soundGroup.audio.spatialBlend = 1; soundGroup.audio.volume = volume * GameSettings.SHIP_VOLUME; if (loop) { // Seek to a random position in the sound file so we don't have harmonic effects with other wheels. soundGroup.audio.time = UnityEngine.Random.Range(0, soundGroup.audio.clip.length); } }
public bool IsGroup(FXGroup group_) { return (Groups & group_) != 0; }
public WtsAnalyzerFXGroup GetGroup(FXGroup fg_) { return RegionBreakdown.FirstOrDefault(x => x.FX_Group == fg_); }
public VariableAnimationSet(ConfigNode node, InternalProp thisProp) { part = thisProp.part; if (!node.HasData) { throw new ArgumentException("No data?!"); } comp = RasterPropMonitorComputer.Instantiate(thisProp); string[] tokens = { }; if (node.HasValue("scale")) { tokens = node.GetValue("scale").Split(','); } if (tokens.Length != 2) { throw new ArgumentException("Could not parse 'scale' parameter."); } if (node.HasValue("variableName")) { string variableName; variableName = node.GetValue("variableName").Trim(); scaleEnds[2] = new VariableOrNumber(variableName, this); } else if (node.HasValue("stateMethod")) { Func<bool> stateFunction = (Func<bool>)comp.GetMethod(node.GetValue("stateMethod").Trim(), thisProp, typeof(Func<bool>)); if (stateFunction != null) { scaleEnds[2] = new VariableOrNumber(stateFunction, this); } else { throw new ArgumentException("Unrecognized stateMethod"); } } else { throw new ArgumentException("Missing variable name."); } scaleEnds[0] = new VariableOrNumber(tokens[0], this); scaleEnds[1] = new VariableOrNumber(tokens[1], this); // That takes care of the scale, now what to do about that scale: if (node.HasValue("reverse")) { if (!bool.TryParse(node.GetValue("reverse"), out reverse)) { throw new ArgumentException("So is 'reverse' true or false?"); } } if (node.HasValue("animationName")) { animationName = node.GetValue("animationName"); if (node.HasValue("animationSpeed")) { animationSpeed = float.Parse(node.GetValue("animationSpeed")); if (reverse) { animationSpeed = -animationSpeed; } } else { animationSpeed = 0.0f; } Animation[] anims = node.HasValue("animateExterior") ? thisProp.part.FindModelAnimators(animationName) : thisProp.FindModelAnimators(animationName); if (anims.Length > 0) { onAnim = anims[0]; onAnim.enabled = true; onAnim[animationName].speed = 0; onAnim[animationName].normalizedTime = reverse ? 1f : 0f; looping = node.HasValue("loopingAnimation"); if (looping) { onAnim[animationName].wrapMode = WrapMode.Loop; onAnim.wrapMode = WrapMode.Loop; onAnim[animationName].speed = animationSpeed; mode = Mode.LoopingAnimation; } else { onAnim[animationName].wrapMode = WrapMode.Once; mode = Mode.Animation; } onAnim.Play(); alwaysActive = node.HasValue("animateExterior"); } else { throw new ArgumentException("Animation could not be found."); } if (node.HasValue("stopAnimationName")) { stopAnimationName = node.GetValue("stopAnimationName"); anims = node.HasValue("animateExterior") ? thisProp.part.FindModelAnimators(stopAnimationName) : thisProp.FindModelAnimators(stopAnimationName); if (anims.Length > 0) { offAnim = anims[0]; offAnim.enabled = true; offAnim[stopAnimationName].speed = 0; offAnim[stopAnimationName].normalizedTime = reverse ? 1f : 0f; if (looping) { offAnim[stopAnimationName].wrapMode = WrapMode.Loop; offAnim.wrapMode = WrapMode.Loop; offAnim[stopAnimationName].speed = animationSpeed; mode = Mode.LoopingAnimation; } else { offAnim[stopAnimationName].wrapMode = WrapMode.Once; mode = Mode.Animation; } } } } else if (node.HasValue("activeColor") && node.HasValue("passiveColor") && node.HasValue("coloredObject")) { if (node.HasValue("colorName")) colorName = node.GetValue("colorName"); passiveColor = ConfigNode.ParseColor32(node.GetValue("passiveColor")); activeColor = ConfigNode.ParseColor32(node.GetValue("activeColor")); colorShiftRenderer = thisProp.FindModelComponent<Renderer>(node.GetValue("coloredObject")); colorShiftRenderer.material.SetColor(colorName, reverse ? activeColor : passiveColor); mode = Mode.Color; } else if (node.HasValue("controlledTransform") && node.HasValue("localRotationStart") && node.HasValue("localRotationEnd")) { controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()); initialRotation = controlledTransform.localRotation; if (node.HasValue("longPath")) { longPath = true; vectorStart = ConfigNode.ParseVector3(node.GetValue("localRotationStart")); vectorEnd = ConfigNode.ParseVector3(node.GetValue("localRotationEnd")); } else { rotationStart = Quaternion.Euler(ConfigNode.ParseVector3(node.GetValue("localRotationStart"))); rotationEnd = Quaternion.Euler(ConfigNode.ParseVector3(node.GetValue("localRotationEnd"))); } mode = Mode.Rotation; } else if (node.HasValue("controlledTransform") && node.HasValue("localTranslationStart") && node.HasValue("localTranslationEnd")) { controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()); initialPosition = controlledTransform.localPosition; vectorStart = ConfigNode.ParseVector3(node.GetValue("localTranslationStart")); vectorEnd = ConfigNode.ParseVector3(node.GetValue("localTranslationEnd")); mode = Mode.Translation; } else if (node.HasValue("controlledTransform") && node.HasValue("localScaleStart") && node.HasValue("localScaleEnd")) { controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()); initialScale = controlledTransform.localScale; vectorStart = ConfigNode.ParseVector3(node.GetValue("localScaleStart")); vectorEnd = ConfigNode.ParseVector3(node.GetValue("localScaleEnd")); mode = Mode.Scale; } else if (node.HasValue("controlledTransform") && node.HasValue("textureLayers") && node.HasValue("textureShiftStart") && node.HasValue("textureShiftEnd")) { affectedMaterial = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()).renderer.material; textureLayer = node.GetValue("textureLayers"); textureShiftStart = ConfigNode.ParseVector2(node.GetValue("textureShiftStart")); textureShiftEnd = ConfigNode.ParseVector2(node.GetValue("textureShiftEnd")); mode = Mode.TextureShift; } else if (node.HasValue("controlledTransform") && node.HasValue("textureLayers") && node.HasValue("textureScaleStart") && node.HasValue("textureScaleEnd")) { affectedMaterial = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()).renderer.material; textureLayer = node.GetValue("textureLayers"); textureScaleStart = ConfigNode.ParseVector2(node.GetValue("textureScaleStart")); textureScaleEnd = ConfigNode.ParseVector2(node.GetValue("textureScaleEnd")); mode = Mode.TextureScale; } else { throw new ArgumentException("Cannot initiate any of the possible action modes."); } if (node.HasValue("threshold")) { threshold = ConfigNode.ParseVector2(node.GetValue("threshold")); } resourceAmount = 0.0f; if (threshold != Vector2.zero) { thresholdMode = true; float min = Mathf.Min(threshold.x, threshold.y); float max = Mathf.Max(threshold.x, threshold.y); threshold.x = min; threshold.y = max; if (node.HasValue("flashingDelay")) { flashingDelay = double.Parse(node.GetValue("flashingDelay")); } if (node.HasValue("alarmSound")) { alarmSoundVolume = 0.5f; if (node.HasValue("alarmSoundVolume")) alarmSoundVolume = float.Parse(node.GetValue("alarmSoundVolume")); audioOutput = JUtil.SetupIVASound(thisProp, node.GetValue("alarmSound"), alarmSoundVolume, false); if (node.HasValue("alarmMustPlayOnce")) { if (!bool.TryParse(node.GetValue("alarmMustPlayOnce"), out alarmMustPlayOnce)) throw new ArgumentException("So is 'alarmMustPlayOnce' true or false?"); } if (node.HasValue("alarmShutdownButton")) SmarterButton.CreateButton(thisProp, node.GetValue("alarmShutdownButton"), AlarmShutdown); if (node.HasValue("alarmSoundLooping")) { if (!bool.TryParse(node.GetValue("alarmSoundLooping"), out alarmSoundLooping)) throw new ArgumentException("So is 'alarmSoundLooping' true or false?"); audioOutput.audio.loop = alarmSoundLooping; } } if (node.HasValue("resourceAmount")) { resourceAmount = float.Parse(node.GetValue("resourceAmount")); } TurnOff(); } }
//private AudioHighPassFilter highPassFilter; //private float highPassTest = 100.0f; /// <summary> /// Fills an FXGroup with sound values /// </summary> /// <param name="group">The group that will receive a new sound</param> /// <param name="name">The name of the sound in the game database. No file extensions. e.g. Firespitter\Sounds\sound_fspropidle</param> /// <param name="loop">Does the sound loop by default?</param> /// <returns></returns> public bool createGroup(FXGroup group, string name, bool loop) { if (name != string.Empty) { if (!GameDatabase.Instance.ExistsAudioClip(name)) return false; group.audio = gameObject.AddComponent<AudioSource>(); group.audio.volume = GameSettings.SHIP_VOLUME; //group.audio.rolloffMode = AudioRolloffMode.Logarithmic; group.audio.rolloffMode = AudioRolloffMode.Linear; group.audio.dopplerLevel = 0f; group.audio.panLevel = 1f; group.audio.clip = GameDatabase.Instance.GetAudioClip(name); group.audio.loop = loop; group.audio.playOnAwake = false; //highPassFilter = group.audio.GetComponent<AudioHighPassFilter>(); return true; } return false; }
private void PlayAudio(FXGroup group) { if (!this._soundFlag || group == null || group.audio == null) { return; } group.audio.Play(); }
public static void PlaySound(FXGroup fx, float volume) { if(fx.audio.isPlaying) { if(fx.audio.volume < volume) fx.audio.volume = volume; } else { fx.audio.volume = volume; fx.audio.Play (); } //if(this.is_debugging) // print (fx.audio.clip.name); }
public void Start() { if (HighLogic.LoadedSceneIsEditor) return; try { if (!groupList.ContainsKey(actionName) && !customGroupList.ContainsKey(actionName)) { JUtil.LogErrorMessage(this, "Action \"{0}\" is not supported.", actionName); return; } // Parse the needs-electric-charge here. if (!string.IsNullOrEmpty(needsElectricCharge)) { switch (needsElectricCharge.ToLowerInvariant().Trim()) { case "true": case "yes": case "1": needsElectricChargeValue = true; break; case "false": case "no": case "0": needsElectricChargeValue = false; break; } } // Now parse consumeOnToggle and consumeWhileActive... if (!string.IsNullOrEmpty(consumeOnToggle)) { string[] tokens = consumeOnToggle.Split(','); if (tokens.Length == 3) { consumeOnToggleName = tokens[0].Trim(); if (!(PartResourceLibrary.Instance.GetDefinition(consumeOnToggleName) != null && float.TryParse(tokens[1].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out consumeOnToggleAmount))) { JUtil.LogErrorMessage(this, "Could not parse \"{0}\"", consumeOnToggle); } switch (tokens[2].Trim().ToLower()) { case "on": consumingOnToggleUp = true; break; case "off": consumingOnToggleDown = true; break; case "both": consumingOnToggleUp = true; consumingOnToggleDown = true; break; default: JUtil.LogErrorMessage(this, "So should I consume resources when turning on, turning off, or both in \"{0}\"?", consumeOnToggle); break; } } } if (!string.IsNullOrEmpty(consumeWhileActive)) { string[] tokens = consumeWhileActive.Split(','); if (tokens.Length == 2) { consumeWhileActiveName = tokens[0].Trim(); if (!(PartResourceLibrary.Instance.GetDefinition(consumeWhileActiveName) != null && float.TryParse(tokens[1].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out consumeWhileActiveAmount))) { JUtil.LogErrorMessage(this, "Could not parse \"{0}\"", consumeWhileActive); } else { consumingWhileActive = true; JUtil.LogMessage(this, "Switch in prop {0} prop id {1} will consume {2} while active at a rate of {3}", internalProp.propName, internalProp.propID, consumeWhileActiveName, consumeWhileActiveAmount); } } } if (groupList.ContainsKey(actionName)) { currentState = vessel.ActionGroups[groupList[actionName]]; // action group switches may not belong to a radio group switchGroupIdentifier = -1; } else { isCustomAction = true; switch (actionName) { case "intlight": persistentVarName = internalLightName; lightObjects = internalModel.FindModelComponents<Light>(); needsElectricChargeValue |= string.IsNullOrEmpty(needsElectricCharge) || needsElectricChargeValue; break; case "plugin": persistentVarName = string.Empty; comp = RasterPropMonitorComputer.Instantiate(internalProp); comp.UpdateRefreshRates(lightCheckRate, lightCheckRate); foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP")) { if (node.GetValue("name") == internalProp.propName) { foreach (ConfigNode pluginConfig in node.GetNodes("MODULE")[moduleID].GetNodes("PLUGINACTION")) { if (pluginConfig.HasValue("name") && pluginConfig.HasValue("actionMethod")) { string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("actionMethod").Trim(); actionHandler = (Action<bool>)comp.GetMethod(action, internalProp, typeof(Action<bool>)); if (actionHandler == null) { JUtil.LogErrorMessage(this, "Failed to instantiate action handler {0}", pluginConfig.GetValue("name")); } else { if (pluginConfig.HasValue("stateMethod")) { string state = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("stateMethod").Trim(); stateHandler = (Func<bool>)comp.GetMethod(state, internalProp, typeof(Func<bool>)); } isPluginAction = true; break; } } } } } if (actionHandler == null) { actionName = "dummy"; JUtil.LogMessage(this, "Plugin handlers did not start, reverting to dummy mode."); } break; default: persistentVarName = "switch" + internalProp.propID + "_" + moduleID; break; } if (!string.IsNullOrEmpty(perPodPersistenceName)) { persistentVarName = perPodPersistenceName; } else { // If there's no persistence name, there's no valid group id for this switch switchGroupIdentifier = -1; } } if (needsElectricChargeValue || !string.IsNullOrEmpty(persistentVarName) || !string.IsNullOrEmpty(perPodMasterSwitchName) || !string.IsNullOrEmpty(masterVariableName)) { if (comp == null) { comp = RasterPropMonitorComputer.Instantiate(internalProp); comp.UpdateRefreshRates(lightCheckRate, lightCheckRate); } if (!string.IsNullOrEmpty(masterVariableName)) { masterVariable = new VariableOrNumber(masterVariableName, this); string[] range = masterVariableRange.Split(','); if(range.Length == 2) { masterRange[0] = new VariableOrNumber(range[0], this); masterRange[1] = new VariableOrNumber(range[1], this); } else { masterVariable = null; } } } // set up the toggle switch if (!string.IsNullOrEmpty(switchTransform)) { SmarterButton.CreateButton(internalProp, switchTransform, Click); } if (isCustomAction) { if (isPluginAction && stateHandler != null) { currentState = stateHandler(); } else { if (!string.IsNullOrEmpty(persistentVarName)) { if (switchGroupIdentifier >= 0) { int activeSwitch = comp.Persistence.GetVar(persistentVarName, 0); currentState = customGroupList[actionName] = (switchGroupIdentifier == activeSwitch); } else { currentState = customGroupList[actionName] = comp.Persistence.GetBool(persistentVarName, initialState); } if (actionName == "intlight") { // We have to restore lighting after reading the // persistent variable. SetInternalLights(customGroupList[actionName]); } } } } if (!string.IsNullOrEmpty(persistentVarName) && !comp.Persistence.HasVar(persistentVarName)) { if (switchGroupIdentifier >= 0) { if (currentState) { comp.Persistence.SetVar(persistentVarName, switchGroupIdentifier); } } else { comp.Persistence.SetVar(persistentVarName, currentState); } } if (!string.IsNullOrEmpty(animationName)) { // Set up the animation Animation[] animators = animateExterior ? part.FindModelAnimators(animationName) : internalProp.FindModelAnimators(animationName); if (animators.Length > 0) { anim = animators[0]; } else { JUtil.LogErrorMessage(this, "Could not find animation \"{0}\" on {2} \"{1}\"", animationName, animateExterior ? part.name : internalProp.name, animateExterior ? "part" : "prop"); return; } anim[animationName].wrapMode = WrapMode.Once; if (currentState ^ reverse) { anim[animationName].speed = float.MaxValue; anim[animationName].normalizedTime = 0; } else { anim[animationName].speed = float.MinValue; anim[animationName].normalizedTime = 1; } anim.Play(animationName); } else if (!string.IsNullOrEmpty(coloredObject)) { // Set up the color shift. colorShiftRenderer = internalProp.FindModelComponent<Renderer>(coloredObject); disabledColorValue = ConfigNode.ParseColor32(disabledColor); enabledColorValue = ConfigNode.ParseColor32(enabledColor); colorShiftRenderer.material.SetColor(colorName, (currentState ^ reverse ? enabledColorValue : disabledColorValue)); } else { JUtil.LogMessage(this, "Warning, neither color nor animation are defined."); } audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false); startupComplete = true; } catch { JUtil.AnnoyUser(this); enabled = false; throw; } }
public extern void AutoPlaceFXGroup(FXGroup group, Transform thruster);
private void ScrapeSound(FXGroup sound, float speed) { if (sound == null || sound.audio == null) return; if (speed > minScrapeSpeed) { if (!sound.audio.isPlaying) sound.audio.Play(); sound.audio.pitch = 1 + Mathf.Log(speed) / 5; if (speed < scrapeFadeSpeed) { // Fade out at low speeds. sound.audio.volume = speed / scrapeFadeSpeed * volume * GameSettings.SHIP_VOLUME; } else sound.audio.volume = volume * GameSettings.SHIP_VOLUME; } else sound.audio.Stop(); }
public VariableAnimationSet(ConfigNode node, InternalProp thisProp, RasterPropMonitorComputer rpmComp, JSIVariableAnimator parent) { varAnim = parent; onChangeDelegate = (Action<float>)Delegate.CreateDelegate(typeof(Action<float>), this, "OnChange"); part = thisProp.part; if (!node.HasData) { throw new ArgumentException("No data?!"); } string[] tokens = { }; if (node.HasValue("scale")) { tokens = node.GetValue("scale").Split(','); } if (tokens.Length != 2) { throw new ArgumentException("Could not parse 'scale' parameter."); } string variableName = string.Empty; if (node.HasValue("variableName")) { variableName = node.GetValue("variableName").Trim(); } else if (node.HasValue("stateMethod")) { string stateMethod = node.GetValue("stateMethod").Trim(); // Verify the state method actually exists Func<bool> stateFunction = (Func<bool>)rpmComp.GetMethod(stateMethod, thisProp, typeof(Func<bool>)); if (stateFunction != null) { variableName = "PLUGIN_" + stateMethod; } else { throw new ArgumentException("Unrecognized stateMethod"); } } else { throw new ArgumentException("Missing variable name."); } if (node.HasValue("modulo")) { variable = new VariableOrNumberRange(rpmComp, variableName, tokens[0], tokens[1], node.GetValue("modulo")); usesModulo = true; } else { variable = new VariableOrNumberRange(rpmComp, variableName, tokens[0], tokens[1]); usesModulo = false; } // That takes care of the scale, now what to do about that scale: if (node.HasValue("reverse")) { if (!bool.TryParse(node.GetValue("reverse"), out reverse)) { throw new ArgumentException("So is 'reverse' true or false?"); } } if (node.HasValue("animationName")) { animationName = node.GetValue("animationName"); if (node.HasValue("animationSpeed")) { animationSpeed = float.Parse(node.GetValue("animationSpeed")); if (reverse) { animationSpeed = -animationSpeed; } } else { animationSpeed = 0.0f; } Animation[] anims = node.HasValue("animateExterior") ? thisProp.part.FindModelAnimators(animationName) : thisProp.FindModelAnimators(animationName); if (anims.Length > 0) { onAnim = anims[0]; onAnim.enabled = true; onAnim[animationName].speed = 0; onAnim[animationName].normalizedTime = reverse ? 1f : 0f; looping = node.HasValue("loopingAnimation"); if (looping) { onAnim[animationName].wrapMode = WrapMode.Loop; onAnim.wrapMode = WrapMode.Loop; onAnim[animationName].speed = animationSpeed; mode = Mode.LoopingAnimation; } else { onAnim[animationName].wrapMode = WrapMode.Once; mode = Mode.Animation; } onAnim.Play(); alwaysActive = node.HasValue("animateExterior"); } else { throw new ArgumentException("Animation could not be found."); } if (node.HasValue("stopAnimationName")) { stopAnimationName = node.GetValue("stopAnimationName"); anims = node.HasValue("animateExterior") ? thisProp.part.FindModelAnimators(stopAnimationName) : thisProp.FindModelAnimators(stopAnimationName); if (anims.Length > 0) { offAnim = anims[0]; offAnim.enabled = true; offAnim[stopAnimationName].speed = 0; offAnim[stopAnimationName].normalizedTime = reverse ? 1f : 0f; if (looping) { offAnim[stopAnimationName].wrapMode = WrapMode.Loop; offAnim.wrapMode = WrapMode.Loop; offAnim[stopAnimationName].speed = animationSpeed; mode = Mode.LoopingAnimation; } else { offAnim[stopAnimationName].wrapMode = WrapMode.Once; mode = Mode.Animation; } } } } else if (node.HasValue("activeColor") && node.HasValue("passiveColor") && node.HasValue("coloredObject")) { string colorNameString = "_EmissiveColor"; if (node.HasValue("colorName")) { colorNameString = node.GetValue("colorName"); } colorName = Shader.PropertyToID(colorNameString); if (reverse) { activeColor = JUtil.ParseColor32(node.GetValue("passiveColor"), thisProp.part, ref rpmComp); passiveColor = JUtil.ParseColor32(node.GetValue("activeColor"), thisProp.part, ref rpmComp); } else { passiveColor = JUtil.ParseColor32(node.GetValue("passiveColor"), thisProp.part, ref rpmComp); activeColor = JUtil.ParseColor32(node.GetValue("activeColor"), thisProp.part, ref rpmComp); } Renderer colorShiftRenderer = thisProp.FindModelComponent<Renderer>(node.GetValue("coloredObject")); affectedMaterial = colorShiftRenderer.material; affectedMaterial.SetColor(colorName, passiveColor); mode = Mode.Color; } else if (node.HasValue("controlledTransform") && node.HasValue("localRotationStart") && node.HasValue("localRotationEnd")) { controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()); initialRotation = controlledTransform.localRotation; if (node.HasValue("longPath")) { longPath = true; if (reverse) { vectorEnd = ConfigNode.ParseVector3(node.GetValue("localRotationStart")); vectorStart = ConfigNode.ParseVector3(node.GetValue("localRotationEnd")); } else { vectorStart = ConfigNode.ParseVector3(node.GetValue("localRotationStart")); vectorEnd = ConfigNode.ParseVector3(node.GetValue("localRotationEnd")); } } else { if (reverse) { rotationEnd = Quaternion.Euler(ConfigNode.ParseVector3(node.GetValue("localRotationStart"))); rotationStart = Quaternion.Euler(ConfigNode.ParseVector3(node.GetValue("localRotationEnd"))); } else { rotationStart = Quaternion.Euler(ConfigNode.ParseVector3(node.GetValue("localRotationStart"))); rotationEnd = Quaternion.Euler(ConfigNode.ParseVector3(node.GetValue("localRotationEnd"))); } } mode = Mode.Rotation; } else if (node.HasValue("controlledTransform") && node.HasValue("localTranslationStart") && node.HasValue("localTranslationEnd")) { controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()); initialPosition = controlledTransform.localPosition; if (reverse) { vectorEnd = ConfigNode.ParseVector3(node.GetValue("localTranslationStart")); vectorStart = ConfigNode.ParseVector3(node.GetValue("localTranslationEnd")); } else { vectorStart = ConfigNode.ParseVector3(node.GetValue("localTranslationStart")); vectorEnd = ConfigNode.ParseVector3(node.GetValue("localTranslationEnd")); } mode = Mode.Translation; } else if (node.HasValue("controlledTransform") && node.HasValue("localScaleStart") && node.HasValue("localScaleEnd")) { controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()); initialScale = controlledTransform.localScale; if (reverse) { vectorEnd = ConfigNode.ParseVector3(node.GetValue("localScaleStart")); vectorStart = ConfigNode.ParseVector3(node.GetValue("localScaleEnd")); } else { vectorStart = ConfigNode.ParseVector3(node.GetValue("localScaleStart")); vectorEnd = ConfigNode.ParseVector3(node.GetValue("localScaleEnd")); } mode = Mode.Scale; } else if (node.HasValue("controlledTransform") && node.HasValue("textureLayers") && node.HasValue("textureShiftStart") && node.HasValue("textureShiftEnd")) { affectedMaterial = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()).GetComponent<Renderer>().material; var textureLayers = node.GetValue("textureLayers").Split(','); for (int i = 0; i < textureLayers.Length; ++i) { textureLayer.Add(textureLayers[i].Trim()); } if (reverse) { textureShiftEnd = ConfigNode.ParseVector2(node.GetValue("textureShiftStart")); textureShiftStart = ConfigNode.ParseVector2(node.GetValue("textureShiftEnd")); } else { textureShiftStart = ConfigNode.ParseVector2(node.GetValue("textureShiftStart")); textureShiftEnd = ConfigNode.ParseVector2(node.GetValue("textureShiftEnd")); } mode = Mode.TextureShift; } else if (node.HasValue("controlledTransform") && node.HasValue("textureLayers") && node.HasValue("textureScaleStart") && node.HasValue("textureScaleEnd")) { affectedMaterial = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()).GetComponent<Renderer>().material; var textureLayers = node.GetValue("textureLayers").Split(','); for (int i = 0; i < textureLayers.Length; ++i) { textureLayer.Add(textureLayers[i].Trim()); } if (reverse) { textureScaleEnd = ConfigNode.ParseVector2(node.GetValue("textureScaleStart")); textureScaleStart = ConfigNode.ParseVector2(node.GetValue("textureScaleEnd")); } else { textureScaleStart = ConfigNode.ParseVector2(node.GetValue("textureScaleStart")); textureScaleEnd = ConfigNode.ParseVector2(node.GetValue("textureScaleEnd")); } mode = Mode.TextureScale; } else { throw new ArgumentException("Cannot initiate any of the possible action modes."); } if (!(node.HasValue("maxRateChange") && float.TryParse(node.GetValue("maxRateChange"), out maxRateChange))) { maxRateChange = 0.0f; } if (maxRateChange >= 60.0f) { // Animation rate is too fast to even notice @60Hz maxRateChange = 0.0f; } else { lastAnimUpdate = Planetarium.GetUniversalTime(); } if (node.HasValue("threshold")) { threshold = ConfigNode.ParseVector2(node.GetValue("threshold")); } resourceAmount = 0.0f; if (threshold != Vector2.zero) { thresholdMode = true; float min = Mathf.Min(threshold.x, threshold.y); float max = Mathf.Max(threshold.x, threshold.y); threshold.x = min; threshold.y = max; if (node.HasValue("flashingDelay")) { flashingDelay = double.Parse(node.GetValue("flashingDelay")); } if (node.HasValue("alarmSound")) { alarmSoundVolume = 0.5f; if (node.HasValue("alarmSoundVolume")) { alarmSoundVolume = float.Parse(node.GetValue("alarmSoundVolume")); } audioOutput = JUtil.SetupIVASound(thisProp, node.GetValue("alarmSound"), alarmSoundVolume, false); if (node.HasValue("alarmMustPlayOnce")) { if (!bool.TryParse(node.GetValue("alarmMustPlayOnce"), out alarmMustPlayOnce)) { throw new ArgumentException("So is 'alarmMustPlayOnce' true or false?"); } } if (node.HasValue("alarmShutdownButton")) { SmarterButton.CreateButton(thisProp, node.GetValue("alarmShutdownButton"), AlarmShutdown); } if (node.HasValue("alarmSoundLooping")) { if (!bool.TryParse(node.GetValue("alarmSoundLooping"), out alarmSoundLooping)) { throw new ArgumentException("So is 'alarmSoundLooping' true or false?"); } audioOutput.audio.loop = alarmSoundLooping; } inIVA = (CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.IVA); GameEvents.OnCameraChange.Add(OnCameraChange); } if (node.HasValue("resourceAmount")) { resourceAmount = float.Parse(node.GetValue("resourceAmount")); if (node.HasValue("resourceName")) { resourceName = node.GetValue("resourceName"); } else { resourceName = "ElectricCharge"; } } TurnOff(Planetarium.GetUniversalTime()); } rpmComp.RegisterVariableCallback(variable.variableName, onChangeDelegate); }
public void Create(ConstructGen<double> wts_, FXGroup[] groups_) { ConstructGen<double> groupConv = new ConstructGen<double>(groups_.Length); groupConv.ColumnHeadings = groups_.Select(x => x.ToString()).ToArray(); Currency[] ccys = wts_.ColumnHeadings.Select(x => Singleton<FXIDs>.Instance[x]).ToArray(); List<int[]> indicies =new List<int[]>(); foreach(FXGroup group in groups_) { List<int> groupIndicies=new List<int>(); for(int i=0;i<ccys.Length;++i) if(ccys[i].IsGroup(group)) groupIndicies.Add(i); indicies.Add(groupIndicies.ToArray()); } foreach (DateTime date in wts_.Dates) { double[] dateWeights = wts_.GetValues(date); double[] buckets = new double[groups_.Length]; for(int g=0;g<groups_.Length;++g) foreach (int index in indicies[g]) buckets[g] += dateWeights[index]; groupConv.SetValues(date, buckets); } DataTable dt1 = groupConv.ToDataTable(groupConv.ColumnHeadings, "Date", "dd-MMM-yyyy"); Chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.Composite; ChartArea area = new ChartArea(); Chart.CompositeChart.ChartAreas.Add(area); AxisItem axisY = new AxisItem(); axisY.Extent = 50; axisY.DataType = AxisDataType.Numeric; axisY.OrientationType = AxisNumber.Y_Axis; axisY.LineColor = Color.Blue; axisY.Labels.Visible = true; area.Axes.Add(axisY); AxisItem axisX = new AxisItem(); axisX.DataType = AxisDataType.String; axisX.Extent = 80; axisX.SetLabelAxisType = Infragistics.UltraChart.Core.Layers.SetLabelAxisType.GroupBySeries; axisX.OrientationType = AxisNumber.X_Axis; axisX.LineColor = Color.Blue; axisX.Labels.Orientation = TextOrientation.VerticalLeftFacing; axisX.Labels.SeriesLabels.Orientation = TextOrientation.VerticalLeftFacing; area.Axes.Add(axisX); AxisItem axisX2 = new AxisItem(); axisX2.DataType = AxisDataType.String; axisX2.Extent = 80; axisX2.OrientationType = AxisNumber.X_Axis; axisX2.LineColor = Color.Blue; axisX2.Labels.Orientation = TextOrientation.VerticalLeftFacing; axisX2.Labels.SeriesLabels.Orientation = TextOrientation.VerticalLeftFacing; axisX2.SetLabelAxisType = SetLabelAxisType.ContinuousData; area.Axes.Add(axisX2); ChartLayerAppearance myColumnLayer = new ChartLayerAppearance(); myColumnLayer.ChartType = ChartType.StackColumnChart; myColumnLayer.ChartArea = area; foreach (FXGroup group in groups_) { NumericSeries series1 = new NumericSeries(); series1.Key = group.ToString(); series1.DataBind(dt1, group.ToString(), "Date"); series1.PEs.Add(new PaintElement(ColorAttribute.GetAttribute(group).Color)); myColumnLayer.Series.Add(series1); Chart.CompositeChart.Series.Add(series1); } DataTable dt2 = wts_.SumRows().ToDataTable(format_:"dd-MMM-yyyy"); ChartLayerAppearance myColumnLayer2 = new ChartLayerAppearance(); myColumnLayer2.ChartType = ChartType.LineChart; myColumnLayer2.ChartArea = area; NumericSeries seriesA = new NumericSeries(); seriesA.Key = "Sum of Wts"; seriesA.DataBind(dt2, "Value", "Date"); seriesA.PEs.Add(new PaintElement(Color.Orange)); myColumnLayer2.Series.Add(seriesA); Chart.CompositeChart.Series.Add(seriesA); LineChartAppearance la = new LineChartAppearance(); la.Thickness = 4; myColumnLayer2.ChartTypeAppearance = la; myColumnLayer.AxisX = axisX; myColumnLayer.AxisY = axisY; myColumnLayer2.AxisX = axisX2; myColumnLayer2.AxisY = axisY; myColumnLayer.SwapRowsAndColumns = true; this.Chart.CompositeChart.ChartLayers.Add(myColumnLayer); this.Chart.CompositeChart.ChartLayers.Add(myColumnLayer2); EstablishDefaultTooltip(); m_wts = wts_; m_groups = groups_; pbSplitIntoYears.BringToFront(); }