repo_name
stringlengths 1
52
| repo_creator
stringclasses 6
values | programming_language
stringclasses 4
values | code
stringlengths 0
9.68M
| num_lines
int64 1
234k
|
---|---|---|---|---|
orrb | openai | C# | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// JointRandomizer component assigns random positions to joints.
public class JointRandomizer : RendererComponent {
public override bool RunComponent(RendererComponent.IOutputContext context) {
JointController[] joint_controllers = GetComponentsInChildren<JointController>();
foreach (JointController joint_controller in joint_controllers) {
switch (joint_controller.joint_type_) {
case JointController.JointType.Ball:
// Assign a random quaternion sampled uniformly from a
// sphere to a ball joint.
joint_controller.UpdateJoint(Random.rotationUniform);
break;
case JointController.JointType.Hinge:
// Assign a random value from the joint limit range to
// a hinge joint.
float range_min = joint_controller.range_[0];
float range_max = joint_controller.range_[1];
if (range_min > float.MinValue && range_max < float.MaxValue) {
joint_controller.UpdateJoint(Random.Range(joint_controller.range_[0], joint_controller.range_[1]));
}
break;
case JointController.JointType.Slide:
// Slide joints don't have ranges, ignore for now.
break;
};
}
return true;
}
public override void DrawEditorGUI() { }
}
| 38 |
orrb | openai | C# | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// LightRandomizer randomizes total illumination of the scene and
// the parameters of individual lights. At first a random scene light
// intensity is drawn, then a random weight is drawn for each light and
// the total intensity is weighted between them. Spotlight angle and
// light color hue can be also randomized.
//
// Configurable properties:
// float min_scene_intensity - minimal sum total intensity of all lights,
// float max_scene_intensity - maximal sum total intensity of all lights,
// float min_light_intensity - minimal individual light contribution weight,
// float max_light_intensity - maximal individual light contribution weight,
// float min_spotlight_angle - minimal spotlight angle in degrees,
// float max_spotlight_angle - maximal spotlight angle in degrees,
// bool randomize_hue - should light color be randomized.
public class LightRandomizer : RendererComponent {
[SerializeField]
[ConfigProperty]
public float min_scene_intensity_ = 1.0f;
[SerializeField]
[ConfigProperty]
public float max_scene_intensity_ = 15.0f;
[SerializeField]
[ConfigProperty]
public float min_light_intensity_ = 1.0f;
[SerializeField]
[ConfigProperty]
public float max_light_intensity_ = 3.0f;
[SerializeField]
[ConfigProperty]
public float min_spotlight_angle_ = 27.0f;
[SerializeField]
[ConfigProperty]
public float max_spotlight_angle_ = 33.0f;
[SerializeField]
[ConfigProperty]
public bool randomize_hue_ = false;
public override bool RunComponent(RendererComponent.IOutputContext context) {
// Find all child light emitters.
Light[] lights = GetComponentsInChildren<Light>();
// Draw a total scene light intensity number.
float scene_intensity = Random.Range(min_scene_intensity_, max_scene_intensity_);
float sum_intensity_denorm = 0.0f;
// Go through all lights, and accumulate random weights.
foreach (Light current_light in lights) {
if (randomize_hue_) {
current_light.color = Random.ColorHSV(0.0f, 1.0f, 0.0f, 0.3f, 0.9f, 1.0f);
} else {
current_light.color = Color.white;
}
// Randomize spot angle.
current_light.spotAngle = Random.Range(min_spotlight_angle_, max_spotlight_angle_);
// Draw a random light intensity weight, from the configured
// range.
current_light.intensity = Random.Range(min_light_intensity_, max_light_intensity_);
sum_intensity_denorm += current_light.intensity;
}
// Distribute total scene intensity between lights, use:
// weight / sum(weights) as factor.
foreach (Light current_light in lights) {
current_light.intensity = current_light.intensity * scene_intensity / sum_intensity_denorm;
}
return true;
}
public override void DrawEditorGUI() {
GUILayout.BeginVertical();
RendererComponent.GUISlider("min_scene_intensity", ref min_scene_intensity_, 0.0f, max_scene_intensity_);
RendererComponent.GUISlider("max_scene_intensity", ref max_scene_intensity_, min_scene_intensity_, 30.0f);
RendererComponent.GUISlider("min_light_intensity", ref min_light_intensity_, 0.0f, max_light_intensity_);
RendererComponent.GUISlider("max_light_intensity", ref max_light_intensity_, min_light_intensity_, 30.0f);
RendererComponent.GUISlider("min_spotlight_angle", ref min_spotlight_angle_, 1.0f, max_spotlight_angle_);
RendererComponent.GUISlider("max_spotlight_angle", ref max_spotlight_angle_, min_spotlight_angle_, 120.0f);
RendererComponent.GUIToggle("randomize_hue", ref randomize_hue_);
GUILayout.EndVertical();
}
}
| 96 |
orrb | openai | C# | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// This randomizer can be used to modify material appearance close
// to a calibrated value. The main idea is to use the HSV representation
// and separately randomize: hue, saturation and value. All three
// dimensions use separate randomization ranges and radii. Additionally,
// the hue spectrum wraps around the red-violet edges. Apart from the main
// material color, emission can also be randomized: with certain probability
// emissive materials will emit light, intensity of emission controlled by
// a separate randomization range and radius. Two parameters from the Unity
// PBR model are also randomized: glossiness and metallic.
//
// Parameter ranges in Unity:
// hue - [0.0, 1.0) wrapped,
// saturation - [0.0, 1.0],
// value - [0.0, 1.0],
// emission - [0.0, +inf), how much light does it produce, values around
// [2.0, 5.0] make lot sense,
// metallic - [0.0, 1.0] is it a diffusive or specular material,
// glossiness - [0.0, 1.0] is it smooth or rough.
//
// Configurable properties:
// string material_prefix - comma separated list of name prefixes for
// materials to randomize,
// string material_blacklist_prefix - comma separated list of name
// prefixes for materials to exclude,
// float hue_radius - maximal perturbation of hue,
// (hue normalized to [0.0, 1.0), wraps around),
// float saturation_radius - maximal perturbation of saturation,
// (saturation normalized to [0.0, 1.0]),
// float value_radius - maximal perturbation of value,
// (value normalized to [0.0, 1.0]),
// float emission_radius - maximal perturbation of emissive strength,
// float min_saturation - used to clamp saturation after randomization,
// float max_saturation - used to clamp saturation after randomization,
// float min_value - used to clamp value after randomization,
// float max_value - used to clamp value after randomization,
// float min_glossiness - used to clamp glossines after randomization,
// float max_glossiness - used to clamp glossines after randomization,
// float min_metallic - used to clamp metallic after randomization,
// float max_metallic - used to clamp metallic after randomization,
// float min_emission - used to clamp emission after randomization,
// float max_emission - used to clamp emission after randomization,
// float emission_probability - what is the probability an emissive material
// will actually emit light, use it to model
// blünkenlights in das komputerrmaschine.
public class MaterialFixedHueRandomizer : RendererComponent {
[SerializeField]
[ConfigProperty]
public string material_prefix_ = "cube";
[SerializeField]
[ConfigProperty]
public string material_blacklist_prefix_ = "";
[SerializeField]
[ConfigProperty]
public float hue_radius_ = 0.02f;
[SerializeField]
[ConfigProperty]
public float saturation_radius_ = 0.15f;
[SerializeField]
[ConfigProperty]
public float value_radius_ = 0.15f;
[SerializeField]
[ConfigProperty]
public float emission_radius_ = 0.0f;
[SerializeField]
[ConfigProperty]
public float min_saturation_ = 0.5f;
[SerializeField]
[ConfigProperty]
public float max_saturation_ = 1.0f;
[SerializeField]
[ConfigProperty]
public float min_value_ = 0.5f;
[SerializeField]
[ConfigProperty]
public float max_value_ = 1.0f;
[SerializeField]
[ConfigProperty]
public float min_metallic_ = 0.05f;
[SerializeField]
[ConfigProperty]
public float max_metallic_ = 0.15f;
[SerializeField]
[ConfigProperty]
public float min_glossiness_ = 0.05f;
[SerializeField]
[ConfigProperty]
public float max_glossiness_ = 0.15f;
[SerializeField]
[ConfigProperty]
public float min_emission_ = 0.0f;
[SerializeField]
[ConfigProperty]
public float max_emission_ = 0.0f;
[SerializeField]
[ConfigProperty]
public float emission_probability_ = 0.25f;
private struct HSVMaterial {
public float h;
public float s;
public float v;
public float e;
public Material m;
};
private List<HSVMaterial> initial_colors_ = new List<HSVMaterial>();
public override bool InitializeComponent(Orrb.RendererComponentConfig config) {
material_prefix_ = ConfigUtils.GetProperty("material_prefix", config, material_prefix_);
material_blacklist_prefix_ = ConfigUtils.GetProperty("material_blacklist_prefix", config,
material_blacklist_prefix_);
UpdateMaterialList();
return UpdateComponent(config);
}
// Cache original parameters in the materials.
private void UpdateMaterialList() {
initial_colors_.Clear();
MeshRenderer[] renderers = GetComponentsInChildren<MeshRenderer>();
string[] prefixes = material_prefix_.Split(new char[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
string[] blacklist = material_blacklist_prefix_.Split(new char[] { ',' },
System.StringSplitOptions.RemoveEmptyEntries);
foreach (MeshRenderer mesh_renderer in renderers) {
foreach (Material material in mesh_renderer.materials) {
// Ignore if name on blacklisted prefix list.
bool blacklisted = false;
foreach (string blacklist_prefix in blacklist) {
if (material.name.StartsWith(blacklist_prefix, System.StringComparison.Ordinal)) {
blacklisted = true;
break;
}
}
if (!blacklisted) {
// Process if name matches the allowed prefix list.
foreach (string prefix in prefixes) {
if (material.name.StartsWith(prefix, System.StringComparison.Ordinal)) {
HSVMaterial hsvm = new HSVMaterial();
Color.RGBToHSV(material.color, out hsvm.h, out hsvm.s, out hsvm.v);
// If this is an emissive material with emission set up,
// cache the original emissive value.
if (material.IsKeywordEnabled("_EMISSION") && material.HasProperty("_EmissionColor")) {
hsvm.e = material.GetColor("_EmissionColor").a;
} else {
hsvm.e = 0.0f;
}
hsvm.m = material;
initial_colors_.Add(hsvm);
}
}
}
}
}
}
public override bool UpdateComponent(Orrb.RendererComponentConfig config) {
string old_material_prefix = material_prefix_;
string old_material_blacklist_prefix = material_blacklist_prefix_;
ConfigUtils.GetProperties(this, config);
if (!material_prefix_.Equals(old_material_prefix) ||
!material_blacklist_prefix_.Equals(old_material_blacklist_prefix)) {
UpdateMaterialList();
}
return true;
}
public override bool RunComponent(RendererComponent.IOutputContext context) {
foreach (HSVMaterial hsvm in initial_colors_) {
// Calculate the clamped randomization ranges.
float hue = Mathf.Repeat(Random.Range(hsvm.h - hue_radius_, hsvm.h + hue_radius_), 1.0f);
float min_s = Mathf.Max(min_saturation_, hsvm.s - saturation_radius_);
float max_s = Mathf.Min(max_saturation_, hsvm.s + saturation_radius_);
float min_v = Mathf.Max(min_value_, hsvm.v - value_radius_);
float max_v = Mathf.Min(max_value_, hsvm.v + value_radius_);
float min_e = Mathf.Max(min_emission_, hsvm.e - emission_radius_);
float max_e = Mathf.Min(max_emission_, hsvm.e + emission_radius_);
// We will keep the alpha exactly as original, do not randomize
// transparency.
float alpha = hsvm.m.color.a;
// Randomize basic properties.
if (hsvm.m.HasProperty("_Color")) {
hsvm.m.color = Random.ColorHSV(hue, hue, min_s, max_s, min_v, max_v, alpha, alpha);
}
if (hsvm.m.HasProperty("_Metallic")) {
hsvm.m.SetFloat("_Metallic", Random.Range(min_metallic_, max_metallic_));
}
if (hsvm.m.HasProperty("_Glossiness")) {
hsvm.m.SetFloat("_Glossiness", Random.Range(min_glossiness_, max_glossiness_));
}
// If the material was originally emissive, randomize emission
// with some probability (blinkenlights).
if (hsvm.m.IsKeywordEnabled("_EMISSION") && hsvm.m.HasProperty("_EmissionColor")) {
if (emission_probability_ > Random.Range(0.0f, 1.0f)) {
hsvm.m.SetColor(
"_EmissionColor",
Random.ColorHSV(hue, hue, min_s, max_s, min_v, max_v, alpha, alpha) * Random.Range(min_e, max_e));
} else {
hsvm.m.SetColor("_EmissionColor", Color.black);
}
}
}
return true;
}
public override void DrawEditorGUI() {
GUILayout.BeginVertical();
RendererComponent.GUIField("material_prefix", ref material_prefix_);
RendererComponent.GUIField("material_blacklist_prefix", ref material_blacklist_prefix_);
RendererComponent.GUIHorizontalLine(1);
RendererComponent.GUISlider("hue_radius", ref hue_radius_, 0.0f, 0.5f);
RendererComponent.GUIHorizontalLine(1);
RendererComponent.GUISlider("saturation_radius", ref saturation_radius_, 0.0f, 1.0f);
RendererComponent.GUISlider("min_saturation", ref min_saturation_, 0.0f, max_saturation_);
RendererComponent.GUISlider("max_saturation", ref max_saturation_, min_saturation_, 1.0f);
RendererComponent.GUIHorizontalLine(1);
RendererComponent.GUISlider("value_radius", ref value_radius_, 0.0f, 1.0f);
RendererComponent.GUISlider("min_value", ref min_value_, 0.0f, max_value_);
RendererComponent.GUISlider("max_value", ref max_value_, min_value_, 1.0f);
RendererComponent.GUIHorizontalLine(1);
RendererComponent.GUISlider("emission_probability", ref emission_probability_, 0.0f, 1.0f);
RendererComponent.GUISlider("emission_radius", ref emission_radius_, 0.0f, 10.0f);
RendererComponent.GUISlider("min_emission", ref min_emission_, 0.0f, max_emission_);
RendererComponent.GUISlider("max_emission", ref max_emission_, min_emission_, 10.0f);
RendererComponent.GUIHorizontalLine(1);
RendererComponent.GUISlider("min_metallic", ref min_metallic_, 0.0f, max_metallic_);
RendererComponent.GUISlider("max_metallic", ref max_metallic_, min_metallic_, 1.0f);
RendererComponent.GUIHorizontalLine(1);
RendererComponent.GUISlider("min_glossiness", ref min_glossiness_, 0.0f, max_glossiness_);
RendererComponent.GUISlider("max_glossiness", ref max_glossiness_, min_glossiness_, 1.0f);
GUILayout.EndVertical();
}
}
| 269 |
orrb | openai | C# | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// MaterialRandomizer assigns random tint, texture and normal map
// to a subset of materials. It also modifies the material's
// glossiness and metallic properties that control how shading
// appears in the Unity PBR model. The textures and normals are
// randomly picked from a small set of random images: checkers,
// patterns, noise, etc... Texture map tiling is also randomized.
//
// Configurable properties:
// string blacklist_prefix - comma separated list of material
// name prefixes to ignore,
// string whitelist_prefix - comma separated list of material
// name prefixes to randomize,
// float min_metallic - used to clamp the metallic randomization range,
// float max_metallic - used to clamp the metallic randomization range,
// float min_glossiness - used to clamp the glossiness randomization range,
// float max_glossiness - used to clamp the glossiness randomization range,
// bool randomize_textures - should textures and normal maps be
// randomly assigned.
public class MaterialRandomizer : RendererComponent {
[SerializeField]
[ConfigProperty]
public string blacklist_prefix_ = "cube";
[SerializeField]
[ConfigProperty]
public string whitelist_prefix_ = "";
[SerializeField]
[ConfigProperty]
public float min_metallic_ = 0.05f;
[SerializeField]
[ConfigProperty]
public float max_metallic_ = 0.25f;
[SerializeField]
[ConfigProperty]
public float min_glossiness_ = 0.0f;
[SerializeField]
[ConfigProperty]
public float max_glossiness_ = 1.0f;
[SerializeField]
[ConfigProperty]
public bool randomize_textures_ = false;
private List<Texture> textures_ = new List<Texture>();
private List<Texture> normals_ = new List<Texture>();
private string[] blacklist_prefixes_ = new string[0];
private string[] whitelist_prefixes_ = new string[0];
public override bool InitializeComponent(Orrb.RendererComponentConfig config) {
textures_.AddRange(Resources.LoadAll<Texture>("Textures"));
normals_.AddRange(Resources.LoadAll<Texture>("Normals"));
return base.InitializeComponent(config);
}
public override bool UpdateComponent(Orrb.RendererComponentConfig config) {
ConfigUtils.GetProperties(this, config);
blacklist_prefixes_ = blacklist_prefix_.Split(new char[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
whitelist_prefixes_ = whitelist_prefix_.Split(new char[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
return true;
}
public override bool RunComponent(RendererComponent.IOutputContext context) {
MeshRenderer[] renderers = GetComponentsInChildren<MeshRenderer>();
foreach (MeshRenderer mesh_renderer in renderers) {
foreach (Material material in mesh_renderer.materials) {
RandomizeMaterial(material);
}
}
return true;
}
private void RandomizeMaterial(Material material) {
foreach (string prefix in blacklist_prefixes_) {
if (material.name.StartsWith(prefix, System.StringComparison.Ordinal)) {
return;
}
}
if (whitelist_prefixes_.Length == 0) {
DoRandomizeMaterial(material);
} else {
foreach (string prefix in whitelist_prefixes_) {
if (material.name.StartsWith(prefix, System.StringComparison.Ordinal)) {
DoRandomizeMaterial(material);
return;
}
}
}
}
private void DoRandomizeMaterial(Material material) {
if (material.HasProperty("_Color")) {
// Do not randomize transparency, keep alpha as it was.
float alpha = material.color.a;
material.color = Random.ColorHSV(0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, alpha, alpha);
}
if (material.HasProperty("_Metallic")) {
material.SetFloat("_Metallic", Random.Range(min_metallic_, max_metallic_));
}
if (material.HasProperty("_Glossiness")) {
material.SetFloat("_Glossiness", Random.Range(min_glossiness_, max_glossiness_));
}
if (randomize_textures_) {
if (material.HasProperty("_MainTex")) {
material.SetTexture("_MainTex", GetRandomTexture());
material.SetTextureScale("_MainTex", new Vector2(Random.Range(0.4f, 4.0f), Random.Range(0.4f, 4.0f)));
material.SetTextureOffset("_MainTex", new Vector2(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f)));
}
if (material.HasProperty("_BumpMap")) {
material.SetTexture("_BumpMap", GetRandomNormal());
material.SetTextureScale("_BumpMap", new Vector2(Random.Range(0.4f, 4.0f), Random.Range(0.4f, 4.0f)));
material.SetTextureOffset("_BumpMap", new Vector2(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f)));
}
} else {
if (material.HasProperty("_MainTex")) {
material.SetTexture("_MainTex", null);
}
if (material.HasProperty("_BumpMap")) {
material.SetTexture("_BumpMap", null);
}
}
}
private Texture GetRandomTexture() {
if (textures_.Count > 0) {
return textures_[Random.Range(0, textures_.Count)];
} else {
return null;
}
}
private Texture GetRandomNormal() {
if (normals_.Count > 0) {
return normals_[Random.Range(0, normals_.Count)];
} else {
return null;
}
}
public override void DrawEditorGUI() {
GUILayout.BeginVertical();
RendererComponent.GUIField("blacklist_prefix", ref blacklist_prefix_);
RendererComponent.GUIField("whitelist_prefix", ref whitelist_prefix_);
RendererComponent.GUISlider("min_metallic", ref min_metallic_, 0.0f, max_metallic_);
RendererComponent.GUISlider("max_metallic", ref max_metallic_, min_metallic_, 1.0f);
RendererComponent.GUISlider("min_glossiness", ref min_glossiness_, 0.0f, max_glossiness_);
RendererComponent.GUISlider("max_glossiness", ref max_glossiness_, min_glossiness_, 1.0f);
RendererComponent.GUIToggle("randomize_textures", ref randomize_textures_);
GUILayout.EndVertical();
}
}
| 172 |
orrb | openai | C# | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
// This randomizer applies a set of post-processing effects on top of the rendered images.
// There are several post-processing profiles, including color gradient, bloom, ambient
// occlusion and grain noise.
//
// Parameter ranges in Unity:
// In ColorGrading:
// hue_shift - [-180, 180]
// saturation - [-100, 100]
// contrast - [-100, 100]
// brightness - [-100, 100]
// temperature - [-100, 100]
// tint - [-100, 100]
// In Bloom:
// intensity - [0.0, 10.0]
// diffusion - [1.0, 10.0]
// In AmbientOcclusion:
// intensity - [0.0, 4.0]
// In Grain:
// intensity - [0.0, 1.0]
// size - [-0.3, 3.0]
//
// Configurable properties:
// bool enable_color_grading - enable effects by ColorGrading profile,
// bool enable_bloom - enable effects by Bloom profile,
// bool enable_ambient_occlusion - enable effects by AmbientOcclusion profile,
// bool enable_grain - enable effects by Grain profile,
// float cg_min_hue_shift - minimum hue shift of all colors,
// float cg_max_hue_shift - maximum hue shift of all colors,
// float cg_min_saturation - minimum saturation of all colors,
// float cg_max_saturation - maximum saturation of all colors,
// float cg_min_contrast - minimum contrast of all colors,
// float cg_max_contrast - maximum contrast of all colors,
// float cg_min_contrast - minimum contrast of all colors,
// float cg_max_contrast - maximum contrast of all colors,
// float cg_min_temperature - minimum color temperature to set the white balance to,
// a larger number corresponds to a warmer temperature,
// while a smaller number induces a cooler one,
// float cg_max_temperature - maximum color temperature to set the white balance to,
// float cg_min_tint - minimum range of tint, a large number is more green-ish while a
// smaller number is more magenta-ish,
// float cg_max_tint - maximum range of tint,
// float bloom_min_intensity - minimum strength of the bloom filter,
// float bloom_max_intensity - maximum strength of the bloom filter,
// float bloom_min_diffusion - minimum extent of veiling effects,
// float bloom_max_diffusion - maximum extent of veiling effects,
// float ao_min_intensity - minimum degree of darkness added by ambient occlusion,
// float ao_max_intensity - maximum degree of darkness added by ambient occlusion,
// float grain_color_probability - probability of enabling colored grain,
// float grain_min_intensity - minimum grain strength,
// float grain_max_intensity - maximum grain strength,
// float grain_min_size - minimum grain particle size,
// float grain_max_size - maximum grain particle size,
public class PostProcessingRandomizer : RendererComponent {
[SerializeField]
[ConfigProperty]
public bool enable_color_grading_ = true;
[SerializeField]
[ConfigProperty]
public float cg_min_hue_shift_ = -10.0f;
[SerializeField]
[ConfigProperty]
public float cg_max_hue_shift_ = 10.0f;
[SerializeField]
[ConfigProperty]
public float cg_min_saturation_ = -20.0f;
[SerializeField]
[ConfigProperty]
public float cg_max_saturation_ = 20.0f;
[SerializeField]
[ConfigProperty]
public float cg_min_contrast_ = -20.0f;
[SerializeField]
[ConfigProperty]
public float cg_max_contrast_ = 20.0f;
[SerializeField]
[ConfigProperty]
public float cg_min_brightness_ = -20.0f;
[SerializeField]
[ConfigProperty]
public float cg_max_brightness_ = 20.0f;
[SerializeField]
[ConfigProperty]
public float cg_min_temperature_ = 0.0f;
[SerializeField]
[ConfigProperty]
public float cg_max_temperature_ = 0.0f;
[SerializeField]
[ConfigProperty]
public float cg_min_tint_ = 0.0f;
[SerializeField]
[ConfigProperty]
public float cg_max_tint_ = 0.0f;
[SerializeField]
[ConfigProperty]
public bool enable_bloom_ = true;
[SerializeField]
[ConfigProperty]
public float bloom_min_intensity_ = 0.75f;
[SerializeField]
[ConfigProperty]
public float bloom_max_intensity_ = 1.25f;
[SerializeField]
[ConfigProperty]
public float bloom_min_diffusion_ = 2.0f;
[SerializeField]
[ConfigProperty]
public float bloom_max_diffusion_ = 2.5f;
[SerializeField]
[ConfigProperty]
public bool enable_ambient_occlusion_ = true;
[SerializeField]
[ConfigProperty]
public float ao_min_intensity_ = 1.75f;
[SerializeField]
[ConfigProperty]
public float ao_max_intensity_ = 2.25f;
[SerializeField]
[ConfigProperty]
public bool enable_grain_ = false;
[SerializeField]
[ConfigProperty]
public float grain_color_probability_ = 0.75f;
[SerializeField]
[ConfigProperty]
public float grain_min_intensity_ = 0.0f;
[SerializeField]
[ConfigProperty]
public float grain_max_intensity_ = 0.0f;
[SerializeField]
[ConfigProperty]
public float grain_min_size_ = 0.0f;
[SerializeField]
[ConfigProperty]
public float grain_max_size_ = 0.0f;
private ColorGrading color_grading_ = null;
private Bloom bloom_ = null;
private AmbientOcclusion ambient_occlusion_ = null;
private Grain grain_ = null;
private PostProcessProfile FindPostprocessingProfile() {
// We should find one PostProcessVolume per camera.
PostProcessVolume[] volumes = GetComponentsInChildren<PostProcessVolume>();
// All the cameras share the same and *only one* profile.
HashSet<PostProcessProfile> profiles = new HashSet<PostProcessProfile>();
foreach (PostProcessVolume volume in volumes) {
profiles.Add(volume.sharedProfile);
}
Debug.Assert(profiles.Count == 1);
// Grab this profile.
HashSet<PostProcessProfile>.Enumerator em = profiles.GetEnumerator();
em.MoveNext();
PostProcessProfile profile = em.Current;
return profile;
}
public override bool InitializeComponent(Orrb.RendererComponentConfig config) {
// Find the post processing profile first.
PostProcessProfile profile = FindPostprocessingProfile();
// Grab the settings we are interested in from this profile.
profile.TryGetSettings(out color_grading_);
profile.TryGetSettings(out bloom_);
profile.TryGetSettings(out ambient_occlusion_);
profile.TryGetSettings(out grain_);
Debug.Assert(color_grading_ != null);
Debug.Assert(bloom_ != null);
Debug.Assert(ambient_occlusion_ != null);
Debug.Assert(grain_ != null);
return base.InitializeComponent(config);
}
public override bool RunComponent(RendererComponent.IOutputContext context) {
if (enable_color_grading_) {
// Randomize hue, satuation & contrast in ColorGrading object.
color_grading_.enabled.value = true;
color_grading_.hueShift.value = Random.Range(cg_min_hue_shift_, cg_max_hue_shift_);
color_grading_.saturation.value = Random.Range(cg_min_saturation_, cg_max_saturation_);
color_grading_.contrast.value = Random.Range(cg_min_contrast_, cg_max_contrast_);
color_grading_.brightness.value = Random.Range(cg_min_brightness_, cg_max_brightness_);
color_grading_.temperature.value = Random.Range(cg_min_temperature_, cg_max_temperature_);
color_grading_.tint.value = Random.Range(cg_min_tint_, cg_max_tint_);
} else {
color_grading_.enabled.value = false;
}
if (enable_bloom_) {
// Randomize intensity and diffusion in Bloom.
bloom_.enabled.value = true;
bloom_.intensity.value = Random.Range(bloom_min_intensity_, bloom_max_intensity_);
bloom_.diffusion.value = Random.Range(bloom_min_diffusion_, bloom_max_diffusion_);
} else {
bloom_.enabled.value = false;
}
if (enable_ambient_occlusion_) {
// Randomize the intensity and radius of shadows in AmbientOcclusion.
ambient_occlusion_.enabled.value = true;
ambient_occlusion_.quality.value = AmbientOcclusionQuality.Medium;
ambient_occlusion_.intensity.value = Random.Range(ao_min_intensity_, ao_max_intensity_);
} else {
ambient_occlusion_.enabled.value = false;
}
// Add Gains noise if needed.
if (enable_grain_) {
// Find Grain
grain_.enabled.value = true;
grain_.colored.value = (Random.Range(0.0f, 1.0f) < grain_color_probability_);
grain_.intensity.value = Random.Range(grain_min_intensity_, grain_max_intensity_);
grain_.size.value = Random.Range(grain_min_size_, grain_max_size_);
} else {
grain_.enabled.value = false;
}
return true;
}
public override void DrawEditorGUI() {
GUILayout.BeginVertical();
// ColorGrading
RendererComponent.GUIToggle("enable_color_grading", ref enable_color_grading_);
RendererComponent.GUISlider("cg_min_hue_shift", ref cg_min_hue_shift_, -180.0f, cg_max_hue_shift_);
RendererComponent.GUISlider("cg_max_hue_shift", ref cg_max_hue_shift_, cg_min_hue_shift_, 180.0f);
RendererComponent.GUISlider("cg_min_saturation", ref cg_min_saturation_, -100.0f, cg_max_saturation_);
RendererComponent.GUISlider("cg_max_saturation", ref cg_max_saturation_, cg_min_saturation_, 100.0f);
RendererComponent.GUISlider("cg_min_contrast", ref cg_min_contrast_, -100.0f, cg_max_contrast_);
RendererComponent.GUISlider("cg_max_contrast", ref cg_max_contrast_, cg_min_contrast_, 100.0f);
RendererComponent.GUISlider("cg_min_brightness", ref cg_min_brightness_, -100.0f, cg_max_brightness_);
RendererComponent.GUISlider("cg_max_brightness", ref cg_max_brightness_, cg_min_brightness_, 100.0f);
RendererComponent.GUISlider("cg_min_contrast", ref cg_min_contrast_, -100.0f, cg_max_contrast_);
RendererComponent.GUISlider("cg_max_contrast", ref cg_max_contrast_, cg_min_contrast_, 100.0f);
RendererComponent.GUISlider("cg_min_temperature", ref cg_min_temperature_, -100.0f, cg_max_temperature_);
RendererComponent.GUISlider("cg_max_temperature", ref cg_max_temperature_, cg_min_temperature_, 100.0f);
RendererComponent.GUISlider("cg_min_tint", ref cg_min_tint_, -100.0f, cg_max_tint_);
RendererComponent.GUISlider("cg_max_tint", ref cg_max_tint_, cg_min_tint_, 100.0f);
RendererComponent.GUIHorizontalLine(1);
// Bloom
RendererComponent.GUIToggle("enable_bloom", ref enable_bloom_);
RendererComponent.GUISlider("bloom_min_intensity", ref bloom_min_intensity_, 0.0f, bloom_max_intensity_);
RendererComponent.GUISlider("bloom_max_intensity", ref bloom_max_intensity_, bloom_min_intensity_, 10.0f);
RendererComponent.GUISlider("bloom_min_diffusion", ref bloom_min_diffusion_, 1.0f, bloom_max_diffusion_);
RendererComponent.GUISlider("bloom_max_diffusion", ref bloom_max_diffusion_, bloom_min_diffusion_, 10.0f);
RendererComponent.GUIHorizontalLine(1);
// Ambient Occlusion
RendererComponent.GUIToggle("enable_ambient_occlusion", ref enable_ambient_occlusion_);
RendererComponent.GUISlider("ao_min_intensity", ref ao_min_intensity_, 0.0f, ao_max_intensity_);
RendererComponent.GUISlider("ao_max_intensity", ref ao_max_intensity_, ao_min_intensity_, 4.0f);
RendererComponent.GUIHorizontalLine(1);
// Grain
RendererComponent.GUIToggle("enable_grain", ref enable_grain_);
RendererComponent.GUISlider("grain_color_probability", ref grain_color_probability_, 0.0f, 1.0f);
RendererComponent.GUISlider("grain_min_intensity", ref grain_min_intensity_, 0.0f, grain_max_intensity_);
RendererComponent.GUISlider("grain_max_intensity", ref grain_max_intensity_, grain_min_intensity_, 1.0f);
RendererComponent.GUISlider("grain_min_size", ref grain_min_size_, -0.3f, grain_max_size_);
RendererComponent.GUISlider("grain_max_size", ref grain_max_size_, grain_min_size_, 3.0f);
GUILayout.EndVertical();
}
}
| 302 |
orrb | openai | C# | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// LightingRig sets up lights in a programatic way and randomizes
// their positions. The rig arranges a number of new lights
// orbiting a specified center point. Mounting distance from the
// center point and the height above it can be separately
// randomized by specifying raspective randomization ranges.
// The newly created lights will be pointed at the center point.
//
// Configurable properties:
// int light_head_count - how many programatic lights should
// be created,
// float min_light_distance - lower bound for the distance
// randomization range,
// float max_light_distance - upper bound for the distance
// randomization range,
// float min_light_height - lower bound for the hight
// randomization range,
// float max_light_height - upper bound for the hight
// randomization range,
// vector3 target - the absolute location the lights orbit around,
// and are targeted at.
public class LightingRig : RendererComponent {
class LightHead {
public GameObject rotator = null;
public Light light = null;
public void SetUp(Vector3 target, float angle, float height, float distance) {
rotator.transform.localPosition = target;
rotator.transform.localRotation = Quaternion.AngleAxis(angle, Vector3.up);
light.transform.localPosition = Vector3.up * height + Vector3.back * distance;
light.transform.LookAt(rotator.transform.position, Vector3.up);
}
}
[SerializeField]
[ConfigProperty]
public int light_head_count_ = 6;
[SerializeField]
[ConfigProperty]
public float min_light_distance_ = 1.0f;
[SerializeField]
[ConfigProperty]
public float max_light_distance_ = 1.5f;
[SerializeField]
[ConfigProperty]
public float min_light_height_ = 0.5f;
[SerializeField]
[ConfigProperty]
public float max_light_height_ = 1.5f;
[SerializeField]
[ConfigProperty]
public Vector3 target_ = Vector3.zero;
private List<LightHead> light_heads_ = new List<LightHead>();
// Remove the lights created by this randomizer.
private void ClearLightHeads() {
foreach (LightHead light_head in light_heads_) {
light_head.light = null;
Destroy(light_head.rotator);
light_head.rotator = null;
}
light_heads_.Clear();
}
// Set up the lighting rig, create programatic lights.
private void BuildLightHeads() {
ClearLightHeads();
for (int i = 0; i < light_head_count_; ++i) {
LightHead light_head = new LightHead();
light_head.rotator = new GameObject(string.Format("light_head_{0}", i));
light_head.rotator.transform.parent = this.transform;
light_head.rotator.transform.localPosition = Vector3.zero;
light_head.light = new GameObject(string.Format("light_{0}", i)).AddComponent<Light>();
light_head.light.transform.parent = light_head.rotator.transform;
light_head.light.transform.localPosition = Vector3.zero;
light_head.light.type = LightType.Spot;
light_head.light.shadows = LightShadows.Soft;
light_head.light.range = Mathf.Sqrt(max_light_distance_ * max_light_distance_ +
max_light_height_ + max_light_height_) + 1.0f;
light_head.light.intensity = 1.0f;
light_head.light.shadowResolution = UnityEngine.Rendering.LightShadowResolution.VeryHigh;
light_head.light.shadowBias = 0.001f;
light_head.light.shadowNormalBias = 0.0f;
light_head.light.spotAngle = 30.0f;
light_heads_.Add(light_head);
}
}
public override bool InitializeComponent(Orrb.RendererComponentConfig config) {
light_head_count_ = ConfigUtils.GetProperty("light_head_count", config, light_head_count_);
BuildLightHeads();
return UpdateComponent(config);
}
public override bool UpdateComponent(Orrb.RendererComponentConfig config) {
int old_light_head_count = light_head_count_;
ConfigUtils.GetProperties(this, config);
if (old_light_head_count != light_head_count_) {
BuildLightHeads();
}
return true;
}
public override bool RunComponent(RendererComponent.IOutputContext context) {
foreach (LightHead light_head in light_heads_) {
// Randomize orbit angle [0.0, 360.0) degrees, and use
// randomization ranges to determine mounting distance
// and mounting height.
light_head.SetUp(target_, Random.Range(0.0f, 360.0f), Random.Range(min_light_height_, max_light_height_),
Random.Range(min_light_distance_, max_light_distance_));
}
return true;
}
public override void DrawEditorGUI() { }
}
| 136 |
orrb | openai | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEngine;
// ConfigUtilities provide a reflection based interoperation between the C# components and protocol
// buffer based RendererComponentConfig structures. The helper functions: Get/SetProperty allow easy
// extraction / injection of singular configurable values. The Get/SetProperties methods allow
// configuring of whole components, and depend on runtime, reflective introspection of the component.
// The ConfigProperty attribute is used to mark configurable fields.
[AttributeUsage(AttributeTargets.Field)]
public class ConfigProperty : Attribute {
}
public class ConfigUtils {
public static float GetProperty(string name, Orrb.RendererComponentConfig config, float default_value) {
if (config != null && config.FloatProperties.ContainsKey(name)) {
return config.FloatProperties[name];
}
return default_value;
}
public static void SetProperty(string name, Orrb.RendererComponentConfig config, float value) {
config.FloatProperties.Add(name, value);
}
public static int GetProperty(string name, Orrb.RendererComponentConfig config, int default_value) {
if (config != null && config.IntProperties.ContainsKey(name)) {
return config.IntProperties[name];
}
return default_value;
}
public static void SetProperty(string name, Orrb.RendererComponentConfig config, int value) {
config.IntProperties.Add(name, value);
}
public static string GetProperty(string name, Orrb.RendererComponentConfig config, string default_value) {
if (config != null && config.StringProperties.ContainsKey(name)) {
return config.StringProperties[name];
}
return default_value;
}
public static void SetProperty(string name, Orrb.RendererComponentConfig config, string value) {
config.StringProperties.Add(name, value);
}
public static bool GetProperty(string name, Orrb.RendererComponentConfig config, bool default_value) {
if (config != null && config.BoolProperties.ContainsKey(name)) {
return config.BoolProperties[name];
}
return default_value;
}
public static void SetProperty(string name, Orrb.RendererComponentConfig config, bool value) {
config.BoolProperties.Add(name, value);
}
public static Vector3 GetProperty(string name, Orrb.RendererComponentConfig config, Vector3 default_value) {
if (config != null && config.Vector3Properties.ContainsKey(name)) {
Orrb.Vector3 vector3 = config.Vector3Properties[name];
return new Vector3(vector3.X, vector3.Y, vector3.Z);
}
return default_value;
}
public static void SetProperty(string name, Orrb.RendererComponentConfig config, Vector3 value) {
Orrb.Vector3 vector3 = new Orrb.Vector3();
vector3.X = value.x;
vector3.Y = value.y;
vector3.Z = value.z;
config.Vector3Properties.Add(name, vector3);
}
public static Vector2 GetProperty(string name, Orrb.RendererComponentConfig config, Vector2 default_value) {
if (config != null && config.Vector2Properties.ContainsKey(name)) {
Orrb.Vector2 vector2 = config.Vector2Properties[name];
return new Vector2(vector2.X, vector2.Y);
}
return default_value;
}
public static void SetProperty(string name, Orrb.RendererComponentConfig config, Vector2 value) {
Orrb.Vector2 vector2 = new Orrb.Vector2();
vector2.X = value.x;
vector2.Y = value.y;
config.Vector2Properties.Add(name, vector2);
}
public static Quaternion GetProperty(string name, Orrb.RendererComponentConfig config, Quaternion default_value) {
if (config != null && config.QuaternionProperties.ContainsKey(name)) {
Orrb.Quaternion quaternion = config.QuaternionProperties[name];
return new Quaternion(quaternion.X, quaternion.Y, quaternion.Z, quaternion.W);
}
return default_value;
}
public static void SetProperty(string name, Orrb.RendererComponentConfig config, Quaternion value) {
Orrb.Quaternion quaternion = new Orrb.Quaternion();
quaternion.X = value.x;
quaternion.Y = value.y;
quaternion.Z = value.z;
quaternion.W = value.w;
config.QuaternionProperties.Add(name, quaternion);
}
public static Color GetProperty(string name, Orrb.RendererComponentConfig config, Color default_value) {
if (config != null && config.ColorProperties.ContainsKey(name)) {
Orrb.Color color = config.ColorProperties[name];
return new Color(color.R, color.G, color.B, color.A);
}
return default_value;
}
public static void SetProperty(string name, Orrb.RendererComponentConfig config, Color value) {
Orrb.Color color = new Orrb.Color();
color.R = value.r;
color.G = value.g;
color.B = value.b;
color.A = value.a;
config.ColorProperties.Add(name, color);
}
public static T GetEnumProperty<T>(string name, Orrb.RendererComponentConfig config, T default_value)
where T : struct, IConvertible {
if (config != null && config.EnumProperties.ContainsKey(name)) {
return (T)Enum.Parse(typeof(T), config.EnumProperties[name]);
}
return default_value;
}
public static void SetEnumProperty<T>(string name, Orrb.RendererComponentConfig config, T value)
where T : struct, IConvertible {
config.EnumProperties.Add(name, value.ToString());
}
public static void GetProperties(object subject, Orrb.RendererComponentConfig config) {
Type utils = typeof(ConfigUtils);
Type[] getter_types = new Type[] { typeof(string), typeof(Orrb.RendererComponentConfig), typeof(string) };
object[] getter_parameters = { null, config, null };
MethodInfo enum_property_getter = utils.GetMethod("GetEnumProperty");
foreach (FieldInfo field_info in subject.GetType().GetFields()) {
if (field_info.IsDefined(typeof(ConfigProperty), true)) {
MethodInfo property_getter = null;
if (field_info.FieldType.IsEnum) {
property_getter = enum_property_getter.MakeGenericMethod(field_info.FieldType);
} else {
getter_types[2] = field_info.FieldType;
property_getter = utils.GetMethod("GetProperty", getter_types);
}
if (property_getter == null) {
Logger.Error("Cannot get property getter for: {0}", field_info.FieldType);
} else {
getter_parameters[0] = GetPropertyName(field_info.Name);
getter_parameters[2] = field_info.GetValue(subject);
field_info.SetValue(subject, property_getter.Invoke(null, getter_parameters));
}
}
}
}
private static string GetPropertyName(string name) {
if (name.EndsWith("_", StringComparison.Ordinal)) {
return name.Substring(0, name.Length - 1);
}
return name;
}
public static void SetProperties(object subject, Orrb.RendererComponentConfig config) {
Type utils = typeof(ConfigUtils);
Type[] setter_types = new Type[] { typeof(string), typeof(Orrb.RendererComponentConfig), typeof(string) };
object[] setter_parameters = { null, config, null };
MethodInfo enum_property_setter = utils.GetMethod("SetEnumProperty");
foreach (FieldInfo field_info in subject.GetType().GetFields()) {
if (field_info.IsDefined(typeof(ConfigProperty), true)) {
MethodInfo property_setter = null;
if (field_info.FieldType.IsEnum) {
property_setter = enum_property_setter.MakeGenericMethod(field_info.FieldType);
} else {
setter_types[2] = field_info.FieldType;
property_setter = utils.GetMethod("SetProperty", setter_types);
}
if (property_setter == null) {
Logger.Error("Cannot get property setter for: {0}.", field_info.FieldType);
} else {
setter_parameters[0] = GetPropertyName(field_info.Name);
setter_parameters[2] = field_info.GetValue(subject);
property_setter.Invoke(null, setter_parameters);
}
}
}
}
public static string ResolveFile(string basedir, string file_path) {
if (Path.IsPathRooted(file_path)) {
return file_path;
} else {
return Path.Combine(basedir, file_path);
}
}
}
| 213 |
orrb | openai | C# | using System;
using System.Collections.Generic;
using MIConvexHull;
using UnityEngine;
// This is a simple wrapper for the MIConvexHull. The static method CreateConvexHull takes a Unity Mesh
// and produces a Unity Mesh with the convex hull.
public class ConvexHull {
public static Mesh CreateConvexHull(Mesh mesh) {
List<MIConvexHull.DefaultVertex> vertices = new List<DefaultVertex>();
foreach (Vector3 vertex in mesh.vertices) {
MIConvexHull.DefaultVertex mi_vertex = new MIConvexHull.DefaultVertex();
mi_vertex.Position = new double[3] { vertex.x, vertex.y, vertex.z };
vertices.Add(mi_vertex);
}
MIConvexHull.ConvexHull<
MIConvexHull.DefaultVertex,
MIConvexHull.DefaultConvexFace<MIConvexHull.DefaultVertex>> mi_hull =
MIConvexHull.ConvexHull.Create(vertices);
List<Vector3> hull_vertices = new List<Vector3>();
foreach (MIConvexHull.DefaultVertex vertex in mi_hull.Points) {
hull_vertices.Add(new Vector3((float)vertex.Position[0], (float)vertex.Position[1], (float)vertex.Position[2]));
}
IList<MIConvexHull.DefaultVertex> mi_hull_vertices = new List<MIConvexHull.DefaultVertex>(mi_hull.Points);
List<int> triangles = new List<int>();
foreach (MIConvexHull.DefaultConvexFace<MIConvexHull.DefaultVertex> face in mi_hull.Faces) {
triangles.Add(mi_hull_vertices.IndexOf(face.Vertices[0]));
triangles.Add(mi_hull_vertices.IndexOf(face.Vertices[1]));
triangles.Add(mi_hull_vertices.IndexOf(face.Vertices[2]));
}
Mesh hull = new Mesh();
hull.vertices = hull_vertices.ToArray();
hull.triangles = triangles.ToArray();
hull.RecalculateNormals();
return hull;
}
}
| 47 |
orrb | openai | C# | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using System.Reflection;
// This utility allows properties (class member variables) to be configured from commandline and
// property files. Use the Flag attribute to mark configurable variables. This utility depends
// on runtime reflexive introspection.
[AttributeUsage(AttributeTargets.Field)]
public class Flag : Attribute {
}
public class Flags {
static private Dictionary<string, object> object_flags_ = new Dictionary<string, object>();
static private Dictionary<string, string> string_flags_ = new Dictionary<string, string>();
static Flags() {
string[] args = System.Environment.GetCommandLineArgs();
foreach (string arg in args) {
string[] split = arg.Split(new char[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (split.Length == 1) {
string bool_flag = split[0];
if (!bool_flag.StartsWith("--", StringComparison.Ordinal)) {
continue;
}
bool_flag = bool_flag.Substring(2);
AddBoolFlag(bool_flag, true);
} else if (split.Length == 2) {
string key = split[0];
string value = split[1];
if (!key.StartsWith("--", StringComparison.Ordinal)) {
continue;
}
key = key.Substring(2);
if ("flags.file".Equals(key)) {
LoadFlagsFromFile(value);
} else {
string_flags_[key] = value;
}
}
}
}
private static void LoadFlagsFromFile(string file_name) {
Logger.Info("Flags::LoadFlagsFromFile::Reading flag file: {0}", file_name);
StreamReader reader = new StreamReader(file_name);
string line = "";
while ((line = reader.ReadLine()) != null) {
string[] split = line.Split(new char[] { ' ' }, 3, StringSplitOptions.RemoveEmptyEntries);
if (split.Length == 2) {
string flag_type = split[0];
string key = split[1];
if (typeof(bool).Name.Equals(flag_type)) {
AddBoolFlag(key, true);
} else if (typeof(string).Name.Equals(flag_type)) {
string_flags_[key] = "";
}
} else if (split.Length == 3) {
string flag_type = split[0];
string key = split[1];
string value = split[2];
if (typeof(bool).Name.Equals(flag_type)) {
AddBoolFlag(key, bool.Parse(value));
} else if (typeof(int).Name.Equals(flag_type)) {
object_flags_[key] = int.Parse(value);
} else if (typeof(float).Name.Equals(flag_type)) {
object_flags_[key] = float.Parse(value);
} else if (typeof(string).Name.Equals(flag_type)) {
object_flags_[key] = value;
string_flags_[key] = value;
} else {
string_flags_[key] = value;
}
}
}
reader.Close();
}
static private void AddBoolFlag(string key, bool value) {
if (key.StartsWith("no", System.StringComparison.Ordinal)) {
object_flags_[key.Substring(2)] = !value;
} else {
object_flags_[key] = value;
}
}
static public object Get<T>(string name, T default_value) {
if (string_flags_.ContainsKey(name)) {
string value = string_flags_[name];
if (typeof(T).IsEnum) {
T retval = (T)Enum.Parse(typeof(T), value, true);
object_flags_[name] = retval;
return retval;
} else if (typeof(T).Equals(typeof(Vector3))) {
Vector3 retval = ParseVector3(value);
object_flags_[name] = retval;
return retval;
} else {
T retval = (T)Convert.ChangeType(value, typeof(T));
object_flags_[name] = retval;
return retval;
}
} else if (object_flags_.ContainsKey(name)) {
return (T)object_flags_[name];
} else {
object_flags_.Add(name, default_value);
return default_value;
}
}
static private Vector3 ParseVector3(string string_vec) {
if (string_vec.StartsWith("(") && string_vec.EndsWith(")")) {
string_vec = string_vec.Substring(1, string_vec.Length - 2);
}
string[] splits = string_vec.Split(new char[] { ',' });
if (splits.Length != 3) {
Logger.Error("Flags::ParseVector3::Invalid Vector3: {0}", string_vec);
return Vector3.zero;
}
return new Vector3(float.Parse(splits[0].Trim()), float.Parse(splits[1].Trim()), float.Parse(splits[2].Trim()));
}
static public void DumpFlags() {
SortedDictionary<string, string> flag_strings = new SortedDictionary<string, string>();
foreach (KeyValuePair<string, object> pair in object_flags_) {
if (pair.Value.GetType().IsEnum) {
flag_strings.Add(pair.Key, string.Format("String {0} {1}", pair.Key, pair.Value));
} else {
flag_strings.Add(pair.Key, string.Format("{0} {1} {2}", pair.Value.GetType().Name, pair.Key, pair.Value));
}
}
foreach (KeyValuePair<string, string> pair in flag_strings) {
System.Console.WriteLine(pair.Value);
}
}
static public void InitFlags(object subject, string prefix) {
MethodInfo flag_getter = typeof(Flags).GetMethod("Get");
foreach (FieldInfo field_info in subject.GetType().GetFields()) {
if (field_info.IsDefined(typeof(Flag), true)) {
MethodInfo typed_flag_getter = flag_getter.MakeGenericMethod(field_info.FieldType);
field_info.SetValue(subject, typed_flag_getter.Invoke(null, new object[] {
GetFlagName (prefix, field_info.Name),
field_info.GetValue (subject)
}));
}
}
}
static private string GetFlagName(string prefix, string flag_name) {
if (flag_name.EndsWith("_")) {
flag_name = flag_name.Substring(0, flag_name.Length - 1);
}
return string.Format("{0}.{1}", prefix, flag_name);
}
}
| 171 |
orrb | openai | C# | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// A simple utility used to unify logging. The time logged is measured in milliseconds relative to
// application startup. An Id and indent / alignment value can be provided in order to make logs
// from multiple servers visually align nicer.
public class Logger {
public enum Level {
DEBUG,
INFO,
WARNING,
ERROR,
FATAL
};
private static string id_ = "";
private static string id_aligned_ = "";
public static void Initialize(string id, int alignment) {
id_ = id;
if (id_.Length > 0 && alignment > id_.Length) {
id_aligned_ = id_.PadLeft(alignment);
} else {
id_aligned_ = id_;
}
}
public static void Info(string format, params object[] objects) {
Log(Level.INFO, format, objects);
}
public static void Warning(string format, params object[] objects) {
Log(Level.WARNING, format, objects);
}
public static void Error(string format, params object[] objects) {
Log(Level.ERROR, format, objects);
}
static void Log(Level level, string format, params object[] objects) {
string message = string.Format(format, objects);
if (id_aligned_.Length > 0) {
message = string.Format("{0}::{1}::{2}::{3}", id_aligned_, LevelToString(level), Millis(), message);
} else {
message = string.Format("{0}::{1}::{2}", LevelToString(level), Millis(), message);
}
Consume(message);
}
private static void Consume(string message) {
System.Console.WriteLine(message);
if (Application.isEditor) {
Debug.Log(message);
}
}
private static string LevelToString(Level level) {
switch (level) {
case Level.DEBUG:
return "D";
case Level.INFO:
return "I";
case Level.WARNING:
return "W";
case Level.ERROR:
return "E";
default:
return "X";
}
}
private static string Millis() {
return ((int)(Time.realtimeSinceStartup * 1000)).ToString("D10");
}
}
| 80 |
orrb | openai | C# | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SceneUtils {
// Create a named game object and attach a component to it.
public static T InstantiateWithController<T>(string name) where T : Component {
GameObject game_object = new GameObject();
return game_object.AddComponent<T>() as T;
}
// Find a named child Component of a given type in a GameObject.
public static T Find<T>(GameObject where, string name, T default_value) where T : Component {
return Find<T>(where.transform, name, default_value);
}
// Find a named child Component of a given type in a Component.
public static T Find<T>(Component where, string name, T default_value) where T : Component {
Transform transform = where.transform;
Transform child = transform.Find(name);
if (child != null && child.GetComponent<T>() != null) {
return child.GetComponent<T>();
} else {
return default_value;
}
}
// Find a named child GameObject in a GameObject.
public static GameObject Find(GameObject where, string name, GameObject default_value) {
return Find(where.transform, name, default_value);
}
// Find a named child GameObject in a Component.
public static GameObject Find(Component where, string name, GameObject default_value) {
Transform transform = where.transform;
Transform child = transform.Find(name);
if (child != null) {
return child.gameObject;
} else {
return default_value;
}
}
}
| 47 |
orrb | openai | C# | using System.Collections.Generic;
using UnityEngine;
using System.Xml;
// Utilities that support reading the MuJoCo XMLs and the property inheritance model that
// it uses.
public class XmlUtils {
public class Defaults {
public XmlNode root;
public XmlNode current;
public Defaults(XmlNode root) : this(root, root) { }
public Defaults(XmlNode root, XmlNode current) {
this.root = root;
this.current = current;
}
public Defaults Resolve(string class_name) {
if (class_name == null) {
return this;
}
return Traverse(root, class_name);
}
private Defaults Traverse(XmlNode node, string class_name) {
if (class_name.Equals(GetString(node, "class", null))) {
return new Defaults(root, node);
}
foreach (XmlNode child_node in GetChildNodes(node, "default")) {
Defaults child_defaults = Traverse(child_node, class_name);
if (child_defaults != null) {
return child_defaults;
}
}
return null;
}
public Defaults GetSubclass(string subclass_name) {
if (current != null) {
return new Defaults(root, GetChildNode(current, subclass_name));
} else {
return new Defaults(root, null);
}
}
};
public static XmlNode GetChildNode(XmlNode node, string name) {
List<XmlNode> child_nodes = GetChildNodes(node, name);
if (child_nodes.Count == 1) {
return child_nodes[0];
} else if (child_nodes.Count == 0) {
return null;
} else {
Logger.Warning("RobotLoader::GetChildNode::Expected only 1 child: {0}, got {1}", name, child_nodes.Count);
return null;
}
}
public static List<XmlNode> GetChildNodes(XmlNode node, string name) {
List<XmlNode> filtered_child_nodes = new List<XmlNode>();
foreach (XmlNode child_node in node.ChildNodes) {
if (child_node.Name.Equals(name)) {
filtered_child_nodes.Add(child_node);
}
}
return filtered_child_nodes;
}
public static bool HasAttributeWithDefaults(XmlNode node, Defaults defaults, string attribute_name) {
if (defaults != null && defaults.current != null) {
return HasAttribute(defaults.current, attribute_name) || HasAttribute(node, attribute_name);
}
return HasAttribute(node, attribute_name);
}
public static bool HasAttribute(XmlNode node, string attribute_name) {
XmlNode attribute_node = node.Attributes.GetNamedItem(attribute_name);
return attribute_node != null;
}
public static Vector2 GetVector2WithDefaults(XmlNode node, Defaults defaults, string vector_name,
Vector2 default_value) {
if (defaults != null && defaults.current != null) {
return GetVector2(node, vector_name, GetVector2(defaults.current, vector_name, default_value));
}
return GetVector2(node, vector_name, default_value);
}
public static Vector2 GetVector2(XmlNode node, string name, Vector2 default_value) {
XmlNode attribute_node = node.Attributes.GetNamedItem(name);
if (attribute_node != null) {
return ParseVector2(attribute_node.Value, default_value);
} else {
return default_value;
}
}
public static Vector3 GetVector3WithDefaults(XmlNode node, Defaults defaults, string vector_name,
Vector3 default_value) {
if (defaults != null && defaults.current != null) {
return GetVector3(node, vector_name, GetVector3(defaults.current, vector_name, default_value));
}
return GetVector3(node, vector_name, default_value);
}
public static Vector3 GetVector3(XmlNode node, string vector_name, Vector3 default_value) {
XmlNode attribute_node = node.Attributes.GetNamedItem(vector_name);
if (attribute_node != null) {
return ParseVector3(attribute_node.Value, default_value);
} else {
return default_value;
}
}
public static Vector4 GetVector4WithDefaults(XmlNode node, Defaults defaults, string vector_name,
Vector4 default_value) {
if (defaults != null && defaults.current != null) {
return GetVector4(node, vector_name, GetVector4(defaults.current, vector_name, default_value));
}
return GetVector4(node, vector_name, default_value);
}
public static Vector4 GetVector4(XmlNode node, string name, Vector4 default_value) {
XmlNode attribute_node = node.Attributes.GetNamedItem(name);
if (attribute_node != null) {
return ParseVector4(attribute_node.Value, default_value);
} else {
return default_value;
}
}
public static Quaternion GetRotationWithDefaults(XmlNode node, Defaults defaults, Quaternion default_value) {
if (defaults != null && defaults.current != null) {
return GetRotation(node, GetRotation(defaults.current, default_value));
}
return GetRotation(node, default_value);
}
public static Quaternion GetRotation(XmlNode node, Quaternion default_value) {
if (HasAttribute(node, "euler")) {
return Quaternion.Euler(XmlUtils.GetVector3(node, "euler", Vector3.zero) * Mathf.Rad2Deg);
} else if (HasAttribute(node, "axisangle")) {
Vector4 axis_angle = XmlUtils.GetVector4(node, "axisangle", Vector4.zero);
return Quaternion.AngleAxis(axis_angle[3] * Mathf.Rad2Deg, new Vector3(axis_angle[0], axis_angle[1], axis_angle[2]));
} else {
return XmlUtils.GetQuaternion(node, "quat", default_value);
}
}
public static Color GetColorWithDefaults(XmlNode node, Defaults defaults, string color_name, Color default_color) {
if (defaults != null && defaults.current != null) {
return GetColor(node, color_name, GetColor(defaults.current, color_name, default_color));
}
return GetColor(node, color_name, default_color);
}
public static Color GetColor(XmlNode node, string color_name, Color default_color) {
XmlNode attribute_node = node.Attributes.GetNamedItem(color_name);
if (attribute_node != null) {
return ParseColor(attribute_node.Value, default_color);
} else {
return default_color;
}
}
public static Quaternion GetQuaternion(XmlNode node, string name, Quaternion default_value) {
XmlNode attribute_node = node.Attributes.GetNamedItem(name);
if (attribute_node != null) {
return ParseQuaternion(attribute_node.Value, default_value);
} else {
return default_value;
}
}
public static string GetStringWithDefaults(XmlNode node, Defaults defaults, string string_name,
string default_value) {
if (defaults != null && defaults.current != null) {
return GetString(node, string_name, GetString(defaults.current, string_name, default_value));
}
return GetString(node, string_name, default_value);
}
public static string GetString(XmlNode node, string string_name, string default_value) {
XmlNode attribute_node = node.Attributes.GetNamedItem(string_name);
if (attribute_node != null) {
return attribute_node.Value;
} else {
return default_value;
}
}
public static float GetFloat(XmlNode node, string name, float default_value) {
XmlNode attribute_node = node.Attributes.GetNamedItem(name);
if (attribute_node != null) {
return float.Parse(attribute_node.Value);
} else {
return default_value;
}
}
public static Vector2 ParseVector2(string text, Vector2 default_vector) {
string[] split = text.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
if (split.Length == 1) {
return Vector2.one * float.Parse(split[0]);
} else if (split.Length == 2 || split.Length == 3) {
return new Vector2(float.Parse(split[0]), float.Parse(split[1]));
} else {
return default_vector;
}
}
public static Vector3 ParseVector3(string text, Vector3 default_vector) {
string[] split = text.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
if (split.Length == 1) {
return Vector3.one * float.Parse(split[0]);
} else if (split.Length == 3 || split.Length == 4) {
return new Vector3(float.Parse(split[0]), float.Parse(split[1]), float.Parse(split[2]));
} else {
return default_vector;
}
}
public static Vector4 ParseVector4(string text, Vector4 default_vector) {
string[] split = text.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
if (split.Length != 4) {
return default_vector;
} else {
return new Vector4(float.Parse(split[0]), float.Parse(split[1]), float.Parse(split[2]), float.Parse(split[3]));
}
}
public static Color ParseColor(string text, Color default_color) {
string[] split = text.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
if (split.Length != 4) {
return default_color;
} else {
return new Color(float.Parse(split[0]), float.Parse(split[1]), float.Parse(split[2]), float.Parse(split[3]));
}
}
public static Quaternion ParseQuaternion(string text, Quaternion default_quaternion) {
string[] split = text.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
if (split.Length != 4) {
return default_quaternion;
} else {
return new Quaternion(float.Parse(split[1]), float.Parse(split[2]), float.Parse(split[3]), float.Parse(split[0]));
}
}
}
| 256 |
orrb | openai | C# | // ===============================================================================================
// The MIT License (MIT) for UnityFBXExporter
//
// UnityFBXExporter was created for Building Crafter (http://u3d.as/ovC) a tool to rapidly
// create high quality buildings right in Unity with no need to use 3D modeling programs.
//
// Copyright (c) 2016 | 8Bit Goose Games, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// ===============================================================================================
using UnityEngine;
using System.Text;
using System.Collections.Generic;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Linq;
namespace UnityFBXExporter
{
public class FBXExporter
{
public static bool ExportGameObjToFBX(GameObject gameObj, string newPath, bool copyMaterials = false, bool copyTextures = false)
{
// Check to see if the extension is right
if(newPath.Remove(0, newPath.LastIndexOf('.')) != ".fbx")
{
Debug.LogError("The end of the path wasn't \".fbx\"");
return false;
}
if(copyMaterials)
CopyComplexMaterialsToPath(gameObj, newPath, copyTextures);
string buildMesh = MeshToString(gameObj, newPath, copyMaterials, copyTextures);
if(System.IO.File.Exists(newPath))
System.IO.File.Delete(newPath);
System.IO.File.WriteAllText(newPath, buildMesh);
#if UNITY_EDITOR
// Import the model properly so it looks for the material instead of by the texture name
// TODO: By calling refresh, it imports the model with the wrong materials, but we can't find the model to import without
// refreshing the database. A chicken and the egg issue
AssetDatabase.Refresh();
string stringLocalPath = newPath.Remove(0, newPath.LastIndexOf("/Assets") + 1);
ModelImporter modelImporter = ModelImporter.GetAtPath(stringLocalPath) as ModelImporter;
if(modelImporter != null)
{
ModelImporterMaterialName modelImportOld = modelImporter.materialName;
modelImporter.materialName = ModelImporterMaterialName.BasedOnMaterialName;
#if UNITY_5_1
modelImporter.normalImportMode = ModelImporterTangentSpaceMode.Import;
#else
modelImporter.importNormals = ModelImporterNormals.Import;
#endif
if (copyMaterials == false)
modelImporter.materialSearch = ModelImporterMaterialSearch.Everywhere;
AssetDatabase.ImportAsset(stringLocalPath, ImportAssetOptions.ForceUpdate);
}
else
{
Debug.Log("Model Importer is null and can't import");
}
AssetDatabase.Refresh();
#endif
return true;
}
public static string VersionInformation
{
get { return "FBX Unity Export version 1.1.1 (Originally created for the Unity Asset, Building Crafter)"; }
}
public static long GetRandomFBXId()
{
return System.BitConverter.ToInt64(System.Guid.NewGuid().ToByteArray(), 0);
}
public static string MeshToString (GameObject gameObj, string newPath, bool copyMaterials = false, bool copyTextures = false)
{
StringBuilder sb = new StringBuilder();
StringBuilder objectProps = new StringBuilder();
objectProps.AppendLine("; Object properties");
objectProps.AppendLine(";------------------------------------------------------------------");
objectProps.AppendLine("");
objectProps.AppendLine("Objects: {");
StringBuilder objectConnections = new StringBuilder();
objectConnections.AppendLine("; Object connections");
objectConnections.AppendLine(";------------------------------------------------------------------");
objectConnections.AppendLine("");
objectConnections.AppendLine("Connections: {");
objectConnections.AppendLine("\t");
Material[] materials = new Material[0];
// First finds all unique materials and compiles them (and writes to the object connections) for funzies
string materialsObjectSerialized = "";
string materialConnectionsSerialized = "";
FBXUnityMaterialGetter.GetAllMaterialsToString(gameObj, newPath, copyMaterials, copyTextures, out materials, out materialsObjectSerialized, out materialConnectionsSerialized);
// Run recursive FBX Mesh grab over the entire gameobject
FBXUnityMeshGetter.GetMeshToString(gameObj, materials, ref objectProps, ref objectConnections);
// write the materials to the objectProps here. Should not do it in the above as it recursive.
objectProps.Append(materialsObjectSerialized);
objectConnections.Append(materialConnectionsSerialized);
// Close up both builders;
objectProps.AppendLine("}");
objectConnections.AppendLine("}");
// ========= Create header ========
// Intro
sb.AppendLine("; FBX 7.3.0 project file");
sb.AppendLine("; Copyright (C) 1997-2010 Autodesk Inc. and/or its licensors.");
sb.AppendLine("; All rights reserved.");
sb.AppendLine("; ----------------------------------------------------");
sb.AppendLine();
// The header
sb.AppendLine("FBXHeaderExtension: {");
sb.AppendLine("\tFBXHeaderVersion: 1003");
sb.AppendLine("\tFBXVersion: 7300");
// Creationg Date Stamp
System.DateTime currentDate = System.DateTime.Now;
sb.AppendLine("\tCreationTimeStamp: {");
sb.AppendLine("\t\tVersion: 1000");
sb.AppendLine("\t\tYear: " + currentDate.Year);
sb.AppendLine("\t\tMonth: " + currentDate.Month);
sb.AppendLine("\t\tDay: " + currentDate.Day);
sb.AppendLine("\t\tHour: " + currentDate.Hour);
sb.AppendLine("\t\tMinute: " + currentDate.Minute);
sb.AppendLine("\t\tSecond: " + currentDate.Second);
sb.AppendLine("\t\tMillisecond: " + currentDate.Millisecond);
sb.AppendLine("\t}");
// Info on the Creator
sb.AppendLine("\tCreator: \"" + VersionInformation + "\"");
sb.AppendLine("\tSceneInfo: \"SceneInfo::GlobalInfo\", \"UserData\" {");
sb.AppendLine("\t\tType: \"UserData\"");
sb.AppendLine("\t\tVersion: 100");
sb.AppendLine("\t\tMetaData: {");
sb.AppendLine("\t\t\tVersion: 100");
sb.AppendLine("\t\t\tTitle: \"\"");
sb.AppendLine("\t\t\tSubject: \"\"");
sb.AppendLine("\t\t\tAuthor: \"\"");
sb.AppendLine("\t\t\tKeywords: \"\"");
sb.AppendLine("\t\t\tRevision: \"\"");
sb.AppendLine("\t\t\tComment: \"\"");
sb.AppendLine("\t\t}");
sb.AppendLine("\t\tProperties70: {");
// Information on how this item was originally generated
string documentInfoPaths = Application.dataPath + newPath + ".fbx";
sb.AppendLine("\t\t\tP: \"DocumentUrl\", \"KString\", \"Url\", \"\", \"" + documentInfoPaths + "\"");
sb.AppendLine("\t\t\tP: \"SrcDocumentUrl\", \"KString\", \"Url\", \"\", \"" + documentInfoPaths + "\"");
sb.AppendLine("\t\t\tP: \"Original\", \"Compound\", \"\", \"\"");
sb.AppendLine("\t\t\tP: \"Original|ApplicationVendor\", \"KString\", \"\", \"\", \"\"");
sb.AppendLine("\t\t\tP: \"Original|ApplicationName\", \"KString\", \"\", \"\", \"\"");
sb.AppendLine("\t\t\tP: \"Original|ApplicationVersion\", \"KString\", \"\", \"\", \"\"");
sb.AppendLine("\t\t\tP: \"Original|DateTime_GMT\", \"DateTime\", \"\", \"\", \"\"");
sb.AppendLine("\t\t\tP: \"Original|FileName\", \"KString\", \"\", \"\", \"\"");
sb.AppendLine("\t\t\tP: \"LastSaved\", \"Compound\", \"\", \"\"");
sb.AppendLine("\t\t\tP: \"LastSaved|ApplicationVendor\", \"KString\", \"\", \"\", \"\"");
sb.AppendLine("\t\t\tP: \"LastSaved|ApplicationName\", \"KString\", \"\", \"\", \"\"");
sb.AppendLine("\t\t\tP: \"LastSaved|ApplicationVersion\", \"KString\", \"\", \"\", \"\"");
sb.AppendLine("\t\t\tP: \"LastSaved|DateTime_GMT\", \"DateTime\", \"\", \"\", \"\"");
sb.AppendLine("\t\t}");
sb.AppendLine("\t}");
sb.AppendLine("}");
// The Global information
sb.AppendLine("GlobalSettings: {");
sb.AppendLine("\tVersion: 1000");
sb.AppendLine("\tProperties70: {");
sb.AppendLine("\t\tP: \"UpAxis\", \"int\", \"Integer\", \"\",1");
sb.AppendLine("\t\tP: \"UpAxisSign\", \"int\", \"Integer\", \"\",1");
sb.AppendLine("\t\tP: \"FrontAxis\", \"int\", \"Integer\", \"\",2");
sb.AppendLine("\t\tP: \"FrontAxisSign\", \"int\", \"Integer\", \"\",1");
sb.AppendLine("\t\tP: \"CoordAxis\", \"int\", \"Integer\", \"\",0");
sb.AppendLine("\t\tP: \"CoordAxisSign\", \"int\", \"Integer\", \"\",1");
sb.AppendLine("\t\tP: \"OriginalUpAxis\", \"int\", \"Integer\", \"\",-1");
sb.AppendLine("\t\tP: \"OriginalUpAxisSign\", \"int\", \"Integer\", \"\",1");
sb.AppendLine("\t\tP: \"UnitScaleFactor\", \"double\", \"Number\", \"\",100"); // NOTE: This sets the resize scale upon import
sb.AppendLine("\t\tP: \"OriginalUnitScaleFactor\", \"double\", \"Number\", \"\",100");
sb.AppendLine("\t\tP: \"AmbientColor\", \"ColorRGB\", \"Color\", \"\",0,0,0");
sb.AppendLine("\t\tP: \"DefaultCamera\", \"KString\", \"\", \"\", \"Producer Perspective\"");
sb.AppendLine("\t\tP: \"TimeMode\", \"enum\", \"\", \"\",11");
sb.AppendLine("\t\tP: \"TimeSpanStart\", \"KTime\", \"Time\", \"\",0");
sb.AppendLine("\t\tP: \"TimeSpanStop\", \"KTime\", \"Time\", \"\",479181389250");
sb.AppendLine("\t\tP: \"CustomFrameRate\", \"double\", \"Number\", \"\",-1");
sb.AppendLine("\t}");
sb.AppendLine("}");
// The Object definations
sb.AppendLine("; Object definitions");
sb.AppendLine(";------------------------------------------------------------------");
sb.AppendLine("");
sb.AppendLine("Definitions: {");
sb.AppendLine("\tVersion: 100");
sb.AppendLine("\tCount: 4");
sb.AppendLine("\tObjectType: \"GlobalSettings\" {");
sb.AppendLine("\t\tCount: 1");
sb.AppendLine("\t}");
sb.AppendLine("\tObjectType: \"Model\" {");
sb.AppendLine("\t\tCount: 1"); // TODO figure out if this count matters
sb.AppendLine("\t\tPropertyTemplate: \"FbxNode\" {");
sb.AppendLine("\t\t\tProperties70: {");
sb.AppendLine("\t\t\t\tP: \"QuaternionInterpolate\", \"enum\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"RotationOffset\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"RotationPivot\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"ScalingOffset\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"ScalingPivot\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"TranslationActive\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"TranslationMin\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"TranslationMax\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"TranslationMinX\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"TranslationMinY\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"TranslationMinZ\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"TranslationMaxX\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"TranslationMaxY\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"TranslationMaxZ\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"RotationOrder\", \"enum\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"RotationSpaceForLimitOnly\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"RotationStiffnessX\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"RotationStiffnessY\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"RotationStiffnessZ\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"AxisLen\", \"double\", \"Number\", \"\",10");
sb.AppendLine("\t\t\t\tP: \"PreRotation\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"PostRotation\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"RotationActive\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"RotationMin\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"RotationMax\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"RotationMinX\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"RotationMinY\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"RotationMinZ\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"RotationMaxX\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"RotationMaxY\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"RotationMaxZ\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"InheritType\", \"enum\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"ScalingActive\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"ScalingMin\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"ScalingMax\", \"Vector3D\", \"Vector\", \"\",1,1,1");
sb.AppendLine("\t\t\t\tP: \"ScalingMinX\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"ScalingMinY\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"ScalingMinZ\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"ScalingMaxX\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"ScalingMaxY\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"ScalingMaxZ\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"GeometricTranslation\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"GeometricRotation\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"GeometricScaling\", \"Vector3D\", \"Vector\", \"\",1,1,1");
sb.AppendLine("\t\t\t\tP: \"MinDampRangeX\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"MinDampRangeY\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"MinDampRangeZ\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"MaxDampRangeX\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"MaxDampRangeY\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"MaxDampRangeZ\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"MinDampStrengthX\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"MinDampStrengthY\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"MinDampStrengthZ\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"MaxDampStrengthX\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"MaxDampStrengthY\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"MaxDampStrengthZ\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"PreferedAngleX\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"PreferedAngleY\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"PreferedAngleZ\", \"double\", \"Number\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"LookAtProperty\", \"object\", \"\", \"\"");
sb.AppendLine("\t\t\t\tP: \"UpVectorProperty\", \"object\", \"\", \"\"");
sb.AppendLine("\t\t\t\tP: \"Show\", \"bool\", \"\", \"\",1");
sb.AppendLine("\t\t\t\tP: \"NegativePercentShapeSupport\", \"bool\", \"\", \"\",1");
sb.AppendLine("\t\t\t\tP: \"DefaultAttributeIndex\", \"int\", \"Integer\", \"\",-1");
sb.AppendLine("\t\t\t\tP: \"Freeze\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"LODBox\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"Lcl Translation\", \"Lcl Translation\", \"\", \"A\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"Lcl Rotation\", \"Lcl Rotation\", \"\", \"A\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"Lcl Scaling\", \"Lcl Scaling\", \"\", \"A\",1,1,1");
sb.AppendLine("\t\t\t\tP: \"Visibility\", \"Visibility\", \"\", \"A\",1");
sb.AppendLine("\t\t\t\tP: \"Visibility Inheritance\", \"Visibility Inheritance\", \"\", \"\",1");
sb.AppendLine("\t\t\t}");
sb.AppendLine("\t\t}");
sb.AppendLine("\t}");
// The geometry, this is IMPORTANT
sb.AppendLine("\tObjectType: \"Geometry\" {");
sb.AppendLine("\t\tCount: 1"); // TODO - this must be set by the number of items being placed.
sb.AppendLine("\t\tPropertyTemplate: \"FbxMesh\" {");
sb.AppendLine("\t\t\tProperties70: {");
sb.AppendLine("\t\t\t\tP: \"Color\", \"ColorRGB\", \"Color\", \"\",0.8,0.8,0.8");
sb.AppendLine("\t\t\t\tP: \"BBoxMin\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"BBoxMax\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"Primary Visibility\", \"bool\", \"\", \"\",1");
sb.AppendLine("\t\t\t\tP: \"Casts Shadows\", \"bool\", \"\", \"\",1");
sb.AppendLine("\t\t\t\tP: \"Receive Shadows\", \"bool\", \"\", \"\",1");
sb.AppendLine("\t\t\t}");
sb.AppendLine("\t\t}");
sb.AppendLine("\t}");
// The materials that are being placed. Has to be simple I think
sb.AppendLine("\tObjectType: \"Material\" {");
sb.AppendLine("\t\tCount: 1");
sb.AppendLine("\t\tPropertyTemplate: \"FbxSurfacePhong\" {");
sb.AppendLine("\t\t\tProperties70: {");
sb.AppendLine("\t\t\t\tP: \"ShadingModel\", \"KString\", \"\", \"\", \"Phong\"");
sb.AppendLine("\t\t\t\tP: \"MultiLayer\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"EmissiveColor\", \"Color\", \"\", \"A\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"EmissiveFactor\", \"Number\", \"\", \"A\",1");
sb.AppendLine("\t\t\t\tP: \"AmbientColor\", \"Color\", \"\", \"A\",0.2,0.2,0.2");
sb.AppendLine("\t\t\t\tP: \"AmbientFactor\", \"Number\", \"\", \"A\",1");
sb.AppendLine("\t\t\t\tP: \"DiffuseColor\", \"Color\", \"\", \"A\",0.8,0.8,0.8");
sb.AppendLine("\t\t\t\tP: \"DiffuseFactor\", \"Number\", \"\", \"A\",1");
sb.AppendLine("\t\t\t\tP: \"Bump\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"NormalMap\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"BumpFactor\", \"double\", \"Number\", \"\",1");
sb.AppendLine("\t\t\t\tP: \"TransparentColor\", \"Color\", \"\", \"A\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"TransparencyFactor\", \"Number\", \"\", \"A\",0");
sb.AppendLine("\t\t\t\tP: \"DisplacementColor\", \"ColorRGB\", \"Color\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"DisplacementFactor\", \"double\", \"Number\", \"\",1");
sb.AppendLine("\t\t\t\tP: \"VectorDisplacementColor\", \"ColorRGB\", \"Color\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"VectorDisplacementFactor\", \"double\", \"Number\", \"\",1");
sb.AppendLine("\t\t\t\tP: \"SpecularColor\", \"Color\", \"\", \"A\",0.2,0.2,0.2");
sb.AppendLine("\t\t\t\tP: \"SpecularFactor\", \"Number\", \"\", \"A\",1");
sb.AppendLine("\t\t\t\tP: \"ShininessExponent\", \"Number\", \"\", \"A\",20");
sb.AppendLine("\t\t\t\tP: \"ReflectionColor\", \"Color\", \"\", \"A\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"ReflectionFactor\", \"Number\", \"\", \"A\",1");
sb.AppendLine("\t\t\t}");
sb.AppendLine("\t\t}");
sb.AppendLine("\t}");
// Explanation of how textures work
sb.AppendLine("\tObjectType: \"Texture\" {");
sb.AppendLine("\t\tCount: 2"); // TODO - figure out if this texture number is important
sb.AppendLine("\t\tPropertyTemplate: \"FbxFileTexture\" {");
sb.AppendLine("\t\t\tProperties70: {");
sb.AppendLine("\t\t\t\tP: \"TextureTypeUse\", \"enum\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"Texture alpha\", \"Number\", \"\", \"A\",1");
sb.AppendLine("\t\t\t\tP: \"CurrentMappingType\", \"enum\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"WrapModeU\", \"enum\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"WrapModeV\", \"enum\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"UVSwap\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"PremultiplyAlpha\", \"bool\", \"\", \"\",1");
sb.AppendLine("\t\t\t\tP: \"Translation\", \"Vector\", \"\", \"A\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"Rotation\", \"Vector\", \"\", \"A\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"Scaling\", \"Vector\", \"\", \"A\",1,1,1");
sb.AppendLine("\t\t\t\tP: \"TextureRotationPivot\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"TextureScalingPivot\", \"Vector3D\", \"Vector\", \"\",0,0,0");
sb.AppendLine("\t\t\t\tP: \"CurrentTextureBlendMode\", \"enum\", \"\", \"\",1");
sb.AppendLine("\t\t\t\tP: \"UVSet\", \"KString\", \"\", \"\", \"default\"");
sb.AppendLine("\t\t\t\tP: \"UseMaterial\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t\tP: \"UseMipMap\", \"bool\", \"\", \"\",0");
sb.AppendLine("\t\t\t}");
sb.AppendLine("\t\t}");
sb.AppendLine("\t}");
sb.AppendLine("}");
sb.AppendLine("");
sb.Append(objectProps.ToString());
sb.Append(objectConnections.ToString());
return sb.ToString();
}
public static void CopyComplexMaterialsToPath(GameObject gameObj, string path, bool copyTextures, string texturesFolder = "/Textures", string materialsFolder = "/Materials")
{
#if UNITY_EDITOR
int folderIndex = path.LastIndexOf('/');
path = path.Remove(folderIndex, path.Length - folderIndex);
// 1. First create the directories that are needed
string texturesPath = path + texturesFolder;
string materialsPath = path + materialsFolder;
if(Directory.Exists(path) == false)
Directory.CreateDirectory(path);
if(Directory.Exists(materialsPath) == false)
Directory.CreateDirectory(materialsPath);
// 2. Copy every distinct Material into the Materials folder
//@cartzhang modify.As meshrender and skinnedrender is same level in inherit relation shape.
// if not check,skinned render ,may lost some materials.
Renderer[] meshRenderers = gameObj.GetComponentsInChildren<Renderer>();
List<Material> everyMaterial = new List<Material>();
for(int i = 0; i < meshRenderers.Length; i++)
{
for(int n = 0; n < meshRenderers[i].sharedMaterials.Length; n++)
{
everyMaterial.Add(meshRenderers[i].sharedMaterials[n]);
}
//Debug.Log(meshRenderers[i].gameObject.name);
}
Dictionary<string, Material> materialMapping = new Dictionary<string, Material>();
foreach (Material material in everyMaterial) {
if (materialMapping.ContainsKey(material.name)) {
continue;
} else {
materialMapping.Add(material.name, material);
}
}
Material[] everyDistinctMaterial = materialMapping.Values.ToArray<Material>();
everyDistinctMaterial = everyDistinctMaterial.OrderBy(o => o.name).ToArray<Material>();
List<string> everyMaterialName = new List<string>();
// Structure of materials naming, is used when packaging up the package
// PARENTNAME_ORIGINALMATNAME.mat
for(int i = 0; i < everyDistinctMaterial.Length; i++)
{
string newName = gameObj.name + "_" + everyDistinctMaterial[i].name;
string fullPath = materialsPath + "/" + newName + ".mat";
if(File.Exists(fullPath))
File.Delete(fullPath);
if(CopyAndRenameAsset(everyDistinctMaterial[i], newName, materialsPath))
everyMaterialName.Add(newName);
}
// 3. Go through newly moved materials and copy every texture and update the material
AssetDatabase.Refresh();
List<Material> allNewMaterials = new List<Material>();
for (int i = 0; i < everyMaterialName.Count; i++)
{
string assetPath = materialsPath;
if(assetPath[assetPath.Length - 1] != '/')
assetPath += "/";
assetPath += everyMaterialName[i] + ".mat";
Material sourceMat = (Material)AssetDatabase.LoadAssetAtPath(assetPath, typeof(Material));
if(sourceMat != null)
allNewMaterials.Add(sourceMat);
}
// Get all the textures from the mesh renderer
if(copyTextures)
{
if(Directory.Exists(texturesPath) == false)
Directory.CreateDirectory(texturesPath);
AssetDatabase.Refresh();
for(int i = 0; i < allNewMaterials.Count; i++)
{
allNewMaterials[i] = CopyTexturesAndAssignCopiesToMaterial(allNewMaterials[i], texturesPath);
}
}
AssetDatabase.Refresh();
#endif
}
public static bool CopyAndRenameAsset(Object obj, string newName, string newFolderPath)
{
#if UNITY_EDITOR
string path = newFolderPath;
if(path[path.Length - 1] != '/')
path += "/";
string assetPath = AssetDatabase.GetAssetPath(obj);
string extension = Path.GetExtension(assetPath);
string newFileName = path + newName + extension;
if(File.Exists(newFileName))
return false;
return AssetDatabase.CopyAsset(assetPath, newFileName);
#else
return false;
#endif
}
/// <summary>
/// Strips the full path of a file
/// </summary>
/// <returns>The file name.</returns>
/// <param name="path">Path.</param>
private static string GetFileName(string path)
{
string fileName = path.ToString();
fileName = fileName.Remove(0, fileName.LastIndexOf('/') + 1);
return fileName;
}
private static Material CopyTexturesAndAssignCopiesToMaterial(Material material, string newPath)
{
if(material.shader.name == "Standard" || material.shader.name == "Standard (Specular setup)")
{
GetTextureUpdateMaterialWithPath(material, "_MainTex", newPath);
if(material.shader.name == "Standard")
GetTextureUpdateMaterialWithPath(material, "_MetallicGlossMap", newPath);
if(material.shader.name == "Standard (Specular setup)")
GetTextureUpdateMaterialWithPath(material, "_SpecGlossMap", newPath);
GetTextureUpdateMaterialWithPath(material, "_BumpMap", newPath);
GetTextureUpdateMaterialWithPath(material, "_BumpMap", newPath);
GetTextureUpdateMaterialWithPath(material, "_BumpMap", newPath);
GetTextureUpdateMaterialWithPath(material, "_BumpMap", newPath);
GetTextureUpdateMaterialWithPath(material, "_ParallaxMap", newPath);
GetTextureUpdateMaterialWithPath(material, "_OcclusionMap", newPath);
GetTextureUpdateMaterialWithPath(material, "_EmissionMap", newPath);
GetTextureUpdateMaterialWithPath(material, "_DetailMask", newPath);
GetTextureUpdateMaterialWithPath(material, "_DetailAlbedoMap", newPath);
GetTextureUpdateMaterialWithPath(material, "_DetailNormalMap", newPath);
}
else
Debug.LogError("WARNING: " + material.name + " is not a physically based shader, may not export to package correctly");
return material;
}
/// <summary>
/// Copies and renames the texture and assigns it to the material provided.
/// NAME FORMAT: Material.name + textureShaderName
/// </summary>
/// <param name="material">Material.</param>
/// <param name="textureShaderName">Texture shader name.</param>
/// <param name="newPath">New path.</param>
private static void GetTextureUpdateMaterialWithPath(Material material, string textureShaderName, string newPath)
{
Texture textureInQ = material.GetTexture(textureShaderName);
if(textureInQ != null)
{
string name = material.name + textureShaderName;
Texture newTexture = (Texture)CopyAndRenameAssetReturnObject(textureInQ, name, newPath);
if(newTexture != null)
material.SetTexture(textureShaderName, newTexture);
}
}
public static Object CopyAndRenameAssetReturnObject(Object obj, string newName, string newFolderPath)
{
#if UNITY_EDITOR
string path = newFolderPath;
if(path[path.Length - 1] != '/')
path += "/";
string testPath = path.Remove(path.Length - 1);
if(System.IO.Directory.Exists(testPath) == false)
{
Debug.LogError("This folder does not exist " + testPath);
return null;
}
string assetPath = AssetDatabase.GetAssetPath(obj);
string fileName = GetFileName(assetPath);
string extension = fileName.Remove(0, fileName.LastIndexOf('.'));
string newFullPathName = path + newName + extension;
if(AssetDatabase.CopyAsset(assetPath, newFullPathName) == false)
return null;
AssetDatabase.Refresh();
return AssetDatabase.LoadAssetAtPath(newFullPathName, typeof(Texture));
#else
return null;
#endif
}
}
}
| 611 |
orrb | openai | C# | // ===============================================================================================
// The MIT License (MIT) for UnityFBXExporter
//
// UnityFBXExporter was created for Building Crafter (http://u3d.as/ovC) a tool to rapidly
// create high quality buildings right in Unity with no need to use 3D modeling programs.
//
// Copyright (c) 2016 | 8Bit Goose Games, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// ===============================================================================================
using UnityEngine;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityFBXExporter
{
public class FBXUnityMaterialGetter
{
/// <summary>
/// Finds all materials in a gameobject and writes them to a string that can be read by the FBX writer
/// </summary>
/// <param name="gameObj">Parent GameObject being exported.</param>
/// <param name="newPath">The path to export to.</param>
/// <param name="materials">Materials which were written to this fbx file.</param>
/// <param name="matObjects">The material objects to write to the file.</param>
/// <param name="connections">The connections to write to the file.</param>
public static void GetAllMaterialsToString(GameObject gameObj, string newPath, bool copyMaterials, bool copyTextures, out Material[] materials, out string matObjects, out string connections)
{
StringBuilder tempObjectSb = new StringBuilder();
StringBuilder tempConnectionsSb = new StringBuilder();
// Need to get all unique materials for the submesh here and then write them in
//@cartzhang modify.As meshrender and skinnedrender is same level in inherit relation shape.
// if not check,skinned render ,may lost some materials.
Renderer[] meshRenders = gameObj.GetComponentsInChildren<Renderer>();
List<Material> uniqueMaterials = new List<Material>();
// Gets all the unique materials within this GameObject Hierarchy
for(int i = 0; i < meshRenders.Length; i++)
{
for(int n = 0; n < meshRenders[i].sharedMaterials.Length; n++)
{
Material mat = meshRenders[i].sharedMaterials[n];
if(uniqueMaterials.Contains(mat) == false && mat != null)
{
uniqueMaterials.Add(mat);
}
}
}
for (int i = 0; i < uniqueMaterials.Count; i++)
{
Material mat = uniqueMaterials[i];
// We rename the material if it is being copied
string materialName = mat.name;
if(copyMaterials)
materialName = gameObj.name + "_" + mat.name;
int referenceId = Mathf.Abs(mat.GetInstanceID());
tempObjectSb.AppendLine();
tempObjectSb.AppendLine("\tMaterial: " + referenceId + ", \"Material::" + materialName + "\", \"\" {");
tempObjectSb.AppendLine("\t\tVersion: 102");
tempObjectSb.AppendLine("\t\tShadingModel: \"phong\"");
tempObjectSb.AppendLine("\t\tMultiLayer: 0");
tempObjectSb.AppendLine("\t\tProperties70: {");
tempObjectSb.AppendFormat("\t\t\tP: \"Diffuse\", \"Vector3D\", \"Vector\", \"\",{0},{1},{2}", mat.color.r, mat.color.g, mat.color.b);
tempObjectSb.AppendLine();
tempObjectSb.AppendFormat("\t\t\tP: \"DiffuseColor\", \"Color\", \"\", \"A\",{0},{1},{2}", mat.color.r, mat.color.g, mat.color.b);
tempObjectSb.AppendLine();
// TODO: Figure out if this property can be written to the FBX file
// if(mat.HasProperty("_MetallicGlossMap"))
// {
// Debug.Log("has metallic gloss map");
// Color color = mat.GetColor("_Color");
// tempObjectSb.AppendFormat("\t\t\tP: \"Specular\", \"Vector3D\", \"Vector\", \"\",{0},{1},{2}", color.r, color.g, color.r);
// tempObjectSb.AppendLine();
// tempObjectSb.AppendFormat("\t\t\tP: \"SpecularColor\", \"ColorRGB\", \"Color\", \" \",{0},{1},{2}", color.r, color.g, color.b);
// tempObjectSb.AppendLine();
// }
if(mat.HasProperty("_SpecColor"))
{
Color color = mat.GetColor("_SpecColor");
tempObjectSb.AppendFormat("\t\t\tP: \"Specular\", \"Vector3D\", \"Vector\", \"\",{0},{1},{2}", color.r, color.g, color.r);
tempObjectSb.AppendLine();
tempObjectSb.AppendFormat("\t\t\tP: \"SpecularColor\", \"ColorRGB\", \"Color\", \" \",{0},{1},{2}", color.r, color.g, color.b);
tempObjectSb.AppendLine();
}
if(mat.HasProperty("_Mode"))
{
Color color = Color.white;
switch((int)mat.GetFloat("_Mode"))
{
case 0: // Map is opaque
break;
case 1: // Map is a cutout
// TODO: Add option if it is a cutout
break;
case 2: // Map is a fade
color = mat.GetColor("_Color");
tempObjectSb.AppendFormat("\t\t\tP: \"TransparentColor\", \"Color\", \"\", \"A\",{0},{1},{2}", color.r, color.g, color.b);
tempObjectSb.AppendLine();
tempObjectSb.AppendFormat("\t\t\tP: \"Opacity\", \"double\", \"Number\", \"\",{0}", color.a);
tempObjectSb.AppendLine();
break;
case 3: // Map is transparent
color = mat.GetColor("_Color");
tempObjectSb.AppendFormat("\t\t\tP: \"TransparentColor\", \"Color\", \"\", \"A\",{0},{1},{2}", color.r, color.g, color.b);
tempObjectSb.AppendLine();
tempObjectSb.AppendFormat("\t\t\tP: \"Opacity\", \"double\", \"Number\", \"\",{0}", color.a);
tempObjectSb.AppendLine();
break;
}
}
// NOTE: Unity doesn't currently import this information (I think) from an FBX file.
if(mat.HasProperty("_EmissionColor"))
{
Color color = mat.GetColor("_EmissionColor");
tempObjectSb.AppendFormat("\t\t\tP: \"Emissive\", \"Vector3D\", \"Vector\", \"\",{0},{1},{2}", color.r, color.g, color.b);
tempObjectSb.AppendLine();
float averageColor = (color.r + color.g + color.b) / 3f;
tempObjectSb.AppendFormat("\t\t\tP: \"EmissiveFactor\", \"Number\", \"\", \"A\",{0}", averageColor);
tempObjectSb.AppendLine();
}
// TODO: Add these to the file based on their relation to the PBR files
// tempObjectSb.AppendLine("\t\t\tP: \"AmbientColor\", \"Color\", \"\", \"A\",0,0,0");
// tempObjectSb.AppendLine("\t\t\tP: \"ShininessExponent\", \"Number\", \"\", \"A\",6.31179285049438");
// tempObjectSb.AppendLine("\t\t\tP: \"Ambient\", \"Vector3D\", \"Vector\", \"\",0,0,0");
// tempObjectSb.AppendLine("\t\t\tP: \"Shininess\", \"double\", \"Number\", \"\",6.31179285049438");
// tempObjectSb.AppendLine("\t\t\tP: \"Reflectivity\", \"double\", \"Number\", \"\",0");
tempObjectSb.AppendLine("\t\t}");
tempObjectSb.AppendLine("\t}");
string textureObjects;
string textureConnections;
SerializedTextures(gameObj, newPath, mat, materialName, copyTextures, out textureObjects, out textureConnections);
tempObjectSb.Append(textureObjects);
tempConnectionsSb.Append(textureConnections);
}
materials = uniqueMaterials.ToArray<Material>();
matObjects = tempObjectSb.ToString();
connections = tempConnectionsSb.ToString();
}
/// <summary>
/// Serializes textures to FBX format.
/// </summary>
/// <param name="gameObj">Parent GameObject being exported.</param>
/// <param name="newPath">The path to export to.</param>
/// <param name="materials">Materials that holds all the textures.</param>
/// <param name="matObjects">The string with the newly serialized texture file.</param>
/// <param name="connections">The string to connect this to the material.</param>
private static void SerializedTextures(GameObject gameObj, string newPath, Material material, string materialName, bool copyTextures, out string objects, out string connections)
{
// TODO: FBX import currently only supports Diffuse Color and Normal Map
// Because it is undocumented, there is no way to easily find out what other textures
// can be attached to an FBX file so it is imported into the PBR shaders at the same time.
// Also NOTE, Unity 5.1.2 will import FBX files with legacy shaders. This is fix done
// in at least 5.3.4.
StringBuilder objectsSb = new StringBuilder();
StringBuilder connectionsSb = new StringBuilder();
int materialId = Mathf.Abs(material.GetInstanceID());
Texture mainTexture = material.GetTexture("_MainTex");
string newObjects = null;
string newConnections = null;
// Serializeds the Main Texture, one of two textures that can be stored in FBX's sysytem
if(mainTexture != null)
{
SerializeOneTexture(gameObj, newPath, material, materialName, materialId, copyTextures, "_MainTex", "DiffuseColor", out newObjects, out newConnections);
objectsSb.AppendLine(newObjects);
connectionsSb.AppendLine(newConnections);
}
if(SerializeOneTexture(gameObj, newPath, material, materialName, materialId, copyTextures, "_BumpMap", "NormalMap", out newObjects, out newConnections))
{
objectsSb.AppendLine(newObjects);
connectionsSb.AppendLine(newConnections);
}
connections = connectionsSb.ToString();
objects = objectsSb.ToString();
}
private static bool SerializeOneTexture(GameObject gameObj,
string newPath,
Material material,
string materialName,
int materialId,
bool copyTextures,
string unityExtension,
string textureType,
out string objects,
out string connections)
{
StringBuilder objectsSb = new StringBuilder();
StringBuilder connectionsSb = new StringBuilder();
Texture texture = material.GetTexture(unityExtension);
if(texture == null)
{
objects = "";
connections = "";
return false;
}
string originalAssetPath = "";
#if UNITY_EDITOR
originalAssetPath = AssetDatabase.GetAssetPath(texture);
#else
Debug.LogError("Unity FBX Exporter can not serialize textures at runtime (yet). Look in FBXUnityMaterialGetter around line 250ish. Fix it and contribute to the project!");
objects = "";
connections = "";
return false;
#endif
string fullDataFolderPath = Application.dataPath;
string textureFilePathFullName = originalAssetPath;
string textureName = Path.GetFileNameWithoutExtension(originalAssetPath);
string textureExtension = Path.GetExtension(originalAssetPath);
// If we are copying the textures over, we update the relative positions
if(copyTextures)
{
int indexOfAssetsFolder = fullDataFolderPath.LastIndexOf("/Assets");
fullDataFolderPath = fullDataFolderPath.Remove(indexOfAssetsFolder, fullDataFolderPath.Length - indexOfAssetsFolder);
string newPathFolder = newPath.Remove(newPath.LastIndexOf('/') + 1, newPath.Length - newPath.LastIndexOf('/') - 1);
textureName = gameObj.name + "_" + material.name + unityExtension;
textureFilePathFullName = fullDataFolderPath + "/" + newPathFolder + textureName + textureExtension;
}
long textureReference = FBXExporter.GetRandomFBXId();
// TODO - test out different reference names to get one that doesn't load a _MainTex when importing.
objectsSb.AppendLine("\tTexture: " + textureReference + ", \"Texture::" + materialName + "\", \"\" {");
objectsSb.AppendLine("\t\tType: \"TextureVideoClip\"");
objectsSb.AppendLine("\t\tVersion: 202");
objectsSb.AppendLine("\t\tTextureName: \"Texture::" + materialName + "\"");
objectsSb.AppendLine("\t\tProperties70: {");
objectsSb.AppendLine("\t\t\tP: \"CurrentTextureBlendMode\", \"enum\", \"\", \"\",0");
objectsSb.AppendLine("\t\t\tP: \"UVSet\", \"KString\", \"\", \"\", \"map1\"");
objectsSb.AppendLine("\t\t\tP: \"UseMaterial\", \"bool\", \"\", \"\",1");
objectsSb.AppendLine("\t\t}");
objectsSb.AppendLine("\t\tMedia: \"Video::" + materialName + "\"");
// Sets the absolute path for the copied texture
objectsSb.Append("\t\tFileName: \"");
objectsSb.Append(textureFilePathFullName);
objectsSb.AppendLine("\"");
// Sets the relative path for the copied texture
// TODO: If we don't copy the textures to a relative path, we must find a relative path to write down here
if(copyTextures)
objectsSb.AppendLine("\t\tRelativeFilename: \"/Textures/" + textureName + textureExtension + "\"");
objectsSb.AppendLine("\t\tModelUVTranslation: 0,0"); // TODO: Figure out how to get the UV translation into here
objectsSb.AppendLine("\t\tModelUVScaling: 1,1"); // TODO: Figure out how to get the UV scaling into here
objectsSb.AppendLine("\t\tTexture_Alpha_Source: \"None\""); // TODO: Add alpha source here if the file is a cutout.
objectsSb.AppendLine("\t\tCropping: 0,0,0,0");
objectsSb.AppendLine("\t}");
connectionsSb.AppendLine("\t;Texture::" + textureName + ", Material::" + materialName + "\"");
connectionsSb.AppendLine("\tC: \"OP\"," + textureReference + "," + materialId + ", \"" + textureType + "\"");
connectionsSb.AppendLine();
objects = objectsSb.ToString();
connections = connectionsSb.ToString();
return true;
}
}
} | 326 |
orrb | openai | C# | // ===============================================================================================
// The MIT License (MIT) for UnityFBXExporter
//
// UnityFBXExporter was created for Building Crafter (http://u3d.as/ovC) a tool to rapidly
// create high quality buildings right in Unity with no need to use 3D modeling programs.
//
// Copyright (c) 2016 | 8Bit Goose Games, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// ===============================================================================================
using UnityEngine;
using System.Collections;
using System.Text;
using System.Collections.Generic;
namespace UnityFBXExporter
{
public class FBXUnityMeshGetter
{
/// <summary>
/// Gets all the meshes and outputs to a string (even grabbing the child of each gameObject)
/// </summary>
/// <returns>The mesh to string.</returns>
/// <param name="gameObj">GameObject Parent.</param>
/// <param name="materials">Every Material in the parent that can be accessed.</param>
/// <param name="objects">The StringBuidler to create objects for the FBX file.</param>
/// <param name="connections">The StringBuidler to create connections for the FBX file.</param>
/// <param name="parentObject">Parent object, if left null this is the top parent.</param>
/// <param name="parentModelId">Parent model id, 0 if top parent.</param>
public static long GetMeshToString(GameObject gameObj,
Material[] materials,
ref StringBuilder objects,
ref StringBuilder connections,
GameObject parentObject = null,
long parentModelId = 0)
{
StringBuilder tempObjectSb = new StringBuilder();
StringBuilder tempConnectionsSb = new StringBuilder();
long geometryId = FBXExporter.GetRandomFBXId();
long modelId = FBXExporter.GetRandomFBXId();
//@cartzhang if SkinnedMeshRender gameobject,but has no meshfilter,add one.
SkinnedMeshRenderer[] meshfilterRender = gameObj.GetComponentsInChildren<SkinnedMeshRenderer>();
for (int i = 0; i < meshfilterRender.Length; i++)
{
if (meshfilterRender[i].GetComponent<MeshFilter>() == null)
{
meshfilterRender[i].gameObject.AddComponent<MeshFilter>();
meshfilterRender[i].GetComponent<MeshFilter>().sharedMesh = GameObject.Instantiate(meshfilterRender[i].sharedMesh);
}
}
// Sees if there is a mesh to export and add to the system
MeshFilter filter = gameObj.GetComponent<MeshFilter>();
string meshName = gameObj.name;
// A NULL parent means that the gameObject is at the top
string isMesh = "Null";
if(filter != null)
{
meshName = filter.sharedMesh.name;
isMesh = "Mesh";
}
if(parentModelId == 0)
tempConnectionsSb.AppendLine("\t;Model::" + meshName + ", Model::RootNode");
else
tempConnectionsSb.AppendLine("\t;Model::" + meshName + ", Model::USING PARENT");
tempConnectionsSb.AppendLine("\tC: \"OO\"," + modelId + "," + parentModelId);
tempConnectionsSb.AppendLine();
tempObjectSb.AppendLine("\tModel: " + modelId + ", \"Model::" + gameObj.name + "\", \"" + isMesh + "\" {");
tempObjectSb.AppendLine("\t\tVersion: 232");
tempObjectSb.AppendLine("\t\tProperties70: {");
tempObjectSb.AppendLine("\t\t\tP: \"RotationOrder\", \"enum\", \"\", \"\",4");
tempObjectSb.AppendLine("\t\t\tP: \"RotationActive\", \"bool\", \"\", \"\",1");
tempObjectSb.AppendLine("\t\t\tP: \"InheritType\", \"enum\", \"\", \"\",1");
tempObjectSb.AppendLine("\t\t\tP: \"ScalingMax\", \"Vector3D\", \"Vector\", \"\",0,0,0");
tempObjectSb.AppendLine("\t\t\tP: \"DefaultAttributeIndex\", \"int\", \"Integer\", \"\",0");
// ===== Local Translation Offset =========
Vector3 position = gameObj.transform.localPosition;
tempObjectSb.Append("\t\t\tP: \"Lcl Translation\", \"Lcl Translation\", \"\", \"A+\",");
// Append the X Y Z coords to the system
tempObjectSb.AppendFormat("{0},{1},{2}", position.x * - 1, position.y, position.z);
tempObjectSb.AppendLine();
// Rotates the object correctly from Unity space
Vector3 localRotation = gameObj.transform.localEulerAngles;
tempObjectSb.AppendFormat("\t\t\tP: \"Lcl Rotation\", \"Lcl Rotation\", \"\", \"A+\",{0},{1},{2}", localRotation.x, localRotation.y * -1, -1 * localRotation.z);
tempObjectSb.AppendLine();
// Adds the local scale of this object
Vector3 localScale = gameObj.transform.localScale;
tempObjectSb.AppendFormat("\t\t\tP: \"Lcl Scaling\", \"Lcl Scaling\", \"\", \"A\",{0},{1},{2}", localScale.x, localScale.y, localScale.z);
tempObjectSb.AppendLine();
tempObjectSb.AppendLine("\t\t\tP: \"currentUVSet\", \"KString\", \"\", \"U\", \"map1\"");
tempObjectSb.AppendLine("\t\t}");
tempObjectSb.AppendLine("\t\tShading: T");
tempObjectSb.AppendLine("\t\tCulling: \"CullingOff\"");
tempObjectSb.AppendLine("\t}");
// Adds in geometry if it exists, if it it does not exist, this is a empty gameObject file and skips over this
if(filter != null)
{
Mesh mesh = filter.sharedMesh;
// =================================
// General Geometry Info
// =================================
// Generate the geometry information for the mesh created
tempObjectSb.AppendLine("\tGeometry: " + geometryId + ", \"Geometry::\", \"Mesh\" {");
// ===== WRITE THE VERTICIES =====
Vector3[] verticies = mesh.vertices;
int vertCount = mesh.vertexCount * 3; // <= because the list of points is just a list of comma seperated values, we need to multiply by three
tempObjectSb.AppendLine("\t\tVertices: *" + vertCount + " {");
tempObjectSb.Append("\t\t\ta: ");
for(int i = 0; i < verticies.Length; i++)
{
if(i > 0)
tempObjectSb.Append(",");
// Points in the verticies. We also reverse the x value because Unity has a reverse X coordinate
tempObjectSb.AppendFormat("{0},{1},{2}", verticies[i].x * - 1, verticies[i].y, verticies[i].z);
}
tempObjectSb.AppendLine();
tempObjectSb.AppendLine("\t\t} ");
// ======= WRITE THE TRIANGLES ========
int triangleCount = mesh.triangles.Length;
int[] triangles = mesh.triangles;
tempObjectSb.AppendLine("\t\tPolygonVertexIndex: *" + triangleCount + " {");
// Write triangle indexes
tempObjectSb.Append("\t\t\ta: ");
for(int i = 0; i < triangleCount; i += 3)
{
if(i > 0)
tempObjectSb.Append(",");
// To get the correct normals, must rewind the triangles since we flipped the x direction
tempObjectSb.AppendFormat("{0},{1},{2}",
triangles[i],
triangles[i + 2],
(triangles[i + 1] * -1) - 1); // <= Tells the poly is ended
}
tempObjectSb.AppendLine();
tempObjectSb.AppendLine("\t\t} ");
tempObjectSb.AppendLine("\t\tGeometryVersion: 124");
tempObjectSb.AppendLine("\t\tLayerElementNormal: 0 {");
tempObjectSb.AppendLine("\t\t\tVersion: 101");
tempObjectSb.AppendLine("\t\t\tName: \"\"");
tempObjectSb.AppendLine("\t\t\tMappingInformationType: \"ByPolygonVertex\"");
tempObjectSb.AppendLine("\t\t\tReferenceInformationType: \"Direct\"");
// ===== WRITE THE NORMALS ==========
Vector3[] normals = mesh.normals;
tempObjectSb.AppendLine("\t\t\tNormals: *" + (triangleCount * 3) + " {");
tempObjectSb.Append("\t\t\t\ta: ");
for(int i = 0; i < triangleCount; i += 3)
{
if(i > 0)
tempObjectSb.Append(",");
// To get the correct normals, must rewind the normal triangles like the triangles above since x was flipped
Vector3 newNormal = normals[triangles[i]];
tempObjectSb.AppendFormat("{0},{1},{2},",
newNormal.x * -1, // Switch normal as is tradition
newNormal.y,
newNormal.z);
newNormal = normals[triangles[i + 2]];
tempObjectSb.AppendFormat("{0},{1},{2},",
newNormal.x * -1, // Switch normal as is tradition
newNormal.y,
newNormal.z);
newNormal = normals[triangles[i + 1]];
tempObjectSb.AppendFormat("{0},{1},{2}",
newNormal.x * -1, // Switch normal as is tradition
newNormal.y,
newNormal.z);
}
tempObjectSb.AppendLine();
tempObjectSb.AppendLine("\t\t\t}");
tempObjectSb.AppendLine("\t\t}");
// ===== WRITE THE COLORS =====
bool containsColors = mesh.colors.Length == verticies.Length;
if(containsColors)
{
Color[] colors = mesh.colors;
Dictionary<Color, int> colorTable = new Dictionary<Color, int>(); // reducing amount of data by only keeping unique colors.
int idx = 0;
// build index table of all the different colors present in the mesh
for (int i = 0; i < colors.Length; i++)
{
if (!colorTable.ContainsKey(colors[i]))
{
colorTable[colors[i]] = idx;
idx++;
}
}
tempObjectSb.AppendLine("\t\tLayerElementColor: 0 {");
tempObjectSb.AppendLine("\t\t\tVersion: 101");
tempObjectSb.AppendLine("\t\t\tName: \"Col\"");
tempObjectSb.AppendLine("\t\t\tMappingInformationType: \"ByPolygonVertex\"");
tempObjectSb.AppendLine("\t\t\tReferenceInformationType: \"IndexToDirect\"");
tempObjectSb.AppendLine("\t\t\tColors: *" + colorTable.Count * 4 + " {");
tempObjectSb.Append("\t\t\t\ta: ");
bool first = true;
foreach (KeyValuePair<Color, int> color in colorTable)
{
if (!first)
tempObjectSb.Append(",");
tempObjectSb.AppendFormat("{0},{1},{2},{3}", color.Key.r, color.Key.g, color.Key.b, color.Key.a);
first = false;
}
tempObjectSb.AppendLine();
tempObjectSb.AppendLine("\t\t\t\t}");
// Color index
tempObjectSb.AppendLine("\t\t\tColorIndex: *" + triangles.Length + " {");
tempObjectSb.Append("\t\t\t\ta: ");
for (int i = 0; i < triangles.Length; i += 3)
{
if (i > 0)
tempObjectSb.Append(",");
// Triangles need to be fliped for the x flip
int index1 = triangles[i];
int index2 = triangles[i + 2];
int index3 = triangles[i + 1];
// Find the color index related to that vertice index
index1 = colorTable[colors[index1]];
index2 = colorTable[colors[index2]];
index3 = colorTable[colors[index3]];
tempObjectSb.AppendFormat("{0},{1},{2}", index1, index2, index3);
}
tempObjectSb.AppendLine();
tempObjectSb.AppendLine("\t\t\t}");
tempObjectSb.AppendLine("\t\t}");
}
else
Debug.LogWarning("Mesh contains " + mesh.vertices.Length + " vertices for " + mesh.colors.Length + " colors. Skip color export");
// ================ UV CREATION =========================
// -- UV 1 Creation
int uvLength = mesh.uv.Length;
Vector2[] uvs = mesh.uv;
tempObjectSb.AppendLine("\t\tLayerElementUV: 0 {"); // the Zero here is for the first UV map
tempObjectSb.AppendLine("\t\t\tVersion: 101");
tempObjectSb.AppendLine("\t\t\tName: \"map1\"");
tempObjectSb.AppendLine("\t\t\tMappingInformationType: \"ByPolygonVertex\"");
tempObjectSb.AppendLine("\t\t\tReferenceInformationType: \"IndexToDirect\"");
tempObjectSb.AppendLine("\t\t\tUV: *" + uvLength * 2 + " {");
tempObjectSb.Append("\t\t\t\ta: ");
for(int i = 0; i < uvLength; i++)
{
if(i > 0)
tempObjectSb.Append(",");
tempObjectSb.AppendFormat("{0},{1}", uvs[i].x, uvs[i].y);
}
tempObjectSb.AppendLine();
tempObjectSb.AppendLine("\t\t\t\t}");
// UV tile index coords
tempObjectSb.AppendLine("\t\t\tUVIndex: *" + triangleCount +" {");
tempObjectSb.Append("\t\t\t\ta: ");
for(int i = 0; i < triangleCount; i += 3)
{
if(i > 0)
tempObjectSb.Append(",");
// Triangles need to be fliped for the x flip
int index1 = triangles[i];
int index2 = triangles[i+2];
int index3 = triangles[i+1];
tempObjectSb.AppendFormat("{0},{1},{2}", index1, index2, index3);
}
tempObjectSb.AppendLine();
tempObjectSb.AppendLine("\t\t\t}");
tempObjectSb.AppendLine("\t\t}");
// -- UV 2 Creation
// TODO: Add UV2 Creation here
// -- Smoothing
// TODO: Smoothing doesn't seem to do anything when importing. This maybe should be added. -KBH
// ============ MATERIALS =============
tempObjectSb.AppendLine("\t\tLayerElementMaterial: 0 {");
tempObjectSb.AppendLine("\t\t\tVersion: 101");
tempObjectSb.AppendLine("\t\t\tName: \"\"");
tempObjectSb.AppendLine("\t\t\tMappingInformationType: \"ByPolygon\"");
tempObjectSb.AppendLine("\t\t\tReferenceInformationType: \"IndexToDirect\"");
int totalFaceCount = 0;
// So by polygon means that we need 1/3rd of how many indicies we wrote.
int numberOfSubmeshes = mesh.subMeshCount;
StringBuilder submeshesSb = new StringBuilder();
// For just one submesh, we set them all to zero
if(numberOfSubmeshes == 1)
{
int numFaces = triangles.Length / 3;
for(int i = 0; i < numFaces; i++)
{
submeshesSb.Append("0,");
totalFaceCount++;
}
}
else
{
List<int[]> allSubmeshes = new List<int[]>();
// Load all submeshes into a space
for(int i = 0; i < numberOfSubmeshes; i++)
allSubmeshes.Add(mesh.GetIndices(i));
// TODO: Optimize this search pattern
for(int i = 0; i < triangles.Length; i += 3)
{
for(int subMeshIndex = 0; subMeshIndex < allSubmeshes.Count; subMeshIndex++)
{
bool breaker = false;
for(int n = 0; n < allSubmeshes[subMeshIndex].Length; n += 3)
{
if(triangles[i] == allSubmeshes[subMeshIndex][n]
&& triangles[i + 1] == allSubmeshes[subMeshIndex][n + 1]
&& triangles[i + 2] == allSubmeshes[subMeshIndex][n + 2])
{
submeshesSb.Append(subMeshIndex.ToString());
submeshesSb.Append(",");
totalFaceCount++;
break;
}
if(breaker)
break;
}
}
}
}
tempObjectSb.AppendLine("\t\t\tMaterials: *" + totalFaceCount + " {");
tempObjectSb.Append("\t\t\t\ta: ");
tempObjectSb.AppendLine(submeshesSb.ToString());
tempObjectSb.AppendLine("\t\t\t} ");
tempObjectSb.AppendLine("\t\t}");
// ============= INFORMS WHAT TYPE OF LATER ELEMENTS ARE IN THIS GEOMETRY =================
tempObjectSb.AppendLine("\t\tLayer: 0 {");
tempObjectSb.AppendLine("\t\t\tVersion: 100");
tempObjectSb.AppendLine("\t\t\tLayerElement: {");
tempObjectSb.AppendLine("\t\t\t\tType: \"LayerElementNormal\"");
tempObjectSb.AppendLine("\t\t\t\tTypedIndex: 0");
tempObjectSb.AppendLine("\t\t\t}");
tempObjectSb.AppendLine("\t\t\tLayerElement: {");
tempObjectSb.AppendLine("\t\t\t\tType: \"LayerElementMaterial\"");
tempObjectSb.AppendLine("\t\t\t\tTypedIndex: 0");
tempObjectSb.AppendLine("\t\t\t}");
tempObjectSb.AppendLine("\t\t\tLayerElement: {");
tempObjectSb.AppendLine("\t\t\t\tType: \"LayerElementTexture\"");
tempObjectSb.AppendLine("\t\t\t\tTypedIndex: 0");
tempObjectSb.AppendLine("\t\t\t}");
if(containsColors)
{
tempObjectSb.AppendLine("\t\t\tLayerElement: {");
tempObjectSb.AppendLine("\t\t\t\tType: \"LayerElementColor\"");
tempObjectSb.AppendLine("\t\t\t\tTypedIndex: 0");
tempObjectSb.AppendLine("\t\t\t}");
}
tempObjectSb.AppendLine("\t\t\tLayerElement: {");
tempObjectSb.AppendLine("\t\t\t\tType: \"LayerElementUV\"");
tempObjectSb.AppendLine("\t\t\t\tTypedIndex: 0");
tempObjectSb.AppendLine("\t\t\t}");
// TODO: Here we would add UV layer 1 for ambient occlusion UV file
// tempObjectSb.AppendLine("\t\t\tLayerElement: {");
// tempObjectSb.AppendLine("\t\t\t\tType: \"LayerElementUV\"");
// tempObjectSb.AppendLine("\t\t\t\tTypedIndex: 1");
// tempObjectSb.AppendLine("\t\t\t}");
tempObjectSb.AppendLine("\t\t}");
tempObjectSb.AppendLine("\t}");
// Add the connection for the model to the geometry so it is attached the right mesh
tempConnectionsSb.AppendLine("\t;Geometry::, Model::" + mesh.name);
tempConnectionsSb.AppendLine("\tC: \"OO\"," + geometryId + "," + modelId);
tempConnectionsSb.AppendLine();
// Add the connection of all the materials in order of submesh
MeshRenderer meshRenderer = gameObj.GetComponent<MeshRenderer>();
if(meshRenderer != null)
{
Material[] allMaterialsInThisMesh = meshRenderer.sharedMaterials;
for(int i = 0; i < allMaterialsInThisMesh.Length; i++)
{
Material mat = allMaterialsInThisMesh[i];
int referenceId = Mathf.Abs(mat.GetInstanceID());
if(mat == null)
{
Debug.LogError("ERROR: the game object " + gameObj.name + " has an empty material on it. This will export problematic files. Please fix and reexport");
continue;
}
tempConnectionsSb.AppendLine("\t;Material::" + mat.name + ", Model::" + mesh.name);
tempConnectionsSb.AppendLine("\tC: \"OO\"," + referenceId + "," + modelId);
tempConnectionsSb.AppendLine();
}
}
}
// Recursively add all the other objects to the string that has been built.
for(int i = 0; i < gameObj.transform.childCount; i++)
{
GameObject childObject = gameObj.transform.GetChild(i).gameObject;
FBXUnityMeshGetter.GetMeshToString(childObject, materials, ref tempObjectSb, ref tempConnectionsSb, gameObj, modelId);
}
objects.Append(tempObjectSb.ToString());
connections.Append(tempConnectionsSb.ToString());
return modelId;
}
//private Mesh CreateMeshInstance(UnityEngine.Object obj,Mesh mesh)
//{
// obj = new UnityEngine.Object();
// Mesh instanceMesh = UnityEngine.Instantiate(Mesh);
//}
}
}
| 502 |
orrb | openai | C# | // ===============================================================================================
// The MIT License (MIT) for UnityFBXExporter
//
// UnityFBXExporter was created for Building Crafter (http://u3d.as/ovC) a tool to rapidly
// create high quality buildings right in Unity with no need to use 3D modeling programs.
//
// Copyright (c) 2016 | 8Bit Goose Games, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// ===============================================================================================
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace UnityFBXExporter
{
public class ExporterMenu : Editor
{
// Dropdown
[MenuItem("GameObject/FBX Exporter/Only GameObject", false, 40)]
public static void ExportDropdownGameObjectToFBX()
{
ExportCurrentGameObject(false, false);
}
[MenuItem("GameObject/FBX Exporter/With new Materials", false, 41)]
public static void ExportDropdownGameObjectAndMaterialsToFBX()
{
ExportCurrentGameObject(true, false);
}
[MenuItem("GameObject/FBX Exporter/With new Materials and Textures", false, 42)]
public static void ExportDropdownGameObjectAndMaterialsTexturesToFBX()
{
ExportCurrentGameObject(true, true);
}
// Assets
[MenuItem("Assets/FBX Exporter/Only GameObject", false, 30)]
public static void ExportGameObjectToFBX()
{
ExportCurrentGameObject(false, false);
}
[MenuItem("Assets/FBX Exporter/With new Materials", false, 31)]
public static void ExportGameObjectAndMaterialsToFBX()
{
ExportCurrentGameObject(true, false);
}
[MenuItem("Assets/FBX Exporter/With new Materials and Textures", false, 32)]
public static void ExportGameObjectAndMaterialsTexturesToFBX()
{
ExportCurrentGameObject(true, true);
}
private static void ExportCurrentGameObject(bool copyMaterials, bool copyTextures)
{
if(Selection.activeGameObject == null)
{
EditorUtility.DisplayDialog("No Object Selected", "Please select any GameObject to Export to FBX", "Okay");
return;
}
GameObject currentGameObject = Selection.activeObject as GameObject;
if(currentGameObject == null)
{
EditorUtility.DisplayDialog("Warning", "Item selected is not a GameObject", "Okay");
return;
}
ExportGameObject(currentGameObject, copyMaterials, copyTextures);
}
/// <summary>
/// Exports ANY Game Object given to it. Will provide a dialog and return the path of the newly exported file
/// </summary>
/// <returns>The path of the newly exported FBX file</returns>
/// <param name="gameObj">Game object to be exported</param>
/// <param name="copyMaterials">If set to <c>true</c> copy materials.</param>
/// <param name="copyTextures">If set to <c>true</c> copy textures.</param>
/// <param name="oldPath">Old path.</param>
public static string ExportGameObject(GameObject gameObj, bool copyMaterials, bool copyTextures, string oldPath = null)
{
if(gameObj == null)
{
EditorUtility.DisplayDialog("Object is null", "Please select any GameObject to Export to FBX", "Okay");
return null;
}
string newPath = GetNewPath(gameObj, oldPath);
if(newPath != null && newPath.Length != 0)
{
bool isSuccess = FBXExporter.ExportGameObjToFBX(gameObj, newPath, copyMaterials, copyTextures);
if(isSuccess)
{
return newPath;
}
else
EditorUtility.DisplayDialog("Warning", "The extension probably wasn't an FBX file, could not export.", "Okay");
}
return null;
}
/// <summary>
/// Creates save dialog window depending on old path or right to the /Assets folder no old path is given
/// </summary>
/// <returns>The new path.</returns>
/// <param name="gameObject">Item to be exported</param>
/// <param name="oldPath">The old path that this object was original at.</param>
private static string GetNewPath(GameObject gameObject, string oldPath = null)
{
// NOTE: This must return a path with the starting "Assets/" or else textures won't copy right
string name = gameObject.name;
string newPath = null;
if(oldPath == null)
newPath = EditorUtility.SaveFilePanelInProject("Export FBX File", name + ".fbx", "fbx", "Export " + name + " GameObject to a FBX file");
else
{
if(oldPath.StartsWith("/Assets"))
{
oldPath = Application.dataPath.Remove(Application.dataPath.LastIndexOf("/Assets"), 7) + oldPath;
oldPath = oldPath.Remove(oldPath.LastIndexOf('/'), oldPath.Length - oldPath.LastIndexOf('/'));
}
newPath = EditorUtility.SaveFilePanel("Export FBX File", oldPath, name + ".fbx", "fbx");
}
int assetsIndex = newPath.IndexOf("Assets");
if(assetsIndex < 0)
return null;
if(assetsIndex > 0)
newPath = newPath.Remove(0, assetsIndex);
return newPath;
}
}
} | 161 |
orrb | openai | C# | using UnityEngine;
using System.Collections;
using UnityEditor;
public class ProceduralTest : MonoBehaviour
{
[MenuItem("Assets/FBX Exporter/Create Object With Procedural Texture", false, 43)]
public static void CreateObject()
{
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
Texture2D texture = new Texture2D(128, 128);
for (int x = 0; x < 128; ++x)
for (int y = 0; y < 128; ++y)
texture.SetPixel(x, y, (x-64)*(x-64) + (y-64)*(y-64) < 1000 ? Color.white : Color.black);
texture.Apply();
Material mat = new Material(Shader.Find("Standard"));
mat.mainTexture = texture;
cube.GetComponent<MeshRenderer>().sharedMaterial = mat;
}
}
| 22 |
retro | openai | C# | using System.Reflection;
using System.Runtime.CompilerServices;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("DotZLib")]
[assembly: AssemblyDescription(".Net bindings for ZLib compression dll 1.2.x")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Henrik Ravn")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) 2004 by Henrik Ravn")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]
| 59 |
retro | openai | C# | //
// © Copyright Henrik Ravn 2004
//
// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace DotZLib
{
#region ChecksumGeneratorBase
/// <summary>
/// Implements the common functionality needed for all <see cref="ChecksumGenerator"/>s
/// </summary>
/// <example></example>
public abstract class ChecksumGeneratorBase : ChecksumGenerator
{
/// <summary>
/// The value of the current checksum
/// </summary>
protected uint _current;
/// <summary>
/// Initializes a new instance of the checksum generator base - the current checksum is
/// set to zero
/// </summary>
public ChecksumGeneratorBase()
{
_current = 0;
}
/// <summary>
/// Initializes a new instance of the checksum generator basewith a specified value
/// </summary>
/// <param name="initialValue">The value to set the current checksum to</param>
public ChecksumGeneratorBase(uint initialValue)
{
_current = initialValue;
}
/// <summary>
/// Resets the current checksum to zero
/// </summary>
public void Reset() { _current = 0; }
/// <summary>
/// Gets the current checksum value
/// </summary>
public uint Value { get { return _current; } }
/// <summary>
/// Updates the current checksum with part of an array of bytes
/// </summary>
/// <param name="data">The data to update the checksum with</param>
/// <param name="offset">Where in <c>data</c> to start updating</param>
/// <param name="count">The number of bytes from <c>data</c> to use</param>
/// <exception cref="ArgumentException">The sum of offset and count is larger than the length of <c>data</c></exception>
/// <exception cref="NullReferenceException"><c>data</c> is a null reference</exception>
/// <exception cref="ArgumentOutOfRangeException">Offset or count is negative.</exception>
/// <remarks>All the other <c>Update</c> methods are implmeneted in terms of this one.
/// This is therefore the only method a derived class has to implement</remarks>
public abstract void Update(byte[] data, int offset, int count);
/// <summary>
/// Updates the current checksum with an array of bytes.
/// </summary>
/// <param name="data">The data to update the checksum with</param>
public void Update(byte[] data)
{
Update(data, 0, data.Length);
}
/// <summary>
/// Updates the current checksum with the data from a string
/// </summary>
/// <param name="data">The string to update the checksum with</param>
/// <remarks>The characters in the string are converted by the UTF-8 encoding</remarks>
public void Update(string data)
{
Update(Encoding.UTF8.GetBytes(data));
}
/// <summary>
/// Updates the current checksum with the data from a string, using a specific encoding
/// </summary>
/// <param name="data">The string to update the checksum with</param>
/// <param name="encoding">The encoding to use</param>
public void Update(string data, Encoding encoding)
{
Update(encoding.GetBytes(data));
}
}
#endregion
#region CRC32
/// <summary>
/// Implements a CRC32 checksum generator
/// </summary>
public sealed class CRC32Checksum : ChecksumGeneratorBase
{
#region DLL imports
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern uint crc32(uint crc, int data, uint length);
#endregion
/// <summary>
/// Initializes a new instance of the CRC32 checksum generator
/// </summary>
public CRC32Checksum() : base() {}
/// <summary>
/// Initializes a new instance of the CRC32 checksum generator with a specified value
/// </summary>
/// <param name="initialValue">The value to set the current checksum to</param>
public CRC32Checksum(uint initialValue) : base(initialValue) {}
/// <summary>
/// Updates the current checksum with part of an array of bytes
/// </summary>
/// <param name="data">The data to update the checksum with</param>
/// <param name="offset">Where in <c>data</c> to start updating</param>
/// <param name="count">The number of bytes from <c>data</c> to use</param>
/// <exception cref="ArgumentException">The sum of offset and count is larger than the length of <c>data</c></exception>
/// <exception cref="NullReferenceException"><c>data</c> is a null reference</exception>
/// <exception cref="ArgumentOutOfRangeException">Offset or count is negative.</exception>
public override void Update(byte[] data, int offset, int count)
{
if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
if ((offset+count) > data.Length) throw new ArgumentException();
GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned);
try
{
_current = crc32(_current, hData.AddrOfPinnedObject().ToInt32()+offset, (uint)count);
}
finally
{
hData.Free();
}
}
}
#endregion
#region Adler
/// <summary>
/// Implements a checksum generator that computes the Adler checksum on data
/// </summary>
public sealed class AdlerChecksum : ChecksumGeneratorBase
{
#region DLL imports
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern uint adler32(uint adler, int data, uint length);
#endregion
/// <summary>
/// Initializes a new instance of the Adler checksum generator
/// </summary>
public AdlerChecksum() : base() {}
/// <summary>
/// Initializes a new instance of the Adler checksum generator with a specified value
/// </summary>
/// <param name="initialValue">The value to set the current checksum to</param>
public AdlerChecksum(uint initialValue) : base(initialValue) {}
/// <summary>
/// Updates the current checksum with part of an array of bytes
/// </summary>
/// <param name="data">The data to update the checksum with</param>
/// <param name="offset">Where in <c>data</c> to start updating</param>
/// <param name="count">The number of bytes from <c>data</c> to use</param>
/// <exception cref="ArgumentException">The sum of offset and count is larger than the length of <c>data</c></exception>
/// <exception cref="NullReferenceException"><c>data</c> is a null reference</exception>
/// <exception cref="ArgumentOutOfRangeException">Offset or count is negative.</exception>
public override void Update(byte[] data, int offset, int count)
{
if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
if ((offset+count) > data.Length) throw new ArgumentException();
GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned);
try
{
_current = adler32(_current, hData.AddrOfPinnedObject().ToInt32()+offset, (uint)count);
}
finally
{
hData.Free();
}
}
}
#endregion
} | 202 |
retro | openai | C# | //
// © Copyright Henrik Ravn 2004
//
// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
using System;
using System.Diagnostics;
namespace DotZLib
{
/// <summary>
/// This class implements a circular buffer
/// </summary>
internal class CircularBuffer
{
#region Private data
private int _capacity;
private int _head;
private int _tail;
private int _size;
private byte[] _buffer;
#endregion
public CircularBuffer(int capacity)
{
Debug.Assert( capacity > 0 );
_buffer = new byte[capacity];
_capacity = capacity;
_head = 0;
_tail = 0;
_size = 0;
}
public int Size { get { return _size; } }
public int Put(byte[] source, int offset, int count)
{
Debug.Assert( count > 0 );
int trueCount = Math.Min(count, _capacity - Size);
for (int i = 0; i < trueCount; ++i)
_buffer[(_tail+i) % _capacity] = source[offset+i];
_tail += trueCount;
_tail %= _capacity;
_size += trueCount;
return trueCount;
}
public bool Put(byte b)
{
if (Size == _capacity) // no room
return false;
_buffer[_tail++] = b;
_tail %= _capacity;
++_size;
return true;
}
public int Get(byte[] destination, int offset, int count)
{
int trueCount = Math.Min(count,Size);
for (int i = 0; i < trueCount; ++i)
destination[offset + i] = _buffer[(_head+i) % _capacity];
_head += trueCount;
_head %= _capacity;
_size -= trueCount;
return trueCount;
}
public int Get()
{
if (Size == 0)
return -1;
int result = (int)_buffer[_head++ % _capacity];
--_size;
return result;
}
}
}
| 84 |
retro | openai | C# | //
// © Copyright Henrik Ravn 2004
//
// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
using System;
using System.Runtime.InteropServices;
namespace DotZLib
{
/// <summary>
/// Implements the common functionality needed for all <see cref="Codec"/>s
/// </summary>
public abstract class CodecBase : Codec, IDisposable
{
#region Data members
/// <summary>
/// Instance of the internal zlib buffer structure that is
/// passed to all functions in the zlib dll
/// </summary>
internal ZStream _ztream = new ZStream();
/// <summary>
/// True if the object instance has been disposed, false otherwise
/// </summary>
protected bool _isDisposed = false;
/// <summary>
/// The size of the internal buffers
/// </summary>
protected const int kBufferSize = 16384;
private byte[] _outBuffer = new byte[kBufferSize];
private byte[] _inBuffer = new byte[kBufferSize];
private GCHandle _hInput;
private GCHandle _hOutput;
private uint _checksum = 0;
#endregion
/// <summary>
/// Initializes a new instance of the <c>CodeBase</c> class.
/// </summary>
public CodecBase()
{
try
{
_hInput = GCHandle.Alloc(_inBuffer, GCHandleType.Pinned);
_hOutput = GCHandle.Alloc(_outBuffer, GCHandleType.Pinned);
}
catch (Exception)
{
CleanUp(false);
throw;
}
}
#region Codec Members
/// <summary>
/// Occurs when more processed data are available.
/// </summary>
public event DataAvailableHandler DataAvailable;
/// <summary>
/// Fires the <see cref="DataAvailable"/> event
/// </summary>
protected void OnDataAvailable()
{
if (_ztream.total_out > 0)
{
if (DataAvailable != null)
DataAvailable( _outBuffer, 0, (int)_ztream.total_out);
resetOutput();
}
}
/// <summary>
/// Adds more data to the codec to be processed.
/// </summary>
/// <param name="data">Byte array containing the data to be added to the codec</param>
/// <remarks>Adding data may, or may not, raise the <c>DataAvailable</c> event</remarks>
public void Add(byte[] data)
{
Add(data,0,data.Length);
}
/// <summary>
/// Adds more data to the codec to be processed.
/// </summary>
/// <param name="data">Byte array containing the data to be added to the codec</param>
/// <param name="offset">The index of the first byte to add from <c>data</c></param>
/// <param name="count">The number of bytes to add</param>
/// <remarks>Adding data may, or may not, raise the <c>DataAvailable</c> event</remarks>
/// <remarks>This must be implemented by a derived class</remarks>
public abstract void Add(byte[] data, int offset, int count);
/// <summary>
/// Finishes up any pending data that needs to be processed and handled.
/// </summary>
/// <remarks>This must be implemented by a derived class</remarks>
public abstract void Finish();
/// <summary>
/// Gets the checksum of the data that has been added so far
/// </summary>
public uint Checksum { get { return _checksum; } }
#endregion
#region Destructor & IDisposable stuff
/// <summary>
/// Destroys this instance
/// </summary>
~CodecBase()
{
CleanUp(false);
}
/// <summary>
/// Releases any unmanaged resources and calls the <see cref="CleanUp()"/> method of the derived class
/// </summary>
public void Dispose()
{
CleanUp(true);
}
/// <summary>
/// Performs any codec specific cleanup
/// </summary>
/// <remarks>This must be implemented by a derived class</remarks>
protected abstract void CleanUp();
// performs the release of the handles and calls the dereived CleanUp()
private void CleanUp(bool isDisposing)
{
if (!_isDisposed)
{
CleanUp();
if (_hInput.IsAllocated)
_hInput.Free();
if (_hOutput.IsAllocated)
_hOutput.Free();
_isDisposed = true;
}
}
#endregion
#region Helper methods
/// <summary>
/// Copies a number of bytes to the internal codec buffer - ready for proccesing
/// </summary>
/// <param name="data">The byte array that contains the data to copy</param>
/// <param name="startIndex">The index of the first byte to copy</param>
/// <param name="count">The number of bytes to copy from <c>data</c></param>
protected void copyInput(byte[] data, int startIndex, int count)
{
Array.Copy(data, startIndex, _inBuffer,0, count);
_ztream.next_in = _hInput.AddrOfPinnedObject();
_ztream.total_in = 0;
_ztream.avail_in = (uint)count;
}
/// <summary>
/// Resets the internal output buffers to a known state - ready for processing
/// </summary>
protected void resetOutput()
{
_ztream.total_out = 0;
_ztream.avail_out = kBufferSize;
_ztream.next_out = _hOutput.AddrOfPinnedObject();
}
/// <summary>
/// Updates the running checksum property
/// </summary>
/// <param name="newSum">The new checksum value</param>
protected void setChecksum(uint newSum)
{
_checksum = newSum;
}
#endregion
}
}
| 199 |
retro | openai | C# | //
// © Copyright Henrik Ravn 2004
//
// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace DotZLib
{
/// <summary>
/// Implements a data compressor, using the deflate algorithm in the ZLib dll
/// </summary>
public sealed class Deflater : CodecBase
{
#region Dll imports
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)]
private static extern int deflateInit_(ref ZStream sz, int level, string vs, int size);
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int deflate(ref ZStream sz, int flush);
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int deflateReset(ref ZStream sz);
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int deflateEnd(ref ZStream sz);
#endregion
/// <summary>
/// Constructs an new instance of the <c>Deflater</c>
/// </summary>
/// <param name="level">The compression level to use for this <c>Deflater</c></param>
public Deflater(CompressLevel level) : base()
{
int retval = deflateInit_(ref _ztream, (int)level, Info.Version, Marshal.SizeOf(_ztream));
if (retval != 0)
throw new ZLibException(retval, "Could not initialize deflater");
resetOutput();
}
/// <summary>
/// Adds more data to the codec to be processed.
/// </summary>
/// <param name="data">Byte array containing the data to be added to the codec</param>
/// <param name="offset">The index of the first byte to add from <c>data</c></param>
/// <param name="count">The number of bytes to add</param>
/// <remarks>Adding data may, or may not, raise the <c>DataAvailable</c> event</remarks>
public override void Add(byte[] data, int offset, int count)
{
if (data == null) throw new ArgumentNullException();
if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
if ((offset+count) > data.Length) throw new ArgumentException();
int total = count;
int inputIndex = offset;
int err = 0;
while (err >= 0 && inputIndex < total)
{
copyInput(data, inputIndex, Math.Min(total - inputIndex, kBufferSize));
while (err >= 0 && _ztream.avail_in > 0)
{
err = deflate(ref _ztream, (int)FlushTypes.None);
if (err == 0)
while (_ztream.avail_out == 0)
{
OnDataAvailable();
err = deflate(ref _ztream, (int)FlushTypes.None);
}
inputIndex += (int)_ztream.total_in;
}
}
setChecksum( _ztream.adler );
}
/// <summary>
/// Finishes up any pending data that needs to be processed and handled.
/// </summary>
public override void Finish()
{
int err;
do
{
err = deflate(ref _ztream, (int)FlushTypes.Finish);
OnDataAvailable();
}
while (err == 0);
setChecksum( _ztream.adler );
deflateReset(ref _ztream);
resetOutput();
}
/// <summary>
/// Closes the internal zlib deflate stream
/// </summary>
protected override void CleanUp() { deflateEnd(ref _ztream); }
}
}
| 107 |
retro | openai | C# | //
// © Copyright Henrik Ravn 2004
//
// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace DotZLib
{
#region Internal types
/// <summary>
/// Defines constants for the various flush types used with zlib
/// </summary>
internal enum FlushTypes
{
None, Partial, Sync, Full, Finish, Block
}
#region ZStream structure
// internal mapping of the zlib zstream structure for marshalling
[StructLayoutAttribute(LayoutKind.Sequential, Pack=4, Size=0, CharSet=CharSet.Ansi)]
internal struct ZStream
{
public IntPtr next_in;
public uint avail_in;
public uint total_in;
public IntPtr next_out;
public uint avail_out;
public uint total_out;
[MarshalAs(UnmanagedType.LPStr)]
string msg;
uint state;
uint zalloc;
uint zfree;
uint opaque;
int data_type;
public uint adler;
uint reserved;
}
#endregion
#endregion
#region Public enums
/// <summary>
/// Defines constants for the available compression levels in zlib
/// </summary>
public enum CompressLevel : int
{
/// <summary>
/// The default compression level with a reasonable compromise between compression and speed
/// </summary>
Default = -1,
/// <summary>
/// No compression at all. The data are passed straight through.
/// </summary>
None = 0,
/// <summary>
/// The maximum compression rate available.
/// </summary>
Best = 9,
/// <summary>
/// The fastest available compression level.
/// </summary>
Fastest = 1
}
#endregion
#region Exception classes
/// <summary>
/// The exception that is thrown when an error occurs on the zlib dll
/// </summary>
public class ZLibException : ApplicationException
{
/// <summary>
/// Initializes a new instance of the <see cref="ZLibException"/> class with a specified
/// error message and error code
/// </summary>
/// <param name="errorCode">The zlib error code that caused the exception</param>
/// <param name="msg">A message that (hopefully) describes the error</param>
public ZLibException(int errorCode, string msg) : base(String.Format("ZLib error {0} {1}", errorCode, msg))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ZLibException"/> class with a specified
/// error code
/// </summary>
/// <param name="errorCode">The zlib error code that caused the exception</param>
public ZLibException(int errorCode) : base(String.Format("ZLib error {0}", errorCode))
{
}
}
#endregion
#region Interfaces
/// <summary>
/// Declares methods and properties that enables a running checksum to be calculated
/// </summary>
public interface ChecksumGenerator
{
/// <summary>
/// Gets the current value of the checksum
/// </summary>
uint Value { get; }
/// <summary>
/// Clears the current checksum to 0
/// </summary>
void Reset();
/// <summary>
/// Updates the current checksum with an array of bytes
/// </summary>
/// <param name="data">The data to update the checksum with</param>
void Update(byte[] data);
/// <summary>
/// Updates the current checksum with part of an array of bytes
/// </summary>
/// <param name="data">The data to update the checksum with</param>
/// <param name="offset">Where in <c>data</c> to start updating</param>
/// <param name="count">The number of bytes from <c>data</c> to use</param>
/// <exception cref="ArgumentException">The sum of offset and count is larger than the length of <c>data</c></exception>
/// <exception cref="ArgumentNullException"><c>data</c> is a null reference</exception>
/// <exception cref="ArgumentOutOfRangeException">Offset or count is negative.</exception>
void Update(byte[] data, int offset, int count);
/// <summary>
/// Updates the current checksum with the data from a string
/// </summary>
/// <param name="data">The string to update the checksum with</param>
/// <remarks>The characters in the string are converted by the UTF-8 encoding</remarks>
void Update(string data);
/// <summary>
/// Updates the current checksum with the data from a string, using a specific encoding
/// </summary>
/// <param name="data">The string to update the checksum with</param>
/// <param name="encoding">The encoding to use</param>
void Update(string data, Encoding encoding);
}
/// <summary>
/// Represents the method that will be called from a codec when new data
/// are available.
/// </summary>
/// <paramref name="data">The byte array containing the processed data</paramref>
/// <paramref name="startIndex">The index of the first processed byte in <c>data</c></paramref>
/// <paramref name="count">The number of processed bytes available</paramref>
/// <remarks>On return from this method, the data may be overwritten, so grab it while you can.
/// You cannot assume that startIndex will be zero.
/// </remarks>
public delegate void DataAvailableHandler(byte[] data, int startIndex, int count);
/// <summary>
/// Declares methods and events for implementing compressors/decompressors
/// </summary>
public interface Codec
{
/// <summary>
/// Occurs when more processed data are available.
/// </summary>
event DataAvailableHandler DataAvailable;
/// <summary>
/// Adds more data to the codec to be processed.
/// </summary>
/// <param name="data">Byte array containing the data to be added to the codec</param>
/// <remarks>Adding data may, or may not, raise the <c>DataAvailable</c> event</remarks>
void Add(byte[] data);
/// <summary>
/// Adds more data to the codec to be processed.
/// </summary>
/// <param name="data">Byte array containing the data to be added to the codec</param>
/// <param name="offset">The index of the first byte to add from <c>data</c></param>
/// <param name="count">The number of bytes to add</param>
/// <remarks>Adding data may, or may not, raise the <c>DataAvailable</c> event</remarks>
void Add(byte[] data, int offset, int count);
/// <summary>
/// Finishes up any pending data that needs to be processed and handled.
/// </summary>
void Finish();
/// <summary>
/// Gets the checksum of the data that has been added so far
/// </summary>
uint Checksum { get; }
}
#endregion
#region Classes
/// <summary>
/// Encapsulates general information about the ZLib library
/// </summary>
public class Info
{
#region DLL imports
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern uint zlibCompileFlags();
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern string zlibVersion();
#endregion
#region Private stuff
private uint _flags;
// helper function that unpacks a bitsize mask
private static int bitSize(uint bits)
{
switch (bits)
{
case 0: return 16;
case 1: return 32;
case 2: return 64;
}
return -1;
}
#endregion
/// <summary>
/// Constructs an instance of the <c>Info</c> class.
/// </summary>
public Info()
{
_flags = zlibCompileFlags();
}
/// <summary>
/// True if the library is compiled with debug info
/// </summary>
public bool HasDebugInfo { get { return 0 != (_flags & 0x100); } }
/// <summary>
/// True if the library is compiled with assembly optimizations
/// </summary>
public bool UsesAssemblyCode { get { return 0 != (_flags & 0x200); } }
/// <summary>
/// Gets the size of the unsigned int that was compiled into Zlib
/// </summary>
public int SizeOfUInt { get { return bitSize(_flags & 3); } }
/// <summary>
/// Gets the size of the unsigned long that was compiled into Zlib
/// </summary>
public int SizeOfULong { get { return bitSize((_flags >> 2) & 3); } }
/// <summary>
/// Gets the size of the pointers that were compiled into Zlib
/// </summary>
public int SizeOfPointer { get { return bitSize((_flags >> 4) & 3); } }
/// <summary>
/// Gets the size of the z_off_t type that was compiled into Zlib
/// </summary>
public int SizeOfOffset { get { return bitSize((_flags >> 6) & 3); } }
/// <summary>
/// Gets the version of ZLib as a string, e.g. "1.2.1"
/// </summary>
public static string Version { get { return zlibVersion(); } }
}
#endregion
}
| 289 |
retro | openai | C# | //
// © Copyright Henrik Ravn 2004
//
// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace DotZLib
{
/// <summary>
/// Implements a compressed <see cref="Stream"/>, in GZip (.gz) format.
/// </summary>
public class GZipStream : Stream, IDisposable
{
#region Dll Imports
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)]
private static extern IntPtr gzopen(string name, string mode);
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int gzclose(IntPtr gzFile);
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int gzwrite(IntPtr gzFile, int data, int length);
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int gzread(IntPtr gzFile, int data, int length);
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int gzgetc(IntPtr gzFile);
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int gzputc(IntPtr gzFile, int c);
#endregion
#region Private data
private IntPtr _gzFile;
private bool _isDisposed = false;
private bool _isWriting;
#endregion
#region Constructors
/// <summary>
/// Creates a new file as a writeable GZipStream
/// </summary>
/// <param name="fileName">The name of the compressed file to create</param>
/// <param name="level">The compression level to use when adding data</param>
/// <exception cref="ZLibException">If an error occurred in the internal zlib function</exception>
public GZipStream(string fileName, CompressLevel level)
{
_isWriting = true;
_gzFile = gzopen(fileName, String.Format("wb{0}", (int)level));
if (_gzFile == IntPtr.Zero)
throw new ZLibException(-1, "Could not open " + fileName);
}
/// <summary>
/// Opens an existing file as a readable GZipStream
/// </summary>
/// <param name="fileName">The name of the file to open</param>
/// <exception cref="ZLibException">If an error occurred in the internal zlib function</exception>
public GZipStream(string fileName)
{
_isWriting = false;
_gzFile = gzopen(fileName, "rb");
if (_gzFile == IntPtr.Zero)
throw new ZLibException(-1, "Could not open " + fileName);
}
#endregion
#region Access properties
/// <summary>
/// Returns true of this stream can be read from, false otherwise
/// </summary>
public override bool CanRead
{
get
{
return !_isWriting;
}
}
/// <summary>
/// Returns false.
/// </summary>
public override bool CanSeek
{
get
{
return false;
}
}
/// <summary>
/// Returns true if this tsream is writeable, false otherwise
/// </summary>
public override bool CanWrite
{
get
{
return _isWriting;
}
}
#endregion
#region Destructor & IDispose stuff
/// <summary>
/// Destroys this instance
/// </summary>
~GZipStream()
{
cleanUp(false);
}
/// <summary>
/// Closes the external file handle
/// </summary>
public void Dispose()
{
cleanUp(true);
}
// Does the actual closing of the file handle.
private void cleanUp(bool isDisposing)
{
if (!_isDisposed)
{
gzclose(_gzFile);
_isDisposed = true;
}
}
#endregion
#region Basic reading and writing
/// <summary>
/// Attempts to read a number of bytes from the stream.
/// </summary>
/// <param name="buffer">The destination data buffer</param>
/// <param name="offset">The index of the first destination byte in <c>buffer</c></param>
/// <param name="count">The number of bytes requested</param>
/// <returns>The number of bytes read</returns>
/// <exception cref="ArgumentNullException">If <c>buffer</c> is null</exception>
/// <exception cref="ArgumentOutOfRangeException">If <c>count</c> or <c>offset</c> are negative</exception>
/// <exception cref="ArgumentException">If <c>offset</c> + <c>count</c> is > buffer.Length</exception>
/// <exception cref="NotSupportedException">If this stream is not readable.</exception>
/// <exception cref="ObjectDisposedException">If this stream has been disposed.</exception>
public override int Read(byte[] buffer, int offset, int count)
{
if (!CanRead) throw new NotSupportedException();
if (buffer == null) throw new ArgumentNullException();
if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
if ((offset+count) > buffer.Length) throw new ArgumentException();
if (_isDisposed) throw new ObjectDisposedException("GZipStream");
GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned);
int result;
try
{
result = gzread(_gzFile, h.AddrOfPinnedObject().ToInt32() + offset, count);
if (result < 0)
throw new IOException();
}
finally
{
h.Free();
}
return result;
}
/// <summary>
/// Attempts to read a single byte from the stream.
/// </summary>
/// <returns>The byte that was read, or -1 in case of error or End-Of-File</returns>
public override int ReadByte()
{
if (!CanRead) throw new NotSupportedException();
if (_isDisposed) throw new ObjectDisposedException("GZipStream");
return gzgetc(_gzFile);
}
/// <summary>
/// Writes a number of bytes to the stream
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <exception cref="ArgumentNullException">If <c>buffer</c> is null</exception>
/// <exception cref="ArgumentOutOfRangeException">If <c>count</c> or <c>offset</c> are negative</exception>
/// <exception cref="ArgumentException">If <c>offset</c> + <c>count</c> is > buffer.Length</exception>
/// <exception cref="NotSupportedException">If this stream is not writeable.</exception>
/// <exception cref="ObjectDisposedException">If this stream has been disposed.</exception>
public override void Write(byte[] buffer, int offset, int count)
{
if (!CanWrite) throw new NotSupportedException();
if (buffer == null) throw new ArgumentNullException();
if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
if ((offset+count) > buffer.Length) throw new ArgumentException();
if (_isDisposed) throw new ObjectDisposedException("GZipStream");
GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned);
try
{
int result = gzwrite(_gzFile, h.AddrOfPinnedObject().ToInt32() + offset, count);
if (result < 0)
throw new IOException();
}
finally
{
h.Free();
}
}
/// <summary>
/// Writes a single byte to the stream
/// </summary>
/// <param name="value">The byte to add to the stream.</param>
/// <exception cref="NotSupportedException">If this stream is not writeable.</exception>
/// <exception cref="ObjectDisposedException">If this stream has been disposed.</exception>
public override void WriteByte(byte value)
{
if (!CanWrite) throw new NotSupportedException();
if (_isDisposed) throw new ObjectDisposedException("GZipStream");
int result = gzputc(_gzFile, (int)value);
if (result < 0)
throw new IOException();
}
#endregion
#region Position & length stuff
/// <summary>
/// Not supported.
/// </summary>
/// <param name="value"></param>
/// <exception cref="NotSupportedException">Always thrown</exception>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Not suppported.
/// </summary>
/// <param name="offset"></param>
/// <param name="origin"></param>
/// <returns></returns>
/// <exception cref="NotSupportedException">Always thrown</exception>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Flushes the <c>GZipStream</c>.
/// </summary>
/// <remarks>In this implementation, this method does nothing. This is because excessive
/// flushing may degrade the achievable compression rates.</remarks>
public override void Flush()
{
// left empty on purpose
}
/// <summary>
/// Gets/sets the current position in the <c>GZipStream</c>. Not suppported.
/// </summary>
/// <remarks>In this implementation this property is not supported</remarks>
/// <exception cref="NotSupportedException">Always thrown</exception>
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
/// <summary>
/// Gets the size of the stream. Not suppported.
/// </summary>
/// <remarks>In this implementation this property is not supported</remarks>
/// <exception cref="NotSupportedException">Always thrown</exception>
public override long Length
{
get
{
throw new NotSupportedException();
}
}
#endregion
}
}
| 302 |
retro | openai | C# | //
// © Copyright Henrik Ravn 2004
//
// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace DotZLib
{
/// <summary>
/// Implements a data decompressor, using the inflate algorithm in the ZLib dll
/// </summary>
public class Inflater : CodecBase
{
#region Dll imports
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)]
private static extern int inflateInit_(ref ZStream sz, string vs, int size);
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int inflate(ref ZStream sz, int flush);
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int inflateReset(ref ZStream sz);
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int inflateEnd(ref ZStream sz);
#endregion
/// <summary>
/// Constructs an new instance of the <c>Inflater</c>
/// </summary>
public Inflater() : base()
{
int retval = inflateInit_(ref _ztream, Info.Version, Marshal.SizeOf(_ztream));
if (retval != 0)
throw new ZLibException(retval, "Could not initialize inflater");
resetOutput();
}
/// <summary>
/// Adds more data to the codec to be processed.
/// </summary>
/// <param name="data">Byte array containing the data to be added to the codec</param>
/// <param name="offset">The index of the first byte to add from <c>data</c></param>
/// <param name="count">The number of bytes to add</param>
/// <remarks>Adding data may, or may not, raise the <c>DataAvailable</c> event</remarks>
public override void Add(byte[] data, int offset, int count)
{
if (data == null) throw new ArgumentNullException();
if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
if ((offset+count) > data.Length) throw new ArgumentException();
int total = count;
int inputIndex = offset;
int err = 0;
while (err >= 0 && inputIndex < total)
{
copyInput(data, inputIndex, Math.Min(total - inputIndex, kBufferSize));
err = inflate(ref _ztream, (int)FlushTypes.None);
if (err == 0)
while (_ztream.avail_out == 0)
{
OnDataAvailable();
err = inflate(ref _ztream, (int)FlushTypes.None);
}
inputIndex += (int)_ztream.total_in;
}
setChecksum( _ztream.adler );
}
/// <summary>
/// Finishes up any pending data that needs to be processed and handled.
/// </summary>
public override void Finish()
{
int err;
do
{
err = inflate(ref _ztream, (int)FlushTypes.Finish);
OnDataAvailable();
}
while (err == 0);
setChecksum( _ztream.adler );
inflateReset(ref _ztream);
resetOutput();
}
/// <summary>
/// Closes the internal zlib inflate stream
/// </summary>
protected override void CleanUp() { inflateEnd(ref _ztream); }
}
}
| 106 |
retro | openai | C# | //
// © Copyright Henrik Ravn 2004
//
// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
using System;
using System.Collections;
using System.IO;
// uncomment the define below to include unit tests
//#define nunit
#if nunit
using NUnit.Framework;
// Unit tests for the DotZLib class library
// ----------------------------------------
//
// Use this with NUnit 2 from http://www.nunit.org
//
namespace DotZLibTests
{
using DotZLib;
// helper methods
internal class Utils
{
public static bool byteArrEqual( byte[] lhs, byte[] rhs )
{
if (lhs.Length != rhs.Length)
return false;
for (int i = lhs.Length-1; i >= 0; --i)
if (lhs[i] != rhs[i])
return false;
return true;
}
}
[TestFixture]
public class CircBufferTests
{
#region Circular buffer tests
[Test]
public void SinglePutGet()
{
CircularBuffer buf = new CircularBuffer(10);
Assert.AreEqual( 0, buf.Size );
Assert.AreEqual( -1, buf.Get() );
Assert.IsTrue(buf.Put( 1 ));
Assert.AreEqual( 1, buf.Size );
Assert.AreEqual( 1, buf.Get() );
Assert.AreEqual( 0, buf.Size );
Assert.AreEqual( -1, buf.Get() );
}
[Test]
public void BlockPutGet()
{
CircularBuffer buf = new CircularBuffer(10);
byte[] arr = {1,2,3,4,5,6,7,8,9,10};
Assert.AreEqual( 10, buf.Put(arr,0,10) );
Assert.AreEqual( 10, buf.Size );
Assert.IsFalse( buf.Put(11) );
Assert.AreEqual( 1, buf.Get() );
Assert.IsTrue( buf.Put(11) );
byte[] arr2 = (byte[])arr.Clone();
Assert.AreEqual( 9, buf.Get(arr2,1,9) );
Assert.IsTrue( Utils.byteArrEqual(arr,arr2) );
}
#endregion
}
[TestFixture]
public class ChecksumTests
{
#region CRC32 Tests
[Test]
public void CRC32_Null()
{
CRC32Checksum crc32 = new CRC32Checksum();
Assert.AreEqual( 0, crc32.Value );
crc32 = new CRC32Checksum(1);
Assert.AreEqual( 1, crc32.Value );
crc32 = new CRC32Checksum(556);
Assert.AreEqual( 556, crc32.Value );
}
[Test]
public void CRC32_Data()
{
CRC32Checksum crc32 = new CRC32Checksum();
byte[] data = { 1,2,3,4,5,6,7 };
crc32.Update(data);
Assert.AreEqual( 0x70e46888, crc32.Value );
crc32 = new CRC32Checksum();
crc32.Update("penguin");
Assert.AreEqual( 0x0e5c1a120, crc32.Value );
crc32 = new CRC32Checksum(1);
crc32.Update("penguin");
Assert.AreEqual(0x43b6aa94, crc32.Value);
}
#endregion
#region Adler tests
[Test]
public void Adler_Null()
{
AdlerChecksum adler = new AdlerChecksum();
Assert.AreEqual(0, adler.Value);
adler = new AdlerChecksum(1);
Assert.AreEqual( 1, adler.Value );
adler = new AdlerChecksum(556);
Assert.AreEqual( 556, adler.Value );
}
[Test]
public void Adler_Data()
{
AdlerChecksum adler = new AdlerChecksum(1);
byte[] data = { 1,2,3,4,5,6,7 };
adler.Update(data);
Assert.AreEqual( 0x5b001d, adler.Value );
adler = new AdlerChecksum();
adler.Update("penguin");
Assert.AreEqual(0x0bcf02f6, adler.Value );
adler = new AdlerChecksum(1);
adler.Update("penguin");
Assert.AreEqual(0x0bd602f7, adler.Value);
}
#endregion
}
[TestFixture]
public class InfoTests
{
#region Info tests
[Test]
public void Info_Version()
{
Info info = new Info();
Assert.AreEqual("1.2.8", Info.Version);
Assert.AreEqual(32, info.SizeOfUInt);
Assert.AreEqual(32, info.SizeOfULong);
Assert.AreEqual(32, info.SizeOfPointer);
Assert.AreEqual(32, info.SizeOfOffset);
}
#endregion
}
[TestFixture]
public class DeflateInflateTests
{
#region Deflate tests
[Test]
public void Deflate_Init()
{
using (Deflater def = new Deflater(CompressLevel.Default))
{
}
}
private ArrayList compressedData = new ArrayList();
private uint adler1;
private ArrayList uncompressedData = new ArrayList();
private uint adler2;
public void CDataAvail(byte[] data, int startIndex, int count)
{
for (int i = 0; i < count; ++i)
compressedData.Add(data[i+startIndex]);
}
[Test]
public void Deflate_Compress()
{
compressedData.Clear();
byte[] testData = new byte[35000];
for (int i = 0; i < testData.Length; ++i)
testData[i] = 5;
using (Deflater def = new Deflater((CompressLevel)5))
{
def.DataAvailable += new DataAvailableHandler(CDataAvail);
def.Add(testData);
def.Finish();
adler1 = def.Checksum;
}
}
#endregion
#region Inflate tests
[Test]
public void Inflate_Init()
{
using (Inflater inf = new Inflater())
{
}
}
private void DDataAvail(byte[] data, int startIndex, int count)
{
for (int i = 0; i < count; ++i)
uncompressedData.Add(data[i+startIndex]);
}
[Test]
public void Inflate_Expand()
{
uncompressedData.Clear();
using (Inflater inf = new Inflater())
{
inf.DataAvailable += new DataAvailableHandler(DDataAvail);
inf.Add((byte[])compressedData.ToArray(typeof(byte)));
inf.Finish();
adler2 = inf.Checksum;
}
Assert.AreEqual( adler1, adler2 );
}
#endregion
}
[TestFixture]
public class GZipStreamTests
{
#region GZipStream test
[Test]
public void GZipStream_WriteRead()
{
using (GZipStream gzOut = new GZipStream("gzstream.gz", CompressLevel.Best))
{
BinaryWriter writer = new BinaryWriter(gzOut);
writer.Write("hi there");
writer.Write(Math.PI);
writer.Write(42);
}
using (GZipStream gzIn = new GZipStream("gzstream.gz"))
{
BinaryReader reader = new BinaryReader(gzIn);
string s = reader.ReadString();
Assert.AreEqual("hi there",s);
double d = reader.ReadDouble();
Assert.AreEqual(Math.PI, d);
int i = reader.ReadInt32();
Assert.AreEqual(42,i);
}
}
#endregion
}
}
#endif
| 275 |
websockify | openai | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace MELT_Command_Websocket
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
}
| 25 |
websockify | openai | C# | using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
namespace MELT_Command_Websocket
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
}
}
| 20 |
websockify | openai | C# | namespace MELT_Command_Websocket
{
partial class ProjectInstaller
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller1
//
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.NetworkService;
this.serviceProcessInstaller1.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceInstaller1});
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
//
// serviceInstaller1
//
this.serviceInstaller1.Description = "noVNC Websocket Service";
this.serviceInstaller1.DisplayName = "noVNC Websocket Service";
this.serviceInstaller1.ServiceName = "noVNC Websocket Service";
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1});
}
#endregion
private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller serviceInstaller1;
}
} | 61 |
websockify | openai | C# | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
namespace MELT_Command_Websocket
{
public partial class Service1 : ServiceBase
{
Process websockify;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
string configpath = AppDomain.CurrentDomain.BaseDirectory + "\\noVNCConfig.ini";
string sockifypath = AppDomain.CurrentDomain.BaseDirectory + "\\websockify.exe";
//Load commandline arguements from config file.
StreamReader streamReader = new StreamReader(configpath);
string arguements = streamReader.ReadLine();
streamReader.Close();
//Start websockify.
websockify = System.Diagnostics.Process.Start(sockifypath, arguements);
}
protected override void OnStop()
{
//Service stopped. Close websockify.
websockify.Kill();
}
}
}
| 42 |
websockify | openai | C# | namespace MELT_Command_Websocket
{
partial class Service1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
#endregion
}
}
| 38 |
websockify | openai | C# | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MELT Command Websocket")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("MELT Command Websocket")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5ab831cb-6852-4ce1-849c-b26725b0e10b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Numerics;
namespace Algorithms;
public static class NewtonSquareRoot
{
public static BigInteger Calculate(BigInteger number)
{
if (number < 0)
{
throw new ArgumentException("Cannot calculate the square root of a negative number.");
}
if (number == 0)
{
return BigInteger.Zero;
}
var bitLength = Convert.ToInt32(Math.Ceiling(BigInteger.Log(number, 2)));
BigInteger root = BigInteger.One << (bitLength / 2);
while (!IsSquareRoot(number, root))
{
root += number / root;
root /= 2;
}
return root;
}
private static bool IsSquareRoot(BigInteger number, BigInteger root)
{
var lowerBound = root * root;
return number >= lowerBound && number <= lowerBound + root + root;
}
}
| 38 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Linq;
namespace Algorithms.DataCompression
{
/// <summary>
/// The Burrows–Wheeler transform (BWT) rearranges a character string into runs of similar characters.
/// This is useful for compression, since it tends to be easy to compress a string that has runs of repeated
/// characters.
/// See <a href="https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform">here</a> for more info.
/// </summary>
public class BurrowsWheelerTransform
{
/// <summary>
/// Encodes the input string using BWT and returns encoded string and the index of original string in the sorted
/// rotation matrix.
/// </summary>
/// <param name="s">Input string.</param>
public (string encoded, int index) Encode(string s)
{
if (s.Length == 0)
{
return (string.Empty, 0);
}
var rotations = GetRotations(s);
Array.Sort(rotations, StringComparer.Ordinal);
var lastColumn = rotations
.Select(x => x[^1])
.ToArray();
var encoded = new string(lastColumn);
return (encoded, Array.IndexOf(rotations, s));
}
/// <summary>
/// Decodes the input string and returns original string.
/// </summary>
/// <param name="s">Encoded string.</param>
/// <param name="index">Index of original string in the sorted rotation matrix.</param>
public string Decode(string s, int index)
{
if (s.Length == 0)
{
return string.Empty;
}
var rotations = new string[s.Length];
for (var i = 0; i < s.Length; i++)
{
for (var j = 0; j < s.Length; j++)
{
rotations[j] = s[j] + rotations[j];
}
Array.Sort(rotations, StringComparer.Ordinal);
}
return rotations[index];
}
private string[] GetRotations(string s)
{
var result = new string[s.Length];
for (var i = 0; i < s.Length; i++)
{
result[i] = s.Substring(i) + s.Substring(0, i);
}
return result;
}
}
}
| 75 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Linq;
using Algorithms.Sorters.Comparison;
using Utilities.Extensions;
namespace Algorithms.DataCompression
{
/// <summary>
/// Greedy lossless compression algorithm.
/// </summary>
public class HuffmanCompressor
{
// TODO: Use partial sorter
private readonly IComparisonSorter<ListNode> sorter;
private readonly Translator translator;
public HuffmanCompressor(IComparisonSorter<ListNode> sorter, Translator translator)
{
this.sorter = sorter;
this.translator = translator;
}
/// <summary>
/// Given an input string, returns a new compressed string
/// using huffman encoding.
/// </summary>
/// <param name="uncompressedText">Text message to compress.</param>
/// <returns>Compressed string and keys to decompress it.</returns>
public (string compressedText, Dictionary<string, string> decompressionKeys) Compress(string uncompressedText)
{
if (string.IsNullOrEmpty(uncompressedText))
{
return (string.Empty, new Dictionary<string, string>());
}
if (uncompressedText.Distinct().Count() == 1)
{
var dict = new Dictionary<string, string>
{
{ "1", uncompressedText[0].ToString() },
};
return (new string('1', uncompressedText.Length), dict);
}
var nodes = GetListNodesFromText(uncompressedText);
var tree = GenerateHuffmanTree(nodes);
var (compressionKeys, decompressionKeys) = GetKeys(tree);
return (translator.Translate(uncompressedText, compressionKeys), decompressionKeys);
}
/// <summary>
/// Finds frequency for each character in the text.
/// </summary>
/// <returns>Symbol-frequency array.</returns>
private static ListNode[] GetListNodesFromText(string text)
{
var occurenceCounts = new Dictionary<char, int>();
foreach (var ch in text)
{
if (!occurenceCounts.ContainsKey(ch))
{
occurenceCounts.Add(ch, 0);
}
occurenceCounts[ch]++;
}
return occurenceCounts.Select(kvp => new ListNode(kvp.Key, 1d * kvp.Value / text.Length)).ToArray();
}
private (Dictionary<string, string> compressionKeys, Dictionary<string, string> decompressionKeys) GetKeys(
ListNode tree)
{
var compressionKeys = new Dictionary<string, string>();
var decompressionKeys = new Dictionary<string, string>();
if (tree.HasData)
{
compressionKeys.Add(tree.Data.ToString(), string.Empty);
decompressionKeys.Add(string.Empty, tree.Data.ToString());
return (compressionKeys, decompressionKeys);
}
if (tree.LeftChild is not null)
{
var (lsck, lsdk) = GetKeys(tree.LeftChild);
compressionKeys.AddMany(lsck.Select(kvp => (kvp.Key, "0" + kvp.Value)));
decompressionKeys.AddMany(lsdk.Select(kvp => ("0" + kvp.Key, kvp.Value)));
}
if (tree.RightChild is not null)
{
var (rsck, rsdk) = GetKeys(tree.RightChild);
compressionKeys.AddMany(rsck.Select(kvp => (kvp.Key, "1" + kvp.Value)));
decompressionKeys.AddMany(rsdk.Select(kvp => ("1" + kvp.Key, kvp.Value)));
return (compressionKeys, decompressionKeys);
}
return (compressionKeys, decompressionKeys);
}
private ListNode GenerateHuffmanTree(ListNode[] nodes)
{
var comparer = new ListNodeComparer();
while (nodes.Length > 1)
{
sorter.Sort(nodes, comparer);
var left = nodes[0];
var right = nodes[1];
var newNodes = new ListNode[nodes.Length - 1];
Array.Copy(nodes, 2, newNodes, 1, nodes.Length - 2);
newNodes[0] = new ListNode(left, right);
nodes = newNodes;
}
return nodes[0];
}
/// <summary>
/// Represents tree structure for the algorithm.
/// </summary>
public class ListNode
{
public ListNode(char data, double frequency)
{
HasData = true;
Data = data;
Frequency = frequency;
}
public ListNode(ListNode leftChild, ListNode rightChild)
{
LeftChild = leftChild;
RightChild = rightChild;
Frequency = leftChild.Frequency + rightChild.Frequency;
}
public char Data { get; }
public bool HasData { get; }
public double Frequency { get; }
public ListNode? RightChild { get; }
public ListNode? LeftChild { get; }
}
public class ListNodeComparer : IComparer<ListNode>
{
public int Compare(ListNode? x, ListNode? y)
{
if (x is null || y is null)
{
return 0;
}
return x.Frequency.CompareTo(y.Frequency);
}
}
}
}
| 168 |
C-Sharp | TheAlgorithms | C# | using System.Collections.Generic;
using System.Linq;
using Algorithms.Knapsack;
using Utilities.Extensions;
namespace Algorithms.DataCompression
{
/// <summary>
/// Greedy lossless compression algorithm.
/// </summary>
public class ShannonFanoCompressor
{
private readonly IHeuristicKnapsackSolver<(char symbol, double frequency)> splitter;
private readonly Translator translator;
public ShannonFanoCompressor(
IHeuristicKnapsackSolver<(char symbol, double frequency)> splitter,
Translator translator)
{
this.splitter = splitter;
this.translator = translator;
}
/// <summary>
/// Given an input string, returns a new compressed string
/// using Shannon-Fano encoding.
/// </summary>
/// <param name="uncompressedText">Text message to compress.</param>
/// <returns>Compressed string and keys to decompress it.</returns>
public (string compressedText, Dictionary<string, string> decompressionKeys) Compress(string uncompressedText)
{
if (string.IsNullOrEmpty(uncompressedText))
{
return (string.Empty, new Dictionary<string, string>());
}
if (uncompressedText.Distinct().Count() == 1)
{
var dict = new Dictionary<string, string>
{
{ "1", uncompressedText[0].ToString() },
};
return (new string('1', uncompressedText.Length), dict);
}
var node = GetListNodeFromText(uncompressedText);
var tree = GenerateShannonFanoTree(node);
var (compressionKeys, decompressionKeys) = GetKeys(tree);
return (translator.Translate(uncompressedText, compressionKeys), decompressionKeys);
}
private (Dictionary<string, string> compressionKeys, Dictionary<string, string> decompressionKeys) GetKeys(
ListNode tree)
{
var compressionKeys = new Dictionary<string, string>();
var decompressionKeys = new Dictionary<string, string>();
if (tree.Data.Length == 1)
{
compressionKeys.Add(tree.Data[0].symbol.ToString(), string.Empty);
decompressionKeys.Add(string.Empty, tree.Data[0].symbol.ToString());
return (compressionKeys, decompressionKeys);
}
if (tree.LeftChild is not null)
{
var (lsck, lsdk) = GetKeys(tree.LeftChild);
compressionKeys.AddMany(lsck.Select(kvp => (kvp.Key, "0" + kvp.Value)));
decompressionKeys.AddMany(lsdk.Select(kvp => ("0" + kvp.Key, kvp.Value)));
}
if (tree.RightChild is not null)
{
var (rsck, rsdk) = GetKeys(tree.RightChild);
compressionKeys.AddMany(rsck.Select(kvp => (kvp.Key, "1" + kvp.Value)));
decompressionKeys.AddMany(rsdk.Select(kvp => ("1" + kvp.Key, kvp.Value)));
}
return (compressionKeys, decompressionKeys);
}
private ListNode GenerateShannonFanoTree(ListNode node)
{
if (node.Data.Length == 1)
{
return node;
}
var left = splitter.Solve(node.Data, 0.5 * node.Data.Sum(x => x.frequency), x => x.frequency, _ => 1);
var right = node.Data.Except(left).ToArray();
node.LeftChild = GenerateShannonFanoTree(new ListNode(left));
node.RightChild = GenerateShannonFanoTree(new ListNode(right));
return node;
}
/// <summary>
/// Finds frequency for each character in the text.
/// </summary>
/// <returns>Symbol-frequency array.</returns>
private ListNode GetListNodeFromText(string text)
{
var occurenceCounts = new Dictionary<char, double>();
for (var i = 0; i < text.Length; i++)
{
var ch = text[i];
if (!occurenceCounts.ContainsKey(ch))
{
occurenceCounts.Add(ch, 0);
}
occurenceCounts[ch]++;
}
return new ListNode(occurenceCounts.Select(kvp => (kvp.Key, 1d * kvp.Value / text.Length)).ToArray());
}
/// <summary>
/// Represents tree structure for the algorithm.
/// </summary>
public class ListNode
{
public ListNode((char symbol, double frequency)[] data) => Data = data;
public (char symbol, double frequency)[] Data { get; }
public ListNode? RightChild { get; set; }
public ListNode? LeftChild { get; set; }
}
}
}
| 135 |
C-Sharp | TheAlgorithms | C# | using System.Collections.Generic;
using System.Text;
namespace Algorithms.DataCompression
{
/// <summary>
/// TODO.
/// </summary>
public class Translator
{
/// <summary>
/// TODO.
/// </summary>
/// <param name="text">TODO. 2.</param>
/// <param name="translationKeys">TODO. 3.</param>
/// <returns>TODO. 4.</returns>
public string Translate(string text, Dictionary<string, string> translationKeys)
{
var sb = new StringBuilder();
var start = 0;
for (var i = 0; i < text.Length; i++)
{
var key = text.Substring(start, i - start + 1);
if (translationKeys.ContainsKey(key))
{
_ = sb.Append(translationKeys[key]);
start = i + 1;
}
}
return sb.ToString();
}
}
}
| 36 |
C-Sharp | TheAlgorithms | C# | using System.Text;
namespace Algorithms.Encoders
{
/// <summary>
/// Encodes using caesar cypher.
/// </summary>
public class CaesarEncoder : IEncoder<int>
{
/// <summary>
/// Encodes text using specified key,
/// time complexity: O(n),
/// space complexity: O(n),
/// where n - text length.
/// </summary>
/// <param name="text">Text to be encoded.</param>
/// <param name="key">Key that will be used to encode the text.</param>
/// <returns>Encoded text.</returns>
public string Encode(string text, int key) => Cipher(text, key);
/// <summary>
/// Decodes text that was encoded using specified key,
/// time complexity: O(n),
/// space complexity: O(n),
/// where n - text length.
/// </summary>
/// <param name="text">Text to be decoded.</param>
/// <param name="key">Key that was used to encode the text.</param>
/// <returns>Decoded text.</returns>
public string Decode(string text, int key) => Cipher(text, -key);
private static string Cipher(string text, int key)
{
var newText = new StringBuilder(text.Length);
for (var i = 0; i < text.Length; i++)
{
if (!char.IsLetter(text[i]))
{
_ = newText.Append(text[i]);
continue;
}
var letterA = char.IsUpper(text[i]) ? 'A' : 'a';
var letterZ = char.IsUpper(text[i]) ? 'Z' : 'z';
var c = text[i] + key;
c -= c > letterZ ? 26 * (1 + (c - letterZ - 1) / 26) : 0;
c += c < letterA ? 26 * (1 + (letterA - c - 1) / 26) : 0;
_ = newText.Append((char)c);
}
return newText.ToString();
}
}
}
| 57 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Text;
namespace Algorithms.Encoders
{
/// <summary>
/// Encodes using Feistel cipher.
/// https://en.wikipedia.org/wiki/Feistel_cipher
/// In cryptography, a Feistel cipher (also known as Luby–Rackoff block cipher)
/// is a symmetric structure used in the construction of block ciphers,
/// named after the German-born physicist and cryptographer Horst Feistel
/// who did pioneering research while working for IBM (USA)
/// A large proportion of block ciphers use the scheme, including the US DES,
/// the Soviet/Russian GOST and the more recent Blowfish and Twofish ciphers.
/// </summary>
public class FeistelCipher : IEncoder<uint>
{
// number of rounds to transform data block, each round a new "round" key is generated.
private const int Rounds = 32;
/// <summary>
/// Encodes text using specified key,
/// where n - text length.
/// </summary>
/// <param name="text">Text to be encoded.</param>
/// <param name="key">Key that will be used to encode the text.</param>
/// <exception cref="ArgumentException">Error: key should be more than 0x00001111 for better encoding, key=0 will throw DivideByZero exception.</exception>
/// <returns>Encoded text.</returns>
public string Encode(string text, uint key)
{
List<ulong> blocksListPlain = SplitTextToBlocks(text);
StringBuilder encodedText = new();
foreach (ulong block in blocksListPlain)
{
uint temp = 0;
// decompose a block to two subblocks 0x0123456789ABCDEF => 0x01234567 & 0x89ABCDEF
uint rightSubblock = (uint)(block & 0x00000000FFFFFFFF);
uint leftSubblock = (uint)(block >> 32);
uint roundKey;
// Feistel "network" itself
for (int round = 0; round < Rounds; round++)
{
roundKey = GetRoundKey(key, round);
temp = rightSubblock ^ BlockModification(leftSubblock, roundKey);
rightSubblock = leftSubblock;
leftSubblock = temp;
}
// compile text string formating the block value to text (hex based), length of the output = 16 byte always
ulong encodedBlock = leftSubblock;
encodedBlock = (encodedBlock << 32) | rightSubblock;
encodedText.Append(string.Format("{0:X16}", encodedBlock));
}
return encodedText.ToString();
}
/// <summary>
/// Decodes text that was encoded using specified key.
/// </summary>
/// <param name="text">Text to be decoded.</param>
/// <param name="key">Key that was used to encode the text.</param>
/// <exception cref="ArgumentException">Error: key should be more than 0x00001111 for better encoding, key=0 will throw DivideByZero exception.</exception>
/// <exception cref="ArgumentException">Error: The length of text should be divisible by 16 as it the block lenght is 16 bytes.</exception>
/// <returns>Decoded text.</returns>
public string Decode(string text, uint key)
{
// The plain text will be padded to fill the size of block (16 bytes)
if (text.Length % 16 != 0)
{
throw new ArgumentException($"The length of {nameof(key)} should be divisible by 16");
}
List<ulong> blocksListEncoded = GetBlocksFromEncodedText(text);
StringBuilder decodedTextHex = new();
foreach (ulong block in blocksListEncoded)
{
uint temp = 0;
// decompose a block to two subblocks 0x0123456789ABCDEF => 0x01234567 & 0x89ABCDEF
uint rightSubblock = (uint)(block & 0x00000000FFFFFFFF);
uint leftSubblock = (uint)(block >> 32);
// Feistel "network" - decoding, the order of rounds and operations on the blocks is reverted
uint roundKey;
for (int round = Rounds - 1; round >= 0; round--)
{
roundKey = GetRoundKey(key, round);
temp = leftSubblock ^ BlockModification(rightSubblock, roundKey);
leftSubblock = rightSubblock;
rightSubblock = temp;
}
// compose decoded block
ulong decodedBlock = leftSubblock;
decodedBlock = (decodedBlock << 32) | rightSubblock;
for(int i = 0; i < 8; i++)
{
ulong a = (decodedBlock & 0xFF00000000000000) >> 56;
// it's a trick, the code works with non zero characters, if your text has ASCII code 0x00 it will be skipped.
if (a != 0)
{
decodedTextHex.Append((char)a);
}
decodedBlock = decodedBlock << 8;
}
}
return decodedTextHex.ToString();
}
// Using the size of block = 8 bytes this function splts the text and returns set of 8 bytes (ulong) blocks
// the last block is extended up to 8 bytes if the tail of the text is smaller than 8 bytes
private static List<ulong> SplitTextToBlocks(string text)
{
List<ulong> blocksListPlain = new();
byte[] textArray = Encoding.ASCII.GetBytes(text);
int offset = 8;
for(int i = 0; i < text.Length; i += 8)
{
// text not always has len%16 == 0, that's why the offset should be adjusted for the last part of the text
if (i > text.Length - 8)
{
offset = text.Length - i;
}
string block = Convert.ToHexString(textArray, i, offset);
blocksListPlain.Add(Convert.ToUInt64(block, 16));
}
return blocksListPlain;
}
// convert the encoded text to the set of ulong values (blocks for decoding)
private static List<ulong> GetBlocksFromEncodedText(string text)
{
List<ulong> blocksListPlain = new();
for(int i = 0; i < text.Length; i += 16)
{
ulong block = Convert.ToUInt64(text.Substring(i, 16), 16);
blocksListPlain.Add(block);
}
return blocksListPlain;
}
// here might be any deterministic math formula
private static uint BlockModification(uint block, uint key)
{
for (int i = 0; i < 32; i++)
{
// 0x55555555 for the better distribution 0 an 1 in the block
block = ((block ^ 0x55555555) * block) % key;
block = block ^ key;
}
return block;
}
// There are many ways to generate a round key, any deterministic math formula does work
private static uint GetRoundKey(uint key, int round)
{
// "round + 2" - to avoid a situation when pow(key,1) ^ key = key ^ key = 0
uint a = (uint)Math.Pow((double)key, round + 2);
return a ^ key;
}
}
}
| 178 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Linq;
using Algorithms.Numeric;
namespace Algorithms.Encoders
{
/// <summary>
/// Lester S. Hill's polygraphic substitution cipher,
/// without representing letters using mod26, using
/// corresponding "(char)value" instead.
/// </summary>
public class HillEncoder : IEncoder<double[,]>
{
private readonly GaussJordanElimination linearEquationSolver;
public HillEncoder() => linearEquationSolver = new GaussJordanElimination(); // TODO: add DI
public string Encode(string text, double[,] key)
{
var preparedText = FillGaps(text);
var chunked = ChunkTextToArray(preparedText);
var splitted = SplitToCharArray(chunked);
var ciphered = new double[chunked.Length][];
for (var i = 0; i < chunked.Length; i++)
{
var vector = new double[3];
Array.Copy(splitted, i * 3, vector, 0, 3);
var product = MatrixCipher(vector, key);
ciphered[i] = product;
}
var merged = MergeArrayList(ciphered);
return BuildStringFromArray(merged);
}
public string Decode(string text, double[,] key)
{
var chunked = ChunkTextToArray(text);
var split = SplitToCharArray(chunked);
var deciphered = new double[chunked.Length][];
for (var i = 0; i < chunked.Length; i++)
{
var vector = new double[3];
Array.Copy(split, i * 3, vector, 0, 3);
var product = MatrixDeCipher(vector, key);
deciphered[i] = product;
}
var merged = MergeArrayList(deciphered);
var str = BuildStringFromArray(merged);
return UnFillGaps(str);
}
/// <summary>
/// Converts elements from the array to their corresponding Unicode characters.
/// </summary>
/// <param name="arr">array of vectors.</param>
/// <returns>Message.</returns>
private static string BuildStringFromArray(double[] arr) => new(arr.Select(c => (char)c).ToArray());
/// <summary>
/// Multiplies the key for the given scalar.
/// </summary>
/// <param name="vector">list of splitted words as numbers.</param>
/// <param name="key">Cipher selected key.</param>
/// <returns>Ciphered vector.</returns>
private static double[] MatrixCipher(double[] vector, double[,] key)
{
var multiplied = new double[vector.Length];
for (var i = 0; i < key.GetLength(1); i++)
{
for (var j = 0; j < key.GetLength(0); j++)
{
multiplied[i] += key[i, j] * vector[j];
}
}
return multiplied;
}
/// <summary>
/// Given a list of vectors, returns a single array of elements.
/// </summary>
/// <param name="list">List of ciphered arrays.</param>
/// <returns>unidimensional list.</returns>
private static double[] MergeArrayList(double[][] list)
{
var merged = new double[list.Length * 3];
for (var i = 0; i < list.Length; i++)
{
Array.Copy(list[i], 0, merged, i * 3, list[0].Length);
}
return merged;
}
/// <summary>
/// Splits the input text message as chunks of words.
/// </summary>
/// <param name="chunked">chunked words list.</param>
/// <returns>spliiter char array.</returns>
private static char[] SplitToCharArray(string[] chunked)
{
var splitted = new char[chunked.Length * 3];
for (var i = 0; i < chunked.Length; i++)
{
for (var j = 0; j < 3; j++)
{
splitted[i * 3 + j] = chunked[i].ToCharArray()[j];
}
}
return splitted;
}
/// <summary>
/// Chunks the input text message.
/// </summary>
/// <param name="text">text message.</param>
/// <returns>array of words.</returns>
private static string[] ChunkTextToArray(string text)
{
// To split the message into chunks
var div = text.Length / 3;
var chunks = new string[div];
for (var i = 0; i < div; i++)
{
chunks.SetValue(text.Substring(i * 3, 3), i);
}
return chunks;
}
/// <summary>
/// Fills a text message with spaces at the end
/// to enable a simple split by 3-length-word.
/// </summary>
/// <param name="text">Text Message.</param>
/// <returns>Modified text Message.</returns>
private static string FillGaps(string text)
{
var remainder = text.Length % 3;
return remainder == 0 ? text : text + new string(' ', 3 - remainder);
}
/// <summary>
/// Removes the extra spaces included on the cipher phase.
/// </summary>
/// <param name="text">Text message.</param>
/// <returns>Deciphered Message.</returns>
private static string UnFillGaps(string text) => text.TrimEnd();
/// <summary>
/// Finds the inverse of the given matrix using a linear equation solver.
/// </summary>
/// <param name="vector">Splitted words vector.</param>
/// <param name="key">Key used for the cipher.</param>
/// <returns>TODO.</returns>
private double[] MatrixDeCipher(double[] vector, double[,] key)
{
// To augment the original key with the given vector.
var augM = new double[3, 4];
for (var i = 0; i < key.GetLength(0); i++)
{
for (var j = 0; j < key.GetLength(1); j++)
{
augM[i, j] = key[i, j];
}
}
for (var k = 0; k < vector.Length; k++)
{
augM[k, 3] = vector[k];
}
_ = linearEquationSolver.Solve(augM);
return new[] { augM[0, 3], augM[1, 3], augM[2, 3] };
}
}
}
| 193 |
C-Sharp | TheAlgorithms | C# | namespace Algorithms.Encoders
{
/// <summary>
/// Encodes and decodes text based on specified key.
/// </summary>
/// <typeparam name="TKey">Type of the key.</typeparam>
public interface IEncoder<TKey>
{
/// <summary>
/// Encodes text using specified key.
/// </summary>
/// <param name="text">Text to be encoded.</param>
/// <param name="key">Key that will be used to encode the text.</param>
/// <returns>Encoded text.</returns>
string Encode(string text, TKey key);
/// <summary>
/// Decodes text that was encoded using specified key.
/// </summary>
/// <param name="text">Text to be decoded.</param>
/// <param name="key">Key that was used to encode the text.</param>
/// <returns>Decoded text.</returns>
string Decode(string text, TKey key);
}
}
| 26 |
C-Sharp | TheAlgorithms | C# | using System.Globalization;
using System.Linq;
using System.Text;
namespace Algorithms.Encoders
{
/// <summary>
/// Class for NYSIIS encoding strings.
/// </summary>
public class NysiisEncoder
{
private static readonly char[] Vowels = { 'A', 'E', 'I', 'O', 'U' };
/// <summary>
/// Encodes a string using the NYSIIS Algorithm.
/// </summary>
/// <param name="text">The string to encode.</param>
/// <returns>The NYSIIS encoded string (all uppercase).</returns>
public string Encode(string text)
{
text = text.ToUpper(CultureInfo.CurrentCulture);
text = TrimSpaces(text);
text = StartReplace(text);
text = EndReplace(text);
for (var i = 1; i < text.Length; i++)
{
text = ReplaceStep(text, i);
}
text = RemoveDuplicates(text);
return TrimEnd(text);
}
private string TrimSpaces(string text) => text.Replace(" ", string.Empty);
private string RemoveDuplicates(string text)
{
var sb = new StringBuilder();
sb.Append(text[0]);
foreach (var c in text)
{
if (sb[^1] != c)
{
sb.Append(c);
}
}
return sb.ToString();
}
private string TrimEnd(string text)
{
var checks = new (string from, string to)?[]
{
("S", string.Empty),
("AY", "Y"),
("A", string.Empty),
};
var replacement = checks.FirstOrDefault(t => text.EndsWith(t!.Value.from));
if (replacement is { })
{
var (from, to) = replacement!.Value;
text = Replace(text, text.Length - from.Length, from.Length, to);
}
return text;
}
private string ReplaceStep(string text, int i)
{
(string from, string to)[] replacements =
{
("EV", "AF"),
("E", "A"),
("I", "A"),
("O", "A"),
("U", "A"),
("Q", "G"),
("Z", "S"),
("M", "N"),
("KN", "NN"),
("K", "C"),
("SCH", "SSS"),
("PH", "FF"),
};
var replaced = TryReplace(text, i, replacements, out text);
if (replaced)
{
return text;
}
// H[vowel] or [vowel]H -> text[i-1]
if (text[i] == 'H')
{
if (!Vowels.Contains(text[i - 1]))
{
return ReplaceWithPrevious();
}
if (i < text.Length - 1 && !Vowels.Contains(text[i + 1]))
{
return ReplaceWithPrevious();
}
}
// [vowel]W -> [vowel]
if (text[i] == 'W' && Vowels.Contains(text[i - 1]))
{
return ReplaceWithPrevious();
}
return text;
string ReplaceWithPrevious() => Replace(text, i, 1, text[i - 1].ToString());
}
private bool TryReplace(string text, int index, (string, string)[] opts, out string result)
{
for (var i = 0; i < opts.Length; i++)
{
var check = opts[i].Item1;
var repl = opts[i].Item2;
if (text.Length >= index + check.Length && text.Substring(index, check.Length) == check)
{
result = Replace(text, index, check.Length, repl);
return true;
}
}
result = text;
return false;
}
private string StartReplace(string start)
{
var checks = new (string from, string to)?[]
{
("MAC", "MCC"),
("KN", "NN"),
("K", "C"),
("PH", "FF"),
("PF", "FF"),
("SCH", "SSS"),
};
var replacement = checks.FirstOrDefault(t => start.StartsWith(t!.Value.from));
if (replacement is { })
{
var (from, to) = replacement!.Value;
start = Replace(start, 0, from.Length, to);
}
return start;
}
private string EndReplace(string end)
{
var checks = new (string from, string to)?[]
{
("EE", "Y"),
("IE", "Y"),
("DT", "D"),
("RT", "D"),
("NT", "D"),
("ND", "D"),
};
var replacement = checks.FirstOrDefault(t => end.EndsWith(t!.Value.from));
if (replacement is { })
{
var (from, to) = replacement!.Value;
end = Replace(end, end.Length - from.Length, from.Length, to);
}
return end;
}
private string Replace(string text, int index, int length, string substitute) =>
text[..index] + substitute + text[(index + length) ..];
}
}
| 181 |
C-Sharp | TheAlgorithms | C# | using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Encoders
{
/// <summary>
/// Class for Soundex encoding strings.
/// </summary>
public class SoundexEncoder
{
/// <summary>
/// Encodes a string using the Soundex Algorithm.
/// </summary>
/// <param name="text">The string to encode.</param>
/// <returns>The Soundex encoded string (one uppercase character and three digits).</returns>
public string Encode(string text)
{
text = text.ToLowerInvariant();
var chars = OmitHAndW(text);
IEnumerable<int> numbers = ProduceNumberCoding(chars);
numbers = CollapseDoubles(numbers);
numbers = OmitVowels(numbers);
numbers = CollapseLeadingDigit(numbers, text[0]);
numbers = numbers.Take(3);
numbers = PadTo3Numbers(numbers);
var final = numbers.ToArray();
return $"{text.ToUpperInvariant()[0]}{final[0]}{final[1]}{final[2]}";
}
private IEnumerable<int> CollapseLeadingDigit(IEnumerable<int> numbers, char c)
{
using var enumerator = numbers.GetEnumerator();
enumerator.MoveNext();
if (enumerator.Current == MapToNumber(c))
{
enumerator.MoveNext();
}
do
{
yield return enumerator.Current;
}
while (enumerator.MoveNext());
}
private IEnumerable<int> PadTo3Numbers(IEnumerable<int> numbers)
{
using var enumerator = numbers.GetEnumerator();
for (var i = 0; i < 3; i++)
{
yield return enumerator.MoveNext()
? enumerator.Current
: 0;
}
}
private IEnumerable<int> OmitVowels(IEnumerable<int> numbers) => numbers.Where(i => i != 0);
private IEnumerable<char> OmitHAndW(string text) => text.Where(c => c != 'h' && c != 'w');
private IEnumerable<int> CollapseDoubles(IEnumerable<int> numbers)
{
var previous = int.MinValue;
foreach (var i in numbers)
{
if (previous != i)
{
yield return i;
previous = i;
}
}
}
private IEnumerable<int> ProduceNumberCoding(IEnumerable<char> text) => text.Select(MapToNumber);
private int MapToNumber(char ch)
{
var mapping = new Dictionary<char, int>
{
['a'] = 0,
['e'] = 0,
['i'] = 0,
['o'] = 0,
['u'] = 0,
['y'] = 0,
['h'] = 8,
['w'] = 8,
['b'] = 1,
['f'] = 1,
['p'] = 1,
['v'] = 1,
['c'] = 2,
['g'] = 2,
['j'] = 2,
['k'] = 2,
['q'] = 2,
['s'] = 2,
['x'] = 2,
['z'] = 2,
['d'] = 3,
['t'] = 3,
['l'] = 4,
['m'] = 5,
['n'] = 5,
['r'] = 6,
};
return mapping[ch];
}
}
}
| 112 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Text;
namespace Algorithms.Encoders
{
/// <summary>
/// Encodes using vigenere cypher.
/// </summary>
public class VigenereEncoder : IEncoder<string>
{
private readonly CaesarEncoder caesarEncoder = new();
/// <summary>
/// Encodes text using specified key,
/// time complexity: O(n),
/// space complexity: O(n),
/// where n - text length.
/// </summary>
/// <param name="text">Text to be encoded.</param>
/// <param name="key">Key that will be used to encode the text.</param>
/// <returns>Encoded text.</returns>
public string Encode(string text, string key) => Cipher(text, key, caesarEncoder.Encode);
/// <summary>
/// Decodes text that was encoded using specified key,
/// time complexity: O(n),
/// space complexity: O(n),
/// where n - text length.
/// </summary>
/// <param name="text">Text to be decoded.</param>
/// <param name="key">Key that was used to encode the text.</param>
/// <returns>Decoded text.</returns>
public string Decode(string text, string key) => Cipher(text, key, caesarEncoder.Decode);
private string Cipher(string text, string key, Func<string, int, string> symbolCipher)
{
key = AppendKey(key, text.Length);
var encodedTextBuilder = new StringBuilder(text.Length);
for (var i = 0; i < text.Length; i++)
{
if (!char.IsLetter(text[i]))
{
_ = encodedTextBuilder.Append(text[i]);
continue;
}
var letterZ = char.IsUpper(key[i]) ? 'Z' : 'z';
var encodedSymbol = symbolCipher(text[i].ToString(), letterZ - key[i]);
_ = encodedTextBuilder.Append(encodedSymbol);
}
return encodedTextBuilder.ToString();
}
private string AppendKey(string key, int length)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentOutOfRangeException($"{nameof(key)} must be non-empty string");
}
var keyBuilder = new StringBuilder(key, length);
while (keyBuilder.Length < length)
{
_ = keyBuilder.Append(key);
}
return keyBuilder.ToString();
}
}
}
| 72 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using DataStructures.Graph;
namespace Algorithms.Graph
{
/// <summary>
/// Breadth First Search - algorithm for traversing graph.
/// Algorithm starts from root node that is selected by the user.
/// Algorithm explores all nodes at the present depth.
/// </summary>
/// <typeparam name="T">Vertex data type.</typeparam>
public class BreadthFirstSearch<T> : IGraphSearch<T> where T : IComparable<T>
{
/// <summary>
/// Traverses graph from start vertex.
/// </summary>
/// <param name="graph">Graph instance.</param>
/// <param name="startVertex">Vertex that search starts from.</param>
/// <param name="action">Action that needs to be executed on each graph vertex.</param>
public void VisitAll(IDirectedWeightedGraph<T> graph, Vertex<T> startVertex, Action<Vertex<T>>? action = default)
{
Bfs(graph, startVertex, action, new HashSet<Vertex<T>>());
}
/// <summary>
/// Traverses graph from start vertex.
/// </summary>
/// <param name="graph">Graph instance.</param>
/// <param name="startVertex">Vertex that search starts from.</param>
/// <param name="action">Action that needs to be executed on each graph vertex.</param>
/// <param name="visited">Hash set with visited vertices.</param>
private void Bfs(IDirectedWeightedGraph<T> graph, Vertex<T> startVertex, Action<Vertex<T>>? action, HashSet<Vertex<T>> visited)
{
var queue = new Queue<Vertex<T>>();
queue.Enqueue(startVertex);
while (queue.Count > 0)
{
var currentVertex = queue.Dequeue();
if (currentVertex == null || visited.Contains(currentVertex))
{
continue;
}
foreach (var vertex in graph.GetNeighbors(currentVertex))
{
queue.Enqueue(vertex!);
}
action?.Invoke(currentVertex);
visited.Add(currentVertex);
}
}
}
}
| 60 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using DataStructures.BinarySearchTree;
namespace Algorithms.Graph
{
/// <summary>
/// Breadth first tree traversal traverses through a binary tree
/// by iterating through each level first.
/// time complexity: O(n).
/// space complexity: O(w) where w is the max width of a binary tree.
/// </summary>
/// <typeparam name="TKey">Type of key held in binary search tree.</typeparam>
public static class BreadthFirstTreeTraversal<TKey>
{
/// <summary>
/// Level Order Traversal returns an array of integers in order
/// of each level of a binary tree. It uses a queue to iterate
/// through each node following breadth first search traversal.
/// </summary>
/// <param name="tree">Passes the binary tree to traverse.</param>
/// <returns>Returns level order traversal.</returns>
public static TKey[] LevelOrderTraversal(BinarySearchTree<TKey> tree)
{
BinarySearchTreeNode<TKey>? root = tree.Root;
TKey[] levelOrder = new TKey[tree.Count];
if (root is null)
{
return Array.Empty<TKey>();
}
Queue<BinarySearchTreeNode<TKey>> breadthTraversal = new Queue<BinarySearchTreeNode<TKey>>();
breadthTraversal.Enqueue(root);
for (int i = 0; i < levelOrder.Length; i++)
{
BinarySearchTreeNode<TKey> current = breadthTraversal.Dequeue();
levelOrder[i] = current.Key;
if (current.Left is not null)
{
breadthTraversal.Enqueue(current.Left);
}
if (current.Right is not null)
{
breadthTraversal.Enqueue(current.Right);
}
}
return levelOrder;
}
/// <summary>
/// Deepest Node return the deepest node in a binary tree. If more
/// than one node is on the deepest level, it is defined as the
/// right-most node of a binary tree. Deepest node uses breadth
/// first traversal to reach the end.
/// </summary>
/// <param name="tree">Tree passed to find deepest node.</param>
/// <returns>Returns the deepest node in the tree.</returns>
public static TKey? DeepestNode(BinarySearchTree<TKey> tree)
{
BinarySearchTreeNode<TKey>? root = tree.Root;
if (root is null)
{
return default(TKey);
}
Queue<BinarySearchTreeNode<TKey>> breadthTraversal = new Queue<BinarySearchTreeNode<TKey>>();
breadthTraversal.Enqueue(root);
TKey deepest = root.Key;
while (breadthTraversal.Count > 0)
{
BinarySearchTreeNode<TKey> current = breadthTraversal.Dequeue();
if (current.Left is not null)
{
breadthTraversal.Enqueue(current.Left);
}
if (current.Right is not null)
{
breadthTraversal.Enqueue(current.Right);
}
deepest = current.Key;
}
return deepest;
}
}
}
| 91 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using DataStructures.Graph;
namespace Algorithms.Graph
{
/// <summary>
/// Depth First Search - algorithm for traversing graph.
/// Algorithm starts from root node that is selected by the user.
/// Algorithm explores as far as possible along each branch before backtracking.
/// </summary>
/// <typeparam name="T">Vertex data type.</typeparam>
public class DepthFirstSearch<T> : IGraphSearch<T> where T : IComparable<T>
{
/// <summary>
/// Traverses graph from start vertex.
/// </summary>
/// <param name="graph">Graph instance.</param>
/// <param name="startVertex">Vertex that search starts from.</param>
/// <param name="action">Action that needs to be executed on each graph vertex.</param>
public void VisitAll(IDirectedWeightedGraph<T> graph, Vertex<T> startVertex, Action<Vertex<T>>? action = default)
{
Dfs(graph, startVertex, action, new HashSet<Vertex<T>>());
}
/// <summary>
/// Traverses graph from start vertex.
/// </summary>
/// <param name="graph">Graph instance.</param>
/// <param name="startVertex">Vertex that search starts from.</param>
/// <param name="action">Action that needs to be executed on each graph vertex.</param>
/// <param name="visited">Hash set with visited vertices.</param>
private void Dfs(IDirectedWeightedGraph<T> graph, Vertex<T> startVertex, Action<Vertex<T>>? action, HashSet<Vertex<T>> visited)
{
action?.Invoke(startVertex);
visited.Add(startVertex);
foreach (var vertex in graph.GetNeighbors(startVertex))
{
if (vertex == null || visited.Contains(vertex))
{
continue;
}
Dfs(graph, vertex!, action, visited);
}
}
}
}
| 51 |
C-Sharp | TheAlgorithms | C# | using System;
using DataStructures.Graph;
namespace Algorithms.Graph
{
/// <summary>
/// Floyd Warshall algorithm on directed weighted graph.
/// </summary>
/// <typeparam name="T">generic type of data in graph.</typeparam>
public class FloydWarshall<T>
{
/// <summary>
/// runs the algorithm.
/// </summary>
/// <param name="graph">graph upon which to run.</param>
/// <returns>
/// a 2D array of shortest paths between any two vertices.
/// where there is no path between two vertices - double.PositiveInfinity is placed.
/// </returns>
public double[,] Run(DirectedWeightedGraph<T> graph)
{
var distances = SetupDistances(graph);
var vertexCount = distances.GetLength(0);
for (var k = 0; k < vertexCount; k++)
{
for (var i = 0; i < vertexCount; i++)
{
for (var j = 0; j < vertexCount; j++)
{
distances[i, j] = distances[i, j] > distances[i, k] + distances[k, j]
? distances[i, k] + distances[k, j]
: distances[i, j];
}
}
}
return distances;
}
/// <summary>
/// setup adjacency matrix for use by main algorithm run.
/// </summary>
/// <param name="graph">graph to dissect adjacency matrix from.</param>
/// <returns>the adjacency matrix in the format mentioned in Run.</returns>
private double[,] SetupDistances(DirectedWeightedGraph<T> graph)
{
var distances = new double[graph.Count, graph.Count];
for (int i = 0; i < distances.GetLength(0); i++)
{
for (var j = 0; j < distances.GetLength(0); j++)
{
var dist = graph.AdjacentDistance(graph.Vertices[i] !, graph.Vertices[j] !);
distances[i, j] = dist != 0 ? dist : double.PositiveInfinity;
}
}
for (var i = 0; i < distances.GetLength(0); i++)
{
distances[i, i] = 0;
}
return distances;
}
}
}
| 66 |
C-Sharp | TheAlgorithms | C# | using System;
using DataStructures.Graph;
namespace Algorithms.Graph
{
public interface IGraphSearch<T>
{
/// <summary>
/// Traverses graph from start vertex.
/// </summary>
/// <param name="graph">Graph instance.</param>
/// <param name="startVertex">Vertex that search starts from.</param>
/// <param name="action">Action that needs to be executed on each graph vertex.</param>
void VisitAll(IDirectedWeightedGraph<T> graph, Vertex<T> startVertex, Action<Vertex<T>>? action = null);
}
}
| 17 |
C-Sharp | TheAlgorithms | C# | using System.Collections.Generic;
using System.Linq;
using DataStructures.Graph;
namespace Algorithms.Graph
{
/// <summary>
/// Implementation of Kosaraju-Sharir's algorithm (also known as Kosaraju's algorithm) to find the
/// strongly connected components (SCC) of a directed graph.
/// See https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm.
/// </summary>
/// <typeparam name="T">Vertex data type.</typeparam>
public static class Kosaraju<T>
{
/// <summary>
/// First DFS for Kosaraju algorithm: traverse the graph creating a reverse order explore list <paramref name="reversed"/>.
/// </summary>
/// <param name="v">Vertex to explore.</param>
/// <param name="graph">Graph instance.</param>
/// <param name="visited">List of already visited vertex.</param>
/// <param name="reversed">Reversed list of vertex for the second DFS.</param>
public static void Visit(Vertex<T> v, IDirectedWeightedGraph<T> graph, HashSet<Vertex<T>> visited, Stack<Vertex<T>> reversed)
{
if (visited.Contains(v))
{
return;
}
// Set v as visited
visited.Add(v);
// Push v in the stack.
// This can also be done with a List, inserting v at the begining of the list
// after visit the neighbors.
reversed.Push(v);
// Visit neighbors
foreach (var u in graph.GetNeighbors(v))
{
Visit(u!, graph, visited, reversed);
}
}
/// <summary>
/// Second DFS for Kosaraju algorithm. Traverse the graph in reversed order
/// assigning a root vertex for every vertex that belong to the same SCC.
/// </summary>
/// <param name="v">Vertex to assign.</param>
/// <param name="root">Root vertext, representative of the SCC.</param>
/// <param name="graph">Graph with vertex and edges.</param>
/// <param name="roots">
/// Dictionary that assigns to each vertex the root of the SCC to which it corresponds.
/// </param>
public static void Assign(Vertex<T> v, Vertex<T> root, IDirectedWeightedGraph<T> graph, Dictionary<Vertex<T>, Vertex<T>> roots)
{
// If v already has a representative vertex (root) already assigned, do nothing.
if (roots.ContainsKey(v))
{
return;
}
// Assign the root to the vertex.
roots.Add(v, root);
// Assign the current root vertex to v neighbors.
foreach (var u in graph.GetNeighbors(v))
{
Assign(u!, root, graph, roots);
}
}
/// <summary>
/// Find the representative vertex of the SCC for each vertex on the graph.
/// </summary>
/// <param name="graph">Graph to explore.</param>
/// <returns>A dictionary that assigns to each vertex a root vertex of the SCC they belong. </returns>
public static Dictionary<Vertex<T>, Vertex<T>> GetRepresentatives(IDirectedWeightedGraph<T> graph)
{
HashSet<Vertex<T>> visited = new HashSet<Vertex<T>>();
Stack<Vertex<T>> reversedL = new Stack<Vertex<T>>();
Dictionary<Vertex<T>, Vertex<T>> representatives = new Dictionary<Vertex<T>, Vertex<T>>();
foreach (var v in graph.Vertices)
{
if (v != null)
{
Visit(v, graph, visited, reversedL);
}
}
visited.Clear();
while (reversedL.Count > 0)
{
Vertex<T> v = reversedL.Pop();
Assign(v, v, graph, representatives);
}
return representatives;
}
/// <summary>
/// Get the Strongly Connected Components for the graph.
/// </summary>
/// <param name="graph">Graph to explore.</param>
/// <returns>An array of SCC.</returns>
public static IEnumerable<Vertex<T>>[] GetScc(IDirectedWeightedGraph<T> graph)
{
var representatives = GetRepresentatives(graph);
Dictionary<Vertex<T>, List<Vertex<T>>> scc = new Dictionary<Vertex<T>, List<Vertex<T>>>();
foreach (var kv in representatives)
{
// Assign all vertex (key) that have the seem root (value) to a single list.
if (scc.ContainsKey(kv.Value))
{
scc[kv.Value].Add(kv.Key);
}
else
{
scc.Add(kv.Value, new List<Vertex<T>> { kv.Key });
}
}
return scc.Values.ToArray();
}
}
}
| 128 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Linq;
using DataStructures.Graph;
namespace Algorithms.Graph.Dijkstra
{
public static class DijkstraAlgorithm
{
/// <summary>
/// Implementation of the Dijkstra shortest path algorithm for cyclic graphs.
/// https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm.
/// </summary>
/// <param name="graph">Graph instance.</param>
/// <param name="startVertex">Starting vertex instance.</param>
/// <typeparam name="T">Generic Parameter.</typeparam>
/// <returns>List of distances from current vertex to all other vertices.</returns>
/// <exception cref="InvalidOperationException">Exception thrown in case when graph is null or start
/// vertex does not belong to graph instance.</exception>
public static DistanceModel<T>[] GenerateShortestPath<T>(DirectedWeightedGraph<T> graph, Vertex<T> startVertex)
{
ValidateGraphAndStartVertex(graph, startVertex);
var visitedVertices = new List<Vertex<T>>();
var distanceArray = InitializeDistanceArray(graph, startVertex);
var currentVertex = startVertex;
var currentPath = 0d;
while (true)
{
visitedVertices.Add(currentVertex);
var neighborVertices = graph
.GetNeighbors(currentVertex)
.Where(x => x != null && !visitedVertices.Contains(x))
.ToList();
foreach (var vertex in neighborVertices)
{
var adjacentDistance = graph.AdjacentDistance(currentVertex, vertex!);
var distance = distanceArray[vertex!.Index];
if (distance.Distance <= currentPath + adjacentDistance)
{
continue;
}
distance.Distance = currentPath + adjacentDistance;
distance.PreviousVertex = currentVertex;
}
var minimalAdjacentVertex = GetMinimalUnvisitedAdjacentVertex(graph, currentVertex, neighborVertices);
if (neighborVertices.Count == 0 || minimalAdjacentVertex is null)
{
break;
}
currentPath += graph.AdjacentDistance(currentVertex, minimalAdjacentVertex);
currentVertex = minimalAdjacentVertex;
}
return distanceArray;
}
private static DistanceModel<T>[] InitializeDistanceArray<T>(
IDirectedWeightedGraph<T> graph,
Vertex<T> startVertex)
{
var distArray = new DistanceModel<T>[graph.Count];
distArray[startVertex.Index] = new DistanceModel<T>(startVertex, startVertex, 0);
foreach (var vertex in graph.Vertices.Where(x => x != null && !x.Equals(startVertex)))
{
distArray[vertex!.Index] = new DistanceModel<T>(vertex, null, double.MaxValue);
}
return distArray;
}
private static void ValidateGraphAndStartVertex<T>(DirectedWeightedGraph<T> graph, Vertex<T> startVertex)
{
if (graph is null)
{
throw new ArgumentNullException(nameof(graph));
}
if (startVertex.Graph != null && !startVertex.Graph.Equals(graph))
{
throw new ArgumentNullException(nameof(graph));
}
}
private static Vertex<T>? GetMinimalUnvisitedAdjacentVertex<T>(
IDirectedWeightedGraph<T> graph,
Vertex<T> startVertex,
IEnumerable<Vertex<T>?> adjacentVertices)
{
var minDistance = double.MaxValue;
Vertex<T>? minVertex = default;
foreach (var vertex in adjacentVertices)
{
var currentDistance = graph.AdjacentDistance(startVertex, vertex!);
if (minDistance <= currentDistance)
{
continue;
}
minDistance = currentDistance;
minVertex = vertex;
}
return minVertex;
}
}
}
| 125 |
C-Sharp | TheAlgorithms | C# | using DataStructures.Graph;
namespace Algorithms.Graph.Dijkstra
{
/// <summary>
/// Entity which represents the Dijkstra shortest distance.
/// Contains: Vertex, Previous Vertex and minimal distance from start vertex.
/// </summary>
/// <typeparam name="T">Generic parameter.</typeparam>
public class DistanceModel<T>
{
public Vertex<T>? Vertex { get; }
public Vertex<T>? PreviousVertex { get; set; }
public double Distance { get; set; }
public DistanceModel(Vertex<T>? vertex, Vertex<T>? previousVertex, double distance)
{
Vertex = vertex;
PreviousVertex = previousVertex;
Distance = distance;
}
public override string ToString() =>
$"Vertex: {Vertex} - Distance: {Distance} - Previous: {PreviousVertex}";
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using DataStructures.DisjointSet;
namespace Algorithms.Graph.MinimumSpanningTree
{
/// <summary>
/// Algorithm to determine the minimum spanning forest of an undirected graph.
/// </summary>
/// <remarks>
/// Kruskal's algorithm is a greedy algorithm that can determine the
/// minimum spanning tree or minimum spanning forest of any undirected
/// graph. Unlike Prim's algorithm, Kruskal's algorithm will work on
/// graphs that are unconnected. This algorithm will always have a
/// running time of O(E log V) where E is the number of edges and V is
/// the number of vertices/nodes.
/// More information: https://en.wikipedia.org/wiki/Kruskal%27s_algorithm .
/// Pseudocode and analysis: https://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/GraphAlgor/primAlgor.htm .
/// </remarks>
public static class Kruskal
{
/// <summary>
/// Determine the minimum spanning tree/forest of the given graph.
/// </summary>
/// <param name="adjacencyMatrix">Adjacency matrix representing the graph.</param>
/// <returns>Adjacency matrix of the minimum spanning tree/forest.</returns>
public static float[,] Solve(float[,] adjacencyMatrix)
{
ValidateGraph(adjacencyMatrix);
var numNodes = adjacencyMatrix.GetLength(0);
var set = new DisjointSet<int>();
var nodes = new Node<int>[numNodes];
var edgeWeightList = new List<float>();
var nodeConnectList = new List<(int, int)>();
// Add nodes to disjoint set
for (var i = 0; i < numNodes; i++)
{
nodes[i] = set.MakeSet(i);
}
// Create lists with edge weights and associated connectivity
for (var i = 0; i < numNodes - 1; i++)
{
for (var j = i + 1; j < numNodes; j++)
{
if (float.IsFinite(adjacencyMatrix[i, j]))
{
edgeWeightList.Add(adjacencyMatrix[i, j]);
nodeConnectList.Add((i, j));
}
}
}
var edges = Solve(set, nodes, edgeWeightList.ToArray(), nodeConnectList.ToArray());
// Initialize minimum spanning tree
var mst = new float[numNodes, numNodes];
for (var i = 0; i < numNodes; i++)
{
mst[i, i] = float.PositiveInfinity;
for (var j = i + 1; j < numNodes; j++)
{
mst[i, j] = float.PositiveInfinity;
mst[j, i] = float.PositiveInfinity;
}
}
foreach (var (node1, node2) in edges)
{
mst[node1, node2] = adjacencyMatrix[node1, node2];
mst[node2, node1] = adjacencyMatrix[node1, node2];
}
return mst;
}
/// <summary>
/// Determine the minimum spanning tree/forest of the given graph.
/// </summary>
/// <param name="adjacencyList">Adjacency list representing the graph.</param>
/// <returns>Adjacency list of the minimum spanning tree/forest.</returns>
public static Dictionary<int, float>[] Solve(Dictionary<int, float>[] adjacencyList)
{
ValidateGraph(adjacencyList);
var numNodes = adjacencyList.Length;
var set = new DisjointSet<int>();
var nodes = new Node<int>[numNodes];
var edgeWeightList = new List<float>();
var nodeConnectList = new List<(int, int)>();
// Add nodes to disjoint set and create list of edge weights and associated connectivity
for (var i = 0; i < numNodes; i++)
{
nodes[i] = set.MakeSet(i);
foreach(var (node, weight) in adjacencyList[i])
{
edgeWeightList.Add(weight);
nodeConnectList.Add((i, node));
}
}
var edges = Solve(set, nodes, edgeWeightList.ToArray(), nodeConnectList.ToArray());
// Create minimum spanning tree
var mst = new Dictionary<int, float>[numNodes];
for (var i = 0; i < numNodes; i++)
{
mst[i] = new Dictionary<int, float>();
}
foreach (var (node1, node2) in edges)
{
mst[node1].Add(node2, adjacencyList[node1][node2]);
mst[node2].Add(node1, adjacencyList[node1][node2]);
}
return mst;
}
/// <summary>
/// Ensure that the given graph is undirected.
/// </summary>
/// <param name="adj">Adjacency matrix of graph to check.</param>
private static void ValidateGraph(float[,] adj)
{
if (adj.GetLength(0) != adj.GetLength(1))
{
throw new ArgumentException("Matrix must be square!");
}
for (var i = 0; i < adj.GetLength(0) - 1; i++)
{
for (var j = i + 1; j < adj.GetLength(1); j++)
{
if (Math.Abs(adj[i, j] - adj[j, i]) > 1e-6)
{
throw new ArgumentException("Matrix must be symmetric!");
}
}
}
}
/// <summary>
/// Ensure that the given graph is undirected.
/// </summary>
/// <param name="adj">Adjacency list of graph to check.</param>
private static void ValidateGraph(Dictionary<int, float>[] adj)
{
for (var i = 0; i < adj.Length; i++)
{
foreach (var edge in adj[i])
{
if (!adj[edge.Key].ContainsKey(i) || Math.Abs(edge.Value - adj[edge.Key][i]) > 1e-6)
{
throw new ArgumentException("Graph must be undirected!");
}
}
}
}
/// <summary>
/// Determine the minimum spanning tree/forest.
/// </summary>
/// <param name="set">Disjoint set needed for set operations.</param>
/// <param name="nodes">List of nodes in disjoint set associated with each node.</param>
/// <param name="edgeWeights">Weights of each edge.</param>
/// <param name="connections">Nodes associated with each item in the <paramref name="edgeWeights"/> parameter.</param>
/// <returns>Array of edges in the minimum spanning tree/forest.</returns>
private static (int, int)[] Solve(DisjointSet<int> set, Node<int>[] nodes, float[] edgeWeights, (int, int)[] connections)
{
var edges = new List<(int, int)>();
Array.Sort(edgeWeights, connections);
foreach (var (node1, node2) in connections)
{
if (set.FindSet(nodes[node1]) != set.FindSet(nodes[node2]))
{
set.UnionSet(nodes[node1], nodes[node2]);
edges.Add((node1, node2));
}
}
return edges.ToArray();
}
}
}
| 193 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Graph.MinimumSpanningTree
{
/// <summary>
/// Class that uses Prim's (Jarnik's algorithm) to determine the minimum
/// spanning tree (MST) of a given graph. Prim's algorithm is a greedy
/// algorithm that can determine the MST of a weighted undirected graph
/// in O(V^2) time where V is the number of nodes/vertices when using an
/// adjacency matrix representation.
/// More information: https://en.wikipedia.org/wiki/Prim%27s_algorithm
/// Pseudocode and runtime analysis: https://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/GraphAlgor/primAlgor.htm .
/// </summary>
public static class PrimMatrix
{
/// <summary>
/// Determine the minimum spanning tree for a given weighted undirected graph.
/// </summary>
/// <param name="adjacencyMatrix">Adjacency matrix for graph to find MST of.</param>
/// <param name="start">Node to start search from.</param>
/// <returns>Adjacency matrix of the found MST.</returns>
public static float[,] Solve(float[,] adjacencyMatrix, int start)
{
ValidateMatrix(adjacencyMatrix);
var numNodes = adjacencyMatrix.GetLength(0);
// Create array to represent minimum spanning tree
var mst = new float[numNodes, numNodes];
// Create array to keep track of which nodes are in the MST already
var added = new bool[numNodes];
// Create array to keep track of smallest edge weight for node
var key = new float[numNodes];
// Create array to store parent of node
var parent = new int[numNodes];
for (var i = 0; i < numNodes; i++)
{
mst[i, i] = float.PositiveInfinity;
key[i] = float.PositiveInfinity;
for (var j = i + 1; j < numNodes; j++)
{
mst[i, j] = float.PositiveInfinity;
mst[j, i] = float.PositiveInfinity;
}
}
// Ensures that the starting node is added first
key[start] = 0;
// Keep looping until all nodes are in tree
for (var i = 0; i < numNodes - 1; i++)
{
GetNextNode(adjacencyMatrix, key, added, parent);
}
// Build adjacency matrix for tree
for (var i = 0; i < numNodes; i++)
{
if (i == start)
{
continue;
}
mst[i, parent[i]] = adjacencyMatrix[i, parent[i]];
mst[parent[i], i] = adjacencyMatrix[i, parent[i]];
}
return mst;
}
/// <summary>
/// Ensure that the given adjacency matrix represents a weighted undirected graph.
/// </summary>
/// <param name="adjacencyMatrix">Adjacency matric to check.</param>
private static void ValidateMatrix(float[,] adjacencyMatrix)
{
// Matrix should be square
if (adjacencyMatrix.GetLength(0) != adjacencyMatrix.GetLength(1))
{
throw new ArgumentException("Adjacency matrix must be square!");
}
// Graph needs to be undirected and connected
for (var i = 0; i < adjacencyMatrix.GetLength(0); i++)
{
var connection = false;
for (var j = 0; j < adjacencyMatrix.GetLength(0); j++)
{
if (Math.Abs(adjacencyMatrix[i, j] - adjacencyMatrix[j, i]) > 1e-6)
{
throw new ArgumentException("Adjacency matrix must be symmetric!");
}
if (!connection && float.IsFinite(adjacencyMatrix[i, j]))
{
connection = true;
}
}
if (!connection)
{
throw new ArgumentException("Graph must be connected!");
}
}
}
/// <summary>
/// Determine which node should be added next to the MST.
/// </summary>
/// <param name="adjacencyMatrix">Adjacency matrix of graph.</param>
/// <param name="key">Currently known minimum edge weight connected to each node.</param>
/// <param name="added">Whether or not a node has been added to the MST.</param>
/// <param name="parent">The node that added the node to the MST. Used for building MST adjacency matrix.</param>
private static void GetNextNode(float[,] adjacencyMatrix, float[] key, bool[] added, int[] parent)
{
var numNodes = adjacencyMatrix.GetLength(0);
var minWeight = float.PositiveInfinity;
var node = -1;
// Find node with smallest node with known edge weight not in tree. Will always start with starting node
for (var i = 0; i < numNodes; i++)
{
if (!added[i] && key[i] < minWeight)
{
minWeight = key[i];
node = i;
}
}
// Add node to mst
added[node] = true;
// Update smallest found edge weights and parent for adjacent nodes
for (var i = 0; i < numNodes; i++)
{
if (!added[i] && adjacencyMatrix[node, i] < key[i])
{
key[i] = adjacencyMatrix[node, i];
parent[i] = node;
}
}
}
}
}
| 151 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Knapsack
{
/// <summary>
/// Branch and bound Knapsack solver.
/// </summary>
/// <typeparam name="T">Type of items in knapsack.</typeparam>
public class BranchAndBoundKnapsackSolver<T>
{
/// <summary>
/// Returns the knapsack containing the items that maximize value while not exceeding weight capacity.
/// Construct a tree structure with total number of items + 1 levels, each node have two child nodes,
/// starting with a dummy item root, each following levels are associated with 1 items, construct the
/// tree in breadth first order to identify the optimal item set.
/// </summary>
/// <param name="items">All items to choose from.</param>
/// <param name="capacity">The maximum weight capacity of the knapsack to be filled.</param>
/// <param name="weightSelector">
/// A function that returns the value of the specified item
/// from the <paramref name="items">items</paramref> list.
/// </param>
/// <param name="valueSelector">
/// A function that returns the weight of the specified item
/// from the <paramref name="items">items</paramref> list.
/// </param>
/// <returns>
/// The array of items that provides the maximum value of the
/// knapsack without exceeding the specified weight <paramref name="capacity">capacity</paramref>.
/// </returns>
public T[] Solve(T[] items, int capacity, Func<T, int> weightSelector, Func<T, double> valueSelector)
{
// This is required for greedy approach in upper bound calculation to work.
items = items.OrderBy(i => valueSelector(i) / weightSelector(i)).ToArray();
// nodesQueue --> used to construct tree in breadth first order
Queue<BranchAndBoundNode> nodesQueue = new();
// maxCumulativeValue --> maximum value while not exceeding weight capacity.
var maxCumulativeValue = 0.0;
// starting node, associated with a temporary created dummy item
BranchAndBoundNode root = new(level: -1, taken: false);
// lastNodeOfOptimalPat --> last item in the optimal item sets identified by this algorithm
BranchAndBoundNode lastNodeOfOptimalPath = root;
nodesQueue.Enqueue(root);
while (nodesQueue.Count != 0)
{
// parent --> parent node which represents the previous item, may or may not be taken into the knapsack
BranchAndBoundNode parent = nodesQueue.Dequeue();
// IF it is the last level, branching cannot be performed
if (parent.Level == items.Length - 1)
{
continue;
}
// create a child node where the associated item is taken into the knapsack
var left = new BranchAndBoundNode(parent.Level + 1, true, parent);
// create a child node where the associated item is not taken into the knapsack
var right = new BranchAndBoundNode(parent.Level + 1, false, parent);
// Since the associated item on current level is taken for the first node,
// set the cumulative weight of first node to cumulative weight of parent node + weight of the associated item,
// set the cumulative value of first node to cumulative value of parent node + value of current level's item.
left.CumulativeWeight = parent.CumulativeWeight + weightSelector(items[left.Level]);
left.CumulativeValue = parent.CumulativeValue + valueSelector(items[left.Level]);
right.CumulativeWeight = parent.CumulativeWeight;
right.CumulativeValue = parent.CumulativeValue;
// IF cumulative weight is smaller than the weight capacity of the knapsack AND
// current cumulative value is larger then the current maxCumulativeValue, update the maxCumulativeValue
if (left.CumulativeWeight <= capacity && left.CumulativeValue > maxCumulativeValue)
{
maxCumulativeValue = left.CumulativeValue;
lastNodeOfOptimalPath = left;
}
left.UpperBound = ComputeUpperBound(left, items, capacity, weightSelector, valueSelector);
right.UpperBound = ComputeUpperBound(right, items, capacity, weightSelector, valueSelector);
// IF upperBound of this node is larger than maxCumulativeValue,
// the current path is still possible to reach or surpass the maximum value,
// add current node to nodesQueue so that nodes below it can be further explored
if (left.UpperBound > maxCumulativeValue && left.CumulativeWeight < capacity)
{
nodesQueue.Enqueue(left);
}
// Cumulative weight is the same as for parent node and < capacity
if (right.UpperBound > maxCumulativeValue)
{
nodesQueue.Enqueue(right);
}
}
return GetItemsFromPath(items, lastNodeOfOptimalPath);
}
// determine items taken based on the path
private static T[] GetItemsFromPath(T[] items, BranchAndBoundNode lastNodeOfPath)
{
List<T> takenItems = new();
// only bogus initial node has no parent
for (var current = lastNodeOfPath; current.Parent is not null; current = current.Parent)
{
if(current.IsTaken)
{
takenItems.Add(items[current.Level]);
}
}
return takenItems.ToArray();
}
/// <summary>
/// Returns the upper bound value of a given node.
/// </summary>
/// <param name="aNode">The given node.</param>
/// <param name="items">All items to choose from.</param>
/// <param name="capacity">The maximum weight capacity of the knapsack to be filled.</param>
/// <param name="weightSelector">
/// A function that returns the value of the specified item
/// from the <paramref name="items">items</paramref> list.
/// </param>
/// <param name="valueSelector">
/// A function that returns the weight of the specified item
/// from the <paramref name="items">items</paramref> list.
/// </param>
/// <returns>
/// upper bound value of the given <paramref name="aNode">node</paramref>.
/// </returns>
private static double ComputeUpperBound(BranchAndBoundNode aNode, T[] items, int capacity, Func<T, int> weightSelector, Func<T, double> valueSelector)
{
var upperBound = aNode.CumulativeValue;
var availableWeight = capacity - aNode.CumulativeWeight;
var nextLevel = aNode.Level + 1;
while (availableWeight > 0 && nextLevel < items.Length)
{
if (weightSelector(items[nextLevel]) <= availableWeight)
{
upperBound += valueSelector(items[nextLevel]);
availableWeight -= weightSelector(items[nextLevel]);
}
else
{
upperBound += valueSelector(items[nextLevel]) / weightSelector(items[nextLevel]) * availableWeight;
availableWeight = 0;
}
nextLevel++;
}
return upperBound;
}
}
}
| 166 |
C-Sharp | TheAlgorithms | C# | namespace Algorithms.Knapsack
{
public class BranchAndBoundNode
{
// isTaken --> true = the item where index = level is taken, vice versa
public bool IsTaken { get; }
// cumulativeWeight --> um of weight of item associated in each nodes starting from root to this node (only item that is taken)
public int CumulativeWeight { get; set; }
// cumulativeValue --> sum of value of item associated in each nodes starting from root to this node (only item that is taken)
public double CumulativeValue { get; set; }
// upperBound --> largest possible value after taking/not taking the item associated to this node (fractional)
public double UpperBound { get; set; }
// level --> level of the node in the tree structure
public int Level { get; }
// parent node
public BranchAndBoundNode? Parent { get; }
public BranchAndBoundNode(int level, bool taken, BranchAndBoundNode? parent = null)
{
Level = level;
IsTaken = taken;
Parent = parent;
}
}
}
| 31 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
namespace Algorithms.Knapsack
{
/// <summary>
/// Dynamic Programming Knapsack solver.
/// </summary>
/// <typeparam name="T">Type of items in knapsack.</typeparam>
public class DynamicProgrammingKnapsackSolver<T>
{
/// <summary>
/// Returns the knapsack containing the items that
/// maximize value while not exceeding weight capacity.
/// </summary>
/// <param name="items">The list of items from which we select ones to be in the knapsack.</param>
/// <param name="capacity">
/// The maximum weight capacity of the knapsack
/// to be filled. Only integer values of this capacity are tried. If
/// a greater resolution is needed, multiply the
/// weights/capacity by a factor of 10.
/// </param>
/// <param name="weightSelector">
/// A function that returns the value of the specified item
/// from the <paramref name="items">items</paramref> list.
/// </param>
/// <param name="valueSelector">
/// A function that returns the weight of the specified item
/// from the <paramref name="items">items</paramref> list.
/// </param>
/// <returns>
/// The array of items that provides the maximum value of the
/// knapsack without exceeding the specified weight <paramref name="capacity">capacity</paramref>.
/// </returns>
public T[] Solve(T[] items, int capacity, Func<T, int> weightSelector, Func<T, double> valueSelector)
{
var cache = Tabulate(items, weightSelector, valueSelector, capacity);
return GetOptimalItems(items, weightSelector, cache, capacity);
}
private static T[] GetOptimalItems(T[] items, Func<T, int> weightSelector, double[,] cache, int capacity)
{
var currentCapacity = capacity;
var result = new List<T>();
for (var i = items.Length - 1; i >= 0; i--)
{
if (cache[i + 1, currentCapacity] > cache[i, currentCapacity])
{
var item = items[i];
result.Add(item);
currentCapacity -= weightSelector(item);
}
}
result.Reverse(); // we added items back to front
return result.ToArray();
}
private static double[,] Tabulate(
T[] items,
Func<T, int> weightSelector,
Func<T, double> valueSelector,
int maxCapacity)
{
// Store the incremental results in a bottom up manner
var n = items.Length;
var results = new double[n + 1, maxCapacity + 1];
for (var i = 0; i <= n; i++)
{
for (var w = 0; w <= maxCapacity; w++)
{
if (i == 0 || w == 0)
{
// If we have no items to take, or
// if we have no capacity in our knapsack
// we cannot possibly have any value
results[i, w] = 0;
}
else if (weightSelector(items[i - 1]) <= w)
{
// Decide if it is better to take or not take this item
var iut = items[i - 1]; // iut = Item under test
var vut = valueSelector(iut); // vut = Value of item under test
var wut = weightSelector(iut); // wut = Weight of item under test
var valueIfTaken = vut + results[i - 1, w - wut];
var valueIfNotTaken = results[i - 1, w];
results[i, w] = Math.Max(valueIfTaken, valueIfNotTaken);
}
else
{
// There is not enough room to take this item
results[i, w] = results[i - 1, w];
}
}
}
return results;
}
}
}
| 102 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Knapsack
{
/// <summary>
/// Solves knapsack problem using some heuristics
/// Sum of values of taken items -> max
/// Sum of weights of taken items. <= capacity.
/// </summary>
/// <typeparam name="T">Type of items in knapsack.</typeparam>
public interface IHeuristicKnapsackSolver<T>
{
/// <summary>
/// Solves knapsack problem using some heuristics
/// Sum of values of taken items -> max
/// Sum of weights of taken items. <= capacity.
/// </summary>
/// <param name="items">All items to choose from.</param>
/// <param name="capacity">How much weight we can take.</param>
/// <param name="weightSelector">Maps item to its weight.</param>
/// <param name="valueSelector">Maps item to its value.</param>
/// <returns>Items that were chosen.</returns>
T[] Solve(T[] items, double capacity, Func<T, double> weightSelector, Func<T, double> valueSelector);
}
}
| 26 |
C-Sharp | TheAlgorithms | C# | namespace Algorithms.Knapsack
{
/// <summary>
/// Solves knapsack problem:
/// to maximize sum of values of taken items,
/// while sum of weights of taken items is less than capacity.
/// </summary>
/// <typeparam name="T">Type of items in knapsack.</typeparam>
public interface IKnapsackSolver<T> : IHeuristicKnapsackSolver<T>
{
}
}
| 13 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
namespace Algorithms.Knapsack
{
/// <summary>
/// Greedy heurictic solver.
/// </summary>
/// <typeparam name="T">Type of items in knapsack.</typeparam>
public class NaiveKnapsackSolver<T> : IHeuristicKnapsackSolver<T>
{
/// <summary>
/// TODO.
/// </summary>
/// <param name="items">TODO. 2.</param>
/// <param name="capacity">TODO. 3.</param>
/// <param name="weightSelector">TODO. 4.</param>
/// <param name="valueSelector">TODO. 5.</param>
/// <returns>TODO. 6.</returns>
public T[] Solve(T[] items, double capacity, Func<T, double> weightSelector, Func<T, double> valueSelector)
{
var weight = 0d;
var left = new List<T>();
foreach (var item in items)
{
var weightDelta = weightSelector(item);
if (weight + weightDelta <= capacity)
{
weight += weightDelta;
left.Add(item);
}
}
return left.ToArray();
}
}
}
| 39 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms.LinearAlgebra.Distances
{
/// <summary>
/// Implementation for Euclidean distance.
/// </summary>
public static class Euclidean
{
/// <summary>
/// Calculate Euclidean distance for two N-Dimensional points.
/// </summary>
/// <param name="point1">First N-Dimensional point.</param>
/// <param name="point2">Second N-Dimensional point.</param>
/// <returns>Calculated Euclidean distance.</returns>
public static double Distance(double[] point1, double[] point2)
{
if (point1.Length != point2.Length)
{
throw new ArgumentException("Both points should have the same dimensionality");
}
// distance = sqrt((x1-y1)^2 + (x2-y2)^2 + ... + (xn-yn)^2)
return Math.Sqrt(point1.Zip(point2, (x1, x2) => (x1 - x2) * (x1 - x2)).Sum());
}
}
}
| 32 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms.LinearAlgebra.Distances
{
/// <summary>
/// Implementation fo Manhattan distance.
/// It is the sum of the lengths of the projections of the line segment between the points onto the coordinate axes.
/// In other words, it is the sum of absolute difference between the measures in all dimensions of two points.
///
/// Its commonly used in regression analysis.
/// </summary>
public static class Manhattan
{
/// <summary>
/// Calculate Manhattan distance for two N-Dimensional points.
/// </summary>
/// <param name="point1">First N-Dimensional point.</param>
/// <param name="point2">Second N-Dimensional point.</param>
/// <returns>Calculated Manhattan distance.</returns>
public static double Distance(double[] point1, double[] point2)
{
if (point1.Length != point2.Length)
{
throw new ArgumentException("Both points should have the same dimensionality");
}
// distance = |x1-y1| + |x2-y2| + ... + |xn-yn|
return point1.Zip(point2, (x1, x2) => Math.Abs(x1 - x2)).Sum();
}
}
}
| 36 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Linq;
using Utilities.Extensions;
namespace Algorithms.LinearAlgebra.Eigenvalue
{
/// <summary>
/// Power iteration method - eigenvalue numeric algorithm, based on recurrent relation:
/// Li+1 = (A * Li) / || A * Li ||, where Li - eigenvector approximation.
/// </summary>
public static class PowerIteration
{
/// <summary>
/// Returns approximation of the dominant eigenvalue and eigenvector of <paramref name="source" /> matrix.
/// </summary>
/// <list type="bullet">
/// <item>
/// <description>The algorithm will not converge if the start vector is orthogonal to the eigenvector.</description>
/// </item>
/// <item>
/// <description>The <paramref name="source" /> matrix must be square-shaped.</description>
/// </item>
/// </list>
/// <param name="source">Source square-shaped matrix.</param>
/// <param name="startVector">Start vector.</param>
/// <param name="error">Accuracy of the result.</param>
/// <returns>Dominant eigenvalue and eigenvector pair.</returns>
/// <exception cref="ArgumentException">The <paramref name="source" /> matrix is not square-shaped.</exception>
/// <exception cref="ArgumentException">The length of the start vector doesn't equal the size of the source matrix.</exception>
public static (double eigenvalue, double[] eigenvector) Dominant(
double[,] source,
double[] startVector,
double error = 0.00001)
{
if (source.GetLength(0) != source.GetLength(1))
{
throw new ArgumentException("The source matrix is not square-shaped.");
}
if (source.GetLength(0) != startVector.Length)
{
throw new ArgumentException(
"The length of the start vector doesn't equal the size of the source matrix.");
}
double eigenNorm;
double[] previousEigenVector;
double[] currentEigenVector = startVector;
do
{
previousEigenVector = currentEigenVector;
currentEigenVector = source.Multiply(
previousEigenVector.ToColumnVector())
.ToRowVector();
eigenNorm = currentEigenVector.Magnitude();
currentEigenVector = currentEigenVector.Select(x => x / eigenNorm).ToArray();
}
while (Math.Abs(currentEigenVector.Dot(previousEigenVector)) < 1.0 - error);
var eigenvalue = source.Multiply(currentEigenVector.ToColumnVector()).ToRowVector().Magnitude();
return (eigenvalue, eigenvector: currentEigenVector);
}
/// <summary>
/// Returns approximation of the dominant eigenvalue and eigenvector of <paramref name="source" /> matrix.
/// Random normalized vector is used as the start vector to decrease chance of orthogonality to the eigenvector.
/// </summary>
/// <list type="bullet">
/// <item>
/// <description>The algorithm will not converge if the start vector is orthogonal to the eigenvector.</description>
/// </item>
/// <item>
/// <description>The <paramref name="source" /> matrix should be square-shaped.</description>
/// </item>
/// </list>
/// <param name="source">Source square-shaped matrix.</param>
/// <param name="error">Accuracy of the result.</param>
/// <returns>Dominant eigenvalue and eigenvector pair.</returns>
/// <exception cref="ArgumentException">The <paramref name="source" /> matrix is not square-shaped.</exception>
/// <exception cref="ArgumentException">The length of the start vector doesn't equal the size of the source matrix.</exception>
public static (double eigenvalue, double[] eigenvector) Dominant(double[,] source, double error = 0.00001) =>
Dominant(source, new Random().NextVector(source.GetLength(1)), error);
}
}
| 88 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace Algorithms.ModularArithmetic
{
/// <summary>
/// Chinese Remainder Theorem: https://en.wikipedia.org/wiki/Chinese_remainder_theorem.
/// </summary>
public static class ChineseRemainderTheorem
{
/// <summary>
/// The Chinese Remainder Theorem is used to compute x for given set of pairs of integers (a_i, n_i) with:
/// <list type="bullet">
/// <item>x = a_0 mod n_0</item>
/// <item>x = a_1 mod n_1</item>
/// <item>...</item>
/// <item>x = a_k mod n_k</item>
/// </list>
/// for 0 <= i < k, for some positive integer k. Additional requirements are:
/// <list type="bullet">
/// <item>n_i > 1 for 0 <= i < k</item>
/// <item>n_i and n_j are coprime, for all 0 <= i < j < k</item>
/// <item>0 <= a_i < n_i, for all 0 <= i < k</item>
/// <item>0 <= x < n_0 * n_1 * ... * n_(k-1)</item>
/// </list>
/// </summary>
/// <param name="listOfAs">An ordered list of a_0, a_1, ..., a_k.</param>
/// <param name="listOfNs">An ordered list of n_0, n_1, ..., n_k.</param>
/// <returns>The value x.</returns>
/// <exception cref="ArgumentException">If any of the requirements is not fulfilled.</exception>
public static long Compute(List<long> listOfAs, List<long> listOfNs)
{
// Check the requirements for this algorithm:
CheckRequirements(listOfAs, listOfNs);
// For performance-reasons compute the product of all n_i as prodN, because we're going to need access to (prodN / n_i) for all i:
var prodN = 1L;
foreach (var n in listOfNs)
{
prodN *= n;
}
var result = 0L;
for (var i = 0; i < listOfNs.Count; i++)
{
var a_i = listOfAs[i];
var n_i = listOfNs[i];
var modulus_i = prodN / n_i;
var bezout_modulus_i = ExtendedEuclideanAlgorithm.Compute(n_i, modulus_i).bezoutB;
result += a_i * bezout_modulus_i * modulus_i;
}
// Make sure, result is in [0, prodN).
result %= prodN;
if (result < 0)
{
result += prodN;
}
return result;
}
/// <summary>
/// The Chinese Remainder Theorem is used to compute x for given set of pairs of integers (a_i, n_i) with:
/// <list type="bullet">
/// <item>x = a_0 mod n_0</item>
/// <item>x = a_1 mod n_1</item>
/// <item>...</item>
/// <item>x = a_k mod n_k</item>
/// </list>
/// for 0 <= i < k, for some positive integer k. Additional requirements are:
/// <list type="bullet">
/// <item>n_i > 1 for 0 <= i < k</item>
/// <item>n_i and n_j are coprime, for all 0 <= i < j < k</item>
/// <item>0 <= a_i < n_i, for all 0 <= i < k</item>
/// <item>0 <= x < n_0 * n_1 * ... * n_(k-1)</item>
/// </list>
/// </summary>
/// <param name="listOfAs">An ordered list of a_0, a_1, ..., a_k.</param>
/// <param name="listOfNs">An ordered list of n_0, n_1, ..., n_k.</param>
/// <returns>The value x.</returns>
/// <exception cref="ArgumentException">If any of the requirements is not fulfilled.</exception>
public static BigInteger Compute(List<BigInteger> listOfAs, List<BigInteger> listOfNs)
{
// Check the requirements for this algorithm:
CheckRequirements(listOfAs, listOfNs);
// For performance-reasons compute the product of all n_i as prodN, because we're going to need access to (prodN / n_i) for all i:
var prodN = BigInteger.One;
foreach (var n in listOfNs)
{
prodN *= n;
}
var result = BigInteger.Zero;
for (var i = 0; i < listOfNs.Count; i++)
{
var a_i = listOfAs[i];
var n_i = listOfNs[i];
var modulus_i = prodN / n_i;
var bezout_modulus_i = ExtendedEuclideanAlgorithm.Compute(n_i, modulus_i).bezoutB;
result += a_i * bezout_modulus_i * modulus_i;
}
// Make sure, result is in [0, prodN).
result %= prodN;
if (result < 0)
{
result += prodN;
}
return result;
}
/// <summary>
/// Checks the requirements for the algorithm and throws an ArgumentException if they are not being met.
/// </summary>
/// <param name="listOfAs">An ordered list of a_0, a_1, ..., a_k.</param>
/// <param name="listOfNs">An ordered list of n_0, n_1, ..., n_k.</param>
/// <exception cref="ArgumentException">If any of the requirements is not fulfilled.</exception>
private static void CheckRequirements(List<long> listOfAs, List<long> listOfNs)
{
if (listOfAs == null || listOfNs == null || listOfAs.Count != listOfNs.Count)
{
throw new ArgumentException("The parameters 'listOfAs' and 'listOfNs' must not be null and have to be of equal length!");
}
if (listOfNs.Any(x => x <= 1))
{
throw new ArgumentException($"The value {listOfNs.First(x => x <= 1)} for some n_i is smaller than or equal to 1.");
}
if (listOfAs.Any(x => x < 0))
{
throw new ArgumentException($"The value {listOfAs.First(x => x < 0)} for some a_i is smaller than 0.");
}
// Check if all pairs of (n_i, n_j) are coprime:
for (var i = 0; i < listOfNs.Count; i++)
{
for (var j = i + 1; j < listOfNs.Count; j++)
{
long gcd;
if ((gcd = ExtendedEuclideanAlgorithm.Compute(listOfNs[i], listOfNs[j]).gcd) != 1L)
{
throw new ArgumentException($"The GCD of n_{i} = {listOfNs[i]} and n_{j} = {listOfNs[j]} equals {gcd} and thus these values aren't coprime.");
}
}
}
}
/// <summary>
/// Checks the requirements for the algorithm and throws an ArgumentException if they are not being met.
/// </summary>
/// <param name="listOfAs">An ordered list of a_0, a_1, ..., a_k.</param>
/// <param name="listOfNs">An ordered list of n_0, n_1, ..., n_k.</param>
/// <exception cref="ArgumentException">If any of the requirements is not fulfilled.</exception>
private static void CheckRequirements(List<BigInteger> listOfAs, List<BigInteger> listOfNs)
{
if (listOfAs == null || listOfNs == null || listOfAs.Count != listOfNs.Count)
{
throw new ArgumentException("The parameters 'listOfAs' and 'listOfNs' must not be null and have to be of equal length!");
}
if (listOfNs.Any(x => x <= 1))
{
throw new ArgumentException($"The value {listOfNs.First(x => x <= 1)} for some n_i is smaller than or equal to 1.");
}
if (listOfAs.Any(x => x < 0))
{
throw new ArgumentException($"The value {listOfAs.First(x => x < 0)} for some a_i is smaller than 0.");
}
// Check if all pairs of (n_i, n_j) are coprime:
for (var i = 0; i < listOfNs.Count; i++)
{
for (var j = i + 1; j < listOfNs.Count; j++)
{
BigInteger gcd;
if ((gcd = ExtendedEuclideanAlgorithm.Compute(listOfNs[i], listOfNs[j]).gcd) != BigInteger.One)
{
throw new ArgumentException($"The GCD of n_{i} = {listOfNs[i]} and n_{j} = {listOfNs[j]} equals {gcd} and thus these values aren't coprime.");
}
}
}
}
}
}
| 194 |
C-Sharp | TheAlgorithms | C# | using System.Numerics;
namespace Algorithms.ModularArithmetic
{
/// <summary>
/// Extended Euclidean algorithm: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm.
/// </summary>
public static class ExtendedEuclideanAlgorithm
{
/// <summary>
/// Computes the greatest common divisor (gcd) of integers a and b, also the coefficients of Bézout's identity,
/// which are integers x and y such that a*bezoutCoefficientOfA + b*bezoutCoefficientOfB = gcd(a, b).
/// </summary>
/// <param name="a">Input number.</param>
/// <param name="b">Second input number.</param>
/// <returns>A record of ExtendedEuclideanAlgorithmResult containing the bezout coefficients of a and b as well as the gcd(a,b).</returns>
public static ExtendedEuclideanAlgorithmResult<long> Compute(long a, long b)
{
long quotient;
long tmp;
var s = 0L;
var bezoutOfA = 1L;
var r = b;
var gcd = a;
var bezoutOfB = 0L;
while (r != 0)
{
quotient = gcd / r; // integer division
tmp = gcd;
gcd = r;
r = tmp - quotient * r;
tmp = bezoutOfA;
bezoutOfA = s;
s = tmp - quotient * s;
}
if (b != 0)
{
bezoutOfB = (gcd - bezoutOfA * a) / b; // integer division
}
return new ExtendedEuclideanAlgorithmResult<long>(bezoutOfA, bezoutOfB, gcd);
}
/// <summary>
/// Computes the greatest common divisor (gcd) of integers a and b, also the coefficients of Bézout's identity,
/// which are integers x and y such that a*bezoutCoefficientOfA + b*bezoutCoefficientOfB = gcd(a, b).
/// </summary>
/// <param name="a">Input number.</param>
/// <param name="b">Second input number.</param>
/// <returns>A record of ExtendedEuclideanAlgorithmResult containing the bezout coefficients of a and b as well as the gcd(a,b).</returns>
public static ExtendedEuclideanAlgorithmResult<BigInteger> Compute(BigInteger a, BigInteger b)
{
BigInteger quotient;
BigInteger tmp;
var s = BigInteger.Zero;
var bezoutOfA = BigInteger.One;
var r = b;
var gcd = a;
var bezoutOfB = BigInteger.Zero;
while (r != 0)
{
quotient = gcd / r; // integer division
tmp = gcd;
gcd = r;
r = tmp - quotient * r;
tmp = bezoutOfA;
bezoutOfA = s;
s = tmp - quotient * s;
}
if (b != 0)
{
bezoutOfB = (gcd - bezoutOfA * a) / b; // integer division
}
return new ExtendedEuclideanAlgorithmResult<BigInteger>(bezoutOfA, bezoutOfB, gcd);
}
/// <summary>
/// The result type for the computation of the Extended Euclidean Algorithm.
/// </summary>
/// <typeparam name="T">The data type of the computation (i.e. long or BigInteger).</typeparam>
/// <param name="bezoutA">The bezout coefficient of the parameter a to the computation.</param>
/// <param name="bezoutB">The bezout coefficient of the parameter b to the computation.</param>
/// <param name="gcd">The greatest common divisor of the parameters a and b to the computation.</param>
public record ExtendedEuclideanAlgorithmResult<T>(T bezoutA, T bezoutB, T gcd);
}
}
| 96 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Numerics;
namespace Algorithms.ModularArithmetic
{
/// <summary>
/// Modular multiplicative inverse: https://en.wikipedia.org/wiki/Modular_multiplicative_inverse.
/// </summary>
public static class ModularMultiplicativeInverse
{
/// <summary>
/// Computes the modular multiplicative inverse of a in Z/nZ, if there is any (i.e. if a and n are coprime).
/// </summary>
/// <param name="a">The number a, of which to compute the multiplicative inverse.</param>
/// <param name="n">The modulus n.</param>
/// <returns>The multiplicative inverse of a in Z/nZ, a value in the interval [0, n).</returns>
/// <exception cref="ArithmeticException">If there exists no multiplicative inverse of a in Z/nZ.</exception>
public static long Compute(long a, long n)
{
var eeaResult = ExtendedEuclideanAlgorithm.Compute(a, n);
// Check if there is an inverse:
if (eeaResult.gcd != 1)
{
throw new ArithmeticException($"{a} is not invertible in Z/{n}Z.");
}
// Make sure, inverseOfA (i.e. the bezout coefficient of a) is in the interval [0, n).
var inverseOfA = eeaResult.bezoutA;
if (inverseOfA < 0)
{
inverseOfA += n;
}
return inverseOfA;
}
/// <summary>
/// Computes the modular multiplicative inverse of a in Z/nZ, if there is any (i.e. if a and n are coprime).
/// </summary>
/// <param name="a">The number a, of which to compute the multiplicative inverse.</param>
/// <param name="n">The modulus n.</param>
/// <returns>The multiplicative inverse of a in Z/nZ, a value in the interval [0, n).</returns>
/// <exception cref="ArithmeticException">If there exists no multiplicative inverse of a in Z/nZ.</exception>
public static BigInteger Compute(BigInteger a, BigInteger n)
{
var eeaResult = ExtendedEuclideanAlgorithm.Compute(a, n);
// Check if there is an inverse:
if (eeaResult.gcd != 1)
{
throw new ArithmeticException($"{a} is not invertible in Z/{n}Z.");
}
// Make sure, inverseOfA (i.e. the bezout coefficient of a) is in the interval [0, n).
var inverseOfA = eeaResult.bezoutA;
if (inverseOfA < 0)
{
inverseOfA += n;
}
return inverseOfA;
}
}
}
| 66 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Numeric
{
/// <summary>
/// In number theory, the aliquot sum s(n) of a positive integer n is the sum of all proper divisors
/// of n, that is, all divisors of n other than n itself. For example, the proper divisors of 15
/// (that is, the positive divisors of 15 that are not equal to 15) are 1, 3 and 5, so the aliquot
/// sum of 15 is 9 i.e. (1 + 3 + 5). Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum.
/// </summary>
public static class AliquotSumCalculator
{
/// <summary>
/// Finds the aliquot sum of an integer number.
/// </summary>
/// <param name="number">Positive number.</param>
/// <returns>The Aliquot Sum.</returns>
/// <exception cref="ArgumentException">Error number is not on interval (0.0; int.MaxValue).</exception>
public static int CalculateAliquotSum(int number)
{
if (number < 0)
{
throw new ArgumentException($"{nameof(number)} cannot be negative");
}
var sum = 0;
for (int i = 1, limit = number / 2; i <= limit; ++i)
{
if (number % i == 0)
{
sum += i;
}
}
return sum;
}
}
}
| 39 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms.Numeric
{
/// <summary>
/// Amicable numbers are two different natural numbers related in such a way that the sum of the proper divisors of
/// each is equal to the other number. That is, σ(a)=b+a and σ(b)=a+b, where σ(n) is equal to the sum of positive divisors of n (see also divisor function).
/// See <a href="https://en.wikipedia.org/wiki/Amicable_numbers">here</a> for more info.
/// </summary>
public static class AmicableNumbersChecker
{
/// <summary>
/// Checks if two numbers are amicable or not.
/// </summary>
/// <param name="x">First number to check.</param>
/// <param name="y">Second number to check.</param>
/// <returns>True if they are amicable numbers. False if not.</returns>
public static bool AreAmicableNumbers(int x, int y)
{
return SumOfDivisors(x) == y && SumOfDivisors(y) == x;
}
private static int SumOfDivisors(int number)
{
var sum = 0; /* sum of its positive divisors */
for (var i = 1; i < number; ++i)
{
if (number % i == 0)
{
sum += i;
}
}
return sum;
}
}
}
| 42 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace Algorithms.Numeric
{
/// <summary>
/// Calculates Automorphic numbers. A number is said to be an Automorphic number
/// if the square of the number will contain the number itself at the end.
/// </summary>
public static class AutomorphicNumber
{
/// <summary>
/// Generates a list of automorphic numbers that are between <paramref name="lowerBound"/> and <paramref name="upperBound"/>
/// inclusive.
/// </summary>
/// <param name="lowerBound">The lower bound of the list.</param>
/// <param name="upperBound">The upper bound of the list.</param>
/// <returns>A list that contains all of the automorphic numbers between <paramref name="lowerBound"/> and <paramref name="upperBound"/> inclusive.</returns>
/// <exception cref="ArgumentException">If the <paramref name="lowerBound"/>
/// or <paramref name="upperBound"/> is not greater than zero
/// or <paramref name="upperBound"/>is lower than the <paramref name="lowerBound"/>.</exception>
public static IEnumerable<int> GetAutomorphicNumbers(int lowerBound, int upperBound)
{
if (lowerBound < 1)
{
throw new ArgumentException($"Lower bound must be greater than 0.");
}
if (upperBound < 1)
{
throw new ArgumentException($"Upper bound must be greater than 0.");
}
if (lowerBound > upperBound)
{
throw new ArgumentException($"The lower bound must be less than or equal to the upper bound.");
}
return Enumerable.Range(lowerBound, upperBound).Where(IsAutomorphic);
}
/// <summary>
/// Checks if a given natural number is automorphic or not.
/// </summary>
/// <param name="number">The number to check.</param>
/// <returns>True if the number is automorphic, false otherwise.</returns>
/// <exception cref="ArgumentException">If the number is non-positive.</exception>
public static bool IsAutomorphic(int number)
{
if (number < 1)
{
throw new ArgumentException($"An automorphic number must always be positive.");
}
BigInteger square = BigInteger.Pow(number, 2);
// Extract the last digits of both numbers
while (number > 0)
{
if (number % 10 != square % 10)
{
return false;
}
number /= 10;
square /= 10;
}
return true;
}
}
}
| 75 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Numerics;
namespace Algorithms.Numeric
{
/// <summary>
/// The binomial coefficients are the positive integers
/// that occur as coefficients in the binomial theorem.
/// </summary>
public static class BinomialCoefficient
{
/// <summary>
/// Calculates Binomial coefficients for given input.
/// </summary>
/// <param name="num">First number.</param>
/// <param name="k">Second number.</param>
/// <returns>Binimial Coefficients.</returns>
public static BigInteger Calculate(BigInteger num, BigInteger k)
{
if (num < k || k < 0)
{
throw new ArgumentException("num ≥ k ≥ 0");
}
// Tricks to gain performance:
// 1. Because (num over k) equals (num over (num-k)), we can save multiplications and divisions
// by replacing k with the minimum of k and (num - k).
k = BigInteger.Min(k, num - k);
// 2. We can simplify the computation of (num! / (k! * (num - k)!)) to ((num * (num - 1) * ... * (num - k + 1) / (k!))
// and thus save some multiplications and divisions.
var numerator = BigInteger.One;
for (var val = num - k + 1; val <= num; val++)
{
numerator *= val;
}
// 3. Typically multiplication is a lot faster than division, therefore compute the value of k! first (i.e. k - 1 multiplications)
// and then divide the numerator by the denominator (i.e. 1 division); instead of performing k - 1 divisions (1 for each factor in k!).
var denominator = BigInteger.One;
for (var val = k; val > BigInteger.One; val--)
{
denominator *= val;
}
return numerator / denominator;
}
}
}
| 50 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
namespace Algorithms.Numeric
{
/// <summary>
/// In mathematics and computational science, the Euler method (also called forward Euler method)
/// is a first-order numerical procedure for solving ordinary differential equations (ODEs)
/// with a given initial value (aka. Cauchy problem). It is the most basic explicit method for numerical integration
/// of ordinary differential equations. The method proceeds in a series of steps. At each step
/// the y-value is calculated by evaluating the differential equation at the previous step,
/// multiplying the result with the step-size and adding it to the last y-value:
/// y_n+1 = y_n + stepSize * f(x_n, y_n).
/// (description adapted from https://en.wikipedia.org/wiki/Euler_method )
/// (see also: https://www.geeksforgeeks.org/euler-method-solving-differential-equation/ ).
/// </summary>
public static class EulerMethod
{
/// <summary>
/// Loops through all the steps until xEnd is reached, adds a point for each step and then
/// returns all the points.
/// </summary>
/// <param name="xStart">Initial conditions x-value.</param>
/// <param name="xEnd">Last x-value.</param>
/// <param name="stepSize">Step-size on the x-axis.</param>
/// <param name="yStart">Initial conditions y-value.</param>
/// <param name="yDerivative">The right hand side of the differential equation.</param>
/// <returns>The solution of the Cauchy problem.</returns>
public static List<double[]> EulerFull(
double xStart,
double xEnd,
double stepSize,
double yStart,
Func<double, double, double> yDerivative)
{
if (xStart >= xEnd)
{
throw new ArgumentOutOfRangeException(
nameof(xEnd),
$"{nameof(xEnd)} should be greater than {nameof(xStart)}");
}
if (stepSize <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(stepSize),
$"{nameof(stepSize)} should be greater than zero");
}
List<double[]> points = new();
double[] firstPoint = { xStart, yStart };
points.Add(firstPoint);
var yCurrent = yStart;
var xCurrent = xStart;
while (xCurrent < xEnd)
{
yCurrent = EulerStep(xCurrent, stepSize, yCurrent, yDerivative);
xCurrent += stepSize;
double[] point = { xCurrent, yCurrent };
points.Add(point);
}
return points;
}
/// <summary>
/// Calculates the next y-value based on the current value of x, y and the stepSize.
/// </summary>
/// <param name="xCurrent">Current x-value.</param>
/// <param name="stepSize">Step-size on the x-axis.</param>
/// <param name="yCurrent">Current y-value.</param>
/// <param name="yDerivative">The right hand side of the differential equation.</param>
/// <returns>The next y-value.</returns>
private static double EulerStep(
double xCurrent,
double stepSize,
double yCurrent,
Func<double, double, double> yDerivative)
{
var yNext = yCurrent + stepSize * yDerivative(xCurrent, yCurrent);
return yNext;
}
}
}
| 86 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Numerics;
namespace Algorithms.Numeric
{
/// <summary>
/// The factorial of a positive integer n, denoted by n!,
/// is the product of all positive integers less than or equal to n.
/// </summary>
public static class Factorial
{
/// <summary>
/// Calculates factorial of a integer number.
/// </summary>
/// <param name="inputNum">Integer Input number.</param>
/// <returns>Factorial of integer input number.</returns>
public static BigInteger Calculate(int inputNum)
{
// Convert integer input to BigInteger
BigInteger num = new BigInteger(inputNum);
// Don't calculate factorial if input is a negative number.
if (BigInteger.Compare(num, BigInteger.Zero) < 0)
{
throw new ArgumentException("Only for num >= 0");
}
// Factorial of numbers greater than 0.
BigInteger result = BigInteger.One;
for (BigInteger i = BigInteger.One; BigInteger.Compare(i, num) <= 0; i = BigInteger.Add(i, BigInteger.One))
{
result = BigInteger.Multiply(result, i);
}
return result;
}
}
}
| 40 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Numeric
{
/// <summary>
/// Algorithm used to find the inverse of any matrix that can be inverted.
/// </summary>
public class GaussJordanElimination
{
private int RowCount { get; set; }
/// <summary>
/// Method to find a linear equation system using gaussian elimination.
/// </summary>
/// <param name="matrix">The key matrix to solve via algorithm.</param>
/// <returns>
/// whether the input matrix has a unique solution or not.
/// and solves on the given matrix.
/// </returns>
public bool Solve(double[,] matrix)
{
RowCount = matrix.GetUpperBound(0) + 1;
if (!CanMatrixBeUsed(matrix))
{
throw new ArgumentException("Please use a n*(n+1) matrix with Length > 0.");
}
var pivot = PivotMatrix(ref matrix);
if (!pivot)
{
return false;
}
Elimination(ref matrix);
return ElementaryReduction(ref matrix);
}
/// <summary>
/// To make simple validation of the matrix to be used.
/// </summary>
/// <param name="matrix">Multidimensional array matrix.</param>
/// <returns>
/// True: if algorithm can be use for given matrix;
/// False: Otherwise.
/// </returns>
private bool CanMatrixBeUsed(double[,] matrix) => matrix?.Length == RowCount * (RowCount + 1) && RowCount > 1;
/// <summary>
/// To prepare given matrix by pivoting rows.
/// </summary>
/// <param name="matrix">Input matrix.</param>
/// <returns>Matrix.</returns>
private bool PivotMatrix(ref double[,] matrix)
{
for (var col = 0; col + 1 < RowCount; col++)
{
if (matrix[col, col] == 0)
{
// To find a non-zero coefficient
var rowToSwap = FindNonZeroCoefficient(ref matrix, col);
if (matrix[rowToSwap, col] != 0)
{
var tmp = new double[RowCount + 1];
for (var i = 0; i < RowCount + 1; i++)
{
// To make the swap with the element above.
tmp[i] = matrix[rowToSwap, i];
matrix[rowToSwap, i] = matrix[col, i];
matrix[col, i] = tmp[i];
}
}
else
{
// To return that the matrix doesn't have a unique solution.
return false;
}
}
}
return true;
}
private int FindNonZeroCoefficient(ref double[,] matrix, int col)
{
var rowToSwap = col + 1;
// To find a non-zero coefficient
for (; rowToSwap < RowCount; rowToSwap++)
{
if (matrix[rowToSwap, col] != 0)
{
return rowToSwap;
}
}
return col + 1;
}
/// <summary>
/// Applies REF.
/// </summary>
/// <param name="matrix">Input matrix.</param>
private void Elimination(ref double[,] matrix)
{
for (var srcRow = 0; srcRow + 1 < RowCount; srcRow++)
{
for (var destRow = srcRow + 1; destRow < RowCount; destRow++)
{
var df = matrix[srcRow, srcRow];
var sf = matrix[destRow, srcRow];
for (var i = 0; i < RowCount + 1; i++)
{
matrix[destRow, i] = matrix[destRow, i] * df - matrix[srcRow, i] * sf;
}
}
}
}
/// <summary>
/// To continue reducing the matrix using RREF.
/// </summary>
/// <param name="matrix">Input matrix.</param>
/// <returns>True if it has a unique solution; false otherwise.</returns>
private bool ElementaryReduction(ref double[,] matrix)
{
for (var row = RowCount - 1; row >= 0; row--)
{
var element = matrix[row, row];
if (element == 0)
{
return false;
}
for (var i = 0; i < RowCount + 1; i++)
{
matrix[row, i] /= element;
}
for (var destRow = 0; destRow < row; destRow++)
{
matrix[destRow, RowCount] -= matrix[destRow, row] * matrix[row, RowCount];
matrix[destRow, row] = 0;
}
}
return true;
}
}
}
| 154 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Numeric;
public static class JosephusProblem
{
/// <summary>
/// Calculates the winner in the Josephus problem.
/// </summary>
/// <param name="n">The number of people in the initial circle.</param>
/// <param name="k">The count of each step. k-1 people are skipped and the k-th is executed.</param>
/// <returns>The 1-indexed position where the player must choose in order to win the game.</returns>
public static long FindWinner(long n, long k)
{
if (k <= 0)
{
throw new ArgumentException("The step cannot be smaller than 1");
}
if (k > n)
{
throw new ArgumentException("The step cannot be greater than the size of the group");
}
long winner = 0;
for (long stepIndex = 1; stepIndex <= n; ++stepIndex)
{
winner = (winner + k) % stepIndex;
}
return winner + 1;
}
}
| 34 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Numeric
{
/// <summary>
/// In number theory, a Keith number or repfigit number is a natural number n in a given number base b with k digits such that
/// when a sequence is created such that the first k terms are the k digits of n and each subsequent term is the sum of the
/// previous k terms, n is part of the sequence.
/// </summary>
public static class KeithNumberChecker
{
/// <summary>
/// Checks if a number is a Keith number or not.
/// </summary>
/// <param name="number">Number to check.</param>
/// <returns>True if it is a Keith number; False otherwise.</returns>
public static bool IsKeithNumber(int number)
{
if (number < 0)
{
throw new ArgumentException($"{nameof(number)} cannot be negative");
}
var tempNumber = number;
var stringNumber = number.ToString();
var digitsInNumber = stringNumber.Length;
/* storing the terms of the series */
var termsArray = new int[number];
for (var i = digitsInNumber - 1; i >= 0; i--)
{
termsArray[i] = tempNumber % 10;
tempNumber /= 10;
}
var sum = 0;
var k = digitsInNumber;
while (sum < number)
{
sum = 0;
for (var j = 1; j <= digitsInNumber; j++)
{
sum += termsArray[k - j];
}
termsArray[k] = sum;
k++;
}
return sum == number;
}
}
}
| 58 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Numeric
{
/// <summary>
/// A Krishnamurthy number is a number whose sum of the factorial of digits
/// is equal to the number itself.
///
/// For example, 145 is a Krishnamurthy number since: 1! + 4! + 5! = 1 + 24 + 120 = 145.
/// </summary>
public static class KrishnamurthyNumberChecker
{
/// <summary>
/// Check if a number is Krishnamurthy number or not.
/// </summary>
/// <param name="n">The number to check.</param>
/// <returns>True if the number is Krishnamurthy, false otherwise.</returns>
public static bool IsKMurthyNumber(int n)
{
int sumOfFactorials = 0;
int tmp = n;
if (n <= 0)
{
return false;
}
while (n != 0)
{
int factorial = (int)Factorial.Calculate(n % 10);
sumOfFactorials += factorial;
n = n / 10;
}
return tmp == sumOfFactorials;
}
}
}
| 39 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Numeric
{
/// <summary>
/// Modular exponentiation is a type of exponentiation performed over a modulus
/// Modular exponentiation c is: c = b^e mod m where b is base, e is exponent, m is modulus
/// (Wiki: https://en.wikipedia.org/wiki/Modular_exponentiation).
/// </summary>
public class ModularExponentiation
{
/// <summary>
/// Performs Modular Exponentiation on b, e, m.
/// </summary>
/// <param name="b">Base.</param>
/// <param name="e">Exponent.</param>
/// <param name="m">Modulus.</param>
/// <returns>Modular Exponential.</returns>
public int ModularPow(int b, int e, int m)
{
// initialize result in variable res
int res = 1;
if (m == 1)
{
// 1 divides every number
return 0;
}
if (m <= 0)
{
// exponential not defined in this case
throw new ArgumentException(string.Format("{0} is not a positive integer", m));
}
for (int i = 0; i < e; i++)
{
res = (res * b) % m;
}
return res;
}
}
}
| 44 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Numeric
{
/// <summary>
/// A Narcissistic number is equal to the sum of the cubes of its digits. For example, 370 is a
/// Narcissistic number because 3*3*3 + 7*7*7 + 0*0*0 = 370.
/// </summary>
public static class NarcissisticNumberChecker
{
/// <summary>
/// Checks if a number is a Narcissistic number or not.
/// </summary>
/// <param name="number">Number to check.</param>
/// <returns>True if is a Narcissistic number; False otherwise.</returns>
public static bool IsNarcissistic(int number)
{
var sum = 0;
var temp = number;
var numberOfDigits = 0;
while (temp != 0)
{
numberOfDigits++;
temp /= 10;
}
temp = number;
while (number > 0)
{
var remainder = number % 10;
var power = (int)Math.Pow(remainder, numberOfDigits);
sum += power;
number /= 10;
}
return sum == temp;
}
}
}
| 41 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Numeric
{
/// <summary>
/// In number theory, a perfect number is a positive integer that is equal to the sum of its positive
/// divisors, excluding the number itself.For instance, 6 has divisors 1, 2 and 3 (excluding
/// itself), and 1 + 2 + 3 = 6, so 6 is a perfect number.
/// </summary>
public static class PerfectNumberChecker
{
/// <summary>
/// Checks if a number is a perfect number or not.
/// </summary>
/// <param name="number">Number to check.</param>
/// <returns>True if is a perfect number; False otherwise.</returns>
/// <exception cref="ArgumentException">Error number is not on interval (0.0; int.MaxValue).</exception>
public static bool IsPerfectNumber(int number)
{
if (number < 0)
{
throw new ArgumentException($"{nameof(number)} cannot be negative");
}
var sum = 0; /* sum of its positive divisors */
for (var i = 1; i < number; ++i)
{
if (number % i == 0)
{
sum += i;
}
}
return sum == number;
}
}
}
| 38 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Numeric
{
/// <summary>
/// A perfect square is an element of algebraic structure that is equal to the square of another element.
/// </summary>
public static class PerfectSquareChecker
{
/// <summary>
/// Checks if a number is a perfect square or not.
/// </summary>
/// <param name="number">Number too check.</param>
/// <returns>True if is a perfect square; False otherwise.</returns>
public static bool IsPerfectSquare(int number)
{
if (number < 0)
{
return false;
}
var sqrt = (int)Math.Sqrt(number);
return sqrt * sqrt == number;
}
}
}
| 27 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
namespace Algorithms.Numeric
{
/// <summary>
/// In numerical analysis, the Runge–Kutta methods are a family of implicit and explicit iterative methods,
/// used in temporal discretization for the approximate solutions of simultaneous nonlinear equations.
/// The most widely known member of the Runge–Kutta family is generally referred to as
/// "RK4", the "classic Runge–Kutta method" or simply as "the Runge–Kutta method".
/// </summary>
public static class RungeKuttaMethod
{
/// <summary>
/// Loops through all the steps until xEnd is reached, adds a point for each step and then
/// returns all the points.
/// </summary>
/// <param name="xStart">Initial conditions x-value.</param>
/// <param name="xEnd">Last x-value.</param>
/// <param name="stepSize">Step-size on the x-axis.</param>
/// <param name="yStart">Initial conditions y-value.</param>
/// <param name="function">The right hand side of the differential equation.</param>
/// <returns>The solution of the Cauchy problem.</returns>
public static List<double[]> ClassicRungeKuttaMethod(
double xStart,
double xEnd,
double stepSize,
double yStart,
Func<double, double, double> function)
{
if (xStart >= xEnd)
{
throw new ArgumentOutOfRangeException(
nameof(xEnd),
$"{nameof(xEnd)} should be greater than {nameof(xStart)}");
}
if (stepSize <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(stepSize),
$"{nameof(stepSize)} should be greater than zero");
}
List<double[]> points = new();
double[] firstPoint = { xStart, yStart };
points.Add(firstPoint);
var yCurrent = yStart;
var xCurrent = xStart;
while (xCurrent < xEnd)
{
var k1 = function(xCurrent, yCurrent);
var k2 = function(xCurrent + 0.5 * stepSize, yCurrent + 0.5 * stepSize * k1);
var k3 = function(xCurrent + 0.5 * stepSize, yCurrent + 0.5 * stepSize * k2);
var k4 = function(xCurrent + stepSize, yCurrent + stepSize * k3);
yCurrent += (1.0 / 6.0) * stepSize * (k1 + 2 * k2 + 2 * k3 + k4);
xCurrent += stepSize;
double[] newPoint = { xCurrent, yCurrent };
points.Add(newPoint);
}
return points;
}
}
}
| 70 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Numeric.Decomposition
{
/// <summary>
/// LU-decomposition factors the "source" matrix as the product of lower triangular matrix
/// and upper triangular matrix.
/// </summary>
public static class Lu
{
/// <summary>
/// Performs LU-decomposition on "source" matrix.
/// Lower and upper matrices have same shapes as source matrix.
/// Note: Decomposition can be applied only to square matrices.
/// </summary>
/// <param name="source">Square matrix to decompose.</param>
/// <returns>Tuple of lower and upper matrix.</returns>
/// <exception cref="ArgumentException">Source matrix is not square shaped.</exception>
public static (double[,] L, double[,] U) Decompose(double[,] source)
{
if (source.GetLength(0) != source.GetLength(1))
{
throw new ArgumentException("Source matrix is not square shaped.");
}
var pivot = source.GetLength(0);
var lower = new double[pivot, pivot];
var upper = new double[pivot, pivot];
for (var i = 0; i < pivot; i++)
{
for (var k = i; k < pivot; k++)
{
double sum = 0;
for (var j = 0; j < i; j++)
{
sum += lower[i, j] * upper[j, k];
}
upper[i, k] = source[i, k] - sum;
}
for (var k = i; k < pivot; k++)
{
if (i == k)
{
lower[i, i] = 1;
}
else
{
double sum = 0;
for (var j = 0; j < i; j++)
{
sum += lower[k, j] * upper[j, i];
}
lower[k, i] = (source[k, i] - sum) / upper[i, i];
}
}
}
return (L: lower, U: upper);
}
/// <summary>
/// Eliminates linear equations system represented as A*x=b, using LU-decomposition,
/// where A - matrix of equation coefficients, b - vector of absolute terms of equations.
/// </summary>
/// <param name="matrix">Matrix of equation coefficients.</param>
/// <param name="coefficients">Vector of absolute terms of equations.</param>
/// <returns>Vector-solution for linear equations system.</returns>
/// <exception cref="ArgumentException">Matrix of equation coefficients is not square shaped.</exception>
public static double[] Eliminate(double[,] matrix, double[] coefficients)
{
if (matrix.GetLength(0) != matrix.GetLength(1))
{
throw new ArgumentException("Matrix of equation coefficients is not square shaped.");
}
var pivot = matrix.GetLength(0);
var upperTransform = new double[pivot, 1]; // U * upperTransform = coefficients
var solution = new double[pivot]; // L * solution = upperTransform
(double[,] l, double[,] u) = Decompose(matrix);
for (var i = 0; i < pivot; i++)
{
double pivotPointSum = 0;
for (var j = 0; j < i; j++)
{
pivotPointSum += upperTransform[j, 0] * l[i, j];
}
upperTransform[i, 0] = (coefficients[i] - pivotPointSum) / l[i, i];
}
for (var i = pivot - 1; i >= 0; i--)
{
double pivotPointSum = 0;
for (var j = i; j < pivot; j++)
{
pivotPointSum += solution[j] * u[i, j];
}
solution[i] = (upperTransform[i, 0] - pivotPointSum) / u[i, i];
}
return solution;
}
}
}
| 115 |
C-Sharp | TheAlgorithms | C# | using System;
using Utilities.Extensions;
using M = Utilities.Extensions.MatrixExtensions;
using V = Utilities.Extensions.VectorExtensions;
namespace Algorithms.Numeric.Decomposition
{
/// <summary>
/// Singular Vector Decomposition decomposes any general matrix into its
/// singular values and a set of orthonormal bases.
/// </summary>
public static class ThinSvd
{
/// <summary>
/// Computes a random unit vector.
/// </summary>
/// <param name="dimensions">The dimensions of the required vector.</param>
/// <returns>The unit vector.</returns>
public static double[] RandomUnitVector(int dimensions)
{
Random random = new();
double[] result = new double[dimensions];
for (var i = 0; i < dimensions; i++)
{
result[i] = 2 * random.NextDouble() - 1;
}
var magnitude = result.Magnitude();
result = result.Scale(1 / magnitude);
return result;
}
/// <summary>
/// Computes a single singular vector for the given matrix, corresponding to the largest singular value.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns>A singular vector, with dimension equal to number of columns of the matrix.</returns>
public static double[] Decompose1D(double[,] matrix) =>
Decompose1D(matrix, 1E-5, 100);
/// <summary>
/// Computes a single singular vector for the given matrix, corresponding to the largest singular value.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <param name="epsilon">The error margin.</param>
/// <param name="maxIterations">The maximum number of iterations.</param>
/// <returns>A singular vector, with dimension equal to number of columns of the matrix.</returns>
public static double[] Decompose1D(double[,] matrix, double epsilon, int maxIterations)
{
var n = matrix.GetLength(1);
var iterations = 0;
double mag;
double[] lastIteration;
double[] currIteration = RandomUnitVector(n);
double[,] b = matrix.Transpose().Multiply(matrix);
do
{
lastIteration = currIteration.Copy();
currIteration = b.MultiplyVector(lastIteration);
currIteration = currIteration.Scale(100);
mag = currIteration.Magnitude();
if (mag > epsilon)
{
currIteration = currIteration.Scale(1 / mag);
}
iterations++;
}
while (lastIteration.Dot(currIteration) < 1 - epsilon && iterations < maxIterations);
return currIteration;
}
public static (double[,] U, double[] S, double[,] V) Decompose(double[,] matrix) =>
Decompose(matrix, 1E-5, 100);
/// <summary>
/// Computes the SVD for the given matrix, with singular values arranged from greatest to least.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <param name="epsilon">The error margin.</param>
/// <param name="maxIterations">The maximum number of iterations.</param>
/// <returns>The SVD.</returns>
public static (double[,] U, double[] S, double[,] V) Decompose(
double[,] matrix,
double epsilon,
int maxIterations)
{
var m = matrix.GetLength(0);
var n = matrix.GetLength(1);
var numValues = Math.Min(m, n);
// sigmas is be a diagonal matrix, hence only a vector is needed
double[] sigmas = new double[numValues];
double[,] us = new double[m, numValues];
double[,] vs = new double[n, numValues];
// keep track of progress
double[,] remaining = matrix.Copy();
// for each singular value
for (var i = 0; i < numValues; i++)
{
// compute the v singular vector
double[] v = Decompose1D(remaining, epsilon, maxIterations);
double[] u = matrix.MultiplyVector(v);
// compute the contribution of this pair of singular vectors
double[,] contrib = u.OuterProduct(v);
// extract the singular value
var s = u.Magnitude();
// v and u should be unit vectors
if (s < epsilon)
{
u = new double[m];
v = new double[n];
}
else
{
u = u.Scale(1 / s);
}
// save u, v and s into the result
for (var j = 0; j < u.Length; j++)
{
us[j, i] = u[j];
}
for (var j = 0; j < v.Length; j++)
{
vs[j, i] = v[j];
}
sigmas[i] = s;
// remove the contribution of this pair and compute the rest
remaining = remaining.Subtract(contrib);
}
return (U: us, S: sigmas, V: vs);
}
}
}
| 146 |
C-Sharp | TheAlgorithms | C# | namespace Algorithms.Numeric.Factorization
{
/// <summary>
/// Finds a factor of a given number or returns false if it's prime.
/// </summary>
public interface IFactorizer
{
/// <summary>
/// Finds a factor of a given number or returns false if it's prime.
/// </summary>
/// <param name="n">Integer to factor.</param>
/// <param name="factor">Found factor.</param>
/// <returns><see langword="true" /> if factor is found, <see langword="false" /> if <paramref name="n" /> is prime.</returns>
bool TryFactor(int n, out int factor);
}
}
| 17 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Linq;
namespace Algorithms.Numeric.Factorization
{
/// <summary>
/// Factors number using trial division algorithm.
/// </summary>
public class TrialDivisionFactorizer : IFactorizer
{
/// <summary>
/// Finds the smallest non trivial factor (i.e.: 1 < factor <= sqrt(<paramref name="n" />)) of a given number or returns false if it's prime.
/// </summary>
/// <param name="n">Integer to factor.</param>
/// <param name="factor">Found factor.</param>
/// <returns><see langword="true" /> if factor is found, <see langword="false" /> if <paramref name="n" /> is prime.</returns>
public bool TryFactor(int n, out int factor)
{
n = Math.Abs(n);
factor = Enumerable.Range(2, (int)Math.Sqrt(n) - 1).FirstOrDefault(i => n % i == 0);
return factor != 0;
}
}
}
| 25 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Numeric.GreatestCommonDivisor
{
/// <summary>
/// Finds greatest common divisor for numbers u and v
/// using binary algorithm.
/// Wiki: https://en.wikipedia.org/wiki/Binary_GCD_algorithm.
/// </summary>
public class BinaryGreatestCommonDivisorFinder : IGreatestCommonDivisorFinder
{
public int FindGcd(int u, int v)
{
// GCD(0, 0) = 0
if (u == 0 && v == 0)
{
return 0;
}
// GCD(0, v) = v; GCD(u, 0) = u
if (u == 0 || v == 0)
{
return u + v;
}
// GCD(-a, -b) = GCD(-a, b) = GCD(a, -b) = GCD(a, b)
u = Math.Sign(u) * u;
v = Math.Sign(v) * v;
// Let shift := lg K, where K is the greatest power of 2 dividing both u and v
var shift = 0;
while (((u | v) & 1) == 0)
{
u >>= 1;
v >>= 1;
shift++;
}
while ((u & 1) == 0)
{
u >>= 1;
}
// From here on, u is always odd
do
{
// Remove all factors of 2 in v as they are not common
// v is not zero, so while will terminate
while ((v & 1) == 0)
{
v >>= 1;
}
// Now u and v are both odd. Swap if necessary so u <= v,
if (u > v)
{
var t = v;
v = u;
u = t;
}
// Here v >= u and v - u is even
v -= u;
}
while (v != 0);
// Restore common factors of 2
return u << shift;
}
}
}
| 72 |
C-Sharp | TheAlgorithms | C# | namespace Algorithms.Numeric.GreatestCommonDivisor
{
/// <summary>
/// TODO.
/// </summary>
public class EuclideanGreatestCommonDivisorFinder : IGreatestCommonDivisorFinder
{
/// <summary>
/// Finds greatest common divisor for numbers a and b
/// using euclidean algorithm.
/// </summary>
/// <param name="a">TODO.</param>
/// <param name="b">TODO. 2.</param>
/// <returns>Greatest common divisor.</returns>
public int FindGcd(int a, int b)
{
if (a == 0 && b == 0)
{
return int.MaxValue;
}
if (a == 0 || b == 0)
{
return a + b;
}
var aa = a;
var bb = b;
var cc = aa % bb;
while (cc != 0)
{
aa = bb;
bb = cc;
cc = aa % bb;
}
return bb;
}
}
}
| 42 |
C-Sharp | TheAlgorithms | C# | namespace Algorithms.Numeric.GreatestCommonDivisor
{
public interface IGreatestCommonDivisorFinder
{
int FindGcd(int a, int b);
}
}
| 8 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Numeric.Decomposition;
using Utilities.Extensions;
namespace Algorithms.Numeric.Pseudoinverse
{
/// <summary>
/// The Moore–Penrose pseudo-inverse A+ of a matrix A,
/// is a general way to find the solution to the following system of linear equations:
/// ~b = A ~y. ~b e R^m; ~y e R^n; A e Rm×n.
/// There are varios methods for construction the pseudo-inverse.
/// This one is based on Singular Value Decomposition (SVD).
/// </summary>
public static class PseudoInverse
{
/// <summary>
/// Return the pseudoinverse of a matrix based on the Moore-Penrose Algorithm.
/// using Singular Value Decomposition (SVD).
/// </summary>
/// <param name="inMat">Input matrix to find its inverse to.</param>
/// <returns>The inverse matrix approximation of the input matrix.</returns>
public static double[,] PInv(double[,] inMat)
{
// To compute the SVD of the matrix to find Sigma.
var (u, s, v) = ThinSvd.Decompose(inMat);
// To take the reciprocal of each non-zero element on the diagonal.
var len = s.Length;
var sigma = new double[len];
for (var i = 0; i < len; i++)
{
sigma[i] = Math.Abs(s[i]) < 0.0001 ? 0 : 1 / s[i];
}
// To construct a diagonal matrix based on the vector result.
var diag = sigma.ToDiagonalMatrix();
// To construct the pseudo-inverse using the computed information above.
var matinv = u.Multiply(diag).Multiply(v.Transpose());
// To Transpose the result matrix.
return matinv.Transpose();
}
}
}
| 47 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Linq;
namespace Algorithms.Numeric.Series
{
/// <summary>
/// Maclaurin series calculates nonlinear functions approximation
/// starting from point x = 0 in a form of infinite power series:
/// f(x) = f(0) + f'(0) * x + ... + (f'n(0) * (x ^ n)) / n! + ...,
/// where n is natural number.
/// </summary>
public static class Maclaurin
{
/// <summary>
/// Calculates approximation of e^x function:
/// e^x = 1 + x + x^2 / 2! + ... + x^n / n! + ...,
/// where n is number of terms (natural number),
/// and x is given point (rational number).
/// </summary>
/// <param name="x">Given point.</param>
/// <param name="n">The number of terms in polynomial.</param>
/// <returns>Approximated value of the function in the given point.</returns>
public static double Exp(double x, int n) =>
Enumerable.Range(0, n).Sum(i => ExpTerm(x, i));
/// <summary>
/// Calculates approximation of sin(x) function:
/// sin(x) = x - x^3 / 3! + ... + (-1)^n * x^(2*n + 1) / (2*n + 1)! + ...,
/// where n is number of terms (natural number),
/// and x is given point (rational number).
/// </summary>
/// <param name="x">Given point.</param>
/// <param name="n">The number of terms in polynomial.</param>
/// <returns>Approximated value of the function in the given point.</returns>
public static double Sin(double x, int n) =>
Enumerable.Range(0, n).Sum(i => SinTerm(x, i));
/// <summary>
/// Calculates approximation of cos(x) function:
/// cos(x) = 1 - x^2 / 2! + ... + (-1)^n * x^(2*n) / (2*n)! + ...,
/// where n is number of terms (natural number),
/// and x is given point (rational number).
/// </summary>
/// <param name="x">Given point.</param>
/// <param name="n">The number of terms in polynomial.</param>
/// <returns>Approximated value of the function in the given point.</returns>
public static double Cos(double x, int n) =>
Enumerable.Range(0, n).Sum(i => CosTerm(x, i));
/// <summary>
/// Calculates approximation of e^x function:
/// e^x = 1 + x + x^2 / 2! + ... + x^n / n! + ...,
/// and x is given point (rational number).
/// </summary>
/// <param name="x">Given point.</param>
/// <param name="error">Last term error value.</param>
/// <returns>Approximated value of the function in the given point.</returns>
/// <exception cref="ArgumentException">Error value is not on interval (0.0; 1.0).</exception>
public static double Exp(double x, double error = 0.00001) => ErrorTermWrapper(x, error, ExpTerm);
/// <summary>
/// Calculates approximation of sin(x) function:
/// sin(x) = x - x^3 / 3! + ... + (-1)^n * x^(2*n + 1) / (2*n + 1)! + ...,
/// and x is given point (rational number).
/// </summary>
/// <param name="x">Given point.</param>
/// <param name="error">Last term error value.</param>
/// <returns>Approximated value of the function in the given point.</returns>
/// <exception cref="ArgumentException">Error value is not on interval (0.0; 1.0).</exception>
public static double Sin(double x, double error = 0.00001) => ErrorTermWrapper(x, error, SinTerm);
/// <summary>
/// Calculates approximation of cos(x) function:
/// cos(x) = 1 - x^2 / 2! + ... + (-1)^n * x^(2*n) / (2*n)! + ...,
/// and x is given point (rational number).
/// </summary>
/// <param name="x">Given point.</param>
/// <param name="error">Last term error value.</param>
/// <returns>Approximated value of the function in the given point.</returns>
/// <exception cref="ArgumentException">Error value is not on interval (0.0; 1.0).</exception>
public static double Cos(double x, double error = 0.00001) => ErrorTermWrapper(x, error, CosTerm);
/// <summary>
/// Wrapper function for calculating approximation with estimated
/// count of terms, where last term value is less than given error.
/// </summary>
/// <param name="x">Given point.</param>
/// <param name="error">Last term error value.</param>
/// <param name="term">Indexed term of approximation series.</param>
/// <returns>Approximated value of the function in the given point.</returns>
/// <exception cref="ArgumentException">Error value is not on interval (0.0; 1.0).</exception>
private static double ErrorTermWrapper(double x, double error, Func<double, int, double> term)
{
if (error <= 0.0 || error >= 1.0)
{
throw new ArgumentException("Error value is not on interval (0.0; 1.0).");
}
var i = 0;
var termCoefficient = 0.0;
var result = 0.0;
do
{
result += termCoefficient;
termCoefficient = term(x, i);
i++;
}
while (Math.Abs(termCoefficient) > error);
return result;
}
/// <summary>
/// Single term for e^x function approximation: x^i / i!.
/// </summary>
/// <param name="x">Given point.</param>
/// <param name="i">Term index from 0 to n.</param>
/// <returns>Single term value.</returns>
private static double ExpTerm(double x, int i) => Math.Pow(x, i) / (long)Factorial.Calculate(i);
/// <summary>
/// Single term for sin(x) function approximation: (-1)^i * x^(2*i + 1) / (2*i + 1)!.
/// </summary>
/// <param name="x">Given point.</param>
/// <param name="i">Term index from 0 to n.</param>
/// <returns>Single term value.</returns>
private static double SinTerm(double x, int i) =>
Math.Pow(-1, i) / ((long)Factorial.Calculate(2 * i + 1)) * Math.Pow(x, 2 * i + 1);
/// <summary>
/// Single term for cos(x) function approximation: (-1)^i * x^(2*i) / (2*i)!.
/// </summary>
/// <param name="x">Given point.</param>
/// <param name="i">Term index from 0 to n.</param>
/// <returns>Single term value.</returns>
private static double CosTerm(double x, int i) =>
Math.Pow(-1, i) / ((long)Factorial.Calculate(2 * i)) * Math.Pow(x, 2 * i);
}
}
| 141 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms.Other
{
/// <summary>
/// Almost all real complex decision-making task is described by more than one criterion.
/// There are different methods to select the best decisions from the defined set of decisions.
/// This class contains implementations of the popular convolution methods: linear and maxmin.
/// </summary>
public static class DecisionsConvolutions
{
/// <summary>
/// This method implements the linear method of decision selection. It is based on
/// the calculation of the "value" for each decision and the selection of the most
/// valuable one.
/// </summary>
/// <param name="matrix">Contains a collection of the criteria sets.</param>
/// <param name="priorities">Contains a set of priorities for each criterion.</param>
/// <returns>The most effective decision that is represented by a set of criterias.</returns>
public static List<decimal> Linear(List<List<decimal>> matrix, List<decimal> priorities)
{
var decisionValues = new List<decimal>();
foreach (var decision in matrix)
{
decimal sum = 0;
for (int i = 0; i < decision.Count; i++)
{
sum += decision[i] * priorities[i];
}
decisionValues.Add(sum);
}
decimal bestDecisionValue = decisionValues.Max();
int bestDecisionIndex = decisionValues.IndexOf(bestDecisionValue);
return matrix[bestDecisionIndex];
}
/// <summary>
/// This method implements maxmin method of the decision selection. It is based on
/// the calculation of the least criteria value and comparison of decisions based
/// on the calculated results.
/// </summary>
/// <param name="matrix">Contains a collection of the criteria sets.</param>
/// <param name="priorities">Contains a set of priorities for each criterion.</param>
/// <returns>The most effective decision that is represented by a set of criterias.</returns>
public static List<decimal> MaxMin(List<List<decimal>> matrix, List<decimal> priorities)
{
var decisionValues = new List<decimal>();
foreach (var decision in matrix)
{
decimal minValue = decimal.MaxValue;
for (int i = 0; i < decision.Count; i++)
{
decimal result = decision[i] * priorities[i];
if (result < minValue)
{
minValue = result;
}
}
decisionValues.Add(minValue);
}
decimal bestDecisionValue = decisionValues.Max();
int bestDecisionIndex = decisionValues.IndexOf(bestDecisionValue);
return matrix[bestDecisionIndex];
}
}
}
| 79 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Numerics;
namespace Algorithms.Other
{
/// <summary>
/// Fermat's prime tester https://en.wikipedia.org/wiki/Fermat_primality_test.
/// </summary>
public static class FermatPrimeChecker
{
/// <summary>
/// Checks if input number is a probable prime.
/// </summary>
/// <param name="numberToTest">Input number.</param>
/// <param name="timesToCheck">Number of times to check.</param>
/// <returns>True if is a prime; False otherwise.</returns>
public static bool IsPrime(int numberToTest, int timesToCheck)
{
// You have to use BigInteger for two reasons:
// 1. The pow operation between two int numbers usually overflows an int
// 2. The pow and modular operation is very optimized
var numberToTestBigInteger = new BigInteger(numberToTest);
var exponentBigInteger = new BigInteger(numberToTest - 1);
// Create a random number generator using the current time as seed
var r = new Random(default(DateTime).Millisecond);
var iterator = 1;
var prime = true;
while (iterator < timesToCheck && prime)
{
var randomNumber = r.Next(1, numberToTest);
var randomNumberBigInteger = new BigInteger(randomNumber);
if (BigInteger.ModPow(randomNumberBigInteger, exponentBigInteger, numberToTestBigInteger) != 1)
{
prime = false;
}
iterator++;
}
return prime;
}
}
}
| 47 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Numerics;
namespace Algorithms.Other
{
/// <summary>
/// Flood fill, also called seed fill, is an algorithm that determines and
/// alters the area connected to a given node in a multi-dimensional array with
/// some matching attribute. It is used in the "bucket" fill tool of paint
/// programs to fill connected, similarly-colored areas with a different color.
/// (description adapted from https://en.wikipedia.org/wiki/Flood_fill)
/// (see also: https://www.techiedelight.com/flood-fill-algorithm/).
/// </summary>
public static class FloodFill
{
private static readonly List<(int xOffset, int yOffset)> Neighbors = new() { (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1) };
/// <summary>
/// Implements the flood fill algorithm through a breadth-first approach using a queue.
/// </summary>
/// <param name="bitmap">The bitmap to which the algorithm is applied.</param>
/// <param name="location">The start location on the bitmap.</param>
/// <param name="targetColor">The old color to be replaced.</param>
/// <param name="replacementColor">The new color to replace the old one.</param>
public static void BreadthFirstSearch(Bitmap bitmap, (int x, int y) location, Color targetColor, Color replacementColor)
{
if (location.x < 0 || location.x >= bitmap.Width || location.y < 0 || location.y >= bitmap.Height)
{
throw new ArgumentOutOfRangeException(nameof(location), $"{nameof(location)} should point to a pixel within the bitmap");
}
var queue = new List<(int x, int y)>();
queue.Add(location);
while (queue.Count > 0)
{
BreadthFirstFill(bitmap, location, targetColor, replacementColor, queue);
}
}
/// <summary>
/// Implements the flood fill algorithm through a depth-first approach through recursion.
/// </summary>
/// <param name="bitmap">The bitmap to which the algorithm is applied.</param>
/// <param name="location">The start location on the bitmap.</param>
/// <param name="targetColor">The old color to be replaced.</param>
/// <param name="replacementColor">The new color to replace the old one.</param>
public static void DepthFirstSearch(Bitmap bitmap, (int x, int y) location, Color targetColor, Color replacementColor)
{
if (location.x < 0 || location.x >= bitmap.Width || location.y < 0 || location.y >= bitmap.Height)
{
throw new ArgumentOutOfRangeException(nameof(location), $"{nameof(location)} should point to a pixel within the bitmap");
}
DepthFirstFill(bitmap, location, targetColor, replacementColor);
}
private static void BreadthFirstFill(Bitmap bitmap, (int x, int y) location, Color targetColor, Color replacementColor, List<(int x, int y)> queue)
{
(int x, int y) currentLocation = queue[0];
queue.RemoveAt(0);
if (bitmap.GetPixel(currentLocation.x, currentLocation.y) == targetColor)
{
bitmap.SetPixel(currentLocation.x, currentLocation.y, replacementColor);
for (int i = 0; i < Neighbors.Count; i++)
{
int x = currentLocation.x + Neighbors[i].xOffset;
int y = currentLocation.y + Neighbors[i].yOffset;
if (x >= 0 && x < bitmap.Width && y >= 0 && y < bitmap.Height)
{
queue.Add((x, y));
}
}
}
}
private static void DepthFirstFill(Bitmap bitmap, (int x, int y) location, Color targetColor, Color replacementColor)
{
if (bitmap.GetPixel(location.x, location.y) == targetColor)
{
bitmap.SetPixel(location.x, location.y, replacementColor);
for (int i = 0; i < Neighbors.Count; i++)
{
int x = location.x + Neighbors[i].xOffset;
int y = location.y + Neighbors[i].yOffset;
if (x >= 0 && x < bitmap.Width && y >= 0 && y < bitmap.Height)
{
DepthFirstFill(bitmap, (x, y), targetColor, replacementColor);
}
}
}
}
}
}
| 100 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms.Other
{
/// <summary>
/// The Gaussian method (coordinate descent method) refers to zero-order methods in which only the value
/// of the function Q(X) at different points in the space of variables is used to organize the search
/// for the extremum. This reduces the overall computational cost of finding the extremum. Also in
/// the Gaussian method, the procedures for finding and moving the operating point are simplified as
/// much as possible.
/// </summary>
public class GaussOptimization
{
/// <summary>
/// Implementation of function extremum search by the Gauss optimization algorithm.
/// </summary>
/// <param name="func">Function for which extremum has to be found.</param>
/// <param name="n">This parameter identifies how much step size will be decreased each iteration.</param>
/// <param name="step">The initial shift step.</param>
/// <param name="eps">This value is used to control the accuracy of the optimization. In case if the error is less than eps,
/// optimization will be stopped.</param>
/// <param name="x1">The first function parameter.</param>
/// <param name="x2">The second function parameter.</param>
/// <returns>A tuple of coordinates of function extremum.</returns>
public (double, double) Optimize(
Func<double, double, double> func,
double n,
double step,
double eps,
double x1,
double x2)
{
// The initial value of the error
double error = 1;
while (Math.Abs(error) > eps)
{
// Calculation of the function with coordinates that are calculated with shift
double bottom = func(x1, x2 - step);
double top = func(x1, x2 + step);
double left = func(x1 - step, x2);
double right = func(x1 + step, x2);
// Determination of the best option.
var possibleFunctionValues = new List<double> { bottom, top, left, right };
double maxValue = possibleFunctionValues.Max();
double maxValueIndex = possibleFunctionValues.IndexOf(maxValue);
// Error evaluation
error = maxValue - func(x1, x2);
// Coordinates update for the best option
switch (maxValueIndex)
{
case 0:
x2 -= step;
break;
case 1:
x2 += step;
break;
case 2:
x1 -= step;
break;
default:
x1 += step;
break;
}
// Step reduction
step /= n;
}
return (x1, x2);
}
}
}
| 81 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Other
{
public static class GeoLocation
{
private const double EarthRadiusKm = 6371.01d;
/// <summary>
/// Calculates spherical distance between 2 points given their latitude, longitude coordinates.
/// https://www.movable-type.co.uk/scripts/latlong.html.
/// </summary>
/// <param name="lat1">Latitude of point A.</param>
/// <param name="lng1">Longitude of point A.</param>
/// <param name="lat2">Latitude of point B.</param>
/// <param name="lng2">Longitude of point B.</param>
/// <returns>Spherical distance between A and B.</returns>
public static double CalculateDistanceFromLatLng(double lat1, double lng1, double lat2, double lng2)
{
var pi180 = Math.PI / 180d;
var lat1Radian = lat1 * pi180;
var lng1Radian = lng1 * pi180;
var lat2Radian = lat2 * pi180;
var lng2Radian = lng2 * pi180;
var diffLat = lat2Radian - lat1Radian;
var diffLng = lng2Radian - lng1Radian;
var haversine =
Math.Sin(diffLat / 2) * Math.Sin(diffLat / 2)
+ Math.Cos(lat1Radian) * Math.Cos(lat2Radian) * Math.Sin(diffLng / 2) * Math.Sin(diffLng / 2);
var distance = EarthRadiusKm * (2d * Math.Atan2(Math.Sqrt(haversine), Math.Sqrt(1 - haversine)));
return distance * 1000; // Convert from km -> m
}
}
}
| 38 |
C-Sharp | TheAlgorithms | C# | using System.Text;
namespace Algorithms.Other
{
/// <summary>
/// Manually converts an integer of certain size to a string of the binary representation.
/// </summary>
public static class Int2Binary
{
/// <summary>
/// Returns string of the binary representation of given Int.
/// </summary>
/// <param name="input">Number to be converted.</param>
/// <returns>Binary representation of input.</returns>
public static string Int2Bin(ushort input)
{
ushort msb = ushort.MaxValue / 2 + 1;
var output = new StringBuilder();
for (var i = 0; i < 16; i++)
{
if (input >= msb)
{
output.Append("1");
input -= msb;
msb /= 2;
}
else
{
output.Append("0");
msb /= 2;
}
}
return output.ToString();
}
/// <summary>
/// Returns string of the binary representation of given Int.
/// </summary>
/// <param name="input">Number to be converted.</param>
/// <returns>Binary representation of input.</returns>
public static string Int2Bin(uint input)
{
var msb = uint.MaxValue / 2 + 1;
var output = new StringBuilder();
for (var i = 0; i < 32; i++)
{
if (input >= msb)
{
output.Append("1");
input -= msb;
msb /= 2;
}
else
{
output.Append("0");
msb /= 2;
}
}
return output.ToString();
}
/// <summary>
/// Returns string of the binary representation of given Int.
/// </summary>
/// <param name="input">Number to be converted.</param>
/// <returns>Binary representation of input.</returns>
public static string Int2Bin(ulong input)
{
var msb = ulong.MaxValue / 2 + 1;
var output = new StringBuilder();
for (var i = 0; i < 64; i++)
{
if (input >= msb)
{
output.Append("1");
input -= msb;
msb /= 2;
}
else
{
output.Append("0");
msb /= 2;
}
}
return output.ToString();
}
}
}
| 92 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Globalization;
namespace Algorithms.Other
{
/// <summary>
/// Date of Easter calculated with Meeus's Julian algorithm.
/// The algorithm is described in Jean Meeus' <a href="https://archive.org/details/astronomicalalgorithmsjeanmeeus1991/page/n73/mode/2up">Astronomical Algorithms (1991, p. 69)</a>.
/// </summary>
public static class JulianEaster
{
/// <summary>
/// Calculates the date of Easter.
/// </summary>
/// <param name="year">Year to calculate the date of Easter.</param>
/// <returns>Date of Easter as a DateTime.</returns>
public static DateTime Calculate(int year)
{
var a = year % 4;
var b = year % 7;
var c = year % 19;
var d = (19 * c + 15) % 30;
var e = (2 * a + 4 * b - d + 34) % 7;
var month = (int)Math.Floor((d + e + 114) / 31M);
var day = ((d + e + 114) % 31) + 1;
DateTime easter = new(year, month, day, new JulianCalendar());
return easter;
}
}
}
| 33 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Numerics;
namespace Algorithms.Other
{
/// <summary>
/// The Koch snowflake is a fractal curve and one of the earliest fractals to
/// have been described. The Koch snowflake can be built up iteratively, in a
/// sequence of stages. The first stage is an equilateral triangle, and each
/// successive stage is formed by adding outward bends to each side of the
/// previous stage, making smaller equilateral triangles.
/// This can be achieved through the following steps for each line:
/// 1. divide the line segment into three segments of equal length.
/// 2. draw an equilateral triangle that has the middle segment from step 1
/// as its base and points outward.
/// 3. remove the line segment that is the base of the triangle from step 2.
/// (description adapted from https://en.wikipedia.org/wiki/Koch_snowflake )
/// (for a more detailed explanation and an implementation in the
/// Processing language, see https://natureofcode.com/book/chapter-8-fractals/
/// #84-the-koch-curve-and-the-arraylist-technique ).
/// </summary>
public static class KochSnowflake
{
/// <summary>
/// Go through the number of iterations determined by the argument "steps".
/// Be careful with high values (above 5) since the time to calculate increases
/// exponentially.
/// </summary>
/// <param name="initialVectors">
/// The vectors composing the shape to which
/// the algorithm is applied.
/// </param>
/// <param name="steps">The number of iterations.</param>
/// <returns>The transformed vectors after the iteration-steps.</returns>
public static List<Vector2> Iterate(List<Vector2> initialVectors, int steps = 5)
{
List<Vector2> vectors = initialVectors;
for (var i = 0; i < steps; i++)
{
vectors = IterationStep(vectors);
}
return vectors;
}
/// <summary>
/// Method to render the Koch snowflake to a bitmap. To save the
/// bitmap the command 'GetKochSnowflake().Save("KochSnowflake.png")' can be used.
/// </summary>
/// <param name="bitmapWidth">The width of the rendered bitmap.</param>
/// <param name="steps">The number of iterations.</param>
/// <returns>The bitmap of the rendered Koch snowflake.</returns>
public static Bitmap GetKochSnowflake(
int bitmapWidth = 600,
int steps = 5)
{
if (bitmapWidth <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(bitmapWidth),
$"{nameof(bitmapWidth)} should be greater than zero");
}
var offsetX = bitmapWidth / 10f;
var offsetY = bitmapWidth / 3.7f;
var vector1 = new Vector2(offsetX, offsetY);
var vector2 = new Vector2(bitmapWidth / 2, (float)Math.Sin(Math.PI / 3) * bitmapWidth * 0.8f + offsetY);
var vector3 = new Vector2(bitmapWidth - offsetX, offsetY);
List<Vector2> initialVectors = new() { vector1, vector2, vector3, vector1 };
List<Vector2> vectors = Iterate(initialVectors, steps);
return GetBitmap(vectors, bitmapWidth, bitmapWidth);
}
/// <summary>
/// Loops through each pair of adjacent vectors. Each line between two adjacent
/// vectors is divided into 4 segments by adding 3 additional vectors in-between
/// the original two vectors. The vector in the middle is constructed through a
/// 60 degree rotation so it is bent outwards.
/// </summary>
/// <param name="vectors">
/// The vectors composing the shape to which
/// the algorithm is applied.
/// </param>
/// <returns>The transformed vectors after the iteration-step.</returns>
private static List<Vector2> IterationStep(List<Vector2> vectors)
{
List<Vector2> newVectors = new();
for (var i = 0; i < vectors.Count - 1; i++)
{
var startVector = vectors[i];
var endVector = vectors[i + 1];
newVectors.Add(startVector);
var differenceVector = endVector - startVector;
newVectors.Add(startVector + differenceVector / 3);
newVectors.Add(startVector + differenceVector / 3 + Rotate(differenceVector / 3, 60));
newVectors.Add(startVector + differenceVector * 2 / 3);
}
newVectors.Add(vectors[^1]);
return newVectors;
}
/// <summary>
/// Standard rotation of a 2D vector with a rotation matrix
/// (see https://en.wikipedia.org/wiki/Rotation_matrix ).
/// </summary>
/// <param name="vector">The vector to be rotated.</param>
/// <param name="angleInDegrees">The angle by which to rotate the vector.</param>
/// <returns>The rotated vector.</returns>
private static Vector2 Rotate(Vector2 vector, float angleInDegrees)
{
var radians = angleInDegrees * (float)Math.PI / 180;
var ca = (float)Math.Cos(radians);
var sa = (float)Math.Sin(radians);
return new Vector2(ca * vector.X - sa * vector.Y, sa * vector.X + ca * vector.Y);
}
/// <summary>
/// Utility-method to render the Koch snowflake to a bitmap.
/// </summary>
/// <param name="vectors">The vectors defining the edges to be rendered.</param>
/// <param name="bitmapWidth">The width of the rendered bitmap.</param>
/// <param name="bitmapHeight">The height of the rendered bitmap.</param>
/// <returns>The bitmap of the rendered edges.</returns>
private static Bitmap GetBitmap(
List<Vector2> vectors,
int bitmapWidth,
int bitmapHeight)
{
Bitmap bitmap = new(bitmapWidth, bitmapHeight);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
// Set the background white
var imageSize = new Rectangle(0, 0, bitmapWidth, bitmapHeight);
graphics.FillRectangle(Brushes.White, imageSize);
// Draw the edges
for (var i = 0; i < vectors.Count - 1; i++)
{
Pen blackPen = new(Color.Black, 1);
var x1 = vectors[i].X;
var y1 = vectors[i].Y;
var x2 = vectors[i + 1].X;
var y2 = vectors[i + 1].Y;
graphics.DrawLine(blackPen, x1, y1, x2, y2);
}
}
return bitmap;
}
}
}
| 158 |
C-Sharp | TheAlgorithms | C# | using System;
namespace Algorithms.Other
{
/// <summary>
/// Luhn algorithm is a simple
/// checksum formula used to validate
/// a variety of identification numbers,
/// such as credit card numbers.
/// More information on the link:
/// https://en.wikipedia.org/wiki/Luhn_algorithm.
/// </summary>
public static class Luhn
{
/// <summary>
/// Checking the validity of a sequence of numbers.
/// </summary>
/// <param name="number">The number that will be checked for validity.</param>
/// <returns>
/// True: Number is valid.
/// False: Number isn`t valid.
/// </returns>
public static bool Validate(string number) => GetSum(number) % 10 == 0;
/// <summary>
/// This algorithm only finds one number.
/// In place of the unknown digit, put "x".
/// </summary>
/// <param name="number">The number in which to find the missing digit.</param>
/// <returns>Missing digit.</returns>
public static int GetLostNum(string number)
{
var lostIndex = number.Length - 1 - number.LastIndexOf("x", StringComparison.CurrentCultureIgnoreCase);
var lostNum = GetSum(number.Replace("x", "0", StringComparison.CurrentCultureIgnoreCase)) * 9 % 10;
// Case 1: If the index of the lost digit is even.
if (lostIndex % 2 == 0)
{
return lostNum;
}
var tempLostNum = lostNum / 2;
// Case 2: if the index of the lost digit isn`t even and that number <= 4.
// Case 3: if the index of the lost digit isn`t even and that number > 4.
return Validate(number.Replace("x", tempLostNum.ToString())) ? tempLostNum : (lostNum + 9) / 2;
}
/// <summary>
/// Computes the sum found by the algorithm.
/// </summary>
/// <param name="number">The number for which the sum will be found.</param>
/// <returns>Sum.</returns>
private static int GetSum(string number)
{
var sum = 0;
for (var i = 0; i < number.Length; i++)
{
var d = number[i] - '0';
d = (i + number.Length) % 2 == 0
? 2 * d
: d;
if (d > 9)
{
d -= 9;
}
sum += d;
}
return sum;
}
}
}
| 75 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Drawing;
namespace Algorithms.Other
{
/// <summary>
/// The Mandelbrot set is the set of complex numbers "c" for which the series
/// "z_(n+1) = z_n * z_n + c" does not diverge, i.e. remains bounded. Thus, a
/// complex number "c" is a member of the Mandelbrot set if, when starting with
/// "z_0 = 0" and applying the iteration repeatedly, the absolute value of
/// "z_n" remains bounded for all "n > 0". Complex numbers can be written as
/// "a + b*i": "a" is the real component, usually drawn on the x-axis, and "b*i"
/// is the imaginary component, usually drawn on the y-axis. Most visualizations
/// of the Mandelbrot set use a color-coding to indicate after how many steps in
/// the series the numbers outside the set cross the divergence threshold.
/// Images of the Mandelbrot set exhibit an elaborate and infinitely
/// complicated boundary that reveals progressively ever-finer recursive detail
/// at increasing magnifications, making the boundary of the Mandelbrot set a
/// fractal curve.
/// (description adapted from https://en.wikipedia.org/wiki/Mandelbrot_set)
/// (see also https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set).
/// </summary>
public static class Mandelbrot
{
/// <summary>
/// Method to generate the bitmap of the Mandelbrot set. Two types of coordinates
/// are used: bitmap-coordinates that refer to the pixels and figure-coordinates
/// that refer to the complex numbers inside and outside the Mandelbrot set. The
/// figure-coordinates in the arguments of this method determine which section
/// of the Mandelbrot set is viewed. The main area of the Mandelbrot set is
/// roughly between "-1.5 < x < 0.5" and "-1 < y < 1" in the figure-coordinates.
/// To save the bitmap the command 'GetBitmap().Save("Mandelbrot.png")' can be used.
/// </summary>
/// <param name="bitmapWidth">The width of the rendered bitmap.</param>
/// <param name="bitmapHeight">The height of the rendered bitmap.</param>
/// <param name="figureCenterX">The x-coordinate of the center of the figure.</param>
/// <param name="figureCenterY">The y-coordinate of the center of the figure.</param>
/// <param name="figureWidth">The width of the figure.</param>
/// <param name="maxStep">Maximum number of steps to check for divergent behavior.</param>
/// <param name="useDistanceColorCoding">Render in color or black and white.</param>
/// <returns>The bitmap of the rendered Mandelbrot set.</returns>
public static Bitmap GetBitmap(
int bitmapWidth = 800,
int bitmapHeight = 600,
double figureCenterX = -0.6,
double figureCenterY = 0,
double figureWidth = 3.2,
int maxStep = 50,
bool useDistanceColorCoding = true)
{
if (bitmapWidth <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(bitmapWidth),
$"{nameof(bitmapWidth)} should be greater than zero");
}
if (bitmapHeight <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(bitmapHeight),
$"{nameof(bitmapHeight)} should be greater than zero");
}
if (maxStep <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(maxStep),
$"{nameof(maxStep)} should be greater than zero");
}
var bitmap = new Bitmap(bitmapWidth, bitmapHeight);
var figureHeight = figureWidth / bitmapWidth * bitmapHeight;
// loop through the bitmap-coordinates
for (var bitmapX = 0; bitmapX < bitmapWidth; bitmapX++)
{
for (var bitmapY = 0; bitmapY < bitmapHeight; bitmapY++)
{
// determine the figure-coordinates based on the bitmap-coordinates
var figureX = figureCenterX + ((double)bitmapX / bitmapWidth - 0.5) * figureWidth;
var figureY = figureCenterY + ((double)bitmapY / bitmapHeight - 0.5) * figureHeight;
var distance = GetDistance(figureX, figureY, maxStep);
// color the corresponding pixel based on the selected coloring-function
bitmap.SetPixel(
bitmapX,
bitmapY,
useDistanceColorCoding ? ColorCodedColorMap(distance) : BlackAndWhiteColorMap(distance));
}
}
return bitmap;
}
/// <summary>
/// Black and white color-coding that ignores the relative distance. The Mandelbrot
/// set is black, everything else is white.
/// </summary>
/// <param name="distance">Distance until divergence threshold.</param>
/// <returns>The color corresponding to the distance.</returns>
private static Color BlackAndWhiteColorMap(double distance) =>
distance >= 1
? Color.FromArgb(255, 0, 0, 0)
: Color.FromArgb(255, 255, 255, 255);
/// <summary>
/// Color-coding taking the relative distance into account. The Mandelbrot set
/// is black.
/// </summary>
/// <param name="distance">Distance until divergence threshold.</param>
/// <returns>The color corresponding to the distance.</returns>
private static Color ColorCodedColorMap(double distance)
{
if (distance >= 1)
{
return Color.FromArgb(255, 0, 0, 0);
}
// simplified transformation of HSV to RGB
// distance determines hue
var hue = 360 * distance;
double saturation = 1;
double val = 255;
var hi = (int)Math.Floor(hue / 60) % 6;
var f = hue / 60 - Math.Floor(hue / 60);
var v = (int)val;
var p = 0;
var q = (int)(val * (1 - f * saturation));
var t = (int)(val * (1 - (1 - f) * saturation));
switch (hi)
{
case 0: return Color.FromArgb(255, v, t, p);
case 1: return Color.FromArgb(255, q, v, p);
case 2: return Color.FromArgb(255, p, v, t);
case 3: return Color.FromArgb(255, p, q, v);
case 4: return Color.FromArgb(255, t, p, v);
default: return Color.FromArgb(255, v, p, q);
}
}
/// <summary>
/// Return the relative distance (ratio of steps taken to maxStep) after which the complex number
/// constituted by this x-y-pair diverges. Members of the Mandelbrot set do not
/// diverge so their distance is 1.
/// </summary>
/// <param name="figureX">The x-coordinate within the figure.</param>
/// <param name="figureY">The y-coordinate within the figure.</param>
/// <param name="maxStep">Maximum number of steps to check for divergent behavior.</param>
/// <returns>The relative distance as the ratio of steps taken to maxStep.</returns>
private static double GetDistance(double figureX, double figureY, int maxStep)
{
var a = figureX;
var b = figureY;
var currentStep = 0;
for (var step = 0; step < maxStep; step++)
{
currentStep = step;
var aNew = a * a - b * b + figureX;
b = 2 * a * b + figureY;
a = aNew;
// divergence happens for all complex number with an absolute value
// greater than 4 (= divergence threshold)
if (a * a + b * b > 4)
{
break;
}
}
return (double)currentStep / (maxStep - 1);
}
}
}
| 178 |
Subsets and Splits