Skip to main content

sim_fmi/
api3.rs

1//! The FMI 3.0 Co-Simulation C functions, on the same instance as the FMI 2.0 ones (`api::Instance`). The type
2//! definitions follow the FMI 3.0 headers (fmi3PlatformTypes.h, fmi3FunctionTypes.h; Copyright Modelica Association
3//! Project "FMI", BSD-2-Clause licence), written out in Rust.
4//!
5//! Supported: `fmi3InstantiateCoSimulation`, initialisation, `fmi3DoStep`, get and set of Float64, Boolean and String
6//! variables (the other types have no variables: any value reference is refused), reset, terminate, FMU state get,
7//! set, free and (de)serialization, directional and adjoint derivatives (zero, see `api`). Not supported, returning
8//! `fmi3Error` or a null instance: Model Exchange and Scheduled Execution, Event Mode, Configuration Mode, clocks,
9//! output derivatives, variable dependencies at run time (the model description has them).
10
11#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
12
13use crate::api::{Instance, Logger, Value, get_strings, instantiate, slice, slice_mut, text, with};
14use std::ffi::{c_char, c_void};
15use std::path::Path;
16
17pub type fmi3Instance = *mut c_void;
18pub type fmi3InstanceEnvironment = *mut c_void;
19pub type fmi3FMUState = *mut c_void;
20pub type fmi3ValueReference = u32;
21pub type fmi3Float64 = f64;
22pub type fmi3Boolean = bool;
23pub type fmi3String = *const c_char;
24pub type fmi3Byte = u8;
25pub type fmi3Status = std::ffi::c_int;
26
27pub const fmi3OK: fmi3Status = 0;
28pub const fmi3Warning: fmi3Status = 1;
29pub const fmi3Discard: fmi3Status = 2;
30pub const fmi3Error: fmi3Status = 3;
31pub const fmi3Fatal: fmi3Status = 4;
32
33pub type fmi3LogMessageCallback = unsafe extern "C" fn(fmi3InstanceEnvironment, fmi3Status, fmi3String, fmi3String);
34pub type fmi3IntermediateUpdateCallback =
35    unsafe extern "C" fn(fmi3InstanceEnvironment, f64, bool, bool, bool, bool, *mut bool, *mut f64);
36
37#[unsafe(no_mangle)]
38pub extern "C" fn fmi3GetVersion() -> *const c_char {
39    c"3.0".as_ptr()
40}
41
42/// `resourcePath` is a plain absolute path to the resources folder, as FMI 3.0 has it.
43///
44/// # Safety
45/// As the FMI standard demands of the caller: valid strings, the callback valid for the instance's life.
46#[unsafe(no_mangle)]
47pub unsafe extern "C" fn fmi3InstantiateCoSimulation(
48    instanceName: fmi3String,
49    instantiationToken: fmi3String,
50    resourcePath: fmi3String,
51    _visible: fmi3Boolean,
52    loggingOn: fmi3Boolean,
53    _eventModeUsed: fmi3Boolean,
54    _earlyReturnAllowed: fmi3Boolean,
55    _requiredIntermediateVariables: *const fmi3ValueReference,
56    _nRequiredIntermediateVariables: usize,
57    instanceEnvironment: fmi3InstanceEnvironment,
58    logMessage: Option<fmi3LogMessageCallback>,
59    _intermediateUpdate: Option<fmi3IntermediateUpdateCallback>,
60) -> fmi3Instance {
61    let resources = Path::new(unsafe { text(resourcePath) });
62    instantiate(
63        unsafe { text(instanceName) },
64        Logger::Fmi3(logMessage),
65        instanceEnvironment,
66        resources,
67        unsafe { text(instantiationToken) },
68        3,
69        true,
70        loggingOn,
71    )
72}
73
74/// Not supported: logs why and returns null.
75///
76/// # Safety
77/// See `fmi3InstantiateCoSimulation`.
78#[unsafe(no_mangle)]
79pub unsafe extern "C" fn fmi3InstantiateModelExchange(
80    instanceName: fmi3String,
81    instantiationToken: fmi3String,
82    resourcePath: fmi3String,
83    _visible: fmi3Boolean,
84    _loggingOn: fmi3Boolean,
85    instanceEnvironment: fmi3InstanceEnvironment,
86    logMessage: Option<fmi3LogMessageCallback>,
87) -> fmi3Instance {
88    let resources = Path::new(unsafe { text(resourcePath) });
89    instantiate(
90        unsafe { text(instanceName) },
91        Logger::Fmi3(logMessage),
92        instanceEnvironment,
93        resources,
94        unsafe { text(instantiationToken) },
95        3,
96        false,
97        false,
98    )
99}
100
101/// Not supported: logs why and returns null.
102///
103/// # Safety
104/// See `fmi3InstantiateCoSimulation`.
105#[unsafe(no_mangle)]
106pub unsafe extern "C" fn fmi3InstantiateScheduledExecution(
107    instanceName: fmi3String,
108    instantiationToken: fmi3String,
109    resourcePath: fmi3String,
110    _visible: fmi3Boolean,
111    _loggingOn: fmi3Boolean,
112    instanceEnvironment: fmi3InstanceEnvironment,
113    logMessage: Option<fmi3LogMessageCallback>,
114    _clockUpdate: *const c_void,
115    _lockPreemption: *const c_void,
116    _unlockPreemption: *const c_void,
117) -> fmi3Instance {
118    let resources = Path::new(unsafe { text(resourcePath) });
119    instantiate(
120        unsafe { text(instanceName) },
121        Logger::Fmi3(logMessage),
122        instanceEnvironment,
123        resources,
124        unsafe { text(instantiationToken) },
125        3,
126        false,
127        false,
128    )
129}
130
131/// # Safety
132/// `c` is null or an instance from `fmi3InstantiateCoSimulation`; it is not used afterwards.
133#[unsafe(no_mangle)]
134pub unsafe extern "C" fn fmi3FreeInstance(c: fmi3Instance) {
135    if !c.is_null() {
136        drop(unsafe { Box::from_raw(c as *mut Instance) });
137    }
138}
139
140/// See `fmi2SetDebugLogging`.
141///
142/// # Safety
143/// See `api::with`; `categories` points to `nCategories` valid strings.
144#[unsafe(no_mangle)]
145pub unsafe extern "C" fn fmi3SetDebugLogging(
146    c: fmi3Instance,
147    loggingOn: fmi3Boolean,
148    nCategories: usize,
149    categories: *const fmi3String,
150) -> fmi3Status {
151    unsafe { crate::api::debug_logging(c, loggingOn, nCategories, categories) }
152}
153
154/// # Safety
155/// See `api::with`.
156#[unsafe(no_mangle)]
157pub unsafe extern "C" fn fmi3EnterInitializationMode(
158    c: fmi3Instance,
159    toleranceDefined: fmi3Boolean,
160    tolerance: f64,
161    startTime: f64,
162    stopTimeDefined: fmi3Boolean,
163    stopTime: f64,
164) -> fmi3Status {
165    unsafe {
166        with(c, |i| {
167            i.setup(toleranceDefined.then_some(tolerance), startTime, stopTimeDefined.then_some(stopTime))?;
168            i.enter_initialisation()
169        })
170    }
171}
172
173/// Without Event Mode, initialisation ends in Step Mode.
174///
175/// # Safety
176/// See `api::with`.
177#[unsafe(no_mangle)]
178pub unsafe extern "C" fn fmi3ExitInitializationMode(c: fmi3Instance) -> fmi3Status {
179    unsafe { with(c, Instance::exit_initialisation) }
180}
181
182/// # Safety
183/// See `api::with`.
184#[unsafe(no_mangle)]
185pub unsafe extern "C" fn fmi3Terminate(c: fmi3Instance) -> fmi3Status {
186    unsafe { with(c, Instance::terminate) }
187}
188
189/// # Safety
190/// See `api::with`.
191#[unsafe(no_mangle)]
192pub unsafe extern "C" fn fmi3Reset(c: fmi3Instance) -> fmi3Status {
193    unsafe { with(c, Instance::reset) }
194}
195
196/// A scalar variable takes one value per value reference.
197fn counts(nvr: usize, n_values: usize) -> Result<(), crate::api::Fail> {
198    if nvr == n_values { Ok(()) } else { Err(("fmi-error-count", format!("{nvr} / {n_values}"))) }
199}
200
201/// # Safety
202/// See `api::with`; `vr` points to `nvr` values, `values` to `nValues`.
203#[unsafe(no_mangle)]
204pub unsafe extern "C" fn fmi3GetFloat64(
205    c: fmi3Instance,
206    vr: *const fmi3ValueReference,
207    nvr: usize,
208    values: *mut f64,
209    nValues: usize,
210) -> fmi3Status {
211    unsafe {
212        with(c, |i| {
213            counts(nvr, nValues)?;
214            for (r, v) in slice(vr, nvr)?.iter().zip(slice_mut(values, nValues)?) {
215                *v = i.get_real(*r)?;
216            }
217            Ok(fmi3OK)
218        })
219    }
220}
221
222/// # Safety
223/// See `fmi3GetFloat64`.
224#[unsafe(no_mangle)]
225pub unsafe extern "C" fn fmi3SetFloat64(
226    c: fmi3Instance,
227    vr: *const fmi3ValueReference,
228    nvr: usize,
229    values: *const f64,
230    nValues: usize,
231) -> fmi3Status {
232    unsafe {
233        with(c, |i| {
234            counts(nvr, nValues)?;
235            for (r, v) in slice(vr, nvr)?.iter().zip(slice(values, nValues)?) {
236                i.set_value(*r, Value::Real(*v))?;
237            }
238            Ok(fmi3OK)
239        })
240    }
241}
242
243/// # Safety
244/// See `fmi3GetFloat64`.
245#[unsafe(no_mangle)]
246pub unsafe extern "C" fn fmi3GetBoolean(
247    c: fmi3Instance,
248    vr: *const fmi3ValueReference,
249    nvr: usize,
250    values: *mut fmi3Boolean,
251    nValues: usize,
252) -> fmi3Status {
253    unsafe {
254        with(c, |i| {
255            counts(nvr, nValues)?;
256            for (r, v) in slice(vr, nvr)?.iter().zip(slice_mut(values, nValues)?) {
257                *v = i.bool_value(i.variable(*r, "Boolean")?);
258            }
259            Ok(fmi3OK)
260        })
261    }
262}
263
264/// # Safety
265/// See `fmi3GetFloat64`.
266#[unsafe(no_mangle)]
267pub unsafe extern "C" fn fmi3SetBoolean(
268    c: fmi3Instance,
269    vr: *const fmi3ValueReference,
270    nvr: usize,
271    values: *const fmi3Boolean,
272    nValues: usize,
273) -> fmi3Status {
274    unsafe {
275        with(c, |i| {
276            counts(nvr, nValues)?;
277            for (r, v) in slice(vr, nvr)?.iter().zip(slice(values, nValues)?) {
278                i.set_value(*r, Value::Bool(*v))?;
279            }
280            Ok(fmi3OK)
281        })
282    }
283}
284
285/// The strings stay valid until the next call of this function on the instance.
286///
287/// # Safety
288/// See `fmi3GetFloat64`.
289#[unsafe(no_mangle)]
290pub unsafe extern "C" fn fmi3GetString(
291    c: fmi3Instance,
292    vr: *const fmi3ValueReference,
293    nvr: usize,
294    values: *mut fmi3String,
295    nValues: usize,
296) -> fmi3Status {
297    if nvr != nValues {
298        return unsafe { with(c, |_| counts(nvr, nValues).map(|_| fmi3OK)) };
299    }
300    unsafe { get_strings(c, vr, nvr, values) }
301}
302
303/// # Safety
304/// See `fmi3GetFloat64`; every string is valid.
305#[unsafe(no_mangle)]
306pub unsafe extern "C" fn fmi3SetString(
307    c: fmi3Instance,
308    vr: *const fmi3ValueReference,
309    nvr: usize,
310    values: *const fmi3String,
311    nValues: usize,
312) -> fmi3Status {
313    unsafe {
314        with(c, |i| {
315            counts(nvr, nValues)?;
316            for (r, v) in slice(vr, nvr)?.iter().zip(slice(values, nValues)?) {
317                i.set_value(*r, Value::Text(text(*v).into()))?;
318            }
319            Ok(fmi3OK)
320        })
321    }
322}
323
324/// # Safety
325/// See `api::with`; the out pointers are null or writable.
326#[unsafe(no_mangle)]
327pub unsafe extern "C" fn fmi3DoStep(
328    c: fmi3Instance,
329    currentCommunicationPoint: f64,
330    communicationStepSize: f64,
331    _noSetFMUStatePriorToCurrentPoint: fmi3Boolean,
332    eventHandlingNeeded: *mut fmi3Boolean,
333    terminateSimulation: *mut fmi3Boolean,
334    earlyReturn: *mut fmi3Boolean,
335    lastSuccessfulTime: *mut f64,
336) -> fmi3Status {
337    unsafe {
338        for flag in [eventHandlingNeeded, terminateSimulation, earlyReturn] {
339            if let Some(flag) = flag.as_mut() {
340                *flag = false;
341            }
342        }
343        let status = with(c, |i| i.do_step(currentCommunicationPoint, communicationStepSize));
344        // A refused step leaves the simulation where it was.
345        if let (Some(time), Some(i)) = (lastSuccessfulTime.as_mut(), (c as *const Instance).as_ref()) {
346            *time = i.now();
347        }
348        status
349    }
350}
351
352/// # Safety
353/// See `fmi2GetFMUstate`.
354#[unsafe(no_mangle)]
355pub unsafe extern "C" fn fmi3GetFMUState(c: fmi3Instance, state: *mut fmi3FMUState) -> fmi3Status {
356    unsafe { crate::api::state_get(c, state) }
357}
358
359/// # Safety
360/// See `fmi2SetFMUstate`.
361#[unsafe(no_mangle)]
362pub unsafe extern "C" fn fmi3SetFMUState(c: fmi3Instance, state: fmi3FMUState) -> fmi3Status {
363    unsafe { crate::api::state_set(c, state) }
364}
365
366/// # Safety
367/// See `fmi2FreeFMUstate`.
368#[unsafe(no_mangle)]
369pub unsafe extern "C" fn fmi3FreeFMUState(c: fmi3Instance, state: *mut fmi3FMUState) -> fmi3Status {
370    unsafe { crate::api::state_free(c, state) }
371}
372
373/// # Safety
374/// See `fmi2SerializedFMUstateSize`.
375#[unsafe(no_mangle)]
376pub unsafe extern "C" fn fmi3SerializedFMUStateSize(
377    c: fmi3Instance,
378    state: fmi3FMUState,
379    size: *mut usize,
380) -> fmi3Status {
381    unsafe { crate::api::state_size(c, state, size) }
382}
383
384/// # Safety
385/// See `fmi2SerializeFMUstate`.
386#[unsafe(no_mangle)]
387pub unsafe extern "C" fn fmi3SerializeFMUState(
388    c: fmi3Instance,
389    state: fmi3FMUState,
390    serializedState: *mut fmi3Byte,
391    size: usize,
392) -> fmi3Status {
393    unsafe { crate::api::state_serialize(c, state, serializedState, size) }
394}
395
396/// # Safety
397/// See `fmi2DeSerializeFMUstate`.
398#[unsafe(no_mangle)]
399pub unsafe extern "C" fn fmi3DeserializeFMUState(
400    c: fmi3Instance,
401    serializedState: *const fmi3Byte,
402    size: usize,
403    state: *mut fmi3FMUState,
404) -> fmi3Status {
405    unsafe { crate::api::state_deserialize(c, serializedState, size, state) }
406}
407
408/// ∂ unknowns / ∂ knowns times the seed: zero (see `api`).
409///
410/// # Safety
411/// See `api::with`; the pointers point to as many values as their counts say.
412#[unsafe(no_mangle)]
413pub unsafe extern "C" fn fmi3GetDirectionalDerivative(
414    c: fmi3Instance,
415    unknowns: *const fmi3ValueReference,
416    nUnknowns: usize,
417    knowns: *const fmi3ValueReference,
418    nKnowns: usize,
419    _seed: *const f64,
420    nSeed: usize,
421    sensitivity: *mut f64,
422    nSensitivity: usize,
423) -> fmi3Status {
424    // One seed per known, one sensitivity per unknown.
425    if nSeed != nKnowns || nSensitivity != nUnknowns {
426        return unsafe { with(c, |_| counts(nKnowns, nSeed).and(counts(nUnknowns, nSensitivity)).map(|_| fmi3OK)) };
427    }
428    unsafe { crate::api::zero_derivative(c, unknowns, nUnknowns, knowns, nKnowns, sensitivity, nSensitivity) }
429}
430
431/// The seed times ∂ unknowns / ∂ knowns: zero (see `api`).
432///
433/// # Safety
434/// See `fmi3GetDirectionalDerivative`.
435#[unsafe(no_mangle)]
436pub unsafe extern "C" fn fmi3GetAdjointDerivative(
437    c: fmi3Instance,
438    unknowns: *const fmi3ValueReference,
439    nUnknowns: usize,
440    knowns: *const fmi3ValueReference,
441    nKnowns: usize,
442    _seed: *const f64,
443    nSeed: usize,
444    sensitivity: *mut f64,
445    nSensitivity: usize,
446) -> fmi3Status {
447    // The adjoint the other way round: one seed per unknown, one sensitivity per known.
448    if nSeed != nUnknowns || nSensitivity != nKnowns {
449        return unsafe { with(c, |_| counts(nUnknowns, nSeed).and(counts(nKnowns, nSensitivity)).map(|_| fmi3OK)) };
450    }
451    unsafe { crate::api::zero_derivative(c, unknowns, nUnknowns, knowns, nKnowns, sensitivity, nSensitivity) }
452}
453
454macro_rules! no_variables {
455    ($($name:ident($type_name:literal $(, $arg:ident: $ty:ty)*);)*) => {$(
456        /// The FMU has no variables of this type: any value reference is refused.
457        ///
458        /// # Safety
459        /// See `fmi3GetFloat64`.
460        #[unsafe(no_mangle)]
461        pub unsafe extern "C" fn $name(c: fmi3Instance, vr: *const fmi3ValueReference, nvr: usize $(, $arg: $ty)*) -> fmi3Status {
462            $(let _ = $arg;)*
463            unsafe { with(c, |i| slice(vr, nvr)?.first().map_or(Ok(fmi3OK), |r| i.variable(*r, $type_name).map(|_| fmi3OK))) }
464        }
465    )*};
466}
467
468no_variables! {
469    fmi3GetFloat32("Float32", values: *mut f32, n: usize);
470    fmi3SetFloat32("Float32", values: *const f32, n: usize);
471    fmi3GetInt8("Int8", values: *mut i8, n: usize);
472    fmi3SetInt8("Int8", values: *const i8, n: usize);
473    fmi3GetUInt8("UInt8", values: *mut u8, n: usize);
474    fmi3SetUInt8("UInt8", values: *const u8, n: usize);
475    fmi3GetInt16("Int16", values: *mut i16, n: usize);
476    fmi3SetInt16("Int16", values: *const i16, n: usize);
477    fmi3GetUInt16("UInt16", values: *mut u16, n: usize);
478    fmi3SetUInt16("UInt16", values: *const u16, n: usize);
479    fmi3GetInt32("Int32", values: *mut i32, n: usize);
480    fmi3SetInt32("Int32", values: *const i32, n: usize);
481    fmi3GetUInt32("UInt32", values: *mut u32, n: usize);
482    fmi3SetUInt32("UInt32", values: *const u32, n: usize);
483    fmi3GetInt64("Int64", values: *mut i64, n: usize);
484    fmi3SetInt64("Int64", values: *const i64, n: usize);
485    fmi3GetUInt64("UInt64", values: *mut u64, n: usize);
486    fmi3SetUInt64("UInt64", values: *const u64, n: usize);
487    fmi3GetBinary("Binary", sizes: *mut usize, values: *mut *const u8, n: usize);
488    fmi3SetBinary("Binary", sizes: *const usize, values: *const *const u8, n: usize);
489    fmi3GetClock("Clock", values: *mut bool);
490    fmi3SetClock("Clock", values: *const bool);
491    fmi3GetIntervalDecimal("Clock", intervals: *mut f64, qualifiers: *mut i32);
492    fmi3GetIntervalFraction("Clock", counters: *mut u64, resolutions: *mut u64, qualifiers: *mut i32);
493    fmi3GetShiftDecimal("Clock", shifts: *mut f64);
494    fmi3GetShiftFraction("Clock", counters: *mut u64, resolutions: *mut u64);
495    fmi3SetIntervalDecimal("Clock", intervals: *const f64);
496    fmi3SetIntervalFraction("Clock", counters: *const u64, resolutions: *const u64);
497    fmi3SetShiftDecimal("Clock", shifts: *const f64);
498    fmi3SetShiftFraction("Clock", counters: *const u64, resolutions: *const u64);
499}
500
501macro_rules! unsupported {
502    ($($name:ident($($arg:ident: $ty:ty),*);)*) => {$(
503        /// Not supported: returns `fmi3Error`.
504        ///
505        /// # Safety
506        /// See `api::with`.
507        #[unsafe(no_mangle)]
508        pub unsafe extern "C" fn $name(c: fmi3Instance, $($arg: $ty),*) -> fmi3Status {
509            $(let _ = $arg;)*
510            unsafe { with(c, |_| Err(("fmi-error-unsupported", stringify!($name).into()))) }
511        }
512    )*};
513}
514
515unsupported! {
516    fmi3EnterEventMode();
517    fmi3EnterStepMode();
518    fmi3EnterConfigurationMode();
519    fmi3ExitConfigurationMode();
520    fmi3GetNumberOfVariableDependencies(vr: fmi3ValueReference, n: *mut usize);
521    fmi3GetVariableDependencies(dependent: fmi3ValueReference, element: *mut usize, independents: *mut fmi3ValueReference, elements: *mut usize, kinds: *mut i32, n: usize);
522    fmi3EvaluateDiscreteStates();
523    fmi3UpdateDiscreteStates(needUpdate: *mut bool, terminate: *mut bool, nominalsChanged: *mut bool, valuesChanged: *mut bool, nextDefined: *mut bool, next: *mut f64);
524    fmi3GetOutputDerivatives(vr: *const fmi3ValueReference, nvr: usize, orders: *const i32, values: *mut f64, n: usize);
525    fmi3ActivateModelPartition(clock: fmi3ValueReference, time: f64);
526    fmi3EnterContinuousTimeMode();
527    fmi3CompletedIntegratorStep(noSetFMUStatePriorToCurrentPoint: bool, enterEventMode: *mut bool, terminate: *mut bool);
528    fmi3SetTime(time: f64);
529    fmi3SetContinuousStates(states: *const f64, n: usize);
530    fmi3GetContinuousStateDerivatives(derivatives: *mut f64, n: usize);
531    fmi3GetEventIndicators(indicators: *mut f64, n: usize);
532    fmi3GetContinuousStates(states: *mut f64, n: usize);
533    fmi3GetNominalsOfContinuousStates(nominals: *mut f64, n: usize);
534    fmi3GetNumberOfEventIndicators(n: *mut usize);
535    fmi3GetNumberOfContinuousStates(n: *mut usize);
536}