Jump to content

[KSP 1.12.x] kOS v1.4.0.0: kOS Scriptable Autopilot System


Dunbaratu

Recommended Posts

37 minutes ago, Alchemist said:

The way kOS handles it, vessel:position returns the center of mass. And the coordinate system is ship-centered, so for current vessel  ship:position=v(0,0,0)

Not the most obvious thing, but that's how it works

Thank you.

Inspired by your reply, I find Ship:Body:Position:Mag-Ship:Body:Radius can tell me the altitude of mass center.

Link to comment
Share on other sites

I don't think there is any way of getting moment of inertia other than actually going through the calculation yourself.

As for why dividing angular momentum and angular velocity doesn't work: Well, two reasons.

1. Both of them are vectors, so the division operation doesn't make much sense unless they are collinear.

2. Moment of inertia is not actually a single value, it is a tensor. Basically a 3 x 3 symmetric matrix. The matrix is diagonalisable, but that still leaves you with potentially 3 different values.

The formula for calculating the tensor is simple enough. The problem is we (at least I) don't know how KSP models the distribution of mass. Whether you need to calculate a sum or an integration depends on that.

Link to comment
Share on other sites

Hi!

I understand kOs made for 1.8.1 now. (1.8.9 in CKAN)

In my 1.9.1 + MH + BG it works. But I have MADLAD message each start:

Matched CC_RemoteTech to the whitelist. Suppressing error
Matched KerKonConConExt to the whitelist. Suppressing error
[ERR 12:08:16.011] kOS: Exception loading telnet config options: Root element is missing.
[ERR 12:08:16.016] kOS: Exception loading telnet config options: Root element is missing.

I do not use telnet. Is it safe to just ignore message?

Will this beautiful mod updated to 1.9.1 ?

Thanks and best wishes!

Link to comment
Share on other sites

7 hours ago, Sebra said:

Hi!

I understand kOs made for 1.8.1 now. (1.8.9 in CKAN)

In my 1.9.1 + MH + BG it works. But I have MADLAD message each start:

Matched CC_RemoteTech to the whitelist. Suppressing error
Matched KerKonConConExt to the whitelist. Suppressing error
[ERR 12:08:16.011] kOS: Exception loading telnet config options: Root element is missing.
[ERR 12:08:16.016] kOS: Exception loading telnet config options: Root element is missing.

I do not use telnet. Is it safe to just ignore message?

Will this beautiful mod updated to 1.9.1 ?

Thanks and best wishes!

The kOS DLL that was compiled for 1.8.1 also works fine with 1.9.1.  SQUAD didn't make any changes that affected kOS between those version.

The Telnet warnings are actually while trying to read the config file for kOS, and the config options related to telnet aren't being loaded right.  Even if you don't use telnet, a failure to read one part of the config file correctly can still possibly break other config options that were meant to be loaded afterward.  I suggest you remove kOS entirely and re-install it.  This will lose your config options and you'll have to set them again, but should (I hope) get rid of that message.

Link to comment
Share on other sites

1 hour ago, Steven Mading said:

I suggest you remove kOS entirely and re-install it.  This will lose your config options and you'll have to set them again, but should (I hope) get rid of that message.

Thanks for answer.

It is strange. I'm sure reinstalled mod with many others before so was sure it will not help me. But message disappears mysteriously.

Thanks for support! I hope kOS will get KSP version updated here and in CKAN.

Link to comment
Share on other sites

  • 2 weeks later...

Hi everyone, 

Is it possible to use kOS to apply keyboard inputs into the flight screen?

  What I mean by this, is that I can set get kOS to set a manoeuvre node at say an AP after reaching a target apoapsis, but normally, instead of calculating it in kOS, I use Precise Manoeuvrer's hotkey function with * mapped to circularise.  What I'd like to do is get kOS to press the * for me, rather than scripting a calculation for the node.

Thanks and Peace.

Link to comment
Share on other sites

17 hours ago, theJesuit said:

Hi everyone, 

Is it possible to use kOS to apply keyboard inputs into the flight screen?

  What I mean by this, is that I can set get kOS to set a manoeuvre node at say an AP after reaching a target apoapsis, but normally, instead of calculating it in kOS, I use Precise Manoeuvrer's hotkey function with * mapped to circularise.  What I'd like to do is get kOS to press the * for me, rather than scripting a calculation for the node.

Thanks and Peace.

That doesn't exist, no.  In fact it takes a lot of work to make kOS *not* send its keypresses to other mods.

Link to comment
Share on other sites

1 hour ago, theJesuit said:

Thanks.

Peace.

