index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/MergeCounts.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MergeCounts {
private static final Logger logger = LoggerFactory.getLogger(MergeCounts.class);
private int expectedTerminalCount;
private int currentTerminalCount;
public MergeCounts(int expectedTerminalCount) {
this.expectedTerminalCount = expectedTerminalCount;
}
public boolean incrementTerminalCountAndCheck() {
currentTerminalCount++;
logger.debug("Current terminal count: " + currentTerminalCount +
" Expected terminal count: " + expectedTerminalCount);
return (currentTerminalCount == expectedTerminalCount);
}
}
| 8,800 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/EndpointInjector.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import rx.Observable;
public interface EndpointInjector {
public Observable<EndpointChange> deltas();
}
| 8,801 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/HeartbeatHandler.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HeartbeatHandler extends ChannelDuplexHandler {
static final Logger logger = LoggerFactory.getLogger(HeartbeatHandler.class);
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent e = (IdleStateEvent) evt;
if (e.state() == IdleState.READER_IDLE) {
logger.warn("Read idle, due to missed heartbeats, closing connection: " + ctx.channel().remoteAddress());
ctx.close();
} else if (e.state() == IdleState.WRITER_IDLE) {
ctx.channel().writeAndFlush(RemoteRxEvent.heartbeat());
}
}
super.userEventTriggered(ctx, evt);
}
}
| 8,802 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/ConnectToConfig.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import io.mantisrx.common.network.Endpoint;
import java.util.HashMap;
import java.util.Map;
import rx.functions.Action0;
import rx.subjects.PublishSubject;
public abstract class ConnectToConfig {
private Endpoint endpoint;
private String name;
private Map<String, String> subscribeParameters = new HashMap<String, String>();
private int subscribeAttempts;
private boolean suppressDecodingErrors = false;
private Action0 connectionDisconnectCallback;
private PublishSubject<Integer> closeTrigger;
public ConnectToConfig(String host, int port, String name,
Map<String, String> subscribeParameters,
int subscribeAttempts,
boolean suppressDecodingErrors,
Action0 connectionDisconnectCallback,
PublishSubject<Integer> closeTrigger) {
endpoint = new Endpoint(host, port);
this.name = name;
this.subscribeParameters.putAll(subscribeParameters);
this.subscribeAttempts = subscribeAttempts;
this.suppressDecodingErrors = suppressDecodingErrors;
this.connectionDisconnectCallback = connectionDisconnectCallback;
this.closeTrigger = closeTrigger;
}
public Action0 getConnectionDisconnectCallback() {
return connectionDisconnectCallback;
}
public PublishSubject<Integer> getCloseTrigger() {
return closeTrigger;
}
public String getHost() {
return endpoint.getHost();
}
public int getPort() {
return endpoint.getPort();
}
public String getName() {
return name;
}
public Map<String, String> getSubscribeParameters() {
return subscribeParameters;
}
public int getSubscribeAttempts() {
return subscribeAttempts;
}
public boolean isSuppressDecodingErrors() {
return suppressDecodingErrors;
}
}
| 8,803 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/ServeObservable.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import io.mantisrx.common.codec.Encoder;
import io.reactivex.mantis.remote.observable.filter.ServerSideFilters;
import io.reactivex.mantis.remote.observable.slotting.RoundRobin;
import io.reactivex.mantis.remote.observable.slotting.SlottingStrategy;
import java.util.Map;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
public class ServeObservable<T> extends ServeConfig<T, T> {
private Encoder<T> encoder;
private Observable<T> observable;
private boolean subscriptionPerConnection;
private boolean isHotStream;
public ServeObservable(Builder<T> builder) {
super(builder.name, builder.slottingStrategy,
builder.filterFunction, builder.maxWriteAttempts);
this.encoder = builder.encoder;
this.subscriptionPerConnection = builder.subscriptionPerConnection;
this.isHotStream = builder.isHotStream;
this.observable = builder.observable;
if (!builder.subscriptionPerConnection) {
applySlottingSideEffectToObservable(builder.observable);
}
}
public boolean isSubscriptionPerConnection() {
return subscriptionPerConnection;
}
public Observable<T> getObservable() {
return observable;
}
public boolean isHotStream() {
return isHotStream;
}
private void applySlottingSideEffectToObservable(Observable<T> o) {
final Observable<T> withSideEffects =
o
.doOnNext(new Action1<T>() {
@Override
public void call(T t) {
slottingStrategy.writeOnSlot(null, t); // null key
}
})
.doOnTerminate(new Action0() {
@Override
public void call() {
slottingStrategy.completeAllConnections();
}
});
final MutableReference<Subscription> subscriptionRef = new MutableReference<>();
slottingStrategy.registerDoAfterFirstConnectionAdded(new Action0() {
@Override
public void call() {
subscriptionRef.setValue(withSideEffects.subscribe());
}
});
slottingStrategy.registerDoAfterLastConnectionRemoved(new Action0() {
@Override
public void call() {
subscriptionRef.getValue().unsubscribe();
}
});
}
public Encoder<T> getEncoder() {
return encoder;
}
public static class Builder<T> {
public boolean isHotStream;
private String name;
private Observable<T> observable;
private SlottingStrategy<T> slottingStrategy = new RoundRobin<>();
private Encoder<T> encoder;
private Func1<Map<String, String>, Func1<T, Boolean>> filterFunction = ServerSideFilters.noFiltering();
private int maxWriteAttempts;
private boolean subscriptionPerConnection;
public Builder<T> name(String name) {
if (name != null && name.length() > 127) {
throw new IllegalArgumentException("Observable name must be less than 127 characters");
}
this.name = name;
return this;
}
public Builder<T> observable(Observable<T> observable) {
this.observable = observable;
return this;
}
public Builder<T> maxWriteAttempts(Observable<T> observable) {
this.observable = observable;
return this;
}
public Builder<T> slottingStrategy(SlottingStrategy<T> slottingStrategy) {
this.slottingStrategy = slottingStrategy;
return this;
}
public Builder<T> encoder(Encoder<T> encoder) {
this.encoder = encoder;
return this;
}
public Builder<T> serverSideFilter(
Func1<Map<String, String>, Func1<T, Boolean>> filterFunc) {
this.filterFunction = filterFunc;
return this;
}
public ServeObservable<T> build() {
return new ServeObservable<T>(this);
}
public Builder<T> subscriptionPerConnection() {
subscriptionPerConnection = true;
return this;
}
public Builder<T> hotStream() {
isHotStream = true;
return this;
}
}
}
| 8,804 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/ServeGroupedObservable.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import io.mantisrx.common.codec.Encoder;
import io.mantisrx.common.metrics.Counter;
import io.mantisrx.common.metrics.Metrics;
import io.mantisrx.common.metrics.MetricsRegistry;
import io.mantisrx.common.network.HashFunctions;
import io.mantisrx.server.core.ServiceRegistry;
import io.reactivex.mantis.remote.observable.filter.ServerSideFilters;
import io.reactivex.mantis.remote.observable.slotting.ConsistentHashing;
import io.reactivex.mantis.remote.observable.slotting.SlottingStrategy;
import io.reactivx.mantis.operators.DisableBackPressureOperator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Notification;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
public class ServeGroupedObservable<K, V> extends ServeConfig<K, Group<String, V>> {
private static final Logger logger = LoggerFactory.getLogger(ServeGroupedObservable.class);
private Encoder<String> keyEncoder;
private Encoder<V> valueEncoder;
private int groupBufferTimeMSec = 250;
private long expiryInSecs = Long.MAX_VALUE;
private Counter groupsExpiredCounter;
public ServeGroupedObservable(Builder<K, V> builder) {
super(builder.name, builder.slottingStrategy, builder.filterFunction,
builder.maxWriteAttempts);
// TODO this should be pushed into builder, default is 0 buffer
String groupBufferTimeMSecStr =
ServiceRegistry.INSTANCE.getPropertiesService().getStringValue("mantis.remoteObservable.groupBufferMSec", "250");
if (groupBufferTimeMSecStr != null && !groupBufferTimeMSecStr.equals("250")) {
groupBufferTimeMSec = Integer.parseInt(groupBufferTimeMSecStr);
}
this.keyEncoder = builder.keyEncoder;
this.valueEncoder = builder.valueEncoder;
this.expiryInSecs = builder.expiryTimeInSecs;
Metrics m = new Metrics.Builder()
.name("ServeGroupedObservable")
.addCounter("groupsExpiredCounter")
.build();
m = MetricsRegistry.getInstance().registerAndGet(m);
groupsExpiredCounter = m.getCounter("groupsExpiredCounter");
applySlottingSideEffectToObservable(builder.observable, builder.minConnectionsToSubscribe);
}
private void applySlottingSideEffectToObservable(
Observable<Observable<GroupedObservable<String, V>>> o,
final Observable<Integer> minConnectionsToSubscribe) {
final AtomicInteger currentMinConnectionsToSubscribe = new AtomicInteger();
minConnectionsToSubscribe
.subscribe(new Action1<Integer>() {
@Override
public void call(Integer t1) {
currentMinConnectionsToSubscribe.set(t1);
}
});
Observable<Observable<List<Group<String, V>>>> listOfGroups = o
.map(new Func1<Observable<GroupedObservable<String, V>>, Observable<List<Group<String, V>>>>() {
@Override
public Observable<List<Group<String, V>>> call(
Observable<GroupedObservable<String, V>> og) {
return
og
.flatMap(new Func1<GroupedObservable<String, V>, Observable<List<Group<String, V>>>>() {
@Override
public Observable<List<Group<String, V>>> call(
final GroupedObservable<String, V> group) {
final byte[] keyBytes = keyEncoder.encode(group.getKey());
final String keyValue = group.getKey();
return
group
// comment out as this causes a NPE to happen in merge. supposedly fixed in rxjava 1.0
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
//logger.info("Expiring group stage in serveGroupedObservable " + group.getKey());
groupsExpiredCounter.increment();
}
})
.timeout(expiryInSecs, TimeUnit.SECONDS, (Observable<? extends V>) Observable.empty())
.materialize()
.lift(new DisableBackPressureOperator<Notification<V>>())
.buffer(groupBufferTimeMSec, TimeUnit.MILLISECONDS)
.filter(new Func1<List<Notification<V>>, Boolean>() {
@Override
public Boolean call(List<Notification<V>> t1) {
return t1 != null && !t1.isEmpty();
}
})
.map(new Func1<List<Notification<V>>, List<Group<String, V>>>() {
@Override
public List<Group<String, V>> call(List<Notification<V>> notifications) {
List<Group<String, V>> groups = new ArrayList<>(notifications.size());
for (Notification<V> notification : notifications) {
groups.add(new Group<String, V>(keyValue, keyBytes, notification));
}
return groups;
}
});
}
});
}
});
final Observable<List<Group<String, V>>> withSideEffects =
Observable
.merge(
listOfGroups
)
.doOnEach(new Observer<List<Group<String, V>>>() {
@Override
public void onCompleted() {
slottingStrategy.completeAllConnections();
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
slottingStrategy.errorAllConnections(e);
}
@Override
public void onNext(List<Group<String, V>> listOfGroups) {
for (Group<String, V> group : listOfGroups) {
slottingStrategy.writeOnSlot(group.getKeyBytes(), group);
}
}
});
final MutableReference<Subscription> subscriptionRef = new MutableReference<>();
final AtomicInteger connectionCount = new AtomicInteger(0);
final AtomicBoolean isSubscribed = new AtomicBoolean();
slottingStrategy.registerDoOnEachConnectionAdded(new Action0() {
@Override
public void call() {
Integer minNeeded = currentMinConnectionsToSubscribe.get();
Integer current = connectionCount.incrementAndGet();
if (current >= minNeeded) {
if (isSubscribed.compareAndSet(false, true)) {
logger.info("MinConnectionsToSubscribe: " + minNeeded + ", has been met, subscribing to observable, current connection count: " + current);
subscriptionRef.setValue(withSideEffects.subscribe());
}
} else {
logger.info("MinConnectionsToSubscribe: " + minNeeded + ", has NOT been met, current connection count: " + current);
}
}
});
slottingStrategy.registerDoAfterLastConnectionRemoved(new Action0() {
@Override
public void call() {
subscriptionRef.getValue().unsubscribe();
logger.info("All connections deregistered, unsubscribed to observable, resetting current connection count: 0");
connectionCount.set(0);
isSubscribed.set(false);
}
});
}
public Encoder<String> getKeyEncoder() {
return keyEncoder;
}
public Encoder<V> getValueEncoder() {
return valueEncoder;
}
public static class Builder<K, V> {
private String name;
private Observable<Observable<GroupedObservable<String, V>>> observable;
private SlottingStrategy<Group<String, V>> slottingStrategy =
new ConsistentHashing<>(name, HashFunctions.ketama());
private Encoder<String> keyEncoder;
private Encoder<V> valueEncoder;
private Func1<Map<String, String>, Func1<K, Boolean>> filterFunction = ServerSideFilters.noFiltering();
private int maxWriteAttempts = 3;
private long expiryTimeInSecs = Long.MAX_VALUE;
private Observable<Integer> minConnectionsToSubscribe = Observable.just(1);
public Builder<K, V> name(String name) {
if (name != null && name.length() > 127) {
throw new IllegalArgumentException("Observable name must be less than 127 characters");
}
this.name = name;
return this;
}
public Builder<K, V> observable(Observable<Observable<GroupedObservable<String, V>>> observable) {
this.observable = observable;
return this;
}
public Builder<K, V> maxWriteAttempts(int maxWriteAttempts) {
this.maxWriteAttempts = maxWriteAttempts;
return this;
}
public Builder<K, V> withExpirySecs(long expiryInSecs) {
this.expiryTimeInSecs = expiryInSecs;
return this;
}
public Builder<K, V> minConnectionsToSubscribe(Observable<Integer> minConnectionsToSubscribe) {
this.minConnectionsToSubscribe = minConnectionsToSubscribe;
return this;
}
public Builder<K, V> slottingStrategy(SlottingStrategy<Group<String, V>> slottingStrategy) {
this.slottingStrategy = slottingStrategy;
return this;
}
public Builder<K, V> keyEncoder(Encoder<String> keyEncoder) {
this.keyEncoder = keyEncoder;
return this;
}
public Builder<K, V> valueEncoder(Encoder<V> valueEncoder) {
this.valueEncoder = valueEncoder;
return this;
}
public Builder<K, V> serverSideFilter(
Func1<Map<String, String>, Func1<K, Boolean>> filterFunc) {
this.filterFunction = filterFunc;
return this;
}
public ServeGroupedObservable<K, V> build() {
return new ServeGroupedObservable<K, V>(this);
}
}
}
| 8,805 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/RemoteRxConnection.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import rx.Observable;
import rx.Observer;
public class RemoteRxConnection<T> {
private Observable<T> observable;
private RxMetrics metrics;
private Observer<Integer> closeTrigger;
public RemoteRxConnection(Observable<T> observable,
RxMetrics metrics, Observer<Integer> closeTrigger) {
this.observable = observable;
this.metrics = metrics;
}
public Observable<T> getObservable() {
return observable;
}
public RxMetrics getMetrics() {
return metrics;
}
public void close() {
closeTrigger.onNext(1);
closeTrigger.onCompleted();
}
}
| 8,806 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/RemoteObservableException.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
public class RemoteObservableException extends Exception {
private static final long serialVersionUID = 1L;
public RemoteObservableException(String message) {
super(message);
}
}
| 8,807 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/NonDataException.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
public class NonDataException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NonDataException(Throwable throwable) {
super(throwable);
}
public NonDataException(String message) {
super(message);
}
}
| 8,808 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/PortSelectorWithinRange.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
public class PortSelectorWithinRange {
private int start;
private int end;
private int attempts = 5;
public PortSelectorWithinRange(int start, int end) {
this.start = start;
this.end = end;
}
public PortSelectorWithinRange(int start, int end, int attempts) {
this.start = start;
this.end = end;
this.attempts = attempts;
}
public int acquirePort() {
for (int i = 0; i < attempts; i++) {
int randomPort = start + (int) (Math.random() * ((end - start) + 1));
Socket socket = null;
try {
socket = new Socket("localhost", randomPort);
} catch (ConnectException e) {
return randomPort;
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
throw new RuntimeException("Could not acquire a port within range, after " + attempts + " attempts");
}
}
| 8,809 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/MutableReference.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
public class MutableReference<T> {
private T value;
public MutableReference() {}
public MutableReference(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
| 8,810 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/ThrowableWithCount.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
public class ThrowableWithCount {
private Throwable throwable;
private Integer count;
public ThrowableWithCount(Throwable throwable, Integer count) {
this.throwable = throwable;
this.count = count;
}
public Throwable getThrowable() {
return throwable;
}
public Integer getCount() {
return count;
}
} | 8,811 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/ServeNestedObservable.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import io.mantisrx.common.codec.Encoder;
import io.reactivex.mantis.remote.observable.filter.ServerSideFilters;
import io.reactivex.mantis.remote.observable.slotting.RoundRobin;
import io.reactivex.mantis.remote.observable.slotting.SlottingStrategy;
import java.util.Map;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Func1;
public class ServeNestedObservable<T> extends ServeConfig<T, T> {
private Encoder<T> encoder;
public ServeNestedObservable(Builder<T> builder) {
super(builder.name, builder.slottingStrategy, builder.filterFunction,
builder.maxWriteAttempts);
this.encoder = builder.encoder;
applySlottingSideEffectToObservable(builder.observable);
}
private void applySlottingSideEffectToObservable(Observable<Observable<T>> o) {
final Observable<T> withSideEffects =
Observable.merge(o)
.doOnEach(new Observer<T>() {
@Override
public void onCompleted() {
slottingStrategy.completeAllConnections();
}
@Override
public void onError(Throwable e) {
slottingStrategy.errorAllConnections(e);
}
@Override
public void onNext(T value) {
slottingStrategy.writeOnSlot(null, value);
}
});
final MutableReference<Subscription> subscriptionRef = new MutableReference<>();
slottingStrategy.registerDoAfterFirstConnectionAdded(new Action0() {
@Override
public void call() {
subscriptionRef.setValue(withSideEffects.subscribe());
}
});
slottingStrategy.registerDoAfterLastConnectionRemoved(new Action0() {
@Override
public void call() {
subscriptionRef.getValue().unsubscribe();
}
});
}
public Encoder<T> getEncoder() {
return encoder;
}
public static class Builder<T> {
private String name;
private Observable<Observable<T>> observable;
private SlottingStrategy<T> slottingStrategy = new RoundRobin<>();
private Encoder<T> encoder;
private Func1<Map<String, String>, Func1<T, Boolean>> filterFunction = ServerSideFilters.noFiltering();
private int maxWriteAttempts = 3;
public Builder<T> name(String name) {
if (name != null && name.length() > 127) {
throw new IllegalArgumentException("Observable name must be less than 127 characters");
}
this.name = name;
return this;
}
public Builder<T> observable(Observable<Observable<T>> observable) {
this.observable = observable;
return this;
}
public Builder<T> maxWriteAttempts(int maxWriteAttempts) {
this.maxWriteAttempts = maxWriteAttempts;
return this;
}
public Builder<T> slottingStrategy(SlottingStrategy<T> slottingStrategy) {
this.slottingStrategy = slottingStrategy;
return this;
}
public Builder<T> encoder(Encoder<T> encoder) {
this.encoder = encoder;
return this;
}
public Builder<T> serverSideFilter(
Func1<Map<String, String>, Func1<T, Boolean>> filterFunc) {
this.filterFunction = filterFunc;
return this;
}
public ServeNestedObservable<T> build() {
return new ServeNestedObservable<T>(this);
}
}
}
| 8,812 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/UnexpectedCompleteSignal.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
public class UnexpectedCompleteSignal extends RuntimeException {
private static final long serialVersionUID = 1L;
public UnexpectedCompleteSignal(String message) {
super(message);
}
}
| 8,813 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/SafeWriter.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import io.mantisrx.common.network.WritableEndpoint;
import io.reactivex.mantis.remote.observable.slotting.SlottingStrategy;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import mantis.io.reactivex.netty.channel.ObservableConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
public class SafeWriter {
static final Logger logger = LoggerFactory.getLogger(SafeWriter.class);
private static final AtomicLong checkIsOpenCounter = new AtomicLong();
private static final int CHECK_IS_OPEN_INTERVAL = 1000;
<T> boolean safeWrite(final ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection,
List<RemoteRxEvent> events,
final MutableReference<Subscription> subReference,
Action0 onSuccessfulWriteCallback,
final Action1<Throwable> onFailedWriteCallback,
final SlottingStrategy<T> slottingStrategyReference,
final WritableEndpoint<T> endpoint) {
boolean writeSuccess = true;
if (checkIsOpenCounter.getAndIncrement() % CHECK_IS_OPEN_INTERVAL == 0) {
if (!connection.isCloseIssued() && connection.getChannel().isActive()) {
writeSuccess = checkWriteableAndWrite(connection, events,
onSuccessfulWriteCallback, onFailedWriteCallback);
} else {
writeSuccess = false;
logger.warn("Detected closed or inactive client connection, force unsubscribe.");
subReference.getValue().unsubscribe();
// release slot
if (slottingStrategyReference != null) {
logger.info("Removing slot for endpoint: " + endpoint);
if (!slottingStrategyReference.removeConnection(endpoint)) {
logger.error("Failed to remove endpoint from slot, endpoint: " + endpoint);
}
}
}
} else {
writeSuccess = checkWriteableAndWrite(connection, events,
onSuccessfulWriteCallback, onFailedWriteCallback);
}
return writeSuccess;
}
private boolean checkWriteableAndWrite(
final ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection,
List<RemoteRxEvent> events, Action0 onSuccessfulWriteCallback,
final Action1<Throwable> onFailedWriteCallback) {
boolean writeSuccess = true;
if (connection.getChannel().isWritable()) {
connection.writeAndFlush(events)
.doOnError(onFailedWriteCallback)
.doOnCompleted(onSuccessfulWriteCallback)
.subscribe();
} else {
writeSuccess = false;
}
return writeSuccess;
}
}
| 8,814 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/RemoteRxServer.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import io.mantisrx.server.core.ServiceRegistry;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.compression.JdkZlibDecoder;
import io.netty.handler.codec.compression.JdkZlibEncoder;
import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.reactivex.mantis.remote.observable.ingress.IngressPolicies;
import io.reactivex.mantis.remote.observable.ingress.IngressPolicy;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import mantis.io.reactivex.netty.RxNetty;
import mantis.io.reactivex.netty.pipeline.PipelineConfigurator;
import mantis.io.reactivex.netty.pipeline.PipelineConfiguratorComposite;
import mantis.io.reactivex.netty.server.RxServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RemoteRxServer {
private static final Logger logger = LoggerFactory.getLogger(RemoteRxServer.class);
private static boolean enableHeartBeating = true;
private static boolean enableNettyLogging = false;
private static boolean enableCompression = true;
private static int maxFrameLength = 5242880; // 5 MB max frame
private static int writeBufferTimeMSec = 100; // 100 millisecond buffer
private RxServer<RemoteRxEvent, List<RemoteRxEvent>> server;
private RxMetrics metrics;
private int port;
RemoteRxServer(RxServer<RemoteRxEvent, List<RemoteRxEvent>> server, RxMetrics metrics) {
this.server = server;
this.metrics = metrics;
loadFastProperties();
}
// Note, this constructor is only to support
// integration with modern implementation
// during migration
public RemoteRxServer() {
metrics = new RxMetrics();
}
@SuppressWarnings("rawtypes")
public RemoteRxServer(Builder builder) {
port = builder.getPort();
// setup configuration state for server
Map<String, ServeConfig> configuredObservables = new HashMap<String, ServeConfig>();
// add configs
for (ServeConfig config : builder.getObservablesConfigured()) {
String observableName = config.getName();
logger.debug("RemoteRxServer configured with remote observable: " + observableName);
configuredObservables.put(observableName, config);
}
metrics = new RxMetrics();
// create server
RxServer<RemoteRxEvent, List<RemoteRxEvent>> server
= RxNetty.newTcpServerBuilder(port, new RemoteObservableConnectionHandler(configuredObservables, builder.getIngressPolicy(),
metrics, writeBufferTimeMSec))
.pipelineConfigurator(new PipelineConfiguratorComposite<RemoteRxEvent, List<RemoteRxEvent>>(
new PipelineConfigurator<RemoteRxEvent, RemoteRxEvent>() {
@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
if (enableNettyLogging) {
pipeline.addFirst(new LoggingHandler(LogLevel.ERROR)); // uncomment to enable debug logging
}
if (enableHeartBeating) {
pipeline.addLast("idleStateHandler", new IdleStateHandler(10, 2, 0));
pipeline.addLast("heartbeat", new HeartbeatHandler());
}
if (enableCompression) {
pipeline.addLast("gzipInflater", new JdkZlibEncoder(ZlibWrapper.GZIP));
pipeline.addLast("gzipDeflater", new JdkZlibDecoder(ZlibWrapper.GZIP));
}
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); // 4 bytes to encode length
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(maxFrameLength, 0, 4, 0, 4)); // max frame = half MB
}
}, new BatchedRxEventPipelineConfigurator()))
.channelOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(1024 * 1024, 5 * 1024 * 1024))
.build();
this.server = server;
logger.info("RemoteRxServer started on port: " + port);
}
public RxMetrics getMetrics() {
return metrics;
}
public void start() {
server.start();
}
public void startAndWait() {
server.startAndWait();
logger.info("RemoteRxServer shutdown on port: " + port);
}
public void shutdown() {
try {
server.shutdown();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
logger.info("RemoteRxServer shutdown on port: " + port);
}
public void blockUntilServerShutdown() {
try {
server.waitTillShutdown();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
logger.info("RemoteRxServer shutdown on port: " + port);
}
private void loadFastProperties() {
String enableHeartBeatingStr =
ServiceRegistry.INSTANCE.getPropertiesService().getStringValue("mantis.netty.enableHeartBeating", "true");
if (enableHeartBeatingStr.equals("false")) {
enableHeartBeating = false;
}
String enableNettyLoggingStr =
ServiceRegistry.INSTANCE.getPropertiesService().getStringValue("mantis.netty.enableLogging", "false");
if (enableNettyLoggingStr.equals("true")) {
enableNettyLogging = true;
}
String enableCompressionStr =
ServiceRegistry.INSTANCE.getPropertiesService().getStringValue("mantis.netty.enableCompression", "true");
if (enableCompressionStr.equals("false")) {
enableCompression = false;
}
String maxFrameLengthStr =
ServiceRegistry.INSTANCE.getPropertiesService().getStringValue("mantis.netty.maxFrameLength", "5242880");
if (maxFrameLengthStr != null && maxFrameLengthStr.length() > 0) {
maxFrameLength = Integer.parseInt(maxFrameLengthStr);
}
String writeBufferTimeMSecStr =
ServiceRegistry.INSTANCE.getPropertiesService().getStringValue("mantis.netty.writeBufferTimeMSec", "100");
if (writeBufferTimeMSecStr != null && writeBufferTimeMSecStr.length() > 0) {
writeBufferTimeMSec = Integer.parseInt(maxFrameLengthStr);
}
}
public static class Builder {
private int port;
@SuppressWarnings("rawtypes")
private Set<ServeConfig> observablesConfigured
= new HashSet<ServeConfig>();
private IngressPolicy ingressPolicy = IngressPolicies.allowAll();
public Builder port(int port) {
this.port = port;
return this;
}
public Builder ingressPolicy(IngressPolicy ingressPolicy) {
this.ingressPolicy = ingressPolicy;
return this;
}
public <T> Builder addObservable(ServeObservable<T> configuration) {
observablesConfigured.add(configuration);
return this;
}
public <T> Builder addObservable(ServeNestedObservable<T> configuration) {
observablesConfigured.add(configuration);
return this;
}
public <K, V> Builder addObservable(ServeGroupedObservable<K, V> configuration) {
observablesConfigured.add(configuration);
return this;
}
public RemoteRxServer build() {
return new RemoteRxServer(this);
}
int getPort() {
return port;
}
@SuppressWarnings("rawtypes")
Set<ServeConfig> getObservablesConfigured() {
return observablesConfigured;
}
IngressPolicy getIngressPolicy() {
return ingressPolicy;
}
}
}
| 8,815 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/EndpointChange.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import io.mantisrx.common.network.Endpoint;
public class EndpointChange {
private final Type type;
private final Endpoint endpoint;
public EndpointChange(final Type type, final Endpoint endpoint) {
this.type = type;
this.endpoint = endpoint;
}
public Type getType() {
return type;
}
public Endpoint getEndpoint() {
return endpoint;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EndpointChange that = (EndpointChange) o;
if (type != that.type) return false;
return endpoint != null ? endpoint.equals(that.endpoint) : that.endpoint == null;
}
@Override
public int hashCode() {
int result = type != null ? type.hashCode() : 0;
result = 31 * result + (endpoint != null ? endpoint.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "EndpointChange{" +
"type=" + type +
", endpoint=" + endpoint +
'}';
}
public enum Type {add, complete}
}
| 8,816 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/MergedObservable.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.subjects.PublishSubject;
import rx.subjects.ReplaySubject;
import rx.subjects.Subject;
public class MergedObservable<T> {
private static final Logger logger = LoggerFactory.getLogger(MergedObservable.class);
private Subject<Observable<T>, Observable<T>> subject;
private MergeCounts counts;
private Map<String, PublishSubject<Integer>> takeUntilSubjects =
new HashMap<String, PublishSubject<Integer>>();
private MergedObservable(int expectedTerminalCount, Subject<Observable<T>, Observable<T>> subject) {
this.subject = subject;
counts = new MergeCounts(expectedTerminalCount);
}
public static <T> MergedObservable<T> create(int expectedTerminalCount) {
return new MergedObservable<T>(expectedTerminalCount, PublishSubject.<Observable<T>>create());
}
public static <T> MergedObservable<T> createWithReplay(int expectedTerminalCount) {
return new MergedObservable<T>(expectedTerminalCount, ReplaySubject.<Observable<T>>create());
}
public synchronized void mergeIn(String key, Observable<T> o) {
if (!takeUntilSubjects.containsKey(key)) {
PublishSubject<Integer> takeUntil = PublishSubject.create();
publishWithCallbacks(key, o.takeUntil(takeUntil), null, null);
takeUntilSubjects.put(key, takeUntil);
} else {
logger.warn("Key alreay exists, ignoring merge request for observable with key: " + key);
}
}
public synchronized void mergeIn(String key, Observable<T> o, Action1<Throwable> errorCallback,
Action0 successCallback) {
if (!takeUntilSubjects.containsKey(key)) {
PublishSubject<Integer> takeUntil = PublishSubject.create();
publishWithCallbacks(key, o.takeUntil(takeUntil), errorCallback, successCallback);
takeUntilSubjects.put(key, takeUntil);
} else {
logger.warn("Key alreay exists, ignoring merge request for observable with key: " + key);
}
}
synchronized void clear() {
takeUntilSubjects.clear();
}
private synchronized void publishWithCallbacks(final String key, Observable<T> o,
final Action1<Throwable> errorCallback, final Action0 successCallback) {
subject.onNext(o
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable t1) {
if (errorCallback != null) {
errorCallback.call(t1);
}
logger.error("Inner observable with key: " + key + " terminated with onError, calling onError() on outer observable." + t1.getMessage(), t1);
takeUntilSubjects.remove(key);
subject.onError(t1);
}
})
.doOnCompleted(new Action0() {
@Override
public void call() {
if (successCallback != null) {
successCallback.call();
}
logger.debug("Inner observable with key: " + key + " completed, incrementing terminal count.");
takeUntilSubjects.remove(key);
if (counts.incrementTerminalCountAndCheck()) {
logger.debug("All inner observables terminated, calling onCompleted() on outer observable.");
subject.onCompleted();
}
}
}));
}
public synchronized void forceComplete(String key) {
PublishSubject<Integer> takeUntil = takeUntilSubjects.get(key);
if (takeUntil != null) {
takeUntil.onNext(1); // complete observable
} else {
logger.debug("Nothing to force complete, key doesn't exist: " + key);
}
}
public synchronized Observable<Observable<T>> get() {
return subject;
}
}
| 8,817 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/RemoteObservableConnectionHandler.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import io.mantisrx.common.codec.Encoder;
import io.mantisrx.common.network.WritableEndpoint;
import io.reactivex.mantis.remote.observable.ingress.IngressPolicy;
import io.reactivex.mantis.remote.observable.slotting.SlottingStrategy;
import io.reactivx.mantis.operators.DisableBackPressureOperator;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import mantis.io.reactivex.netty.channel.ConnectionHandler;
import mantis.io.reactivex.netty.channel.ObservableConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Notification;
import rx.Notification.Kind;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
public class RemoteObservableConnectionHandler implements
ConnectionHandler<RemoteRxEvent, List<RemoteRxEvent>> {
private static final Logger logger = LoggerFactory.getLogger(RemoteObservableConnectionHandler.class);
@SuppressWarnings("rawtypes")
private Map<String, ServeConfig> observables;
private RxMetrics serverMetrics;
private IngressPolicy ingressPolicy;
private int writeBufferTimeMSec;
@SuppressWarnings("rawtypes")
public RemoteObservableConnectionHandler(
Map<String, ServeConfig> observables,
IngressPolicy ingressPolicy,
RxMetrics metrics,
int writeBufferTimeMSec) {
this.observables = observables;
this.ingressPolicy = ingressPolicy;
this.serverMetrics = metrics;
this.writeBufferTimeMSec = writeBufferTimeMSec;
}
@Override
public Observable<Void> handle(final
ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection) {
logger.info("Connection received: " + connection.getChannel().remoteAddress());
if (ingressPolicy.allowed(connection)) {
return setupConnection(connection);
} else {
Exception e = new RemoteObservableException("Connection rejected due to ingress policy");
return Observable.error(e);
}
}
@SuppressWarnings( {"rawtypes", "unchecked"})
private <T> Subscription serveObservable(
final Observable<T> observable,
final ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection,
final RemoteRxEvent event,
final Func1<Map<String, String>, Func1<T, Boolean>> filterFunction,
final Encoder<T> encoder,
final ServeObservable<T> serveConfig,
final WritableEndpoint<Observable<T>> endpoint) {
final MutableReference<Subscription> subReference = new MutableReference<>();
subReference.setValue(
observable
.filter(filterFunction.call(event.getSubscribeParameters()))
.doOnCompleted(new Action0() {
@Override
public void call() {
logger.info("OnCompleted recieved in serveObservable, sending to client.");
}
})
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable t1) {
logger.info("OnError received in serveObservable, sending to client: ", t1);
}
})
.materialize()
.lift(new DisableBackPressureOperator<Notification<T>>())
.buffer(writeBufferTimeMSec, TimeUnit.MILLISECONDS)
.filter(new Func1<List<Notification<T>>, Boolean>() {
@Override
public Boolean call(List<Notification<T>> t1) {
return t1 != null && !t1.isEmpty();
}
})
.map(new Func1<List<Notification<T>>, List<RemoteRxEvent>>() {
@Override
public List<RemoteRxEvent> call(List<Notification<T>> notifications) {
List<RemoteRxEvent> rxEvents = new ArrayList<RemoteRxEvent>(notifications.size());
for (Notification<T> notification : notifications) {
if (notification.getKind() == Notification.Kind.OnNext) {
rxEvents.add(RemoteRxEvent.next(event.getName(), encoder.encode(notification.getValue())));
} else if (notification.getKind() == Notification.Kind.OnError) {
rxEvents.add(RemoteRxEvent.error(event.getName(), RemoteObservable.fromThrowableToBytes(notification.getThrowable())));
} else if (notification.getKind() == Notification.Kind.OnCompleted) {
rxEvents.add(RemoteRxEvent.completed(event.getName()));
} else {
throw new RuntimeException("Unsupported notification kind: " + notification.getKind());
}
}
return rxEvents;
}
})
.filter(new Func1<List<RemoteRxEvent>, Boolean>() {
@Override
public Boolean call(List<RemoteRxEvent> t1) {
return t1 != null && !t1.isEmpty();
}
})
.subscribe(new WriteBytesObserver(connection, subReference, serverMetrics,
serveConfig.getSlottingStrategy(), endpoint)));
return subReference.getValue();
}
@SuppressWarnings( {"unchecked", "rawtypes"})
private <T> Subscription serveNestedObservable(
final Observable<T> observable,
final ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection,
final RemoteRxEvent event,
final Func1<Map<String, String>, Func1<T, Boolean>> filterFunction,
final Encoder<T> encoder,
final ServeNestedObservable<Observable<T>> serveConfig,
final WritableEndpoint<Observable<T>> endpoint) {
final MutableReference<Subscription> subReference = new MutableReference<>();
subReference.setValue(
observable
.filter(filterFunction.call(event.getSubscribeParameters()))
.doOnCompleted(new Action0() {
@Override
public void call() {
logger.info("OnCompleted recieved in serveNestedObservable, sending to client.");
}
})
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable t1) {
logger.info("OnError received in serveNestedObservable, sending to client: ", t1);
}
})
.map(new Func1<T, byte[]>() {
@Override
public byte[] call(T t1) {
return encoder.encode(t1);
}
})
.materialize()
.map(new Func1<Notification<byte[]>, RemoteRxEvent>() {
@Override
public RemoteRxEvent call(Notification<byte[]> notification) {
if (notification.getKind() == Notification.Kind.OnNext) {
return RemoteRxEvent.next(event.getName(), notification.getValue());
} else if (notification.getKind() == Notification.Kind.OnError) {
return RemoteRxEvent.error(event.getName(), RemoteObservable.fromThrowableToBytes(notification.getThrowable()));
} else if (notification.getKind() == Notification.Kind.OnCompleted) {
return RemoteRxEvent.completed(event.getName());
} else {
throw new RuntimeException("Unsupported notification kind: " + notification.getKind());
}
}
})
.lift(new DisableBackPressureOperator<RemoteRxEvent>())
.buffer(writeBufferTimeMSec, TimeUnit.MILLISECONDS)
.filter(new Func1<List<RemoteRxEvent>, Boolean>() {
@Override
public Boolean call(List<RemoteRxEvent> t1) {
return t1 != null && !t1.isEmpty();
}
})
.filter(new Func1<List<RemoteRxEvent>, Boolean>() {
@Override
public Boolean call(List<RemoteRxEvent> t1) {
return t1 != null && !t1.isEmpty();
}
})
.subscribe(new WriteBytesObserver(connection, subReference, serverMetrics,
serveConfig.getSlottingStrategy(), endpoint)));
return subReference.getValue();
}
private <K, V> Subscription serveGroupedObservable(
final Observable<Group<K, V>> groups,
final ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection,
final RemoteRxEvent event,
final Func1<Map<String, String>, Func1<K, Boolean>> filterFunction,
final Encoder<K> keyEncoder,
final Encoder<V> valueEncoder,
final ServeGroupedObservable<K, V> serveConfig,
final WritableEndpoint<GroupedObservable<K, V>> endpoint) {
final MutableReference<Subscription> subReference = new MutableReference<>();
subReference.setValue(groups
// filter out groups based on subscription parameters
.filter(new Func1<Group<K, V>, Boolean>() {
@Override
public Boolean call(Group<K, V> group) {
return filterFunction.call(event.getSubscribeParameters())
.call(group.getKeyValue());
}
})
.doOnCompleted(new Action0() {
@Override
public void call() {
logger.info("OnCompleted recieved in serveGroupedObservable, sending to client.");
}
})
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable t1) {
logger.info("OnError received in serveGroupedObservable, sending to client: ", t1);
}
})
.materialize()
.lift(new DisableBackPressureOperator<Notification<Group<K, V>>>())
.buffer(writeBufferTimeMSec, TimeUnit.MILLISECONDS)
.filter(new Func1<List<Notification<Group<K, V>>>, Boolean>() {
@Override
public Boolean call(List<Notification<Group<K, V>>> t1) {
return t1 != null && !t1.isEmpty();
}
})
.map(new Func1<List<Notification<Group<K, V>>>, List<RemoteRxEvent>>() {
@Override
public List<RemoteRxEvent> call(final List<Notification<Group<K, V>>> groupNotifications) {
List<RemoteRxEvent> rxEvents = new ArrayList<RemoteRxEvent>(groupNotifications.size());
for (Notification<Group<K, V>> groupNotification : groupNotifications) {
if (Kind.OnNext == groupNotification.getKind()) {
// encode inner group notification
Group<K, V> group = groupNotification.getValue();
final int keyLength = group.getKeyBytes().length;
Notification<V> notification = groupNotification.getValue().getNotification();
byte[] data = null;
if (Kind.OnNext == notification.getKind()) {
V value = notification.getValue();
byte[] valueBytes = valueEncoder.encode(value);
// 1 byte for notification type,
// 4 bytes is to encode key length as int
data = ByteBuffer.allocate(1 + 4 + keyLength + valueBytes.length)
.put((byte) 1)
.putInt(keyLength)
.put(group.getKeyBytes())
.put(valueBytes)
.array();
} else if (Kind.OnCompleted == notification.getKind()) {
data = ByteBuffer.allocate(1 + 4 + keyLength)
.put((byte) 2)
.putInt(keyLength)
.put(group.getKeyBytes())
.array();
} else if (Kind.OnError == notification.getKind()) {
Throwable error = notification.getThrowable();
byte[] errorBytes = RemoteObservable.fromThrowableToBytes(error);
data = ByteBuffer.allocate(1 + 4 + keyLength + errorBytes.length)
.put((byte) 3)
.putInt(keyLength)
.put(group.getKeyBytes())
.put(errorBytes)
.array();
}
rxEvents.add(RemoteRxEvent.next(event.getName(), data));
} else if (Kind.OnCompleted == groupNotification.getKind()) {
rxEvents.add(RemoteRxEvent.completed(event.getName()));
} else if (Kind.OnError == groupNotification.getKind()) {
rxEvents.add(RemoteRxEvent.error(event.getName(),
RemoteObservable.fromThrowableToBytes(groupNotification.getThrowable())));
} else {
throw new RuntimeException("Unsupported notification type: " + groupNotification.getKind());
}
}
return rxEvents;
}
})
.filter(new Func1<List<RemoteRxEvent>, Boolean>() {
@Override
public Boolean call(List<RemoteRxEvent> t1) {
return t1 != null && !t1.isEmpty();
}
})
.subscribe(new WriteBytesObserver(connection, subReference, serverMetrics,
serveConfig.getSlottingStrategy(), endpoint)));
return subReference.getValue();
}
@SuppressWarnings( {"unchecked", "rawtypes"})
private void subscribe(final MutableReference<Subscription> unsubscribeCallbackReference,
RemoteRxEvent event, final ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection,
ServeConfig configuration, WritableEndpoint endpoint) {
Func1 filterFunction = configuration.getFilterFunction();
Subscription subscription = null;
if (configuration instanceof ServeObservable) {
ServeObservable serveObservable = (ServeObservable) configuration;
if (serveObservable.isSubscriptionPerConnection()) {
Observable toServe = serveObservable.getObservable();
if (serveObservable.isHotStream()) {
toServe = toServe.share();
}
subscription = serveObservable(toServe, connection,
event, filterFunction, serveObservable.getEncoder(), serveObservable, endpoint);
} else {
subscription = serveObservable(endpoint.read(), connection,
event, filterFunction, serveObservable.getEncoder(), serveObservable, endpoint);
}
} else if (configuration instanceof ServeGroupedObservable) {
ServeGroupedObservable sgo = (ServeGroupedObservable) configuration;
subscription = serveGroupedObservable(endpoint.read(), connection,
event, filterFunction, sgo.getKeyEncoder(), sgo.getValueEncoder(),
sgo, endpoint);
} else if (configuration instanceof ServeNestedObservable) {
ServeNestedObservable serveNestedObservable = (ServeNestedObservable) configuration;
subscription = serveNestedObservable(endpoint.read(), connection,
event, filterFunction, serveNestedObservable.getEncoder(), serveNestedObservable, endpoint);
}
unsubscribeCallbackReference.setValue(subscription);
}
@SuppressWarnings( {"rawtypes", "unchecked"})
private Observable<Void> handleSubscribeRequest(RemoteRxEvent event, final ObservableConnection<RemoteRxEvent,
List<RemoteRxEvent>> connection, MutableReference<SlottingStrategy> slottingStrategyReference,
MutableReference<Subscription> unsubscribeCallbackReference,
MutableReference<WritableEndpoint> slottingIdReference) {
// check if observable exists in configs
String observableName = event.getName();
ServeConfig config = observables.get(observableName);
if (config == null) {
return Observable.error(new RemoteObservableException("No remote observable configuration found for name: " + observableName));
}
if (event.getType() == RemoteRxEvent.Type.subscribed) {
String slotId = null;
Map<String, String> subscriptionParameters = event.getSubscribeParameters();
if (subscriptionParameters != null) {
slotId = subscriptionParameters.get("slotId");
}
InetSocketAddress address = (InetSocketAddress) connection.getChannel().remoteAddress();
WritableEndpoint endpoint = new WritableEndpoint<>(address.getHostName(), address.getPort(), slotId,
connection);
SlottingStrategy slottingStrategy = config.getSlottingStrategy();
slottingIdReference.setValue(endpoint);
slottingStrategyReference.setValue(slottingStrategy);
logger.info("Connection received on server from client endpoint: " + endpoint + ", subscribed to observable: " + observableName);
serverMetrics.incrementSubscribedCount();
subscribe(unsubscribeCallbackReference, event, connection, config, endpoint);
if (!slottingStrategy.addConnection(endpoint)) {
// unable to slot connection
logger.warn("Failed to slot connection for endpoint: " + endpoint);
connection.close(true);
}
}
return Observable.empty();
}
@SuppressWarnings("rawtypes")
private Observable<Void> setupConnection(final ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection) {
// state associated with connection
// used to initiate 'unsubscribe' callback to subscriber
final MutableReference<Subscription> unsubscribeCallbackReference = new MutableReference<Subscription>();
// used to release slot when connection completes
final MutableReference<SlottingStrategy> slottingStrategyReference = new MutableReference<SlottingStrategy>();
// used to get slotId for connection
final MutableReference<WritableEndpoint> slottingIdReference = new MutableReference<WritableEndpoint>();
return connection.getInput()
// filter out unsupported operations
.filter(new Func1<RemoteRxEvent, Boolean>() {
@Override
public Boolean call(RemoteRxEvent event) {
boolean supportedOperation = false;
if (event.getType() == RemoteRxEvent.Type.subscribed ||
event.getType() == RemoteRxEvent.Type.unsubscribed) {
supportedOperation = true;
}
return supportedOperation;
}
})
.flatMap(new Func1<RemoteRxEvent, Observable<Void>>() {
@SuppressWarnings("unchecked")
@Override
public Observable<Void> call(RemoteRxEvent event) {
if (event.getType() == RemoteRxEvent.Type.subscribed) {
return handleSubscribeRequest(event, connection, slottingStrategyReference, unsubscribeCallbackReference,
slottingIdReference);
} else if (event.getType() == RemoteRxEvent.Type.unsubscribed) {
Subscription subscription = unsubscribeCallbackReference.getValue();
if (subscription != null) {
subscription.unsubscribe();
}
serverMetrics.incrementUnsubscribedCount();
// release slot
if (slottingStrategyReference.getValue() != null) {
if (!slottingStrategyReference.getValue().removeConnection(slottingIdReference.getValue())) {
logger.error("Failed to remove endpoint from slot, endpoint: " + slottingIdReference.getValue());
}
}
logger.info("Connection: " + connection.getChannel()
.remoteAddress() + " unsubscribed, closing connection");
connection.close(true);
}
return Observable.empty();
}
});
}
} | 8,818 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/ServeConfig.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import io.reactivex.mantis.remote.observable.slotting.SlottingStrategy;
import java.util.Map;
import rx.functions.Func1;
public abstract class ServeConfig<T, O> {
SlottingStrategy<O> slottingStrategy;
private String name;
private Func1<Map<String, String>, Func1<T, Boolean>> filterFunction;
private int maxWriteAttempts;
public ServeConfig(String name,
SlottingStrategy<O> slottingStrategy, Func1<Map<String, String>,
Func1<T, Boolean>> filterFunction, int maxWriteAttempts) {
this.name = name;
this.slottingStrategy = slottingStrategy;
this.filterFunction = filterFunction;
this.maxWriteAttempts = maxWriteAttempts;
}
public int getMaxWriteAttempts() {
return maxWriteAttempts;
}
public String getName() {
return name;
}
public SlottingStrategy<O> getSlottingStrategy() {
return slottingStrategy;
}
public Func1<Map<String, String>, Func1<T, Boolean>> getFilterFunction() {
return filterFunction;
}
}
| 8,819 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/DynamicConnectionSet.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import io.mantisrx.common.MantisGroup;
import io.mantisrx.common.metrics.Gauge;
import io.mantisrx.common.metrics.Metrics;
import io.mantisrx.common.network.Endpoint;
import io.reactivex.mantis.remote.observable.reconciliator.ConnectionSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.jctools.queues.SpscArrayQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.Observer;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.functions.Func3;
import rx.observables.GroupedObservable;
import rx.subjects.PublishSubject;
public class DynamicConnectionSet<T> implements ConnectionSet<T> {
private static final Logger logger = LoggerFactory.getLogger(DynamicConnectionSet.class);
private static final SpscArrayQueue<MantisGroup<?, ?>> inputQueue = new SpscArrayQueue<MantisGroup<?, ?>>(1000);
private static int MIN_TIME_SEC_DEFAULT = 1;
private static int MAX_TIME_SEC_DEFAULT = 10;
private EndpointInjector endpointInjector;
private PublishSubject<EndpointChange> reconciliatorConnector = PublishSubject.create();
private Func3<Endpoint, Action0, PublishSubject<Integer>, RemoteRxConnection<T>> toObservableFunc;
private Metrics connectionMetrics;
private PublishSubject<Set<Endpoint>> activeConnectionsSubject = PublishSubject.create();
private Lock activeConnectionsLock = new ReentrantLock();
private Map<String, Endpoint> currentActiveConnections = new HashMap<>();
private int minTimeoutOnUnexpectedTerminateSec;
private int maxTimeoutOnUnexpectedTerminateSec;
private Gauge activeConnectionsGauge;
private Gauge closedConnections;
private Gauge forceCompletedConnections;
private Random random = new Random();
public DynamicConnectionSet(Func3<Endpoint, Action0, PublishSubject<Integer>, RemoteRxConnection<T>>
toObservableFunc, int minTimeoutOnUnexpectedTerminateSec, int maxTimeoutOnUnexpectedTerminateSec) {
this.toObservableFunc = toObservableFunc;
connectionMetrics = new Metrics.Builder()
.name("DynamicConnectionSet")
.addGauge("activeConnections")
.addGauge("closedConnections")
.addGauge("forceCompletedConnections")
.build();
activeConnectionsGauge = connectionMetrics.getGauge("activeConnections");
closedConnections = connectionMetrics.getGauge("closedConnections");
forceCompletedConnections = connectionMetrics.getGauge("forceCompletedConnections");
this.minTimeoutOnUnexpectedTerminateSec = minTimeoutOnUnexpectedTerminateSec;
this.maxTimeoutOnUnexpectedTerminateSec = maxTimeoutOnUnexpectedTerminateSec;
}
public DynamicConnectionSet(Func3<Endpoint, Action0, PublishSubject<Integer>, RemoteRxConnection<T>>
toObservableFunc) {
this(toObservableFunc, MIN_TIME_SEC_DEFAULT, MAX_TIME_SEC_DEFAULT);
}
public static <K, V> DynamicConnectionSet<GroupedObservable<K, V>> create(
final ConnectToGroupedObservable.Builder<K, V> config, int maxTimeBeforeDisconnectSec) {
Func3<Endpoint, Action0, PublishSubject<Integer>, RemoteRxConnection<GroupedObservable<K, V>>> toObservableFunc = new
Func3<Endpoint, Action0, PublishSubject<Integer>, RemoteRxConnection<GroupedObservable<K, V>>>() {
@Override
public RemoteRxConnection<GroupedObservable<K, V>> call(Endpoint endpoint, Action0 disconnectCallback,
PublishSubject<Integer> closeConnectionTrigger) {
// copy config, change host, port and id
ConnectToGroupedObservable.Builder<K, V> configCopy = new ConnectToGroupedObservable.Builder<K, V>(config);
configCopy
.host(endpoint.getHost())
.port(endpoint.getPort())
.closeTrigger(closeConnectionTrigger)
.connectionDisconnectCallback(disconnectCallback)
.slotId(endpoint.getSlotId());
return RemoteObservable.connect(configCopy.build());
}
};
return new DynamicConnectionSet<GroupedObservable<K, V>>(toObservableFunc, MIN_TIME_SEC_DEFAULT, maxTimeBeforeDisconnectSec);
}
// NJ
public static <K, V> DynamicConnectionSet<MantisGroup<K, V>> createMGO(
final ConnectToGroupedObservable.Builder<K, V> config, int maxTimeBeforeDisconnectSec, final SpscArrayQueue<MantisGroup<?, ?>> inputQueue) {
Func3<Endpoint, Action0, PublishSubject<Integer>, RemoteRxConnection<MantisGroup<K, V>>> toObservableFunc
= new Func3<Endpoint, Action0, PublishSubject<Integer>, RemoteRxConnection<MantisGroup<K, V>>>() {
@Override
public RemoteRxConnection<MantisGroup<K, V>> call(Endpoint endpoint, Action0 disconnectCallback,
PublishSubject<Integer> closeConnectionTrigger) {
// copy config, change host, port and id
ConnectToGroupedObservable.Builder<K, V> configCopy = new ConnectToGroupedObservable.Builder<K, V>(config);
configCopy
.host(endpoint.getHost())
.port(endpoint.getPort())
.closeTrigger(closeConnectionTrigger)
.connectionDisconnectCallback(disconnectCallback)
.slotId(endpoint.getSlotId());
return RemoteObservable.connectToMGO(configCopy.build(), inputQueue);
}
};
return new DynamicConnectionSet<MantisGroup<K, V>>(toObservableFunc, MIN_TIME_SEC_DEFAULT, maxTimeBeforeDisconnectSec);
}
public static <K, V> DynamicConnectionSet<GroupedObservable<K, V>> create(
final ConnectToGroupedObservable.Builder<K, V> config) {
return create(config, MAX_TIME_SEC_DEFAULT);
}
// NJ
public static <K, V> DynamicConnectionSet<MantisGroup<K, V>> createMGO(
final ConnectToGroupedObservable.Builder<K, V> config) {
return createMGO(config, MAX_TIME_SEC_DEFAULT, inputQueue);
}
public static <T> DynamicConnectionSet<T> create(
final ConnectToObservable.Builder<T> config, int maxTimeBeforeDisconnectSec) {
Func3<Endpoint, Action0, PublishSubject<Integer>, RemoteRxConnection<T>> toObservableFunc = new
Func3<Endpoint, Action0, PublishSubject<Integer>, RemoteRxConnection<T>>() {
@Override
public RemoteRxConnection<T> call(Endpoint endpoint, Action0 disconnectCallback,
PublishSubject<Integer> closeConnectionTrigger) {
// copy config, change host, port and id
ConnectToObservable.Builder<T> configCopy = new ConnectToObservable.Builder<T>(config);
configCopy
.host(endpoint.getHost())
.port(endpoint.getPort())
.closeTrigger(closeConnectionTrigger)
.connectionDisconnectCallback(disconnectCallback)
.slotId(endpoint.getSlotId());
return RemoteObservable.connect(configCopy.build());
}
};
return new DynamicConnectionSet<T>(toObservableFunc, MIN_TIME_SEC_DEFAULT, maxTimeBeforeDisconnectSec);
}
public static <T> DynamicConnectionSet<T> create(
final ConnectToObservable.Builder<T> config) {
return create(config, MAX_TIME_SEC_DEFAULT);
}
public void setEndpointInjector(EndpointInjector endpointInjector) {
this.endpointInjector = endpointInjector;
}
public Observer<EndpointChange> reconciliatorObserver() {
return reconciliatorConnector;
}
public Metrics getConnectionMetrics() {
return connectionMetrics;
}
public Observable<Observable<T>> observables() {
return
endpointInjector
.deltas()
.doOnCompleted(() -> logger.info("onComplete on injector deltas"))
.doOnError(t -> logger.error("caught unexpected error {}", t.getMessage(), t))
.doOnSubscribe(new Action0() {
@Override
public void call() {
logger.info("Subscribing, clearing active connection set");
resetActiveConnections();
}
})
.groupBy(t1 -> Endpoint.uniqueHost(t1.getEndpoint().getHost(), t1.getEndpoint().getPort(), t1.getEndpoint().getSlotId()))
.flatMap(new Func1<GroupedObservable<String, EndpointChange>, Observable<Observable<T>>>() {
@Override
public Observable<Observable<T>> call(
final GroupedObservable<String, EndpointChange> group) {
final PublishSubject<Integer> closeConnectionTrigger = PublishSubject.create();
return group
.doOnNext(new Action1<EndpointChange>() {
@Override
public void call(EndpointChange change) {
// side effect to force complete
if (EndpointChange.Type.complete == change.getType() &&
activeConnectionsContains(group.getKey(), change.getEndpoint())) {
logger.info("Received complete request, removing connection from active set, " + change.getEndpoint().getHost() +
" port: " + change.getEndpoint().getPort() + " id: " + change.getEndpoint().getSlotId());
forceCompletedConnections.increment();
removeConnection(group.getKey(), change.getEndpoint());
closeConnectionTrigger.onNext(1);
}
}
})
.filter(new Func1<EndpointChange, Boolean>() {
@Override
public Boolean call(EndpointChange change) {
// active connection check is to ensure
// latent adds are not allowed. This can
// occur if dynamicConnection set
// and reconciliator are chained together.
// Reconciliator will "see" changes
// before dynamic connection set add will
// assume connection is missing from set
boolean contains = activeConnectionsContains(group.getKey(), change.getEndpoint());
if (contains) {
logger.info("Skipping latent add for endpoint, already in active set: " + change);
}
return EndpointChange.Type.add == change.getType() &&
!contains;
}
})
.map(new Func1<EndpointChange, Observable<T>>() {
@Override
public Observable<T> call(final EndpointChange toAdd) {
logger.info("Received add request, adding connection to active set, " + toAdd.getEndpoint().getHost() +
" port: " + toAdd.getEndpoint().getPort() + ", with client id: " + toAdd.getEndpoint().getSlotId());
addConnection(group.getKey(), toAdd.getEndpoint());
Action0 disconnectCallback = new Action0() {
@Override
public void call() {
int timeToWait = random.nextInt((maxTimeoutOnUnexpectedTerminateSec - minTimeoutOnUnexpectedTerminateSec) + 1)
+ minTimeoutOnUnexpectedTerminateSec;
logger.info("Connection disconnected, waiting " + timeToWait + " seconds before removing from active set of connections: " + toAdd);
Observable.timer(timeToWait, TimeUnit.SECONDS)
.doOnCompleted(new Action0() {
@Override
public void call() {
logger.warn("Removing connection from active set, " + toAdd);
closedConnections.increment();
removeConnection(group.getKey(), toAdd.getEndpoint());
}
}).subscribe();
}
};
RemoteRxConnection<T> connection = toObservableFunc.call(toAdd.getEndpoint(), disconnectCallback,
closeConnectionTrigger);
return connection.getObservable()
.doOnCompleted(toAdd.getEndpoint().getCompletedCallback())
.doOnError(toAdd.getEndpoint().getErrorCallback());
}
});
}
});
}
public Observable<Set<Endpoint>> activeConnections() {
return activeConnectionsSubject;
}
public boolean activeConnectionsContains(String id, Endpoint endpoint) {
try {
activeConnectionsLock.lock();
return currentActiveConnections.containsKey(id);
} finally {
activeConnectionsLock.unlock();
}
}
public void resetActiveConnections() {
try {
activeConnectionsLock.lock();
currentActiveConnections.clear();
activeConnectionsGauge.set(0);
activeConnectionsSubject.onNext(new HashSet<Endpoint>());
} finally {
activeConnectionsLock.unlock();
}
}
public void addConnection(String id, Endpoint toAdd) {
try {
activeConnectionsLock.lock();
if (!currentActiveConnections.containsKey(id)) {
currentActiveConnections.put(id, new Endpoint(toAdd.getHost(),
toAdd.getPort(), toAdd.getSlotId(),
toAdd.getCompletedCallback(),
toAdd.getErrorCallback()));
activeConnectionsGauge.increment();
activeConnectionsSubject.onNext(new HashSet<Endpoint>(currentActiveConnections.values()));
}
} finally {
activeConnectionsLock.unlock();
}
}
public void removeConnection(String id, Endpoint toRemove) {
try {
activeConnectionsLock.lock();
if (currentActiveConnections.containsKey(id)) {
currentActiveConnections.remove(id);
activeConnectionsGauge.decrement();
activeConnectionsSubject.onNext(new HashSet<Endpoint>(currentActiveConnections.values()));
}
} finally {
activeConnectionsLock.unlock();
}
}
}
| 8,820 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/RemoteObservable.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import com.mantisrx.common.utils.NettyUtils;
import io.mantisrx.common.MantisGroup;
import io.mantisrx.common.codec.Decoder;
import io.mantisrx.common.codec.Encoder;
import io.mantisrx.server.core.ServiceRegistry;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.compression.JdkZlibDecoder;
import io.netty.handler.codec.compression.JdkZlibEncoder;
import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.reactivex.mantis.remote.observable.ingress.IngressPolicies;
import io.reactivex.mantis.remote.observable.ingress.IngressPolicy;
import io.reactivx.mantis.operators.DropOperator;
import io.reactivx.mantis.operators.GroupedObservableUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.TimeUnit;
import mantis.io.reactivex.netty.RxNetty;
import mantis.io.reactivex.netty.channel.ObservableConnection;
import mantis.io.reactivex.netty.pipeline.PipelineConfigurator;
import mantis.io.reactivex.netty.pipeline.PipelineConfiguratorComposite;
import org.jctools.queues.SpscArrayQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Notification;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Observer;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.observables.GroupedObservable;
public class RemoteObservable {
private static final Logger logger = LoggerFactory.getLogger(RemoteObservable.class);
private static boolean enableHeartBeating = true;
private static boolean enableNettyLogging = false;
private static boolean enableCompression = true;
private static int maxFrameLength = 5242880; // 5 MB max frame
// NJ
static {
NettyUtils.setNettyThreads();
}
private RemoteObservable() { }
private static void loadFastProperties() {
String enableHeartBeatingStr =
ServiceRegistry.INSTANCE.getPropertiesService().getStringValue("mantis.netty.enableHeartBeating", "true");
if (enableHeartBeatingStr.equals("false")) {
enableHeartBeating = false;
}
String enableNettyLoggingStr =
ServiceRegistry.INSTANCE.getPropertiesService().getStringValue("mantis.netty.enableLogging", "false");
if (enableNettyLoggingStr.equals("true")) {
enableNettyLogging = true;
}
String enableCompressionStr =
ServiceRegistry.INSTANCE.getPropertiesService().getStringValue("mantis.netty.enableCompression", "true");
if (enableCompressionStr.equals("false")) {
enableCompression = false;
}
String maxFrameLengthStr =
ServiceRegistry.INSTANCE.getPropertiesService().getStringValue("mantis.netty.maxFrameLength", "5242880");
if (maxFrameLengthStr != null && maxFrameLengthStr.length() > 0) {
maxFrameLength = Integer.parseInt(maxFrameLengthStr);
}
}
private static Func1<? super Observable<? extends Throwable>, ? extends Observable<?>> retryLogic(final
ConnectToConfig params) {
return new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(
Observable<? extends Throwable> attempts) {
return
attempts
.zipWith(Observable.range(1, params.getSubscribeAttempts())
, new Func2<Throwable, Integer, ThrowableWithCount>() {
@Override
public ThrowableWithCount call(Throwable t1, Integer retryAttempt) {
return new ThrowableWithCount(t1, retryAttempt);
}
})
.flatMap(new Func1<ThrowableWithCount, Observable<?>>() {
@Override
public Observable<?> call(ThrowableWithCount notificationWithCount) {
logger.debug("Failed to subscribe to remote observable: " + params.getName(),
notificationWithCount.getThrowable());
logger.info("Failed to subscribe to remote observable: " + params.getName() + ""
+ " at host: " + params.getHost() + " on port: " + params.getPort() + " subscribe "
+ "attempt: " + notificationWithCount.getCount() + " of: " + params.getSubscribeAttempts());
if (notificationWithCount.getCount() == params.getSubscribeAttempts()) {
Throwable t = notificationWithCount.getThrowable();
if (t != null) {
return Observable.error(notificationWithCount.getThrowable());
}
}
return Observable.timer(notificationWithCount.getCount(), TimeUnit.SECONDS);
}
});
}
};
}
public static <T> RemoteRxConnection<T> connect(final ConnectToObservable<T> params) {
final RxMetrics metrics = new RxMetrics();
return new RemoteRxConnection<T>(Observable.create(new OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> subscriber) {
RemoteUnsubscribe remoteUnsubscribe = new RemoteUnsubscribe(params.getName());
// wrapped in Observable.create() to inject unsubscribe callback
subscriber.add(remoteUnsubscribe); // unsubscribed callback
// create connection
createTcpConnectionToServer(params, remoteUnsubscribe, metrics,
params.getConnectionDisconnectCallback(),
params.getCloseTrigger())
.subscribe(subscriber);
}
}), metrics, params.getCloseTrigger());
}
public static <K, V> RemoteRxConnection<GroupedObservable<K, V>> connect(
final ConnectToGroupedObservable<K, V> config) {
final RxMetrics metrics = new RxMetrics();
return new RemoteRxConnection<GroupedObservable<K, V>>(Observable.create(
new OnSubscribe<GroupedObservable<K, V>>() {
@Override
public void call(Subscriber<? super GroupedObservable<K, V>> subscriber) {
RemoteUnsubscribe remoteUnsubscribe = new RemoteUnsubscribe(config.getName());
// wrapped in Observable.create() to inject unsubscribe callback
subscriber.add(remoteUnsubscribe); // unsubscribed callback
// create connection
createTcpConnectionToServer(config, remoteUnsubscribe, metrics,
config.getConnectionDisconnectCallback(),
config.getCloseTrigger())
.retryWhen(retryLogic(config))
.subscribe(subscriber);
}
}), metrics, config.getCloseTrigger());
}
// NJ
public static <K, V> RemoteRxConnection<MantisGroup<K, V>> connectToMGO(
final ConnectToGroupedObservable<K, V> config, final SpscArrayQueue<MantisGroup<?, ?>> inputQueue) {
final RxMetrics metrics = new RxMetrics();
return new RemoteRxConnection<MantisGroup<K, V>>(Observable.create(
new OnSubscribe<MantisGroup<K, V>>() {
@Override
public void call(Subscriber<? super MantisGroup<K, V>> subscriber) {
RemoteUnsubscribe remoteUnsubscribe = new RemoteUnsubscribe(config.getName());
// wrapped in Observable.create() to inject unsubscribe callback
subscriber.add(remoteUnsubscribe); // unsubscribed callback
// create connection
createTcpConnectionToGOServer(config, remoteUnsubscribe, metrics,
config.getConnectionDisconnectCallback(),
config.getCloseTrigger(),
inputQueue)
.retryWhen(retryLogic(config))
.subscribe(subscriber);
}
}), metrics, config.getCloseTrigger());
}
public static <T> Observable<T> connect(final String host, final int port, final Decoder<T> decoder) {
return connect(new ConnectToObservable.Builder<T>()
.host(host)
.port(port)
.decoder(decoder)
.build()).getObservable();
}
private static <K, V> Observable<GroupedObservable<K, V>> createTcpConnectionToServer(final ConnectToGroupedObservable<K, V> params,
final RemoteUnsubscribe remoteUnsubscribe, final RxMetrics metrics,
final Action0 connectionDisconnectCallback, Observable<Integer> closeTrigger) {
final Decoder<K> keyDecoder = params.getKeyDecoder();
final Decoder<V> valueDecoder = params.getValueDecoder();
loadFastProperties();
return
RxNetty.createTcpClient(params.getHost(), params.getPort(), new PipelineConfiguratorComposite<RemoteRxEvent, List<RemoteRxEvent>>(
new PipelineConfigurator<RemoteRxEvent, List<RemoteRxEvent>>() {
@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
if (enableNettyLogging) {
pipeline.addFirst(new LoggingHandler(LogLevel.ERROR)); // uncomment to enable debug logging
}
if (enableHeartBeating) {
pipeline.addLast("idleStateHandler", new IdleStateHandler(10, 2, 0));
pipeline.addLast("heartbeat", new HeartbeatHandler());
}
if (enableCompression) {
pipeline.addLast("gzipInflater", new JdkZlibEncoder(ZlibWrapper.GZIP));
pipeline.addLast("gzipDeflater", new JdkZlibDecoder(ZlibWrapper.GZIP));
}
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); // 4 bytes to encode length
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(maxFrameLength, 0, 4, 0, 4)); // max frame = half MB
}
}, new BatchedRxEventPipelineConfigurator()))
.connect()
// send subscription request, get input stream
.flatMap(new Func1<ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>>, Observable<RemoteRxEvent>>() {
@Override
public Observable<RemoteRxEvent> call(final ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection) {
connection.writeAndFlush(RemoteRxEvent.subscribed(params.getName(), params.getSubscribeParameters())); // send subscribe event to server
remoteUnsubscribe.setConnection(connection);
return connection.getInput()
.lift(new DropOperator<RemoteRxEvent>("incoming_" + RemoteObservable.class.getCanonicalName() + "_createTcpConnectionToServerGroups"));
}
})
.doOnCompleted(new Action0() {
@Override
public void call() {
// connection completed
logger.warn("Detected connection completed when trying to connect to host: " + params.getHost() + " port: " + params.getPort());
connectionDisconnectCallback.call();
}
})
.onErrorResumeNext(new Func1<Throwable, Observable<RemoteRxEvent>>() {
@Override
public Observable<RemoteRxEvent> call(Throwable t1) {
logger.warn("Detected connection error when trying to connect to host: " + params.getHost() + " port: " + params.getPort(), t1);
connectionDisconnectCallback.call();
// complete if error occurs
return Observable.empty();
}
})
.takeUntil(closeTrigger)
// data received from server
.map(new Func1<RemoteRxEvent, Notification<byte[]>>() {
@Override
public Notification<byte[]> call(RemoteRxEvent rxEvent) {
if (rxEvent.getType() == RemoteRxEvent.Type.next) {
metrics.incrementNextCount();
return Notification.createOnNext(rxEvent.getData());
} else if (rxEvent.getType() == RemoteRxEvent.Type.error) {
metrics.incrementErrorCount();
return Notification.createOnError(fromBytesToThrowable(rxEvent.getData()));
} else if (rxEvent.getType() == RemoteRxEvent.Type.completed) {
metrics.incrementCompletedCount();
return Notification.createOnCompleted();
} else {
throw new RuntimeException("RemoteRxEvent of type:" + rxEvent.getType() + ", not supported.");
}
}
})
.<byte[]>dematerialize()
.groupBy(
new Func1<byte[], K>() {
@Override
public K call(byte[] bytes) {
ByteBuffer buff = ByteBuffer.wrap((byte[]) bytes);
buff.get(); // ignore notification type in key selector
int keyLength = buff.getInt();
byte[] key = new byte[keyLength];
buff.get(key);
return keyDecoder.decode(key);
}
}
, new Func1<byte[], Notification<V>>() {
@Override
public Notification<V> call(byte[] bytes) {
ByteBuffer buff = ByteBuffer.wrap((byte[]) bytes);
byte notificationType = buff.get();
if (notificationType == 1) {
int keyLength = buff.getInt();
int end = buff.limit();
int dataLength = end - 4 - 1 - keyLength;
byte[] valueBytes = new byte[dataLength];
buff.position(4 + 1 + keyLength);
buff.get(valueBytes, 0, dataLength);
V value = valueDecoder.decode(valueBytes);
return Notification.createOnNext(value);
} else if (notificationType == 2) {
return Notification.createOnCompleted();
} else if (notificationType == 3) {
int keyLength = buff.getInt();
int end = buff.limit();
int dataLength = end - 4 - 1 - keyLength;
byte[] errorBytes = new byte[dataLength];
buff.position(4 + 1 + keyLength);
buff.get(errorBytes, 0, dataLength);
return Notification.createOnError(fromBytesToThrowable(errorBytes));
} else {
throw new RuntimeException("Notification encoding not support: " + notificationType);
}
}
})
.map(new Func1<GroupedObservable<K, Notification<V>>, GroupedObservable<K, V>>() {
@Override
public GroupedObservable<K, V> call(
GroupedObservable<K, Notification<V>> group) {
return GroupedObservableUtils.createGroupedObservable(
group.getKey(), group.<V>dematerialize());
}
})
.doOnEach(new Observer<GroupedObservable<K, V>>() {
@Override
public void onCompleted() {
logger.info("RemoteRxEvent, name: {} onCompleted()", params.getName());
}
@Override
public void onError(Throwable e) {
logger.error("RemoteRxEvent, name: {} onError()", params.getName(), e);
}
@Override
public void onNext(GroupedObservable<K, V> group) {
if (logger.isDebugEnabled()) {
logger.debug("RemoteRxEvent, name: {} new key: {}", params.getName(), group.getKey());
}
}
});
}
private static <K, V> Observable<MantisGroup<K, V>> createTcpConnectionToGOServer(final ConnectToGroupedObservable<K, V> params,
final RemoteUnsubscribe remoteUnsubscribe, final RxMetrics metrics,
final Action0 connectionDisconnectCallback, Observable<Integer> closeTrigger,
final SpscArrayQueue<MantisGroup<?, ?>> inputQueue) {
final Decoder<K> keyDecoder = params.getKeyDecoder();
final Decoder<V> valueDecoder = params.getValueDecoder();
loadFastProperties();
return
RxNetty.createTcpClient(params.getHost(), params.getPort(), new PipelineConfiguratorComposite<RemoteRxEvent, List<RemoteRxEvent>>(
new PipelineConfigurator<RemoteRxEvent, List<RemoteRxEvent>>() {
@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
if (enableNettyLogging) {
pipeline.addFirst(new LoggingHandler(LogLevel.ERROR)); // uncomment to enable debug logging
}
if (enableHeartBeating) {
pipeline.addLast("idleStateHandler", new IdleStateHandler(10, 2, 0));
pipeline.addLast("heartbeat", new HeartbeatHandler());
}
if (enableCompression) {
pipeline.addLast("gzipInflater", new JdkZlibEncoder(ZlibWrapper.GZIP));
pipeline.addLast("gzipDeflater", new JdkZlibDecoder(ZlibWrapper.GZIP));
}
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); // 4 bytes to encode length
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(maxFrameLength, 0, 4, 0, 4)); // max frame = half MB
}
}, new BatchedRxEventPipelineConfigurator()))
.connect()
// send subscription request, get input stream
.flatMap(new Func1<ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>>, Observable<RemoteRxEvent>>() {
@Override
public Observable<RemoteRxEvent> call(final ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection) {
connection.writeAndFlush(RemoteRxEvent.subscribed(params.getName(), params.getSubscribeParameters())); // send subscribe event to server
remoteUnsubscribe.setConnection(connection);
return connection.getInput()
.lift(new DropOperator<RemoteRxEvent>("incoming_" + RemoteObservable.class.getCanonicalName() + "_createTcpConnectionToServerGroups"));
}
})
.doOnCompleted(new Action0() {
@Override
public void call() {
// connection completed
logger.warn("Detected connection completed when trying to connect to host: " + params.getHost() + " port: " + params.getPort());
connectionDisconnectCallback.call();
}
})
.onErrorResumeNext(new Func1<Throwable, Observable<RemoteRxEvent>>() {
@Override
public Observable<RemoteRxEvent> call(Throwable t1) {
logger.warn("Detected connection error when trying to connect to host: " + params.getHost() + " port: " + params.getPort(), t1);
connectionDisconnectCallback.call();
// complete if error occurs
return Observable.empty();
}
})
.takeUntil(closeTrigger)
.filter(new Func1<RemoteRxEvent, Boolean>() {
@Override
public Boolean call(RemoteRxEvent rxEvent) {
return (rxEvent.getType() == RemoteRxEvent.Type.next);
}
})
// data received from server
.map(new Func1<RemoteRxEvent, Notification<byte[]>>() {
@Override
public Notification<byte[]> call(RemoteRxEvent rxEvent) {
metrics.incrementNextCount();
return Notification.createOnNext(rxEvent.getData());
}
})
.<byte[]>dematerialize()
.map(new Func1<byte[], MantisGroup<K, V>>() {
@Override
public MantisGroup<K, V> call(byte[] bytes) {
ByteBuffer buff = ByteBuffer.wrap((byte[]) bytes);
buff.get(); // ignore notification type in key selector
int keyLength = buff.getInt();
byte[] key = new byte[keyLength];
buff.get(key);
K keyVal = keyDecoder.decode(key);
V value = null;
buff = ByteBuffer.wrap((byte[]) bytes);
byte notificationType = buff.get();
if (notificationType == 1) {
//int keyLength = buff.getInt();
int end = buff.limit();
int dataLength = end - 4 - 1 - keyLength;
byte[] valueBytes = new byte[dataLength];
buff.position(4 + 1 + keyLength);
buff.get(valueBytes, 0, dataLength);
value = valueDecoder.decode(valueBytes);
} else {
throw new RuntimeException("Notification encoding not support: " + notificationType);
}
return new MantisGroup<K, V>(keyVal, value);
}
})
.doOnEach(new Observer<MantisGroup<K, V>>() {
@Override
public void onCompleted() {
logger.info("RemoteRxEvent, name: " + params.getName() + " onCompleted()");
}
@Override
public void onError(Throwable e) {
logger.error("RemoteRxEvent, name: " + params.getName() + " onError()", e);
}
@Override
public void onNext(MantisGroup<K, V> group) {
if (logger.isDebugEnabled()) {
logger.debug("RemoteRxEvent, name: " + params.getName() + " new key: " + group.getKeyValue());
}
}
});
}
private static <T> Observable<T> createTcpConnectionToServer(final ConnectToObservable<T> params,
final RemoteUnsubscribe remoteUnsubscribe, final RxMetrics metrics,
final Action0 connectionDisconnectCallback, Observable<Integer> closeTrigger) {
final Decoder<T> decoder = params.getDecoder();
loadFastProperties();
return
RxNetty.createTcpClient(params.getHost(), params.getPort(), new PipelineConfiguratorComposite<RemoteRxEvent, List<RemoteRxEvent>>(
new PipelineConfigurator<RemoteRxEvent, List<RemoteRxEvent>>() {
@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
if (enableNettyLogging) {
pipeline.addFirst(new LoggingHandler(LogLevel.ERROR)); // uncomment to enable debug logging
}
if (enableHeartBeating) {
pipeline.addLast("idleStateHandler", new IdleStateHandler(10, 2, 0));
pipeline.addLast("heartbeat", new HeartbeatHandler());
}
if (enableCompression) {
pipeline.addLast("gzipInflater", new JdkZlibEncoder(ZlibWrapper.GZIP));
pipeline.addLast("gzipDeflater", new JdkZlibDecoder(ZlibWrapper.GZIP));
}
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); // 4 bytes to encode length
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(maxFrameLength, 0, 4, 0, 4)); // max frame = half MB
}
}, new BatchedRxEventPipelineConfigurator()))
.connect()
// send subscription request, get input stream
.flatMap(new Func1<ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>>, Observable<RemoteRxEvent>>() {
@Override
public Observable<RemoteRxEvent> call(final ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection) {
connection.writeAndFlush(RemoteRxEvent.subscribed(params.getName(), params.getSubscribeParameters())); // send subscribe event to server
remoteUnsubscribe.setConnection(connection);
return connection.getInput()
.lift(new DropOperator<RemoteRxEvent>("incoming_" + RemoteObservable.class.getCanonicalName() + "_createTcpConnectionToServer"));
}
})
.doOnCompleted(new Action0() {
@Override
public void call() {
// connection completed
logger.warn("Detected connection completed when trying to connect to host: " + params.getHost() + " port: " + params.getPort());
connectionDisconnectCallback.call();
}
})
.onErrorResumeNext(new Func1<Throwable, Observable<RemoteRxEvent>>() {
@Override
public Observable<RemoteRxEvent> call(Throwable t1) {
logger.warn("Detected connection error when trying to connect to host: " + params.getHost() + " port: " + params.getPort(), t1);
connectionDisconnectCallback.call();
// complete if error occurs
return Observable.empty();
}
})
.takeUntil(closeTrigger)
.map(new Func1<RemoteRxEvent, Notification<T>>() {
@Override
public Notification<T> call(RemoteRxEvent rxEvent) {
if (rxEvent.getType() == RemoteRxEvent.Type.next) {
metrics.incrementNextCount();
return Notification.createOnNext(decoder.decode(rxEvent.getData()));
} else if (rxEvent.getType() == RemoteRxEvent.Type.error) {
metrics.incrementErrorCount();
return Notification.createOnError(fromBytesToThrowable(rxEvent.getData()));
} else if (rxEvent.getType() == RemoteRxEvent.Type.completed) {
metrics.incrementCompletedCount();
return Notification.createOnCompleted();
} else {
throw new RuntimeException("RemoteRxEvent of type: " + rxEvent.getType() + ", not supported.");
}
}
})
.<T>dematerialize()
.doOnEach(new Observer<T>() {
@Override
public void onCompleted() {
logger.info("RemoteRxEvent: " + params.getName() + " onCompleted()");
}
@Override
public void onError(Throwable e) {
logger.error("RemoteRxEvent: " + params.getName() + " onError()", e);
}
@Override
public void onNext(T t) {
if (logger.isDebugEnabled()) {
logger.debug("RemoteRxEvent: " + params.getName() + " onNext(): " + t);
}
}
});
}
public static <T> RemoteRxServer serve(int port, final Observable<T> observable, final Encoder<T> encoder) {
return new RemoteRxServer(configureServerFromParams(null, port, observable, encoder,
IngressPolicies.allowAll()));
}
public static <T> RemoteRxServer serve(int port, String name, final Observable<T> observable, final Encoder<T> encoder) {
return new RemoteRxServer(configureServerFromParams(name, port, observable, encoder,
IngressPolicies.allowAll()));
}
private static <T> RemoteRxServer.Builder configureServerFromParams(String name, int port, Observable<T> observable,
Encoder<T> encoder, IngressPolicy ingressPolicy) {
return new RemoteRxServer
.Builder()
.port(port)
.ingressPolicy(ingressPolicy)
.addObservable(new ServeObservable.Builder<T>()
.name(name)
.encoder(encoder)
.observable(observable)
.subscriptionPerConnection()
.build());
}
static byte[] fromThrowableToBytes(Throwable t) {
ByteArrayOutputStream baos = null;
ObjectOutput out = null;
try {
// create a new exception
// throw away data that may not
// be serializable
Constructor<? extends Throwable> con = t.getClass().getConstructor(String.class);
Throwable newInstance = con.newInstance(t.getMessage());
newInstance.setStackTrace(t.getStackTrace());
baos = new ByteArrayOutputStream();
out = new ObjectOutputStream(baos);
out.writeObject(newInstance);
} catch (IOException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
logger.error("Failed to convert throwable to bytes", e);
throw new RuntimeException(e);
} finally {
try {
if (out != null) {out.close();}
if (baos != null) {baos.close();}
} catch (IOException e1) {
e1.printStackTrace();
throw new RuntimeException(e1);
}
}
return baos.toByteArray();
}
static Throwable fromBytesToThrowable(byte[] bytes) {
Throwable t = null;
ByteArrayInputStream bis = null;
ObjectInput in = null;
try {
bis = new ByteArrayInputStream(bytes);
in = new ObjectInputStream(bis);
t = (Throwable) in.readObject();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e1) {
throw new RuntimeException(e1);
} finally {
try {
if (bis != null) {bis.close();}
if (in != null) {in.close();}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return t;
}
}
| 8,821 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/RemoteUnsubscribe.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import java.util.List;
import mantis.io.reactivex.netty.channel.ObservableConnection;
import rx.Subscription;
import rx.subscriptions.BooleanSubscription;
public class RemoteUnsubscribe implements Subscription {
private ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection;
private BooleanSubscription subscription = new BooleanSubscription();
private String observableName;
public RemoteUnsubscribe(String observableName) {
this.observableName = observableName;
}
@Override
public void unsubscribe() {
if (connection != null) {
connection.writeAndFlush(RemoteRxEvent.unsubscribed(observableName)); // write unsubscribe event to server
}
subscription.unsubscribe();
}
@Override
public boolean isUnsubscribed() {
return subscription.isUnsubscribed();
}
void setConnection(
ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection) {
this.connection = connection;
}
}
| 8,822 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/RemoteRxEvent.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class RemoteRxEvent {
private String name;
private Type type;
private byte[] data;
private Map<String, String> subscriptionParameters;
public RemoteRxEvent(String name,
Type type, byte[] data, Map<String, String> subscriptionParameters) {
this.name = name;
this.type = type;
this.data = data;
this.subscriptionParameters = subscriptionParameters;
}
public static List<RemoteRxEvent> heartbeat() {
List<RemoteRxEvent> list = new ArrayList<RemoteRxEvent>(1);
list.add(new RemoteRxEvent(null, Type.heartbeat, null, null));
return list;
}
public static RemoteRxEvent nonDataError(String name, byte[] errorData) {
return new RemoteRxEvent(null, Type.nonDataError, errorData, null);
}
public static RemoteRxEvent next(String name, byte[] nextData) {
return new RemoteRxEvent(name, Type.next, nextData, null);
}
public static RemoteRxEvent completed(String name) {
return new RemoteRxEvent(name, Type.completed, null, null);
}
public static RemoteRxEvent error(String name, byte[] errorData) {
return new RemoteRxEvent(name, Type.error, errorData, null);
}
public static List<RemoteRxEvent> subscribed(String name, Map<String, String> subscriptionParameters) {
List<RemoteRxEvent> list = new ArrayList<RemoteRxEvent>(1);
list.add(new RemoteRxEvent(name, Type.subscribed, null, subscriptionParameters));
return list;
}
public static List<RemoteRxEvent> unsubscribed(String name) {
List<RemoteRxEvent> list = new ArrayList<RemoteRxEvent>(1);
list.add(new RemoteRxEvent(name, Type.unsubscribed, null, null));
return list;
}
public byte[] getData() {
return data;
}
public Type getType() {
return type;
}
public String getName() {
return name;
}
Map<String, String> getSubscribeParameters() {
return subscriptionParameters;
}
@Override
public String toString() {
return "RemoteRxEvent [name=" + name + ", type=" + type
+ ", subscriptionParameters=" + subscriptionParameters + "]";
}
public enum Type {
next, completed, error, subscribed, unsubscribed,
heartbeat, // used by clients to close connection
// during a network partition to avoid
// scenario where client subscription is active
// but server has forced unsubscribe due to partition.
// A server will force unsubscribe if unable to
// write to client after a certain number of attempts.
nonDataError // used by server to inform client of errors
// occurred that are not on the data
// stream, example: slotting error
}
}
| 8,823 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/slotting/SlottedData.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable.slotting;
import io.mantisrx.common.network.Endpoint;
import java.util.Set;
public class SlottedData<T> {
private Set<Endpoint> endpoints;
private T data;
public SlottedData(Set<Endpoint> endpoints, T data) {
this.endpoints = endpoints;
this.data = data;
}
public boolean sendToEndpoint(Endpoint endpoint) {
return endpoints.contains(endpoint);
}
public T getData() {
return data;
}
}
| 8,824 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/slotting/SlottingStrategies.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable.slotting;
public class SlottingStrategies {
private SlottingStrategies() {}
}
| 8,825 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/slotting/SlottingStrategy.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable.slotting;
import io.mantisrx.common.network.WritableEndpoint;
import rx.functions.Action0;
public abstract class SlottingStrategy<T> {
Action0 doAfterFirstConnectionAdded = new Action0() {
@Override
public void call() {}
};
Action0 doAfterLastConnectionRemoved = new Action0() {
@Override
public void call() {}
};
Action0 doOnEachConnectionAdded = new Action0() {
@Override
public void call() {}
};
Action0 doOnEachConnectionRemoved = new Action0() {
@Override
public void call() {}
};
public void registerDoOnEachConnectionRemoved(Action0 doOnEachConnectionRemoved) {
this.doOnEachConnectionRemoved = doOnEachConnectionRemoved;
}
public void registerDoOnEachConnectionAdded(Action0 doOnEachConnectionAdded) {
this.doOnEachConnectionAdded = doOnEachConnectionAdded;
}
public void registerDoAfterFirstConnectionAdded(Action0 doAfterFirstConnectionAdded) {
this.doAfterFirstConnectionAdded = doAfterFirstConnectionAdded;
}
public void registerDoAfterLastConnectionRemoved(Action0 doAfterLastConnectionRemoved) {
this.doAfterLastConnectionRemoved = doAfterLastConnectionRemoved;
}
public abstract boolean addConnection(WritableEndpoint<T> endpoint);
public abstract boolean removeConnection(WritableEndpoint<T> endpoint);
public abstract void writeOnSlot(byte[] keyBytes, T data);
public abstract void completeAllConnections();
public abstract void errorAllConnections(Throwable e);
}
| 8,826 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/slotting/ConsistentHashing.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable.slotting;
import io.mantisrx.common.metrics.Gauge;
import io.mantisrx.common.metrics.Metrics;
import io.mantisrx.common.network.HashFunction;
import io.mantisrx.common.network.HashFunctions;
import io.mantisrx.common.network.ServerSlotManager.SlotAssignmentManager;
import io.mantisrx.common.network.WritableEndpoint;
import java.util.LinkedList;
import java.util.List;
public class ConsistentHashing<T> extends SlottingStrategy<T> {
private SlotAssignmentManager<T> manager;
private List<WritableEndpoint<T>> connections = new LinkedList<>();
private Gauge activeConnections;
private Metrics metrics;
public ConsistentHashing(String ringName, HashFunction function) {
manager = new SlotAssignmentManager<T>(function, ringName);
metrics = new Metrics.Builder()
.name("ConsistentHashing")
.addGauge("activeConnections")
.build();
activeConnections = metrics.getGauge("activeConnections");
}
public ConsistentHashing() {
this("default-ring", HashFunctions.ketama());
}
public Metrics getMetrics() {
return metrics;
}
@Override
public synchronized boolean addConnection(WritableEndpoint<T> endpoint) {
boolean wasEmpty = manager.isEmpty();
// force adding slot to manager
boolean isRegistered = manager.forceRegisterServer(endpoint);
if (wasEmpty && isRegistered) {
doAfterFirstConnectionAdded.call();
}
if (isRegistered) {
connections.add(endpoint);
doOnEachConnectionAdded.call();
}
activeConnections.set(connections.size());
return isRegistered;
}
@Override
public synchronized boolean removeConnection(WritableEndpoint<T> endpoint) {
// remove connection, do not remove slot
boolean isDeregistered = connections.remove(endpoint);
if (isDeregistered && connections.isEmpty()) {
doAfterLastConnectionRemoved.call();
}
if (isDeregistered) {
doOnEachConnectionRemoved.call();
}
activeConnections.set(connections.size());
return isDeregistered;
}
@Override
public void writeOnSlot(byte[] keyBytes, T data) {
manager.lookup(keyBytes).write(data);
}
@Override
// TODO should completeAll and errorAll de-register?
public synchronized void completeAllConnections() {
for (WritableEndpoint<T> endpoint : manager.endpoints()) {
endpoint.complete();
}
}
@Override
public synchronized void errorAllConnections(Throwable e) {
for (WritableEndpoint<T> endpoint : manager.endpoints()) {
endpoint.error(e);
}
}
}
| 8,827 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/slotting/RoundRobin.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable.slotting;
import io.mantisrx.common.metrics.Metrics;
import io.mantisrx.common.network.RoundRobinRouter;
import io.mantisrx.common.network.WritableEndpoint;
public class RoundRobin<T> extends SlottingStrategy<T> {
private RoundRobinRouter<T> router = new RoundRobinRouter<>();
public Metrics getMetrics() {
return router.getMetrics();
}
@Override
public synchronized boolean addConnection(WritableEndpoint<T> endpoint) {
boolean wasEmpty = router.isEmpty();
boolean isRegistered = router.add(endpoint);
if (wasEmpty && isRegistered) {
doAfterFirstConnectionAdded.call();
}
return isRegistered;
}
@Override
public synchronized boolean removeConnection(WritableEndpoint<T> endpoint) {
boolean isDeregistered = router.remove(endpoint);
if (isDeregistered && router.isEmpty()) {
doAfterLastConnectionRemoved.call();
}
return isDeregistered;
}
@Override
public void writeOnSlot(byte[] keyBytes, T data) {
router.nextSlot().write(data);
}
@Override
// TODO should completeAll and errorAll de-register?
public void completeAllConnections() {
router.completeAllEndpoints();
}
@Override
public void errorAllConnections(Throwable e) {
router.errorAllEndpoints(e);
}
}
| 8,828 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/ingress/IngressPolicies.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable.ingress;
import io.reactivex.mantis.remote.observable.RemoteRxEvent;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import mantis.io.reactivex.netty.channel.ObservableConnection;
import rx.Observable;
import rx.subjects.ReplaySubject;
public class IngressPolicies {
private IngressPolicies() {}
public static IngressPolicy whiteListPolicy(Observable<Set<String>> whiteList) {
return new InetAddressWhiteListIngressPolicy(whiteList);
}
public static IngressPolicy allowOnlyLocalhost() {
ReplaySubject<Set<String>> subject = ReplaySubject.create();
Set<String> list = new HashSet<String>();
list.add("127.0.0.1");
subject.onNext(list);
return new InetAddressWhiteListIngressPolicy(subject);
}
public static IngressPolicy allowAll() {
return new IngressPolicy() {
@Override
public boolean allowed(
ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection) {
return true;
}
};
}
}
| 8,829 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/ingress/IngressPolicy.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable.ingress;
import io.reactivex.mantis.remote.observable.RemoteRxEvent;
import java.util.List;
import mantis.io.reactivex.netty.channel.ObservableConnection;
public interface IngressPolicy {
public boolean allowed(ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection);
}
| 8,830 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/ingress/InetAddressWhiteListIngressPolicy.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable.ingress;
import io.reactivex.mantis.remote.observable.RemoteRxEvent;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import mantis.io.reactivex.netty.channel.ObservableConnection;
import rx.Observable;
import rx.functions.Action1;
public class InetAddressWhiteListIngressPolicy implements IngressPolicy {
private AtomicReference<Set<String>> whiteList = new AtomicReference<Set<String>>();
InetAddressWhiteListIngressPolicy(Observable<Set<String>> allowedIpAddressesObservable) {
allowedIpAddressesObservable.subscribe(new Action1<Set<String>>() {
@Override
public void call(Set<String> newList) {
whiteList.set(newList);
}
});
}
@Override
public boolean allowed(
ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection) {
InetSocketAddress inetSocketAddress
= (InetSocketAddress) connection.getChannel().remoteAddress();
return whiteList.get().contains(inetSocketAddress.getAddress().getHostAddress());
}
}
| 8,831 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/reconciliator/ConnectionSet.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable.reconciliator;
import io.mantisrx.common.network.Endpoint;
import java.util.Set;
import rx.Observable;
public interface ConnectionSet<T> {
public Observable<Set<Endpoint>> activeConnections();
public Observable<Observable<T>> observables();
}
| 8,832 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/reconciliator/Check.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable.reconciliator;
public class Check<T> {
private T expected;
private T actual;
private boolean passedCheck;
private long timestamp;
public Check(T expected, T actual,
boolean passedCheck, long timestamp) {
this.expected = expected;
this.actual = actual;
this.passedCheck = passedCheck;
this.timestamp = timestamp;
}
public T getExpected() {
return expected;
}
public T getActual() {
return actual;
}
public boolean isPassedCheck() {
return passedCheck;
}
public long getTimestamp() {
return timestamp;
}
}
| 8,833 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/reconciliator/Outcome.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable.reconciliator;
public class Outcome {
private int numChecks;
private int numFailedChecks;
private double failurePercentage;
private boolean exceedsFailureThreshold;
public Outcome(int numChecks, int numFailedChecks,
double failurePercentage, boolean exceedsFailureThreshold) {
this.numChecks = numChecks;
this.numFailedChecks = numFailedChecks;
this.failurePercentage = failurePercentage;
this.exceedsFailureThreshold = exceedsFailureThreshold;
}
public int getNumChecks() {
return numChecks;
}
public int getNumFailedChecks() {
return numFailedChecks;
}
public double getFailurePercentage() {
return failurePercentage;
}
public boolean isExceedsFailureThreshold() {
return exceedsFailureThreshold;
}
}
| 8,834 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/reconciliator/Reconciliator.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable.reconciliator;
import io.mantisrx.common.metrics.Counter;
import io.mantisrx.common.metrics.Gauge;
import io.mantisrx.common.metrics.Metrics;
import io.mantisrx.common.network.Endpoint;
import io.reactivex.mantis.remote.observable.DynamicConnectionSet;
import io.reactivex.mantis.remote.observable.EndpointChange;
import io.reactivex.mantis.remote.observable.EndpointChange.Type;
import io.reactivex.mantis.remote.observable.EndpointInjector;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.subjects.PublishSubject;
public class Reconciliator<T> {
private static final Logger logger = LoggerFactory.getLogger(Reconciliator.class);
private static final AtomicBoolean startedReconciliation = new AtomicBoolean(false);
private String name;
private Subscription subscription;
private DynamicConnectionSet<T> connectionSet;
private PublishSubject<Set<Endpoint>> currentExpectedSet = PublishSubject.create();
private EndpointInjector injector;
private PublishSubject<EndpointChange> reconciledChanges = PublishSubject.create();
private Metrics metrics;
private Counter reconciliationCheck;
private Gauge running;
private Gauge expectedSetSize;
Reconciliator(Builder<T> builder) {
this.name = builder.name;
this.injector = builder.injector;
this.connectionSet = builder.connectionSet;
metrics = new Metrics.Builder()
.name("Reconciliator_" + name)
.addCounter("reconciliationCheck")
.addGauge("expectedSetSize")
.addGauge("running")
.build();
reconciliationCheck = metrics.getCounter("reconciliationCheck");
running = metrics.getGauge("running");
expectedSetSize = metrics.getGauge("expectedSetSize");
}
public Metrics getMetrics() {
return metrics;
}
private Observable<EndpointChange> deltas() {
final Map<String, Endpoint> sideEffectState = new HashMap<String, Endpoint>();
final PublishSubject<Integer> stopReconciliator = PublishSubject.create();
return
Observable.merge(
reconciledChanges
.takeUntil(stopReconciliator)
.doOnCompleted(() -> {
logger.info("onComplete triggered for reconciledChanges");
})
.doOnError(e -> logger.error("caught exception for reconciledChanges {}", e.getMessage(), e))
,
injector
.deltas()
.doOnCompleted(new Action0() {
@Override
public void call() {
// injector has completed recieving updates, complete reconciliator
// observable
logger.info("Stopping reconciliator, injector completed.");
stopReconciliator.onNext(1);
stopReconciliation();
}
})
.doOnError(e -> logger.error("caught exception for injector deltas {}", e.getMessage(), e))
.doOnNext(new Action1<EndpointChange>() {
@Override
public void call(EndpointChange newEndpointChange) {
String id = Endpoint.uniqueHost(newEndpointChange.getEndpoint().getHost(),
newEndpointChange.getEndpoint().getPort(), newEndpointChange.getEndpoint().getSlotId());
if (sideEffectState.containsKey(id)) {
if (newEndpointChange.getType() == Type.complete) {
// remove from expecected set
expectedSetSize.decrement();
sideEffectState.remove(id);
currentExpectedSet.onNext(new HashSet<Endpoint>(sideEffectState.values()));
}
} else {
if (newEndpointChange.getType() == Type.add) {
expectedSetSize.increment();
sideEffectState.put(id, new Endpoint(newEndpointChange.getEndpoint().getHost(),
newEndpointChange.getEndpoint().getPort(), newEndpointChange.getEndpoint().getSlotId()));
currentExpectedSet.onNext(new HashSet<Endpoint>(sideEffectState.values()));
}
}
}
})
)
.doOnError(t -> logger.error("caught error processing reconciliator deltas {}", t.getMessage(), t))
.doOnSubscribe(
new Action0() {
@Override
public void call() {
logger.info("Subscribed to deltas for {}, clearing active connection set", name);
connectionSet.resetActiveConnections();
startReconciliation();
}
})
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
logger.info("Unsubscribed from deltas for {}", name);
}
});
}
private void startReconciliation() {
if (startedReconciliation.compareAndSet(false, true)) {
logger.info("Starting reconciliation for name: " + name);
running.increment();
subscription =
Observable
.combineLatest(currentExpectedSet, connectionSet.activeConnections(),
new Func2<Set<Endpoint>, Set<Endpoint>, Void>() {
@Override
public Void call(Set<Endpoint> expected, Set<Endpoint> actual) {
reconciliationCheck.increment();
boolean check = expected.equals(actual);
logger.debug("Check result: " + check + ", size expected: " + expected.size() + " actual: " + actual.size() + ", for values expected: " + expected + " versus actual: " + actual);
if (!check) {
// reconcile adds
Set<Endpoint> expectedDiff = new HashSet<Endpoint>(expected);
expectedDiff.removeAll(actual);
if (expectedDiff.size() > 0) {
for (Endpoint endpoint : expectedDiff) {
logger.info("Connection missing from expected set, adding missing connection: " + endpoint);
reconciledChanges.onNext(new EndpointChange(Type.add, endpoint));
}
}
// reconile removes
Set<Endpoint> actualDiff = new HashSet<Endpoint>(actual);
actualDiff.removeAll(expected);
if (actualDiff.size() > 0) {
for (Endpoint endpoint : actualDiff) {
logger.info("Unexpected connection in active set, removing connection: " + endpoint);
reconciledChanges.onNext(new EndpointChange(Type.complete, endpoint));
}
}
}
return null;
}
})
.onErrorResumeNext(new Func1<Throwable, Observable<? extends Void>>() {
@Override
public Observable<? extends Void> call(Throwable throwable) {
logger.error("caught error in Reconciliation for {}", name, throwable);
return Observable.empty();
}
})
.doOnCompleted(new Action0() {
@Override
public void call() {
logger.error("onComplete in Reconciliation observable chain for {}", name);
stopReconciliation();
}
})
.subscribe();
} else {
logger.info("reconciliation already started for {}", name);
}
}
private void stopReconciliation() {
if (startedReconciliation.compareAndSet(true, false)) {
logger.info("Stopping reconciliation for name: " + name);
running.decrement();
subscription.unsubscribe();
} else {
logger.info("reconciliation already stopped for name: " + name);
}
}
public Observable<Observable<T>> observables() {
connectionSet.setEndpointInjector(new EndpointInjector() {
@Override
public Observable<EndpointChange> deltas() {
return Reconciliator.this.deltas();
}
});
return connectionSet.observables();
}
public static class Builder<T> {
private String name;
private EndpointInjector injector;
private DynamicConnectionSet<T> connectionSet;
public Builder<T> connectionSet(DynamicConnectionSet<T> connectionSet) {
this.connectionSet = connectionSet;
return this;
}
public Builder<T> name(String name) {
this.name = name;
return this;
}
public Builder<T> injector(EndpointInjector injector) {
this.injector = injector;
return this;
}
public Reconciliator<T> build() {
return new Reconciliator<T>(this);
}
}
}
| 8,835 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/filter/ServerSideFilters.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.remote.observable.filter;
import java.util.Map;
import rx.functions.Func1;
public class ServerSideFilters {
private ServerSideFilters() {}
public static <T> Func1<Map<String, String>, Func1<T, Boolean>> noFiltering() {
return new Func1<Map<String, String>, Func1<T, Boolean>>() {
@Override
public Func1<T, Boolean> call(Map<String, String> t1) {
return new Func1<T, Boolean>() {
@Override
public Boolean call(T t1) {
return true;
}
};
}
};
}
public static Func1<Map<String, String>, Func1<Integer, Boolean>> oddsAndEvens() {
return new Func1<Map<String, String>, Func1<Integer, Boolean>>() {
@Override
public Func1<Integer, Boolean> call(final Map<String, String> params) {
return new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer t1) {
if (params == null || params.isEmpty() ||
!params.containsKey("type")) {
return true; // no filtering
} else {
String type = params.get("type");
if ("even".equals(type)) {
return (t1 % 2 == 0);
} else if ("odd".equals(type)) {
return (t1 % 2 != 0);
} else {
throw new RuntimeException("Unsupported filter param 'type' for oddsAndEvens: " + type);
}
}
}
};
}
};
}
}
| 8,836 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/netty | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/netty/codec/Decoder.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.netty.codec;
/**
* @param <T> type
*
* @deprecated As of release 0.601, use {@link io.mantisrx.common.codec.Decoder} instead
*/
@Deprecated
public interface Decoder<T> {
public T decode(byte[] bytes);
}
| 8,837 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/netty | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/netty/codec/Codecs.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.netty.codec;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
/**
* @deprecated As of release 0.601, use {@link io.mantisrx.common.codec.Codecs} instead
*/
@Deprecated
public class Codecs {
public static Codec<Integer> integer() {
return new Codec<Integer>() {
@Override
public Integer decode(byte[] bytes) {
return ByteBuffer.wrap(bytes).getInt();
}
@Override
public byte[] encode(final Integer value) {
return ByteBuffer.allocate(4).putInt(value).array();
}
};
}
private static Codec<String> stringWithEncoding(String encoding) {
final Charset charset = Charset.forName(encoding);
return new Codec<String>() {
@Override
public String decode(byte[] bytes) {
return new String(bytes, charset);
}
@Override
public byte[] encode(final String value) {
return value.getBytes(charset);
}
};
}
public static Codec<String> stringAscii() {
final Charset charset = Charset.forName("US-ASCII");
return new Codec<String>() {
@Override
public String decode(byte[] bytes) {
return new String(bytes, charset);
}
@Override
public byte[] encode(final String value) {
final byte[] bytes = new byte[value.length()];
for (int i = 0; i < value.length(); i++)
bytes[i] = (byte) value.charAt(i);
return bytes;
}
};
}
public static Codec<String> stringUtf8() {
return stringWithEncoding("UTF-8");
}
public static Codec<String> string() {
return stringUtf8();
}
public static Codec<byte[]> bytearray() {
return new Codec<byte[]>() {
@Override
public byte[] decode(byte[] bytes) {
return bytes;
}
@Override
public byte[] encode(final byte[] value) {
return value;
}
};
}
}
| 8,838 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/netty | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/netty/codec/Codec.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.netty.codec;
/**
* @param <T> type
*
* @deprecated As of release 0.601, use {@link io.mantisrx.common.codec.Codec} instead
*/
@Deprecated
public interface Codec<T> extends Encoder<T>, Decoder<T> {
}
| 8,839 |
0 | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/netty | Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/netty/codec/Encoder.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.netty.codec;
/**
* @param <T> type
*
* @deprecated As of release 0.601, use {@link io.mantisrx.common.codec.Encoder} instead
*/
@Deprecated
public interface Encoder<T> {
public byte[] encode(T value);
}
| 8,840 |
0 | Create_ds/mantis/mantis-runtime-loader/src/test/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime-loader/src/test/java/io/mantisrx/runtime/loader/SubscriptionStateHandlerImplTest.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.loader;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import io.mantisrx.common.util.DelegateClock;
import io.mantisrx.runtime.loader.SubscriptionStateHandlerImpl.SubscriptionState;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
public class SubscriptionStateHandlerImplTest {
@Test
public void testSubscriptionState() {
final AtomicReference<Clock> clock = new AtomicReference<>(Clock.fixed(Instant.ofEpochSecond(1), ZoneId.systemDefault()));
SubscriptionState state = SubscriptionState.of(new DelegateClock(clock));
assertFalse(state.isSubscribed());
clock.updateAndGet(c -> Clock.offset(c, Duration.ofSeconds(100)));
assertTrue(state.isUnsubscribedFor(Duration.ofSeconds(100)));
assertTrue(state.hasRunFor(Duration.ofSeconds(100)));
assertFalse(state.hasRunFor(Duration.ofSeconds(101)));
assertEquals(Duration.ofSeconds(100), state.getUnsubscribedDuration());
state = state.onSinkSubscribed();
assertTrue(state.isSubscribed());
assertFalse(state.isUnsubscribedFor(Duration.ofSeconds(10)));
assertTrue(state.hasRunFor(Duration.ofSeconds(100)));
clock.updateAndGet(c -> Clock.offset(c, Duration.ofSeconds(100)));
state = state.onSinkUnsubscribed();
assertTrue(state.isUnsubscribedFor(Duration.ofSeconds(0)));
assertFalse(state.isUnsubscribedFor(Duration.ofSeconds(1)));
assertTrue(state.hasRunFor(Duration.ofSeconds(200)));
assertFalse(state.hasRunFor(Duration.ofSeconds(201)));
assertEquals(Duration.ofSeconds(0), state.getUnsubscribedDuration());
}
}
| 8,841 |
0 | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader/SubscriptionStateHandlerImpl.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.loader;
import io.mantisrx.server.master.client.MantisMasterGateway;
import io.mantisrx.shaded.com.google.common.base.Preconditions;
import io.mantisrx.shaded.com.google.common.util.concurrent.AbstractScheduledService;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
/**
* SubscriptionStateHandler that kills the job if the sink has been unsubscribed for subscriptionTimeout seconds.
*/
@Slf4j
class SubscriptionStateHandlerImpl extends AbstractScheduledService implements SinkSubscriptionStateHandler {
private final String jobId;
private final MantisMasterGateway masterClientApi;
private final Duration subscriptionTimeout;
private final Duration minRuntime;
private final AtomicReference<SubscriptionState> currentState = new AtomicReference<>();
private final Clock clock;
SubscriptionStateHandlerImpl(String jobId, MantisMasterGateway masterClientApi, long subscriptionTimeoutSecs, long minRuntimeSecs, Clock clock) {
Preconditions.checkArgument(subscriptionTimeoutSecs > 0, "subscriptionTimeoutSecs should be > 0");
this.jobId = jobId;
this.masterClientApi = masterClientApi;
this.subscriptionTimeout = Duration.ofSeconds(subscriptionTimeoutSecs);
this.minRuntime = Duration.ofSeconds(minRuntimeSecs);
this.clock = clock;
}
@Override
public void startUp() {
currentState.compareAndSet(null, SubscriptionState.of(clock));
log.info("SubscriptionStateHandlerImpl service started.");
}
@Override
protected Scheduler scheduler() {
// scheduler that runs every second to check if the subscriber is unsubscribed for subscriptionTimeoutSecs.
return Scheduler.newFixedDelaySchedule(1, 1, TimeUnit.SECONDS);
}
@Override
protected void runOneIteration() {
SubscriptionState state = currentState.get();
if (state.isUnsubscribedFor(subscriptionTimeout) && state.hasRunFor(minRuntime)) {
try {
log.info("Calling master to kill due to subscription timeout");
masterClientApi.killJob(jobId, "MantisWorker", "No subscriptions for " +
subscriptionTimeout.getSeconds() + " secs")
.single()
.toBlocking()
.first();
} catch (Exception e) {
log.error("Failed to kill job {} due to no subscribers for {} seconds", jobId, state.getUnsubscribedDuration().getSeconds());
}
}
}
@Override
public void onSinkUnsubscribed() {
if (currentState.get() == null) {
log.error("currentState in SubscriptionStateHandlerImpl is not set onSinkUnsubscribed");
return;
}
currentState.updateAndGet(SubscriptionState::onSinkUnsubscribed);
}
@Override
public void onSinkSubscribed() {
Preconditions.checkNotNull(currentState.get(), "currentState is not intialized onSinkSubscribed.");
currentState.updateAndGet(SubscriptionState::onSinkSubscribed);
}
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
@Value
static class SubscriptionState {
boolean subscribed;
Instant startedAt;
Instant lastUnsubscriptionTime;
Clock clock;
static SubscriptionState of(Clock clock) {
return new SubscriptionState(false, clock.instant(), clock.instant(), clock);
}
public SubscriptionState onSinkSubscribed() {
if (isSubscribed()) {
return this;
} else {
return new SubscriptionState(true, startedAt, lastUnsubscriptionTime, clock);
}
}
public SubscriptionState onSinkUnsubscribed() {
if (isSubscribed()) {
return new SubscriptionState(false, startedAt, clock.instant(), clock);
} else {
return this;
}
}
public boolean hasRunFor(Duration duration) {
return Duration.between(startedAt, clock.instant()).compareTo(duration) >= 0;
}
public boolean isUnsubscribedFor(Duration duration) {
return !isSubscribed() && Duration.between(lastUnsubscriptionTime, clock.instant()).compareTo(duration) >= 0;
}
public Duration getUnsubscribedDuration() {
Preconditions.checkState(!isSubscribed());
return Duration.between(lastUnsubscriptionTime, clock.instant());
}
}
}
| 8,842 |
0 | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader/TaskFactory.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.loader;
import io.mantisrx.server.core.ExecuteStageRequest;
import org.apache.flink.util.UserCodeClassLoader;
/**
* Interface to factory building ITask implementation instance. Can be override to use customized ITask impl.
*/
public interface TaskFactory {
RuntimeTask getRuntimeTaskInstance(ExecuteStageRequest request, ClassLoader cl);
default UserCodeClassLoader getUserCodeClassLoader(
ExecuteStageRequest request,
ClassLoaderHandle classLoaderHandle) {
try {
return classLoaderHandle.createUserCodeClassloader(request);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
| 8,843 |
0 | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader/RuntimeTask.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.loader;
import io.mantisrx.shaded.com.google.common.util.concurrent.Service;
import org.apache.flink.util.UserCodeClassLoader;
/**
* Interface to load core runtime work load from external host (mesos or TaskExecutor).
* [Note] To avoid dependency conflicts in TaskExecutors running in custom structure
* e.g. SpringBoot based runtime, adding dependency here shall be carefully reviewed.
* Do not have any shared Mantis library that will be used on both TaskExecutor and implementations of
* RuntimeTask in here and use primitive types in general.
*/
public interface RuntimeTask extends Service {
void initialize(
String executeStageRequestString,
String workerConfigurationString,
UserCodeClassLoader userCodeClassLoader);
String getWorkerId();
}
| 8,844 |
0 | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader/SinkSubscriptionStateHandler.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.loader;
import io.mantisrx.server.core.ExecuteStageRequest;
import io.mantisrx.server.master.client.MantisMasterGateway;
import io.mantisrx.shaded.com.google.common.util.concurrent.AbstractIdleService;
import io.mantisrx.shaded.com.google.common.util.concurrent.Service;
import java.time.Clock;
import java.util.function.Function;
public interface SinkSubscriptionStateHandler extends Service {
void onSinkSubscribed();
void onSinkUnsubscribed();
// Factory for making subscription state handlers. the first argument of the apply() function
// corresponds to the ExecuteStageRequest which contains details about the job/stage that needs
// to be executed in Mantis.
interface Factory extends Function<ExecuteStageRequest, SinkSubscriptionStateHandler> {
static Factory forEphemeralJobsThatNeedToBeKilledInAbsenceOfSubscriber(MantisMasterGateway gateway, Clock clock) {
return executeStageRequest -> {
if (executeStageRequest.getSubscriptionTimeoutSecs() > 0) {
return new SubscriptionStateHandlerImpl(
executeStageRequest.getJobId(),
gateway,
executeStageRequest.getSubscriptionTimeoutSecs(),
executeStageRequest.getMinRuntimeSecs(),
clock);
} else {
return NOOP_INSTANCE;
}
};
}
}
static SinkSubscriptionStateHandler noop() {
return NOOP_INSTANCE;
}
static final SinkSubscriptionStateHandler NOOP_INSTANCE =
new NoopSinkSubscriptionStateHandler();
class NoopSinkSubscriptionStateHandler extends AbstractIdleService implements SinkSubscriptionStateHandler {
@Override
public void onSinkSubscribed() {
}
@Override
public void onSinkUnsubscribed() {
}
@Override
protected void startUp() throws Exception {
}
@Override
protected void shutDown() throws Exception {
}
}
}
| 8,845 |
0 | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader/ClassLoaderHandle.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.loader;
import io.mantisrx.server.core.ExecuteStageRequest;
import io.mantisrx.shaded.com.google.common.collect.ImmutableList;
import java.io.Closeable;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.Collection;
import org.apache.flink.util.SimpleUserCodeClassLoader;
import org.apache.flink.util.UserCodeClassLoader;
/**
* Handle to retrieve a user code class loader for the associated job.
*/
public interface ClassLoaderHandle extends Closeable {
/**
* Gets or resolves the user code class loader for the associated job.
*
* <p>In order to retrieve the user code class loader the caller has to specify the required
* jars and class paths. Upon calling this method first for a job, it will make sure that
* the required jars are present and potentially cache the created user code class loader.
* Every subsequent call to this method, will ensure that created user code class loader can
* fulfill the required jar files and class paths.
*
* @param requiredJarFiles requiredJarFiles the user code class loader needs to load
* @return the user code class loader fulfilling the requirements
* @throws IOException if the required jar files cannot be downloaded
* @throws IllegalStateException if the cached user code class loader does not fulfill the
* requirements
*/
UserCodeClassLoader getOrResolveClassLoader(Collection<URI> requiredJarFiles,
Collection<URL> requiredClasspaths) throws IOException;
void cacheJobArtifacts(Collection<URI> artifacts);
/**
* ClassLoaderHandle that just returns the classloader field that's assigned at the time of construction
* on query for any new handles.
* <p>
* This is primarily used for testing purposes when the classloader doesn't need to get any files.
*/
static ClassLoaderHandle fixed(ClassLoader classLoader) {
return new ClassLoaderHandle() {
@Override
public UserCodeClassLoader getOrResolveClassLoader(Collection<URI> requiredJarFiles, Collection<URL> requiredClasspaths) throws IOException {
return SimpleUserCodeClassLoader.create(classLoader);
}
@Override
public void cacheJobArtifacts(Collection<URI> artifacts) {}
@Override
public void close() throws IOException {
}
};
}
default UserCodeClassLoader createUserCodeClassloader(ExecuteStageRequest executeStageRequest) throws Exception {
// triggers the download of all missing jar files from the job manager
final UserCodeClassLoader userCodeClassLoader =
this.getOrResolveClassLoader(ImmutableList.of(executeStageRequest.getJobJarUrl().toURI()),
ImmutableList.of());
return userCodeClassLoader;
}
}
| 8,846 |
0 | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader/config/WorkerConfiguration.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.loader.config;
import io.mantisrx.server.core.CoreConfiguration;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnore;
import io.mantisrx.shaded.com.google.common.base.Splitter;
import io.mantisrx.shaded.com.google.common.collect.ImmutableMap;
import java.io.File;
import java.net.URI;
import java.util.Map;
import org.apache.flink.api.common.time.Time;
import org.skife.config.Config;
import org.skife.config.Default;
import org.skife.config.DefaultNull;
public interface WorkerConfiguration extends CoreConfiguration {
// Old configurations for mesos
@Config("mantis.agent.mesos.slave.port")
@Default("5051")
int getMesosSlavePort();
// ------------------------------------------------------------------------
// Task Executor machine related configurations
// ------------------------------------------------------------------------
@Config({"mantis.taskexecutor.id", "MANTIS_TASKEXECUTOR_ID"})
@DefaultNull
String getTaskExecutorId();
default String getTaskExecutorHostName() {
return getExternalAddress();
}
@Config({"mantis.taskexecutor.cluster-id", "MANTIS_TASKEXECUTOR_CLUSTER_ID"})
@Default("DEFAULT_CLUSTER")
String getClusterId();
@Config("mantis.taskexecutor.ports.metrics")
@Default("5051")
int getMetricsPort();
@Config("mantis.taskexecutor.ports.debug")
@Default("5052")
int getDebugPort();
@Config("mantis.taskexecutor.ports.console")
@Default("5053")
int getConsolePort();
@Config("mantis.taskexecutor.ports.custom")
@Default("5054")
int getCustomPort();
@Config("mantis.taskexecutor.ports.sink")
@Default("5055")
int getSinkPort();
// ------------------------------------------------------------------------
// heartbeat connection related configurations
// ------------------------------------------------------------------------
@Config("mantis.taskexecutor.heartbeats.interval")
@Default("10000")
int heartbeatInternalInMs();
@Config("mantis.taskexecutor.heartbeats.tolerable-consecutive-heartbeat-failures")
@Default("3")
int getTolerableConsecutiveHeartbeatFailures();
@Config("mantis.taskexecutor.heartbeats.timeout.ms")
@Default("5000")
int heartbeatTimeoutMs();
@Config("mantis.taskexecutor.heartbeats.retry.initial-delay.ms")
@Default("1000")
long heartbeatRetryInitialDelayMs();
@Config("mantis.taskexecutor.heartbeats.retry.max-delay.ms")
@Default("5000")
long heartbeatRetryMaxDelayMs();
@Config("mantis.taskexecutor.registration.retry.initial-delay.ms")
@Default("2000")
long registrationRetryInitialDelayMillis();
@Config("mantis.taskexecutor.registration.retry.mutliplier")
@Default("2")
double registrationRetryMultiplier();
@Config("mantis.taskexecutor.registration.retry.randomization-factor")
@Default("0.5")
double registrationRetryRandomizationFactor();
@Config("mantis.taskexecutor.registration.retry.max-attempts")
@Default("5")
int registrationRetryMaxAttempts();
@Config("mantis.taskexecutor.registration.store")
@DefaultNull
File getRegistrationStoreDir();
default Time getHeartbeatTimeout() {
return Time.milliseconds(heartbeatTimeoutMs());
}
default Time getHeartbeatInterval() {
return Time.milliseconds(heartbeatInternalInMs());
}
// ------------------------------------------------------------------------
// RPC related configurations
// ------------------------------------------------------------------------
@Config({"mantis.taskexecutor.rpc.external-address", "MANTIS_TASKEXECUTOR_RPC_EXTERNAL_ADDRESS"})
@Default("localhost")
String getExternalAddress();
@Config("mantis.taskexecutor.rpc.port-range")
@Default("")
String getExternalPortRange();
@Config("mantis.taskexecutor.rpc.bind-address")
@DefaultNull
String getBindAddress();
@Config("mantis.taskexecutor.rpc.bind-port")
@DefaultNull
Integer getBindPort();
@Config("mantis.taskexecutor.metrics.collector")
@Default("io.mantisrx.server.worker.mesos.MesosMetricsCollector")
MetricsCollector getUsageSupplier();
// ------------------------------------------------------------------------
// BlobStore related configurations
// ------------------------------------------------------------------------
@Config("mantis.taskexecutor.blob-store.storage-dir")
@DefaultNull
URI getBlobStoreArtifactDir();
@Config("mantis.taskexecutor.blob-store.local-cache")
@DefaultNull
File getLocalStorageDir();
@Config("mantis.taskexecutor.hardware.network-bandwidth-in-mb")
@Default(value = "128.0")
double getNetworkBandwidthInMB();
@Config("mantis.taskexecutor.attributes")
@Default(value = "")
String taskExecutorAttributes();
@JsonIgnore
default Map<String, String> getTaskExecutorAttributes() {
String input = taskExecutorAttributes();
if (input == null || input.isEmpty()) {
return ImmutableMap.of();
}
return Splitter.on(",").withKeyValueSeparator(':').split(input);
}
}
| 8,847 |
0 | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader/config/WorkerConfigurationUtils.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.loader.config;
import io.mantisrx.common.JsonSerializer;
import io.mantisrx.server.core.MetricsCoercer;
import io.mantisrx.server.master.client.config.PluginCoercible;
import java.io.IOException;
import java.util.Properties;
import org.skife.config.ConfigurationObjectFactory;
public class WorkerConfigurationUtils {
public static <T extends WorkerConfiguration> T frmProperties(Properties properties, Class<T> tClass) {
ConfigurationObjectFactory configurationObjectFactory = new ConfigurationObjectFactory(
properties);
configurationObjectFactory.addCoercible(new MetricsCoercer(properties));
configurationObjectFactory.addCoercible(new PluginCoercible<>(MetricsCollector.class, properties));
return configurationObjectFactory.build(tClass);
}
public static <T extends WorkerConfiguration> WorkerConfigurationWritable toWritable(T configSource) {
return WorkerConfigurationWritable.builder()
.bindAddress(configSource.getBindAddress())
.bindPort(configSource.getBindPort())
.blobStoreArtifactDir(configSource.getBlobStoreArtifactDir())
.consolePort(configSource.getConsolePort())
.clusterId(configSource.getClusterId())
.customPort(configSource.getCustomPort())
.debugPort(configSource.getDebugPort())
.externalAddress(configSource.getExternalAddress())
.externalPortRange(configSource.getExternalPortRange())
.heartbeatInternalInMs(configSource.heartbeatInternalInMs())
.heartbeatTimeoutMs(configSource.heartbeatTimeoutMs())
.isLocalMode(configSource.isLocalMode())
.leaderAnnouncementPath(configSource.getLeaderAnnouncementPath())
.localStorageDir(configSource.getLocalStorageDir())
.mesosSlavePort(configSource.getMesosSlavePort())
.metricsCollector(configSource.getUsageSupplier())
.metricsPort(configSource.getMetricsPort())
.metricsPublisher(configSource.getMetricsPublisher())
.metricsPublisherFrequencyInSeconds(configSource.getMetricsPublisherFrequencyInSeconds())
.networkBandwidthInMB(configSource.getNetworkBandwidthInMB())
.sinkPort(configSource.getSinkPort())
.taskExecutorId(configSource.getTaskExecutorId())
.taskExecutorAttributesStr(configSource.taskExecutorAttributes())
.zkConnectionMaxRetries(configSource.getZkConnectionMaxRetries())
.zkConnectionTimeoutMs(configSource.getZkConnectionTimeoutMs())
.zkConnectionString(configSource.getZkConnectionString())
.zkConnectionRetrySleepMs(configSource.getZkConnectionRetrySleepMs())
.zkRoot(configSource.getZkRoot())
.build();
}
public static WorkerConfigurationWritable stringToWorkerConfiguration(String sourceStr) throws IOException {
JsonSerializer ser = new JsonSerializer();
return ser.fromJSON(sourceStr, WorkerConfigurationWritable.class);
}
}
| 8,848 |
0 | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader/config/MetricsCollector.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.loader.config;
import java.io.IOException;
/**
* Abstraction useful for collecting metrics about the node on which the worker task is running.
* The metrics that are collected from the node are available via the metrics port, which is used
* by the jobmanager node then for auto-scaling.
*/
public interface MetricsCollector {
Usage get() throws IOException;
}
| 8,849 |
0 | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader/config/WorkerConfigurationWritable.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.loader.config;
import io.mantisrx.common.metrics.MetricsPublisher;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.File;
import java.net.URI;
import lombok.Builder;
import lombok.Data;
/**
* This is a workaround solution to bridge the worker configuration to a serializable format between worker process
* entry and RuntimeTask implementations.
*/
@Data
@Builder
public class WorkerConfigurationWritable implements WorkerConfiguration {
int mesosSlavePort;
int zkConnectionTimeoutMs;
int zkConnectionRetrySleepMs;
int zkConnectionMaxRetries;
String zkConnectionString;
String leaderAnnouncementPath;
String zkRoot;
boolean isLocalMode;
int metricsPublisherFrequencyInSeconds;
String taskExecutorId;
String clusterId;
int metricsPort;
int debugPort;
int consolePort;
int customPort;
int sinkPort;
int heartbeatInternalInMs;
int tolerableConsecutiveHeartbeatFailures;
int heartbeatTimeoutMs;
long heartbeatRetryInitialDelayMs;
long heartbeatRetryMaxDelayMs;
long registrationRetryInitialDelayMillis;
double registrationRetryMultiplier;
double registrationRetryRandomizationFactor;
int registrationRetryMaxAttempts;
String externalAddress;
String externalPortRange;
String bindAddress;
Integer bindPort;
URI blobStoreArtifactDir;
File localStorageDir;
double networkBandwidthInMB;
String taskExecutorAttributesStr;
int asyncHttpClientMaxConnectionsPerHost;
int asyncHttpClientConnectionTimeoutMs;
int asyncHttpClientRequestTimeoutMs;
int asyncHttpClientReadTimeoutMs;
@JsonIgnore
MetricsPublisher metricsPublisher;
@JsonIgnore
MetricsCollector metricsCollector;
@Override
public int getZkConnectionTimeoutMs() {
return this.zkConnectionTimeoutMs;
}
@Override
public int getZkConnectionRetrySleepMs() {
return this.zkConnectionRetrySleepMs;
}
@Override
public int getZkConnectionMaxRetries() {
return this.zkConnectionMaxRetries;
}
@Override
public String getZkConnectionString() {
return this.zkConnectionString;
}
@Override
public String getLeaderAnnouncementPath() {
return this.leaderAnnouncementPath;
}
@Override
public String getZkRoot() {
return this.zkRoot;
}
@Override
public boolean isLocalMode() {
return this.isLocalMode;
}
@Override
public MetricsPublisher getMetricsPublisher() {
return this.metricsPublisher;
}
@Override
public int getMetricsPublisherFrequencyInSeconds() {
return this.metricsPublisherFrequencyInSeconds;
}
@Override
public int getMesosSlavePort() {
return this.mesosSlavePort;
}
@Override
public String getTaskExecutorId() {
return this.taskExecutorId;
}
@Override
public String getClusterId() {
return this.clusterId;
}
@Override
public int getMetricsPort() {
return this.metricsPort;
}
@Override
public int getDebugPort() {
return this.debugPort;
}
@Override
public int getConsolePort() {
return this.consolePort;
}
@Override
public int getCustomPort() {
return this.customPort;
}
@Override
public int getSinkPort() {
return this.sinkPort;
}
@Override
public int heartbeatInternalInMs() {
return this.heartbeatInternalInMs;
}
@Override
public int getTolerableConsecutiveHeartbeatFailures() {
return this.tolerableConsecutiveHeartbeatFailures;
}
@Override
public int heartbeatTimeoutMs() {
return this.heartbeatTimeoutMs;
}
@Override
public long heartbeatRetryInitialDelayMs() {
return this.heartbeatRetryInitialDelayMs;
}
@Override
public long heartbeatRetryMaxDelayMs() {
return this.heartbeatRetryMaxDelayMs;
}
@Override
public long registrationRetryInitialDelayMillis() {
return this.registrationRetryInitialDelayMillis;
}
@Override
public double registrationRetryMultiplier() {
return this.registrationRetryMultiplier;
}
@Override
public double registrationRetryRandomizationFactor() {
return this.registrationRetryRandomizationFactor;
}
@Override
public int registrationRetryMaxAttempts() {
return this.registrationRetryMaxAttempts;
}
@Override
public String getExternalAddress() {
return this.externalAddress;
}
@Override
public String getExternalPortRange() {
return this.externalPortRange;
}
@Override
public String getBindAddress() {
return this.bindAddress;
}
@Override
public Integer getBindPort() {
return this.bindPort;
}
@Override
public MetricsCollector getUsageSupplier() {
return this.metricsCollector;
}
@Override
public URI getBlobStoreArtifactDir() {
return this.blobStoreArtifactDir;
}
@Override
public File getLocalStorageDir() {
return this.localStorageDir;
}
@Override
public double getNetworkBandwidthInMB() {
return this.networkBandwidthInMB;
}
@Override
public String taskExecutorAttributes() {
return this.taskExecutorAttributesStr;
}
@Override
public File getRegistrationStoreDir() {
return null;
}
}
| 8,850 |
0 | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader | Create_ds/mantis/mantis-runtime-loader/src/main/java/io/mantisrx/runtime/loader/config/Usage.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.loader.config;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
import lombok.Value;
@RequiredArgsConstructor
@Value
@Builder
public class Usage {
double cpusLimit;
double cpusSystemTimeSecs;
double cpusUserTimeSecs;
double memLimit;
double memRssBytes;
double memAnonBytes;
double networkReadBytes;
double networkWriteBytes;
}
| 8,851 |
0 | Create_ds/mantis/mantis-testcontainers/src/test | Create_ds/mantis/mantis-testcontainers/src/test/java/TestContainerHelloWorld.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import io.mantisrx.common.metrics.LoggingMetricsPublisher;
import io.mantisrx.server.master.resourcecluster.TaskExecutorID;
import io.mantisrx.shaded.com.fasterxml.jackson.core.type.TypeReference;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper;
import io.mantisrx.shaded.org.apache.curator.framework.CuratorFramework;
import io.mantisrx.shaded.org.apache.curator.framework.CuratorFrameworkFactory;
import io.mantisrx.shaded.org.apache.curator.retry.RetryOneTime;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import okhttp3.HttpUrl.Builder;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.junit.BeforeClass;
import org.junit.Test;
import org.testcontainers.containers.Container;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.images.builder.ImageFromDockerfile;
import org.testcontainers.utility.Base58;
import org.testcontainers.utility.MountableFile;
@Slf4j
public class TestContainerHelloWorld {
private static final int ZOOKEEPER_PORT = 2181;
private static final int CONTROL_PLANE_API_PORT = 8100;
private static final String ZOOKEEPER_ALIAS = "zookeeper";
// set to false to run remote/pre-bulit images.
private static final boolean USE_LOCAL_BUILT_IMAGE = true;
private static final String CONTROL_PLANE_ALIAS = "mantiscontrolplane";
private static final String CLUSTER_ID = "testcluster1";
private static final String JOB_CLUSTER_NAME = "hello-sine-testcontainers";
private static final String CONTAINER_ARTIFACT_PATH = "/apps/mantis/mantis-server-agent/mantis-artifacts/storage/";
private static final String LOGGING_ENABLED_METRICS_GROUP =
"MasterApiMetrics;DeadLetterActor;JobDiscoveryRoute";
private static final String JOB_CLUSTER_CREATE = "{\"jobDefinition\":{\"name\":\"hello-sine-testcontainers\","
+ "\"user\":\"mantisoss\",\"jobJarFileLocation\":\"file:///mantis-examples-sine-function-2.1.0-SNAPSHOT"
+ ".zip\"," +
"\"version\":\"0.2.9 2018-05-29 16:12:56\",\"schedulingInfo\":{\"stages\":{" +
"\"1\":{\"numberOfInstances\":\"1\",\"machineDefinition\":{\"cpuCores\":\"1\",\"memoryMB\":\"1024\",\"diskMB\":\"1024\",\"networkMbps\":\"128\",\"numPorts\":\"1\"},\"scalable\":true," +
"\"scalingPolicy\":{" +
"},\"softConstraints\":[],\"hardConstraints\":[]}}}," +
"\"parameters\":[{\"name\":\"useRandom\",\"value\":\"false\"}],\"labels\":[{\"name\":\"_mantis"
+ ".resourceCluster\",\"value\":\"testcluster1\"},"
+ "{\"name\":\"_mantis.user\",\"value\":\"mantisoss\"},{\"name\":\"_mantis"
+ ".ownerEmail\",\"value\":\"mantisoss@netflix.com\"},{\"name\":\"_mantis.jobType\",\"value\":\"other\"},"
+ "{\"name\":\"_mantis.criticality\",\"value\":\"low\"},{\"name\":\"_mantis.artifact.version\",\"value\":\"0.2.9\"}]," +
"\"migrationConfig\":{\"strategy\":\"PERCENTAGE\",\"configString\":\"{\\\"percentToMove\\\":25,\\\"intervalMs\\\":60000}\"},\"slaMin\":\"0\",\"slaMax\":\"0\",\"cronSpec\":null,\"cronPolicy\":\"KEEP_EXISTING\",\"isReadyForJobMaster\":true}," +
"\"owner\":{\"contactEmail\":\"mantisoss@netflix.com\",\"description\":\"\",\"name\":\"Mantis OSS\","
+ "\"repo\":\"\",\"teamName\":\"\"}}";
private static final String QUICK_SUBMIT =
"{\"name\":\"hello-sine-testcontainers\",\"user\":\"mantisoss\",\"jobSla\":{\"durationType\":\"Perpetual\","
+ "\"runtimeLimitSecs\":\"0\",\"minRuntimeSecs\":\"0\",\"userProvidedType\":\"\"}}";
private static final String REGULAR_SUBMIT = "{\"name\":\"hello-sine-testcontainers\",\"user\":\"mantisoss\","
+ "\"jobJarFileLocation\":\"file:///mantis-examples-sine-function-2.1.0-SNAPSHOT.zip\",\"version\":\"0.2.9 2018-05-29 16:12:56\","
+ "\"subscriptionTimeoutSecs\":\"0\",\"jobSla\":{\"durationType\":\"Transient\","
+ "\"runtimeLimitSecs\":\"300\",\"minRuntimeSecs\":\"0\"},"
+ "\"schedulingInfo\":{\"stages\":{\"1\":{\"numberOfInstances\":1,\"machineDefinition\":{\"cpuCores\":1,"
+ "\"memoryMB\":1024,\"diskMB\":1024,\"networkMbps\":128,\"numPorts\":\"1\"},\"scalable\":true,"
+ "\"softConstraints\":[],\"hardConstraints\":[]}}},\"parameters\":[{\"name\":\"useRandom\",\"value\":\"false\"}],"
+ "\"isReadyForJobMaster\":false}";
private static final OkHttpClient HTTP_CLIENT = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
private static final Path path = Paths.get("../mantis-control-plane/mantis-control-plane-server/build/docker/Dockerfile");
public static final String JAVA_OPTS = "--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/sun.net.util=ALL-UNNAMED";
private static ImageFromDockerfile controlPlaneDockerFile;
private static ImageFromDockerfile agentDockerFile;
private static Network network = Network.newNetwork();
private static GenericContainer<?> zookeeper;
private static GenericContainer<?> controlPlaneLeader;
private static String controlPlaneLeaderUrl;
private static String controlPlaneHost;
private static int controlPlanePort;
private static OkHttpClient client = new OkHttpClient();
@BeforeClass
public static void prepareControlPlane() throws Exception {
log.info("Building control plane image from: {}", path);
controlPlaneDockerFile =
new ImageFromDockerfile("localhost/testcontainers/mantis_control_plane_server_" + Base58.randomString(4).toLowerCase())
.withDockerfile(path);
zookeeper =
new GenericContainer<>("zookeeper:3.8.0")
.withNetwork(network)
.withNetworkAliases(ZOOKEEPER_ALIAS)
.withExposedPorts(ZOOKEEPER_PORT);
controlPlaneLeader = USE_LOCAL_BUILT_IMAGE ?
new GenericContainer<>(controlPlaneDockerFile)
.withEnv(LoggingMetricsPublisher.LOGGING_ENABLED_METRICS_GROUP_ID_LIST_KEY,
LOGGING_ENABLED_METRICS_GROUP)
.withEnv("JAVA_OPTS", JAVA_OPTS)
.withNetwork(network)
.withNetworkAliases(CONTROL_PLANE_ALIAS)
.withExposedPorts(CONTROL_PLANE_API_PORT)
:
new GenericContainer<>("netflixoss/mantiscontrolplaneserver:latest")
.withEnv(LoggingMetricsPublisher.LOGGING_ENABLED_METRICS_GROUP_ID_LIST_KEY,
LOGGING_ENABLED_METRICS_GROUP)
.withEnv("JAVA_OPTS", JAVA_OPTS)
.withNetwork(network)
.withNetworkAliases(CONTROL_PLANE_ALIAS)
.withExposedPorts(CONTROL_PLANE_API_PORT);
zookeeper.start();
zkCheck(zookeeper);
// master.addEnv("MANTIS_ZOOKEEPER_CONNECTSTRING", "zk:2181");
controlPlaneLeader.start();
log.info("Finish start controlPlaneLeader");
controlPlaneLeaderUrl = String.format(
"http://%s:%d/api/", controlPlaneLeader.getHost(), controlPlaneLeader.getMappedPort(CONTROL_PLANE_API_PORT));
log.info("Using control plane url: {}", controlPlaneLeaderUrl);
controlPlaneHost = controlPlaneLeader.getHost();
controlPlanePort = controlPlaneLeader.getMappedPort(CONTROL_PLANE_API_PORT);
Path agentDockerFilePath = Paths.get("../mantis-server/mantis-server-agent/build/docker/Dockerfile");
log.info("Building agent image from: {}", agentDockerFilePath);
agentDockerFile =
new ImageFromDockerfile("localhost/testcontainers/mantis_agent_" + Base58.randomString(4).toLowerCase())
.withDockerfile(agentDockerFilePath);
assertTrue("Failed to create job cluster", createJobCluster(controlPlaneHost, controlPlanePort));
assertTrue("Failed to get job cluster", getJobCluster(controlPlaneHost, controlPlanePort));
}
@Test
public void testQuickSubmitJob() throws IOException, InterruptedException {
Request request = new Request.Builder()
.url(controlPlaneLeaderUrl + "v1/resourceClusters/list")
.build();
Response response = client.newCall(request).execute();
log.info(response.body().string());
// Create agent(s)
final String agentId0 = "agentquicksubmit";
final String agent0Hostname = String.format("%s%shostname", agentId0, CLUSTER_ID);
GenericContainer<?> agent0 = createAgent(agentId0, CLUSTER_ID, agent0Hostname, agentDockerFile, network);
if (!ensureAgentStarted(
controlPlaneHost,
controlPlanePort,
CLUSTER_ID,
agentId0,
agent0,
5,
Duration.ofSeconds(3).toMillis())) {
fail("Failed to register agent: " + agent0.getContainerId());
}
quickSubmitJobCluster(controlPlaneHost, controlPlanePort);
if (!ensureJobWorkerStarted(
controlPlaneHost,
controlPlanePort,
5,
Duration.ofSeconds(2).toMillis())) {
fail("Failed to start job worker.");
}
// test sse
String cmd = "curl -N -H \"Accept: text/event-stream\" \"localhost:5055\" & sleep 3; kill $!";
Container.ExecResult lsResult = agent0.execInContainer("bash", "-c", cmd);
String stdout = lsResult.getStdout();
log.info("stdout: {}", stdout);
assertTrue(stdout.contains("data: {\"x\":"));
testTEStates(controlPlaneHost, controlPlanePort, agentId0);
/*
Uncomment following lines to keep the containers running.
*/
// log.warn("Waiting for exit test.");
// Thread.sleep(Duration.ofSeconds(3600).toMillis());
}
@Test
public void testRegularSubmitJob() throws IOException, InterruptedException {
Request request = new Request.Builder()
.url(controlPlaneLeaderUrl + "v1/resourceClusters/list")
.build();
Response response = client.newCall(request).execute();
log.info(response.body().string());
// Create agent(s)
final String agentId0 = "agentregularsubmit";
final String agent0Hostname = String.format("%s%shostname", agentId0, CLUSTER_ID);
GenericContainer<?> agent0 = createAgent(agentId0, CLUSTER_ID, agent0Hostname, agentDockerFile, network);
if (!ensureAgentStarted(
controlPlaneHost,
controlPlanePort,
CLUSTER_ID,
agentId0,
agent0,
5,
Duration.ofSeconds(3).toMillis())) {
fail("Failed to register agent: " + agent0.getContainerId());
}
submitJobCluster(controlPlaneHost, controlPlanePort);
if (!ensureJobWorkerStarted(
controlPlaneHost,
controlPlanePort,
5,
Duration.ofSeconds(2).toMillis())) {
fail("Failed to start job worker.");
}
// test sse
String cmd = "curl -N -H \"Accept: text/event-stream\" \"localhost:5055\" & sleep 3; kill $!";
Container.ExecResult lsResult = agent0.execInContainer("bash", "-c", cmd);
String stdout = lsResult.getStdout();
log.info("stdout: {}", stdout);
assertTrue(stdout.contains("data: {\"x\":"));
testTEStates(controlPlaneHost, controlPlanePort, agentId0);
/*
Uncomment following lines to keep the containers running.
*/
// log.warn("Waiting for exit test.");
// Thread.sleep(Duration.ofSeconds(3600).toMillis());
}
private static void zkCheck(GenericContainer<?> zookeeper) throws Exception {
final String path = "/messages/zk-tc";
final String content = "Running Zookeeper with Testcontainers";
String connectionString = zookeeper.getHost() + ":" + zookeeper.getMappedPort(ZOOKEEPER_PORT);
log.info(connectionString);
CuratorFramework curatorFramework = CuratorFrameworkFactory
.builder()
.connectString(connectionString)
.retryPolicy(new RetryOneTime(100))
.build();
curatorFramework.start();
curatorFramework.create().creatingParentsIfNeeded().forPath(path, content.getBytes());
byte[] bytes = curatorFramework.getData().forPath(path);
curatorFramework.close();
assertEquals(new String(bytes, StandardCharsets.UTF_8), content);
System.out.println("ZK check pass!");
}
private GenericContainer<?> createAgent(String agentId, String resourceClusterId, String hostname,
ImageFromDockerfile dockerFile, Network network) {
// setup sample job artifact
MountableFile sampleArtifact = MountableFile.forHostPath(
Paths.get("../mantis-examples/mantis-examples-sine-function/build/distributions/mantis-examples-sine-function-2.1.0-SNAPSHOT.zip"));
return USE_LOCAL_BUILT_IMAGE ?
new GenericContainer<>(dockerFile)
.withEnv("mantis_taskexecutor_cluster_id".toUpperCase(), resourceClusterId)
.withEnv("mantis_taskexecutor_id".toUpperCase(), agentId)
.withEnv("MANTIS_TASKEXECUTOR_RPC_EXTERNAL_ADDRESS", hostname)
.withEnv("JAVA_OPTS", JAVA_OPTS)
.withCopyFileToContainer(sampleArtifact, CONTAINER_ARTIFACT_PATH)
.withNetwork(network)
.withCreateContainerCmdModifier(it -> it.withName(hostname))
:
new GenericContainer<>("netflixoss/mantisserveragent:latest")
.withEnv("mantis_taskexecutor_cluster_id".toUpperCase(), resourceClusterId)
.withEnv("mantis_taskexecutor_id".toUpperCase(), agentId)
.withEnv("MANTIS_TASKEXECUTOR_RPC_EXTERNAL_ADDRESS", hostname)
.withEnv("JAVA_OPTS", JAVA_OPTS)
.withCopyFileToContainer(sampleArtifact, CONTAINER_ARTIFACT_PATH)
.withNetwork(network)
.withCreateContainerCmdModifier(it -> it.withName(hostname));
}
private boolean ensureAgentStarted(
String controlPlaneHost,
int controlPlanePort,
String resourceClusterId,
String agentId,
GenericContainer<?> agent,
int retries,
long sleepMillis) {
agent.start();
log.info("{} agent started.", agent.getContainerId());
HttpUrl reqUrl = new Builder()
.scheme("http")
.host(controlPlaneHost)
.port(controlPlanePort)
.addPathSegments("api/v1/resourceClusters")
.addPathSegment(resourceClusterId)
.addPathSegment("getRegisteredTaskExecutors")
.build();
log.info("Req: {}", reqUrl);
for(int i = 0; i < retries; i++) {
Request request = new Request.Builder()
.url(reqUrl)
.build();
try {
Response response = HTTP_CLIENT.newCall(request).execute();
String responseBody = response.body().string();
log.info("Registered agents: {}.", responseBody);
List<TaskExecutorID> listResponses =
mapper.readValue(responseBody, new TypeReference<List<TaskExecutorID>>() {});
for (TaskExecutorID taskExecutorID : listResponses) {
if (taskExecutorID.getResourceId().equals(agentId)) {
log.info("Agent {} has registered to {}.", agentId, resourceClusterId);
return true;
}
}
Thread.sleep(sleepMillis);
} catch (Exception e) {
log.warn("Get registred agent call error", e);
}
}
return false;
}
private boolean ensureJobWorkerStarted(
String controlPlaneHost,
int controlPlanePort,
int retries,
long sleepMillis) {
log.info("waiting for job worker to start.");
HttpUrl reqUrl = new Builder()
.scheme("http")
.host(controlPlaneHost)
.port(controlPlanePort)
.addPathSegments("api/v1/jobClusters")
.addPathSegment(JOB_CLUSTER_NAME)
.addPathSegment("latestJobDiscoveryInfo")
.build();
log.info("Req: {}", reqUrl);
for(int i = 0; i < retries; i++) {
Request request = new Request.Builder()
.url(reqUrl)
.build();
try {
Response response = HTTP_CLIENT.newCall(request).execute();
String responseBody = response.body().string();
log.info("Job cluster state: {}.", responseBody);
if (responseBody.contains("\"state\":\"Started\"")) {
log.info("Job worker started.");
return true;
}
Thread.sleep(sleepMillis);
} catch (Exception e) {
log.warn("Get registered agent call error", e);
}
}
return false;
}
private static boolean createJobCluster(
String controlPlaneHost,
int controlPlanePort) {
HttpUrl reqUrl = new Builder()
.scheme("http")
.host(controlPlaneHost)
.port(controlPlanePort)
.addPathSegments("api/v1/jobClusters")
.build();
log.info("Req: {}", reqUrl);
RequestBody body = RequestBody.create(
JOB_CLUSTER_CREATE, MediaType.parse("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url(reqUrl)
.post(body)
.build();
try {
Response response = HTTP_CLIENT.newCall(request).execute();
String responseBody = response.body().string();
log.info("Created job cluster response: {}.", responseBody);
} catch (Exception e) {
log.warn("Create cluster call error", e);
return false;
}
return true;
}
private void testTEStates(
String controlPlaneHost,
int controlPlanePort,
String agentId) {
try
{
Optional<Response> responseO = checkTeState(controlPlaneHost, controlPlanePort, agentId);
assertTrue(responseO.isPresent());
assertTrue(responseO.get().isSuccessful());
String resBody = responseO.get().body().string();
log.info("agent {}: {}", agentId, resBody);
assertTrue(resBody.contains("\"registered\":true,\"runningTask\":true"));
responseO = checkTeState(controlPlaneHost, controlPlanePort, "invalid");
assertTrue(responseO.isPresent());
assertEquals(404, responseO.get().code());
}
catch (IOException ioe) {
log.error("failed to check TE state", ioe);
fail("failed to check TE state " + ioe);
}
}
private Optional<Response> checkTeState(
String controlPlaneHost,
int controlPlanePort,
String teId) {
HttpUrl reqUrl = new Builder()
.scheme("http")
.host(controlPlaneHost)
.port(controlPlanePort)
.addPathSegments("api/v1/resourceClusters")
.addPathSegment(CLUSTER_ID)
.addPathSegment("taskExecutors")
.addPathSegment(teId)
.addPathSegment("getTaskExecutorState")
.build();
log.info("Req: {}", reqUrl);
Request request = new Request.Builder()
.url(reqUrl)
.get()
.build();
try {
Response response = HTTP_CLIENT.newCall(request).execute();
return Optional.of(response);
} catch (Exception e) {
log.warn("Get TE state call error", e);
return Optional.empty();
}
}
private boolean quickSubmitJobCluster(
String controlPlaneHost,
int controlPlanePort) {
HttpUrl reqUrl = new Builder()
.scheme("http")
.host(controlPlaneHost)
.port(controlPlanePort)
.addPathSegments("api/namedjob/quicksubmit")
.build();
log.info("Req: {}", reqUrl);
RequestBody body = RequestBody.create(
QUICK_SUBMIT, MediaType.parse("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url(reqUrl)
.post(body)
.build();
try {
Response response = HTTP_CLIENT.newCall(request).execute();
String responseBody = response.body().string();
log.info("Quick submit job response: {}.", responseBody);
} catch (Exception e) {
log.warn("Quick submit job call error", e);
}
return true;
}
private boolean submitJobCluster(
String controlPlaneHost,
int controlPlanePort) {
HttpUrl reqUrl = new Builder()
.scheme("http")
.host(controlPlaneHost)
.port(controlPlanePort)
.addPathSegments("api/submit")
.build();
log.info("Req: {}", reqUrl);
RequestBody body = RequestBody.create(
REGULAR_SUBMIT, MediaType.parse("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url(reqUrl)
.post(body)
.build();
try {
Response response = HTTP_CLIENT.newCall(request).execute();
String responseBody = response.body().string();
log.info("Regular submit job response: {}.", responseBody);
} catch (Exception e) {
log.warn("Regular submit job call error", e);
}
return true;
}
private static boolean getJobCluster(
String controlPlaneHost,
int controlPlanePort) {
HttpUrl reqUrl = new Builder()
.scheme("http")
.host(controlPlaneHost)
.port(controlPlanePort)
.addPathSegments("api/v1/jobClusters")
.addPathSegment(JOB_CLUSTER_NAME)
.build();
log.info("Req: {}", reqUrl);
Request request = new Request.Builder()
.url(reqUrl)
.build();
try {
Response response = HTTP_CLIENT.newCall(request).execute();
String responseBody = response.body().string();
log.info("Get job cluster response: {}.", responseBody);
} catch (Exception e) {
log.warn("GET job cluster call error", e);
}
return true;
}
private boolean getJobSink(
GenericContainer<?> agent) {
HttpUrl reqUrl = new Builder()
.scheme("http")
.host(agent.getHost())
.port(agent.getMappedPort(5055))
.build();
log.info("Req: {}", reqUrl);
Request request = new Request.Builder()
.url(reqUrl)
.build();
try {
Response response = HTTP_CLIENT.newCall(request).execute();
String responseBody = response.body().string();
log.info("Get job sink response: {}.", responseBody);
} catch (Exception e) {
log.warn("GET job sink call error", e);
}
return true;
}
}
| 8,852 |
0 | Create_ds/lumberyard/dev/Code/Tools/Android | Create_ds/lumberyard/dev/Code/Tools/Android/ProjectBuilder/ProjectActivity.java |
package ${ANDROID_PACKAGE};
import android.util.Log;
import com.amazon.lumberyard.LumberyardActivity;
////////////////////////////////////////////////////////////////////////////////////////////////////
public class ${ANDROID_PROJECT_ACTIVITY} extends LumberyardActivity
{
// since we are using the NativeActivity, all we need to manually load is the
// shared c++ libray we are using
static
{
Log.d("LMBR", "BootStrap: Starting Library load");
System.loadLibrary("c++_shared");
Log.d("LMBR", "BootStrap: Finished Library load");
}
} | 8,853 |
0 | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/test/SimpleObject.java | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
package com.amazon.test;
import java.util.Random;
public class SimpleObject
{
public class Foo
{
public Foo(int seed)
{
Random rand = new Random(seed);
m_value = rand.nextInt();
}
// ----
public int m_value;
}
// ----
public SimpleObject() {}
public boolean GetBool() { return true; }
public boolean[] GetBoolArray() { return new boolean[] { true, false, true, false }; }
public char GetChar() { return 'L'; }
public char[] GetCharArray() { return new char[] { 'L', 'u', 'm', 'b', 'e', 'r', 'y', 'a', 'r', 'd' }; }
public byte GetByte() { return 1; }
public byte[] GetByteArray() { return new byte[] { 1, 2, 4, 8, 16, 32 }; }
public short GetShort() { return 128; }
public short[] GetShortArray() { return new short[] { 128, 256, 512, 1024, 2048, 8192 }; }
public int GetInt() { return 32768; }
public int[] GetIntArray() { return new int[] { 32768, 65536, 131072, 262144, 524288, 1048576 }; }
public float GetFloat() { return (float)Math.PI; }
public float[] GetFloatArray()
{
float[] result = new float[6];
for (int i = 0; i < 6; ++i)
{
result[i] = (float)(i + 1) / 7.0f;
}
return result;
}
public double GetDouble() { return Math.PI; }
public double[] GetDoubleArray()
{
double[] result = new double[6];
for (int i = 0; i < 6; ++i)
{
result[i] = (double)(i + 1) / 7.0;
}
return result;
}
public Class GetClass() { return this.getClass(); }
public String GetString() { return "Amazon Lumberyard"; }
public Foo GetObject() { return new Foo(1); }
public Foo[] GetObjectArray() { return new Foo[] { new Foo(1), new Foo(2), new Foo(3), new Foo(4) }; }
// ----
private static final String TAG = "SimpleObject";
} | 8,854 |
0 | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard/ActivityResultsListener.java | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
package com.amazon.lumberyard;
import android.app.Activity;
import android.content.Intent;
////////////////////////////////////////////////////////////////
public abstract class ActivityResultsListener
{
public ActivityResultsListener(Activity activity)
{
((LumberyardActivity)activity).RegisterActivityResultsListener(this);
}
public abstract boolean ProcessActivityResult(int requestCode, int resultCode, Intent data);
}
| 8,855 |
0 | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard/LumberyardActivity.java | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
package com.amazon.lumberyard;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.NativeActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Point;
import android.Manifest;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Looper;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.lang.InterruptedException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.amazon.lumberyard.io.APKHandler;
import com.amazon.lumberyard.io.obb.ObbDownloaderActivity;
////////////////////////////////////////////////////////////////
public class LumberyardActivity extends NativeActivity
{
////////////////////////////////////////////////////////////////
// Native methods
public static native void nativeOnRequestPermissionsResult(boolean granted);
////////////////////////////////////////////////////////////////
@Override
public void onBackPressed()
{
// by doing nothing here will prevent the activity from being exited (the default behaviour)
}
////////////////////////////////////////////////////////////////
// called from the native to get the application package name
// e.g. com.lumberyard.samples for SamplesProject
public String GetPackageName()
{
return getApplicationContext().getPackageName();
}
////////////////////////////////////////////////////////////////
// called from the native to get the app version code
// android:versionCode in the AndroidManifest.xml.
public int GetAppVersionCode()
{
try
{
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
return pInfo.versionCode;
}
catch (NameNotFoundException e)
{
return 0;
}
}
////////////////////////////////////////////////////////////////
// called from the native code to show the Java splash screen
public void ShowSplashScreen()
{
Log.d(TAG, "ShowSplashScreen called");
this.runOnUiThread(new Runnable() {
@Override
public void run()
{
if (!m_splashShowing)
{
ShowSplashScreenImpl();
}
else
{
Log.d(TAG, "The splash screen is already showing");
}
}
});
}
////////////////////////////////////////////////////////////////
// called from the native code to dismiss the Java splash screen
public void DismissSplashScreen()
{
Log.d(TAG, "DismissSplashScreen called");
if (m_splashShowing)
{
this.runOnUiThread(new Runnable() {
@Override
public void run()
{
if (m_slashWindow != null)
{
Log.d(TAG, "Dismissing the splash screen");
m_slashWindow.dismiss();
m_slashWindow = null;
}
else
{
Log.d(TAG, "There is no splash screen to dismiss");
}
}
});
m_splashShowing = false;
}
}
////////////////////////////////////////////////////////////////
public void RegisterActivityResultsListener(ActivityResultsListener listener)
{
m_activityResultsListeners.add(listener);
}
////////////////////////////////////////////////////////////////
public void UnregisterActivityResultsListener(ActivityResultsListener listener)
{
m_activityResultsListeners.remove(listener);
}
////////////////////////////////////////////////////////////////
// Starts the download of the obb files and waits (block) until the activity finishes.
// Return true in case of success, false otherwise.
public boolean DownloadObb()
{
Intent downloadIntent = new Intent(this, ObbDownloaderActivity.class);
ActivityResult result = new ActivityResult();
if (launchActivity(downloadIntent, DOWNLOAD_OBB_REQUEST, true, result))
{
return result.m_result == Activity.RESULT_OK;
}
return false;
}
////////////////////////////////////////////////////////////////
// Returns the value of a boolean resource.
public boolean GetBooleanResource(String resourceName)
{
Resources resources = this.getResources();
int resourceId = resources.getIdentifier(resourceName, "bool", this.getPackageName());
return resources.getBoolean(resourceId);
}
////////////////////////////////////////////////////////////////
// Request permissions at runtime.
public void RequestPermission(final String permission, final String rationale)
{
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED)
{
Random rand = new Random();
m_runtimePermissionRequestCode = rand.nextInt(500);
final int requestCode = m_runtimePermissionRequestCode;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission))
{
final LumberyardActivity activity = this;
Runnable uiDialog = new Runnable()
{
public void run()
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
TextView textView = new TextView(activity);
String title = new String("Reason for requesting " + permission);
textView.setText(title + "\n" + rationale);
builder.setCustomTitle(textView);
builder.setItems(new String[]{"OK"}, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int index) {
ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode);
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
};
activity.runOnUiThread(uiDialog);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
}
}
else
{
nativeOnRequestPermissionsResult(true);
}
}
// ----
////////////////////////////////////////////////////////////////
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (GetBooleanResource("enable_keep_screen_on"))
{
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
ProcessImmersiveModeSetting();
APKHandler.SetAssetManager(getAssets());
AndroidDeviceManager.context = this;
boolean useMainObb = GetBooleanResource("use_main_obb");
boolean usePatchObb = GetBooleanResource("use_patch_obb");
if (IsBootstrapInAPK() && (useMainObb || usePatchObb))
{
Log.d(TAG, "Using OBB expansion files for game assets");
File obbRootPath = getApplicationContext().getObbDir();
String packageName = GetPackageName();
int appVersionCode = GetAppVersionCode();
String mainObbFilePath = String.format("%s/main.%d.%s.obb", obbRootPath, appVersionCode, packageName);
String patchObbFilePath = String.format("%s/patch.%d.%s.obb", obbRootPath, appVersionCode, packageName);
File mainObbFile = new File(mainObbFilePath);
File patchObbFile = new File(patchObbFilePath);
boolean needToDownload = ( (useMainObb && !mainObbFile.canRead())
|| (usePatchObb && !patchObbFile.canRead()));
if (needToDownload)
{
Log.d(TAG, "Attempting to download the OBB expansion files");
boolean downloadResult = DownloadObb();
if (!downloadResult)
{
Log.e(TAG, "****************************************************************");
Log.e(TAG, "Failed to download the OBB expansion file. Exiting...");
Log.e(TAG, "****************************************************************");
finish();
}
}
}
else
{
Log.d(TAG, "Assets already on the device, not using the OBB expansion files.");
}
// ensure we use the music media stream
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
////////////////////////////////////////////////////////////////
@Override
protected void onDestroy()
{
// Signal any thread that is waiting for the result of an activity
for(ActivityResult result : m_waitingResultList)
{
synchronized(result)
{
result.m_isRunning = false;
result.notifyAll();
}
}
// Ideally we should be calling super.onDestroy() here and going through the "graceful" shutdown process,
// however some deadlock(s) happen in the static de-allocation preventing the process to naturally exit.
// On phones, and most tablets, this doesn't happen because the process is terminated by the system but
// while running in Samsung DEX mode it's kept alive until it seemingly exits naturally. Manually killing
// the process in the onDestroy is probably the best compromise until the graceful exit is fixed with LY-70527
android.os.Process.killProcess(android.os.Process.myPid());
}
////////////////////////////////////////////////////////////////
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
if (hasFocus)
{
ProcessImmersiveModeSetting();
}
}
////////////////////////////////////////////////////////////////
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
for (ActivityResultsListener listener : m_activityResultsListeners)
{
listener.ProcessActivityResult(requestCode, resultCode, data);
}
}
////////////////////////////////////////////////////////////////
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
if (requestCode == m_runtimePermissionRequestCode)
{
if (grantResults.length > 0)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Log.d(TAG, "Permission Granted");
nativeOnRequestPermissionsResult(true);
}
else
{
Log.d(TAG, "Permission Denied");
nativeOnRequestPermissionsResult(false);
}
}
else
{
// Request was cancelled
nativeOnRequestPermissionsResult(false);
}
m_runtimePermissionRequestCode = -1;
}
}
// ----
////////////////////////////////////////////////////////////////
private boolean launchActivity(Intent intent, final int activityRequestCode, boolean waitForResult, final ActivityResult result)
{
if (waitForResult)
{
if (Looper.myLooper() == Looper.getMainLooper())
{
// Can't block if we are on the UI Thread.
return false;
}
ActivityResultsListener activityListener = new ActivityResultsListener(this)
{
@Override
public boolean ProcessActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == activityRequestCode)
{
synchronized(result)
{
result.m_result = resultCode;
result.m_isRunning = false;
result.notify();
}
return true;
}
return false;
}
};
this.RegisterActivityResultsListener(activityListener);
m_waitingResultList.add(result);
result.m_isRunning = true;
startActivityForResult(intent, activityRequestCode);
synchronized(result)
{
// Wait until the downloader activity finishes.
boolean ret = true;
while (result.m_isRunning)
{
try
{
result.wait();
}
catch(InterruptedException exception)
{
ret = false;
}
}
this.UnregisterActivityResultsListener(activityListener);
m_waitingResultList.remove(result);
return ret;
}
}
else
{
startActivityForResult(intent, activityRequestCode);
return true;
}
}
////////////////////////////////////////////////////////////////
private boolean IsBootstrapInAPK()
{
try
{
InputStream bootstrap = getAssets().open("bootstrap.cfg", AssetManager.ACCESS_UNKNOWN);
bootstrap.close();
return true;
}
catch (IOException exception)
{
return false;
}
}
////////////////////////////////////////////////////////////////
private void ShowSplashScreenImpl()
{
Log.d(TAG, "Showing the Splash Screen");
// load the splash screen view
Resources resources = getResources();
int layoutId = resources.getIdentifier("splash_screen", "layout", getPackageName());
LayoutInflater factory = LayoutInflater.from(this);
View splashView = factory.inflate(layoutId, null);
// get the resolution of the display
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
// create the popup with the splash screen layout. this is because the standard
// view hierarchy for Android apps doesn't exist when using the NativeActivity
m_slashWindow = new PopupWindow(splashView, size.x, size.y);
m_slashWindow.setClippingEnabled(false);
// add a dummy layout to the main view for the splash popup window
LinearLayout mainLayout = new LinearLayout(this);
setContentView(mainLayout);
// show the splash window
m_slashWindow.showAtLocation(mainLayout, Gravity.CENTER, 0, 0);
m_slashWindow.update();
m_splashShowing = true;
}
////////////////////////////////////////////////////////////////
private void ProcessImmersiveModeSetting()
{
int systemUiFlags = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
if (!GetBooleanResource("disable_immersive_mode"))
{
systemUiFlags |= (View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_FULLSCREEN |
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
getWindow().getDecorView().setSystemUiVisibility(systemUiFlags);
}
// ----
////////////////////////////////////////////////////////////////
private class ActivityResult
{
public int m_result;
public boolean m_isRunning;
}
// ----
private static final int DOWNLOAD_OBB_REQUEST = 1337;
private static final String TAG = "LMBR";
private PopupWindow m_slashWindow = null;
private boolean m_splashShowing = false;
private int m_runtimePermissionRequestCode = -1;
private List<ActivityResultsListener> m_activityResultsListeners = new ArrayList<ActivityResultsListener>();
private List<ActivityResult> m_waitingResultList = new ArrayList<ActivityResult>();
}
| 8,856 |
0 | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard/AndroidDeviceManager.java | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
package com.amazon.lumberyard;
import android.app.ActivityManager;
import android.content.Context;
////////////////////////////////////////////////////////////////////////////////////////////////////
public class AndroidDeviceManager
{
public static Context context;
public static final float bytesInGB = (1024.0f * 1024.0f * 1024.0f);
public static float GetDeviceRamInGB()
{
ActivityManager actManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
actManager.getMemoryInfo(memInfo);
float totalMemory = memInfo.totalMem / bytesInGB;
return totalMemory;
}
}
| 8,857 |
0 | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard/NativeUI/LumberyardNativeUI.java | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
package com.amazon.lumberyard.NativeUI;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicReference;
public class LumberyardNativeUI
{
public static void DisplayDialog(final Activity activity, final String title, final String message, final String[] options)
{
Log.d("LMBR", "DisplayDialog called");
userSelection = new AtomicReference<String>("");
userSelection.set("");
Runnable uiDialog = new Runnable()
{
public void run()
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
TextView textView = new TextView(activity);
textView.setText(title + "\n" + message);
builder.setCustomTitle(textView);
builder.setItems(options, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int index) {
userSelection.set(options[index]);
Log.d("LMBR", "Selected option: " + userSelection.get());
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
};
activity.runOnUiThread(uiDialog);
}
public static String GetUserSelection()
{
return userSelection.get();
}
public static AtomicReference<String> userSelection;
}
| 8,858 |
0 | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard/input/KeyboardHandler.java | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
package com.amazon.lumberyard.input;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.view.View;
////////////////////////////////////////////////////////////////
public class KeyboardHandler
{
// ----
// KeyboardHandler (public)
// ----
public static native void SendUnicodeText(String unicodeText);
////////////////////////////////////////////////////////////////
public KeyboardHandler(Activity activity)
{
m_activity = activity;
m_inputManager = (InputMethodManager)m_activity.getSystemService(Context.INPUT_METHOD_SERVICE);
}
////////////////////////////////////////////////////////////////
public void ShowTextInput()
{
m_activity.runOnUiThread(new Runnable() {
@Override
public void run()
{
if (m_textView == null)
{
m_textView = new DummyTextView(m_activity);
ViewGroup viewGroup = (ViewGroup)GetView();
viewGroup.addView(m_textView);
}
m_textView.Show();
m_inputManager.showSoftInput(m_textView, 0);
}
});
}
////////////////////////////////////////////////////////////////
public void HideTextInput()
{
if (m_textView != null)
{
m_activity.runOnUiThread(new Runnable() {
@Override
public void run()
{
m_inputManager.hideSoftInputFromWindow(m_textView.getWindowToken(), 0);
m_textView.Hide();
}
});
}
}
////////////////////////////////////////////////////////////////
public boolean IsShowing()
{
if (m_textView != null)
{
return m_textView.IsShowing();
}
return false;
}
// ----
private class DummyTextView extends View
{
////////////////////////////////////////////////////////////////
public DummyTextView(Context context)
{
super(context);
setFocusableInTouchMode(true);
setFocusable(true);
m_isShowing = false;
}
////////////////////////////////////////////////////////////////
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (event.isPrintingKey())
{
int unicode = event.getUnicodeChar();
String character = String.valueOf((char)unicode);
Log.d(s_tag, String.format("OnKeyDown - Unicode: %s - Printed character: %s", unicode, character));
SendUnicodeText(character);
}
return super.onKeyDown(keyCode, event);
}
////////////////////////////////////////////////////////////////
@Override
public boolean onKeyMultiple(int keyCode, int count, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_MULTIPLE && keyCode == KeyEvent.KEYCODE_UNKNOWN)
{
String text = event.getCharacters();
Log.d(s_tag, String.format("onKeyMultiple - Text: %s", text));
if (text != null)
{
SendUnicodeText(text);
}
}
return super.onKeyMultiple(keyCode, count, event);
}
////////////////////////////////////////////////////////////////
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
Hide();
}
return super.onKeyPreIme(keyCode, event);
}
////////////////////////////////////////////////////////////////
public boolean IsShowing()
{
return m_isShowing;
}
////////////////////////////////////////////////////////////////
public void Show()
{
m_windowFlags = GetView().getSystemUiVisibility();
setVisibility(View.VISIBLE);
requestFocus();
m_isShowing = true;
}
////////////////////////////////////////////////////////////////
public void Hide()
{
setVisibility(View.GONE);
m_isShowing = false;
GetView().setSystemUiVisibility(m_windowFlags);
}
// ----
private boolean m_isShowing;
private int m_windowFlags;
}
// ----
////////////////////////////////////////////////////////////////
private View GetView()
{
return m_activity.getWindow().getDecorView();
}
// ----
private static final String s_tag = "KeyboardHandler";
private Activity m_activity;
private InputMethodManager m_inputManager;
private DummyTextView m_textView;
} | 8,859 |
0 | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard/input/MouseDevice.java | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
package com.amazon.lumberyard.input;
import android.app.Activity;
import android.content.Context;
import android.hardware.input.InputManager;
import android.view.InputDevice;
import java.util.HashSet;
import java.util.Set;
public class MouseDevice
implements InputManager.InputDeviceListener
{
public native void OnMouseConnected();
public native void OnMouseDisconnected();
public MouseDevice(Activity activity)
{
m_inputManager = (InputManager)activity.getSystemService(Context.INPUT_SERVICE);
int[] devices = m_inputManager.getInputDeviceIds();
for (int deviceId : devices)
{
if (IsMouseDevice(deviceId))
{
m_mouseDeviceIds.add(deviceId);
}
}
final InputManager.InputDeviceListener listener = this;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
// run the registration on the main thread to use it's looper as the handler
// instead of creating one specifically for listening to mouse [dis]connections
m_inputManager.registerInputDeviceListener(listener, null);
}
});
}
@Override
public void onInputDeviceAdded(int deviceId)
{
if (IsMouseDevice(deviceId))
{
m_mouseDeviceIds.add(deviceId);
// only inform the native code if we change from having no mice connected, extra
// are effectively ignored and folded into one "master" device
if (m_mouseDeviceIds.size() == 1)
{
OnMouseConnected();
}
}
}
@Override
public void onInputDeviceChanged(int deviceId)
{
// do nothing
}
@Override
public void onInputDeviceRemoved(int deviceId)
{
if (m_mouseDeviceIds.contains(deviceId))
{
m_mouseDeviceIds.remove(deviceId);
// only inform the native code if we change to having no mice connected
if (m_mouseDeviceIds.size() == 0)
{
OnMouseDisconnected();
}
}
}
public boolean IsConnected()
{
return (m_mouseDeviceIds.size() > 0);
}
private boolean IsMouseDevice(int deviceId)
{
InputDevice device = m_inputManager.getInputDevice(deviceId);
if (device == null)
{
return false;
}
int sources = device.getSources();
return (sources == InputDevice.SOURCE_MOUSE);
}
private InputManager m_inputManager = null;
private Set<Integer> m_mouseDeviceIds = new HashSet<>();
}
| 8,860 |
0 | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard/input/MotionSensorManager.java | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
package com.amazon.lumberyard.input;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.Display;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import java.lang.Math;
////////////////////////////////////////////////////////////////////////////////////////////////////
public class MotionSensorManager implements SensorEventListener
{
private class MotionSensorData
{
private class SensorData3D
{
private float x;
private float y;
private float z;
private boolean updated;
}
private class SensorData4D
{
private float x;
private float y;
private float z;
private float w;
private boolean updated;
}
private SensorData3D accelerationRaw = new SensorData3D();
private SensorData3D accelerationUser = new SensorData3D();
private SensorData3D accelerationGravity = new SensorData3D();
private SensorData3D rotationRateRaw = new SensorData3D();
private SensorData3D rotationRateUnbiased = new SensorData3D();
private SensorData3D magneticFieldRaw = new SensorData3D();
private SensorData3D magneticFieldUnbiased = new SensorData3D();
private SensorData4D orientation = new SensorData4D();
}
private static final float METRES_PER_SECOND_SQUARED_TO_GFORCE = -1.0f / SensorManager.GRAVITY_EARTH;
private static final int MOTION_SENSOR_DATA_PACKED_LENGTH = 34;
private MotionSensorData m_motionSensorData = new MotionSensorData();
private float[] m_motionSensorDataPacked = new float[MOTION_SENSOR_DATA_PACKED_LENGTH];
private SensorManager m_sensorManager = null;
private Display m_defaultDisplay = null;
private float m_orientationAdjustmentRadiansZ = 0.0f;
private int m_orientationSensorToUse = Sensor.TYPE_GAME_ROTATION_VECTOR;
public MotionSensorManager(Activity activity)
{
m_sensorManager = (SensorManager)activity.getSystemService(Context.SENSOR_SERVICE);
m_defaultDisplay = ((WindowManager)activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
// If the game rotation vector is not available, default to the regular rotation vector.
if ((m_sensorManager != null) && (m_sensorManager.getDefaultSensor(m_orientationSensorToUse) == null))
{
m_orientationSensorToUse = Sensor.TYPE_ROTATION_VECTOR;
}
}
// Called when a motion sensor's accuracy changes
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
// Called when a motion sensor event is dispatched
@Override
public void onSensorChanged(SensorEvent event)
{
int currentDisplayRotation = m_defaultDisplay != null ?
m_defaultDisplay.getRotation() :
Surface.ROTATION_0;
Sensor sensor = event.sensor;
switch (sensor.getType())
{
case Sensor.TYPE_ACCELEROMETER:
{
// Convert to the same unit of measurement as returned natively by iOS,
// which is (arguably) more useful to use directly for game development.
AlignWithDisplay(m_motionSensorData.accelerationRaw,
event.values[0] * METRES_PER_SECOND_SQUARED_TO_GFORCE,
event.values[1] * METRES_PER_SECOND_SQUARED_TO_GFORCE,
event.values[2] * METRES_PER_SECOND_SQUARED_TO_GFORCE,
currentDisplayRotation);
}
break;
case Sensor.TYPE_LINEAR_ACCELERATION:
{
// Convert to the same unit of measurement as returned natively by iOS,
// which is (arguably) more useful to use directly for game development.
AlignWithDisplay(m_motionSensorData.accelerationUser,
event.values[0] * METRES_PER_SECOND_SQUARED_TO_GFORCE,
event.values[1] * METRES_PER_SECOND_SQUARED_TO_GFORCE,
event.values[2] * METRES_PER_SECOND_SQUARED_TO_GFORCE,
currentDisplayRotation);
}
break;
case Sensor.TYPE_GRAVITY:
{
// Convert to the same unit of measurement as returned natively by iOS,
// which is (arguably) more useful to use directly for game development.
AlignWithDisplay(m_motionSensorData.accelerationGravity,
event.values[0] * METRES_PER_SECOND_SQUARED_TO_GFORCE,
event.values[1] * METRES_PER_SECOND_SQUARED_TO_GFORCE,
event.values[2] * METRES_PER_SECOND_SQUARED_TO_GFORCE,
currentDisplayRotation);
}
break;
case Sensor.TYPE_GYROSCOPE_UNCALIBRATED:
{
AlignWithDisplay(m_motionSensorData.rotationRateRaw,
event.values[0],
event.values[1],
event.values[2],
currentDisplayRotation);
}
break;
case Sensor.TYPE_GYROSCOPE:
{
AlignWithDisplay(m_motionSensorData.rotationRateUnbiased,
event.values[0],
event.values[1],
event.values[2],
currentDisplayRotation);
}
break;
case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED:
{
AlignWithDisplay(m_motionSensorData.magneticFieldRaw,
event.values[0],
event.values[1],
event.values[2],
currentDisplayRotation);
}
break;
case Sensor.TYPE_MAGNETIC_FIELD:
{
AlignWithDisplay(m_motionSensorData.magneticFieldUnbiased,
event.values[0],
event.values[1],
event.values[2],
currentDisplayRotation);
}
break;
case Sensor.TYPE_GAME_ROTATION_VECTOR:
case Sensor.TYPE_ROTATION_VECTOR:
{
m_motionSensorData.orientation.x = event.values[0];
m_motionSensorData.orientation.y = event.values[1];
m_motionSensorData.orientation.z = event.values[2];
m_motionSensorData.orientation.w = event.values[3];
// Android doesn't provide us with any quaternion math,
// so we do the alignment in MotionSensorinputDevice.cpp
m_orientationAdjustmentRadiansZ = GetOrientationAdjustmentRadiansZ(currentDisplayRotation);
m_motionSensorData.orientation.updated = true;
}
break;
}
}
private void AlignWithDisplay(MotionSensorData.SensorData3D o_sensorData, float x, float y, float z, int displayRotation)
{
switch (displayRotation)
{
case Surface.ROTATION_90:
{
o_sensorData.x = -y;
o_sensorData.y = -z;
o_sensorData.z = x;
}
break;
case Surface.ROTATION_180:
{
o_sensorData.x = -x;
o_sensorData.y = -z;
o_sensorData.z = -y;
}
break;
case Surface.ROTATION_270:
{
o_sensorData.x = y;
o_sensorData.y = -z;
o_sensorData.z = -x;
}
break;
case Surface.ROTATION_0:
default:
{
o_sensorData.x = x;
o_sensorData.y = -z;
o_sensorData.z = y;
}
break;
}
o_sensorData.updated = true;
}
private float GetOrientationAdjustmentRadiansZ(int displayRotation)
{
switch (displayRotation)
{
case Surface.ROTATION_90:
{
return (float)(-Math.PI * 0.5d);
}
case Surface.ROTATION_180:
{
return (float)Math.PI;
}
case Surface.ROTATION_270:
{
return (float)(Math.PI * 0.5d);
}
case Surface.ROTATION_0:
default:
{
return 0.0f;
}
}
}
// Called from native code to query availability of motion sensor data.
public boolean IsMotionSensorDataAvailable(boolean accelerometerRaw,
boolean accelerometerUser,
boolean accelerometerGravity,
boolean rotationRateRaw,
boolean rotationRateUnbiased,
boolean magneticFieldRaw,
boolean magneticFieldUnbiased,
boolean orientation)
{
if (m_sensorManager == null)
{
return false;
}
if (accelerometerRaw && m_sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) == null)
{
return false;
}
if (accelerometerUser && m_sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION) == null)
{
return false;
}
if (accelerometerGravity && m_sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY) == null)
{
return false;
}
if (rotationRateRaw && m_sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE_UNCALIBRATED) == null)
{
return false;
}
if (rotationRateUnbiased && m_sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) == null)
{
return false;
}
if (magneticFieldRaw && m_sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED) == null)
{
return false;
}
if (magneticFieldUnbiased && m_sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) == null)
{
return false;
}
if (orientation && m_sensorManager.getDefaultSensor(m_orientationSensorToUse) == null)
{
return false;
}
return false;
}
// Called from native code to refresh motion sensors.
// state: -1 = disable, 0 = unchanged, 1 = enable
public void RefreshMotionSensors(float updateIntervalSeconds,
int accelerometerRawState,
int accelerometerUserState,
int accelerometerGravityState,
int rotationRateRawState,
int rotationRateUnbiasedState,
int magneticFieldRawState,
int magneticFieldUnbiasedState,
int orientationState)
{
int updateIntervalMicroeconds = (int)(updateIntervalSeconds * 1000000);
RefreshMotionSensor(Sensor.TYPE_ACCELEROMETER, accelerometerRawState, updateIntervalMicroeconds);
RefreshMotionSensor(Sensor.TYPE_LINEAR_ACCELERATION, accelerometerUserState, updateIntervalMicroeconds);
RefreshMotionSensor(Sensor.TYPE_GRAVITY, accelerometerGravityState, updateIntervalMicroeconds);
RefreshMotionSensor(Sensor.TYPE_GYROSCOPE_UNCALIBRATED, rotationRateRawState, updateIntervalMicroeconds);
RefreshMotionSensor(Sensor.TYPE_GYROSCOPE, rotationRateUnbiasedState, updateIntervalMicroeconds);
RefreshMotionSensor(Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED, magneticFieldRawState, updateIntervalMicroeconds);
RefreshMotionSensor(Sensor.TYPE_MAGNETIC_FIELD, magneticFieldUnbiasedState, updateIntervalMicroeconds);
RefreshMotionSensor(m_orientationSensorToUse, orientationState, updateIntervalMicroeconds);
}
private void RefreshMotionSensor(int sensorType, int state, int updateIntervalMicroeconds)
{
if (m_sensorManager == null)
{
return;
}
// state: -1 = disable, 0 = unchanged, 1 = enable
switch (state)
{
case 1:
{
Sensor defaultSensor = m_sensorManager.getDefaultSensor(sensorType);
if (defaultSensor != null)
{
m_sensorManager.registerListener(this, defaultSensor, updateIntervalMicroeconds);
}
}
break;
case -1:
{
Sensor defaultSensor = m_sensorManager.getDefaultSensor(sensorType);
if (defaultSensor != null)
{
m_sensorManager.unregisterListener(this, defaultSensor);
}
}
break;
}
}
// Called from native code to retrieve the latest motion sensor data.
public float[] RequestLatestMotionSensorData()
{
// While we would ideally like to just return m_motionSensorData directly,
// the native C++ code would then need to 'reach back' through the JNI
// for each field just to access the raw data. Simply returning a float
// array packed with all the required values is far more efficient, at
// the expense of the native C++ code having to access the data through
// 'magic' array indices instead of explcitly naming the class fields.
//
// Additionally, while explicitly calling out the class fields provides
// a modicum of safety, lots of boilerplate code is needed, and while we
// may in future append additional sensor data the existing elements are
// unlikely to ever change. Combined with the above mentioned performance
// considerations, this approach seems preferable on most fronts.
m_motionSensorDataPacked[0] = m_motionSensorData.accelerationRaw.updated ? 1 : 0;
m_motionSensorDataPacked[1] = m_motionSensorData.accelerationRaw.x;
m_motionSensorDataPacked[2] = m_motionSensorData.accelerationRaw.y;
m_motionSensorDataPacked[3] = m_motionSensorData.accelerationRaw.z;
m_motionSensorData.accelerationRaw.updated = false;
m_motionSensorDataPacked[4] = m_motionSensorData.accelerationUser.updated ? 1 : 0;
m_motionSensorDataPacked[5] = m_motionSensorData.accelerationUser.x;
m_motionSensorDataPacked[6] = m_motionSensorData.accelerationUser.y;
m_motionSensorDataPacked[7] = m_motionSensorData.accelerationUser.z;
m_motionSensorData.accelerationUser.updated = false;
m_motionSensorDataPacked[8] = m_motionSensorData.accelerationGravity.updated ? 1 : 0;
m_motionSensorDataPacked[9] = m_motionSensorData.accelerationGravity.x;
m_motionSensorDataPacked[10] = m_motionSensorData.accelerationGravity.y;
m_motionSensorDataPacked[11] = m_motionSensorData.accelerationGravity.z;
m_motionSensorData.accelerationGravity.updated = false;
m_motionSensorDataPacked[12] = m_motionSensorData.rotationRateRaw.updated ? 1 : 0;
m_motionSensorDataPacked[13] = m_motionSensorData.rotationRateRaw.x;
m_motionSensorDataPacked[14] = m_motionSensorData.rotationRateRaw.y;
m_motionSensorDataPacked[15] = m_motionSensorData.rotationRateRaw.z;
m_motionSensorData.rotationRateRaw.updated = false;
m_motionSensorDataPacked[16] = m_motionSensorData.rotationRateUnbiased.updated ? 1 : 0;
m_motionSensorDataPacked[17] = m_motionSensorData.rotationRateUnbiased.x;
m_motionSensorDataPacked[18] = m_motionSensorData.rotationRateUnbiased.y;
m_motionSensorDataPacked[19] = m_motionSensorData.rotationRateUnbiased.z;
m_motionSensorData.rotationRateUnbiased.updated = false;
m_motionSensorDataPacked[20] = m_motionSensorData.magneticFieldRaw.updated ? 1 : 0;
m_motionSensorDataPacked[21] = m_motionSensorData.magneticFieldRaw.x;
m_motionSensorDataPacked[22] = m_motionSensorData.magneticFieldRaw.y;
m_motionSensorDataPacked[23] = m_motionSensorData.magneticFieldRaw.z;
m_motionSensorData.magneticFieldRaw.updated = false;
m_motionSensorDataPacked[24] = m_motionSensorData.magneticFieldUnbiased.updated ? 1 : 0;
m_motionSensorDataPacked[25] = m_motionSensorData.magneticFieldUnbiased.x;
m_motionSensorDataPacked[26] = m_motionSensorData.magneticFieldUnbiased.y;
m_motionSensorDataPacked[27] = m_motionSensorData.magneticFieldUnbiased.z;
m_motionSensorData.magneticFieldUnbiased.updated = false;
m_motionSensorDataPacked[28] = m_motionSensorData.orientation.updated ? 1 : 0;
m_motionSensorDataPacked[29] = m_motionSensorData.orientation.x;
m_motionSensorDataPacked[30] = m_motionSensorData.orientation.y;
m_motionSensorDataPacked[31] = m_motionSensorData.orientation.z;
m_motionSensorDataPacked[32] = m_motionSensorData.orientation.w;
m_motionSensorDataPacked[33] = m_orientationAdjustmentRadiansZ;
m_motionSensorData.orientation.updated = false;
return m_motionSensorDataPacked;
}
}
| 8,861 |
0 | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard/io/APKHandler.java | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
package com.amazon.lumberyard.io;
import android.content.res.AssetManager;
import android.util.Log;
import java.io.IOException;
import android.app.Activity;
////////////////////////////////////////////////////////////////
public class APKHandler
{
////////////////////////////////////////////////////////////////
public static void SetAssetManager(AssetManager assetManager)
{
s_assetManager = assetManager;
}
////////////////////////////////////////////////////////////////
public static String[] GetFilesAndDirectoriesInPath(String path)
{
String[] filelist = {};
try
{
filelist = s_assetManager.list(path);
}
catch (IOException e)
{
Log.e(s_tag, String.format("File I/O error: %s", e.getMessage()));
e.printStackTrace();
}
finally
{
if (s_debug)
{
Log.d(s_tag, String.format("Files in path: %s", path));
for(String name : filelist)
{
Log.d(s_tag, String.format(" -- %s", name));
}
}
return filelist;
}
}
////////////////////////////////////////////////////////////////
public static boolean IsDirectory(String path)
{
String[] filelist = {};
boolean retVal = false;
try
{
filelist = s_assetManager.list(path);
if(filelist.length > 0)
{
retVal = true;
}
}
catch (IOException e)
{
Log.e(s_tag, String.format("File I/O error: %s", e.getMessage()));
e.printStackTrace();
}
finally
{
return retVal;
}
}
// ----
private static final String s_tag = "LMBR";
private static AssetManager s_assetManager = null;
private static boolean s_debug = false;
} | 8,862 |
0 | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard/io | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard/io/obb/ObbDownloaderService.java | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
package com.amazon.lumberyard.io.obb;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import com.google.android.vending.expansion.downloader.impl.DownloaderService;
import com.google.android.vending.licensing.util.Base64;
import com.google.android.vending.licensing.util.Base64DecoderException;
////////////////////////////////////////////////////////////////
// Service needed by the downloader library in order to get the public key, salt and alarm receiver class.
public class ObbDownloaderService extends DownloaderService
{
////////////////////////////////////////////////////////////////
@Override
public void onCreate ()
{
super.onCreate();
Context context = getApplicationContext();
Resources resources = getResources();
int stringId = resources.getIdentifier("public_key", "string", context.getPackageName());
m_base64PublicKey = resources.getString(stringId);
stringId = resources.getIdentifier("obfuscator_salt", "string", context.getPackageName());
String base64Salt = resources.getString(stringId);
if (!base64Salt.isEmpty())
{
try
{
m_salt = Base64.decode(base64Salt);
}
catch (Base64DecoderException e)
{
Log.e("ObbDownloaderService", "Failed to decode the salt string");
}
}
}
////////////////////////////////////////////////////////////////
@Override
public String getPublicKey()
{
return m_base64PublicKey;
}
////////////////////////////////////////////////////////////////
@Override
public byte[] getSALT()
{
return m_salt;
}
////////////////////////////////////////////////////////////////
@Override
public String getAlarmReceiverClassName()
{
return ObbDownloaderAlarmReceiver.class.getName();
}
////////////////////////////////////////////////////////////////
private String m_base64PublicKey;
private byte[] m_salt = new byte[] { 23, 12, 4, -12, -34, 23,
-120, 122, -23, -104, -2, -4, 12, 3, -21, 123, -11, 4, -11, 32
};
} | 8,863 |
0 | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard/io | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard/io/obb/ObbDownloaderAlarmReceiver.java | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
package com.amazon.lumberyard.io.obb;
import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
////////////////////////////////////////////////////////////////
// Alarm receiver needeed by the Downloader library for reasuming the download of the Obb.
public class ObbDownloaderAlarmReceiver extends BroadcastReceiver
{
////////////////////////////////////////////////////////////////
@Override
public void onReceive(Context context, Intent intent)
{
try
{
DownloaderClientMarshaller.startDownloadServiceIfRequired(context, intent, ObbDownloaderService.class);
}
catch (NameNotFoundException e)
{
e.printStackTrace();
}
}
} | 8,864 |
0 | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard/io | Create_ds/lumberyard/dev/Code/Framework/AzAndroid/java/com/amazon/lumberyard/io/obb/ObbDownloaderActivity.java | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
package com.amazon.lumberyard.io.obb;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Messenger;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.android.vending.expansion.downloader.Constants;
import com.google.android.vending.expansion.downloader.DownloadProgressInfo;
import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller;
import com.google.android.vending.expansion.downloader.DownloaderServiceMarshaller;
import com.google.android.vending.expansion.downloader.Helpers;
import com.google.android.vending.expansion.downloader.IDownloaderClient;
import com.google.android.vending.expansion.downloader.IDownloaderService;
import com.google.android.vending.expansion.downloader.IStub;
import java.lang.Exception;
////////////////////////////////////////////////////////////////
// Activity that handles the download of the APK expansion package (Obb)
public class ObbDownloaderActivity extends Activity implements IDownloaderClient
{
////////////////////////////////////////////////////////////////
@Override
public void onServiceConnected(Messenger messenger)
{
m_remoteService = DownloaderServiceMarshaller.CreateProxy(messenger);
m_remoteService.onClientUpdated(m_downloaderClientStub.getMessenger());
}
////////////////////////////////////////////////////////////////
@Override
public void onDownloadStateChanged(int newState)
{
setState(newState);
boolean showDashboard = true;
boolean showCellMessage = false;
boolean paused;
boolean indeterminate;
switch (newState)
{
case IDownloaderClient.STATE_IDLE:
// STATE_IDLE means the service is listening, so it's
// safe to start making calls via m_remoteService.
paused = false;
indeterminate = true;
break;
case IDownloaderClient.STATE_CONNECTING:
case IDownloaderClient.STATE_FETCHING_URL:
showDashboard = true;
paused = false;
indeterminate = true;
break;
case IDownloaderClient.STATE_DOWNLOADING:
paused = false;
showDashboard = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_FAILED_CANCELED:
case IDownloaderClient.STATE_FAILED:
case IDownloaderClient.STATE_FAILED_FETCHING_URL:
case IDownloaderClient.STATE_FAILED_UNLICENSED:
paused = true;
showDashboard = false;
indeterminate = false;
break;
case IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION:
case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION:
showDashboard = false;
paused = true;
indeterminate = false;
showCellMessage = true;
break;
case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
paused = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_PAUSED_ROAMING:
case IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE:
paused = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_COMPLETED:
showDashboard = false;
paused = false;
indeterminate = false;
endActivity(Activity.RESULT_OK);
return;
default:
paused = true;
indeterminate = true;
showDashboard = true;
}
int newDashboardVisibility = showDashboard ? View.VISIBLE : View.GONE;
if (m_dashboard.getVisibility() != newDashboardVisibility)
{
m_dashboard.setVisibility(newDashboardVisibility);
}
int cellMessageVisibility = showCellMessage ? View.VISIBLE : View.GONE;
if (m_cellMessage.getVisibility() != cellMessageVisibility)
{
m_cellMessage.setVisibility(cellMessageVisibility);
}
m_progressBar.setIndeterminate(indeterminate);
setButtonPausedState(paused);
}
////////////////////////////////////////////////////////////////
@Override
public void onDownloadProgress(DownloadProgressInfo progress)
{
m_averageSpeed.setText(getString(m_kbPerSecondTextId, Helpers.getSpeedString(progress.mCurrentSpeed)));
m_timeRemaining.setText(getString(m_timeRemainingTextId, Helpers.getTimeRemaining(progress.mTimeRemaining)));
progress.mOverallTotal = progress.mOverallTotal;
m_progressBar.setMax((int) (progress.mOverallTotal >> 8));
m_progressBar.setProgress((int) (progress.mOverallProgress >> 8));
m_progressPercent.setText(Long.toString(progress.mOverallProgress * 100 / progress.mOverallTotal) + "%");
m_progressFraction.setText(Helpers.getDownloadProgressString(progress.mOverallProgress, progress.mOverallTotal));
}
////////////////////////////////////////////////////////////////
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Build an Intent to start this activity from the Notification
Intent notifierIntent = new Intent(ObbDownloaderActivity.this, ObbDownloaderActivity.this.getClass());
notifierIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifierIntent, PendingIntent.FLAG_UPDATE_CURRENT);
try
{
// Start the download service (if required)
int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this, pendingIntent, ObbDownloaderService.class);
// If download has started, initialize this activity to show download progress
if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED)
{
initializeUI();
return;
}
}
catch (Exception e)
{
endActivity(Activity.RESULT_CANCELED);
return;
}
endActivity(Activity.RESULT_OK);
}
////////////////////////////////////////////////////////////////
@Override
protected void onResume()
{
if (m_downloaderClientStub != null)
{
m_downloaderClientStub.connect(this);
}
super.onResume();
}
////////////////////////////////////////////////////////////////
@Override
protected void onStop()
{
if (m_downloaderClientStub != null)
{
m_downloaderClientStub.disconnect(this);
}
super.onStop();
}
////////////////////////////////////////////////////////////////
protected void endActivity(int result)
{
if (isFinishing())
{
return;
}
Intent returnIntent = new Intent();
setResult(result, returnIntent);
finish();
}
////////////////////////////////////////////////////////////////
private void setState(int newState)
{
if (m_state != newState)
{
m_state = newState;
m_statusText.setText(Helpers.getDownloaderStringResourceIDFromState(newState));
}
}
////////////////////////////////////////////////////////////////
private void setButtonPausedState(boolean paused)
{
m_statePaused = paused;
int stringResourceID = paused ? m_buttonResumeTextId : m_buttonPauseTextId;
m_pauseButton.setText(stringResourceID);
}
////////////////////////////////////////////////////////////////
private void initializeUI()
{
Resources resources = this.getResources();
String packageName = getApplicationContext().getPackageName();
m_downloaderClientStub = DownloaderClientMarshaller.CreateStub(this, ObbDownloaderService.class);
setContentView(resources.getIdentifier("obb_downloader", "layout", packageName));
m_progressBar = (ProgressBar) findViewById(resources.getIdentifier("progressBar", "id", packageName));
m_statusText = (TextView) findViewById(resources.getIdentifier("statusText", "id", packageName));
m_progressFraction = (TextView) findViewById(resources.getIdentifier("progressAsFraction", "id", packageName));
m_progressPercent = (TextView) findViewById(resources.getIdentifier("progressAsPercentage", "id", packageName));
m_averageSpeed = (TextView) findViewById(resources.getIdentifier("progressAverageSpeed", "id", packageName));
m_timeRemaining = (TextView) findViewById(resources.getIdentifier("progressTimeRemaining", "id", packageName));
m_dashboard = findViewById(resources.getIdentifier("downloaderDashboard", "id", packageName));
m_cellMessage = findViewById(resources.getIdentifier("approveCellular", "id", packageName));
m_pauseButton = (Button) findViewById(resources.getIdentifier("pauseButton", "id", packageName));
m_wiFiSettingsButton = (Button) findViewById(resources.getIdentifier("wifiSettingsButton", "id", packageName));
m_buttonResumeTextId = resources.getIdentifier("text_button_resume", "string", packageName);
m_buttonPauseTextId = resources.getIdentifier("text_button_pause", "string", packageName);
m_timeRemainingTextId = resources.getIdentifier("time_remaining", "string", packageName);
m_kbPerSecondTextId = resources.getIdentifier("kilobytes_per_second", "string", packageName);
m_pauseButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
if (m_statePaused)
{
m_remoteService.requestContinueDownload();
}
else
{
m_remoteService.requestPauseDownload();
}
setButtonPausedState(!m_statePaused);
}
});
m_wiFiSettingsButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
});
Button resumeOnCell = (Button) findViewById(resources.getIdentifier("resumeOverCellular", "id", packageName));
resumeOnCell.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
m_remoteService.setDownloadFlags(IDownloaderService.FLAGS_DOWNLOAD_OVER_CELLULAR);
m_remoteService.requestContinueDownload();
m_cellMessage.setVisibility(View.GONE);
}
});
}
private static final String TAG = "ObbDownloaderActivity";
private ProgressBar m_progressBar;
private TextView m_statusText;
private TextView m_progressFraction;
private TextView m_progressPercent;
private TextView m_averageSpeed;
private TextView m_timeRemaining;
private View m_dashboard;
private View m_cellMessage;
private Button m_pauseButton;
private Button m_wiFiSettingsButton;
private boolean m_statePaused;
private int m_state;
private IDownloaderService m_remoteService;
private IStub m_downloaderClientStub;
private int m_buttonResumeTextId;
private int m_buttonPauseTextId;
private int m_kbPerSecondTextId;
private int m_timeRemainingTextId;
} | 8,865 |
0 | Create_ds/lumberyard/dev/Gems/Microphone/Code/Source/Platform/Android/java/com/amazon/lumberyard | Create_ds/lumberyard/dev/Gems/Microphone/Code/Source/Platform/Android/java/com/amazon/lumberyard/Microphone/MicrophoneSystemComponent.java | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
package com.amazon.lumberyard.Microphone;
import android.media.AudioRecord;
import android.media.AudioFormat;
import android.media.MediaRecorder;
import android.util.Log;
import java.lang.Thread;
import java.lang.Runnable;
import java.lang.String;
import java.nio.ByteBuffer;
public class MicrophoneSystemComponent implements Runnable
{
private AudioRecord recorder = null;
private Thread recordingThread = null;
private int bufferSize = 0;
private int format = 0;
private int sampleRate = 0;
private int numChannels = 0;
private static final int guaranteedSampleRate = 44100;
private static final int desiredChannels = 1;
private static final int desiredBitRate = 16;
private static final int bufferSizeMultiplier = 10;
private static final int frameSize = 1024;
private static MicrophoneSystemComponent instance = null;
public static native void SendCurrentData(byte[] data, int size);
public static MicrophoneSystemComponent getInstance() {
if(instance == null)
{
instance = new MicrophoneSystemComponent();
}
return instance;
}
public static boolean InitializeDevice()
{
return getInstance().InitializeDeviceImpl(guaranteedSampleRate, desiredChannels, desiredBitRate, false);
}
public static void ShutdownDevice()
{
getInstance().ShutdownDeviceImpl();
}
public static boolean StartSession()
{
return getInstance().StartSessionImpl();
}
public static void EndSession()
{
getInstance().EndSessionImpl();
}
public static boolean IsCapturing()
{
return getInstance().IsCapturingImpl();
}
public static void ProcessData(ByteBuffer buffer, int sizeRead)
{
byte[] data = new byte[sizeRead];
buffer.get(data, 0, sizeRead);
SendCurrentData(data, sizeRead);
}
private boolean InitializeDeviceImpl(int sampleRateIn, int numChannelsIn, int bitsPerSampleIn, boolean isFloatIn)
{
sampleRate = sampleRateIn;
if(numChannelsIn == 1)
{
numChannels = AudioFormat.CHANNEL_IN_MONO;
}
else if(numChannelsIn == 2)
{
numChannels = AudioFormat.CHANNEL_IN_STEREO;
}
else
{
Log.d("LMBR", String.format("Microphone::InitializeDevice, channel count wasn't 1 or 2. Instead got %d", numChannelsIn));
}
if(isFloatIn == true)
{
format = AudioFormat.ENCODING_PCM_FLOAT;
}
else
{
if(bitsPerSampleIn == 8)
{
format = AudioFormat.ENCODING_PCM_8BIT;
}
else if(bitsPerSampleIn == 16)
{
format = AudioFormat.ENCODING_PCM_16BIT;
}
else
{
Log.d("LMBR", String.format("Microphone::InitializeDevice, bits per sample wasn't 8 or 16. Instead got %d", bitsPerSampleIn));
}
}
if(format != 0 && sampleRate != 0 && numChannels != 0)
{
// 44100 is the only guaranteed sample rate, so always use that and then downsample as needed
bufferSize = AudioRecord.getMinBufferSize(guaranteedSampleRate, numChannels, format) * bufferSizeMultiplier;
if(bufferSize != AudioRecord.ERROR_BAD_VALUE && bufferSize != AudioRecord.ERROR)
{
recorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, guaranteedSampleRate, numChannels, format, bufferSize);
if(recorder != null && recorder.getState() == AudioRecord.STATE_INITIALIZED)
{
return true;
}
}
}
Log.d("LMBR", "Microphone::InitializeDevice, unable to create AudioRecord");
return false;
}
private void ShutdownDeviceImpl()
{
if(recorder != null && recorder.getState() == AudioRecord.STATE_INITIALIZED)
{
recorder.stop();
recorder.release();
}
recorder = null;
recordingThread = null;
}
private boolean StartSessionImpl()
{
if(recorder != null && recorder.getState() == AudioRecord.STATE_INITIALIZED)
{
if(IsCapturingImpl())
{
EndSessionImpl();
}
recorder.startRecording();
recordingThread = new Thread(this);
recordingThread.start();
return true;
}
return false;
}
private void EndSessionImpl()
{
if(recorder != null && recorder.getState() == AudioRecord.STATE_INITIALIZED)
{
recorder.stop();
}
}
private boolean IsCapturingImpl()
{
if(recorder != null)
{
return recorder.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING;
}
else
{
return false;
}
}
@Override
public void run()
{
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
while(recorder.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING)
{
ByteBuffer tempBuf = ByteBuffer.allocateDirect(frameSize);
int sizeRead = recorder.read(tempBuf, frameSize);
if(sizeRead >= 1)
{
ProcessData(tempBuf, sizeRead);
}
}
}
@Override
protected void finalize() throws Throwable
{
super.finalize();
ShutdownDeviceImpl();
}
} | 8,866 |
0 | Create_ds/lumberyard/dev/Gems/InAppPurchases/Code/Source/Platform/Android/java/com/amazon/lumberyard | Create_ds/lumberyard/dev/Gems/InAppPurchases/Code/Source/Platform/Android/java/com/amazon/lumberyard/iap/LumberyardInAppBilling.java | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
package com.amazon.lumberyard.iap;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;
public class LumberyardInAppBilling implements PurchasesUpdatedListener
{
public LumberyardInAppBilling(Activity activity)
{
m_activity = activity;
m_packageName = m_activity.getPackageName();
Resources resources = m_activity.getResources();
int stringId = resources.getIdentifier("public_key", "string", m_activity.getPackageName());
m_appPublicKey = resources.getString(stringId);
m_setupDone = false;
final LumberyardInAppBilling iapInstance = this;
if (!IsKindleDevice())
{
(new Thread(new Runnable()
{
public void run()
{
Looper.prepare();
m_billingClient = BillingClient.newBuilder(m_activity).setListener(iapInstance).build();
m_billingClient.startConnection(new BillingClientStateListener()
{
@Override
public void onBillingSetupFinished(int responseCode)
{
Log.d(s_tag, "Service connected");
if (!m_billingClient.isReady())
{
Log.d(s_tag, m_packageName + " IN_APP items not supported!");
return;
}
int subscriptionsResponseCode = m_billingClient.isFeatureSupported(BillingClient.FeatureType.SUBSCRIPTIONS);
if (!VerifyResponseCode(subscriptionsResponseCode))
{
return;
}
subscriptionsResponseCode = m_billingClient.isFeatureSupported(BillingClient.FeatureType.SUBSCRIPTIONS_UPDATE);
if (!VerifyResponseCode(subscriptionsResponseCode))
{
return;
}
m_setupDone = true;
}
@Override
public void onBillingServiceDisconnected()
{
Log.d(s_tag, "Service disconnected");
}
});
Looper.loop();
}
})).start();
}
Log.d(s_tag, "Instance created");
}
public static native void nativeProductInfoRetrieved(Object[] productDetails);
public static native void nativePurchasedProductsRetrieved(Object[] purchasedProductDetails);
public static native void nativeNewProductPurchased(Object[] purchaseReceipt);
public static native void nativePurchaseConsumed(String purchaseToken);
public void UnbindService()
{
if (!m_setupDone)
{
Log.e(s_tag, "Not initialized!");
return;
}
m_setupDone = false;
m_billingClient.endConnection();
m_billingClient = null;
}
public void QueryProductInfo(final String[] skuListArray)
{
if (!m_setupDone)
{
Log.e(s_tag, "Not initialized!");
return;
}
m_numResponses = 0;
final ArrayList<ProductDetails> responseList = new ArrayList<>();
List<String> skuList = Arrays.asList(skuListArray);
SkuDetailsResponseListener responseListener = new SkuDetailsResponseListener()
{
@Override
public void onSkuDetailsResponse(int responseCode, List<SkuDetails> skuDetailsList)
{
m_numResponses++;
if (!VerifyResponseCode(responseCode))
{
return;
}
for (SkuDetails skuDetails : skuDetailsList)
{
ProductDetails productDetails = new ProductDetails();
productDetails.m_productId = skuDetails.getSku();
productDetails.m_title = skuDetails.getTitle();
productDetails.m_description = skuDetails.getDescription();
productDetails.m_price = skuDetails.getPrice();
productDetails.m_currencyCode = skuDetails.getPriceCurrencyCode();
productDetails.m_type = skuDetails.getType();
productDetails.m_priceMicro = skuDetails.getPriceAmountMicros();
responseList.add(productDetails);
}
// Wait for responses for both subscriptions and regular products
if (m_numResponses == 2)
{
nativeProductInfoRetrieved(responseList.toArray());
}
}
};
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);
m_billingClient.querySkuDetailsAsync(params.build(), responseListener);
params.setSkusList(skuList).setType(BillingClient.SkuType.SUBS);
m_billingClient.querySkuDetailsAsync(params.build(), responseListener);
}
public void PurchaseProduct(String productSku, String developerPayload, String productType)
{
if (!m_setupDone)
{
Log.e(s_tag, "Not initialized!");
return;
}
BillingFlowParams flowParams = BillingFlowParams.newBuilder().setSku(productSku).setType(productType).build();
int responseCode = m_billingClient.launchBillingFlow(m_activity, flowParams);
if (!VerifyResponseCode(responseCode))
{
return;
}
Log.d(s_tag, "Purchase flow initiated.");
}
@Override
public void onPurchasesUpdated(int responseCode, List<Purchase> purchases)
{
if (!VerifyResponseCode(responseCode))
{
return;
}
ArrayList<PurchasedProductDetails> purchasedProducts = new ArrayList<>();
ParsePurchasedProducts(purchases, purchasedProducts);
nativeNewProductPurchased(purchasedProducts.toArray());
}
public void QueryPurchasedProducts()
{
if (!m_setupDone)
{
Log.e(s_tag, "Not initialized!");
return;
}
ArrayList<PurchasedProductDetails> purchasedProducts = new ArrayList<>();
if (!QueryPurchasedProductsBySkuType(BillingClient.SkuType.INAPP, purchasedProducts) || !QueryPurchasedProductsBySkuType(BillingClient.SkuType.SUBS, purchasedProducts))
{
return;
}
nativePurchasedProductsRetrieved(purchasedProducts.toArray());
}
public void ConsumePurchase(final String purchaseToken)
{
if (!m_setupDone)
{
Log.e(s_tag, "Not initialized!");
return;
}
ConsumeResponseListener listener = new ConsumeResponseListener()
{
@Override
public void onConsumeResponse(int responseCode, String purchaseToken)
{
if (!VerifyResponseCode(responseCode))
{
return;
}
nativePurchaseConsumed(purchaseToken);
}
};
m_billingClient.consumeAsync(purchaseToken, listener);
}
public boolean IsKindleDevice()
{
if (Build.MANUFACTURER.equals("Amazon") && Build.MODEL.contains("KF"))
{
Log.e(s_tag, "Kindle devices not currently supported");
return true;
}
return false;
}
private boolean QueryPurchasedProductsBySkuType(String skuType, ArrayList<PurchasedProductDetails> purchasedProducts)
{
Purchase.PurchasesResult purchasesResult = m_billingClient.queryPurchases(skuType);
if (!VerifyResponseCode(purchasesResult.getResponseCode()))
{
return false;
}
ParsePurchasedProducts(purchasesResult.getPurchasesList(), purchasedProducts);
return true;
}
private void ParsePurchasedProducts(List<Purchase> purchases, ArrayList<PurchasedProductDetails> purchasedProducts)
{
for (Purchase purchase : purchases)
{
PurchasedProductDetails purchasedProductDetails = new PurchasedProductDetails();
purchasedProductDetails.m_productId = purchase.getSku();
purchasedProductDetails.m_orderId = purchase.getOrderId();
purchasedProductDetails.m_packageName = purchase.getPackageName();
purchasedProductDetails.m_purchaseToken = purchase.getPurchaseToken();
purchasedProductDetails.m_signature = purchase.getSignature();
purchasedProductDetails.m_purchaseTime = purchase.getPurchaseTime();
purchasedProductDetails.m_isAutoRenewing = purchase.isAutoRenewing();
purchasedProducts.add(purchasedProductDetails);
}
}
private boolean VerifyResponseCode(int responseCode)
{
if (responseCode != BillingClient.BillingResponse.OK)
{
Log.d(s_tag, m_packageName + " returned error code " + BILLING_RESPONSE_RESULT_STRINGS[responseCode]);
return false;
}
return true;
}
public class ProductDetails
{
public String m_title;
public String m_description;
public String m_productId;
public String m_price;
public String m_currencyCode;
public String m_type;
public long m_priceMicro;
};
public class PurchasedProductDetails
{
public String m_productId;
public String m_orderId;
public String m_packageName;
public String m_purchaseToken;
public String m_signature;
public long m_purchaseTime;
public boolean m_isAutoRenewing;
};
private static final String[] BILLING_RESPONSE_RESULT_STRINGS = {
"Billing response result is ok",
"User cancelled the request",
"The requested service is unavailable",
"Billing is currently unavailable",
"The requested item is unavailable",
"Developer error",
"Error",
"The item being purchased is already owned by the user",
"The item is not owned by the user"
};
private static final String s_tag = "LumberyardInAppBilling";
private Activity m_activity;
private BillingClient m_billingClient;
private String m_appPublicKey;
private String m_packageName;
private boolean m_setupDone;
private int m_numResponses;
} | 8,867 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiVector.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
import java.nio.ByteBuffer;
/**
* Wrapper for 3-dimensional vectors.<p>
*
* This wrapper is also used to represent 1- and 2-dimensional vectors. In
* these cases only the x (or the x and y coordinate) will be used.
* Accessing unused components will throw UnsupportedOperationExceptions.<p>
*
* The wrapper is writable, i.e., changes performed via the set-methods will
* modify the underlying mesh.
*/
public final class AiVector {
/**
* Constructor.
*
* @param buffer the buffer to wrap
* @param offset offset into buffer
* @param numComponents number vector of components
*/
public AiVector(ByteBuffer buffer, int offset, int numComponents) {
if (null == buffer) {
throw new IllegalArgumentException("buffer may not be null");
}
m_buffer = buffer;
m_offset = offset;
m_numComponents = numComponents;
}
/**
* Returns the x value.
*
* @return the x value
*/
public float getX() {
return m_buffer.getFloat(m_offset);
}
/**
* Returns the y value.<p>
*
* May only be called on 2- or 3-dimensional vectors.
*
* @return the y value
*/
public float getY() {
if (m_numComponents <= 1) {
throw new UnsupportedOperationException(
"vector has only 1 component");
}
return m_buffer.getFloat(m_offset + 4);
}
/**
* Returns the z value.<p>
*
* May only be called on 3-dimensional vectors.
*
* @return the z value
*/
public float getZ() {
if (m_numComponents <= 2) {
throw new UnsupportedOperationException(
"vector has only 2 components");
}
return m_buffer.getFloat(m_offset + 8);
}
/**
* Sets the x component.
*
* @param x the new value
*/
public void setX(float x) {
m_buffer.putFloat(m_offset, x);
}
/**
* Sets the y component.<p>
*
* May only be called on 2- or 3-dimensional vectors.
*
* @param y the new value
*/
public void setY(float y) {
if (m_numComponents <= 1) {
throw new UnsupportedOperationException(
"vector has only 1 component");
}
m_buffer.putFloat(m_offset + 4, y);
}
/**
* Sets the z component.<p>
*
* May only be called on 3-dimensional vectors.
*
* @param z the new value
*/
public void setZ(float z) {
if (m_numComponents <= 2) {
throw new UnsupportedOperationException(
"vector has only 2 components");
}
m_buffer.putFloat(m_offset + 8, z);
}
/**
* Returns the number of components in this vector.
*
* @return the number of components
*/
public int getNumComponents() {
return m_numComponents;
}
@Override
public String toString() {
return "[" + getX() + ", " + getY() + ", " + getZ() + "]";
}
/**
* Wrapped buffer.
*/
private final ByteBuffer m_buffer;
/**
* Offset into m_buffer.
*/
private final int m_offset;
/**
* Number of components.
*/
private final int m_numComponents;
}
| 8,868 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiTextureType.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
/**
* Defines the purpose of a texture.<p>
*
* This is a very difficult topic. Different 3D packages support different
* kinds of textures. For very common texture types, such as bumpmaps, the
* rendering results depend on implementation details in the rendering
* pipelines of these applications. Assimp loads all texture references from
* the model file and tries to determine which of the predefined texture
* types below is the best choice to match the original use of the texture
* as closely as possible.<p>
*
* In content pipelines you'll usually define how textures have to be handled,
* and the artists working on models have to conform to this specification,
* regardless which 3D tool they're using.
*/
public enum AiTextureType {
/**
* The texture is combined with the result of the diffuse
* lighting equation.
*/
DIFFUSE(0x1),
/**
* The texture is combined with the result of the specular
* lighting equation.
*/
SPECULAR(0x2),
/**
* The texture is combined with the result of the ambient
* lighting equation.
*/
AMBIENT(0x3),
/**
* The texture is added to the result of the lighting
* calculation. It isn't influenced by incoming light.
*/
EMISSIVE(0x4),
/**
* The texture is a height map.<p>
*
* By convention, higher gray-scale values stand for
* higher elevations from the base height.
*/
HEIGHT(0x5),
/**
* The texture is a (tangent space) normal-map.<p>
*
* Again, there are several conventions for tangent-space
* normal maps. Assimp does (intentionally) not distinguish here.
*/
NORMALS(0x6),
/**
* The texture defines the glossiness of the material.<p>
*
* The glossiness is in fact the exponent of the specular
* (phong) lighting equation. Usually there is a conversion
* function defined to map the linear color values in the
* texture to a suitable exponent. Have fun.
*/
SHININESS(0x7),
/**
* The texture defines per-pixel opacity.<p>
*
* Usually 'white' means opaque and 'black' means
* 'transparency'. Or quite the opposite. Have fun.
*/
OPACITY(0x8),
/**
* Displacement texture.<p>
*
* The exact purpose and format is application-dependent.
* Higher color values stand for higher vertex displacements.
*/
DISPLACEMENT(0x9),
/**
* Lightmap texture (aka Ambient Occlusion).<p>
*
* Both 'Lightmaps' and dedicated 'ambient occlusion maps' are
* covered by this material property. The texture contains a
* scaling value for the final color value of a pixel. Its
* intensity is not affected by incoming light.
*/
LIGHTMAP(0xA),
/**
* Reflection texture.<p>
*
* Contains the color of a perfect mirror reflection.
* Rarely used, almost never for real-time applications.
*/
REFLECTION(0xB),
/**
* Unknown texture.<p>
*
* A texture reference that does not match any of the definitions
* above is considered to be 'unknown'. It is still imported,
* but is excluded from any further postprocessing.
*/
UNKNOWN(0xC);
/**
* Utility method for converting from c/c++ based integer enums to java
* enums.<p>
*
* This method is intended to be used from JNI and my change based on
* implementation needs.
*
* @param rawValue an integer based enum value (as defined by assimp)
* @return the enum value corresponding to rawValue
*/
static AiTextureType fromRawValue(int rawValue) {
for (AiTextureType type : AiTextureType.values()) {
if (type.m_rawValue == rawValue) {
return type;
}
}
throw new IllegalArgumentException("unexptected raw value: " +
rawValue);
}
/**
* Utility method for converting from java enums to c/c++ based integer
* enums.<p>
*
* @param type the type to convert, may not be null
* @return the rawValue corresponding to type
*/
static int toRawValue(AiTextureType type) {
return type.m_rawValue;
}
/**
* Constructor.
*
* @param rawValue maps java enum to c/c++ integer enum values
*/
private AiTextureType(int rawValue) {
m_rawValue = rawValue;
}
/**
* The mapped c/c++ integer enum value.
*/
private final int m_rawValue;
}
| 8,869 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiBuiltInWrapperProvider.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
import java.nio.ByteBuffer;
/**
* Wrapper provider using jassimp built in types.
*/
public final class AiBuiltInWrapperProvider implements AiWrapperProvider<
AiVector, AiMatrix4f, AiColor, AiNode, AiQuaternion> {
@Override
public AiVector wrapVector3f(ByteBuffer buffer, int offset,
int numComponents) {
return new AiVector(buffer, offset, numComponents);
}
@Override
public AiMatrix4f wrapMatrix4f(float[] data) {
return new AiMatrix4f(data);
}
@Override
public AiColor wrapColor(ByteBuffer buffer, int offset) {
return new AiColor(buffer, offset);
}
@Override
public AiNode wrapSceneNode(Object parent, Object matrix,
int[] meshReferences, String name) {
return new AiNode((AiNode) parent, matrix, meshReferences, name);
}
@Override
public AiQuaternion wrapQuaternion(ByteBuffer buffer, int offset) {
return new AiQuaternion(buffer, offset);
}
}
| 8,870 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiShadingMode.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
/**
* Defines all shading modes supported by the library.<p>
*
* The list of shading modes has been taken from Blender.
* See Blender documentation for more information. The API does
* not distinguish between "specular" and "diffuse" shaders (thus the
* specular term for diffuse shading models like Oren-Nayar remains
* undefined).<p>
* Again, this value is just a hint. Assimp tries to select the shader whose
* most common implementation matches the original rendering results of the
* 3D modeller which wrote a particular model as closely as possible.
*/
public enum AiShadingMode {
/**
* Flat shading.<p>
*
* Shading is done on per-face base, diffuse only. Also known as
* 'faceted shading'.
*/
FLAT(0x1),
/**
* Simple Gouraud shading.
*/
GOURAUD(0x2),
/**
* Phong-Shading.
*/
PHONG(0x3),
/**
* Phong-Blinn-Shading.
*/
BLINN(0x4),
/**
* Toon-Shading per pixel.<p>
*
* Also known as 'comic' shader.
*/
TOON(0x5),
/**
* OrenNayar-Shading per pixel.<p>
*
* Extension to standard Lambertian shading, taking the roughness of the
* material into account
*/
OREN_NAYAR(0x6),
/**
* Minnaert-Shading per pixel.<p>
*
* Extension to standard Lambertian shading, taking the "darkness" of the
* material into account
*/
MINNAERT(0x7),
/**
* CookTorrance-Shading per pixel.<p>
*
* Special shader for metallic surfaces.
*/
COOK_TORRANCE(0x8),
/**
* No shading at all.<p>
*
* Constant light influence of 1.0.
*/
NO_SHADING(0x9),
/**
* Fresnel shading.
*/
FRESNEL(0xa);
/**
* Utility method for converting from c/c++ based integer enums to java
* enums.<p>
*
* This method is intended to be used from JNI and my change based on
* implementation needs.
*
* @param rawValue an integer based enum value (as defined by assimp)
* @return the enum value corresponding to rawValue
*/
static AiShadingMode fromRawValue(int rawValue) {
for (AiShadingMode type : AiShadingMode.values()) {
if (type.m_rawValue == rawValue) {
return type;
}
}
throw new IllegalArgumentException("unexptected raw value: " +
rawValue);
}
/**
* Constructor.
*
* @param rawValue maps java enum to c/c++ integer enum values
*/
private AiShadingMode(int rawValue) {
m_rawValue = rawValue;
}
/**
* The mapped c/c++ integer enum value.
*/
private final int m_rawValue;
}
| 8,871 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiMesh.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
/**
* A mesh represents a geometry or model with a single material.
* <p>
*
* <h3>Data</h3>
* Meshes usually consist of a number of vertices and a series of faces
* referencing the vertices. In addition there might be a series of bones, each
* of them addressing a number of vertices with a certain weight. Vertex data is
* presented in channels with each channel containing a single per-vertex
* information such as a set of texture coordinates or a normal vector.<p>
*
* Faces consist of one or more references to vertices, called vertex indices.
* The {@link #getPrimitiveTypes()} method can be used to check what
* face types are present in the mesh. Note that a single mesh can possess
* faces of different types. The number of indices used by a specific face can
* be retrieved with the {@link #getFaceNumIndices(int)} method.
*
*
* <h3>API for vertex and face data</h3>
* The jassimp interface for accessing vertex and face data is not a one-to-one
* mapping of the c/c++ interface. The c/c++ interface uses an object-oriented
* approach to represent data, which provides a considerable
* overhead using a naive java based realization (cache locality would be
* unpredictable and most likely bad, bulk data transfer would be impossible).
* <p>
*
* The jassimp interface uses flat byte buffers to store vertex and face data.
* This data can be accessed through three APIs:
* <ul>
* <li><b>Buffer API:</b> the <code>getXXXBuffer()</code> methods return
* raw data buffers.
* <li><b>Direct API:</b> the <code>getXXX()</code> methods allow reading
* and writing of individual data values.
* <li><b>Wrapped API:</b> the <code>getWrappedXXX()</code> methods provide
* an object oriented view on the data.
* </ul>
*
* The Buffer API is optimized for use in conjunction with rendering APIs
* such as LWJGL. The returned buffers are guaranteed to have native byte order
* and to be direct byte buffers. They can be passed directly to LWJGL
* methods, e.g., to fill VBOs with data. Each invocation of a
* <code>getXXXBuffer()</code> method will return a new view of the internal
* buffer, i.e., if is safe to use the relative byte buffer operations.
* The Buffer API provides the best performance of all three APIs, especially
* if large data volumes have to be processed.<p>
*
* The Direct API provides an easy to use interface for reading and writing
* individual data values. Its performance is comparable to the Buffer API's
* performance for these operations. The main difference to the Buffer API is
* the missing support for bulk operations. If you intend to retrieve or modify
* large subsets of the raw data consider using the Buffer API, especially
* if the subsets are contiguous.
* <p>
*
* The Wrapped API offers an object oriented interface for accessing
* and modifying mesh data. As the name implies, this interface is realized
* through wrapper objects that provide a view on the raw data. For each
* invocation of a <code>getWrappedXXX()</code> method, a new wrapper object
* is created. Iterating over mesh data via this interface will create many
* short-lived wrapper objects which -depending on usage and virtual machine-
* may cause considerable garbage collection overhead. The Wrapped API provides
* the worst performance of all three APIs, which may nevertheless still be
* good enough to warrant its usage. See {@link AiWrapperProvider} for more
* details on wrappers.
*
*
* <h3>API for bones</h3>
* As there is no standardized way for doing skinning in different graphics
* engines, bones are not represented as flat buffers but as object structure.
* Users of this library should convert this structure to the format required
* by the specific graphics engine.
*
*
* <h3>Changing Data</h3>
* This class is designed to be mutable, i.e., the returned objects and buffers
* may be modified. It is not possible to add/remove vertices as this would
* require reallocation of the data buffers. Wrapped objects may or may not
* propagate changes to the underlying data buffers. Consult the documentation
* of your wrapper provider for details. The built in wrappers will propagate
* changes.
* <p>
* Modification of face data is theoretically possible by modifying the face
* buffer and the faceOffset buffer however it is strongly disadvised to do so
* because it might break all algorithms that depend on the internal consistency
* of these two data structures.
*/
public final class AiMesh {
/**
* Number of bytes per float value.
*/
private final int SIZEOF_FLOAT = Jassimp.NATIVE_FLOAT_SIZE;
/**
* Number of bytes per int value.
*/
private final int SIZEOF_INT = Jassimp.NATIVE_INT_SIZE;
/**
* Size of an AiVector3D in the native world.
*/
private final int SIZEOF_V3D = Jassimp.NATIVE_AIVEKTOR3D_SIZE;
/**
* The primitive types used by this mesh.
*/
private final Set<AiPrimitiveType> m_primitiveTypes =
EnumSet.noneOf(AiPrimitiveType.class);
/**
* Number of vertices in this mesh.
*/
private int m_numVertices = 0;
/**
* Number of faces in this mesh.
*/
private int m_numFaces = 0;
/**
* Material used by this mesh.
*/
private int m_materialIndex = -1;
/**
* The name of the mesh.
*/
private String m_name = "";
/**
* Buffer for vertex position data.
*/
private ByteBuffer m_vertices = null;
/**
* Buffer for faces/ indices.
*/
private ByteBuffer m_faces = null;
/**
* Index structure for m_faces.<p>
*
* Only used by meshes that are not pure triangular
*/
private ByteBuffer m_faceOffsets = null;
/**
* Buffer for normals.
*/
private ByteBuffer m_normals = null;
/**
* Buffer for tangents.
*/
private ByteBuffer m_tangents = null;
/**
* Buffer for bitangents.
*/
private ByteBuffer m_bitangents = null;
/**
* Vertex colors.
*/
private ByteBuffer[] m_colorsets =
new ByteBuffer[JassimpConfig.MAX_NUMBER_COLORSETS];
/**
* Number of UV components for each texture coordinate set.
*/
private int[] m_numUVComponents = new int[JassimpConfig.MAX_NUMBER_TEXCOORDS];
/**
* Texture coordinates.
*/
private ByteBuffer[] m_texcoords =
new ByteBuffer[JassimpConfig.MAX_NUMBER_TEXCOORDS];
/**
* Bones.
*/
private final List<AiBone> m_bones = new ArrayList<AiBone>();
/**
* This class is instantiated via JNI, no accessible constructor.
*/
private AiMesh() {
/* nothing to do */
}
/**
* Returns the primitive types used by this mesh.
*
* @return a set of primitive types used by this mesh
*/
public Set<AiPrimitiveType> getPrimitiveTypes() {
return m_primitiveTypes;
}
/**
* Tells whether the mesh is a pure triangle mesh, i.e., contains only
* triangular faces.<p>
*
* To automatically triangulate meshes the
* {@link AiPostProcessSteps#TRIANGULATE} post processing option can be
* used when loading the scene
*
* @return true if the mesh is a pure triangle mesh, false otherwise
*/
public boolean isPureTriangle() {
return m_primitiveTypes.contains(AiPrimitiveType.TRIANGLE) &&
m_primitiveTypes.size() == 1;
}
/**
* Tells whether the mesh has vertex positions.<p>
*
* Meshes almost always contain position data
*
* @return true if positions are available
*/
public boolean hasPositions() {
return m_vertices != null;
}
/**
* Tells whether the mesh has faces.<p>
*
* Meshes almost always contain faces
*
* @return true if faces are available
*/
public boolean hasFaces() {
return m_faces != null;
}
/**
* Tells whether the mesh has normals.
*
* @return true if normals are available
*/
public boolean hasNormals() {
return m_normals != null;
}
/**
* Tells whether the mesh has tangents and bitangents.<p>
*
* It is not possible that it contains tangents and no bitangents (or the
* other way round). The existence of one of them implies that the second
* is there, too.
*
* @return true if tangents and bitangents are available
*/
public boolean hasTangentsAndBitangents() {
return m_tangents != null && m_tangents != null;
}
/**
* Tells whether the mesh has a vertex color set.
*
* @param colorset index of the color set
* @return true if colors are available
*/
public boolean hasColors(int colorset) {
return m_colorsets[colorset] != null;
}
/**
* Tells whether the mesh has any vertex colors.<p>
*
* Use {@link #hasColors(int)} to check which color sets are
* available.
*
* @return true if any colors are available
*/
public boolean hasVertexColors() {
for (ByteBuffer buf : m_colorsets) {
if (buf != null) {
return true;
}
}
return false;
}
/**
* Tells whether the mesh has a texture coordinate set.
*
* @param coords index of the texture coordinate set
* @return true if texture coordinates are available
*/
public boolean hasTexCoords(int coords) {
return m_texcoords[coords] != null;
}
/**
* Tells whether the mesh has any texture coordinate sets.<p>
*
* Use {@link #hasTexCoords(int)} to check which texture coordinate
* sets are available
*
* @return true if any texture coordinates are available
*/
public boolean hasTexCoords() {
for (ByteBuffer buf : m_texcoords) {
if (buf != null) {
return true;
}
}
return false;
}
/**
* Tells whether the mesh has bones.
*
* @return true if bones are available
*/
public boolean hasBones() {
return !m_bones.isEmpty();
}
/**
* Returns the bones of this mesh.
*
* @return a list of bones
*/
public List<AiBone> getBones() {
return m_bones;
}
/**
* Returns the number of vertices in this mesh.
*
* @return the number of vertices.
*/
public int getNumVertices() {
return m_numVertices;
}
/**
* Returns the number of faces in the mesh.
*
* @return the number of faces
*/
public int getNumFaces() {
return m_numFaces;
}
/**
* Returns the number of vertex indices for a single face.
*
* @param face the face
* @return the number of indices
*/
public int getFaceNumIndices(int face) {
if (null == m_faceOffsets) {
if (face >= m_numFaces || face < 0) {
throw new IndexOutOfBoundsException("Index: " + face +
", Size: " + m_numFaces);
}
return 3;
}
else {
/*
* no need to perform bound checks here as the array access will
* throw IndexOutOfBoundsExceptions if the index is invalid
*/
if (face == m_numFaces - 1) {
return m_faces.capacity() / 4 - m_faceOffsets.getInt(face * 4);
}
return m_faceOffsets.getInt((face + 1) * 4) -
m_faceOffsets.getInt(face * 4);
}
}
/**
* Returns the number of UV components for a texture coordinate set.<p>
*
* Possible values range from 1 to 3 (1D to 3D texture coordinates)
*
* @param coords the coordinate set
* @return the number of components
*/
public int getNumUVComponents(int coords) {
return m_numUVComponents[coords];
}
/**
* Returns the material used by this mesh.<p>
*
* A mesh does use only a single material. If an imported model uses
* multiple materials, the import splits up the mesh. Use this value
* as index into the scene's material list.
*
* @return the material index
*/
public int getMaterialIndex() {
return m_materialIndex;
}
/**
* Returns the name of the mesh.<p>
*
* Not all meshes have a name, if no name is set an empty string is
* returned.
*
* @return the name or an empty string if no name is set
*/
public String getName() {
return m_name;
}
// CHECKSTYLE:OFF
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("Mesh(").append(m_numVertices).append(" vertices, ").
append(m_numFaces).append(" faces");
if (hasNormals()) {
buf.append(", normals");
}
if (hasTangentsAndBitangents()) {
buf.append(", (bi-)tangents");
}
if (hasVertexColors()) {
buf.append(", colors");
}
if (hasTexCoords()) {
buf.append(", texCoords");
}
buf.append(")");
return buf.toString();
}
// CHECKSTYLE:ON
// {{ Buffer API
/**
* Returns a buffer containing vertex positions.<p>
*
* A vertex position consists of a triple of floats, the buffer will
* therefore contain <code>3 * getNumVertices()</code> floats
*
* @return a native-order direct buffer, or null if no data is available
*/
public FloatBuffer getPositionBuffer() {
if (m_vertices == null) {
return null;
}
return m_vertices.asFloatBuffer();
}
/**
* Returns a buffer containing face data.<p>
*
* You should use the {@link #getIndexBuffer()} method if you are
* interested in getting an index buffer used by graphics APIs such as
* LWJGL.<p>
*
* The buffer contains all vertex indices from all faces as a flat list. If
* the mesh is a pure triangle mesh, the buffer returned by this method is
* identical to the buffer returned by {@link #getIndexBuffer()}. For other
* meshes, the {@link #getFaceOffsets()} method can be used to retrieve
* an index structure that allows addressing individual faces in the list.
*
* @return a native-order direct buffer, or null if no data is available
*/
public IntBuffer getFaceBuffer() {
if (m_faces == null) {
return null;
}
return m_faces.asIntBuffer();
}
/**
* Returns an index structure for the buffer returned by
* {@link #getFaceBuffer()}.<p>
*
* You should use the {@link #getIndexBuffer()} method if you are
* interested in getting an index buffer used by graphics APIs such as
* LWJGL.<p>
*
* The returned buffer contains one integer entry for each face. This entry
* specifies the offset at which the face's data is located inside the
* face buffer. The difference between two subsequent entries can be used
* to determine how many vertices belong to a given face (the last face
* contains all entries between the offset and the end of the face buffer).
*
* @return a native-order direct buffer, or null if no data is available
*/
public IntBuffer getFaceOffsets() {
if (m_faceOffsets == null) {
return null;
}
return m_faceOffsets.asIntBuffer();
}
/**
* Returns a buffer containing vertex indices for the mesh's faces.<p>
*
* This method may only be called on pure triangle meshes, i.e., meshes
* containing only triangles. The {@link #isPureTriangle()} method can be
* used to check whether this is the case.<p>
*
* Indices are stored as integers, the buffer will therefore contain
* <code>3 * getNumVertices()</code> integers (3 indices per triangle)
*
* @return a native-order direct buffer
* @throws UnsupportedOperationException
* if the mesh is not a pure triangle mesh
*/
public IntBuffer getIndexBuffer() {
if (!isPureTriangle()) {
throw new UnsupportedOperationException(
"mesh is not a pure triangle mesh");
}
return getFaceBuffer();
}
/**
* Returns a buffer containing normals.<p>
*
* A normal consists of a triple of floats, the buffer will
* therefore contain <code>3 * getNumVertices()</code> floats
*
* @return a native-order direct buffer
*/
public FloatBuffer getNormalBuffer() {
if (m_normals == null) {
return null;
}
return m_normals.asFloatBuffer();
}
/**
* Returns a buffer containing tangents.<p>
*
* A tangent consists of a triple of floats, the buffer will
* therefore contain <code>3 * getNumVertices()</code> floats
*
* @return a native-order direct buffer
*/
public FloatBuffer getTangentBuffer() {
if (m_tangents == null) {
return null;
}
return m_tangents.asFloatBuffer();
}
/**
* Returns a buffer containing bitangents.<p>
*
* A bitangent consists of a triple of floats, the buffer will
* therefore contain <code>3 * getNumVertices()</code> floats
*
* @return a native-order direct buffer
*/
public FloatBuffer getBitangentBuffer() {
if (m_bitangents == null) {
return null;
}
return m_bitangents.asFloatBuffer();
}
/**
* Returns a buffer containing vertex colors for a color set.<p>
*
* A vertex color consists of 4 floats (red, green, blue and alpha), the
* buffer will therefore contain <code>4 * getNumVertices()</code> floats
*
* @param colorset the color set
*
* @return a native-order direct buffer, or null if no data is available
*/
public FloatBuffer getColorBuffer(int colorset) {
if (m_colorsets[colorset] == null) {
return null;
}
return m_colorsets[colorset].asFloatBuffer();
}
/**
* Returns a buffer containing coordinates for a texture coordinate set.<p>
*
* A texture coordinate consists of up to 3 floats (u, v, w). The actual
* number can be queried via {@link #getNumUVComponents(int)}. The
* buffer will contain
* <code>getNumUVComponents(coords) * getNumVertices()</code> floats
*
* @param coords the texture coordinate set
*
* @return a native-order direct buffer, or null if no data is available
*/
public FloatBuffer getTexCoordBuffer(int coords) {
if (m_texcoords[coords] == null) {
return null;
}
return m_texcoords[coords].asFloatBuffer();
}
// }}
// {{ Direct API
/**
* Returns the x-coordinate of a vertex position.
*
* @param vertex the vertex index
* @return the x coordinate
*/
public float getPositionX(int vertex) {
if (!hasPositions()) {
throw new IllegalStateException("mesh has no positions");
}
checkVertexIndexBounds(vertex);
return m_vertices.getFloat(vertex * 3 * SIZEOF_FLOAT);
}
/**
* Returns the y-coordinate of a vertex position.
*
* @param vertex the vertex index
* @return the y coordinate
*/
public float getPositionY(int vertex) {
if (!hasPositions()) {
throw new IllegalStateException("mesh has no positions");
}
checkVertexIndexBounds(vertex);
return m_vertices.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);
}
/**
* Returns the z-coordinate of a vertex position.
*
* @param vertex the vertex index
* @return the z coordinate
*/
public float getPositionZ(int vertex) {
if (!hasPositions()) {
throw new IllegalStateException("mesh has no positions");
}
checkVertexIndexBounds(vertex);
return m_vertices.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);
}
/**
* Returns a vertex reference from a face.<p>
*
* A face contains <code>getFaceNumIndices(face)</code> vertex references.
* This method returns the n'th of these. The returned index can be passed
* directly to the vertex oriented methods, such as
* <code>getPosition()</code> etc.
*
* @param face the face
* @param n the reference
* @return a vertex index
*/
public int getFaceVertex(int face, int n) {
if (!hasFaces()) {
throw new IllegalStateException("mesh has no faces");
}
if (face >= m_numFaces || face < 0) {
throw new IndexOutOfBoundsException("Index: " + face + ", Size: " +
m_numFaces);
}
if (n >= getFaceNumIndices(face) || n < 0) {
throw new IndexOutOfBoundsException("Index: " + n + ", Size: " +
getFaceNumIndices(face));
}
int faceOffset = 0;
if (m_faceOffsets == null) {
faceOffset = 3 * face * SIZEOF_INT;
}
else {
faceOffset = m_faceOffsets.getInt(face * SIZEOF_INT) * SIZEOF_INT;
}
return m_faces.getInt(faceOffset + n * SIZEOF_INT);
}
/**
* Returns the x-coordinate of a vertex normal.
*
* @param vertex the vertex index
* @return the x coordinate
*/
public float getNormalX(int vertex) {
if (!hasNormals()) {
throw new IllegalStateException("mesh has no normals");
}
checkVertexIndexBounds(vertex);
return m_normals.getFloat(vertex * 3 * SIZEOF_FLOAT);
}
/**
* Returns the y-coordinate of a vertex normal.
*
* @param vertex the vertex index
* @return the y coordinate
*/
public float getNormalY(int vertex) {
if (!hasNormals()) {
throw new IllegalStateException("mesh has no normals");
}
checkVertexIndexBounds(vertex);
return m_normals.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);
}
/**
* Returns the z-coordinate of a vertex normal.
*
* @param vertex the vertex index
* @return the z coordinate
*/
public float getNormalZ(int vertex) {
if (!hasNormals()) {
throw new IllegalStateException("mesh has no normals");
}
checkVertexIndexBounds(vertex);
return m_normals.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);
}
/**
* Returns the x-coordinate of a vertex tangent.
*
* @param vertex the vertex index
* @return the x coordinate
*/
public float getTangentX(int vertex) {
if (!hasTangentsAndBitangents()) {
throw new IllegalStateException("mesh has no tangents");
}
checkVertexIndexBounds(vertex);
return m_tangents.getFloat(vertex * 3 * SIZEOF_FLOAT);
}
/**
* Returns the y-coordinate of a vertex bitangent.
*
* @param vertex the vertex index
* @return the y coordinate
*/
public float getTangentY(int vertex) {
if (!hasTangentsAndBitangents()) {
throw new IllegalStateException("mesh has no bitangents");
}
checkVertexIndexBounds(vertex);
return m_tangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);
}
/**
* Returns the z-coordinate of a vertex tangent.
*
* @param vertex the vertex index
* @return the z coordinate
*/
public float getTangentZ(int vertex) {
if (!hasTangentsAndBitangents()) {
throw new IllegalStateException("mesh has no tangents");
}
checkVertexIndexBounds(vertex);
return m_tangents.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);
}
/**
* Returns the x-coordinate of a vertex tangent.
*
* @param vertex the vertex index
* @return the x coordinate
*/
public float getBitangentX(int vertex) {
if (!hasTangentsAndBitangents()) {
throw new IllegalStateException("mesh has no bitangents");
}
checkVertexIndexBounds(vertex);
return m_bitangents.getFloat(vertex * 3 * SIZEOF_FLOAT);
}
/**
* Returns the y-coordinate of a vertex tangent.
*
* @param vertex the vertex index
* @return the y coordinate
*/
public float getBitangentY(int vertex) {
if (!hasTangentsAndBitangents()) {
throw new IllegalStateException("mesh has no bitangents");
}
checkVertexIndexBounds(vertex);
return m_bitangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);
}
/**
* Returns the z-coordinate of a vertex tangent.
*
* @param vertex the vertex index
* @return the z coordinate
*/
public float getBitangentZ(int vertex) {
if (!hasTangentsAndBitangents()) {
throw new IllegalStateException("mesh has no bitangents");
}
checkVertexIndexBounds(vertex);
return m_bitangents.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);
}
/**
* Returns the red color component of a color from a vertex color set.
*
* @param vertex the vertex index
* @param colorset the color set
* @return the red color component
*/
public float getColorR(int vertex, int colorset) {
if (!hasColors(colorset)) {
throw new IllegalStateException("mesh has no colorset " + colorset);
}
checkVertexIndexBounds(vertex);
/* bound checks for colorset are done by java for us */
return m_colorsets[colorset].getFloat(vertex * 4 * SIZEOF_FLOAT);
}
/**
* Returns the green color component of a color from a vertex color set.
*
* @param vertex the vertex index
* @param colorset the color set
* @return the green color component
*/
public float getColorG(int vertex, int colorset) {
if (!hasColors(colorset)) {
throw new IllegalStateException("mesh has no colorset " + colorset);
}
checkVertexIndexBounds(vertex);
/* bound checks for colorset are done by java for us */
return m_colorsets[colorset].getFloat((vertex * 4 + 1) * SIZEOF_FLOAT);
}
/**
* Returns the blue color component of a color from a vertex color set.
*
* @param vertex the vertex index
* @param colorset the color set
* @return the blue color component
*/
public float getColorB(int vertex, int colorset) {
if (!hasColors(colorset)) {
throw new IllegalStateException("mesh has no colorset " + colorset);
}
checkVertexIndexBounds(vertex);
/* bound checks for colorset are done by java for us */
return m_colorsets[colorset].getFloat((vertex * 4 + 2) * SIZEOF_FLOAT);
}
/**
* Returns the alpha color component of a color from a vertex color set.
*
* @param vertex the vertex index
* @param colorset the color set
* @return the alpha color component
*/
public float getColorA(int vertex, int colorset) {
if (!hasColors(colorset)) {
throw new IllegalStateException("mesh has no colorset " + colorset);
}
checkVertexIndexBounds(vertex);
/* bound checks for colorset are done by java for us */
return m_colorsets[colorset].getFloat((vertex * 4 + 3) * SIZEOF_FLOAT);
}
/**
* Returns the u component of a coordinate from a texture coordinate set.
*
* @param vertex the vertex index
* @param coords the texture coordinate set
* @return the u component
*/
public float getTexCoordU(int vertex, int coords) {
if (!hasTexCoords(coords)) {
throw new IllegalStateException(
"mesh has no texture coordinate set " + coords);
}
checkVertexIndexBounds(vertex);
/* bound checks for coords are done by java for us */
return m_texcoords[coords].getFloat(
vertex * m_numUVComponents[coords] * SIZEOF_FLOAT);
}
/**
* Returns the v component of a coordinate from a texture coordinate set.<p>
*
* This method may only be called on 2- or 3-dimensional coordinate sets.
* Call <code>getNumUVComponents(coords)</code> to determine how may
* coordinate components are available.
*
* @param vertex the vertex index
* @param coords the texture coordinate set
* @return the v component
*/
public float getTexCoordV(int vertex, int coords) {
if (!hasTexCoords(coords)) {
throw new IllegalStateException(
"mesh has no texture coordinate set " + coords);
}
checkVertexIndexBounds(vertex);
/* bound checks for coords are done by java for us */
if (getNumUVComponents(coords) < 2) {
throw new IllegalArgumentException("coordinate set " + coords +
" does not contain 2D texture coordinates");
}
return m_texcoords[coords].getFloat(
(vertex * m_numUVComponents[coords] + 1) * SIZEOF_FLOAT);
}
/**
* Returns the w component of a coordinate from a texture coordinate set.<p>
*
* This method may only be called on 3-dimensional coordinate sets.
* Call <code>getNumUVComponents(coords)</code> to determine how may
* coordinate components are available.
*
* @param vertex the vertex index
* @param coords the texture coordinate set
* @return the w component
*/
public float getTexCoordW(int vertex, int coords) {
if (!hasTexCoords(coords)) {
throw new IllegalStateException(
"mesh has no texture coordinate set " + coords);
}
checkVertexIndexBounds(vertex);
/* bound checks for coords are done by java for us */
if (getNumUVComponents(coords) < 3) {
throw new IllegalArgumentException("coordinate set " + coords +
" does not contain 3D texture coordinates");
}
return m_texcoords[coords].getFloat(
(vertex * m_numUVComponents[coords] + 1) * SIZEOF_FLOAT);
}
// }}
// {{ Wrapped API
/**
* Returns the vertex position as 3-dimensional vector.<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built-in behavior is to return a {@link AiVector}.
*
* @param vertex the vertex index
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the position wrapped as object
*/
public <V3, M4, C, N, Q> V3 getWrappedPosition(int vertex,
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
if (!hasPositions()) {
throw new IllegalStateException("mesh has no positions");
}
checkVertexIndexBounds(vertex);
return wrapperProvider.wrapVector3f(m_vertices,
vertex * 3 * SIZEOF_FLOAT, 3);
}
/**
* Returns the vertex normal as 3-dimensional vector.<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built-in behavior is to return a {@link AiVector}.
*
* @param vertex the vertex index
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the normal wrapped as object
*/
public <V3, M4, C, N, Q> V3 getWrappedNormal(int vertex,
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
if (!hasNormals()) {
throw new IllegalStateException("mesh has no positions");
}
checkVertexIndexBounds(vertex);
return wrapperProvider.wrapVector3f(m_normals,
vertex * 3 * SIZEOF_FLOAT, 3);
}
/**
* Returns the vertex tangent as 3-dimensional vector.<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built-in behavior is to return a {@link AiVector}.
*
* @param vertex the vertex index
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the tangent wrapped as object
*/
public <V3, M4, C, N, Q> V3 getWrappedTangent(int vertex,
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
if (!hasTangentsAndBitangents()) {
throw new IllegalStateException("mesh has no tangents");
}
checkVertexIndexBounds(vertex);
return wrapperProvider.wrapVector3f(m_tangents,
vertex * 3 * SIZEOF_FLOAT, 3);
}
/**
* Returns the vertex bitangent as 3-dimensional vector.<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built-in behavior is to return a {@link AiVector}.
*
* @param vertex the vertex index
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the bitangent wrapped as object
*/
public <V3, M4, C, N, Q> V3 getWrappedBitangent(int vertex,
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
if (!hasTangentsAndBitangents()) {
throw new IllegalStateException("mesh has no bitangents");
}
checkVertexIndexBounds(vertex);
return wrapperProvider.wrapVector3f(m_bitangents,
vertex * 3 * SIZEOF_FLOAT, 3);
}
/**
* Returns the vertex color.<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built-in behavior is to return a {@link AiColor}.
*
* @param vertex the vertex index
* @param colorset the color set
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the vertex color wrapped as object
*/
public <V3, M4, C, N, Q> C getWrappedColor(int vertex, int colorset,
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
if (!hasColors(colorset)) {
throw new IllegalStateException("mesh has no colorset " + colorset);
}
checkVertexIndexBounds(vertex);
return wrapperProvider.wrapColor(
m_colorsets[colorset], vertex * 4 * SIZEOF_FLOAT);
}
/**
* Returns the texture coordinates as n-dimensional vector.<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built-in behavior is to return a {@link AiVector}.
*
* @param vertex the vertex index
* @param coords the texture coordinate set
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the texture coordinates wrapped as object
*/
public <V3, M4, C, N, Q> V3 getWrappedTexCoords(int vertex, int coords,
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
if (!hasTexCoords(coords)) {
throw new IllegalStateException(
"mesh has no texture coordinate set " + coords);
}
checkVertexIndexBounds(vertex);
return wrapperProvider.wrapVector3f(m_texcoords[coords],
vertex * 3 * SIZEOF_FLOAT, getNumUVComponents(coords));
}
// }}
// {{ Helpers
/**
* Throws an exception if the vertex index is not in the allowed range.
*
* @param vertex the index to check
*/
private void checkVertexIndexBounds(int vertex) {
if (vertex >= m_numVertices || vertex < 0) {
throw new IndexOutOfBoundsException("Index: " + vertex +
", Size: " + m_numVertices);
}
}
// }}
// {{ JNI interface
/*
* Channel constants used by allocate data channel. Do not modify or use
* as these may change at will
*/
// CHECKSTYLE:OFF
private static final int NORMALS = 0;
private static final int TANGENTS = 1;
private static final int BITANGENTS = 2;
private static final int COLORSET = 3;
private static final int TEXCOORDS_1D = 4;
private static final int TEXCOORDS_2D = 5;
private static final int TEXCOORDS_3D = 6;
// CHECKSTYLE:ON
/**
* This method is used by JNI. Do not call or modify.<p>
*
* Sets the primitive types enum set
*
* @param types the bitwise or'ed c/c++ aiPrimitiveType enum values
*/
@SuppressWarnings("unused")
private void setPrimitiveTypes(int types) {
AiPrimitiveType.fromRawValue(m_primitiveTypes, types);
}
/**
* This method is used by JNI. Do not call or modify.<p>
*
* Allocates byte buffers
*
* @param numVertices the number of vertices in the mesh
* @param numFaces the number of faces in the mesh
* @param optimizedFaces set true for optimized face representation
* @param faceBufferSize size of face buffer for non-optimized face
* representation
*/
@SuppressWarnings("unused")
private void allocateBuffers(int numVertices, int numFaces,
boolean optimizedFaces, int faceBufferSize) {
/*
* the allocated buffers are native order direct byte buffers, so they
* can be passed directly to LWJGL or similar graphics APIs
*/
/* ensure face optimization is possible */
if (optimizedFaces && !isPureTriangle()) {
throw new IllegalArgumentException("mesh is not purely triangular");
}
m_numVertices = numVertices;
m_numFaces = numFaces;
/* allocate for each vertex 3 floats */
if (m_numVertices > 0) {
m_vertices = ByteBuffer.allocateDirect(numVertices * 3 *
SIZEOF_FLOAT);
m_vertices.order(ByteOrder.nativeOrder());
}
if (m_numFaces > 0) {
/* for optimized faces allocate 3 integers per face */
if (optimizedFaces) {
m_faces = ByteBuffer.allocateDirect(numFaces * 3 * SIZEOF_INT);
m_faces.order(ByteOrder.nativeOrder());
}
/*
* for non-optimized faces allocate the passed in buffer size
* and allocate the face index structure
*/
else {
m_faces = ByteBuffer.allocateDirect(faceBufferSize);
m_faces.order(ByteOrder.nativeOrder());
m_faceOffsets = ByteBuffer.allocateDirect(numFaces *
SIZEOF_INT);
m_faceOffsets.order(ByteOrder.nativeOrder());
}
}
}
/**
* This method is used by JNI. Do not call or modify.<p>
*
* Allocates a byte buffer for a vertex data channel
*
* @param channelType the channel type
* @param channelIndex sub-index, used for types that can have multiple
* channels, such as texture coordinates
*/
@SuppressWarnings("unused")
private void allocateDataChannel(int channelType, int channelIndex) {
switch (channelType) {
case NORMALS:
m_normals = ByteBuffer.allocateDirect(
m_numVertices * 3 * SIZEOF_FLOAT);
m_normals.order(ByteOrder.nativeOrder());
break;
case TANGENTS:
m_tangents = ByteBuffer.allocateDirect(
m_numVertices * 3 * SIZEOF_FLOAT);
m_tangents.order(ByteOrder.nativeOrder());
break;
case BITANGENTS:
m_bitangents = ByteBuffer.allocateDirect(
m_numVertices * 3 * SIZEOF_FLOAT);
m_bitangents.order(ByteOrder.nativeOrder());
break;
case COLORSET:
m_colorsets[channelIndex] = ByteBuffer.allocateDirect(
m_numVertices * 4 * SIZEOF_FLOAT);
m_colorsets[channelIndex].order(ByteOrder.nativeOrder());
break;
case TEXCOORDS_1D:
m_numUVComponents[channelIndex] = 1;
m_texcoords[channelIndex] = ByteBuffer.allocateDirect(
m_numVertices * 1 * SIZEOF_FLOAT);
m_texcoords[channelIndex].order(ByteOrder.nativeOrder());
break;
case TEXCOORDS_2D:
m_numUVComponents[channelIndex] = 2;
m_texcoords[channelIndex] = ByteBuffer.allocateDirect(
m_numVertices * 2 * SIZEOF_FLOAT);
m_texcoords[channelIndex].order(ByteOrder.nativeOrder());
break;
case TEXCOORDS_3D:
m_numUVComponents[channelIndex] = 3;
m_texcoords[channelIndex] = ByteBuffer.allocateDirect(
m_numVertices * 3 * SIZEOF_FLOAT);
m_texcoords[channelIndex].order(ByteOrder.nativeOrder());
break;
default:
throw new IllegalArgumentException("unsupported channel type");
}
}
// }}
}
| 8,872 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiLight.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
/**
* Describes a light source.<p>
*
* Assimp supports multiple sorts of light sources, including
* directional, point and spot lights. All of them are defined with just
* a single structure and distinguished by their parameters.
* Note - some file formats (such as 3DS, ASE) export a "target point" -
* the point a spot light is looking at (it can even be animated). Assimp
* writes the target point as a subnode of a spotlights's main node,
* called "<spotName>.Target". However, this is just additional
* information then, the transformation tracks of the main node make the
* spot light already point in the right direction.
*/
public final class AiLight {
/**
* Constructor.
*
* @param name
* @param type
* @param position
* @param direction
* @param attenuationConstant
* @param attenuationLinear
* @param attenuationQuadratic
* @param diffuse
* @param specular
* @param ambient
* @param innerCone
* @param outerCone
*/
AiLight(String name, int type, Object position, Object direction,
float attenuationConstant, float attenuationLinear,
float attenuationQuadratic, Object diffuse, Object specular,
Object ambient, float innerCone, float outerCone) {
m_name = name;
m_type = AiLightType.fromRawValue(type);
m_position = position;
m_direction = direction;
m_attenuationConstant = attenuationConstant;
m_attenuationLinear = attenuationLinear;
m_attenuationQuadratic = attenuationQuadratic;
m_diffuse = diffuse;
m_specular = specular;
m_ambient = ambient;
m_innerCone = innerCone;
m_outerCone = outerCone;
}
/**
* Returns the name of the light source.<p>
*
* There must be a node in the scenegraph with the same name.
* This node specifies the position of the light in the scene
* hierarchy and can be animated.
*
* @return the name
*/
public String getName() {
return m_name;
}
/**
* Returns The type of the light source.
*
* @return the type
*/
public AiLightType getType() {
return m_type;
}
/**
* Returns the position of the light.<p>
*
* The position is relative to the transformation of the scene graph node
* corresponding to the light. The position is undefined for directional
* lights.<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built in behavior is to return an {@link AiVector}.
*
*
* @param wrapperProvider the wrapper provider (used for type inference)
*
* @return the position
*/
@SuppressWarnings("unchecked")
public <V3, M4, C, N, Q> V3 getPosition(AiWrapperProvider<V3, M4, C, N, Q>
wrapperProvider) {
return (V3) m_position;
}
/**
* Returns the direction of the light.<p>
*
* The direction is relative to the transformation of the scene graph node
* corresponding to the light. The direction is undefined for point lights.
* The vector may be normalized, but it needn't..<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built in behavior is to return an {@link AiVector}.
*
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the position
*/
@SuppressWarnings("unchecked")
public <V3, M4, C, N, Q> V3 getDirection(AiWrapperProvider<V3, M4, C, N, Q>
wrapperProvider) {
return (V3) m_direction;
}
/**
* Constant light attenuation factor.<p>
*
* The intensity of the light source at a given distance 'd' from
* the light's position is
* <code>Atten = 1/( att0 + att1 * d + att2 * d*d)</code>
* This member corresponds to the att0 variable in the equation.
* Naturally undefined for directional lights.
*
* @return the constant light attenuation factor
*/
public float getAttenuationConstant() {
return m_attenuationConstant;
}
/**
* Linear light attenuation factor.<p>
*
* The intensity of the light source at a given distance 'd' from
* the light's position is
* <code>Atten = 1/( att0 + att1 * d + att2 * d*d)</code>
* This member corresponds to the att1 variable in the equation.
* Naturally undefined for directional lights.
*
* @return the linear light attenuation factor
*/
public float getAttenuationLinear() {
return m_attenuationLinear;
}
/**
* Quadratic light attenuation factor.<p>
*
* The intensity of the light source at a given distance 'd' from
* the light's position is
* <code>Atten = 1/( att0 + att1 * d + att2 * d*d)</code>
* This member corresponds to the att2 variable in the equation.
* Naturally undefined for directional lights.
*
* @return the quadratic light attenuation factor
*/
public float getAttenuationQuadratic() {
return m_attenuationQuadratic;
}
/**
* Diffuse color of the light source.<p>
*
* The diffuse light color is multiplied with the diffuse
* material color to obtain the final color that contributes
* to the diffuse shading term.<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built in behavior is to return an {@link AiColor}.
*
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the diffuse color (alpha will be 1)
*/
@SuppressWarnings("unchecked")
public <V3, M4, C, N, Q> C getColorDiffuse(
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
return (C) m_diffuse;
}
/**
* Specular color of the light source.<p>
*
* The specular light color is multiplied with the specular
* material color to obtain the final color that contributes
* to the specular shading term.<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built in behavior is to return an {@link AiColor}.
*
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the specular color (alpha will be 1)
*/
@SuppressWarnings("unchecked")
public <V3, M4, C, N, Q> C getColorSpecular(
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
return (C) m_specular;
}
/**
* Ambient color of the light source.<p>
*
* The ambient light color is multiplied with the ambient
* material color to obtain the final color that contributes
* to the ambient shading term. Most renderers will ignore
* this value it, is just a remaining of the fixed-function pipeline
* that is still supported by quite many file formats.<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built in behavior is to return an {@link AiColor}.
*
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the ambient color (alpha will be 1)
*/
@SuppressWarnings("unchecked")
public <V3, M4, C, N, Q> C getColorAmbient(
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
return (C) m_ambient;
}
/**
* Inner angle of a spot light's light cone.<p>
*
* The spot light has maximum influence on objects inside this
* angle. The angle is given in radians. It is 2PI for point
* lights and undefined for directional lights.
*
* @return the inner angle
*/
public float getAngleInnerCone() {
return m_innerCone;
}
/**
* Outer angle of a spot light's light cone.<p>
*
* The spot light does not affect objects outside this angle.
* The angle is given in radians. It is 2PI for point lights and
* undefined for directional lights. The outer angle must be
* greater than or equal to the inner angle.
* It is assumed that the application uses a smooth
* interpolation between the inner and the outer cone of the
* spot light.
*
* @return the outer angle
*/
public float getAngleOuterCone() {
return m_outerCone;
}
/**
* Name.
*/
private final String m_name;
/**
* Type.
*/
private final AiLightType m_type;
/**
* Position.
*/
private final Object m_position;
/**
* Direction.
*/
private final Object m_direction;
/**
* Constant attenuation.
*/
private final float m_attenuationConstant;
/**
* Linear attenuation.
*/
private final float m_attenuationLinear;
/**
* Quadratic attenuation.
*/
private final float m_attenuationQuadratic;
/**
* Diffuse color.
*/
private final Object m_diffuse;
/**
* Specular color.
*/
private final Object m_specular;
/**
* Ambient color.
*/
private final Object m_ambient;
/**
* Inner cone of spotlight.
*/
private final float m_innerCone;
/**
* Outer cone of spotlight.
*/
private final float m_outerCone;
}
| 8,873 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiWrapperProvider.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
import java.nio.ByteBuffer;
/**
* Provides wrapper objects for raw data buffers.<p>
*
* It is likely that applications using Jassimp will already have a scene
* graph implementation and/ or the typical math related classes such as
* vectors, matrices, etc.<p>
*
* To ease the integration with existing code, Jassimp can be customized to
* represent the scene graph and compound data structures such as vectors and
* matrices with user supplied classes.<p>
*
* All methods returning wrapped objects rely on the AiWrapperProvider to
* create individual instances. Custom wrappers can be created by implementing
* AiWrapperProvider and registering the implementation via
* {@link Jassimp#setWrapperProvider(AiWrapperProvider)} <b>before</b> the
* scene is imported.<p>
*
* The methods returning wrapped types take an AiWrapperProvider instance. This
* instance must match the instance set via
* {@link Jassimp#setWrapperProvider(AiWrapperProvider)}. The method parameter
* is used to infer the type of the returned object. The passed in wrapper
* provider is not necessarily used to actually create the wrapped object, as
* the object may be cached for performance reasons. <b>It is not possible to
* use different AiWrapperProviders throughout the lifetime of an imported
* scene.</b>
*
* @param <V3> the type used to represent vectors
* @param <M4> the type used to represent matrices
* @param <C> the type used to represent colors
* @param <N> the type used to represent scene graph nodes
* @param <Q> the type used to represent quaternions
*/
public interface AiWrapperProvider<V3, M4, C, N, Q> {
/**
* Wraps a vector.<p>
*
* Most vectors are 3-dimensional, i.e., with 3 components. The exception
* are texture coordinates, which may be 1- or 2-dimensional. A vector
* consists of numComponents floats (x,y,z) starting from offset
*
* @param buffer the buffer to wrap
* @param offset the offset into buffer
* @param numComponents the number of components
* @return the wrapped vector
*/
V3 wrapVector3f(ByteBuffer buffer, int offset, int numComponents);
/**
* Wraps a 4x4 matrix of floats.<p>
*
* The calling code will allocate a new array for each invocation of this
* method. It is safe to store a reference to the passed in array and
* use the array to store the matrix data.
*
* @param data the matrix data in row-major order
* @return the wrapped matrix
*/
M4 wrapMatrix4f(float[] data);
/**
* Wraps a RGBA color.<p>
*
* A color consists of 4 float values (r,g,b,a) starting from offset
*
* @param buffer the buffer to wrap
* @param offset the offset into buffer
* @return the wrapped color
*/
C wrapColor(ByteBuffer buffer, int offset);
/**
* Wraps a scene graph node.<p>
*
* See {@link AiNode} for a description of the scene graph structure used
* by assimp.<p>
*
* The parent node is either null or an instance returned by this method.
* It is therefore safe to cast the passed in parent object to the
* implementation specific type
*
* @param parent the parent node
* @param matrix the transformation matrix
* @param meshReferences array of mesh references (indexes)
* @param name the name of the node
* @return the wrapped scene graph node
*/
N wrapSceneNode(Object parent, Object matrix, int[] meshReferences,
String name);
/**
* Wraps a quaternion.<p>
*
* A quaternion consists of 4 float values (w,x,y,z) starting from offset
*
* @param buffer the buffer to wrap
* @param offset the offset into buffer
* @return the wrapped quaternion
*/
Q wrapQuaternion(ByteBuffer buffer, int offset);
}
| 8,874 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiAnimation.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
import java.util.ArrayList;
import java.util.List;
/**
* An animation.<p>
*
* An animation consists of keyframe data for a number of nodes. For
* each node affected by the animation a separate series of data is given.<p>
*
* Like {@link AiMesh}, the animation related classes offer a Buffer API, a
* Direct API and a wrapped API. Please consult the documentation of
* {@link AiMesh} for a description and comparison of these APIs.
*/
public final class AiAnimation {
/**
* Name.
*/
private final String m_name;
/**
* Duration.
*/
private final double m_duration;
/**
* Ticks per second.
*/
private final double m_ticksPerSecond;
/**
* Bone animation channels.
*/
private final List<AiNodeAnim> m_nodeAnims = new ArrayList<AiNodeAnim>();
/**
* Constructor.
*
* @param name name
* @param duration duration
* @param ticksPerSecond ticks per second
*/
AiAnimation(String name, double duration, double ticksPerSecond) {
m_name = name;
m_duration = duration;
m_ticksPerSecond = ticksPerSecond;
}
/**
* Returns the name of the animation.<p>
*
* If the modeling package this data was exported from does support only
* a single animation channel, this name is usually empty (length is zero).
*
* @return the name
*/
public String getName() {
return m_name;
}
/**
* Returns the duration of the animation in ticks.
*
* @return the duration
*/
public double getDuration() {
return m_duration;
}
/**
* Returns the ticks per second.<p>
*
* 0 if not specified in the imported file
*
* @return the number of ticks per second
*/
public double getTicksPerSecond() {
return m_ticksPerSecond;
}
/**
* Returns the number of bone animation channels.<p>
*
* Each channel affects a single node. This method will return the same
* value as <code>getChannels().size()</code>
*
* @return the number of bone animation channels
*/
public int getNumChannels() {
return m_nodeAnims.size();
}
/**
* Returns the list of bone animation channels.<p>
*
* Each channel affects a single node. The array is mNumChannels in size.
*
* @return the list of bone animation channels
*/
public List<AiNodeAnim> getChannels() {
return m_nodeAnims;
}
/**
* Returns the number of mesh animation channels.<p>
*
* Each channel affects a single mesh and defines vertex-based animation.
* This method will return the same value as
* <code>getMeshChannels().size()</code>
*
* @return the number of mesh animation channels
*/
public int getNumMeshChannels() {
throw new UnsupportedOperationException("not implemented yet");
}
/**
* Returns the list of mesh animation channels.<p>
*
* Each channel affects a single mesh.
*
* @return the list of mesh animation channels
*/
public List<AiMeshAnim> getMeshChannels() {
throw new UnsupportedOperationException("not implemented yet");
}
}
| 8,875 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiMaterial.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Data structure for a material.<p>
*
* Depending on the imported scene and scene format, individual properties
* might be present or not. A list of all imported properties can be retrieved
* via {@link #getProperties()}.<p>
*
* This class offers <code>getXXX()</code> for all supported properties. These
* methods are fail-save, i.e., will return a default value when the
* corresponding property is not set. To change the built in default values,
* use the <code>setDefaultXXX()</code> methods.<p>
*
* If your application expects a certain set of properties to be available,
* the {@link #hasProperties(Set)} method can be used to check whether all
* these properties are actually set. If this check fails, you can still
* use this material via the <code>getXXX()</code> methods without special
* error handling code as the implementation guarantees to return default
* values for missing properties. This check will not work on texture related
* properties (i.e., properties starting with <code>TEX_</code>).
*/
public final class AiMaterial {
/**
* List of properties.
*/
private final List<Property> m_properties = new ArrayList<Property>();
/**
* Number of textures for each type.
*/
private final Map<AiTextureType, Integer> m_numTextures =
new EnumMap<AiTextureType, Integer>(AiTextureType.class);
/**
* Enumerates all supported material properties.
*/
public static enum PropertyKey {
/**
* Name.
*/
NAME("?mat.name", String.class),
/**
* Two-sided flag.
*/
TWO_SIDED("$mat.twosided", Integer.class),
/**
* Shading mode.
*/
SHADING_MODE("$mat.shadingm", AiShadingMode.class),
/**
* Wireframe flag.
*/
WIREFRAME("$mat.wireframe", Integer.class),
/**
* Blend mode.
*/
BLEND_MODE("$mat.blend", AiBlendMode.class),
/**
* Opacity.
*/
OPACITY("$mat.opacity", Float.class),
/**
* Bump scaling.
*/
BUMP_SCALING("$mat.bumpscaling", Float.class),
/**
* Shininess.
*/
SHININESS("$mat.shininess", Float.class),
/**
* Reflectivity.
*/
REFLECTIVITY("$mat.reflectivity", Float.class),
/**
* Shininess strength.
*/
SHININESS_STRENGTH("$mat.shinpercent", Float.class),
/**
* Refract index.
*/
REFRACTI("$mat.refracti", Float.class),
/**
* Diffuse color.
*/
COLOR_DIFFUSE("$clr.diffuse", Object.class),
/**
* Ambient color.
*/
COLOR_AMBIENT("$clr.ambient", Object.class),
/**
* Ambient color.
*/
COLOR_SPECULAR("$clr.specular", Object.class),
/**
* Emissive color.
*/
COLOR_EMISSIVE("$clr.emissive", Object.class),
/**
* Transparent color.
*/
COLOR_TRANSPARENT("$clr.transparent", Object.class),
/**
* Reflective color.
*/
COLOR_REFLECTIVE("$clr.reflective", Object.class),
/**
* Global background image.
*/
GLOBAL_BACKGROUND_IMAGE("?bg.global", String.class),
/**
* Texture file path.
*/
TEX_FILE("$tex.file", String.class),
/**
* Texture uv index.
*/
TEX_UV_INDEX("$tex.uvwsrc", Integer.class),
/**
* Texture blend factor.
*/
TEX_BLEND("$tex.blend", Float.class),
/**
* Texture operation.
*/
TEX_OP("$tex.op", AiTextureOp.class),
/**
* Texture map mode for u axis.
*/
TEX_MAP_MODE_U("$tex.mapmodeu", AiTextureMapMode.class),
/**
* Texture map mode for v axis.
*/
TEX_MAP_MODE_V("$tex.mapmodev", AiTextureMapMode.class),
/**
* Texture map mode for w axis.
*/
TEX_MAP_MODE_W("$tex.mapmodew", AiTextureMapMode.class);
/**
* Constructor.
*
* @param key key name as used by assimp
* @param type key type, used for casts and checks
*/
private PropertyKey(String key, Class<?> type) {
m_key = key;
m_type = type;
}
/**
* Key.
*/
private final String m_key;
/**
* Type.
*/
private final Class<?> m_type;
}
/**
* A very primitive RTTI system for the contents of material properties.
*/
public static enum PropertyType {
/**
* Array of single-precision (32 Bit) floats.
*/
FLOAT(0x1),
/**
* The material property is a string.
*/
STRING(0x3),
/**
* Array of (32 Bit) integers.
*/
INTEGER(0x4),
/**
* Simple binary buffer, content undefined. Not convertible to anything.
*/
BUFFER(0x5);
/**
* Utility method for converting from c/c++ based integer enums to java
* enums.<p>
*
* This method is intended to be used from JNI and my change based on
* implementation needs.
*
* @param rawValue an integer based enum value (as defined by assimp)
* @return the enum value corresponding to rawValue
*/
static PropertyType fromRawValue(int rawValue) {
for (PropertyType type : PropertyType.values()) {
if (type.m_rawValue == rawValue) {
return type;
}
}
throw new IllegalArgumentException("unexptected raw value: " +
rawValue);
}
/**
* Constructor.
*
* @param rawValue maps java enum to c/c++ integer enum values
*/
private PropertyType(int rawValue) {
m_rawValue = rawValue;
}
/**
* The mapped c/c++ integer enum value.
*/
private final int m_rawValue;
}
/**
* Data structure for a single material property.<p>
*
* As an user, you'll probably never need to deal with this data structure.
* Just use the provided get() family of functions to query material
* properties easily.
*/
public static final class Property {
/**
* Key.
*/
private final String m_key;
/**
* Semantic.
*/
private final int m_semantic;
/**
* Index.
*/
private final int m_index;
/**
* Type.
*/
private final PropertyType m_type;
/**
* Data.
*/
private final Object m_data;
/**
* Constructor.
*
* @param key
* @param semantic
* @param index
* @param type
* @param data
*/
Property(String key, int semantic, int index, int type,
Object data) {
m_key = key;
m_semantic = semantic;
m_index = index;
m_type = PropertyType.fromRawValue(type);
m_data = data;
}
/**
* Constructor.
*
* @param key
* @param semantic
* @param index
* @param type
* @param dataLen
*/
Property(String key, int semantic, int index, int type,
int dataLen) {
m_key = key;
m_semantic = semantic;
m_index = index;
m_type = PropertyType.fromRawValue(type);
ByteBuffer b = ByteBuffer.allocateDirect(dataLen);
b.order(ByteOrder.nativeOrder());
m_data = b;
}
/**
* Returns the key of the property.<p>
*
* Keys are generally case insensitive.
*
* @return the key
*/
public String getKey() {
return m_key;
}
/**
* Textures: Specifies their exact usage semantic.
* For non-texture properties, this member is always 0
* (or, better-said, #aiTextureType_NONE).
*
* @return the semantic
*/
public int getSemantic() {
return m_semantic;
}
/**
* Textures: Specifies the index of the texture.
* For non-texture properties, this member is always 0.
*
* @return the index
*/
public int getIndex() {
return m_index;
}
/**
* Type information for the property.<p>
*
* Defines the data layout inside the data buffer. This is used
* by the library internally to perform debug checks and to
* utilize proper type conversions.
* (It's probably a hacky solution, but it works.)
*
* @return the type
*/
public PropertyType getType() {
return m_type;
}
/**
* Binary buffer to hold the property's value.
* The size of the buffer is always mDataLength.
*
* @return the data
*/
public Object getData() {
return m_data;
}
}
/**
* Constructor.
*/
AiMaterial() {
/* nothing to do */
}
/**
* Checks whether the given set of properties is available.
*
* @param keys the keys to check
* @return true if all properties are available, false otherwise
*/
public boolean hasProperties(Set<PropertyKey> keys) {
for (PropertyKey key : keys) {
if (null == getProperty(key.m_key)) {
return false;
}
}
return true;
}
/**
* Sets a default value.<p>
*
* The passed in Object must match the type of the key as returned by
* the corresponding <code>getXXX()</code> method.
*
* @param key the key
* @param defaultValue the new default, may not be null
* @throws IllegalArgumentException if defaultValue is null or has a wrong
* type
*/
public void setDefault(PropertyKey key, Object defaultValue) {
if (null == defaultValue) {
throw new IllegalArgumentException("defaultValue may not be null");
}
if (key.m_type != defaultValue.getClass()) {
throw new IllegalArgumentException(
"defaultValue has wrong type, " +
"expected: " + key.m_type + ", found: " +
defaultValue.getClass());
}
m_defaults.put(key, defaultValue);
}
// {{ Fail-save Getters
/**
* Returns the name of the material.<p>
*
* If missing, defaults to empty string
*
* @return the name
*/
public String getName() {
return getTyped(PropertyKey.NAME, String.class);
}
/**
* Returns the two-sided flag.<p>
*
* If missing, defaults to 0
*
* @return the two-sided flag
*/
public int getTwoSided() {
return getTyped(PropertyKey.TWO_SIDED, Integer.class);
}
/**
* Returns the shading mode.<p>
*
* If missing, defaults to {@link AiShadingMode#FLAT}
*
* @return the shading mode
*/
public AiShadingMode getShadingMode() {
Property p = getProperty(PropertyKey.SHADING_MODE.m_key);
if (null == p || null == p.getData()) {
return (AiShadingMode) m_defaults.get(PropertyKey.SHADING_MODE);
}
return AiShadingMode.fromRawValue((Integer) p.getData());
}
/**
* Returns the wireframe flag.<p>
*
* If missing, defaults to 0
*
* @return the wireframe flag
*/
public int getWireframe() {
return getTyped(PropertyKey.WIREFRAME, Integer.class);
}
/**
* Returns the blend mode.<p>
*
* If missing, defaults to {@link AiBlendMode#DEFAULT}
*
* @return the blend mode
*/
public AiBlendMode getBlendMode() {
Property p = getProperty(PropertyKey.BLEND_MODE.m_key);
if (null == p || null == p.getData()) {
return (AiBlendMode) m_defaults.get(PropertyKey.BLEND_MODE);
}
return AiBlendMode.fromRawValue((Integer) p.getData());
}
/**
* Returns the opacity.<p>
*
* If missing, defaults to 1.0
*
* @return the opacity
*/
public float getOpacity() {
return getTyped(PropertyKey.OPACITY, Float.class);
}
/**
* Returns the bump scaling factor.<p>
*
* If missing, defaults to 1.0
*
* @return the bump scaling factor
*/
public float getBumpScaling() {
return getTyped(PropertyKey.BUMP_SCALING, Float.class);
}
/**
* Returns the shininess.<p>
*
* If missing, defaults to 1.0
*
* @return the shininess
*/
public float getShininess() {
return getTyped(PropertyKey.SHININESS, Float.class);
}
/**
* Returns the reflectivity.<p>
*
* If missing, defaults to 0.0
*
* @return the reflectivity
*/
public float getReflectivity() {
return getTyped(PropertyKey.REFLECTIVITY, Float.class);
}
/**
* Returns the shininess strength.<p>
*
* If missing, defaults to 0.0
*
* @return the shininess strength
*/
public float getShininessStrength() {
return getTyped(PropertyKey.SHININESS_STRENGTH, Float.class);
}
/**
* Returns the refract index.<p>
*
* If missing, defaults to 0.0
*
* @return the refract index
*/
public float getRefractIndex() {
return getTyped(PropertyKey.REFRACTI, Float.class);
}
/**
* Returns the diffuse color.<p>
*
* If missing, defaults to opaque white (1.0, 1.0, 1.0, 1.0)<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built-in behavior is to return a {@link AiVector}.
*
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the diffuse color
*/
@SuppressWarnings("unchecked")
public <V3, M4, C, N, Q> C getDiffuseColor(
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
Property p = getProperty(PropertyKey.COLOR_DIFFUSE.m_key);
if (null == p || null == p.getData()) {
Object def = m_defaults.get(PropertyKey.COLOR_DIFFUSE);
if (def == null) {
return (C) Jassimp.wrapColor4(1.0f, 1.0f, 1.0f, 1.0f);
}
return (C) def;
}
return (C) p.getData();
}
/**
* Returns the ambient color.<p>
*
* If missing, defaults to opaque white (1.0, 1.0, 1.0, 1.0)<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built-in behavior is to return a {@link AiVector}.
*
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the ambient color
*/
@SuppressWarnings("unchecked")
public <V3, M4, C, N, Q> C getAmbientColor(
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
Property p = getProperty(PropertyKey.COLOR_AMBIENT.m_key);
if (null == p || null == p.getData()) {
Object def = m_defaults.get(PropertyKey.COLOR_AMBIENT);
if (def == null) {
return (C) Jassimp.wrapColor4(1.0f, 1.0f, 1.0f, 1.0f);
}
return (C) def;
}
return (C) p.getData();
}
/**
* Returns the specular color.<p>
*
* If missing, defaults to opaque white (1.0, 1.0, 1.0, 1.0)<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built-in behavior is to return a {@link AiVector}.
*
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the specular color
*/
@SuppressWarnings("unchecked")
public <V3, M4, C, N, Q> C getSpecularColor(
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
Property p = getProperty(PropertyKey.COLOR_SPECULAR.m_key);
if (null == p || null == p.getData()) {
Object def = m_defaults.get(PropertyKey.COLOR_SPECULAR);
if (def == null) {
return (C) Jassimp.wrapColor4(1.0f, 1.0f, 1.0f, 1.0f);
}
return (C) def;
}
return (C) p.getData();
}
/**
* Returns the emissive color.<p>
*
* If missing, defaults to opaque white (1.0, 1.0, 1.0, 1.0)<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built-in behavior is to return a {@link AiVector}.
*
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the emissive color
*/
@SuppressWarnings("unchecked")
public <V3, M4, C, N, Q> C getEmissiveColor(
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
Property p = getProperty(PropertyKey.COLOR_EMISSIVE.m_key);
if (null == p || null == p.getData()) {
Object def = m_defaults.get(PropertyKey.COLOR_EMISSIVE);
if (def == null) {
return (C) Jassimp.wrapColor4(1.0f, 1.0f, 1.0f, 1.0f);
}
return (C) def;
}
return (C) p.getData();
}
/**
* Returns the transparent color.<p>
*
* If missing, defaults to opaque white (1.0, 1.0, 1.0, 1.0)<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built-in behavior is to return a {@link AiVector}.
*
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the transparent color
*/
@SuppressWarnings("unchecked")
public <V3, M4, C, N, Q> C getTransparentColor(
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
Property p = getProperty(PropertyKey.COLOR_TRANSPARENT.m_key);
if (null == p || null == p.getData()) {
Object def = m_defaults.get(PropertyKey.COLOR_TRANSPARENT);
if (def == null) {
return (C) Jassimp.wrapColor4(1.0f, 1.0f, 1.0f, 1.0f);
}
return (C) def;
}
return (C) p.getData();
}
/**
* Returns the reflective color.<p>
*
* If missing, defaults to opaque white (1.0, 1.0, 1.0, 1.0)<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).<p>
*
* The built-in behavior is to return a {@link AiVector}.
*
* @param wrapperProvider the wrapper provider (used for type inference)
* @return the reflective color
*/
@SuppressWarnings("unchecked")
public <V3, M4, C, N, Q> C getReflectiveColor(
AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) {
Property p = getProperty(PropertyKey.COLOR_REFLECTIVE.m_key);
if (null == p || null == p.getData()) {
Object def = m_defaults.get(PropertyKey.COLOR_REFLECTIVE);
if (def == null) {
return (C) Jassimp.wrapColor4(1.0f, 1.0f, 1.0f, 1.0f);
}
return (C) def;
}
return (C) p.getData();
}
/**
* Returns the global background image.<p>
*
* If missing, defaults to empty string
*
* @return the global background image
*/
public String getGlobalBackgroundImage() {
return getTyped(PropertyKey.GLOBAL_BACKGROUND_IMAGE, String.class);
}
/**
* Returns the number of textures of the given type.
*
* @param type the type
* @return the number of textures
*/
public int getNumTextures(AiTextureType type) {
return m_numTextures.get(type);
}
/**
* Returns the texture file.<p>
*
* If missing, defaults to empty string
*
* @param type the texture type
* @param index the index in the texture stack
* @return the file
* @throws IndexOutOfBoundsException if index is invalid
*/
public String getTextureFile(AiTextureType type, int index) {
checkTexRange(type, index);
return getTyped(PropertyKey.TEX_FILE, type, index, String.class);
}
/**
* Returns the index of the UV coordinate set used by the texture.<p>
*
* If missing, defaults to 0
*
* @param type the texture type
* @param index the index in the texture stack
* @return the UV index
* @throws IndexOutOfBoundsException if index is invalid
*/
public int getTextureUVIndex(AiTextureType type, int index) {
checkTexRange(type, index);
return getTyped(PropertyKey.TEX_UV_INDEX, type, index, Integer.class);
}
/**
* Returns the blend factor of the texture.<p>
*
* If missing, defaults to 1.0
*
* @param type the texture type
* @param index the index in the texture stack
* @return the blend factor
*/
public float getBlendFactor(AiTextureType type, int index) {
checkTexRange(type, index);
return getTyped(PropertyKey.TEX_BLEND, type, index, Float.class);
}
/**
* Returns the texture operation.<p>
*
* If missing, defaults to {@link AiTextureOp#ADD}
*
* @param type the texture type
* @param index the index in the texture stack
* @return the texture operation
*/
public AiTextureOp getTextureOp(AiTextureType type, int index) {
checkTexRange(type, index);
Property p = getProperty(PropertyKey.TEX_OP.m_key);
if (null == p || null == p.getData()) {
return (AiTextureOp) m_defaults.get(PropertyKey.TEX_OP);
}
return AiTextureOp.fromRawValue((Integer) p.getData());
}
/**
* Returns the texture mapping mode for the u axis.<p>
*
* If missing, defaults to {@link AiTextureMapMode#CLAMP}
*
* @param type the texture type
* @param index the index in the texture stack
* @return the texture mapping mode
*/
public AiTextureMapMode getTextureMapModeU(AiTextureType type, int index) {
checkTexRange(type, index);
Property p = getProperty(PropertyKey.TEX_MAP_MODE_U.m_key);
if (null == p || null == p.getData()) {
return (AiTextureMapMode) m_defaults.get(
PropertyKey.TEX_MAP_MODE_U);
}
return AiTextureMapMode.fromRawValue((Integer) p.getData());
}
/**
* Returns the texture mapping mode for the v axis.<p>
*
* If missing, defaults to {@link AiTextureMapMode#CLAMP}
*
* @param type the texture type
* @param index the index in the texture stack
* @return the texture mapping mode
*/
public AiTextureMapMode getTextureMapModeV(AiTextureType type, int index) {
checkTexRange(type, index);
Property p = getProperty(PropertyKey.TEX_MAP_MODE_V.m_key);
if (null == p || null == p.getData()) {
return (AiTextureMapMode) m_defaults.get(
PropertyKey.TEX_MAP_MODE_V);
}
return AiTextureMapMode.fromRawValue((Integer) p.getData());
}
/**
* Returns the texture mapping mode for the w axis.<p>
*
* If missing, defaults to {@link AiTextureMapMode#CLAMP}
*
* @param type the texture type
* @param index the index in the texture stack
* @return the texture mapping mode
*/
public AiTextureMapMode getTextureMapModeW(AiTextureType type, int index) {
checkTexRange(type, index);
Property p = getProperty(PropertyKey.TEX_MAP_MODE_W.m_key);
if (null == p || null == p.getData()) {
return (AiTextureMapMode) m_defaults.get(
PropertyKey.TEX_MAP_MODE_W);
}
return AiTextureMapMode.fromRawValue((Integer) p.getData());
}
/**
* Returns all information related to a single texture.
*
* @param type the texture type
* @param index the index in the texture stack
* @return the texture information
*/
public AiTextureInfo getTextureInfo(AiTextureType type, int index) {
return new AiTextureInfo(type, index, getTextureFile(type, index),
getTextureUVIndex(type, index), getBlendFactor(type, index),
getTextureOp(type, index), getTextureMapModeW(type, index),
getTextureMapModeW(type, index),
getTextureMapModeW(type, index));
}
// }}
// {{ Generic Getters
/**
* Returns a single property based on its key.
*
* @param key the key
* @return the property or null if the property is not set
*/
public Property getProperty(String key) {
for (Property property : m_properties) {
if (property.getKey().equals(key)) {
return property;
}
}
return null;
}
/**
* Returns a single property based on its key.
*
* @param key the key
* @param semantic the semantic type (texture type)
* @param index the index
* @return the property or null if the property is not set
*/
public Property getProperty(String key, int semantic, int index) {
for (Property property : m_properties) {
if (property.getKey().equals(key) &&
property.m_semantic == semantic &&
property.m_index == index) {
return property;
}
}
return null;
}
/**
* Returns all properties of the material.
*
* @return the list of properties
*/
public List<Property> getProperties() {
return m_properties;
}
// }}
/**
* Helper method. Returns typed property data.
*
* @param <T> type
* @param key the key
* @param clazz type
* @return the data
*/
private <T> T getTyped(PropertyKey key, Class<T> clazz) {
Property p = getProperty(key.m_key);
if (null == p || null == p.getData()) {
return clazz.cast(m_defaults.get(key));
}
return clazz.cast(p.getData());
}
/**
* Helper method. Returns typed property data.
*
* @param <T> type
* @param key the key
* @param type the texture type
* @param index the texture index
* @param clazz type
* @return the data
*/
private <T> T getTyped(PropertyKey key, AiTextureType type, int index,
Class<T> clazz) {
Property p = getProperty(key.m_key, AiTextureType.toRawValue(type),
index);
if (null == p || null == p.getData()) {
return clazz.cast(m_defaults.get(key));
}
return clazz.cast(p.getData());
}
/**
* Checks that index is valid an throw an exception if not.
*
* @param type the type
* @param index the index to check
*/
private void checkTexRange(AiTextureType type, int index) {
if (index < 0 || index > m_numTextures.get(type)) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " +
m_numTextures.get(type));
}
}
/**
* Defaults for missing properties.
*/
private Map<PropertyKey, Object> m_defaults =
new EnumMap<PropertyKey, Object>(PropertyKey.class);
{
setDefault(PropertyKey.NAME, "");
setDefault(PropertyKey.TWO_SIDED, 0);
setDefault(PropertyKey.SHADING_MODE, AiShadingMode.FLAT);
setDefault(PropertyKey.WIREFRAME, 0);
setDefault(PropertyKey.BLEND_MODE, AiBlendMode.DEFAULT);
setDefault(PropertyKey.OPACITY, 1.0f);
setDefault(PropertyKey.BUMP_SCALING, 1.0f);
setDefault(PropertyKey.SHININESS, 1.0f);
setDefault(PropertyKey.REFLECTIVITY, 0.0f);
setDefault(PropertyKey.SHININESS_STRENGTH, 0.0f);
setDefault(PropertyKey.REFRACTI, 0.0f);
/* bypass null checks for colors */
m_defaults.put(PropertyKey.COLOR_DIFFUSE, null);
m_defaults.put(PropertyKey.COLOR_AMBIENT, null);
m_defaults.put(PropertyKey.COLOR_SPECULAR, null);
m_defaults.put(PropertyKey.COLOR_EMISSIVE, null);
m_defaults.put(PropertyKey.COLOR_TRANSPARENT, null);
m_defaults.put(PropertyKey.COLOR_REFLECTIVE, null);
setDefault(PropertyKey.GLOBAL_BACKGROUND_IMAGE, "");
/* texture related values */
setDefault(PropertyKey.TEX_FILE, "");
setDefault(PropertyKey.TEX_UV_INDEX, 0);
setDefault(PropertyKey.TEX_BLEND, 1.0f);
setDefault(PropertyKey.TEX_OP, AiTextureOp.ADD);
setDefault(PropertyKey.TEX_MAP_MODE_U, AiTextureMapMode.CLAMP);
setDefault(PropertyKey.TEX_MAP_MODE_V, AiTextureMapMode.CLAMP);
setDefault(PropertyKey.TEX_MAP_MODE_W, AiTextureMapMode.CLAMP);
/* ensure we have defaults for everything */
for (PropertyKey key : PropertyKey.values()) {
if (!m_defaults.containsKey(key)) {
throw new IllegalStateException("missing default for: " + key);
}
}
}
/**
* This method is used by JNI, do not call or modify.
*
* @param type the type
* @param number the number
*/
@SuppressWarnings("unused")
private void setTextureNumber(int type, int number) {
m_numTextures.put(AiTextureType.fromRawValue(type), number);
}
}
| 8,876 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiMeshAnim.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
/**
* This class is a stub - mesh animations are currently not supported.
*/
public class AiMeshAnim {
}
| 8,877 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiSceneFlag.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
import java.util.Set;
/**
* Status flags for {@link AiScene}s.
*/
public enum AiSceneFlag {
/**
* Specifies that the scene data structure that was imported is not
* complete.<p>
*
* This flag bypasses some internal validations and allows the import
* of animation skeletons, material libraries or camera animation paths
* using Assimp. Most applications won't support such data.
*/
INCOMPLETE(0x1),
/**
* This flag is set by the validation
* ({@link AiPostProcessSteps#VALIDATE_DATA_STRUCTURE
* VALIDATE_DATA_STRUCTURE})
* postprocess-step if the validation is successful.<p>
*
* In a validated scene you can be sure that any cross references in the
* data structure (e.g. vertex indices) are valid.
*/
VALIDATED(0x2),
/**
* * This flag is set by the validation
* ({@link AiPostProcessSteps#VALIDATE_DATA_STRUCTURE
* VALIDATE_DATA_STRUCTURE})
* postprocess-step if the validation is successful but some issues have
* been found.<p>
*
* This can for example mean that a texture that does not exist is
* referenced by a material or that the bone weights for a vertex don't sum
* to 1.0 ... . In most cases you should still be able to use the import.
* This flag could be useful for applications which don't capture Assimp's
* log output.
*/
VALIDATION_WARNING(0x4),
/**
* This flag is currently only set by the
* {@link jassimp.AiPostProcessSteps#JOIN_IDENTICAL_VERTICES
* JOIN_IDENTICAL_VERTICES}.<p>
*
* It indicates that the vertices of the output meshes aren't in the
* internal verbose format anymore. In the verbose format all vertices are
* unique, no vertex is ever referenced by more than one face.
*/
NON_VERBOSE_FORMAT(0x8),
/**
* Denotes pure height-map terrain data.<p>
*
* Pure terrains usually consist of quads, sometimes triangles, in a
* regular grid. The x,y coordinates of all vertex positions refer to the
* x,y coordinates on the terrain height map, the z-axis stores the
* elevation at a specific point.<p>
*
* TER (Terragen) and HMP (3D Game Studio) are height map formats.
* <p>
* Assimp is probably not the best choice for loading *huge* terrains -
* fully triangulated data takes extremely much free store and should be
* avoided as long as possible (typically you'll do the triangulation when
* you actually need to render it).
*/
TERRAIN(0x10);
/**
* The mapped c/c++ integer enum value.
*/
private final int m_rawValue;
/**
* Utility method for converting from c/c++ based integer enums to java
* enums.<p>
*
* This method is intended to be used from JNI and my change based on
* implementation needs.
*
* @param set the target set to fill
* @param rawValue an integer based enum value (as defined by assimp)
*/
static void fromRawValue(Set<AiSceneFlag> set, int rawValue) {
for (AiSceneFlag type : AiSceneFlag.values()) {
if ((type.m_rawValue & rawValue) != 0) {
set.add(type);
}
}
}
/**
* Constructor.
*
* @param rawValue maps java enum to c/c++ integer enum values
*/
private AiSceneFlag(int rawValue) {
m_rawValue = rawValue;
}
}
| 8,878 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiAnimBehavior.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
/**
* Defines how an animation channel behaves outside the defined time range.
*/
public enum AiAnimBehavior {
/**
* The value from the default node transformation is taken.
*/
DEFAULT(0x0),
/**
* The nearest key value is used without interpolation.
*/
CONSTANT(0x1),
/**
* The value of the nearest two keys is linearly extrapolated for the
* current time value.
*/
LINEAR(0x2),
/**
* The animation is repeated.<p>
*
* If the animation key go from n to m and the current time is t, use the
* value at (t-n) % (|m-n|).
*/
REPEAT(0x3);
/**
* Utility method for converting from c/c++ based integer enums to java
* enums.<p>
*
* This method is intended to be used from JNI and my change based on
* implementation needs.
*
* @param rawValue an integer based enum value (as defined by assimp)
* @return the enum value corresponding to rawValue
*/
static AiAnimBehavior fromRawValue(int rawValue) {
for (AiAnimBehavior type : AiAnimBehavior.values()) {
if (type.m_rawValue == rawValue) {
return type;
}
}
throw new IllegalArgumentException("unexptected raw value: " +
rawValue);
}
/**
* Constructor.
*
* @param rawValue maps java enum to c/c++ integer enum values
*/
private AiAnimBehavior(int rawValue) {
m_rawValue = rawValue;
}
/**
* The mapped c/c++ integer enum value.
*/
private final int m_rawValue;
}
| 8,879 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/JaiDebug.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
import java.nio.ByteBuffer;
/**
* Debug/utility methods.
*/
public final class JaiDebug {
/**
* Pure static class, no accessible constructor.
*/
private JaiDebug() {
/* nothing to do */
}
/**
* Dumps vertex positions of a mesh to stdout.<p>
*
* @param mesh the mesh
*/
public static void dumpPositions(AiMesh mesh) {
if (!mesh.hasPositions()) {
System.out.println("mesh has no vertex positions");
return;
}
for (int i = 0; i < mesh.getNumVertices(); i++) {
System.out.println("[" +
mesh.getPositionX(i) + ", " +
mesh.getPositionY(i) + ", " +
mesh.getPositionZ(i) + "]"
);
}
}
/**
* Dumps faces of a mesh to stdout.<p>
*
* @param mesh the mesh
*/
public static void dumpFaces(AiMesh mesh) {
if (!mesh.hasFaces()) {
System.out.println("mesh has no faces");
return;
}
for (int face = 0; face < mesh.getNumFaces(); face++) {
int faceNumIndices = mesh.getFaceNumIndices(face);
System.out.print(faceNumIndices + ": ");
for (int vertex = 0; vertex < faceNumIndices; vertex++) {
int reference = mesh.getFaceVertex(face, vertex);
System.out.print("[" +
mesh.getPositionX(reference) + ", " +
mesh.getPositionY(reference) + ", " +
mesh.getPositionZ(reference) + "] "
);
}
System.out.println();
}
}
/**
* Dumps a vertex color set of a mesh to stdout.<p>
*
* @param mesh the mesh
* @param colorset the color set
*/
public static void dumpColorset(AiMesh mesh, int colorset) {
if (!mesh.hasColors(colorset)) {
System.out.println("mesh has no vertex color set " + colorset);
return;
}
for (int i = 0; i < mesh.getNumVertices(); i++) {
System.out.println("[" +
mesh.getColorR(i, colorset) + ", " +
mesh.getColorG(i, colorset) + ", " +
mesh.getColorB(i, colorset) + ", " +
mesh.getColorA(i, colorset) + "]"
);
}
}
/**
* Dumps a texture coordinate set of a mesh to stdout.
*
* @param mesh the mesh
* @param coords the coordinates
*/
public static void dumpTexCoords(AiMesh mesh, int coords) {
if (!mesh.hasTexCoords(coords)) {
System.out.println("mesh has no texture coordinate set " + coords);
return;
}
for (int i = 0; i < mesh.getNumVertices(); i++) {
int numComponents = mesh.getNumUVComponents(coords);
System.out.print("[" + mesh.getTexCoordU(i, coords));
if (numComponents > 1) {
System.out.print(", " + mesh.getTexCoordV(i, coords));
}
if (numComponents > 2) {
System.out.print(", " + mesh.getTexCoordW(i, coords));
}
System.out.println("]");
}
}
/**
* Dumps a single material property to stdout.
*
* @param property the property
*/
public static void dumpMaterialProperty(AiMaterial.Property property) {
System.out.print(property.getKey() + " " + property.getSemantic() +
" " + property.getIndex() + ": ");
Object data = property.getData();
if (data instanceof ByteBuffer) {
ByteBuffer buf = (ByteBuffer) data;
for (int i = 0; i < buf.capacity(); i++) {
System.out.print(Integer.toHexString(buf.get(i) & 0xFF) + " ");
}
System.out.println();
}
else {
System.out.println(data.toString());
}
}
/**
* Dumps all properties of a material to stdout.
*
* @param material the material
*/
public static void dumpMaterial(AiMaterial material) {
for (AiMaterial.Property prop : material.getProperties()) {
dumpMaterialProperty(prop);
}
}
/**
* Dumps an animation channel to stdout.
*
* @param nodeAnim the channel
*/
public static void dumpNodeAnim(AiNodeAnim nodeAnim) {
for (int i = 0; i < nodeAnim.getNumPosKeys(); i++) {
System.out.println(i + ": " + nodeAnim.getPosKeyTime(i) +
" ticks, " + nodeAnim.getPosKeyVector(i, Jassimp.BUILTIN));
}
}
}
| 8,880 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiMatrix4f.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
/**
* Simple 4x4 matrix of floats.
*/
public final class AiMatrix4f {
/**
* Wraps the given array of floats as matrix.
* <p>
*
* The array must have exactly 16 entries. The data in the array must be in
* row-major order.
*
* @param data
* the array to wrap, may not be null
*/
public AiMatrix4f(float[] data) {
if (data == null) {
throw new IllegalArgumentException("data may not be null");
}
if (data.length != 16) {
throw new IllegalArgumentException("array length is not 16");
}
m_data = data;
}
/**
* Gets an element of the matrix.
*
* @param row
* the row
* @param col
* the column
* @return the element at the given position
*/
public float get(int row, int col) {
if (row < 0 || row > 3) {
throw new IndexOutOfBoundsException("Index: " + row + ", Size: 4");
}
if (col < 0 || col > 3) {
throw new IndexOutOfBoundsException("Index: " + col + ", Size: 4");
}
return m_data[row * 4 + col];
}
/**
* Stores the matrix in a new direct ByteBuffer with native byte order.
* <p>
*
* The returned buffer can be passed to rendering APIs such as LWJGL, e.g.,
* as parameter for <code>GL20.glUniformMatrix4()</code>. Be sure to set
* <code>transpose</code> to <code>true</code> in this case, as OpenGL
* expects the matrix in column order.
*
* @return a new native order, direct ByteBuffer
*/
public FloatBuffer toByteBuffer() {
ByteBuffer bbuf = ByteBuffer.allocateDirect(16 * 4);
bbuf.order(ByteOrder.nativeOrder());
FloatBuffer fbuf = bbuf.asFloatBuffer();
fbuf.put(m_data);
fbuf.flip();
return fbuf;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 4; col++) {
buf.append(m_data[row * 4 + col]).append(" ");
}
buf.append("\n");
}
return buf.toString();
}
/**
* Data buffer.
*/
private final float[] m_data;
}
| 8,881 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/Jassimp.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.EnumSet;
import java.util.Set;
/**
* Entry point to the jassimp library.<p>
*
* Use {@link #importFile(String, Set)} to load a file.
*
* <h3>General Notes and Pitfalls</h3>
* Due to the loading via JNI, strings (for example as returned by the
* <code>getName()</code> methods) are not interned. You should therefore
* compare strings the way it should be done, i.e, via <code>equals()</code>.
* Pointer comparison will fail.
*/
public final class Jassimp {
/**
* The native interface.
*
* @param filename the file to load
* @param postProcessing post processing flags
* @return the loaded scene, or null if an error occurred
* @throws IOException if an error occurs
*/
private static native AiScene aiImportFile(String filename,
long postProcessing, AiIOSystem<?> ioSystem,
AiProgressHandler progressHandler) throws IOException;
/**
* The active wrapper provider.
*/
private static AiWrapperProvider<?, ?, ?, ?, ?> s_wrapperProvider =
new AiBuiltInWrapperProvider();
/**
* The library loader to load the native library.
*/
private static JassimpLibraryLoader s_libraryLoader =
new JassimpLibraryLoader();
/**
* Status flag if the library is loaded.
*
* Volatile to avoid problems with double checked locking.
*
*/
private static volatile boolean s_libraryLoaded = false;
/**
* Lock for library loading.
*/
private static final Object s_libraryLoadingLock = new Object();
/**
* The default wrapper provider using built in types.
*/
public static final AiWrapperProvider<?, ?, ?, ?, ?> BUILTIN =
new AiBuiltInWrapperProvider();
/**
* Imports a file via assimp without post processing.
*
* @param filename the file to import
* @return the loaded scene
* @throws IOException if an error occurs
*/
public static AiScene importFile(String filename) throws IOException {
return importFile(filename, EnumSet.noneOf(AiPostProcessSteps.class));
}
/**
* Imports a file via assimp without post processing.
*
* @param filename the file to import
* @param ioSystem ioSystem to load files, or null for default
* @return the loaded scene
* @throws IOException if an error occurs
*/
public static AiScene importFile(String filename, AiIOSystem<?> ioSystem)
throws IOException {
return importFile(filename, EnumSet.noneOf(AiPostProcessSteps.class), ioSystem);
}
/**
* Imports a file via assimp.
*
* @param filename the file to import
* @param postProcessing post processing flags
* @return the loaded scene, or null if an error occurred
* @throws IOException if an error occurs
*/
public static AiScene importFile(String filename,
Set<AiPostProcessSteps> postProcessing)
throws IOException {
return importFile(filename, postProcessing, null);
}
/**
* Imports a file via assimp.
*
* @param filename the file to import
* @param postProcessing post processing flags
* @param ioSystem ioSystem to load files, or null for default
* @return the loaded scene, or null if an error occurred
* @throws IOException if an error occurs
*/
public static AiScene importFile(String filename,
Set<AiPostProcessSteps> postProcessing, AiIOSystem<?> ioSystem)
throws IOException {
return importFile(filename, postProcessing, ioSystem, null);
}
/**
* Imports a file via assimp.
*
* @param filename the file to import
* @param postProcessing post processing flags
* @param ioSystem ioSystem to load files, or null for default
* @return the loaded scene, or null if an error occurred
* @throws IOException if an error occurs
*/
public static AiScene importFile(String filename,
Set<AiPostProcessSteps> postProcessing, AiIOSystem<?> ioSystem,
AiProgressHandler progressHandler) throws IOException {
loadLibrary();
return aiImportFile(filename, AiPostProcessSteps.toRawValue(
postProcessing), ioSystem, progressHandler);
}
/**
* Returns the size of a struct or ptimitive.<p>
*
* @return the result of sizeof call
*/
public static native int getVKeysize();
/**
* @see #getVKeysize
*/
public static native int getQKeysize();
/**
* @see #getVKeysize
*/
public static native int getV3Dsize();
/**
* @see #getVKeysize
*/
public static native int getfloatsize();
/**
* @see #getVKeysize
*/
public static native int getintsize();
/**
* @see #getVKeysize
*/
public static native int getuintsize();
/**
* @see #getVKeysize
*/
public static native int getdoublesize();
/**
* @see #getVKeysize
*/
public static native int getlongsize();
/**
* Returns a human readable error description.<p>
*
* This method can be called when one of the import methods fails, i.e.,
* throws an exception, to get a human readable error description.
*
* @return the error string
*/
public static native String getErrorString();
/**
* Returns the active wrapper provider.<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).
*
* @return the active wrapper provider
*/
public static AiWrapperProvider<?, ?, ?, ?, ?> getWrapperProvider() {
return s_wrapperProvider;
}
/**
* Sets a new wrapper provider.<p>
*
* This method is part of the wrapped API (see {@link AiWrapperProvider}
* for details on wrappers).
*
* @param wrapperProvider the new wrapper provider
*/
public static void setWrapperProvider(AiWrapperProvider<?, ?, ?, ?, ?>
wrapperProvider) {
s_wrapperProvider = wrapperProvider;
}
public static void setLibraryLoader(JassimpLibraryLoader libraryLoader) {
s_libraryLoader = libraryLoader;
}
/**
* Helper method for wrapping a matrix.<p>
*
* Used by JNI, do not modify!
*
* @param data the matrix data
* @return the wrapped matrix
*/
static Object wrapMatrix(float[] data) {
return s_wrapperProvider.wrapMatrix4f(data);
}
/**
* Helper method for wrapping a color (rgb).<p>
*
* Used by JNI, do not modify!
*
* @param red red component
* @param green green component
* @param blue blue component
* @return the wrapped color
*/
static Object wrapColor3(float red, float green, float blue) {
return wrapColor4(red, green, blue, 1.0f);
}
/**
* Helper method for wrapping a color (rgba).<p>
*
* Used by JNI, do not modify!
*
* @param red red component
* @param green green component
* @param blue blue component
* @param alpha alpha component
* @return the wrapped color
*/
static Object wrapColor4(float red, float green, float blue, float alpha) {
ByteBuffer temp = ByteBuffer.allocate(4 * 4);
temp.putFloat(red);
temp.putFloat(green);
temp.putFloat(blue);
temp.putFloat(alpha);
temp.flip();
return s_wrapperProvider.wrapColor(temp, 0);
}
/**
* Helper method for wrapping a vector.<p>
*
* Used by JNI, do not modify!
*
* @param x x component
* @param y y component
* @param z z component
* @return the wrapped vector
*/
static Object wrapVec3(float x, float y, float z) {
ByteBuffer temp = ByteBuffer.allocate(3 * 4);
temp.putFloat(x);
temp.putFloat(y);
temp.putFloat(z);
temp.flip();
return s_wrapperProvider.wrapVector3f(temp, 0, 3);
}
/**
* Helper method for wrapping a scene graph node.<p>
*
* Used by JNI, do not modify!
*
* @param parent the parent node
* @param matrix the transformation matrix
* @param meshRefs array of matrix references
* @param name the name of the node
* @return the wrapped matrix
*/
static Object wrapSceneNode(Object parent, Object matrix, int[] meshRefs,
String name) {
return s_wrapperProvider.wrapSceneNode(parent, matrix, meshRefs, name);
}
/**
* Helper method to load the library using the provided JassimpLibraryLoader.<p>
*
* Synchronized to avoid race conditions.
*/
private static void loadLibrary()
{
if(!s_libraryLoaded)
{
synchronized(s_libraryLoadingLock)
{
if(!s_libraryLoaded)
{
s_libraryLoader.loadLibrary();
NATIVE_AIVEKTORKEY_SIZE = getVKeysize();
NATIVE_AIQUATKEY_SIZE = getQKeysize();
NATIVE_AIVEKTOR3D_SIZE = getV3Dsize();
NATIVE_FLOAT_SIZE = getfloatsize();
NATIVE_INT_SIZE = getintsize();
NATIVE_UINT_SIZE = getuintsize();
NATIVE_DOUBLE_SIZE = getdoublesize();
NATIVE_LONG_SIZE = getlongsize();
s_libraryLoaded = true;
}
}
}
}
/**
* Pure static class, no accessible constructor.
*/
private Jassimp() {
/* nothing to do */
}
public static int NATIVE_AIVEKTORKEY_SIZE;
public static int NATIVE_AIQUATKEY_SIZE;
public static int NATIVE_AIVEKTOR3D_SIZE;
public static int NATIVE_FLOAT_SIZE;
public static int NATIVE_INT_SIZE;
public static int NATIVE_UINT_SIZE;
public static int NATIVE_DOUBLE_SIZE;
public static int NATIVE_LONG_SIZE;
}
| 8,882 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiTextureOp.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
/**
* Defines how the Nth texture of a specific type is combined with the result
* of all previous layers.<p>
*
* Example (left: key, right: value): <br>
* <code><pre>
* DiffColor0 - gray
* DiffTextureOp0 - aiTextureOpMultiply
* DiffTexture0 - tex1.png
* DiffTextureOp0 - aiTextureOpAdd
* DiffTexture1 - tex2.png
* </pre></code>
*
* Written as equation, the final diffuse term for a specific pixel would be:
* <code><pre>
* diffFinal = DiffColor0 * sampleTex(DiffTexture0,UV0) +
* sampleTex(DiffTexture1,UV0) * diffContrib;
* </pre></code>
* where 'diffContrib' is the intensity of the incoming light for that pixel.
*/
public enum AiTextureOp {
/**
* <code>T = T1 * T2</code>.
*/
MULTIPLY(0x0),
/**
* <code>T = T1 + T2</code>.
*/
ADD(0x1),
/**
* <code>T = T1 - T2</code>.
*/
SUBTRACT(0x2),
/**
* <code>T = T1 / T2</code>.
*/
DIVIDE(0x3),
/**
* <code>T = (T1 + T2) - (T1 * T2)</code> .
*/
SMOOTH_ADD(0x4),
/**
* <code>T = T1 + (T2-0.5)</code>.
*/
SIGNED_ADD(0x5);
/**
* Utility method for converting from c/c++ based integer enums to java
* enums.<p>
*
* This method is intended to be used from JNI and my change based on
* implementation needs.
*
* @param rawValue an integer based enum value (as defined by assimp)
* @return the enum value corresponding to rawValue
*/
static AiTextureOp fromRawValue(int rawValue) {
for (AiTextureOp type : AiTextureOp.values()) {
if (type.m_rawValue == rawValue) {
return type;
}
}
throw new IllegalArgumentException("unexptected raw value: " +
rawValue);
}
/**
* Constructor.
*
* @param rawValue maps java enum to c/c++ integer enum values
*/
private AiTextureOp(int rawValue) {
m_rawValue = rawValue;
}
/**
* The mapped c/c++ integer enum value.
*/
private final int m_rawValue;
}
| 8,883 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiTextureInfo.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
/**
* Data structure for texture related material properties.
*/
public final class AiTextureInfo {
/**
* Constructor.
*
* @param type type
* @param index index
* @param file file
* @param uvIndex uv index
* @param blend blend factor
* @param texOp texture operation
* @param mmU map mode for u axis
* @param mmV map mode for v axis
* @param mmW map mode for w axis
*/
AiTextureInfo(AiTextureType type, int index, String file,
int uvIndex, float blend, AiTextureOp texOp, AiTextureMapMode mmU,
AiTextureMapMode mmV, AiTextureMapMode mmW) {
m_type = type;
m_index = index;
m_file = file;
m_uvIndex = uvIndex;
m_blend = blend;
m_textureOp = texOp;
m_textureMapModeU = mmU;
m_textureMapModeV = mmV;
m_textureMapModeW = mmW;
}
/**
* Specifies the type of the texture (e.g. diffuse, specular, ...).
*
* @return the type.
*/
public AiTextureType getType() {
return m_type;
}
/**
* Index of the texture in the texture stack.<p>
*
* Each type maintains a stack of textures, i.e., there may be a diffuse.0,
* a diffuse.1, etc
*
* @return the index
*/
public int getIndex() {
return m_index;
}
/**
* Returns the path to the texture file.
*
* @return the path
*/
public String getFile() {
return m_file;
}
/**
* Returns the index of the UV coordinate set.
*
* @return the uv index
*/
public int getUVIndex() {
return m_uvIndex;
}
/**
* Returns the blend factor.
*
* @return the blend factor
*/
public float getBlend() {
return m_blend;
}
/**
* Returns the texture operation used to combine this texture and the
* preceding texture in the stack.
*
* @return the texture operation
*/
public AiTextureOp getTextureOp() {
return m_textureOp;
}
/**
* Returns the texture map mode for U texture axis.
*
* @return the texture map mode
*/
public AiTextureMapMode getTextureMapModeU() {
return m_textureMapModeU;
}
/**
* Returns the texture map mode for V texture axis.
*
* @return the texture map mode
*/
public AiTextureMapMode getTextureMapModeV() {
return m_textureMapModeV;
}
/**
* Returns the texture map mode for W texture axis.
*
* @return the texture map mode
*/
public AiTextureMapMode getTextureMapModeW() {
return m_textureMapModeW;
}
/**
* Type.
*/
private final AiTextureType m_type;
/**
* Index.
*/
private final int m_index;
/**
* Path.
*/
private final String m_file;
/**
* UV index.
*/
private final int m_uvIndex;
/**
* Blend factor.
*/
private final float m_blend;
/**
* Texture operation.
*/
private final AiTextureOp m_textureOp;
/**
* Map mode U axis.
*/
private final AiTextureMapMode m_textureMapModeU;
/**
* Map mode V axis.
*/
private final AiTextureMapMode m_textureMapModeV;
/**
* Map mode W axis.
*/
private final AiTextureMapMode m_textureMapModeW;
}
| 8,884 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiIOSystem.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
public interface AiIOSystem <T extends AiIOStream>
{
/**
*
* Open a new file with a given path.
* When the access to the file is finished, call close() to release all associated resources
*
* @param path Path to the file
* @param ioMode file I/O mode. Required are: "wb", "w", "wt", "rb", "r", "rt".
*
* @return AiIOStream or null if an error occurred
*/
public T open(String path, String ioMode);
/**
* Tests for the existence of a file at the given path.
*
* @param path path to the file
* @return true if there is a file with this path, else false.
*/
public boolean exists(String path);
/**
* Returns the system specific directory separator.<p>
*
* @return System specific directory separator
*/
public char getOsSeparator();
/**
* Closes the given file and releases all resources associated with it.
*
* @param file The file instance previously created by Open().
*/
public void close(T file);
}
| 8,885 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiPrimitiveType.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
import java.util.Set;
/**
* Enumerates the types of geometric primitives supported by Assimp.<p>
*/
public enum AiPrimitiveType {
/**
* A point primitive.
*/
POINT(0x1),
/**
* A line primitive.
*/
LINE(0x2),
/**
* A triangular primitive.
*/
TRIANGLE(0x4),
/**
* A higher-level polygon with more than 3 edges.<p>
*
* A triangle is a polygon, but polygon in this context means
* "all polygons that are not triangles". The "Triangulate"-Step is provided
* for your convenience, it splits all polygons in triangles (which are much
* easier to handle).
*/
POLYGON(0x8);
/**
* Utility method for converting from c/c++ based integer enums to java
* enums.<p>
*
* This method is intended to be used from JNI and my change based on
* implementation needs.
*
* @param set the target set to fill
* @param rawValue an integer based enum value (as defined by assimp)
*/
static void fromRawValue(Set<AiPrimitiveType> set, int rawValue) {
for (AiPrimitiveType type : AiPrimitiveType.values()) {
if ((type.m_rawValue & rawValue) != 0) {
set.add(type);
}
}
}
/**
* Constructor.
*
* @param rawValue maps java enum to c/c++ integer enum values
*/
private AiPrimitiveType(int rawValue) {
m_rawValue = rawValue;
}
/**
* The mapped c/c++ integer enum value.
*/
private final int m_rawValue;
}
| 8,886 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiBoneWeight.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
/**
* A single influence of a bone on a vertex.
*/
public final class AiBoneWeight {
/**
* Constructor.
*/
AiBoneWeight() {
/* nothing to do */
}
/**
* Index of the vertex which is influenced by the bone.
*
* @return the vertex index
*/
public int getVertexId() {
return m_vertexId;
}
/**
* The strength of the influence in the range (0...1).<p>
*
* The influence from all bones at one vertex amounts to 1
*
* @return the influence
*/
public float getWeight() {
return m_weight;
}
/**
* Vertex index.
*/
private int m_vertexId;
/**
* Influence of bone on vertex.
*/
private float m_weight;
}
| 8,887 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiQuaternion.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
import java.nio.ByteBuffer;
/**
* Wrapper for a quaternion.<p>
*
* The wrapper is writable, i.e., changes performed via the set-methods will
* modify the underlying mesh/animation.
*/
public final class AiQuaternion {
/**
* Wrapped buffer.
*/
private final ByteBuffer m_buffer;
/**
* Offset into m_buffer.
*/
private final int m_offset;
/**
* Constructor.
*
* @param buffer the buffer to wrap
* @param offset offset into buffer
*/
public AiQuaternion(ByteBuffer buffer, int offset) {
if (null == buffer) {
throw new IllegalArgumentException("buffer may not be null");
}
m_buffer = buffer;
m_offset = offset;
}
/**
* Returns the x value.
*
* @return the x value
*/
public float getX() {
return m_buffer.getFloat(m_offset + 4);
}
/**
* Returns the y value.
*
* @return the y value
*/
public float getY() {
return m_buffer.getFloat(m_offset + 8);
}
/**
* Returns the z value.
*
* @return the z value
*/
public float getZ() {
return m_buffer.getFloat(m_offset + 12);
}
/**
* Returns the w value.
*
* @return the w value
*/
public float getW() {
return m_buffer.getFloat(m_offset);
}
/**
* Sets the x component.
*
* @param x the new value
*/
public void setX(float x) {
m_buffer.putFloat(m_offset + 4, x);
}
/**
* Sets the y component.
*
* @param y the new value
*/
public void setY(float y) {
m_buffer.putFloat(m_offset + 8, y);
}
/**
* Sets the z component.
*
* @param z the new value
*/
public void setZ(float z) {
m_buffer.putFloat(m_offset + 12, z);
}
/**
* Sets the z component.
*
* @param w the new value
*/
public void setW(float w) {
m_buffer.putFloat(m_offset, w);
}
@Override
public String toString() {
return "[" + getX() + ", " + getY() + ", " + getZ() + ", " +
getW() + "]";
}
}
| 8,888 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiColor.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
import java.nio.ByteBuffer;
/**
* Wrapper for colors.<p>
*
* The wrapper is writable, i.e., changes performed via the set-methods will
* modify the underlying mesh.
*/
public final class AiColor {
/**
* Wrapped buffer.
*/
private final ByteBuffer m_buffer;
/**
* Offset into m_buffer.
*/
private final int m_offset;
/**
* Constructor.
*
* @param buffer the buffer to wrap
* @param offset offset into buffer
*/
public AiColor(ByteBuffer buffer, int offset) {
m_buffer = buffer;
m_offset = offset;
}
/**
* Returns the red color component.
*
* @return the red component
*/
public float getRed() {
return m_buffer.getFloat(m_offset);
}
/**
* Returns the green color component.
*
* @return the green component
*/
public float getGreen() {
return m_buffer.getFloat(m_offset + 4);
}
/**
* Returns the blue color component.
*
* @return the blue component
*/
public float getBlue() {
return m_buffer.getFloat(m_offset + 8);
}
/**
* Returns the alpha color component.
*
* @return the alpha component
*/
public float getAlpha() {
return m_buffer.getFloat(m_offset + 12);
}
/**
* Sets the red color component.
*
* @param red the new value
*/
public void setRed(float red) {
m_buffer.putFloat(m_offset, red);
}
/**
* Sets the green color component.
*
* @param green the new value
*/
public void setGreen(float green) {
m_buffer.putFloat(m_offset + 4, green);
}
/**
* Sets the blue color component.
*
* @param blue the new value
*/
public void setBlue(float blue) {
m_buffer.putFloat(m_offset + 8, blue);
}
/**
* Sets the alpha color component.
*
* @param alpha the new value
*/
public void setAlpha(float alpha) {
m_buffer.putFloat(m_offset + 12, alpha);
}
@Override
public String toString() {
return "[" + getRed() + ", " + getGreen() + ", " + getBlue() + ", " +
getAlpha() + "]";
}
}
| 8,889 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiConfigOptions.java | /*
* $Revision$
* $Date$
*/
package jassimp;
/**
* Lists all possible configuration options.<p>
*
* This class is work-in-progress
*/
public enum AiConfigOptions {
/**
* Maximum bone count per mesh for the SplitbyBoneCount step.<p>
*
* Meshes are split until the maximum number of bones is reached. The
* default value is AI_SBBC_DEFAULT_MAX_BONES, which may be altered at
* compile-time. This limit is imposed by the native jassimp library
* and typically is 60.<p>
*
* Property data type: integer.
*/
PP_SBBC_MAX_BONES("PP_SBBC_MAX_BONES"),
/**
* Specifies the maximum angle that may be between two vertex tangents
* that their tangents and bi-tangents are smoothed.<p>
*
* This applies to the CalcTangentSpace-Step. The angle is specified
* in degrees. The maximum value is 175.<p>
*
* Property type: float. Default value: 45 degrees
*/
PP_CT_MAX_SMOOTHING_ANGLE("PP_CT_MAX_SMOOTHING_ANGLE"),
/**
* Source UV channel for tangent space computation.<p>
*
* The specified channel must exist or an error will be raised.<p>
*
* Property type: integer. Default value: 0
*/
PP_CT_TEXTURE_CHANNEL_INDEX("PP_CT_TEXTURE_CHANNEL_INDEX"),
/**
* Specifies the maximum angle that may be between two face normals
* at the same vertex position that their are smoothed together.<p>
*
* Sometimes referred to as 'crease angle'. This applies to the
* GenSmoothNormals-Step. The angle is specified in degrees, so 180 is PI.
* The default value is 175 degrees (all vertex normals are smoothed). The
* maximum value is 175, too.<p>
*
* Property type: float.<p>
*
* Warning: setting this option may cause a severe loss of performance. The
* performance is unaffected if the {@link #CONFIG_FAVOUR_SPEED} flag is
* set but the output quality may be reduced.
*/
PP_GSN_MAX_SMOOTHING_ANGLE("PP_GSN_MAX_SMOOTHING_ANGLE"),
/**
* Sets the colormap (= palette) to be used to decode embedded textures in
* MDL (Quake or 3DGS) files.<p>
*
* This must be a valid path to a file. The file is 768 (256*3) bytes
* large and contains RGB triplets for each of the 256 palette entries.
* The default value is colormap.lmp. If the file is not found,
* a default palette (from Quake 1) is used.<p>
*
* Property type: string.
*/
IMPORT_MDL_COLORMAP("IMPORT_MDL_COLORMAP"),
/**
* Configures the #aiProcess_RemoveRedundantMaterials step to keep
* materials matching a name in a given list.<p>
*
* This is a list of 1 to n strings, ' ' serves as delimiter character.
* Identifiers containing whitespaces must be enclosed in *single*
* quotation marks. For example:<tt>
* "keep-me and_me_to anotherMaterialToBeKept \'name with whitespace\'"</tt>.
* If a material matches on of these names, it will not be modified or
* removed by the postprocessing step nor will other materials be replaced
* by a reference to it.<p>
*
* This option might be useful if you are using some magic material names
* to pass additional semantics through the content pipeline. This ensures
* they won't be optimized away, but a general optimization is still
* performed for materials not contained in the list.<p>
*
* Property type: String. Default value: n/a<p>
*
* <b>Note:</b>Linefeeds, tabs or carriage returns are treated as
* whitespace. Material names are case sensitive.
*/
PP_RRM_EXCLUDE_LIST("PP_RRM_EXCLUDE_LIST"),
/**
* Configures the {@link AiPostProcessSteps#PRE_TRANSFORM_VERTICES} step
* to keep the scene hierarchy. Meshes are moved to worldspace, but no
* optimization is performed (read: meshes with equal materials are not
* joined. The total number of meshes won't change).<p>
*
* This option could be of use for you if the scene hierarchy contains
* important additional information which you intend to parse.
* For rendering, you can still render all meshes in the scene without
* any transformations.<p>
*
* Property type: bool. Default value: false.
*/
PP_PTV_KEEP_HIERARCHY("PP_PTV_KEEP_HIERARCHY"),
/**
* Configures the {@link AiPostProcessSteps#PRE_TRANSFORM_VERTICES} step
* to normalize all vertex components into the [-1,1] range.<p>
*
* That is, a bounding box for the whole scene is computed, the maximum
* component is taken and all meshes are scaled appropriately (uniformly
* of course!). This might be useful if you don't know the spatial
* dimension of the input data.<p>
*
* Property type: bool. Default value: false.
*/
PP_PTV_NORMALIZE("PP_PTV_NORMALIZE"),
/**
* Configures the {@link AiPostProcessSteps#FIND_DEGENERATES} step to
* remove degenerated primitives from the import - immediately.<p>
*
* The default behaviour converts degenerated triangles to lines and
* degenerated lines to points. See the documentation to the
* {@link AiPostProcessSteps#FIND_DEGENERATES} step for a detailed example
* of the various ways to get rid of these lines and points if you don't
* want them.<p>
*
* Property type: bool. Default value: false.
*/
PP_FD_REMOVE("PP_FD_REMOVE")
// // ---------------------------------------------------------------------------
// /** @brief Configures the #aiProcess_OptimizeGraph step to preserve nodes
// * matching a name in a given list.
// *
// * This is a list of 1 to n strings, ' ' serves as delimiter character.
// * Identifiers containing whitespaces must be enclosed in *single*
// * quotation marks. For example:<tt>
// * "keep-me and_me_to anotherNodeToBeKept \'name with whitespace\'"</tt>.
// * If a node matches on of these names, it will not be modified or
// * removed by the postprocessing step.<br>
// * This option might be useful if you are using some magic node names
// * to pass additional semantics through the content pipeline. This ensures
// * they won't be optimized away, but a general optimization is still
// * performed for nodes not contained in the list.
// * Property type: String. Default value: n/a
// * @note Linefeeds, tabs or carriage returns are treated as whitespace.
// * Node names are case sensitive.
// */
// #define AI_CONFIG_PP_OG_EXCLUDE_LIST \
// "PP_OG_EXCLUDE_LIST"
//
// // ---------------------------------------------------------------------------
// /** @brief Set the maximum number of triangles in a mesh.
// *
// * This is used by the "SplitLargeMeshes" PostProcess-Step to determine
// * whether a mesh must be split or not.
// * @note The default value is AI_SLM_DEFAULT_MAX_TRIANGLES
// * Property type: integer.
// */
// #define AI_CONFIG_PP_SLM_TRIANGLE_LIMIT \
// "PP_SLM_TRIANGLE_LIMIT"
//
// // default value for AI_CONFIG_PP_SLM_TRIANGLE_LIMIT
// #if (!defined AI_SLM_DEFAULT_MAX_TRIANGLES)
// # define AI_SLM_DEFAULT_MAX_TRIANGLES 1000000
// #endif
//
// // ---------------------------------------------------------------------------
// /** @brief Set the maximum number of vertices in a mesh.
// *
// * This is used by the "SplitLargeMeshes" PostProcess-Step to determine
// * whether a mesh must be split or not.
// * @note The default value is AI_SLM_DEFAULT_MAX_VERTICES
// * Property type: integer.
// */
// #define AI_CONFIG_PP_SLM_VERTEX_LIMIT \
// "PP_SLM_VERTEX_LIMIT"
//
// // default value for AI_CONFIG_PP_SLM_VERTEX_LIMIT
// #if (!defined AI_SLM_DEFAULT_MAX_VERTICES)
// # define AI_SLM_DEFAULT_MAX_VERTICES 1000000
// #endif
//
// // ---------------------------------------------------------------------------
// /** @brief Set the maximum number of bones affecting a single vertex
// *
// * This is used by the #aiProcess_LimitBoneWeights PostProcess-Step.
// * @note The default value is AI_LBW_MAX_WEIGHTS
// * Property type: integer.*/
// #define AI_CONFIG_PP_LBW_MAX_WEIGHTS \
// "PP_LBW_MAX_WEIGHTS"
//
// // default value for AI_CONFIG_PP_LBW_MAX_WEIGHTS
// #if (!defined AI_LMW_MAX_WEIGHTS)
// # define AI_LMW_MAX_WEIGHTS 0x4
// #endif // !! AI_LMW_MAX_WEIGHTS
//
// // ---------------------------------------------------------------------------
// /** @brief Lower the deboning threshold in order to remove more bones.
// *
// * This is used by the #aiProcess_Debone PostProcess-Step.
// * @note The default value is AI_DEBONE_THRESHOLD
// * Property type: float.*/
// #define AI_CONFIG_PP_DB_THRESHOLD \
// "PP_DB_THRESHOLD"
//
// // default value for AI_CONFIG_PP_LBW_MAX_WEIGHTS
// #if (!defined AI_DEBONE_THRESHOLD)
// # define AI_DEBONE_THRESHOLD 1.0f
// #endif // !! AI_DEBONE_THRESHOLD
//
// // ---------------------------------------------------------------------------
// /** @brief Require all bones qualify for deboning before removing any
// *
// * This is used by the #aiProcess_Debone PostProcess-Step.
// * @note The default value is 0
// * Property type: bool.*/
// #define AI_CONFIG_PP_DB_ALL_OR_NONE \
// "PP_DB_ALL_OR_NONE"
//
// /** @brief Default value for the #AI_CONFIG_PP_ICL_PTCACHE_SIZE property
// */
// #ifndef PP_ICL_PTCACHE_SIZE
// # define PP_ICL_PTCACHE_SIZE 12
// #endif
//
// // ---------------------------------------------------------------------------
// /** @brief Set the size of the post-transform vertex cache to optimize the
// * vertices for. This configures the #aiProcess_ImproveCacheLocality step.
// *
// * The size is given in vertices. Of course you can't know how the vertex
// * format will exactly look like after the import returns, but you can still
// * guess what your meshes will probably have.
// * @note The default value is #PP_ICL_PTCACHE_SIZE. That results in slight
// * performance improvements for most nVidia/AMD cards since 2002.
// * Property type: integer.
// */
// #define AI_CONFIG_PP_ICL_PTCACHE_SIZE "PP_ICL_PTCACHE_SIZE"
//
// // ---------------------------------------------------------------------------
// /** @brief Enumerates components of the aiScene and aiMesh data structures
// * that can be excluded from the import using the #aiPrpcess_RemoveComponent step.
// *
// * See the documentation to #aiProcess_RemoveComponent for more details.
// */
// enum aiComponent
// {
// /** Normal vectors */
// #ifdef SWIG
// aiComponent_NORMALS = 0x2,
// #else
// aiComponent_NORMALS = 0x2u,
// #endif
//
// /** Tangents and bitangents go always together ... */
// #ifdef SWIG
// aiComponent_TANGENTS_AND_BITANGENTS = 0x4,
// #else
// aiComponent_TANGENTS_AND_BITANGENTS = 0x4u,
// #endif
//
// /** ALL color sets
// * Use aiComponent_COLORn(N) to specify the N'th set */
// aiComponent_COLORS = 0x8,
//
// /** ALL texture UV sets
// * aiComponent_TEXCOORDn(N) to specify the N'th set */
// aiComponent_TEXCOORDS = 0x10,
//
// /** Removes all bone weights from all meshes.
// * The scenegraph nodes corresponding to the bones are NOT removed.
// * use the #aiProcess_OptimizeGraph step to do this */
// aiComponent_BONEWEIGHTS = 0x20,
//
// /** Removes all node animations (aiScene::mAnimations).
// * The corresponding scenegraph nodes are NOT removed.
// * use the #aiProcess_OptimizeGraph step to do this */
// aiComponent_ANIMATIONS = 0x40,
//
// /** Removes all embedded textures (aiScene::mTextures) */
// aiComponent_TEXTURES = 0x80,
//
// /** Removes all light sources (aiScene::mLights).
// * The corresponding scenegraph nodes are NOT removed.
// * use the #aiProcess_OptimizeGraph step to do this */
// aiComponent_LIGHTS = 0x100,
//
// /** Removes all light sources (aiScene::mCameras).
// * The corresponding scenegraph nodes are NOT removed.
// * use the #aiProcess_OptimizeGraph step to do this */
// aiComponent_CAMERAS = 0x200,
//
// /** Removes all meshes (aiScene::mMeshes). */
// aiComponent_MESHES = 0x400,
//
// /** Removes all materials. One default material will
// * be generated, so aiScene::mNumMaterials will be 1. */
// aiComponent_MATERIALS = 0x800,
//
//
// /** This value is not used. It is just there to force the
// * compiler to map this enum to a 32 Bit integer. */
// #ifndef SWIG
// _aiComponent_Force32Bit = 0x9fffffff
// #endif
// };
//
// // Remove a specific color channel 'n'
// #define aiComponent_COLORSn(n) (1u << (n+20u))
//
// // Remove a specific UV channel 'n'
// #define aiComponent_TEXCOORDSn(n) (1u << (n+25u))
//
// // ---------------------------------------------------------------------------
// /** @brief Input parameter to the #aiProcess_RemoveComponent step:
// * Specifies the parts of the data structure to be removed.
// *
// * See the documentation to this step for further details. The property
// * is expected to be an integer, a bitwise combination of the
// * #aiComponent flags defined above in this header. The default
// * value is 0. Important: if no valid mesh is remaining after the
// * step has been executed (e.g you thought it was funny to specify ALL
// * of the flags defined above) the import FAILS. Mainly because there is
// * no data to work on anymore ...
// */
// #define AI_CONFIG_PP_RVC_FLAGS \
// "PP_RVC_FLAGS"
//
// // ---------------------------------------------------------------------------
// /** @brief Input parameter to the #aiProcess_SortByPType step:
// * Specifies which primitive types are removed by the step.
// *
// * This is a bitwise combination of the aiPrimitiveType flags.
// * Specifying all of them is illegal, of course. A typical use would
// * be to exclude all line and point meshes from the import. This
// * is an integer property, its default value is 0.
// */
// #define AI_CONFIG_PP_SBP_REMOVE \
// "PP_SBP_REMOVE"
//
// // ---------------------------------------------------------------------------
// /** @brief Input parameter to the #aiProcess_FindInvalidData step:
// * Specifies the floating-point accuracy for animation values. The step
// * checks for animation tracks where all frame values are absolutely equal
// * and removes them. This tweakable controls the epsilon for floating-point
// * comparisons - two keys are considered equal if the invariant
// * abs(n0-n1)>epsilon holds true for all vector respectively quaternion
// * components. The default value is 0.f - comparisons are exact then.
// */
// #define AI_CONFIG_PP_FID_ANIM_ACCURACY \
// "PP_FID_ANIM_ACCURACY"
//
//
// // TransformUVCoords evaluates UV scalings
// #define AI_UVTRAFO_SCALING 0x1
//
// // TransformUVCoords evaluates UV rotations
// #define AI_UVTRAFO_ROTATION 0x2
//
// // TransformUVCoords evaluates UV translation
// #define AI_UVTRAFO_TRANSLATION 0x4
//
// // Everything baked together -> default value
// #define AI_UVTRAFO_ALL (AI_UVTRAFO_SCALING | AI_UVTRAFO_ROTATION | AI_UVTRAFO_TRANSLATION)
//
// // ---------------------------------------------------------------------------
// /** @brief Input parameter to the #aiProcess_TransformUVCoords step:
// * Specifies which UV transformations are evaluated.
// *
// * This is a bitwise combination of the AI_UVTRAFO_XXX flags (integer
// * property, of course). By default all transformations are enabled
// * (AI_UVTRAFO_ALL).
// */
// #define AI_CONFIG_PP_TUV_EVALUATE \
// "PP_TUV_EVALUATE"
//
// // ---------------------------------------------------------------------------
// /** @brief A hint to assimp to favour speed against import quality.
// *
// * Enabling this option may result in faster loading, but it needn't.
// * It represents just a hint to loaders and post-processing steps to use
// * faster code paths, if possible.
// * This property is expected to be an integer, != 0 stands for true.
// * The default value is 0.
// */
// #define AI_CONFIG_FAVOUR_SPEED \
// "FAVOUR_SPEED"
//
//
// // ###########################################################################
// // IMPORTER SETTINGS
// // Various stuff to fine-tune the behaviour of specific importer plugins.
// // ###########################################################################
//
//
// // ---------------------------------------------------------------------------
// /** @brief Set the vertex animation keyframe to be imported
// *
// * ASSIMP does not support vertex keyframes (only bone animation is supported).
// * The library reads only one frame of models with vertex animations.
// * By default this is the first frame.
// * \note The default value is 0. This option applies to all importers.
// * However, it is also possible to override the global setting
// * for a specific loader. You can use the AI_CONFIG_IMPORT_XXX_KEYFRAME
// * options (where XXX is a placeholder for the file format for which you
// * want to override the global setting).
// * Property type: integer.
// */
// #define AI_CONFIG_IMPORT_GLOBAL_KEYFRAME "IMPORT_GLOBAL_KEYFRAME"
//
// #define AI_CONFIG_IMPORT_MD3_KEYFRAME "IMPORT_MD3_KEYFRAME"
// #define AI_CONFIG_IMPORT_MD2_KEYFRAME "IMPORT_MD2_KEYFRAME"
// #define AI_CONFIG_IMPORT_MDL_KEYFRAME "IMPORT_MDL_KEYFRAME"
// #define AI_CONFIG_IMPORT_MDC_KEYFRAME "IMPORT_MDC_KEYFRAME"
// #define AI_CONFIG_IMPORT_SMD_KEYFRAME "IMPORT_SMD_KEYFRAME"
// #define AI_CONFIG_IMPORT_UNREAL_KEYFRAME "IMPORT_UNREAL_KEYFRAME"
//
//
// // ---------------------------------------------------------------------------
// /** @brief Configures the AC loader to collect all surfaces which have the
// * "Backface cull" flag set in separate meshes.
// *
// * Property type: bool. Default value: true.
// */
// #define AI_CONFIG_IMPORT_AC_SEPARATE_BFCULL \
// "IMPORT_AC_SEPARATE_BFCULL"
//
// // ---------------------------------------------------------------------------
// /** @brief Configures whether the AC loader evaluates subdivision surfaces (
// * indicated by the presence of the 'subdiv' attribute in the file). By
// * default, Assimp performs the subdivision using the standard
// * Catmull-Clark algorithm
// *
// * * Property type: bool. Default value: true.
// */
// #define AI_CONFIG_IMPORT_AC_EVAL_SUBDIVISION \
// "IMPORT_AC_EVAL_SUBDIVISION"
//
// // ---------------------------------------------------------------------------
// /** @brief Configures the UNREAL 3D loader to separate faces with different
// * surface flags (e.g. two-sided vs. single-sided).
// *
// * * Property type: bool. Default value: true.
// */
// #define AI_CONFIG_IMPORT_UNREAL_HANDLE_FLAGS \
// "UNREAL_HANDLE_FLAGS"
//
// // ---------------------------------------------------------------------------
// /** @brief Configures the terragen import plugin to compute uv's for
// * terrains, if not given. Furthermore a default texture is assigned.
// *
// * UV coordinates for terrains are so simple to compute that you'll usually
// * want to compute them on your own, if you need them. This option is intended
// * for model viewers which want to offer an easy way to apply textures to
// * terrains.
// * * Property type: bool. Default value: false.
// */
// #define AI_CONFIG_IMPORT_TER_MAKE_UVS \
// "IMPORT_TER_MAKE_UVS"
//
// // ---------------------------------------------------------------------------
// /** @brief Configures the ASE loader to always reconstruct normal vectors
// * basing on the smoothing groups loaded from the file.
// *
// * Some ASE files have carry invalid normals, other don't.
// * * Property type: bool. Default value: true.
// */
// #define AI_CONFIG_IMPORT_ASE_RECONSTRUCT_NORMALS \
// "IMPORT_ASE_RECONSTRUCT_NORMALS"
//
// // ---------------------------------------------------------------------------
// /** @brief Configures the M3D loader to detect and process multi-part
// * Quake player models.
// *
// * These models usually consist of 3 files, lower.md3, upper.md3 and
// * head.md3. If this property is set to true, Assimp will try to load and
// * combine all three files if one of them is loaded.
// * Property type: bool. Default value: true.
// */
// #define AI_CONFIG_IMPORT_MD3_HANDLE_MULTIPART \
// "IMPORT_MD3_HANDLE_MULTIPART"
//
// // ---------------------------------------------------------------------------
// /** @brief Tells the MD3 loader which skin files to load.
// *
// * When loading MD3 files, Assimp checks whether a file
// * <md3_file_name>_<skin_name>.skin is existing. These files are used by
// * Quake III to be able to assign different skins (e.g. red and blue team)
// * to models. 'default', 'red', 'blue' are typical skin names.
// * Property type: String. Default value: "default".
// */
// #define AI_CONFIG_IMPORT_MD3_SKIN_NAME \
// "IMPORT_MD3_SKIN_NAME"
//
// // ---------------------------------------------------------------------------
// /** @brief Specify the Quake 3 shader file to be used for a particular
// * MD3 file. This can also be a search path.
// *
// * By default Assimp's behaviour is as follows: If a MD3 file
// * <tt><any_path>/models/<any_q3_subdir>/<model_name>/<file_name>.md3</tt> is
// * loaded, the library tries to locate the corresponding shader file in
// * <tt><any_path>/scripts/<model_name>.shader</tt>. This property overrides this
// * behaviour. It can either specify a full path to the shader to be loaded
// * or alternatively the path (relative or absolute) to the directory where
// * the shaders for all MD3s to be loaded reside. Assimp attempts to open
// * <tt><dir>/<model_name>.shader</tt> first, <tt><dir>/<file_name>.shader</tt>
// * is the fallback file. Note that <dir> should have a terminal (back)slash.
// * Property type: String. Default value: n/a.
// */
// #define AI_CONFIG_IMPORT_MD3_SHADER_SRC \
// "IMPORT_MD3_SHADER_SRC"
//
// // ---------------------------------------------------------------------------
// /** @brief Configures the LWO loader to load just one layer from the model.
// *
// * LWO files consist of layers and in some cases it could be useful to load
// * only one of them. This property can be either a string - which specifies
// * the name of the layer - or an integer - the index of the layer. If the
// * property is not set the whole LWO model is loaded. Loading fails if the
// * requested layer is not available. The layer index is zero-based and the
// * layer name may not be empty.<br>
// * Property type: Integer. Default value: all layers are loaded.
// */
// #define AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY \
// "IMPORT_LWO_ONE_LAYER_ONLY"
//
// // ---------------------------------------------------------------------------
// /** @brief Configures the MD5 loader to not load the MD5ANIM file for
// * a MD5MESH file automatically.
// *
// * The default strategy is to look for a file with the same name but the
// * MD5ANIM extension in the same directory. If it is found, it is loaded
// * and combined with the MD5MESH file. This configuration option can be
// * used to disable this behaviour.
// *
// * * Property type: bool. Default value: false.
// */
// #define AI_CONFIG_IMPORT_MD5_NO_ANIM_AUTOLOAD \
// "IMPORT_MD5_NO_ANIM_AUTOLOAD"
//
// // ---------------------------------------------------------------------------
// /** @brief Defines the begin of the time range for which the LWS loader
// * evaluates animations and computes aiNodeAnim's.
// *
// * Assimp provides full conversion of LightWave's envelope system, including
// * pre and post conditions. The loader computes linearly subsampled animation
// * chanels with the frame rate given in the LWS file. This property defines
// * the start time. Note: animation channels are only generated if a node
// * has at least one envelope with more tan one key assigned. This property.
// * is given in frames, '0' is the first frame. By default, if this property
// * is not set, the importer takes the animation start from the input LWS
// * file ('FirstFrame' line)<br>
// * Property type: Integer. Default value: taken from file.
// *
// * @see AI_CONFIG_IMPORT_LWS_ANIM_END - end of the imported time range
// */
// #define AI_CONFIG_IMPORT_LWS_ANIM_START \
// "IMPORT_LWS_ANIM_START"
// #define AI_CONFIG_IMPORT_LWS_ANIM_END \
// "IMPORT_LWS_ANIM_END"
//
// // ---------------------------------------------------------------------------
// /** @brief Defines the output frame rate of the IRR loader.
// *
// * IRR animations are difficult to convert for Assimp and there will
// * always be a loss of quality. This setting defines how many keys per second
// * are returned by the converter.<br>
// * Property type: integer. Default value: 100
// */
// #define AI_CONFIG_IMPORT_IRR_ANIM_FPS \
// "IMPORT_IRR_ANIM_FPS"
//
//
// // ---------------------------------------------------------------------------
// /** @brief Ogre Importer will try to load this Materialfile.
// *
// * Ogre Meshes contain only the MaterialName, not the MaterialFile. If there
// * is no material file with the same name as the material, Ogre Importer will
// * try to load this file and search the material in it.
// * <br>
// * Property type: String. Default value: guessed.
// */
// #define AI_CONFIG_IMPORT_OGRE_MATERIAL_FILE "IMPORT_OGRE_MATERIAL_FILE"
//
//
// // ---------------------------------------------------------------------------
// /** @brief Ogre Importer detect the texture usage from its filename
// *
// * Normally, a texture is loaded as a colormap, if no target is specified in the
// * materialfile. Is this switch is enabled, texture names ending with _n, _l, _s
// * are used as normalmaps, lightmaps or specularmaps.
// * <br>
// * Property type: Bool. Default value: false.
// */
// #define AI_CONFIG_IMPORT_OGRE_TEXTURETYPE_FROM_FILENAME "IMPORT_OGRE_TEXTURETYPE_FROM_FILENAME"
//
//
//
// // ---------------------------------------------------------------------------
// /** @brief Specifies whether the IFC loader skips over IfcSpace elements.
// *
// * IfcSpace elements (and their geometric representations) are used to
// * represent, well, free space in a building storey.<br>
// * Property type: Bool. Default value: true.
// */
// #define AI_CONFIG_IMPORT_IFC_SKIP_SPACE_REPRESENTATIONS "IMPORT_IFC_SKIP_SPACE_REPRESENTATIONS"
//
//
// // ---------------------------------------------------------------------------
// /** @brief Specifies whether the IFC loader skips over
// * shape representations of type 'Curve2D'.
// *
// * A lot of files contain both a faceted mesh representation and a outline
// * with a presentation type of 'Curve2D'. Currently Assimp doesn't convert those,
// * so turning this option off just clutters the log with errors.<br>
// * Property type: Bool. Default value: true.
// */
// #define AI_CONFIG_IMPORT_IFC_SKIP_CURVE_REPRESENTATIONS "IMPORT_IFC_SKIP_CURVE_REPRESENTATIONS"
//
// // ---------------------------------------------------------------------------
// /** @brief Specifies whether the IFC loader will use its own, custom triangulation
// * algorithm to triangulate wall and floor meshes.
// *
// * If this property is set to false, walls will be either triangulated by
// * #aiProcess_Triangulate or will be passed through as huge polygons with
// * faked holes (i.e. holes that are connected with the outer boundary using
// * a dummy edge). It is highly recommended to set this property to true
// * if you want triangulated data because #aiProcess_Triangulate is known to
// * have problems with the kind of polygons that the IFC loader spits out for
// * complicated meshes.
// * Property type: Bool. Default value: true.
// */
// #define AI_CONFIG_IMPORT_IFC_CUSTOM_TRIANGULATION "IMPORT_IFC_CUSTOM_TRIANGULATION"
//
;
private AiConfigOptions(String name) {
m_name = name;
}
private final String m_name;
}
| 8,890 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiTextureMapping.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
/**
* Defines how the mapping coords for a texture are generated.<p>
*
* Real-time applications typically require full UV coordinates, so the use of
* the {@link AiPostProcessSteps#GEN_UV_COORDS} step is highly recommended.
* It generates proper UV channels for non-UV mapped objects, as long as an
* accurate description how the mapping should look like (e.g spherical) is
* given.
*/
public enum AiTextureMapping {
/**
* The mapping coordinates are taken from an UV channel.
*
* The #AI_MATKEY_UVWSRC key specifies from which UV channel
* the texture coordinates are to be taken from (remember,
* meshes can have more than one UV channel).
*/
// aiTextureMapping_UV = 0x0,
//
// /** Spherical mapping */
// aiTextureMapping_SPHERE = 0x1,
//
// /** Cylindrical mapping */
// aiTextureMapping_CYLINDER = 0x2,
//
// /** Cubic mapping */
// aiTextureMapping_BOX = 0x3,
//
// /** Planar mapping */
// aiTextureMapping_PLANE = 0x4,
//
// /** Undefined mapping. Have fun. */
// aiTextureMapping_OTHER = 0x5,
}
| 8,891 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiClassLoaderIOSystem.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* IOSystem based on the Java classloader.<p>
*
* This IOSystem allows loading models directly from the
* classpath. No extraction to the file system is
* necessary.
*
* @author Jesper Smith
*
*/
public class AiClassLoaderIOSystem implements AiIOSystem<AiInputStreamIOStream>
{
private final Class<?> clazz;
private final ClassLoader classLoader;
/**
* Construct a new AiClassLoaderIOSystem.<p>
*
* This constructor uses a ClassLoader to resolve
* resources.
*
* @param classLoader classLoader to resolve resources.
*/
public AiClassLoaderIOSystem(ClassLoader classLoader) {
this.clazz = null;
this.classLoader = classLoader;
}
/**
* Construct a new AiClassLoaderIOSystem.<p>
*
* This constructor uses a Class to resolve
* resources.
*
* @param class<?> class to resolve resources.
*/
public AiClassLoaderIOSystem(Class<?> clazz) {
this.clazz = clazz;
this.classLoader = null;
}
@Override
public AiInputStreamIOStream open(String filename, String ioMode) {
try {
InputStream is;
if(clazz != null) {
is = clazz.getResourceAsStream(filename);
}
else if (classLoader != null) {
is = classLoader.getResourceAsStream(filename);
}
else {
System.err.println("[" + getClass().getSimpleName() +
"] No class or classLoader provided to resolve " + filename);
return null;
}
if(is != null) {
return new AiInputStreamIOStream(is);
}
else {
System.err.println("[" + getClass().getSimpleName() +
"] Cannot find " + filename);
return null;
}
}
catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
public void close(AiInputStreamIOStream file) {
}
@Override
public boolean exists(String path)
{
URL url = null;
if(clazz != null) {
url = clazz.getResource(path);
}
else if (classLoader != null) {
url = classLoader.getResource(path);
}
if(url == null)
{
return false;
}
return true;
}
@Override
public char getOsSeparator()
{
return '/';
}
}
| 8,892 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiMetadataEntry.java | package jassimp;
/*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
public class AiMetadataEntry
{
public enum AiMetadataType
{
AI_BOOL, AI_INT32, AI_UINT64, AI_FLOAT, AI_DOUBLE, AI_AISTRING, AI_AIVECTOR3D
}
private AiMetadataType mType;
private Object mData;
public AiMetadataType getMetaDataType()
{
return mType;
}
public Object getData()
{
return mData;
}
public static boolean getAiBoolAsBoolean(AiMetadataEntry metadataEntry)
{
checkTypeBeforeCasting(metadataEntry, AiMetadataType.AI_BOOL);
return (boolean) metadataEntry.mData;
}
public static int getAiInt32AsInteger(AiMetadataEntry metadataEntry)
{
checkTypeBeforeCasting(metadataEntry, AiMetadataType.AI_INT32);
return (int) metadataEntry.mData;
}
public static long getAiUint64AsLong(AiMetadataEntry metadataEntry)
{
checkTypeBeforeCasting(metadataEntry, AiMetadataType.AI_UINT64);
return (long) metadataEntry.mData;
}
public static float getAiFloatAsFloat(AiMetadataEntry metadataEntry)
{
checkTypeBeforeCasting(metadataEntry, AiMetadataType.AI_FLOAT);
return (float) metadataEntry.mData;
}
public static double getAiDoubleAsDouble(AiMetadataEntry metadataEntry)
{
checkTypeBeforeCasting(metadataEntry, AiMetadataType.AI_DOUBLE);
return (double) metadataEntry.mData;
}
public static String getAiStringAsString(AiMetadataEntry metadataEntry)
{
checkTypeBeforeCasting(metadataEntry, AiMetadataType.AI_AISTRING);
return (String) metadataEntry.mData;
}
public static AiVector getAiAiVector3DAsAiVector(AiMetadataEntry metadataEntry)
{
checkTypeBeforeCasting(metadataEntry, AiMetadataType.AI_AIVECTOR3D);
return (AiVector) metadataEntry.mData;
}
private static void checkTypeBeforeCasting(AiMetadataEntry entry, AiMetadataType expectedType)
{
if(entry.mType != expectedType)
{
throw new RuntimeException("Cannot cast entry of type " + entry.mType.name() + " to " + expectedType.name());
}
}
}
| 8,893 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiProgressHandler.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
public interface AiProgressHandler
{
boolean update(float percentage);
}
| 8,894 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiConfig.java | /*
* $Revision$
* $Date$
*/
package jassimp;
/**
* Configuration interface for assimp importer.<p>
*
* This class is work-in-progress
*/
public class AiConfig {
}
| 8,895 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/JassimpLibraryLoader.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
/**
* Library loader for the jassimp library.<p>
*
* The default implementation uses "System.loadLibrary" to
* load the jassimp native library. <p>
*
* Custom implementations should override the loadLibrary()
* function.
*
*/
public class JassimpLibraryLoader
{
/**
* Function to load the native jassimp library.
*
* Called the first time Jassimp.importFile() is
* called.
*/
public void loadLibrary()
{
System.loadLibrary("jassimp");
}
}
| 8,896 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiLightType.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
/**
* List of light types supported by {@link AiLight}.
*/
public enum AiLightType {
/**
* A directional light source.<p>
*
* A directional light has a well-defined direction but is infinitely far
* away. That's quite a good approximation for sun light.
*/
DIRECTIONAL(0x1),
/**
* A point light source.<p>
*
* A point light has a well-defined position in space but no direction -
* it emits light in all directions. A normal bulb is a point light.
*/
POINT(0x2),
/**
* A spot light source.<p>
*
* A spot light emits light in a specific angle. It has a position and a
* direction it is pointing to. A good example for a spot light is a light
* spot in sport arenas.
*/
SPOT(0x3),
/**
* The generic light level of the world, including the bounces of all other
* lightsources. <p>
*
* Typically, there's at most one ambient light in a scene.
* This light type doesn't have a valid position, direction, or
* other properties, just a color.
*/
AMBIENT(0x4);
/**
* Utility method for converting from c/c++ based integer enums to java
* enums.<p>
*
* This method is intended to be used from JNI and my change based on
* implementation needs.
*
* @param rawValue an integer based enum value (as defined by assimp)
* @return the enum value corresponding to rawValue
*/
static AiLightType fromRawValue(int rawValue) {
for (AiLightType type : AiLightType.values()) {
if (type.m_rawValue == rawValue) {
return type;
}
}
throw new IllegalArgumentException("unexptected raw value: " +
rawValue);
}
/**
* Constructor.
*
* @param rawValue maps java enum to c/c++ integer enum values
*/
private AiLightType(int rawValue) {
m_rawValue = rawValue;
}
/**
* The mapped c/c++ integer enum value.
*/
private final int m_rawValue;
}
| 8,897 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiBlendMode.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
/**
* Defines alpha-blend flags.<p>
*
* If you're familiar with OpenGL or D3D, these flags aren't new to you.
* They define *how* the final color value of a pixel is computed, basing
* on the previous color at that pixel and the new color value from the
* material. The blend formula is:
* <br><code>
* SourceColor * SourceBlend + DestColor * DestBlend
* </code><br>
* where <code>DestColor</code> is the previous color in the framebuffer at
* this position and <code>SourceColor</code> is the material color before the
* transparency calculation.
*/
public enum AiBlendMode {
/**
* Default blending.<p>
*
* Formula:
* <code>
* SourceColor*SourceAlpha + DestColor*(1-SourceAlpha)
* </code>
*/
DEFAULT(0x0),
/**
* Additive blending.<p>
*
* Formula:
* <code>
* SourceColor*1 + DestColor*1
* </code>
*/
ADDITIVE(0x1);
/**
* Utility method for converting from c/c++ based integer enums to java
* enums.<p>
*
* This method is intended to be used from JNI and my change based on
* implementation needs.
*
* @param rawValue an integer based enum value (as defined by assimp)
* @return the enum value corresponding to rawValue
*/
static AiBlendMode fromRawValue(int rawValue) {
for (AiBlendMode type : AiBlendMode.values()) {
if (type.m_rawValue == rawValue) {
return type;
}
}
throw new IllegalArgumentException("unexptected raw value: " +
rawValue);
}
/**
* Constructor.
*
* @param rawValue maps java enum to c/c++ integer enum values
*/
private AiBlendMode(int rawValue) {
m_rawValue = rawValue;
}
/**
* The mapped c/c++ integer enum value.
*/
private final int m_rawValue;
}
| 8,898 |
0 | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src | Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/JassimpConfig.java | /*
---------------------------------------------------------------------------
Open Asset Import Library - Java Binding (jassimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package jassimp;
/**
* Global configuration values (limits).
*/
public final class JassimpConfig {
/**
* Maximum number of vertex color sets.
*/
public static final int MAX_NUMBER_COLORSETS = 8;
/**
* Maximum number of texture coordinate sets.
*/
public static final int MAX_NUMBER_TEXCOORDS = 8;
/**
* Pure static class, no accessible constructor.
*/
private JassimpConfig() {
/* nothing to do */
}
}
| 8,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.