use of com.jme3.util.IntMap.Entry in project jmonkeyengine by jMonkeyEngine.
the class MaterialContext method applyMaterial.
/**
* Applies material to a given geometry.
*
* @param geometry
* the geometry
* @param geometriesOMA
* the geometries OMA
* @param userDefinedUVCoordinates
* UV coords defined by user
* @param blenderContext
* the blender context
*/
public void applyMaterial(Geometry geometry, Long geometriesOMA, Map<String, List<Vector2f>> userDefinedUVCoordinates, BlenderContext blenderContext) {
Material material = null;
if (shadeless) {
material = new Material(blenderContext.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md");
if (!transparent) {
diffuseColor.a = 1;
}
material.setColor("Color", diffuseColor);
} else {
material = new Material(blenderContext.getAssetManager(), "Common/MatDefs/Light/Lighting.j3md");
material.setBoolean("UseMaterialColors", Boolean.TRUE);
// setting the colors
if (!transparent) {
diffuseColor.a = 1;
}
material.setColor("Diffuse", diffuseColor);
material.setColor("Specular", specularColor);
material.setFloat("Shininess", shininess);
material.setColor("Ambient", new ColorRGBA(ambientFactor, ambientFactor, ambientFactor, 1f));
}
// applying textures
int textureIndex = 0;
if (loadedTextures != null && loadedTextures.size() > 0) {
if (loadedTextures.size() > TextureHelper.TEXCOORD_TYPES.length) {
LOGGER.log(Level.WARNING, "The blender file has defined more than {0} different textures. JME supports only {0} UV mappings.", TextureHelper.TEXCOORD_TYPES.length);
}
for (CombinedTexture combinedTexture : loadedTextures) {
if (textureIndex < TextureHelper.TEXCOORD_TYPES.length) {
String usedUserUVSet = combinedTexture.flatten(geometry, geometriesOMA, userDefinedUVCoordinates, blenderContext);
this.setTexture(material, combinedTexture.getMappingType(), combinedTexture.getResultTexture());
List<Vector2f> uvs = combinedTexture.getResultUVS();
if (uvs != null && uvs.size() > 0) {
VertexBuffer uvCoordsBuffer = new VertexBuffer(TextureHelper.TEXCOORD_TYPES[textureIndex++]);
uvCoordsBuffer.setupData(Usage.Static, 2, Format.Float, BufferUtils.createFloatBuffer(uvs.toArray(new Vector2f[uvs.size()])));
geometry.getMesh().setBuffer(uvCoordsBuffer);
}
if (usedUserUVSet != null) {
userDefinedUVCoordinates = new HashMap<>(userDefinedUVCoordinates);
userDefinedUVCoordinates.remove(usedUserUVSet);
}
} else {
LOGGER.log(Level.WARNING, "The texture could not be applied because JME only supports up to {0} different UV's.", TextureHelper.TEXCOORD_TYPES.length);
}
}
}
if (userDefinedUVCoordinates != null && userDefinedUVCoordinates.size() > 0) {
LOGGER.fine("Storing unused, user defined UV coordinates sets.");
if (userDefinedUVCoordinates.size() > TextureHelper.TEXCOORD_TYPES.length) {
LOGGER.log(Level.WARNING, "The blender file has defined more than {0} different UV coordinates for the mesh. JME supports only {0} UV coordinates buffers.", TextureHelper.TEXCOORD_TYPES.length);
}
for (Entry<String, List<Vector2f>> entry : userDefinedUVCoordinates.entrySet()) {
if (textureIndex < TextureHelper.TEXCOORD_TYPES.length) {
List<Vector2f> uvs = entry.getValue();
VertexBuffer uvCoordsBuffer = new VertexBuffer(TextureHelper.TEXCOORD_TYPES[textureIndex++]);
uvCoordsBuffer.setupData(Usage.Static, 2, Format.Float, BufferUtils.createFloatBuffer(uvs.toArray(new Vector2f[uvs.size()])));
geometry.getMesh().setBuffer(uvCoordsBuffer);
} else {
LOGGER.log(Level.WARNING, "The user's UV set named: '{0}' could not be stored because JME only supports up to {1} different UV's.", new Object[] { entry.getKey(), TextureHelper.TEXCOORD_TYPES.length });
}
}
}
// applying additional data
material.setName(name);
if (vertexColor) {
material.setBoolean(shadeless ? "VertexColor" : "UseVertexColor", true);
}
material.getAdditionalRenderState().setFaceCullMode(faceCullMode != null ? faceCullMode : blenderContext.getBlenderKey().getFaceCullMode());
if (transparent) {
material.setTransparent(true);
material.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
geometry.setQueueBucket(Bucket.Transparent);
}
geometry.setMaterial(material);
}
use of com.jme3.util.IntMap.Entry in project jmonkeyengine by jMonkeyEngine.
the class TestCustomAnim method simpleInitApp.
@Override
public void simpleInitApp() {
AmbientLight al = new AmbientLight();
rootNode.addLight(al);
DirectionalLight dl = new DirectionalLight();
dl.setDirection(Vector3f.UNIT_XYZ.negate());
rootNode.addLight(dl);
Box box = new Box(1, 1, 1);
VertexBuffer weightsHW = new VertexBuffer(Type.HWBoneWeight);
VertexBuffer indicesHW = new VertexBuffer(Type.HWBoneIndex);
indicesHW.setUsage(Usage.CpuOnly);
weightsHW.setUsage(Usage.CpuOnly);
box.setBuffer(weightsHW);
box.setBuffer(indicesHW);
// Setup bone weight buffer
FloatBuffer weights = FloatBuffer.allocate(box.getVertexCount() * 4);
VertexBuffer weightsBuf = new VertexBuffer(Type.BoneWeight);
weightsBuf.setupData(Usage.CpuOnly, 4, Format.Float, weights);
box.setBuffer(weightsBuf);
// Setup bone index buffer
ByteBuffer indices = ByteBuffer.allocate(box.getVertexCount() * 4);
VertexBuffer indicesBuf = new VertexBuffer(Type.BoneIndex);
indicesBuf.setupData(Usage.CpuOnly, 4, Format.UnsignedByte, indices);
box.setBuffer(indicesBuf);
// Create bind pose buffers
box.generateBindPose(true);
// Create skeleton
bone = new Bone("root");
bone.setBindTransforms(Vector3f.ZERO, Quaternion.IDENTITY, Vector3f.UNIT_XYZ);
bone.setUserControl(true);
skeleton = new Skeleton(new Bone[] { bone });
// Assign all verticies to bone 0 with weight 1
for (int i = 0; i < box.getVertexCount() * 4; i += 4) {
// assign vertex to bone index 0
indices.array()[i + 0] = 0;
indices.array()[i + 1] = 0;
indices.array()[i + 2] = 0;
indices.array()[i + 3] = 0;
// set weight to 1 only for first entry
weights.array()[i + 0] = 1;
weights.array()[i + 1] = 0;
weights.array()[i + 2] = 0;
weights.array()[i + 3] = 0;
}
// Maximum number of weights per bone is 1
box.setMaxNumWeights(1);
// Create model
Geometry geom = new Geometry("box", box);
geom.setMaterial(assetManager.loadMaterial("Textures/Terrain/BrickWall/BrickWall.j3m"));
Node model = new Node("model");
model.attachChild(geom);
// Create skeleton control
SkeletonControl skeletonControl = new SkeletonControl(skeleton);
model.addControl(skeletonControl);
rootNode.attachChild(model);
}
use of com.jme3.util.IntMap.Entry in project jmonkeyengine by jMonkeyEngine.
the class TestAndroidSensors method simpleUpdate.
@Override
public void simpleUpdate(float tpf) {
if (!initialCalibrationComplete) {
// is a sensor joystick axis
for (IntMap.Entry<Joystick> entry : joystickMap) {
for (JoystickAxis axis : entry.getValue().getAxes()) {
if (axis instanceof SensorJoystickAxis) {
logger.log(Level.INFO, "Calibrating Axis: {0}", axis.toString());
((SensorJoystickAxis) axis).calibrateCenter();
}
}
}
initialCalibrationComplete = true;
}
if (enableGeometryRotation) {
rotationQuat.fromAngles(anglesCurrent);
rotationQuat.normalizeLocal();
if (useAbsolute) {
geomZero.setLocalRotation(rotationQuat);
} else {
geomZero.rotate(rotationQuat);
}
anglesCurrent[0] = anglesCurrent[1] = anglesCurrent[2] = 0f;
}
}
use of com.jme3.util.IntMap.Entry in project jmonkeyengine by jMonkeyEngine.
the class Material method read.
public void read(JmeImporter im) throws IOException {
InputCapsule ic = im.getCapsule(this);
name = ic.readString("name", null);
additionalState = (RenderState) ic.readSavable("render_state", null);
transparent = ic.readBoolean("is_transparent", false);
// Load the material def
String defName = ic.readString("material_def", null);
HashMap<String, MatParam> params = (HashMap<String, MatParam>) ic.readStringSavableMap("parameters", null);
boolean enableVcolor = false;
boolean separateTexCoord = false;
boolean applyDefaultValues = false;
boolean guessRenderStateApply = false;
int ver = ic.getSavableVersion(Material.class);
if (ver < 1) {
applyDefaultValues = true;
}
if (ver < 2) {
guessRenderStateApply = true;
}
if (im.getFormatVersion() == 0) {
// Enable compatibility with old models
if (defName.equalsIgnoreCase("Common/MatDefs/Misc/VertexColor.j3md")) {
// Using VertexColor, switch to Unshaded and set VertexColor=true
enableVcolor = true;
defName = "Common/MatDefs/Misc/Unshaded.j3md";
} else if (defName.equalsIgnoreCase("Common/MatDefs/Misc/SimpleTextured.j3md") || defName.equalsIgnoreCase("Common/MatDefs/Misc/SolidColor.j3md")) {
// Using SimpleTextured/SolidColor, just switch to Unshaded
defName = "Common/MatDefs/Misc/Unshaded.j3md";
} else if (defName.equalsIgnoreCase("Common/MatDefs/Misc/WireColor.j3md")) {
// Using WireColor, set wireframe renderstate = true and use Unshaded
getAdditionalRenderState().setWireframe(true);
defName = "Common/MatDefs/Misc/Unshaded.j3md";
} else if (defName.equalsIgnoreCase("Common/MatDefs/Misc/Unshaded.j3md")) {
// Uses unshaded, ensure that the proper param is set
MatParam value = params.get("SeperateTexCoord");
if (value != null && ((Boolean) value.getValue()) == true) {
params.remove("SeperateTexCoord");
separateTexCoord = true;
}
}
assert applyDefaultValues && guessRenderStateApply;
}
def = (MaterialDef) im.getAssetManager().loadAsset(new AssetKey(defName));
paramValues = new ListMap<String, MatParam>();
// load the textures and update nextTexUnit
for (Map.Entry<String, MatParam> entry : params.entrySet()) {
MatParam param = entry.getValue();
if (param instanceof MatParamTexture) {
MatParamTexture texVal = (MatParamTexture) param;
// do not add to param values
if (texVal.getTextureValue() == null || texVal.getTextureValue().getImage() == null) {
continue;
}
}
if (im.getFormatVersion() == 0 && param.getName().startsWith("m_")) {
// Ancient version of jME3 ...
param.setName(param.getName().substring(2));
}
if (def.getMaterialParam(param.getName()) == null) {
logger.log(Level.WARNING, "The material parameter is not defined: {0}. Ignoring..", param.getName());
} else {
checkSetParam(param.getVarType(), param.getName());
paramValues.put(param.getName(), param);
}
}
if (applyDefaultValues) {
// not available
for (MatParam param : def.getMaterialParams()) {
if (param.getValue() != null && paramValues.get(param.getName()) == null) {
setParam(param.getName(), param.getVarType(), param.getValue());
}
}
}
if (guessRenderStateApply && additionalState != null) {
// Try to guess values of "apply" render state based on defaults
// if value != default then set apply to true
additionalState.applyPolyOffset = additionalState.offsetEnabled;
additionalState.applyBlendMode = additionalState.blendMode != BlendMode.Off;
additionalState.applyColorWrite = !additionalState.colorWrite;
additionalState.applyCullMode = additionalState.cullMode != FaceCullMode.Back;
additionalState.applyDepthTest = !additionalState.depthTest;
additionalState.applyDepthWrite = !additionalState.depthWrite;
additionalState.applyStencilTest = additionalState.stencilTest;
additionalState.applyWireFrame = additionalState.wireframe;
}
if (enableVcolor) {
setBoolean("VertexColor", true);
}
if (separateTexCoord) {
setBoolean("SeparateTexCoord", true);
}
}
use of com.jme3.util.IntMap.Entry in project jmonkeyengine by jMonkeyEngine.
the class FbxMesh method createGeometries.
private List<Geometry> createGeometries() throws IOException {
Mesh mesh = new Mesh();
mesh.setMode(Mode.Triangles);
// Moreover quads should be triangulated (this increases number of vertices)
if (indices != null) {
iCount = indices.length;
srcVertexCount = vertices.length / 3;
// Indices contains negative numbers to define polygon last index
// Check indices strides to be sure we have triangles or quads
vCount = 0;
// Count number of vertices to be produced
int polyVertCount = 0;
for (int i = 0; i < iCount; ++i) {
int index = indices[i];
polyVertCount++;
if (index < 0) {
if (polyVertCount == 3) {
// A triangle
vCount += 3;
} else if (polyVertCount == 4) {
// A quad produce two triangles
vCount += 6;
} else {
throw new AssetLoadException("Unsupported PolygonVertexIndex stride");
}
polyVertCount = 0;
}
}
// Unroll index array into vertex mapping
vertexMap = new ArrayList<>(vCount);
indexMap = new ArrayList<>(vCount);
polyVertCount = 0;
for (int i = 0; i < iCount; ++i) {
int index = indices[i];
polyVertCount++;
if (index < 0) {
int lastIndex = -(index + 1);
if (polyVertCount == 3) {
vertexMap.add(indices[i - 2]);
vertexMap.add(indices[i - 1]);
vertexMap.add(lastIndex);
indexMap.add(i - 2);
indexMap.add(i - 1);
indexMap.add(i - 0);
} else if (polyVertCount == 4) {
vertexMap.add(indices[i - 3]);
vertexMap.add(indices[i - 2]);
vertexMap.add(indices[i - 1]);
vertexMap.add(indices[i - 3]);
vertexMap.add(indices[i - 1]);
vertexMap.add(lastIndex);
indexMap.add(i - 3);
indexMap.add(i - 2);
indexMap.add(i - 1);
indexMap.add(i - 3);
indexMap.add(i - 1);
indexMap.add(i - 0);
}
polyVertCount = 0;
}
}
// Build reverse vertex mapping
reverseVertexMap = new ArrayList<>(srcVertexCount);
for (int i = 0; i < srcVertexCount; ++i) reverseVertexMap.add(new ArrayList<Integer>());
for (int i = 0; i < vCount; ++i) {
int index = vertexMap.get(i);
reverseVertexMap.get(index).add(i);
}
} else {
// Stub for no vertex indexing (direct mapping)
iCount = vCount = srcVertexCount;
vertexMap = new ArrayList<>(vCount);
indexMap = new ArrayList<>(vCount);
reverseVertexMap = new ArrayList<>(vCount);
for (int i = 0; i < vCount; ++i) {
vertexMap.set(i, i);
indexMap.set(i, i);
List<Integer> l = new ArrayList<Integer>(1);
l.add(i);
reverseVertexMap.add(l);
}
}
if (vertices != null) {
// Unroll vertices data array
FloatBuffer posBuf = BufferUtils.createFloatBuffer(vCount * 3);
mesh.setBuffer(VertexBuffer.Type.Position, 3, posBuf);
int srcCount = vertices.length / 3;
for (int i = 0; i < vCount; ++i) {
int index = vertexMap.get(i);
if (index > srcCount)
throw new AssetLoadException("Invalid vertex mapping. Unexpected lookup vertex " + index + " from " + srcCount);
// XXX Why we should scale by unit size?
float x = (float) vertices[3 * index + 0] / scene.unitSize * scene.xAxis;
float y = (float) vertices[3 * index + 1] / scene.unitSize * scene.yAxis;
float z = (float) vertices[3 * index + 2] / scene.unitSize * scene.zAxis;
posBuf.put(x).put(y).put(z);
}
}
if (normals != null) {
// Unroll normals data array
FloatBuffer normBuf = BufferUtils.createFloatBuffer(vCount * 3);
mesh.setBuffer(VertexBuffer.Type.Normal, 3, normBuf);
List<Integer> mapping = null;
if (normalsMapping.equals("ByVertice"))
mapping = vertexMap;
else if (normalsMapping.equals("ByPolygonVertex"))
mapping = indexMap;
else
throw new IOException("Unknown normals mapping type: " + normalsMapping);
int srcCount = normals.length / 3;
for (int i = 0; i < vCount; ++i) {
int index = mapping.get(i);
if (index > srcCount)
throw new AssetLoadException("Invalid normal mapping. Unexpected lookup normal " + index + " from " + srcCount);
float x = (float) normals[3 * index + 0] * scene.xAxis;
float y = (float) normals[3 * index + 1] * scene.yAxis;
float z = (float) normals[3 * index + 2] * scene.zAxis;
normBuf.put(x).put(y).put(z);
}
}
if (tangents != null) {
// Unroll normals data array
FloatBuffer tanBuf = BufferUtils.createFloatBuffer(vCount * 4);
mesh.setBuffer(VertexBuffer.Type.Tangent, 4, tanBuf);
List<Integer> mapping = null;
if (tangentsMapping.equals("ByVertice"))
mapping = vertexMap;
else if (tangentsMapping.equals("ByPolygonVertex"))
mapping = indexMap;
else
throw new IOException("Unknown tangents mapping type: " + tangentsMapping);
int srcCount = tangents.length / 3;
for (int i = 0; i < vCount; ++i) {
int index = mapping.get(i);
if (index > srcCount)
throw new AssetLoadException("Invalid tangent mapping. Unexpected lookup tangent " + index + " from " + srcCount);
float x = (float) tangents[3 * index + 0] * scene.xAxis;
float y = (float) tangents[3 * index + 1] * scene.yAxis;
float z = (float) tangents[3 * index + 2] * scene.zAxis;
tanBuf.put(x).put(y).put(z).put(-1.0f);
}
}
if (binormals != null) {
// Unroll normals data array
FloatBuffer binormBuf = BufferUtils.createFloatBuffer(vCount * 3);
mesh.setBuffer(VertexBuffer.Type.Binormal, 3, binormBuf);
List<Integer> mapping = null;
if (binormalsMapping.equals("ByVertice"))
mapping = vertexMap;
else if (binormalsMapping.equals("ByPolygonVertex"))
mapping = indexMap;
else
throw new IOException("Unknown binormals mapping type: " + binormalsMapping);
int srcCount = binormals.length / 3;
for (int i = 0; i < vCount; ++i) {
int index = mapping.get(i);
if (index > srcCount)
throw new AssetLoadException("Invalid binormal mapping. Unexpected lookup binormal " + index + " from " + srcCount);
float x = (float) binormals[3 * index + 0] * scene.xAxis;
float y = (float) binormals[3 * index + 1] * scene.yAxis;
float z = (float) binormals[3 * index + 2] * scene.zAxis;
binormBuf.put(x).put(y).put(z);
}
}
for (int uvLayer = 0; uvLayer < uvs.size(); ++uvLayer) {
double[] uv = uvs.get(uvLayer);
int[] uvIndex = uvIndexes.size() > uvLayer ? uvIndexes.get(uvLayer) : null;
List<Integer> unIndexMap = vertexMap;
if (uvIndex != null) {
int uvIndexSrcCount = uvIndex.length;
if (uvIndexSrcCount != iCount)
throw new AssetLoadException("Invalid number of texcoord index data " + uvIndexSrcCount + " expected " + iCount);
// Unroll UV index array
unIndexMap = new ArrayList<>(vCount);
int polyVertCount = 0;
for (int i = 0; i < iCount; ++i) {
int index = indices[i];
polyVertCount++;
if (index < 0) {
if (polyVertCount == 3) {
unIndexMap.add(uvIndex[i - 2]);
unIndexMap.add(uvIndex[i - 1]);
unIndexMap.add(uvIndex[i - 0]);
} else if (polyVertCount == 4) {
unIndexMap.add(uvIndex[i - 3]);
unIndexMap.add(uvIndex[i - 2]);
unIndexMap.add(uvIndex[i - 1]);
unIndexMap.add(uvIndex[i - 3]);
unIndexMap.add(uvIndex[i - 1]);
unIndexMap.add(uvIndex[i - 0]);
}
polyVertCount = 0;
}
}
}
// Unroll UV data array
FloatBuffer tcBuf = BufferUtils.createFloatBuffer(vCount * 2);
VertexBuffer.Type type = VertexBuffer.Type.TexCoord;
switch(uvLayer) {
case 1:
type = VertexBuffer.Type.TexCoord2;
break;
case 2:
type = VertexBuffer.Type.TexCoord3;
break;
case 3:
type = VertexBuffer.Type.TexCoord4;
break;
case 4:
type = VertexBuffer.Type.TexCoord5;
break;
case 5:
type = VertexBuffer.Type.TexCoord6;
break;
case 6:
type = VertexBuffer.Type.TexCoord7;
break;
case 7:
type = VertexBuffer.Type.TexCoord8;
break;
}
mesh.setBuffer(type, 2, tcBuf);
int srcCount = uv.length / 2;
for (int i = 0; i < vCount; ++i) {
int index = unIndexMap.get(i);
if (index > srcCount)
throw new AssetLoadException("Invalid texcoord mapping. Unexpected lookup texcoord " + index + " from " + srcCount);
float u = (index >= 0) ? (float) uv[2 * index + 0] : 0;
float v = (index >= 0) ? (float) uv[2 * index + 1] : 0;
tcBuf.put(u).put(v);
}
}
List<Geometry> geometries = new ArrayList<Geometry>();
if (materialsReference.equals("IndexToDirect") && materialsMapping.equals("ByPolygon")) {
IntMap<List<Integer>> indexBuffers = new IntMap<>();
for (int polygon = 0; polygon < materials.length; ++polygon) {
int material = materials[polygon];
List<Integer> list = indexBuffers.get(material);
if (list == null) {
list = new ArrayList<>();
indexBuffers.put(material, list);
}
list.add(polygon * 3 + 0);
list.add(polygon * 3 + 1);
list.add(polygon * 3 + 2);
}
Iterator<Entry<List<Integer>>> iterator = indexBuffers.iterator();
while (iterator.hasNext()) {
Entry<List<Integer>> e = iterator.next();
int materialId = e.getKey();
List<Integer> indexes = e.getValue();
Mesh newMesh = mesh.clone();
newMesh.setBuffer(VertexBuffer.Type.Index, 3, toArray(indexes.toArray(new Integer[indexes.size()])));
newMesh.setStatic();
newMesh.updateBound();
newMesh.updateCounts();
Geometry geom = new Geometry();
geom.setMesh(newMesh);
geometries.add(geom);
geom.setUserData("FBXMaterial", materialId);
}
} else {
mesh.setStatic();
mesh.updateBound();
mesh.updateCounts();
Geometry geom = new Geometry();
geom.setMesh(mesh);
geometries.add(geom);
}
return geometries;
}
Aggregations