I just took a look at Unity's forums to see if this is even possible to implement and it doesn't look like it is.  For Unity programs trying to stick to the cross-platform APIs, only Unity's underlying proprietary code is allowed to generate Unity keypress events.  Apps written on top of Unity can only treat keyboard events as read-only, as far as I can tell.  (The exception being if you're willing to violate the cross-platform environment by directly calling the OS-specific routines that slip underneath Unity, and basically making it an OS-specific mod, or maybe having to make several variants of the mod to install depending on OS.)

 

 

Link to comment
Share on other sites

1 hour ago, Steven Mading said:

I just took a look at Unity's forums to see if this is even possible to implement and it doesn't look like it is.  For Unity programs trying to stick to the cross-platform APIs, only Unity's underlying proprietary code is allowed to generate Unity keypress events.  Apps written on top of Unity can only treat keyboard events as read-only, as far as I can tell.  (The exception being if you're willing to violate the cross-platform environment by directly calling the OS-specific routines that slip underneath Unity, and basically making it an OS-specific mod, or maybe having to make several variants of the mod to install depending on OS.)

 

 

Oh well!

I've also had some fun adding a little piece of kOS coding to my launch and engine burn scripts with the 3.1+ versions of kerbalism which have engine failures.  You learn to use launch clamps obviously but needing to add a powerdown sequence if things go awry.  I has trying to do it manually, but kOS scripting is so much better!

Peace.

Link to comment
Share on other sites

Not sure if this has been talked about but I can't get the mod to work. I'm not sure if its conflicting with current mods, but KSP won't load (it stays on loading screen saying "Loading Expansions"). I'm running latest version (v1.9.1), and I have Infernal Robotics Next, Solaris Hypernautics, Near Future Propulsion, Near Future Solar, Near Future Launch Vehicle, Community Tech Tree, Kerbal Attachment System, Kerbal Inventory System, OPT, Kerbal Planetary Base Systems, SCANsat, and Tweakscale (sorry for the long list). Any known issues with any of these mods?

Thank you! I really hope I can get this mod working!

Edited by shibles
Link to comment
Share on other sites

  • 2 weeks later...

I found:

// kOS 1.2.1 in KSP 1.9.1
Local Function ppp {
    Parameter a.
    Set b to a+5.
    Local c to a+6.
    Print "a is "+a. //show: a is 10
    Print "b is "+b. //show: b is 15
    Print "c is "+c. //show: c is 30
    Return True.
}

Lock a to 10.
Lock b to 20.
Lock c to 30.
ppp( 40 ).

It looks that the LOCKED variable have priority over function PARAMETER and Local variable.
Is it bug? Thanks.

Edited by Lookerksy
correct
Link to comment
Share on other sites

A question on the string for the KUniverse:QUICKSAVETO(name) where the name is the string.

Can I set name to whatever I want like a combination of date and name of the craft? Or would I put SHIPNAME instead of the name it he quicksave function?

Thanks,

Peace.

Link to comment
Share on other sites

14 hours ago, theJesuit said:

Or would I put SHIPNAME instead of the name it he quicksave function?

I have read this sentence about 5 times and still can't understand what you were trying to ask.  Can you phrase it differently?

Link to comment
Share on other sites

On 3/22/2020 at 1:14 PM, scimas said:

I don't think there is any way of getting moment of inertia other than actually going through the calculation yourself.

As for why dividing angular momentum and angular velocity doesn't work: Well, two reasons.

1. Both of them are vectors, so the division operation doesn't make much sense unless they are collinear.

2. Moment of inertia is not actually a single value, it is a tensor. Basically a 3 x 3 symmetric matrix. The matrix is diagonalisable, but that still leaves you with potentially 3 different values.

The formula for calculating the tensor is simple enough. The problem is we (at least I) don't know how KSP models the distribution of mass. Whether you need to calculate a sum or an integration depends on that.

