licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
code
236
@testset "Statistics" begin fname = joinpath(dirname(@__FILE__), "..", "data", "test_Hz19.5-testing.bdf") s = read_SSR(fname) @testset "Global Field Power" begin ~ = gfp(s.data) # TODO: Check result end end
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
code
2656
using Neuroimaging, Test, BDF @testset "GeneralEEG" begin fname = joinpath(dirname(@__FILE__), "..", "data", "test_Hz19.5-testing.bdf") s = read_EEG(fname) @test isa(s, NeuroimagingMeasurement) @test isa(s, EEG) @testset "Show" begin show(s) end @testset "Read file" begin s = read_EEG(fname) @info samplingrate(s) @test samplingrate(s) == 8192.0 @info samplingrate(s) @test samplingrate(Int, s) == 8192 @test isa(samplingrate(s), AbstractFloat) == true @test isa(samplingrate(Int, s), Int) == true @test isapprox(maximum(s.data[:, 2]), 54.5939; atol = 0.1) @test isapprox(minimum(s.data[:, 4]), -175.2503; atol = 0.1) s = read_EEG(fname, valid_triggers = [8]) s = read_EEG(fname, min_epoch_length = 8388) s = read_EEG(fname, max_epoch_length = 8389) s = read_EEG(fname) original_length = length(s.triggers["Index"]) s = read_EEG(fname, remove_first = 10) @test original_length - 10 == length(s.triggers["Index"]) s = read_EEG(fname, max_epochs = 12) @test length(s.triggers["Index"]) == 12 s = read_EEG(fname) s.triggers = extra_triggers(s.triggers, 1, 7, 0.7, samplingrate(s)) @test length(s.triggers["Index"]) == 56 end @testset "Sensors" begin s1 = sensors(deepcopy(s)) @test length(s1) == 6 @test length(x(s1)) == 6 @test length(labels(s1)) == 6 end @testset "Channel names" begin s1 = deepcopy(s) s1 = channelnames(s1, 1, "A01") s1 = channelnames(s1, 2, "A05") s1 = channelnames(s1, 3, "A11") s1 = channelnames(s1, 4, "B03") s1 = channelnames(s1, 5, "A17") s1 = channelnames(s1, 6, "B17") @test channelnames(s1) == ["A01", "A05", "A11", "B03", "A17", "B17"] end @testset "Triggers" begin dats, evtTab, trigs, statusChan = readBDF(fname) sampRate = readBDFHeader(fname)["sampRate"][1] @test trigs == create_channel( evtTab, dats, sampRate, code = "code", index = "idx", duration = "dur", ) @test trigs == trigger_channel(read_EEG(fname, valid_triggers = collect(-1000:10000))) # Convert between events and channels dats, evtTab, trigs, statusChan = readBDF(fname) events = create_events(trigs, sampRate) channel = create_channel(events, dats, sampRate) @test size(channel) == size(trigs) @test channel == trigs end end
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
code
2326
@testset "Coordinates" begin @testset "Create" begin @testset "Brain Vision" begin bv = BrainVision(0, 0, 0) @testset "Show" begin show(bv) end end @testset "Talairach" begin tal = Talairach(68.3, -26.9, 8.3) @testset "Show" begin show(tal) end end @testset "SPM" begin spm = SPM(68.3, -26.9, 8.3) @testset "Show" begin show(spm) end end @testset "Unknown" begin uk = UnknownCoordinate(1.2, 2, 3.2) @testset "Show" begin show(uk) end end end @testset "Convert" begin @testset "MNI -> Talairach" begin # Values from table IV in Lancaster et al 2007 # TODO Find better points to translate mni = SPM(73.7u"mm", -26.0u"mm", 7.0u"mm") tal = Talairach(68.3u"mm", -26.9u"mm", 8.3u"mm") mni_converted = convert(Talairach, mni) dist = euclidean(mni_converted, tal) @test isapprox(dist, 0; atol = 2) # As an electrode # Test as an electrode e = Electrode("test", SPM(73.7u"mm", -26.0u"mm", 7.0u"mm"), Dict()) e = conv_spm_mni2tal(e) @test isapprox(e.coordinate.x, tal.x; atol = 1.5u"m") @test isapprox(e.coordinate.y, tal.y; atol = 1.5u"m") @test isapprox(e.coordinate.z, tal.z; atol = 1.5u"m") @test isa(e, Neuroimaging.Sensor) == true @test isa(e, Neuroimaging.Electrode) == true @test isa(e.coordinate, Neuroimaging.Talairach) == true end @testset "BrainVision -> Talairach" begin # TODO this just tests it runs, need to check values bv = BrainVision(0, 0, 0) tal = Talairach(128u"mm", 128u"mm", 128u"mm") @test isapprox(euclidean(convert(Talairach, bv), tal), 0; atol = 1.5) end end @testset "Distances" begin @test euclidean(Talairach(0, 0, 0), Talairach(1, 1, 1)) == sqrt.(3) v = [0, 0, 0] @test euclidean(Talairach(1, 1, 1), v) == sqrt.(3) @test euclidean(v, Talairach(1, 1, 1)) == sqrt.(3) end end
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
code
1980
using Unitful, Statistics @testset "Dipoles" begin dips = Dipole[] @testset "Create" begin dip1 = Dipole("Talairach", 1u"m", 2u"m", 1u"m", 0, 0, 0, 1, 1, 1) dip2 = Dipole("Talairach", 1u"m", 2u"m", 3u"m", 0, 0, 0, 2, 2, 2) dips = push!(dips, dip1) dips = push!(dips, dip2) @test length(dips) == 2 end @testset "Show" begin show(dips[1]) show(dips) end @testset "Mean" begin b = Neuroimaging.mean(dips) @test b.x == 1.0u"m" @test b.y == 2.0u"m" @test b.z == 2.0u"m" end @testset "Std" begin b = Neuroimaging.std(dips) @test b.x == 0.0u"m" @test b.y == 0.0u"m" @test b.z == Statistics.std([1, 3])u"m" end @testset "Best" begin dip1 = Dipole("Talairach", 1u"mm", 2u"mm", 1u"mm", 0, 0, 0, 1, 1, 1) dip2 = Dipole("Talairach", 1u"mm", 2u"mm", 3u"mm", 0, 0, 0, 2, 2, 2) dip3 = Dipole("Talairach", 3u"mm", 2u"mm", 3u"mm", 0, 0, 0, 2, 2, 2) dip4 = Dipole("Talairach", 3u"mm", 4u"mm", 3u"mm", 0, 0, 0, 2, 2, 2) dips = Dipole[] dips = push!(dips, dip1) dips = push!(dips, dip2) dips = push!(dips, dip3) dips = push!(dips, dip4) # Takes the closest dipole bd = best_dipole(dip2, dips) @test bd == dip2 # Takes a larger dipole thats further away if within specified radius dip5 = Dipole("Talairach", 1u"mm", 2.01u"mm", 3u"mm", 0, 0, 0, 2, 2, 20) dips = push!(dips, dip5) bd = best_dipole(dip2, dips) @test bd == dip5 # Reduce radius bd = best_dipole(dip2, dips, maxdist = 0.00000001) @test bd == dip2 # Or when nothing of appropriate size bd = best_dipole( Dipole("Talairach", 10u"mm", 2.01u"mm", 3u"mm", 0, 0, 0, 2, 2, 20), dips, min_dipole_size = 999, ) @test isnan(bd) end end
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
code
2150
@testset "Leadfield" begin L = 1 @testset "Create" begin L = Leadfield( rand(2000, 3, 6), vec(rand(2000, 1)), vec(rand(2000, 1)), vec(rand(2000, 1)), vec([ "Cz", "80Hz_SWN_70dB_R", "20Hz_SWN_70dB_R", "40Hz_SWN_70dB_R", "10Hz_SWN_70dB_R", "_4Hz_SWN_70dB_R", ]), ) @test size(L.L) == (2000, 3, 6) end @testset "Show" begin show(L) end @testset "Match" begin s = read_SSR(joinpath(dirname(@__FILE__), "../../data", "test_Hz19.5-testing.bdf")) L1 = match_leadfield(L, s) @test size(L1.L) == (2000, 3, 6) keep_channel!(s, ["Cz", "80Hz_SWN_70dB_R", "20Hz_SWN_70dB_R", "40Hz_SWN_70dB_R"]) L2 = match_leadfield(deepcopy(L), s) @test size(L2.L) == (2000, 3, 4) @test L2.L[:, :, 1] == L1.L[:, :, 1] @test L2.L[:, :, 2] == L1.L[:, :, 3] @test L2.L[:, :, 4] == L1.L[:, :, 6] @test L2.sensors == channelnames(s) s = merge_channels(s, "Cz", "garbage") @test_throws BoundsError match_leadfield(L, s) L = Leadfield( rand(2000, 3, 5), vec(rand(2000, 1)), vec(rand(2000, 1)), vec(rand(2000, 1)), vec(["Cz", "80Hz_SWN_70dB_R", "10Hz_SWN_70dB_R", "_4Hz_SWN_70dB_R"]), ) @test_throws ErrorException match_leadfield(L, s) end @testset "Operations" begin ldf = Leadfield( rand(5, 3, 2), collect(1:5.0), collect(1:5.0), collect(1:5.0), ["ch1", "ch2"], ) @testset "Find location" begin for n = 1:size(ldf.L, 1) @test n == find_location(ldf, Talairach(ldf.x[n], ldf.y[n], ldf.z[n])) end for n = 1:size(ldf.L, 1) @test n == find_location( ldf, Talairach(ldf.x[n] + 0.1, ldf.y[n] - 0.1, ldf.z[n]), ) end end end end
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
code
12258
@testset "Steady State Responses" begin fname = joinpath(dirname(@__FILE__), "..", "..", "data", "test_Hz19.5-testing.bdf") fname2 = joinpath(dirname(@__FILE__), "..", "..", "data", "tmp", "test_Hz19.5-copy.bdf") fname_out = joinpath(dirname(@__FILE__), "..", "..", "data", "tmp", "testwrite.bdf") cp(fname, fname2, force = true) # So doesnt use .mat file s = read_SSR(fname) @test isa(s, NeuroimagingMeasurement) @test isa(s, EEG) @test isa(s, SSR) @testset "Show" begin show(s) end @testset "Read file" begin s = read_SSR(fname2) @info samplingrate(s) @test samplingrate(s) == 8192.0 @info samplingrate(s) @test samplingrate(Int, s) == 8192 @test isa(samplingrate(s), AbstractFloat) == true @test isa(samplingrate(Int, s), Int) == true @info modulationrate(s) @test modulationrate(s) == 19.5 @test isa(modulationrate(s), AbstractFloat) == true @test isapprox(maximum(s.data[:, 2]), 54.5939; atol = 0.1) @test isapprox(minimum(s.data[:, 4]), -175.2503; atol = 0.1) s = read_SSR(fname, valid_triggers = [8]) s = read_SSR(fname, min_epoch_length = 8388) s = read_SSR(fname, max_epoch_length = 8389) s = read_SSR(fname) original_length = length(s.triggers["Index"]) s = read_SSR(fname, remove_first = 10) @test original_length - 10 == length(s.triggers["Index"]) s = read_SSR(fname, max_epochs = 12) @test length(s.triggers["Index"]) == 12 s = read_SSR(fname) s.triggers = extra_triggers(s.triggers, 1, 7, 0.7, samplingrate(s)) @test length(s.triggers["Index"]) == 56 end @testset "Channel names" begin s1 = deepcopy(s) s1 = channelnames(s1, 1, "A01") s1 = channelnames(s1, 2, "A05") s1 = channelnames(s1, 3, "A11") s1 = channelnames(s1, 4, "B03") s1 = channelnames(s1, 5, "A17") s1 = channelnames(s1, 6, "B17") @test channelnames(s1) == ["A01", "A05", "A11", "B03", "A17", "B17"] end @testset "Triggers" begin dats, evtTab, trigs, statusChan = readBDF(fname) sampRate = readBDFHeader(fname)["sampRate"][1] @test trigs == create_channel( evtTab, dats, sampRate, code = "code", index = "idx", duration = "dur", ) @test trigs == trigger_channel(read_SSR(fname, valid_triggers = collect(-1000:10000))) # Convert between events and channels dats, evtTab, trigs, statusChan = readBDF(fname) events = create_events(trigs, sampRate) channel = create_channel(events, dats, sampRate) @test size(channel) == size(trigs) @test channel == trigs end @testset "Extra Triggers" begin s = read_SSR(fname) end @testset "Extract epochs" begin s = extract_epochs(s, valid_triggers = [1, 2]) @test size(s.processing["epochs"]) == (8388, 28, 6) s = extract_epochs(s, valid_triggers = [1]) @test size(s.processing["epochs"]) == (16776, 14, 6) s = extract_epochs(s, valid_triggers = 1) @test size(s.processing["epochs"]) == (16776, 14, 6) s = extract_epochs(s) @test size(s.processing["epochs"]) == (8388, 28, 6) if VERSION >= VersionNumber(0, 4, 0) @test_throws ArgumentError extract_epochs(s, valid_triggers = -4) else @test_throws ErrorException extract_epochs(s, valid_triggers = -4) end end @testset "Epoch rejection" begin s = epoch_rejection(s) @test floor(28 * 0.95) == size(s.processing["epochs"], 2) @test_throws BoundsError epoch_rejection(s, retain_percentage = 1.1) @test_throws BoundsError epoch_rejection(s, retain_percentage = -0.1) for r = 0.1:0.1:1 s = extract_epochs(s) s = epoch_rejection(s, retain_percentage = r) @test floor(28 * r) == size(s.processing["epochs"], 2) end end @testset "Channel rejection" begin s1 = channel_rejection(deepcopy(s)) @test size(s1.processing["epochs"]) == (8388, 28, 5) data = randn(400, 10) * diagm(0 => [1, 1, 2, 1, 11, 1, 2, 100, 1, 1]) valid = channel_rejection(data, 20, 1) @test valid == [true true true true false true true false true true] end @testset "Create sweeps" begin s = extract_epochs(s) @test_throws ErrorException create_sweeps(s) for l = 4:4:24 s = extract_epochs(s) s = create_sweeps(s, epochsPerSweep = l) @test size(s.processing["sweeps"], 2) == floor(28 / l) @test size(s.processing["sweeps"], 1) == l * size(s.processing["epochs"], 1) @test size(s.processing["sweeps"], 3) == size(s.processing["epochs"], 3) end s = read_SSR(fname) s = extract_epochs(s) s = create_sweeps(s; epochsPerSweep = 4) @test size(s.processing["sweeps"]) == (33552, 7, 6) julia_result = average_epochs(s.processing["sweeps"]) filen = matopen(joinpath(dirname(@__FILE__), "..", "..", "data", "sweeps.mat")) matlab_sweeps = read(filen, "sweep") close(filen) @test size(matlab_sweeps[:, 1:6]) == size(julia_result) @test isapprox(matlab_sweeps[:, 1:6], julia_result; atol = 0.01) # why so different? end @testset "Low pass filter" begin s2 = lowpass_filter(deepcopy(s)) end @testset "High pass filter" begin s2 = highpass_filter(deepcopy(s)) end @testset "Band pass filter" begin s2 = bandpass_filter(deepcopy(s)) end @testset "Downsample" begin s2 = downsample(deepcopy(s), 1 // 4) @test size(s2.data, 1) == div(size(s.data, 1), 4) end @testset "Rereference" begin s2 = rereference(deepcopy(s), "Cz") @test size(s2.data, 1) == 237568 @test_throws ArgumentError rereference(deepcopy(s), "C5") @test_throws ArgumentError rereference(deepcopy(s), ["t3", "old"]) @test_throws ArgumentError rereference(deepcopy(s), ["Cz", "old"]) end @testset "Merge channels" begin s2 = merge_channels(deepcopy(s), "Cz", "MergedCz") s2 = merge_channels(deepcopy(s), ["Cz" "10Hz_SWN_70dB_R"], "Merged") end @testset "Concatenate" begin s2 = hcat(deepcopy(s), deepcopy(s)) @test size(s2.data, 1) == 2 * size(s.data, 1) @test size(s2.data, 2) == size(s.data, 2) keep_channel!(s2, ["Cz" "10Hz_SWN_70dB_R"]) @test_throws ArgumentError hcat(s, s2) end @testset "Remove channels" begin s = extract_epochs(s) s = create_sweeps(s, epochsPerSweep = 2) s2 = deepcopy(s) remove_channel!(s2, "Cz") @test size(s2.data, 2) == 5 @test size(s2.processing["epochs"], 3) == 5 @test size(s2.processing["epochs"], 1) == size(s.processing["epochs"], 1) @test size(s2.processing["epochs"], 2) == size(s.processing["epochs"], 2) @test size(s2.processing["sweeps"], 3) == 5 @test size(s2.processing["sweeps"], 1) == size(s.processing["sweeps"], 1) @test size(s2.processing["sweeps"], 2) == size(s.processing["sweeps"], 2) s2 = deepcopy(s) remove_channel!(s2, ["10Hz_SWN_70dB_R"]) @test size(s2.data, 2) == 5 s2 = deepcopy(s) remove_channel!(s2, [2]) @test size(s2.data, 2) == 5 @test s2.data[:, 2] == s.data[:, 3] s2 = deepcopy(s) remove_channel!(s2, 3) @test size(s2.data, 2) == 5 @test s2.data[:, 3] == s.data[:, 4] s2 = deepcopy(s) remove_channel!(s2, [2, 4]) @test size(s2.data, 2) == 4 @test s2.data[:, 2] == s.data[:, 3] @test s2.data[:, 3] == s.data[:, 5] @test size(s2.processing["epochs"], 3) == 4 @test size(s2.processing["epochs"], 1) == size(s.processing["epochs"], 1) @test size(s2.processing["epochs"], 2) == size(s.processing["epochs"], 2) @test size(s2.processing["sweeps"], 3) == 4 @test size(s2.processing["sweeps"], 1) == size(s.processing["sweeps"], 1) @test size(s2.processing["sweeps"], 2) == size(s.processing["sweeps"], 2) s2 = deepcopy(s) remove_channel!(s2, ["Cz", "10Hz_SWN_70dB_R"]) @test size(s2.data, 2) == 4 end @testset "Keep channels" begin s2 = deepcopy(s) remove_channel!(s2, [2, 4]) # Check keeping channel is same as removing channels s3 = deepcopy(s) keep_channel!(s3, [1, 3, 5, 6]) @test s3.data == s2.data @test s3.processing["sweeps"] == s2.processing["sweeps"] # Check order of removal does not matter s3 = deepcopy(s) keep_channel!(s3, [3, 5, 1, 6]) @test s3.data == s2.data @test s3.processing["sweeps"] == s2.processing["sweeps"] # Check can remove by name s3 = deepcopy(s) keep_channel!(s3, ["20Hz_SWN_70dB_R", "_4Hz_SWN_70dB_R", "Cz", "80Hz_SWN_70dB_R"]) @test s3.data == s2.data @test s3.processing["sweeps"] == s2.processing["sweeps"] # Check the order of removal does not matter s4 = deepcopy(s) keep_channel!(s4, ["_4Hz_SWN_70dB_R", "20Hz_SWN_70dB_R", "80Hz_SWN_70dB_R", "Cz"]) @test s3.data == s4.data @test s3.processing["sweeps"] == s4.processing["sweeps"] end @testset "Frequency fixing" begin @test assr_frequency(4) == 3.90625 @test assr_frequency([4, 10, 20, 40, 80]) == [3.90625, 9.765625, 19.53125, 40.0390625, 80.078125] end @testset "Write files" begin s = read_SSR(fname) s.header["subjID"] = "test" write_SSR(s, fname_out) s = read_SSR(fname, valid_triggers = collect(-1000:10000)) s.header["subjID"] = "test" write_SSR(s, fname_out) s2 = read_SSR(fname_out, valid_triggers = collect(-1000:10000)) @test s.data == s2.data @test s.triggers == s2.triggers @test s.samplingrate == s2.samplingrate @test occursin("test", s2.header["subjID"]) == true s = channelnames(s, ["B24", "B16", "A3", "B18", "A02", "B17"]) write_SSR(s, fname_out) s2 = read_SSR(fname_out) @test channelnames(s2) == ["CP2", "Cz", "AF3", "C4", "AF7", "C2"] end @testset "Ftest" begin s = read_SSR(fname) s.modulationrate = 19.5 * 1.0u"Hz" s = rereference(s, "Cz") s = extract_epochs(s) s = create_sweeps(s, epochsPerSweep = 4) snrDb, signal_phase, signal_power, noise_power, statistic = ftest(s.processing["sweeps"], 40.0391, 8192, 2.5, nothing, 2) @test isnan(snrDb[1]) == true @test isnan(statistic[1]) == true @test isapprox( snrDb[2:end], [-7.0915, -7.8101, 2.6462, -10.2675, -4.1863]; atol = 0.001, ) @test isapprox( statistic[2:end], [0.8233, 0.8480, 0.1721, 0.9105, 0.6854]; atol = 0.001, ) s = ftest(s, side_freq = 2.5, Note = "Original channels", Additional_columns = 22) @test isnan(s.processing["statistics"][!, :SNRdB][1]) == true @test isapprox( s.processing["statistics"][!, :SNRdB][2:end], [-1.2386, 0.5514, -1.5537, -2.7541, -6.7079]; atol = 0.001, ) s = ftest(s, side_freq = 1.2, Note = "SecondTest", Additional_columns = 24) @testset "Save results" begin save_results(s) file_name = string(s.file_name, ".csv") @test isfile(file_name) end end @testset "Adding triggers" begin for rate in [4, 10, 20, 40] s = read_SSR(fname) s.modulationrate = rate * 1.0u"Hz" s = add_triggers(s) s = extract_epochs(s) @test isapprox(size(s.processing["epochs"], 1) * rate / 8192, 1; atol = 0.005) end end end
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
code
2257
using Neuroimaging, Test @testset "Sensors" begin fname = joinpath(dirname(@__FILE__), "..", "..", "data", "test.sfp") s = read_sfp(fname) @testset "Read file" begin s = read_sfp(fname) @test length(s) == 3 end @testset "Show" begin show(s) show(s[1]) end @testset "Info" begin @test label(s) == ["Fp1", "Fpz", "Fp2"] @test label(s[1]) == "Fp1" @test labels(s) == ["Fp1", "Fpz", "Fp2"] @test labels(s[1]) == "Fp1" @test Neuroimaging.x(s) == [-27.747648u"m", -0.085967u"m", 27.676888u"m"] @test Neuroimaging.x(s[1]) == -27.747648u"m" @test Neuroimaging.y(s) == [98.803864u"m", 103.555275u"m", 99.133354u"m"] @test Neuroimaging.y(s[1]) == 98.803864u"m" @test Neuroimaging.z(s) == [34.338360u"m", 34.357265u"m", 34.457005u"m"] @test Neuroimaging.z(s[1]) == 34.338360u"m" end @testset "Matching" begin a, b = match_sensors(s, ["Fp1", "Fp2"]) end @testset "Leadfield matching" begin L = ones(4, 3, 5) L[:, :, 2] = L[:, :, 2] * 2 L[:, :, 3] = L[:, :, 3] * 3 L[:, :, 4] = L[:, :, 4] * 4 L[:, :, 5] = L[:, :, 5] * 5 L, idx = match_sensors(L, ["meh", "Cz", "Fp1", "Fp2", "eh"], ["Fp2", "Cz"]) @test size(L) == (4, 3, 2) @test L[:, :, 1] == ones(4, 3) * 4 @test L[:, :, 2] == ones(4, 3) * 2 @test idx == [4, 2] end @testset "Standard sets" begin @test length(EEG_64_10_20) == 64 @test length(EEG_Vanvooren_2014) == 18 @test length(EEG_Vanvooren_2014_Left) == 9 @test length(EEG_Vanvooren_2014_Right) == 9 end @testset "Optodes" begin label = "source1" coord = Talairach(68.3, -26.9, 8.3) s = Source(label, coord, Dict()) @test isa(s, Neuroimaging.Sensor) @test isa(s, Neuroimaging.Optode) @test isa(s, Neuroimaging.Source) @test !isa(s, Neuroimaging.Detector) @test !isa(s, Neuroimaging.Electrode) d = Detector(label, coord, Dict()) @test isa(d, Neuroimaging.Sensor) @test isa(d, Neuroimaging.Optode) @test isa(d, Neuroimaging.Detector) end end
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
code
6323
@testset "Volume Image" begin fname = joinpath(dirname(@__FILE__), "../../data", "test-3d.dat") t = read_VolumeImage(fname) t2 = read_VolumeImage(fname) @testset "Reading" begin t = read_VolumeImage(fname) @test isa(t, Neuroimaging.VolumeImage) == true end @testset "Create" begin # Array n = VolumeImage( t.data, t.units, t.x, t.y, t.z, t.t, t.method, t.info, t.coord_system, ) @test isa(n, Neuroimaging.VolumeImage) == true @test isequal(n.data, t.data) == true # Vector d = zeros(length(t.data)) x = zeros(length(t.data)) y = zeros(length(t.data)) z = zeros(length(t.data)) s = zeros(length(t.data)) # t is already taken i = 1 for xi = 1:length(t.x) for yi = 1:length(t.y) for zi = 1:length(t.z) for ti = 1:length(t.t) d[i] = ustrip(t.data[xi, yi, zi, ti]) x[i] = ustrip(t.x[xi]) y[i] = ustrip(t.y[yi]) z[i] = ustrip(t.z[zi]) s[i] = ustrip(t.t[ti]) i += 1 end end end end n2 = VolumeImage(d, t.units, x, y, z, s, t.method, t.info, t.coord_system) @test isa(n2, Neuroimaging.VolumeImage) == true @test isequal(n2.data, t.data) == true @test isequal(n2.x, t.x) == true @test isequal(n2.y, t.y) == true @test isequal(n2.z, t.z) == true @test isequal(n2.t, t.t) == true # 4D array da = zeros(2, 3, 4, 5) xa = [1.0, 2] ya = [1.0, 2, 3] za = [1.0, 2, 3, 4] ta = [1.0, 2, 3, 4, 5] VolumeImage(da, "s", xa, ya, za, ta, "m", Dict(), "unkonwn") end @testset "Querying" begin x, y, z = find_location(t, 0.001, 20, -6) @test x == 16 @test y == 36 @test z == 1 end @testset "Maths" begin @test isequal(t, t2) == true @test t + t == t * 2 t4 = t * 4 @test t4 / 2 == t + t @test t4 / 2 == t4 - t - t t2 = read_VolumeImage(fname) t2.units = "A/m^3" tdiv = t tdiv.data = tdiv.data .+ 0.2 tdiv = tdiv / tdiv @test minimum(tdiv.data) == 1 @test maximum(tdiv.data) == 1 end @testset "Min/Max" begin t = read_VolumeImage(fname) @test maximum(t) == 33.2692985535 @test minimum(t) == -7.5189352036 b = t * 2 @test b.data[1, 1, 1] == 2 * b.data[1, 1, 1] @test b.data[2, 2, 2] == 2 * b.data[2, 2, 2] c = Neuroimaging.mean([b, t]) @test size(c.data) == size(b.data) @test c.data[1, 1, 1] == (b.data[1, 1, 1] + t.data[1, 1, 1]) / 2 @test maximum([b, t]) == maximum(t) * 2 @test minimum([b, t]) == minimum(b) n = normalise([b, t]) @test maximum(n) <= 1.0 @test minimum(n) >= -1.0 end @testset "Dimension checks" begin t2 = deepcopy(t) t2.x = t2.x[1:3] @test_throws KeyError Neuroimaging.dimensions_equal(t, t2) t2 = deepcopy(t) t2.y = t2.y[1:3] @test_throws KeyError Neuroimaging.dimensions_equal(t, t2) t2 = deepcopy(t) t2.z = t2.z[1:3] @test_throws KeyError Neuroimaging.dimensions_equal(t, t2) # t2 = read_VolumeImage(joinpath(dirname(@__FILE__), "../../data", "test-4d.dat")) # @test_throws KeyError Neuroimaging.dimensions_equal(t, t2) end @testset "Average" begin s = Neuroimaging.mean(t) end @testset "Find dipoles" begin t = read_VolumeImage(fname) dips = find_dipoles(Neuroimaging.mean(t)) @test size(dips) == (16,) #dips = Neuroimaging.new_dipole_method(mean(t)) #@test size(dips) == (9,) # fname = joinpath(dirname(@__FILE__), "../../data", "test-4d.dat") # t2 = read_VolumeImage(fname) # dips = find_dipoles(Neuroimaging.mean(t2)) # @test size(dips) == (3,) # Test dipoles are returned in order of size @test issorted([dip.size for dip in dips], rev = true) == true end # @testset "Best Dipole" begin # dips = find_dipoles(Neuroimaging.mean(t)) # # Plots.pyplot(size=(1400, 400)) # # p = plot(t, c = :inferno) # # p = plot(p, Talairach(-0.04, 0.01, 0.02)) # bd = best_dipole(Talairach(-0.05, 0, 0.01), dips) # #p = plot(p, Talairach(-0.05, 0, 0.01), c = :red) # @test float(bd.x) ≈ -0.0525 atol = 0.001 # @test float(bd.y) ≈ -0.00378 atol = 0.001 # @test float(bd.z) ≈ 0.0168099 atol = 0.001 # # Take closest # bd = best_dipole(Talairach(-0.05, 0, 0.01), dips, maxdist = 0.0015) # @test float(bd.x) ≈ -0.0525 atol = 0.001 # @test float(bd.y) ≈ -0.00378 atol = 0.001 # @test float(bd.z) ≈ 0.0168099 atol = 0.001 # # Take only valid dipole # dists = [euclidean(Talairach(-0.05, 0, 0.01), dip) for dip=dips] # bd = best_dipole(Talairach(-0.05, 0, 0.01), dips, maxdist = 0.015) # @test float(bd.x) ≈ -0.0525 atol = 0.001 # @test float(bd.y) ≈ -0.00378 atol = 0.001 # @test float(bd.z) ≈ 0.0168099 atol = 0.001 # bd = best_dipole(Talairach(-0.05, 0, 0.01), Dipole[]) # @test isnan(bd) == true # end @testset "Show" begin show(t) show(normalise(t)) t.info["Regularisation"] = 1.2 show(t) end @testset "Plotting" begin Neuroimaging.plot(Neuroimaging.mean(t)) Neuroimaging.plot(Neuroimaging.mean(t), min_val = 0, max_val = 50) Neuroimaging.plot( Neuroimaging.mean(t), elp = joinpath(dirname(@__FILE__), "../../data", "test.elp"), ) p = Neuroimaging.plot(Neuroimaging.mean(t), threshold = 24) @testset "Overlay dipole" begin dips = find_dipoles(Neuroimaging.mean(t)) p = Neuroimaging.plot(p, dips) p = Neuroimaging.plot(p, dips[1], c = :red) end end end
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
1387
# Contributing to Neuroimaging.jl Contributions to this project are warmly welcomed. The project accepts contributions in the form of bug reports, fixes, feature requests or additions, documentation improvements (including typo corrections), etc. The best way to start contributing is by opening an issue on our GitHub page to discuss ideas for changes or enhancements, or to tell us about behavior that you think might be a bug. This project has many areas that could be improved. If you think something could be done better, then it probably can. I welcome constructive contributions. ## Contributing code If you wish to make a contribution first raise an issue. To contribute code you should submit it as a PR. Your code will then be run through the various continuous integration (CI) services. The CI checks for various issues such as spelling mistakes, code errors, documentation errors, code coverage, etc. Do not worry if the CI comes back negative the first time, we can work through any issues together. #### Requirements for code to be accepted Before any new code is accepted we will need to ensure that: * The code has unit tests * The code is documented * The code is demonstrated in an example in the documentation As above, do not worry if all these conditions are not initially met. First submit what you have and we can work through the improvements together.
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
293
# Neuroimaging.jl News ## v0.3.1 * Remove warnings * Clean test output ## v0.3.0 * Drop support for julia v0.5 * Only supports julia v0.6 ## v0.2.0 * Dropped support for julia v0.4 * Only supports julia v0.5 ## v0.1.1 * Added support for julia v0.5 * Last version to support julia v0.4
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
1086
# Neuromaging.jl [![Documentation](https://img.shields.io/badge/Documentation-Dev-blue)](https://rob-luke.github.io/Neuroimaging.jl/) [![Tests Julia 1](https://github.com/rob-luke/Neuroimaging.jl/actions/workflows/runtests.yml/badge.svg)](https://github.com/rob-luke/Neuroimaging.jl/actions/workflows/runtests.yml) [![codecov](https://codecov.io/gh/rob-luke/Neuroimaging.jl/branch/main/graph/badge.svg?token=8IY5Deklvg)](https://codecov.io/gh/rob-luke/Neuroimaging.jl) Process neuroimaging data using the [Julia](http://julialang.org/) language. ## Documentation See https://rob-luke.github.io/Neuroimaging.jl ## Contributing This package has been around since Julia v0.1! The Julia language has evolved since the early days, and there are many places in the codebase that should be bought up to date with the latest Julia standards. We are currently trying to revitalise this project, so if you have any feedback or suggestions please let us know. See [CONTRIBUTING.md](https://github.com/rob-luke/Neuroimaging.jl/blob/main/CONTRIBUTING.md) for details on how to get involved.
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
438
# Input/Output Functions are provided to read and write data in various formats. ## Readers In addition to reading EEG data the following file reading functions are available. ```@meta CurrentModule = Neuroimaging ``` ```@docs import_biosemi read_elp read_avr read_evt read_sfp read_dat read_bsa ``` ## Writers In addition to reading EEG data the following file reading functions are available. ```@docs write_avr write_dat ```
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
1020
# Low-Level Function API As well as providing convenient types for analysis. This package also provides low-level functions for dealing with data in its raw form. These low-level functions are described below. Note: Currently sorting out the docs, so its a bit of a mess. Is there an automated way to list all functions using documenter? --- ```@meta CurrentModule = Neuroimaging ``` ## Preprocessing ### Filtering ```@docs highpass_filter lowpass_filter bandpass_filter compensate_for_filter ``` ### Referencing ```@docs rereference remove_template ``` ### Epoching ```@docs epoch_rejection peak2peak extract_epochs ``` ## Channels ```@docs match_sensors channel_rejection ``` ## Triggers TODO: Make a type subsection similar to EEG and ASSR. ```@docs join_triggers validate_triggers clean_triggers ``` ## Dipoles TODO: Make a type subsection similar to EEG and ASSR. ```@docs find_dipoles find_location ``` ## Plotting ```@docs plot_single_channel_timeseries plot_multi_channel_timeseries ```
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
1470
# Neuroimaging.jl Manual A [Julia](http://julialang.org) package for processing neuroimaging data. ### Installation To install this package enter the package manager by pressing `]` at the julia prompt and enter: ```julia pkg> add Neuroimaging ``` ### Overview This package provides a framework for processing neuroimaging data. It provides tools to handle high level data structures such as EEG data types, electrode and optode sensor types, coordinate systems etc. Low-level functions are also provided for operating on Julia native data types. An overview of different data types is provided along with an example for each type and list of available functions. This is followed by a list of the low-level function APIs. !!! note "This package is in the process of being updated" This package has been around since Julia v0.1! The Julia language has evolved since the early days, and there are many places in the codebase that should be bought up to date with the latest Julia standards. General improvements are planned to this package. But before changes are made, the existing features and functions will be documented. This will help to highlight what has already been implemented, and where improvements need to be made. For a rough plan of how the package is being redeveloped see the GitHub issues and [project board](https://github.com/rob-luke/Neuroimaging.jl/projects/1). ```@meta CurrentModule = Neuroimaging ```
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
3977
# Data Types A feature of the Julia programming language is the strong type system. This package exploits that strength and defines various types for storing information about your neuroimaging data. A general hierarchy of neuroimaging types is provided. A number of types are provided to handle different types of data. Functions are provided to perform common operations on each type. For example, the function `channelnames` would return the correct information when called on a general eeg recording or steady state response data type. Users should interact with types using function, and not address the underlying fields directly. This allows the underlying data type to be improved without breaking existing code. For example, do not address `sensor.label`, you should use `label(sensor)`. Types also exist for storing metadata. For example, `electrodes` are a sub type of the `Sensor` type. And the position of the sensors may be in the `Talairach` space, which is a subtype of the `Coordinate` type. This type hierarchy may be more than two levels deep. For example, the `source` type inherits from the `optode` type which inherits from the `sensor` type. All functions that operate on the top level type will also operate on lower level types, but not all functions that operate on low level types would operate on the top level. For example, the `SSR` type supports the function `modulationrate()` but the `EEG` type does not, as not all EEG measurements were obtained with a modulated stimulus. A brief description of each type is provided below. See the following documentation sections for more details of each type, including examples and function APIs. ## Supported Data Types ```@meta CurrentModule = Neuroimaging ``` ```@docs Neuroimaging ``` ### Measurement This package provides for different neuroimaging techniques such as EEG and fNIRS. All of these types inherit from the top level abstract `NeuroimagingMeasurement` type. ```@docs NeuroimagingMeasurement ``` Within the `NeuroimagingMeasurement` type a sub type is provided for each supported imaging modality (e.g., `EEG`). Within each imaging modality, types are provided to represent the experimental paradigm used to collect the data (e.g., `SSR` or `RestingStateEEG`). Additionally a `General` type is provided for data that is collected using a paradigm not yet supported in _Neuroimaging.jl_ (e.g., `GeneralEEG`). This hierarchical structure allows for specific features to be added to analysis procedures for specific experimental designs, while inheriting generic features and function from the parent types. For example, see the [Auditory Steady State Response Example](@ref) which uses the `SSR` type which is a sub type of `EEG`. In this example, we see that any EEG function to be run on `SSR` data, such as filtering or resampling, but also allows for application specific functions such as specific frequency analysis statistical tests. !!! note "Support for more types is welcomed" If you would like to add support for a different experimental paradigm by adding a sub type then please raise an issue on the GitHub page and we can work through it together. Some additional types that would be good to support are `RestingStateEEG`, `EventRelatedPotential`, etc. ```@docs EEG GeneralEEG SSR ``` ### Sensor Support is provided for the storing of sensor information via the `Sensor` type. As with the neuroimaging type, several sub types inherit from this top level type. ```@docs Sensor ``` Support is currently provided for EEG and fNIRS sensor types. Additional types are welcomed. ```@docs Electrode Optode Source Detector ``` ### Coordinate Support is provided for the storing of coordinate information via the `Coordinate` type. ```@docs Coordinate ``` Specific coordinate systems available are. ```@docs BrainVision Talairach SPM UnknownCoordinate ``` ### Other These types need to be better documented. ```@docs VolumeImage Dipole ```
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
712
# Introduction Auditory steady state-responses (ASSRs) are neural responses to periodic auditory stimuli (Picton, 2010). When a repetitive stimulus is perceived by the listener, EEG measurements contain increased activity at the repetition or modulation frequency (fm). The frequency specific nature of the response allows for truly objective response detection. The most common use of ASSRs is to obtain frequency specific hearing thresholds, this is achieved by reducing the stimulus intensity until no response is detected (Rance et al., 1995). [Luke 2016](https://limo.libis.be/primo-explore/fulldisplay?docid=LIRIAS1777844&context=L&vid=Lirias&search_scope=Lirias&tab=default_tab&lang=en_US&fromSitemap=1)
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
6285
# Auditory Steady State Response Example This tutorial demonstrates how to analyse an EEG measurement that was acquired while the participant was listening to a modulated noise. This stimulus should evoke an Auditory Steady State Response (ASSR) that can be observed in the signal. The stimulus was modulated at 40.0391 Hz. As such, the frequency content of the signal will be examined. An increase in stimulus locked activity is expected at the modulation rate and harmonics, but not other frequencies. A standard ASSR analysis is performed. After an introduction to the data structure, a high pass filter is applied, the signal is referenced to Cz, epochs are extracted then combined in to sweeps, then finally an f-test is applied to the sweep data in the frequency domain. For further details on analysis see: * Picton, Terence W. Human auditory evoked potentials. Plural Publishing, 2010. * Luke, Robert, Astrid De Vos, and Jan Wouters. "Source analysis of auditory steady-state responses in acoustic and electric hearing." NeuroImage 147 (2017): 568-576. * Luke, Robert, et al. "Assessing temporal modulation sensitivity using electrically evoked auditory steady state responses." Hearing research 324 (2015): 37-45. !!! note "Refactoring in progress" This example demonstrates the existing capabilities of the package. General improvements are planned to this package. But before changes are made, the existing features and functions will be documented. This will help to highlight was has already been implemented, and where improvements need to be made. For a rough plan of how the package is being redeveloped see the GitHub issues and [project board](https://github.com/rob-luke/Neuroimaging.jl/projects/1). ## Read data First we read the measurement data which is stored in biosemi data format. ```@example fileread using DisplayAs # hide using Neuroimaging, DataDeps, Unitful data_path = joinpath( datadep"ExampleSSR", "Neuroimaging.jl-example-data-master", "neuroimaingSSR.bdf", ) s = read_SSR(data_path) ``` The function will extract the modulation from the function name if available. In this case the file name was not meaningful, and so we must inform the software of information that is essential to analysis, but not stored in the data. When analysing a steady state response a modulation rate is required. Which can be set according to: ```@example fileread s.modulationrate = 40.0391u"Hz" s ``` ## Preprocessing ```@example fileread s = highpass_filter(s) s = rereference(s, "Cz") remove_channel!(s, "Cz") s ``` ## Visualise processed continuous data ```@example fileread using Plots # hide plot_timeseries(s, channels="TP7") current() |> DisplayAs.PNG # hide ``` ## Epoch and combine data To emphasise the stimulus locked nature of the response and combat clock drift the signal is then cut in to epochs based on the trigger information. To increase the available frequency resolution the epochs are then concatenated in to sweeps. ```@example fileread s = extract_epochs(s) s = create_sweeps(s, epochsPerSweep = 8) ``` ## Extract Steady State Response Statistics Standard statistical tests can then be run on the data. An ftest will automatically convert the sweeps in to the frequency domain and apply the appropriate tests with sane default values. By default, it analyses the modulation frequency. The result is stored in the `statistics` processing log by default, but this can be specified by the user. ```@example fileread s = ftest(s) s.processing["statistics"] ``` ## Visualise spectrum Next we can visualise the spectral content of the signal. As the response statistics have already been computed, this will be overlaid on the plot. ```@example fileread plot_spectrum(s, 3) current() |> DisplayAs.PNG # hide ``` ## Quantify the false positive rate of statistical analysis While its interesting to observe a significant response at the modulation rate as expected, it is important to ensure that the false detection rate at other frequencies is not too high. As such we can analyse all other frequencies from 10 to 400 Hz and quantify the false detection rate. For this example file the resulting false detection rate is slightly over 5%. ```@example fileread using DataFrames, Query, Statistics s = ftest(s, freq_of_interest=[10:38; 42:400]) s.processing["statistics"][!, "Significant"] = Int.(s.processing["statistics"][!, "Statistic"] .< 0.05) s.processing["statistics"] |> @groupby(_.AnalysisType) |> @map({AnalysisType=key(_), FalseDiscoveryRate_Percentage=100*Statistics.mean(_.Significant)}) |> DataFrame ``` ## Visualise response amplitude Finally we can plot the ASSR spectrum. You can use the same convenient function as above, but here we will demonstrate how to do this using the `StatsPlot` library. This is possible because the results are stored in the format of a data frame. We will also mark with red dots the frequency components which contained a significant stimulus locked response according to the f-test. And we add a vertical line at the modulation rate. ```@example fileread using StatsPlots df = s.processing["statistics"] |> @groupby(_.AnalysisFrequency) |> @map({AnalysisFrequency=key(_), AverageAmplitude=Statistics.mean(_.SignalAmplitude), AverageStatistic=Int(Statistics.mean(_.Statistic).<0.05)}) |> @orderby_descending(_.AnalysisFrequency) |> DataFrame vline([40], ylims=(0, 0.3), colour="grey", line=:dash, lab="Modulation rate") df |> @df StatsPlots.plot!(:AnalysisFrequency, :AverageAmplitude, xlabel="Frequency (Hz)", ylabel="Amplitude (uV)", lab="", color="black") df|> @filter(_.AverageStatistic == 1) |> @df StatsPlots.scatter!(:AnalysisFrequency, :AverageAmplitude, color="red", ms=4, lab="Significant response") current() |> DisplayAs.PNG # hide ``` ## Conclusion An analysis pipeline of a steady state response measurement has been demonstrated. Importing the file and specifying the required information was described. As was preprocessing and statistical analysis. The false detection rate of the analysis was quantified. Finally, a figure was created to summarise the underlying data and demonstrate the increased stimulus locked response at the modulation rate.
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
474
# Functions In addition to the function available for processing EEG data, a number of functions are provided specifically for the processing of SSR data ## Import ```@docs read_SSR ``` ### Filtering ```@docs highpass_filter(::SSR) lowpass_filter(::SSR) bandpass_filter(::SSR) downsample(s::SSR, ratio::Rational) ``` ## Preprocessing ```@docs extract_epochs(::SSR) ``` ## Statistics ```@docs ftest(::SSR) ``` ## Plotting ```@docs plot_spectrum(::SSR, ::Int) ```
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
3481
# Coordinate Systems There are a wide variety of coordinate systems used in Neuroimaging. `Neuroimaging.jl` provides a coordinate data type, and several subtypes associated with specific systems. Conversion between coordinate systems is available. For a general overview of coordinate systems in neuroimaging see: * https://mne.tools/dev/auto_tutorials/forward/20_source_alignment.html * https://www.fieldtriptoolbox.org/faq/coordsys/ This package currently supports `SPM`, `BrainVision`, and `Talairach` coordinates and conversion. Additionally, an `Unknown` coordinate system can be used if you don't know how your locations are mapped. !!! note "Refactoring in progress" This example demonstrates the existing capabilities of the package. General improvements are planned to this package. But before changes are made, the existing features and functions will be documented. This will help to highlight was has already been implemented, and where improvements need to be made. For a rough plan of how the package is being redeveloped see the GitHub issues and [project board](https://github.com/rob-luke/Neuroimaging.jl/projects/1). ## Create a coordinate We can create a coordinate point by calling the appropriate type. Internally `Neuroimaging.jl` uses SI units, so meters for these locations. But the results are displayed in the more convenient centimeter notation. By default everything is SI units, so if you pass in a distance without specifying the unit it will be in meters. ```@example fileread using DisplayAs # hide using Neuroimaging, Unitful SPM(0.0737, -0.0260, 0.0070) ``` However, it is clearer and less prone to error if you specify the unit at construction, and let the internals handle the conversion. ```@example fileread location_1 = SPM(73.7u"mm", -26u"mm", 7u"mm") ``` Note that this position is taken from table IV from: * Lancaster, Jack L., et al. "Bias between MNI and Talairach coordinates analyzed using the ICBM‐152 brain template." Human brain mapping 28.11 (2007): 1194-1205. ## Conversion between coordinates To convert between different coordinate systems simply call the `convert` function with the first arguments as the desired coordinate system. The `show` function displays the passed type nicely with domain appropriate units. ```@example fileread show(convert(Talairach, location_1)) ``` And we can see that the resulting value is similar to what is provided in the Lancaster 2007 article. Although not exact, there is some loss in the transformations. ## Sensors Sensors contain location information stored as coordinate types. So if we load an EEG measurement... ```@example fileread using Neuroimaging, DataDeps data_path = joinpath( datadep"ExampleSSR", "Neuroimaging.jl-example-data-master", "neuroimaingSSR.bdf", ) s = read_SSR(data_path) ``` we can then query the sensors by calling... ```@example fileread sensors(s) ``` And we can see that there are 7 electrodes with standard 10-20 names. However, they do not have positions encoded by default. !!! note "Great first issue" A mapping for standard position names like 10-20 or 10-05 to coordinates would be a great improvement to the project. We can query the coordinate positions for the electrodes. For example, to obtain the x locations for all sensors in the EEG measurement use... ```@example fileread x(sensors(s)) ``` or to get all the labels use... ```@example fileread labels(sensors(s)) ```
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
929
# EEG Electroencephalography (EEG) is an electrophysiological monitoring method to record electrical activity on the scalp that has been shown to represent the macroscopic activity of the surface layer of the brain underneath. EEG measures voltage fluctuations resulting from ionic current within the neurons of the brain. Clinically, EEG refers to the recording of the brain's spontaneous electrical activity over a period of time, as recorded from multiple electrodes placed on the scalp. Diagnostic applications generally focus either on event-related potentials or on the spectral content of EEG. The former investigates potential fluctuations time locked to an event, such as 'stimulus onset' or 'button press'. The latter analyses the type of neural oscillations (popularly called "brain waves") that can be observed in EEG signals in the frequency domain. [Wikipedia](https://en.wikipedia.org/wiki/Electroencephalography)
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
4145
# Example This example demonstrates basic processing of an EEG measurement with Neuroimaging.jl`. An example file is imported, and the basic properties of the data structure are reported including sampling rate and channel information. Simple preprocessing, such as referencing and channel manipulation is demonstrated. And the data of a single channel and multiple channels is visualised. !!! note "Refactoring in progress" This example demonstrates the existing capabilities of the package. General improvements are planned to this package. But before changes are made, the existing features and functions will be documented. This will help to highlight was has already been implemented, and where improvements need to be made. For a rough plan of how the package is being redeveloped see the GitHub issues and [project board](https://github.com/rob-luke/Neuroimaging.jl/projects/1). ## Import EEG measurement in to Neuroimaging.jl for analysis The first step in this example is to import the required packages. In addition to importing the `Neuroimaging.jl` package, the `DataDeps` package is imported to facilitate access to the example dataset _ExampleSSR_ which contains an example EEG measurement in the Biosemi data format. To read the data the function `read_EEG` is used. This returns the data as a `GeneralEEG` type which stores EEG measurements that are not associated with any particular experimental paradigm. ```@example fileread using DisplayAs # hide using Neuroimaging, DataDeps data_path = joinpath( datadep"ExampleSSR", "Neuroimaging.jl-example-data-master", "neuroimaingSSR.bdf", ) s = read_EEG(data_path) ``` To view a summary of the returned data simply call the returned variable. ```@example fileread s ``` ## Probe information about the EEG measurement The summary output of the imported data only includes basic information. Several functions are provided to access more detailed aspects of the recording. To list the names of the channels in this measurement call: ```@example fileread channelnames(s) ``` Similarly to query the sample rate of the measurement. Internally `Neuroimaging.jl` makes extensive use of the `Uniful` package and stores many values with their associated units. To obtain the sampling rate in Hz as a floating point number call: ```@example fileread samplingrate(s) ``` !!! tip "Accessing data structure fields" Note that we call the function `channelnames`, and do not access properties of the type itself. This allows the use of the same functions across multiple datatypes due to the excellent dispatch system in the Julia language. Accessing the fields of data types directly is not supported in `Neuroimaging.jl` and may break at any time. If you wish to access an internal type field and a function is not provided then raise a GitHub issue. ## Basic signal processing for EEG data Once data is imported then standard preprocessing procedures can be applied. For example to rereference the data to the `Cz` channel call: ```@example fileread s = rereference(s, "Cz") ``` After which the Cz channel will not contain meaningful information any longer. So you may wish to remove it from further analysis. You can remove multiple channels by providing an array of channel names by calling: ```@example fileread remove_channel!(s, ["Cz", "TP7"]) s ``` And the resulting data structure will now have less channels as the output describes. ## Visualise continuous EEG data It is also useful to visualise the EEG data. You can view a single channel or subset of channels by passing the string or strings you wish to plot. ```@example fileread using Plots # hide plot_timeseries(s, channels="F6") current() |> DisplayAs.PNG # hide ``` Or you can plot all channels by calling `plot_timeseries` with no arguments. ```@example fileread using Plots # hide plot_timeseries(s) current() |> DisplayAs.PNG # hide ``` ## Conclusion A demonstration of how to read in EEG data was provided. A brief explanation of how to query the returned data type was discussed. Basic signal processing and plotting was demonstrated.
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
606
# Functions In addition to the function available for processing EEG data, a number of functions are provided specifically for the processing of SSR data ## Import ```@docs read_EEG ``` ## Querying data ```@docs samplingrate(::EEG) channelnames(::EEG) sensors(::EEG) ``` ## Manipulating data ```@docs hcat(::EEG, ::EEG) add_channel(::EEG, ::Vector, ::AbstractString) remove_channel!(::EEG, ::AbstractString) keep_channel!(::EEG, ::AbstractString) trim_channel(::EEG, ::Int) merge_channels ``` ## Epoching ```@docs epoch_rejection(a::EEG) ``` ## Plotting ```@docs plot_timeseries(::EEG) ```
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
1054
# Source Modelling `Neuroimaging.jl` supports opening volume image data. In this example we open a `.dat` file as is exported by the BESA software. Volume image data represents the estimated activity at each source location. The magnitude of the activity can be displayed in a figure (see below). In this example we read data from an EEG distributed source analysis procedure run in the BESA software using the CLARA approach (Jordanov T., Hoechstetter K., Berg P., Paul-Jordanov I., Scherg M. CLARA: classical LORETA analysis recursively applied. F1000Posters. 2014;5:895.). ```@example fileread using DisplayAs, Plots # hide using Neuroimaging data_path = joinpath("..", "..", "..", "test", "data", "test-3d.dat") t = read_VolumeImage(data_path) ``` ## Plotting Next we can view the volume image by calling the plot method on it. Note that each dot represents the distributed source activity at that location, in this location the estimates are in units nAm/cm^3. ```@example fileread Neuroimaging.plot(t) current() |> DisplayAs.PNG # hide ```
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "BSD-3-Clause" ]
1.1.2
658b4dd2b445c13a4fef067f98cd0f9c97a72a7c
docs
198
# Source Code All source code resides in this directory. Low level functions are split in to folders by functionality. Higher level types, that call the low level functions, exist in `types`.
Neuroimaging
https://github.com/rob-luke/Neuroimaging.jl.git
[ "MIT" ]
0.1.0
5cc7400ff141a91c7c1b0fd1ba5eea46910b09e3
code
848
push!(LOAD_PATH,"../src/") using Documenter using SmoothedSpectralAbscissa ; const SSA=SmoothedSpectralAbscissa using Plots,NamedColors using LinearAlgebra using Random DocMeta.setdocmeta!(SmoothedSpectralAbscissa, :DocTestSetup, :(using SmoothedSpectralAbscissa); recursive=true) makedocs(; modules=[SmoothedSpectralAbscissa], authors="Dylan Festa", repo="https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl/blob/{commit}{path}#{line}", sitename="SmoothedSpectralAbscissa.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://dylanfesta.github.io/SmoothedSpectralAbscissa.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/dylanfesta/SmoothedSpectralAbscissa.jl", devbranch="master", )
SmoothedSpectralAbscissa
https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl.git
[ "MIT" ]
0.1.0
5cc7400ff141a91c7c1b0fd1ba5eea46910b09e3
code
1736
# # Comparison between SSA and SA #= In this example, I compare changes in the SA and in the SSA for a matrix that varies parametrically. =# # ### Initialization using Plots,NamedColors using LinearAlgebra using Random using SmoothedSpectralAbscissa ; const SSA=SmoothedSpectralAbscissa Random.seed!(0); # the function below generates a random non-normal matrix function rand_nonnormal(n::Integer,(ud::Real)=1.01) mat = randn(n,n) ./ sqrt(n) sh = schur(mat) upd = diagm(0=>fill(1.0,n),1=>fill(ud,n-1)) return sh.vectors*upd*sh.Schur*inv(upd)*sh.vectors' end; # ### Example matrix generated parametrically n = 100 mat1 = rand_nonnormal(n,0.8) mat2 = randn(n,n) ./ sqrt(n) mat(θ) = @. θ*mat1 + (1-θ)*mat2 thetas = range(0.0,1.0;length=100); # Now we look at the spectral abscissa as a function of the parameter ## #src # ### Set ϵ for the SSA ssa_eps_vals = [0.005,0.001,0.0005]; # ### Compute and plot the SA sas = map(θ->SSA.spectral_abscissa(mat(θ)),thetas) plt=plot(thetas,sas ; color=:black, linewidth=3,lab="SA", xlabel="θ",ylabel="SA value",leg=:top) # ### Compute and plot the SSA mycols=cgrad([colorant"DarkGreen",colorant"orange"]) for ϵ in ssa_eps_vals ssas = map(θ->SSA.ssa(mat(θ),ϵ),thetas) plot!(plt,thetas,ssas ; linewidth=2.5 , lab="SSA $ϵ",palette=mycols) end plot!(plt,xlabel="θ",ylabel="SA/SSA value",leg=:top) #= This plot shows that the SSA is a smoothed version of the SA, and coverges to it as as ϵ decreases. Moreover if we reduce the SSA parametrically, we find (approximately) a good minimum for the SA, as well. =# # Literate.markdown("examples/01_show_ssa.jl","docs/src";documenter=true,repo_root_url="https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl/blob/master") #src
SmoothedSpectralAbscissa
https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl.git
[ "MIT" ]
0.1.0
5cc7400ff141a91c7c1b0fd1ba5eea46910b09e3
code
6737
# # Faster convergence for linear dynamcs #= In this example, I show how the SSA can be used as objective to guarantee convergence or faster convergence for a linear dynamical system. =# # ## Optimization of all matrix elements # ### Initialization using Plots,NamedColors using LinearAlgebra using Random using SmoothedSpectralAbscissa ; const SSA=SmoothedSpectralAbscissa Random.seed!(0); # ### Linear Dynamics #= Consider continuous linear dynamics, regulated by ```math \frac{\text{d} \mathbf{x}}{\text{d}t} = A \mathbf{x} ``` The soluton is analytic and takes the form: ```math \mathbf{x}(t) = \exp( A\,t )\;\mathbf{x}_0 ``` Where $\mathbf{x}_0$ are the initial conditions. The function below computes the dynamical evolution of the system. =# function run_linear_dyn(A::Matrix{R},x0::Vector{R},tmax::Real,dt::Real=0.01) where R ts = range(0,tmax;step=dt) ret = Matrix{R}(undef,length(x0),length(ts)) for (k,t) in enumerate(ts) ret[:,k]=exp(A.*t)*x0 end retnrm = mapslices(norm,ret;dims=1)[:] return ts,ret,retnrm end; # ### The optimization of the objective is done through Optim.jl and BFGS using Optim function objective_and_grad_simple(x::Vector{R},grad::Union{Nothing,Vector{R}}, n::Integer,ssa_eps::R,alloc::SSA.SSAAlloc) where R mat=reshape(x,(n,n)) gradmat = isnothing(grad) ? nothing : similar(mat) obj = SSA.ssa!(mat,gradmat,alloc,ssa_eps) if !isnothing(grad) for i in eachindex(gradmat) grad[i]=gradmat[i] end end return obj end; ## #src # ### Start with an unstable matrix n = 50 A = randn(n,n) ./ sqrt(n) + 0.2I x0=randn(n) times,_,dyn_norms = run_linear_dyn(A,x0,3.,0.1) plot(times,dyn_norms; leg=false,linewidth=3,color=:black,xlabel="time",ylabel="norm(x(t))") # as expected, the norm grows exponentially with time. # ### Now do the gradient-based optimization const ssa_eps=0.001 const alloc = SSA.SSAAlloc(n) const y0 = A[:]; #= The objective function to be minimized is ```math \text{obj}(A) = \text{SSA}(A) + \lambda \frac12 \left\| A - A_0 \right\|^2 ``` Where $\lambda$ sets the relative weight. We are reducing the SSA while keeping the matrix elements close to their initial value. Adding some form of regularization is **always** necessary when otpimizing. If not, the SSA would run to $-\infty$. =# function objfun!(F,G,y) λ = 50.0/length(y) # regularizer weight obj=objective_and_grad_simple(y,G,n,ssa_eps,alloc) # SSA and gradient ydiffs = y.-y0 obj += 0.5*λ*mapreduce(x->x^2,+,ydiffs) # add the regularizer if !isnothing(G) @. G += λ*ydiffs # add gradient of regularizer end return obj end; # ### Optimize and show the results opt_out = optimize(Optim.only_fg!(objfun!),A[:],BFGS(),Optim.Options(iterations=50)) y_opt=Optim.minimizer(opt_out) A_opt = reshape(y_opt,(n,n)) times,_,dyn_norms_opt = run_linear_dyn(A_opt,x0,3.,0.1) plot(times,dyn_norms_opt; leg=false,linewidth=3,color=:blue,xlabel="time",ylabel="norm(x(t)) optimized") #= The optimized matrix produces stable dynamics, as shown in the plot above. We can also take a look at the matrices before and after optimization =# heatmap(hcat(A,fill(NaN,n,10),A_opt);ratio=1,axis=nothing,ticks=nothing,border=:none, colorbar=nothing) #= The optimized version simply has negative diagonal terms. This may appear a bit trivial. In the next part, I optimize a system *excluding* the diagonal. =# # ## Optimization that excludes the diagonal #= Here I consider a matrix that is stable, but produces a large nonlinear amplification. It is generated by the function: =# function rand_nonnormal(n::Integer,(ud::Real)=1.01) mat = randn(n,n) ./ sqrt(n) @show SSA.spectral_abscissa(mat) mat = mat - (1.1*SSA.spectral_abscissa(mat))*I sh = schur(mat) upd = diagm(0=>fill(1.0,n),1=>fill(ud,n-1)) return sh.vectors*upd*sh.Schur*inv(upd)*sh.vectors' end # Let's make one and see how it looks like A = rand_nonnormal(n,1.0) x0=randn(n) times,dyn_t,dyn_norms = run_linear_dyn(A,x0,30.,0.5) plot(times,dyn_norms; leg=false,linewidth=3,color=:black,xlabel="time",ylabel="norm(x(t))") #= The norm is initally amplified, and decreases slowly. This is due to the non-normality of matrix $A$. =# # ### Objective function that excludes diagonal function objective_and_grad_nodiag(x::Vector{R},grad::Union{Nothing,Vector{R}}, n::Integer,ssa_eps::R,alloc::SSA.SSAAlloc,A0::Matrix{R}) where R mat=reshape(x,(n,n)) for i in 1:n mat[i,i]=A0[i,i] # diagonal copied from original matrix end gradmat = isnothing(grad) ? nothing : similar(mat) obj = SSA.ssa!(mat,gradmat,alloc,ssa_eps) if !isnothing(grad) for i in 1:n gradmat[i,i] = 0.0 # diagonal has zero gradient end for i in eachindex(gradmat) grad[i]=gradmat[i] # copy the gradient end end return obj end; # ### Optimizer and optimization #= The only difference from before is using `objective_and_grad_nodiag` rather than `objective_and_grad_simple` =# const ssa_eps=0.001 const alloc = SSA.SSAAlloc(n) const y0 = A[:]; function objfun!(F,G,y) λ = 1.0/length(y) # regularizer weight obj=objective_and_grad_nodiag(y,G,n,ssa_eps,alloc,A) # add the regularizer ydiffs = y.-y0 obj += 0.5*λ*mapreduce(x->x^2,+,ydiffs) if !isnothing(G) @. G += λ*ydiffs # gradient of regularizer end return obj end opt_out = optimize(Optim.only_fg!(objfun!),A[:],BFGS(),Optim.Options(iterations=50)) y_opt=Optim.minimizer(opt_out) A_opt = reshape(y_opt,(n,n)); # Now the optimized matrix looks remarkably similar to ro the original one, # as shown below. heatmap(hcat(A,fill(NaN,n,10),A_opt);ratio=1,axis=nothing,ticks=nothing,border=:none) # Here I show the differences between $A$ and $A_{\text{opt}}$. # (in case you don't believe they are different) heatmap(A-A_opt;ratio=1,axis=nothing,ticks=nothing,border=:none) # Let's compare the time evolution of the norms times,dyn_t_opt,dyn_norms_opt = run_linear_dyn(A_opt,x0,30.,0.5) plot(times,[dyn_norms dyn_norms_opt]; leg=:topright,linewidth=3,color=[:black :blue], xlabel="time",ylabel="norm(x(t))", label=["before otpimization" "after optimization"]) #= ![So much stability!](./meme1.png) =# # ## Extras #= In gradient based optimization with no automatic differentiation, it is always necessary to test the gradient of the objective function. The procedure is illustrated below. =# using Calculus function test_gradient(myobjfun,y0) grad_an = similar(y0) _ = myobjfun(1.0,grad_an,y0) # compute gradient analytically grad_num = Calculus.gradient(y->myobjfun(1.0,nothing,y),y0) # compute it numerically return (grad_an,grad_num) end _ = let do_the_test = false if do_the_test (x1,x2)=test_gradient(objfun!,randn(n^2)) scatter(x1,x2;ratio=1) plot!(identity) end end
SmoothedSpectralAbscissa
https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl.git
[ "MIT" ]
0.1.0
5cc7400ff141a91c7c1b0fd1ba5eea46910b09e3
code
5161
# # Optimiziation of an excitatory/inhibitory (E/I) recurrent network #= In this example, I optimize an RNN network with E/I units. The dynamics is expressed as follows: ```math \tau\, \frac{\text{d} \mathbf{u}}{\text{d}t} = - \mathbf{u} + W \left(\mathbf{u}\right) + \mathbf{h} ``` Where $W$ is a connection matrix with no autapses that preserves the separation between E and I units (Dale's law). There is also a sparseness parameter for $W$, to increase the difficulty (and as proof of concept). Then there is a leak term $-\mathbf{u}$ and a constant external input $\mathbf{h}$. Finally the activation function $f\left( \cdot \right)$ is a rectified-linear function. =# # ## Initialization using Plots,NamedColors using LinearAlgebra,Statistics using Random using SmoothedSpectralAbscissa ; const SSA=SmoothedSpectralAbscissa using OrdinaryDiffEq # to run the dynamics Random.seed!(0) iofunction(x::Real) = max(0.0,x) function run_rnn_dynamics(u0::Vector{R},W::Matrix{R},h::Vector{R}, tmax::R,dt::R=0.01;verbose=false) where R f = function (du,u,p,t) mul!(du,W,iofunction.(u)) @. du = du - u + h return du end prob = ODEProblem(f,u0,(0.,tmax)) solv = solve(prob,Tsit5();verbose=verbose,saveat=dt) ret_u =hcat(solv.u...) ret_norms = mapslices(norm,ret_u;dims=1)[:] return solv.t,ret_u,ret_norms end; # ## Build the starting weight matrix const sparseness = 0.5 const ne = 35 const ni = 15 const ntot = ne+ni Wmask = hcat(fill(1.,ntot,ne),fill(-1.,ntot,ni)) # 1 for E , -1 for I, 0. for no connection for i in 1:ntot,j in 1:ntot if i==j || rand()<sparseness Wmask[i,j]=0. end end heatmap(Wmask;ratio=1,color=:greys,axis=nothing,ticks=nothing,border=:none) #= The matrix `Wmask` shown above specifies the connectivy (presence of an edge, and sign) The initial matrix is defined as follows: =# W0 = 2.0 .* rand(ntot,ntot) .* Wmask; #= Even with the leaky term, the dynamics is quite unstable, due to the presence of excitatory closed loops, and not enough inhibition. =# u0 = 3.0.*randn(ntot) h = 0.1 .* rand(ntot) times,dyn_t,dyn_norms = run_rnn_dynamics(u0,W0,h,10.0,0.05) plot(times,dyn_norms; leg=false,linewidth=3,color=:black,xlabel="time",ylabel="norm(x(t))", yscale=:log10,label="before optimization") # Note that the y-scale is exponential here. The system is highly unstable. # ## Objective function that excludes diagonal using Optim #= To keep the signs of $W_{i,j}$ I make a reparametrization as follows. ```math W_{i,j} = s_j \; \exp\left(\beta_{i,j}\right) ``` I then need to propagate the gradient of the SSA. I will also inclide a 2-norm regularizer on the weights =# function objective_and_grad_constraints(x::Vector{R},grad::Union{Nothing,Vector{R}}, n::Integer,ssa_eps::R,alloc::SSA.SSAAlloc,W0::Matrix{R}) where R betas=reshape(x,(n,n)) mat = @. exp(betas) * W0 # transform, apply constraints gradmat = isnothing(grad) ? nothing : similar(mat) obj = SSA.ssa!(mat,gradmat,alloc,ssa_eps) if !isnothing(grad) gradmat .*= mat # propagate gradient for constraint for i in eachindex(gradmat) grad[i]=gradmat[i] end end return obj end; # ## Optimizer and optimization const ssa_eps=0.005 const alloc = SSA.SSAAlloc(ntot) const y0 = map(w-> w!=0. ? log(abs(w)) : 0. ,W0[:]) function objfun!(F,G,y) λ = 3.0/length(y) # regularizer calibration obj=objective_and_grad_constraints(y,G,ntot,ssa_eps,alloc,W0) # add the regularizer obj += 0.5*λ*mapreduce(x->x^2,+,y) if !isnothing(G) @. G += λ*y # gradient of regularizer end return obj end opt_out = optimize(Optim.only_fg!(objfun!),y0,BFGS(),Optim.Options(iterations=1_000)) y_opt=Optim.minimizer(opt_out) W_opt = Wmask .* exp.(reshape(y_opt,(ntot,ntot))); # convert from beta to weight # Comparison between inital matrix and the optimized verion. Note the E/I separation. heatmap(hcat(W0,fill(NaN,ntot,10),W_opt);ratio=1,axis=nothing,ticks=nothing,border=:none) # Now, as before I consider the norm... times,dyn_t_opt,dyn_norms_opt = run_rnn_dynamics(u0,W_opt,h,30.0,0.05) plot(times,dyn_norms_opt; leg=:topright,linewidth=3,color=[:blue], xlabel="time",ylabel="norm(x(t))", label="after optimization") #= STABLE ! There seems to be a large initial amplificaiton, but the activity settles to low values. =# # ## Extras #= In gradient based optimization with no automatic differentiation, it is always necessary to test the gradient of the objective function. The procedure is illustrated below. =# using Calculus function test_gradient(myobjfun,y0) grad_an = similar(y0) _ = myobjfun(1.0,grad_an,y0) # compute gradient analytically grad_num = Calculus.gradient(y->myobjfun(1.0,nothing,y),y0) # compute it numerically for (k,y) in enumerate(y0) if y == 0. grad_num[k] = 0. end end return (grad_an,grad_num) end #= To enable testing, set `do_the_test=true` It is advised to reduce the size of the system. =# (x1,x2)=test_gradient(objfun!,randn(ntot^2)) scatter(x1,x2;ratio=1) plot!(identity) # Literate.markdown("examples/03_EI.jl","docs/src";documenter=true,repo_root_url="https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl/blob/master") #src
SmoothedSpectralAbscissa
https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl.git
[ "MIT" ]
0.1.0
5cc7400ff141a91c7c1b0fd1ba5eea46910b09e3
code
9233
module SmoothedSpectralAbscissa using LinearAlgebra, Roots abstract type AbstractIOMatrices end struct IOIdentity <:AbstractIOMatrices end abstract type OptimMethod end struct OptimOrder2 end struct OptimNewton end @inline function spectral_abscissa(A::Matrix{R}) where R convert(R,maximum(real.(eigvals(A)))) end # trace of matrix product @inline function trace_of_product(A::Matrix{R},B::Matrix{R}) where R n=size(A,1) acc=zero(R) for i in 1:n, j in 1:n @inbounds acc += A[i,j]*B[j,i] end return acc end # remove value from the diagonal # equivalent to copy!(A,A-s*I) @inline function subtract_diagonal!(A::Matrix{R},s::R) where R n=size(A,1) @simd for i in 1:n @inbounds A[i,i] -= s end return nothing end """ default_eps_ssa(A::Matrix{Float64}) -> eps_ssa default value for the ``\\varepsilon`` used to compute the SSA. It scales with the matrix size, so that it takes the value 0.05 for a ``150 \\times 150`` matrix. """ default_eps_ssa(A::Matrix{<:Real}) = 0.01 * 150.0 / size(A,1) struct SSAAlloc{R,C} R::Matrix{R} R_alloc::Matrix{R} Rt::Matrix{R} Z::Matrix{R} Zt::Matrix{R} D::Matrix{R} D_alloc::Matrix{R} Dt::Matrix{R} At::Matrix{R} P::Matrix{R} Q::Matrix{R} YZt_alloc::Matrix{R} A_eigvals::Vector{C} end """ SSAAlloc(n::Integer) -> SSAAlloc Memory allocation to avoid re-allocating space for repeated SSA computations. # Arguments - `n::Integer`: the size of the matrix (or matrices) on which the SSA will be computed """ function SSAAlloc(n::Integer) return SSAAlloc( map( _ -> Matrix{Float64}(undef,n,n),1:12)... , Vector{ComplexF32}(undef,n)) end """ SSAAlloc(A::Matrix) -> SSAAlloc Memory allocation to avoid re-allocating space for repeated SSA computations. This corresponds to `SSAAlloc(size(A,1))` """ function SSAAlloc(A::Matrix{<:Real}) return SSAAlloc(size(A,1)) end """ PQ_init!(PQ::SSAAlloc,A::Matrix) -> nothing Stores some (costly) pre-computed quantities on SSAAlloc. Should be called only once before the root-finding procedure. Schur decompositions are performed here. """ function PQ_init!(PQ::SSAAlloc{R,C},A::Matrix{R}) where {R,C} At=transpose!(PQ.At,A) F = schur(A) copyto!(PQ.R,F.T) copyto!(PQ.Z,F.Z) copyto!(PQ.A_eigvals,F.values) F = schur!(At) copyto!(PQ.Rt,F.T) copyto!(PQ.Zt,F.Z) mul!(PQ.D,transpose(PQ.Z),PQ.Z,-1.0,0.0) mul!(PQ.Dt,transpose(PQ.Zt),PQ.Zt,-1.0,0.0) return nothing end @inline function spectral_abscissa(PQ::SSAAlloc{R,C}) where {R,C} return convert(R,maximum(real.(PQ.A_eigvals))) end function get_P_or_Q!(PorQ::M,s::Real,Z::M,R::M,D::M, YZt_alloc::M) where M<:Matrix{<:Real} subtract_diagonal!(R,s) Y, scale = LAPACK.trsyl!('N','T', R, R, D) mul!(YZt_alloc,Y,transpose(Z)) mul!(PorQ,Z,YZt_alloc,inv(scale),0.0) return nothing end function get_P!(s::T, PQ::SSAAlloc{T,C}) where {T,C} R=copyto!(PQ.R_alloc,PQ.R) D=copyto!(PQ.D_alloc,PQ.D) get_P_or_Q!(PQ.P,s,PQ.Z,R,D,PQ.YZt_alloc) return nothing end function get_Q!(s::T, PQ::SSAAlloc{T,C}) where {T,C} R=copyto!(PQ.R_alloc,PQ.Rt) D=copyto!(PQ.D_alloc,PQ.Dt) get_P_or_Q!(PQ.Q,s,PQ.Zt,R,D,PQ.YZt_alloc) return nothing end function ssa_simple_obj(s::R,PQ::SSAAlloc{R,C},ssa_eps::R,sa::R) where {R,C} get_P!( max(sa+eps(10.0),s) ,PQ) # SSA is not defined below SA ! return inv(tr(PQ.P)) - ssa_eps end # Find zero with Newton! function ssa_simple_obj_newton(s::R,PQ::SSAAlloc{R,C},ssa_eps::R,sa::R) where {R,C} _s = max(sa+eps(10.0),s) get_P!(_s,PQ) # SSA is not defined below SA ! get_Q!(_s,PQ) fs = tr(PQ.P) mdfs = 2.0*trace_of_product(PQ.P,PQ.Q) obj = inv(fs) - ssa_eps dobj = mdfs/(fs*fs) return (obj,obj/dobj) end """ ssa!(A,grad,PQ,ssa_eps=nothing ; io_matrices=SmoothedSpectralAbscissa.IOIdentity, optim_method=SmoothedSpectralAbscissa.OptimOrder2) -> ssa_value Computes the smoothed spectral abscissa (SSA) of matrix A and its gradient (optionally). If `ssa_eps` is not specified, the default value is set by `default_eps_ssa(A)` # Arguments - `A::Matrix{<:Real}`: A square matrix - `grad::Union{Nothing,Matrix{<:Real}}`: `nothing` skips the gradient computation. To compute the gradient, provide a matrix `grad` of the same size as A. The matrix will be rewritten in-place with entries ``\\frac{\\partial\\; \\tilde{\\alpha}_\\varepsilon(A)}{\\partial\\; A_{i,j}}`` - `alloc::SSAAlloc` : Pre-allocated matrices for iterative computations. Can be generated by `SSAAlloc(A)` - `ssa_eps::Union{Nothing,R}=nothing` The ``\\varepsilon`` parameter associated with the SSA computation. If not specified, it is set by `default_eps_ssa(A)` - `io_matrices=SmoothedSpectralAbscissa.IOIdentity` : input and output matrix. **WARNING** for now the only option is identity. - `optim_method=SmoothedSpectralAbscissa.OptimOrder2` : root finding algorithm. Two methods implemented: `OptimOrder2` and `OptimNewton`. # Returns - `ssa_value<:Real`: this is ``\\tilde{\\alpha}_\\varepsilon(A)`` """ function ssa!(A::Matrix{R},grad::Union{Nothing,Matrix{R}}, alloc::SSAAlloc{R,C}, ssa_eps::Union{Nothing,R}=nothing ; optim_method::Type=OptimOrder2, io_matrices::Type=IOIdentity) where {R,C} _ssa_eps = something(ssa_eps, default_eps_ssa(A)) return ssa!(A,grad,alloc,_ssa_eps,optim_method,io_matrices) end # Order2() to find roots function ssa!(A::Matrix{R},grad::Union{Nothing,Matrix{R}}, alloc::SSAAlloc{R,C}, ssa_eps::R , optim_method::Type{OptimOrder2}, io_matrices::Type{IOIdentity}) where {R,C} PQ_init!(alloc,A) _sa = spectral_abscissa(alloc) # _start = _sa + 0.1abs(_sa) _start = _sa + 0.5*ssa_eps objfun(s)=ssa_simple_obj(s,alloc,ssa_eps,_sa) _method = Roots.Order2() s_star::R = find_zero(objfun, _start,_method;maxevals=1_000) isnothing(grad) && return s_star # compute gradient get_P!(s_star,alloc) get_Q!(s_star,alloc) cc=inv(trace_of_product(alloc.Q,alloc.P)) mul!(grad,alloc.Q,alloc.P,cc,0.0) return s_star end # newton to find roots function ssa!(A::Matrix{R},grad::Union{Nothing,Matrix{R}}, alloc::SSAAlloc{R,C}, ssa_eps::R , optim_method::Type{OptimNewton}, io_matrices::Type{IOIdentity}) where {R,C} PQ_init!(alloc,A) _sa = spectral_abscissa(alloc) # _start = _sa + 0.1abs(_sa) _start = _sa + 0.5*ssa_eps objfun(s)=ssa_simple_obj_newton(s,alloc,ssa_eps,_sa) _method = Roots.Newton() s_star::R = find_zero(objfun, _start,_method;maxevals=1_000) isnothing(grad) && return s_star # compute gradient get_P!(s_star,alloc) get_Q!(s_star,alloc) cc=inv(trace_of_product(alloc.Q,alloc.P)) mul!(grad,alloc.Q,alloc.P,cc,0.0) return s_star end """ ssa_simple!(A,grad,PQ,ssa_eps=nothing) -> ssa deprecated ... kept for testing """ function ssa_simple!(A::Matrix{R},grad::Union{Nothing,Matrix{R}}, PQ::SSAAlloc{R,C},ssa_eps::Union{Nothing,R}=nothing) where {R,C} return ssa!(A,grad,PQ,ssa_eps) end # short versions that also allocates the memory """ ssa(A,ssa_eps=nothing) -> ssa_val Computes the smoothed spectral abscissa (SSA) of matrix A (with identity input-output weighting matrices). If `ssa_eps` is not specified, the default value is set by `default_eps_ssa(A)` # Arguments - `A::Matrix{<:Real}`: A square matrix - `ssa_eps::Union{Nothing,R}=nothing` The ``\\varepsilon`` parameter associated with the SSA computation. If not specified, it is set by `default_eps_ssa(A)` - `io_matrices=SmoothedSpectralAbscissa.IOIdentity` : input and output matrix. **WARNING** for now the only option is identity. # Returns - `ssa_val<:Real`: this is the ``\\tilde{\\alpha}_\\varepsilon(A)`` """ function ssa(A::Matrix{R},ssa_eps::Union{Nothing,R}=nothing, io_matrices::Type=IOIdentity) where R alloc=SSAAlloc(size(A,1)) _epsssa = something(ssa_eps, default_eps_ssa(A)) return ssa!(copy(A),nothing,alloc, _epsssa;io_matrices=io_matrices) end """ ssa_withgradient(A,ssa_eps) -> (ssa_val,gradient_matrix) Computes the Smoothed Spectral Abscissa (SSA) of matrix A and also its gradient with respect to each element of A. If `ssa_eps` is not specified, the default value is set by `default_eps_ssa(A)` In case you need to call the SSA iteratively (e.g. gradient-based optimization), please consider pre-allocating memory and using `ssa_simple!(...)`. # Arguments - `A::Matrix{<:Real}`: A square matrix - `ssa_eps::Union{Nothing,R}=nothing` The ``\\varepsilon`` parameter associated with the SSA computation. If not specified, it is set by `default_eps_ssa(A)` - `io_matrices=SmoothedSpectralAbscissa.IOIdentity` : input and output matrix. **WARNING** for now the only option is identity. # Returns - `ssa_val<:Real`: this is the ``\\tilde{\\alpha}_\\varepsilon(A)`` - `gradient_matrix::Matrix{<:Real}`: the gradient of the SSA w.r.t. each entry of matrix `A` """ function ssa_withgradient(A::Matrix{R},ssa_eps::Union{Nothing,R}=nothing, io_matrices::Type=IOIdentity) where R alloc=SSAAlloc(size(A,1)) gradmat=similar(A) epsssa = something(ssa_eps, default_eps_ssa(A)) _ssa = ssa!(copy(A),gradmat,alloc, epsssa;io_matrices=io_matrices) return ssa,gradmat end end # module
SmoothedSpectralAbscissa
https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl.git
[ "MIT" ]
0.1.0
5cc7400ff141a91c7c1b0fd1ba5eea46910b09e3
code
857
using Pkg Pkg.activate(joinpath(@__DIR__,"..")) using LinearAlgebra using BenchmarkTools, Test using Cthulhu using Plots ; theme(:dark) using SmoothedSpectralAbscissa ; const SSA = SmoothedSpectralAbscissa function rand_gauss(n::Integer) return randn(n,n) ./ sqrt(n) end function rand_nonnormal(n::Integer,(ud::Real)=1.01) mat = rand_gauss(n) sh = schur(mat) upd = diagm(0=>fill(1.0,n),1=>fill(ud,n-1)) return sh.vectors*upd*sh.Schur*inv(upd)*sh.vectors' end ## sizes = [25,50,75,100,125,150] ssa_times = similar(sizes,Float64) ssa_allocs = similar(ssa_times) for (k,n) in enumerate(sizes) alloc = SSA.SSAAlloc(n) A=rand_nonnormal(n,1.0) be = @benchmark SSA.ssa!($A,nothing,$alloc) ssa_times[k] = median(be.times) ssa_allocs[k] = be.allocs end ## bar(sizes,ssa_times;leg=false,yscale=:log10) @show ssa_times ./ ssa_times_old
SmoothedSpectralAbscissa
https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl.git
[ "MIT" ]
0.1.0
5cc7400ff141a91c7c1b0fd1ba5eea46910b09e3
code
3806
using SmoothedSpectralAbscissa ; const SSA=SmoothedSpectralAbscissa using LinearAlgebra, Random using Roots,Calculus using Test Random.seed!(0) """ lyap_simple!(A::AbstractMatrix) returns the naive implementation of the Lyapunov objective function and its derivative. Can be used for testing, plotting, etc """ function lyap_simple!(A::AbstractMatrix) function myf(s::Float64)::Float64 P = lyap(A - UniformScaling(s),one(A)) tr(P) end function d_myf(s::Float64)::Float64 sc,Id = UniformScaling(s), one(A) P = lyap(A - sc,Id) Q = lyap(A' - sc,Id) -2.0tr(P*Q) end myf,d_myf end """ ssa_test(A::Matrix{Float64}) This is the easiest implementation for testing and benchmarking. """ function ssa_test(A::Matrix{Float64} ; ssa_eps=nothing) myf,d_myf = lyap_simple!(A) ssa_eps = something(ssa_eps,SSA.default_eps_ssa(A)) myg(s)= 1.0 / myf(s) - ssa_eps d_myg(s) = - d_myf(s) / myf(s)^2 sa = SSA.spectral_abscissa(A) ssa_start = sa + eps(3sa) find_zero( (myg,d_myg),ssa_start, Roots.Newton()) end function f_for_gradient(vmat) n = sqrt(length(vmat)) @assert isinteger(n) n = Int64(n) mat = copy(reshape(vmat,(n,n))) return SSA.ssa(mat) end # @testset "SA and SSA" begin # check SA n = 100 mat = randn(n,n) + 7.4517I alloc = SSA.SSAAlloc(n) @test begin sa1 = maximum(real.(eigvals(mat))) SSA.PQ_init!(alloc,mat) sa2 = SSA.spectral_abscissa(alloc) sa3 = SSA.spectral_abscissa(mat) isapprox(sa1,sa2 ; rtol=1E-4) && isapprox(sa1,sa3 ; rtol=1E-4) end # now test SSA against simpler version ssa1 = ssa_test(mat) ssa2 = SSA.ssa(mat) @test isapprox(ssa1,ssa2 ; rtol=1E-4) # same , but with a different epsilon mat = randn(n,n) + 1.456I eps = 0.31313131 ssa1 = ssa_test(mat; ssa_eps=eps) ssa2 = SSA.ssa(mat,eps) @test isapprox(ssa1,ssa2 ; rtol=1E-4) end @testset "SSA Vs Lyapunov eq" begin # when the epsilon of the ssa is the inverse of the energy integral # (computed by the lyap eq) , then the SSA is zero n = 130 idm =diagm(0=>fill(1.0,n)) matd = diagm(0=>fill(-0.05,n)) fval=tr(lyap(matd,idm)) ssa=SSA.ssa!(matd,nothing,SSA.SSAAlloc(n),inv(fval)) @test isapprox(ssa,0.0;atol=1E-6) matrand=randn(n,n) ./ sqrt(n) - 1.1I fval=tr(lyap(matrand,idm)) ssa = SSA.ssa!(matrand,nothing,SSA.SSAAlloc(n),inv(fval)) @test isapprox(ssa,0.0;atol=1E-6) matrand2 = matrand + 1.234I ssa = SSA.ssa!(matrand2,nothing,SSA.SSAAlloc(n),inv(fval)) @test isapprox(ssa,1.234;atol=1E-6) end @testset "SSA Newton method" begin n = 50 matrand=randn(n,n) ./ sqrt(n) alloc=SSA.SSAAlloc(n) SSA.PQ_init!(alloc,matrand) sa_mat = SSA.spectral_abscissa(matrand) eps_ssa = SSA.default_eps_ssa(matrand) fungrad(s) = SSA.ssa_simple_obj_newton(s,alloc,eps_ssa,sa_mat)[1] stests=range(sa_mat+0.01,3sa_mat;length=100) grad_num = map(s->Calculus.gradient(fungrad,s),stests) grad_an = let vv = map(s->SSA.ssa_simple_obj_newton(s,alloc,eps_ssa,sa_mat),stests) map(v-> v[1]/v[2],vv) end @test all(isapprox.(grad_num,grad_an;atol=1E-5)) ssa = SSA.ssa_simple!(matrand,nothing,alloc) ssa_ntw = SSA.ssa!(matrand,nothing,alloc;optim_method=SSA.OptimNewton) @test isapprox(ssa,ssa_ntw;atol=1E-5) end @testset "SSA gradient" begin n = 26 mat = rand(n,n) + UniformScaling(2.222) @test begin ssa1 = ssa_test(mat) ssa2 = SSA.ssa(mat) isapprox(ssa1,ssa2 ; rtol=1E-4) end @test begin ssa,grad_an = SSA.ssa_withgradient(mat) grad_num = Calculus.gradient(f_for_gradient,mat[:]) all(isapprox.(grad_an[:],grad_num ; rtol=1E-3) ) end end
SmoothedSpectralAbscissa
https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl.git
[ "MIT" ]
0.1.0
5cc7400ff141a91c7c1b0fd1ba5eea46910b09e3
code
2644
using Pkg ; Pkg.activate(joinpath(@__DIR__,"..")) using SmoothedSpectralAbscissa ; const SSA = SmoothedSpectralAbscissa using Test using Plots using BenchmarkTools using LinearAlgebra using Random using Roots ## """ lyap_simple(A::AbstractMatrix) returns the naive implementation of the Lyapunov objective function and its derivative. Can be used for testing, plotting, etc """ function lyap_simple(A::AbstractMatrix) function myf(s::Float64)::Float64 P = lyap(A - UniformScaling(s),one(A)) tr(P) end function d_myf(s::Float64)::Float64 sc,Id = UniformScaling(s), one(A) P = lyap(A - sc,Id) Q = lyap(A' - sc,Id) -2.0tr(P*Q) end myf,d_myf end """ ssa_test(A::Matrix{Float64}) This is the easiest implementation, to make sure it is the same as in the ocaml code, and try to benchmark it already. """ function ssa_test(A::Matrix{Float64}) myf,d_myf = lyap_simple(A) ssa_eps = SSA.default_eps_ssa(A) myg(s)= 1.0 / myf(s) - ssa_eps d_myg(s) = - d_myf(s) / myf(s)^2 sa = SSA.spectral_abscissa(A) ssa_start = sa + eps(3sa) find_zero( (myg,d_myg),ssa_start, Roots.Newton()) # find_zero( myg ,ssa_start, Order1()) end ## function ssa_simple(A::AbstractMatrix, with_gradient::Bool,PQ, ssa_eps::Union{Nothing,Float64}=nothing) _ssa_eps = something(ssa_eps, SSA.default_eps_ssa(A)) SSA.PQ_init!(A,PQ) _sa = SSA.spectral_abscissa(PQ) _start = _sa + 1.05_ssa_eps g(s)=SSA._g(s,PQ,_ssa_eps,_sa) x = range(_start, 10 ; length=200) y = g.(x) (x,y) end ## # check SA n = 100 mat = randn(n,n) + UniformScaling(7.4517) Malloc = SSA.SSAAlloc(n) @test begin sa1 = maximum(real.(eigvals(mat))) SSA.PQ_init!(mat,Malloc) sa2 = SSA.spectral_abscissa(Malloc) sa3 = SSA.spectral_abscissa(mat) isapprox(sa1,sa2 ; rtol=1E-4) && isapprox(sa1,sa3 ; rtol=1E-4) end # now test SSA against simpler version ssa1 = ssa_test(mat) SSA.default_eps_ssa(mat) |> typeof ssa2 = SSA.ssa_simple(mat) @test isapprox(ssa1,ssa2 ; rtol=1E-4) # same , but with a different epsilon mat = randn(n,n) + UniformScaling(1.456) eps = 0.31313131 ssa1 = ssa_test(mat; ssa_eps=eps) ssa2 = SSA.ssa_simple(mat,eps) @test isapprox(ssa1,ssa2 ; rtol=1E-4) ## const n = 100 Alloc = SSA.SSAAlloc(n) A = randn(n,n) SSA.PQ_init!(A,Alloc) SSA.spectral_abscissa(A) SSA.spectral_abscissa(Alloc) ssa_test(A) xt,yt = ssa_simple(A,false,Alloc) plot(xt,yt ; leg = false, linewidth=3) using Cthulhu @code_warntype SSA.ssa_simple(A) descend(SSA.get_P!, Tuple{Float64,SSA.SSAAlloc{Array{Float64,2},Array{Complex{Float32},1}}})
SmoothedSpectralAbscissa
https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl.git
[ "MIT" ]
0.1.0
5cc7400ff141a91c7c1b0fd1ba5eea46910b09e3
code
1679
using Pkg Pkg.activate(joinpath(@__DIR__,"..")) using LinearAlgebra using BenchmarkTools, Test using Cthulhu using Plots ; theme(:dark) using SmoothedSpectralAbscissa ; const SSA = SmoothedSpectralAbscissa # using OrdinaryDiffEq using StochasticDiffEq ## function easydyn(mat::Matrix{R},x0::Vector{R},tmax::Real,dt::Real=0.01) where R ts = range(0,tmax;step=dt) ret = Matrix{R}(undef,length(x0),length(ts)) for (k,t) in enumerate(ts) ret[:,k]=exp(mat.*t)*x0 end retnrm = mapslices(norm,ret;dims=1)[:] return ts,ret,retnrm end function lessnormal(mat::Matrix{R},d::R) where R n=size(mat,1) sh = schur(mat) upd = diagm(0=>fill(1.0,n),1=>fill(d,n-1)) return sh.vectors*upd*sh.Schur*inv(upd)*sh.vectors' end function dyn_noise(mat::Matrix{R}, x0::Vector{R},noiselevel::Real,t_end::Real; stepsize::Real=0.05,verbose=false) where R<:Real f(du,u,p,t) = let _du = mat*u ; copy!(du,_du) ; end σ_f(du,u,p,t) = fill!(du,noiselevel) prob = SDEProblem(f,σ_f,x0,(0.,t_end)) solv = solve(prob,EM();verbose=verbose,dt=stepsize) ret_u = hcat(solv.u...) retnrm = mapslices(norm,ret_u;dims=1)[:] return solv.t,ret_u,retnrm end ## n = 15 idm =diagm(0=>fill(1.0,n)) matrand=randn(n,n) ./ sqrt(n) - 1.1I matrandln = lessnormal(matrand,1.00001) alloc=SSA.SSAAlloc(n) ## SSA.ssa!(matrand,nothing,alloc) SSA.ssa!(matrandln,nothing,alloc) ## @btime SSA.ssa!($matrand,nothing,$alloc) @btime SSA.ssa!($matrandln,nothing,$alloc) println("\n\n") @btime SSA.ssa!($matrand,nothing,$alloc;optim_method=SSA.OptimNewton) @btime SSA.ssa!($matrandln,nothing,$alloc;optim_method=SSA.OptimNewton ) ## @descend_code_warntype SSA.ssa!(matrand,nothing,alloc)
SmoothedSpectralAbscissa
https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl.git
[ "MIT" ]
0.1.0
5cc7400ff141a91c7c1b0fd1ba5eea46910b09e3
docs
1354
# SmoothedSpectralAbscissa | **Documentation** | **Build Status** | |:------------------------- |:--------------------------------------------------------------------- | | [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://dylanfesta.github.io/SmoothedSpectralAbscissa.jl/dev) | [![Build Status](https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl/workflows/CI/badge.svg)](https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl/actions) [![Coverage](https://codecov.io/gh/dylanfesta/SmoothedSpectralAbscissa.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/dylanfesta/SmoothedSpectralAbscissa.jl) | This package implements a memory-efficient algorithm to compute the smoothed spectral abscissa (SSA) of square matrices, and the associated gradient. The computation can be optimized for recursion, so that each new calculation does not reallocate memory. I implemented only the "simplified" version that does not have projections. The algorithm is described in the following paper: > The Smoothed Spectral Abscissa for Robust Stability Optimization , J Vanbiervliet et al , 2009. [DOI: 10.1137/070704034](https://doi.org/10.1137/070704034) **WORK IN PROGRESS!** [Documentation and usage](https://dylanfesta.github.io/SmoothedSpectralAbscissa.jl/dev)
SmoothedSpectralAbscissa
https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl.git
[ "MIT" ]
0.1.0
5cc7400ff141a91c7c1b0fd1ba5eea46910b09e3
docs
1981
```@meta EditURL = "https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl/blob/master/examples/01_show_ssa.jl" ``` # Comparison between SSA and SA In this example, I compare changes in the SA and in the SSA for a matrix that varies parametrically. ### Initialization ```@example 01_show_ssa using Plots,NamedColors using LinearAlgebra using Random using SmoothedSpectralAbscissa ; const SSA=SmoothedSpectralAbscissa Random.seed!(0); nothing #hide ``` the function below generates a random non-normal matrix ```@example 01_show_ssa function rand_nonnormal(n::Integer,(ud::Real)=1.01) mat = randn(n,n) ./ sqrt(n) sh = schur(mat) upd = diagm(0=>fill(1.0,n),1=>fill(ud,n-1)) return sh.vectors*upd*sh.Schur*inv(upd)*sh.vectors' end; nothing #hide ``` ### Example matrix generated parametrically ```@example 01_show_ssa n = 100 mat1 = rand_nonnormal(n,0.8) mat2 = randn(n,n) ./ sqrt(n) mat(θ) = @. θ*mat1 + (1-θ)*mat2 thetas = range(0.0,1.0;length=100); nothing #hide ``` Now we look at the spectral abscissa as a function of the parameter ### Set ϵ for the SSA ```@example 01_show_ssa ssa_eps_vals = [0.005,0.001,0.0005]; nothing #hide ``` ### Compute and plot the SA ```@example 01_show_ssa sas = map(θ->SSA.spectral_abscissa(mat(θ)),thetas) plt=plot(thetas,sas ; color=:black, linewidth=3,lab="SA", xlabel="θ",ylabel="SA value",leg=:top) ``` ### Compute and plot the SSA ```@example 01_show_ssa mycols=cgrad([colorant"DarkGreen",colorant"orange"]) for ϵ in ssa_eps_vals ssas = map(θ->SSA.ssa(mat(θ),ϵ),thetas) plot!(plt,thetas,ssas ; linewidth=2.5 , lab="SSA $ϵ",palette=mycols) end plot!(plt,xlabel="θ",ylabel="SA/SSA value",leg=:top) ``` This plot shows that the SSA is a smoothed version of the SA, and coverges to it as as ϵ decreases. Moreover if we reduce the SSA parametrically, we find (approximately) a good minimum for the SA, as well. --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
SmoothedSpectralAbscissa
https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl.git
[ "MIT" ]
0.1.0
5cc7400ff141a91c7c1b0fd1ba5eea46910b09e3
docs
7404
```@meta EditURL = "https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl/blob/master/examples/02_dynamics.jl" ``` # Faster convergence for linear dynamcs In this example, I show how the SSA can be used as objective to guarantee convergence or faster convergence for a linear dynamical system. ## Optimization of all matrix elements ### Initialization ```@example 02_dynamics using Plots,NamedColors using LinearAlgebra using Random using SmoothedSpectralAbscissa ; const SSA=SmoothedSpectralAbscissa Random.seed!(0); nothing #hide ``` ### Linear Dynamics Consider continuous linear dynamics, regulated by ```math \frac{\text{d} \mathbf{x}}{\text{d}t} = A \mathbf{x} ``` The soluton is analytic and takes the form: ```math \mathbf{x}(t) = \exp( A\,t )\;\mathbf{x}_0 ``` Where $\mathbf{x}_0$ are the initial conditions. The function below computes the dynamical evolution of the system. ```@example 02_dynamics function run_linear_dyn(A::Matrix{R},x0::Vector{R},tmax::Real,dt::Real=0.01) where R ts = range(0,tmax;step=dt) ret = Matrix{R}(undef,length(x0),length(ts)) for (k,t) in enumerate(ts) ret[:,k]=exp(A.*t)*x0 end retnrm = mapslices(norm,ret;dims=1)[:] return ts,ret,retnrm end; nothing #hide ``` ### The optimization of the objective is done through Optim.jl and BFGS ```@example 02_dynamics using Optim function objective_and_grad_simple(x::Vector{R},grad::Union{Nothing,Vector{R}}, n::Integer,ssa_eps::R,alloc::SSA.SSAAlloc) where R mat=reshape(x,(n,n)) gradmat = isnothing(grad) ? nothing : similar(mat) obj = SSA.ssa!(mat,gradmat,alloc,ssa_eps) if !isnothing(grad) for i in eachindex(gradmat) grad[i]=gradmat[i] end end return obj end; nothing #hide ``` ### Start with an unstable matrix ```@example 02_dynamics n = 50 A = randn(n,n) ./ sqrt(n) + 0.2I x0=randn(n) times,_,dyn_norms = run_linear_dyn(A,x0,3.,0.1) plot(times,dyn_norms; leg=false,linewidth=3,color=:black,xlabel="time",ylabel="norm(x(t))") ``` as expected, the norm grows exponentially with time. ### Now do the gradient-based optimization ```@example 02_dynamics const ssa_eps=0.001 const alloc = SSA.SSAAlloc(n) const y0 = A[:]; nothing #hide ``` The objective function to be minimized is ```math \text{obj}(A) = \text{SSA}(A) + \lambda \frac12 \left\| A - A_0 \right\|^2 ``` Where $\lambda$ sets the relative weight. We are reducing the SSA while keeping the matrix elements close to their initial value. Adding some form of regularization is **always** necessary when otpimizing. If not, the SSA would run to $-\infty$. ```@example 02_dynamics function objfun!(F,G,y) λ = 50.0/length(y) # regularizer weight obj=objective_and_grad_simple(y,G,n,ssa_eps,alloc) # SSA and gradient ydiffs = y.-y0 obj += 0.5*λ*mapreduce(x->x^2,+,ydiffs) # add the regularizer if !isnothing(G) @. G += λ*ydiffs # add gradient of regularizer end return obj end; nothing #hide ``` ### Optimize and show the results ```@example 02_dynamics opt_out = optimize(Optim.only_fg!(objfun!),A[:],BFGS(),Optim.Options(iterations=50)) y_opt=Optim.minimizer(opt_out) A_opt = reshape(y_opt,(n,n)) times,_,dyn_norms_opt = run_linear_dyn(A_opt,x0,3.,0.1) plot(times,dyn_norms_opt; leg=false,linewidth=3,color=:blue,xlabel="time",ylabel="norm(x(t)) optimized") ``` The optimized matrix produces stable dynamics, as shown in the plot above. We can also take a look at the matrices before and after optimization ```@example 02_dynamics heatmap(hcat(A,fill(NaN,n,10),A_opt);ratio=1,axis=nothing,ticks=nothing,border=:none, colorbar=nothing) ``` The optimized version simply has negative diagonal terms. This may appear a bit trivial. In the next part, I optimize a system *excluding* the diagonal. ## Optimization that excludes the diagonal Here I consider a matrix that is stable, but produces a large nonlinear amplification. It is generated by the function: ```@example 02_dynamics function rand_nonnormal(n::Integer,(ud::Real)=1.01) mat = randn(n,n) ./ sqrt(n) @show SSA.spectral_abscissa(mat) mat = mat - (1.1*SSA.spectral_abscissa(mat))*I sh = schur(mat) upd = diagm(0=>fill(1.0,n),1=>fill(ud,n-1)) return sh.vectors*upd*sh.Schur*inv(upd)*sh.vectors' end ``` Let's make one and see how it looks like ```@example 02_dynamics A = rand_nonnormal(n,1.0) x0=randn(n) times,dyn_t,dyn_norms = run_linear_dyn(A,x0,30.,0.5) plot(times,dyn_norms; leg=false,linewidth=3,color=:black,xlabel="time",ylabel="norm(x(t))") ``` The norm is initally amplified, and decreases slowly. This is due to the non-normality of matrix $A$. ### Objective function that excludes diagonal ```@example 02_dynamics function objective_and_grad_nodiag(x::Vector{R},grad::Union{Nothing,Vector{R}}, n::Integer,ssa_eps::R,alloc::SSA.SSAAlloc,A0::Matrix{R}) where R mat=reshape(x,(n,n)) for i in 1:n mat[i,i]=A0[i,i] # diagonal copied from original matrix end gradmat = isnothing(grad) ? nothing : similar(mat) obj = SSA.ssa!(mat,gradmat,alloc,ssa_eps) if !isnothing(grad) for i in 1:n gradmat[i,i] = 0.0 # diagonal has zero gradient end for i in eachindex(gradmat) grad[i]=gradmat[i] # copy the gradient end end return obj end; nothing #hide ``` ### Optimizer and optimization The only difference from before is using `objective_and_grad_nodiag` rather than `objective_and_grad_simple` ```@example 02_dynamics const ssa_eps=0.001 const alloc = SSA.SSAAlloc(n) const y0 = A[:]; function objfun!(F,G,y) λ = 1.0/length(y) # regularizer weight obj=objective_and_grad_nodiag(y,G,n,ssa_eps,alloc,A) # add the regularizer ydiffs = y.-y0 obj += 0.5*λ*mapreduce(x->x^2,+,ydiffs) if !isnothing(G) @. G += λ*ydiffs # gradient of regularizer end return obj end opt_out = optimize(Optim.only_fg!(objfun!),A[:],BFGS(),Optim.Options(iterations=50)) y_opt=Optim.minimizer(opt_out) A_opt = reshape(y_opt,(n,n)); nothing #hide ``` Now the optimized matrix looks remarkably similar to ro the original one, as shown below. ```@example 02_dynamics heatmap(hcat(A,fill(NaN,n,10),A_opt);ratio=1,axis=nothing,ticks=nothing,border=:none) ``` Here I show the differences between $A$ and $A_{\text{opt}}$. (in case you don't believe they are different) ```@example 02_dynamics heatmap(A-A_opt;ratio=1,axis=nothing,ticks=nothing,border=:none) ``` Let's compare the time evolution of the norms ```@example 02_dynamics times,dyn_t_opt,dyn_norms_opt = run_linear_dyn(A_opt,x0,30.,0.5) plot(times,[dyn_norms dyn_norms_opt]; leg=:topright,linewidth=3,color=[:black :blue], xlabel="time",ylabel="norm(x(t))", label=["before otpimization" "after optimization"]) ``` ![So much stability!](./meme1.png) ## Extras In gradient based optimization with no automatic differentiation, it is always necessary to test the gradient of the objective function. The procedure is illustrated below. ```@example 02_dynamics using Calculus function test_gradient(myobjfun,y0) grad_an = similar(y0) _ = myobjfun(1.0,grad_an,y0) # compute gradient analytically grad_num = Calculus.gradient(y->myobjfun(1.0,nothing,y),y0) # compute it numerically return (grad_an,grad_num) end _ = let do_the_test = false if do_the_test (x1,x2)=test_gradient(objfun!,randn(n^2)) scatter(x1,x2;ratio=1) plot!(identity) end end ``` --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
SmoothedSpectralAbscissa
https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl.git
[ "MIT" ]
0.1.0
5cc7400ff141a91c7c1b0fd1ba5eea46910b09e3
docs
5461
```@meta EditURL = "https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl/blob/master/examples/03_EI.jl" ``` # Optimiziation of an excitatory/inhibitory (E/I) recurrent network In this example, I optimize an RNN network with E/I units. The dynamics is expressed as follows: ```math \tau\, \frac{\text{d} \mathbf{u}}{\text{d}t} = - \mathbf{u} + W \left(\mathbf{u}\right) + \mathbf{h} ``` Where $W$ is a connection matrix with no autapses that preserves the separation between E and I units (Dale's law). There is also a sparseness parameter for $W$, to increase the difficulty (and as proof of concept). Then there is a leak term $-\mathbf{u}$ and a constant external input $\mathbf{h}$. Finally the activation function $f\left( \cdot \right)$ is a rectified-linear function. ## Initialization ```@example 03_EI using Plots,NamedColors using LinearAlgebra,Statistics using Random using SmoothedSpectralAbscissa ; const SSA=SmoothedSpectralAbscissa using OrdinaryDiffEq # to run the dynamics Random.seed!(0) iofunction(x::Real) = max(0.0,x) function run_rnn_dynamics(u0::Vector{R},W::Matrix{R},h::Vector{R}, tmax::R,dt::R=0.01;verbose=false) where R f = function (du,u,p,t) mul!(du,W,iofunction.(u)) @. du = du - u + h return du end prob = ODEProblem(f,u0,(0.,tmax)) solv = solve(prob,Tsit5();verbose=verbose,saveat=dt) ret_u =hcat(solv.u...) ret_norms = mapslices(norm,ret_u;dims=1)[:] return solv.t,ret_u,ret_norms end; nothing #hide ``` ## Build the starting weight matrix ```@example 03_EI const sparseness = 0.5 const ne = 35 const ni = 15 const ntot = ne+ni Wmask = hcat(fill(1.,ntot,ne),fill(-1.,ntot,ni)) # 1 for E , -1 for I, 0. for no connection for i in 1:ntot,j in 1:ntot if i==j || rand()<sparseness Wmask[i,j]=0. end end heatmap(Wmask;ratio=1,color=:greys,axis=nothing,ticks=nothing,border=:none) ``` The matrix `Wmask` shown above specifies the connectivy (presence of an edge, and sign) The initial matrix is defined as follows: ```@example 03_EI W0 = 2.0 .* rand(ntot,ntot) .* Wmask; nothing #hide ``` Even with the leaky term, the dynamics is quite unstable, due to the presence of excitatory closed loops, and not enough inhibition. ```@example 03_EI u0 = 3.0.*randn(ntot) h = 0.1 .* rand(ntot) times,dyn_t,dyn_norms = run_rnn_dynamics(u0,W0,h,10.0,0.05) plot(times,dyn_norms; leg=false,linewidth=3,color=:black,xlabel="time",ylabel="norm(x(t))", yscale=:log10,label="before optimization") ``` Note that the y-scale is exponential here. The system is highly unstable. ## Objective function that excludes diagonal ```@example 03_EI using Optim ``` To keep the signs of $W_{i,j}$ I make a reparametrization as follows. ```math W_{i,j} = s_j \; \exp\left(\beta_{i,j}\right) ``` I then need to propagate the gradient of the SSA. I will also inclide a 2-norm regularizer on the weights ```@example 03_EI function objective_and_grad_constraints(x::Vector{R},grad::Union{Nothing,Vector{R}}, n::Integer,ssa_eps::R,alloc::SSA.SSAAlloc,W0::Matrix{R}) where R betas=reshape(x,(n,n)) mat = @. exp(betas) * W0 # transform, apply constraints gradmat = isnothing(grad) ? nothing : similar(mat) obj = SSA.ssa!(mat,gradmat,alloc,ssa_eps) if !isnothing(grad) gradmat .*= mat # propagate gradient for constraint for i in eachindex(gradmat) grad[i]=gradmat[i] end end return obj end; nothing #hide ``` ## Optimizer and optimization ```@example 03_EI const ssa_eps=0.005 const alloc = SSA.SSAAlloc(ntot) const y0 = map(w-> w!=0. ? log(abs(w)) : 0. ,W0[:]) function objfun!(F,G,y) λ = 3.0/length(y) # regularizer calibration obj=objective_and_grad_constraints(y,G,ntot,ssa_eps,alloc,W0) # add the regularizer obj += 0.5*λ*mapreduce(x->x^2,+,y) if !isnothing(G) @. G += λ*y # gradient of regularizer end return obj end opt_out = optimize(Optim.only_fg!(objfun!),y0,BFGS(),Optim.Options(iterations=1_000)) y_opt=Optim.minimizer(opt_out) W_opt = Wmask .* exp.(reshape(y_opt,(ntot,ntot))); # convert from beta to weight nothing #hide ``` Comparison between inital matrix and the optimized verion. Note the E/I separation. ```@example 03_EI heatmap(hcat(W0,fill(NaN,ntot,10),W_opt);ratio=1,axis=nothing,ticks=nothing,border=:none) ``` Now, as before I consider the norm... ```@example 03_EI times,dyn_t_opt,dyn_norms_opt = run_rnn_dynamics(u0,W_opt,h,30.0,0.05) plot(times,dyn_norms_opt; leg=:topright,linewidth=3,color=[:blue], xlabel="time",ylabel="norm(x(t))", label="after optimization") ``` STABLE ! There seems to be a large initial amplificaiton, but the activity settles to low values. ## Extras In gradient based optimization with no automatic differentiation, it is always necessary to test the gradient of the objective function. The procedure is illustrated below. ```@example 03_EI using Calculus function test_gradient(myobjfun,y0) grad_an = similar(y0) _ = myobjfun(1.0,grad_an,y0) # compute gradient analytically grad_num = Calculus.gradient(y->myobjfun(1.0,nothing,y),y0) # compute it numerically for (k,y) in enumerate(y0) if y == 0. grad_num[k] = 0. end end return (grad_an,grad_num) end ``` To enable testing, set `do_the_test=true` It is advised to reduce the size of the system. ```@example 03_EI (x1,x2)=test_gradient(objfun!,randn(ntot^2)) scatter(x1,x2;ratio=1) plot!(identity) ``` --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
SmoothedSpectralAbscissa
https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl.git
[ "MIT" ]
0.1.0
5cc7400ff141a91c7c1b0fd1ba5eea46910b09e3
docs
2756
# Smoothed Spectral Abscissa (SSA) [![](https://img.shields.io/static/v1?logo=GitHub&label=.&message=SmoothedSpectralAbscissa.jl&color=blue)](https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl) This package computes the smoothed spectral abscissa (SSA) of square matrices, and the associated gradient, as described in: > The Smoothed Spectral Abscissa for Robust Stability Optimization , J Vanbiervliet et al , 2009. [DOI: 10.1137/070704034](https://doi.org/10.1137/070704034) The SSA is a smooth upper bound to the spectral abscissa of a matrix, that is, the highest real part of the eigenvalues. The current version implements only the "simplified" version of SSA, i.e. the one where input and output transformations are identity matrices. ## Definition of SSA Consider a square real matrix ``A``, that regulates a dynamical system as follows: ``\text{d} \mathbf{x}/\text{d}t = A\,\mathbf{x}``. The stability of the dynamical system can be assessed using the following quantity: ```math f(A,s) := \int_0^{\infty} \text{d}t \;\left\| \exp\left( \left(A-sI\right)t \right)\right\|^2 ``` where ``\left\| M \right\|^2 := \text{trace}\left(M \,M^\top \right)``. For a given ``\varepsilon``, the SSA can be denoted as ``\tilde{\alpha}_\varepsilon(A)``. By definition, it satisfies the following equality: ```math f(A,\tilde{\alpha}_\varepsilon(A)) = \frac{1}{\varepsilon} ``` The SSA is an upper bound to the spectral abscissa (SA) of ``A``. If matrix ``A`` is modified so that its SSA is below 0, the SA of ``A`` will also be negative, which guarantees the stability of the associated linear dynamics. ## Usage This module does not export functions in the global scope. It is therefore convenient to shorten the module name as follows: ```julia using SmoothedSpectralAbscissa ; const SSA=SmoothedSpectralAbscissa ``` It then becomes possible to use the shorter notation `SSA.foo` in place of `SmoothedSpectralAbscissa.foo`. The functions below compute the SSA (and its gradient) for a matrix ``A``. ```@docs SSA.ssa ``` ```@docs SSA.ssa_withgradient ``` ## Examples 1. [**Comparison of SA and SSA**](./01_show_ssa.md) 2. [**Stability-optimized linear systems**](./02_dynamics.md) 3. [**Optimization of excitatory/inhibitory recurrent neural network**](./03_EI.md) ## Advanced Interface When the SSA is used as optimization objective, it is convenient to use the advanced interface to avoid memory reallocation. The memory is pre-allocated in an object of type `SSA.SSAlloc`, which can then be used to call the `SSA.ssa_simple(...)` function multiple times. ```@docs SSA.SSAAlloc ``` Once the space is allocated, the SSA and its gradient can be computed by the following function. ```@docs SSA.ssa! ``` ## Index ```@index ```
SmoothedSpectralAbscissa
https://github.com/dylanfesta/SmoothedSpectralAbscissa.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
132
function check_error(error_code) error_code == RPR_SUCCESS && return return error("Error code returned: $(error_code)") end
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
2026
using Clang using Clang.Generators using RadeonProRender_jll # current version checked in is v2.2.9 include_dir = joinpath(RadeonProRender_jll.artifact_dir, "include") # LIBCLANG_HEADERS are those headers to be wrapped. headers = joinpath.(include_dir, [ "RadeonProRender_v2.h", "RadeonProRender_MaterialX.h", "RadeonProRender_GL.h" ]) # wrapper generator options options = load_options(joinpath(@__DIR__, "rpr.toml")) # add compiler flags, e.g. "-DXXXXXXXXX" args = get_default_args() push!(args, "-I$include_dir") push!(args, "-D__APPLE__") push!(args, "-DRPR_API_USE_HEADER_V2") ctx = create_context(headers, args, options) # run generator build!(ctx, BUILDSTAGE_NO_PRINTING) isline(ex) = Meta.isexpr(ex, :line) || isa(ex, LineNumberNode) striplines!(@nospecialize(expr)) = isline(expr) ? false : true function striplines!(expr::Expr) isline(expr) && return false args = filter!(striplines!, expr.args) return true end function rewrite!(e::Expr) if Meta.isexpr(e, :function) func_args = e.args[1].args last_arg = func_args[end] body = e.args[2] ccall_expr = body.args[end] type_tuple = ccall_expr.args[4] new_body = if startswith(string(last_arg), "out_") last_type_ptr = type_tuple.args[end] @assert Meta.isexpr(last_type_ptr, :curly) @assert last_type_ptr.args[1] == :Ptr last_type = last_type_ptr.args[2] pop!(func_args) # remove from input args :($(last_arg) = Ref{$(last_type)}(); check_error($(ccall_expr)); return $(last_arg)[]) elseif ccall_expr.args[3] == :rpr_status :(check_error($(ccall_expr))) else ccall_expr end e.args[2] = new_body end striplines!(e) return end function rewrite!(dag::ExprDAG) for node in get_nodes(dag) for expr in get_exprs(node) rewrite!(expr) end end end rewrite!(ctx.dag) cd(@__DIR__) build!(ctx, BUILDSTAGE_PRINTING_ONLY)
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
927
using Tar, Inflate, SHA, Downloads, CodecZlib rpr_version = v"3.1.2" url = "https://github.com/JuliaGraphics/RadeonProRender.jl/releases/download/binaries-v$(rpr_version)/hipbin.tar.gz" # TODO use in a tempdir? Also, fetch specific commit kernel_folder = joinpath(@__DIR__, "..", "..", "RadeonProRenderSDKKernels") |> normpath exclude(path) = any(x -> endswith(path, x), [".git", ".gitattributes", "README.md"]) io = IOBuffer() Tar.create(!exclude, kernel_folder, io) bin = take!(io) compressed = transcode(GzipCompressor, bin) filename = joinpath(@__DIR__, "hipbin.tar.gz") write(filename, compressed) sha = bytes2hex(open(sha256, filename)) git_tree_sha1 = Tar.tree_hash(IOBuffer(bin)) Inflate.inflate_gzip(filename) artifact = """ [hipbin] git-tree-sha1 = $(repr(git_tree_sha1)) [[hipbin.download]] url = $(repr(url)) sha256 = $(repr(sha)) """ write(joinpath(@__DIR__, "..", "Artifacts.toml"), artifact)
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
630
using RadeonProRender using Documenter DocMeta.setdocmeta!(RadeonProRender, :DocTestSetup, :(using RadeonProRender); recursive=true) makedocs(; modules=[RadeonProRender], authors="Simon Danisch", repo="https://github.com/SimonDanisch/RadeonProRender.jl/blob/{commit}{path}#{line}", sitename="RadeonProRender.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://SimonDanisch.github.io/RadeonProRender.jl", assets=String[]), pages=["Home" => "index.md"]) deploydocs(; repo="github.com/SimonDanisch/RadeonProRender.jl")
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
3118
using RadeonProRender, GeometryBasics, Colors const RPR = RadeonProRender using Colors: N0f8 # Create a scene context = RPR.Context() scene = RPR.Scene(context) matsys = RPR.MaterialSystem(context, 0) camera = RPR.Camera(context) lookat!(camera, Vec3f(3), Vec3f(0), Vec3f(0, 0, 1)) set!(scene, camera) # create some x,y,z data function create_mesh(DN = 512, dphi=pi/200.0f0, dtheta=dphi) phi = 0.0f0:dphi:(pi + dphi * 1.5f0) theta = (0.0f0:dtheta:(2.0f0 * pi + dtheta * 1.5f0))' m0 = 4.0f0; m1 = 3.0f0; m2 = 2.0f0; m3 = 3.0f0; m4 = 6.0f0; m5 = 2.0f0; m6 = 6.0f0; m7 = 4.0f0; a = @. sin(m0 * phi) ^ m1 b = @. cos(m2 * phi) ^ m3 c = @. sin(m4 * theta) ^ m5 d = @. cos(m6 * theta) ^ m7 r = @. a + b + c + d; x = @. r * sin(phi) * cos(theta) y = @. r * cos(phi) z = @. r * sin(phi) * sin(theta) xyz = Point3f[Point3f(x[i, j], y[i, j], z[i, j]) for i in 1:size(x, 1), j in 1:size(x, 2)] r = Tesselation(Rect2f((0, 0), (1, 1)), size(x)) # decomposing a rectangle into uv and triangles is what we need to map the z coordinates on # since the xyz data assumes the coordinates to have the same neighouring relations # like a grid faces = decompose(GLTriangleFace, r) uv = decompose_uv(r) # with this we can beuild a mesh return GeometryBasics.Mesh(meta(vec(xyz), uv=uv), faces), xyz end raw_mesh, xyz = create_mesh() surfacemesh = RPR.Shape(context, raw_mesh) push!(scene, surfacemesh) # create layered material tex = RPR.MaterialNode(matsys, RPR.RPR_MATERIAL_NODE_IMAGE_TEXTURE) base = RPR.MaterialNode(matsys, RPR.RPR_MATERIAL_NODE_DIFFUSE) top = RPR.MaterialNode(matsys, RPR.RPR_MATERIAL_NODE_REFLECTION) # Diffuse color set!(base, RPR.RPR_MATERIAL_INPUT_COLOR, tex); set!(base, RPR.RPR_MATERIAL_INPUT_ROUGHNESS, 0.12, 0.0, 0.0, 1.0) set!(top, RPR.RPR_MATERIAL_INPUT_COLOR, 0.1, 0.3, 0.9, 1.0) # Create layered shader layered = RPR.layeredshader(matsys, base, top) colorim = map(xyz) do xyz return RGBA{N0f8}(clamp(abs(xyz[1]), 0, 1), clamp(abs(xyz[2]), 0, 1), clamp(abs(xyz[3]), 0, 1), 1.0) end color = RPR.Image(context, colorim) set!(tex, RPR.RPR_MATERIAL_INPUT_DATA, color) set!(surfacemesh, layered) set!(context, scene) ibl = RPR.EnvironmentLight(context) image_path = joinpath(@__DIR__, "studio026.exr") set!(ibl, context, image_path) set!(scene, ibl) set_standard_tonemapping!(context) fb_size = (800, 600) frame_buffer = RPR.FrameBuffer(context, RGBA, fb_size) frame_bufferSolved = RPR.FrameBuffer(context, RGBA, fb_size) frame_buffer_post = RPR.FrameBuffer(context, RGBA, fb_size) set!(context, RPR.RPR_AOV_COLOR, frame_buffer) begin clear!(frame_buffer) clear!(frame_buffer_post) RPR.rprContextSetParameterByKey1u(context, RPR.RPR_CONTEXT_ITERATIONS, 100) RPR.render(context) RPR.rprContextResolveFrameBuffer(context, frame_buffer, frame_bufferSolved, true) RPR.save(frame_bufferSolved, "surface_mesh.png") RPR.rprContextResolveFrameBuffer(context, frame_buffer, frame_buffer_post, false) RPR.save(frame_buffer_post, "surface_mesh_postprocess.png") end
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
4677
using RadeonProRender, GeometryBasics, Colors const RPR = RadeonProRender function translationmatrix(t::Vec{3,T}) where {T} T0, T1 = zero(T), one(T) return Mat{4}(T1, T0, T0, T0, T0, T1, T0, T0, T0, T0, T1, T0, t[1], t[2], t[3], T1) end context = RPR.Context() scene = RPR.Scene(context) matsys = RPR.MaterialSystem(context, 0) camera = RPR.Camera(context) lookat!(camera, Vec3f(8, 0, 5), Vec3f(2, 0, 2), Vec3f(0, 0, 1)) RPR.rprCameraSetFocalLength(camera, 45.0) set!(scene, camera) set!(context, scene) env_light = RadeonProRender.EnvironmentLight(context) image_path = RPR.assetpath("studio026.exr") img = RPR.Image(context, image_path) set!(env_light, img) setintensityscale!(env_light, 1.1) push!(scene, env_light) light = RPR.PointLight(context) transform!(light, translationmatrix(Vec3f(2, 0, 5))) f = 16 RPR.setradiantpower!(light, 700 / f, 641 / f, 630 / f) push!(scene, light) function add_shape!(scene, context, matsys, mesh; material=RPR.RPR_MATERIAL_NODE_DIFFUSE, color=colorant"green", roughness=0.01) rpr_mesh = RPR.Shape(context, mesh) push!(scene, rpr_mesh) m = RPR.MaterialNode(matsys, material) set!(m, RPR.RPR_MATERIAL_INPUT_COLOR, color) set!(m, RPR.RPR_MATERIAL_INPUT_ROUGHNESS, roughness, roughness, roughness, roughness) set!(rpr_mesh, m) return rpr_mesh, m end mesh, mat = add_shape!(scene, context, matsys, Rect3f(Vec3f(-10, -10, -1), Vec3f(20, 20, 1)); color=colorant"white") mesh, mat = add_shape!(scene, context, matsys, Rect3f(Vec3f(0, -10, 0), Vec3f(0.1, 20, 5)); color=colorant"white") mesh, mat = add_shape!(scene, context, matsys, Rect3f(Vec3f(0, -2, 0), Vec3f(5, 0.1, 5)); color=colorant"white") mesh, mat = add_shape!(scene, context, matsys, Rect3f(Vec3f(0, 2, 0), Vec3f(5, 0.1, 5)); color=colorant"white") mesh, mat = add_shape!(scene, context, matsys, Tesselation(Sphere(Point3f(2, 0, 2), 0.95f0), 100); color=colorant"white") rpr_mesh = RPR.Shape(context, Tesselation(Sphere(Point3f(2, 0, 2), 1.0f0), 100)) push!(scene, rpr_mesh) material = RPR.MaterialNode(matsys, RPR.RPR_MATERIAL_NODE_UBERV2) # set!(material, RPR.RPR_MATERIAL_INPUT_UBER_DIFFUSE_COLOR, 0.358878, 0.497024 , 1.07771, 1.0) # set!(material, RPR.RPR_MATERIAL_INPUT_UBER_DIFFUSE_WEIGHT, Vec4f(0.0)...) # set!(material, RPR.RPR_MATERIAL_INPUT_UBER_DIFFUSE_ROUGHNESS, Vec4f(0.1)...) # set!(material, RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_COLOR, 0.01f0, 0.01f0, 0.01f0, 0.01f0) # set!(material, RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_WEIGHT, Vec4f(0.01)...) # set!(material, RPR.RPR_MATERIAL_INPUT_UBER_TRANSPARENCY, Vec4f(0.99)...) set!(material, RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_COLOR, Vec4f(0.358878, 0.497024 , 1.07771, 1.0)...) set!(material, RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_WEIGHT, Vec4f(0.8)...) set!(material, RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_ROUGHNESS, Vec4f(0.01)...) set!(material, RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_IOR, Vec4f(1.0)...) set!(material, RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_ABSORPTION_COLOR, Vec4f(0.7, 0.6, 0.09, 1.0)...) set!(material, RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_ABSORPTION_DISTANCE, Vec4f(3.0)...) set!(material, RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_CAUSTICS, Vec4f(0.0)...) # set!(material, RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_ROUGHNESS, 0.1f0, 0f0, 0f0, 0f0) # set!(material, RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_MODE, Int(RPR.RPR_UBER_MATERIAL_IOR_MODE_PBR)) # set!(material, RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_METALNESS, 0.f0, 0f0, 0f0, 0f0) set!(material, RPR.RPR_MATERIAL_INPUT_UBER_SSS_SCATTER_COLOR, 0.358878, 0.497024 , 1.07771, 1.0) set!(material, RPR.RPR_MATERIAL_INPUT_UBER_SSS_SCATTER_DISTANCE, Vec4f(3)...) set!(material, RPR.RPR_MATERIAL_INPUT_UBER_SSS_SCATTER_DIRECTION, Vec4f(0)...) set!(material, RPR.RPR_MATERIAL_INPUT_UBER_SSS_WEIGHT, Vec4f(1)...) set!(material, RPR.RPR_MATERIAL_INPUT_UBER_SSS_MULTISCATTER, 1) # set!(material, RPR.RPR_MATERIAL_INPUT_UBER_BACKSCATTER_WEIGHT, Vec4f(1.0)...) # set!(material, RPR.RPR_MATERIAL_INPUT_UBER_BACKSCATTER_COLOR, 0.4, 0.4, 0.5, 0.1) set!(rpr_mesh, material) fb_size = (800, 600) frame_buffer = RPR.FrameBuffer(context, RGBA, fb_size) frame_bufferSolved = RPR.FrameBuffer(context, RGBA, fb_size) set!(context, RPR.RPR_AOV_COLOR, frame_buffer) set_standard_tonemapping!(context) begin clear!(frame_buffer) RPR.rprContextSetParameterByKey1u(context, RPR.RPR_CONTEXT_ITERATIONS, 200) RPR.render(context) RPR.rprContextResolveFrameBuffer(context, frame_buffer, frame_bufferSolved, false) RPR.save(frame_bufferSolved, "test.png") end
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
2622
using RadeonProRender, GeometryBasics, Colors const RPR = RadeonProRender function translationmatrix(t::Vec{3,T}) where {T} T0, T1 = zero(T), one(T) return Mat{4}(T1, T0, T0, T0, T0, T1, T0, T0, T0, T0, T1, T0, t[1], t[2], t[3], T1) end context = RPR.Context() scene = RPR.Scene(context) matsys = RPR.MaterialSystem(context, 0) camera = RPR.Camera(context) lookat!(camera, Vec3f(8, 0, 5), Vec3f(2, 0, 2), Vec3f(0, 0, 1)) RPR.rprCameraSetFocalLength(camera, 45.0) set!(scene, camera) set!(context, scene) env_light = RadeonProRender.EnvironmentLight(context) image_path = joinpath(@__DIR__, "studio026.exr") img = RPR.Image(context, image_path) set!(env_light, img) setintensityscale!(env_light, 1.1) push!(scene, env_light) light = RPR.PointLight(context) transform!(light, translationmatrix(Vec3f(2, 0, 5))) f = 20 RPR.setradiantpower!(light, 500 / f, 641 / f, 630 / f) push!(scene, light) function add_shape!(scene, context, matsys, mesh; material=RPR.RPR_MATERIAL_NODE_DIFFUSE, color=colorant"green", roughness=0.01) rpr_mesh = RadeonProRender.Shape(context, mesh) push!(scene, rpr_mesh) m = RPR.MaterialNode(matsys, material) set!(m, RPR.RPR_MATERIAL_INPUT_COLOR, color) set!(m, RPR.RPR_MATERIAL_INPUT_ROUGHNESS, roughness, roughness, roughness, roughness) set!(rpr_mesh, m) return rpr_mesh, m end mesh, mat = add_shape!(scene, context, matsys, Rect3f(Vec3f(-10, -10, -1), Vec3f(20, 20, 1)); color=colorant"white") mesh, mat = add_shape!(scene, context, matsys, Rect3f(Vec3f(0, -10, 0), Vec3f(0.1, 20, 5)); color=colorant"white") mesh, mat = add_shape!(scene, context, matsys, Rect3f(Vec3f(0, -2, 0), Vec3f(5, 0.1, 5)); color=colorant"white") mesh, mat = add_shape!(scene, context, matsys, Rect3f(Vec3f(0, 2, 0), Vec3f(5, 0.1, 5)); color=colorant"white") mesh, mat_sphere = add_shape!(scene, context, matsys, Tesselation(Sphere(Point3f(2, 0, 2), 1.0f0), 100); material=RPR.RPR_MATERIAL_NODE_MICROFACET, roughness=0.2, color=colorant"red") fb_size = (800, 600) frame_buffer = RPR.FrameBuffer(context, RGBA, fb_size) frame_bufferSolved = RPR.FrameBuffer(context, RGBA, fb_size) set!(context, RPR.RPR_AOV_COLOR, frame_buffer) set_standard_tonemapping!(context) begin clear!(frame_buffer) RPR.rprContextSetParameterByKey1u(context, RPR.RPR_CONTEXT_ITERATIONS, 100) RPR.render(context) RPR.rprContextResolveFrameBuffer(context, frame_buffer, frame_bufferSolved, false) RPR.save(frame_bufferSolved, "test.png") end
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
2850
using RadeonProRender, GeometryBasics, Colors const RPR = RadeonProRender function translationmatrix(t::Vec{3,T}) where {T} T0, T1 = zero(T), one(T) return Mat{4}(T1, T0, T0, T0, T0, T1, T0, T0, T0, T0, T1, T0, t[1], t[2], t[3], T1) end isdefined(Main, :context) && RPR.release(context) context = RPR.Context() scene = RPR.Scene(context) matsys = RPR.MaterialSystem(context, 0) camera = RPR.Camera(context) lookat!(camera, Vec3f(7, 0, 5), Vec3f(2, 0, 2), Vec3f(0, 0, 1)) RPR.rprCameraSetFocalLength(camera, 45.0) set!(scene, camera) set!(context, scene) env_light = RadeonProRender.EnvironmentLight(context) image_path = joinpath(@__DIR__, "studio026.exr") img = RPR.Image(context, image_path) set!(env_light, img) setintensityscale!(env_light, 1.1) push!(scene, env_light) light = RPR.PointLight(context) transform!(light, translationmatrix(Vec3f(2, 0, 5))) f = 20 RPR.setradiantpower!(light, 500 / f, 641 / f, 630 / f) push!(scene, light) function add_shape!(scene, context, matsys, mesh; material=RPR.RPR_MATERIAL_NODE_DIFFUSE, color=colorant"green", roughness=0.01) rpr_mesh = RadeonProRender.Shape(context, mesh) push!(scene, rpr_mesh) m = RPR.MaterialNode(matsys, material) set!(m, RPR.RPR_MATERIAL_INPUT_COLOR, color) set!(m, RPR.RPR_MATERIAL_INPUT_ROUGHNESS, roughness, roughness, roughness, roughness) set!(rpr_mesh, m) return rpr_mesh, m end mesh, mat = add_shape!(scene, context, matsys, Rect3f(Vec3f(-50, -50, -1), Vec3f(50*2, 50*2, 1)); color=colorant"white") x, y = collect(-8:0.5:8), collect(-8:0.5:8) z = [sinc(√(X^2 + Y^2) / π) for X ∈ x, Y ∈ y] M, N = size(z) points = map(x-> x ./ Point3f(4, 4, 1.0) .+ Point3f(0, 0, 1.0), vec(Point3f.(x, y', z))) # Connect the vetices with faces, as one would use for a 2D Rectangle # grid with M,N grid points faces = decompose(LineFace{GLIndex}, Tesselation(Rect2(0, 0, 1, 1), (M, N))) indices = RPR.rpr_int[] for elem in faces push!(indices, first(elem)-1, first(elem)-1, last(elem)-1, last(elem)-1) end curve = RPR.Curve(context, points, indices, [0.01], [Vec2f(0.1)], [length(faces)]) m = RPR.MaterialNode(matsys, RPR.RPR_MATERIAL_NODE_DIFFUSE) set!(m, RPR.RPR_MATERIAL_INPUT_COLOR, colorant"red") set!(m, RPR.RPR_MATERIAL_INPUT_ROUGHNESS, 0.0, 0.0, 0.0, 0.0) set!(curve, m) push!(scene, curve) fb_size = (800, 600) frame_buffer = RPR.FrameBuffer(context, RGBA, fb_size) frame_bufferSolved = RPR.FrameBuffer(context, RGBA, fb_size) set!(context, RPR.RPR_AOV_COLOR, frame_buffer) set_standard_tonemapping!(context) begin clear!(frame_buffer) RPR.rprContextSetParameterByKey1u(context, RPR.RPR_CONTEXT_ITERATIONS, 200) @time RPR.render(context) RPR.rprContextResolveFrameBuffer(context, frame_buffer, frame_bufferSolved, false) RPR.save(frame_bufferSolved, "curves.png") end
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
3544
using RadeonProRender, MeshIO, FileIO, GeometryBasics, Colors using Makie using Colors: N0f8 const RPR = RadeonProRender loadasset(paths...) = FileIO.load(joinpath(dirname(pathof(Makie)), "..", "assets", paths...)) function trans_matrix(scale::Vec3, rotation::Vec3) trans_scale = Makie.transformationmatrix(Vec3f(0), scale) rotation = Mat4f(to_rotation(rotation)) return trans_scale * rotation end # Create a scene context = RPR.Context() matsys = RPR.MaterialSystem(context, 0) scene = RPR.Scene(context) set!(context, scene) set_standard_tonemapping!(context) camera = RPR.Camera(context) lookat!(camera, Vec3f(1.5), Vec3f(0), Vec3f(0, 0, 1)) RPR.rprCameraSetFocalLength(camera, 45.0) set!(scene, camera) env_light = RadeonProRender.EnvironmentLight(context) image_path = joinpath(@__DIR__, "studio026.exr") img = RPR.Image(context, image_path) set!(env_light, img) setintensityscale!(env_light, 1.5) push!(scene, env_light) light = RPR.PointLight(context) transform!(light, Makie.translationmatrix(Vec3f(2, 2, 4))) RPR.setradiantpower!(light, 500, 641, 800) push!(scene, light) """ Generate scales for instances """ function update_scales!(last_scales, t) n = length(last_scales) for i in 1:n last_scales[i] = Vec3f(1, 1, sin((t * n) / i)) ./ 3.1 end return last_scales end """ Generate color for instances """ function update_colors!(last_colors, t) l = length(last_colors) for i in eachindex(last_colors) last_colors[i] = RGBA{N0f8}(i / l, (cos(t) + 1) / 2, (sin(i / l / 3) + 1) / 2.0, 1.0) end return last_colors end # create some geometry t = 2.0f0 * pi cat = loadasset("cat.obj") sphere = Sphere(Point3f(0), 1.0f0) position = decompose(Point3f, sphere) # use sphere vertices as position scale_start = Vec3f[Vec3f(1, 1, rand()) for i in 1:length(position)] # create a signal of changing colors color = update_colors!(zeros(RGBA{N0f8}, length(position)), t) # use sphere normals as rotation vector rotations = -decompose_normals(sphere) # create material system diffuse = RPR.MaterialNode(matsys, RPR.RPR_MATERIAL_NODE_DIFFUSE) # create firerender shape primitive = RPR.Shape(context, cat) # pre allocate instances fr_instances = [RPR.Shape(context, primitive) for i in 1:(length(position) - 1)] push!(fr_instances, primitive) # pre allocate shaders fr_shader = [RPR.MaterialNode(matsys, RPR.RPR_MATERIAL_NODE_REFLECTION) for elem in 1:length(position)] # set shaders and attach instances to scene for (shader, inst) in zip(fr_shader, fr_instances) set!(inst, shader) push!(scene, inst) end # update scene with the instance signal fb_size = (800, 600) frame_buffer = RPR.FrameBuffer(context, RGBA, fb_size) frame_bufferSolved = RPR.FrameBuffer(context, RGBA, fb_size) set!(context, RPR.RPR_AOV_COLOR, frame_buffer) function render_scene(path, n=5) clear!(frame_buffer) RPR.rprContextSetParameterByKey1u(context, RPR.RPR_CONTEXT_ITERATIONS, n) RPR.render(context) RPR.rprContextResolveFrameBuffer(context, frame_buffer, frame_bufferSolved, false) RPR.save(frame_bufferSolved, path) end for (i, t) in enumerate(LinRange(0, 3.0, 1000)) color = update_colors!(color, t) scale_start = update_scales!(scale_start, t) for (scale, rotation, c, inst, shader) in zip(scale_start, rotations, color, fr_instances, fr_shader) transform!(inst, trans_matrix(scale, rotation)) set!(shader, RPR.RPR_MATERIAL_INPUT_COLOR, c) end path = joinpath(@__DIR__, "instances", "frame$i.png") render_scene(path, 100) end
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
2020
using RadeonProRender, GeometryTypes, GLAbstraction, GLVisualize, Colors, ModernGL, FileIO, Reactive const FR = RadeonProRender w = glscreen() # create interactive context, which uses gl interop to display render result # with opengl context, glframebuffer = interactive_context(w) scene = FR.Scene(context) set!(context, scene) # create a RadeonProRender.Camera from a GLAbstraction.Camera camera = FR.Camera(context, glframebuffer, PerspectiveCamera(w.inputs, Vec3f(3), Vec3f(0))) set!(scene, camera) DN = 512 # borrow loadasset from GLVisualize (just uses load(GLVisualize.assetpath(name))) # Load an obj cat = FR.Shape(context, loadasset("cat.obj")) push!(scene, cat) transform!(cat, translationmatrix(Vec3f(0, 0.5, 0))) # Load an obj r = SimpleRectangle{Float32}(-5, -5, 10, 10) plane = FR.Shape(context, r, (div(DN, 2), div(DN, 2))) push!(scene, plane) matsys = FR.MaterialSystem(context, 0) diffuse = FR.MaterialNode(matsys, FR.MATERIAL_NODE_REFLECTION) reflective = FR.MaterialNode(matsys, FR.MATERIAL_NODE_DIFFUSE) tex = FR.MaterialNode(matsys, FR.MATERIAL_NODE_IMAGE_TEXTURE) set!(diffuse, "color", HSVA(181, 0.23, 0.5, 1.0)) # all colors from the Color package can be used pirange = linspace(0, 4pi, DN) set!(tex, "data", context, RGBA{U8}[RGBA{U8}((sin(x) + 1) / 2, (cos(x) + 1) / 2, (cos(x) + 1) / 4, (cos(x) * sin(x) + 1) / 2) for x in pirange, y in pirange]) set!(reflective, "color", tex) set!(cat, diffuse) set!(plane, reflective) set!(plane, context, Float32[(sin(x) * cos(y) + 1) / 2.0f0 for x in pirange, y in pirange]) setdisplacementscale!(plane, 1.0) # seems like displacement doesn't work without setting subdevision to at least 1 setsubdivisions!(plane, 1) # create a HDR ligth ibl = FR.EnvironmentLight(context) imgpath = joinpath(homedir(), "Desktop", "FRSDK 1.078", "Resources", "Textures", "Apartment.hdr") set!(ibl, context, imgpath) set!(scene, ibl) set_standard_tonemapping!(context; aacellsize=1.0, aasamples=1.0) tiledrenderloop(w, context, glframebuffer)
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
2870
using RadeonProRender, GeometryBasics, Colors using Colors const RPR = RadeonProRender function setup_scene() context = RPR.Context(resource=RPR.RPR_CREATION_FLAGS_ENABLE_GPU1, plugin=RPR.Northstar) scene = RPR.Scene(context) matsys = RPR.MaterialSystem(context, 0) camera = RPR.Camera(context) lookat!(camera, Vec3f(8, 0, 5), Vec3f(2, 0, 2), Vec3f(0, 0, 1)) RPR.rprCameraSetFocalLength(camera, 45.0) set!(scene, camera) set!(context, scene) env_light = RadeonProRender.EnvironmentLight(context) image_path = RPR.assetpath("studio026.exr") img = RPR.Image(context, image_path) set!(env_light, img) setintensityscale!(env_light, 1.1) push!(scene, env_light) light = RPR.PointLight(context) transform!(light, Float32[1.0 0.0 0.0 2.0; 0.0 1.0 0.0 0.0; 0.0 0.0 1.0 5.0; 0.0 0.0 0.0 1.0]) f = 20 RPR.setradiantpower!(light, 500 / f, 641 / f, 630 / f) push!(scene, light) context, scene, matsys end context, scene, matsys = setup_scene() vol_cube = RPR.VolumeCube(context) transform = Float32[4 0 0 0 0 4 0 0 0 0 4 0 0 0 0 1] transform!(vol_cube, transform) push!(scene, vol_cube) r = LinRange(-1, 1, 100) cube = [(x .^ 2 + y .^ 2 + z .^ 2) for x in r, y in r, z in r] volume = Float32.(cube .* (cube .> 1.4)) mini, maxi = extrema(volume) grid = RPR.VoxelGrid(context, (volume .- mini) ./ (maxi - mini)) gridsampler = RPR.GridSamplerMaterial(matsys) gridsampler.data = grid ramp = [ RGB{Float32}(1.f0, 0.f0, 0.f0), RGB{Float32}(0.f0, 1.f0, 0.f0), RGB{Float32}(0.f0, 0.f0, 1.f0) ] img = RPR.Image(context, ramp) gridsampler2 = RPR.GridSamplerMaterial(matsys) gridsampler2.data = RPR.VoxelGrid(context, volume.*10f0) rampSampler2 = RPR.ImageTextureMaterial(matsys) rampSampler2.data = img rampSampler2.uv = gridsampler2 # for ramp texture, it's better to clamp it to edges. # set!(rampSampler2, RPR.RPR_MATERIAL_INPUT_WRAP_U, RPR.RPR_IMAGE_WRAP_TYPE_CLAMP_TO_EDGE) # set!(rampSampler2, RPR.RPR_MATERIAL_INPUT_WRAP_V, RPR.RPR_IMAGE_WRAP_TYPE_CLAMP_TO_EDGE) volmat = RPR.VolumeMaterial(matsys) RPR.rprShapeSetVolumeMaterial(vol_cube, volmat.node) volmat.density = Vec4f(10, 0, 0, 0) volmat.densitygrid = gridsampler volmat.color = rampSampler2 function render(context, path) fb_size = (800, 600) frame_buffer = RPR.FrameBuffer(context, RGBA, fb_size) frame_bufferSolved = RPR.FrameBuffer(context, RGBA, fb_size) set!(context, RPR.RPR_AOV_COLOR, frame_buffer) set_standard_tonemapping!(context) clear!(frame_buffer) RPR.rprContextSetParameterByKey1u(context, RPR.RPR_CONTEXT_ITERATIONS, 5000) @time RPR.render(context) RPR.rprContextResolveFrameBuffer(context, frame_buffer, frame_bufferSolved, false) return RPR.save(frame_bufferSolved, path) end path = joinpath(@__DIR__, "test.png") render(context, path)
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
2861
using RadeonProRender, GeometryTypes, GLAbstraction, GLVisualize, Colors, ModernGL, FileIO, Reactive using GLWindow const FR = RadeonProRender w = glscreen() # Create OpenCL context using a single GPU, which is the default context, glframebuffer = interactive_context(w) # Create a scene scene = FR.Scene(context) N = 256 const xrange = linspace(-5.0f0, 5.0f0, N) const yrange = linspace(-5.0f0, 5.0f0, N) z = Float32[sin(1.3 * x) * cos(0.9 * y) + cos(0.8 * x) * sin(1.9 * y) + cos(y * 0.2 * x) for x in xrange, y in yrange] mini = minimum(z) maxi = maximum(z) const cmap = map(x -> RGBA{U8}(x, 1.0), colormap("Blues")) to_color(val, mini, maxi) = cmap[floor(Int, (((val - mini) / (maxi - mini)) * (length(cmap) - 1))) + 1] image = map(z) do height return to_color(height, mini, maxi) end plane = FR.Shape(context, SimpleRectangle(-5, -5, 10, 10), (N, N)) push!(scene, plane) const t = Signal(2.0f0 * pi) matsys = FR.MaterialSystem(context, 0) reflective = FR.MaterialNode(matsys, FR.MATERIAL_NODE_MICROFACET) tex = FR.MaterialNode(matsys, FR.MATERIAL_NODE_IMAGE_TEXTURE) displace = FR.Image(context, z) color = FR.Image(context, image) set!(tex, "data", color) set!(reflective, "color", tex) set!(plane, reflective) set!(plane, displace) setdisplacementscale!(plane, 1.0) setsubdivisions!(plane, 1) preserve(map(t) do i z = Float32[sin(1.3 * x * i) * cos(0.9 * y * i) + cos(0.8 * x * i) * sin(1.9 * y * i) + cos(y * 0.2 * x * i) for x in xrange, y in yrange] mini = minimum(z) maxi = maximum(z) image = map(z) do height return to_color(height, mini, maxi) end displace = FR.Image(context, z) color = FR.Image(context, image) set!(tex, "data", color) return set!(plane, displace) end) camera = FR.Camera(context) lookat!(camera, Vec3f(0, 9.5, 11), Vec3f(0), Vec3f(0, 0, 1)) FR.CameraSetFocusDistance(camera.x, 7.0f0) FR.CameraSetFStop(camera.x, 1.8f0) set!(scene, camera) set!(context, scene) ibl = FR.EnvironmentLight(context) imgpath = joinpath("C:\\", "Program Files", "KeyShot6", "bin", "Materials 2k.hdr") set!(ibl, context, imgpath) set!(scene, ibl) pl = FR.PointLight(context); setradiantpower!(pl, fill(10.0f0^3, 3)...) transform!(pl, translationmatrix(Vec3f(0, 0, 7))) push!(scene, pl) set_standard_tonemapping!(context) frame = 1 for i in (0.5f0:0.01f0:(pi * 2.0f0)) push!(t, i) yield() isopen(w) || break clear!(glframebuffer) for i in 1:10 glBindTexture(GL_TEXTURE_2D, 0) @time render(context) isopen(w) || break GLWindow.render_frame(w) end isopen(w) || break try screenshot(w; path="test$frame.png") catch e println(e) end frame += 1 end
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
3118
using RadeonProRender, GeometryBasics, Colors const RPR = RadeonProRender using Colors: N0f8 # Create a scene context = RPR.Context() scene = RPR.Scene(context) matsys = RPR.MaterialSystem(context, 0) camera = RPR.Camera(context) lookat!(camera, Vec3f(3), Vec3f(0), Vec3f(0, 0, 1)) set!(scene, camera) # create some x,y,z data function create_mesh(DN = 512, dphi=pi/200.0f0, dtheta=dphi) phi = 0.0f0:dphi:(pi + dphi * 1.5f0) theta = (0.0f0:dtheta:(2.0f0 * pi + dtheta * 1.5f0))' m0 = 4.0f0; m1 = 3.0f0; m2 = 2.0f0; m3 = 3.0f0; m4 = 6.0f0; m5 = 2.0f0; m6 = 6.0f0; m7 = 4.0f0; a = @. sin(m0 * phi) ^ m1 b = @. cos(m2 * phi) ^ m3 c = @. sin(m4 * theta) ^ m5 d = @. cos(m6 * theta) ^ m7 r = @. a + b + c + d; x = @. r * sin(phi) * cos(theta) y = @. r * cos(phi) z = @. r * sin(phi) * sin(theta) xyz = Point3f[Point3f(x[i, j], y[i, j], z[i, j]) for i in 1:size(x, 1), j in 1:size(x, 2)] r = Tesselation(Rect2f((0, 0), (1, 1)), size(x)) # decomposing a rectangle into uv and triangles is what we need to map the z coordinates on # since the xyz data assumes the coordinates to have the same neighouring relations # like a grid faces = decompose(GLTriangleFace, r) uv = decompose_uv(r) # with this we can beuild a mesh return GeometryBasics.Mesh(meta(vec(xyz), uv=uv), faces), xyz end raw_mesh, xyz = create_mesh() surfacemesh = RPR.Shape(context, raw_mesh) push!(scene, surfacemesh) # create layered material tex = RPR.MaterialNode(matsys, RPR.RPR_MATERIAL_NODE_IMAGE_TEXTURE) base = RPR.MaterialNode(matsys, RPR.RPR_MATERIAL_NODE_DIFFUSE) top = RPR.MaterialNode(matsys, RPR.RPR_MATERIAL_NODE_REFLECTION) # Diffuse color set!(base, RPR.RPR_MATERIAL_INPUT_COLOR, tex); set!(base, RPR.RPR_MATERIAL_INPUT_ROUGHNESS, 0.12, 0.0, 0.0, 1.0) set!(top, RPR.RPR_MATERIAL_INPUT_COLOR, 0.1, 0.3, 0.9, 1.0) # Create layered shader layered = RPR.layeredshader(matsys, base, top) colorim = map(xyz) do xyz return RGBA{N0f8}(clamp(abs(xyz[1]), 0, 1), clamp(abs(xyz[2]), 0, 1), clamp(abs(xyz[3]), 0, 1), 1.0) end color = RPR.Image(context, colorim) set!(tex, RPR.RPR_MATERIAL_INPUT_DATA, color) set!(surfacemesh, layered) set!(context, scene) ibl = RPR.EnvironmentLight(context) image_path = joinpath(@__DIR__, "studio026.exr") set!(ibl, context, image_path) set!(scene, ibl) set_standard_tonemapping!(context) fb_size = (800, 600) frame_buffer = RPR.FrameBuffer(context, RGBA, fb_size) frame_bufferSolved = RPR.FrameBuffer(context, RGBA, fb_size) frame_buffer_post = RPR.FrameBuffer(context, RGBA, fb_size) set!(context, RPR.RPR_AOV_COLOR, frame_buffer) begin clear!(frame_buffer) clear!(frame_buffer_post) RPR.rprContextSetParameterByKey1u(context, RPR.RPR_CONTEXT_ITERATIONS, 100) RPR.render(context) RPR.rprContextResolveFrameBuffer(context, frame_buffer, frame_bufferSolved, true) RPR.save(frame_bufferSolved, "surface_mesh.png") RPR.rprContextResolveFrameBuffer(context, frame_buffer, frame_buffer_post, false) RPR.save(frame_buffer_post, "surface_mesh_postprocess.png") end
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
2757
using RadeonProRender, GeometryBasics, Colors const RPR = RadeonProRender function translationmatrix(t::Vec{3,T}) where {T} T0, T1 = zero(T), one(T) return Mat{4}(T1, T0, T0, T0, T0, T1, T0, T0, T0, T0, T1, T0, t[1], t[2], t[3], T1) end isdefined(Main, :context) && RPR.release(context) context = RPR.Context() scene = RPR.Scene(context) set!(context, scene) matsys = RPR.MaterialSystem(context, 0) camera = RPR.Camera(context) lookat!(camera, Vec3f(1.5, 0.75, 1.5), Vec3f(0), Vec3f(0, 0, 1)) RPR.rprCameraSetFocalLength(camera, 45.0) set!(scene, camera) env_light = RadeonProRender.EnvironmentLight(context) image_path = joinpath(@__DIR__, "studio026.exr") img = RPR.Image(context, image_path) set!(env_light, img) setintensityscale!(env_light, 1.2) push!(scene, env_light) light = RPR.PointLight(context) transform!(light, translationmatrix(Vec3f(2, 0, 5))) f = 1.5 RPR.setradiantpower!(light, 500 / f, 641 / f, 630 / f) push!(scene, light) vol_cube = RadeonProRender.Shape(context, Rect3f(Vec3f(0), Vec3f(1))) push!(scene, vol_cube) color_lookup = [colorant"red", colorant"yellow", colorant"green"] convert(Vector{RGB{Float32}}, color_lookup) density_lookup = [Vec3f.(10:-1:0);] n = 128 gridvals = Float32[] indices1 = UInt64[] for x in 0:(n-1) for y in 0:(n-1) for z in 0:(n-1) v = y / n push!(indices1, (x)*(n*n) + (y)*(n)+z) push!(gridvals, v) end end end (a, b) = -1, 2 r = range(-3, stop = 3, length = 800) z = ((x,y) -> y.^4 - x.^4 + a.*y.^2 + b.*x.^2).(r, r') me = [cos.(2 .* pi .* sqrt.(x.^2 + y.^2)) .* (4 .* z) for x=r, y=r, z=r] mini, maxi = extrema(me) grid = RPR.VoxelGrid(context, (me .- mini) ./ (maxi - mini)) volume1 = RPR.HeteroVolume(context) RPR.set_albedo_grid!(volume1, grid) RPR.set_albedo_lookup!(volume1, color_lookup) RPR.set_density_grid!(volume1, grid) RPR.set_density_lookup!(volume1, density_lookup) mat = RPR.MaterialNode(matsys, RPR.RPR_MATERIAL_NODE_TRANSPARENT) set!(mat, RPR.RPR_MATERIAL_INPUT_COLOR, 1.0f0, 1.0f0, 1.0f0, 1.0f0) RPR.rprSceneAttachHeteroVolume(scene, volume1) set!(vol_cube, volume1) set!(vol_cube, mat) fb_size = (800, 600) frame_buffer = RPR.FrameBuffer(context, RGBA, fb_size) frame_bufferSolved = RPR.FrameBuffer(context, RGBA, fb_size) set!(context, RPR.RPR_AOV_COLOR, frame_buffer) # to avoid dark transparency, we raise recursion RPR.rprContextSetParameterByKey1u(context, RPR.RPR_CONTEXT_MAX_RECURSION, 10) # set_standard_tonemapping!(context) begin clear!(frame_buffer) RPR.rprContextSetParameterByKey1u(context, RPR.RPR_CONTEXT_ITERATIONS, 4) RPR.render(context) RPR.rprContextResolveFrameBuffer(context, frame_buffer, frame_bufferSolved, true) RPR.save(frame_bufferSolved, "test.png") end
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
184430
module RPR using RadeonProRender_jll export RadeonProRender_jll using CEnum function check_error(error_code) error_code == RPR_SUCCESS && return return error("Error code returned: $(error_code)") end const rpr_char = Cchar const rpr_uchar = Cuchar const rpr_int = Cint const rpr_uint = Cuint const rpr_long = Clong const rpr_ulong = Culong const rpr_short = Cshort const rpr_ushort = Cushort const rpr_float = Cfloat const rpr_double = Cdouble const rpr_longlong = Clonglong const rpr_bool = Cint const rpr_bitfield = rpr_uint struct rpr_context_t _::Ptr{Cvoid} end const rpr_context = Ptr{rpr_context_t} struct rpr_camera_t _::Ptr{Cvoid} end const rpr_camera = Ptr{rpr_camera_t} struct rpr_shape_t _::Ptr{Cvoid} end const rpr_shape = Ptr{rpr_shape_t} struct rpr_light_t _::Ptr{Cvoid} end const rpr_light = Ptr{rpr_light_t} struct rpr_scene_t _::Ptr{Cvoid} end const rpr_scene = Ptr{rpr_scene_t} struct rpr_image_t _::Ptr{Cvoid} end const rpr_image = Ptr{rpr_image_t} struct rpr_buffer_t _::Ptr{Cvoid} end const rpr_buffer = Ptr{rpr_buffer_t} struct rpr_hetero_volume_t _::Ptr{Cvoid} end const rpr_hetero_volume = Ptr{rpr_hetero_volume_t} struct rpr_grid_t _::Ptr{Cvoid} end const rpr_grid = Ptr{rpr_grid_t} struct rpr_curve_t _::Ptr{Cvoid} end const rpr_curve = Ptr{rpr_curve_t} struct rpr_framebuffer_t _::Ptr{Cvoid} end const rpr_framebuffer = Ptr{rpr_framebuffer_t} struct rpr_material_system_t _::Ptr{Cvoid} end const rpr_material_system = Ptr{rpr_material_system_t} struct rpr_material_node_t _::Ptr{Cvoid} end const rpr_material_node = Ptr{rpr_material_node_t} struct rpr_post_effect_t _::Ptr{Cvoid} end const rpr_post_effect = Ptr{rpr_post_effect_t} struct rpr_context_properties_t _::Ptr{Cvoid} end const rpr_context_properties = Ptr{rpr_context_properties_t} struct rpr_composite_t _::Ptr{Cvoid} end const rpr_composite = Ptr{rpr_composite_t} struct rpr_lut_t _::Ptr{Cvoid} end const rpr_lut = Ptr{rpr_lut_t} const rpr_image_option = rpr_uint const rpr_context_type = rpr_uint const rpr_creation_flags = rpr_bitfield const rpr_channel_order = rpr_uint const rpr_channel_type = rpr_uint const rpr_material_system_type = rpr_uint const rpr_environment_override = rpr_uint @cenum rpr_status::Int32 begin RPR_SUCCESS = 0 RPR_ERROR_COMPUTE_API_NOT_SUPPORTED = -1 RPR_ERROR_OUT_OF_SYSTEM_MEMORY = -2 RPR_ERROR_OUT_OF_VIDEO_MEMORY = -3 RPR_ERROR_SHADER_COMPILATION = -4 RPR_ERROR_INVALID_LIGHTPATH_EXPR = -5 RPR_ERROR_INVALID_IMAGE = -6 RPR_ERROR_INVALID_AA_METHOD = -7 RPR_ERROR_UNSUPPORTED_IMAGE_FORMAT = -8 RPR_ERROR_INVALID_GL_TEXTURE = -9 RPR_ERROR_INVALID_CL_IMAGE = -10 RPR_ERROR_INVALID_OBJECT = -11 RPR_ERROR_INVALID_PARAMETER = -12 RPR_ERROR_INVALID_TAG = -13 RPR_ERROR_INVALID_LIGHT = -14 RPR_ERROR_INVALID_CONTEXT = -15 RPR_ERROR_UNIMPLEMENTED = -16 RPR_ERROR_INVALID_API_VERSION = -17 RPR_ERROR_INTERNAL_ERROR = -18 RPR_ERROR_IO_ERROR = -19 RPR_ERROR_UNSUPPORTED_SHADER_PARAMETER_TYPE = -20 RPR_ERROR_MATERIAL_STACK_OVERFLOW = -21 RPR_ERROR_INVALID_PARAMETER_TYPE = -22 RPR_ERROR_UNSUPPORTED = -23 RPR_ERROR_OPENCL_OUT_OF_HOST_MEMORY = -24 RPR_ERROR_OPENGL = -25 RPR_ERROR_OPENCL = -26 RPR_ERROR_NULLPTR = -27 RPR_ERROR_NODETYPE = -28 RPR_ERROR_ABORTED = -29 end @cenum rpr_parameter_type::UInt32 begin RPR_PARAMETER_TYPE_UNDEF = 0 RPR_PARAMETER_TYPE_FLOAT = 1 RPR_PARAMETER_TYPE_FLOAT2 = 2 RPR_PARAMETER_TYPE_FLOAT3 = 3 RPR_PARAMETER_TYPE_FLOAT4 = 4 RPR_PARAMETER_TYPE_IMAGE = 5 RPR_PARAMETER_TYPE_STRING = 6 RPR_PARAMETER_TYPE_SHADER = 7 RPR_PARAMETER_TYPE_UINT = 8 RPR_PARAMETER_TYPE_ULONG = 9 RPR_PARAMETER_TYPE_LONGLONG = 10 end @cenum rpr_creation_flags_t::Int32 begin RPR_CREATION_FLAGS_ENABLE_GPU0 = 1 RPR_CREATION_FLAGS_ENABLE_GPU1 = 2 RPR_CREATION_FLAGS_ENABLE_GPU2 = 4 RPR_CREATION_FLAGS_ENABLE_GPU3 = 8 RPR_CREATION_FLAGS_ENABLE_CPU = 16 RPR_CREATION_FLAGS_ENABLE_GL_INTEROP = 32 RPR_CREATION_FLAGS_ENABLE_GPU4 = 64 RPR_CREATION_FLAGS_ENABLE_GPU5 = 128 RPR_CREATION_FLAGS_ENABLE_GPU6 = 256 RPR_CREATION_FLAGS_ENABLE_GPU7 = 512 RPR_CREATION_FLAGS_ENABLE_METAL = 1024 RPR_CREATION_FLAGS_ENABLE_GPU8 = 2048 RPR_CREATION_FLAGS_ENABLE_GPU9 = 4096 RPR_CREATION_FLAGS_ENABLE_GPU10 = 8192 RPR_CREATION_FLAGS_ENABLE_GPU11 = 16384 RPR_CREATION_FLAGS_ENABLE_GPU12 = 32768 RPR_CREATION_FLAGS_ENABLE_GPU13 = 65536 RPR_CREATION_FLAGS_ENABLE_GPU14 = 131072 RPR_CREATION_FLAGS_ENABLE_GPU15 = 262144 RPR_CREATION_FLAGS_ENABLE_HIP = 524288 RPR_CREATION_FLAGS_ENABLE_OPENCL = 1048576 RPR_CREATION_FLAGS_ENABLE_DEBUG = -2147483648 end @cenum rpr_aa_filter::UInt32 begin RPR_FILTER_NONE = 0 RPR_FILTER_BOX = 1 RPR_FILTER_TRIANGLE = 2 RPR_FILTER_GAUSSIAN = 3 RPR_FILTER_MITCHELL = 4 RPR_FILTER_LANCZOS = 5 RPR_FILTER_BLACKMANHARRIS = 6 end @cenum rpr_context_sampler_type::UInt32 begin RPR_CONTEXT_SAMPLER_TYPE_SOBOL = 1 RPR_CONTEXT_SAMPLER_TYPE_RANDOM = 2 RPR_CONTEXT_SAMPLER_TYPE_CMJ = 3 end @cenum rpr_primvar_interpolation_type::UInt32 begin RPR_PRIMVAR_INTERPOLATION_CONSTANT = 1 RPR_PRIMVAR_INTERPOLATION_UNIFORM = 2 RPR_PRIMVAR_INTERPOLATION_VERTEX = 3 RPR_PRIMVAR_INTERPOLATION_FACEVARYING_NORMAL = 4 RPR_PRIMVAR_INTERPOLATION_FACEVARYING_UV = 5 end @cenum rpr_shape_type::UInt32 begin RPR_SHAPE_TYPE_MESH = 1 RPR_SHAPE_TYPE_INSTANCE = 2 end @cenum rpr_light_type::UInt32 begin RPR_LIGHT_TYPE_POINT = 1 RPR_LIGHT_TYPE_DIRECTIONAL = 2 RPR_LIGHT_TYPE_SPOT = 3 RPR_LIGHT_TYPE_ENVIRONMENT = 4 RPR_LIGHT_TYPE_SKY = 5 RPR_LIGHT_TYPE_IES = 6 RPR_LIGHT_TYPE_SPHERE = 7 RPR_LIGHT_TYPE_DISK = 8 end @cenum rpr_context_info::UInt32 begin RPR_CONTEXT_CREATION_FLAGS = 258 RPR_CONTEXT_CACHE_PATH = 259 RPR_CONTEXT_RENDER_STATUS = 260 RPR_CONTEXT_RENDER_STATISTICS = 261 RPR_CONTEXT_DEVICE_COUNT = 262 RPR_CONTEXT_PARAMETER_COUNT = 263 RPR_CONTEXT_ACTIVE_PLUGIN = 264 RPR_CONTEXT_SCENE = 265 RPR_CONTEXT_ITERATIONS = 267 RPR_CONTEXT_IMAGE_FILTER_TYPE = 268 RPR_CONTEXT_TONE_MAPPING_TYPE = 275 RPR_CONTEXT_TONE_MAPPING_LINEAR_SCALE = 276 RPR_CONTEXT_TONE_MAPPING_PHOTO_LINEAR_SENSITIVITY = 277 RPR_CONTEXT_TONE_MAPPING_PHOTO_LINEAR_EXPOSURE = 278 RPR_CONTEXT_TONE_MAPPING_PHOTO_LINEAR_FSTOP = 279 RPR_CONTEXT_TONE_MAPPING_REINHARD02_PRE_SCALE = 280 RPR_CONTEXT_TONE_MAPPING_REINHARD02_POST_SCALE = 281 RPR_CONTEXT_TONE_MAPPING_REINHARD02_BURN = 282 RPR_CONTEXT_MAX_RECURSION = 283 RPR_CONTEXT_RAY_CAST_EPSILON = 284 RPR_CONTEXT_RADIANCE_CLAMP = 285 RPR_CONTEXT_X_FLIP = 286 RPR_CONTEXT_Y_FLIP = 287 RPR_CONTEXT_TEXTURE_GAMMA = 288 RPR_CONTEXT_PDF_THRESHOLD = 289 RPR_CONTEXT_RENDER_MODE = 290 RPR_CONTEXT_ROUGHNESS_CAP = 291 RPR_CONTEXT_DISPLAY_GAMMA = 292 RPR_CONTEXT_MATERIAL_STACK_SIZE = 293 RPR_CONTEXT_CUTTING_PLANES = 294 RPR_CONTEXT_GPU0_NAME = 295 RPR_CONTEXT_GPU1_NAME = 296 RPR_CONTEXT_GPU2_NAME = 297 RPR_CONTEXT_GPU3_NAME = 298 RPR_CONTEXT_CPU_NAME = 299 RPR_CONTEXT_GPU4_NAME = 300 RPR_CONTEXT_GPU5_NAME = 301 RPR_CONTEXT_GPU6_NAME = 302 RPR_CONTEXT_GPU7_NAME = 303 RPR_CONTEXT_TONE_MAPPING_EXPONENTIAL_INTENSITY = 304 RPR_CONTEXT_FRAMECOUNT = 305 RPR_CONTEXT_TEXTURE_COMPRESSION = 306 RPR_CONTEXT_AO_RAY_LENGTH = 307 RPR_CONTEXT_OOC_TEXTURE_CACHE = 308 RPR_CONTEXT_PREVIEW = 309 RPR_CONTEXT_CPU_THREAD_LIMIT = 310 RPR_CONTEXT_LAST_ERROR_MESSAGE = 311 RPR_CONTEXT_MAX_DEPTH_DIFFUSE = 312 RPR_CONTEXT_MAX_DEPTH_GLOSSY = 313 RPR_CONTEXT_OOC_CACHE_PATH = 314 RPR_CONTEXT_MAX_DEPTH_REFRACTION = 315 RPR_CONTEXT_MAX_DEPTH_GLOSSY_REFRACTION = 316 RPR_CONTEXT_RENDER_LAYER_MASK = 317 RPR_CONTEXT_SINGLE_LEVEL_BVH_ENABLED = 318 RPR_CONTEXT_TRANSPARENT_BACKGROUND = 319 RPR_CONTEXT_MAX_DEPTH_SHADOW = 320 RPR_CONTEXT_API_VERSION = 321 RPR_CONTEXT_GPU8_NAME = 322 RPR_CONTEXT_GPU9_NAME = 323 RPR_CONTEXT_GPU10_NAME = 324 RPR_CONTEXT_GPU11_NAME = 325 RPR_CONTEXT_GPU12_NAME = 326 RPR_CONTEXT_GPU13_NAME = 327 RPR_CONTEXT_GPU14_NAME = 328 RPR_CONTEXT_GPU15_NAME = 329 RPR_CONTEXT_API_VERSION_MINOR = 330 RPR_CONTEXT_METAL_PERFORMANCE_SHADER = 331 RPR_CONTEXT_USER_TEXTURE_0 = 332 RPR_CONTEXT_USER_TEXTURE_1 = 333 RPR_CONTEXT_USER_TEXTURE_2 = 334 RPR_CONTEXT_USER_TEXTURE_3 = 335 RPR_CONTEXT_MIPMAP_LOD_OFFSET = 336 RPR_CONTEXT_AO_RAY_COUNT = 337 RPR_CONTEXT_SAMPLER_TYPE = 338 RPR_CONTEXT_ADAPTIVE_SAMPLING_TILE_SIZE = 339 RPR_CONTEXT_ADAPTIVE_SAMPLING_MIN_SPP = 340 RPR_CONTEXT_ADAPTIVE_SAMPLING_THRESHOLD = 341 RPR_CONTEXT_TILE_SIZE = 342 RPR_CONTEXT_LIST_CREATED_CAMERAS = 343 RPR_CONTEXT_LIST_CREATED_MATERIALNODES = 344 RPR_CONTEXT_LIST_CREATED_LIGHTS = 345 RPR_CONTEXT_LIST_CREATED_SHAPES = 346 RPR_CONTEXT_LIST_CREATED_POSTEFFECTS = 347 RPR_CONTEXT_LIST_CREATED_HETEROVOLUMES = 348 RPR_CONTEXT_LIST_CREATED_GRIDS = 349 RPR_CONTEXT_LIST_CREATED_BUFFERS = 350 RPR_CONTEXT_LIST_CREATED_IMAGES = 351 RPR_CONTEXT_LIST_CREATED_FRAMEBUFFERS = 352 RPR_CONTEXT_LIST_CREATED_SCENES = 353 RPR_CONTEXT_LIST_CREATED_CURVES = 354 RPR_CONTEXT_LIST_CREATED_MATERIALSYSTEM = 355 RPR_CONTEXT_LIST_CREATED_COMPOSITE = 356 RPR_CONTEXT_LIST_CREATED_LUT = 357 RPR_CONTEXT_AA_ENABLED = 358 RPR_CONTEXT_ACTIVE_PIXEL_COUNT = 359 RPR_CONTEXT_TRACING_ENABLED = 360 RPR_CONTEXT_TRACING_PATH = 361 RPR_CONTEXT_TILE_RECT = 362 RPR_CONTEXT_PLUGIN_VERSION = 363 RPR_CONTEXT_RUSSIAN_ROULETTE_DEPTH = 364 RPR_CONTEXT_SHADOW_CATCHER_BAKING = 365 RPR_CONTEXT_RENDER_UPDATE_CALLBACK_FUNC = 366 RPR_CONTEXT_RENDER_UPDATE_CALLBACK_DATA = 367 RPR_CONTEXT_COMPILE_CALLBACK_FUNC = 1537 RPR_CONTEXT_COMPILE_CALLBACK_DATA = 1538 RPR_CONTEXT_TEXTURE_CACHE_PATH = 368 RPR_CONTEXT_OCIO_CONFIG_PATH = 369 RPR_CONTEXT_OCIO_RENDERING_COLOR_SPACE = 370 RPR_CONTEXT_CONTOUR_USE_OBJECTID = 371 RPR_CONTEXT_CONTOUR_USE_MATERIALID = 372 RPR_CONTEXT_CONTOUR_USE_NORMAL = 373 RPR_CONTEXT_CONTOUR_USE_UV = 390 RPR_CONTEXT_CONTOUR_NORMAL_THRESHOLD = 374 RPR_CONTEXT_CONTOUR_UV_THRESHOLD = 391 RPR_CONTEXT_CONTOUR_UV_SECONDARY = 404 RPR_CONTEXT_CONTOUR_LINEWIDTH_OBJECTID = 375 RPR_CONTEXT_CONTOUR_LINEWIDTH_MATERIALID = 376 RPR_CONTEXT_CONTOUR_LINEWIDTH_NORMAL = 377 RPR_CONTEXT_CONTOUR_LINEWIDTH_UV = 392 RPR_CONTEXT_CONTOUR_ANTIALIASING = 378 RPR_CONTEXT_CONTOUR_DEBUG_ENABLED = 383 RPR_CONTEXT_GPUINTEGRATOR = 379 RPR_CONTEXT_CPUINTEGRATOR = 380 RPR_CONTEXT_BEAUTY_MOTION_BLUR = 381 RPR_CONTEXT_CAUSTICS_REDUCTION = 382 RPR_CONTEXT_GPU_MEMORY_LIMIT = 384 RPR_CONTEXT_RENDER_LAYER_LIST = 385 RPR_CONTEXT_WINDING_ORDER_CORRECTION = 386 RPR_CONTEXT_DEEP_SUBPIXEL_MERGE_Z_THRESHOLD = 387 RPR_CONTEXT_DEEP_GPU_ALLOCATION_LEVEL = 388 RPR_CONTEXT_DEEP_COLOR_ENABLED = 389 RPR_CONTEXT_FOG_COLOR = 393 RPR_CONTEXT_FOG_DISTANCE = 394 RPR_CONTEXT_FOG_HEIGHT = 395 RPR_CONTEXT_ATMOSPHERE_VOLUME_COLOR = 396 RPR_CONTEXT_ATMOSPHERE_VOLUME_DENSITY = 397 RPR_CONTEXT_ATMOSPHERE_VOLUME_RADIANCE_CLAMP = 399 RPR_CONTEXT_FOG_HEIGHT_OFFSET = 398 RPR_CONTEXT_INDIRECT_DOWNSAMPLE = 400 RPR_CONTEXT_CRYPTOMATTE_EXTENDED = 401 RPR_CONTEXT_CRYPTOMATTE_SPLIT_INDIRECT = 402 RPR_CONTEXT_FOG_DIRECTION = 403 RPR_CONTEXT_RANDOM_SEED = 4096 RPR_CONTEXT_IBL_DISPLAY = 405 RPR_CONTEXT_FRAMEBUFFER_SAVE_FLOAT32 = 406 RPR_CONTEXT_UPDATE_TIME_CALLBACK_FUNC = 407 RPR_CONTEXT_UPDATE_TIME_CALLBACK_DATA = 408 RPR_CONTEXT_RENDER_TIME_CALLBACK_FUNC = 409 RPR_CONTEXT_RENDER_TIME_CALLBACK_DATA = 410 RPR_CONTEXT_FIRST_ITERATION_TIME_CALLBACK_FUNC = 411 RPR_CONTEXT_FIRST_ITERATION_TIME_CALLBACK_DATA = 412 RPR_CONTEXT_IMAGE_FILTER_RADIUS = 413 RPR_CONTEXT_PRECOMPILED_BINARY_PATH = 414 RPR_CONTEXT_NAME = 7829367 RPR_CONTEXT_UNIQUE_ID = 7829368 RPR_CONTEXT_CUSTOM_PTR = 7829369 end @cenum rpr_camera_info::UInt32 begin RPR_CAMERA_TRANSFORM = 513 RPR_CAMERA_FSTOP = 514 RPR_CAMERA_APERTURE_BLADES = 515 RPR_CAMERA_RESPONSE = 516 RPR_CAMERA_EXPOSURE = 517 RPR_CAMERA_FOCAL_LENGTH = 518 RPR_CAMERA_SENSOR_SIZE = 519 RPR_CAMERA_MODE = 520 RPR_CAMERA_ORTHO_WIDTH = 521 RPR_CAMERA_ORTHO_HEIGHT = 522 RPR_CAMERA_FOCUS_DISTANCE = 523 RPR_CAMERA_POSITION = 524 RPR_CAMERA_LOOKAT = 525 RPR_CAMERA_UP = 526 RPR_CAMERA_FOCAL_TILT = 527 RPR_CAMERA_LENS_SHIFT = 528 RPR_CAMERA_IPD = 529 RPR_CAMERA_TILT_CORRECTION = 530 RPR_CAMERA_NEAR_PLANE = 531 RPR_CAMERA_FAR_PLANE = 532 RPR_CAMERA_LINEAR_MOTION = 533 RPR_CAMERA_ANGULAR_MOTION = 534 RPR_CAMERA_MOTION_TRANSFORMS_COUNT = 535 RPR_CAMERA_MOTION_TRANSFORMS = 536 RPR_CAMERA_POST_SCALE = 537 RPR_CAMERA_UV_DISTORTION = 538 RPR_CAMERA_NAME = 7829367 RPR_CAMERA_UNIQUE_ID = 7829368 RPR_CAMERA_CUSTOM_PTR = 7829369 end @cenum rpr_image_info::UInt32 begin RPR_IMAGE_FORMAT = 769 RPR_IMAGE_DESC = 770 RPR_IMAGE_DATA = 771 RPR_IMAGE_DATA_SIZEBYTE = 772 RPR_IMAGE_WRAP = 773 RPR_IMAGE_FILTER = 774 RPR_IMAGE_GAMMA = 775 RPR_IMAGE_MIPMAP_ENABLED = 776 RPR_IMAGE_MIP_COUNT = 777 RPR_IMAGE_GAMMA_FROM_FILE = 778 RPR_IMAGE_UDIM = 779 RPR_IMAGE_OCIO_COLORSPACE = 780 RPR_IMAGE_INTERNAL_COMPRESSION = 781 RPR_IMAGE_NAME = 7829367 RPR_IMAGE_UNIQUE_ID = 7829368 RPR_IMAGE_CUSTOM_PTR = 7829369 end @cenum rpr_buffer_info::UInt32 begin RPR_BUFFER_DESC = 848 RPR_BUFFER_DATA = 849 RPR_BUFFER_NAME = 7829367 RPR_BUFFER_UNIQUE_ID = 7829368 RPR_BUFFER_CUSTOM_PTR = 7829369 end @cenum rpr_shape_info::UInt32 begin RPR_SHAPE_TYPE = 1025 RPR_SHAPE_VIDMEM_USAGE = 1026 RPR_SHAPE_TRANSFORM = 1027 RPR_SHAPE_MATERIAL = 1028 RPR_SHAPE_LINEAR_MOTION = 1029 RPR_SHAPE_ANGULAR_MOTION = 1030 RPR_SHAPE_SHADOW_FLAG = 1032 RPR_SHAPE_SUBDIVISION_FACTOR = 1033 RPR_SHAPE_DISPLACEMENT_SCALE = 1034 RPR_SHAPE_SHADOW_CATCHER_FLAG = 1038 RPR_SHAPE_VOLUME_MATERIAL = 1039 RPR_SHAPE_OBJECT_GROUP_ID = 1040 RPR_SHAPE_SUBDIVISION_CREASEWEIGHT = 1041 RPR_SHAPE_SUBDIVISION_BOUNDARYINTEROP = 1042 RPR_SHAPE_DISPLACEMENT_MATERIAL = 1043 RPR_SHAPE_MATERIALS_PER_FACE = 1045 RPR_SHAPE_SCALE_MOTION = 1046 RPR_SHAPE_HETERO_VOLUME = 1047 RPR_SHAPE_LAYER_MASK = 1048 RPR_SHAPE_VISIBILITY_PRIMARY_ONLY_FLAG = 1036 RPR_SHAPE_VISIBILITY_SHADOW = 1050 RPR_SHAPE_VISIBILITY_REFLECTION = 1051 RPR_SHAPE_VISIBILITY_REFRACTION = 1052 RPR_SHAPE_VISIBILITY_TRANSPARENT = 1053 RPR_SHAPE_VISIBILITY_DIFFUSE = 1054 RPR_SHAPE_VISIBILITY_GLOSSY_REFLECTION = 1055 RPR_SHAPE_VISIBILITY_GLOSSY_REFRACTION = 1056 RPR_SHAPE_VISIBILITY_LIGHT = 1057 RPR_SHAPE_LIGHT_GROUP_ID = 1058 RPR_SHAPE_STATIC = 1059 RPR_SHAPE_PER_VERTEX_VALUE0 = 1060 RPR_SHAPE_PER_VERTEX_VALUE1 = 1061 RPR_SHAPE_PER_VERTEX_VALUE2 = 1062 RPR_SHAPE_PER_VERTEX_VALUE3 = 1063 RPR_SHAPE_REFLECTION_CATCHER_FLAG = 1064 RPR_SHAPE_OBJECT_ID = 1065 RPR_SHAPE_SUBDIVISION_AUTO_RATIO_CAP = 1066 RPR_SHAPE_MOTION_TRANSFORMS_COUNT = 1067 RPR_SHAPE_MOTION_TRANSFORMS = 1068 RPR_SHAPE_CONTOUR_IGNORE = 1069 RPR_SHAPE_RENDER_LAYER_LIST = 1070 RPR_SHAPE_SHADOW_COLOR = 1071 RPR_SHAPE_VISIBILITY_RECEIVE_SHADOW = 1072 RPR_SHAPE_PRIMVARS = 1073 RPR_SHAPE_ENVIRONMENT_LIGHT = 1074 RPR_SHAPE_NAME = 7829367 RPR_SHAPE_UNIQUE_ID = 7829368 RPR_SHAPE_CUSTOM_PTR = 7829369 end @cenum rpr_mesh_info::UInt32 begin RPR_MESH_POLYGON_COUNT = 1281 RPR_MESH_VERTEX_COUNT = 1282 RPR_MESH_NORMAL_COUNT = 1283 RPR_MESH_UV_COUNT = 1284 RPR_MESH_VERTEX_ARRAY = 1285 RPR_MESH_NORMAL_ARRAY = 1286 RPR_MESH_UV_ARRAY = 1287 RPR_MESH_VERTEX_INDEX_ARRAY = 1288 RPR_MESH_NORMAL_INDEX_ARRAY = 1289 RPR_MESH_UV_INDEX_ARRAY = 1290 RPR_MESH_VERTEX_STRIDE = 1292 RPR_MESH_NORMAL_STRIDE = 1293 RPR_MESH_UV_STRIDE = 1294 RPR_MESH_VERTEX_INDEX_STRIDE = 1295 RPR_MESH_NORMAL_INDEX_STRIDE = 1296 RPR_MESH_UV_INDEX_STRIDE = 1297 RPR_MESH_NUM_FACE_VERTICES_ARRAY = 1298 RPR_MESH_UV2_COUNT = 1299 RPR_MESH_UV2_ARRAY = 1300 RPR_MESH_UV2_INDEX_ARRAY = 1301 RPR_MESH_UV2_STRIDE = 1302 RPR_MESH_UV2_INDEX_STRIDE = 1303 RPR_MESH_UV_DIM = 1304 RPR_MESH_MOTION_DIMENSION = 1305 RPR_MESH_VOLUME_FLAG = 1306 end @cenum rpr_scene_info::UInt32 begin RPR_SCENE_SHAPE_COUNT = 1793 RPR_SCENE_LIGHT_COUNT = 1794 RPR_SCENE_SHAPE_LIST = 1796 RPR_SCENE_LIGHT_LIST = 1797 RPR_SCENE_CAMERA = 1798 RPR_SCENE_CAMERA_RIGHT = 1799 RPR_SCENE_BACKGROUND_IMAGE = 1800 RPR_SCENE_AABB = 1805 RPR_SCENE_HETEROVOLUME_LIST = 1806 RPR_SCENE_HETEROVOLUME_COUNT = 1807 RPR_SCENE_CURVE_LIST = 1808 RPR_SCENE_CURVE_COUNT = 1809 RPR_SCENE_ENVIRONMENT_LIGHT = 1810 RPR_SCENE_NAME = 7829367 RPR_SCENE_UNIQUE_ID = 7829368 RPR_SCENE_CUSTOM_PTR = 7829369 end @cenum rpr_lut_info::UInt32 begin RPR_LUT_FILENAME = 2128 RPR_LUT_DATA = 2129 end @cenum rpr_light_info::UInt32 begin RPR_LIGHT_TYPE = 2049 RPR_LIGHT_TRANSFORM = 2051 RPR_LIGHT_GROUP_ID = 2053 RPR_LIGHT_RENDER_LAYER_LIST = 2054 RPR_LIGHT_VISIBILITY_LIGHT = 2055 RPR_LIGHT_NAME = 7829367 RPR_LIGHT_UNIQUE_ID = 7829368 RPR_LIGHT_CUSTOM_PTR = 7829369 RPR_POINT_LIGHT_RADIANT_POWER = 2052 RPR_DIRECTIONAL_LIGHT_RADIANT_POWER = 2056 RPR_DIRECTIONAL_LIGHT_SHADOW_SOFTNESS_ANGLE = 2058 RPR_SPOT_LIGHT_RADIANT_POWER = 2059 RPR_SPOT_LIGHT_CONE_SHAPE = 2060 RPR_SPOT_LIGHT_IMAGE = 2061 RPR_ENVIRONMENT_LIGHT_IMAGE = 2063 RPR_ENVIRONMENT_LIGHT_INTENSITY_SCALE = 2064 RPR_ENVIRONMENT_LIGHT_PORTAL_LIST = 2072 RPR_ENVIRONMENT_LIGHT_PORTAL_COUNT = 2073 RPR_ENVIRONMENT_LIGHT_OVERRIDE_REFLECTION = 2074 RPR_ENVIRONMENT_LIGHT_OVERRIDE_REFRACTION = 2075 RPR_ENVIRONMENT_LIGHT_OVERRIDE_TRANSPARENCY = 2076 RPR_ENVIRONMENT_LIGHT_OVERRIDE_BACKGROUND = 2077 RPR_ENVIRONMENT_LIGHT_OVERRIDE_IRRADIANCE = 2078 RPR_SKY_LIGHT_TURBIDITY = 2066 RPR_SKY_LIGHT_ALBEDO = 2067 RPR_SKY_LIGHT_SCALE = 2068 RPR_SKY_LIGHT_DIRECTION = 2069 RPR_SKY_LIGHT_PORTAL_LIST = 2080 RPR_SKY_LIGHT_PORTAL_COUNT = 2081 RPR_IES_LIGHT_RADIANT_POWER = 2070 RPR_IES_LIGHT_IMAGE_DESC = 2071 RPR_SPHERE_LIGHT_RADIANT_POWER = 2082 RPR_SPHERE_LIGHT_RADIUS = 2084 RPR_DISK_LIGHT_RADIANT_POWER = 2083 RPR_DISK_LIGHT_RADIUS = 2085 RPR_DISK_LIGHT_ANGLE = 2086 RPR_DISK_LIGHT_INNER_ANGLE = 2087 end @cenum rpr_parameter_info::UInt32 begin RPR_PARAMETER_NAME = 4609 RPR_PARAMETER_TYPE = 4611 RPR_PARAMETER_DESCRIPTION = 4612 RPR_PARAMETER_VALUE = 4613 end @cenum rpr_framebuffer_info::UInt32 begin RPR_FRAMEBUFFER_FORMAT = 4865 RPR_FRAMEBUFFER_DESC = 4866 RPR_FRAMEBUFFER_DATA = 4867 RPR_FRAMEBUFFER_GL_TARGET = 4868 RPR_FRAMEBUFFER_GL_MIPLEVEL = 4869 RPR_FRAMEBUFFER_GL_TEXTURE = 4870 RPR_FRAMEBUFFER_LPE = 4871 RPR_FRAMEBUFFER_NAME = 7829367 RPR_FRAMEBUFFER_UNIQUE_ID = 7829368 RPR_FRAMEBUFFER_CUSTOM_PTR = 7829369 end @cenum rpr_component_type::UInt32 begin RPR_COMPONENT_TYPE_UINT8 = 1 RPR_COMPONENT_TYPE_FLOAT16 = 2 RPR_COMPONENT_TYPE_FLOAT32 = 3 RPR_COMPONENT_TYPE_UNKNOWN = 4 RPR_COMPONENT_TYPE_DEEP = 5 RPR_COMPONENT_TYPE_UINT32 = 6 end @cenum rpr_buffer_element_type::UInt32 begin RPR_BUFFER_ELEMENT_TYPE_INT32 = 1 RPR_BUFFER_ELEMENT_TYPE_FLOAT32 = 2 end @cenum rpr_render_mode::UInt32 begin RPR_RENDER_MODE_GLOBAL_ILLUMINATION = 1 RPR_RENDER_MODE_DIRECT_ILLUMINATION = 2 RPR_RENDER_MODE_DIRECT_ILLUMINATION_NO_SHADOW = 3 RPR_RENDER_MODE_WIREFRAME = 4 RPR_RENDER_MODE_MATERIAL_INDEX = 5 RPR_RENDER_MODE_POSITION = 6 RPR_RENDER_MODE_NORMAL = 7 RPR_RENDER_MODE_TEXCOORD = 8 RPR_RENDER_MODE_AMBIENT_OCCLUSION = 9 RPR_RENDER_MODE_DIFFUSE = 10 end @cenum rpr_camera_mode::UInt32 begin RPR_CAMERA_MODE_PERSPECTIVE = 1 RPR_CAMERA_MODE_ORTHOGRAPHIC = 2 RPR_CAMERA_MODE_LATITUDE_LONGITUDE_360 = 3 RPR_CAMERA_MODE_LATITUDE_LONGITUDE_STEREO = 4 RPR_CAMERA_MODE_CUBEMAP = 5 RPR_CAMERA_MODE_CUBEMAP_STEREO = 6 RPR_CAMERA_MODE_FISHEYE = 7 end @cenum rpr_tonemapping_operator::UInt32 begin RPR_TONEMAPPING_OPERATOR_NONE = 0 RPR_TONEMAPPING_OPERATOR_LINEAR = 1 RPR_TONEMAPPING_OPERATOR_PHOTOLINEAR = 2 RPR_TONEMAPPING_OPERATOR_AUTOLINEAR = 3 RPR_TONEMAPPING_OPERATOR_MAXWHITE = 4 RPR_TONEMAPPING_OPERATOR_REINHARD02 = 5 RPR_TONEMAPPING_OPERATOR_EXPONENTIAL = 6 end @cenum rpr_volume_type::UInt32 begin RPR_VOLUME_TYPE_NONE = 65535 RPR_VOLUME_TYPE_HOMOGENEOUS = 0 RPR_VOLUME_TYPE_HETEROGENEOUS = 1 end @cenum rpr_material_system_info::UInt32 begin RPR_MATERIAL_SYSTEM_NODE_LIST = 4352 end @cenum rpr_material_node_info::UInt32 begin RPR_MATERIAL_NODE_TYPE = 4353 RPR_MATERIAL_NODE_SYSTEM = 4354 RPR_MATERIAL_NODE_INPUT_COUNT = 4355 RPR_MATERIAL_NODE_ID = 4356 RPR_MATERIAL_NODE_NAME = 7829367 RPR_MATERIAL_NODE_UNIQUE_ID = 7829368 RPR_MATERIAL_CUSTOM_PTR = 7829369 end @cenum rpr_material_node_input_info::UInt32 begin RPR_MATERIAL_NODE_INPUT_NAME = 4355 RPR_MATERIAL_NODE_INPUT_DESCRIPTION = 4357 RPR_MATERIAL_NODE_INPUT_VALUE = 4358 RPR_MATERIAL_NODE_INPUT_TYPE = 4359 end @cenum rpr_material_node_type::UInt32 begin RPR_MATERIAL_NODE_DIFFUSE = 1 RPR_MATERIAL_NODE_MICROFACET = 2 RPR_MATERIAL_NODE_REFLECTION = 3 RPR_MATERIAL_NODE_REFRACTION = 4 RPR_MATERIAL_NODE_MICROFACET_REFRACTION = 5 RPR_MATERIAL_NODE_TRANSPARENT = 6 RPR_MATERIAL_NODE_EMISSIVE = 7 RPR_MATERIAL_NODE_WARD = 8 RPR_MATERIAL_NODE_ADD = 9 RPR_MATERIAL_NODE_BLEND = 10 RPR_MATERIAL_NODE_ARITHMETIC = 11 RPR_MATERIAL_NODE_FRESNEL = 12 RPR_MATERIAL_NODE_NORMAL_MAP = 13 RPR_MATERIAL_NODE_IMAGE_TEXTURE = 14 RPR_MATERIAL_NODE_NOISE2D_TEXTURE = 15 RPR_MATERIAL_NODE_DOT_TEXTURE = 16 RPR_MATERIAL_NODE_GRADIENT_TEXTURE = 17 RPR_MATERIAL_NODE_CHECKER_TEXTURE = 18 RPR_MATERIAL_NODE_CONSTANT_TEXTURE = 19 RPR_MATERIAL_NODE_INPUT_LOOKUP = 20 RPR_MATERIAL_NODE_BLEND_VALUE = 22 RPR_MATERIAL_NODE_PASSTHROUGH = 23 RPR_MATERIAL_NODE_ORENNAYAR = 24 RPR_MATERIAL_NODE_FRESNEL_SCHLICK = 25 RPR_MATERIAL_NODE_DIFFUSE_REFRACTION = 27 RPR_MATERIAL_NODE_BUMP_MAP = 28 RPR_MATERIAL_NODE_VOLUME = 29 RPR_MATERIAL_NODE_MICROFACET_ANISOTROPIC_REFLECTION = 30 RPR_MATERIAL_NODE_MICROFACET_ANISOTROPIC_REFRACTION = 31 RPR_MATERIAL_NODE_TWOSIDED = 32 RPR_MATERIAL_NODE_UV_PROCEDURAL = 33 RPR_MATERIAL_NODE_MICROFACET_BECKMANN = 34 RPR_MATERIAL_NODE_PHONG = 35 RPR_MATERIAL_NODE_BUFFER_SAMPLER = 36 RPR_MATERIAL_NODE_UV_TRIPLANAR = 37 RPR_MATERIAL_NODE_AO_MAP = 38 RPR_MATERIAL_NODE_USER_TEXTURE_0 = 39 RPR_MATERIAL_NODE_USER_TEXTURE_1 = 40 RPR_MATERIAL_NODE_USER_TEXTURE_2 = 41 RPR_MATERIAL_NODE_USER_TEXTURE_3 = 42 RPR_MATERIAL_NODE_UBERV2 = 43 RPR_MATERIAL_NODE_TRANSFORM = 44 RPR_MATERIAL_NODE_RGB_TO_HSV = 45 RPR_MATERIAL_NODE_HSV_TO_RGB = 46 RPR_MATERIAL_NODE_USER_TEXTURE = 47 RPR_MATERIAL_NODE_TOON_CLOSURE = 48 RPR_MATERIAL_NODE_TOON_RAMP = 49 RPR_MATERIAL_NODE_VORONOI_TEXTURE = 50 RPR_MATERIAL_NODE_GRID_SAMPLER = 51 RPR_MATERIAL_NODE_BLACKBODY = 52 RPR_MATERIAL_NODE_RAMP = 53 RPR_MATERIAL_NODE_PRIMVAR_LOOKUP = 54 RPR_MATERIAL_NODE_ROUNDED_CORNER = 55 RPR_MATERIAL_NODE_MATX_DIFFUSE_BRDF = 4096 RPR_MATERIAL_NODE_MATX_DIELECTRIC_BRDF = 4097 RPR_MATERIAL_NODE_MATX_GENERALIZED_SCHLICK_BRDF = 4098 RPR_MATERIAL_NODE_MATX_NOISE3D = 4099 RPR_MATERIAL_NODE_MATX_TANGENT = 4100 RPR_MATERIAL_NODE_MATX_NORMAL = 4101 RPR_MATERIAL_NODE_MATX_POSITION = 4102 RPR_MATERIAL_NODE_MATX_ROUGHNESS_ANISOTROPY = 4103 RPR_MATERIAL_NODE_MATX_ROTATE3D = 4104 RPR_MATERIAL_NODE_MATX_NORMALIZE = 4105 RPR_MATERIAL_NODE_MATX_IFGREATER = 4106 RPR_MATERIAL_NODE_MATX_SHEEN_BRDF = 4107 RPR_MATERIAL_NODE_MATX_DIFFUSE_BTDF = 4108 RPR_MATERIAL_NODE_MATX_CONVERT = 4109 RPR_MATERIAL_NODE_MATX_SUBSURFACE_BRDF = 4110 RPR_MATERIAL_NODE_MATX_DIELECTRIC_BTDF = 4111 RPR_MATERIAL_NODE_MATX_CONDUCTOR_BRDF = 4112 RPR_MATERIAL_NODE_MATX_FRESNEL = 4113 RPR_MATERIAL_NODE_MATX_LUMINANCE = 4114 RPR_MATERIAL_NODE_MATX_FRACTAL3D = 4115 RPR_MATERIAL_NODE_MATX_MIX = 4116 RPR_MATERIAL_NODE_MATX = 4117 RPR_MATERIAL_NODE_MATX_ARTISTIC_IOR = 4118 RPR_MATERIAL_NODE_MATX_GENERALIZED_SCHLICK_BTDF = 4119 RPR_MATERIAL_NODE_MATX_LAYER = 4120 RPR_MATERIAL_NODE_MATX_THIN_FILM = 4121 RPR_MATERIAL_NODE_MATX_BITANGENT = 4122 RPR_MATERIAL_NODE_MATX_TEXCOORD = 4123 RPR_MATERIAL_NODE_MATX_MODULO = 4124 RPR_MATERIAL_NODE_MATX_ABSVAL = 4125 RPR_MATERIAL_NODE_MATX_SIGN = 4126 RPR_MATERIAL_NODE_MATX_FLOOR = 4127 RPR_MATERIAL_NODE_MATX_CEIL = 4128 RPR_MATERIAL_NODE_MATX_ATAN2 = 4129 RPR_MATERIAL_NODE_MATX_SQRT = 4130 RPR_MATERIAL_NODE_MATX_LN = 4131 RPR_MATERIAL_NODE_MATX_EXP = 4132 RPR_MATERIAL_NODE_MATX_CLAMP = 4133 RPR_MATERIAL_NODE_MATX_MIN = 4134 RPR_MATERIAL_NODE_MATX_MAX = 4135 RPR_MATERIAL_NODE_MATX_MAGNITUDE = 4136 RPR_MATERIAL_NODE_MATX_CROSSPRODUCT = 4137 RPR_MATERIAL_NODE_MATX_REMAP = 4138 RPR_MATERIAL_NODE_MATX_SMOOTHSTEP = 4139 RPR_MATERIAL_NODE_MATX_RGBTOHSV = 4140 RPR_MATERIAL_NODE_MATX_HSVTORGB = 4141 RPR_MATERIAL_NODE_MATX_IFGREATEREQ = 4142 RPR_MATERIAL_NODE_MATX_IFEQUAL = 4143 RPR_MATERIAL_NODE_MATX_SWIZZLE = 4144 RPR_MATERIAL_NODE_MATX_NOISE2D = 4145 RPR_MATERIAL_NODE_MATX_PLUS = 4146 RPR_MATERIAL_NODE_MATX_MINUS = 4147 RPR_MATERIAL_NODE_MATX_DIFFERENCE = 4148 RPR_MATERIAL_NODE_MATX_BURN = 4149 RPR_MATERIAL_NODE_MATX_DODGE = 4150 RPR_MATERIAL_NODE_MATX_SCREEN = 4151 RPR_MATERIAL_NODE_MATX_OVERLAY = 4152 RPR_MATERIAL_NODE_MATX_INSIDE = 4153 RPR_MATERIAL_NODE_MATX_OUTSIDE = 4154 RPR_MATERIAL_NODE_MATX_RAMPLR = 4155 RPR_MATERIAL_NODE_MATX_RAMPTB = 4156 RPR_MATERIAL_NODE_MATX_SPLITLR = 4157 RPR_MATERIAL_NODE_MATX_SPLITTB = 4158 RPR_MATERIAL_NODE_MATX_CELLNOISE2D = 4159 RPR_MATERIAL_NODE_MATX_CELLNOISE3D = 4160 RPR_MATERIAL_NODE_MATX_ROTATE2D = 4161 RPR_MATERIAL_NODE_MATX_DOT = 4162 RPR_MATERIAL_NODE_MATX_RANGE = 4163 RPR_MATERIAL_NODE_MATX_SWITCH = 4164 RPR_MATERIAL_NODE_MATX_EXTRACT = 4165 RPR_MATERIAL_NODE_MATX_COMBINE2 = 4166 RPR_MATERIAL_NODE_MATX_COMBINE3 = 4167 RPR_MATERIAL_NODE_MATX_COMBINE4 = 4168 RPR_MATERIAL_NODE_MATX_TRIPLANARPROJECTION = 4169 RPR_MATERIAL_NODE_MATX_MULTIPLY = 4170 end @cenum rpr_material_node_input::UInt32 begin RPR_MATERIAL_INPUT_COLOR = 0 RPR_MATERIAL_INPUT_COLOR0 = 1 RPR_MATERIAL_INPUT_COLOR1 = 2 RPR_MATERIAL_INPUT_NORMAL = 3 RPR_MATERIAL_INPUT_UV = 4 RPR_MATERIAL_INPUT_DATA = 5 RPR_MATERIAL_INPUT_ROUGHNESS = 6 RPR_MATERIAL_INPUT_IOR = 7 RPR_MATERIAL_INPUT_ROUGHNESS_X = 8 RPR_MATERIAL_INPUT_ROUGHNESS_Y = 9 RPR_MATERIAL_INPUT_ROTATION = 10 RPR_MATERIAL_INPUT_WEIGHT = 11 RPR_MATERIAL_INPUT_OP = 12 RPR_MATERIAL_INPUT_INVEC = 13 RPR_MATERIAL_INPUT_UV_SCALE = 14 RPR_MATERIAL_INPUT_VALUE = 15 RPR_MATERIAL_INPUT_REFLECTANCE = 16 RPR_MATERIAL_INPUT_SCALE = 17 RPR_MATERIAL_INPUT_SCATTERING = 18 RPR_MATERIAL_INPUT_ABSORBTION = 19 RPR_MATERIAL_INPUT_EMISSION = 20 RPR_MATERIAL_INPUT_G = 21 RPR_MATERIAL_INPUT_MULTISCATTER = 22 RPR_MATERIAL_INPUT_COLOR2 = 23 RPR_MATERIAL_INPUT_COLOR3 = 24 RPR_MATERIAL_INPUT_ANISOTROPIC = 25 RPR_MATERIAL_INPUT_FRONTFACE = 26 RPR_MATERIAL_INPUT_BACKFACE = 27 RPR_MATERIAL_INPUT_ORIGIN = 28 RPR_MATERIAL_INPUT_ZAXIS = 29 RPR_MATERIAL_INPUT_XAXIS = 30 RPR_MATERIAL_INPUT_THRESHOLD = 31 RPR_MATERIAL_INPUT_OFFSET = 32 RPR_MATERIAL_INPUT_UV_TYPE = 33 RPR_MATERIAL_INPUT_RADIUS = 34 RPR_MATERIAL_INPUT_SIDE = 35 RPR_MATERIAL_INPUT_CAUSTICS = 36 RPR_MATERIAL_INPUT_TRANSMISSION_COLOR = 37 RPR_MATERIAL_INPUT_THICKNESS = 38 RPR_MATERIAL_INPUT_0 = 39 RPR_MATERIAL_INPUT_1 = 40 RPR_MATERIAL_INPUT_2 = 41 RPR_MATERIAL_INPUT_3 = 42 RPR_MATERIAL_INPUT_4 = 43 RPR_MATERIAL_INPUT_SCHLICK_APPROXIMATION = 44 RPR_MATERIAL_INPUT_APPLYSURFACE = 45 RPR_MATERIAL_INPUT_TANGENT = 46 RPR_MATERIAL_INPUT_DISTRIBUTION = 47 RPR_MATERIAL_INPUT_BASE = 48 RPR_MATERIAL_INPUT_TINT = 49 RPR_MATERIAL_INPUT_EXPONENT = 50 RPR_MATERIAL_INPUT_AMPLITUDE = 51 RPR_MATERIAL_INPUT_PIVOT = 52 RPR_MATERIAL_INPUT_POSITION = 53 RPR_MATERIAL_INPUT_AMOUNT = 54 RPR_MATERIAL_INPUT_AXIS = 55 RPR_MATERIAL_INPUT_LUMACOEFF = 56 RPR_MATERIAL_INPUT_REFLECTIVITY = 57 RPR_MATERIAL_INPUT_EDGE_COLOR = 58 RPR_MATERIAL_INPUT_VIEW_DIRECTION = 59 RPR_MATERIAL_INPUT_INTERIOR = 60 RPR_MATERIAL_INPUT_OCTAVES = 61 RPR_MATERIAL_INPUT_LACUNARITY = 62 RPR_MATERIAL_INPUT_DIMINISH = 63 RPR_MATERIAL_INPUT_WRAP_U = 64 RPR_MATERIAL_INPUT_WRAP_V = 65 RPR_MATERIAL_INPUT_WRAP_W = 66 RPR_MATERIAL_INPUT_5 = 67 RPR_MATERIAL_INPUT_6 = 68 RPR_MATERIAL_INPUT_7 = 69 RPR_MATERIAL_INPUT_8 = 70 RPR_MATERIAL_INPUT_9 = 71 RPR_MATERIAL_INPUT_10 = 72 RPR_MATERIAL_INPUT_11 = 73 RPR_MATERIAL_INPUT_12 = 74 RPR_MATERIAL_INPUT_13 = 75 RPR_MATERIAL_INPUT_14 = 76 RPR_MATERIAL_INPUT_15 = 77 RPR_MATERIAL_INPUT_DIFFUSE_RAMP = 78 RPR_MATERIAL_INPUT_SHADOW = 79 RPR_MATERIAL_INPUT_MID = 80 RPR_MATERIAL_INPUT_HIGHLIGHT = 81 RPR_MATERIAL_INPUT_POSITION1 = 82 RPR_MATERIAL_INPUT_POSITION2 = 83 RPR_MATERIAL_INPUT_RANGE1 = 84 RPR_MATERIAL_INPUT_RANGE2 = 85 RPR_MATERIAL_INPUT_INTERPOLATION = 86 RPR_MATERIAL_INPUT_RANDOMNESS = 87 RPR_MATERIAL_INPUT_DIMENSION = 88 RPR_MATERIAL_INPUT_OUTTYPE = 89 RPR_MATERIAL_INPUT_DENSITY = 90 RPR_MATERIAL_INPUT_DENSITYGRID = 91 RPR_MATERIAL_INPUT_DISPLACEMENT = 92 RPR_MATERIAL_INPUT_TEMPERATURE = 93 RPR_MATERIAL_INPUT_KELVIN = 94 RPR_MATERIAL_INPUT_EXTINCTION = 95 RPR_MATERIAL_INPUT_THIN_FILM = 96 RPR_MATERIAL_INPUT_TOP = 97 RPR_MATERIAL_INPUT_HIGHLIGHT2 = 98 RPR_MATERIAL_INPUT_SHADOW2 = 99 RPR_MATERIAL_INPUT_POSITION_SHADOW = 100 RPR_MATERIAL_INPUT_POSITION_HIGHLIGHT = 101 RPR_MATERIAL_INPUT_RANGE_SHADOW = 102 RPR_MATERIAL_INPUT_RANGE_HIGHLIGHT = 103 RPR_MATERIAL_INPUT_TOON_5_COLORS = 104 RPR_MATERIAL_INPUT_X = 105 RPR_MATERIAL_INPUT_Y = 106 RPR_MATERIAL_INPUT_Z = 107 RPR_MATERIAL_INPUT_W = 108 RPR_MATERIAL_INPUT_LIGHT = 109 RPR_MATERIAL_INPUT_MID_IS_ALBEDO = 110 RPR_MATERIAL_INPUT_SAMPLES = 111 RPR_MATERIAL_INPUT_BASE_NORMAL = 112 RPR_MATERIAL_INPUT_UBER_DIFFUSE_COLOR = 2320 RPR_MATERIAL_INPUT_UBER_DIFFUSE_WEIGHT = 2343 RPR_MATERIAL_INPUT_UBER_DIFFUSE_ROUGHNESS = 2321 RPR_MATERIAL_INPUT_UBER_DIFFUSE_NORMAL = 2322 RPR_MATERIAL_INPUT_UBER_REFLECTION_COLOR = 2323 RPR_MATERIAL_INPUT_UBER_REFLECTION_WEIGHT = 2344 RPR_MATERIAL_INPUT_UBER_REFLECTION_ROUGHNESS = 2324 RPR_MATERIAL_INPUT_UBER_REFLECTION_ANISOTROPY = 2325 RPR_MATERIAL_INPUT_UBER_REFLECTION_ANISOTROPY_ROTATION = 2326 RPR_MATERIAL_INPUT_UBER_REFLECTION_MODE = 2327 RPR_MATERIAL_INPUT_UBER_REFLECTION_IOR = 2328 RPR_MATERIAL_INPUT_UBER_REFLECTION_METALNESS = 2329 RPR_MATERIAL_INPUT_UBER_REFLECTION_NORMAL = 2345 RPR_MATERIAL_INPUT_UBER_REFLECTION_DIELECTRIC_REFLECTANCE = 2366 RPR_MATERIAL_INPUT_UBER_REFRACTION_COLOR = 2330 RPR_MATERIAL_INPUT_UBER_REFRACTION_WEIGHT = 2346 RPR_MATERIAL_INPUT_UBER_REFRACTION_ROUGHNESS = 2331 RPR_MATERIAL_INPUT_UBER_REFRACTION_IOR = 2332 RPR_MATERIAL_INPUT_UBER_REFRACTION_NORMAL = 2347 RPR_MATERIAL_INPUT_UBER_REFRACTION_THIN_SURFACE = 2333 RPR_MATERIAL_INPUT_UBER_REFRACTION_ABSORPTION_COLOR = 2348 RPR_MATERIAL_INPUT_UBER_REFRACTION_ABSORPTION_DISTANCE = 2349 RPR_MATERIAL_INPUT_UBER_REFRACTION_CAUSTICS = 2350 RPR_MATERIAL_INPUT_UBER_COATING_COLOR = 2334 RPR_MATERIAL_INPUT_UBER_COATING_WEIGHT = 2351 RPR_MATERIAL_INPUT_UBER_COATING_ROUGHNESS = 2335 RPR_MATERIAL_INPUT_UBER_COATING_MODE = 2336 RPR_MATERIAL_INPUT_UBER_COATING_IOR = 2337 RPR_MATERIAL_INPUT_UBER_COATING_METALNESS = 2338 RPR_MATERIAL_INPUT_UBER_COATING_NORMAL = 2339 RPR_MATERIAL_INPUT_UBER_COATING_TRANSMISSION_COLOR = 2352 RPR_MATERIAL_INPUT_UBER_COATING_THICKNESS = 2353 RPR_MATERIAL_INPUT_UBER_SHEEN = 2354 RPR_MATERIAL_INPUT_UBER_SHEEN_TINT = 2355 RPR_MATERIAL_INPUT_UBER_SHEEN_WEIGHT = 2356 RPR_MATERIAL_INPUT_UBER_EMISSION_COLOR = 2340 RPR_MATERIAL_INPUT_UBER_EMISSION_WEIGHT = 2341 RPR_MATERIAL_INPUT_UBER_EMISSION_MODE = 2357 RPR_MATERIAL_INPUT_UBER_TRANSPARENCY = 2342 RPR_MATERIAL_INPUT_UBER_SSS_SCATTER_COLOR = 2359 RPR_MATERIAL_INPUT_UBER_SSS_SCATTER_DISTANCE = 2360 RPR_MATERIAL_INPUT_UBER_SSS_SCATTER_DIRECTION = 2361 RPR_MATERIAL_INPUT_UBER_SSS_WEIGHT = 2362 RPR_MATERIAL_INPUT_UBER_SSS_MULTISCATTER = 2363 RPR_MATERIAL_INPUT_UBER_BACKSCATTER_WEIGHT = 2364 RPR_MATERIAL_INPUT_UBER_BACKSCATTER_COLOR = 2365 RPR_MATERIAL_INPUT_ADDRESS = 2366 RPR_MATERIAL_INPUT_TYPE = 2367 RPR_MATERIAL_INPUT_UBER_FRESNEL_SCHLICK_APPROXIMATION = 44 end @cenum rpr_material_input_raster::UInt32 begin RPR_MATERIAL_INPUT_RASTER_METALLIC = 2305 RPR_MATERIAL_INPUT_RASTER_ROUGHNESS = 2306 RPR_MATERIAL_INPUT_RASTER_SUBSURFACE = 2307 RPR_MATERIAL_INPUT_RASTER_ANISOTROPIC = 2308 RPR_MATERIAL_INPUT_RASTER_SPECULAR = 2309 RPR_MATERIAL_INPUT_RASTER_SPECULARTINT = 2310 RPR_MATERIAL_INPUT_RASTER_SHEEN = 2311 RPR_MATERIAL_INPUT_RASTER_SHEENTINT = 2312 RPR_MATERIAL_INPUT_RASTER_CLEARCOAT = 2314 RPR_MATERIAL_INPUT_RASTER_CLEARCOATGLOSS = 2315 RPR_MATERIAL_INPUT_RASTER_COLOR = 2316 RPR_MATERIAL_INPUT_RASTER_NORMAL = 2317 end @cenum rpr_interpolation_mode::UInt32 begin RPR_INTERPOLATION_MODE_NONE = 0 RPR_INTERPOLATION_MODE_LINEAR = 1 RPR_INTERPOLATION_MODE_EXPONENTIAL_UP = 2 RPR_INTERPOLATION_MODE_EXPONENTIAL_DOWN = 3 RPR_INTERPOLATION_MODE_SMOOTH = 4 RPR_INTERPOLATION_MODE_BUMP = 5 RPR_INTERPOLATION_MODE_SPIKE = 6 end @cenum rpr_ubermaterial_ior_mode::UInt32 begin RPR_UBER_MATERIAL_IOR_MODE_PBR = 1 RPR_UBER_MATERIAL_IOR_MODE_METALNESS = 2 end @cenum rpr_ubermaterial_emission_mode::UInt32 begin RPR_UBER_MATERIAL_EMISSION_MODE_SINGLESIDED = 1 RPR_UBER_MATERIAL_EMISSION_MODE_DOUBLESIDED = 2 end @cenum rpr_material_node_arithmetic_operation::UInt32 begin RPR_MATERIAL_NODE_OP_ADD = 0 RPR_MATERIAL_NODE_OP_SUB = 1 RPR_MATERIAL_NODE_OP_MUL = 2 RPR_MATERIAL_NODE_OP_DIV = 3 RPR_MATERIAL_NODE_OP_SIN = 4 RPR_MATERIAL_NODE_OP_COS = 5 RPR_MATERIAL_NODE_OP_TAN = 6 RPR_MATERIAL_NODE_OP_SELECT_X = 7 RPR_MATERIAL_NODE_OP_SELECT_Y = 8 RPR_MATERIAL_NODE_OP_SELECT_Z = 9 RPR_MATERIAL_NODE_OP_COMBINE = 10 RPR_MATERIAL_NODE_OP_DOT3 = 11 RPR_MATERIAL_NODE_OP_CROSS3 = 12 RPR_MATERIAL_NODE_OP_LENGTH3 = 13 RPR_MATERIAL_NODE_OP_NORMALIZE3 = 14 RPR_MATERIAL_NODE_OP_POW = 15 RPR_MATERIAL_NODE_OP_ACOS = 16 RPR_MATERIAL_NODE_OP_ASIN = 17 RPR_MATERIAL_NODE_OP_ATAN = 18 RPR_MATERIAL_NODE_OP_AVERAGE_XYZ = 19 RPR_MATERIAL_NODE_OP_AVERAGE = 20 RPR_MATERIAL_NODE_OP_MIN = 21 RPR_MATERIAL_NODE_OP_MAX = 22 RPR_MATERIAL_NODE_OP_FLOOR = 23 RPR_MATERIAL_NODE_OP_MOD = 24 RPR_MATERIAL_NODE_OP_ABS = 25 RPR_MATERIAL_NODE_OP_SHUFFLE_YZWX = 26 RPR_MATERIAL_NODE_OP_SHUFFLE_ZWXY = 27 RPR_MATERIAL_NODE_OP_SHUFFLE_WXYZ = 28 RPR_MATERIAL_NODE_OP_MAT_MUL = 29 RPR_MATERIAL_NODE_OP_SELECT_W = 30 RPR_MATERIAL_NODE_OP_DOT4 = 31 RPR_MATERIAL_NODE_OP_LOG = 32 RPR_MATERIAL_NODE_OP_LOWER_OR_EQUAL = 33 RPR_MATERIAL_NODE_OP_LOWER = 34 RPR_MATERIAL_NODE_OP_GREATER_OR_EQUAL = 35 RPR_MATERIAL_NODE_OP_GREATER = 36 RPR_MATERIAL_NODE_OP_EQUAL = 37 RPR_MATERIAL_NODE_OP_NOT_EQUAL = 38 RPR_MATERIAL_NODE_OP_AND = 39 RPR_MATERIAL_NODE_OP_OR = 40 RPR_MATERIAL_NODE_OP_TERNARY = 41 RPR_MATERIAL_NODE_OP_EXP = 42 RPR_MATERIAL_NODE_OP_ROTATE2D = 43 RPR_MATERIAL_NODE_OP_ROTATE3D = 44 RPR_MATERIAL_NODE_OP_NOP = 45 RPR_MATERIAL_NODE_OP_CEIL = 4138 RPR_MATERIAL_NODE_OP_ROUND = 4139 RPR_MATERIAL_NODE_OP_SIGN = 4140 RPR_MATERIAL_NODE_OP_SQRT = 4143 RPR_MATERIAL_NODE_OP_CLAMP = 4149 end @cenum rpr_material_node_lookup_value::UInt32 begin RPR_MATERIAL_NODE_LOOKUP_UV = 0 RPR_MATERIAL_NODE_LOOKUP_N = 1 RPR_MATERIAL_NODE_LOOKUP_P = 2 RPR_MATERIAL_NODE_LOOKUP_INVEC = 3 RPR_MATERIAL_NODE_LOOKUP_OUTVEC = 4 RPR_MATERIAL_NODE_LOOKUP_UV1 = 5 RPR_MATERIAL_NODE_LOOKUP_P_LOCAL = 6 RPR_MATERIAL_NODE_LOOKUP_VERTEX_VALUE0 = 7 RPR_MATERIAL_NODE_LOOKUP_VERTEX_VALUE1 = 8 RPR_MATERIAL_NODE_LOOKUP_VERTEX_VALUE2 = 9 RPR_MATERIAL_NODE_LOOKUP_VERTEX_VALUE3 = 10 RPR_MATERIAL_NODE_LOOKUP_SHAPE_RANDOM_COLOR = 11 RPR_MATERIAL_NODE_LOOKUP_OBJECT_ID = 12 RPR_MATERIAL_NODE_LOOKUP_PRIMITIVE_RANDOM_COLOR = 13 end @cenum rpr_material_gradient_procedural_type::UInt32 begin RPR_MATERIAL_GRADIENT_PROCEDURAL_TYPE_LINEAR = 1 RPR_MATERIAL_GRADIENT_PROCEDURAL_TYPE_QUADRATIC = 2 RPR_MATERIAL_GRADIENT_PROCEDURAL_TYPE_EASING = 3 RPR_MATERIAL_GRADIENT_PROCEDURAL_TYPE_DIAGONAL = 4 RPR_MATERIAL_GRADIENT_PROCEDURAL_TYPE_SPHERICAL = 5 RPR_MATERIAL_GRADIENT_PROCEDURAL_TYPE_QUAD_SPHERE = 6 RPR_MATERIAL_GRADIENT_PROCEDURAL_TYPE_RADIAL = 7 end @cenum rpr_material_node_uvtype_value::UInt32 begin RPR_MATERIAL_NODE_UVTYPE_PLANAR = 0 RPR_MATERIAL_NODE_UVTYPE_CYLINDICAL = 1 RPR_MATERIAL_NODE_UVTYPE_SPHERICAL = 2 RPR_MATERIAL_NODE_UVTYPE_PROJECT = 3 end @cenum rpr_material_node_transform_op::UInt32 begin RPR_MATERIAL_NODE_TRANSFORM_ROTATE_LOCAL_TO_WORLD = 1 end @cenum rpr_post_effect_info::UInt32 begin RPR_POST_EFFECT_TYPE = 0 RPR_POST_EFFECT_WHITE_BALANCE_COLOR_SPACE = 4 RPR_POST_EFFECT_WHITE_BALANCE_COLOR_TEMPERATURE = 5 RPR_POST_EFFECT_SIMPLE_TONEMAP_EXPOSURE = 6 RPR_POST_EFFECT_SIMPLE_TONEMAP_CONTRAST = 7 RPR_POST_EFFECT_SIMPLE_TONEMAP_ENABLE_TONEMAP = 8 RPR_POST_EFFECT_BLOOM_RADIUS = 9 RPR_POST_EFFECT_BLOOM_THRESHOLD = 10 RPR_POST_EFFECT_BLOOM_WEIGHT = 11 RPR_POST_EFFECT_NAME = 7829367 RPR_POST_EFFECT_UNIQUE_ID = 7829368 RPR_POST_EFFECT_CUSTOM_PTR = 7829369 end @cenum rpr_aov::UInt32 begin RPR_AOV_COLOR = 0 RPR_AOV_OPACITY = 1 RPR_AOV_WORLD_COORDINATE = 2 RPR_AOV_UV = 3 RPR_AOV_MATERIAL_ID = 4 RPR_AOV_GEOMETRIC_NORMAL = 5 RPR_AOV_SHADING_NORMAL = 6 RPR_AOV_DEPTH = 7 RPR_AOV_OBJECT_ID = 8 RPR_AOV_OBJECT_GROUP_ID = 9 RPR_AOV_SHADOW_CATCHER = 10 RPR_AOV_BACKGROUND = 11 RPR_AOV_EMISSION = 12 RPR_AOV_VELOCITY = 13 RPR_AOV_DIRECT_ILLUMINATION = 14 RPR_AOV_INDIRECT_ILLUMINATION = 15 RPR_AOV_AO = 16 RPR_AOV_DIRECT_DIFFUSE = 17 RPR_AOV_DIRECT_REFLECT = 18 RPR_AOV_INDIRECT_DIFFUSE = 19 RPR_AOV_INDIRECT_REFLECT = 20 RPR_AOV_REFRACT = 21 RPR_AOV_VOLUME = 22 RPR_AOV_LIGHT_GROUP0 = 23 RPR_AOV_LIGHT_GROUP1 = 24 RPR_AOV_LIGHT_GROUP2 = 25 RPR_AOV_LIGHT_GROUP3 = 26 RPR_AOV_DIFFUSE_ALBEDO = 27 RPR_AOV_VARIANCE = 28 RPR_AOV_VIEW_SHADING_NORMAL = 29 RPR_AOV_REFLECTION_CATCHER = 30 RPR_AOV_COLOR_RIGHT = 31 RPR_AOV_LPE_0 = 32 RPR_AOV_LPE_1 = 33 RPR_AOV_LPE_2 = 34 RPR_AOV_LPE_3 = 35 RPR_AOV_LPE_4 = 36 RPR_AOV_LPE_5 = 37 RPR_AOV_LPE_6 = 38 RPR_AOV_LPE_7 = 39 RPR_AOV_LPE_8 = 40 RPR_AOV_CAMERA_NORMAL = 41 RPR_AOV_MATTE_PASS = 42 RPR_AOV_SSS = 43 RPR_AOV_CRYPTOMATTE_MAT0 = 48 RPR_AOV_CRYPTOMATTE_MAT1 = 49 RPR_AOV_CRYPTOMATTE_MAT2 = 50 RPR_AOV_CRYPTOMATTE_MAT3 = 51 RPR_AOV_CRYPTOMATTE_MAT4 = 52 RPR_AOV_CRYPTOMATTE_MAT5 = 53 RPR_AOV_CRYPTOMATTE_OBJ0 = 56 RPR_AOV_CRYPTOMATTE_OBJ1 = 57 RPR_AOV_CRYPTOMATTE_OBJ2 = 58 RPR_AOV_CRYPTOMATTE_OBJ3 = 59 RPR_AOV_CRYPTOMATTE_OBJ4 = 60 RPR_AOV_CRYPTOMATTE_OBJ5 = 61 RPR_AOV_DEEP_COLOR = 64 RPR_AOV_LIGHT_GROUP4 = 80 RPR_AOV_LIGHT_GROUP5 = 81 RPR_AOV_LIGHT_GROUP6 = 82 RPR_AOV_LIGHT_GROUP7 = 83 RPR_AOV_LIGHT_GROUP8 = 84 RPR_AOV_LIGHT_GROUP9 = 85 RPR_AOV_LIGHT_GROUP10 = 86 RPR_AOV_LIGHT_GROUP11 = 87 RPR_AOV_LIGHT_GROUP12 = 88 RPR_AOV_LIGHT_GROUP13 = 89 RPR_AOV_LIGHT_GROUP14 = 90 RPR_AOV_LIGHT_GROUP15 = 91 RPR_AOV_MESH_ID = 96 end @cenum rpr_post_effect_type::UInt32 begin RPR_POST_EFFECT_TONE_MAP = 0 RPR_POST_EFFECT_WHITE_BALANCE = 1 RPR_POST_EFFECT_SIMPLE_TONEMAP = 2 RPR_POST_EFFECT_NORMALIZATION = 3 RPR_POST_EFFECT_GAMMA_CORRECTION = 4 RPR_POST_EFFECT_BLOOM = 5 end @cenum rpr_color_space::UInt32 begin RPR_COLOR_SPACE_SRGB = 1 RPR_COLOR_SPACE_ADOBE_RGB = 2 RPR_COLOR_SPACE_REC2020 = 3 RPR_COLOR_SPACE_DCIP3 = 4 end @cenum rpr_material_node_input_type::UInt32 begin RPR_MATERIAL_NODE_INPUT_TYPE_FLOAT4 = 1 RPR_MATERIAL_NODE_INPUT_TYPE_UINT = 2 RPR_MATERIAL_NODE_INPUT_TYPE_NODE = 3 RPR_MATERIAL_NODE_INPUT_TYPE_IMAGE = 4 RPR_MATERIAL_NODE_INPUT_TYPE_BUFFER = 5 RPR_MATERIAL_NODE_INPUT_TYPE_GRID = 6 RPR_MATERIAL_NODE_INPUT_TYPE_DATA = 7 RPR_MATERIAL_NODE_INPUT_TYPE_LIGHT = 8 end @cenum rpr_subdiv_boundary_interfop_type::UInt32 begin RPR_SUBDIV_BOUNDARY_INTERFOP_TYPE_EDGE_AND_CORNER = 1 RPR_SUBDIV_BOUNDARY_INTERFOP_TYPE_EDGE_ONLY = 2 end @cenum rpr_image_wrap_type::UInt32 begin RPR_IMAGE_WRAP_TYPE_REPEAT = 1 RPR_IMAGE_WRAP_TYPE_MIRRORED_REPEAT = 2 RPR_IMAGE_WRAP_TYPE_CLAMP_TO_EDGE = 3 RPR_IMAGE_WRAP_TYPE_CLAMP_ZERO = 5 RPR_IMAGE_WRAP_TYPE_CLAMP_ONE = 6 end @cenum rpr_voronoi_out_type::UInt32 begin RPR_VORONOI_OUT_TYPE_DISTANCE = 1 RPR_VORONOI_OUT_TYPE_COLOR = 2 RPR_VORONOI_OUT_TYPE_POSITION = 3 end @cenum rpr_image_filter_type::UInt32 begin RPR_IMAGE_FILTER_TYPE_NEAREST = 1 RPR_IMAGE_FILTER_TYPE_LINEAR = 2 end @cenum rpr_composite_info::UInt32 begin RPR_COMPOSITE_TYPE = 1 RPR_COMPOSITE_FRAMEBUFFER_INPUT_FB = 2 RPR_COMPOSITE_NORMALIZE_INPUT_COLOR = 3 RPR_COMPOSITE_NORMALIZE_INPUT_AOVTYPE = 4 RPR_COMPOSITE_CONSTANT_INPUT_VALUE = 5 RPR_COMPOSITE_LERP_VALUE_INPUT_COLOR0 = 6 RPR_COMPOSITE_LERP_VALUE_INPUT_COLOR1 = 7 RPR_COMPOSITE_LERP_VALUE_INPUT_WEIGHT = 8 RPR_COMPOSITE_ARITHMETIC_INPUT_COLOR0 = 9 RPR_COMPOSITE_ARITHMETIC_INPUT_COLOR1 = 10 RPR_COMPOSITE_ARITHMETIC_INPUT_OP = 11 RPR_COMPOSITE_GAMMA_CORRECTION_INPUT_COLOR = 12 RPR_COMPOSITE_LUT_INPUT_LUT = 13 RPR_COMPOSITE_LUT_INPUT_COLOR = 14 RPR_COMPOSITE_NAME = 7829367 RPR_COMPOSITE_UNIQUE_ID = 7829368 RPR_COMPOSITE_CUSTOM_PTR = 7829369 end @cenum rpr_composite_type::UInt32 begin RPR_COMPOSITE_ARITHMETIC = 1 RPR_COMPOSITE_LERP_VALUE = 2 RPR_COMPOSITE_INVERSE = 3 RPR_COMPOSITE_NORMALIZE = 4 RPR_COMPOSITE_GAMMA_CORRECTION = 5 RPR_COMPOSITE_EXPOSURE = 6 RPR_COMPOSITE_CONTRAST = 7 RPR_COMPOSITE_SIDE_BY_SIDE = 8 RPR_COMPOSITE_TONEMAP_ACES = 9 RPR_COMPOSITE_TONEMAP_REINHARD = 10 RPR_COMPOSITE_TONEMAP_LINEAR = 11 RPR_COMPOSITE_FRAMEBUFFER = 12 RPR_COMPOSITE_CONSTANT = 13 RPR_COMPOSITE_LUT = 14 end @cenum rpr_grid_parameter::UInt32 begin RPR_GRID_SIZE_X = 2352 RPR_GRID_SIZE_Y = 2353 RPR_GRID_SIZE_Z = 2354 RPR_GRID_DATA = 2355 RPR_GRID_DATA_SIZEBYTE = 2356 RPR_GRID_INDICES = 2358 RPR_GRID_INDICES_NUMBER = 2359 RPR_GRID_INDICES_TOPOLOGY = 2360 RPR_GRID_NAME = 7829367 RPR_GRID_UNIQUE_ID = 7829368 RPR_GRID_CUSTOM_PTR = 7829369 end @cenum rpr_hetero_volume_parameter::UInt32 begin RPR_HETEROVOLUME_TRANSFORM = 1845 RPR_HETEROVOLUME_ALBEDO_V2 = 1852 RPR_HETEROVOLUME_DENSITY_V2 = 1853 RPR_HETEROVOLUME_EMISSION_V2 = 1854 RPR_HETEROVOLUME_ALBEDO_LOOKUP_VALUES = 1855 RPR_HETEROVOLUME_ALBEDO_LOOKUP_VALUES_COUNT = 1856 RPR_HETEROVOLUME_DENSITY_LOOKUP_VALUES = 1857 RPR_HETEROVOLUME_DENSITY_LOOKUP_VALUES_COUNT = 1858 RPR_HETEROVOLUME_EMISSION_LOOKUP_VALUES = 1859 RPR_HETEROVOLUME_EMISSION_LOOKUP_VALUES_COUNT = 1860 RPR_HETEROVOLUME_ALBEDO_SCALE = 1861 RPR_HETEROVOLUME_DENSITY_SCALE = 1862 RPR_HETEROVOLUME_EMISSION_SCALE = 1863 RPR_HETEROVOLUME_NAME = 7829367 RPR_HETEROVOLUME_UNIQUE_ID = 7829368 RPR_HETEROVOLUME_CUSTOM_PTR = 7829369 end @cenum rpr_grid_indices_topology::UInt32 begin RPR_GRID_INDICES_TOPOLOGY_I_U64 = 2384 RPR_GRID_INDICES_TOPOLOGY_XYZ_U32 = 2385 RPR_GRID_INDICES_TOPOLOGY_I_S64 = 2386 RPR_GRID_INDICES_TOPOLOGY_XYZ_S32 = 2387 end @cenum rpr_curve_parameter::UInt32 begin RPR_CURVE_CONTROLPOINTS_COUNT = 2096 RPR_CURVE_CONTROLPOINTS_DATA = 2097 RPR_CURVE_CONTROLPOINTS_STRIDE = 2098 RPR_CURVE_INDICES_COUNT = 2099 RPR_CURVE_INDICES_DATA = 2100 RPR_CURVE_RADIUS = 2101 RPR_CURVE_UV = 2102 RPR_CURVE_COUNT_CURVE = 2103 RPR_CURVE_SEGMENTS_PER_CURVE = 2104 RPR_CURVE_CREATION_FLAG = 2105 RPR_CURVE_NAME = 7829367 RPR_CURVE_UNIQUE_ID = 7829368 RPR_CURVE_CUSTOM_PTR = 7829369 RPR_CURVE_TRANSFORM = 1027 RPR_CURVE_MATERIAL = 1028 RPR_CURVE_VISIBILITY_PRIMARY_ONLY_FLAG = 1036 RPR_CURVE_VISIBILITY_SHADOW = 1050 RPR_CURVE_VISIBILITY_REFLECTION = 1051 RPR_CURVE_VISIBILITY_REFRACTION = 1052 RPR_CURVE_VISIBILITY_TRANSPARENT = 1053 RPR_CURVE_VISIBILITY_DIFFUSE = 1054 RPR_CURVE_VISIBILITY_GLOSSY_REFLECTION = 1055 RPR_CURVE_VISIBILITY_GLOSSY_REFRACTION = 1056 RPR_CURVE_VISIBILITY_LIGHT = 1057 RPR_CURVE_VISIBILITY_RECEIVE_SHADOW = 1072 end struct rpr_image_desc image_width::rpr_uint image_height::rpr_uint image_depth::rpr_uint image_row_pitch::rpr_uint image_slice_pitch::rpr_uint end struct rpr_buffer_desc nb_element::rpr_uint element_type::rpr_buffer_element_type element_channel_size::rpr_uint end struct rpr_framebuffer_desc fb_width::rpr_uint fb_height::rpr_uint end struct rpr_render_statistics gpumem_usage::rpr_longlong gpumem_total::rpr_longlong gpumem_max_allocation::rpr_longlong sysmem_usage::rpr_longlong end struct rpr_image_format num_components::rpr_uint type::rpr_component_type end struct rpr_framebuffer_format num_components::rpr_uint type::rpr_component_type end struct rpr_ies_image_desc w::rpr_int h::rpr_int data::Ptr{rpr_char} filename::Ptr{rpr_char} end """ rprRegisterPlugin(path) Register rendering plugin <Description> ### Parameters * `path`: Path of plugin to load (for UNICODE, supports UTF-8 encoding) ### Returns unique identifier of plugin, -1 otherwise """ function rprRegisterPlugin(path) ccall((:rprRegisterPlugin, libRadeonProRender64), rpr_int, (Ptr{rpr_char},), path) end """ rprCreateContext(api_version, pluginIDs, pluginCount, creation_flags, props, cache_path) Create rendering context Rendering context is a root concept encapsulating the render states and responsible for execution control. All the entities in Radeon ProRender are created for a particular rendering context. Entities created for some context can't be used with other contexts. Possible error codes for this call are: RPR\\_ERROR\\_COMPUTE\\_API\\_NOT\\_SUPPORTED RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_INVALID\\_API\\_VERSION RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `api_version`: Api version constant * `context_type`: Determines compute API to use, OPENCL only is supported for now * `creation_flags`: Determines multi-gpu or cpu-gpu configuration * `props`: Context creation properties. Specifies a list of context property names and their corresponding values. Each property name is immediately followed by the corresponding desired value. The list is terminated with 0. * `cache_path`: Full path to kernel cache created by Radeon ProRender, NULL means to use current folder (for UNICODE, supports UTF-8 encoding) * `cpu_thread_limit`: Limit for the number of threads used for CPU rendering * `out_context`: Pointer to context object ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCreateContext(api_version, pluginIDs, pluginCount, creation_flags, props, cache_path) out_context = Ref{rpr_context}() check_error(ccall((:rprCreateContext, libRadeonProRender64), rpr_status, (rpr_uint, Ptr{rpr_int}, Csize_t, rpr_creation_flags, Ptr{rpr_context_properties}, Ptr{rpr_char}, Ptr{rpr_context}), api_version, pluginIDs, pluginCount, creation_flags, props, cache_path, out_context)) return out_context[] end """ rprContextSetActivePlugin(context, pluginID) Set active context plugin """ function rprContextSetActivePlugin(context, pluginID) check_error(ccall((:rprContextSetActivePlugin, libRadeonProRender64), rpr_status, (rpr_context, rpr_int), context, pluginID)) end """ rprContextGetInfo(context, context_info, size, data, size_ret) Query information about a context The workflow is usually two-step: query with the data == NULL and size = 0 to get the required buffer size in size\\_ret, then query with size\\_ret == NULL to fill the buffer with the data. Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `context`: The context to query * `context_info`: The type of info to query * `size`: The size of the buffer pointed by data * `data`: The buffer to store queried info * `size_ret`: Returns the size in bytes of the data being queried ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextGetInfo(context, context_info, size, data, size_ret) check_error(ccall((:rprContextGetInfo, libRadeonProRender64), rpr_status, (rpr_context, rpr_context_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), context, context_info, size, data, size_ret)) end """ rprContextGetParameterInfo(context, param_idx, parameter_info, size, data, size_ret) Query information about a context parameter The workflow is usually two-step: query with the data == NULL and size = 0 to get the required buffer size in size\\_ret, then query with size\\_ret == NULL to fill the buffer with the data Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `context`: The context to query * `param_idx`: The index of the parameter - must be between 0 and (value stored by RPR\\_CONTEXT\\_PARAMETER\\_COUNT)-1 * `parameter_info`: The type of info to query * `size`: The size of the buffer pointed by data * `data`: The buffer to store queried info * `size_ret`: Returns the size in bytes of the data being queried ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextGetParameterInfo(context, param_idx, parameter_info, size, data, size_ret) check_error(ccall((:rprContextGetParameterInfo, libRadeonProRender64), rpr_status, (rpr_context, Cint, rpr_parameter_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), context, param_idx, parameter_info, size, data, size_ret)) end """ rprContextGetAOV(context, aov) Query the AOV ### Parameters * `context`: The context to get a frame buffer from * `out_fb`: Pointer to framebuffer object ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextGetAOV(context, aov) out_fb = Ref{rpr_framebuffer}() check_error(ccall((:rprContextGetAOV, libRadeonProRender64), rpr_status, (rpr_context, rpr_aov, Ptr{rpr_framebuffer}), context, aov, out_fb)) return out_fb[] end """ rprContextSetAOV(context, aov, frame_buffer) Set AOV ### Parameters * `context`: The context to set AOV * `aov`: AOV * `frame_buffer`: Frame buffer object to set ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextSetAOV(context, aov, frame_buffer) check_error(ccall((:rprContextSetAOV, libRadeonProRender64), rpr_status, (rpr_context, rpr_aov, rpr_framebuffer), context, aov, frame_buffer)) end """ rprContextAttachRenderLayer(context, renderLayerString) ### Parameters * `context`: The context to set * `renderLayerString`: Render layer name to attach ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextAttachRenderLayer(context, renderLayerString) check_error(ccall((:rprContextAttachRenderLayer, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_char}), context, renderLayerString)) end """ rprContextDetachRenderLayer(context, renderLayerString) ### Parameters * `context`: The context to set * `renderLayerString`: Render layer name to detach ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextDetachRenderLayer(context, renderLayerString) check_error(ccall((:rprContextDetachRenderLayer, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_char}), context, renderLayerString)) end """ rprFrameBufferSetLPE(frame_buffer, lpe) Set a LPE ( Light Path Expression ) to a framebuffer. Note that this framebuffer should also be assigned to a LPE AOV: RPR\\_AOV\\_LPE\\_0 , RPR\\_AOV\\_LPE\\_1 .... ### Parameters * `frame_buffer`: Frame buffer object to set * `lpe`: Light Path Expression ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprFrameBufferSetLPE(frame_buffer, lpe) check_error(ccall((:rprFrameBufferSetLPE, libRadeonProRender64), rpr_status, (rpr_framebuffer, Ptr{rpr_char}), frame_buffer, lpe)) end """ rprContextSetAOVindexLookup(context, key, colorR, colorG, colorB, colorA) Set AOV Index Lookup Color change the color of AOV rendering IDs, like : RPR\\_AOV\\_MATERIAL\\_ID , RPR\\_AOV\\_OBJECT\\_ID, RPR\\_AOV\\_OBJECT\\_GROUP\\_ID. for example, you can render all the shapes with ObjectGroupID=4 in the Red color inside the RPR\\_AOV\\_OBJECT\\_GROUP\\_ID AOV ### Parameters * `context`: The context to set AOV index lookup * `key`: id * `colorR`: red channel * `colorG`: green channel * `colorB`: blue channel * `colorA`: alpha channel ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextSetAOVindexLookup(context, key, colorR, colorG, colorB, colorA) check_error(ccall((:rprContextSetAOVindexLookup, libRadeonProRender64), rpr_status, (rpr_context, rpr_int, rpr_float, rpr_float, rpr_float, rpr_float), context, key, colorR, colorG, colorB, colorA)) end """ rprContextSetCuttingPlane(context, index, a, b, c, d) Set a Cutting Plane (also called Clipping plane). Notes: - In order to disable the 'index' cutting plane, set (A,B,C,D) = (0,0,0,0) By default, on context creation all cutting planes are disabled. - Index can be any number. It doesn't need to define the list of plane as a contiguous list of indices. - If the number of enabled planes is greater than the limit supported by the renderer, then RPR\\_ERROR\\_UNSUPPORTED is return by the function. - The normal of the equation plane points toward the area that is kept. - If several clipping planes are used the rendered area will be the one commonly facing all the planes. - Plane equation is Ax + By + Cz + D = 0 ### Parameters * `context`: The context to set the Cutting Plane * `index`: cutting plane index ( starts from 0 ) * `a`: equation plane A * `b`: equation plane B * `c`: equation plane C * `d`: equation plane D ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextSetCuttingPlane(context, index, a, b, c, d) check_error(ccall((:rprContextSetCuttingPlane, libRadeonProRender64), rpr_status, (rpr_context, rpr_int, rpr_float, rpr_float, rpr_float, rpr_float), context, index, a, b, c, d)) end """ rprContextSetAOVindicesLookup(context, keyOffset, keyCount, colorRGBA) call a batch of [`rprContextSetAOVindexLookup`](@ref) example: [`rprContextSetAOVindicesLookup`](@ref)(ctx, 2, 3, table); is equivalent to call : [`rprContextSetAOVindexLookup`](@ref)(ctx, 2, table[0], table[1], table[2], table[3]); [`rprContextSetAOVindexLookup`](@ref)(ctx, 3, table[4], table[5], table[6], table[7]); [`rprContextSetAOVindexLookup`](@ref)(ctx, 4, table[8], table[9], table[10], table[11]); Depending on the plugin, [`rprContextSetAOVindicesLookup`](@ref) could be faster than calling several [`rprContextSetAOVindexLookup`](@ref). """ function rprContextSetAOVindicesLookup(context, keyOffset, keyCount, colorRGBA) check_error(ccall((:rprContextSetAOVindicesLookup, libRadeonProRender64), rpr_status, (rpr_context, rpr_int, rpr_int, Ptr{rpr_float}), context, keyOffset, keyCount, colorRGBA)) end """ rprContextSetUserTexture(context, index, gpuCode, cpuCode) API user can create its own procedural texture. The API needs both a GPU code ( OpenCL string code ) and a CPU code ( callback ) (API function supported by Northstar only) example: #define DEFINE\\_FUNC(FUNCNAME, FUNC) FUNC; const std::string g\\_str\\_##FUNCNAME = #FUNC; DEFINE\\_FUNC( RprCustomMatA , void RprCustomMatA(float* a, float* b, float* c, float* d, float* e, float* f, float* valueOut){ valueOut[0]=0.0; valueOut[1]=sin(d[0]*3.14159); valueOut[2]=0.0; } ); [`rprContextSetUserTexture`](@ref)(context, 3, g\\_str\\_RprCustomMatA.c\\_str(), RprCustomMatA); // use slot 3 // create material based on slot 3 : [`rpr_material_node`](@ref) matUserTex3; [`rprMaterialSystemCreateNode`](@ref)(matsys, RPR\\_MATERIAL\\_NODE\\_USER\\_TEXTURE, & matUserTex3); [`rprMaterialNodeSetInputUByKey`](@ref)(matUserTex3, RPR\\_MATERIAL\\_INPUT\\_OP, 3 ); // bind matUserTex3 to slot 3 [`rprMaterialNodeSetInputNByKey`](@ref)(matUserTex3, RPR\\_MATERIAL\\_INPUT\\_4, paramInput ); // bind 'paramInput' to the 'e' argument of 'RprCustomMatA' Notes: - If only the GPU is used, a nullptr can be given to 'cpuCode'. - RPR\\_MATERIAL\\_NODE\\_USER\\_TEXTURE\\_0...RPR\\_MATERIAL\\_NODE\\_USER\\_TEXTURE\\_3 , RPR\\_CONTEXT\\_USER\\_TEXTURE\\_0...RPR\\_CONTEXT\\_USER\\_TEXTURE\\_3 are deprecated and should only be used with the old Tahoe plugin. - When exporting the RPR scene to RPRS or GLTF, the CPU callback pointer will be lost in the imported scene. """ function rprContextSetUserTexture(context, index, gpuCode, cpuCode) check_error(ccall((:rprContextSetUserTexture, libRadeonProRender64), rpr_status, (rpr_context, rpr_int, Ptr{rpr_char}, Ptr{Cvoid}), context, index, gpuCode, cpuCode)) end """ rprContextGetUserTexture(context, index, bufferSizeByte, buffer, size_ret) get the gpuCode string set by [`rprContextSetUserTexture`](@ref). (API function supported by Northstar only) """ function rprContextGetUserTexture(context, index, bufferSizeByte, buffer, size_ret) check_error(ccall((:rprContextGetUserTexture, libRadeonProRender64), rpr_status, (rpr_context, rpr_int, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), context, index, bufferSizeByte, buffer, size_ret)) end """ rprContextSetScene(context, scene) Set the scene The scene is a collection of objects and lights along with all the data required to shade those. The scene is used by the context to render the image. ### Parameters * `context`: The context to set the scene * `scene`: The scene to set ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextSetScene(context, scene) check_error(ccall((:rprContextSetScene, libRadeonProRender64), rpr_status, (rpr_context, rpr_scene), context, scene)) end """ rprContextGetScene(arg0) Get the current scene The scene is a collection of objects and lights along with all the data required to shade those. The scene is used by the context ro render the image. ### Parameters * `context`: The context to get the scene from * `out_scene`: Pointer to scene object ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextGetScene(arg0) out_scene = Ref{rpr_scene}() check_error(ccall((:rprContextGetScene, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_scene}), arg0, out_scene)) return out_scene[] end """ rprContextSetParameterByKey1u(context, in_input, x) Set context parameter Parameters are used to control rendering modes, global sampling and AA settings, etc ### Parameters * `context`: The context to set the value to * `in_input`: Param name, can be any RPR\\_CONTEXT\\_* value * `x,y,z,w`: Parameter value ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextSetParameterByKey1u(context, in_input, x) check_error(ccall((:rprContextSetParameterByKey1u, libRadeonProRender64), rpr_status, (rpr_context, rpr_context_info, rpr_uint), context, in_input, x)) end function rprContextSetParameterByKeyPtr(context, in_input, x) check_error(ccall((:rprContextSetParameterByKeyPtr, libRadeonProRender64), rpr_status, (rpr_context, rpr_context_info, Ptr{Cvoid}), context, in_input, x)) end function rprContextSetParameterByKey1f(context, in_input, x) check_error(ccall((:rprContextSetParameterByKey1f, libRadeonProRender64), rpr_status, (rpr_context, rpr_context_info, rpr_float), context, in_input, x)) end function rprContextSetParameterByKey3f(context, in_input, x, y, z) check_error(ccall((:rprContextSetParameterByKey3f, libRadeonProRender64), rpr_status, (rpr_context, rpr_context_info, rpr_float, rpr_float, rpr_float), context, in_input, x, y, z)) end function rprContextSetParameterByKey4f(context, in_input, x, y, z, w) check_error(ccall((:rprContextSetParameterByKey4f, libRadeonProRender64), rpr_status, (rpr_context, rpr_context_info, rpr_float, rpr_float, rpr_float, rpr_float), context, in_input, x, y, z, w)) end function rprContextSetParameterByKeyString(context, in_input, value) check_error(ccall((:rprContextSetParameterByKeyString, libRadeonProRender64), rpr_status, (rpr_context, rpr_context_info, Ptr{rpr_char}), context, in_input, value)) end """ rprContextSetInternalParameter4f(context, pluginIndex, paramName, x, y, z, w) This is an internal/experimental backdoor for RPR developers team. A classic usage of RPR doesn't require usage of this call. Use this only if you understand what you are doing. It's sending the name/value directly to the plugin without any process of RPR API. the 'paramName' is not related with the parameters of [`rprContextSetParameterByKey4f`](@ref). 'pluginIndex' can be used if the context has more than one plugin - Not Implemented for now, set it to 0. """ function rprContextSetInternalParameter4f(context, pluginIndex, paramName, x, y, z, w) check_error(ccall((:rprContextSetInternalParameter4f, libRadeonProRender64), rpr_status, (rpr_context, rpr_uint, Ptr{rpr_char}, rpr_float, rpr_float, rpr_float, rpr_float), context, pluginIndex, paramName, x, y, z, w)) end function rprContextSetInternalParameter1u(context, pluginIndex, paramName, x) check_error(ccall((:rprContextSetInternalParameter1u, libRadeonProRender64), rpr_status, (rpr_context, rpr_uint, Ptr{rpr_char}, rpr_uint), context, pluginIndex, paramName, x)) end function rprContextSetInternalParameterBuffer(context, pluginIndex, paramName, buffer, bufferSizeByte) check_error(ccall((:rprContextSetInternalParameterBuffer, libRadeonProRender64), rpr_status, (rpr_context, rpr_uint, Ptr{rpr_char}, Ptr{Cvoid}, Csize_t), context, pluginIndex, paramName, buffer, bufferSizeByte)) end function rprContextGetInternalParameter4f(context, pluginIndex, paramName, x, y, z, w) check_error(ccall((:rprContextGetInternalParameter4f, libRadeonProRender64), rpr_status, (rpr_context, rpr_uint, Ptr{rpr_char}, Ptr{rpr_float}, Ptr{rpr_float}, Ptr{rpr_float}, Ptr{rpr_float}), context, pluginIndex, paramName, x, y, z, w)) end function rprContextGetInternalParameter1u(context, pluginIndex, paramName, x) check_error(ccall((:rprContextGetInternalParameter1u, libRadeonProRender64), rpr_status, (rpr_context, rpr_uint, Ptr{rpr_char}, Ptr{rpr_uint}), context, pluginIndex, paramName, x)) end function rprContextGetInternalParameterBuffer(context, pluginIndex, paramName, bufferSizeByte, buffer, size_ret) check_error(ccall((:rprContextGetInternalParameterBuffer, libRadeonProRender64), rpr_status, (rpr_context, rpr_uint, Ptr{rpr_char}, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), context, pluginIndex, paramName, bufferSizeByte, buffer, size_ret)) end """ rprContextRender(context) Perform evaluation and accumulation of a single sample (or number of AA samples if AA is enabled) The call is blocking and the image is ready when returned. The context accumulates the samples in order to progressively refine the image and enable interactive response. So each new call to Render refines the resultin image with 1 (or num aa samples) color samples. Call [`rprFrameBufferClear`](@ref) if you want to start rendering new image instead of refining the previous one. Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_INTERNAL\\_ERROR RPR\\_ERROR\\_MATERIAL\\_STACK\\_OVERFLOW if you have the RPR\\_ERROR\\_MATERIAL\\_STACK\\_OVERFLOW error, you have created a shader graph with too many nodes. you can check the nodes limit with [`rprContextGetInfo`](@ref)(,RPR\\_CONTEXT\\_MATERIAL\\_STACK\\_SIZE,) ### Parameters * `context`: The context object ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextRender(context) check_error(ccall((:rprContextRender, libRadeonProRender64), rpr_status, (rpr_context,), context)) end """ rprContextAbortRender(context) can be called in a different thread to interrupt the rendering then, [`rprContextRender`](@ref) will return RPR\\_ERROR\\_ABORTED instead of RPR\\_SUCCESS """ function rprContextAbortRender(context) check_error(ccall((:rprContextAbortRender, libRadeonProRender64), rpr_status, (rpr_context,), context)) end """ rprContextRenderTile(context, xmin, xmax, ymin, ymax) Perform evaluation and accumulation of a single sample (or number of AA samples if AA is enabled) on the part of the image The call is blocking and the image is ready when returned. The context accumulates the samples in order to progressively refine the image and enable interactive response. So each new call to Render refines the resultin image with 1 (or num aa samples) color samples. Call [`rprFrameBufferClear`](@ref) if you want to start rendering new image instead of refining the previous one. Possible error codes are: RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_INTERNAL\\_ERROR ### Parameters * `context`: The context to use for the rendering * `xmin`: X coordinate of the top left corner of a tile * `xmax`: X coordinate of the bottom right corner of a tile * `ymin`: Y coordinate of the top left corner of a tile * `ymax`: Y coordinate of the bottom right corner of a tile ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextRenderTile(context, xmin, xmax, ymin, ymax) check_error(ccall((:rprContextRenderTile, libRadeonProRender64), rpr_status, (rpr_context, rpr_uint, rpr_uint, rpr_uint, rpr_uint), context, xmin, xmax, ymin, ymax)) end """ rprContextClearMemory(context) Clear all video memory used by the context This function should be called after all context objects have been destroyed. It guarantees that all context memory is freed and returns the context into its initial state. Will be removed later. Possible error codes are: RPR\\_ERROR\\_INTERNAL\\_ERROR ### Parameters * `context`: The context to wipe out ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextClearMemory(context) check_error(ccall((:rprContextClearMemory, libRadeonProRender64), rpr_status, (rpr_context,), context)) end """ rprContextCreateImage(context, format, image_desc, data) Create an image from memory data Images are used as HDRI maps or inputs for various shading system nodes. Possible error codes are: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_UNSUPPORTED\\_IMAGE\\_FORMAT RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `context`: The context to create image * `format`: Image format * `image_desc`: Image layout description * `data`: Image data in system memory, can be NULL in which case the memory is allocated * `out_image`: Pointer to image object ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextCreateImage(context, format, image_desc, data) out_image = Ref{rpr_image}() check_error(ccall((:rprContextCreateImage, libRadeonProRender64), rpr_status, (rpr_context, rpr_image_format, Ptr{rpr_image_desc}, Ptr{Cvoid}, Ptr{rpr_image}), context, format, image_desc, data, out_image)) return out_image[] end """ rprContextCreateBuffer(context, buffer_desc, data) Create a buffer from memory data Buffers are used as arbitrary input for other nodes RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_UNSUPPORTED\\_IMAGE\\_FORMAT RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `context`: The context to create image * `buffer_desc`: Buffer layout description * `data`: Image data in system memory, can be NULL in which case the memory is allocated * `out_buffer`: Pointer to buffer object ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextCreateBuffer(context, buffer_desc, data) out_buffer = Ref{rpr_buffer}() check_error(ccall((:rprContextCreateBuffer, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_buffer_desc}, Ptr{Cvoid}, Ptr{rpr_buffer}), context, buffer_desc, data, out_buffer)) return out_buffer[] end """ rprContextCreateImageFromFile(context, path) Create an image from file Images are used as HDRI maps or inputs for various shading system nodes. The following image formats are supported: PNG, JPG, TGA, BMP, TIFF, TX(0-mip), HDR, EXR Possible error codes are: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_UNSUPPORTED\\_IMAGE\\_FORMAT RPR\\_ERROR\\_INVALID\\_PARAMETER RPR\\_ERROR\\_IO\\_ERROR ### Parameters * `context`: The context to create image * `path`: NULL terminated path to an image file (can be relative) (for UNICODE, supports UTF-8 encoding) * `out_image`: Pointer to image object ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextCreateImageFromFile(context, path) out_image = Ref{rpr_image}() check_error(ccall((:rprContextCreateImageFromFile, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_char}, Ptr{rpr_image}), context, path, out_image)) return out_image[] end """ rprContextCreateImageFromFileMemory(context, extension, data, dataSizeByte) similar to [`rprContextCreateImageFromFile`](@ref), except that the file input as a memory buffer extension must look like : ".png" , ".bmp" , ".hdr" , ".exr" , ".jpg" .... """ function rprContextCreateImageFromFileMemory(context, extension, data, dataSizeByte) out_image = Ref{rpr_image}() check_error(ccall((:rprContextCreateImageFromFileMemory, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_char}, Ptr{Cvoid}, Csize_t, Ptr{rpr_image}), context, extension, data, dataSizeByte, out_image)) return out_image[] end """ rprContextCreateScene(context) Create a scene Scene serves as a container for lights and objects. Possible error codes are: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY ### Parameters * `out_scene`: Pointer to scene object ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextCreateScene(context) out_scene = Ref{rpr_scene}() check_error(ccall((:rprContextCreateScene, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_scene}), context, out_scene)) return out_scene[] end """ rprContextCreateInstance(context, shape) Create an instance of an object Possible error codes are: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `context`: The context to create an instance for * `shape`: Parent shape for an instance * `out_instance`: Pointer to instance object ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextCreateInstance(context, shape) out_instance = Ref{rpr_shape}() check_error(ccall((:rprContextCreateInstance, libRadeonProRender64), rpr_status, (rpr_context, rpr_shape, Ptr{rpr_shape}), context, shape, out_instance)) return out_instance[] end """ rprContextCreateMesh(context, vertices, num_vertices, vertex_stride, normals, num_normals, normal_stride, texcoords, num_texcoords, texcoord_stride, vertex_indices, vidx_stride, normal_indices, nidx_stride, texcoord_indices, tidx_stride, num_face_vertices, num_faces) Create a mesh Radeon ProRender supports mixed meshes consisting of triangles and quads. Possible error codes are: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `vertices`: Pointer to position data (each position is described with 3 [`rpr_float`](@ref) numbers) * `num_vertices`: Number of entries in position array * `vertex_stride`: Number of bytes between the beginnings of two successive position entries * `normals`: Pointer to normal data (each normal is described with 3 [`rpr_float`](@ref) numbers), can be NULL * `num_normals`: Number of entries in normal array * `normal_stride`: Number of bytes between the beginnings of two successive normal entries * `texcoord`: Pointer to texcoord data (each texcoord is described with 2 [`rpr_float`](@ref) numbers), can be NULL * `num_texcoords`: Number of entries in texcoord array * `texcoord_stride`: Number of bytes between the beginnings of two successive texcoord entries * `vertex_indices`: Pointer to an array of vertex indices * `vidx_stride`: Number of bytes between the beginnings of two successive vertex index entries * `normal_indices`: Pointer to an array of normal indices * `nidx_stride`: Number of bytes between the beginnings of two successive normal index entries * `texcoord_indices`: Pointer to an array of texcoord indices * `tidx_stride`: Number of bytes between the beginnings of two successive texcoord index entries * `num_face_vertices`: Pointer to an array of num\\_faces numbers describing number of vertices for each face (can be 3(triangle) or 4(quad)) * `num_faces`: Number of faces in the mesh * `out_mesh`: Pointer to mesh object ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextCreateMesh(context, vertices, num_vertices, vertex_stride, normals, num_normals, normal_stride, texcoords, num_texcoords, texcoord_stride, vertex_indices, vidx_stride, normal_indices, nidx_stride, texcoord_indices, tidx_stride, num_face_vertices, num_faces) out_mesh = Ref{rpr_shape}() check_error(ccall((:rprContextCreateMesh, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_float}, Csize_t, rpr_int, Ptr{rpr_float}, Csize_t, rpr_int, Ptr{rpr_float}, Csize_t, rpr_int, Ptr{rpr_int}, rpr_int, Ptr{rpr_int}, rpr_int, Ptr{rpr_int}, rpr_int, Ptr{rpr_int}, Csize_t, Ptr{rpr_shape}), context, vertices, num_vertices, vertex_stride, normals, num_normals, normal_stride, texcoords, num_texcoords, texcoord_stride, vertex_indices, vidx_stride, normal_indices, nidx_stride, texcoord_indices, tidx_stride, num_face_vertices, num_faces, out_mesh)) return out_mesh[] end function rprContextCreateMeshEx(context, vertices, num_vertices, vertex_stride, normals, num_normals, normal_stride, perVertexFlag, num_perVertexFlags, perVertexFlag_stride, numberOfTexCoordLayers, texcoords, num_texcoords, texcoord_stride, vertex_indices, vidx_stride, normal_indices, nidx_stride, texcoord_indices, tidx_stride, num_face_vertices, num_faces) out_mesh = Ref{rpr_shape}() check_error(ccall((:rprContextCreateMeshEx, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_float}, Csize_t, rpr_int, Ptr{rpr_float}, Csize_t, rpr_int, Ptr{rpr_int}, Csize_t, rpr_int, rpr_int, Ptr{Ptr{rpr_float}}, Ptr{Csize_t}, Ptr{rpr_int}, Ptr{rpr_int}, rpr_int, Ptr{rpr_int}, rpr_int, Ptr{Ptr{rpr_int}}, Ptr{rpr_int}, Ptr{rpr_int}, Csize_t, Ptr{rpr_shape}), context, vertices, num_vertices, vertex_stride, normals, num_normals, normal_stride, perVertexFlag, num_perVertexFlags, perVertexFlag_stride, numberOfTexCoordLayers, texcoords, num_texcoords, texcoord_stride, vertex_indices, vidx_stride, normal_indices, nidx_stride, texcoord_indices, tidx_stride, num_face_vertices, num_faces, out_mesh)) return out_mesh[] end function rprContextCreateMeshEx2(context, vertices, num_vertices, vertex_stride, normals, num_normals, normal_stride, perVertexFlag, num_perVertexFlags, perVertexFlag_stride, numberOfTexCoordLayers, texcoords, num_texcoords, texcoord_stride, vertex_indices, vidx_stride, normal_indices, nidx_stride, texcoord_indices, tidx_stride, num_face_vertices, num_faces, mesh_properties) out_mesh = Ref{rpr_shape}() check_error(ccall((:rprContextCreateMeshEx2, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_float}, Csize_t, rpr_int, Ptr{rpr_float}, Csize_t, rpr_int, Ptr{rpr_int}, Csize_t, rpr_int, rpr_int, Ptr{Ptr{rpr_float}}, Ptr{Csize_t}, Ptr{rpr_int}, Ptr{rpr_int}, rpr_int, Ptr{rpr_int}, rpr_int, Ptr{Ptr{rpr_int}}, Ptr{rpr_int}, Ptr{rpr_int}, Csize_t, Ptr{rpr_mesh_info}, Ptr{rpr_shape}), context, vertices, num_vertices, vertex_stride, normals, num_normals, normal_stride, perVertexFlag, num_perVertexFlags, perVertexFlag_stride, numberOfTexCoordLayers, texcoords, num_texcoords, texcoord_stride, vertex_indices, vidx_stride, normal_indices, nidx_stride, texcoord_indices, tidx_stride, num_face_vertices, num_faces, mesh_properties, out_mesh)) return out_mesh[] end """ rprContextCreateCamera(context) Create a camera There are several camera types supported by a single [`rpr_camera`](@ref) type. Possible error codes are: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY ### Parameters * `context`: The context to create a camera for * `out_camera`: Pointer to camera object ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextCreateCamera(context) out_camera = Ref{rpr_camera}() check_error(ccall((:rprContextCreateCamera, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_camera}), context, out_camera)) return out_camera[] end """ rprContextCreateFrameBuffer(context, format, fb_desc) Create framebuffer object Framebuffer is used to store final rendering result. Possible error codes are: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY ### Parameters * `context`: The context to create framebuffer * `format`: Framebuffer format * `fb_desc`: Framebuffer layout description * `status`: Pointer to framebuffer object ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprContextCreateFrameBuffer(context, format, fb_desc) out_fb = Ref{rpr_framebuffer}() check_error(ccall((:rprContextCreateFrameBuffer, libRadeonProRender64), rpr_status, (rpr_context, rpr_framebuffer_format, Ptr{rpr_framebuffer_desc}, Ptr{rpr_framebuffer}), context, format, fb_desc, out_fb)) return out_fb[] end """ rprContextGetFunctionPtr(context, function_name) Loads extension function from context """ function rprContextGetFunctionPtr(context, function_name) out_function_ptr = Ref{Ptr{Cvoid}}() check_error(ccall((:rprContextGetFunctionPtr, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_char}, Ptr{Ptr{Cvoid}}), context, function_name, out_function_ptr)) return out_function_ptr[] end """ rprCameraGetInfo(camera, camera_info, size, data, size_ret) Query information about a camera The workflow is usually two-step: query with the data == NULL to get the required buffer size, then query with size\\_ret == NULL to fill the buffer with the data. Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `camera`: The camera to query * `camera_info`: The type of info to query * `size`: The size of the buffer pointed by data * `data`: The buffer to store queried info * `size_ret`: Returns the size in bytes of the data being queried ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraGetInfo(camera, camera_info, size, data, size_ret) check_error(ccall((:rprCameraGetInfo, libRadeonProRender64), rpr_status, (rpr_camera, rpr_camera_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), camera, camera_info, size, data, size_ret)) end """ rprCameraSetFocalLength(camera, flength) Set camera focal length. ### Parameters * `camera`: The camera to set focal length * `flength`: Focal length in millimeters, default is 35mm ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraSetFocalLength(camera, flength) check_error(ccall((:rprCameraSetFocalLength, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float), camera, flength)) end function rprCameraSetMotionTransformCount(camera, transformCount) check_error(ccall((:rprCameraSetMotionTransformCount, libRadeonProRender64), rpr_status, (rpr_camera, rpr_uint), camera, transformCount)) end function rprCameraSetMotionTransform(camera, transpose, transform, timeIndex) check_error(ccall((:rprCameraSetMotionTransform, libRadeonProRender64), rpr_status, (rpr_camera, rpr_bool, Ptr{rpr_float}, rpr_uint), camera, transpose, transform, timeIndex)) end """ rprCameraSetFocusDistance(camera, fdist) Set camera focus distance ### Parameters * `camera`: The camera to set focus distance * `fdist`: Focus distance in meters, default is 1m ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraSetFocusDistance(camera, fdist) check_error(ccall((:rprCameraSetFocusDistance, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float), camera, fdist)) end """ rprCameraSetTransform(camera, transpose, transform) Set world transform for the camera ### Parameters * `camera`: The camera to set transform for * `transpose`: Determines whether the basis vectors are in columns(false) or in rows(true) of the matrix * `transform`: Array of 16 [`rpr_float`](@ref) values (row-major form) ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraSetTransform(camera, transpose, transform) check_error(ccall((:rprCameraSetTransform, libRadeonProRender64), rpr_status, (rpr_camera, rpr_bool, Ptr{rpr_float}), camera, transpose, transform)) end """ rprCameraSetSensorSize(camera, width, height) Set sensor size for the camera Default sensor size is the one corresponding to full frame 36x24mm sensor ### Parameters * `camera`: The camera to set transform for * `width`: Sensor width in millimeters * `height`: Sensor height in millimeters ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraSetSensorSize(camera, width, height) check_error(ccall((:rprCameraSetSensorSize, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float, rpr_float), camera, width, height)) end """ rprCameraLookAt(camera, posx, posy, posz, atx, aty, atz, upx, upy, upz) Set camera transform in lookat form ### Parameters * `camera`: The camera to set transform for * `posx`: X component of the position * `posy`: Y component of the position * `posz`: Z component of the position * `atx`: X component of the center point * `aty`: Y component of the center point * `atz`: Z component of the center point * `upx`: X component of the up vector * `upy`: Y component of the up vector * `upz`: Z component of the up vector ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraLookAt(camera, posx, posy, posz, atx, aty, atz, upx, upy, upz) check_error(ccall((:rprCameraLookAt, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float, rpr_float, rpr_float, rpr_float, rpr_float, rpr_float, rpr_float, rpr_float, rpr_float), camera, posx, posy, posz, atx, aty, atz, upx, upy, upz)) end """ rprCameraSetFStop(camera, fstop) Set f-stop for the camera ### Parameters * `camera`: The camera to set f-stop for * `fstop`: f-stop value in mm^-1, default is FLT\\_MAX ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraSetFStop(camera, fstop) check_error(ccall((:rprCameraSetFStop, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float), camera, fstop)) end """ rprCameraSetApertureBlades(camera, num_blades) Set the number of aperture blades Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `camera`: The camera to set aperture blades for * `num_blades`: Number of aperture blades 4 to 32 ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraSetApertureBlades(camera, num_blades) check_error(ccall((:rprCameraSetApertureBlades, libRadeonProRender64), rpr_status, (rpr_camera, rpr_uint), camera, num_blades)) end """ rprCameraSetExposure(camera, exposure) Set the exposure of a camera Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `camera`: The camera to set aperture blades for * `exposure`: Represents a time length in the same time scale than [`rprShapeSetMotionTransform`](@ref),[`rprCameraSetMotionTransform`](@ref)... ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraSetExposure(camera, exposure) check_error(ccall((:rprCameraSetExposure, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float), camera, exposure)) end """ rprCameraSetMode(camera, mode) Set camera mode Camera modes include: RPR\\_CAMERA\\_MODE\\_PERSPECTIVE RPR\\_CAMERA\\_MODE\\_ORTHOGRAPHIC RPR\\_CAMERA\\_MODE\\_LATITUDE\\_LONGITUDE\\_360 RPR\\_CAMERA\\_MODE\\_LATITUDE\\_LONGITUDE\\_STEREO RPR\\_CAMERA\\_MODE\\_CUBEMAP RPR\\_CAMERA\\_MODE\\_CUBEMAP\\_STEREO RPR\\_CAMERA\\_MODE\\_FISHEYE ### Parameters * `camera`: The camera to set mode for * `mode`: Camera mode, default is RPR\\_CAMERA\\_MODE\\_PERSPECTIVE ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraSetMode(camera, mode) check_error(ccall((:rprCameraSetMode, libRadeonProRender64), rpr_status, (rpr_camera, rpr_camera_mode), camera, mode)) end """ rprCameraSetOrthoWidth(camera, width) Set orthographic view volume width ### Parameters * `camera`: The camera to set volume width for * `width`: View volume width in meters, default is 1 meter ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraSetOrthoWidth(camera, width) check_error(ccall((:rprCameraSetOrthoWidth, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float), camera, width)) end function rprCameraSetFocalTilt(camera, tilt) check_error(ccall((:rprCameraSetFocalTilt, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float), camera, tilt)) end function rprCameraSetIPD(camera, ipd) check_error(ccall((:rprCameraSetIPD, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float), camera, ipd)) end function rprCameraSetLensShift(camera, shiftx, shifty) check_error(ccall((:rprCameraSetLensShift, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float, rpr_float), camera, shiftx, shifty)) end function rprCameraSetTiltCorrection(camera, tiltX, tiltY) check_error(ccall((:rprCameraSetTiltCorrection, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float, rpr_float), camera, tiltX, tiltY)) end """ rprCameraSetOrthoHeight(camera, height) Set orthographic view volume height ### Parameters * `camera`: The camera to set volume height for * `width`: View volume height in meters, default is 1 meter ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraSetOrthoHeight(camera, height) check_error(ccall((:rprCameraSetOrthoHeight, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float), camera, height)) end """ rprCameraSetNearPlane(camera, near) Set near plane of a camera ### Parameters * `camera`: The camera to set near plane for * `near`: Near plane distance in meters, default is 0.01f ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraSetNearPlane(camera, near) check_error(ccall((:rprCameraSetNearPlane, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float), camera, near)) end """ rprCameraSetPostScale(camera, scale) Set the post scale of camera ( 2D camera zoom ) ### Parameters * `camera`: The camera to set * `scale`: post scale value. ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraSetPostScale(camera, scale) check_error(ccall((:rprCameraSetPostScale, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float), camera, scale)) end """ rprCameraSetFarPlane(camera, far) Set far plane of a camera ### Parameters * `camera`: The camera to set far plane for * `far`: Far plane distance in meters, default is 100000000.f ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraSetFarPlane(camera, far) check_error(ccall((:rprCameraSetFarPlane, libRadeonProRender64), rpr_status, (rpr_camera, rpr_float), camera, far)) end """ rprCameraSetUVDistortion(camera, distortionMap) Set distorion image for camera ### Parameters * `camera`: The camera to set UV Distortion for * `distortionMap`: distorion image ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCameraSetUVDistortion(camera, distortionMap) check_error(ccall((:rprCameraSetUVDistortion, libRadeonProRender64), rpr_status, (rpr_camera, rpr_image), camera, distortionMap)) end """ rprImageGetInfo(image, image_info, size, data, size_ret) Query information about an image The workflow is usually two-step: query with the data == NULL to get the required buffer size, then query with size\\_ret == NULL to fill the buffer with the data Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `image`: An image object to query * `image_info`: The type of info to query * `size`: The size of the buffer pointed by data * `data`: The buffer to store queried info * `size_ret`: Returns the size in bytes of the data being queried ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprImageGetInfo(image, image_info, size, data, size_ret) check_error(ccall((:rprImageGetInfo, libRadeonProRender64), rpr_status, (rpr_image, rpr_image_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), image, image_info, size, data, size_ret)) end """ rprImageSetWrap(image, type) this is DEPRECATED in the Northstar plugin. In this plugin, the wrapping is done inside the RPR\\_MATERIAL\\_NODE\\_IMAGE\\_TEXTURE owning the image, example: [`rprMaterialNodeSetInputUByKey`](@ref)(materialNodeTexture, RPR\\_MATERIAL\\_INPUT\\_WRAP\\_U, RPR\\_IMAGE\\_WRAP\\_TYPE\\_REPEAT); ### Parameters * `image`: The image to set wrap for * `type`: ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprImageSetWrap(image, type) check_error(ccall((:rprImageSetWrap, libRadeonProRender64), rpr_status, (rpr_image, rpr_image_wrap_type), image, type)) end """ rprImageSetInternalCompression(image, compressionEnabled) ( Northstar-only feature ) By default, images are compressed by the Northstar renderer. Setting 'compressionEnabled'=0 will disable the compression for the images. For better performance, it's advised to only disable it for textures that need it. """ function rprImageSetInternalCompression(image, compressionEnabled) check_error(ccall((:rprImageSetInternalCompression, libRadeonProRender64), rpr_status, (rpr_image, rpr_uint), image, compressionEnabled)) end """ rprImageSetOcioColorspace(image, ocioColorspace) Set the OCIO Color Space """ function rprImageSetOcioColorspace(image, ocioColorspace) check_error(ccall((:rprImageSetOcioColorspace, libRadeonProRender64), rpr_status, (rpr_image, Ptr{rpr_char}), image, ocioColorspace)) end """ rprImageSetUDIM(imageUdimRoot, tileIndex, imageTile) Set a tile to an UDIM image. ### Parameters * `imageUdimRoot`: must be an UDIM image ( created with no data: [`rprContextCreateImage`](@ref)(context, {0,RPR\\_COMPONENT\\_TYPE\\_UINT8}, nullptr, nullptr, ); ) * `tileIndex`: a valid UDIM index: 1001 , 1002, 1003 ... 1011, 1012, 1013 ... etc ... * `imageTile`: a valid classic [`rpr_image`](@ref) """ function rprImageSetUDIM(imageUdimRoot, tileIndex, imageTile) check_error(ccall((:rprImageSetUDIM, libRadeonProRender64), rpr_status, (rpr_image, rpr_uint, rpr_image), imageUdimRoot, tileIndex, imageTile)) end """ rprImageSetFilter(image, type) ### Parameters * `image`: The image to set filter for * `type`: ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprImageSetFilter(image, type) check_error(ccall((:rprImageSetFilter, libRadeonProRender64), rpr_status, (rpr_image, rpr_image_filter_type), image, type)) end """ rprImageSetGamma(image, type) ### Parameters * `image`: The image to set gamma for * `type`: ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprImageSetGamma(image, type) check_error(ccall((:rprImageSetGamma, libRadeonProRender64), rpr_status, (rpr_image, rpr_float), image, type)) end """ rprImageSetMipmapEnabled(image, enabled) ### Parameters * `image`: The image to set mipmap for * `enabled`: true (enable) or false (disable) ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprImageSetMipmapEnabled(image, enabled) check_error(ccall((:rprImageSetMipmapEnabled, libRadeonProRender64), rpr_status, (rpr_image, rpr_bool), image, enabled)) end """ rprShapeSetTransform(shape, transpose, transform) Set shape world transform ### Parameters * `shape`: The shape to set transform for * `transpose`: Determines whether the basis vectors are in columns(false) or in rows(true) of the matrix * `transform`: Array of 16 [`rpr_float`](@ref) values (row-major form) ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetTransform(shape, transpose, transform) check_error(ccall((:rprShapeSetTransform, libRadeonProRender64), rpr_status, (rpr_shape, rpr_bool, Ptr{rpr_float}), shape, transpose, transform)) end """ rprShapeSetVertexValue(in_shape, setIndex, indices, values, indicesCount) assign custom float value to some vertices of the mesh example : // indicesSet and values must have the same size [`rpr_int`](@ref) indicesSet[] = {4,0,1,2,3}; [`rpr_float`](@ref) values[] = { 0.8 , 0.1 , 0.0 , 1.0 , 1.0 }; [`rprShapeSetVertexValue`](@ref)(meshC, 0 , indicesSet , values , sizeof(indicesSet)/sizeof(indicesSet[0]) ); setIndex can be between 0 and 3 : we can assign up to 4 floats for each vertex. ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetVertexValue(in_shape, setIndex, indices, values, indicesCount) check_error(ccall((:rprShapeSetVertexValue, libRadeonProRender64), rpr_status, (rpr_shape, rpr_int, Ptr{rpr_int}, Ptr{rpr_float}, rpr_int), in_shape, setIndex, indices, values, indicesCount)) end function rprShapeSetPrimvar(in_shape, key, data, floatCount, componentCount, interop) check_error(ccall((:rprShapeSetPrimvar, libRadeonProRender64), rpr_status, (rpr_shape, rpr_uint, Ptr{rpr_float}, rpr_uint, rpr_uint, rpr_primvar_interpolation_type), in_shape, key, data, floatCount, componentCount, interop)) end """ rprShapeSetSubdivisionFactor(shape, factor) Set shape subdivision ### Parameters * `shape`: The shape to set subdivision for * `factor`: Number of subdivision steps to do ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetSubdivisionFactor(shape, factor) check_error(ccall((:rprShapeSetSubdivisionFactor, libRadeonProRender64), rpr_status, (rpr_shape, rpr_uint), shape, factor)) end """ rprShapeSetSubdivisionAutoRatioCap(shape, autoRatioCap) Enable or Disable the auto ratio cap for subdivision autoRatioCap is a value from 0.0 to 1.0. autoRatioCap=1.0 means very large polygons, less tessellation. as it goes to 0.0, it does more tessellation. This value is ratio of the largest edge in the screen. Example: If you want to make an edge 10 pixels on 1080p, you need to set 10/1080. ### Parameters * `shape`: The shape to set * `autoRatioCap`: 0.0 to 1.0 ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetSubdivisionAutoRatioCap(shape, autoRatioCap) check_error(ccall((:rprShapeSetSubdivisionAutoRatioCap, libRadeonProRender64), rpr_status, (rpr_shape, rpr_float), shape, autoRatioCap)) end """ rprShapeSetSubdivisionCreaseWeight(shape, factor) ### Parameters * `shape`: The shape to set subdivision for * `factor`: ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetSubdivisionCreaseWeight(shape, factor) check_error(ccall((:rprShapeSetSubdivisionCreaseWeight, libRadeonProRender64), rpr_status, (rpr_shape, rpr_float), shape, factor)) end """ rprShapeAttachRenderLayer(shape, renderLayerString) ### Parameters * `shape`: The shape to set * `renderLayerString`: Render layer name to attach ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeAttachRenderLayer(shape, renderLayerString) check_error(ccall((:rprShapeAttachRenderLayer, libRadeonProRender64), rpr_status, (rpr_shape, Ptr{rpr_char}), shape, renderLayerString)) end """ rprShapeDetachRenderLayer(shape, renderLayerString) ### Parameters * `shape`: The shape to set * `renderLayerString`: Render layer name to detach ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeDetachRenderLayer(shape, renderLayerString) check_error(ccall((:rprShapeDetachRenderLayer, libRadeonProRender64), rpr_status, (rpr_shape, Ptr{rpr_char}), shape, renderLayerString)) end """ rprLightAttachRenderLayer(light, renderLayerString) ### Parameters * `light`: The light to set * `renderLayerString`: Render layer name to attach ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprLightAttachRenderLayer(light, renderLayerString) check_error(ccall((:rprLightAttachRenderLayer, libRadeonProRender64), rpr_status, (rpr_light, Ptr{rpr_char}), light, renderLayerString)) end """ rprLightDetachRenderLayer(light, renderLayerString) ### Parameters * `light`: The light to set * `renderLayerString`: Render layer name to detach ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprLightDetachRenderLayer(light, renderLayerString) check_error(ccall((:rprLightDetachRenderLayer, libRadeonProRender64), rpr_status, (rpr_light, Ptr{rpr_char}), light, renderLayerString)) end """ rprShapeSetSubdivisionBoundaryInterop(shape, type) ### Parameters * `shape`: The shape to set subdivision for * `type`: ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetSubdivisionBoundaryInterop(shape, type) check_error(ccall((:rprShapeSetSubdivisionBoundaryInterop, libRadeonProRender64), rpr_status, (rpr_shape, rpr_subdiv_boundary_interfop_type), shape, type)) end """ rprShapeAutoAdaptSubdivisionFactor(shape, framebuffer, camera, factor) Call this function to automatically set the Subdivision Factor depending on the camera position, frame buffer size. You can retrieve the internally computed factor with [`rprShapeGetInfo`](@ref)(...,RPR\\_SHAPE\\_SUBDIVISION\\_FACTOR,...) You have to call this function each time you want to re-adapt the Subdivision Factor : internally the factor will NOT be automatically re-computed when camera/shape/framebuffer changes. ### Parameters * `shape`: The shape to set subdivision for * `framebuffer`: frame buffer used for factor adaptation * `camera`: camera used for factor adaptation * `factor`: factor to regulate the intensity of adaptation ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeAutoAdaptSubdivisionFactor(shape, framebuffer, camera, factor) check_error(ccall((:rprShapeAutoAdaptSubdivisionFactor, libRadeonProRender64), rpr_status, (rpr_shape, rpr_framebuffer, rpr_camera, rpr_int), shape, framebuffer, camera, factor)) end """ rprShapeSetDisplacementScale(shape, minscale, maxscale) Set displacement scale ### Parameters * `shape`: The shape to set subdivision for * `scale`: The amount of displacement applied ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetDisplacementScale(shape, minscale, maxscale) check_error(ccall((:rprShapeSetDisplacementScale, libRadeonProRender64), rpr_status, (rpr_shape, rpr_float, rpr_float), shape, minscale, maxscale)) end """ rprShapeSetObjectGroupID(shape, objectGroupID) Set object group ID (mainly for debugging). ### Parameters * `shape`: The shape to set * `objectGroupID`: The ID ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetObjectGroupID(shape, objectGroupID) check_error(ccall((:rprShapeSetObjectGroupID, libRadeonProRender64), rpr_status, (rpr_shape, rpr_uint), shape, objectGroupID)) end """ rprShapeSetObjectID(shape, objectID) Set object ID (mainly for debugging). ### Parameters * `shape`: The shape to set * `objectID`: The ID ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetObjectID(shape, objectID) check_error(ccall((:rprShapeSetObjectID, libRadeonProRender64), rpr_status, (rpr_shape, rpr_uint), shape, objectID)) end """ rprShapeSetLightGroupID(shape, lightGroupID) Set light group ID when shape has an emissive material (mainly for debugging). ### Parameters * `shape`: The shape to set * `lightGroupID`: The ID ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetLightGroupID(shape, lightGroupID) check_error(ccall((:rprShapeSetLightGroupID, libRadeonProRender64), rpr_status, (rpr_shape, rpr_uint), shape, lightGroupID)) end """ rprShapeSetLayerMask(shape, layerMask) Set object rendering layer mask then, use rprContextSetParameter1u(context,"renderLayerMask",mask) in order to render only a group of shape WARNING: this function is deprecated and will be removed in the future, use [`rprShapeAttachRenderLayer`](@ref)/[`rprShapeDetachRenderLayer`](@ref) and [`rprContextAttachRenderLayer`](@ref)/[`rprContextDetachRenderLayer`](@ref) instead ### Parameters * `shape`: The shape to set * `layerMask`: The render mask ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetLayerMask(shape, layerMask) check_error(ccall((:rprShapeSetLayerMask, libRadeonProRender64), rpr_status, (rpr_shape, rpr_uint), shape, layerMask)) end """ rprShapeSetDisplacementMaterial(shape, materialNode) Set displacement texture ### Parameters * `shape`: The shape to set subdivision for * `materialNode`: Displacement texture , as material. ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetDisplacementMaterial(shape, materialNode) check_error(ccall((:rprShapeSetDisplacementMaterial, libRadeonProRender64), rpr_status, (rpr_shape, rpr_material_node), shape, materialNode)) end """ rprShapeSetMaterial(shape, node) Set shape material """ function rprShapeSetMaterial(shape, node) check_error(ccall((:rprShapeSetMaterial, libRadeonProRender64), rpr_status, (rpr_shape, rpr_material_node), shape, node)) end """ rprShapeSetMaterialFaces(shape, node, face_indices, num_faces) Set shape materials for specific faces ### Parameters * `shape`: The shape to set the material for * `node`: The material to set * `face_indices`: ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetMaterialFaces(shape, node, face_indices, num_faces) check_error(ccall((:rprShapeSetMaterialFaces, libRadeonProRender64), rpr_status, (rpr_shape, rpr_material_node, Ptr{rpr_int}, Csize_t), shape, node, face_indices, num_faces)) end """ rprShapeSetVolumeMaterial(shape, node) Set shape volume material """ function rprShapeSetVolumeMaterial(shape, node) check_error(ccall((:rprShapeSetVolumeMaterial, libRadeonProRender64), rpr_status, (rpr_shape, rpr_material_node), shape, node)) end function rprShapeSetMotionTransformCount(shape, transformCount) check_error(ccall((:rprShapeSetMotionTransformCount, libRadeonProRender64), rpr_status, (rpr_shape, rpr_uint), shape, transformCount)) end function rprShapeSetMotionTransform(shape, transpose, transform, timeIndex) check_error(ccall((:rprShapeSetMotionTransform, libRadeonProRender64), rpr_status, (rpr_shape, rpr_bool, Ptr{rpr_float}, rpr_uint), shape, transpose, transform, timeIndex)) end """ rprShapeSetVisibilityFlag(shape, visibilityFlag, visible) Set visibility flag ### Parameters * `shape`: The shape to set visibility for * `visibilityFlag`: . one of the visibility flags : RPR\\_SHAPE\\_VISIBILITY\\_PRIMARY\\_ONLY\\_FLAG RPR\\_SHAPE\\_VISIBILITY\\_SHADOW RPR\\_SHAPE\\_VISIBILITY\\_REFLECTION RPR\\_SHAPE\\_VISIBILITY\\_REFRACTION RPR\\_SHAPE\\_VISIBILITY\\_TRANSPARENT RPR\\_SHAPE\\_VISIBILITY\\_DIFFUSE RPR\\_SHAPE\\_VISIBILITY\\_GLOSSY\\_REFLECTION RPR\\_SHAPE\\_VISIBILITY\\_GLOSSY\\_REFRACTION RPR\\_SHAPE\\_VISIBILITY\\_LIGHT RPR\\_SHAPE\\_VISIBILITY\\_RECEIVE\\_SHADOW * `visible`: set the flag to TRUE or FALSE ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetVisibilityFlag(shape, visibilityFlag, visible) check_error(ccall((:rprShapeSetVisibilityFlag, libRadeonProRender64), rpr_status, (rpr_shape, rpr_shape_info, rpr_bool), shape, visibilityFlag, visible)) end """ rprCurveSetVisibilityFlag(curve, visibilityFlag, visible) Set visibility flag ### Parameters * `curve`: The curve to set visibility for * `visibilityFlag`: . one of the visibility flags : RPR\\_CURVE\\_VISIBILITY\\_PRIMARY\\_ONLY\\_FLAG RPR\\_CURVE\\_VISIBILITY\\_SHADOW RPR\\_CURVE\\_VISIBILITY\\_REFLECTION RPR\\_CURVE\\_VISIBILITY\\_REFRACTION RPR\\_CURVE\\_VISIBILITY\\_TRANSPARENT RPR\\_CURVE\\_VISIBILITY\\_DIFFUSE RPR\\_CURVE\\_VISIBILITY\\_GLOSSY\\_REFLECTION RPR\\_CURVE\\_VISIBILITY\\_GLOSSY\\_REFRACTION RPR\\_CURVE\\_VISIBILITY\\_LIGHT RPR\\_CURVE\\_VISIBILITY\\_RECEIVE\\_SHADOW * `visible`: set the flag to TRUE or FALSE ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCurveSetVisibilityFlag(curve, visibilityFlag, visible) check_error(ccall((:rprCurveSetVisibilityFlag, libRadeonProRender64), rpr_status, (rpr_curve, rpr_curve_parameter, rpr_bool), curve, visibilityFlag, visible)) end """ rprShapeSetVisibility(shape, visible) Set visibility flag This function sets all RPR\\_SHAPE\\_VISIBILITY\\_* flags to the 'visible' argument value Calling [`rprShapeSetVisibilityFlag`](@ref)(xxx,visible); on each flags would lead to the same result. ### Parameters * `shape`: The shape to set visibility for * `visible`: Determines if the shape is visible or not ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetVisibility(shape, visible) check_error(ccall((:rprShapeSetVisibility, libRadeonProRender64), rpr_status, (rpr_shape, rpr_bool), shape, visible)) end """ rprLightSetVisibilityFlag(light, visibilityFlag, visible) Set visibility flag for Light ### Parameters * `light`: The light to set visibility for * `visibilityFlag`: one of the visibility flags : - RPR\\_LIGHT\\_VISIBILITY\\_LIGHT * `visible`: set the flag to TRUE or FALSE ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprLightSetVisibilityFlag(light, visibilityFlag, visible) check_error(ccall((:rprLightSetVisibilityFlag, libRadeonProRender64), rpr_status, (rpr_light, rpr_light_info, rpr_bool), light, visibilityFlag, visible)) end """ rprCurveSetVisibility(curve, visible) Set visibility flag This function sets all RPR\\_CURVE\\_VISIBILITY\\_* flags to the 'visible' argument value Calling [`rprCurveSetVisibilityFlag`](@ref)(xxx,visible); on each flags would lead to the same result. ### Parameters * `curve`: The curve to set visibility for * `visible`: Determines if the curve is visible or not ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCurveSetVisibility(curve, visible) check_error(ccall((:rprCurveSetVisibility, libRadeonProRender64), rpr_status, (rpr_curve, rpr_bool), curve, visible)) end """ rprShapeSetVisibilityInSpecular(shape, visible) Set visibility flag for specular refleacted rays This function sets both RPR\\_SHAPE\\_VISIBILITY\\_REFLECTION and RPR\\_SHAPE\\_VISIBILITY\\_REFRACTION flags to the 'visible' argument value Calling [`rprShapeSetVisibilityFlag`](@ref)(xxx,visible); on those 2 flags would lead to the same result. ### Parameters * `shape`: The shape to set visibility for * `visible`: Determines if the shape is visible or not ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetVisibilityInSpecular(shape, visible) check_error(ccall((:rprShapeSetVisibilityInSpecular, libRadeonProRender64), rpr_status, (rpr_shape, rpr_bool), shape, visible)) end """ rprShapeSetShadowCatcher(shape, shadowCatcher) Set shadow catcher flag ### Parameters * `shape`: The shape to set shadow catcher flag for * `shadowCatcher`: Determines if the shape behaves as shadow catcher ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetShadowCatcher(shape, shadowCatcher) check_error(ccall((:rprShapeSetShadowCatcher, libRadeonProRender64), rpr_status, (rpr_shape, rpr_bool), shape, shadowCatcher)) end """ rprShapeSetShadowColor(shape, r, g, b) Set shadow color ### Parameters * `shape`: The shape to set shadow color for * `r`: Red component of the color * `g`: Green component of the color * `b`: Blue component of the color ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetShadowColor(shape, r, g, b) check_error(ccall((:rprShapeSetShadowColor, libRadeonProRender64), rpr_status, (rpr_shape, rpr_float, rpr_float, rpr_float), shape, r, g, b)) end """ rprShapeSetReflectionCatcher(shape, reflectionCatcher) Set Reflection catcher flag ### Parameters * `shape`: The shape to set Reflection catcher flag for * `reflectionCatcher`: Determines if the shape behaves as Reflection catcher ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetReflectionCatcher(shape, reflectionCatcher) check_error(ccall((:rprShapeSetReflectionCatcher, libRadeonProRender64), rpr_status, (rpr_shape, rpr_bool), shape, reflectionCatcher)) end """ rprShapeSetContourIgnore(shape, ignoreInContour) Set 1 if ignore shape in the Contour rendering flag. ( This flag is used only if Contour is enabled ) ### Parameters * `shape`: The shape to set * `ignoreInContour`: 0 or 1. ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetContourIgnore(shape, ignoreInContour) check_error(ccall((:rprShapeSetContourIgnore, libRadeonProRender64), rpr_status, (rpr_shape, rpr_bool), shape, ignoreInContour)) end """ rprShapeSetEnvironmentLight(shape, envLight) Set 1 if the shape should be treated as an environment light (finite sphere environment light). ### Parameters * `shape`: The shape to set * `envLight`: 0 or 1. ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeSetEnvironmentLight(shape, envLight) check_error(ccall((:rprShapeSetEnvironmentLight, libRadeonProRender64), rpr_status, (rpr_shape, rpr_bool), shape, envLight)) end """ rprShapeMarkStatic(in_shape, in_is_static) Sets static flag on shape. Setting such flag will result in marking object as static. Such objects can be processed more efficiently but with some restrictions: * Static object can't change its properties. * Static object can't change its transformation. !!! note Static flag can be set only before first call to [`rprContextRender`](@ref). By default all objects created as dynamic. ### Parameters * `in_shape`: shape to set flag on * `in_is_static`: is object static or not """ function rprShapeMarkStatic(in_shape, in_is_static) check_error(ccall((:rprShapeMarkStatic, libRadeonProRender64), rpr_status, (rpr_shape, rpr_bool), in_shape, in_is_static)) end """ rprLightSetTransform(light, transpose, transform) Set light world transform ### Parameters * `light`: The light to set transform for * `transpose`: Determines whether the basis vectors are in columns(false) or in rows(true) of the matrix * `transform`: Array of 16 [`rpr_float`](@ref) values (row-major form) ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprLightSetTransform(light, transpose, transform) check_error(ccall((:rprLightSetTransform, libRadeonProRender64), rpr_status, (rpr_light, rpr_bool, Ptr{rpr_float}), light, transpose, transform)) end """ rprLightSetGroupId(light, groupId) Set light group ID. This parameter can be used with RPR\\_AOV\\_LIGHT\\_GROUP0, RPR\\_AOV\\_LIGHT\\_GROUP1, ... ### Parameters * `light`: The light to set transform for * `groupId`: -1 to remove the group. or a value between 0 and 3. ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprLightSetGroupId(light, groupId) check_error(ccall((:rprLightSetGroupId, libRadeonProRender64), rpr_status, (rpr_light, rpr_uint), light, groupId)) end """ rprShapeGetInfo(arg0, arg1, arg2, arg3, arg4) Query information about a shape The workflow is usually two-step: query with the data == NULL to get the required buffer size, then query with size\\_ret == NULL to fill the buffer with the data Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `shape`: The shape object to query * `material_info`: The type of info to query * `size`: The size of the buffer pointed by data * `data`: The buffer to store queried info * `size_ret`: Returns the size in bytes of the data being queried ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprShapeGetInfo(arg0, arg1, arg2, arg3, arg4) check_error(ccall((:rprShapeGetInfo, libRadeonProRender64), rpr_status, (rpr_shape, rpr_shape_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), arg0, arg1, arg2, arg3, arg4)) end """ rprMeshGetInfo(mesh, mesh_info, size, data, size_ret) Query information about a mesh The workflow is usually two-step: query with the data == NULL to get the required buffer size, then query with size\\_ret == NULL to fill the buffer with the data Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `shape`: The mesh to query * `mesh_info`: The type of info to query * `size`: The size of the buffer pointed by data * `data`: The buffer to store queried info * `size_ret`: Returns the size in bytes of the data being queried ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprMeshGetInfo(mesh, mesh_info, size, data, size_ret) check_error(ccall((:rprMeshGetInfo, libRadeonProRender64), rpr_status, (rpr_shape, rpr_mesh_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), mesh, mesh_info, size, data, size_ret)) end """ rprCurveGetInfo(curve, curve_info, size, data, size_ret) Query information about a Curve The workflow is usually two-step: query with the data == NULL to get the required buffer size, then query with size\\_ret == NULL to fill the buffer with the data Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `shape`: The Curve to query * `rpr_curve_parameter`: The type of info to query * `size`: The size of the buffer pointed by data * `data`: The buffer to store queried info * `size_ret`: Returns the size in bytes of the data being queried ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprCurveGetInfo(curve, curve_info, size, data, size_ret) check_error(ccall((:rprCurveGetInfo, libRadeonProRender64), rpr_status, (rpr_curve, rpr_curve_parameter, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), curve, curve_info, size, data, size_ret)) end """ rprHeteroVolumeGetInfo(heteroVol, heteroVol_info, size, data, size_ret) Query information about a hetero volume The workflow is usually two-step: query with the data == NULL to get the required buffer size, then query with size\\_ret == NULL to fill the buffer with the data Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `heteroVol`: The heteroVolume to query * `heteroVol_info`: The type of info to query * `size`: The size of the buffer pointed by data * `data`: The buffer to store queried info * `size_ret`: Returns the size in bytes of the data being queried ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprHeteroVolumeGetInfo(heteroVol, heteroVol_info, size, data, size_ret) check_error(ccall((:rprHeteroVolumeGetInfo, libRadeonProRender64), rpr_status, (rpr_hetero_volume, rpr_hetero_volume_parameter, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), heteroVol, heteroVol_info, size, data, size_ret)) end function rprGridGetInfo(grid, grid_info, size, data, size_ret) check_error(ccall((:rprGridGetInfo, libRadeonProRender64), rpr_status, (rpr_grid, rpr_grid_parameter, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), grid, grid_info, size, data, size_ret)) end """ rprBufferGetInfo(buffer, buffer_info, size, data, size_ret) Query information about a Buffer The workflow is usually two-step: query with the data == NULL to get the required buffer size, then query with size\\_ret == NULL to fill the buffer with the data Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `buffer`: The heteroVolume to query * `buffer_info`: The type of info to query * `size`: The size of the buffer pointed by data * `data`: The buffer to store queried info * `size_ret`: Returns the size in bytes of the data being queried ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprBufferGetInfo(buffer, buffer_info, size, data, size_ret) check_error(ccall((:rprBufferGetInfo, libRadeonProRender64), rpr_status, (rpr_buffer, rpr_buffer_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), buffer, buffer_info, size, data, size_ret)) end """ rprInstanceGetBaseShape(shape) Get the parent shape for an instance Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `shape`: The shape to get a parent shape from * `status`: RPR\\_SUCCESS in case of success, error code otherwise ### Returns Shape object """ function rprInstanceGetBaseShape(shape) out_shape = Ref{rpr_shape}() check_error(ccall((:rprInstanceGetBaseShape, libRadeonProRender64), rpr_status, (rpr_shape, Ptr{rpr_shape}), shape, out_shape)) return out_shape[] end """ rprContextCreatePointLight(context) Create point light Create analytic point light represented by a point in space. Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY ### Parameters * `context`: The context to create a light for * `status`: RPR\\_SUCCESS in case of success, error code otherwise ### Returns Light object """ function rprContextCreatePointLight(context) out_light = Ref{rpr_light}() check_error(ccall((:rprContextCreatePointLight, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_light}), context, out_light)) return out_light[] end """ rprPointLightSetRadiantPower3f(light, r, g, b) Set radiant power of a point light source ### Parameters * `r`: R component of a radiant power vector * `g`: G component of a radiant power vector * `b`: B component of a radiant power vector ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprPointLightSetRadiantPower3f(light, r, g, b) check_error(ccall((:rprPointLightSetRadiantPower3f, libRadeonProRender64), rpr_status, (rpr_light, rpr_float, rpr_float, rpr_float), light, r, g, b)) end """ rprContextCreateSpotLight(context, light) Create spot light Create analytic spot light Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY ### Parameters * `context`: The context to create a light for * `status`: RPR\\_SUCCESS in case of success, error code otherwise ### Returns Light object """ function rprContextCreateSpotLight(context, light) check_error(ccall((:rprContextCreateSpotLight, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_light}), context, light)) end function rprContextCreateSphereLight(context, light) check_error(ccall((:rprContextCreateSphereLight, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_light}), context, light)) end function rprContextCreateDiskLight(context, light) check_error(ccall((:rprContextCreateDiskLight, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_light}), context, light)) end """ rprSpotLightSetRadiantPower3f(light, r, g, b) Set radiant power of a spot light source ### Parameters * `r`: R component of a radiant power vector * `g`: G component of a radiant power vector * `b`: B component of a radiant power vector ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSpotLightSetRadiantPower3f(light, r, g, b) check_error(ccall((:rprSpotLightSetRadiantPower3f, libRadeonProRender64), rpr_status, (rpr_light, rpr_float, rpr_float, rpr_float), light, r, g, b)) end """ rprSpotLightSetImage(light, img) turn this spot-light into a textured light. 'img' can be NULL to disable textured. """ function rprSpotLightSetImage(light, img) check_error(ccall((:rprSpotLightSetImage, libRadeonProRender64), rpr_status, (rpr_light, rpr_image), light, img)) end """ rprSphereLightSetRadiantPower3f(light, r, g, b) Set Power for Sphere Light ### Parameters * `r`: R component of a radiant power vector * `g`: G component of a radiant power vector * `b`: B component of a radiant power vector ### Returns status RPR\\_SUCCESS in case of success, error code otherwise """ function rprSphereLightSetRadiantPower3f(light, r, g, b) check_error(ccall((:rprSphereLightSetRadiantPower3f, libRadeonProRender64), rpr_status, (rpr_light, rpr_float, rpr_float, rpr_float), light, r, g, b)) end """ rprSphereLightSetRadius(light, radius) Set Radius for Sphere Light ### Parameters * `radius`: Radius to set ### Returns status RPR\\_SUCCESS in case of success, error code otherwise """ function rprSphereLightSetRadius(light, radius) check_error(ccall((:rprSphereLightSetRadius, libRadeonProRender64), rpr_status, (rpr_light, rpr_float), light, radius)) end """ rprDiskLightSetRadiantPower3f(light, r, g, b) Set Power for Disk Light ### Parameters * `r`: R component of a radiant power vector * `g`: G component of a radiant power vector * `b`: B component of a radiant power vector ### Returns status RPR\\_SUCCESS in case of success, error code otherwise """ function rprDiskLightSetRadiantPower3f(light, r, g, b) check_error(ccall((:rprDiskLightSetRadiantPower3f, libRadeonProRender64), rpr_status, (rpr_light, rpr_float, rpr_float, rpr_float), light, r, g, b)) end """ rprDiskLightSetRadius(light, radius) Set Radius for Disk Light ### Parameters * `radius`: Radius to set ### Returns status RPR\\_SUCCESS in case of success, error code otherwise """ function rprDiskLightSetRadius(light, radius) check_error(ccall((:rprDiskLightSetRadius, libRadeonProRender64), rpr_status, (rpr_light, rpr_float), light, radius)) end """ rprDiskLightSetAngle(light, angle) Set Outer Angle for Disk Light ### Parameters * `angle`: Outer angle in radians ### Returns status RPR\\_SUCCESS in case of success, error code otherwise """ function rprDiskLightSetAngle(light, angle) check_error(ccall((:rprDiskLightSetAngle, libRadeonProRender64), rpr_status, (rpr_light, rpr_float), light, angle)) end """ rprDiskLightSetInnerAngle(light, innerAngle) Set Inner Angle for Disk Light ### Parameters * `innerAngle`: Inner angle in radians ### Returns status RPR\\_SUCCESS in case of success, error code otherwise """ function rprDiskLightSetInnerAngle(light, innerAngle) check_error(ccall((:rprDiskLightSetInnerAngle, libRadeonProRender64), rpr_status, (rpr_light, rpr_float), light, innerAngle)) end """ rprSpotLightSetConeShape(light, iangle, oangle) Set cone shape for a spot light Spot light produces smooth penumbra in a region between inner and outer circles, the area inside the inner cicrle receives full power while the area outside the outer one is fully in shadow. ### Parameters * `iangle`: Inner angle of a cone in radians * `oangle`: Outer angle of a coner in radians, should be greater that or equal to inner angle ### Returns status RPR\\_SUCCESS in case of success, error code otherwise """ function rprSpotLightSetConeShape(light, iangle, oangle) check_error(ccall((:rprSpotLightSetConeShape, libRadeonProRender64), rpr_status, (rpr_light, rpr_float, rpr_float), light, iangle, oangle)) end """ rprContextCreateDirectionalLight(context) Create directional light Create analytic directional light. Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY ### Parameters * `context`: The context to create a light for * `status`: RPR\\_SUCCESS in case of success, error code otherwise ### Returns light id of a newly created light """ function rprContextCreateDirectionalLight(context) out_light = Ref{rpr_light}() check_error(ccall((:rprContextCreateDirectionalLight, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_light}), context, out_light)) return out_light[] end """ rprDirectionalLightSetRadiantPower3f(light, r, g, b) Set radiant power of a directional light source ### Parameters * `r`: R component of a radiant power vector * `g`: G component of a radiant power vector * `b`: B component of a radiant power vector ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprDirectionalLightSetRadiantPower3f(light, r, g, b) check_error(ccall((:rprDirectionalLightSetRadiantPower3f, libRadeonProRender64), rpr_status, (rpr_light, rpr_float, rpr_float, rpr_float), light, r, g, b)) end """ rprDirectionalLightSetShadowSoftnessAngle(light, softnessAngle) Set softness of shadow produced by the light ### Parameters * `softnessAngle`: (in Radian) value should be between [ 0 ; pi/4 ]. 0.0 means sharp shadow ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprDirectionalLightSetShadowSoftnessAngle(light, softnessAngle) check_error(ccall((:rprDirectionalLightSetShadowSoftnessAngle, libRadeonProRender64), rpr_status, (rpr_light, rpr_float), light, softnessAngle)) end """ rprContextCreateEnvironmentLight(context) Create an environment light Environment light is a light based on lightprobe. Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY ### Parameters * `context`: The context to create a light for * `status`: RPR\\_SUCCESS in case of success, error code otherwise ### Returns Light object """ function rprContextCreateEnvironmentLight(context) out_light = Ref{rpr_light}() check_error(ccall((:rprContextCreateEnvironmentLight, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_light}), context, out_light)) return out_light[] end """ rprEnvironmentLightSetImage(env_light, image) Set image for an environment light Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER RPR\\_ERROR\\_UNSUPPORTED\\_IMAGE\\_FORMAT ### Parameters * `env_light`: Environment light * `image`: Image object to set ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprEnvironmentLightSetImage(env_light, image) check_error(ccall((:rprEnvironmentLightSetImage, libRadeonProRender64), rpr_status, (rpr_light, rpr_image), env_light, image)) end """ rprEnvironmentLightSetIntensityScale(env_light, intensity_scale) Set intensity scale or an env light ### Parameters * `env_light`: Environment light * `intensity_scale`: Intensity scale ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprEnvironmentLightSetIntensityScale(env_light, intensity_scale) check_error(ccall((:rprEnvironmentLightSetIntensityScale, libRadeonProRender64), rpr_status, (rpr_light, rpr_float), env_light, intensity_scale)) end """ rprEnvironmentLightAttachPortal(scene, env_light, portal) Set portal for environment light to accelerate convergence of indoor scenes Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `env_light`: Environment light * `portal`: Portal mesh, might have multiple components ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprEnvironmentLightAttachPortal(scene, env_light, portal) check_error(ccall((:rprEnvironmentLightAttachPortal, libRadeonProRender64), rpr_status, (rpr_scene, rpr_light, rpr_shape), scene, env_light, portal)) end """ rprEnvironmentLightDetachPortal(scene, env_light, portal) Remove portal for environment light. Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `env_light`: Environment light * `portal`: Portal mesh, that have been added to light. ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprEnvironmentLightDetachPortal(scene, env_light, portal) check_error(ccall((:rprEnvironmentLightDetachPortal, libRadeonProRender64), rpr_status, (rpr_scene, rpr_light, rpr_shape), scene, env_light, portal)) end """ rprEnvironmentLightSetEnvironmentLightOverride(in_ibl, overrideType, in_iblOverride) Sets/Gets environment override on IBL This function sets overrides for different parts of IBL. overrideType argument can take following values: * RPR\\_ENVIRONMENT\\_LIGHT\\_OVERRIDE\\_REFLECTION * RPR\\_ENVIRONMENT\\_LIGHT\\_OVERRIDE\\_REFRACTION * RPR\\_ENVIRONMENT\\_LIGHT\\_OVERRIDE\\_TRANSPARENCY * RPR\\_ENVIRONMENT\\_LIGHT\\_OVERRIDE\\_BACKGROUND * RPR\\_ENVIRONMENT\\_LIGHT\\_OVERRIDE\\_IRRADIANCE ### Parameters * `in_ibl`: image based light created with [`rprContextCreateEnvironmentLight`](@ref) * `overrideType`: override parameter * `in_iblOverride`: image based light created with [`rprContextCreateEnvironmentLight`](@ref) """ function rprEnvironmentLightSetEnvironmentLightOverride(in_ibl, overrideType, in_iblOverride) check_error(ccall((:rprEnvironmentLightSetEnvironmentLightOverride, libRadeonProRender64), rpr_status, (rpr_light, rpr_environment_override, rpr_light), in_ibl, overrideType, in_iblOverride)) end function rprEnvironmentLightGetEnvironmentLightOverride(in_ibl, overrideType) out_iblOverride = Ref{rpr_light}() check_error(ccall((:rprEnvironmentLightGetEnvironmentLightOverride, libRadeonProRender64), rpr_status, (rpr_light, rpr_environment_override, Ptr{rpr_light}), in_ibl, overrideType, out_iblOverride)) return out_iblOverride[] end """ rprContextCreateSkyLight(context) Create sky light Analytical sky model Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY ### Parameters * `context`: The context to create a light for * `status`: RPR\\_SUCCESS in case of success, error code otherwise ### Returns Light object """ function rprContextCreateSkyLight(context) out_light = Ref{rpr_light}() check_error(ccall((:rprContextCreateSkyLight, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_light}), context, out_light)) return out_light[] end """ rprSkyLightSetTurbidity(skylight, turbidity) Set turbidity of a sky light ### Parameters * `skylight`: Sky light * `turbidity`: Turbidity value ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSkyLightSetTurbidity(skylight, turbidity) check_error(ccall((:rprSkyLightSetTurbidity, libRadeonProRender64), rpr_status, (rpr_light, rpr_float), skylight, turbidity)) end """ rprSkyLightSetAlbedo(skylight, albedo) Set albedo of a sky light ### Parameters * `skylight`: Sky light * `albedo`: Albedo value ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSkyLightSetAlbedo(skylight, albedo) check_error(ccall((:rprSkyLightSetAlbedo, libRadeonProRender64), rpr_status, (rpr_light, rpr_float), skylight, albedo)) end """ rprSkyLightSetScale(skylight, scale) Set scale of a sky light ### Parameters * `skylight`: Sky light * `scale`: Scale value ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSkyLightSetScale(skylight, scale) check_error(ccall((:rprSkyLightSetScale, libRadeonProRender64), rpr_status, (rpr_light, rpr_float), skylight, scale)) end """ rprSkyLightSetDirection(skylight, x, y, z) Set the direction of the sky light ### Parameters * `skylight`: Sky light * `x`: direction x * `y`: direction y * `z`: direction z ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSkyLightSetDirection(skylight, x, y, z) check_error(ccall((:rprSkyLightSetDirection, libRadeonProRender64), rpr_status, (rpr_light, rpr_float, rpr_float, rpr_float), skylight, x, y, z)) end """ rprSkyLightAttachPortal(scene, skylight, portal) Set portal for sky light to accelerate convergence of indoor scenes Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `skylight`: Sky light * `portal`: Portal mesh, might have multiple components ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSkyLightAttachPortal(scene, skylight, portal) check_error(ccall((:rprSkyLightAttachPortal, libRadeonProRender64), rpr_status, (rpr_scene, rpr_light, rpr_shape), scene, skylight, portal)) end """ rprSkyLightDetachPortal(scene, skylight, portal) Remove portal for Sky light. Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `env_light`: Sky light * `portal`: Portal mesh, that have been added to light. ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSkyLightDetachPortal(scene, skylight, portal) check_error(ccall((:rprSkyLightDetachPortal, libRadeonProRender64), rpr_status, (rpr_scene, rpr_light, rpr_shape), scene, skylight, portal)) end """ rprContextCreateIESLight(context, light) Create IES light Create IES light Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY ### Parameters * `context`: The context to create a light for * `status`: RPR\\_SUCCESS in case of success, error code otherwise ### Returns Light object """ function rprContextCreateIESLight(context, light) check_error(ccall((:rprContextCreateIESLight, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_light}), context, light)) end """ rprIESLightSetRadiantPower3f(light, r, g, b) Set radiant power of a IES light source ### Parameters * `r`: R component of a radiant power vector * `g`: G component of a radiant power vector * `b`: B component of a radiant power vector ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprIESLightSetRadiantPower3f(light, r, g, b) check_error(ccall((:rprIESLightSetRadiantPower3f, libRadeonProRender64), rpr_status, (rpr_light, rpr_float, rpr_float, rpr_float), light, r, g, b)) end """ rprIESLightSetImageFromFile(env_light, imagePath, nx, ny) Set image for an IES light Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER RPR\\_ERROR\\_UNSUPPORTED\\_IMAGE\\_FORMAT : If the format of the IES file is not supported by Radeon ProRender. RPR\\_ERROR\\_IO\\_ERROR : If the IES image path file doesn't exist. ### Parameters * `env_light`: Environment light * `imagePath`: Image path to set (for UNICODE, supports UTF-8 encoding) * `nx`: resolution X of the IES image * `ny`: resolution Y of the IES image ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprIESLightSetImageFromFile(env_light, imagePath, nx, ny) check_error(ccall((:rprIESLightSetImageFromFile, libRadeonProRender64), rpr_status, (rpr_light, Ptr{rpr_char}, rpr_int, rpr_int), env_light, imagePath, nx, ny)) end """ rprIESLightSetImageFromIESdata(env_light, iesData, nx, ny) Set image for an IES light Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER RPR\\_ERROR\\_UNSUPPORTED\\_IMAGE\\_FORMAT : If the format of the IES data is not supported by Radeon ProRender. ### Parameters * `env_light`: Environment light * `iesData`: Image data string defining the IES. null terminated string. IES format. * `nx`: resolution X of the IES image * `ny`: resolution Y of the IES image ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprIESLightSetImageFromIESdata(env_light, iesData, nx, ny) check_error(ccall((:rprIESLightSetImageFromIESdata, libRadeonProRender64), rpr_status, (rpr_light, Ptr{rpr_char}, rpr_int, rpr_int), env_light, iesData, nx, ny)) end """ rprLightGetInfo(light, info, size, data, size_ret) Query information about a light The workflow is usually two-step: query with the data == NULL to get the required buffer size, then query with size\\_ret == NULL to fill the buffer with the data Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `light`: The light to query * `light_info`: The type of info to query * `size`: The size of the buffer pointed by data * `data`: The buffer to store queried info * `size_ret`: Returns the size in bytes of the data being queried ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprLightGetInfo(light, info, size, data, size_ret) check_error(ccall((:rprLightGetInfo, libRadeonProRender64), rpr_status, (rpr_light, rpr_light_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), light, info, size, data, size_ret)) end """ rprSceneClear(scene) Remove all objects from a scene Also detaches the camera A scene is essentially a collection of shapes, lights and volume regions. ### Parameters * `scene`: The scene to clear ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSceneClear(scene) check_error(ccall((:rprSceneClear, libRadeonProRender64), rpr_status, (rpr_scene,), scene)) end """ rprSceneAttachShape(scene, shape) Attach a shape to the scene A scene is essentially a collection of shapes, lights and volume regions. ### Parameters * `scene`: The scene to attach * `shape`: The shape to attach ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSceneAttachShape(scene, shape) check_error(ccall((:rprSceneAttachShape, libRadeonProRender64), rpr_status, (rpr_scene, rpr_shape), scene, shape)) end """ rprSceneDetachShape(scene, shape) Detach a shape from the scene A scene is essentially a collection of shapes, lights and volume regions. ### Parameters * `scene`: The scene to dettach from ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSceneDetachShape(scene, shape) check_error(ccall((:rprSceneDetachShape, libRadeonProRender64), rpr_status, (rpr_scene, rpr_shape), scene, shape)) end """ rprSceneAttachHeteroVolume(scene, heteroVolume) Attach a heteroVolume to the scene A scene is essentially a collection of shapes, lights and volume regions. ### Parameters * `scene`: The scene to attach * `heteroVolume`: The heteroVolume to attach ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSceneAttachHeteroVolume(scene, heteroVolume) check_error(ccall((:rprSceneAttachHeteroVolume, libRadeonProRender64), rpr_status, (rpr_scene, rpr_hetero_volume), scene, heteroVolume)) end """ rprSceneDetachHeteroVolume(scene, heteroVolume) Detach a heteroVolume from the scene A scene is essentially a collection of shapes, lights and volume regions. ### Parameters * `scene`: The scene to dettach from ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSceneDetachHeteroVolume(scene, heteroVolume) check_error(ccall((:rprSceneDetachHeteroVolume, libRadeonProRender64), rpr_status, (rpr_scene, rpr_hetero_volume), scene, heteroVolume)) end function rprSceneAttachCurve(scene, curve) check_error(ccall((:rprSceneAttachCurve, libRadeonProRender64), rpr_status, (rpr_scene, rpr_curve), scene, curve)) end function rprSceneDetachCurve(scene, curve) check_error(ccall((:rprSceneDetachCurve, libRadeonProRender64), rpr_status, (rpr_scene, rpr_curve), scene, curve)) end function rprCurveSetMaterial(curve, material) check_error(ccall((:rprCurveSetMaterial, libRadeonProRender64), rpr_status, (rpr_curve, rpr_material_node), curve, material)) end function rprCurveSetTransform(curve, transpose, transform) check_error(ccall((:rprCurveSetTransform, libRadeonProRender64), rpr_status, (rpr_curve, rpr_bool, Ptr{rpr_float}), curve, transpose, transform)) end """ rprContextCreateCurve(context, out_curve, num_controlPoints, controlPointsData, controlPointsStride, num_indices, curveCount, indicesData, radius, textureUV, segmentPerCurve, creationFlag_tapered) Create a set of curves A [`rpr_curve`](@ref) is a set of curves A curve is a set of segments A segment is always composed of 4 3D points ### Parameters * `controlPointsData`: array of [`rpr_float`](@ref)[num\\_controlPoints*3] * `controlPointsStride`: in most of cases, for contiguous controlPointsData, should be set to 3*sizeof(float) * `num_indices`: should be set at : 4*(number of segments) * `indicesData`: array of [`rpr_uint`](@ref)[num\\_indices] . those are indices to the controlPointsData array. * `radius`: array of N float. if curve is not tapered, N = curveCount. if curve is tapered, N = 2*(number of segments) * `textureUV`: array of float2[curveCount]. * `segmentPerCurve`: array of [`rpr_int`](@ref)[curveCount]. (number of segments) = sum of each element of this array. * `creationFlag_tapered`: Set it to 0 by default. Set to 1 if using tapered radius. May be used for other bit field options in the future (so, don't set it to a value > 1 for now.) """ function rprContextCreateCurve(context, out_curve, num_controlPoints, controlPointsData, controlPointsStride, num_indices, curveCount, indicesData, radius, textureUV, segmentPerCurve, creationFlag_tapered) check_error(ccall((:rprContextCreateCurve, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_curve}, Csize_t, Ptr{rpr_float}, rpr_int, Csize_t, rpr_uint, Ptr{rpr_uint}, Ptr{rpr_float}, Ptr{rpr_float}, Ptr{rpr_int}, rpr_uint), context, out_curve, num_controlPoints, controlPointsData, controlPointsStride, num_indices, curveCount, indicesData, radius, textureUV, segmentPerCurve, creationFlag_tapered)) end """ rprSceneAttachLight(scene, light) Attach a light to the scene A scene is essentially a collection of shapes, lights and volume regions ### Parameters * `scene`: The scene to attach * `light`: The light to attach ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSceneAttachLight(scene, light) check_error(ccall((:rprSceneAttachLight, libRadeonProRender64), rpr_status, (rpr_scene, rpr_light), scene, light)) end """ rprSceneDetachLight(scene, light) Detach a light from the scene A scene is essentially a collection of shapes, lights and volume regions ### Parameters * `scene`: The scene to dettach from * `light`: The light to detach ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSceneDetachLight(scene, light) check_error(ccall((:rprSceneDetachLight, libRadeonProRender64), rpr_status, (rpr_scene, rpr_light), scene, light)) end """ rprSceneSetEnvironmentLight(in_scene, in_light) Sets/gets environment override as active in scene ### Parameters * `in_scene`: scene * `in_light`: ibl """ function rprSceneSetEnvironmentLight(in_scene, in_light) check_error(ccall((:rprSceneSetEnvironmentLight, libRadeonProRender64), rpr_status, (rpr_scene, rpr_light), in_scene, in_light)) end function rprSceneGetEnvironmentLight(in_scene) out_light = Ref{rpr_light}() check_error(ccall((:rprSceneGetEnvironmentLight, libRadeonProRender64), rpr_status, (rpr_scene, Ptr{rpr_light}), in_scene, out_light)) return out_light[] end """ rprSceneGetInfo(scene, info, size, data, size_ret) Query information about a scene The workflow is usually two-step: query with the data == NULL to get the required buffer size, then query with size\\_ret == NULL to fill the buffer with the data Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `scene`: The scene to query * `info`: The type of info to query * `size`: The size of the buffer pointed by data * `data`: The buffer to store queried info * `size_ret`: Returns the size in bytes of the data being queried ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSceneGetInfo(scene, info, size, data, size_ret) check_error(ccall((:rprSceneGetInfo, libRadeonProRender64), rpr_status, (rpr_scene, rpr_scene_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), scene, info, size, data, size_ret)) end """ rprSceneSetBackgroundImage(scene, image) Set background image for the scene which does not affect the scene lighting, it is shown as view-independent rectangular background Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `scene`: The scene to set background for * `image`: Background image ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSceneSetBackgroundImage(scene, image) check_error(ccall((:rprSceneSetBackgroundImage, libRadeonProRender64), rpr_status, (rpr_scene, rpr_image), scene, image)) end """ rprSceneGetBackgroundImage(scene) Get background image ### Parameters * `scene`: The scene to get background image from * `status`: RPR\\_SUCCESS in case of success, error code otherwise ### Returns Image object """ function rprSceneGetBackgroundImage(scene) out_image = Ref{rpr_image}() check_error(ccall((:rprSceneGetBackgroundImage, libRadeonProRender64), rpr_status, (rpr_scene, Ptr{rpr_image}), scene, out_image)) return out_image[] end """ rprSceneSetCameraRight(scene, camera) Set right camera for the scene This is the main camera which for rays generation for the scene. ### Parameters * `scene`: The scene to set camera for * `camera`: Camera ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSceneSetCameraRight(scene, camera) check_error(ccall((:rprSceneSetCameraRight, libRadeonProRender64), rpr_status, (rpr_scene, rpr_camera), scene, camera)) end """ rprSceneGetCameraRight(scene) Get right camera for the scene ### Parameters * `scene`: The scene to get camera for * `status`: RPR\\_SUCCESS in case of success, error code otherwise ### Returns camera id for the camera if any, NULL otherwise """ function rprSceneGetCameraRight(scene) out_camera = Ref{rpr_camera}() check_error(ccall((:rprSceneGetCameraRight, libRadeonProRender64), rpr_status, (rpr_scene, Ptr{rpr_camera}), scene, out_camera)) return out_camera[] end """ rprSceneSetCamera(scene, camera) Set camera for the scene This is the main camera which for rays generation for the scene. ### Parameters * `scene`: The scene to set camera for * `camera`: Camera ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprSceneSetCamera(scene, camera) check_error(ccall((:rprSceneSetCamera, libRadeonProRender64), rpr_status, (rpr_scene, rpr_camera), scene, camera)) end """ rprSceneGetCamera(scene) Get camera for the scene ### Parameters * `scene`: The scene to get camera for * `status`: RPR\\_SUCCESS in case of success, error code otherwise ### Returns camera id for the camera if any, NULL otherwise """ function rprSceneGetCamera(scene) out_camera = Ref{rpr_camera}() check_error(ccall((:rprSceneGetCamera, libRadeonProRender64), rpr_status, (rpr_scene, Ptr{rpr_camera}), scene, out_camera)) return out_camera[] end """ rprFrameBufferGetInfo(framebuffer, info, size, data, size_ret) Query information about a framebuffer The workflow is usually two-step: query with the data == NULL to get the required buffer size, then query with size\\_ret == NULL to fill the buffer with the data Possible error codes: RPR\\_ERROR\\_INVALID\\_PARAMETER ### Parameters * `framebuffer`: Framebuffer object to query * `info`: The type of info to query * `size`: The size of the buffer pointed by data * `data`: The buffer to store queried info * `size_ret`: Returns the size in bytes of the data being queried ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprFrameBufferGetInfo(framebuffer, info, size, data, size_ret) check_error(ccall((:rprFrameBufferGetInfo, libRadeonProRender64), rpr_status, (rpr_framebuffer, rpr_framebuffer_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), framebuffer, info, size, data, size_ret)) end """ rprFrameBufferClear(frame_buffer) Clear contents of a framebuffer to zero Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY The call is blocking and the image is ready when returned ### Parameters * `frame_buffer`: Framebuffer to clear ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprFrameBufferClear(frame_buffer) check_error(ccall((:rprFrameBufferClear, libRadeonProRender64), rpr_status, (rpr_framebuffer,), frame_buffer)) end """ rprFrameBufferFillWithColor(frame_buffer, r, g, b, a) Fill contents of a framebuffer with a single color Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY The call is blocking and the image is ready when returned. If you want to fill with zeros, it's advised to use [`rprFrameBufferClear`](@ref). ### Parameters * `frame_buffer`: Framebuffer to clear * `r,g,b,a`: : the color to fill ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprFrameBufferFillWithColor(frame_buffer, r, g, b, a) check_error(ccall((:rprFrameBufferFillWithColor, libRadeonProRender64), rpr_status, (rpr_framebuffer, rpr_float, rpr_float, rpr_float, rpr_float), frame_buffer, r, g, b, a)) end """ rprFrameBufferSaveToFile(frame_buffer, file_path) Save frame buffer to file. In case the file format is .bin, the header of the saved file contains [`rpr_framebuffer_desc`](@ref) and [`rpr_framebuffer_format`](@ref) at very begining. The remaining data is raw data of saved framebuffer. Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY ### Parameters * `frame_buffer`: Frame buffer to save * `file_path`: Path to file (for UNICODE, supports UTF-8 encoding) ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprFrameBufferSaveToFile(frame_buffer, file_path) check_error(ccall((:rprFrameBufferSaveToFile, libRadeonProRender64), rpr_status, (rpr_framebuffer, Ptr{rpr_char}), frame_buffer, file_path)) end """ rprFrameBufferSaveToFileEx(framebufferList, framebufferCount, filePath, extraOptions) Save frame buffer to file Same that [`rprFrameBufferSaveToFile`](@ref), but more options. A list of frambuffers can be given, they will be saved to a multilayer EXR. 'extraOptions' is not used for now, but may be use in the future to define some export options, like channel configurations, compression... It must be set to NULL for now. For layer names, the framebuffer names ( from [`rprObjectSetName`](@ref) ) will be used if it exists. As this function is new ( 2.01.6 SDK ) and still experimental, its arguments may change in the future. """ function rprFrameBufferSaveToFileEx(framebufferList, framebufferCount, filePath, extraOptions) check_error(ccall((:rprFrameBufferSaveToFileEx, libRadeonProRender64), rpr_status, (Ptr{rpr_framebuffer}, rpr_uint, Ptr{rpr_char}, Ptr{Cvoid}), framebufferList, framebufferCount, filePath, extraOptions)) end """ rprContextResolveFrameBuffer(context, src_frame_buffer, dst_frame_buffer, noDisplayGamma) Resolve framebuffer Convert the input Renderer's native raw format 'src\\_frame\\_buffer' into an output 'dst\\_frame\\_buffer' that can be used for final rendering. src\\_frame\\_buffer and dst\\_frame\\_buffer should usually have the same dimension/format. src\\_frame\\_buffer is the result of a [`rprContextRender`](@ref) and should be attached to an AOV with [`rprContextSetAOV`](@ref) before the [`rprContextRender`](@ref) call. dst\\_frame\\_buffer should not be attached to any AOV. The post process that is applied to src\\_frame\\_buffer depends on the AOV it's attached to. So it's important to not modify its AOV ( with [`rprContextSetAOV`](@ref) ) between the [`rprContextRender`](@ref) and [`rprContextResolveFrameBuffer`](@ref) calls. If noDisplayGamma=FALSE, then RPR\\_CONTEXT\\_DISPLAY\\_GAMMA is applied to the dst\\_frame\\_buffer otherwise, display gamma is not used. It's recommended to set it to FALSE for AOVs representing colors ( like RPR\\_AOV\\_COLOR ) and use TRUE for other AOVs. """ function rprContextResolveFrameBuffer(context, src_frame_buffer, dst_frame_buffer, noDisplayGamma) check_error(ccall((:rprContextResolveFrameBuffer, libRadeonProRender64), rpr_status, (rpr_context, rpr_framebuffer, rpr_framebuffer, rpr_bool), context, src_frame_buffer, dst_frame_buffer, noDisplayGamma)) end """ rprMaterialSystemGetInfo(in_material_system, type, in_size, in_data) Create material system Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY """ function rprMaterialSystemGetInfo(in_material_system, type, in_size, in_data) out_size = Ref{Csize_t}() check_error(ccall((:rprMaterialSystemGetInfo, libRadeonProRender64), rpr_status, (rpr_material_system, rpr_material_system_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), in_material_system, type, in_size, in_data, out_size)) return out_size[] end """ rprContextCreateMaterialSystem(in_context, type) Get material system information Possible error codes: RPR\\_ERROR\\_INTERNAL\\_ERROR """ function rprContextCreateMaterialSystem(in_context, type) out_matsys = Ref{rpr_material_system}() check_error(ccall((:rprContextCreateMaterialSystem, libRadeonProRender64), rpr_status, (rpr_context, rpr_material_system_type, Ptr{rpr_material_system}), in_context, type, out_matsys)) return out_matsys[] end """ rprMaterialSystemGetSize(in_context) Create material node Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY """ function rprMaterialSystemGetSize(in_context) out_size = Ref{rpr_uint}() check_error(ccall((:rprMaterialSystemGetSize, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_uint}), in_context, out_size)) return out_size[] end """ rprMaterialSystemCreateNode(in_matsys, in_type) Returns the number of material nodes for a given material system Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY """ function rprMaterialSystemCreateNode(in_matsys, in_type) out_node = Ref{rpr_material_node}() check_error(ccall((:rprMaterialSystemCreateNode, libRadeonProRender64), rpr_status, (rpr_material_system, rpr_material_node_type, Ptr{rpr_material_node}), in_matsys, in_type, out_node)) return out_node[] end """ rprMaterialNodeSetID(in_node, id) set the RPR\\_MATERIAL\\_NODE\\_ID of a material. this ID doesn't need to be unique. this ID can be rendered with the RPR\\_AOV\\_MATERIAL\\_ID AOV - color of this AOV can be customized with [`rprContextSetAOVindexLookup`](@ref). """ function rprMaterialNodeSetID(in_node, id) check_error(ccall((:rprMaterialNodeSetID, libRadeonProRender64), rpr_status, (rpr_material_node, rpr_uint), in_node, id)) end """ rprMaterialNodeSetInputNByKey(in_node, in_input, in_input_node) Connect nodes Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY """ function rprMaterialNodeSetInputNByKey(in_node, in_input, in_input_node) check_error(ccall((:rprMaterialNodeSetInputNByKey, libRadeonProRender64), rpr_status, (rpr_material_node, rpr_material_node_input, rpr_material_node), in_node, in_input, in_input_node)) end """ rprMaterialNodeSetInputFByKey(in_node, in_input, in_value_x, in_value_y, in_value_z, in_value_w) Set float input value Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY """ function rprMaterialNodeSetInputFByKey(in_node, in_input, in_value_x, in_value_y, in_value_z, in_value_w) check_error(ccall((:rprMaterialNodeSetInputFByKey, libRadeonProRender64), rpr_status, (rpr_material_node, rpr_material_node_input, rpr_float, rpr_float, rpr_float, rpr_float), in_node, in_input, in_value_x, in_value_y, in_value_z, in_value_w)) end """ rprMaterialNodeSetInputDataByKey(in_node, in_input, data, dataSizeByte) Set generic data input value: Some complex materials inputs may need more than 4-floats or int. This API can be used to set any generic input data. Use it only when documentation requests to do it for specific material inputs. """ function rprMaterialNodeSetInputDataByKey(in_node, in_input, data, dataSizeByte) check_error(ccall((:rprMaterialNodeSetInputDataByKey, libRadeonProRender64), rpr_status, (rpr_material_node, rpr_material_node_input, Ptr{Cvoid}, Csize_t), in_node, in_input, data, dataSizeByte)) end """ rprMaterialNodeSetInputUByKey(in_node, in_input, in_value) Set uint input value Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY """ function rprMaterialNodeSetInputUByKey(in_node, in_input, in_value) check_error(ccall((:rprMaterialNodeSetInputUByKey, libRadeonProRender64), rpr_status, (rpr_material_node, rpr_material_node_input, rpr_uint), in_node, in_input, in_value)) end """ rprMaterialNodeSetInputImageDataByKey(in_node, in_input, image) Set image input value Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY """ function rprMaterialNodeSetInputImageDataByKey(in_node, in_input, image) check_error(ccall((:rprMaterialNodeSetInputImageDataByKey, libRadeonProRender64), rpr_status, (rpr_material_node, rpr_material_node_input, rpr_image), in_node, in_input, image)) end """ rprMaterialNodeSetInputLightDataByKey(in_node, in_input, light) Set light input value """ function rprMaterialNodeSetInputLightDataByKey(in_node, in_input, light) check_error(ccall((:rprMaterialNodeSetInputLightDataByKey, libRadeonProRender64), rpr_status, (rpr_material_node, rpr_material_node_input, rpr_light), in_node, in_input, light)) end """ rprMaterialNodeSetInputBufferDataByKey(in_node, in_input, buffer) Set Buffer input value """ function rprMaterialNodeSetInputBufferDataByKey(in_node, in_input, buffer) check_error(ccall((:rprMaterialNodeSetInputBufferDataByKey, libRadeonProRender64), rpr_status, (rpr_material_node, rpr_material_node_input, rpr_buffer), in_node, in_input, buffer)) end """ rprMaterialNodeSetInputGridDataByKey(in_node, in_input, grid) Set Grid input value """ function rprMaterialNodeSetInputGridDataByKey(in_node, in_input, grid) check_error(ccall((:rprMaterialNodeSetInputGridDataByKey, libRadeonProRender64), rpr_status, (rpr_material_node, rpr_material_node_input, rpr_grid), in_node, in_input, grid)) end function rprMaterialNodeGetInfo(in_node, in_info, in_size, in_data) out_size = Ref{Csize_t}() check_error(ccall((:rprMaterialNodeGetInfo, libRadeonProRender64), rpr_status, (rpr_material_node, rpr_material_node_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), in_node, in_info, in_size, in_data, out_size)) return out_size[] end function rprMaterialNodeGetInputInfo(in_node, in_input_idx, in_info, in_size, in_data) out_size = Ref{Csize_t}() check_error(ccall((:rprMaterialNodeGetInputInfo, libRadeonProRender64), rpr_status, (rpr_material_node, rpr_int, rpr_material_node_input_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), in_node, in_input_idx, in_info, in_size, in_data, out_size)) return out_size[] end function rprContextCreateComposite(context, in_type) out_composite = Ref{rpr_composite}() check_error(ccall((:rprContextCreateComposite, libRadeonProRender64), rpr_status, (rpr_context, rpr_composite_type, Ptr{rpr_composite}), context, in_type, out_composite)) return out_composite[] end function rprContextCreateLUTFromFile(context, fileLutPath) out_lut = Ref{rpr_lut}() check_error(ccall((:rprContextCreateLUTFromFile, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_char}, Ptr{rpr_lut}), context, fileLutPath, out_lut)) return out_lut[] end function rprContextCreateLUTFromData(context, lutData) out_lut = Ref{rpr_lut}() check_error(ccall((:rprContextCreateLUTFromData, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_char}, Ptr{rpr_lut}), context, lutData, out_lut)) return out_lut[] end function rprCompositeSetInputFb(composite, inputName, input) check_error(ccall((:rprCompositeSetInputFb, libRadeonProRender64), rpr_status, (rpr_composite, Ptr{rpr_char}, rpr_framebuffer), composite, inputName, input)) end function rprCompositeSetInputC(composite, inputName, input) check_error(ccall((:rprCompositeSetInputC, libRadeonProRender64), rpr_status, (rpr_composite, Ptr{rpr_char}, rpr_composite), composite, inputName, input)) end function rprCompositeSetInputLUT(composite, inputName, input) check_error(ccall((:rprCompositeSetInputLUT, libRadeonProRender64), rpr_status, (rpr_composite, Ptr{rpr_char}, rpr_lut), composite, inputName, input)) end function rprCompositeSetInput4f(composite, inputName, x, y, z, w) check_error(ccall((:rprCompositeSetInput4f, libRadeonProRender64), rpr_status, (rpr_composite, Ptr{rpr_char}, Cfloat, Cfloat, Cfloat, Cfloat), composite, inputName, x, y, z, w)) end function rprCompositeSetInput1u(composite, inputName, value) check_error(ccall((:rprCompositeSetInput1u, libRadeonProRender64), rpr_status, (rpr_composite, Ptr{rpr_char}, rpr_uint), composite, inputName, value)) end function rprCompositeSetInputOp(composite, inputName, op) check_error(ccall((:rprCompositeSetInputOp, libRadeonProRender64), rpr_status, (rpr_composite, Ptr{rpr_char}, rpr_material_node_arithmetic_operation), composite, inputName, op)) end function rprCompositeCompute(composite, fb) check_error(ccall((:rprCompositeCompute, libRadeonProRender64), rpr_status, (rpr_composite, rpr_framebuffer), composite, fb)) end function rprCompositeGetInfo(composite, composite_info, size, data, size_ret) check_error(ccall((:rprCompositeGetInfo, libRadeonProRender64), rpr_status, (rpr_composite, rpr_composite_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), composite, composite_info, size, data, size_ret)) end """ rprObjectDelete(obj) Delete object [`rprObjectDelete`](@ref)(obj) deletes 'obj' from memory. User has to make sure that 'obj' will not be used anymore after this call. Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY """ function rprObjectDelete(obj) check_error(ccall((:rprObjectDelete, libRadeonProRender64), rpr_status, (Ptr{Cvoid},), obj)) end """ rprObjectSetName(node, name) Set material node name ### Parameters * `node`: Node to set the name for * `name`: NULL terminated string name ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprObjectSetName(node, name) check_error(ccall((:rprObjectSetName, libRadeonProRender64), rpr_status, (Ptr{Cvoid}, Ptr{rpr_char}), node, name)) end """ rprObjectSetCustomPointer(node, customPtr) Set a custom pointer to an RPR object ( [`rpr_shape`](@ref), [`rpr_image`](@ref) ... ) The custom pointer is not used internally by RPR. The API user only is responsible of it. An example of usage of this pointer is the C++ wrapper ( RadeonProRender.hpp ) ### Parameters * `node`: Node to set the 'custom pointer' for * `customPtr`: Any 8 bytes value decided by the API user. ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprObjectSetCustomPointer(node, customPtr) check_error(ccall((:rprObjectSetCustomPointer, libRadeonProRender64), rpr_status, (Ptr{Cvoid}, Ptr{Cvoid}), node, customPtr)) end """ rprObjectGetCustomPointer(node, customPtr_out) outputs the 'custom pointer' set by [`rprObjectSetCustomPointer`](@ref). Equivalent of the calls : [`rprImageGetInfo`](@ref)(image,RPR\\_IMAGE\\_CUSTOM\\_PTR,...) for [`rpr_image`](@ref) , [`rprCameraGetInfo`](@ref)(camera,RPR\\_CAMERA\\_CUSTOM\\_PTR,...) for [`rpr_camera`](@ref) , ...etc... ### Returns RPR\\_SUCCESS in case of success, error code otherwise """ function rprObjectGetCustomPointer(node, customPtr_out) check_error(ccall((:rprObjectGetCustomPointer, libRadeonProRender64), rpr_status, (Ptr{Cvoid}, Ptr{Ptr{Cvoid}}), node, customPtr_out)) end """ rprContextCreatePostEffect(context, type) Create post effect Create analytic point light represented by a point in space. Possible error codes: RPR\\_ERROR\\_OUT\\_OF\\_VIDEO\\_MEMORY RPR\\_ERROR\\_OUT\\_OF\\_SYSTEM\\_MEMORY ### Parameters * `context`: The context to create a light for * `status`: RPR\\_SUCCESS in case of success, error code otherwise ### Returns Light object """ function rprContextCreatePostEffect(context, type) out_effect = Ref{rpr_post_effect}() check_error(ccall((:rprContextCreatePostEffect, libRadeonProRender64), rpr_status, (rpr_context, rpr_post_effect_type, Ptr{rpr_post_effect}), context, type, out_effect)) return out_effect[] end function rprContextAttachPostEffect(context, effect) check_error(ccall((:rprContextAttachPostEffect, libRadeonProRender64), rpr_status, (rpr_context, rpr_post_effect), context, effect)) end function rprContextDetachPostEffect(context, effect) check_error(ccall((:rprContextDetachPostEffect, libRadeonProRender64), rpr_status, (rpr_context, rpr_post_effect), context, effect)) end function rprPostEffectSetParameter1u(effect, name, x) check_error(ccall((:rprPostEffectSetParameter1u, libRadeonProRender64), rpr_status, (rpr_post_effect, Ptr{rpr_char}, rpr_uint), effect, name, x)) end function rprPostEffectSetParameter1f(effect, name, x) check_error(ccall((:rprPostEffectSetParameter1f, libRadeonProRender64), rpr_status, (rpr_post_effect, Ptr{rpr_char}, rpr_float), effect, name, x)) end function rprPostEffectSetParameter3f(effect, name, x, y, z) check_error(ccall((:rprPostEffectSetParameter3f, libRadeonProRender64), rpr_status, (rpr_post_effect, Ptr{rpr_char}, rpr_float, rpr_float, rpr_float), effect, name, x, y, z)) end function rprPostEffectSetParameter4f(effect, name, x, y, z, w) check_error(ccall((:rprPostEffectSetParameter4f, libRadeonProRender64), rpr_status, (rpr_post_effect, Ptr{rpr_char}, rpr_float, rpr_float, rpr_float, rpr_float), effect, name, x, y, z, w)) end function rprContextGetAttachedPostEffectCount(context, nb) check_error(ccall((:rprContextGetAttachedPostEffectCount, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_uint}), context, nb)) end function rprContextGetAttachedPostEffect(context, i) out_effect = Ref{rpr_post_effect}() check_error(ccall((:rprContextGetAttachedPostEffect, libRadeonProRender64), rpr_status, (rpr_context, rpr_uint, Ptr{rpr_post_effect}), context, i, out_effect)) return out_effect[] end function rprPostEffectGetInfo(effect, info, size, data, size_ret) check_error(ccall((:rprPostEffectGetInfo, libRadeonProRender64), rpr_status, (rpr_post_effect, rpr_post_effect_info, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), effect, info, size, data, size_ret)) end function rprContextCreateGrid(context, out_grid, gridSizeX, gridSizeY, gridSizeZ, indicesList, numberOfIndices, indicesListTopology, gridData, gridDataSizeByte, gridDataTopology___unused) check_error(ccall((:rprContextCreateGrid, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_grid}, Csize_t, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, rpr_grid_indices_topology, Ptr{Cvoid}, Csize_t, rpr_uint), context, out_grid, gridSizeX, gridSizeY, gridSizeZ, indicesList, numberOfIndices, indicesListTopology, gridData, gridDataSizeByte, gridDataTopology___unused)) end function rprContextCreateHeteroVolume(context) out_heteroVolume = Ref{rpr_hetero_volume}() check_error(ccall((:rprContextCreateHeteroVolume, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_hetero_volume}), context, out_heteroVolume)) return out_heteroVolume[] end function rprShapeSetHeteroVolume(shape, heteroVolume) check_error(ccall((:rprShapeSetHeteroVolume, libRadeonProRender64), rpr_status, (rpr_shape, rpr_hetero_volume), shape, heteroVolume)) end function rprHeteroVolumeSetTransform(heteroVolume, transpose, transform) check_error(ccall((:rprHeteroVolumeSetTransform, libRadeonProRender64), rpr_status, (rpr_hetero_volume, rpr_bool, Ptr{rpr_float}), heteroVolume, transpose, transform)) end function rprHeteroVolumeSetEmissionGrid(heteroVolume, grid) check_error(ccall((:rprHeteroVolumeSetEmissionGrid, libRadeonProRender64), rpr_status, (rpr_hetero_volume, rpr_grid), heteroVolume, grid)) end function rprHeteroVolumeSetDensityGrid(heteroVolume, grid) check_error(ccall((:rprHeteroVolumeSetDensityGrid, libRadeonProRender64), rpr_status, (rpr_hetero_volume, rpr_grid), heteroVolume, grid)) end function rprHeteroVolumeSetAlbedoGrid(heteroVolume, grid) check_error(ccall((:rprHeteroVolumeSetAlbedoGrid, libRadeonProRender64), rpr_status, (rpr_hetero_volume, rpr_grid), heteroVolume, grid)) end function rprHeteroVolumeSetEmissionLookup(heteroVolume, ptr, n) check_error(ccall((:rprHeteroVolumeSetEmissionLookup, libRadeonProRender64), rpr_status, (rpr_hetero_volume, Ptr{rpr_float}, rpr_uint), heteroVolume, ptr, n)) end function rprHeteroVolumeSetDensityLookup(heteroVolume, ptr, n) check_error(ccall((:rprHeteroVolumeSetDensityLookup, libRadeonProRender64), rpr_status, (rpr_hetero_volume, Ptr{rpr_float}, rpr_uint), heteroVolume, ptr, n)) end function rprHeteroVolumeSetAlbedoLookup(heteroVolume, ptr, n) check_error(ccall((:rprHeteroVolumeSetAlbedoLookup, libRadeonProRender64), rpr_status, (rpr_hetero_volume, Ptr{rpr_float}, rpr_uint), heteroVolume, ptr, n)) end function rprHeteroVolumeSetAlbedoScale(heteroVolume, scale) check_error(ccall((:rprHeteroVolumeSetAlbedoScale, libRadeonProRender64), rpr_status, (rpr_hetero_volume, rpr_float), heteroVolume, scale)) end function rprHeteroVolumeSetEmissionScale(heteroVolume, scale) check_error(ccall((:rprHeteroVolumeSetEmissionScale, libRadeonProRender64), rpr_status, (rpr_hetero_volume, rpr_float), heteroVolume, scale)) end function rprHeteroVolumeSetDensityScale(heteroVolume, scale) check_error(ccall((:rprHeteroVolumeSetDensityScale, libRadeonProRender64), rpr_status, (rpr_hetero_volume, rpr_float), heteroVolume, scale)) end """ rprLoadMaterialX(in_context, in_matsys, xmlData, incudeData, includeCount, resourcePaths, resourcePathsCount, imageAlreadyCreated_count, imageAlreadyCreated_paths, imageAlreadyCreated_list, listNodesOut, listNodesOut_count, listImagesOut, listImagesOut_count, rootNodeOut, rootDisplacementNodeOut) Parse a MaterialX XML data, and create the Material graph composed of rpr\\_material\\_nodes, and rpr\\_images -----> This function is part of the 'Version 1' API - deprecated and replaced by the 'Version 2' API This function is NOT traced. However internally it's calling some RPR API to build the graph, those calls are traced. ### Parameters * `xmlData`: null-terminated string of the MaterialX XML data * `resourcePaths`: and resourcePathsCount list of paths used for image loading * `imageAlreadyCreated_count`: * `imageAlreadyCreated_paths`: * `imageAlreadyCreated_list`: We can specify a list of [`rpr_image`](@ref) that are already loaded. If [`rprLoadMaterialX`](@ref) finds any images in the XML belonging to this list it will use it directly instead of creating it with [`rprContextCreateImageFromFile`](@ref) Those images will not be added in the listImagesOut list. example to add an image in the imageAlreadyCreated list: imageAlreadyCreated\\_count = 1 imageAlreadyCreated\\_paths[0] = "../../Textures/UVCheckerMap13-1024.png" // same path specified in the 'value' of the image in the XML imageAlreadyCreated\\_list[0] = ([`rpr_image`](@ref)) existing\\_rpr\\_image imageAlreadyCreated\\_paths and imageAlreadyCreated\\_list must have the same size. * `listNodesOut`: * `listImagesOut`: Thoses 2 buffers are allocated by [`rprLoadMaterialX`](@ref), then you should use [`rprLoadMaterialX_free`](@ref) to free them. they contain the list of rpr\\_material and [`rpr_image`](@ref) created by [`rprLoadMaterialX`](@ref). * `rootNodeOut`: Closure node in the material graph. Index inside listNodesOut. Could be -1 if an error occured. This is the material that should be assigned to shape: [`rprShapeSetMaterial`](@ref)(shape,listNodesOut[rootNodeOut]); """ function rprLoadMaterialX(in_context, in_matsys, xmlData, incudeData, includeCount, resourcePaths, resourcePathsCount, imageAlreadyCreated_count, imageAlreadyCreated_paths, imageAlreadyCreated_list, listNodesOut, listNodesOut_count, listImagesOut, listImagesOut_count, rootNodeOut, rootDisplacementNodeOut) check_error(ccall((:rprLoadMaterialX, libRadeonProRender64), rpr_status, (rpr_context, rpr_material_system, Ptr{Cchar}, Ptr{Ptr{Cchar}}, Cint, Ptr{Ptr{Cchar}}, Cint, Cint, Ptr{Ptr{Cchar}}, Ptr{rpr_image}, Ptr{Ptr{rpr_material_node}}, Ptr{rpr_uint}, Ptr{Ptr{rpr_image}}, Ptr{rpr_uint}, Ptr{rpr_uint}, Ptr{rpr_uint}), in_context, in_matsys, xmlData, incudeData, includeCount, resourcePaths, resourcePathsCount, imageAlreadyCreated_count, imageAlreadyCreated_paths, imageAlreadyCreated_list, listNodesOut, listNodesOut_count, listImagesOut, listImagesOut_count, rootNodeOut, rootDisplacementNodeOut)) end """ rprLoadMaterialX_free(listNodes, listImages) Free the buffers allocated by [`rprLoadMaterialX`](@ref) -----> This function is part of the 'Version 1' API - deprecated and replaced by the 'Version 2' API It does NOT call any [`rprObjectDelete`](@ref) Internally it's doing a simple: delete[] listNodes; delete[] listImages; This function is NOT traced. """ function rprLoadMaterialX_free(listNodes, listImages) check_error(ccall((:rprLoadMaterialX_free, libRadeonProRender64), rpr_status, (Ptr{rpr_material_node}, Ptr{rpr_image}), listNodes, listImages)) end """ rprMaterialXAddResourceFolder(in_context, resourcePath) Add resource search path. -----> Note: This function is part of the 'Version 2' MaterialX API that replaces 'Version 1' example: [`rprMaterialXAddResourceFolder`](@ref)(context, "dependency/"); [`rprMaterialXAddResourceFolder`](@ref)(context, "../imageLib/"); [`rprMaterialXSetFile`](@ref)(material, "materialx.mtlx"); During the parsing of "materialx.mtlx" inside the [`rprMaterialXSetFile`](@ref) call, the folder path "dependency/" , "../imageLib/" will be used to search any files referenced in the materialX """ function rprMaterialXAddResourceFolder(in_context, resourcePath) check_error(ccall((:rprMaterialXAddResourceFolder, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_char}), in_context, resourcePath)) end """ rprMaterialXCleanResourceFolder(in_context) Clean the list created by [`rprMaterialXAddResourceFolder`](@ref) calls -----> Note: This function is part of the 'Version 2' MaterialX API that replaces 'Version 1' """ function rprMaterialXCleanResourceFolder(in_context) check_error(ccall((:rprMaterialXCleanResourceFolder, libRadeonProRender64), rpr_status, (rpr_context,), in_context)) end """ rprMaterialXAddDependencyMtlx(in_context, resourcePath) Add a dependency Mtlx file. -----> Note: This function is part of the 'Version 2' MaterialX API that replaces 'Version 1' example: [`rprMaterialXAddDependencyMtlx`](@ref)(context, "standard\\_surface.mtlx"); [`rprMaterialXSetFile`](@ref)(material, "materialx.mtlx"); During the parsing of "materialx.mtlx" inside the [`rprMaterialXSetFile`](@ref) call, standard\\_surface.mtlx is also parsed and used as a dependancy file. """ function rprMaterialXAddDependencyMtlx(in_context, resourcePath) check_error(ccall((:rprMaterialXAddDependencyMtlx, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_char}), in_context, resourcePath)) end """ rprMaterialXAddDependencyMtlxAsBuffer(in_context, buffer, bufferSize) Add a dependency Mtlx file. Same than [`rprMaterialXAddDependencyMtlx`](@ref), but input a file buffer instead of the file. -----> Note: This function is part of the 'Version 2' MaterialX API that replaces 'Version 1' 'buffer' represents the content of a XML string defining the MaterialX material. The size of the buffer is defined by 'bufferSize', not by a null-terminated character. example: [`rprMaterialXAddDependencyMtlxAsBuffer`](@ref)(context, inbuffer, size); [`rprMaterialXSetFile`](@ref)(material, "materialx.mtlx"); During the parsing of "materialx.mtlx" inside the [`rprMaterialXSetFile`](@ref) call, 'inbuffer' is also parsed and used as a dependancy file. """ function rprMaterialXAddDependencyMtlxAsBuffer(in_context, buffer, bufferSize) check_error(ccall((:rprMaterialXAddDependencyMtlxAsBuffer, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_char}, Csize_t), in_context, buffer, bufferSize)) end """ rprMaterialXCleanDependencyMtlx(in_context) Clean the list created by [`rprMaterialXAddDependencyMtlx`](@ref) / [`rprMaterialXAddDependencyMtlxAsBuffer`](@ref) calls -----> Note: This function is part of the 'Version 2' MaterialX API that replaces 'Version 1' """ function rprMaterialXCleanDependencyMtlx(in_context) check_error(ccall((:rprMaterialXCleanDependencyMtlx, libRadeonProRender64), rpr_status, (rpr_context,), in_context)) end """ rprMaterialXAddPreloadedImage(in_context, imgPath, img) Add a pre-loaded image to the MaterialX creation. -----> Note: This function is part of the 'Version 2' MaterialX API that replaces 'Version 1' example: [`rprMaterialXAddPreloadedImage`](@ref)(context, "images/back.png" , imgA); [`rprMaterialXAddPreloadedImage`](@ref)(context, "images/skin.png" , imgB); [`rprMaterialXSetFile`](@ref)(material, "materialx.mtlx"); During the parsing of "materialx.mtlx" inside the [`rprMaterialXSetFile`](@ref) call, if an image uses the exact path "images/back.png" or "images/skin.png" , then [`rprMaterialXSetFile`](@ref) will use imgA/imgB instead of creation the image itself. """ function rprMaterialXAddPreloadedImage(in_context, imgPath, img) check_error(ccall((:rprMaterialXAddPreloadedImage, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_char}, rpr_image), in_context, imgPath, img)) end """ rprMaterialXCleanPreloadedImages(in_context) Clean the map created by [`rprMaterialXAddPreloadedImage`](@ref) calls. -----> Note: This function is part of the 'Version 2' MaterialX API that replaces 'Version 1' """ function rprMaterialXCleanPreloadedImages(in_context) check_error(ccall((:rprMaterialXCleanPreloadedImages, libRadeonProRender64), rpr_status, (rpr_context,), in_context)) end """ rprMaterialXSetFile(material, xmlPath) Assign the materialX file to a RPR material. -----> Note: This function is part of the 'Version 2' MaterialX API that replaces 'Version 1' The material must be created as RPR\\_MATERIAL\\_NODE\\_MATX type. """ function rprMaterialXSetFile(material, xmlPath) check_error(ccall((:rprMaterialXSetFile, libRadeonProRender64), rpr_status, (rpr_material_node, Ptr{rpr_char}), material, xmlPath)) end """ rprMaterialXSetFileAsBuffer(material, buffer, bufferSize) Same that [`rprMaterialXSetFile`](@ref) but input a file buffer instead of the file. -----> Note: This function is part of the 'Version 2' MaterialX API that replaces 'Version 1' 'buffer' represents the content of a XML string defining the MaterialX material. The size of the buffer is defined by 'bufferSize', not by a null-terminated character. """ function rprMaterialXSetFileAsBuffer(material, buffer, bufferSize) check_error(ccall((:rprMaterialXSetFileAsBuffer, libRadeonProRender64), rpr_status, (rpr_material_node, Ptr{rpr_char}, Csize_t), material, buffer, bufferSize)) end """ rprMaterialXGetLoaderMessages(in_context, size, data, size_ret) Return the Warning/Error messages from the last MaterialX Loading. This function helps to debug. If [`rprMaterialXSetFile`](@ref)/[`rprMaterialXSetFileAsBuffer`](@ref) fails, it's a good practice to call [`rprMaterialXGetLoaderMessages`](@ref) just after. 'size' is the size of allocated 'data' buffer. 'data' can be nullptr if we only want to get 'size\\_ret'. 'size\\_ret' is the actual size of the out buffer - can be nullptr. """ function rprMaterialXGetLoaderMessages(in_context, size, data, size_ret) check_error(ccall((:rprMaterialXGetLoaderMessages, libRadeonProRender64), rpr_status, (rpr_context, Csize_t, Ptr{Cvoid}, Ptr{Csize_t}), in_context, size, data, size_ret)) end """ rprMaterialXBindGeomPropToPrimvar(in_context, geompropvalue, key) In MaterialX, Geompropvalue are referenced as strings, example: input name="geomprop" type="string" value="UVset01" We can map this MaterialX Geompropvalue to a RadeonProRender Primvar, example: [`rprMaterialXBindGeomPropToPrimvar`](@ref)(context, "UVset01", 100 ); In this example, the materialX "UVset01" will be used as the RadeonProRender Primvar key=100 ( created with [`rprShapeSetPrimvar`](@ref) ) Internally this is a map from geompropvalue to key, meaning a geompropvalue only has 1 unique key, but 1 key can have several geompropvalue. """ function rprMaterialXBindGeomPropToPrimvar(in_context, geompropvalue, key) check_error(ccall((:rprMaterialXBindGeomPropToPrimvar, libRadeonProRender64), rpr_status, (rpr_context, Ptr{rpr_char}, rpr_uint), in_context, geompropvalue, key)) end const rpr_GLuint = Cuint const rpr_GLint = Cint const rpr_GLenum = Cuint const rpr_gl_object_type = rpr_uint const rpr_gl_texture_info = rpr_uint const rpr_gl_platform_info = rpr_uint function rprContextCreateFramebufferFromGLTexture2D(context, target, miplevel, texture) out_fb = Ref{rpr_framebuffer}() check_error(ccall((:rprContextCreateFramebufferFromGLTexture2D, libRadeonProRender64), rpr_status, (rpr_context, rpr_GLenum, rpr_GLint, rpr_GLuint, Ptr{rpr_framebuffer}), context, target, miplevel, texture, out_fb)) return out_fb[] end const RPR_VERSION_MAJOR = 3 const RPR_VERSION_MINOR = 1 const RPR_VERSION_REVISION = 2 const RPR_VERSION_BUILD = 0xd1cb11d8 const RPR_VERSION_MAJOR_MINOR_REVISION = 0x00300102 const RPR_API_VERSION = RPR_VERSION_MAJOR_MINOR_REVISION const RPR_API_VERSION_MINOR = RPR_VERSION_BUILD const RPR_OBJECT_NAME = 0x00777777 const RPR_OBJECT_UNIQUE_ID = 0x00777778 const RPR_OBJECT_CUSTOM_PTR = 0x00777779 const RPR_INSTANCE_PARENT_SHAPE = 0x1601 const RPR_FALSE = Cuint(0) const RPR_TRUE = Cuint(1) const RPR_INVALID_GL_SHAREGROUP_REFERENCE_KHR = -1000 const RPR_GL_CONTEXT_KHR = 0x2001 const RPR_EGL_DISPLAY_KHR = 0x2002 const RPR_GLX_DISPLAY_KHR = 0x2003 const RPR_WGL_HDC_KHR = 0x2004 const RPR_CGL_SHAREGROUP_KHR = 0x2005 # exports const PREFIXES = ["RPR", "rpr"] for name in names(@__MODULE__; all=true), prefix in PREFIXES if startswith(string(name), prefix) @eval export $name end end end # module
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
654
module RadeonProRender using GeometryBasics using Colors using CEnum using RadeonProRender_jll using Printf using Pkg.Artifacts assetpath(paths...) = normpath(joinpath(@__DIR__, "..", "assets", paths...)) include("LibRPR.jl") using .RPR include("highlevel-api.jl") include("materials.jl") export set! export setradiantpower! export setintensityscale! export setportal! export setalbedo! export setturbidity! export setscale! export clear! export transform! export layeredshader export TileIterator export set_standard_tonemapping! export setsubdivisions! export setdisplacementscale! export lookat! export Tahoe, Northstar, Hybrid, HybridPro end
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
28865
""" All RadeonProRender types inherit from RPRObject """ abstract type RPRObject{PtrType} end Base.pointer(object::RPRObject) = object.pointer Base.cconvert(::Type{T}, object::RPRObject{T}) where {T<:Ptr} = object Base.unsafe_convert(::Type{T}, object::RPRObject{T}) where {T} = pointer(object) function Base.unsafe_convert(::Type{Ptr{Nothing}}, object::RPRObject{T}) where {T} return Base.unsafe_convert(Ptr{Nothing}, pointer(object)) end function release(object::RPRObject) remove_from_context!(object.parent, object) if object.pointer != C_NULL rprObjectDelete(object) end object.pointer = C_NULL if hasproperty(object, :referenced_memory) object.referenced_memory = nothing end return end @enum PluginType Tahoe Northstar Hybrid HybridPro using Libdl function plugin_path(plugin::PluginType) if plugin == Tahoe return RadeonProRender_jll.libTahoe64 elseif plugin == Northstar return RadeonProRender_jll.libNorthstar64 end Sys.isapple() && error("Only Tahoe and Northstar are supported") path_base = dirname(RadeonProRender_jll.libNorthstar64) # Hybrid isn't currently part of Binarybuilder products, since its missing on Apple if plugin == Hybrid return joinpath(path_base, "Hybrid.$(Libdl.dlext)") elseif plugin == HybridPro return joinpath(path_base, "HybridPro.$(Libdl.dlext)") end end # Aliases for the incredibly long creation flag names const GPU0 = RPR_CREATION_FLAGS_ENABLE_GPU0 const GPU1 = RPR_CREATION_FLAGS_ENABLE_GPU1 const GPU2 = RPR_CREATION_FLAGS_ENABLE_GPU2 const GPU3 = RPR_CREATION_FLAGS_ENABLE_GPU3 const CPU = RPR_CREATION_FLAGS_ENABLE_CPU const GL_INTEROP = RPR_CREATION_FLAGS_ENABLE_GL_INTEROP const GPU4 = RPR_CREATION_FLAGS_ENABLE_GPU4 const GPU5 = RPR_CREATION_FLAGS_ENABLE_GPU5 const GPU6 = RPR_CREATION_FLAGS_ENABLE_GPU6 const GPU7 = RPR_CREATION_FLAGS_ENABLE_GPU7 const METAL = RPR_CREATION_FLAGS_ENABLE_METAL const GPU8 = RPR_CREATION_FLAGS_ENABLE_GPU8 const GPU9 = RPR_CREATION_FLAGS_ENABLE_GPU9 const GPU10 = RPR_CREATION_FLAGS_ENABLE_GPU10 const GPU11 = RPR_CREATION_FLAGS_ENABLE_GPU11 const GPU12 = RPR_CREATION_FLAGS_ENABLE_GPU12 const GPU13 = RPR_CREATION_FLAGS_ENABLE_GPU13 const GPU14 = RPR_CREATION_FLAGS_ENABLE_GPU14 const GPU15 = RPR_CREATION_FLAGS_ENABLE_GPU15 const HIP = RPR_CREATION_FLAGS_ENABLE_HIP const OPENCL = RPR_CREATION_FLAGS_ENABLE_OPENCL const DEBUG = RPR_CREATION_FLAGS_ENABLE_DEBUG mutable struct Context <: RPRObject{rpr_context} pointer::rpr_context objects::Base.IdSet{RPRObject} plugin::PluginType function Context(plugin::PluginType, creation_flags, singleton=true, cache_path=C_NULL) id = RPR.rprRegisterPlugin(plugin_path(plugin)) @assert(id != -1) plugin_ids = [id] if plugin == Northstar hipbin = artifact"hipbin" GC.@preserve hipbin begin binpath_ptr = convert(Ptr{Cvoid}, UInt64(RPR.RPR_CONTEXT_PRECOMPILED_BINARY_PATH)) props = rpr_context_properties[binpath_ptr, pointer(hipbin), convert(Ptr{Cvoid}, 0)] ctx_ptr = RPR.rprCreateContext(RPR.RPR_API_VERSION, plugin_ids, 1, creation_flags, props, cache_path) end else # No hip needed here ctx_ptr = RPR.rprCreateContext(RPR.RPR_API_VERSION, plugin_ids, 1, creation_flags, C_NULL, cache_path) end RPR.rprContextSetActivePlugin(ctx_ptr, id) ctx = new(ctx_ptr, Base.IdSet{RPRObject}(), plugin) if singleton if isassigned(ACTIVE_CONTEXT) @info("releasing old context") release(ACTIVE_CONTEXT[]) end ACTIVE_CONTEXT[] = ctx end return ctx end end const ACTIVE_CONTEXT = Base.RefValue{Context}() get_context(object::RPRObject) = get_context(object.parent) get_context(context::Context) = context function add_to_context!(contextlike::RPRObject, object::RPRObject) return push!(get_context(contextlike).objects, object) end function remove_from_context!(contextlike::RPRObject, object::RPRObject) return delete!(get_context(contextlike).objects, object) end """ Context() Empty constructor, defaults to using opencl, GPU0 and Tahoe as the rendering plugin. * `resource::rpr_creation_flags_t = RPR_CREATION_FLAGS_ENABLE_GPU0` * `plugin::PluginType=Northstar`: can be Tahoe, Northstar or Hybrid or HybridPro. Everything is tested with Northstar, which is a complete rewrite of Tahoe. Hybrid is for real time rendering and only supports Uber material. * `singleton = true`: set to true, to only allow one context at the same time. This is useful, to immediately free all old resources when creating a new context, instead of relying on the GC. """ function Context(; plugin=Northstar, resource=RPR_CREATION_FLAGS_ENABLE_GPU0, singleton=true) return Context(plugin, resource, singleton) end """ Wraps a RadeonProRender type into a gc registered higher level type. arguments: `name`: name of the Julia type `typ`: type of the RadeonProRender object `target`: RadeonProRender constructor function `args`: arguments to constructor function `super` Julia super type """ macro rpr_wrapper_type(name, typ, target, args, super) argnames = args.args parent = argnames[1] expr = quote mutable struct $name{PT} <: $super{$typ} pointer::$typ parent::PT $name(pointer::$typ, parent::PT) where {PT} = new{PT}(pointer, parent) function $name($(argnames...)) ptr = $target($(argnames...)) object = new{typeof($parent)}(ptr, $parent) add_to_context!($parent, object) return object end end end return esc(expr) end function release(context::Context) if context.pointer == C_NULL @assert isempty(context.objects) return end scenes = Scene[] for object in copy(context.objects) if object isa Scene push!(scenes, object) else release(object) end end empty!(context.objects) foreach(s -> (rprSceneClear(s); release(s)), scenes) empty!(scenes) rprContextClearMemory(context) rprObjectDelete(context) context.pointer = C_NULL return end @rpr_wrapper_type MaterialSystem rpr_material_system rprContextCreateMaterialSystem (context, typ) RPRObject @rpr_wrapper_type MaterialNode rpr_material_node rprMaterialSystemCreateNode (matsystem, typ) RPRObject @rpr_wrapper_type Camera rpr_camera rprContextCreateCamera (context,) RPRObject @rpr_wrapper_type Scene rpr_scene rprContextCreateScene (context,) RPRObject @rpr_wrapper_type PostEffect rpr_post_effect rprContextCreatePostEffect (context, type) RPRObject function set!(pe::PostEffect, param::String, x::Number) return rprPostEffectSetParameter1f(pe, param, x) end mutable struct VoxelGrid <: RPRObject{rpr_grid} pointer::rpr_grid parent::Context referenced_memory::Any end function VoxelGrid(context::Context, nx, ny, nz, grid_values::AbstractArray, grid_indices::AbstractArray) grid_ptr = Ref{rpr_grid}() grid_indices = convert(Vector{UInt64}, vec(grid_indices)) valuesf0 = convert(Vector{Float32}, vec(grid_values)) rprContextCreateGrid(context, grid_ptr, nx, ny, nz, grid_indices, length(grid_indices), RPR.RPR_GRID_INDICES_TOPOLOGY_I_U64, valuesf0, sizeof(valuesf0), 0) grid = VoxelGrid(grid_ptr[], context, (valuesf0, grid_indices)) add_to_context!(context, grid) return grid end function VoxelGrid(context, values::AbstractArray{<:Number,3}) indices = UInt64.((1:length(values)) .- 1) return VoxelGrid(context, size(values)..., values, indices) end mutable struct Curve <: RPRObject{rpr_curve} pointer::rpr_curve parent::Context referenced_memory::Any end function Curve(context::Context, control_points::AbstractVector, indices::AbstractVector, radius::AbstractVector, uvs::AbstractVector, segments_per_curve::AbstractVector, creationFlag_tapered=0) curve_ref = Ref{rpr_curve}() control_pointsf0 = convert(Vector{Point3f}, control_points) indices_i = convert(Vector{RPR.rpr_int}, indices) segments_per_curve_i = convert(Vector{RPR.rpr_int}, segments_per_curve) uvs_f0 = convert(Vector{Vec2f}, uvs) radiusf0 = convert(Vector{Float32}, radius) rprContextCreateCurve(context, curve_ref, length(control_pointsf0), control_pointsf0, sizeof(Point3f), length(indices_i), length(segments_per_curve_i), indices_i, radiusf0, uvs_f0, segments_per_curve_i, creationFlag_tapered) curve = Curve(curve_ref[], context, (control_pointsf0, indices_i, segments_per_curve_i, uvs_f0, radiusf0)) add_to_context!(context, curve) return curve end @rpr_wrapper_type HeteroVolume rpr_hetero_volume rprContextCreateHeteroVolume (context,) RPRObject function set_albedo_lookup!(volume::HeteroVolume, colors::AbstractVector) return RPR.rprHeteroVolumeSetAlbedoLookup(volume, convert(Vector{RGB{Float32}}, colors), length(colors)) end function set_albedo_grid!(volume::HeteroVolume, albedo::VoxelGrid) return RPR.rprHeteroVolumeSetAlbedoGrid(volume, albedo) end function set_density_lookup!(volume::HeteroVolume, density::AbstractVector) return RPR.rprHeteroVolumeSetDensityLookup(volume, convert(Vector{Vec3f}, density), length(density)) end function set_density_grid!(volume::HeteroVolume, density::VoxelGrid) return RPR.rprHeteroVolumeSetDensityGrid(volume, density) end function Base.push!(scene::Scene, volume::HeteroVolume) return rprSceneAttachHeteroVolume(scene, volume) end mutable struct Shape <: RPRObject{rpr_shape} pointer::rpr_shape parent::Context referenced_arrays::Any end function set!(shape::Shape, volume::HeteroVolume) return rprShapeSetHeteroVolume(shape, volume) end """ Abstract AbstractLight Type """ abstract type AbstractLight{PtrType} <: RPRObject{PtrType} end @rpr_wrapper_type EnvironmentLight rpr_light rprContextCreateEnvironmentLight (context,) AbstractLight @rpr_wrapper_type PointLight rpr_light rprContextCreatePointLight (context,) AbstractLight @rpr_wrapper_type DirectionalLight rpr_light rprContextCreateDirectionalLight (context,) AbstractLight @rpr_wrapper_type SkyLight rpr_light rprContextCreateSkyLight (context,) AbstractLight @rpr_wrapper_type SpotLight rpr_light rprContextCreateSpotLight (context,) AbstractLight """ Default shape constructor which works with every Geometry from the package GeometryTypes (Meshes and geometry primitives alike). """ function Shape(context::Context, meshlike; kw...) m = uv_normal_mesh(meshlike; kw...) v, n, fs, uv = decompose(Point3f, m), normals(m), faces(m), texturecoordinates(m) if isnothing(n) n = normals(v, fs) end return Shape(context, v, n, fs, uv) end #= The yield + nospecialize somehow prevent some stack/memory corruption when run with `--check-bounds=yes` This is kind of magical and still under investigation. MWE: https://gist.github.com/SimonDanisch/475064ae102141554f65e926f3070630 =# function Shape(context::Context, vertices, normals, faces, uvs) @assert length(vertices) == length(normals) @assert length(vertices) == length(uvs) vraw = decompose(Point3f, vertices) nraw = decompose(Vec3f, normals) uvraw = map(uv -> Vec2f(1 - uv[2], 1 - uv[1]), uvs) f = decompose(TriangleFace{OffsetInteger{-1,rpr_int}}, faces) iraw = collect(reinterpret(rpr_int, f)) facelens = fill(rpr_int(3), length(faces)) @assert eltype(vraw) == Point3f @assert eltype(nraw) == Vec3f @assert eltype(uvraw) == Vec2f foreach(i -> checkbounds(vertices, i + 1), iraw) rpr_mesh = rprContextCreateMesh(context, vraw, length(vertices), sizeof(Point3f), nraw, length(normals), sizeof(Vec3f), uvraw, length(uvs), sizeof(Vec2f), iraw, sizeof(rpr_int), iraw, sizeof(rpr_int), iraw, sizeof(rpr_int), facelens, length(faces)) jl_references = (vraw, nraw, uvraw, iraw, facelens) shape = Shape(rpr_mesh, context, jl_references) add_to_context!(context, shape) return shape end """ Creating a shape from a shape is interpreted as creating an instance. """ function Shape(context::Context, shape::Shape) inst = Shape(rprContextCreateInstance(context, shape), context, nothing) add_to_context!(context, inst) return inst end """ VolumeCube(context::Context) Creates a cube that can be used for rendering a volume! """ function VolumeCube(context::Context) mesh_props = Vector{UInt32}(undef, 16) mesh_props[1] = UInt32(RPR.RPR_MESH_VOLUME_FLAG) mesh_props[2] = UInt32(1) # enable the Volume flag for the Mesh mesh_props[3] = UInt32(0) # Volume shapes don't need any vertices data: the bounds of volume will only be defined by the grid. # Also, make sure to enable the RPR_MESH_VOLUME_FLAG rpr_mesh = RPR.rprContextCreateMeshEx2(context, C_NULL, 0, 0, C_NULL, 0, 0, C_NULL, 0, 0, 0, C_NULL, C_NULL, C_NULL, C_NULL, 0, C_NULL, 0, C_NULL, C_NULL, C_NULL, 0, mesh_props) return Shape(rpr_mesh, context, []) end """ Create layered shader give two shaders and respective IORs """ function layeredshader(matsys, base, top, weight=(0.5, 0.5, 0.5, 1.0)) layered = MaterialNode(matsys, RPR.RPR_MATERIAL_NODE_BLEND) set!(layered, RPR.RPR_MATERIAL_INPUT_COLOR0, base) # Set shader for top layer set!(layered, RPR.RPR_MATERIAL_INPUT_COLOR1, top) # Set index of refraction for base layer set!(layered, RPR.RPR_MATERIAL_INPUT_WEIGHT, weight...) return layered end """ FrameBuffer wrapper type """ mutable struct FrameBuffer <: RPRObject{rpr_framebuffer} pointer::rpr_framebuffer parent::Context end function FrameBuffer(context::Context, c::Type{C}, dims::NTuple{2,Int}) where {C<:Colorant} desc = Ref(RPR.rpr_framebuffer_desc(dims...)) fmt = RPR.rpr_framebuffer_format(length(c), RPR_COMPONENT_TYPE_FLOAT32) frame_buffer = FrameBuffer(RPR.rprContextCreateFrameBuffer(context, fmt, desc), context) add_to_context!(context, frame_buffer) return frame_buffer end function get_data(framebuffer::FrameBuffer) framebuffer_size = Ref{Csize_t}() RPR.rprFrameBufferGetInfo(framebuffer, RPR.RPR_FRAMEBUFFER_DATA, 0, C_NULL, framebuffer_size) data = zeros(RGBA{Float32}, framebuffer_size[] ÷ sizeof(RGBA{Float32})) @assert sizeof(data) == framebuffer_size[] RPR.rprFrameBufferGetInfo(framebuffer, RPR.RPR_FRAMEBUFFER_DATA, framebuffer_size[], data, C_NULL) return data end """ Image wrapper type """ mutable struct Image <: RPRObject{rpr_image} pointer::rpr_image parent::Context referenced_memory::Any end """ Automatically generated the correct `rpr_image_format` for an array """ rpr_image_format(a::Array) = rpr_image_format(eltype(a)) function rpr_image_format(::Type{T}) where {T<:Union{Colorant,Number}} return RPR.rpr_image_format(T <: Number ? 1 : length(T), component_type(T)) end """ Gets the correct component type for Images from array element types """ component_type(x::Type{T}) where {T<:Colorant} = component_type(eltype(T)) component_type(x::Type{T}) where {T<:Union{UInt8,Colors.N0f8}} = RPR_COMPONENT_TYPE_UINT8 component_type(x::Type{T}) where {T<:Union{Float16}} = RPR_COMPONENT_TYPE_FLOAT16 component_type(x::Type{T}) where {T<:Union{Float32}} = RPR_COMPONENT_TYPE_FLOAT32 """ Creates the correct `rpr_image_desc` for a given array. """ function rpr_image_desc(image::Array{T,N}) where {T,N} row_pitch = size(image, 1) * sizeof(T) imsize = N == 1 ? (1, 1, 0) : ntuple(i -> N < i ? 0 : size(image, i), 3) return RPR.rpr_image_desc(imsize..., row_pitch, 0) end """ Automatically creates an Image from a matrix of colors """ function Image(context::Context, image::Array{T,N}) where {T,N} desc_ref = Ref(rpr_image_desc(image)) img = Image(rprContextCreateImage(context, rpr_image_format(image), desc_ref, image), context, (image, desc_ref)) add_to_context!(context, img) return img end function Image(context::Context, image::AbstractArray) return Image(context, collect(image)) end """ Automatically loads an image from the given `path` """ function Image(context::Context, path::AbstractString) img = Image(rprContextCreateImageFromFile(context, path), context, nothing) add_to_context!(context, img) return img end """ Sets the radiant power for a given Light """ function setradiantpower!(light::AbstractLight, color::Colorant{T,3}) where {T} c = RGB{Float32}(color) return setradiantpower!(light, comp1(c), comp2(c), comp3(c)) end function setradiantpower!(light::PointLight, r::Number, g::Number, b::Number) return rprPointLightSetRadiantPower3f(light, rpr_float(r), rpr_float(g), rpr_float(b)) end function setradiantpower!(light::SpotLight, r::Number, g::Number, b::Number) return rprSpotLightSetRadiantPower3f(light, rpr_float(r), rpr_float(g), rpr_float(b)) end function setradiantpower!(light::DirectionalLight, r::Number, g::Number, b::Number) return rprDirectionalLightSetRadiantPower3f(light, rpr_float(r), rpr_float(g), rpr_float(b)) end """ Sets the image for an EnvironmentLight """ function set!(light::EnvironmentLight, image::Image) return rprEnvironmentLightSetImage(light, image) end function set!(light::EnvironmentLight, context::Context, image::Array) return set!(light, Image(context, image)) end function set!(light::EnvironmentLight, context::Context, path::AbstractString) return set!(light, Image(context, path)) end """ Sets the intensity scale an EnvironmentLight """ function setintensityscale!(light::EnvironmentLight, intensity_scale::Number) return rprEnvironmentLightSetIntensityScale(light, intensity_scale) end """ Sets a portal for a Light """ function setportal!(light::AbstractLight, portal::AbstractGeometry) return setportal!(light, Shape(portal)) end function setportal!(light::EnvironmentLight, portal::Shape) return rprEnvironmentLightSetPortal(light, portal) end function setportal!(light::SkyLight, portal::Shape) return rprSkyLightSetPortal(light, portal) end """ Sets the albedo for a SkyLight """ setalbedo!(skylight::SkyLight, albedo::Number) = rprSkyLightSetAlbedo(skylight.x, albedo) """ Sets the turbidity for a SkyLight """ setturbidity!(skylight::SkyLight, turbidity::Number) = rprSkyLightSetTurbidity(skylight.x, turbidity) """ Sets the scale for a SkyLight """ setscale!(skylight::SkyLight, scale::Number) = rprSkyLightSetScale(skylight, scale) function set!(context::Context, parameter::rpr_context_info, f::AbstractFloat) return rprContextSetParameterByKey1f(context, parameter, f) end function set!(context::Context, parameter::rpr_context_info, ui::Integer) return rprContextSetParameterByKey1u(context, parameter, ui) end function set!(context::Context, parameter::rpr_context_info, ui) # overload for enums return rprContextSetParameterByKey1u(context, parameter, ui) end set!(context::Context, aov::rpr_aov, fb::FrameBuffer) = rprContextSetAOV(context, aov, fb) function set!(shape::Shape, image::Image) return rprShapeSetDisplacementImage(shape, image) end function set!(shape::Shape, context::Context, image::Array) return set!(shape, Image(context, image)) end """ Sets arbitrary values to RadeonProRender objects """ set!(context::Context, framebuffer::FrameBuffer) = rprContextSetFrameBuffer(context, framebuffer) function set!(base::MaterialNode, parameter::rpr_material_node_input, a::Number, b::Number, c::Number, d::Number) return rprMaterialNodeSetInputFByKey(base, parameter, a, b, c, d) end function set!(base::MaterialNode, parameter::rpr_material_node_input, ui::Integer) return rprMaterialNodeSetInputUByKey(base, parameter, ui) end function set!(base::MaterialNode, parameter::rpr_material_node_input, f::Vec4) return set!(base, parameter, f...) end function set!(base::MaterialNode, parameter::rpr_material_node_input, color::Colorant) c = RGBA{Float32}(color) return set!(base, parameter, comp1(c), comp2(c), comp3(c), alpha(c)) end function set!(mat::MaterialNode, parameter::rpr_material_node_input, enum) return set!(mat, parameter, UInt(enum)) end function set!(shape::Shape, material::MaterialNode) return rprShapeSetMaterial(shape, material) end function set!(shape::Curve, material::MaterialNode) return rprCurveSetMaterial(shape, material) end function set!(material::MaterialNode, parameter::rpr_material_node_input, material2::MaterialNode) return rprMaterialNodeSetInputNByKey(material, parameter, material2) end function set!(shape::MaterialNode, parameter::rpr_material_node_input, grid::VoxelGrid) return rprMaterialNodeSetInputGridDataByKey(shape, parameter, grid) end function set!(material::MaterialNode, parameter::rpr_material_node_input, image::Image) return rprMaterialNodeSetInputImageDataByKey(material, parameter, image) end function set!(material::MaterialNode, parameter::rpr_material_node_input, context::Context, image::Array) return set!(material, parameter, Image(context, image)) end function set!(context::Context, scene::Scene) return rprContextSetScene(context, scene) end function set!(scene::Scene, light::EnvironmentLight) return rprSceneSetEnvironmentLight(scene, light) end function set!(scene::Scene, camera::Camera) return rprSceneSetCamera(scene, camera) end """ Sets the displacement scale for a shape """ function setdisplacementscale!(shape::Shape, scale::Number) return rprShapeSetDisplacementScale(shape, rpr_float(scale)) end """ Sets the subdivions for a shape """ function setsubdivisions!(shape::Shape, subdivions::Integer) return rprShapeSetSubdivisionFactor(shape, rpr_uint(subdivions)) end """ Transforms firerender objects with a transformation matrix """ function transform!(shape::Shape, transform::AbstractMatrix) return rprShapeSetTransform(shape, false, convert(Matrix{Float32}, transform)) end function transform!(light::AbstractLight, transform::AbstractMatrix) return rprLightSetTransform(light, false, convert(Matrix{Float32}, transform)) end function transform!(camera::Camera, transform::AbstractMatrix) return rprCameraSetTransform(camera, false, convert(Matrix{Float32}, transform)) end """ Clears a scene """ clear!(scene::Scene) = rprSceneClear(scene) """ Clears a framebuffer """ clear!(frame_buffer::FrameBuffer) = rprFrameBufferClear(frame_buffer) """ Pushes objects to Scene """ function Base.push!(scene::Scene, shape::Shape) return rprSceneAttachShape(scene, shape) end function Base.push!(scene::Scene, curve::Curve) return rprSceneAttachCurve(scene, curve) end function Base.push!(scene::Scene, light::AbstractLight) return rprSceneAttachLight(scene, light) end function set!(context::Context, pe::PostEffect) return rprContextAttachPostEffect(context, pe) end function Base.delete!(scene::Scene, light::AbstractLight) return rprSceneDetachLight(scene, light) end function Base.delete!(scene::Scene, shape::Shape) return rprSceneDetachShape(scene, shape) end """ Gets the currently attached EnvironmentLight from a scene """ function Base.get(scene::Scene, ::Type{EnvironmentLight}) return EnvironmentLight(rprSceneGetEnvironmentLight(scene)) end """ Gets the currently attached Camera from a scene """ function Base.get(scene::Scene, ::Type{Camera}) return Camera(rprSceneGetCamera(scene)) end """ Sets the lookat of a camera """ function lookat!(camera::Camera, position::Vec3, lookatvec::Vec3, upvec::Vec3) return rprCameraLookAt(camera, position..., lookatvec..., upvec...) end """ renders the context """ function render(context::Context) return rprContextRender(context) end """ Renders a tile of the context """ function render(context::Context, tile::Rect) mini, maxi = minimum(tile), maximum(tile) return rprContextRenderTile(context, mini[1], maxi[1], mini[2], maxi[2]) end """ Saves a picture of the current framebuffer at `path` """ function save(fb::FrameBuffer, path::AbstractString) return rprFrameBufferSaveToFile(fb, path) end #= Some iterators for tiled rendering =# """ Iterates randomly over an iterable """ struct RandomIterator{T} iterable::T end function Base.iterate(ti::RandomIterator, state=rand(1:length(ti.iterable))) return (ti.iterable[state], rand(1:length(ti.iterable))) end """ Iterates randomly over all elements in an iterable. The middle has a higher sampling probability. """ struct MiddleSampleIterator{T} iterable::T end function multiplier(i, j, n1, n2) a = abs(mod(i - div(n1, 2), n1) - div(n1, 2)) b = abs(mod(j - div(n2, 2), n2) - div(n2, 2)) return max(a, b) end function init_sample_pool(ti) samplepool = Tuple{Int,Int}[] for i in 1:size(ti.iterable, 1) for j in 1:size(ti.iterable, 2) append!(samplepool, fill((i, j), multiplier(i, j, size(ti.iterable)...))) end end return samplepool end function Base.iterate(ti::MiddleSampleIterator, state=init_sample_pool(ti)) isempty(state) && return nothing i = rand(1:length(state)) i2 = state[i] filter!(state) do s return s != i2 end i = sub2ind(size(ti.iterable), i2...) return (ti.iterable[i], state) end """ Iterates over all tiles in a Rectangular parent tile. """ struct TileIterator size::Vec{2,Int} tile_size::Vec{2,Int} lengths::Vec{2,Int} end function TileIterator(size, tile_size) s, ts = Vec(size), Vec(tile_size) lengths = Vec{2,Int}(ceil(Vec{2,Float64}(s) ./ Vec{2,Float64}(ts))) return TileIterator(s, ts, lengths) end function Base.getindex(ti::TileIterator, i, j) ts = Vec(ti.tile_size) xymin = (Vec(i, j) .- 1) .* ts xymax = xymin .+ ts return Rect(xymin, min(xymax, ti.size) .- xymin) end function Base.getindex(ti::TileIterator, linear_index::Int) i, j = ind2sub(size(ti), linear_index) return ti[i, j] end Base.size(ti::TileIterator, i) = ti.lengths[i] Base.size(ti::TileIterator) = (ti.lengths...,) Base.length(ti::TileIterator) = prod(ti.lengths) function Base.iterate(ti::TileIterator, state=1) length(ti) > state && return nothing return ti[state], state + 1 end """ Customizable defaults for the most common tonemapping operations """ function set_standard_tonemapping!(context; typ=RPR.RPR_TONEMAPPING_OPERATOR_PHOTOLINEAR, photolinear_sensitivity=0.5f0, photolinear_exposure=0.5f0, photolinear_fstop=2.0f0, reinhard02_prescale=1.0f0, reinhard02_postscale=1.0f0, reinhard02_burn=1.0f0, linear_scale=1.0f0, aacellsize=4.0, imagefilter_type=RPR.RPR_FILTER_BLACKMANHARRIS, aasamples=4.0) if context.plugin != HybridPro norm = PostEffect(context, RPR.RPR_POST_EFFECT_NORMALIZATION) set!(context, norm) tonemap = PostEffect(context, RPR.RPR_POST_EFFECT_TONE_MAP) set!(context, tonemap) set!(context, RPR.RPR_CONTEXT_TONE_MAPPING_TYPE, typ) set!(context, RPR.RPR_CONTEXT_TONE_MAPPING_LINEAR_SCALE, linear_scale) set!(context, RPR.RPR_CONTEXT_TONE_MAPPING_PHOTO_LINEAR_SENSITIVITY, photolinear_sensitivity) set!(context, RPR.RPR_CONTEXT_TONE_MAPPING_PHOTO_LINEAR_EXPOSURE, photolinear_exposure) set!(context, RPR.RPR_CONTEXT_TONE_MAPPING_PHOTO_LINEAR_FSTOP, photolinear_fstop) set!(context, RPR.RPR_CONTEXT_TONE_MAPPING_REINHARD02_PRE_SCALE, reinhard02_prescale) set!(context, RPR.RPR_CONTEXT_TONE_MAPPING_REINHARD02_POST_SCALE, reinhard02_postscale) set!(context, RPR.RPR_CONTEXT_TONE_MAPPING_REINHARD02_BURN, reinhard02_burn) set!(context, RPR.RPR_CONTEXT_IMAGE_FILTER_TYPE, imagefilter_type) gamma = PostEffect(context, RPR.RPR_POST_EFFECT_GAMMA_CORRECTION) set!(context, gamma) set!(context, RPR.RPR_CONTEXT_DISPLAY_GAMMA, 1.0) end # set!(context, "aacellsize", aacellsize) # set!(context, "aasamples", aasamples) # set!(context, RPR.RPR_CONTEXT_AA_ENABLED, UInt(1)) # bloom = PostEffect(context, RPR.RPR_POST_EFFECT_BLOOM) # set!(context, bloom) # set!(bloom, "weight", 1.0f0) # set!(bloom, "radius", 0.4f0) # set!(bloom, "threshold", 0.2f0) return end
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
32570
abstract type RPRMaterial end struct Material{Typ} <: RPRMaterial node::MaterialNode parameters::Dict{Symbol,Any} matsys::MaterialSystem end function set!(shape::Union{Curve, Shape}, material::Material) return set!(shape, material.node) end function set!(m::MaterialNode, input::RPR.rpr_material_node_input, m2::Material) return set!(m, input, m2.node) end const ALL_MATERIALS = [:Diffuse => RPR.RPR_MATERIAL_NODE_DIFFUSE, :Microfacet => RPR.RPR_MATERIAL_NODE_MICROFACET, :Reflection => RPR.RPR_MATERIAL_NODE_REFLECTION, :Refraction => RPR.RPR_MATERIAL_NODE_REFRACTION, :MicrofacetRefraction => RPR.RPR_MATERIAL_NODE_MICROFACET_REFRACTION, :Transparent => RPR.RPR_MATERIAL_NODE_TRANSPARENT, :Emissive => RPR.RPR_MATERIAL_NODE_EMISSIVE, :Ward => RPR.RPR_MATERIAL_NODE_WARD, :Add => RPR.RPR_MATERIAL_NODE_ADD, :Blend => RPR.RPR_MATERIAL_NODE_BLEND, :Arithmetic => RPR.RPR_MATERIAL_NODE_ARITHMETIC, :Fresnel => RPR.RPR_MATERIAL_NODE_FRESNEL, :NormalMap => RPR.RPR_MATERIAL_NODE_NORMAL_MAP, :ImageTexture => RPR.RPR_MATERIAL_NODE_IMAGE_TEXTURE, :Noise2dTexture => RPR.RPR_MATERIAL_NODE_NOISE2D_TEXTURE, :DotTexture => RPR.RPR_MATERIAL_NODE_DOT_TEXTURE, :GradientTexture => RPR.RPR_MATERIAL_NODE_GRADIENT_TEXTURE, :CheckerTexture => RPR.RPR_MATERIAL_NODE_CHECKER_TEXTURE, :ConstantTexture => RPR.RPR_MATERIAL_NODE_CONSTANT_TEXTURE, :InputLookup => RPR.RPR_MATERIAL_NODE_INPUT_LOOKUP, :BlendValue => RPR.RPR_MATERIAL_NODE_BLEND_VALUE, :Passthrough => RPR.RPR_MATERIAL_NODE_PASSTHROUGH, :Orennayar => RPR.RPR_MATERIAL_NODE_ORENNAYAR, :FresnelSchlick => RPR.RPR_MATERIAL_NODE_FRESNEL_SCHLICK, :DiffuseRefraction => RPR.RPR_MATERIAL_NODE_DIFFUSE_REFRACTION, :BumpMap => RPR.RPR_MATERIAL_NODE_BUMP_MAP, :Volume => RPR.RPR_MATERIAL_NODE_VOLUME, :MicrofacetAnisotropicReflection => RPR.RPR_MATERIAL_NODE_MICROFACET_ANISOTROPIC_REFLECTION, :MicrofacetAnisotropicRefraction => RPR.RPR_MATERIAL_NODE_MICROFACET_ANISOTROPIC_REFRACTION, :Twosided => RPR.RPR_MATERIAL_NODE_TWOSIDED, :UvProcedural => RPR.RPR_MATERIAL_NODE_UV_PROCEDURAL, :MicrofacetBeckmann => RPR.RPR_MATERIAL_NODE_MICROFACET_BECKMANN, :Phong => RPR.RPR_MATERIAL_NODE_PHONG, :BufferSampler => RPR.RPR_MATERIAL_NODE_BUFFER_SAMPLER, :UvTriplanar => RPR.RPR_MATERIAL_NODE_UV_TRIPLANAR, :AoMap => RPR.RPR_MATERIAL_NODE_AO_MAP, :UserTexture_0 => RPR.RPR_MATERIAL_NODE_USER_TEXTURE_0, :UserTexture_1 => RPR.RPR_MATERIAL_NODE_USER_TEXTURE_1, :UserTexture_2 => RPR.RPR_MATERIAL_NODE_USER_TEXTURE_2, :UserTexture_3 => RPR.RPR_MATERIAL_NODE_USER_TEXTURE_3, :Uber => RPR.RPR_MATERIAL_NODE_UBERV2, :Transform => RPR.RPR_MATERIAL_NODE_TRANSFORM, :RgbToHsv => RPR.RPR_MATERIAL_NODE_RGB_TO_HSV, :HsvToRgb => RPR.RPR_MATERIAL_NODE_HSV_TO_RGB, :UserTexture => RPR.RPR_MATERIAL_NODE_USER_TEXTURE, :ToonClosure => RPR.RPR_MATERIAL_NODE_TOON_CLOSURE, :ToonRamp => RPR.RPR_MATERIAL_NODE_TOON_RAMP, :VoronoiTexture => RPR.RPR_MATERIAL_NODE_VORONOI_TEXTURE, :GridSampler => RPR.RPR_MATERIAL_NODE_GRID_SAMPLER, :Blackbody => RPR.RPR_MATERIAL_NODE_BLACKBODY, :MatxDiffuseBrdf => RPR.RPR_MATERIAL_NODE_MATX_DIFFUSE_BRDF, :MatxDielectricBrdf => RPR.RPR_MATERIAL_NODE_MATX_DIELECTRIC_BRDF, :MatxGeneralizedSchlickBrdf => RPR.RPR_MATERIAL_NODE_MATX_GENERALIZED_SCHLICK_BRDF, :MatxNoise3d => RPR.RPR_MATERIAL_NODE_MATX_NOISE3D, :MatxTangent => RPR.RPR_MATERIAL_NODE_MATX_TANGENT, :MatxNormal => RPR.RPR_MATERIAL_NODE_MATX_NORMAL, :MatxPosition => RPR.RPR_MATERIAL_NODE_MATX_POSITION, :MatxRoughnessAnisotropy => RPR.RPR_MATERIAL_NODE_MATX_ROUGHNESS_ANISOTROPY, :MatxRotate3d => RPR.RPR_MATERIAL_NODE_MATX_ROTATE3D, :MatxNormalize => RPR.RPR_MATERIAL_NODE_MATX_NORMALIZE, :MatxIfgreater => RPR.RPR_MATERIAL_NODE_MATX_IFGREATER, :MatxSheenBrdf => RPR.RPR_MATERIAL_NODE_MATX_SHEEN_BRDF, :MatxDiffuseBtdf => RPR.RPR_MATERIAL_NODE_MATX_DIFFUSE_BTDF, :MatxConvert => RPR.RPR_MATERIAL_NODE_MATX_CONVERT, :MatxSubsurfaceBrdf => RPR.RPR_MATERIAL_NODE_MATX_SUBSURFACE_BRDF, :MatxDielectricBtdf => RPR.RPR_MATERIAL_NODE_MATX_DIELECTRIC_BTDF, :MatxConductorBrdf => RPR.RPR_MATERIAL_NODE_MATX_CONDUCTOR_BRDF, :MatxFresnel => RPR.RPR_MATERIAL_NODE_MATX_FRESNEL, :MatxLuminance => RPR.RPR_MATERIAL_NODE_MATX_LUMINANCE, :MatxFractal3d => RPR.RPR_MATERIAL_NODE_MATX_FRACTAL3D, :MatxMix => RPR.RPR_MATERIAL_NODE_MATX_MIX, :Matx => RPR.RPR_MATERIAL_NODE_MATX] const ALL_MATERIALS_DICT = Dict(ALL_MATERIALS) function Material(matsys::MaterialSystem, @nospecialize(attributes)) type = if haskey(attributes, :type) attributes[:type] else :Uber # default, since it supports most attributes & is the only one supported by all backends end material_enum = get(ALL_MATERIALS_DICT, type) do error("Material type: $(type) not supported. Choose from RadeonProRender.ALL_MATERIALS") end delete!(attributes, :type) return Material{material_enum}(matsys; attributes...) end for (name, enum) in ALL_MATERIALS @eval const $(Symbol(name, :Material)) = Material{$(enum)} end function snake2camel(str) str = replace(lowercase(str), r"_(.)" => r -> uppercase(r[2])) return uppercase(str[1]) * str[2:end] end function Base.show(io::IO, material::Material{Typ}) where {Typ} typ_str = snake2camel(replace(string(Typ), "RPR_MATERIAL_NODE_" => "")) println(io, typ_str, "Material:") params = getfield(material, :parameters) maxlen = 1 if !isempty(keys(params)) maxlen = maximum(x -> length(string(x)), keys(params)) + 1 end fstr = Printf.Format(" %-$(maxlen)s %s\n") for (k, v) in params Printf.format(io, fstr, string(k, ":"), v) end end function (::Type{Material{Typ}})(matsys::MaterialSystem; kw...) where {Typ} mat = Material{Typ}(MaterialNode(matsys, Typ), Dict{Symbol,Any}(kw), matsys) for (key, value) in kw setproperty!(mat, key, value) end return mat end function Base.setproperty!(material::T, field::Symbol, value::Vec4) where {T<:Material} set!(material.node, field2enum(T, field), value...) getfield(material, :parameters)[field] = value return end function Base.setproperty!(material::T, field::Symbol, value::Vec3) where {T<:Material} setproperty!(material, field, Vec4f(value..., 0.0)) return end function set!(shape::Shape, volume::VolumeMaterial) rprShapeSetVolumeMaterial(shape, volume.node) return end convert_to_type(matsys::MaterialSystem, ::Type{<:Number}, value) = Vec4f(value) convert_to_type(matsys::MaterialSystem, ::Type{<:Number}, value::CEnum.Cenum) = value convert_to_type(matsys::MaterialSystem, ::Type{<:Number}, value::Material) = value convert_to_type(matsys::MaterialSystem, ::Type{<:Colorant}, value) = to_color(value) convert_to_type(matsys::MaterialSystem, ::Type{<:Colorant}, value::Material) = value function convert_to_type(matsys::MaterialSystem, ::Type{<: Number}, value::AbstractMatrix) convert_to_type(matsys, Material, Float32.(value)) end function convert_to_type(matsys::MaterialSystem, ::Type{<: Number}, value::AbstractMatrix{<: Colorant}) convert_to_type(matsys, RGB, value) end function convert_to_type(matsys::MaterialSystem, ::Type{<: Colorant}, value::AbstractMatrix{<:Number}) convert_to_type(matsys, Float32, value) end function convert_to_type(matsys::MaterialSystem, ::Type{<: Colorant}, value::AbstractMatrix{<:Color3}) convert_to_type(matsys, Material, convert(Matrix{RGB{Float32}}, value)) end function convert_to_type(matsys::MaterialSystem, ::Type{<: Colorant}, value::AbstractMatrix{<:TransparentColor}) convert_to_type(matsys, Material, convert(Matrix{RGBA{Float32}}, value)) end function convert_to_type(matsys::MaterialSystem, ::Type{<: Material}, value::AbstractMatrix) return Texture(matsys, value) end function convert_to_type(matsys::MaterialSystem, ::Type{<: Image}, value::Image) return value end function convert_to_type(matsys::MaterialSystem, ::Type{<: Image}, value::AbstractMatrix) return Texture(matsys, value) end function convert_to_type(matsys::MaterialSystem, ::Type{<: Union{Colorant, Image}}, value::Material) return value end function convert_to_type(matsys::MaterialSystem, typ, value) return value end function Base.setproperty!(material::T, field::Symbol, value) where {T<:Material} info = material_field_info() field_enum = field2enum(T, field) field_type = info[field_enum] if field_type isa Tuple type, range = field_type field_type = type # ignore range for now end matsys = material.matsys set!(material.node, field_enum, convert_to_type(matsys, field_type, value)) getfield(material, :parameters)[field] = value return end function Base.setproperty!(material::T, field::Symbol, c::Color3) where {T<:Material} set!(material.node, field2enum(T, field), red(c), green(c), blue(c), 0.0) getfield(material, :parameters)[field] = c return end function Base.setproperty!(material::T, field::Symbol, value::Nothing) where {T<:Material} # TODO, can you actually unset a material property? end function field2enum(::Type{T}, field::Symbol) where {T} info = material_info(T) if haskey(info, field) return getfield(info, field) else error("Material $(T) doesn't have the property $(field)") end end function Base.propertynames(m::T) where {T<:Material} info = material_info(T) return propertynames(info) end function material_info(::Type{UberMaterial}) return (color=RPR.RPR_MATERIAL_INPUT_UBER_DIFFUSE_COLOR, diffuse_weight=RPR.RPR_MATERIAL_INPUT_UBER_DIFFUSE_WEIGHT, diffuse_roughness=RPR.RPR_MATERIAL_INPUT_UBER_DIFFUSE_ROUGHNESS, diffuse_normal=RPR.RPR_MATERIAL_INPUT_UBER_DIFFUSE_NORMAL, reflection_color=RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_COLOR, reflection_weight=RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_WEIGHT, reflection_roughness=RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_ROUGHNESS, reflection_anisotropy=RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_ANISOTROPY, reflection_anisotropy_rotation=RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_ANISOTROPY_ROTATION, reflection_mode=RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_MODE, reflection_ior=RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_IOR, reflection_metalness=RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_METALNESS, reflection_normal=RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_NORMAL, reflection_dielectric_reflectance=RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_DIELECTRIC_REFLECTANCE, refraction_color=RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_COLOR, refraction_weight=RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_WEIGHT, refraction_roughness=RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_ROUGHNESS, refraction_ior=RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_IOR, refraction_normal=RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_NORMAL, refraction_thin_surface=RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_THIN_SURFACE, refraction_absorption_color=RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_ABSORPTION_COLOR, refraction_absorption_distance=RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_ABSORPTION_DISTANCE, refraction_caustics=RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_CAUSTICS, coating_color=RPR.RPR_MATERIAL_INPUT_UBER_COATING_COLOR, coating_weight=RPR.RPR_MATERIAL_INPUT_UBER_COATING_WEIGHT, coating_roughness=RPR.RPR_MATERIAL_INPUT_UBER_COATING_ROUGHNESS, coating_mode=RPR.RPR_MATERIAL_INPUT_UBER_COATING_MODE, coating_ior=RPR.RPR_MATERIAL_INPUT_UBER_COATING_IOR, coating_metalness=RPR.RPR_MATERIAL_INPUT_UBER_COATING_METALNESS, coating_normal=RPR.RPR_MATERIAL_INPUT_UBER_COATING_NORMAL, coating_transmission_color=RPR.RPR_MATERIAL_INPUT_UBER_COATING_TRANSMISSION_COLOR, coating_thickness=RPR.RPR_MATERIAL_INPUT_UBER_COATING_THICKNESS, sheen=RPR.RPR_MATERIAL_INPUT_UBER_SHEEN, sheen_tint=RPR.RPR_MATERIAL_INPUT_UBER_SHEEN_TINT, sheen_weight=RPR.RPR_MATERIAL_INPUT_UBER_SHEEN_WEIGHT, emission_color=RPR.RPR_MATERIAL_INPUT_UBER_EMISSION_COLOR, emission_weight=RPR.RPR_MATERIAL_INPUT_UBER_EMISSION_WEIGHT, emission_mode=RPR.RPR_MATERIAL_INPUT_UBER_EMISSION_MODE, transparency=RPR.RPR_MATERIAL_INPUT_UBER_TRANSPARENCY, sss_scatter_color=RPR.RPR_MATERIAL_INPUT_UBER_SSS_SCATTER_COLOR, sss_scatter_distance=RPR.RPR_MATERIAL_INPUT_UBER_SSS_SCATTER_DISTANCE, sss_scatter_direction=RPR.RPR_MATERIAL_INPUT_UBER_SSS_SCATTER_DIRECTION, sss_weight=RPR.RPR_MATERIAL_INPUT_UBER_SSS_WEIGHT, sss_multiscatter=RPR.RPR_MATERIAL_INPUT_UBER_SSS_MULTISCATTER, backscatter_weight=RPR.RPR_MATERIAL_INPUT_UBER_BACKSCATTER_WEIGHT, backscatter_color=RPR.RPR_MATERIAL_INPUT_UBER_BACKSCATTER_COLOR, fresnel_schlick_approximation=RPR.RPR_MATERIAL_INPUT_UBER_FRESNEL_SCHLICK_APPROXIMATION) end function material_info(::Type{DiffuseMaterial}) return (color=RPR.RPR_MATERIAL_INPUT_COLOR, normal=RPR.RPR_MATERIAL_INPUT_NORMAL, roughness=RPR.RPR_MATERIAL_INPUT_ROUGHNESS) end function material_info(::Type{DiffuseRefractionMaterial}) return material_info(DiffuseMaterial) end function material_info(::Type{BumpMapMaterial}) return (color=RPR.RPR_MATERIAL_INPUT_COLOR, scale=RPR.RPR_MATERIAL_INPUT_SCALE) end function material_info(::Type{VolumeMaterial}) return (scattering=RPR.RPR_MATERIAL_INPUT_SCATTERING, absorption=RPR.RPR_MATERIAL_INPUT_ABSORBTION, emission=RPR.RPR_MATERIAL_INPUT_EMISSION, scatter_direction=RPR.RPR_MATERIAL_INPUT_G, multiscatter=RPR.RPR_MATERIAL_INPUT_MULTISCATTER, densitygrid=RPR.RPR_MATERIAL_INPUT_DENSITYGRID, density=RPR_MATERIAL_INPUT_DENSITY, color=RPR_MATERIAL_INPUT_COLOR) end function material_info(::Type{GridSamplerMaterial}) return (data=RPR.RPR_MATERIAL_INPUT_DATA,) end function material_info(::Type{MicrofacetAnisotropicReflectionMaterial}) return (color=RPR.RPR_MATERIAL_INPUT_COLOR, normal=RPR.RPR_MATERIAL_INPUT_NORMAL, ior=RPR.RPR_MATERIAL_INPUT_IOR, roughness=RPR.RPR_MATERIAL_INPUT_ROUGHNESS, anisotropic=RPR.RPR_MATERIAL_INPUT_ANISOTROPIC, rotation=RPR.RPR_MATERIAL_INPUT_ROTATION) end function material_info(::Type{PhongMaterial}) return (color=RPR.RPR_MATERIAL_INPUT_COLOR, normal=RPR.RPR_MATERIAL_INPUT_NORMAL, ior=RPR.RPR_MATERIAL_INPUT_IOR, roughness=RPR.RPR_MATERIAL_INPUT_ROUGHNESS) end function material_info(::Type{BlendMaterial}) return (color1=RPR.RPR_MATERIAL_INPUT_COLOR0, color2=RPR.RPR_MATERIAL_INPUT_COLOR1, weight=RPR.RPR_MATERIAL_INPUT_WEIGHT, transmission_color=RPR.RPR_MATERIAL_INPUT_TRANSMISSION_COLOR, thickness=RPR.RPR_MATERIAL_INPUT_THICKNESS) end function material_info(::Type{MicrofacetAnisotropicRefractionMaterial}) return material_info(MicrofacetAnisotropicReflectionMaterial) end function material_info(::Type{MicrofacetMaterial}) return (color=RPR.RPR_MATERIAL_INPUT_COLOR, normal=RPR.RPR_MATERIAL_INPUT_NORMAL, ior=RPR.RPR_MATERIAL_INPUT_IOR, roughness=RPR.RPR_MATERIAL_INPUT_ROUGHNESS) end function material_info(::Type{TwosidedMaterial}) return (frontface=RPR.RPR_MATERIAL_INPUT_FRONTFACE, backface=RPR.RPR_MATERIAL_INPUT_BACKFACE) end function material_info(::Type{EmissiveMaterial}) return (color=RPR.RPR_MATERIAL_INPUT_COLOR,) end function material_info(::Type{RefractionMaterial}) return (color=RPR.RPR_MATERIAL_INPUT_COLOR, normal=RPR.RPR_MATERIAL_INPUT_NORMAL, ior=RPR.RPR_MATERIAL_INPUT_IOR, caustics=RPR.RPR_MATERIAL_INPUT_CAUSTICS) end function material_info(::Type{ReflectionMaterial}) return (color=RPR.RPR_MATERIAL_INPUT_COLOR, normal=RPR.RPR_MATERIAL_INPUT_NORMAL) end function material_info(::Type{TransparentMaterial}) return (color=RPR.RPR_MATERIAL_INPUT_COLOR,) end function material_info(::Type{ImageTextureMaterial}) return (data=RPR.RPR_MATERIAL_INPUT_DATA, uv=RPR.RPR_MATERIAL_INPUT_UV) end function material_info(::Type{InputLookupMaterial}) return (value=RPR.RPR_MATERIAL_INPUT_VALUE,) end function material_info(::Type{ArithmeticMaterial}) return (color1=RPR.RPR_MATERIAL_INPUT_COLOR0, color2=RPR.RPR_MATERIAL_INPUT_COLOR1, color3=RPR.RPR_MATERIAL_INPUT_COLOR2, color4=RPR.RPR_MATERIAL_INPUT_COLOR3, op=RPR.RPR_MATERIAL_INPUT_OP) end function material_field_info() f01 = (Float32, (0, 1)) return Dict(RPR.RPR_MATERIAL_INPUT_COLOR => RGB, RPR.RPR_MATERIAL_INPUT_COLOR0 => Material, RPR.RPR_MATERIAL_INPUT_COLOR1 => Material, RPR.RPR_MATERIAL_INPUT_NORMAL => Vec3, RPR.RPR_MATERIAL_INPUT_UV => Vec2, RPR.RPR_MATERIAL_INPUT_DATA => Image, RPR.RPR_MATERIAL_INPUT_ROUGHNESS => f01, RPR.RPR_MATERIAL_INPUT_IOR => (Float32, (1, 5)), RPR.RPR_MATERIAL_INPUT_ROUGHNESS_X => f01, RPR.RPR_MATERIAL_INPUT_ROUGHNESS_Y => f01, RPR.RPR_MATERIAL_INPUT_ROTATION => f01, RPR.RPR_MATERIAL_INPUT_WEIGHT => f01, RPR.RPR_MATERIAL_INPUT_OP => RPR.rpr_material_node_arithmetic_operation, # RPR.RPR_MATERIAL_INPUT_INVEC => , # RPR.RPR_MATERIAL_INPUT_UV_SCALE => , RPR.RPR_MATERIAL_INPUT_VALUE => RPR.rpr_material_node_lookup_value, RPR.RPR_MATERIAL_INPUT_REFLECTANCE => f01, RPR.RPR_MATERIAL_INPUT_SCALE => f01, RPR.RPR_MATERIAL_INPUT_SCATTERING => RGBA, RPR.RPR_MATERIAL_INPUT_ABSORBTION => RGBA, RPR.RPR_MATERIAL_INPUT_EMISSION => RGBA, RPR.RPR_MATERIAL_INPUT_G => (Float32, (-1, 1)), # Forward or back scattering. RPR.RPR_MATERIAL_INPUT_MULTISCATTER => Bool, RPR.RPR_MATERIAL_INPUT_COLOR2 => RGBA, RPR.RPR_MATERIAL_INPUT_COLOR3 => RGBA, RPR.RPR_MATERIAL_INPUT_ANISOTROPIC => (Float32, (-1, 1)), # amount forwards/backward RPR.RPR_MATERIAL_INPUT_FRONTFACE => Material, RPR.RPR_MATERIAL_INPUT_BACKFACE => Material, # RPR.RPR_MATERIAL_INPUT_ORIGIN => , # RPR.RPR_MATERIAL_INPUT_ZAXIS => , # RPR.RPR_MATERIAL_INPUT_XAXIS => , # RPR.RPR_MATERIAL_INPUT_THRESHOLD => , # RPR.RPR_MATERIAL_INPUT_OFFSET => , # RPR.RPR_MATERIAL_INPUT_UV_TYPE => , # RPR.RPR_MATERIAL_INPUT_RADIUS => , # RPR.RPR_MATERIAL_INPUT_SIDE => , RPR.RPR_MATERIAL_INPUT_CAUSTICS => Bool, RPR.RPR_MATERIAL_INPUT_TRANSMISSION_COLOR => RGBA, RPR.RPR_MATERIAL_INPUT_THICKNESS => f01, # RPR.RPR_MATERIAL_INPUT_0 => , # RPR.RPR_MATERIAL_INPUT_1 => , # RPR.RPR_MATERIAL_INPUT_2 => , # RPR.RPR_MATERIAL_INPUT_3 => , # RPR.RPR_MATERIAL_INPUT_4 => , RPR.RPR_MATERIAL_INPUT_SCHLICK_APPROXIMATION => Float32, # RPR.RPR_MATERIAL_INPUT_APPLYSURFACE => , # RPR.RPR_MATERIAL_INPUT_TANGENT => , # RPR.RPR_MATERIAL_INPUT_DISTRIBUTION => , # RPR.RPR_MATERIAL_INPUT_BASE => , # RPR.RPR_MATERIAL_INPUT_TINT => , # RPR.RPR_MATERIAL_INPUT_EXPONENT => , # RPR.RPR_MATERIAL_INPUT_AMPLITUDE => , # RPR.RPR_MATERIAL_INPUT_PIVOT => , # RPR.RPR_MATERIAL_INPUT_POSITION => , # RPR.RPR_MATERIAL_INPUT_AMOUNT => , # RPR.RPR_MATERIAL_INPUT_AXIS => , # RPR.RPR_MATERIAL_INPUT_LUMACOEFF => , # RPR.RPR_MATERIAL_INPUT_REFLECTIVITY => , # RPR.RPR_MATERIAL_INPUT_EDGE_COLOR => , # RPR.RPR_MATERIAL_INPUT_VIEW_DIRECTION => , # RPR.RPR_MATERIAL_INPUT_INTERIOR => , # RPR.RPR_MATERIAL_INPUT_OCTAVES => , # RPR.RPR_MATERIAL_INPUT_LACUNARITY => , # RPR.RPR_MATERIAL_INPUT_DIMINISH => , # RPR.RPR_MATERIAL_INPUT_WRAP_U => , # RPR.RPR_MATERIAL_INPUT_WRAP_V => , # RPR.RPR_MATERIAL_INPUT_WRAP_W => , # RPR.RPR_MATERIAL_INPUT_5 => , # RPR.RPR_MATERIAL_INPUT_6 => , # RPR.RPR_MATERIAL_INPUT_7 => , # RPR.RPR_MATERIAL_INPUT_8 => , # RPR.RPR_MATERIAL_INPUT_9 => , # RPR.RPR_MATERIAL_INPUT_10 => , # RPR.RPR_MATERIAL_INPUT_11 => , # RPR.RPR_MATERIAL_INPUT_12 => , # RPR.RPR_MATERIAL_INPUT_13 => , # RPR.RPR_MATERIAL_INPUT_14 => , # RPR.RPR_MATERIAL_INPUT_15 => , # RPR.RPR_MATERIAL_INPUT_DIFFUSE_RAMP => , # RPR.RPR_MATERIAL_INPUT_SHADOW => , # RPR.RPR_MATERIAL_INPUT_MID => , # RPR.RPR_MATERIAL_INPUT_HIGHLIGHT => , # RPR.RPR_MATERIAL_INPUT_POSITION1 => , # RPR.RPR_MATERIAL_INPUT_POSITION2 => , # RPR.RPR_MATERIAL_INPUT_RANGE1 => , # RPR.RPR_MATERIAL_INPUT_RANGE2 => , # RPR.RPR_MATERIAL_INPUT_INTERPOLATION => , # RPR.RPR_MATERIAL_INPUT_RANDOMNESS => , # RPR.RPR_MATERIAL_INPUT_DIMENSION => , # RPR.RPR_MATERIAL_INPUT_OUTTYPE => , RPR.RPR_MATERIAL_INPUT_DENSITY => Vec4f, RPR.RPR_MATERIAL_INPUT_DENSITYGRID => VoxelGrid, # RPR.RPR_MATERIAL_INPUT_DISPLACEMENT => , # RPR.RPR_MATERIAL_INPUT_TEMPERATURE => , # RPR.RPR_MATERIAL_INPUT_KELVIN => , RPR.RPR_MATERIAL_INPUT_UBER_DIFFUSE_COLOR => RGB, RPR.RPR_MATERIAL_INPUT_UBER_DIFFUSE_WEIGHT => f01, RPR.RPR_MATERIAL_INPUT_UBER_DIFFUSE_ROUGHNESS => f01, RPR.RPR_MATERIAL_INPUT_UBER_DIFFUSE_NORMAL => Vec3f, RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_COLOR => RGB, RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_WEIGHT => f01, RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_ROUGHNESS => f01, RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_ANISOTROPY => (Float32, (-1, 1)), RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_ANISOTROPY_ROTATION => f01, RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_MODE => f01, RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_IOR => (Float32, (1, 5)), RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_METALNESS => f01, RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_NORMAL => Vec3f, RPR.RPR_MATERIAL_INPUT_UBER_REFLECTION_DIELECTRIC_REFLECTANCE => f01, RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_COLOR => RGB, RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_WEIGHT => f01, RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_ROUGHNESS => f01, RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_IOR => (Float32, (1, 5)), RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_NORMAL => Vec3f, RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_THIN_SURFACE => Bool, RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_ABSORPTION_COLOR => RGB, RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_ABSORPTION_DISTANCE => Float32, # soft 0-10 RPR.RPR_MATERIAL_INPUT_UBER_REFRACTION_CAUSTICS => Bool, RPR.RPR_MATERIAL_INPUT_UBER_COATING_COLOR => RGB, RPR.RPR_MATERIAL_INPUT_UBER_COATING_WEIGHT => f01, RPR.RPR_MATERIAL_INPUT_UBER_COATING_ROUGHNESS => f01, RPR.RPR_MATERIAL_INPUT_UBER_COATING_MODE => f01, RPR.RPR_MATERIAL_INPUT_UBER_COATING_IOR => (Float32, (1, 5)), RPR.RPR_MATERIAL_INPUT_UBER_COATING_METALNESS => f01, RPR.RPR_MATERIAL_INPUT_UBER_COATING_NORMAL => Vec3f, RPR.RPR_MATERIAL_INPUT_UBER_COATING_TRANSMISSION_COLOR => RGB, RPR.RPR_MATERIAL_INPUT_UBER_COATING_THICKNESS => Float32, # soft 0-10 RPR.RPR_MATERIAL_INPUT_UBER_SHEEN => RGB, RPR.RPR_MATERIAL_INPUT_UBER_SHEEN_TINT => f01, RPR.RPR_MATERIAL_INPUT_UBER_SHEEN_WEIGHT => f01, RPR.RPR_MATERIAL_INPUT_UBER_EMISSION_COLOR => RGB, RPR.RPR_MATERIAL_INPUT_UBER_EMISSION_WEIGHT => f01, RPR.RPR_MATERIAL_INPUT_UBER_EMISSION_MODE => Bool, RPR.RPR_MATERIAL_INPUT_UBER_TRANSPARENCY => f01, RPR.RPR_MATERIAL_INPUT_UBER_SSS_SCATTER_COLOR => RGB, RPR.RPR_MATERIAL_INPUT_UBER_SSS_SCATTER_DISTANCE => Vec3f, # soft 0-10 RPR.RPR_MATERIAL_INPUT_UBER_SSS_SCATTER_DIRECTION => (Float32, (-1, 1)), RPR.RPR_MATERIAL_INPUT_UBER_SSS_WEIGHT => f01, RPR.RPR_MATERIAL_INPUT_UBER_SSS_MULTISCATTER => Bool, RPR.RPR_MATERIAL_INPUT_UBER_BACKSCATTER_WEIGHT => f01, RPR.RPR_MATERIAL_INPUT_UBER_BACKSCATTER_COLOR => RGB # RPR.RPR_MATERIAL_INPUT_ADDRESS => , # RPR.RPR_MATERIAL_INPUT_TYPE => , # RPR.RPR_MATERIAL_INPUT_UBER_FRESNEL_SCHLICK_APPROXIMATION => , ) end to_color(c::Colorant) = convert(RGBA{Float32}, c) to_color(c::Union{Symbol,String}) = parse(RGBA{Float32}, string(c)) function LayerMaterial(a, b; weight=Vec3f(0.5), transmission_color=nothing, thickness=Vec3f(0.1)) return BlendMaterial(a.matsys; color1=a.node, color2=b.node, weight=weight, transmission_color=transmission_color, thickness=thickness) end function ShinyMetal(matsys; kw...) return MicrofacetMaterial(matsys; color=to_color(:white), roughness=Vec3f(0.0), ior=Vec3f(1.5), # Aluminium kw...) end function Chrome(matsys; kw...) return MicrofacetMaterial(matsys; color=to_color(:gray), roughness=Vec3f(0.01), ior=Vec3f(1.390), # Aluminium kw...) end function Plastic(matsys; kw...) return UberMaterial(matsys; color=to_color(:yellow), reflection_color=Vec4f(1), reflection_weight=Vec4f(1), reflection_roughness=Vec4f(0), reflection_anisotropy=Vec4f(0), reflection_anisotropy_rotation=Vec4f(0), reflection_metalness=Vec4f(0), reflection_ior=Vec4f(1.5), refraction_weight=Vec4f(0), coating_weight=Vec4f(0), sheen_weight=Vec4f(0), emission_weight=Vec3f(0), transparency=Vec4f(0), reflection_mode=UInt(RPR.RPR_UBER_MATERIAL_IOR_MODE_PBR), emission_mode=UInt(RPR.RPR_UBER_MATERIAL_EMISSION_MODE_SINGLESIDED), coating_mode=UInt(RPR.RPR_UBER_MATERIAL_IOR_MODE_PBR), sss_multiscatter=false, refraction_thin_surface=false) end function Glass(matsys; kw...) return UberMaterial(matsys; reflection_color=Vec4f(0.9), reflection_weight=Vec4f(1.0), reflection_roughness=Vec4f(0.0), reflection_anisotropy=Vec4f(0.0), reflection_anisotropy_rotation=Vec4f(0.0), reflection_mode=1, reflection_ior=Vec4f(1.5), refraction_color=Vec4f(0.9), refraction_weight=Vec4f(1.0), refraction_roughness=Vec4f(0.0), refraction_ior=Vec4f(1.5), refraction_thin_surface=false, refraction_absorption_color=Vec4f(0.6, 0.8, 0.6, 0.0), refraction_absorption_distance=Vec4f(150), refraction_caustics=true, coating_weight=Vec4f(0), sheen_weight=Vec4f(0), emission_weight=Vec4f(0), transparency=Vec4f(0), kw...) end function arithmetic_material(op, args...) idx = findfirst(x -> x isa Material, args) mat_arg = args[idx] mat = ArithmeticMaterial(mat_arg.matsys) for (i, arg) in enumerate(args) setproperty!(mat, Symbol("color$i"), arg) end mat.op = op return mat end function Base.:(*)(mat::Material, arg) return arithmetic_material(RPR.RPR_MATERIAL_NODE_OP_MUL, mat, arg) end function Texture(matsys::MaterialSystem, matrix::AbstractMatrix; uv=nothing) context = get_context(matsys) img = Image(context, matrix) tex = ImageTextureMaterial(matsys) tex.data = img if !isnothing(uv) tex.uv = uv end return tex end """ Matx(matsys::MaterialSystem, path::String) Load a Material X xml definition from a `.mtlx` file. Only works with Northstar plugin! """ function Matx(matsys::MaterialSystem, path::String) ctx = get_context(matsys) if ctx.plugin != Northstar error("Matx needs Northstar plugin") end mat = MatxMaterial(matsys) RPR.rprMaterialXSetFile(mat.node, path) return mat end function DielectricBrdfX(matsys::MaterialSystem) return Matx(matsys, assetpath("textures", "matx_dielectricBrdf.mtlx")) end function SurfaceGoldX(matsys::MaterialSystem) ctx = get_context(matsys) RPR.rprMaterialXAddDependencyMtlx(ctx, assetpath("textures", "matx_standard_surface.mtlx")) return Matx(matsys, assetpath("textures", "matx_standard_surface_gold.mtlx")) end function CarPaintX(matsys::MaterialSystem) ctx = get_context(matsys) RPR.rprMaterialXAddDependencyMtlx(ctx, assetpath("textures", "matx_standard_surface.mtlx")) return Matx(matsys, assetpath("textures", "matx_standard_surface_xi_carPaint.mtlx")) end function StandardMetalX(matsys::MaterialSystem) return Matx(matsys, assetpath("textures", "matx_standard_surface_metal_texture.mtlx")) end # begin # mesh!(ax, m, material=athmo) # athmo = RPR.UberMaterial(matsys) # athmo.color = Vec4f(1, 1, 1, 1) # athmo.diffuse_weight = Vec4f(0, 0, 0, 0) # athmo.diffuse_roughness = Vec4f(0) # athmo.reflection_ior = Vec4f(1.0) # athmo.refraction_color = Vec4f(0.5, 0.5, 0.7, 0) # athmo.refraction_weight = Vec4f(1) # athmo.refraction_roughness = Vec4f(0) # athmo.refraction_ior =Vec4f(1.0) # athmo.refraction_absorption_color = Vec4f(0.9, 0.3, 0.1, 1) # athmo.refraction_absorption_distance = Vec4f(1) # athmo.refraction_caustics = false # athmo.sss_scatter_color = Vec4f(1.4, 0.8, 0.3, 0) # athmo.sss_scatter_distance = Vec4f(0.3) # athmo.sss_scatter_direction = Vec4f(0) # athmo.sss_weight = Vec4f(1) # athmo.backscatter_weight = Vec4f(1) # athmo.backscatter_color = Vec4f(0.9, 0.1, 0.1, 1) # athmo.reflection_mode = UInt(RPR.RPR_UBER_MATERIAL_IOR_MODE_PBR) # athmo.emission_mode = UInt(RPR.RPR_UBER_MATERIAL_EMISSION_MODE_DOUBLESIDED) # athmo.coating_mode = UInt(RPR.RPR_UBER_MATERIAL_IOR_MODE_PBR) # athmo.sss_multiscatter = true # athmo.refraction_thin_surface = false # notify(refresh) # end
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
2217
import GLMakie.GLAbstraction: Texture, render, std_renderobject, LazyShader import GLMakie.GLAbstraction: @frag_str, @vert_str import ModernGL: GL_TEXTURE_2D function FrameBuffer(context::Context, t::Texture{T,2}) where {T} frame_buffer = ContextCreateFramebufferFromGLTexture2D(context, GL_TEXTURE_2D, 0, t.id) x = FrameBuffer(frame_buffer) finalizer(release, x) return x end """ Creates an interactive context with the help of glvisualize to view the texture """ function interactive_context(glwindow) context = Context(RPR_CREATION_FLAGS_ENABLE_GPU0 | RPR_CREATION_FLAGS_ENABLE_GL_INTEROP) w, h = widths(glwindow) texture = Texture(RGBA{Float16}, (w, h)) view_tex(texture, glwindow) g_frame_buffer = FrameBuffer(context, texture) set!(context, RPR_AOV_COLOR, g_frame_buffer) return context, g_frame_buffer end """ blocking renderloop that uses tiling """ function tiledrenderloop(glwindow, context, framebuffer) ti = TileIterator(widths(glwindow), (256, 256)) tile_state = iterate(ti) while isopen(glwindow) glBindTexture(GL_TEXTURE_2D, 0) if isnothing(tile_state) # reset iterator tile_state = iterate(ti) end render(context, tile_state[1]) tile_state = iterate(ti, tile_state[2]) GLWindow.render_frame(glwindow) end end const tex_frag = frag""" {{GLSL_VERSION}} in vec2 o_uv; out vec4 fragment_color; out uvec2 fragment_groupid; uniform sampler2D image; void main(){ vec4 color = texture(image, o_uv); fragment_color = color/color.a; fragment_groupid = uvec2(0); } """ const tex_vert = vert""" {{GLSL_VERSION}} in vec2 vertices; in vec2 texturecoordinates; out vec2 o_uv; void main(){ o_uv = texturecoordinates; gl_Position = vec4(vertices, 0, 1); } """ """ A matrix of colors is interpreted as an image """ function view_tex(tex::Texture{T,2}, window) where {T} data = Dict{Symbol,Any}(:image => tex, :primitive => GLUVMesh2D(SimpleRectangle{Float32}(-1.0f0, -1.0f0, 2.0f0, 2.0f0))) robj = std_renderobject(data, LazyShader(tex_vert, tex_frag)) return view(robj, window; camera=:nothing) end
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
code
2281
using Test using RadeonProRender, GeometryBasics, Colors const RPR = RadeonProRender context = RPR.Context(resource=RPR.RPR_CREATION_FLAGS_ENABLE_CPU, plugin=RPR.Northstar) scene = RPR.Scene(context) matsys = RPR.MaterialSystem(context, 0) camera = RPR.Camera(context) lookat!(camera, Vec3f(8, 0, 5), Vec3f(2, 0, 2), Vec3f(0, 0, 1)) RPR.rprCameraSetFocalLength(camera, 45.0) set!(scene, camera) set!(context, scene) env_light = RadeonProRender.EnvironmentLight(context) image_path = RPR.assetpath("studio026.exr") img = RPR.Image(context, image_path) set!(env_light, img) setintensityscale!(env_light, 1.1) push!(scene, env_light) light = RPR.PointLight(context) transform!(light, Float32[1.0 0.0 0.0 2.0; 0.0 1.0 0.0 0.0; 0.0 0.0 1.0 5.0; 0.0 0.0 0.0 1.0]) f = 20 RPR.setradiantpower!(light, 500 / f, 641 / f, 630 / f) push!(scene, light) function add_shape!(scene, context, matsys, mesh; color=colorant"white") rpr_mesh = RadeonProRender.Shape(context, mesh) push!(scene, rpr_mesh) m = RPR.Plastic(matsys) m.color = color set!(rpr_mesh, m) return rpr_mesh, m end mesh, mat = add_shape!(scene, context, matsys, Rect3f(Vec3f(-10, -10, -1), Vec3f(20, 20, 1)); color=colorant"white") mesh, mat = add_shape!(scene, context, matsys, Rect3f(Vec3f(0, -10, 0), Vec3f(0.1, 20, 5)); color=colorant"green") mesh, mat = add_shape!(scene, context, matsys, Rect3f(Vec3f(0, -2, 0), Vec3f(5, 0.1, 5)); color=colorant"red") mesh, mat = add_shape!(scene, context, matsys, Rect3f(Vec3f(0, 2, 0), Vec3f(5, 0.1, 5)); color=colorant"blue") mesh, mat_sphere = add_shape!(scene, context, matsys, Tesselation(Sphere(Point3f(2, 0, 2), 1.0f0), 100); color=colorant"red") fb_size = (800, 600) frame_buffer = RPR.FrameBuffer(context, RGBA, fb_size) frame_bufferSolved = RPR.FrameBuffer(context, RGBA, fb_size) set!(context, RPR.RPR_AOV_COLOR, frame_buffer) set_standard_tonemapping!(context) clear!(frame_buffer) path = joinpath(@__DIR__, "test.png") RPR.rprContextSetParameterByKey1u(context, RPR.RPR_CONTEXT_ITERATIONS, 1) @time RPR.render(context) RPR.rprContextResolveFrameBuffer(context, frame_buffer, frame_bufferSolved, false) RPR.save(frame_bufferSolved, path) @test isfile(path)
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
docs
1210
# RadeonProRender Julia wrapper for AMD's [RadeonProRender](https://radeon-pro.github.io/RadeonProRenderDocs/en/index.html) library. ### Installation (Windows and Linux only right now!) In the Julia REPL, execute ```Julia Pkg.add("RadeonProRender") ``` # Displaced surface ![cat particles](https://github.com/JuliaGraphics/RadeonProRender.jl/blob/master/docs/surface.png?raw=true) [video](https://vimeo.com/154175783) [code](https://github.com/JuliaGraphics/RadeonProRender.jl/blob/master/examples/simple_displace.jl) # 3D wrapped surface ![surface mesh](https://github.com/JuliaGraphics/RadeonProRender.jl/blob/master/docs/surfmesh.png?raw=true) [video](https://vimeo.com/154174476) [code](https://github.com/JuliaGraphics/RadeonProRender.jl/blob/master/examples/surfacemesh.jl) # Particles ![surface mesh](https://github.com/JuliaGraphics/RadeonProRender.jl/blob/master/docs/carticles.png?raw=true) [video](https://vimeo.com/154174460) [code](https://github.com/JuliaGraphics/RadeonProRender.jl/blob/master/examples/instancing.jl) # Interactivity (slow, because of my slow hardware) ![surface mesh](https://github.com/JuliaGraphics/RadeonProRender.jl/blob/master/docs/interactive.gif?raw=true)
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
docs
2783
```julia using RadeonProRender, GeometryBasics, Colors const RPR = RadeonProRender function translationmatrix(t::Vec{3,T}) where {T} T0, T1 = zero(T), one(T) return Mat{4}(T1, T0, T0, T0, T0, T1, T0, T0, T0, T0, T1, T0, t[1], t[2], t[3], T1) end context = RPR.Context() scene = RPR.Scene(context) matsys = RPR.MaterialSystem(context, 0) camera = RPR.Camera(context) lookat!(camera, Vec3f(7, 0, 5), Vec3f(2, 0, 2), Vec3f(0, 0, 1)) RPR.rprCameraSetFocalLength(camera, 45.0) set!(scene, camera) set!(context, scene) env_light = RPR.EnvironmentLight(context) image_path = RPR.assetpath("studio026.exr") img = RPR.Image(context, image_path) set!(env_light, img) setintensityscale!(env_light, 1.1) push!(scene, env_light) light = RPR.PointLight(context) transform!(light, translationmatrix(Vec3f(2, 0, 5))) f = 20 RPR.setradiantpower!(light, 500 / f, 641 / f, 630 / f) push!(scene, light) function add_shape!(scene, context, matsys, mesh; material=RPR.RPR_MATERIAL_NODE_DIFFUSE, color=colorant"green", roughness=0.01) rpr_mesh = RPR.Shape(context, mesh) push!(scene, rpr_mesh) m = RPR.MaterialNode(matsys, material) set!(m, RPR.RPR_MATERIAL_INPUT_COLOR, color) set!(m, RPR.RPR_MATERIAL_INPUT_ROUGHNESS, roughness, roughness, roughness, roughness) set!(rpr_mesh, m) return rpr_mesh, m end mesh, mat = add_shape!(scene, context, matsys, Rect3f(Vec3f(-50, -50, -1), Vec3f(50*2, 50*2, 1)); color=colorant"white") x, y = collect(-8:0.5:8), collect(-8:0.5:8) z = [sinc(√(X^2 + Y^2) / π) for X ∈ x, Y ∈ y] M, N = size(z) points = map(x-> x ./ Point3f(4, 4, 1.0) .+ Point3f(0, 0, 1.0), vec(Point3f.(x, y', z))) # Connect the vetices with faces, as one would use for a 2D Rectangle # grid with M,N grid points faces = decompose(LineFace{GLIndex}, Tesselation(Rect2(0, 0, 1, 1), (M, N))) indices = RPR.rpr_int[] for elem in faces push!(indices, first(elem)-1, first(elem)-1, last(elem)-1, last(elem)-1) end curve = RPR.Curve(context, points, indices, [0.01], [Vec2f(0.1)], [length(faces)]) m = RPR.MaterialNode(matsys, RPR.RPR_MATERIAL_NODE_DIFFUSE) set!(m, RPR.RPR_MATERIAL_INPUT_COLOR, colorant"red") set!(m, RPR.RPR_MATERIAL_INPUT_ROUGHNESS, 0.0, 0.0, 0.0, 0.0) set!(curve, m) push!(scene, curve) fb_size = (800, 600) frame_buffer = RPR.FrameBuffer(context, RGBA, fb_size) frame_bufferSolved = RPR.FrameBuffer(context, RGBA, fb_size) set!(context, RPR.RPR_AOV_COLOR, frame_buffer) set_standard_tonemapping!(context) begin clear!(frame_buffer) RPR.rprContextSetParameterByKey1u(context, RPR.RPR_CONTEXT_ITERATIONS, 200) @time RPR.render(context) RPR.rprContextResolveFrameBuffer(context, frame_buffer, frame_bufferSolved, false) RPR.save(frame_bufferSolved, "curves.png") end ```
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.3.1
11a0186aa3101587e21c16b5baaffefd7f13c43f
docs
215
```@meta CurrentModule = RadeonProRender ``` # RadeonProRender Documentation for [RadeonProRender](https://github.com/SimonDanisch/RadeonProRender.jl). ```@index ``` ```@autodocs Modules = [RadeonProRender] ```
RadeonProRender
https://github.com/JuliaGraphics/RadeonProRender.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
682
using DynamicModelTestUtils using Documenter DocMeta.setdocmeta!(DynamicModelTestUtils, :DocTestSetup, :(using DynamicModelTestUtils); recursive=true) makedocs(; modules=[DynamicModelTestUtils], authors="Ben Chung <[email protected]> and contributors", repo="https://github.com/BenChung/DynamicModelTestUtils.jl/blob/{commit}{path}#{line}", sitename="DynamicModelTestUtils.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", edit_link="master", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs( repo = "github.com/JuliaComputing/DynamicModelTestUtils.jl.git", )
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
911
module ModelTestingCalibration using ModelTesting, ModelingToolkit using JuliaSimModelOptimizer function ModelTesting.validate(model::AbstractTimeDependentSystem, data; pem_coefficient=nothing, search_space = nothing, experiment_kwargs...) if !(:model_transformations ∈ keys(experiment_kwargs)) if !isnothing(pem_coefficient) model_transformations = [PredictionErrorMethod(pem_coefficient)] else model_transformations = [] end else model_transformations = experiment_kwargs[:model_transformations] end experiment = Experiment(data, model; model_transformations = model_transformations, filter(arg->first(arg) != :model_transformations, experiment_kwargs)...) # no search space - this is just a validation run i = InverseProblem([experiment], nothing, search_space) return simulate(experiment, i) end end
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
457
module DynamicModelTestUtils using DataFrames, StatsBase, LinearAlgebra using ModelingToolkit, SciMLBase, SymbolicIndexingInterface using CSV, Test abstract type DiscreteEvaluation end abstract type Metric end include("test/measured.jl") include("test/discretize.jl") include("test/instant.jl") include("test/compare.jl") include("problem_config/problem.jl") include("deploy/deploy.jl") include("deploy/restore.jl") include("integration/regression.jl") end
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
7354
using Git # this is substantially derivative of Documenter.jl's usage of git to run gh-pages abstract type DeployTarget end Base.@kwdef struct DeployConfig branch::String = "" repo::String = "" subfolder::String = "" all_ok::Bool = false end @enum AuthenticationMethod SSH HTTPS authentication_method(::DeployTarget) = SSH function authenticated_repo_url end post_status(cfg::Union{DeployTarget,Nothing}; kwargs...) = nothing function data_key(::DeployTarget) return ENV["DATA_KEY"] end function deploy_folder end function currentdir() d = Base.source_dir() d === nothing ? pwd() : d end const NO_KEY_ENV = Dict( "DOCUMENTER_KEY" => nothing, "DOCUMENTER_KEY_PREVIEWS" => nothing, ) function deploy( root = currentdir(), target = "data", dirname = ""; repo = error("no 'repo' keyword provided."), branch = "data", deploy_type::DeployTarget = nothing, archive = nothing ) deploy_config = deploy_folder(deploy_type; branch=branch, repo=repo, dataurl=dirname) if !deploy_config.all_ok return end deploy_branch = deploy_config.branch deploy_repo = deploy_config.repo deploy_subfolder = deploy_config.subfolder cd(root) do sha = try readchomp(`$(git()) rev-parse --short HEAD`) catch # git rev-parse will throw an error and return code 128 if it is not being # run in a git repository, which will make run/readchomp throw an exception. # We'll assume that if readchomp fails it is due to this and set the sha # variable accordingly. "(not-git-repo)" end @debug "setting up target directory." isdir(target) || mkpath(target) startswith(realpath(target), realpath(root)) || error(""" target must be a subdirectory of root, got: target: $(realpath(target)) root: $(realpath(root)) """) @debug "pushing new data to remote: '$deploy_repo:$deploy_branch'." mktempdir() do temp git_push( temp, deploy_repo; branch=deploy_branch, dirname=dirname, target=target, sha=sha, deploy_type=deploy_type, subfolder=deploy_subfolder, forcepush=false, archive=archive ) end end end function git_push( temp, repo; branch="gh-pages", dirname="", target="site", sha="", forcepush=false, deploy_type, subfolder, archive = false ) dirname = isempty(dirname) ? temp : joinpath(temp, dirname) isdir(dirname) || mkpath(dirname) target_dir = abspath(target) # Generate a closure with common commands for ssh and https function git_commands(sshconfig=nothing) # Setup git. run(`$(git()) init`) run(`$(git()) config user.name "todo"`) run(`$(git()) config user.email "[email protected]"`) if sshconfig !== nothing run(`$(git()) config core.sshCommand "ssh -F $(sshconfig)"`) end # Fetch from remote and checkout the branch. run(`$(git()) remote add upstream $upstream`) try run(`$(git()) fetch upstream`) catch e @error """ Git failed to fetch $upstream This can be caused by a DATA_KEY variable that is not correctly set up. Make sure that the environment variable is properly set up as a Base64-encoded string of the SSH private key. You may need to re-generate the keys. """ rethrow(e) end try run(`$(git()) checkout -b $branch upstream/$branch`) catch e @info """ Checking out $branch failed, creating a new orphaned branch. This usually happens when deploying to a repository for the first time and the $branch branch does not exist yet. The fatal error above is expected output from Git in this situation. """ @debug "checking out $branch failed with error: $e" run(`$(git()) checkout --orphan $branch`) run(`$(git()) commit --allow-empty -m "Initial empty commit for data"`) end # Copy docs to `subfolder` directory. deploy_dir = subfolder === nothing ? dirname : joinpath(dirname, subfolder) gitrm_copy(target_dir, deploy_dir) # Add, commit, and push the docs to the remote. run(`$(git()) add -A -- ':!.data-identity-file.tmp' ':!**/.data-identity-file.tmp'`) if !success(`$(git()) diff --cached --exit-code`) if !isnothing(archive) run(`$(git()) commit -m "build based on $sha"`) @info "Skipping push and writing repository to an archive" archive run(`$(git()) archive -o $(archive) HEAD`) elseif forcepush run(`$(git()) commit --amend --date=now -m "build based on $sha"`) run(`$(git()) push -fq upstream HEAD:$branch`) else run(`$(git()) commit -m "build based on $sha"`) run(`$(git()) push -q upstream HEAD:$branch`) end else @info "new data identical to the old -- not committing nor pushing." end end # The upstream URL to which we push new content authenticated with token upstream = authenticated_repo_url(deploy_type) try cd(() -> withenv(git_commands, NO_KEY_ENV...), temp) post_status(deploy_type; repo=repo, type="success", subfolder=subfolder) catch e @error "Failed to push:" exception=(e, catch_backtrace()) post_status(deploy_type; repo=repo, type="error") rethrow(e) end end """ gitrm_copy(src, dst) Uses `git rm -r` to remove `dst` and then copies `src` to `dst`. Assumes that the working directory is within the git repository of `dst` is when the function is called. This is to get around [#507](https://github.com/JuliaDocs/Documenter.jl/issues/507) on filesystems that are case-insensitive (e.g. on OS X, Windows). Without doing a `git rm` first, `git add -A` will not detect case changes in filenames. """ function gitrm_copy(src, dst) # Remove individual entries since with versions=nothing the root # would be removed and we want to preserve previews if isdir(dst) for x in filter!(!in((".git", "previews")), readdir(dst)) # --ignore-unmatch so that we wouldn't get errors if dst does not exist run(`$(git()) rm -rf --ignore-unmatch $(joinpath(dst, x))`) end end # git rm also remove parent directories # if they are empty so need to mkpath after mkpath(dst) # Copy individual entries rather then the full folder since with # versions=nothing it would replace the root including e.g. the .git folder for x in readdir(src) cp(joinpath(src, x), joinpath(dst, x); force=true) end end struct FilesystemDeployConfig <: DynamicModelTestUtils.DeployTarget repo_path :: String subfolder :: String end function DynamicModelTestUtils.deploy_folder(c::FilesystemDeployConfig; branch, repo, kwargs...) DynamicModelTestUtils.DeployConfig(; all_ok = true, subfolder = c.subfolder, branch, repo) end DynamicModelTestUtils.authentication_method(::FilesystemDeployConfig) = DynamicModelTestUtils.HTTPS DynamicModelTestUtils.authenticated_repo_url(c::FilesystemDeployConfig) = c.repo_path
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
1028
function load_data(action; root=currentdir(), branch="data") mktempdir() do temp cd(temp) do run(`$(git()) init`) run(`$(git()) config user.name "todo"`) run(`$(git()) config user.email "[email protected]"`) run(`$(git()) remote add upstream $root`) run(`$(git()) fetch upstream`) try run(`$(git()) checkout -b $branch upstream/$branch`) catch e @info """ Checking out $branch failed, creating a new orphaned branch. This usually happens when deploying to a repository for the first time and the $branch branch does not exist yet. The fatal error above is expected output from Git in this situation. Generate and commit some data to $branch, then try again. """ throw(Exception("checking out $branch failed with error: $e")) end action(temp) end end end
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
2767
function default_comparison(name, sol, df; tol=1e-3, show_results=true, kwargs...) cmp_df = compare(sol, df; kwargs...) if show_results @show cmp_df end # this is lame but is better than the alternatives for (idx, var) in enumerate(cmp_df[:, :var]) for (cidx, col) in enumerate(names(cmp_df)) if col ∈ ["observed", "var"] continue end @test cmp_df[idx, cidx] < tol # "Solution $name differs from regression data using metric $col on variable $var by $(cmp_df[idx, cidx])." end end return cmp_df end function regression_test( runs::Dict{Symbol, <:SciMLBase.AbstractTimeseriesSolution}, rootdir=currentdir(), data_dir="data", should_deploy="--deploy_data" ∈ ARGS; make_output_dir=false, clean_output_dir=false, deploy_only=false, restore=(go, root) -> load_data(go; root=root), cmp=(name, sol, df) -> default_comparison(name, sol, df), do_load=(filename) -> CSV.read(filename, DataFrame), discretize=(sol) -> discretize_solution(sol), save=(filename, df) -> CSV.write(filename, df), do_deploy=deploy, mk_filename=(symbol) -> string(symbol) * ".csv") should_save = false data_fulldir = joinpath(rootdir, data_dir) if !isfile(data_fulldir) && make_output_dir mkpath(data_fulldir) should_save = true elseif isfile(data_fulldir) && make_output_dir if clean_output_dir if !isempty(readdir(data_fulldir)) for rmfile in readdir(data_fulldir) @warn "Removing existing data file $rmfile" rm(rmfile) end end end should_save = true end if !deploy_only restore(rootdir) do restored cd(restored) do for (name, new_sol) in runs @assert isfile(mk_filename(name)) data = do_load(mk_filename(name)) cmp(name, new_sol, data) end end end end if should_save for (name, new_sol) in runs save(joinpath(data_fulldir, mk_filename(name)), discretize(new_sol)) end end if should_save && should_deploy do_deploy(rootdir, data_dir, deploy_type = DynamicModelTestUtils.FilesystemDeployConfig(rootdir, "."), repo = rootdir) elseif !should_save && should_deploy mktempdir() do temp cd(temp) do mkdir(data_dir) do_deploy(temp, data_dir, deploy_type = DynamicModelTestUtils.FilesystemDeployConfig(rootdir, "."), repo = rootdir) end end end end
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
721
module ProblemHelpers import SciMLBase using DataFrames # some thin wrappers over remake initial_condition(prob::SciMLBase.AbstractDEProblem, u0) = remake(prob, u0 = u0) tspan(prob::SciMLBase.AbstractDEProblem, tspan) = remake(prob, tspan = tspan) parameters(prob::SciMLBase.AbstractDEProblem, ps) = remake(prob, p = ps) remake_solver_kwarg(prob, merge; kwargs...) = remake(prob; kwargs = mergewith(merge, kwargs, prob.kwargs)) tstops(prob::SciMLBase.AbstractDEProblem, tstops) = remake_solver_kwarg(prob, (new, old) -> sort!([new; old]); tstops = tstops) tstops(prob::SciMLBase.AbstractDEProblem, tstops::DataFrame) = tstops(prob, collect(tstops[:, :timestamp])) export initial_condition, tspan, parameters, tstops end
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
7635
""" `DefaultComparison` is a convenience default comparison method for solutions and reference data. By default it's instantiated with l∞, l1, l2, RMS, and final l1 comparsons. More can be added by passing a dict of name=>comparison function pairs into `field_cmp`, with the signature (delta, dt_delta, t) -> [vector difference]. The arguments of these comparison functions are `delta` for the raw difference beteween the value, `dt_delta` for the product of dt and delta (if you want to approximate the integral of the error), and the timestamps at which the data was produced. The arguments consist of a vector per compared field. """ struct DefaultComparison field_cmp::Dict{Symbol, Function} function DefaultComparison(field_cmp::Dict{Symbol, Function}=Dict{Symbol, Function}(); use_defaults=true) if use_defaults merge!(field_cmp, Dict{Symbol, Function}([ :L∞ => (delta, dt_delta, t) -> norm.(dt_delta, Inf), :L1 => (delta, dt_delta, t) -> norm.(dt_delta, 1), :L2 => (delta, dt_delta, t) -> norm.(dt_delta, 2), :rms => (delta, dt_delta, t) -> sqrt.(1/length(t) .* sum.(map(d-> d .^ 2, dt_delta))), :final => (delta, dt_delta, t) -> last.(delta)])) end return new(field_cmp) end end """ (d::DefaultComparison)(c, names, b, t, n, r) Default comparison implementation. Returns a dataframe that describes the result of running each comparison operation on the given data. #Arguments * `c`: The symbolic container from which the values we're comparing came * `names`: The names to output for the fields we're comparing (not always the same as the names of the fields being compared) * `b`: The symbolic variables that are being compared * `t`: The timestamps at which the comparison is taking place * `n`: The new values being compared * `r`: The reference values to compare against """ function (d::DefaultComparison)(c, names, b, t, n, r) delta = map((o, re) -> o .- re, n, r) dt_delta = map(d -> 0.5 * (d[1:end-1] .+ d[2:end]) .* (t[2:end] .- t[1:end-1]), delta) cmps = [name => cmper(delta, dt_delta, t) for (name, cmper) in d.field_cmp] return DataFrame([:var => names, cmps..., :observed => SymbolicIndexingInterface.is_observed.(c, b)]) end function default_near_zero(result; ϵ=1e-7) obses = stack(result, 2:ncol(result)-1) for obs in eachrow(obses) @test obs[:value] < ϵ || "$(obs[:variable])($(obs[:var])) = $(obs[:value]) > ϵ = $ϵ" end @show result end """ compare( new_sol::SciMLBase.AbstractTimeseriesSolution, reference::DataFrame, over::Vector{<:Union{Pair{<:Any, String}, Pair{<:Any, Pair{String, String}}}} cmp=DefaultComparison(); warn_observed=true) Lower level version of `compare` that lets you specify the mapping from values in `new_sol` (specified as either variable => name or variable => (input_name, output_name) pairs) to the column names in `reference`. The tuple-result version lets you specify what the column names are when passed to the comparison method. Since the mapping is explicit this version does not take `to_name`, but it still does take `warn_observed`. See the implicit-comparison version of `compare` for more information. """ function compare( new_sol::SciMLBase.AbstractTimeseriesSolution, reference::DataFrame, over::Vector{<:Union{Pair{<:Any, String}, Pair{<:Any, Pair{String, String}}}}, cmp=DefaultComparison(); warn_observed=true) basis = first.(over) reference_basis = map(e -> e isa Pair ? first(e) : e, last.(over)) output_names = map((n1, n2) -> n2 isa Pair ? last(n2) : string(n1), basis, last.(over)) @assert "timestamp" ∈ names(reference) "The dataset must contain a column named `timestamp`" new_container = SymbolicIndexingInterface.symbolic_container(new_sol) @assert all(SymbolicIndexingInterface.is_observed.((new_container, ), basis) .| SymbolicIndexingInterface.is_variable.((new_container, ), basis)) "All basis symbols must be observed in the new system" @assert all(b ∈ names(reference) for b in reference_basis) "The reference basis must be a subset of the columns in the reference data" if new_sol.dense dat = new_sol(reference[:, :timestamp], idxs=basis) obs = [[dat[i, j] for j=1:nrow(reference)] for i in eachindex(basis)] ref = collect.(eachcol(reference[:, Not(:timestamp)])) cmp(new_container, output_names, basis, reference[:, :timestamp], obs, ref) else foldl(red, cmp(row[:timestamp], new_sol[row[:timestamp], basis], row[reference_basis]) for row in eachrow(reference); init=isnothing(init) ? nothing : init(basis)) end end """ compare( new_sol::SciMLBase.AbstractTimeseriesSolution, reference::DataFrame, cmp=DefaultComparison(); to_name=string, warn_observed=true) `compare` compares the results of `new_sol` to a result in `reference`, which may come from either experiment or a previous model execution. The format of `reference` is that produced by [`discretize_solution`](@ref): * A column named "timestamp" that indicates the time the measurement was taken (referenced to the same timebase as the solution provided) * Columns with names matching the names in the completed system `new_sol` (fully qualified) If `new_sol` is dense then the discretization nodes don't need to line up with the `reference` and the interpolant will be used instead. If it is not dense then the user must ensure that the saved states in are at the same times as the "timestamp"s are in the reference data. `compare` will use the comparison method specified by `cmp` to compare the two solutions; by default it uses the [`DefaultComparison`](@ref) (which offers l1, l2, and rms comparisons per observed value), but you can pass your own. Look at `DefaultComparison` for more details on how. The two optional named parameters are `to_name` (which is used to convert the symbolic variables in `new_sol` into valid column names for the dataframe) and `warn_observed` which controls whether `compare` complains about comparing observed values to non-observed values. We suggest leaving `warn_observed` on for regression testing (it'll give you a note when MTK changes the simplifcation of the system). """ function compare( new_sol::SciMLBase.AbstractTimeseriesSolution, reference::DataFrame, cmp=DefaultComparison(); to_name=string, warn_observed=true) @assert "timestamp" ∈ names(reference) "The dataset must contain a column named `timestamp`" eval_syms = reference_syms(SymbolicIndexingInterface.symbolic_container(new_sol), reference, to_name, warn_observed) return compare(new_sol, reference, eval_syms .=> setdiff(names(reference), ["timestamp"]), cmp) end function reference_syms(new_container, reference, to_name, warn_observed) all_available = SymbolicIndexingInterface.all_variable_symbols(new_container) all_available_syms = Dict(to_name.(all_available) .=> all_available) return [ begin @assert ref_name ∈ keys(all_available_syms) "Reference value $ref_name not found in the new solution (either as state or observed)" matching_sym = all_available_syms[ref_name] if warn_observed && SymbolicIndexingInterface.is_observed(new_container, matching_sym) @warn "The variable $matching_sym is observed in the new solution while the past $ref_name is provided explicitly; problem structure may have changed" end matching_sym end for ref_name in setdiff(names(reference), ["timestamp"])] end export compare
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
3875
_symbolic_subset(a, b) = all(av->any(bv->isequal(av, bv), b), a) function namespace_symbol(prefix, sym) return Symbol(string(prefix) * "/" * string(sym)) end function make_cols(names, rows) cols = [] for (i, name) in enumerate(names) col = zeros(length(rows)) for (j, row) in enumerate(rows) col[j] = row[i] end push!(cols, name=>col) end return cols end """ discretize_solution(solution::SciMLBase.AbstractTimeseriesSolution[, time_ref::SciMLBase.AbstractTimeseriesSolution]; measured=nothing, all_observed=false) `discretize_solution` takes a solution and an optional time reference and converts it into a dataframe. This dataframe will contain either: * The variables (unknowns or observeds) named in `measured`, if provided. * The variables marked as `measured` if `all_observed` is `false` and `measured` is `nothing`. * All variables in the system if `all_observed` is `true` and `measured` is `nothing`. The dataframe will contain a column called `timestamp` for each of the discretization times and a column for each observed value. If no time reference is provided then the timebase used to discretize `solution` will be used instead. """ function discretize_solution(solution::SciMLBase.AbstractTimeseriesSolution, time_ref::SciMLBase.AbstractTimeseriesSolution; measured=nothing, all_observed=false) container = SymbolicIndexingInterface.symbolic_container(time_ref) ref_t_vars = independent_variable_symbols(container) if length(ref_t_vars) > 1 @error "PDE solutions not currently supported; only one iv is allowed" end return discretize_solution(solution, time_ref[first(ref_t_vars)]; measured=measured, all_observed=all_observed) end function discretize_solution(solution::SciMLBase.AbstractTimeseriesSolution, time_ref::DataFrame; measured=nothing, all_observed=false) @assert "timestamp" ∈ names(time_ref) "The dataset B must contain a column named `timestamp`" return discretize_solution(solution, collect(time_ref[!, "timestamp"]); measured=measured, all_observed=all_observed) end function discretize_solution(solution::SciMLBase.AbstractTimeseriesSolution; measured=nothing, all_observed=false) container = SymbolicIndexingInterface.symbolic_container(solution) ref_t_vars = independent_variable_symbols(container) if length(ref_t_vars) > 1 @error "PDE solutions not currently supported; only one iv is allowed" end return discretize_solution(solution, solution[first(ref_t_vars)]; measured=measured, all_observed=all_observed ) end function discretize_solution(solution::SciMLBase.AbstractTimeseriesSolution, time_ref::AbstractArray; measured=nothing, all_observed=false) container = SymbolicIndexingInterface.symbolic_container(solution) if isnothing(measured) if all_observed measured = all_variable_symbols(container) else measured = measured_values(container) end end ref_t_vars = independent_variable_symbols(container) if length(ref_t_vars) > 1 @error "PDE solutions not currently supported; only one iv is allowed" end ref_t_var = first(ref_t_vars) matching_timebase = solution[ref_t_var] == time_ref if matching_timebase # if the time_ref match the timebase of the problem then use the value at the nodes regardless of if it's dense or sparse cols = make_cols(String["timestamp"; measured_names(measured)], solution[[ref_t_var; measured]]) elseif solution.dense # continious-time solution, use the interpolant cols = make_cols(String["timestamp"; measured_names(measured)], solution(time_ref, idxs=[ref_t_var; measured])) else throw("Cannot discretize_solution sparse solution about a different timebase.") end return DataFrame(cols) end export discretize_solution
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
1208
function test_instantaneous( sys::ModelingToolkit.AbstractSystem, ic, checks::Num; t = nothing) return test_instantaneous(sys, ic, checks; t = t) end """ test_instantaneous(sys::ModelingToolkit.AbstractSystem, ic, checks::Union{Num, Array}; t = nothing) `test_instantaneous` is a helper wrapper around constructing and executing an `ODEProblem` at a specific condition. It's intended for use in basic sanity checking of MTK models, for example to ensure that the derivative at a given condition has the correct sign. It should be passed the system, the initial condition dictionary to be given to the ODEProblem constructor (including parameters), and a list of observable values from the system to extract from the ODEProblem. If `checks` is a single `Num` then the result will be that observed value; otherwise it will return an array in the same order as the provided checks. """ function test_instantaneous( sys::ModelingToolkit.AbstractSystem, ic, checks::Array; t = nothing) t = isnothing(t) ? 0.0 : t prob = ODEProblem(sys, ic, (0.0, 0.0)) getter = getu(prob, checks) return getter(prob) end export test_instantaneous
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
1184
struct MeasuredVariable end Symbolics.option_to_metadata_type(::Val{:measured}) = MeasuredVariable ismeasured(x::Num, args...) = ismeasured(Symbolics.unwrap(x), args...) function ismeasured(x, default = false) p = Symbolics.getparent(x, nothing) p === nothing || (x = p) Symbolics.getmetadata(x, MeasuredVariable, default) end function setmeasured(x) setmetadata(x, MeasuredVariable, true) end function measured_values(sys, v=all_variable_symbols(sys)) filter(x -> ismeasured(x, false), v) end function measured_system_values(sys) reference_container = symbolic_container(sys) return measured_values(reference_container) end function measured_names(measured) return string.(measured) end @mtkmodel MeasureComponent begin @variables begin value(t), [measured = true] end end function Measurement(sensor; name) @assert length(variable_symbols(sensor)) == 1 "The Measurement helper requires that the measurement component have only one scalar-valued state" @variables t value(t) [measured = true] return ODESystem([ value ~ first(sensor.states) ], t; name = name) end export Measurement, MeasureComponent
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
2813
using ModelingToolkitStandardLibrary.Electrical using ModelingToolkitStandardLibrary.Blocks: Constant using SymbolicIndexingInterface @testset "Block Modeling" begin @testset "RC Functional" begin R = 1.0 C = 1.0 V = 1.0 @variables t @named resistor = Resistor(R = R) @named capacitor = Capacitor(C = C) @named source = Voltage() @named constant = Constant(k = V) @named ground = Ground() @named sensor = PotentialSensor() @named key_parameter = MeasureComponent() rc_eqs = [connect(constant.output, source.V) connect(source.p, resistor.p) connect(resistor.n, capacitor.p) connect(capacitor.n, source.n, ground.g) connect(sensor.p, capacitor.p) sensor.phi ~ key_parameter.value] @named rc_model = ODESystem(rc_eqs, t, systems = [resistor, capacitor, constant, source, ground, sensor, key_parameter]) sys = structural_simplify(rc_model) prob1 = ODEProblem(sys, Pair[], (0, 10.0)) sol1 = solve(prob1, Tsit5()) prob2 = ODEProblem(sys, Pair[capacitor.C => 0.9], (0, 10.0)) # this converges to nearly the same solution but is a little too fast sol2 = solve(prob2, Tsit5()) prob3 = ODEProblem(sys, Pair[capacitor.C => 5.0], (0, 10.0)) # this doesn't stabilize in the allotted time sol3 = solve(prob3, Tsit5()) d1 = discretize_solution(sol1, sol1) ds1 = discretize_solution(sol1, sol1; measured=SymbolicIndexingInterface.all_variable_symbols(sys)) @test sum(compare(sol1, ds1; warn_observed=false)[:, :L∞]) < 0.01 @test sum(compare(sol2, ds1; warn_observed=false)[:, :L∞]) > sum(compare(sol1, ds1; warn_observed=false)[:, :L∞]) @test sum(compare(sol3, ds1; warn_observed=false)[:, :L∞]) > sum(compare(sol2, ds1; warn_observed=false)[:, :L∞]) @test sum(compare(sol1, ds1; warn_observed=false)[:, :L∞]) > sum(compare(sol1, d1; warn_observed=false)[:, :L∞]) @test sum(compare(sol2, ds1; warn_observed=false)[:, :L∞]) > sum(compare(sol2, d1; warn_observed=false)[:, :L∞]) @test sum(compare(sol3, ds1; warn_observed=false)[:, :L∞]) > sum(compare(sol3, d1; warn_observed=false)[:, :L∞]) # construct a fictional power measurement power_synth = select(ds1, :timestamp, ["capacitor₊v(t)", "capacitor₊i(t)"] => ((v, i) -> v .* i) => "power") @test compare(sol1, power_synth, [capacitor.i * capacitor.v => "power" => "power"])[1, "L∞"] < 0.01 @test compare(sol2, power_synth, [capacitor.i * capacitor.v => "power" => "power"])[1, "L∞"] < 0.05 @test compare(sol3, power_synth, [capacitor.i * capacitor.v => "power" => "power"])[1, "L∞"] < 0.3 end end
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
4793
using Git, CSV @testset "deploy" begin @testset "bare" begin mktempdir() do dir cd(dir) do mkdir("repo") run(`$(git()) -C repo init -q --bare`) full_repo_path = joinpath(pwd(), "repo") mkdir("runs") write("runs/run.csv", "1,2,3") DynamicModelTestUtils.deploy( pwd(), "runs", deploy_type = DynamicModelTestUtils.FilesystemDeployConfig(full_repo_path, "."), repo = full_repo_path ) run(`$(git()) clone -q -b data $(full_repo_path) worktree`) println(readdir("worktree/")) @test isfile(joinpath("worktree", "run.csv")) DynamicModelTestUtils.load_data(root=full_repo_path) do localdir @test isfile("run.csv") end end end end @testset "RC deploy" begin R = 1.0 C = 1.0 V = 1.0 @variables t @named resistor = Resistor(R = R) @named capacitor = Capacitor(C = C) @named source = Voltage() @named constant = Constant(k = V) @named ground = Ground() @named sensor = PotentialSensor() @named key_parameter = MeasureComponent() rc_eqs = [connect(constant.output, source.V) connect(source.p, resistor.p) connect(resistor.n, capacitor.p) connect(capacitor.n, source.n, ground.g) connect(sensor.p, capacitor.p) sensor.phi ~ key_parameter.value] @named rc_model = ODESystem(rc_eqs, t, systems = [resistor, capacitor, constant, source, ground, sensor, key_parameter]) sys = structural_simplify(rc_model) prob1 = ODEProblem(sys, Pair[], (0, 10.0)) sol = solve(prob1, Tsit5()) d1 = discretize_solution(sol) mktempdir() do dir cd(dir) do mkdir("repo") run(`$(git()) -C repo init -q --bare`) full_repo_path = joinpath(pwd(), "repo") mkdir("data") CSV.write("data/output.csv", d1) DynamicModelTestUtils.deploy( pwd(), "data", deploy_type = DynamicModelTestUtils.FilesystemDeployConfig(full_repo_path, "."), repo = full_repo_path, ) DynamicModelTestUtils.load_data(root=full_repo_path) do localdir @test isfile("output.csv") restored = CSV.read("output.csv", DataFrame) @test sum(compare(sol, restored)[:, :L∞]) < 0.01 end end end end @testset "RC regression" begin R = 1.0 C = 1.0 V = 1.0 @variables t @named resistor = Resistor(R = R) @named capacitor = Capacitor(C = C) @named source = Voltage() @named constant = Constant(k = V) @named ground = Ground() @named sensor = PotentialSensor() @named key_parameter = MeasureComponent() rc_eqs = [connect(constant.output, source.V) connect(source.p, resistor.p) connect(resistor.n, capacitor.p) connect(capacitor.n, source.n, ground.g) connect(sensor.p, capacitor.p) sensor.phi ~ key_parameter.value] @named rc_model = ODESystem(rc_eqs, t, systems = [resistor, capacitor, constant, source, ground, sensor, key_parameter]) sys = structural_simplify(rc_model) prob1 = ODEProblem(sys, Pair[], (0, 10.0)) sol = solve(prob1, Tsit5()) prob2 = ODEProblem(sys, Pair[capacitor.C => 0.5], (0, 10.0)) sol2 = solve(prob2, Tsit5()) println("\n\n\nstart deploy test") mktempdir() do dir cd(dir) do mkdir("repo") run(`$(git()) -C repo init -q --bare`) full_repo_path = joinpath(pwd(), "repo") DynamicModelTestUtils.regression_test(Dict(:rc => sol), full_repo_path, "data", true; deploy_only = true, make_output_dir = true) println("deployed! to $full_repo_path") run(`$(git()) clone -q -b data $(full_repo_path) worktree`) println(readdir("worktree/")) DynamicModelTestUtils.regression_test(Dict( :rc => sol ), full_repo_path) #DynamicModelTestUtils.regression_test(Dict( # :rc => sol2 #), full_repo_path) end end end end
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
1135
@testset "Instantaneous" begin @testset "RC Functional" begin R = 1.0 C = 1.0 V = 1.0 @variables t @named resistor = Resistor(R = R) @named capacitor = Capacitor(C = C) @named source = Voltage() @named constant = Constant(k = V) @named ground = Ground() @named sensor = PotentialSensor() rc_eqs = [connect(constant.output, source.V) connect(source.p, resistor.p) connect(resistor.n, capacitor.p) connect(capacitor.n, source.n, ground.g) connect(sensor.p, capacitor.p)] @named rc_model = ODESystem(rc_eqs, t, systems = [resistor, capacitor, constant, source, ground, sensor]) sys = structural_simplify(rc_model) @test test_instantaneous(sys, [], [resistor.v]; t = 0.0)[1] > 0 @test test_instantaneous(sys, [], [resistor.i]; t = 0.0)[1] > 0 @test test_instantaneous(sys, [constant.k => 0.0], [resistor.v]; t = 0.0)[1] == 0 @test test_instantaneous(sys, [constant.k => 5.0], [resistor.v]; t = 0.0)[1] == 5 end end
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
code
330
#using JuliaSimModelOptimizer using DynamicModelTestUtils using DifferentialEquations, DataFrames, ModelingToolkit import SymbolicIndexingInterface using Test @testset "DynamicModelTestUtils.jl" begin #include("timeseries.jl") include("block_modeling.jl") include("instantaneous.jl") include("deployment.jl") end
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
docs
361
# DynamicModelTestUtils DynamicModelTestUtils is a simple package that wraps SymbolicIndexingInterface to provide straightforward model regression analysis & comparision functionality. It can export model result data using `discretize_solution` into a DataFrame and can compare against those DataFrames using `compare`. It's intended for use in CI pipelines.
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.2
ac31f04f4e5f0161782471b9c913faa26902b475
docs
586
```@meta CurrentModule = DynamicModelTestUtils ``` # DynamicModelTestUtils Documentation for [DynamicModelTestUtils](https://github.com/BenChung/DynamicModelTestUtils.jl). DynamicModelTestUtils is intended to facilitate the easy testing and post-facto analysis of ModelingToolkit models. It currently provides two key bits of functionality: * Serialization of MTK solutions into a common format through `discretize_solution`. * Comparison of solutions to each other and to previously-saved data through `compare`. ```@index ``` ```@autodocs Modules = [DynamicModelTestUtils] ```
DynamicModelTestUtils
https://github.com/JuliaComputing/DynamicModelTestUtils.jl.git
[ "MIT" ]
0.1.0
2147f4d3442e2cc9a3e7d3961dda2341e3f4f3c4
code
730
using CitationRecipes using Documenter DocMeta.setdocmeta!(CitationRecipes, :DocTestSetup, :(using CitationRecipes); recursive=true) makedocs(; modules=[CitationRecipes], authors="singularitti <[email protected]> and contributors", repo="https://github.com/singularitti/CitationRecipes.jl/blob/{commit}{path}#{line}", sitename="CitationRecipes.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://singularitti.github.io/CitationRecipes.jl", edit_link="main", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/singularitti/CitationRecipes.jl", devbranch="main", )
CitationRecipes
https://github.com/singularitti/CitationRecipes.jl.git
[ "MIT" ]
0.1.0
2147f4d3442e2cc9a3e7d3961dda2341e3f4f3c4
code
1168
module CitationRecipes using Bibliography: Entry, xyear using RecipesBase: AbstractPlot, @recipe, @series, @shorthands @recipe function f( ::Type{Val{:experimentaldata}}, plt::AbstractPlot; ref=nothing, n_authors=1 ) label = if ref isa Entry join((truncate_authors(ref, n_authors), xyear(ref)), ", ") else string(get(plotattributes, :label, "")) end seriestype := :scatter # It has to be `:=`! markersize --> 3 markerstrokecolor --> :auto markerstrokewidth --> 0 label --> label return () end @shorthands experimentaldata @recipe function f(::Type{Val{:prediction}}, plt::AbstractPlot; ref=nothing, n_authors=1) label = if ref isa Entry join((truncate_authors(ref, n_authors), xyear(ref)), ", ") else string(get(plotattributes, :label, "")) end seriestype := :path # It has to be `:=`! label --> label return () end @shorthands prediction function truncate_authors(ref::Entry, n::Integer) authors = Iterators.take(ref.authors, n) suffix = n < length(ref.authors) ? "et. al." : "" return join([[author.last for author in authors]; suffix], ", ") end end
CitationRecipes
https://github.com/singularitti/CitationRecipes.jl.git
[ "MIT" ]
0.1.0
2147f4d3442e2cc9a3e7d3961dda2341e3f4f3c4
code
103
using CitationRecipes using Test @testset "CitationRecipes.jl" begin # Write your tests here. end
CitationRecipes
https://github.com/singularitti/CitationRecipes.jl.git
[ "MIT" ]
0.1.0
2147f4d3442e2cc9a3e7d3961dda2341e3f4f3c4
docs
4044
# CitationRecipes | **Documentation** | **Build Status** | **Others** | | :--------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------: | | [![Stable][docs-stable-img]][docs-stable-url] [![Dev][docs-dev-img]][docs-dev-url] | [![Build Status][gha-img]][gha-url] [![Build Status][appveyor-img]][appveyor-url] [![Build Status][cirrus-img]][cirrus-url] [![pipeline status][gitlab-img]][gitlab-url] [![Coverage][codecov-img]][codecov-url] | [![GitHub license][license-img]][license-url] [![Code Style: Blue][style-img]][style-url] | [docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [docs-stable-url]: https://singularitti.github.io/CitationRecipes.jl/stable [docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg [docs-dev-url]: https://singularitti.github.io/CitationRecipes.jl/dev [gha-img]: https://github.com/singularitti/CitationRecipes.jl/workflows/CI/badge.svg [gha-url]: https://github.com/singularitti/CitationRecipes.jl/actions [appveyor-img]: https://ci.appveyor.com/api/projects/status/github/singularitti/CitationRecipes.jl?svg=true [appveyor-url]: https://ci.appveyor.com/project/singularitti/CitationRecipes-jl [cirrus-img]: https://api.cirrus-ci.com/github/singularitti/CitationRecipes.jl.svg [cirrus-url]: https://cirrus-ci.com/github/singularitti/CitationRecipes.jl [gitlab-img]: https://gitlab.com/singularitti/CitationRecipes.jl/badges/main/pipeline.svg [gitlab-url]: https://gitlab.com/singularitti/CitationRecipes.jl/-/pipelines [codecov-img]: https://codecov.io/gh/singularitti/CitationRecipes.jl/branch/main/graph/badge.svg [codecov-url]: https://codecov.io/gh/singularitti/CitationRecipes.jl [license-img]: https://img.shields.io/github/license/singularitti/CitationRecipes.jl [license-url]: https://github.com/singularitti/CitationRecipes.jl/blob/main/LICENSE [style-img]: https://img.shields.io/badge/code%20style-blue-4495d1.svg [style-url]: https://github.com/invenia/BlueStyle The code is [hosted on GitHub](https://github.com/singularitti/CitationRecipes.jl), with some continuous integration services to test its validity. This repository is created and maintained by [@singularitti](https://github.com/singularitti). You are very welcome to contribute. ## Installation The package can be installed with the Julia package manager. From the Julia REPL, type `]` to enter the Pkg REPL mode and run: ``` pkg> add CitationRecipes ``` Or, equivalently, via the [`Pkg` API](https://pkgdocs.julialang.org/v1/getting-started/): ```julia julia> import Pkg; Pkg.add("CitationRecipes") ``` ## Documentation - [**STABLE**][docs-stable-url] — **documentation of the most recently tagged version.** - [**DEV**][docs-dev-url] — _documentation of the in-development version._ ## Project status The package is tested against, and being developed for, Julia `1.6` and above on Linux, macOS, and Windows. ## Questions and contributions You are welcome to post usage questions on [our discussion page][discussions-url]. Contributions are very welcome, as are feature requests and suggestions. Please open an [issue][issues-url] if you encounter any problems. The [Contributing](@ref) page has guidelines that should be followed when opening pull requests and contributing code. [discussions-url]: https://github.com/singularitti/CitationRecipes.jl/discussions [issues-url]: https://github.com/singularitti/CitationRecipes.jl/issues
CitationRecipes
https://github.com/singularitti/CitationRecipes.jl.git
[ "MIT" ]
0.1.0
2147f4d3442e2cc9a3e7d3961dda2341e3f4f3c4
docs
1999
```@meta CurrentModule = CitationRecipes ``` # CitationRecipes Documentation for [CitationRecipes](https://github.com/singularitti/CitationRecipes.jl). See the [Index](@ref main-index) for the complete list of documented functions and types. The code is [hosted on GitHub](https://github.com/singularitti/CitationRecipes.jl), with some continuous integration services to test its validity. This repository is created and maintained by [@singularitti](https://github.com/singularitti). You are very welcome to contribute. ## Installation The package can be installed with the Julia package manager. From the Julia REPL, type `]` to enter the Pkg REPL mode and run: ```julia pkg> add CitationRecipes ``` Or, equivalently, via the `Pkg` API: ```@repl import Pkg; Pkg.add("CitationRecipes") ``` ## Documentation - [**STABLE**](https://singularitti.github.io/CitationRecipes.jl/stable) — **documentation of the most recently tagged version.** - [**DEV**](https://singularitti.github.io/CitationRecipes.jl/dev) — _documentation of the in-development version._ ## Project status The package is tested against, and being developed for, Julia `1.6` and above on Linux, macOS, and Windows. ## Questions and contributions Usage questions can be posted on [our discussion page](https://github.com/singularitti/CitationRecipes.jl/discussions). Contributions are very welcome, as are feature requests and suggestions. Please open an [issue](https://github.com/singularitti/CitationRecipes.jl/issues) if you encounter any problems. The [Contributing](@ref) page has a few guidelines that should be followed when opening pull requests and contributing code. ## Manual outline ```@contents Pages = [ "installation.md", "developers/contributing.md", "developers/style-guide.md", "developers/design-principles.md", "troubleshooting.md", ] Depth = 3 ``` ## Library outline ```@contents Pages = ["public.md"] ``` ### [Index](@id main-index) ```@index Pages = ["public.md"] ```
CitationRecipes
https://github.com/singularitti/CitationRecipes.jl.git
[ "MIT" ]
0.1.0
2147f4d3442e2cc9a3e7d3961dda2341e3f4f3c4
docs
5241
# [Installation Guide](@id installation) Here are the installation instructions for package [CitationRecipes](https://github.com/singularitti/CitationRecipes.jl). If you have trouble installing it, please refer to our [Troubleshooting](@ref) page for more information. ## Install Julia First, you should install [Julia](https://julialang.org/). We recommend downloading it from [its official website](https://julialang.org/downloads/). Please follow the detailed instructions on its website if you have to [build Julia from source](https://docs.julialang.org/en/v1/devdocs/build/build/). Some computing centers provide preinstalled Julia. Please contact your administrator for more information in that case. Here's some additional information on [how to set up Julia on HPC systems](https://github.com/hlrs-tasc/julia-on-hpc-systems). If you have [Homebrew](https://brew.sh) installed, [open `Terminal.app`](https://support.apple.com/guide/terminal/open-or-quit-terminal-apd5265185d-f365-44cb-8b09-71a064a42125/mac) and type ```shell brew install julia ``` to install it as a [formula](https://docs.brew.sh/Formula-Cookbook). If you are also using macOS and want to install it as a prebuilt binary app, type ```shell brew install --cask julia ``` instead. If you want to install multiple Julia versions in the same operating system, a recommended way is to use a version manager such as [`juliaup`](https://github.com/JuliaLang/juliaup). First, [install `juliaup`](https://github.com/JuliaLang/juliaup#installation). Then, run ```shell juliaup add release juliaup default release ``` to configure the `julia` command to start the latest stable version of Julia (this is also the default value). There is a [short video introduction to `juliaup`](https://youtu.be/14zfdbzq5BM) made by its authors. ### Which version should I pick? You can install the "Current stable release" or the "Long-term support (LTS) release". - The "Current stable release" is the latest release of Julia. It has access to newer features, and is likely faster. - The "Long-term support release" is an older version of Julia that has continued to receive bug and security fixes. However, it may not have the latest features or performance improvements. For most users, you should install the "Current stable release", and whenever Julia releases a new version of the current stable release, you should update your version of Julia. Note that any code you write on one version of the current stable release will continue to work on all subsequent releases. For users in restricted software environments (e.g., your enterprise IT controls what software you can install), you may be better off installing the long-term support release because you will not have to update Julia as frequently. Versions higher than `v1.3`, especially `v1.6`, are strongly recommended. This package may not work on `v1.0` and below. Since the Julia team has set `v1.6` as the LTS release, we will gradually drop support for versions below `v1.6`. Julia and Julia packages support multiple operating systems and CPU architectures; check [this table](https://julialang.org/downloads/#supported_platforms) to see if it can be installed on your machine. For Mac computers with M-series processors, this package and its dependencies may not work. Please install the Intel-compatible version of Julia (for macOS x86-64) if any platform-related error occurs. ## Install CitationRecipes Now I am using [macOS](https://en.wikipedia.org/wiki/MacOS) as a standard platform to explain the following steps: 1. Open `Terminal.app`, and type `julia` to start an interactive session (known as the [REPL](https://docs.julialang.org/en/v1/stdlib/REPL/)). 2. Run the following commands and wait for them to finish: ```julia-repl julia> using Pkg julia> Pkg.update() julia> Pkg.add("CitationRecipes") ``` 3. Run ```julia-repl julia> using CitationRecipes ``` and have fun! 4. While using, please keep this Julia session alive. Restarting might cost some time. If you want to install the latest in-development (probably buggy) version of CitationRecipes, type ```@repl using Pkg Pkg.update() pkg"add https://github.com/singularitti/CitationRecipes.jl" ``` in the second step above. ## Update CitationRecipes Please [watch](https://docs.github.com/en/account-and-profile/managing-subscriptions-and-notifications-on-github/setting-up-notifications/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository) our [GitHub repository](https://github.com/singularitti/CitationRecipes.jl) for new releases. Once we release a new version, you can update CitationRecipes by typing ```@repl using Pkg Pkg.update("CitationRecipes") Pkg.gc() ``` in the Julia REPL. ## Uninstall and reinstall CitationRecipes Sometimes errors may occur if the package is not properly installed. In this case, you may want to uninstall and reinstall the package. Here is how to do that: 1. To uninstall, in a Julia session, run ```julia-repl julia> using Pkg julia> Pkg.rm("CitationRecipes") julia> Pkg.gc() ``` 2. Press `ctrl+d` to quit the current session. Start a new Julia session and reinstall CitationRecipes.
CitationRecipes
https://github.com/singularitti/CitationRecipes.jl.git
[ "MIT" ]
0.1.0
2147f4d3442e2cc9a3e7d3961dda2341e3f4f3c4
docs
2150
# Troubleshooting ```@contents Pages = ["troubleshooting.md"] Depth = 3 ``` This page collects some possible errors you may encounter and trick how to fix them. If you have some questions about how to use this code, you are welcome to [discuss with us](https://github.com/singularitti/CitationRecipes.jl/discussions). If you have additional tips, please either [report an issue](https://github.com/singularitti/CitationRecipes.jl/issues/new) or [submit a PR](https://github.com/singularitti/CitationRecipes.jl/compare) with suggestions. ## Installation problems ### Cannot find the `julia` executable Make sure you have Julia installed in your environment. Please download the latest [stable version](https://julialang.org/downloads/#current_stable_release) for your platform. If you are using a *nix system, the recommended way is to use [Juliaup](https://github.com/JuliaLang/juliaup). If you do not want to install Juliaup or you are using other platforms that Julia supports, download the corresponding binaries. Then, create a symbolic link to the Julia executable. If the path is not in your `$PATH` environment variable, export it to your `$PATH`. Some clusters, like [Habanero](https://confluence.columbia.edu/confluence/display/rcs/Habanero+HPC+Cluster+User+Documentation), [Comet](https://www.sdsc.edu/support/user_guides/comet.html), or [Expanse](https://www.sdsc.edu/services/hpc/expanse/index.html), already have Julia installed as a module, you may just `module load julia` to use it. If not, either install by yourself or contact your administrator. ## Loading CitationRecipes ### Julia compiles/loads slow First, we recommend you download the latest version of Julia. Usually, the newest version has the best performance. If you just want Julia to do a simple task and only once, you could start the Julia REPL with ```bash julia --compile=min ``` to minimize compilation or ```bash julia --optimize=0 ``` to minimize optimizations, or just use both. Or you could make a system image and run with ```bash julia --sysimage custom-image.so ``` See [Fredrik Ekre's talk](https://youtu.be/IuwxE3m0_QQ?t=313) for details.
CitationRecipes
https://github.com/singularitti/CitationRecipes.jl.git
[ "MIT" ]
0.1.0
2147f4d3442e2cc9a3e7d3961dda2341e3f4f3c4
docs
8537
# Contributing ```@contents Pages = ["contributing.md"] Depth = 3 ``` Welcome! This document explains some ways you can contribute to CitationRecipes. ## Code of conduct This project and everyone participating in it is governed by the ["Contributor Covenant Code of Conduct"](https://github.com/MineralsCloud/.github/blob/main/CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. ## Join the community forum First up, join the [community forum](https://github.com/singularitti/CitationRecipes.jl/discussions). The forum is a good place to ask questions about how to use CitationRecipes. You can also use the forum to discuss possible feature requests and bugs before raising a GitHub issue (more on this below). Aside from asking questions, the easiest way you can contribute to CitationRecipes is to help answer questions on the forum! ## Improve the documentation Chances are, if you asked (or answered) a question on the community forum, then it is a sign that the [documentation](https://singularitti.github.io/CitationRecipes.jl/dev/) could be improved. Moreover, since it is your question, you are probably the best-placed person to improve it! The docs are written in Markdown and are built using [Documenter.jl](https://github.com/JuliaDocs/Documenter.jl). You can find the source of all the docs [here](https://github.com/singularitti/CitationRecipes.jl/tree/main/docs). If your change is small (like fixing typos, or one or two sentence corrections), the easiest way to do this is via GitHub's online editor. (GitHub has [help](https://help.github.com/articles/editing-files-in-another-user-s-repository/) on how to do this.) If your change is larger, or touches multiple files, you will need to make the change locally and then use Git to submit a [pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests). (See [Contribute code to CitationRecipes](@ref) below for more on this.) ## File a bug report Another way to contribute to CitationRecipes is to file [bug reports](https://github.com/singularitti/CitationRecipes.jl/issues/new?template=bug_report.md). Make sure you read the info in the box where you write the body of the issue before posting. You can also find a copy of that info [here](https://github.com/singularitti/CitationRecipes.jl/blob/main/.github/ISSUE_TEMPLATE/bug_report.md). !!! tip If you're unsure whether you have a real bug, post on the [community forum](https://github.com/singularitti/CitationRecipes.jl/discussions) first. Someone will either help you fix the problem, or let you know the most appropriate place to open a bug report. ## Contribute code to CitationRecipes Finally, you can also contribute code to CitationRecipes! !!! warning If you do not have experience with Git, GitHub, and Julia development, the first steps can be a little daunting. However, there are lots of tutorials available online, including: - [GitHub](https://guides.github.com/activities/hello-world/) - [Git and GitHub](https://try.github.io/) - [Git](https://git-scm.com/book/en/v2) - [Julia package development](https://docs.julialang.org/en/v1/stdlib/Pkg/#Developing-packages-1) Once you are familiar with Git and GitHub, the workflow for contributing code to CitationRecipes is similar to the following: ### Step 1: decide what to work on The first step is to find an [open issue](https://github.com/singularitti/CitationRecipes.jl/issues) (or open a new one) for the problem you want to solve. Then, _before_ spending too much time on it, discuss what you are planning to do in the issue to see if other contributors are fine with your proposed changes. Getting feedback early can improve code quality, and avoid time spent writing code that does not get merged into CitationRecipes. !!! tip At this point, remember to be patient and polite; you may get a _lot_ of comments on your issue! However, do not be afraid! Comments mean that people are willing to help you improve the code that you are contributing to CitationRecipes. ### Step 2: fork CitationRecipes Go to [https://github.com/singularitti/CitationRecipes.jl](https://github.com/singularitti/CitationRecipes.jl) and click the "Fork" button in the top-right corner. This will create a copy of CitationRecipes under your GitHub account. ### Step 3: install CitationRecipes locally Similar to [Installation](@ref), open the Julia REPL and run: ```@repl using Pkg Pkg.update() Pkg.develop("CitationRecipes") ``` Then the package will be cloned to your local machine. On *nix systems, the default path is `~/.julia/dev/CitationRecipes` unless you modify the [`JULIA_DEPOT_PATH`](http://docs.julialang.org/en/v1/manual/environment-variables/#JULIA_DEPOT_PATH-1) environment variable. If you're on Windows, this will be `C:\\Users\\<my_name>\\.julia\\dev\\CitationRecipes`. In the following text, we will call it `PKGROOT`. Go to `PKGROOT`, start a new Julia session and run ```@repl using Pkg Pkg.instantiate() ``` to instantiate the project. ### Step 4: checkout a new branch !!! note In the following, replace any instance of `GITHUB_ACCOUNT` with your GitHub username. The next step is to checkout a development branch. In a terminal (or command prompt on Windows), run: ```shell cd ~/.julia/dev/CitationRecipes git remote add GITHUB_ACCOUNT https://github.com/GITHUB_ACCOUNT/CitationRecipes.jl.git git checkout main git pull git checkout -b my_new_branch ``` ### Step 5: make changes Now make any changes to the source code inside the `~/.julia/dev/CitationRecipes` directory. Make sure you: - Follow our [Style Guide](@ref style) and [run `JuliaFormatter.jl`](@ref formatter) - Add tests and documentation for any changes or new features !!! tip When you change the source code, you'll need to restart Julia for the changes to take effect. This is a pain, so install [Revise.jl](https://github.com/timholy/Revise.jl). ### Step 6a: test your code changes To test that your changes work, run the CitationRecipes test-suite by opening Julia and running: ```@repl cd("~/.julia/dev/CitationRecipes") using Pkg Pkg.activate(".") Pkg.test() ``` !!! warning Running the tests might take a long time. !!! tip If you're using `Revise.jl`, you can also run the tests by calling `include`: ```julia include("test/runtests.jl") ``` This can be faster if you want to re-run the tests multiple times. ### Step 6b: test your documentation changes Open Julia, then run: ```@repl cd("~/.julia/dev/CitationRecipes/docs") using Pkg Pkg.activate(".") include("src/make.jl") ``` After a while, a folder `PKGROOT/docs/build` will appear. Open `PKGROOT/docs/build/index.html` with your favorite browser, and have fun! !!! warning Building the documentation might take a long time. !!! tip If there's a problem with the tests that you don't know how to fix, don't worry. Continue to step 5, and one of the CitationRecipes contributors will comment on your pull request telling you how to fix things. ### Step 7: make a pull request Once you've made changes, you're ready to push the changes to GitHub. Run: ```shell cd ~/.julia/dev/CitationRecipes git add . git commit -m "A descriptive message of the changes" git push -u GITHUB_ACCOUNT my_new_branch ``` Then go to [https://github.com/singularitti/CitationRecipes.jl/pulls](https://github.com/singularitti/CitationRecipes.jl/pulls) and follow the instructions that pop up to open a pull request. ### Step 8: respond to comments At this point, remember to be patient and polite; you may get a _lot_ of comments on your pull request! However, do not be afraid! A lot of comments means that people are willing to help you improve the code that you are contributing to CitationRecipes. To respond to the comments, go back to step 5, make any changes, test the changes in step 6, and then make a new commit in step 7. Your PR will automatically update. ### Step 9: cleaning up Once the PR is merged, clean-up your Git repository ready for the next contribution! ```shell cd ~/.julia/dev/CitationRecipes git checkout main git pull ``` !!! note If you have suggestions to improve this guide, please make a pull request! It's particularly helpful if you do this after your first pull request because you'll know all the parts that could be explained better. Thanks for contributing to CitationRecipes!
CitationRecipes
https://github.com/singularitti/CitationRecipes.jl.git
[ "MIT" ]
0.1.0
2147f4d3442e2cc9a3e7d3961dda2341e3f4f3c4
docs
15492
# Design Principles ```@contents Pages = ["design-principles.md"] Depth = 3 ``` We adopt some [`SciML`](https://sciml.ai/) design [guidelines](https://github.com/SciML/SciMLStyle) here. Please read it before contributing! ## Consistency vs adherence According to PEP8: > A style guide is about consistency. Consistency with this style guide is important. > Consistency within a project is more important. Consistency within one module or function is the most important. > > However, know when to be inconsistent—sometimes style guide recommendations just aren't > applicable. When in doubt, use your best judgment. Look at other examples and decide what > looks best. And don’t hesitate to ask! ## Community contribution guidelines For a comprehensive set of community contribution guidelines, refer to [ColPrac](https://github.com/SciML/ColPrac). A relevant point to highlight PRs should do one thing. In the context of style, this means that PRs which update the style of a package's code should not be mixed with fundamental code contributions. This separation makes it easier to ensure that large style improvement are isolated from substantive (and potentially breaking) code changes. ## Open source contributions are allowed to start small and grow over time If the standard for code contributions is that every PR needs to support every possible input type that anyone can think of, the barrier would be too high for newcomers. Instead, the principle is to be as correct as possible to begin with, and grow the generic support over time. All recommended functionality should be tested, any known generality issues should be documented in an issue (and with a `@test_broken` test when possible). However, a function which is known to not be GPU-compatible is not grounds to block merging, rather it is an encouragement for a follow-up PR to improve the general type support! ## Generic code is preferred unless code is known to be specific For example, the code: ```@repl function f(A, B) for i in 1:length(A) A[i] = A[i] + B[i] end end ``` would not be preferred for two reasons. One is that it assumes `A` uses one-based indexing, which would fail in cases like [OffsetArrays](https://github.com/JuliaArrays/OffsetArrays.jl) and [FFTViews](https://github.com/JuliaArrays/FFTViews.jl). Another issue is that it requires indexing, while not all array types support indexing (for example, [CuArrays](https://github.com/JuliaGPU/CuArrays.jl)). A more generic compatible implementation of this function would be to use broadcast, for example: ```@repl function f(A, B) @. A = A + B end ``` which would allow support for a wider variety of array types. ## Internal types should match the types used by users when possible If `f(A)` takes the input of some collections and computes an output from those collections, then it should be expected that if the user gives `A` as an `Array`, the computation should be done via `Array`s. If `A` was a `CuArray`, then it should be expected that the computation should be internally done using a `CuArray` (or appropriately error if not supported). For these reasons, constructing arrays via generic methods, like `similar(A)`, is preferred when writing `f` instead of using non-generic constructors like `Array(undef,size(A))` unless the function is documented as being non-generic. ## Trait definition and adherence to generic interface is preferred when possible Julia provides many interfaces, for example: - [Iteration](https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-iteration) - [Indexing](https://docs.julialang.org/en/v1/manual/interfaces/#Indexing) - [Broadcast](https://docs.julialang.org/en/v1/manual/interfaces/#man-interfaces-broadcasting) Those interfaces should be followed when possible. For example, when defining broadcast overloads, one should implement a `BroadcastStyle` as suggested by the documentation instead of simply attempting to bypass the broadcast system via `copyto!` overloads. When interface functions are missing, these should be added to Base Julia or an interface package, like [ArrayInterface.jl](https://github.com/JuliaArrays/ArrayInterface.jl). Such traits should be declared and used when appropriate. For example, if a line of code requires mutation, the trait `ArrayInterface.ismutable(A)` should be checked before attempting to mutate, and informative error messages should be written to capture the immutable case (or, an alternative code which does not mutate should be given). One example of this principle is demonstrated in the generation of Jacobian matrices. In many scientific applications, one may wish to generate a Jacobian cache from the user's input `u0`. A naive way to generate this Jacobian is `J = similar(u0,length(u0),length(u0))`. However, this will generate a Jacobian `J` such that `J isa Matrix`. ## Macros should be limited and only be used for syntactic sugar Macros define new syntax, and for this reason they tend to be less composable than other coding styles and require prior familiarity to be easily understood. One principle to keep in mind is, "can the person reading the code easily picture what code is being generated?". For example, a user of Soss.jl may not know what code is being generated by: ```julia @model (x, α) begin σ ~ Exponential() β ~ Normal() y ~ For(x) do xj Normal(α + β * xj, σ) end return y end ``` and thus using such a macro as the interface is not preferred when possible. However, a macro like [`@muladd`](https://github.com/SciML/MuladdMacro.jl) is trivial to picture on a code (it recursively transforms `a*b + c` to `muladd(a,b,c)` for more [accuracy and efficiency](https://en.wikipedia.org/wiki/Multiply%E2%80%93accumulate_operation)), so using such a macro for example: ```julia julia> @macroexpand(@muladd k3 = f(t + c3 * dt, @. uprev + dt * (a031 * k1 + a032 * k2))) :(k3 = f((muladd)(c3, dt, t), (muladd).(dt, (muladd).(a032, k2, (*).(a031, k1)), uprev))) ``` is recommended. Some macros in this category are: - `@inbounds` - [`@muladd`](https://github.com/SciML/MuladdMacro.jl) - `@view` - [`@named`](https://github.com/SciML/ModelingToolkit.jl) - `@.` - [`@..`](https://github.com/YingboMa/FastBroadcast.jl) Some performance macros, like `@simd`, `@threads`, or [`@turbo` from LoopVectorization.jl](https://github.com/JuliaSIMD/LoopVectorization.jl), make an exception in that their generated code may be foreign to many users. However, they still are classified as appropriate uses as they are syntactic sugar since they do (or should) not change the behavior of the program in measurable ways other than performance. ## Errors should be caught as high as possible, and error messages should be contextualized for newcomers Whenever possible, defensive programming should be used to check for potential errors before they are encountered deeper within a package. For example, if one knows that `f(u0,p)` will error unless `u0` is the size of `p`, this should be caught at the start of the function to throw a domain specific error, for example "parameters and initial condition should be the same size". ## Subpackaging and interface packages is preferred over conditional modules via Requires.jl Requires.jl should be avoided at all costs. If an interface package exists, such as [ChainRulesCore.jl](https://github.com/JuliaDiff/ChainRulesCore.jl) for defining automatic differentiation rules without requiring a dependency on the whole ChainRules.jl system, or [RecipesBase.jl](https://github.com/JuliaPlots/RecipesBase.jl) which allows for defining Plots.jl plot recipes without a dependency on Plots.jl, a direct dependency on these interface packages is preferred. Otherwise, instead of resorting to a conditional dependency using Requires.jl, it is preferred one creates subpackages, i.e. smaller independent packages kept within the same Github repository with independent versioning and package management. An example of this is seen in [Optimization.jl](https://github.com/SciML/Optimization.jl) which has subpackages like [OptimizationBBO.jl](https://github.com/SciML/Optimization.jl/tree/master/lib/OptimizationBBO) for BlackBoxOptim.jl support. Some important interface packages to know about are: - [ChainRulesCore.jl](https://github.com/JuliaDiff/ChainRulesCore.jl) - [RecipesBase.jl](https://github.com/JuliaPlots/RecipesBase.jl) - [ArrayInterface.jl](https://github.com/JuliaArrays/ArrayInterface.jl) - [CommonSolve.jl](https://github.com/SciML/CommonSolve.jl) - [SciMLBase.jl](https://github.com/SciML/SciMLBase.jl) ## Functions should either attempt to be non-allocating and reuse caches, or treat inputs as immutable Mutating codes and non-mutating codes fall into different worlds. When a code is fully immutable, the compiler can better reason about dependencies, optimize the code, and check for correctness. However, many times a code making the fullest use of mutation can outperform even what the best compilers of today can generate. That said, the worst of all worlds is when code mixes mutation with non-mutating code. Not only is this a mishmash of coding styles, it has the potential non-locality and compiler proof issues of mutating code while not fully benefiting from the mutation. ## Out-Of-Place and Immutability is preferred when sufficient performant Mutation is used to get more performance by decreasing the amount of heap allocations. However, if it's not helpful for heap allocations in a given spot, do not use mutation. Mutation is scary and should be avoided unless it gives an immediate benefit. For example, if matrices are sufficiently large, then `A*B` is as fast as `mul!(C,A,B)`, and thus writing `A*B` is preferred (unless the rest of the function is being careful about being fully non-allocating, in which case this should be `mul!` for consistency). Similarly, when defining types, using `struct` is preferred to `mutable struct` unless mutating the struct is a common occurrence. Even if mutating the struct is a common occurrence, see whether using [Setfield.jl](https://github.com/jw3126/Setfield.jl) is sufficient. The compiler will optimize the construction of immutable structs, and thus this can be more efficient if it's not too much of a code hassle. ## Tests should attempt to cover a wide gamut of input types Code coverage numbers are meaningless if one does not consider the input types. For example, one can hit all the code with `Array`, but that does not test whether `CuArray` is compatible! Thus, it's always good to think of coverage not in terms of lines of code but in terms of type coverage. A good list of number types to think about are: - `Float64` - `Float32` - `Complex` - [`Dual`](https://github.com/JuliaDiff/ForwardDiff.jl) - `BigFloat` Array types to think about testing are: - `Array` - [`OffsetArray`](https://github.com/JuliaArrays/OffsetArrays.jl) - [`CuArray`](https://github.com/JuliaGPU/CUDA.jl) ## When in doubt, a submodule should become a subpackage or separate package Keep packages to one core idea. If there's something separate enough to be a submodule, could it instead be a separate well-tested and documented package to be used by other packages? Most likely yes. ## Globals should be avoided whenever possible Global variables should be avoided whenever possible. When required, global variables should be constants and have an all uppercase name separated with underscores (e.g. `MY_CONSTANT`). They should be defined at the top of the file, immediately after imports and exports but before an `__init__` function. If you truly want mutable global style behavior you may want to look into mutable containers. ## Type-stable and Type-grounded code is preferred wherever possible Type-stable and type-grounded code helps the compiler create not only more optimized code, but also faster to compile code. Always keep containers well-typed, functions specializing on the appropriate arguments, and types concrete. ## Closures should be avoided whenever possible Closures can cause accidental type instabilities that are difficult to track down and debug; in the long run it saves time to always program defensively and avoid writing closures in the first place, even when a particular closure would not have been problematic. A similar argument applies to reading code with closures; if someone is looking for type instabilities, this is faster to do when code does not contain closures. Furthermore, if you want to update variables in an outer scope, do so explicitly with `Ref`s or self defined structs. For example, ```julia map(Base.Fix2(getindex, i), vector_of_vectors) ``` is preferred over ```julia map(v -> v[i], vector_of_vectors) ``` or ```julia [v[i] for v in vector_of_vectors] ``` ## Numerical functionality should use the appropriate generic numerical interfaces While you can use `A\b` to do a linear solve inside a package, that does not mean that you should. This interface is only sufficient for performing factorizations, and so that limits the scaling choices, the types of `A` that can be supported, etc. Instead, linear solves within packages should use LinearSolve.jl. Similarly, nonlinear solves should use NonlinearSolve.jl. Optimization should use Optimization.jl. Etc. This allows the full generic choice to be given to the user without depending on every solver package (effectively recreating the generic interfaces within each package). ## Functions should capture one underlying principle Functions mean one thing. Every dispatch of `+` should be "the meaning of addition on these types". While in theory you could add dispatches to `+` that mean something different, that will fail in generic code for which `+` means addition. Thus, for generic code to work, code needs to adhere to one meaning for each function. Every dispatch should be an instantiation of that meaning. ## Internal choices should be exposed as options whenever possible Whenever possible, numerical values and choices within scripts should be exposed as options to the user. This promotes code reusability beyond the few cases the author may have expected. ## Prefer code reuse over rewrites whenever possible If a package has a function you need, use the package. Add a dependency if you need to. If the function is missing a feature, prefer to add that feature to said package and then add it as a dependency. If the dependency is potentially troublesome, for example because it has a high load time, prefer to spend time helping said package fix these issues and add the dependency. Only when it does not seem possible to make the package "good enough" should using the package be abandoned. If it is abandoned, consider building a new package for this functionality as you need it, and then make it a dependency. ## Prefer to not shadow functions Two functions can have the same name in Julia by having different namespaces. For example, `X.f` and `Y.f` can be two different functions, with different dispatches, but the same name. This should be avoided whenever possible. Instead of creating `MyPackage.sort`, consider adding dispatches to `Base.sort` for your types if these new dispatches match the underlying principle of the function. If it doesn't, prefer to use a different name. While using `MyPackage.sort` is not conflicting, it is going to be confusing for most people unfamiliar with your code, so `MyPackage.special_sort` would be more helpful to newcomers reading the code.
CitationRecipes
https://github.com/singularitti/CitationRecipes.jl.git
[ "MIT" ]
0.1.0
2147f4d3442e2cc9a3e7d3961dda2341e3f4f3c4
docs
2296
# [Style Guide](@id style) ```@contents Pages = ["style.md"] Depth = 3 ``` This section describes the coding style rules that apply to our code and that we recommend you to use it also. In some cases, our style guide diverges from Julia's official [Style Guide](https://docs.julialang.org/en/v1/manual/style-guide/) (Please read it!). All such cases will be explicitly noted and justified. Our style guide adopts many recommendations from the [BlueStyle](https://github.com/invenia/BlueStyle). Please read the [BlueStyle](https://github.com/invenia/BlueStyle) before contributing to this package. If not following, your pull requests may not be accepted. !!! info The style guide is always a work in progress, and not all CitationRecipes code follows the rules. When modifying CitationRecipes, please fix the style violations of the surrounding code (i.e., leave the code tidier than when you started). If large changes are needed, consider separating them into another pull request. ## Formatting ### [Run JuliaFormatter](@id formatter) CitationRecipes uses [JuliaFormatter](https://github.com/domluna/JuliaFormatter.jl) as an auto-formatting tool. We use the options contained in [`.JuliaFormatter.toml`](https://github.com/singularitti/CitationRecipes.jl/blob/main/.JuliaFormatter.toml). To format your code, `cd` to the CitationRecipes directory, then run: ```@repl using Pkg Pkg.add("JuliaFormatter") using JuliaFormatter: format format("docs"); format("src"); format("test"); ``` !!! info A continuous integration check verifies that all PRs made to CitationRecipes have passed the formatter. The following sections outline extra style guide points that are not fixed automatically by JuliaFormatter. ### Use the Julia extension for Visual Studio Code Please use [VS Code](https://code.visualstudio.com/) with the [Julia extension](https://marketplace.visualstudio.com/items?itemName=julialang.language-julia) to edit, format, and test your code. We do not recommend using other editors to edit your code for the time being. This extension already has [JuliaFormatter](https://github.com/domluna/JuliaFormatter.jl) integrated. So to format your code, follow the steps listed [here](https://www.julia-vscode.org/docs/stable/userguide/formatter/).
CitationRecipes
https://github.com/singularitti/CitationRecipes.jl.git
[ "BSD-3-Clause" ]
0.1.4
688e5028028e0dd8807efe6fff4a55a1a0832818
code
503
using Documenter, OptimalTransmissionRouting Documenter.makedocs( modules = OptimalTransmissionRouting, format = Documenter.HTML(), sitename = "OptimalTransmissionRouting", authors = "Hakan Ergun", pages = [ "Home" => "index.md" ] ) Documenter.deploydocs( target = "build", repo = "github.com/Electa-Git/OptimalTransmissionRouting.jl.git", branch = "gh-pages", devbranch = "main", versions = ["stable" => "v^", "v#.#"], push_preview = false )
OptimalTransmissionRouting
https://github.com/Electa-Git/OptimalTransmissionRouting.jl.git
[ "BSD-3-Clause" ]
0.1.4
688e5028028e0dd8807efe6fff4a55a1a0832818
code
1379
isdefined(Base, :__precompile__) && __precompile__() module OptimalTransmissionRouting # import Compat import JuMP import Memento import Images import FileIO import ColorTypes import Plots # Create our module level logger (this will get precompiled) const _LOGGER = Memento.getlogger(@__MODULE__) # Register the module level logger at runtime so that folks can access the logger via `getlogger(PowerModels)` # NOTE: If this line is not included then the precompiled `_PM._LOGGER` won't be registered at runtime. __init__() = Memento.register(_LOGGER) include("core/define_weights.jl") include("core/image2weight.jl") include("core/optimal_routing.jl") include("core/costs_and_equipment_details.jl") include("core/a_star.jl") include("core/impedance_parameters.jl") include("core/spatial_data_preparation.jl") include("io/plot_optimal_path.jl") # Spatial image files # include("spatial_image_files/clc_agricultural.tif") # include("spatial_image_files/clc_mountains.tif") # include("spatial_image_files/clc_natural.tif") # include("spatial_image_files/clc_urban.tif") # include("spatial_image_files/clc_graph_Europe.tif") # include("spatial_image_files/clc_grid_225kv_400kv.tif") # include("spatial_image_files/natura2000.tif") # include("spatial_image_files/clc_railroads.tif") # include("spatial_image_files/clc_roads.tif") # include("spatial_image_files/sea.tif") end
OptimalTransmissionRouting
https://github.com/Electa-Git/OptimalTransmissionRouting.jl.git
[ "BSD-3-Clause" ]
0.1.4
688e5028028e0dd8807efe6fff4a55a1a0832818
code
12281
function optimize_route(spatial_data, spatial_data_matrices, cost_data, equipment_data, input_data) # weights_ac = snw.weights_ac_cable; # snw.meanweight_ac=alg_fac*min(weighy_ac(weighy_ac~=0)); # weighy_dc=snw.weights_dc_cable; # snw.meanweight_dc=alg_fac*min(weighy_dc(weighy_dc~=0)); # snw.meanweight_dc=alg_fac*min([snw.weights]); # snw.meanweight_dc=1; # snw.meanweight_ac=snw.meanweight_dc; start_position, finish_position = determine_start_and_end_node(spatial_data_matrices, input_data) average_weight = sum(spatial_data["segment_weights"]) / size(spatial_data["segment_weights"] ,1) minimum_weight = minimum(spatial_data["segment_weights"][spatial_data["segment_weights"] .!= 0]) from_node = start_position to_node = finish_position OPEN_COUNT = 1 path_cost = 0 offshore_distance = 0 average_weight = minimum_weight target_distance = estimate_initial_distance(start_position, finish_position, spatial_data, average_weight) hn = path_cost gn = target_distance fn = target_distance wn = target_distance ac_cable = 0 dc_cable = 0 ac_dc_transition = 0 OPEN = my_insert_open(from_node, to_node, hn, gn, fn, wn, ac_dc_transition, ac_cable, dc_cable, offshore_distance, spatial_data) OPEN[OPEN_COUNT, 1] = 0 CLOSED_COUNT = 1 CLOSED = [from_node] NoPath = 1 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # START ALGORITHM #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% while (from_node != finish_position) && (NoPath == 1) exp_array = my_expand_array(from_node, path_cost, start_position, finish_position, CLOSED, spatial_data, offshore_distance, input_data, average_weight, equipment_data) exp_count = size(exp_array, 1) # UPDATE LIST OPEN WITH THE SUCCESSOR NODES # OPEN LIST FORMAT #-------------------------------------------------------------------------- #IS ON LIST 1/0 |X val |Y val |Parent X val |Parent Y val |h(n) |g(n)|f(n)| #-------------------------------------------------------------------------- #EXPANDED ARRAY FORMAT #-------------------------------- #|X val |Y val ||h(n) |g(n)|f(n)| #-------------------------------- for i = 1 : exp_count flag = 0 if any(OPEN[1 : OPEN_COUNT, 2] .== exp_array[i, 1]) j = findfirst(OPEN[1 : OPEN_COUNT, 2] .== exp_array[i, 1]) if exp_array[i, 4] <= OPEN[j, 10] OPEN[j, 3] = from_node OPEN[j, 4] = spatial_data["nodes"][from_node, 2] OPEN[j, 5] = spatial_data["nodes"][from_node, 3] OPEN[j, 8] = exp_array[i, 2] OPEN[j, 9] = exp_array[i, 3] OPEN[j, 10] = exp_array[i, 4] OPEN[j, 11] = exp_array[i, 5] OPEN[j, 12] = exp_array[i, 6] OPEN[j, 13] = exp_array[i, 7] OPEN[j, 14] = exp_array[i, 8] OPEN[j, 15] = exp_array[i, 9] end else OPEN_COUNT = OPEN_COUNT + 1 new_line = my_insert_open(exp_array[i, 1], from_node, exp_array[i, 2], exp_array[i, 3], exp_array[i,4], exp_array[i,5], exp_array[i,6], exp_array[i,7], exp_array[i,8], exp_array[i,9], spatial_data) OPEN = [OPEN; new_line] end end index_min_node = my_min_fn(OPEN, OPEN_COUNT, finish_position) if index_min_node != -1 from_node = Int.(OPEN[index_min_node, 2]) path_cost = OPEN[index_min_node, 8] offshore_distance = OPEN[index_min_node, 15] CLOSED_COUNT = CLOSED_COUNT + 1 CLOSED = [CLOSED; from_node] OPEN[index_min_node, 1] = 0 else NoPath = 0 end end i = size(CLOSED, 1) nodeval = CLOSED[i] i = 1 optimal_path = nodeval ac_dc = OPEN[OPEN[:, 2] .== nodeval, 12] ac_cab = OPEN[OPEN[:, 2] .== nodeval, 13] dc_cab = OPEN[OPEN[:, 2] .== nodeval, 14] i = i + 1 c_tot = 0 if nodeval == finish_position parent_node = Int.(OPEN[OPEN[:, 2] .== nodeval, 3][1]) c_tot = c_tot + OPEN[OPEN[:,2] .== nodeval, 11][1] while parent_node != start_position optimal_path = [optimal_path; parent_node] ac_dc = [ac_dc; OPEN[OPEN[:, 2] .== parent_node, 12][1]] ac_cab = [ac_cab; OPEN[OPEN[:, 2] .== parent_node, 13[1]]] dc_cab = [dc_cab; OPEN[OPEN[:, 2] .== parent_node, 14][1]] c_tot = c_tot + OPEN[OPEN[:, 2] .== parent_node, 11][1] parent_node = Int.(OPEN[OPEN[:, 2] .== parent_node, 3][1]) i = i + 1 end optimal_path = [optimal_path; start_position] end return c_tot, optimal_path, ac_dc, ac_cab, dc_cab end function determine_start_and_end_node(spatial_data_matrices, input_data) idx1 = findall(spatial_data_matrices["ohl"]["nodes"][:, 2] .== input_data["start_node"]["x"]) idx2 = findall(spatial_data_matrices["ohl"]["nodes"][:, 3] .== input_data["start_node"]["y"]) start_position = intersect(idx1, idx2) idx3 = findall(spatial_data_matrices["ohl"]["nodes"][:, 2] .== input_data["end_node"]["x"]) idx4 = findall(spatial_data_matrices["ohl"]["nodes"][:, 3] .== input_data["end_node"]["y"]) finish_position = intersect(idx3, idx4) sp = start_position[1] fp = finish_position[1] return sp, fp end function estimate_initial_distance(start_position, finish_position, spatial_data, average_weight) distance = sqrt.((spatial_data["nodes"][start_position, 2] - spatial_data["nodes"][finish_position, 2]).^2 + (spatial_data["nodes"][start_position, 3] - spatial_data["nodes"][finish_position, 3]).^2) * average_weight d = distance[1] return d end function my_insert_open(from_node, to_node, hn, gn, fn, wn, ac_dc, ac_cab, dc_cab, offshore_distance, spatial_data) new_row = zeros(1, 15) new_row[1,1] = 1 new_row[1,2] = Int.(from_node) new_row[1,3] = Int.(to_node) new_row[1,4] = spatial_data["nodes"][Int.(from_node) ,2] new_row[1,5] = spatial_data["nodes"][Int.(from_node) ,3] new_row[1,6] = spatial_data["nodes"][Int.(to_node) ,2] new_row[1,7] = spatial_data["nodes"][Int.(to_node) ,3] new_row[1,8] = hn new_row[1,9] = gn new_row[1,10] = fn new_row[1,11] = wn new_row[1,12] = ac_dc new_row[1,13] = ac_cab new_row[1,14] = dc_cab new_row[1,15] = offshore_distance return new_row end function my_expand_array(from_node, hn, start_node, finish_node, CLOSED, spatial_data, offshore_distance, input_data, average_weight, equipment_data) seg_index1 = findall(spatial_data["segments"][:, 2] .== from_node) seg_index2 = findall(spatial_data["segments"][:, 3] .== from_node) exp_array = Array{Float64, 2}(undef, 0, 9) for idx = 1:length(seg_index1) current_node = Int.(spatial_data["segments"][seg_index1[idx], 3]) if !any(CLOSED .== current_node) seg_index = seg_index1[idx] new_line = zeros(1, 9) new_line[1, 1] = current_node distance = sqrt((spatial_data["nodes"][from_node, 2] - spatial_data["nodes"][current_node, 2])^2 + (spatial_data["nodes"][from_node, 3] - spatial_data["nodes"][current_node, 3])^2) d_off = input_data["resolution_factor"] * distance * (1 - spatial_data["onshore_flag"][seg_index]) * (1 - spatial_data["onshore_nodes"][from_node]) * (1 - spatial_data["onshore_nodes"][current_node]) w_off = 1 if (offshore_distance + d_off) > equipment_data["ugc"]["offshore"]["maximum_distance"] w_off = 1e9 end new_line[1, 2] = hn + distance_w(from_node, current_node, spatial_data, seg_index, w_off) if d_off == 0 new_line[1, 9] = 0 else new_line[1, 9] = offshore_distance + d_off end od = distance_off(finish_node, current_node, spatial_data, seg_index, input_data) new_line[1, 3] = distance_est(finish_node, current_node, spatial_data, average_weight) new_line[1, 4] = new_line[1, 2] + new_line[1, 3] new_line[1, 5] = new_line[1, 2] - hn new_line[1, 6] = 0 #nw.ac_dc(seg_index) new_line[1, 7] = spatial_data["ohl_ugc_transition"][seg_index1[idx]] new_line[1, 8] = spatial_data["ohl_ugc_transition"][seg_index1[idx]] exp_array = [exp_array; new_line] end end for idx = 1:length(seg_index2) current_node = Int.(spatial_data["segments"][seg_index2[idx], 2]) if !any(CLOSED .== current_node) seg_index = seg_index2[idx] new_line = zeros(1, 9) new_line[1, 1] = current_node distance = sqrt((spatial_data["nodes"][from_node, 2] - spatial_data["nodes"][current_node, 2])^2 + (spatial_data["nodes"][from_node, 3] - spatial_data["nodes"][current_node, 3])^2) d_off = input_data["resolution_factor"] * distance * (1 - spatial_data["onshore_flag"][seg_index]) * (1 - spatial_data["onshore_nodes"][from_node]) * (1 - spatial_data["onshore_nodes"][current_node]) w_off = 1 if (offshore_distance + d_off ) > equipment_data["ugc"]["offshore"]["maximum_distance"] w_off = 1e9 end new_line[1, 2] = hn + distance_w(from_node, current_node, spatial_data, seg_index, w_off) if d_off == 0 new_line[1, 9] = 0 else new_line[1, 9] = offshore_distance + d_off end od = distance_off(finish_node, current_node, spatial_data, seg_index, input_data) new_line[1, 3] = distance_est(finish_node, current_node, spatial_data, average_weight) new_line[1, 4] = new_line[1, 2] + new_line[1, 3] new_line[1, 5] = new_line[1, 2] - hn new_line[1, 6] = 0 #nw.ac_dc(seg_index) new_line[1, 7] = spatial_data["ohl_ugc_transition"][seg_index2[idx]] new_line[1, 8] = spatial_data["ohl_ugc_transition"][seg_index2[idx]] exp_array = [exp_array; new_line] end end return exp_array end function distance_w(from_node, to_node, spatial_data, index, w_off) distance = sqrt((spatial_data["nodes"][from_node, 2] - spatial_data["nodes"][to_node, 2])^2 + (spatial_data["nodes"][from_node, 3] - spatial_data["nodes"][to_node, 3])^2) * spatial_data["segment_weights"][index] * w_off d = distance[1] return d end function distance_est(from_node, to_node, spatial_data, average_weight) distance = sqrt((spatial_data["nodes"][from_node, 2] - spatial_data["nodes"][to_node, 2])^2 + (spatial_data["nodes"][from_node, 3] - spatial_data["nodes"][to_node, 3])^2) * average_weight d = distance[1] return d end function distance_off(from_node, to_node, spatial_data, index, input_data) distance = sqrt((spatial_data["nodes"][from_node, 2] - spatial_data["nodes"][to_node, 2])^2 + (spatial_data["nodes"][from_node, 3] - spatial_data["nodes"][to_node, 3])^2) * (1-spatial_data["onshore_flag"][index]) * input_data["resolution_factor"] d = distance[1] return d end function my_min_fn(OPEN, OPEN_COUNT, finish_node) index = (1:OPEN_COUNT)' temp_array = [OPEN[OPEN[1:OPEN_COUNT, 1] .== 1, :] index[OPEN[1:OPEN_COUNT, 1] .== 1]] goal_index = findall(OPEN[:, 1] .== finish_node) if !isempty(goal_index) i_min = goal_index end if size(temp_array, 1) != 0 temp_min = Int.(findfirst(temp_array[:, 10] .== minimum(temp_array[:, 10]))) i_min = Int.(temp_array[temp_min[1], end]) else i_min = -1 end return i_min end
OptimalTransmissionRouting
https://github.com/Electa-Git/OptimalTransmissionRouting.jl.git
[ "BSD-3-Clause" ]
0.1.4
688e5028028e0dd8807efe6fff4a55a1a0832818
code
9445
function calculate_costs_and_losses(input_data; equipment = "ohl") equipment_ = join([input_data["technology"],"_",equipment]) if equipment_ == "ac_ohl" costs, equipment_details = ac_ohl_costs_and_losses(input_data) elseif equipment_ == "ac_ugc" costs, equipment_details = ac_ugc_costs_and_losses(input_data) elseif equipment_ == "dc_ohl" costs, equipment_details = dc_ohl_costs_and_losses(input_data) elseif equipment_ == "dc_ugc" costs, equipment_details = dc_ugc_costs_and_losses(input_data) end return costs, equipment_details end function ac_ohl_costs_and_losses(input_data) w = 2*pi*50 # frequency minimum_distance = sqrt((input_data["start_node"]["x"]-input_data["end_node"]["x"])^2 + (input_data["start_node"]["y"]-input_data["start_node"]["y"])^2) Avecorg=[16 25 50 70 95 120 150 170 185 210 230 240 265 300 340 380 435 450 490 550 560 680] A = Avecorg[end] # Start with highest cross-section C = -0.00003705 * input_data["voltages"]["ac_ohl"]^2 + 0.03257649 * input_data["voltages"]["ac_ohl"] + 5.965161265 # estimate capacitance in nF Imax = -0.00170712*A.^2 + 2.64505501*A + 97.70512024 # estimate maximum current Ic = w * (C*1e-9) * minimum_distance * (input_data["voltages"]["ac_ohl"] * 1e3) /sqrt(3) # Calculate capacitive current I = input_data["power_rating"] * 1e6 / (sqrt(3) * input_data["voltages"]["ac_ohl"] * 1e3) # Calculate transmission current n = ceil(I/(2*sqrt(Imax^2-(Ic/2)^2))) # Calculate minimum number of circuits nb = ceil(I/(n*sqrt(Imax^2-(Ic/2)^2))) # Calculate minumm number of bundles Imax1 = sqrt((I/(n*nb))^2+(Ic/2).^2) # Calculate actual current per conductor K1 = -0.00170712 K2 = 2.64505501 K3 = 97.70512024 - Imax1; A_new = min(679, real((1 / (2*K1) * (-K2 + sqrt(K2^2 - 4 * K1 * K3))))) Avec = Avecorg Aindex = A_new .< Avec if all(Aindex==0) A = Avecorg[end] else A = Avec[length(Avec) - sum(Aindex) + 1] end costs = Dict{String, Any}() costs["investment"] = n * ((60+0.4 * input_data["voltages"]["ac_ohl"] + 0.4 * A * nb^(1/4)) * 1e3) costs["installation"] = n * (500*1e3) * sqrt(input_data["voltages"]["ac_ohl"] / 400) equipment_details = Dict{String,Any}() equipment_details["cross_section"] = A equipment_details["circuits"] = n equipment_details["bundles"] = nb return costs, equipment_details end function ac_ugc_costs_and_losses(input_data) w = 2*pi*50 # frequency minimum_distance = 30; Avecorg_offshore = [70 95 120 150 185 240 300 400 500 630 800 1000 1200 1400] A_offshore = Avecorg_offshore[end] C_offshore = (-1.21*1e-7 * A_offshore^2 + 0.000286276 * A_offshore + 0.08212371) * 1.762251064 * input_data["voltages"]["ac_ugc"]^(-0.45531498) / 0.17 Imax_offshore = -5.7698e-4 * A_offshore^2 + 1.1793 * A_offshore + 212.33 Ic_max_offshore = sqrt(2) * Imax_offshore / 2 maximum_distance = Ic_max_offshore / (w * (C_offshore * 1e-6) * (input_data["voltages"]["ac_ugc"] * 1e3 )/ sqrt(3)) Ic_offshore = w * (C_offshore * 1e-6) * minimum_distance * (input_data["voltages"]["ac_ugc"] * 1e3) / sqrt(3) I_offshore = input_data["power_rating"] * 1e6 /(sqrt(3) * input_data["voltages"]["ac_ugc"] * 1e3) n_c_offshore = ceil(I_offshore / (sqrt(Imax_offshore^2-(Ic_offshore/2)^2))) Imax1_offshore = sqrt((I_offshore/n_c_offshore)^2+(Ic_offshore/2).^2) K1=5.7698e-4 K2=1.1793; K3=212.33-Imax1_offshore; Anew_offshore = min(999,real((1/(2*K1).*(-K2+sqrt(K2.^2-4*K1.*K3))))) Avec_offshore = Avecorg_offshore Aindex = Anew_offshore .< Avec_offshore if all(Aindex==0) A_offshore = Avecorg_offshore[end] else A_offshore = Avec_offshore[length(Avec_offshore)-sum(Aindex)+1] end Q_offshore = sqrt(3) * Ic_offshore * input_data["voltages"]["ac_ugc"] / 1e3 K1=5.8038; K2=0.044525; K3=0.0072; costs = Dict{String, Any}() costs["offshore"] = Dict{String, Any}() costs["offshore"]["investment"] = 1.3e6 * n_c_offshore * (K1+K2*exp(K3*(sqrt(3) * input_data["voltages"]["ac_ugc"] * Imax1_offshore)/1e6))/8.98+ n_c_offshore * Q_offshore *7e6 /(130*minimum_distance) costs["offshore"]["installation"] = 7e5 * (input_data["voltages"]["ac_ugc"]/400)^(1/2)*(n_c_offshore)^0.9 equipment_details = Dict{String, Any}() equipment_details["offshore"] = Dict{String, Any}() equipment_details["offshore"]["cross_section"] = A_offshore equipment_details["offshore"]["circuits"] = n_c_offshore equipment_details["offshore"]["maximum_distance"] = maximum_distance equipment_details["offshore"]["circuits"] = n_c_offshore ## ONSHORE CABLES Avecorg = [300 400 500 630 800 1000 1200 1400 1600 2000 2500] A = Avecorg[end] C = 0.2 Imax = 26.938 * A^(0.521); Ic= w * (C * 1e-6)*minimum_distance * (input_data["voltages"]["ac_ugc"] * 1e3) / sqrt(3) I = input_data["power_rating"] * 1e6 / (sqrt(3) * input_data["voltages"]["ac_ugc"] * 1e3) n_c = ceil(I / (sqrt(Imax^2 - (Ic/2)^2))) Imax1 = sqrt((I / n_c)^2 + (Ic/2).^2) Anew = (Imax1 / 26.938)^(1/0.521) Avec = Avecorg Aindex = Anew .< Avec if all(Aindex == 0) A = Avecorg[end] else A = Avec[length(Avec)-sum(Aindex)+1] end Q = sqrt(3) * Ic * input_data["voltages"]["ac_ugc"] / 1e3 costs["onshore"] = Dict{String, Any}() costs["onshore"]["investment"] = 1e6 * ((input_data["voltages"]["ac_ugc"] / 400)^2+ 0.25 * A/2000)*n_c + n_c * Q * 3e6 /(130*minimum_distance) + 0.25e6*(input_data["voltages"]["ac_ugc"]/400) costs["onshore"]["installation"] = 1e6 * (input_data["voltages"]["ac_ugc"] / 400)^(1/2)*(n_c)^0.9 costs["onshore"]["transition"] = 3 * n_c * 1e6 * (input_data["voltages"]["ac_ugc"]/400)^(1/2) equipment_details["onshore"] = Dict{String, Any}() equipment_details["onshore"]["cross_section"] = A equipment_details["onshore"]["circuits"] = n_c return costs, equipment_details end function dc_ohl_costs_and_losses(input_data) Avecorg = [16 25 50 70 95 120 150 170 185 210 230 240 265 300 340 380 435 450 490 550 560 680] A = maximum(Avecorg) Imax=(-0.00170712*A^2 + 2.64505501 * A +97.70512024) * 1.2 I = input_data["power_rating"] * 1e6 / (2 * input_data["voltages"]["dc_ohl"] * 1e3) n = ceil(I/(2*Imax)) nb = ceil(I/(n*Imax)) Imax1 = I / (n * nb) K1 = -0.00170712 * 1.2 K2 = 2.64505501 * 1.2 K3 = 97.70512024 * 1.2 - Imax1 Anew = min(679, real((1/ (2 * K1) * (-K2 + sqrt(K2^2-4 * K1 * K3))))) Avec = Avecorg; Aindex = Anew .< Avec if all(Aindex == 0) A = Avecorg[end] else A = Avec[length(Avec)-sum(Aindex) + 1] end costs = Dict{String, Any}() costs["investment"] = n * (60+0.4 * input_data["voltages"]["dc_ohl"] + 0.4 * A * nb^(1/4)) * 1e3 * 2/3 costs["installation"] = n * 2/3 * (500*1e3) * sqrt(input_data["voltages"]["dc_ohl"] / 320) costs["converter"] = (input_data["power_rating"] /1000) * (0.8 + 0.2 * sqrt(input_data["voltages"]["dc_ohl"]/320)) * 100e6 equipment_details = Dict{String,Any}() equipment_details["cross_section"] = A equipment_details["circuits"] = n equipment_details["bundles"] = nb return costs, equipment_details end function dc_ugc_costs_and_losses(input_data) Avecorg = [95 120 150 185 240 300 400 500 630 800 1000 1200 1400 1600 1800 2000 2200 2400 2600 2800 3000] A = maximum(Avecorg) Imax = 25.22218157 * A^(0.57255569) I = input_data["power_rating"] * 1e6/(2*input_data["voltages"]["dc_ugc"] *1e3) n = ceil(I/Imax) Imax1 = I /n Anew = (Imax1/25.22218157)^(1/0.57255569) Avec = Avecorg Aindex = Anew .< Avec if all(Aindex == 0) A = 3000 else A = Avec[length(Avec)-sum(Aindex)+1] end costs = Dict{String, Any}() costs["offshore"] = Dict{String, Any}() costs["onshore"] = Dict{String, Any}() costs["onshore"]["converter"] = (input_data["power_rating"] /1000) * (0.8 + 0.2 * sqrt(input_data["voltages"]["dc_ugc"] / 320)) * 100e6 costs["onshore"]["investment"] = n * ((0.0022 * input_data["voltages"]["dc_ugc"] -0.4338) * 1e6 + (0.4906 * input_data["voltages"]["dc_ugc"]^(-0.652)) * input_data["voltages"]["dc_ugc"] * Imax1 * 1e3)/8.94448 costs["onshore"]["installation"] = n^0.9 * 700000 * (input_data["voltages"]["dc_ugc"]/320)^(1/2) costs["onshore"]["transition"] = 2 * n * 1e6 * (input_data["voltages"]["dc_ugc"]/320)^(1/2) costs["offshore"]["converter"] = (input_data["power_rating"] /1000) * (0.8 + 0.2 * sqrt(input_data["voltages"]["dc_ugc"]/320)) * 100e6 costs["offshore"]["investment"] = n * ((0.0022 * input_data["voltages"]["dc_ugc"] - 0.4338) * 1e6 + (0.4906 * input_data["voltages"]["dc_ugc"]^(-0.652)) * input_data["voltages"]["dc_ugc"] * Imax1*1e3)/8.94448 costs["offshore"]["installation"] = n^0.9 * 1e6 * (input_data["voltages"]["dc_ugc"]/320)^(1/2) equipment_details = Dict{String, Any}() equipment_details["onshore"] = Dict{String, Any}() equipment_details["onshore"]["cross_section"] = A equipment_details["onshore"]["circuits"] = n equipment_details["offshore"] = Dict{String, Any}() equipment_details["offshore"]["cross_section"] = A equipment_details["offshore"]["circuits"] = n equipment_details["offshore"]["maximum_distance"] = 5000 # dummy number return costs, equipment_details end
OptimalTransmissionRouting
https://github.com/Electa-Git/OptimalTransmissionRouting.jl.git
[ "BSD-3-Clause" ]
0.1.4
688e5028028e0dd8807efe6fff4a55a1a0832818
code
14768
function define_weights_voltages(strategy) # Create dictionary of spatial weights for different equipment types / areas spatial_weights = Dict{String, Any}() # Weights for AC OHL spatial_weights["ac_ohl"] = Dict{String, Any}() spatial_weights["ac_ohl"]["nature"] = 2.5 spatial_weights["ac_ohl"]["urban"] = 40 spatial_weights["ac_ohl"]["mountain"] = 10 spatial_weights["ac_ohl"]["sea"] = 40 spatial_weights["ac_ohl"]["Natura2000"] = 40 spatial_weights["ac_ohl"]["grid"] = 1 spatial_weights["ac_ohl"]["agricultural"] = 1 spatial_weights["ac_ohl"]["roads"] = 1 spatial_weights["ac_ohl"]["railroads"] = 1 if strategy == "OHL_on_existing_corridors" spatial_weights["ac_ohl"]["agricultural"] = 40 spatial_weights["ac_ohl"]["nature"] = 40 spatial_weights["ac_ohl"]["mountain"] = 40 end if strategy == "cables_only" spatial_weights["ac_ohl"]["agricultural"] = 40 spatial_weights["ac_ohl"]["nature"] = 40 spatial_weights["ac_ohl"]["mountain"] = 40 spatial_weights["ac_ohl"]["grid"] = 40 spatial_weights["ac_ohl"]["roads"] = 40 spatial_weights["ac_ohl"]["railroads"] = 40 end # Weights for AC UGC spatial_weights["ac_ugc"] = Dict{String, Any}() spatial_weights["ac_ugc"]["nature"] = 1.5 spatial_weights["ac_ugc"]["urban"] = 2.5 spatial_weights["ac_ugc"]["mountain"] = 4.5 spatial_weights["ac_ugc"]["sea"] = 0.75 spatial_weights["ac_ugc"]["Natura2000"] = 40 spatial_weights["ac_ugc"]["grid"] = 1 spatial_weights["ac_ugc"]["agricultural"] = 1 spatial_weights["ac_ugc"]["roads"] = 1 spatial_weights["ac_ugc"]["railroads"] = 1 # Weights for DC OHL spatial_weights["dc_ohl"] = Dict{String, Any}() spatial_weights["dc_ohl"]["nature"] = 2.5 spatial_weights["dc_ohl"]["urban"] = 40 spatial_weights["dc_ohl"]["mountain"] = 10 spatial_weights["dc_ohl"]["sea"] = 40 spatial_weights["dc_ohl"]["Natura2000"] = 10 spatial_weights["dc_ohl"]["grid"] = 1 spatial_weights["dc_ohl"]["agricultural"] = 1 spatial_weights["dc_ohl"]["roads"] = 1 spatial_weights["dc_ohl"]["railroads"] = 1 if strategy == "OHL_on_existing_corridors" spatial_weights["dc_ohl"]["agricultural"] = 40 spatial_weights["dc_ohl"]["nature"] = 40 spatial_weights["dc_ohl"]["mountain"] = 40 end if strategy == "cables_only" spatial_weights["dc_ohl"]["agricultural"] = 40 spatial_weights["dc_ohl"]["nature"] = 40 spatial_weights["dc_ohl"]["mountain"] = 40 spatial_weights["dc_ohl"]["grid"] = 40 spatial_weights["dc_ohl"]["roads"] = 40 spatial_weights["dc_ohl"]["railroads"] = 40 end # Weights for AC UGC spatial_weights["dc_ugc"] = Dict{String, Any}() spatial_weights["dc_ugc"]["nature"] = 1.5 spatial_weights["dc_ugc"]["urban"] = 2.5 spatial_weights["dc_ugc"]["mountain"] = 4.5 spatial_weights["dc_ugc"]["sea"] = 0.75 spatial_weights["dc_ugc"]["Natura2000"] = 10 spatial_weights["dc_ugc"]["grid"] = 1 spatial_weights["dc_ugc"]["agricultural"] = 1 spatial_weights["dc_ugc"]["roads"] = 1 spatial_weights["dc_ugc"]["railroads"] = 1 # Define transmission voltage levels voltages = Dict{String, Any}() voltages["ac_ohl"] = 400 voltages["dc_ohl"] = 400 voltages["ac_ugc"] = 400 voltages["dc_ugc"] = 320 #Minimum resolution resolution = Dict{String, Any}() resolution["delta_min"] = 4 resolution["weight_min"] = Dict{String, Any}() resolution["weight_min"]["ac_ohl"] = 1 resolution["weight_min"]["ac_ugc"] = 1 resolution["weight_min"]["dc_ohl"] = 1 resolution["weight_min"]["dc_ugc"] = 1 impedances = Dict{String,Any}() impedances["ac"] = Dict{String,Any}() impedances["ac"]["ohl"] = Dict{String,Any}() impedances["ac"]["ohl"]["16"] = Dict{String,Any}() impedances["ac"]["ohl"]["16"]["r"] = 1.874 impedances["ac"]["ohl"]["16"]["x"] = 0.347 impedances["ac"]["ohl"]["16"]["c"] = 13.06 impedances["ac"]["ohl"]["25"] = Dict{String,Any}() impedances["ac"]["ohl"]["25"]["r"] = 1.118 impedances["ac"]["ohl"]["25"]["x"] = 0.334 impedances["ac"]["ohl"]["25"]["c"] = 13.06 impedances["ac"]["ohl"]["50"] = Dict{String,Any}() impedances["ac"]["ohl"]["50"]["r"] = 0.574 impedances["ac"]["ohl"]["50"]["x"] = 0.312 impedances["ac"]["ohl"]["50"]["c"] = 13.06 impedances["ac"]["ohl"]["70"] = Dict{String,Any}() impedances["ac"]["ohl"]["70"]["r"] = 0.404 impedances["ac"]["ohl"]["70"]["x"] = 0.302 impedances["ac"]["ohl"]["70"]["c"] = 13.06 impedances["ac"]["ohl"]["95"] = Dict{String,Any}() impedances["ac"]["ohl"]["95"]["r"] = 0.300 impedances["ac"]["ohl"]["95"]["x"] = 0.291 impedances["ac"]["ohl"]["95"]["c"] = 13.06 impedances["ac"]["ohl"]["120"] = Dict{String,Any}() impedances["ac"]["ohl"]["120"]["r"] = 0.252 impedances["ac"]["ohl"]["120"]["x"] = 0.284 impedances["ac"]["ohl"]["120"]["c"] = 13.06 impedances["ac"]["ohl"]["150"] = Dict{String,Any}() impedances["ac"]["ohl"]["150"]["r"] = 0.190 impedances["ac"]["ohl"]["150"]["x"] = 0.279 impedances["ac"]["ohl"]["150"]["c"] = 13.06 impedances["ac"]["ohl"]["170"] = Dict{String,Any}() impedances["ac"]["ohl"]["170"]["r"] = 0.165 impedances["ac"]["ohl"]["170"]["x"] = 0.276 impedances["ac"]["ohl"]["170"]["c"] = 13.06 impedances["ac"]["ohl"]["185"] = Dict{String,Any}() impedances["ac"]["ohl"]["185"]["r"] = 0.154 impedances["ac"]["ohl"]["185"]["x"] = 0.274 impedances["ac"]["ohl"]["185"]["c"] = 13.06 impedances["ac"]["ohl"]["210"] = Dict{String,Any}() impedances["ac"]["ohl"]["210"]["r"] = 0.133 impedances["ac"]["ohl"]["210"]["x"] = 0.270 impedances["ac"]["ohl"]["210"]["c"] = 13.06 impedances["ac"]["ohl"]["230"] = Dict{String,Any}() impedances["ac"]["ohl"]["230"]["r"] = 0.122 impedances["ac"]["ohl"]["230"]["x"] = 0.268 impedances["ac"]["ohl"]["230"]["c"] = 13.06 impedances["ac"]["ohl"]["240"] = Dict{String,Any}() impedances["ac"]["ohl"]["240"]["r"] = 0.116 impedances["ac"]["ohl"]["240"]["x"] = 0.267 impedances["ac"]["ohl"]["240"]["c"] = 13.06 impedances["ac"]["ohl"]["265"] = Dict{String,Any}() impedances["ac"]["ohl"]["265"]["r"] = 0.107 impedances["ac"]["ohl"]["265"]["x"] = 0.264 impedances["ac"]["ohl"]["265"]["c"] = 13.06 impedances["ac"]["ohl"]["300"] = Dict{String,Any}() impedances["ac"]["ohl"]["300"]["r"] = 0.093 impedances["ac"]["ohl"]["300"]["x"] = 0.261 impedances["ac"]["ohl"]["300"]["c"] = 13.06 impedances["ac"]["ohl"]["340"] = Dict{String,Any}() impedances["ac"]["ohl"]["340"]["r"] = 0.083 impedances["ac"]["ohl"]["340"]["x"] = 0.258 impedances["ac"]["ohl"]["340"]["c"] = 13.06 impedances["ac"]["ohl"]["380"] = Dict{String,Any}() impedances["ac"]["ohl"]["380"]["r"] = 0.074 impedances["ac"]["ohl"]["380"]["x"] = 0.255 impedances["ac"]["ohl"]["380"]["c"] = 13.06 impedances["ac"]["ohl"]["435"] = Dict{String,Any}() impedances["ac"]["ohl"]["435"]["r"] = 0.065 impedances["ac"]["ohl"]["435"]["x"] = 0.252 impedances["ac"]["ohl"]["435"]["c"] = 13.06 impedances["ac"]["ohl"]["450"] = Dict{String,Any}() impedances["ac"]["ohl"]["450"]["r"] = 0.063 impedances["ac"]["ohl"]["450"]["x"] = 0.251 impedances["ac"]["ohl"]["450"]["c"] = 13.06 impedances["ac"]["ohl"]["490"] = Dict{String,Any}() impedances["ac"]["ohl"]["490"]["r"] = 0.058 impedances["ac"]["ohl"]["490"]["x"] = 0.249 impedances["ac"]["ohl"]["490"]["c"] = 13.06 impedances["ac"]["ohl"]["550"] = Dict{String,Any}() impedances["ac"]["ohl"]["550"]["r"] = 0.051 impedances["ac"]["ohl"]["550"]["x"] = 0.246 impedances["ac"]["ohl"]["550"]["c"] = 13.06 impedances["ac"]["ohl"]["560"] = Dict{String,Any}() impedances["ac"]["ohl"]["560"]["r"] = 0.050 impedances["ac"]["ohl"]["560"]["x"] = 0.26 impedances["ac"]["ohl"]["560"]["c"] = 13.06 impedances["ac"]["ohl"]["680"] = Dict{String,Any}() impedances["ac"]["ohl"]["680"]["r"] = 0.042 impedances["ac"]["ohl"]["680"]["x"] = 0.241 impedances["ac"]["ohl"]["680"]["c"] = 13.06 impedances["ac"]["ugc"] = Dict{String,Any}() impedances["ac"]["ugc"]["300"] = Dict{String,Any}() impedances["ac"]["ugc"]["300"]["r"] = 0.069 impedances["ac"]["ugc"]["300"]["x"] = 0.110 impedances["ac"]["ugc"]["300"]["c"] = 375 impedances["ac"]["ugc"]["400"] = Dict{String,Any}() impedances["ac"]["ugc"]["400"]["r"] = 0.057 impedances["ac"]["ugc"]["400"]["x"] = 0.130 impedances["ac"]["ugc"]["400"]["c"] = 170 impedances["ac"]["ugc"]["500"] = Dict{String,Any}() impedances["ac"]["ugc"]["500"]["r"] = 0.047 impedances["ac"]["ugc"]["500"]["x"] = 0.125 impedances["ac"]["ugc"]["500"]["c"] = 180 impedances["ac"]["ugc"]["630"] = Dict{String,Any}() impedances["ac"]["ugc"]["630"]["r"] = 0.038 impedances["ac"]["ugc"]["630"]["x"] = 0.122 impedances["ac"]["ugc"]["630"]["c"] = 200 impedances["ac"]["ugc"]["800"] = Dict{String,Any}() impedances["ac"]["ugc"]["800"]["r"] = 0.027 impedances["ac"]["ugc"]["800"]["x"] = 0.102 impedances["ac"]["ugc"]["800"]["c"] = 402 impedances["ac"]["ugc"]["1200"] = Dict{String,Any}() impedances["ac"]["ugc"]["1200"]["r"] = 0.0151 impedances["ac"]["ugc"]["1200"]["x"] = 0.116 impedances["ac"]["ugc"]["1200"]["c"] = 210 impedances["ac"]["ugc"]["1600"] = Dict{String,Any}() impedances["ac"]["ugc"]["1600"]["r"] = 0.0113 impedances["ac"]["ugc"]["1600"]["x"] = 0.111 impedances["ac"]["ugc"]["1600"]["c"] = 231 impedances["ac"]["ugc"]["2000"] = Dict{String,Any}() impedances["ac"]["ugc"]["2000"]["r"] = 0.010 impedances["ac"]["ugc"]["2000"]["x"] = 0.1099 impedances["ac"]["ugc"]["2000"]["c"] = 240 impedances["ac"]["ugc"]["2500"] = Dict{String,Any}() impedances["ac"]["ugc"]["2500"]["r"] = 0.0095 impedances["ac"]["ugc"]["2500"]["x"] = 0.098 impedances["ac"]["ugc"]["2500"]["c"] = 260 impedances["dc"] = Dict{String,Any}() impedances["dc"]["ohl"] = Dict{String,Any}() for (cross_section, cs) in impedances["ac"]["ohl"] impedances["dc"]["ohl"][cross_section] = Dict{String,Any}() impedances["dc"]["ohl"][cross_section]["r"] = cs["r"] impedances["dc"]["ohl"][cross_section]["x"] = 0 impedances["dc"]["ohl"][cross_section]["c"] = 0 end impedances["dc"]["ugc"] = Dict{String,Any}() impedances["dc"]["ugc"]["95"] = Dict{String, Any}() impedances["dc"]["ugc"]["95"]["r"] = 0.247 impedances["dc"]["ugc"]["95"]["x"] = 0 impedances["dc"]["ugc"]["95"]["c"] = 0 impedances["dc"]["ugc"]["120"] = Dict{String, Any}() impedances["dc"]["ugc"]["120"]["r"] = 0.196 impedances["dc"]["ugc"]["120"]["x"] = 0 impedances["dc"]["ugc"]["120"]["c"] = 0 impedances["dc"]["ugc"]["150"] = Dict{String, Any}() impedances["dc"]["ugc"]["150"]["r"] = 0.16 impedances["dc"]["ugc"]["150"]["x"] = 0 impedances["dc"]["ugc"]["150"]["c"] = 0 impedances["dc"]["ugc"]["185"] = Dict{String, Any}() impedances["dc"]["ugc"]["185"]["r"] = 0.128 impedances["dc"]["ugc"]["185"]["x"] = 0 impedances["dc"]["ugc"]["185"]["c"] = 0 impedances["dc"]["ugc"]["240"] = Dict{String, Any}() impedances["dc"]["ugc"]["240"]["r"] = 0.097 impedances["dc"]["ugc"]["240"]["x"] = 0 impedances["dc"]["ugc"]["240"]["c"] = 0 impedances["dc"]["ugc"]["300"] = Dict{String, Any}() impedances["dc"]["ugc"]["300"]["r"] = 0.08 impedances["dc"]["ugc"]["300"]["x"] = 0 impedances["dc"]["ugc"]["300"]["c"] = 0 impedances["dc"]["ugc"]["400"] = Dict{String, Any}() impedances["dc"]["ugc"]["400"]["r"] = 0.062 impedances["dc"]["ugc"]["400"]["x"] = 0 impedances["dc"]["ugc"]["400"]["c"] = 0 impedances["dc"]["ugc"]["500"] = Dict{String, Any}() impedances["dc"]["ugc"]["500"]["r"] = 0.0508 impedances["dc"]["ugc"]["500"]["x"] = 0 impedances["dc"]["ugc"]["500"]["c"] = 0 impedances["dc"]["ugc"]["630"] = Dict{String, Any}() impedances["dc"]["ugc"]["630"]["r"] = 0.039 impedances["dc"]["ugc"]["630"]["x"] = 0 impedances["dc"]["ugc"]["630"]["c"] = 0 impedances["dc"]["ugc"]["800"] = Dict{String, Any}() impedances["dc"]["ugc"]["800"]["r"] = 0.032 impedances["dc"]["ugc"]["800"]["x"] = 0 impedances["dc"]["ugc"]["800"]["c"] = 0 impedances["dc"]["ugc"]["1000"] = Dict{String, Any}() impedances["dc"]["ugc"]["1000"]["r"] = 0.024 impedances["dc"]["ugc"]["1000"]["x"] = 0 impedances["dc"]["ugc"]["1000"]["c"] = 0 impedances["dc"]["ugc"]["1200"] = Dict{String, Any}() impedances["dc"]["ugc"]["1200"]["r"] = 0.021 impedances["dc"]["ugc"]["1200"]["x"] = 0 impedances["dc"]["ugc"]["1200"]["c"] = 0 impedances["dc"]["ugc"]["1400"] = Dict{String, Any}() impedances["dc"]["ugc"]["1400"]["r"] = 0.019 impedances["dc"]["ugc"]["1400"]["x"] = 0 impedances["dc"]["ugc"]["1400"]["c"] = 0 impedances["dc"]["ugc"]["1600"] = Dict{String, Any}() impedances["dc"]["ugc"]["1600"]["r"] = 0.017 impedances["dc"]["ugc"]["1600"]["x"] = 0 impedances["dc"]["ugc"]["1600"]["c"] = 0 impedances["dc"]["ugc"]["1800"] = Dict{String, Any}() impedances["dc"]["ugc"]["1800"]["r"] = 0.0155 impedances["dc"]["ugc"]["1800"]["x"] = 0 impedances["dc"]["ugc"]["1800"]["c"] = 0 impedances["dc"]["ugc"]["2000"] = Dict{String, Any}() impedances["dc"]["ugc"]["2000"]["r"] = 0.014 impedances["dc"]["ugc"]["2000"]["x"] = 0 impedances["dc"]["ugc"]["2000"]["c"] = 0 impedances["dc"]["ugc"]["2200"] = Dict{String, Any}() impedances["dc"]["ugc"]["2200"]["r"] = 0.013 impedances["dc"]["ugc"]["2200"]["x"] = 0 impedances["dc"]["ugc"]["2200"]["c"] = 0 impedances["dc"]["ugc"]["2400"] = Dict{String, Any}() impedances["dc"]["ugc"]["2400"]["r"] = 0.012 impedances["dc"]["ugc"]["2400"]["x"] = 0 impedances["dc"]["ugc"]["2400"]["c"] = 0 impedances["dc"]["ugc"]["2600"] = Dict{String, Any}() impedances["dc"]["ugc"]["2600"]["r"] = 0.010 impedances["dc"]["ugc"]["2600"]["x"] = 0 impedances["dc"]["ugc"]["2600"]["c"] = 0 impedances["dc"]["ugc"]["2800"] = Dict{String, Any}() impedances["dc"]["ugc"]["2800"]["r"] = 0.09 impedances["dc"]["ugc"]["2800"]["x"] = 0 impedances["dc"]["ugc"]["2800"]["c"] = 0 impedances["dc"]["ugc"]["3000"] = Dict{String, Any}() impedances["dc"]["ugc"]["3000"]["r"] = 0.075 impedances["dc"]["ugc"]["3000"]["x"] = 0 impedances["dc"]["ugc"]["3000"]["c"] = 0 return spatial_weights, voltages, resolution, impedances end
OptimalTransmissionRouting
https://github.com/Electa-Git/OptimalTransmissionRouting.jl.git
[ "BSD-3-Clause" ]
0.1.4
688e5028028e0dd8807efe6fff4a55a1a0832818
code
5137
function convert_image_files_to_weights(bus1, bus2) # create dictionary with rbg rgb_values rgb_values = Dict{String, Any}() boundaries = Dict{String, Any}() nodes_lp = Dict{String, Any}() plot_dictionary = Dict{String, Any}() #To Do add rnage based on input location img_ag = Images.load("../src/spatial_image_files/clc_agricultural.tif") img_overlay = zeros(size(img_ag)) rgb_values, img_overlay = convert2integer(img_ag, rgb_values, "agricultural", 1, img_overlay) img_sea = Images.load("../src/spatial_image_files/sea.tif") rgb_values, img_overlay = convert2integer(img_sea, rgb_values, "sea", 2, img_overlay) img_grid = Images.load("../src/spatial_image_files/grid_225kv_400kv.tif") rgb_values, img_overlay = convert2integer(img_grid, rgb_values, "grid", 3, img_overlay) img_roads = Images.load("../src/spatial_image_files/roads.tif") rgb_values, img_overlay = convert2integer(img_roads, rgb_values, "roads", 3, img_overlay) img_railroads = Images.load("../src/spatial_image_files/railroads.tif") rgb_values, img_overlay = convert2integer(img_railroads, rgb_values, "railroads", 3, img_overlay) img_nature = Images.load("../src/spatial_image_files/clc_natural.tif") rgb_values, img_overlay = convert2integer(img_nature, rgb_values, "nature", 4, img_overlay) img_mountains = Images.load("../src/spatial_image_files/clc_mountains.tif") rgb_values, img_overlay = convert2integer(img_mountains, rgb_values, "mountain", 5, img_overlay) img_urban = Images.load("../src/spatial_image_files/clc_urban.tif") rgb_values, img_overlay = convert2integer(img_urban, rgb_values, "urban", 6, img_overlay) img_natura2000 = Images.load("../src/spatial_image_files/Natura2000.tif") rgb_values, img_overlay = convert2integer(img_natura2000, rgb_values, "Natura2000", 7, img_overlay) X1,Y1 = convert_latlon_to_etrs89(bus1["longitude"], bus1["latitude"]) X2,Y2 = convert_latlon_to_etrs89(bus2["longitude"], bus2["latitude"]) # http://www.eea.europa.eu/data-and-maps/data/corine-land-cover-2006-raster-2 x0=1500000; xmax=7400000; y0=900000; ymax=5500000; resolution=2500; # Calculate the positions pof the nodes xpos=round.([(X1-x0),(X2-x0)] / resolution) ypos=round.([(ymax-Y1),(ymax-Y2)] / resolution) # Determine range: Euclidian distance +/- 30% d = round(0.3 * sqrt((xpos[1] - xpos[1])^2 + (ypos[1] - ypos[2])^2)) x_min = min(xpos[1], xpos[2]) - d x_max = max(xpos[1], xpos[2]) + d y_min = min(ypos[1], ypos[2]) - d y_max = max(ypos[1], ypos[2]) + d boundaries["xmin"] = x_min boundaries["xmax"] = x_max boundaries["ymin"] = y_min boundaries["ymax"] = y_max xpos_plot=round.([(X1-x0); (X2-x0)]/resolution .- x_max) #range(1,1); ypos_plot=round.([(ymax-Y1); (ymax-Y2)]/resolution .- y_min) #- range(2,1); nodes_lp["x1"] = xpos[1] nodes_lp["x2"] = xpos[2] nodes_lp["y1"] = ypos[1] nodes_lp["y2"] = ypos[2] plot_dictionary["overlay_image"] = img_overlay plot_dictionary["x_position"] = xpos plot_dictionary["y_position"] = ypos return rgb_values, nodes_lp, boundaries, plot_dictionary end function convert2integer(image, rgb_values, imagename, factor, img_overlay) rw = Images.rawview(Images.channelview(image)) bitarray = (rw .!== 0x00000000) rgb_values[imagename] = ones(size(bitarray)) .* bitarray img = findall(x->x==1, rgb_values[imagename]) for idx = 1:length(img) img_overlay[img[idx]] = max(factor, img_overlay[img[idx]]) end return rgb_values, img_overlay end function convert_latlon_to_etrs89(longitude, latitude) # Coordinate transformation based on IOGP Geomatics # Guidance Note Number 7, part 2 # Coordinate Conversions and Transformations including Formulas # Section 3.4.2 Lambert Azimuthal Equal Area (EPSG Dataset coordinate operation method code 9820) # https://www.iogp.org/bookstore/product/coordinate-conversions-and-transformation-including-formulas/ # fixed parameters a = 6378137.0 e = 0.081819191 phi0 = 0.907571211 # rad = 52 degree North lambda0 = 0.174532925 # rad = 10 degree East FE = 4321000 # False easting in m FN = 3210000 # False nortinh in m phi = latitude * pi / 180 lambda = longitude * pi / 180 q = (1 - e^2) * ((sin(phi) / (1 - e^2 * sin(phi)^2)) - ((1 / (2 * e)) * log((1 - e * sin(phi)) / (1 + e * sin(phi))))) q0 = (1 - e^2) * ((sin(phi0) / (1 - e^2 * sin(phi0)^2)) - ((1 / (2 * e)) * log((1 - e * sin(phi0)) / (1 + e * sin(phi0))))) qp = (1 - e^2) * ((1 / (1 - e^2)) - ((1 / (2 * e) * log((1 - e) / (1 + e))))) Rq = a * (qp / 2)^0.5 beta = asin(q / qp) beta0 = asin(q0 / qp) B = Rq * (2 / (1+ sin(beta0) * sin(beta) + (cos(beta0) * cos(beta) * cos(lambda - lambda0))))^0.5 D = a * (cos(phi0) / (1 - e^2 * sin(phi0)^2)^0.5) / (Rq * cos(beta0)) E = FE + (B*D) * (cos(beta) * sin(lambda - lambda0)) N = FN + (B/D) * (cos(beta0) * sin(beta) - (sin(beta0) * cos(beta) * cos(lambda - lambda0))) return E, N end
OptimalTransmissionRouting
https://github.com/Electa-Git/OptimalTransmissionRouting.jl.git
[ "BSD-3-Clause" ]
0.1.4
688e5028028e0dd8807efe6fff4a55a1a0832818
code
3345
function determine_impedance_parameters(input_data, spatial_data, spatial_data_matrices, optimal_path, equipment_data) r = 0 x = 0 bc = 0 r_pu = 0 x_pu = 0 bc_pu = 0 km = 0 km_ohl = 0 km_ugc = 0 for idx = 1 : size(optimal_path, 1) - 1 ohl_cable = ohl_or_cable(spatial_data, spatial_data_matrices, optimal_path[idx], optimal_path[idx + 1]) r_, x_, bc_, r_pu_, x_pu_, bc_pu_ = get_impedance_data(equipment_data, ohl_cable, input_data) km_ = get_segment_distance(spatial_data, spatial_data_matrices, optimal_path[idx], optimal_path[idx + 1]) km = km + km_ if ohl_cable == "ohl" km_ohl = km_ohl + km_ else km_ugc = km_ugc + km_ end r = r + (r_ * km_) r_pu = r_pu + (r_pu_ * km_) x = x + (x_ * km_) x_pu = x_pu +(x_pu_ * km_) bc = bc + (bc_ * km_) bc_pu = bc_pu + (bc_pu_ * km_) end route_impedance = Dict{String, Any}() route_length = Dict{String, Any}() route_length["total_length"] = km route_length["ohl_length"] = km_ohl route_length["ugc_length"] = km_ugc route_impedance["r"] = r route_impedance["x"] = x route_impedance["bc"] = bc route_impedance["r_pu"] = r_pu route_impedance["x_pu"] = x_pu route_impedance["bc_pu"] = bc_pu return route_impedance, route_length end function get_impedance_data(equipment_data::Dict, ohl_cable::String, input_data::Dict) technology = input_data["technology"] cross_section = equipment_data[ohl_cable]["onshore"]["cross_section"] circuits = equipment_data[ohl_cable]["onshore"]["circuits"] if ohl_cable == "ohl" bundles = input_data[ohl_cable]["onshore"]["bundles"] else bundles = 1 end r = input_data["impedances"][technology][ohl_cable]["$cross_section"]["r"] / (bundles * circuits) x = input_data["impedances"][technology][ohl_cable]["$cross_section"]["x"] / (bundles * circuits) bc = input_data["impedances"][technology][ohl_cable]["$cross_section"]["c"] * circuits * 10e-9 * 2 * pi * 50 v_str = join([technology, "_", ohl_cable]) voltage = input_data["voltages"][v_str] Zbase = voltage^2 / 100 r_pu = r / Zbase x_pu = x / Zbase bc_pu = bc * Zbase return r, x, bc, r_pu, x_pu, bc_pu end function get_segment_distance(spatial_data::Dict, spatial_data_matrices::Dict, node_id1::Int, node_id2::Int) index_s1 = findall(node_id1 .== spatial_data["segments"][:, 2]) index_s2 = findall(node_id2 .== spatial_data["segments"][:, 3]) index_s = intersect(index_s1, index_s2) if isempty(index_s) index_s1 = findall(node_id2 .== spatial_data["segments"][:, 2]) index_s2 = findall(node_id1 .== spatial_data["segments"][:, 3]) index_s = intersect(index_s1, index_s2) end if !isempty(findall(index_s .== spatial_data_matrices["ohl"]["segments"][:, 1])) km = spatial_data_matrices["ohl"]["segment_km"][index_s] else index_ugc = index_s[1] - size(spatial_data_matrices["ohl"]["segments"], 1) if !isempty(findall(index_s .== spatial_data_matrices["ugc"]["segments"][:, 1])) km = spatial_data_matrices["ugc"]["segment_km"][index_ugc] else km = 0 end end return km end
OptimalTransmissionRouting
https://github.com/Electa-Git/OptimalTransmissionRouting.jl.git
[ "BSD-3-Clause" ]
0.1.4
688e5028028e0dd8807efe6fff4a55a1a0832818
code
586
function do_optimal_routing(input_data) spatial_data, spatial_data_matrices, cost_data, equipment_data = prepare_spatial_data(input_data) c_tot, optimal_path, ac_dc, ac_cab, dc_cab = optimize_route(spatial_data, spatial_data_matrices, cost_data, equipment_data, input_data) route_impedance, route_length = determine_impedance_parameters(input_data, spatial_data, spatial_data_matrices, optimal_path, equipment_data) return spatial_data, spatial_data_matrices, cost_data, equipment_data, c_tot, optimal_path, ac_dc, ac_cab, dc_cab, route_impedance, route_length end
OptimalTransmissionRouting
https://github.com/Electa-Git/OptimalTransmissionRouting.jl.git
[ "BSD-3-Clause" ]
0.1.4
688e5028028e0dd8807efe6fff4a55a1a0832818
code
16781
function prepare_spatial_data(input_data) # OHL spatial_data_ohl, costs_ohl, equipment_data_ohl = build_spatial_matrices_and_cost_data(input_data; equipment = "ohl") spatial_data_ugc, costs_ugc, equipment_data_ugc = build_spatial_matrices_and_cost_data(input_data; equipment = "ugc") spatial_data = merge_maps(spatial_data_ohl, costs_ohl, spatial_data_ugc, costs_ugc, input_data) spatial_data_matrices = Dict{String, Any}() cost_data = Dict{String, Any}() equipment_data = Dict{String, Any}() spatial_data_matrices["ohl"] = spatial_data_ohl spatial_data_matrices["ugc"] = spatial_data_ugc cost_data["ohl"] = costs_ohl cost_data["ugc"] = costs_ugc equipment_data["ohl"] = equipment_data_ohl equipment_data["ugc"] = equipment_data_ugc return spatial_data, spatial_data_matrices, cost_data, equipment_data end function build_spatial_matrices_and_cost_data(input_data; equipment = "ohl") # prepare boundaries xmax = size(input_data["rgb_values"]["sea"], 2) + 1 ymax = size(input_data["rgb_values"]["sea"], 1) + 1 x_border_min = Int(input_data["boundaries"]["xmin"]) x_border_max = Int(input_data["boundaries"]["xmax"]) y_border_min = Int(input_data["boundaries"]["ymin"]) y_border_max = Int(input_data["boundaries"]["ymax"]) x_node_min = Int(min(input_data["start_node"]["x"], input_data["end_node"]["x"])) x_node_max = Int(max(input_data["start_node"]["x"], input_data["end_node"]["x"])) y_node_min = Int(min(input_data["start_node"]["y"], input_data["end_node"]["y"])) y_node_max = Int(max(input_data["start_node"]["y"], input_data["end_node"]["y"])) delta_x = Int(max(input_data["resolution_factor"],(x_node_max-x_node_min)/xmax)) delta_y = Int(max(input_data["resolution_factor"],(y_node_max-y_node_min)/ymax)) # make grid x = collect(x_node_min : delta_x : x_node_max) y = collect(y_node_min : delta_y : y_node_max) if x[end] != x_node_max x = [x; x_node_max] end if y[end] != y_node_max y = [y; y_node_max] end x_beg = collect(x_border_min : delta_x : x[1]) if x_beg[end] != x[1] x_beg = [x; x[1]] end if length(x) == 1 x_beg[end] = [] end y_beg = collect(y_border_min : delta_y : y[1]) if y_beg[end] != y[1] y_beg = [y; y[1]] end if length(y) == 1 y_beg[end]= [] end x = [x_beg; x[2:end-1]; collect(x[end] : delta_x : x_border_max)] y = [y_beg; y[2:end-1]; collect(y[end] : delta_y : y_border_max)] X = x' .* ones(size(y, 1)) Y = (ones(size(x, 1)))' .* y node_weights = Dict{String, Any}() for (area_idx, area) in input_data["rgb_values"] node_weights[area_idx] = assign_rgb_values(X, Y, x, y, input_data, area_idx) end onshore_nodes = ones(size(node_weights["sea"],1),1) onshore_nodes = 1 .- node_weights["sea"][:,4] nodes = node_weights["sea"][:, 1:3] equipment_ = join([input_data["technology"],"_",equipment]) node_weights = assign_node_weights(node_weights, input_data, equipment_) segments, segment_weights, segment_km, onshore_flag = create_segments_and_segment_weights(nodes, node_weights, onshore_nodes, input_data, X, Y, x, y, delta_x, delta_y) costs, equipment_details = calculate_costs_and_losses(input_data; equipment = equipment) spatial_data = Dict{String, Any}() spatial_data["nodes"] = nodes spatial_data["node_weights"] = node_weights spatial_data["onshore_nodes"] = onshore_nodes spatial_data["segments"] = segments spatial_data["segment_weights"] = segment_weights spatial_data["segment_km"] = segment_km spatial_data["onshore_flag"] = onshore_flag return spatial_data, costs, equipment_details end function assign_rgb_values(X, Y, x, y, input_data, area) nodes_w = zeros(size(x, 1) * size(y, 1), 4) for idx = 1 : size(X, 2) nodes_w[((idx-1) * size(X,1)+1) : idx * size(X,1) ,1] = ((idx-1) * size(X,1)+1) :idx * size(X,1) nodes_w[((idx-1) * size(X,1)+1) : idx * size(X,1), 2] = X[:, idx] nodes_w[((idx-1) * size(X,1)+1) : idx * size(X,1), 3] = Y[:, idx] nodes_w[((idx-1) * size(X,1)+1) : idx * size(X,1), 4] = input_data["rgb_values"][area][y, Int.(x[idx])] end return nodes_w end function assign_node_weights(node_weights, input_data, equipment) for (area, value) in input_data["spatial_weights"][equipment] node_weights[area][:, 4] = node_weights[area][:, 4] * input_data["spatial_weights"][equipment][area] end node_weights_ = zeros(size(node_weights["sea"])) node_weights_[:, 1:3] = node_weights["sea"][:, 1:3] for idx = 1:size(node_weights_, 1) for (area, value) in node_weights if node_weights_[idx, 4] == 0 && node_weights[area][idx, 4] !=0 node_weights_[idx, 4] = node_weights[area][idx, 4] end if node_weights_[idx, 4] != 0 && node_weights[area][idx, 4] !=0 if input_data["overlapping_area_weight"] == "minimum" node_weights_[idx, 4] = min(node_weights[area][idx, 4], node_weights_[idx, 4]) else node_weights_[idx, 4] = (node_weights[area][idx, 4] + node_weights_[idx, 4]) / 2 end end end node_weights_[idx, 4] = max(1, node_weights_[idx, 4]) end return node_weights_ end function create_segments_and_segment_weights(nodes, node_weights, onshore_nodes, input_data, X, Y, x, y, delta_x, delta_y) segments = zeros((length(x)-1)*length(y)+(length(y)-1)*length(x)+2*((length(x)-1)*(length(y)-1)),3); segments[:,1]=(1:size(segments,1))' segment_weights=ones(size(segments,1),1) onshore_flag=ones(size(segments,1),1) segment_km=ones(size(segment_weights)) # Construct all segments: Up, to the side, and diagonal up. for idx = 1 : size(X, 2) - 1 # PART1 segments[(4*(idx-1)*size(X,1)+1-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] = nodes[((idx-1)*size(X,1)+1):idx*size(X,1),1] segments[(4*(idx-1)*size(X,1)+1-3*(idx-1)):4:4*idx*size(X,1)-3*idx,3] = segments[(4*(idx-1)*size(X,1)+1-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] .+ 1 if input_data["overlapping_area_weight"] == "minimum" segment_weights[(4*(idx-1)*size(X,1)+1-3*(idx-1)):4:4*idx*size(X,1)-3*idx] = minimum(node_weights[((idx-1)*size(X,1)+1):idx*size(X,1), 4],node_weights[segments[(4*(idx-1)*size(X,1)+1-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2+1],4]) elseif input_data["overlapping_area_weight"] == "average" w1 = node_weights[((idx-1)*size(X,1)+1):idx*size(X,1),4] w2 = node_weights[Int.(segments[(4*(idx-1)*size(X,1)+1-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] .+ 1), 4] segment_weights[(4*(idx-1)*size(X,1)+1-3*(idx-1)):4:4*idx*size(X,1)-3*idx] = (w1 + w2) ./ 2 else print("Overlapping area weight must be average or minimum") end idx_ = Int.(segments[(4*(idx-1)*size(X,1)+1-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2].+1) idx__ = ((idx-1)*size(X,1)+1):idx*size(X,1) onshore_flag[(4*(idx-1)*size(X,1)+1-3*(idx-1)):4:4*idx*size(X,1)-3*idx] = minimum([onshore_nodes[idx__],onshore_nodes[idx_]]) segments[4*idx*size(X,1)-3*idx,3] = segments[4*idx*size(X,1)-3*idx,2]+size(X,1) idx1 = (4*(idx-1)*size(X,1)+1-3*(idx-1)):4:4*idx*size(X,1)-3*idx segment_km[idx1] = sqrt.((nodes[Int.(segments[idx1,2]),2]-nodes[Int.(segments[idx1,3]),2]).^2+(nodes[Int.(segments[idx1,2]),3]-nodes[Int.(segments[idx1,3]),3]).^2) # PART 2 segments[(4*(idx-1)*size(X,1)+2-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] = nodes[((idx-1)*size(X,1)+1):idx*size(X,1)-1,1] segments[(4*(idx-1)*size(X,1)+2-3*(idx-1)):4:4*idx*size(X,1)-3*idx,3] = segments[(4*(idx-1)*size(X,1)+2-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] .+ size(X,1) if input_data["overlapping_area_weight"] == "minimum" segment_weights[(4*(idx-1)*size(X,1)+2-3*(idx-1)):4:4*idx*size(X,1)-3*idx] = mininimum(node_weights[((idx-1)*size(X,1)+1):idx*size(X,1)-1, 4],node_weights[segments[(4*(idx-1)*size(X,1)+2-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2]+size(X,1), 4]) elseif input_data["overlapping_area_weight"] == "average" w1 = node_weights[((idx-1)*size(X,1)+1):idx*size(X,1)-1, 4] w2 = node_weights[Int.(segments[(4*(idx-1)*size(X,1)+2-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] .+ size(X,1)), 4] segment_weights[(4*(idx-1)*size(X,1)+2-3*(idx-1)):4:4*idx*size(X,1)-3*idx] = (w1 + w2) ./ 2 else print("Overlapping area weight must be average or minimum") end idx__ = Int.(((idx-1)*size(X,1)+1):idx*size(X,1) .- 1) idx_ = Int.(segments[(4*(idx-1)*size(X,1)+2-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] .+ size(X,1)) onshore_flag[(4*(idx-1)*size(X,1)+2-3*(idx-1)):4:4*idx*size(X,1)-3*idx] = minimum([onshore_nodes[idx__],onshore_nodes[idx_]]) idx1 = Int.((4*(idx-1)*size(X,1)+2-3*(idx-1)):4:4*idx*size(X,1)-3*idx) segment_km[idx1] = sqrt.((nodes[Int.(segments[idx1,2]),2]-nodes[Int.(segments[idx1,3]),2]).^2+(nodes[Int.(segments[idx1,2]),3]-nodes[Int.(segments[idx1,3]),3]).^2) #PART 3 segments[(4*(idx-1)*size(X,1)+3-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] = nodes[((idx-1)*size(X,1)+1):idx*size(X,1)-1,1] segments[(4*(idx-1)*size(X,1)+3-3*(idx-1)):4:4*idx*size(X,1)-3*idx,3] = segments[(4*(idx-1)*size(X,1)+3-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] .+ size(X,1) .+ 1 if input_data["overlapping_area_weight"] == "minimum" segment_weights[(4*(idx-1)*size(X,1)+3-3*(idx-1)):4:4*idx*size(X,1)-3*idx] = minimum(node_weights[((idx-1)*size(X,1)+1):idx*size(X,1)-1, 4], node_weights[segments[(4*(idx-1)*size(X,1)+3-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] + size(X,1)+1, 4]) elseif input_data["overlapping_area_weight"] == "average" w1 = node_weights[((idx-1)*size(X,1)+1):idx*size(X,1)-1, 4] w2 = node_weights[Int.(segments[(4*(idx-1)*size(X,1)+3-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] .+ size(X,1) .+ 1), 4] segment_weights[(4*(idx-1)*size(X,1)+3-3*(idx-1)):4:4*idx*size(X,1)-3*idx] = (w1 + w2) ./ 2 else print("Overlapping area weight must be average or minimum") end idx__ = Int.(((idx-1)*size(X,1)+1):idx*size(X,1)-1) idx_ = Int.(segments[(4*(idx-1)*size(X,1)+3-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] .+ size(X,1) .+ 1) onshore_flag[(4*(idx-1)*size(X,1)+3-3*(idx-1)):4:4*idx*size(X,1)-3*idx] = minimum([onshore_nodes[idx__],onshore_nodes[idx_]]) idx1 = Int.((4*(idx-1)*size(X,1)+3-3*(idx-1)):4:4*idx*size(X,1)-3*idx) segment_km[idx1]=sqrt.((nodes[Int.(segments[idx1,2]),2]-nodes[Int.(segments[idx1,3]),2]).^2+(nodes[Int.(segments[idx1,2]),3]-nodes[Int.(segments[idx1,3]),3]).^2) #PART 4 segments[(4*(idx-1)*size(X,1)+4-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] = nodes[((idx-1)*size(X,1)+1)+1:idx*size(X,1),1] segments[(4*(idx-1)*size(X,1)+4-3*(idx-1)):4:4*idx*size(X,1)-3*idx,3] = segments[(4*(idx-1)*size(X,1)+2-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] .+ size(X,1) if input_data["overlapping_area_weight"] == "minimum" segment_weights[(4*(idx-1)*size(X,1)+4-3*(idx-1)):4:4*idx*size(X,1)-3*idx] = minimum(node_weights[((idx-1)*size(X,1)+1)+1:idx*size(X,1), 4],node_weights[segments[(4*(idx-1)*size(X,1)+2-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2]+size(X,1), 4]) elseif input_data["overlapping_area_weight"] == "average" w1 = node_weights[((idx-1)*size(X,1)+1)+1:idx*size(X,1), 4] w2 = node_weights[Int.(segments[(4*(idx-1)*size(X,1)+2-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] .+ size(X,1)), 4] segment_weights[(4*(idx-1)*size(X,1)+4-3*(idx-1)):4:4*idx*size(X,1)-3*idx] = (w1 + w2) ./ 2 else print("Overlapping area weight must be average or minimum") end idx__ = ((idx-1)*size(X,1)+1)+1:idx*size(X,1) idx_ = Int.(segments[(4*(idx-1)*size(X,1)+2-3*(idx-1)):4:4*idx*size(X,1)-3*idx,2] .+ size(X,1)) onshore_flag[(4*(idx-1)*size(X,1)+4-3*(idx-1)):4:4*idx*size(X,1)-3*idx] = minimum([onshore_nodes[idx__],onshore_nodes[idx_]]) idx1 = Int.((4*(idx-1)*size(X,1)+4-3*(idx-1)):4:4*idx*size(X,1)-3*idx) segment_km[idx1]=sqrt.((nodes[Int.(segments[idx1,2]),2]-nodes[Int.(segments[idx1,3]),2]).^2+(nodes[Int.(segments[idx1,2]),3]-nodes[Int.(segments[idx1,3]),3]).^2) end segments[end-size(X,1)+2:end,2] = nodes[end-size(X,1)+1:end-1,1] segments[end-size(X,1)+2:end,3] = segments[end-size(X,1)+2:end,2] .+ 1 if input_data["overlapping_area_weight"] == "minimum" segment_weights[end-size(X,1)+2:end] = minimum(node_weights[end-size(X,1)+1:end-1, 4], node_weights[Int.(segments[end-size(X,1)+2:end, 2] .+ 1) , 4]) elseif input_data["overlapping_area_weight"] == "average" w1 = node_weights[end-size(X,1)+1:end-1, 4] w2 = node_weights[Int.(segments[end-size(X,1)+2:end,2] .+ 1), 4] segment_weights[end-size(X,1)+2:end] = (w1 + w2) ./ 2 else print("Overlapping area weight must be average or minimum") end onshore_flag[end-size(X,1)+2:end] = onshore_nodes[Int.(segments[end-size(X,1)+2:end,2] .+ 1)] .* onshore_nodes[end - size(X,1) + 1 : end-1] segment_km[end - size(X,1) + 2 : end] .= delta_y * input_data["resolution_factor"] return segments, segment_weights, segment_km, onshore_flag end function merge_maps(spatial_data_ohl, costs_ohl, spatial_data_ugc, costs_ugc, input_data) costs_ohl["ohl_km"] = spatial_data_ohl["segment_km"] .* (spatial_data_ohl["segment_weights"] .* costs_ohl["installation"] .+ costs_ohl["investment"]) ./ input_data["resolution_factor"] costs_ugc["ugc_km"] = spatial_data_ugc["segment_km"] .* ((spatial_data_ugc["segment_weights"] .* ((costs_ugc["onshore"]["installation"] .* spatial_data_ugc["onshore_flag"]) .+ (costs_ugc["offshore"]["installation"] .* (1 .- spatial_data_ugc["onshore_flag"])))) .+ ((costs_ugc["onshore"]["investment"] .* spatial_data_ugc["onshore_flag"]) .+ (costs_ugc["offshore"]["investment"] .* (1 .- spatial_data_ugc["onshore_flag"])))) ./ input_data["resolution_factor"] # Update segment weights based on costs spatial_data_ohl["segment_weights"] = (spatial_data_ohl["segment_weights"] .* costs_ohl["installation"] .+ costs_ohl["investment"]) .* input_data["resolution_factor"] spatial_data_ugc["segment_weights"] = ((spatial_data_ugc["segment_weights"] .* ((costs_ugc["onshore"]["installation"] .* spatial_data_ugc["onshore_flag"]) .+ (costs_ugc["offshore"]["installation"] .* (1 .- spatial_data_ugc["onshore_flag"])))) .+ ((costs_ugc["onshore"]["investment"] .* spatial_data_ugc["onshore_flag"]) .+ (costs_ugc["offshore"]["investment"] .* (1 .- spatial_data_ugc["onshore_flag"])))) .* input_data["resolution_factor"] # # Connect OHL and UGC maps # # Step 1) Shift node indexes for the UGC map with the number of nodes for OHL spatial_data_ugc["segments"][:, 1] = spatial_data_ugc["segments"][:, 1] .+ size(spatial_data_ohl["segments"], 1) spatial_data_ugc["segments"][:, 2:3] = spatial_data_ugc["segments"][:, 2:3] .+ size(spatial_data_ohl["nodes"], 1) spatial_data_ugc["nodes"][:, 1] = spatial_data_ohl["nodes"][:,1] .+ size(spatial_data_ohl["nodes"], 1) spatial_data = Dict{String, Any}() spatial_data["segments"] = [spatial_data_ohl["segments"]; spatial_data_ugc["segments"]] spatial_data["nodes"] = [spatial_data_ohl["nodes"]; spatial_data_ugc["nodes"]] spatial_data["onshore_nodes"] = [spatial_data_ohl["onshore_nodes"]; spatial_data_ugc["onshore_nodes"]] spatial_data["segment_weights"] = [spatial_data_ohl["segment_weights"]; spatial_data_ugc["segment_weights"]] spatial_data["onshore_flag"] = [spatial_data_ohl["onshore_flag"]; spatial_data_ugc["onshore_flag"]] # # Step 2) Connect OHL and UGC maps at each X, Y point (node) via a new segment number_of_additional_segments = size(spatial_data_ohl["nodes"], 1) segment_idx = 1 : (spatial_data["segments"][end, 1] + number_of_additional_segments) segment_from_node = [spatial_data["segments"][:, 2]; spatial_data_ohl["nodes"][:, 1]] segment_to_node = [spatial_data["segments"][:, 3]; spatial_data_ugc["nodes"][:, 1]] spatial_data["segments"] = [segment_idx segment_from_node segment_to_node] spatial_data["segment_weights"] = [spatial_data["segment_weights"]; zeros(number_of_additional_segments, 1)] spatial_data["onshore_flag"] = [spatial_data["onshore_flag"]; ones(number_of_additional_segments, 1)] spatial_data["ohl_ugc_transition"] = [zeros(2 * size(spatial_data["segments"], 1)); ones(number_of_additional_segments, 1)] return spatial_data end
OptimalTransmissionRouting
https://github.com/Electa-Git/OptimalTransmissionRouting.jl.git
[ "BSD-3-Clause" ]
0.1.4
688e5028028e0dd8807efe6fff4a55a1a0832818
code
2576
function plot_result(plot_dictionary, input_data, spatial_data, spatial_data_matrices, optimal_path) A = zeros(3, size(plot_dictionary["overlay_image"],1), size(plot_dictionary["overlay_image"],2) ) look_up_table = [0 255 0; 176 224 230;255 255 255;255 255 0; 218 165 32;255 160 122;255 0 0] ./ 255 for i in 1:size(plot_dictionary["overlay_image"], 1) for j in 1:size(plot_dictionary["overlay_image"], 2) A[:, i, j] = look_up_table[Int.(plot_dictionary["overlay_image"][i, j]), :]' end end p = Images.colorview(ColorTypes.RGB, A) Plots.plot(p) for idx = 1 : size(optimal_path, 1) - 1 x1 = spatial_data["nodes"][optimal_path[idx], 2] y1 = spatial_data["nodes"][optimal_path[idx], 3] x2 = spatial_data["nodes"][optimal_path[idx + 1], 2] y2 = spatial_data["nodes"][optimal_path[idx + 1], 3] ohl_cable = ohl_or_cable(spatial_data, spatial_data_matrices, optimal_path[idx], optimal_path[idx + 1]) if input_data["technology"] == "dc" if ohl_cable == "ugc" p = Plots.plot!([x1, x2], [y1, y2], color = :brown, linewidth = 2, label = "") else p = Plots.plot!([x1, x2], [y1, y2], color = :brown, linestyle = :dot, linewidth = 2, label = "") end else if ohl_cable == "ugc" p = Plots.plot!([x1, x2], [y1, y2], color = :black, linewidth = 2, label = "") else p = Plots.plot!([x1, x2], [y1, y2], color = :black, linestyle = :dot, linewidth = 2, label = "") end end end Plots.plot!(xlims=(input_data["boundaries"]["xmin"],input_data["boundaries"]["xmax"]), ylims = (input_data["boundaries"]["ymin"], input_data["boundaries"]["ymax"])) plot_file = join(["plot_test_",input_data["strategy"],"_",input_data["technology"],".pdf"]) Plots.savefig(p, plot_file) end function ohl_or_cable(spatial_data, spatial_data_matrices, node_id1, node_id2) index_s1 = findall(node_id1 .== spatial_data["segments"][:, 2]) index_s2 = findall(node_id2 .== spatial_data["segments"][:, 3]) index_s = intersect(index_s1, index_s2) if isempty(index_s) index_s1 = findall(node_id2 .== spatial_data["segments"][:, 2]) index_s2 = findall(node_id1 .== spatial_data["segments"][:, 3]) index_s = intersect(index_s1, index_s2) end if any(index_s[1] .== spatial_data_matrices["ohl"]["segments"][:, 1]) ohl_cable = "ohl" else ohl_cable = "ugc" end return ohl_cable end
OptimalTransmissionRouting
https://github.com/Electa-Git/OptimalTransmissionRouting.jl.git
[ "BSD-3-Clause" ]
0.1.4
688e5028028e0dd8807efe6fff4a55a1a0832818
code
7891
# Some branch in Italy bus1 = Dict{String, Any}() bus1["longitude"] = 16.2487678 bus1["latitude"] = 40.358515 bus2 = Dict{String, Any}() bus2["longitude"] = 14.1482998 bus2["latitude"] = 37.5900782 # strategy = "all_permitted" # strategy = "OHL_on_existing_corridors" strategy = "cables_only" spatial_weights, voltages, resolution, impedances = OTR.define_weights_voltages(strategy) rgb_values, nodes_lp, boundaries, plot_dictionary = OTR.convert_image_files_to_weights(bus1, bus2) #define inputs input_data = Dict{String, Any}() input_data["resolution_factor"] = 2 # resolution_factor 1,2,3, ... to speed up algorithm input_data["algorithm_factor"] = 1 # algorithm_factor 1.....1.3 to speed up Astar algorithm, goes at expense of accuracy input_data["distance"] = 2.5 # do not change: this is the standard resolution of the environmental data input_data["algorithm"] = "Astar" # "Astar" or "Dijkstra" input_data["voltages"] = voltages # transmission voltages input_data["spatial_weights"] = spatial_weights # spatial weights input_data["rgb_values"] = rgb_values # Spatial data as RGB values input_data["boundaries"] = boundaries # VBoundaries of the area (to avoid using full European range) input_data["overlapping_area_weight"] = "average" # "average" = average weight of the spatial weights; "minimum" = minimum of the overlapping weights input_data["strategy"] = strategy # or "OHL_on_existing_corridors" or "cables_only" input_data["losses"] = 0.01 # proxy for losses input_data["lifetime"] = 30 # lifetime: NOT USED in FLEXPLAN input_data["interest"] = 0.02 # Interest: NOT USED in FLEXPLAN input_data["technology"] = "dc" # or "dc" input_data["power_rating"] = 2000 # power rating input_data["start_node"] = Dict{String, Any}() input_data["start_node"]["x"] = nodes_lp["x1"] input_data["start_node"]["y"] = nodes_lp["y1"] input_data["end_node"] = Dict{String, Any}() input_data["end_node"]["x"] = nodes_lp["x2"] input_data["end_node"]["y"] = nodes_lp["y2"] input_data["impedances"] = impedances # Provide look-up table for OHL & OGC impedances @testset "DC cables only" begin strategy = "cables_only" input_data["technology"] = "dc" # or "dc" input_data["strategy"] = strategy @time spatial_data, spatial_data_matrices, cost_data, equipment_data, c_tot, optimal_path, ac_dc, ac_cab, dc_cab, route_impedance, route_length = OTR.do_optimal_routing(input_data) @testset "cost data" begin @test isapprox(cost_data["ohl"]["ohl_km"][1], 1.24362898072976e7; atol = 1e0) @test isapprox(cost_data["ohl"]["ohl_km"][17], 1.5231374779172337e7; atol = 1e0) @test isapprox(cost_data["ohl"]["ohl_km"][9639], 2.1540416786293026e7; atol = 1e0) end @testset "total cost" begin @test isapprox(c_tot, 9.807293638249868e8; atol = 1e0) end @testset "optimal path" begin @test isapprox(optimal_path[52], 13019) @test isapprox(optimal_path[15], 10790) end @testset "impedance_data" begin @test isapprox(route_impedance["r_pu"], 0.001619311421391319, atol = 1e-5) @test isapprox(route_impedance["x_pu"], 0.0, atol = 1e-3) @test isapprox(route_impedance["bc_pu"], 0.0, atol = 1e-3) end @testset "route_length" begin @test isapprox(route_length["total_length"], 174.544725, atol = 1e-1) @test isapprox(route_length["ohl_length"], 0.0, atol = 1e-3) @test isapprox(route_length["ugc_length"], 174.54472, atol = 1e-3) end end @testset "DC all permitted" begin strategy = "all_permitted" input_data["technology"] = "dc" # or "dc" input_data["strategy"] = strategy @time spatial_data, spatial_data_matrices, cost_data, equipment_data, c_tot, optimal_path, ac_dc, ac_cab, dc_cab, route_impedance, route_length = OTR.do_optimal_routing(input_data) @testset "cost data" begin @test isapprox(cost_data["ohl"]["ohl_km"][1], 1.24362898072976e7; atol = 1e0) @test isapprox(cost_data["ohl"]["ohl_km"][17], 1.5231374779172337e7; atol = 1e0) @test isapprox(cost_data["ohl"]["ohl_km"][9639], 2.1540416786293026e7; atol = 1e0) end @testset "total cost" begin @test isapprox(c_tot, 9.807293638249868e8; atol = 1e0) end @testset "optimal path" begin @test isapprox(optimal_path[52], 13019) @test isapprox(optimal_path[15], 10790) end @testset "impedance_data" begin @test isapprox(route_impedance["r"], 1.6581748955047106, atol = 1e-3) @test isapprox(route_impedance["x_pu"], 0.0, atol = 1e-3) @test isapprox(route_impedance["bc_pu"], 0.0, atol = 1e-3) end @testset "route_length" begin @test isapprox(route_length["total_length"], 174.544725, atol = 1e-1) @test isapprox(route_length["ohl_length"], 0.0, atol = 1e-3) @test isapprox(route_length["ugc_length"], 174.54472, atol = 1e-3) end end @testset "AC cables only" begin strategy = "cables_only" input_data["technology"] = "ac" # or "dc" input_data["strategy"] = strategy @time spatial_data, spatial_data_matrices, cost_data, equipment_data, c_tot, optimal_path, ac_dc, ac_cab, dc_cab, route_impedance, route_length = OTR.do_optimal_routing(input_data) @testset "cost data" begin @test isapprox(cost_data["ohl"]["ohl_km"][1], 4.072540970760065e7; atol = 1e0) @test isapprox(cost_data["ohl"]["ohl_km"][17], 4.072540970760065e7; atol = 1e0) @test isapprox(cost_data["ohl"]["ohl_km"][9639], 5.759442674168975e7; atol = 1e0) end @testset "total cost" begin @test isapprox(c_tot, 2.0405224791992671e9; atol = 1e0) end @testset "optimal path" begin @test isapprox(optimal_path[52], 13027) @test isapprox(optimal_path[15], 10790) end @testset "impedance_data" begin @test isapprox(route_impedance["r_pu"], 0.0005509232966856801, atol = 1e-6) @test isapprox(route_impedance["x"], 9.09313399161207, atol = 1e-3) @test isapprox(route_impedance["bc_pu"], 485.0546916571823, atol = 1e-3) end @testset "route_length" begin @test isapprox(route_length["total_length"], 185.57416, atol = 1e-1) @test isapprox(route_length["ohl_length"], 0.0, atol = 1e-3) @test isapprox(route_length["ugc_length"], 185.57416, atol = 1e-3) end end @testset "AC all permitted" begin strategy = "all_permitted" input_data["technology"] = "ac" # or "dc" input_data["strategy"] = strategy @time spatial_data, spatial_data_matrices, cost_data, equipment_data, c_tot, optimal_path, ac_dc, ac_cab, dc_cab, route_impedance, route_length = OTR.do_optimal_routing(input_data) @testset "cost data" begin @test isapprox(cost_data["ohl"]["ohl_km"][1], 4.072540970760065e7; atol = 1e0) @test isapprox(cost_data["ohl"]["ohl_km"][17], 4.072540970760065e7; atol = 1e0) @test isapprox(cost_data["ohl"]["ohl_km"][9639], 5.759442674168975e7; atol = 1e0) end @testset "total cost" begin @test isapprox(c_tot, 2.0405224791992671e9; atol = 1e0) end @testset "optimal path" begin @test isapprox(optimal_path[52], 13027) @test isapprox(optimal_path[15], 10790) end @testset "impedance_data" begin @test isapprox(route_impedance["r_pu"], 0.0005509232966856801, atol = 1e-6) @test isapprox(route_impedance["x"], 9.09313399161207, atol = 1e-3) @test isapprox(route_impedance["bc_pu"], 485.0546916571823, atol = 1e-3) end @testset "route_length" begin @test isapprox(route_length["total_length"], 185.57416, atol = 1e-1) @test isapprox(route_length["ohl_length"], 0.0, atol = 1e-3) @test isapprox(route_length["ugc_length"], 185.57416, atol = 1e-3) end end # For plotting the pdf of the result # OTR.plot_result(plot_dictionary, input_data, spatial_data, spatial_data_matrices, optimal_path) #
OptimalTransmissionRouting
https://github.com/Electa-Git/OptimalTransmissionRouting.jl.git
[ "BSD-3-Clause" ]
0.1.4
688e5028028e0dd8807efe6fff4a55a1a0832818
code
197
import OptimalTransmissionRouting; const OTR = OptimalTransmissionRouting import Images using ColorTypes using Plots using Test @testset "OptimalTransmissionRouting" begin include("main.jl") end
OptimalTransmissionRouting
https://github.com/Electa-Git/OptimalTransmissionRouting.jl.git