Material.java 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. /*
  2. * Copyright (c) 2009-2012 jMonkeyEngine
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are
  7. * met:
  8. *
  9. * * Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. *
  12. * * Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. *
  16. * * Neither the name of 'jMonkeyEngine' nor the names of its contributors
  17. * may be used to endorse or promote products derived from this software
  18. * without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  22. * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  24. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  25. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  28. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  29. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  30. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. package com.jme3.material;
  33. import com.jme3.asset.AssetKey;
  34. import com.jme3.asset.AssetManager;
  35. import com.jme3.asset.CloneableSmartAsset;
  36. import com.jme3.export.*;
  37. import com.jme3.light.*;
  38. import com.jme3.material.RenderState.BlendMode;
  39. import com.jme3.material.RenderState.FaceCullMode;
  40. import com.jme3.material.TechniqueDef.LightMode;
  41. import com.jme3.material.TechniqueDef.ShadowMode;
  42. import com.jme3.math.*;
  43. import com.jme3.renderer.Caps;
  44. import com.jme3.renderer.RenderManager;
  45. import com.jme3.renderer.Renderer;
  46. import com.jme3.renderer.queue.RenderQueue.Bucket;
  47. import com.jme3.scene.Geometry;
  48. import com.jme3.shader.Shader;
  49. import com.jme3.shader.Uniform;
  50. import com.jme3.shader.VarType;
  51. import com.jme3.texture.Texture;
  52. import com.jme3.util.ListMap;
  53. import com.jme3.util.TempVars;
  54. import java.io.IOException;
  55. import java.util.*;
  56. import java.util.logging.Level;
  57. import java.util.logging.Logger;
  58. /**
  59. * <code>Material</code> describes the rendering style for a given
  60. * {@link Geometry}.
  61. * <p>A material is essentially a list of {@link MatParam parameters},
  62. * those parameters map to uniforms which are defined in a shader.
  63. * Setting the parameters can modify the behavior of a
  64. * shader.
  65. * <p/>
  66. *
  67. * @author Kirill Vainer
  68. */
  69. public class Material implements CloneableSmartAsset, Cloneable, Savable {
  70. // Version #2: Fixed issue with RenderState.apply*** flags not getting exported
  71. public static final int SAVABLE_VERSION = 2;
  72. private static final Logger logger = Logger.getLogger(Material.class.getName());
  73. private static final RenderState additiveLight = new RenderState();
  74. private static final RenderState depthOnly = new RenderState();
  75. private static final Quaternion nullDirLight = new Quaternion(0, -1, 0, -1);
  76. static {
  77. depthOnly.setDepthTest(true);
  78. depthOnly.setDepthWrite(true);
  79. depthOnly.setFaceCullMode(RenderState.FaceCullMode.Back);
  80. depthOnly.setColorWrite(false);
  81. additiveLight.setBlendMode(RenderState.BlendMode.AlphaAdditive);
  82. additiveLight.setDepthWrite(false);
  83. }
  84. private AssetKey key;
  85. private String name;
  86. private MaterialDef def;
  87. private ListMap<String, MatParam> paramValues = new ListMap<String, MatParam>();
  88. private Technique technique;
  89. private HashMap<String, Technique> techniques = new HashMap<String, Technique>();
  90. private int nextTexUnit = 0;
  91. private RenderState additionalState = null;
  92. private RenderState mergedRenderState = new RenderState();
  93. private boolean transparent = false;
  94. private boolean receivesShadows = false;
  95. private int sortingId = -1;
  96. private transient ColorRGBA ambientLightColor = new ColorRGBA(0, 0, 0, 1);
  97. public Material(MaterialDef def) {
  98. if (def == null) {
  99. throw new NullPointerException("Material definition cannot be null");
  100. }
  101. this.def = def;
  102. // Load default values from definition (if any)
  103. for (MatParam param : def.getMaterialParams()) {
  104. if (param.getValue() != null) {
  105. setParam(param.getName(), param.getVarType(), param.getValue());
  106. }
  107. }
  108. }
  109. public Material(AssetManager contentMan, String defName) {
  110. this((MaterialDef) contentMan.loadAsset(new AssetKey(defName)));
  111. }
  112. /**
  113. * Do not use this constructor. Serialization purposes only.
  114. */
  115. public Material() {
  116. }
  117. /**
  118. * Returns the asset key name of the asset from which this material was loaded.
  119. *
  120. * <p>This value will be <code>null</code> unless this material was loaded
  121. * from a .j3m file.
  122. *
  123. * @return Asset key name of the j3m file
  124. */
  125. public String getAssetName() {
  126. return key != null ? key.getName() : null;
  127. }
  128. /**
  129. * @return the name of the material (not the same as the asset name), the returned value can be null
  130. */
  131. public String getName() {
  132. return name;
  133. }
  134. /**
  135. * This method sets the name of the material.
  136. * The name is not the same as the asset name.
  137. * It can be null and there is no guarantee of its uniqness.
  138. * @param name the name of the material
  139. */
  140. public void setName(String name) {
  141. this.name = name;
  142. }
  143. public void setKey(AssetKey key) {
  144. this.key = key;
  145. }
  146. public AssetKey getKey() {
  147. return key;
  148. }
  149. /**
  150. * Returns the sorting ID or sorting index for this material.
  151. *
  152. * <p>The sorting ID is used internally by the system to sort rendering
  153. * of geometries. It sorted to reduce shader switches, if the shaders
  154. * are equal, then it is sorted by textures.
  155. *
  156. * @return The sorting ID used for sorting geometries for rendering.
  157. */
  158. public int getSortId() {
  159. Technique t = getActiveTechnique();
  160. if (sortingId == -1 && t != null && t.getShader() != null) {
  161. int texId = -1;
  162. for (int i = 0; i < paramValues.size(); i++) {
  163. MatParam param = paramValues.getValue(i);
  164. if (param instanceof MatParamTexture) {
  165. MatParamTexture tex = (MatParamTexture) param;
  166. if (tex.getTextureValue() != null && tex.getTextureValue().getImage() != null) {
  167. if (texId == -1) {
  168. texId = 0;
  169. }
  170. texId += tex.getTextureValue().getImage().getId() % 0xff;
  171. }
  172. }
  173. }
  174. sortingId = texId + t.getShader().getId() * 1000;
  175. }
  176. return sortingId;
  177. }
  178. /**
  179. * Clones this material. The result is returned.
  180. */
  181. @Override
  182. public Material clone() {
  183. try {
  184. Material mat = (Material) super.clone();
  185. if (additionalState != null) {
  186. mat.additionalState = additionalState.clone();
  187. }
  188. mat.technique = null;
  189. mat.techniques = new HashMap<String, Technique>();
  190. mat.paramValues = new ListMap<String, MatParam>();
  191. for (int i = 0; i < paramValues.size(); i++) {
  192. Map.Entry<String, MatParam> entry = paramValues.getEntry(i);
  193. mat.paramValues.put(entry.getKey(), entry.getValue().clone());
  194. }
  195. return mat;
  196. } catch (CloneNotSupportedException ex) {
  197. throw new AssertionError(ex);
  198. }
  199. }
  200. /**
  201. * Compares two materials and returns true if they are equal.
  202. * This methods compare definition, parameters, additional render states.
  203. * Since materials are mutable objects, implementing equals() properly is not possible,
  204. * hence the name contentEquals().
  205. *
  206. * @param otherObj the material to compare to this material
  207. * @return true if the materials are equal.
  208. */
  209. public boolean contentEquals(Object otherObj) {
  210. if (!(otherObj instanceof Material)) {
  211. return false;
  212. }
  213. Material other = (Material) otherObj;
  214. // Early exit if the material are the same object
  215. if (this == other) {
  216. return true;
  217. }
  218. // Check material definition
  219. if (this.getMaterialDef() != other.getMaterialDef()) {
  220. return false;
  221. }
  222. // Early exit if the size of the params is different
  223. if (this.paramValues.size() != other.paramValues.size()) {
  224. return false;
  225. }
  226. // Checking technique
  227. if (this.technique != null || other.technique != null) {
  228. // Techniques are considered equal if their names are the same
  229. // E.g. if user chose custom technique for one material but
  230. // uses default technique for other material, the materials
  231. // are not equal.
  232. String thisDefName = this.technique != null ? this.technique.getDef().getName() : "Default";
  233. String otherDefName = other.technique != null ? other.technique.getDef().getName() : "Default";
  234. if (!thisDefName.equals(otherDefName)) {
  235. return false;
  236. }
  237. }
  238. // Comparing parameters
  239. for (String paramKey : paramValues.keySet()) {
  240. MatParam thisParam = this.getParam(paramKey);
  241. MatParam otherParam = other.getParam(paramKey);
  242. // This param does not exist in compared mat
  243. if (otherParam == null) {
  244. return false;
  245. }
  246. if (!otherParam.equals(thisParam)) {
  247. return false;
  248. }
  249. }
  250. // Comparing additional render states
  251. if (additionalState == null) {
  252. if (other.additionalState != null) {
  253. return false;
  254. }
  255. } else {
  256. if (!additionalState.equals(other.additionalState)) {
  257. return false;
  258. }
  259. }
  260. return true;
  261. }
  262. /**
  263. * Works like {@link Object#hashCode() } except it may change together with the material as the material is mutable by definition.
  264. */
  265. public int contentHashCode() {
  266. int hash = 7;
  267. hash = 29 * hash + (this.def != null ? this.def.hashCode() : 0);
  268. hash = 29 * hash + (this.paramValues != null ? this.paramValues.hashCode() : 0);
  269. hash = 29 * hash + (this.technique != null ? this.technique.getDef().getName().hashCode() : 0);
  270. hash = 29 * hash + (this.additionalState != null ? this.additionalState.contentHashCode() : 0);
  271. return hash;
  272. }
  273. /**
  274. * Returns the currently active technique.
  275. * <p>
  276. * The technique is selected automatically by the {@link RenderManager}
  277. * based on system capabilities. Users may select their own
  278. * technique by using
  279. * {@link #selectTechnique(java.lang.String, com.jme3.renderer.RenderManager) }.
  280. *
  281. * @return the currently active technique.
  282. *
  283. * @see #selectTechnique(java.lang.String, com.jme3.renderer.RenderManager)
  284. */
  285. public Technique getActiveTechnique() {
  286. return technique;
  287. }
  288. /**
  289. * Check if the transparent value marker is set on this material.
  290. * @return True if the transparent value marker is set on this material.
  291. * @see #setTransparent(boolean)
  292. */
  293. public boolean isTransparent() {
  294. return transparent;
  295. }
  296. /**
  297. * Set the transparent value marker.
  298. *
  299. * <p>This value is merely a marker, by itself it does nothing.
  300. * Generally model loaders will use this marker to indicate further
  301. * up that the material is transparent and therefore any geometries
  302. * using it should be put into the {@link Bucket#Transparent transparent
  303. * bucket}.
  304. *
  305. * @param transparent the transparent value marker.
  306. */
  307. public void setTransparent(boolean transparent) {
  308. this.transparent = transparent;
  309. }
  310. /**
  311. * Check if the material should receive shadows or not.
  312. *
  313. * @return True if the material should receive shadows.
  314. *
  315. * @see Material#setReceivesShadows(boolean)
  316. */
  317. public boolean isReceivesShadows() {
  318. return receivesShadows;
  319. }
  320. /**
  321. * Set if the material should receive shadows or not.
  322. *
  323. * <p>This value is merely a marker, by itself it does nothing.
  324. * Generally model loaders will use this marker to indicate
  325. * the material should receive shadows and therefore any
  326. * geometries using it should have the {@link ShadowMode#Receive} set
  327. * on them.
  328. *
  329. * @param receivesShadows if the material should receive shadows or not.
  330. */
  331. public void setReceivesShadows(boolean receivesShadows) {
  332. this.receivesShadows = receivesShadows;
  333. }
  334. /**
  335. * Acquire the additional {@link RenderState render state} to apply
  336. * for this material.
  337. *
  338. * <p>The first call to this method will create an additional render
  339. * state which can be modified by the user to apply any render
  340. * states in addition to the ones used by the renderer. Only render
  341. * states which are modified in the additional render state will be applied.
  342. *
  343. * @return The additional render state.
  344. */
  345. public RenderState getAdditionalRenderState() {
  346. if (additionalState == null) {
  347. additionalState = RenderState.ADDITIONAL.clone();
  348. }
  349. return additionalState;
  350. }
  351. /**
  352. * Get the material definition (j3md file info) that <code>this</code>
  353. * material is implementing.
  354. *
  355. * @return the material definition this material implements.
  356. */
  357. public MaterialDef getMaterialDef() {
  358. return def;
  359. }
  360. /**
  361. * Returns the parameter set on this material with the given name,
  362. * returns <code>null</code> if the parameter is not set.
  363. *
  364. * @param name The parameter name to look up.
  365. * @return The MatParam if set, or null if not set.
  366. */
  367. public MatParam getParam(String name) {
  368. return paramValues.get(name);
  369. }
  370. /**
  371. * Returns the texture parameter set on this material with the given name,
  372. * returns <code>null</code> if the parameter is not set.
  373. *
  374. * @param name The parameter name to look up.
  375. * @return The MatParamTexture if set, or null if not set.
  376. */
  377. public MatParamTexture getTextureParam(String name) {
  378. MatParam param = paramValues.get(name);
  379. if (param instanceof MatParamTexture) {
  380. return (MatParamTexture) param;
  381. }
  382. return null;
  383. }
  384. /**
  385. * Returns a collection of all parameters set on this material.
  386. *
  387. * @return a collection of all parameters set on this material.
  388. *
  389. * @see #setParam(java.lang.String, com.jme3.shader.VarType, java.lang.Object)
  390. */
  391. public Collection<MatParam> getParams() {
  392. return paramValues.values();
  393. }
  394. /**
  395. * Check if setting the parameter given the type and name is allowed.
  396. * @param type The type that the "set" function is designed to set
  397. * @param name The name of the parameter
  398. */
  399. private void checkSetParam(VarType type, String name) {
  400. MatParam paramDef = def.getMaterialParam(name);
  401. if (paramDef == null) {
  402. throw new IllegalArgumentException("Material parameter is not defined: " + name);
  403. }
  404. if (type != null && paramDef.getVarType() != type) {
  405. logger.log(Level.WARNING, "Material parameter being set: {0} with "
  406. + "type {1} doesn''t match definition types {2}", new Object[]{name, type.name(), paramDef.getVarType()});
  407. }
  408. }
  409. /**
  410. * Pass a parameter to the material shader.
  411. *
  412. * @param name the name of the parameter defined in the material definition (j3md)
  413. * @param type the type of the parameter {@link VarType}
  414. * @param value the value of the parameter
  415. */
  416. public void setParam(String name, VarType type, Object value) {
  417. checkSetParam(type, name);
  418. if (type.isTextureType()) {
  419. setTextureParam(name, type, (Texture)value);
  420. } else {
  421. MatParam val = getParam(name);
  422. if (val == null) {
  423. MatParam paramDef = def.getMaterialParam(name);
  424. paramValues.put(name, new MatParam(type, name, value, paramDef.getFixedFuncBinding()));
  425. } else {
  426. val.setValue(value);
  427. }
  428. if (technique != null) {
  429. technique.notifyParamChanged(name, type, value);
  430. }
  431. }
  432. }
  433. /**
  434. * Clear a parameter from this material. The parameter must exist
  435. * @param name the name of the parameter to clear
  436. */
  437. public void clearParam(String name) {
  438. checkSetParam(null, name);
  439. MatParam matParam = getParam(name);
  440. if (matParam == null) {
  441. return;
  442. }
  443. paramValues.remove(name);
  444. if (matParam instanceof MatParamTexture) {
  445. int texUnit = ((MatParamTexture) matParam).getUnit();
  446. nextTexUnit--;
  447. for (MatParam param : paramValues.values()) {
  448. if (param instanceof MatParamTexture) {
  449. MatParamTexture texParam = (MatParamTexture) param;
  450. if (texParam.getUnit() > texUnit) {
  451. texParam.setUnit(texParam.getUnit() - 1);
  452. }
  453. }
  454. }
  455. sortingId = -1;
  456. }
  457. if (technique != null) {
  458. technique.notifyParamChanged(name, null, null);
  459. }
  460. }
  461. /**
  462. * Set a texture parameter.
  463. *
  464. * @param name The name of the parameter
  465. * @param type The variable type {@link VarType}
  466. * @param value The texture value of the parameter.
  467. *
  468. * @throws IllegalArgumentException is value is null
  469. */
  470. public void setTextureParam(String name, VarType type, Texture value) {
  471. if (value == null) {
  472. throw new IllegalArgumentException();
  473. }
  474. checkSetParam(type, name);
  475. MatParamTexture val = getTextureParam(name);
  476. if (val == null) {
  477. paramValues.put(name, new MatParamTexture(type, name, value, nextTexUnit++));
  478. } else {
  479. val.setTextureValue(value);
  480. }
  481. if (technique != null) {
  482. technique.notifyParamChanged(name, type, nextTexUnit - 1);
  483. }
  484. // need to recompute sort ID
  485. sortingId = -1;
  486. }
  487. /**
  488. * Pass a texture to the material shader.
  489. *
  490. * @param name the name of the texture defined in the material definition
  491. * (j3md) (for example Texture for Lighting.j3md)
  492. * @param value the Texture object previously loaded by the asset manager
  493. */
  494. public void setTexture(String name, Texture value) {
  495. if (value == null) {
  496. // clear it
  497. clearParam(name);
  498. return;
  499. }
  500. VarType paramType = null;
  501. switch (value.getType()) {
  502. case TwoDimensional:
  503. paramType = VarType.Texture2D;
  504. break;
  505. case TwoDimensionalArray:
  506. paramType = VarType.TextureArray;
  507. break;
  508. case ThreeDimensional:
  509. paramType = VarType.Texture3D;
  510. break;
  511. case CubeMap:
  512. paramType = VarType.TextureCubeMap;
  513. break;
  514. default:
  515. throw new UnsupportedOperationException("Unknown texture type: " + value.getType());
  516. }
  517. setTextureParam(name, paramType, value);
  518. }
  519. /**
  520. * Pass a Matrix4f to the material shader.
  521. *
  522. * @param name the name of the matrix defined in the material definition (j3md)
  523. * @param value the Matrix4f object
  524. */
  525. public void setMatrix4(String name, Matrix4f value) {
  526. setParam(name, VarType.Matrix4, value);
  527. }
  528. /**
  529. * Pass a boolean to the material shader.
  530. *
  531. * @param name the name of the boolean defined in the material definition (j3md)
  532. * @param value the boolean value
  533. */
  534. public void setBoolean(String name, boolean value) {
  535. setParam(name, VarType.Boolean, value);
  536. }
  537. /**
  538. * Pass a float to the material shader.
  539. *
  540. * @param name the name of the float defined in the material definition (j3md)
  541. * @param value the float value
  542. */
  543. public void setFloat(String name, float value) {
  544. setParam(name, VarType.Float, value);
  545. }
  546. /**
  547. * Pass an int to the material shader.
  548. *
  549. * @param name the name of the int defined in the material definition (j3md)
  550. * @param value the int value
  551. */
  552. public void setInt(String name, int value) {
  553. setParam(name, VarType.Int, value);
  554. }
  555. /**
  556. * Pass a Color to the material shader.
  557. *
  558. * @param name the name of the color defined in the material definition (j3md)
  559. * @param value the ColorRGBA value
  560. */
  561. public void setColor(String name, ColorRGBA value) {
  562. setParam(name, VarType.Vector4, value);
  563. }
  564. /**
  565. * Pass a Vector2f to the material shader.
  566. *
  567. * @param name the name of the Vector2f defined in the material definition (j3md)
  568. * @param value the Vector2f value
  569. */
  570. public void setVector2(String name, Vector2f value) {
  571. setParam(name, VarType.Vector2, value);
  572. }
  573. /**
  574. * Pass a Vector3f to the material shader.
  575. *
  576. * @param name the name of the Vector3f defined in the material definition (j3md)
  577. * @param value the Vector3f value
  578. */
  579. public void setVector3(String name, Vector3f value) {
  580. setParam(name, VarType.Vector3, value);
  581. }
  582. /**
  583. * Pass a Vector4f to the material shader.
  584. *
  585. * @param name the name of the Vector4f defined in the material definition (j3md)
  586. * @param value the Vector4f value
  587. */
  588. public void setVector4(String name, Vector4f value) {
  589. setParam(name, VarType.Vector4, value);
  590. }
  591. private ColorRGBA getAmbientColor(LightList lightList) {
  592. ambientLightColor.set(0, 0, 0, 1);
  593. for (int j = 0; j < lightList.size(); j++) {
  594. Light l = lightList.get(j);
  595. if (l instanceof AmbientLight) {
  596. ambientLightColor.addLocal(l.getColor());
  597. }
  598. }
  599. ambientLightColor.a = 1.0f;
  600. return ambientLightColor;
  601. }
  602. /**
  603. * Uploads the lights in the light list as two uniform arrays.<br/><br/> *
  604. * <p>
  605. * <code>uniform vec4 g_LightColor[numLights];</code><br/> //
  606. * g_LightColor.rgb is the diffuse/specular color of the light.<br/> //
  607. * g_Lightcolor.a is the type of light, 0 = Directional, 1 = Point, <br/> //
  608. * 2 = Spot. <br/> <br/>
  609. * <code>uniform vec4 g_LightPosition[numLights];</code><br/> //
  610. * g_LightPosition.xyz is the position of the light (for point lights)<br/>
  611. * // or the direction of the light (for directional lights).<br/> //
  612. * g_LightPosition.w is the inverse radius (1/r) of the light (for
  613. * attenuation) <br/> </p>
  614. */
  615. protected void updateLightListUniforms(Shader shader, Geometry g, int numLights) {
  616. if (numLights == 0) { // this shader does not do lighting, ignore.
  617. return;
  618. }
  619. LightList lightList = g.getWorldLightList();
  620. Uniform lightColor = shader.getUniform("g_LightColor");
  621. Uniform lightPos = shader.getUniform("g_LightPosition");
  622. Uniform lightDir = shader.getUniform("g_LightDirection");
  623. lightColor.setVector4Length(numLights);
  624. lightPos.setVector4Length(numLights);
  625. lightDir.setVector4Length(numLights);
  626. Uniform ambientColor = shader.getUniform("g_AmbientLightColor");
  627. ambientColor.setValue(VarType.Vector4, getAmbientColor(lightList));
  628. int lightIndex = 0;
  629. for (int i = 0; i < numLights; i++) {
  630. if (lightList.size() <= i) {
  631. lightColor.setVector4InArray(0f, 0f, 0f, 0f, lightIndex);
  632. lightPos.setVector4InArray(0f, 0f, 0f, 0f, lightIndex);
  633. } else {
  634. Light l = lightList.get(i);
  635. ColorRGBA color = l.getColor();
  636. lightColor.setVector4InArray(color.getRed(),
  637. color.getGreen(),
  638. color.getBlue(),
  639. l.getType().getId(),
  640. i);
  641. switch (l.getType()) {
  642. case Directional:
  643. DirectionalLight dl = (DirectionalLight) l;
  644. Vector3f dir = dl.getDirection();
  645. lightPos.setVector4InArray(dir.getX(), dir.getY(), dir.getZ(), -1, lightIndex);
  646. break;
  647. case Point:
  648. PointLight pl = (PointLight) l;
  649. Vector3f pos = pl.getPosition();
  650. float invRadius = pl.getInvRadius();
  651. lightPos.setVector4InArray(pos.getX(), pos.getY(), pos.getZ(), invRadius, lightIndex);
  652. break;
  653. case Spot:
  654. SpotLight sl = (SpotLight) l;
  655. Vector3f pos2 = sl.getPosition();
  656. Vector3f dir2 = sl.getDirection();
  657. float invRange = sl.getInvSpotRange();
  658. float spotAngleCos = sl.getPackedAngleCos();
  659. lightPos.setVector4InArray(pos2.getX(), pos2.getY(), pos2.getZ(), invRange, lightIndex);
  660. lightDir.setVector4InArray(dir2.getX(), dir2.getY(), dir2.getZ(), spotAngleCos, lightIndex);
  661. break;
  662. case Ambient:
  663. // skip this light. Does not increase lightIndex
  664. continue;
  665. default:
  666. throw new UnsupportedOperationException("Unknown type of light: " + l.getType());
  667. }
  668. }
  669. lightIndex++;
  670. }
  671. while (lightIndex < numLights) {
  672. lightColor.setVector4InArray(0f, 0f, 0f, 0f, lightIndex);
  673. lightPos.setVector4InArray(0f, 0f, 0f, 0f, lightIndex);
  674. lightIndex++;
  675. }
  676. }
  677. protected void renderMultipassLighting(Shader shader, Geometry g, RenderManager rm) {
  678. Renderer r = rm.getRenderer();
  679. LightList lightList = g.getWorldLightList();
  680. Uniform lightDir = shader.getUniform("g_LightDirection");
  681. Uniform lightColor = shader.getUniform("g_LightColor");
  682. Uniform lightPos = shader.getUniform("g_LightPosition");
  683. Uniform ambientColor = shader.getUniform("g_AmbientLightColor");
  684. boolean isFirstLight = true;
  685. boolean isSecondLight = false;
  686. for (int i = 0; i < lightList.size(); i++) {
  687. Light l = lightList.get(i);
  688. if (l instanceof AmbientLight) {
  689. continue;
  690. }
  691. if (isFirstLight) {
  692. // set ambient color for first light only
  693. ambientColor.setValue(VarType.Vector4, getAmbientColor(lightList));
  694. isFirstLight = false;
  695. isSecondLight = true;
  696. } else if (isSecondLight) {
  697. ambientColor.setValue(VarType.Vector4, ColorRGBA.Black);
  698. // apply additive blending for 2nd and future lights
  699. r.applyRenderState(additiveLight);
  700. isSecondLight = false;
  701. }
  702. TempVars vars = TempVars.get();
  703. Quaternion tmpLightDirection = vars.quat1;
  704. Quaternion tmpLightPosition = vars.quat2;
  705. ColorRGBA tmpLightColor = vars.color;
  706. Vector4f tmpVec = vars.vect4f;
  707. ColorRGBA color = l.getColor();
  708. tmpLightColor.set(color);
  709. tmpLightColor.a = l.getType().getId();
  710. lightColor.setValue(VarType.Vector4, tmpLightColor);
  711. switch (l.getType()) {
  712. case Directional:
  713. DirectionalLight dl = (DirectionalLight) l;
  714. Vector3f dir = dl.getDirection();
  715. tmpLightPosition.set(dir.getX(), dir.getY(), dir.getZ(), -1);
  716. lightPos.setValue(VarType.Vector4, tmpLightPosition);
  717. tmpLightDirection.set(0, 0, 0, 0);
  718. lightDir.setValue(VarType.Vector4, tmpLightDirection);
  719. break;
  720. case Point:
  721. PointLight pl = (PointLight) l;
  722. Vector3f pos = pl.getPosition();
  723. float invRadius = pl.getInvRadius();
  724. tmpLightPosition.set(pos.getX(), pos.getY(), pos.getZ(), invRadius);
  725. lightPos.setValue(VarType.Vector4, tmpLightPosition);
  726. tmpLightDirection.set(0, 0, 0, 0);
  727. lightDir.setValue(VarType.Vector4, tmpLightDirection);
  728. break;
  729. case Spot:
  730. SpotLight sl = (SpotLight) l;
  731. Vector3f pos2 = sl.getPosition();
  732. Vector3f dir2 = sl.getDirection();
  733. float invRange = sl.getInvSpotRange();
  734. float spotAngleCos = sl.getPackedAngleCos();
  735. tmpLightPosition.set(pos2.getX(), pos2.getY(), pos2.getZ(), invRange);
  736. lightPos.setValue(VarType.Vector4, tmpLightPosition);
  737. //We transform the spot directoin in view space here to save 5 varying later in the lighting shader
  738. //one vec4 less and a vec4 that becomes a vec3
  739. //the downside is that spotAngleCos decoding happen now in the frag shader.
  740. tmpVec.set(dir2.getX(), dir2.getY(), dir2.getZ(), 0);
  741. rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec);
  742. tmpLightDirection.set(tmpVec.getX(), tmpVec.getY(), tmpVec.getZ(), spotAngleCos);
  743. lightDir.setValue(VarType.Vector4, tmpLightDirection);
  744. break;
  745. default:
  746. throw new UnsupportedOperationException("Unknown type of light: " + l.getType());
  747. }
  748. vars.release();
  749. r.setShader(shader);
  750. r.renderMesh(g.getMesh(), g.getLodLevel(), 1);
  751. }
  752. if (isFirstLight && lightList.size() > 0) {
  753. // There are only ambient lights in the scene. Render
  754. // a dummy "normal light" so we can see the ambient
  755. ambientColor.setValue(VarType.Vector4, getAmbientColor(lightList));
  756. lightColor.setValue(VarType.Vector4, ColorRGBA.BlackNoAlpha);
  757. lightPos.setValue(VarType.Vector4, nullDirLight);
  758. r.setShader(shader);
  759. r.renderMesh(g.getMesh(), g.getLodLevel(), 1);
  760. }
  761. }
  762. /**
  763. * Select the technique to use for rendering this material.
  764. * <p>
  765. * If <code>name</code> is "Default", then one of the
  766. * {@link MaterialDef#getDefaultTechniques() default techniques}
  767. * on the material will be selected. Otherwise, the named technique
  768. * will be found in the material definition.
  769. * <p>
  770. * Any candidate technique for selection (either default or named)
  771. * must be verified to be compatible with the system, for that, the
  772. * <code>renderManager</code> is queried for capabilities.
  773. *
  774. * @param name The name of the technique to select, pass "Default" to
  775. * select one of the default techniques.
  776. * @param renderManager The {@link RenderManager render manager}
  777. * to query for capabilities.
  778. *
  779. * @throws IllegalArgumentException If "Default" is passed and no default
  780. * techniques are available on the material definition, or if a name
  781. * is passed but there's no technique by that name.
  782. * @throws UnsupportedOperationException If no candidate technique supports
  783. * the system capabilities.
  784. */
  785. public void selectTechnique(String name, RenderManager renderManager) {
  786. // check if already created
  787. Technique tech = techniques.get(name);
  788. // When choosing technique, we choose one that
  789. // supports all the caps.
  790. EnumSet<Caps> rendererCaps = renderManager.getRenderer().getCaps();
  791. if (tech == null) {
  792. if (name.equals("Default")) {
  793. List<TechniqueDef> techDefs = def.getDefaultTechniques();
  794. if (techDefs == null || techDefs.isEmpty()) {
  795. throw new IllegalArgumentException("No default techniques are available on material '" + def.getName() + "'");
  796. }
  797. TechniqueDef lastTech = null;
  798. for (TechniqueDef techDef : techDefs) {
  799. if (rendererCaps.containsAll(techDef.getRequiredCaps())) {
  800. // use the first one that supports all the caps
  801. tech = new Technique(this, techDef);
  802. techniques.put(name, tech);
  803. break;
  804. }
  805. lastTech = techDef;
  806. }
  807. if (tech == null) {
  808. throw new UnsupportedOperationException("No default technique on material '" + def.getName() + "'\n"
  809. + " is supported by the video hardware. The caps "
  810. + lastTech.getRequiredCaps() + " are required.");
  811. }
  812. } else {
  813. // create "special" technique instance
  814. TechniqueDef techDef = def.getTechniqueDef(name);
  815. if (techDef == null) {
  816. throw new IllegalArgumentException("For material " + def.getName() + ", technique not found: " + name);
  817. }
  818. if (!rendererCaps.containsAll(techDef.getRequiredCaps())) {
  819. throw new UnsupportedOperationException("The explicitly chosen technique '" + name + "' on material '" + def.getName() + "'\n"
  820. + "requires caps " + techDef.getRequiredCaps() + " which are not "
  821. + "supported by the video renderer");
  822. }
  823. tech = new Technique(this, techDef);
  824. techniques.put(name, tech);
  825. }
  826. } else if (technique == tech) {
  827. // attempting to switch to an already
  828. // active technique.
  829. return;
  830. }
  831. technique = tech;
  832. tech.makeCurrent(def.getAssetManager(), true, rendererCaps);
  833. // shader was changed
  834. sortingId = -1;
  835. }
  836. private void autoSelectTechnique(RenderManager rm) {
  837. if (technique == null) {
  838. selectTechnique("Default", rm);
  839. } else {
  840. technique.makeCurrent(def.getAssetManager(), false, rm.getRenderer().getCaps());
  841. }
  842. }
  843. /**
  844. * Preloads this material for the given render manager.
  845. * <p>
  846. * Preloading the material can ensure that when the material is first
  847. * used for rendering, there won't be any delay since the material has
  848. * been already been setup for rendering.
  849. *
  850. * @param rm The render manager to preload for
  851. */
  852. public void preload(RenderManager rm) {
  853. autoSelectTechnique(rm);
  854. Renderer r = rm.getRenderer();
  855. TechniqueDef techDef = technique.getDef();
  856. Collection<MatParam> params = paramValues.values();
  857. for (MatParam param : params) {
  858. if (param instanceof MatParamTexture) {
  859. MatParamTexture texParam = (MatParamTexture) param;
  860. r.setTexture(0, texParam.getTextureValue());
  861. } else {
  862. if (!techDef.isUsingShaders()) {
  863. continue;
  864. }
  865. technique.updateUniformParam(param.getName(), param.getVarType(), param.getValue());
  866. }
  867. }
  868. Shader shader = technique.getShader();
  869. if (techDef.isUsingShaders()) {
  870. r.setShader(shader);
  871. }
  872. }
  873. private void clearUniformsSetByCurrent(Shader shader) {
  874. ListMap<String, Uniform> uniforms = shader.getUniformMap();
  875. int size = uniforms.size();
  876. for (int i = 0; i < size; i++) {
  877. Uniform u = uniforms.getValue(i);
  878. u.clearSetByCurrentMaterial();
  879. }
  880. }
  881. private void resetUniformsNotSetByCurrent(Shader shader) {
  882. ListMap<String, Uniform> uniforms = shader.getUniformMap();
  883. int size = uniforms.size();
  884. for (int i = 0; i < size; i++) {
  885. Uniform u = uniforms.getValue(i);
  886. if (!u.isSetByCurrentMaterial()) {
  887. u.clearValue();
  888. }
  889. }
  890. }
  891. /**
  892. * Called by {@link RenderManager} to render the geometry by
  893. * using this material.
  894. *
  895. * @param geom The geometry to render
  896. * @param rm The render manager requesting the rendering
  897. */
  898. public void render(Geometry geom, RenderManager rm) {
  899. autoSelectTechnique(rm);
  900. Renderer r = rm.getRenderer();
  901. TechniqueDef techDef = technique.getDef();
  902. if (techDef.getLightMode() == LightMode.MultiPass
  903. && geom.getWorldLightList().size() == 0) {
  904. return;
  905. }
  906. if (rm.getForcedRenderState() != null) {
  907. r.applyRenderState(rm.getForcedRenderState());
  908. } else {
  909. if (techDef.getRenderState() != null) {
  910. r.applyRenderState(techDef.getRenderState().copyMergedTo(additionalState, mergedRenderState));
  911. } else {
  912. r.applyRenderState(RenderState.DEFAULT.copyMergedTo(additionalState, mergedRenderState));
  913. }
  914. }
  915. // update camera and world matrices
  916. // NOTE: setWorldTransform should have been called already
  917. if (techDef.isUsingShaders()) {
  918. // reset unchanged uniform flag
  919. clearUniformsSetByCurrent(technique.getShader());
  920. rm.updateUniformBindings(technique.getWorldBindUniforms());
  921. }
  922. // setup textures and uniforms
  923. for (int i = 0; i < paramValues.size(); i++) {
  924. MatParam param = paramValues.getValue(i);
  925. param.apply(r, technique);
  926. }
  927. Shader shader = technique.getShader();
  928. // send lighting information, if needed
  929. switch (techDef.getLightMode()) {
  930. case Disable:
  931. r.setLighting(null);
  932. break;
  933. case SinglePass:
  934. updateLightListUniforms(shader, geom, 4);
  935. break;
  936. case FixedPipeline:
  937. r.setLighting(geom.getWorldLightList());
  938. break;
  939. case MultiPass:
  940. // NOTE: Special case!
  941. resetUniformsNotSetByCurrent(shader);
  942. renderMultipassLighting(shader, geom, rm);
  943. // very important, notice the return statement!
  944. return;
  945. }
  946. // upload and bind shader
  947. if (techDef.isUsingShaders()) {
  948. // any unset uniforms will be set to 0
  949. resetUniformsNotSetByCurrent(shader);
  950. r.setShader(shader);
  951. }
  952. r.renderMesh(geom.getMesh(), geom.getLodLevel(), 1);
  953. }
  954. public void write(JmeExporter ex) throws IOException {
  955. OutputCapsule oc = ex.getCapsule(this);
  956. oc.write(def.getAssetName(), "material_def", null);
  957. oc.write(additionalState, "render_state", null);
  958. oc.write(transparent, "is_transparent", false);
  959. oc.writeStringSavableMap(paramValues, "parameters", null);
  960. }
  961. public void read(JmeImporter im) throws IOException {
  962. InputCapsule ic = im.getCapsule(this);
  963. additionalState = (RenderState) ic.readSavable("render_state", null);
  964. transparent = ic.readBoolean("is_transparent", false);
  965. // Load the material def
  966. String defName = ic.readString("material_def", null);
  967. HashMap<String, MatParam> params = (HashMap<String, MatParam>) ic.readStringSavableMap("parameters", null);
  968. boolean enableVcolor = false;
  969. boolean separateTexCoord = false;
  970. boolean applyDefaultValues = false;
  971. boolean guessRenderStateApply = false;
  972. int ver = ic.getSavableVersion(Material.class);
  973. if (ver < 1) {
  974. applyDefaultValues = true;
  975. }
  976. if (ver < 2) {
  977. guessRenderStateApply = true;
  978. }
  979. if (im.getFormatVersion() == 0) {
  980. // Enable compatibility with old models
  981. if (defName.equalsIgnoreCase("Common/MatDefs/Misc/VertexColor.j3md")) {
  982. // Using VertexColor, switch to Unshaded and set VertexColor=true
  983. enableVcolor = true;
  984. defName = "Common/MatDefs/Misc/Unshaded.j3md";
  985. } else if (defName.equalsIgnoreCase("Common/MatDefs/Misc/SimpleTextured.j3md")
  986. || defName.equalsIgnoreCase("Common/MatDefs/Misc/SolidColor.j3md")) {
  987. // Using SimpleTextured/SolidColor, just switch to Unshaded
  988. defName = "Common/MatDefs/Misc/Unshaded.j3md";
  989. } else if (defName.equalsIgnoreCase("Common/MatDefs/Misc/WireColor.j3md")) {
  990. // Using WireColor, set wireframe renderstate = true and use Unshaded
  991. getAdditionalRenderState().setWireframe(true);
  992. defName = "Common/MatDefs/Misc/Unshaded.j3md";
  993. } else if (defName.equalsIgnoreCase("Common/MatDefs/Misc/Unshaded.j3md")) {
  994. // Uses unshaded, ensure that the proper param is set
  995. MatParam value = params.get("SeperateTexCoord");
  996. if (value != null && ((Boolean) value.getValue()) == true) {
  997. params.remove("SeperateTexCoord");
  998. separateTexCoord = true;
  999. }
  1000. }
  1001. assert applyDefaultValues && guessRenderStateApply;
  1002. }
  1003. def = (MaterialDef) im.getAssetManager().loadAsset(new AssetKey(defName));
  1004. paramValues = new ListMap<String, MatParam>();
  1005. // load the textures and update nextTexUnit
  1006. for (Map.Entry<String, MatParam> entry : params.entrySet()) {
  1007. MatParam param = entry.getValue();
  1008. if (param instanceof MatParamTexture) {
  1009. MatParamTexture texVal = (MatParamTexture) param;
  1010. if (nextTexUnit < texVal.getUnit() + 1) {
  1011. nextTexUnit = texVal.getUnit() + 1;
  1012. }
  1013. // the texture failed to load for this param
  1014. // do not add to param values
  1015. if (texVal.getTextureValue() == null || texVal.getTextureValue().getImage() == null) {
  1016. continue;
  1017. }
  1018. }
  1019. if (im.getFormatVersion() == 0 && param.getName().startsWith("m_")) {
  1020. // Ancient version of jME3 ...
  1021. param.setName(param.getName().substring(2));
  1022. }
  1023. checkSetParam(param.getVarType(), param.getName());
  1024. paramValues.put(param.getName(), param);
  1025. }
  1026. if (applyDefaultValues) {
  1027. // compatability with old versions where default vars were
  1028. // not available
  1029. for (MatParam param : def.getMaterialParams()) {
  1030. if (param.getValue() != null && paramValues.get(param.getName()) == null) {
  1031. setParam(param.getName(), param.getVarType(), param.getValue());
  1032. }
  1033. }
  1034. }
  1035. if (guessRenderStateApply && additionalState != null) {
  1036. // Try to guess values of "apply" render state based on defaults
  1037. // if value != default then set apply to true
  1038. additionalState.applyPolyOffset = additionalState.offsetEnabled;
  1039. additionalState.applyAlphaFallOff = additionalState.alphaTest;
  1040. additionalState.applyAlphaTest = additionalState.alphaTest;
  1041. additionalState.applyBlendMode = additionalState.blendMode != BlendMode.Off;
  1042. additionalState.applyColorWrite = !additionalState.colorWrite;
  1043. additionalState.applyCullMode = additionalState.cullMode != FaceCullMode.Back;
  1044. additionalState.applyDepthTest = !additionalState.depthTest;
  1045. additionalState.applyDepthWrite = !additionalState.depthWrite;
  1046. additionalState.applyPointSprite = additionalState.pointSprite;
  1047. additionalState.applyStencilTest = additionalState.stencilTest;
  1048. additionalState.applyWireFrame = additionalState.wireframe;
  1049. }
  1050. if (enableVcolor) {
  1051. setBoolean("VertexColor", true);
  1052. }
  1053. if (separateTexCoord) {
  1054. setBoolean("SeparateTexCoord", true);
  1055. }
  1056. }
  1057. }