I find there has "MOMENT_OF_INERTIA" (unit: kg*m^2) in kRPC Documentation.
(http://krpc.github.io/krpc/python/api/space-center/vessel.html)
It means API including it.
Maybe it can be added into the next version kOS ? (unit: ton*m^2)

I admit it's difficult to calculate the moment of inertia of the vessel.
I designed experiment to measure different parts, but I can't explain all the result by formulas in physics textbook.

If there is a way to get the moment of inertia directly, there won't be so much trouble.

Link to comment
Share on other sites

  • 2 weeks later...

I found What I believe an errata in the github kOS doc site:

(not a problem for me... but then I eat c++ etc for breakfast, and know what a recursive descent parser and LL(1) is. Own the dragon book etc.)

https://ksp-kos.github.io/KOS/structures/collections/iterator.html

The first code example sets 

SET MyCurrent TO MyList:ITERATOR.

but then in the print references to non existent variable MyIter

PRINT  <..elided..> MyIter:INDEX  <..> MyIter:VALUE .

It appears to be a refactoring error.

Its fine for people who already knew what iterators were,  but newbs might cry a bit.

I guess this is where they learn coding is like playing kerbals, explosions (during testing) are fine.

If it don't make sense poke it.

Sorry if you'd prefer this logged through github (I lost my login in the dark ages)

 

Link to comment
Share on other sites

5 hours ago, AxleGreaser said:

I found What I believe an errata in the github kOS doc site:

(not a problem for me... but then I eat c++ etc for breakfast, and know what a recursive descent parser and LL(1) is. Own the dragon book etc.)

https://ksp-kos.github.io/KOS/structures/collections/iterator.html

The first code example sets 


SET MyCurrent TO MyList:ITERATOR.

but then in the print references to non existent variable MyIter


PRINT  <..elided..> MyIter:INDEX  <..> MyIter:VALUE .

It appears to be a refactoring error.

Its fine for people who already knew what iterators were,  but newbs might cry a bit.

I guess this is where they learn coding is like playing kerbals, explosions (during testing) are fine.

If it don't make sense poke it.

Sorry if you'd prefer this logged through github (I lost my login in the dark ages)

 

I just made this an issue in github - thanks for bringing it to my attention.

Link to comment
Share on other sites

On 5/2/2020 at 6:05 PM, Lookerksy said:

I admit it's difficult to calculate the moment of inertia of the vessel.
I designed experiment to measure different parts, but I can't explain all the result by formulas in physics textbook.

Im curious, (AKA want to save myself repeating anything you've done)

What experiment?

--------

My thinking ....

If I consider an FLT800 tank (longest little one 360Liq/440Oxy) it has 3 axis of rotation that formulas about cylinders (of uniform? density) in physics text book might tell me about.

about its long axis, where its inertia should be (and by observation in the game) is lower.  (as evidenced by 1 tank rockets spin faster/easier on their long axis.)

about either cross axis (pitch or yaw for std long rocket) that tank has more inertia.

And at that point text book formulas cease telling me anything (much)(as I really shouldn't assume uniform density?).

Egs: of things the formulas dont, and cant say. (given the observable facts/measurements that we do have)

The tank when empty weighs less than when full, but its quite likely (IRL/TextBook) its inertia wont in any way be proportional to the decrease as the non fuel part of the mass is more likely skin of the tank and has more angular inertia per unit of mass as it is further from the center.

In general in KSP as we dont really know how the mass of any part is internally distributed we cant form firm conclusions about what inertia we expect it to have. (see unity and colliders below)

We do have general ones that are visually true such as tanks spin easier on the long rather than short axis. But TBMK thats it.

Well that and they are 100% fully baffled and the fuel never runs to one end when part way full. (tanks float flat) (but for ang/inertia when say 10% Full, we dont know if the 5% is all at either end, all near the mid point or spread out such that each extra 10% of fuel adds the same amount of inertia on all three axis as the last. Lots of stuff is likely for simulation simplicity, none match what would be text book reality.)

Egs of things physics formulas (one of them) can say. (and IMO is likely to be true in game)

The parallel axis theorem tells us things.

http://hyperphysics.phy-astr.gsu.edu/hbase/parax.html

We (I) could even conceivably test if a reaction wheel actually generates the torgue it says is its max when I give it an input command (WASDQE),

OR

whether even that is mediated by some PID somewhere meaning I don't always get max torque the KSP doc says can exist. (do they ease in?)(When i dont know stuff anything is possible)

I can do that by constructing two ships with identical parts and then positioning the parts on one ship so the parts distance from the axis of rotation is different.

When i do that I get a known change in moment of inertia (according to theorem above), based only on knowing mass of part and distance of the parts COM from the axis of rotation.

By adjusting that to a range of values I will get a range of in game measured inertias and a range of expected changes in inertia. The gradient of how much known numerical changes in inertia effected angular acceleration ought to agree with the torque we thought we (the part) applied. Also the Y intercept with zero offset will be the angular inertia of the parts around their own axis.

(and just because kerbals... and rockets explode, we could put rockets (of known thrust) on pinwheel arms and apply known force F and radius R. Although we might find we rapidly needed to know Young's modulus of the parts/connections as well. And wouldn't that be a shame.)

and note how that does not rely on me assuming the torque parts do what the torque parts say they can do. As I don't know for sure if they always do that.

In my observation, SAS for instance appears (to my eyes) to have the torque parts exert variable torque depending on its internal PIDs logic state. I might be imagining the last part Ive never measured the angular acceleration of a ship SAS is controlling.

------

lastly an Idea Ive just been having, 3 parallel FLT800 tanks with only enough fuel for 1. By transferring fuel from middle tank to both outrigger tanks at a known from precise edit distance from the central tank that gives me known variable amount of extra inertia. I could then measure how much extra inertia in kgm I need in order to compensate for removing the part I wanted to measure the axial inertia of.

That there are shed load of parts. Everyone of which would require (3 axis *) 1 VAB and 1 hyper edit 1 spin it up measurement, 1 exit ship and disassemble part, a new spin it up and measure how much fuel needs to be transferred to get the same moment of inertia. Seems like a huge grind, more than when I made ground relay token ring network. (with 100.00% occlusion by sea level)(relay networks see through mountains and terrain.)

Approaching it as an IT problem rather than kerbal science.

Id be guessing underlying unity stuff like this

https://docs.unity3d.com/ScriptReference/Rigidbody.ResetInertiaTensor.html

is where it all comes from, so it >may< be feasible kOS could be changed to ask unity what the inertia tensor of a part is...
physics-less parts and perhaps the MKS one that can even out lopsided attached loads, might/likely do weird stuff.

(edit as per previous post, https://krpc.github.io/krpc/python/api/space-center/vessel.html is where KSP exposes such a thing.)

My conclusion.....

Moar torque, have enough torque that i don't need to think too much about predicting how long a vessel will take to rotate. (ignore that i don't know ang inertia, fix that in the VAB.)
AKA flight plans don't.... horizontal suicide burn (zero out horizontal surface V) @ 20m height/periapsis off the ground then try to rotate and suicide burn the 20m fall.  or whatever height makes that "practical")

although .... Jeb has twinkling in his eye now. 5g single engine Suicide burn landing.... under the mun arch..... probably needs vernor engines to rotate fast enough(no VTOL).

'Bill' on the other hand wants to 'land' on the under surface of the arch.

me: Bloody kerbals.

 

 

 

Edited by AxleGreaser
Link to comment
Share on other sites

I have a weird vecDraw problem.   (and its one that i perhaps have a Kludge to get past?)

And second as I am using  KSP 1.9.1, that may be the entire problem...

but what Id like is any clues on anything else that might be a bug of mine.

or advice on what a patterns of writing code make reliable persistent thunks for vecDraws.

or if my problem is there what can make the Vecdraws themselves robustly persistent.

======================

Kludge: See the code snippet below....  If instead of creating the VecDraws in the process of adding them to the list...

(copied as a technique from the bounding box example off the doc website)

If I first assign them to a local variables (v1 & v2) then listVecs:add(v1), listVecs:add(v1) them to the list it all works fine again...

Going via a local variable of limited scope 'ought to' make no difference. but one 'works' and one doesn't.

(im expecting that i hate intelligent garbage collection, and yearn for my c++ levels of control.)

=======================

Where the problem is NOT

All the math/geometery is fine, when It draws the vectors they are in the right places. but after number of seconds they tend to just disappear. And whichever one i construct first seems flakier than the last one. 

Its like something it is doing a garbage cleanup and taking my vect draws. (sometimes after 8 or even more seconds of stability)

Either that or me using Geocoordinates:AltitudePosition(0) in the call backs (thunks) is naughty?

========

What Im doing

Goal/use case.

I am drawing some very long vectors (>20000m) (I am using them to show the limits of where in space can be accessed by coms from ground based relay landed on a mountain. (note 1) hence I am drawing a line tangent to the 600km sea level kerbin Ball. And doing so in the navigation direction of the "ship:position", but starting at the mountain top relay.

lots of vector math yadda yadda. Then I store the geocoordinate of the tangent point in the global variable  TangMid (as it stores lat long) I can recover position vectors later in the VecDraw call back.

In the code snippet below

Global Tanglen is how long a vec to drawn in green before the tangent, and then red vector is drawn after the tangent. In the use case story, if the red Vec intersects a second mountain then I can put relay up there and the two ground stations can see one another.

 

My code looks in part like this

    ListVecs:Add( VecDraw (
        {return TangMid:AltitudePosition(0) - Tanglen * (TangMid:AltitudePosition(0) - Relaybeacon:position):normalized. }, {return Tanglen * (TangMid:AltitudePosition(0) - Relaybeacon:position):normalized.}
            ,    RGB(0,1,0), "TangVec G", 1, true, 12,false,false)).

    ListVecs:Add( VecDraw (
        {return TangMid:AltitudePosition(0).}, {return 40000 * ( TangMid:AltitudePosition(0) - Relaybeacon:position):normalized.}
            ,    RGB(1,0,0), "TangVec R", 1, true, 12,false,false)).

RelayBeacon is Global was set to a named   vessel("nameOfMoutainTopRelay")

ListVecs is a global list() where I keep the vecDraws and then can later go through and show or not show them.

 

I also have code so i can turn the vecs on and off slaved to Lights = on/off.

When I go through and set Show=true on every Vec in the ListVecs  (both vecs) only the last one actually seems to appear.

if I cause a recalc of the vectors (toggle RCS to do so) Then both appear intially. But if I turn the show off on both and back on only the second one comes back.

I print out the label of each vecDraw as I set show to true, so I know, for sure that, I turned them on. 

Sometimes the one that does display simply blinks out. if it does and I turn show =false then show = true again , I can usually get it to come back.

Thus It still exists, but something just forgot(?) about it.

Note the vecs I am drawing do start and end kms away from where the ship is... so if there is some scoping algorithm to decide whats irrelvant, perhaps Im falling foul of that. (but all effects described are visible when zoomed way way out. And the kludge effect of inserting the local variables seems very weird.

============================

 

(note 1) Don't ask why for ground relays? I know the game is about space. I am building token ring (full loop) ground relay network around the equator because i can....  Id did it once cave man (orienteering and dead reckoning to place the relays). Now I am trying it again but using KOS as a surveying tool.

Link to comment
Share on other sites

7 hours ago, Steven Mading said:

@AxleGreaserThere's just not enough information to know what you're talking about.  Too much guesswork about what the rest of your code is doing that isn't shown.

Also ... if there is no help with what I can get as clarity of my issue so far, that is fine. My Kludge works. (no kerbals died relays got surveyed && laid). Eventually I will get it tracked down and better isolated (smaller kOS program), or I will read the kOS source code, or kOS will get updated to certainly work with 1.9.1 an any changes to GC and then my Kludge problems will go away.

==============

As all the vector computations are valid and work and produce the right result. (when my ought to do nothing local variable kludge is present)

Id have thought that The VecDraw (as described) call back getting it ALL data from global variables holding geoccordinates, a ship:position vector and other global variables holding scalar/float constants. (EG length)

Especially when coupled with the fact that the vectors sometimes just blink out. (and the implied: no my code doesn't have other rogue loops/triggers turning say visibility on and off, (don't exist) and that I made sure the only code that ever messed with vectDraw:Show was paired with code printing what it did.
Also coupled with the knowledge that my kludge (assigning the vecDraw to local variable makes it work) whereas putting it directly into the List:Add( ) makes it not. Which pretty much means the rest of my code is valid? And there must be something about assigning to local variable before the putting it in list that is different to just putting it in the list directly.

Also as stated that modifying code so that it stores vecDraws in (otherwise unused) local variables or not makes the bug appear or disappear, would i thought be rather characterising of whats going on.

AKA I thought Id covered the rest of my code with where the problem is not. And that it does draw the vecs in the right places, when it does draw them and that sometimes even though theyd been put there then they just blinked out.

============================

but sure if it would make it easier, and  youd like to see more of it its here.

But note even that not quite all of it is as I also use a debug boot loader to load this pop open a terminal and run this script, so that  revert to launch reloads edits made on my hard disk.

I am not against also uploading those but they seem too far.

 

This comment was added to the code in the spoiler. (not compiled or run)

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// This is my kludge version that works.  (removing variable v1 ... v6 and assigning VecDraws diretcly to List() does not.

// When i change it and dont store the VecDraws in local variables first it fails to display all the VecDraws.

// TBMK it "ought to" be 100% true that using or not using lcoal vars should make no difference at all.

 

Spoiler
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
Spoiler


// This code assists Planes laying Ground Relays

/////////////////////
// Draws vectors from selected Craft as if it is a ground Relay.
// Green no more than last 20 km From craft to ITS spherical horizon, Then Red past that point for 20 more km.
// Darker colors for another Vect 1km left and right
//
// When Lights are on Vec Draws are displayed
// When RCS is switched on curent plane position is set as the direction.
// and the complex reclacs are done once.
//

runoncepath( "0:/lib/IPUSpeedStack.ks" ).   // Libary code for Sets UP Speed higher.
// Called with PushUpIPU(500).

global Done is false.

Global RelayName is "Wizz".
Global RelayBeacon is 0.


function GetRelay {
    if HasTarget {    
        set RelayBeacon to Target.
        set RelayName to Target:Name.
    }  else {
        set RelayBeacon to Vessel(RelayName).
    }
    return Relaybeacon.
}
GetRelay().

Global SurfaceTangentTolerance is 0.1.

Global ListVecParams is list().
Global ListVecs is list().
Global VecsShown is false.

Global Recalc is true.

function ShowVecs {
    return lights = true AND ListVecs:length > 1.
}


///////////////////////////////////////
//  Find geoloc in direction of pos on Horizon
//
function FindTangent {
        declare parameter  Tpos.
    
    global RBpos is RelayBeacon:position.
        global DirVec is Tpos-RBPos.
        // vector towards Tpos that is paralle to ground at Relay.
        local hVec is VECTOREXCLUDE(Relaybeacon:Up:FOREVECTOR,DirVec).

 

        local RR is  (RBpos - ship:Body:position):mag.  // distance of relay to COPlanet
        local CosAng is (Ship:Body:radius + SurfaceTangentTolerance ) / RR. // cos of angle to Tangent point.

//        print "RalyR" + RR + "CosAng " + CosAng.
        
        local TanAng is sqrt(1-CosAng*CosAng) / CosAng.
        local DistToTangentHigh is TanAng * RR.
        // Should be position on Body at zero alt.
        local PosTang is  RBpos + DistToTangentHigh * hVec:normalized.
        // PosTang is UP High but it is Over The target

//        Print "DTTH " + DistToTangentHigh.
//        Print "sanity check  0 =  " + ((PosTang- ship:Body:position):mag - Ship:Body:radius).

        global TangCoord is Ship:Body:GEOPOSITIONOF(PosTang).
        
        return TangCoord.  // This geo position of Comms tangent
}


function vecListFlip {
        parameter L.
        parameter Shown.

// These two prints make sure none of my code was actually due to a my bug turning the vecs on and off in way I didnt notice

 Print "vecs shown " + Shown.

        local Vcs is 0.
        for Vcs in L {
                    set Vcs:show to Shown.
                    print "vecs" + Vcs:label + " = " + Vcs:show.

// When the vecdraw blinks off this line of code DID not just execute.
// This line of code ONLY excutes and prints when i mean it to, and it si not causing the lack of visibile vetcors


        }
}

global TangMid is kerbin:GEOPOSITIONLATLNG(0,0).
Global TangLen is 0.
global TangLeft is kerbin:GEOPOSITIONLATLNG(0,0).
global TangRight is kerbin:GEOPOSITIONLATLNG(0,0).

function MakeLabel {
   parameter Which.
   return "".   // This line of code Can have label name in  returning "vector " + Which when iwant to see the labels.

   // Ive also tested the code with string literals as the label for each vector.
}

function RecalcVecs {
    
    set TangMid to FindTangent(Ship:position).
    local TangDir is (TangMid:AltitudePosition(0) - Relaybeacon:position).
    local TangDist is TangDir:mag.

    // length of vector before tangent (not long than actual dist to tangent.)
    set Tanglen to min( TangDist, 60000).   
    
    local uTangUpV is (TangMid:position - Relaybeacon:Body:position):normalized.
    local uRV is vcrs(uTangUpV,TangDir):normalized.
    
    // Put the lines 1km apart unless we are quite close to the Relay as is super low.
    local tangWidth is max( 500, TangDist/10).
    local tangpos is TangMid:AltitudePosition(0).
    set TangRight to FindTangent(tangpos + tangWidth * uRV).
    set Tangleft to FindTangent(tangpos - tangWidth * uRV).
    
    
    vecListFlip(ListVecs, false). //turn them off and wipe therm
    ListVecs:clear().
    
    //make new ones
    //Print "Adding vecDraws".

 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// This is my kludge version that works.

// When i change it and dont store the VecDraws in local variables first it fails to display all the VecDraws.

// TBMK it "ought to" be 100% true that using or not using lcoal vars should make no difference at all.

    local v1 is VecDraw (
        {return TangMid:AltitudePosition(0).}, {return 140000 * ( TangMid:AltitudePosition(0) - Relaybeacon:position):normalized.}
            ,    RGB(1,0,0), MakeLabel("MR") , 1, true, 4,false,false).
     local v2 is VecDraw (
        {return TangMid:AltitudePosition(0) - Tanglen * (TangMid:AltitudePosition(0) - Relaybeacon:position):normalized. }, {return Tanglen * (TangMid:AltitudePosition(0) - Relaybeacon:position):normalized.}
            ,    RGB(0,1,0), MakeLabel("MR"), 1, true, 4,false,false).
    ListVecs:Add(v1).
    ListVecs:Add(v2).

  local Colr is 0.6.
    local Bl is 0.5.
    local v3 is VecDraw (
        {return TangLeft:AltitudePosition(0).}, {return 120000 * ( TangLeft:AltitudePosition(0) - Relaybeacon:position):normalized.}
            ,    RGB(Colr,0,Bl), MakeLabel("LR"), 1, true, 2.0,false,false).
     local v4 is VecDraw (
        {return TangLeft:AltitudePosition(0) - Tanglen * (TangLeft:AltitudePosition(0) - Relaybeacon:position):normalized. }, {return Tanglen * (TangLeft:AltitudePosition(0) - Relaybeacon:position):normalized.}
            ,    RGB(0,Colr,Bl), MakeLabel("LG"), 1, true, 2.0,false,false).
    ListVecs:Add(v3).
    ListVecs:Add(v4).

    local v5 is VecDraw (
        {return TangRight:AltitudePosition(0).}, {return 120000 * ( TangRight:AltitudePosition(0) - Relaybeacon:position):normalized.}
            ,    RGB(Colr,0,Bl), MakeLabel("RR"), 1, true, 2.0,false,false).
     local v6 is VecDraw (
        {return TangRight:AltitudePosition(0) - Tanglen * (TangRight:AltitudePosition(0) - Relaybeacon:position):normalized. }, {return Tanglen * (TangRight:AltitudePosition(0) - Relaybeacon:position):normalized.}
            ,    RGB(0,Colr,Bl), MakeLabel("RG"), 1, true, 2.0,false,false).
    ListVecs:Add(v5).
    ListVecs:Add(v6).

    
    //vecListFlip(ListVecs, true).
}

set lights to true.
set RCS to true.
set brakes to true.
PushUpIPU(500).

until Done {

  if ( lights = true) {
        if RCS = true {
            if recalc = true {
               // Print "doing recalc".
                    GetRelay().
                    RecalcVecs().

                    set recalc to false.
            }
        }
        if VecsShown = false {
            vecListFlip(ListVecs, true). //turn them off and wipe therm
            set VecsShown to true.
        }

    }    else {
      if VecsShown = true {
            vecListFlip(ListVecs, false). //turn them off and wipe therm
            set VecsShown to false.
        }
    }
    
    
    if RCS = true {
    //        print "recalc Is true".
            set recalc to true.
    }

//    Print TangMid + "/" + Tanglen.

 // print ListVecs.

    wait 1.
}

clearvecdraws().

 

 

Edited by AxleGreaser
clarity
Link to comment
Share on other sites

So My VecDraw code got refined. (and works reliably)

I only use this design pattern now.

Pattern: Vectors are only ever created as Globals and they are only done so once. If i want them not visible for now I set show=false. 

And I might well put all the individually named Global VecDraws in a list so I can find all the Shows to set to false. But the vec Draws were made and assigned Globally.

The anonymous call Backs { } in them refer to Global variables that define what I want drawn in terms of whatever frame of reference I want them to be stationary in. hence in my ground station relay surveying code I use geocoordinates to say where on the planet (lat long) to draw the vectors. And the Globally defined VecDraws know how to do that starting from the 'cached' geocoordinates (+limited (hence fast)math).

meanwhile.... I have this essential Program (in the spoiler below), probably most useful for submarines and they all obviously require "Frickin lasers".

And Jeb insists all the Rockets he flies has one out the front. He claims it makes them aerodynamicky, Bill thinks he just wants reminder which way hes going.)

Although Bill does insist it useful and is a Ruler and useful for guiding base construction and layout.

Although he does warn that utlizing KAS, + MKS FlexoTubes to build Reeeeeeeeally tall Coms towers (to see over ocean straits) with their COM > 100m  above ground/sea level summons *lots* of krakens. And that once yet get one upright Flying within physics load distance ever again is perhaps unwise. Get it landed and on rails and then never touch it again.

Edit: Addendum: A somewhat improved multifunction ruler. It can now auto redock pipes in bases is they get unglued by KAS operations.

There exist large physical designs where undocking thing turns off auto struts and everything goes bang, hence the need for instant auto redocking.

When building more than say 100m tall on kerbin these things become critical....  :O

 

Spoiler
 
 
 
1
Spoiler

// Making sure the boot loading code localised this on the HD is highly advised if useing it to build "Coms towers" out of contact with KSC. ;)

ClearvecDraws().  //does this mess up multiple rulers?
set CONFIG:IPU to 500.

Global TagName is "Plumb".

// TAGBits is global set up by the bootloading code that parsed the processors tag with _ seperators.
// These later tag bits let the ruler be controlled.
// The earlier tag bits defined that the ruler code ought to get loaded  
if TagBits:length > 3 {
    set TagName to TagBits[3].
}

Global DocStuff is false.
Global DocName is "Dont".
if TagBits:length > 4 {
    set DocName to TagBits[4].
    set DocStuff to true.
}

Global PlumbPart is core:part.
local MyPartList to SHIP:PARTSDUBBED(TagName).
if MyPartList:length >0 {
    set PlumbPart to MyPartList[0].
}

 


Global RulerLength is 50.
Global RulerLabel is "50m".
Global Rulervec1 is VecDraw (
        { return PlumbPart:position - PlumbPart:facing:forevector * RulerLength. }, { return PlumbPart:facing:forevector * 2*RulerLength.  }
            ,    RGB(1,0,0), RulerLabel , 1, true, 0.05,false,false).

Global Rulervec2 is VecDraw (
        { return PlumbPart:position - PlumbPart:facing:starvector * RulerLength.. }, { return PlumbPart:facing:starvector * 2*RulerLength.  }
            ,    RGB(1,0.5,0), RulerLabel , 1, true, 0.05,false,false).

Global Rulervec3 is VecDraw (
        { return PlumbPart:position - PlumbPart:facing:topvector * RulerLength.. }, { return PlumbPart:facing:topvector * 2*RulerLength.  }
            ,    RGB(1,0,0.5), RulerLabel , 1, true, 0.05,false,false).

Global PlumbLength is 200.
Global RulerLabel is "50m".
Global Plumbvec is VecDraw (
        { return PlumbPart:position -Ship:Up:forevector * PlumbLength + (Ship:North:forevector * 0.05). }, { return Ship:Up:forevector * PlumbLength * 2.  }
            ,    RGB(0,1,0), RulerLabel , 1, true, 0.05,false,false).
            
Global Done is false.            
local waitTime is 0.1.

local mods is 0.
local MyPartsList is 0.
local AMods is 0.
local pts is 0.
until Done {
        set WaitTime to 0.1 .
    
        if RCS = false {
            set Rulervec1:show to false.
            set Rulervec2:show to false.
            set Rulervec3:show to false.
            set Plumbvec:show to false.
        } else {
            set Rulervec1:show to true.
            set Rulervec2:show to true.
            set Rulervec3:show to true.
            set Plumbvec:show to true.
        
        }
        
        if DocStuff {
            set MyPartList to SHIP:PARTSTAGGEDPATTERN(DocName).
            for pts in MyPartList { //These parts are probablystill in the ships part list....
                set AMods to pts:Modules.
                // wait 0.5.    // This when uncommented helps find race condtions on parts going phooey.
                    
                if pts:hasModule("KASLinkSourceInteractive") {    
                    PRINT "TEST Source " + pts:tag.
                    set mods to pts:getmodule("KASLinkSourceInteractive").
                    if mods:hasEvent("link mode: undocked") {
                        if pts:Ship = Ship {
                                mods:doEvent("link mode: undocked").
                                // wait 0.1.
                                HUDTEXT(Ship:Name  + "Src Link = " + pts:tag,
                                5, 2, 12, magenta, true).
                        }  // else {                                 HUDTEXT(Ship:Name  + "barf ",                5, 2, 12, magenta, true). }

                        
                      set waitTime to 0.1 . //shorten wait time to 1 tick?
                         // do I I should I wait even after the dock?
                         // Where be the most Krakens
                    }    
                }    
                if pts:hasModule("KASLinkTargetBase") {    
                    PRINT "TEST Target " + pts:tag.
                    set mods to pts:getmodule("KASLinkTargetBase").
                    if mods:hasEvent("link mode: undocked") {
                        if pts:Ship = Ship {
                                mods:doEvent("link mode: undocked").
                                //wait 0.1.
                                HUDTEXT(Ship:Name  + " Targ Link = " + pts:tag,
                                        5, 2, 12, magenta, true).
                        } // else {                                 HUDTEXT(Ship:Name  + "barf ",                5, 2, 12, magenta, true). }

                        set waitTime to 0.1 . //shorten wait time to 1 tick?
                         // do I I should I wait even after the dock?
                         // Where be the most Krakens
                    }    
                }    
            }
        }    

    //print "tick".

    wait waitTime.
}           

 

       

 

Edited by AxleGreaser
gave more useful fuller version fo the Engineers ruler code.
Link to comment
Share on other sites

This thread is quite old. Please consider starting a new thread rather than reviving this one.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...