1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 | // AntennaRange // // AntennaRelay.cs // // Copyright © 2014-2015, toadicus // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used // to endorse or promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using ToadicusTools.DebugTools; using ToadicusTools.Extensions; using UnityEngine; namespace AntennaRange { /// <summary> /// Relay code at the heart of AntennaRange /// </summary> public class AntennaRelay { // We don't have a Bard, so we'll hide Kerbin here. private static CelestialBody _Kerbin; /// <summary> /// Fetches, caches, and returns a <see cref="CelestialBody"/> reference to Kerbin /// </summary> public static CelestialBody Kerbin { get { if (_Kerbin == null && FlightGlobals.ready) { _Kerbin = FlightGlobals.GetHomeBody(); } return _Kerbin; } } #if BENCH private static ushort relayCount = 0; private static ulong searchCount = 0u; private static ulong searchTimer = 0u; private readonly static RollingAverage averager = new RollingAverage(16); private static long doubleAverageTime = long.MaxValue; private System.Diagnostics.Stopwatch performanceTimer = new System.Diagnostics.Stopwatch(); #endif private bool canTransmit; private IAntennaRelay nearestRelay; private IAntennaRelay bestOccludedRelay; /// <summary> /// The <see cref="AntennaRange.ModuleLimitedDataTransmitter"/> reference underlying this AntennaRelay, as an /// <see cref="AntennaRange.IAntennaRelay"/> /// </summary> protected IAntennaRelay moduleRef; /// <summary> /// Gets the parent Vessel. /// </summary> /// <value>The parent Vessel.</value> public virtual Vessel vessel { get { return this.moduleRef.vessel; } } /// <summary> /// Gets the target <see cref="AntennaRange.IAntennaRelay"/>relay. /// </summary> public IAntennaRelay targetRelay { get; protected set; } /// <summary> /// Gets a value indicating whether this <see cref="AntennaRange.IAntennaRelay"/> Relay is communicating /// directly with Kerbin. /// </summary> public virtual bool KerbinDirect { get; protected set; } /// <summary> /// Gets or sets the nominal link distance, in meters. /// </summary> public virtual double NominalLinkSqrDistance { get; protected set; } /// <summary> /// Gets or sets the maximum link distance, in meters. /// </summary> public virtual double MaximumLinkSqrDistance { get; protected set; } /// <summary> /// Gets the first <see cref="CelestialBody"/> found to be blocking line of sight. /// </summary> public virtual CelestialBody firstOccludingBody { get; protected set; } /// <summary> /// Gets the transmit distance. /// </summary> /// <value>The transmit distance.</value> public double CurrentLinkSqrDistance { get { if (this.KerbinDirect || this.targetRelay == null) { return this.SqrDistanceTo(Kerbin); } else { return this.SqrDistanceTo(this.targetRelay); } } } /// <summary> /// Gets the current link resource rate in EC/MiT. /// </summary> /// <value>The current link resource rate in EC/MiT.</value> public virtual double CurrentLinkResourceRate { get { return this.DataResourceCost; } } public virtual double CurrentNetworkResourceRate { get { double totalRate = 0; IAntennaRelay nextLink = this.moduleRef; while (nextLink != null) { totalRate += nextLink.DataResourceCost; if (nextLink.KerbinDirect) { break; } nextLink = nextLink.targetRelay; } return totalRate; } } /// <summary> /// Gets or sets the link status. /// </summary> public virtual ConnectionStatus LinkStatus { get; protected set; } /// <summary> /// Gets the nominal transmit distance at which the Antenna behaves just as prescribed by Squad's config. /// </summary> public virtual double nominalTransmitDistance { get; set; } /// <summary> /// The maximum distance at which this relay can operate. /// </summary> /// <value>The max transmit distance.</value> public virtual double maxTransmitDistance { get; set; } /* * The next two functions overwrite the behavior of the stock functions and do not perform equivalently, except * in that they both return floats. Here's some quick justification: * * The stock implementation of GetTransmitterScore (which I cannot override) is: * Score = (1 + DataResourceCost) / DataRate * * The stock DataRate and DataResourceCost are: * DataRate = packetSize / packetInterval * DataResourceCost = packetResourceCost / packetSize * * So, the resulting score is essentially in terms of joules per byte per baud. Rearranging that a bit, it * could also look like joule-seconds per byte per byte, or newton-meter-seconds per byte per byte. Either way, * that metric is not a very reasonable one. * * Two metrics that might make more sense are joules per byte or joules per byte per second. The latter case * would look like: * DataRate = packetSize / packetInterval * DataResourceCost = packetResourceCost * * The former case, which I've chosen to implement below, is: * DataRate = packetSize * DataResourceCost = packetResourceCost * * So... hopefully that doesn't screw with anything else. * */ /// <summary> /// Override ModuleDataTransmitter.DataRate to just return packetSize, because we want antennas to be scored in /// terms of joules/byte /// </summary> public virtual float DataRate { get { this.RecalculateTransmissionRates(); if (this.CanTransmit()) { return this.moduleRef.PacketSize; } else { return float.Epsilon; } } } /// <summary> /// Override ModuleDataTransmitter.DataResourceCost to just return packetResourceCost, because we want antennas /// to be scored in terms of joules/byte /// </summary> public virtual double DataResourceCost { get { this.RecalculateTransmissionRates(); if (this.CanTransmit()) { return this.moduleRef.PacketResourceCost; } else { return float.PositiveInfinity; } } } /// <summary> /// Determines whether this instance can transmit. /// </summary> /// <returns><c>true</c> if this instance can transmit; otherwise, <c>false</c>.</returns> public virtual bool CanTransmit() { return this.canTransmit; } // Before transmission, set packetSize. Per above, packet size increases with the inverse square of // distance. packetSize maxes out at _basepacketSize * maxDataFactor. public void RecalculateTransmissionRates() { float rangeFactor = (float)(this.NominalLinkSqrDistance / this.CurrentLinkSqrDistance); if (ARConfiguration.FixedPowerCost) { this.moduleRef.PacketResourceCost = this.moduleRef.BasePacketResourceCost; this.moduleRef.PacketSize = Mathf.Min( this.moduleRef.BasePacketSize * rangeFactor, this.moduleRef.BasePacketSize * this.moduleRef.MaxDataFactor ); } else { if (this.CurrentLinkSqrDistance > this.NominalLinkSqrDistance) { this.moduleRef.PacketSize = this.moduleRef.BasePacketSize; this.moduleRef.PacketResourceCost = this.moduleRef.BasePacketResourceCost / rangeFactor; } else { this.moduleRef.PacketSize = Mathf.Min( this.moduleRef.BasePacketSize * rangeFactor, this.moduleRef.BasePacketSize * this.moduleRef.MaxDataFactor ); this.moduleRef.PacketResourceCost = this.moduleRef.BasePacketResourceCost; } } this.moduleRef.PacketSize *= this.moduleRef.PacketThrottle / 100f; this.moduleRef.PacketResourceCost *= this.moduleRef.PacketThrottle / 100f; } public double GetPotentialLinkCost(double currentSqrDistance, double nominalSqrDistance) { double cost; float rangeFactor = (float)(nominalSqrDistance / currentSqrDistance); if (ARConfiguration.FixedPowerCost || currentSqrDistance <= NominalLinkSqrDistance) { cost = this.moduleRef.BasePacketResourceCost; } else { cost = this.moduleRef.BasePacketResourceCost / rangeFactor; } cost *= this.moduleRef.PacketThrottle / 100f; return cost; } public double GetPotentialLinkCost(IAntennaRelay potentialTarget) { if (potentialTarget == null) { return double.PositiveInfinity; } double nominalSqrDistance; if (ARConfiguration.UseAdditiveRanges) { nominalSqrDistance = this.nominalTransmitDistance * potentialTarget.nominalTransmitDistance; } else { nominalSqrDistance = this.nominalTransmitDistance * this.nominalTransmitDistance; } double currentSqrDistance = this.SqrDistanceTo(potentialTarget); return GetPotentialLinkCost(currentSqrDistance, nominalSqrDistance); } public double GetPotentialLinkCost(CelestialBody body) { if (body == null || body != Kerbin) { return double.PositiveInfinity; } double nominalSqrDistance; if (ARConfiguration.UseAdditiveRanges) { nominalSqrDistance = this.nominalTransmitDistance * ARConfiguration.KerbinNominalRange; } else { nominalSqrDistance = this.nominalTransmitDistance * this.nominalTransmitDistance; } double currentSqrDistance = this.SqrDistanceTo(body); return GetPotentialLinkCost(currentSqrDistance, nominalSqrDistance); } /// <summary> /// Finds the nearest relay. /// </summary> /// <returns>The nearest relay or null, if no relays in range.</returns> public void FindNearestRelay() { if (!FlightGlobals.ready) { return; } PooledDebugLogger log; #if DEBUG log = PooledDebugLogger.New(this); #endif #if BENCH this.performanceTimer.Restart(); long startVesselLoopTicks; long totalVesselLoopTicks; string slowestLOSVesselName = string.Empty; long slowestLOSVesselTicks = long.MinValue; long startLOSVesselTicks; long totalLOSVesselTicks; string slowestCircularVesselName = string.Empty; long slowestCircularVesselTicks = long.MinValue; long startCircularVesselTicks; long totalCircularVesselTicks; long startKerbinLOSTicks; long totalKerbinLOSTicks; long statusResolutionTicks; ushort usefulVesselCount = 0; #endif log.AppendFormat("{0}: Target search started).", this.ToString()); #if DEBUG try { #endif // Declare a bunch of variables we'll be using. CelestialBody bodyOccludingBestOccludedRelay = null; IAntennaRelay needle; double nearestRelaySqrQuotient = double.PositiveInfinity; double bestOccludedSqrQuotient = double.PositiveInfinity; double potentialSqrDistance; double maxLinkSqrDistance; double potentialSqrQuotient; double kerbinSqrDistance; double kerbinSqrQuotient; bool isCircular; int iterCount; // Blank everything we're trying to find before the search. this.firstOccludingBody = null; this.bestOccludedRelay = null; this.targetRelay = null; this.nearestRelay = null; // Default to KerbinDirect = true in case something in here doesn't work right. this.KerbinDirect = true; /* * Loop through the useful relays as determined by ARFlightController and check each for line of sight and * distance, searching for the relay with the best distance/maxRange ratio that is in sight, in range, and * can transmit, also stashing the "best" relay outside of line of sight for failure report. * */ IAntennaRelay potentialBestRelay; CelestialBody fob; #if BENCH startVesselLoopTicks = performanceTimer.ElapsedTicks; #endif for (int rIdx = 0; rIdx < ARFlightController.UsefulRelays.Count; rIdx++) { potentialBestRelay = ARFlightController.UsefulRelays[rIdx]; log.AppendFormat("\n\tgot useful relay {0}", potentialBestRelay == null ? "null" : potentialBestRelay.ToString()); if (potentialBestRelay == null) { log.Append("\n\t...skipping null relay"); continue; } if (potentialBestRelay == this || potentialBestRelay.vessel == this.vessel) { log.AppendFormat( "\n\t...skipping relay {0} because it or its vessel ({1}) is the same as ours" + "\n\t\t(our vessel is {2})", potentialBestRelay, potentialBestRelay.vessel == null ? "null" : potentialBestRelay.vessel.vesselName, this.vessel == null ? "null" : this.vessel.vesselName ); continue; } #if BENCH usefulVesselCount++; #endif // Find the distance from here to the vessel... log.Append("\n\tgetting distance to potential vessel"); potentialSqrDistance = this.SqrDistanceTo(potentialBestRelay); log.Append("\n\tgetting best vessel relay"); log.Append("\n\tgetting max link distance to potential relay"); if (ARConfiguration.UseAdditiveRanges) { maxLinkSqrDistance = this.maxTransmitDistance * potentialBestRelay.maxTransmitDistance; } else { maxLinkSqrDistance = this.maxTransmitDistance * this.maxTransmitDistance; } log.AppendFormat("\n\tmax link distance: {0}", maxLinkSqrDistance); potentialSqrQuotient = potentialSqrDistance / maxLinkSqrDistance; #if BENCH startLOSVesselTicks = performanceTimer.ElapsedTicks; #endif log.Append("\n\t\tdoing LOS check"); // Skip vessels to which we do not have line of sight. if ( ARConfiguration.RequireLineOfSight && !this.vessel.hasLineOfSightTo(potentialBestRelay.vessel, out fob, ARConfiguration.RadiusRatio) ) { #if BENCH totalLOSVesselTicks = performanceTimer.ElapsedTicks - startLOSVesselTicks; if (totalLOSVesselTicks > slowestLOSVesselTicks) { slowestLOSVesselTicks = totalLOSVesselTicks; slowestLOSVesselName = vessel.vesselName; } #endif log.Append("\n\t\t...failed LOS check"); log.AppendFormat("\n\t\t\t{0}: Relay {1} not in line of sight.", this.ToString(), potentialBestRelay); log.AppendFormat("\n\t\t\tpotentialSqrDistance: {0}", potentialSqrDistance); log.AppendFormat("\n\t\t\tbestOccludedSqrQuotient: {0}", bestOccludedSqrQuotient); log.AppendFormat("\n\t\t\tmaxTransmitSqrDistance: {0}", maxLinkSqrDistance); if ( (potentialSqrQuotient < bestOccludedSqrQuotient) && (potentialSqrQuotient <= 1d) && potentialBestRelay.CanTransmit() ) { log.Append("\n\t\t...vessel is close enough to and potentialBestRelay can transmit"); log.AppendFormat("\n\t\t...{0} found new best occluded relay {1}", this, potentialBestRelay); this.bestOccludedRelay = potentialBestRelay; bodyOccludingBestOccludedRelay = fob; bestOccludedSqrQuotient = potentialSqrQuotient; } else { log.Append("\n\t\t...vessel is not close enough to check for occluded relays, carrying on"); } continue; } #if BENCH else { totalLOSVesselTicks = performanceTimer.ElapsedTicks - startLOSVesselTicks; } if (totalLOSVesselTicks > slowestLOSVesselTicks) { slowestLOSVesselTicks = totalLOSVesselTicks; slowestLOSVesselName = vessel.vesselName; } #endif log.Append("\n\t\t...passed LOS check"); /* * ...so that we can skip the vessel if it is further away than a vessel we've already checked. * */ if (potentialSqrQuotient > nearestRelaySqrQuotient) { log.AppendFormat("\n\t{0}: Relay {1} discarded because it is farther than another the nearest relay.", this.ToString(), potentialBestRelay ); continue; } log.Append("\n\t\t...passed distance check"); if (potentialBestRelay.CanTransmit()) { #if BENCH startCircularVesselTicks = performanceTimer.ElapsedTicks; #endif needle = potentialBestRelay; isCircular = false; iterCount = 0; while (needle != null) { iterCount++; if (needle.KerbinDirect) { break; } if (needle.targetRelay == null) { break; } if (needle.targetRelay.vessel == this.vessel || needle == this.moduleRef) { isCircular = true; break; } // Avoid infinite loops when we're not catching things right. if (iterCount > FlightGlobals.Vessels.Count) { this.LogError( "iterCount exceeded while checking for circular network; assuming it is circular" + "\n\tneedle={0}" + "\n\tthis.moduleRef={1}", needle == null ? "null" : string.Format( "{0}, needle.KerbinDirect={1}, needle.targetRelay={2}", needle, needle.KerbinDirect, needle.targetRelay == null ? "null" : string.Format( "{0}\n\tneedle.targetRelay.vessel={1}", needle.targetRelay, needle.targetRelay.vessel == null ? "null" : needle.targetRelay.vessel.vesselName ) ), this.moduleRef == null ? "null" : this.moduleRef.ToString() ); isCircular = true; break; } needle = needle.targetRelay; } if (!isCircular) { nearestRelaySqrQuotient = potentialSqrQuotient; this.nearestRelay = potentialBestRelay; log.AppendFormat("\n\t{0}: found new nearest relay {1} ({2}m²)", this.ToString(), this.nearestRelay.ToString(), Math.Sqrt(nearestRelaySqrQuotient) ); } else { log.AppendFormat("\n\t\t...connection to {0} would result in a circular network, skipping", potentialBestRelay ); } #if BENCH totalCircularVesselTicks = performanceTimer.ElapsedTicks - startCircularVesselTicks; if (totalCircularVesselTicks > slowestCircularVesselTicks) { slowestCircularVesselName = vessel.vesselName; slowestCircularVesselTicks = totalCircularVesselTicks; } #endif } } #if BENCH totalVesselLoopTicks = performanceTimer.ElapsedTicks - startVesselLoopTicks; #endif CelestialBody bodyOccludingKerbin = null; kerbinSqrDistance = this.vessel.DistanceTo(Kerbin) - Kerbin.Radius; kerbinSqrDistance *= kerbinSqrDistance; if (ARConfiguration.UseAdditiveRanges) { kerbinSqrQuotient = kerbinSqrDistance / (this.maxTransmitDistance * ARConfiguration.KerbinRelayRange); } else { kerbinSqrQuotient = kerbinSqrDistance / (this.maxTransmitDistance * this.maxTransmitDistance); } log.AppendFormat("\n{0} ({1}): Search done, figuring status.", this.ToString(), this.GetType().Name); log.AppendFormat( "\n{0}: nearestRelay={1} ({2})), bestOccludedRelay={3} ({4}), kerbinSqrDistance={5}m²)", this, this.nearestRelay == null ? "null" : this.nearestRelay.ToString(), nearestRelaySqrQuotient, this.bestOccludedRelay == null ? "null" : this.bestOccludedRelay.ToString(), bestOccludedSqrQuotient, kerbinSqrDistance ); #if BENCH startKerbinLOSTicks = this.performanceTimer.ElapsedTicks; #endif // If we don't have LOS to Kerbin, focus on relays if ( ARConfiguration.RequireLineOfSight && !this.vessel.hasLineOfSightTo(Kerbin, out bodyOccludingKerbin, ARConfiguration.RadiusRatio) ) { #if BENCH totalKerbinLOSTicks = this.performanceTimer.ElapsedTicks - startKerbinLOSTicks; #endif log.AppendFormat("\n\tKerbin LOS is blocked by {0}.", bodyOccludingKerbin.bodyName); // nearestRelaySqrDistance will be infinity if all relays are occluded or none exist. // Therefore, this will only be true if a valid relay is in range. if (nearestRelaySqrQuotient <= 1d) { log.AppendFormat("\n\t\tCan transmit to nearby relay {0} ({1} <= {2}).", this.nearestRelay == null ? "null" : this.nearestRelay.ToString(), nearestRelaySqrQuotient, 1d); this.KerbinDirect = false; this.canTransmit = true; this.targetRelay = this.nearestRelay; } // If this isn't true, we can't transmit, but pick a second best of bestOccludedRelay and Kerbin anyway else { log.AppendFormat("\n\t\tCan't transmit to nearby relay {0} ({1} > {2}).", this.nearestRelay == null ? "null" : this.nearestRelay.ToString(), nearestRelaySqrQuotient, 1d); this.canTransmit = false; // If the best occluded relay is closer than Kerbin, check it against the nearest relay. // Since bestOccludedSqrDistance is infinity if there are no occluded relays, this is safe if (bestOccludedSqrQuotient < kerbinSqrQuotient) { log.AppendFormat("\n\t\t\tBest occluded relay is closer than Kerbin ({0} < {1})", bestOccludedRelay, kerbinSqrDistance); this.KerbinDirect = false; // If the nearest relay is closer than the best occluded relay, pick it. // Since nearestRelaySqrDistane is infinity if there are no nearby relays, this is safe. if (nearestRelaySqrQuotient < bestOccludedSqrQuotient) { log.AppendFormat("\n\t\t\t\t...but the nearest relay is closer ({0} < {1}), so picking it.", nearestRelaySqrQuotient, bestOccludedSqrQuotient); this.targetRelay = this.nearestRelay; this.firstOccludingBody = null; } // Otherwise, target the best occluded relay. else { log.AppendFormat("\n\t\t\t\t...and closer than the nearest relay ({0} >= {1}), so picking it.", nearestRelaySqrQuotient, bestOccludedSqrQuotient); this.targetRelay = bestOccludedRelay; this.firstOccludingBody = bodyOccludingBestOccludedRelay; } } // Otherwise, check Kerbin against the nearest relay. // Since we have LOS, blank the first occluding body. else { log.AppendFormat("\n\t\t\tKerbin is closer than the best occluded relay ({0} >= {1})", bestOccludedRelay, kerbinSqrDistance); // If the nearest relay is closer than Kerbin, pick it. // Since nearestRelaySqrDistane is infinity if there are no nearby relays, this is safe. if (nearestRelaySqrQuotient < kerbinSqrQuotient) { log.AppendFormat("\n\t\t\t\t...but the nearest relay is closer ({0} < {1}), so picking it.", nearestRelaySqrQuotient, kerbinSqrQuotient); this.KerbinDirect = false; this.firstOccludingBody = null; this.targetRelay = this.nearestRelay; } // Otherwise, pick Kerbin. else { log.AppendFormat("\n\t\t\t\t...and closer than the nearest relay ({0} >= {1}), so picking it.", nearestRelaySqrQuotient, kerbinSqrQuotient); this.KerbinDirect = true; this.firstOccludingBody = bodyOccludingKerbin; this.targetRelay = null; } } } } // If we do have LOS to Kerbin, try to prefer the closest of nearestRelay and Kerbin else { #if BENCH totalKerbinLOSTicks = this.performanceTimer.ElapsedTicks - startKerbinLOSTicks; #endif log.AppendFormat("\n\tKerbin is in LOS."); // If the nearest relay is closer than Kerbin and in range, transmit to it. if (nearestRelaySqrQuotient <= 1d) { log.AppendFormat("\n\t\tCan transmit to nearby relay {0} ({1} <= {2}).", this.nearestRelay == null ? "null" : this.nearestRelay.ToString(), nearestRelaySqrQuotient, 1d); this.canTransmit = true; // If the nearestRelay is closer than Kerbin, use it. if (nearestRelaySqrQuotient < kerbinSqrQuotient) { log.AppendFormat("\n\t\t\tPicking relay {0} over Kerbin ({1} < {2}).", this.nearestRelay == null ? "null" : this.nearestRelay.ToString(), nearestRelaySqrQuotient, kerbinSqrQuotient); this.KerbinDirect = false; this.targetRelay = this.nearestRelay; } // Otherwise, Kerbin is closer, so use it. else { log.AppendFormat("\n\t\t\tBut picking Kerbin over nearby relay {0} ({1} >= {2}).", this.nearestRelay == null ? "null" : this.nearestRelay.ToString(), nearestRelaySqrQuotient, kerbinSqrQuotient); this.KerbinDirect = true; this.targetRelay = null; } } // If the nearest relay is out of range, we still need to check on Kerbin. else { log.AppendFormat("\n\t\tCan't transmit to nearby relay {0} ({1} > {2}).", this.nearestRelay == null ? "null" : this.nearestRelay.ToString(), nearestRelaySqrQuotient, 1d); // If Kerbin is in range, use it. if (kerbinSqrQuotient <= 1d) { log.AppendFormat("\n\t\t\tCan transmit to Kerbin ({0} <= {1}).", kerbinSqrQuotient, 1d); this.canTransmit = true; this.KerbinDirect = true; this.targetRelay = null; } // If Kerbin is out of range and the nearest relay is out of range, pick a second best between // Kerbin and bestOccludedRelay else { log.AppendFormat("\n\t\t\tCan't transmit to Kerbin ({0} > {1}).", kerbinSqrQuotient, 1d); this.canTransmit = false; // If the best occluded relay is closer than Kerbin, check it against the nearest relay. // Since bestOccludedSqrDistance is infinity if there are no occluded relays, this is safe if (bestOccludedSqrQuotient < kerbinSqrQuotient) { log.AppendFormat("\n\t\t\tBest occluded relay is closer than Kerbin ({0} < {1})", bestOccludedRelay, kerbinSqrDistance); this.KerbinDirect = false; // If the nearest relay is closer than the best occluded relay, pick it. // Since nearestRelaySqrDistane is infinity if there are no nearby relays, this is safe. if (nearestRelaySqrQuotient < bestOccludedSqrQuotient) { log.AppendFormat("\n\t\t\t\t...but the nearest relay is closer ({0} < {1}), so picking it.", nearestRelaySqrQuotient, bestOccludedSqrQuotient); this.targetRelay = this.nearestRelay; this.firstOccludingBody = null; } // Otherwise, target the best occluded relay. else { log.AppendFormat("\n\t\t\t\t...and closer than the nearest relay ({0} >= {1}), so picking it.", nearestRelaySqrQuotient, bestOccludedSqrQuotient); this.targetRelay = bestOccludedRelay; this.firstOccludingBody = bodyOccludingBestOccludedRelay; } } // Otherwise, check Kerbin against the nearest relay. // Since we have LOS, blank the first occluding body. else { log.AppendFormat("\n\t\t\tKerbin is closer than the best occluded relay ({0} >= {1})", bestOccludedRelay, kerbinSqrDistance); this.firstOccludingBody = null; // If the nearest relay is closer than Kerbin, pick it. // Since nearestRelaySqrDistane is infinity if there are no nearby relays, this is safe. if (nearestRelaySqrQuotient < kerbinSqrQuotient) { log.AppendFormat("\n\t\t\t\t...but the nearest relay is closer ({0} < {1}), so picking it.", nearestRelaySqrQuotient, kerbinSqrQuotient); this.KerbinDirect = false; this.targetRelay = this.nearestRelay; } // Otherwise, pick Kerbin. else { log.AppendFormat("\n\t\t\t\t...and closer than the nearest relay ({0} >= {1}), so picking it.", nearestRelaySqrQuotient, kerbinSqrQuotient); this.KerbinDirect = true; this.targetRelay = null; } } } } } if (ARConfiguration.UseAdditiveRanges) { if (this.KerbinDirect) { this.NominalLinkSqrDistance = this.nominalTransmitDistance * ARConfiguration.KerbinNominalRange; this.MaximumLinkSqrDistance = this.maxTransmitDistance * ARConfiguration.KerbinRelayRange; } else { this.NominalLinkSqrDistance = this.nominalTransmitDistance * this.targetRelay.nominalTransmitDistance; this.MaximumLinkSqrDistance = this.maxTransmitDistance * this.targetRelay.maxTransmitDistance; } } else { this.NominalLinkSqrDistance = this.nominalTransmitDistance * this.nominalTransmitDistance; this.MaximumLinkSqrDistance = this.maxTransmitDistance * this.maxTransmitDistance; } if (this.canTransmit) { if (this.CurrentLinkSqrDistance < this.NominalLinkSqrDistance) { this.LinkStatus = ConnectionStatus.Optimal; } else { this.LinkStatus = ConnectionStatus.Suboptimal; } } else { this.LinkStatus = ConnectionStatus.None; } #if BENCH statusResolutionTicks = performanceTimer.ElapsedTicks - startKerbinLOSTicks - totalKerbinLOSTicks; #endif log.AppendFormat("\n{0}: Target search and status determination complete.", this.ToString()); #if DEBUG } catch (Exception ex) { log.AppendFormat("\nCaught {0}: {1}\n{2}", ex.GetType().FullName, ex.ToString(), ex.StackTrace); #if QUIT_ON_EXCEPTION UnityEngine.Application.Quit(); #endif } finally { #endif log.Print(false); #if DEBUG } #endif #if BENCH AntennaRelay.searchTimer += (ulong)this.performanceTimer.ElapsedTicks; AntennaRelay.searchCount++; this.performanceTimer.Stop(); double averageSearchTime = (double)AntennaRelay.searchTimer / (double)AntennaRelay.searchCount; if (AntennaRelay.searchCount >= 8000u / (ulong)ARConfiguration.UpdateDelay) { AntennaRelay.searchCount = 0u; AntennaRelay.searchTimer = 0u; AntennaRelay.averager.AddItem(averageSearchTime); AntennaRelay.doubleAverageTime = (long)(AntennaRelay.averager.Average * 2d); } if (this.performanceTimer.ElapsedTicks > AntennaRelay.doubleAverageTime) { System.Text.StringBuilder sb = Tools.GetStringBuilder(); sb.AppendFormat(Tools.SIFormatter, "[AntennaRelay] FindNearestRelay search for {0}" + " took significantly longer than average ({1:S3}s vs {2:S3}s)", this.ToString(), (double)this.performanceTimer.ElapsedTicks / (double)System.Diagnostics.Stopwatch.Frequency, (double)AntennaRelay.averager.Average / (double)System.Diagnostics.Stopwatch.Frequency ); sb.AppendFormat(Tools.SIFormatter, "\n\tVessel loop time: {0:S3}s", (double)totalVesselLoopTicks / (double)System.Diagnostics.Stopwatch.Frequency ); sb.AppendFormat(Tools.SIFormatter, "\n\t\tAverage vessel time for each of {1} vessels: {0:S3}s", (double)totalVesselLoopTicks / (double)System.Diagnostics.Stopwatch.Frequency / (double)usefulVesselCount, usefulVesselCount ); sb.AppendFormat(Tools.SIFormatter, "\n\t\tSlowest vessel LOS check: {0:S3}s to {1}", (double)slowestLOSVesselTicks / (double)System.Diagnostics.Stopwatch.Frequency, slowestLOSVesselName ); sb.AppendFormat(Tools.SIFormatter, "\n\t\tSlowest circular relay check: {0:S3}s for {1}", (double)slowestCircularVesselTicks / (double)System.Diagnostics.Stopwatch.Frequency, slowestCircularVesselName ); sb.AppendFormat(Tools.SIFormatter, "\n\tKerbin LOS check: {0:S3}s", (double)totalKerbinLOSTicks / (double)System.Diagnostics.Stopwatch.Frequency ); sb.AppendFormat(Tools.SIFormatter, "\n\tStatus resolution check: {0:S3}s", (double)statusResolutionTicks / (double)System.Diagnostics.Stopwatch.Frequency ); // sb.AppendFormat(Tools.SIFormatter, "", start) this.LogWarning(sb.ToString()); Tools.PutStringBuilder(sb); } #endif } /// <summary> /// Returns a <see cref="System.String"/> that represents the current <see cref="AntennaRange.AntennaRelay"/>. /// </summary> /// <returns>A <see cref="System.String"/> that represents the current <see cref="AntennaRange.AntennaRelay"/>.</returns> public override string ToString() { if (this is ProtoAntennaRelay) { return (this as ProtoAntennaRelay).ToString(); } return this.moduleRef.ToString(); } /// <summary> /// Initializes a new instance of the <see cref="AntennaRange.AntennaRelay"/> class. /// </summary> /// <param name="module">The module reference underlying this AntennaRelay, /// as an <see cref="AntennaRange.IAntennaRelay"/></param> public AntennaRelay(IAntennaRelay module) { this.moduleRef = module; #if BENCH AntennaRelay.relayCount++; #endif this.LogDebug("{0}: constructed {1}", this.GetType().Name, this.ToString()); } } } |