forked from shiplab/vesseljs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvessel.module.js
3950 lines (2590 loc) · 108 KB
/
vessel.module.js
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
const REVISION = "v0.14-alpha";
//@EliasHasle
/*Base class for objects that are constructed from
a literal object.
Constructors can take more parameters than the specification, but the specification must be the first parameter.
setFromSpecification will typically be overridden by derived classes. Overriding implementations will typically do some sanity checking.
getSpecification will also typically be overridden. The default implementation here is just a sketch. Maybe not even correct for the simplest subclasses.
Maybe this can be improved by implementing fromJSON and to toJSON methods.
*/
class JSONSpecObject {
constructor( specification, baseObjects ) {
if ( specification === null ) {
console.warn( "JSONSpecObject: null specification provided. Defaulting to empty specification." );
specification = {};
} else if ( typeof specification === "object" ) ; else {
/*else if (typeof specification === "string") {
try {
specification = JSON.parse(specification);
} catch(e) {
console.error("JSONSpecObject: "+ e.message + "\n Defaulting to empty specification.");
specification = {};
}
}*/
if ( typeof specification !== "undefined" ) {
console.error( "JSONSpecObject: Invalid constructor parameter. Defaulting to empty specification." );
}
specification = {};
}
if ( baseObjects ) {
this.baseObjects = baseObjects;
}
this.setFromSpecification( specification );
}
setFromSpecification( specification ) {
//No sanity checking by default.
Object.assign( this, specification );
return this;
}
getSpecification() {
let spec = {};
for ( k of Object.keys( this ) ) {
if ( this.hasOwnProperty( k ) ) spec[ k ] = this[ k ];
}
return spec;
}
//toJSON is the standard way. Added here for testing.
toJSON() {
return this.getSpecification();
}
//fromJSON is added as an alternative and better name.
fromJSON( spec ) {
return this.setFromSpecification( spec );
}
}
//@EliasHasle
//Some interpolation helpers. Only linear and bilinear for now.
/*Function that takes a sorted array as input, and finds the last index that holds a numerical value less than, or equal to, a given value.
Returns an object with the index and an interpolation parameter mu that gives the position of value between index and index+1.
*/
function bisectionSearch( array, value ) {
if ( value < array[ 0 ] ) {
console.warn( "bisectionSearch: requested value below lowest array element. Returning undefined." );
return { index: undefined, mu: undefined };
}
let index = 0, upper = array.length;
while ( upper > index + 1 ) {
let c = Math.floor( 0.5 * ( index + upper ) );
if ( array[ c ] === value ) return { index: c, mu: 0 };
else if ( array[ c ] < value ) index = c;
else upper = c;
}
/*if (index === array.length) {
console.error("bisectionSearch: index===array.length. This should never happen.");
}*/
let mu = ( value - array[ index ] ) / ( array[ index + 1 ] - array[ index ] );
if ( index === array.length - 1 ) {
console.warn( "bisectionSearch: Reached end of array. Simple interpolation will result in NaN." );
mu = undefined;
}
return { index, mu };
}
//linear interpolation
//Defaults are not finally decided
//returns NaN if a and b are NaN or mu is NaN.
function lerp( a, b, mu = 0.5 ) {
if ( isNaN( a ) ) return b;
if ( isNaN( b ) ) return a;
return ( 1 - mu ) * a + mu * b;
}
//Test. Not safe yet.
function linearFromArrays( xx, yy, x ) {
let { index, mu } = bisectionSearch( xx, x );
if ( index === undefined || mu === undefined ) return 0;
return lerp( yy[ index ], yy[ index + 1 ], mu );
}
//Find coefficients for 1, x, y, xy.
//This doesn't yet handle zero-lengths well.
function bilinearCoeffs( x1, x2, y1, y2, z00, z01, z10, z11 ) {
let X = ( x2 - x1 );
let Y = ( y2 - y1 );
if ( X === 0 || Y === 0 ) {
//console.warn("bilinearCoeffs: Zero base area. Setting coefficients to zero.");
return [ 0, 0, 0, 0 ];
}
let Ainv = 1 / ( X * Y );
//constant coeff:
let b00 = Ainv * ( z00 * x2 * y2 - z10 * x1 * y2 - z01 * x2 * y1 + z11 * x1 * y1 );
//x coeff:
let b10 = Ainv * ( - z00 * y2 + z10 * y2 + z01 * y1 - z11 * y1 );
//y coeff:
let b01 = Ainv * ( - z00 * x2 + z10 * x1 + z01 * x2 - z11 * x1 );
//xy coeff:
let b11 = Ainv * ( z00 - z10 - z01 + z11 );
return [ b00, b10, b01, b11 ];
}
//Maybe I could do some simple linear interpolation in collapsed cases.
//But then I have to be sure what the z values and coefficients mean.
//I have apparently not documented this well.
function bilinear( x1, x2, y1, y2, z11, z12, z21, z22, x, y ) {
let [ b00, b10, b01, b11 ] =
bilinearCoeffs( x1, x2, y1, y2, z11, z12, z21, z22 );
let fromCoeffs = b00 + b10 * x + b01 * y + b11 * x * y;
//The following is supposed to be equivalent. Some tests yielding identical results (and no tests so far yielding different results) suggest that the calculations are in fact equivalent.
/*let mux = (x-x1)/(x2-x1);
let muy = (y-y1)/(y2-y1);
let fromUnitSquare = bilinearUnitSquare(z11, z12, z21, z22, mux, muy);
console.log("fromCoeffs=", fromCoeffs, ", fromUnitSquare=", fromUnitSquare);*/
return fromCoeffs;
}
class BaseObject extends JSONSpecObject {
constructor( specification ) {
super( specification );
this.weightCache = {};
}
setFromSpecification( spec ) {
this.id = spec.id;
this.affiliations = spec.affiliations || {};
this.boxDimensions = spec.boxDimensions || { length: undefined, width: undefined, height: undefined };
this.weightInformation = spec.weightInformation;
this.cost = spec.cost || { currency: undefined, value: undefined };
this.capabilities = spec.capabilities || {};
this.file3D = spec.file3D;
this.baseState = spec.baseState;
return this;
}
getSpecification() {
return {
id: this.id,
affiliations: this.affiliations,
boxDimensions: this.boxDimensions,
weightInformation: this.weightInformation,
cost: this.cost,
capabilities: this.capabilities,
file3D: this.file3D,
baseState: this.baseState
};
}
//Maybe this will take more state parameters than just fullness.
getWeight( fullness ) {
fullness = fullness || 0;
let wi = this.weightInformation;
//Should maybe have been this.capabilities.weightInformation?
//(Fluid) container properties default to no content:
let d = wi.contentDensity || 0;
let v = wi.volumeCapacity || 0;
//Maybe we should have another handling of cargo (with variable density)
let m = wi.lightweight + d * v * fullness;
let cg;
if ( wi.fullnessCGMapping !== undefined ) {
let fcgm = wi.fullnessCGMapping;
let fs = fcgm.fullnesses;
let cgs = fcgm.cgs;
//Find closest entries:
let { index: i, mu: mu } = bisectionSearch( fs, fullness );
cg = [];
for ( let j = 0; j < 3; j ++ ) {
let c;
if ( i < fs.length - 1 )
//Linear interpolation between closest entries:
c = lerp( cgs[ i ][ j ], cgs[ i + 1 ][ j ], mu );
else c = cgs[ i ][ j ];
//if (c===null || isNaN(c)) console.error("BaseObject.getWeight: Invalid value found after interpolation.");
cg.push( c );
}
} else if ( wi.cg !== undefined ) {
//console.log("BaseObject.getWeight: Using specified cg.");
cg = wi.cg;
} else {
console.warn( "BaseObject.getWeight: No cg or fullnessCGMapping supplied. Defaults to center of bounding box." );
cg = [ 0, 0, 0.5 * this.boxDimensions.height ];
}
let w = { mass: m, cg: { x: cg[ 0 ], y: cg[ 1 ], z: cg[ 2 ] } };
return w;
}
}
//@EliasHasle
//Some small helpers for operations on 3D vectors
//A vector is simply defined as an object with properties x,y,z.
const Vectors = {
clone: function ( v ) {
return { x: v.x, y: v.y, z: v.z };
},
scale: function ( v, s ) {
return { x: s * v.x, y: s * v.y, z: s * v.z };
},
norm: function ( v ) {
return Math.sqrt( v.x ** 2 + v.y ** 2 + v.z ** 2 );
},
normalize: function ( v ) {
let l = norm( v );
return { x: v.x / l, y: v.y / l, z: v.z / l };
},
normSquared: function ( v ) {
return v.x ** 2 + v.y ** 2 + v.z ** 2;
},
/*Adds two or more vectors given as individual parameters,
and returns a new vector that is the component-wise
sum of the input vectors.*/
add: function ( u, v, ...rest ) {
if ( rest.length > 0 ) return Vectors.sum( [ u, v ] + rest );
return { x: u.x + v.x, y: u.y + v.y, z: u.z + v.z };
},
//Takes an array of vectors as input, and returns a new vector
//that is the component-wise sum of the input vectors.
sum: function ( vectors ) {
let S = { x: 0, y: 0, z: 0 };
for ( let i = 0; i < vectors.length; i ++ ) {
let v = vectors[ i ];
S.x += v.x;
S.y += v.y;
S.z += v.z;
}
return S;
},
//Takes two vector parameters u,v, and returns the vector u-v.
sub: function ( u, v ) {
//return Vectors.add(u, Vectors.scale(v, -1)); //equivalent
return { x: u.x - v.x, y: u.y - v.y, z: u.z - v.z };
},
dot: function ( u, v ) {
return u.x * v.x + u.y * v.y + u.z * v.z;
},
cross: function ( u, v ) {
return {
x: u.y * v.z - u.z * v.y,
y: u.z * v.x - u.x * v.z,
z: u.x * v.y - u.y * v.x
};
},
mulComponents: function ( u, v ) {
return {
x: u.x * v.x,
y: u.y * v.y,
z: u.z * v.z
};
},
//Return the result of rotating the vector v by angles r={x,y,z} in radians.
//Intrinsic ZYX order (yaw,pitch,roll) is achieved by applying world axis rotations in XYZ order.
rotateTaitBryan: function ( v, r ) {
let c, s;
//Rotate around x axis
c = Math.cos( r.x );
s = Math.sin( r.x );
v = {
x: v.x,
y: v.y * c - v.z * s,
z: v.y * s + v.z * c
};
//Then around y axis
c = Math.cos( r.y );
s = Math.sin( r.y );
v = {
x: v.z * s + v.x * c,
y: v.y,
z: v.z * c - v.x * s
};
//Then around z axis
c = Math.cos( r.z );
s = Math.sin( r.z );
v = {
x: v.x * c - v.y * s,
y: v.x * s + v.y * c,
z: v.z
};
return v;
}
};
class DerivedObject extends JSONSpecObject {
constructor( specification, baseObjects ) {
super( specification, baseObjects );
}
setFromSpecification( spec ) {
this.id = spec.id;
this.group = spec.group || null;
this.affiliations = spec.affiliations;
if ( typeof spec.baseObject === "string" ) {
this.baseObject = this.baseObjects[ spec.baseObject ];
} else {
this.baseObject = new BaseObject( spec.baseObject );
}
this.referenceState = spec.referenceState;
//this.referenceStateVersion = 0;
this.style = spec.style || {};
return this;
}
getSpecification() {
let spec = {
id: this.id,
group: this.group,
affiliations: this.affiliations,
referenceState: this.referenceState,
style: this.style
};
if ( this.baseObjects[ this.baseObject.id ] !== undefined ) {
spec.baseObject = this.baseObject.id;
} else {
spec.baseObject = this.baseObject.getSpecification();
}
return spec;
}
getWeight( state ) {
let oState = state.getObjectState( this );
//Support disabled objects:
if ( oState.exists === false ) {
return { mass: 0, cg: { x: 0, y: 0, z: 0 } };
}
let p = {
x: oState.xCentre,
y: oState.yCentre,
z: oState.zBase
};
let w = this.baseObject.getWeight( oState.fullness );
let m = w.mass;
let cg = Vectors.add( p, w.cg );
if ( isNaN( cg.x + cg.y + cg.z ) ) {
console.error( "DerivedObject.getWeight: returning NaN values." );
}
return { mass: m, cg: cg };
}
}
//@MrEranwe
//@EliasHasle
//Elias notes:
//LCB and LCG were obviously considered in another coordinate system than we are using. I have corrected this, assuming that the wrong coordinate system had the origin centered longitudinally.
//The hull mass is off by several orders of magnitude. Checking the paper, it seems likely that the "typical" K parameters are aimed at producing units of tonnes, not kg.
//It is not mathematically correct to strip down the structural weight calculation the way it is done here, because the exponentiation (E^1.36) cannot be simply decomposed as a sum of exponentiated terms (with the same exponent).
//Elias has only reviewed and modified the hull weight calculation.
// This function estimates the structural weight of the hull. This includes the weight of the basic hull to its depth amidships.
// It is based on Watson and Gilfillan modeling approach using a specific modification of the Lloyd’s Equipment Numeral E as the independent variable.
//
//
// Inputs
// K is the structural weight coefficient. Parsons, chapter 11, table 11.VII.
// L is LWL or LBP
// B is molded beam
// T is molded draft
// D is molded depth
// Superstructures and shiphouses are not being considered in the weight
// CB is the block coefficient
// LCB is the Longitudinal Center of Bouyancy
//
// Return
// It returns an object on the format {mass:1234, cg: {x:4,y:3,z:2}}, where the unit of mass is unclear, and x,y,z is in meters from aft,center,bottom, respectively.
function parametricWeightHull( K, L, B, T, D, CB, Fn ) {
// Calculates estimated structural weight
// E is the Lloyd’s Equipment Numeral
let E = L * ( B + T ) + 0.85 * L * ( D - T );
// CbCorrected is the estimated corrected block coefficient
let CBCorrected = CB + ( 1 - CB ) * ( ( 0.8 * D - T ) / ( 3 * T ) );
// W is the estimated structural weight
let W = K * Math.pow( E, 1.36 ) * ( 1 + 0.5 * ( CBCorrected - 0.7 ) );
// Calculates LCG and VCG
// VCGHull is the Vertical Center of Gravity of the hull
let VCGHull = 0;
if ( L < 120 ) {
VCGHull = 0.01 * D * ( 46.6 + 0.135 * ( 0.81 - CB ) * Math.pow( L / D, 2 ) ) + 0.008 * D * ( L / D - 6.5 );
} else {
VCGHull = 0.01 * D * ( 46.6 + 0.135 * ( 0.81 - CB ) * Math.pow( L / D, 2 ) );
}
// LCB is the longitudinal Center of Buoyancy converted from
// percentage plus forward of amidships to meters from aft
let LCB = Fn ? 0.5 * L + ( 9.7 - 45 * Fn ) * L / 100 : L * 0.516;
// LCGHull is the Longitudinal Center of Gravity of the hull in meters from aft
let LCGHull = LCB - 0.15 * L / 100;
// Returns the object
return { mass: W, cg: { x: LCGHull, y: 0, z: VCGHull } };
}
//@EliasHasle
//All inputs are numbers. The axes are given by a single coordinate.
function steiner( I, A, sourceAxis, targetAxis ) {
return I + A * ( sourceAxis - targetAxis ) ** 2;
}
//Calculate area, center, Ix, Iy.
function trapezoidCalculation( xbase0, xbase1, xtop0, xtop1, ybase, ytop ) {
let a = xbase1 - xbase0;
let b = xtop1 - xtop0;
let h = ytop - ybase;
if ( a < 0 || b < 0 || h < 0 ) {
console.warn( "trapezoidCalculation: Unsupported input. Possibly not a valid trapezoid." );
}
let A = 0.5 * ( a + b ) * h;
let yc = ( a == 0 && b == 0 ) ? ybase + 0.5 * h : ybase + h * ( 2 * a + b ) / ( 3 * ( a + b ) );
let d = xbase0 + 0.5 * a; //shorthand
let xc = h === 0 ? 0.25 * ( xbase0 + xbase1 + xtop0 + xtop1 ) : d + ( xtop0 + 0.5 * b - d ) * ( yc - ybase ) / h;
let Ix = ( a == 0 && b == 0 ) ? 0 : h ** 3 * ( a ** 2 + 4 * a * b + b ** 2 ) / ( 36 * ( a + b ) );
//For Iy I must decompose (I think negative results will work fine):
let Art1 = 0.5 * ( xtop0 - xbase0 ) * h;
let xcrt1 = xbase0 + ( xtop0 - xbase0 ) / 3;
let Iyrt1 = ( xtop0 - xbase0 ) ** 3 * h / 36;
let Arec = ( xbase1 - xtop0 ) * h;
let xcrec = 0.5 * ( xtop0 + xbase1 );
let Iyrec = ( xbase1 - xtop0 ) ** 3 * h / 12;
let Art2 = 0.5 * ( xbase1 - xtop1 ) * h;
let xcrt2 = ( xtop1 + ( xbase1 - xtop1 ) / 3 );
let Iyrt2 = ( xbase1 - xtop1 ) ** 3 * h / 36;
let Iy = steiner( Iyrt1, Art1, xcrt1, xc )
+ steiner( Iyrec, Arec, xcrec, xc )
+ steiner( Iyrt2, Art2, xcrt2, xc );
let maxX = Math.max.apply( null, [ xbase0, xbase1, xtop0, xtop1 ] );
let minX = Math.min.apply( null, [ xbase0, xbase1, xtop0, xtop1 ] );
let maxY = Math.max( ybase, ytop );
let minY = Math.min( ybase, ytop );
return { A: A, xc: xc, yc: yc, Ix: Ix, Iy: Iy, maxX: maxX, minX: minX, maxY: maxY, minY: minY };
}
function combineAreas( array ) {
let A = 0;
let xc = 0;
let yc = 0;
let maxX = 0,
minX = 0,
maxY = 0,
minY = 0;
let L = array.length;
let foundMinY = false;
let foundMaxY = false;
for ( let i = 0; i < L; i ++ ) {
let e = array[ i ];
A += e.A;
xc += e.xc * e.A;
yc += e.yc * e.A;
if ( ! isNaN( e.maxX ) && e.maxX > maxX ) maxX = e.maxX;
if ( ! isNaN( e.minX ) && e.minX < minX ) minX = e.minX;
if ( ! isNaN( e.maxY ) && e.maxY > maxY && ! foundMaxY && foundMinY ) {
maxY = e.maxY;
if ( e.A === 0 ) {
foundMaxY = true;
}
}
if ( ! isNaN( e.minY ) && ! foundMinY ) {
if ( e.A !== 0 ) {
minY = e.minY;
foundMinY = true;
}
}
}
if ( ! foundMaxY ) maxY = array[ L - 1 ].maxY; //if foundMaxY is false then the ship is a barge and a different logic must apply @ferrari212
let Ix = 0;
let Iy = 0;
if ( A !== 0 ) {
xc /= A;
yc /= A;
} else {
//console.warn("Zero area combination.");
//console.trace();
xc /= L;
yc /= L;
}
for ( let i = 0; i < array.length; i ++ ) {
let e = array[ i ];
Ix += steiner( e.Ix, e.A, e.yc, yc );
Iy += steiner( e.Iy, e.A, e.xc, xc );
}
return { A: A, xc: xc, yc: yc, Ix: Ix, Iy: Iy, maxX: maxX, minX: minX, maxY: maxY, minY: minY };
}
//x and y here refers to coordinates in the plane that is being calculated on.
function sectionCalculation( { xs, ymins, ymaxs } ) {
//console.group/*Collapsed*/("sectionCalculation");
//console.info("Arguments (xs, ymins, ymaxs): ", arguments[0]);
let calculations = [];
for ( let i = 0; i < xs.length - 1; i ++ ) {
let xbase = xs[ i ];
let xtop = xs[ i + 1 ];
let ybase0 = ymins[ i ] || 0;
let ybase1 = ymaxs[ i ] || 0;
let ytop0 = ymins[ i + 1 ] || 0;
let ytop1 = ymaxs[ i + 1 ] || 0;
calculations.push( trapezoidCalculation( ybase0, ybase1, ytop0, ytop1, xbase, xtop ) );
}
let C = combineAreas( calculations ); //Might be zero areas!
let output = { A: C.A, maxX: C.maxY, minX: C.minY, maxY: C.maxX, minY: C.minX, xc: C.yc, yc: C.xc, Ix: C.Iy, Iy: C.Ix, Abb: ( C.maxY - C.minY ) * ( C.maxX - C.minX ) };
//console.info("Output: ", output);
//console.groupEnd();
return output;
}
//For wetted area. I think this is right, but it is not tested.
//The numerical integral will not scale well with larger geometries.
//Then the full analytical solution is needed.
function bilinearArea( x1, x2, y1, y2, z11, z12, z21, z22, segs = 5 ) {
let [ b00, b10, b01, b11 ] = bilinearCoeffs( x1, x2, y1, y2, z11, z12, z21, z22 );
/*
z(x,y) = b00 + b10*x + b01*y + b11*xy
Partial derivative in x: b10 + b11*y
Partial derivative in y: b01 + b11*x
I think this will be right:
Tx(y) = (1, 0, b10+b11*y)
Ty(x) = (0, 1, b01+b11*x)
Then:
Tx X Ty = (-(b10+b11*y), -(b01+b11*x), 1)
|Tx X Ty| = sqrt((b10+b11*y)^2 + (b01+b11*x)^2 + 1)
Now, to get the area I need to integrate |Tx X Ty| over X,Y.
Wolfram Alpha gave me this for the inner integral using x (indefinite):
integral sqrt((b01 + b11 x)^2 + 1 + (b10+b11*y)^2) dx = ((b01 + b11*x) sqrt((b01 + b11*x)^2 + 1 + (b10+b11*y)^2) + (1 + (b10+b11*y)^2)*ln(sqrt((b01 + b11*x)^2 + 1 + (b10+b11*y)^2) + b01 + b11*x))/(2*b11) + constant
That means this for the definite integral:
((b01 + b11*x2)*sqrt((b01 + b11*x2)^2 + 1 + (b10+b11*y)^2) + 1 + (b10+b11*y)^2*ln(sqrt((b01 + b11*x2)^2 + 1 + (b10+b11*y)^2) + b01 + b11*x2))/(2*b11) - ((b01 + b11*x1)*sqrt((b01 + b11*x1)^2 + 1 + (b10+b11*y)^2) + (1 + (b10+b11*y)^2)*ln(sqrt((b01 + b11*x1)^2 + 1 + (b10+b11*y)^2) + b01 + b11*x1))/(2*b11)
=
(b01 + b11*x2)*sqrt((b01 + b11*x2)^2 + 1 + (b10+b11*y)^2)/(2*b11)
+(1 + (b10+b11*y)^2)*ln(sqrt((b01 + b11*x2)^2 + 1 + (b10+b11*y)^2) + b01 + b11*x2)/(2*b11))
- (b01 + b11*x1)*sqrt((b01 + b11*x1)^2 + 1 + (b10+b11*y)^2)/(2*b11)
- (1 + (b10+b11*y)^2)*ln(sqrt((b01 + b11*x1)^2 + 1 + (b10+b11*y)^2) + b01 + b11*x1)/(2*b11)
=
(b01 + b11*x2)*sqrt((b01 + b11*x2)^2 + 1 + (b10+b11*y)^2)/(2*b11)
- (b01 + b11*x1)*sqrt((b01 + b11*x1)^2 + 1 + (b10+b11*y)^2)/(2*b11)
+(1 + (b10+b11*y)^2)*ln(sqrt((b01 + b11*x2)^2 + 1 + (b10+b11*y)^2) + b01 + b11*x2)/(2*b11))
- (1 + (b10+b11*y)^2)*ln(sqrt((b01 + b11*x1)^2 + 1 + (b10+b11*y)^2) + b01 + b11*x1)/(2*b11)
The two first integrals are similar, and the two last are also similar. With A=+-(b01 + b11*xi)/(2*b11), B=(b01 + b11*xi)^2+1, C=b10 and D=b11 (where xi represents either x1 or x2, and +- represents + for x2 and - for x1), I can calculate the integral of sqrt(B+(C+D*y)^2) and multiply by A. That integral is on the same form as the first one.
The two last integrals can be represented by setting A=+-1/(2*b11), B=(b01 + b11*xi)^2+1, C=b01+b11*xi, D=b10, E=b11, and calculating the integral of (1+(D+E*y)^2)*ln(sqrt(B+(D+E*y)^2)+C), and multiplying by A.
Here is the integration result from Wolfram Alpha:
integral(1 + (D + E y)^2) log(sqrt(B + (D + E y)^2) + C) dy = (-(6 (B^2 - 2 B C^2 - 3 B + C^4 + 3 C^2) tan^(-1)((D + E y)/sqrt(B - C^2)))/sqrt(B - C^2) + (6 (B^2 - 2 B C^2 - 3 B + C^4 + 3 C^2) tan^(-1)((C (D + E y))/(sqrt(B - C^2) sqrt(B + (D + E y)^2))))/sqrt(B - C^2) + 6 (B - C^2 - 3) (D + E y) + 3 C (-3 B + 2 C^2 + 6) log(sqrt(B + (D + E y)^2) + D + E y) + 3 C (D + E y) sqrt(B + (D + E y)^2) + 6 ((D + E y)^2 + 3) (D + E y) log(sqrt(B + (D + E y)^2) + C) - 2 (D + E y)^3)/(18 E) + constant
I am glad I did not try to do this by hand. But combining these formulae, we can get an exact integral of the area of a bilinear patch. Later. Bilinear patches are not an exact representation anyway. We may opt for something else.
*/
//Simple numerical calculation of double integral:
let A = 0;
let X = x2 - x1, Y = y2 - y1;
let N = segs, M = segs;
for ( let i = 0; i < N; i ++ ) {
let x = x1 + ( ( i + 0.5 ) / N ) * X;
for ( let j = 0; j < M; j ++ ) {
let y = y1 + ( ( j + 0.5 ) / M ) * Y;
A += Math.sqrt( ( b10 + b11 * y ) ** 2 + ( b01 + b11 * x ) ** 2 + 1 );
}
}
A *= X * Y / ( N * M ); //dx dy
return A;
}
//@EliasHasle
//I have been doing some tests here of a simplified calculation.
//The results so far indicate that, for the prism hull, the results are almost identical, except that with the simple calculation the center of volume is almost right (but wrong enough to disqualify such a simple calculation).
/*Note that the coordinate system used here has xy as a grid, with z as heights on the grid, but in the intended application, which is calculations on transverse hull offsets, this z corresponds to the vessel y axis, and y corresponds to the vessel z axis. In any application of this function, the conversion between coordinate systems must be taken care of appropriately.*/
// xy
function patchColumnCalculation( x1, x2, y1, y2, z00, z01, z10, z11 ) {
//VOLUME:
//Analysis based on a bilinear patch:
// /*
// From here I call mux for x, and muy for y.
// Integral over unit square:
// INT[x from 0 to 1, INT[y from 0 to 1, (a00 + a10*x + a01*y + a11*x*y) dy] dx]
// = INT[x from 0 to 1, (a00+a10*x+0.5*a01+0.5*a11*x) dx]
// = a00 + 0.5*a10 + 0.5*a01 + 0.25*a11
// Note that by expanding a00,a10,a01,a11, it is demonstrated that this (rather unsurprisingly) is exactly equivalent to taking the average z offset of the control points.
// */
let X = x2 - x1;
let Y = y2 - y1;
let Ab = X * Y; //area of base of patch column
//let zAvg = (a00 + 0.5*a10 + 0.5*a01 + 0.25*a11);
let zAvg = 0.25 * ( z00 + z01 + z10 + z11 ); //equivalent
let V = Math.abs( Ab * zAvg ); //works
//CENTER OF VOLUME
let zc = 0.5 * zAvg;
//Very approximate center of volume
//(does not account for different signs on z values,
//but that should be OK for hull offsets)
//let xc = (x1*(z00+z01)+x2*(z10+z11))/((z00+z01+z10+z11) || 1);
//let yc = (y1*(z00+z10)+y2*(z01+z11))/((z00+z01+z10+z11) || 1);
// /*
// To find xc properly, I need to integrate x*z over the unit square, divide by zAvg(?) and scale and translate to ship coordinates afterwards:
// INT[x from 0 to 1, INT[y from 0 to 1, x*(a00 + a10*x + a01*y + a11*x*y) dy] dx] =
// INT[x from 0 to 1, INT[y from 0 to 1, (a00*x + a10*x^2 + a01*xy + a11*x^2*y) dy] dx] =
// INT[x from 0 to 1, (a00*x + a10*x^2 + 0.5*a01*x + 0.5*a11*x^2) dx]
// = (0.5*a00 + a10/3 + 0.25*a01 + a11/6)
//Trying to expand the coeffs to original z offsets:
// = (0.5*z00 + (z10-z00)/3 + 0.25*(z01-z00) + (z00+z00-z01-z10)/6)
// = ((1/12)*z00 + (1/6)*z10 + (1/12)*z01 + (1/6)*z00)
//Divide by zAvg to get muxc, then scale and translate to xc.
let xc = x1 + X * ( ( ( 1 / 12 ) * z00 + ( 1 / 6 ) * z10 + ( 1 / 12 ) * z01 + ( 1 / 6 ) * z11 ) / ( zAvg || 1 ) );
//console.log("x1=%.2f, X=%.2f, muxc = %.2f", x1, X, (((1/12)*z00 + (1/6)*z10 + (1/12)*z01 + (1/6)*z11) / (zAvg || 1)));
//Similar for yc (modified symmetrically)
let yc = y1 + Y * ( ( ( 1 / 12 ) * z00 + ( 1 / 12 ) * z10 + ( 1 / 6 ) * z01 + ( 1 / 6 ) * z11 ) / ( zAvg || 1 ) );
//console.log("Patch column Cv = (%.2f, %.2f, %.2f)", xc,yc,zc);
//AREA
//These two methods give very similar results, within about 1% difference for the fishing boat hull (used in PX121.json).
//Simple triangle average approximation for area (works)
/*let As = elementArea(
{x: x1, y: y1, z: z00},
{x: x1, y: y2, z: z01},
{x: x2, y: y1, z: z10},
{x: x2, y: y2, z: z11});*/
//Bilinear area calculation. Works too, but is currently numerical, and quite complex (which means it is bug-prone and hard to maintain). But it is more exact, even with just a few segments for numerical integration (the last, optional, parameter)
let As = Math.abs( bilinearArea( x1, x2, y1, y2, z00, z01, z10, z11 ) );
return { Ab: Ab, As: As, V: V, Cv: { x: xc, y: yc, z: zc } };
}
//Input: array of objects with calculation results for elements.
//Output: the combined results.
function combineVolumes( array ) {
let V = 0;
let As = 0;
let Cv = { x: 0, y: 0, z: 0 };
let L = array.length;
//if (L===0) return {V,As,Cv};
for ( let i = 0; i < L; i ++ ) {
let e = array[ i ];
V += e.V;
As += e.As; //typically wetted area
//console.log(e.Cv);
Cv = Vectors.add( Cv, Vectors.scale( e.Cv, e.V ) );
}
Cv = Vectors.scale( Cv, 1 / ( V || L || 1 ) );
//console.info("combineVolumes: Combined Cv is (" + Cv.x + ", " + Cv.y + ", " + Cv.z + ").");
return { V, As, Cv };//{V: V, As: As, Cv: Cv};
}
class Hull extends JSONSpecObject {
constructor( spec ) {
super( spec );
}
setFromSpecification( spec ) {
this.halfBreadths = spec.halfBreadths;
//this.buttockHeights = spec.buttockHeights;
this.attributes = spec.attributes; //this could/should include LOA, BOA, Depth
this.levelsNeedUpdate = true;
this.style = spec.style || {};
return this;
}
getWeight( designState ) {
let ha = this.attributes;
let B = ha.BOA;
let D = ha.Depth;
let cp = designState.calculationParameters;
let K = cp.K;
let L = cp.LWL_design;
let T = cp.Draft_design;
let Cb = cp.Cb_design;
let vsm = 0.514444 * cp.speed; // Convert the design speed from knots to m/s
let Fn = vsm / Math.pow( 9.81 * L, 0.5 ); // Calculates Froude number
//This is not a good way to estimate the hull weight.
let parsons = parametricWeightHull( K, L, B, T, D, Cb, Fn );
parsons.mass *= 1000; //ad hoc conversion to kg, because the example K value is aimed at ending with tonnes.
let output = parsons;
//console.info("Hull weight:", output);
return output;
}
getStation( x ) {
let ha = this.attributes;
let xr = x / ha.LOA;
let sts = this.halfBreadths.stations;
let wls = this.halfBreadths.waterlines;
let tab = this.halfBreadths.table;
let { index: a, mu: mu } = bisectionSearch( sts, xr );
let st;
if ( a < 0 || a >= sts.length ) st = new Array( wls.length ).fill( null );
else if ( a + 1 === sts.length ) st = tab.map( row => row[ sts.length - 1 ] );
else {
st = [];
for ( let j = 0; j < wls.length; j ++ ) {
let after = tab[ j ][ a ];
let forward = tab[ j ][ a + 1 ];
if ( ( after === null || isNaN( after ) ) && ( forward === null || isNaN( forward ) ) ) {
st.push( null );
} else {
//Simply correcting by "|| 0" is not consistent with what is done in getWaterline. It may be better to correct upper nulls by nearest neighbor below.
st.push( lerp( after || 0, forward || 0, mu ) );
}
}
}
for ( let j = 0; j < this.halfBreadths.waterlines.length; j ++ ) {
st[ j ] *= 0.5 * ha.BOA;
if ( isNaN( st[ j ] ) || st[ j ] === null ) st[ j ] = null;
}
return st;
}
getWaterline( z ) {
let ha = this.attributes;
let zr = z / ha.Depth; //using zr requires fewer operations and less memory than a scaled copy of wls.
let wls = this.halfBreadths.waterlines;//.map(wl=>wl*ha.Depth);
let sts = this.halfBreadths.stations;
let tab = this.halfBreadths.table;
if ( zr < wls[ 0 ] ) {
//console.warn("getWaterLine: z below lowest defined waterline. Defaulting to all zero offsets.");
return new Array( sts.length ).fill( 0 );
} else {
let a, mu;
if ( zr > wls[ wls.length - 1 ] ) {
//console.warn("getWaterLine: z above highest defined waterline. Proceeding with highest data entries.");