repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/core/common/AccessToken.java
src/main/java/org/jeewx/api/core/common/AccessToken.java
package org.jeewx.api.core.common; import com.alibaba.fastjson.JSONObject; public class AccessToken { private String appid; private String appscret; public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getAppscret() { return appscret; } public void setAppscret(String appscret) { this.appscret = appscret; } public AccessToken(String appid, String appscret) { this.setAppid(appid); this.setAppscret(appscret); } public String getNewAccessToken() { String token = null; String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET".replace("APPID", this.getAppid()).replace("APPSECRET", this.getAppscret()); JSONObject jsonObject = WxstoreUtils.httpRequest(requestUrl, "GET", null); if (null != jsonObject) { try { token = jsonObject.getString("access_token"); } catch (Exception e) { token = null; } } return token; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/core/common/MyX509TrustManager.java
src/main/java/org/jeewx/api/core/common/MyX509TrustManager.java
package org.jeewx.api.core.common; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; public class MyX509TrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/core/common/JSONHelper.java
src/main/java/org/jeewx/api/core/common/JSONHelper.java
package org.jeewx.api.core.common; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.commons.beanutils.BeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * JSON和JAVA的POJO的相互转换 * @author 张代浩 * JSONHelper.java */ public final class JSONHelper { private static final Logger logger = LoggerFactory.getLogger(JSONHelper.class); // 将POJO转换成JSON public static String bean2json(Object object) { JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(object)); return jsonObject.toString(); } /*** * 将List对象序列化为JSON文本 */ public static <T> String toJSONString(List<T> list) { return JSON.toJSONString(list); } /*** * 将对象序列化为JSON文本 * * @param object * @return */ public static String toJSONString(Object object) { return JSON.toJSONString(object); } /*** * 将JSON对象数组序列化为JSON文本 * * @param jsonArray * @return */ public static String toJSONString(JSONArray jsonArray) { return jsonArray.toString(); } /*** * 将JSON对象序列化为JSON文本 * * @param jsonObject * @return */ public static String toJSONString(JSONObject jsonObject) { return jsonObject.toString(); } /*** * 将对象转换为JSON对象 * * @param object * @return */ public static JSONObject toJSONObject(Object object) { return JSONObject.parseObject(JSON.toJSONString(object)); } /*** * 将对象转换为List<Map<String,Object>> * * @param object * @return */ // 返回非实体类型(Map<String,Object>)的List public static List<Map<String, Object>> toList(Object object) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(object)); for (Object obj : jsonArray) { JSONObject jsonObject = (JSONObject) obj; Map<String, Object> map = new HashMap<String, Object>(); Iterator it = jsonObject.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); Object value = jsonObject.get(key); map.put((String) key, value); } list.add(map); } return list; } /*** * 将JSON对象数组转换为传入类型的List * * @param <T> * @param jsonArray * @param objectClass * @return */ public static <T> List<T> toList(JSONArray jsonArray, Class<T> objectClass) { return jsonArray.toJavaList(objectClass); } /*** * 将对象转换为传入类型的List * * @param <T> * @param jsonArray * @param objectClass * @return */ @SuppressWarnings("unchecked") public static <T> List<T> toList(Object object, Class<T> objectClass) { JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(object)); return jsonArray.toJavaList(objectClass); } /*** * 将JSON对象转换为传入类型的对象 * * @param <T> * @param jsonObject * @param beanClass * @return */ @SuppressWarnings("unchecked") public static <T> T toBean(JSONObject jsonObject, Class<T> beanClass) { return jsonObject.toJavaObject(beanClass); } /*** * 将将对象转换为传入类型的对象 * * @param <T> * @param object * @param beanClass * @return */ public static <T> T toBean(Object object, Class<T> beanClass) { JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(object)); return jsonObject.toJavaObject(beanClass); } /*** * 将JSON文本反序列化为主从关系的实体 * * @param <T> * 泛型T 代表主实体类型 * @param <D> * 泛型D 代表从实体类型 * @param jsonString * JSON文本 * @param mainClass * 主实体类型 * @param detailName * 从实体类在主实体类中的属性名称 * @param detailClass * 从实体类型 * @return */ public static <T, D> T toBean(String jsonString, Class<T> mainClass, String detailName, Class<D> detailClass) { JSONObject jsonObject = JSONObject.parseObject(jsonString); JSONArray jsonArray = (JSONArray) jsonObject.get(detailName); T mainEntity = JSONHelper.toBean(jsonObject, mainClass); List<D> detailList = JSONHelper.toList(jsonArray, detailClass); try { BeanUtils.setProperty(mainEntity, detailName, detailList); } catch (Exception ex) { throw new RuntimeException("主从关系JSON反序列化实体失败!"); } return mainEntity; } /*** * 将JSON文本反序列化为主从关系的实体 * * @param <T>泛型T 代表主实体类型 * @param <D1>泛型D1 代表从实体类型 * @param <D2>泛型D2 代表从实体类型 * @param jsonString * JSON文本 * @param mainClass * 主实体类型 * @param detailName1 * 从实体类在主实体类中的属性 * @param detailClass1 * 从实体类型 * @param detailName2 * 从实体类在主实体类中的属性 * @param detailClass2 * 从实体类型 * @return */ public static <T, D1, D2> T toBean(String jsonString, Class<T> mainClass, String detailName1, Class<D1> detailClass1, String detailName2, Class<D2> detailClass2) { JSONObject jsonObject = JSONObject.parseObject(jsonString); JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1); JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2); T mainEntity = JSONHelper.toBean(jsonObject, mainClass); List<D1> detailList1 = JSONHelper.toList(jsonArray1, detailClass1); List<D2> detailList2 = JSONHelper.toList(jsonArray2, detailClass2); try { BeanUtils.setProperty(mainEntity, detailName1, detailList1); BeanUtils.setProperty(mainEntity, detailName2, detailList2); } catch (Exception ex) { throw new RuntimeException("主从关系JSON反序列化实体失败!"); } return mainEntity; } /*** * 将JSON文本反序列化为主从关系的实体 * * @param <T>泛型T 代表主实体类型 * @param <D1>泛型D1 代表从实体类型 * @param <D2>泛型D2 代表从实体类型 * @param jsonString * JSON文本 * @param mainClass * 主实体类型 * @param detailName1 * 从实体类在主实体类中的属性 * @param detailClass1 * 从实体类型 * @param detailName2 * 从实体类在主实体类中的属性 * @param detailClass2 * 从实体类型 * @param detailName3 * 从实体类在主实体类中的属性 * @param detailClass3 * 从实体类型 * @return */ public static <T, D1, D2, D3> T toBean(String jsonString, Class<T> mainClass, String detailName1, Class<D1> detailClass1, String detailName2, Class<D2> detailClass2, String detailName3, Class<D3> detailClass3) { JSONObject jsonObject = JSONObject.parseObject(jsonString); JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1); JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2); JSONArray jsonArray3 = (JSONArray) jsonObject.get(detailName3); T mainEntity = JSONHelper.toBean(jsonObject, mainClass); List<D1> detailList1 = JSONHelper.toList(jsonArray1, detailClass1); List<D2> detailList2 = JSONHelper.toList(jsonArray2, detailClass2); List<D3> detailList3 = JSONHelper.toList(jsonArray3, detailClass3); try { BeanUtils.setProperty(mainEntity, detailName1, detailList1); BeanUtils.setProperty(mainEntity, detailName2, detailList2); BeanUtils.setProperty(mainEntity, detailName3, detailList3); } catch (Exception ex) { throw new RuntimeException("主从关系JSON反序列化实体失败!"); } return mainEntity; } /*** * 将JSON文本反序列化为主从关系的实体 * * @param <T> * 主实体类型 * @param jsonString * JSON文本 * @param mainClass * 主实体类型 * @param detailClass * 存放了多个从实体在主实体中属性名称和类型 * @return */ public static <T> T toBean(String jsonString, Class<T> mainClass, HashMap<String, Class> detailClass) { JSONObject jsonObject = JSONObject.parseObject(jsonString); T mainEntity = JSONHelper.toBean(jsonObject, mainClass); for (Object key : detailClass.keySet()) { try { Class value = (Class) detailClass.get(key); BeanUtils.setProperty(mainEntity, key.toString(), value); } catch (Exception ex) { throw new RuntimeException("主从关系JSON反序列化实体失败!"); } } return mainEntity; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/core/common/util/StringTemplateLoader.java
src/main/java/org/jeewx/api/core/common/util/StringTemplateLoader.java
package org.jeewx.api.core.common.util; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import freemarker.cache.TemplateLoader; /** * * @author 张代浩 * */ public class StringTemplateLoader implements TemplateLoader { private static final String DEFAULT_TEMPLATE_KEY = "_default_template_key"; private Map templates = new HashMap(); public StringTemplateLoader(String defaultTemplate) { if (defaultTemplate != null && !defaultTemplate.equals("")) { templates.put(DEFAULT_TEMPLATE_KEY, defaultTemplate); } } public void AddTemplate(String name, String template) { if (name == null || template == null || name.equals("") || template.equals("")) { return; } if (!templates.containsKey(name)) { templates.put(name, template); } } public void closeTemplateSource(Object templateSource) throws IOException { } public Object findTemplateSource(String name) throws IOException { if (name == null || name.equals("")) { name = DEFAULT_TEMPLATE_KEY; } return templates.get(name); } public long getLastModified(Object templateSource) { return 0; } public Reader getReader(Object templateSource, String encoding) throws IOException { return new StringReader((String) templateSource); } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/core/common/util/WeixinUtil.java
src/main/java/org/jeewx/api/core/common/util/WeixinUtil.java
package org.jeewx.api.core.common.util; import java.util.HashMap; import java.util.Map; public class WeixinUtil { public static String parseWeiXinHttpUrl(String url,Map<String, Object> paras) { return FreemarkerUtil.parseTemplateContent(url, paras); } public static String parseWeiXinHttpUrl(String url,String access_token) { Map<String,Object> paras = new HashMap<String,Object>(); paras.put("ACCESS_TOKEN", access_token); return FreemarkerUtil.parseTemplateContent(url, paras); } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/core/common/util/FreemarkerUtil.java
src/main/java/org/jeewx/api/core/common/util/FreemarkerUtil.java
package org.jeewx.api.core.common.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Map; import freemarker.core.TemplateClassResolver; import freemarker.template.Configuration; import freemarker.template.Template; import org.jeewx.api.core.common.util.StringTemplateLoader ; /** * * @Title:FreemarkerHelper * @description:Freemarker引擎协助类 * @author 赵俊夫 * @date Jul 5, 2013 2:58:29 PM * @version V1.0 */ public class FreemarkerUtil { private static Configuration _tplConfig = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); public FreemarkerUtil(){ } public FreemarkerUtil(String dir) { try { _tplConfig.setDirectoryForTemplateLoading(new File(dir)); //必须freemarker字段为空,报错 _tplConfig.setClassicCompatible(true); //update-begin-author:scott date:2023-8-15 for: freemarker模板注入问题 禁止解析ObjectConstructor,Execute和freemarker.template.utility.JythonRuntime。 _tplConfig.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER); //update-end-author:scott date:2023-8-15 for: freemarker模板注入问题 禁止解析ObjectConstructor,Execute和freemarker.template.utility.JythonRuntime。 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 解析ftl * * @param tplName * 模板名 * @param encoding * 编码 * @param paras * 参数 * @return */ public String parseTemplate(String tplName, String encoding, Map<String, Object> paras) { try { StringWriter swriter = new StringWriter(); Template mytpl = null; mytpl = _tplConfig.getTemplate(tplName, encoding); mytpl.process(paras, swriter); return swriter.toString(); } catch (Exception e) { e.printStackTrace(); return e.toString(); } } public void genStaticPage(String tplPath, String tplName, Map<String, Object> paras) { Writer out = null; try { out = new OutputStreamWriter(new FileOutputStream(tplName),"UTF-8"); Template mytpl = null; mytpl = _tplConfig.getTemplate(tplPath, "UTF-8"); mytpl.process(paras, out); } catch (Exception e) { e.printStackTrace(); } finally { if (null != out) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } public String parseTemplate(String tplName, Map<String, Object> paras) { return this.parseTemplate(tplName, "utf-8", paras); } /** * 解析ftl * @param tplContent 模板内容 * @param encoding 编码 * @param paras 参数 * @return String 模板解析后内容 */ public String parseTemplateContent(String tplContent, Map<String, Object> paras, String encoding) { Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); //update-begin-author:scott date:2023-8-15 for: freemarker模板注入问题 禁止解析ObjectConstructor,Execute和freemarker.template.utility.JythonRuntime。 cfg.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER); //update-end-author:scott date:2023-8-15 for: freemarker模板注入问题 禁止解析ObjectConstructor,Execute和freemarker.template.utility.JythonRuntime。 StringWriter writer = new StringWriter(); cfg.setTemplateLoader(new StringTemplateLoader(tplContent)); encoding = encoding==null?"UTF-8":encoding; cfg.setDefaultEncoding(encoding); Template template; try { template = cfg.getTemplate(""); template.process(paras, writer); } catch (Exception e) { e.printStackTrace(); } return writer.toString(); } /** * 解析ftl * @param tplContent 模板内容 * @param encoding 编码 * @param paras 参数 * @return String 模板解析后内容 */ public static String parseTemplateContent(String tplContent,Map<String, Object> paras) { Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); StringWriter writer = new StringWriter(); cfg.setTemplateLoader(new StringTemplateLoader(tplContent)); //update-begin-author:scott date:2023-8-15 for: freemarker模板注入问题 禁止解析ObjectConstructor,Execute和freemarker.template.utility.JythonRuntime。 cfg.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER); //update-end-author:scott date:2023-8-15 for: freemarker模板注入问题 禁止解析ObjectConstructor,Execute和freemarker.template.utility.JythonRuntime。 cfg.setDefaultEncoding("UTF-8"); Template template; try { template = cfg.getTemplate(""); template.process(paras, writer); } catch (Exception e) { e.printStackTrace(); } return writer.toString(); } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/core/annotation/ReqType.java
src/main/java/org/jeewx/api/core/annotation/ReqType.java
package org.jeewx.api.core.annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * 微信请求处理类型 * @author sfli.sir * */ @Retention(RetentionPolicy.RUNTIME) public @interface ReqType { public String value() default ""; }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/core/handler/WeiXinReqHandler.java
src/main/java/org/jeewx/api/core/handler/WeiXinReqHandler.java
package org.jeewx.api.core.handler; import org.jeewx.api.core.exception.WexinReqException; import org.jeewx.api.core.req.model.WeixinReqParam; /** * 获取微信接口的信息 * @author liguo * */ public interface WeiXinReqHandler { public String doRequest(WeixinReqParam weixinReqParam) throws WexinReqException; }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/core/handler/impl/WeixinReqLogoUploadHandler.java
src/main/java/org/jeewx/api/core/handler/impl/WeixinReqLogoUploadHandler.java
package org.jeewx.api.core.handler.impl; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.Map; import org.jeewx.api.core.annotation.ReqType; import org.jeewx.api.core.exception.WexinReqException; import org.jeewx.api.core.handler.WeiXinReqHandler; import org.jeewx.api.core.req.model.WeixinReqConfig; import org.jeewx.api.core.req.model.WeixinReqParam; import org.jeewx.api.core.util.HttpRequestProxy; import org.jeewx.api.core.util.WeiXinReqUtil; import org.jeewx.api.coupon.location.model.LocationInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WeixinReqLogoUploadHandler implements WeiXinReqHandler { private static Logger logger = LoggerFactory.getLogger(WeixinReqLogoUploadHandler.class); @SuppressWarnings("rawtypes") public String doRequest(WeixinReqParam weixinReqParam) throws WexinReqException { // TODO Auto-generated method stub String strReturnInfo = ""; if(weixinReqParam instanceof LocationInfo){ LocationInfo uploadMedia = (LocationInfo) weixinReqParam; ReqType reqType = uploadMedia.getClass().getAnnotation(ReqType.class); WeixinReqConfig objConfig = WeiXinReqUtil.getWeixinReqConfig(reqType.value()); if(objConfig != null){ String reqUrl = objConfig.getUrl(); String fileName = uploadMedia.getFilePathName(); File file = new File(fileName) ; InputStream fileIn = null; try { fileIn = new FileInputStream(file); String extName = fileName.substring(fileName.lastIndexOf(".") + 1);//扩展名 String contentType = WeiXinReqUtil.getFileContentType(extName); if(contentType == null){ logger.error("没有找到对应的文件类型"); } Map parameters = WeiXinReqUtil.getWeixinReqParam(weixinReqParam); parameters.remove("filePathName"); strReturnInfo = HttpRequestProxy.uploadMedia(reqUrl, parameters, "UTF-8", fileIn, file.getName(), contentType); } catch (FileNotFoundException e) { // TODO Auto-generated catch block throw new WexinReqException(e); } } }else if(weixinReqParam instanceof LocationInfo){ LocationInfo uploadMedia = (LocationInfo) weixinReqParam; ReqType reqType = uploadMedia.getClass().getAnnotation(ReqType.class); WeixinReqConfig objConfig = WeiXinReqUtil.getWeixinReqConfig(reqType.value()); if(objConfig != null){ String reqUrl = objConfig.getUrl(); String fileName = uploadMedia.getFilePathName(); File file = new File(fileName) ; InputStream fileIn = null; try { fileIn = new FileInputStream(file); String extName = fileName.substring(fileName.lastIndexOf(".") + 1);//扩展名 String contentType = WeiXinReqUtil.getFileContentType(extName); if(contentType == null || !contentType.equals("image/jpeg")){ throw new WexinReqException("上传LOGO 大小限制1MB,像素为300*300,支持JPG格式以达到最佳效果"); } Map parameters = WeiXinReqUtil.getWeixinReqParam(weixinReqParam); parameters.remove("filePathName"); strReturnInfo = HttpRequestProxy.uploadMedia(reqUrl, parameters, "UTF-8", fileIn, file.getName(), contentType); } catch (FileNotFoundException e) { // TODO Auto-generated catch block throw new WexinReqException(e); } } }else{ logger.info("没有找到对应的配置信息"); } return strReturnInfo; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/core/handler/impl/WeixinReqMediaUploadHandler.java
src/main/java/org/jeewx/api/core/handler/impl/WeixinReqMediaUploadHandler.java
package org.jeewx.api.core.handler.impl; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.Map; import org.jeewx.api.core.annotation.ReqType; import org.jeewx.api.core.exception.WexinReqException; import org.jeewx.api.core.handler.WeiXinReqHandler; import org.jeewx.api.core.req.model.UploadMedia; import org.jeewx.api.core.req.model.WeixinReqConfig; import org.jeewx.api.core.req.model.WeixinReqParam; import org.jeewx.api.core.req.model.kfaccount.KfaccountUploadheadimg; import org.jeewx.api.core.util.HttpRequestProxy; import org.jeewx.api.core.util.WeiXinReqUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WeixinReqMediaUploadHandler implements WeiXinReqHandler { private static Logger logger = LoggerFactory.getLogger(WeixinReqMediaUploadHandler.class); @SuppressWarnings("rawtypes") public String doRequest(WeixinReqParam weixinReqParam) throws WexinReqException { // TODO Auto-generated method stub String strReturnInfo = ""; if(weixinReqParam instanceof UploadMedia){ UploadMedia uploadMedia = (UploadMedia) weixinReqParam; ReqType reqType = uploadMedia.getClass().getAnnotation(ReqType.class); WeixinReqConfig objConfig = WeiXinReqUtil.getWeixinReqConfig(reqType.value()); if(objConfig != null){ String reqUrl = objConfig.getUrl(); String fileName = uploadMedia.getFilePathName(); File file = new File(fileName) ; InputStream fileIn = null; try { fileIn = new FileInputStream(file); String extName = fileName.substring(fileName.lastIndexOf(".") + 1);//扩展名 String contentType = WeiXinReqUtil.getFileContentType(extName); if(contentType == null){ logger.error("没有找到对应的文件类型"); } Map parameters = WeiXinReqUtil.getWeixinReqParam(weixinReqParam); parameters.remove("filePathName"); strReturnInfo = HttpRequestProxy.uploadMedia(reqUrl, parameters, "UTF-8", fileIn, file.getName(), contentType); } catch (FileNotFoundException e) { // TODO Auto-generated catch block throw new WexinReqException(e); } } }else if(weixinReqParam instanceof KfaccountUploadheadimg){ KfaccountUploadheadimg uploadMedia = (KfaccountUploadheadimg) weixinReqParam; ReqType reqType = uploadMedia.getClass().getAnnotation(ReqType.class); WeixinReqConfig objConfig = WeiXinReqUtil.getWeixinReqConfig(reqType.value()); if(objConfig != null){ String reqUrl = objConfig.getUrl(); String fileName = uploadMedia.getFilePathName(); File file = new File(fileName) ; InputStream fileIn = null; try { fileIn = new FileInputStream(file); String extName = fileName.substring(fileName.lastIndexOf(".") + 1);//扩展名 String contentType = WeiXinReqUtil.getFileContentType(extName); if(contentType == null || !contentType.equals("image/jpeg")){ throw new WexinReqException("头像图片文件必须是jpg格式,推荐使用640*640大小的图片以达到最佳效果"); } Map parameters = WeiXinReqUtil.getWeixinReqParam(weixinReqParam); parameters.remove("filePathName"); strReturnInfo = HttpRequestProxy.uploadMedia(reqUrl, parameters, "UTF-8", fileIn, file.getName(), contentType); } catch (FileNotFoundException e) { // TODO Auto-generated catch block throw new WexinReqException(e); } } }else{ logger.info("没有找到对应的配置信息"); } return strReturnInfo; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/core/handler/impl/WeixinReqMediaDownHandler.java
src/main/java/org/jeewx/api/core/handler/impl/WeixinReqMediaDownHandler.java
package org.jeewx.api.core.handler.impl; import java.util.Map; import org.jeewx.api.core.annotation.ReqType; import org.jeewx.api.core.exception.WexinReqException; import org.jeewx.api.core.handler.WeiXinReqHandler; import org.jeewx.api.core.req.model.DownloadMedia; import org.jeewx.api.core.req.model.WeixinReqConfig; import org.jeewx.api.core.req.model.WeixinReqParam; import org.jeewx.api.core.util.HttpRequestProxy; import org.jeewx.api.core.util.WeiXinReqUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WeixinReqMediaDownHandler implements WeiXinReqHandler { private static Logger logger = LoggerFactory.getLogger(WeixinReqMediaDownHandler.class); @SuppressWarnings("rawtypes") public String doRequest(WeixinReqParam weixinReqParam) throws WexinReqException { // TODO Auto-generated method stub String strReturnInfo = ""; if(weixinReqParam.getClass().isAnnotationPresent(ReqType.class)){ DownloadMedia downloadMedia = (DownloadMedia) weixinReqParam; ReqType reqType = weixinReqParam.getClass().getAnnotation(ReqType.class); WeixinReqConfig objConfig = WeiXinReqUtil.getWeixinReqConfig(reqType.value()); if(objConfig != null){ String reqUrl = objConfig.getUrl(); String filePath = downloadMedia.getFilePath(); Map parameters = WeiXinReqUtil.getWeixinReqParam(weixinReqParam); parameters.remove("filePathName"); strReturnInfo = HttpRequestProxy.downMadGet(reqUrl, parameters, "UTF-8",filePath,downloadMedia.getMedia_id()); } }else{ logger.info("没有找到对应的配置信息"); } return strReturnInfo; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/core/handler/impl/WeixinReqMenuCreateHandler.java
src/main/java/org/jeewx/api/core/handler/impl/WeixinReqMenuCreateHandler.java
package org.jeewx.api.core.handler.impl; import com.alibaba.fastjson.JSON; import org.jeewx.api.core.annotation.ReqType; import org.jeewx.api.core.exception.WexinReqException; import org.jeewx.api.core.handler.WeiXinReqHandler; import org.jeewx.api.core.req.model.WeixinReqConfig; import org.jeewx.api.core.req.model.WeixinReqParam; import org.jeewx.api.core.req.model.menu.MenuCreate; import org.jeewx.api.core.req.model.menu.WeixinButton; import org.jeewx.api.core.util.HttpRequestProxy; import org.jeewx.api.core.util.WeiXinReqUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 菜单创建的处理 * @author sfli.sir * */ public class WeixinReqMenuCreateHandler implements WeiXinReqHandler { private static Logger logger = LoggerFactory.getLogger(WeixinReqMenuCreateHandler.class); @SuppressWarnings("rawtypes") public String doRequest(WeixinReqParam weixinReqParam) throws WexinReqException{ // TODO Auto-generated method stub String strReturnInfo = ""; if(weixinReqParam.getClass().isAnnotationPresent(ReqType.class)){ ReqType reqType = weixinReqParam.getClass().getAnnotation(ReqType.class); WeixinReqConfig objConfig = WeiXinReqUtil.getWeixinReqConfig(reqType.value()); if(objConfig != null){ String reqUrl = objConfig.getUrl(); MenuCreate mc = (MenuCreate) weixinReqParam; Map<String, String> parameters = new HashMap<String, String>(); parameters.put("access_token", mc.getAccess_token()); String jsonData = "{"+getMenuButtonJson("button",mc.getButton())+"}"; logger.info("处理创建菜单"+jsonData); strReturnInfo = HttpRequestProxy.doJsonPost(reqUrl, parameters, jsonData); } }else{ logger.info("没有找到对应的配置信息"); } return strReturnInfo; } /** * 单独处理菜单 json信息 * @param name * @param b * @return */ private String getMenuButtonJson(String name,List<WeixinButton> b){ StringBuffer json = new StringBuffer(); json.append("\""+name+"\":["); if(b==null || b.size() == 0){ return json.append("]").toString(); } List<WeixinButton> sub_button = null; String objJson = ""; for(WeixinButton m : b){ sub_button = m.getSub_button(); m.setSub_button(null); objJson = JSON.toJSONString(m); json.append(objJson); if(sub_button != null && sub_button.size() > 0){ json.setLength(json.length()-1); json.append(","); objJson = getMenuButtonJson("sub_button",sub_button); json.append(objJson); json.append("}"); } m.setSub_button(sub_button); json.append(","); } json.setLength(json.length()-1); json.append("]"); return json.toString(); } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/core/handler/impl/WeixinReqDefaultHandler.java
src/main/java/org/jeewx/api/core/handler/impl/WeixinReqDefaultHandler.java
package org.jeewx.api.core.handler.impl; import java.util.Map; import org.jeewx.api.core.annotation.ReqType; import org.jeewx.api.core.exception.WexinReqException; import org.jeewx.api.core.handler.WeiXinReqHandler; import org.jeewx.api.core.req.model.WeixinReqConfig; import org.jeewx.api.core.req.model.WeixinReqParam; import org.jeewx.api.core.util.HttpRequestProxy; import org.jeewx.api.core.util.WeiXinConstant; import org.jeewx.api.core.util.WeiXinReqUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WeixinReqDefaultHandler implements WeiXinReqHandler { private static Logger logger = LoggerFactory.getLogger(WeixinReqDefaultHandler.class); @SuppressWarnings("rawtypes") public String doRequest(WeixinReqParam weixinReqParam) throws WexinReqException{ // TODO Auto-generated method stub String strReturnInfo = ""; if(weixinReqParam.getClass().isAnnotationPresent(ReqType.class)){ ReqType reqType = weixinReqParam.getClass().getAnnotation(ReqType.class); WeixinReqConfig objConfig = WeiXinReqUtil.getWeixinReqConfig(reqType.value()); if(objConfig != null){ String reqUrl = objConfig.getUrl(); String method = objConfig.getMethod(); String datatype = objConfig.getDatatype(); Map parameters = WeiXinReqUtil.getWeixinReqParam(weixinReqParam); if(WeiXinConstant.JSON_DATA_TYPE.equalsIgnoreCase(datatype)){ parameters.clear(); parameters.put("access_token", weixinReqParam.getAccess_token()); weixinReqParam.setAccess_token(null); String jsonData = WeiXinReqUtil.getWeixinParamJson(weixinReqParam); strReturnInfo = HttpRequestProxy.doJsonPost(reqUrl, parameters, jsonData); }else{ if(WeiXinConstant.REQUEST_GET.equalsIgnoreCase(method)){ strReturnInfo = HttpRequestProxy.doGet(reqUrl, parameters, "UTF-8"); }else{ strReturnInfo = HttpRequestProxy.doPost(reqUrl, parameters, "UTF-8"); } } } }else{ logger.info("没有找到对应的配置信息"); } return strReturnInfo; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/core/handler/impl/WeixinReqTemplateMessageHandler.java
src/main/java/org/jeewx/api/core/handler/impl/WeixinReqTemplateMessageHandler.java
package org.jeewx.api.core.handler.impl; import com.alibaba.fastjson.JSON; import org.jeewx.api.core.annotation.ReqType; import org.jeewx.api.core.exception.WexinReqException; import org.jeewx.api.core.handler.WeiXinReqHandler; import org.jeewx.api.core.req.model.WeixinReqConfig; import org.jeewx.api.core.req.model.WeixinReqParam; import org.jeewx.api.core.req.model.message.IndustryTemplateMessageSend; import org.jeewx.api.core.req.model.message.TemplateMessage; import org.jeewx.api.core.util.HttpRequestProxy; import org.jeewx.api.core.util.WeiXinReqUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; /** * 模板消息发送 * @author sfli.sir * */ public class WeixinReqTemplateMessageHandler implements WeiXinReqHandler { private static Logger logger = LoggerFactory.getLogger(WeixinReqTemplateMessageHandler.class); @SuppressWarnings("rawtypes") public String doRequest(WeixinReqParam weixinReqParam) throws WexinReqException{ // TODO Auto-generated method stub String strReturnInfo = ""; if(weixinReqParam.getClass().isAnnotationPresent(ReqType.class)){ ReqType reqType = weixinReqParam.getClass().getAnnotation(ReqType.class); WeixinReqConfig objConfig = WeiXinReqUtil.getWeixinReqConfig(reqType.value()); if(objConfig != null){ String reqUrl = objConfig.getUrl(); IndustryTemplateMessageSend mc = (IndustryTemplateMessageSend) weixinReqParam; Map<String, String> parameters = new HashMap<String, String>(); parameters.put("access_token", mc.getAccess_token()); String jsonData = getMsgJson(mc) ; logger.info("处理模板消息"+jsonData); strReturnInfo = HttpRequestProxy.doJsonPost(reqUrl, parameters, jsonData); } }else{ logger.info("没有找到对应的配置信息"); } return strReturnInfo; } /** * 单独处理 json信息 * @param name * @param b * @return */ private String getMsgJson(IndustryTemplateMessageSend mc){ StringBuffer json = new StringBuffer(); TemplateMessage tm = mc.getData(); mc.setData(null); String objJson = JSON.toJSONString(mc); mc.setData(tm); json.append(objJson); json.setLength(json.length()-1); json.append(","); json.append("\"data\":{"); objJson = JSON.toJSONString(tm.getFirst()); json.append(" \"first\":"); json.append(objJson); json.append(","); objJson = JSON.toJSONString(tm.getKeynote1()); json.append(" \"keynote1\":"); json.append(objJson); json.append(","); objJson = JSON.toJSONString(tm.getKeynote2()); json.append(" \"keynote2\":"); json.append(objJson); json.append(","); objJson = JSON.toJSONString(tm.getKeynote3()); json.append(" \"keynote3\":"); json.append(objJson); json.append(","); objJson = JSON.toJSONString(tm.getRemark()); json.append(" \"remark\":"); json.append(objJson); json.append("}}"); return json.toString(); } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/extend/CustomJsonConfig.java
src/main/java/org/jeewx/api/extend/CustomJsonConfig.java
package org.jeewx.api.extend; import com.alibaba.fastjson.serializer.PropertyFilter; import com.alibaba.fastjson.support.config.FastJsonConfig; /** * 过滤不需要转换的属性 * @author luobaoli * */ public class CustomJsonConfig extends FastJsonConfig { @SuppressWarnings("rawtypes") private Class clazz; public CustomJsonConfig(){ } public CustomJsonConfig(Class clazz,final String exclude){ this.clazz = clazz; setSerializeFilters(new PropertyFilter() { public boolean apply(Object arg0, String param, Object arg2) { if(param.equals(exclude))return true; return false; } }); } public CustomJsonConfig(Class clazz,final String[] excludes){ this.clazz = clazz; setSerializeFilters(new PropertyFilter() { public boolean apply(Object arg0, String param, Object arg2) { for(String exclude:excludes){ if(param.equals(exclude))return true; } return false; } }); } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/qrcode/QRCode.java
src/main/java/org/jeewx/api/qrcode/QRCode.java
/** * */ package org.jeewx.api.qrcode; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Hashtable; import java.util.Map; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.EncodeHintType; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.MultiFormatWriter; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; /** * 利用zxing开源工具生成二维码QRCode * * @date 2012-10-26 * @author xhw * */ public class QRCode { private static final int BLACK = 0xff000000; private static final int WHITE = 0xFFFFFFFF; /** * @param args */ public static void main(String[] args) { /** * 在com.google.zxing.MultiFormatWriter类中,定义了一些我们不知道的码,二维码只是其中的一种<br> * public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) throws WriterException { Writer writer; switch (format) { case EAN_8: writer = new EAN8Writer(); break; case EAN_13: writer = new EAN13Writer(); break; case UPC_A: writer = new UPCAWriter(); break; case QR_CODE: writer = new QRCodeWriter(); break; case CODE_39: writer = new Code39Writer(); break; case CODE_128: writer = new Code128Writer(); break; case ITF: writer = new ITFWriter(); break; case PDF_417: writer = new PDF417Writer(); break; case CODABAR: writer = new CodaBarWriter(); break; default: throw new IllegalArgumentException("No encoder available for format " + format); } return writer.encode(contents, format, width, height, hints); } */ String filePostfix="png"; File file = new File("C://test_QR_CODE."+filePostfix); QRCode.encode("http://www.baidu.com", file,filePostfix, BarcodeFormat.QR_CODE, 500, 500, null); QRCode.decode(file); } /** * 生成QRCode二维码<br> * 在编码时需要将com.google.zxing.qrcode.encoder.Encoder.java中的<br> * static final String DEFAULT_BYTE_MODE_ENCODING = "ISO8859-1";<br> * 修改为UTF-8,否则中文编译后解析不了<br> * @param contents 二维码的内容 * @param file 二维码保存的路径,如:C://test_QR_CODE.png * @param filePostfix 生成二维码图片的格式:png,jpeg,gif等格式 * @param format qrcode码的生成格式 * @param width 图片宽度 * @param height 图片高度 * @param hints */ public static void encode(String contents, File file,String filePostfix, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) { try { BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, format, width, height); writeToFile(bitMatrix, filePostfix, file); } catch (Exception e) { e.printStackTrace(); } } /** * 生成二维码图片<br> * * @param matrix * @param format * 图片格式 * @param file * 生成二维码图片位置 * @throws IOException */ public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { BufferedImage image = toBufferedImage(matrix); ImageIO.write(image, format, file); } /** * 生成二维码内容<br> * * @param matrix * @return */ public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE); } } return image; } /** * 解析QRCode二维码 */ @SuppressWarnings("unchecked") public static void decode(File file) { try { BufferedImage image; try { image = ImageIO.read(file); if (image == null) { System.out.println("Could not decode image"); } LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Result result; @SuppressWarnings("rawtypes") Hashtable hints = new Hashtable(); //解码设置编码方式为:utf-8 hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); result = new MultiFormatReader().decode(bitmap, hints); String resultStr = result.getText(); System.out.println("解析后内容:" + resultStr); } catch (IOException ioe) { System.out.println(ioe.toString()); } catch (ReaderException re) { System.out.println(re.toString()); } } catch (Exception ex) { System.out.println(ex.toString()); } } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/JwMessageCommentAPI.java
src/main/java/org/jeewx/api/wxsendmsg/JwMessageCommentAPI.java
package org.jeewx.api.wxsendmsg; import com.alibaba.fastjson.JSONObject; import org.jeewx.api.core.common.WxstoreUtils; import org.jeewx.api.core.exception.WexinReqException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JwMessageCommentAPI { private static Logger logger = LoggerFactory.getLogger(JwMessageCommentAPI.class); /** * 打开评论 */ private static String comment_open_url = "https://api.weixin.qq.com/cgi-bin/comment/open?access_token=ACCESS_TOKEN"; /** * 关闭评论 */ private static String comment_close_url = "https://api.weixin.qq.com/cgi-bin/comment/close?access_token=ACCESS_TOKEN"; /** * 查看指定文章的评论数据 */ private static String comment_list_url = "https://api.weixin.qq.com/cgi-bin/comment/list?access_token=ACCESS_TOKEN"; /** * 将评论标记精选 */ private static String comment_markelect = "https://api.weixin.qq.com/cgi-bin/comment/markelect?access_token=ACCESS_TOKEN"; /** * 将评论取消精选 */ private static String comment_unmarkelect = "https://api.weixin.qq.com/cgi-bin/comment/unmarkelect?access_token=ACCESS_TOKEN"; /** * 删除评论 */ private static String comment_delete = "https://api.weixin.qq.com/cgi-bin/comment/delete?access_token=ACCESS_TOKEN"; /** * 回复评论 */ private static String comment_reply_add = "https://api.weixin.qq.com/cgi-bin/comment/reply/add?access_token=ACCESS_TOKEN"; /** * 删除回复 */ private static String comment_reply_delete = "https://api.weixin.qq.com/cgi-bin/comment/reply/delete?access_token=ACCESS_TOKEN"; /** * 开启评论 * @param accesstoken * @param msg_data_id * @param index * @throws WexinReqException * @return { “errcode”: ERRCODE, “errmsg” : ERRMSG } */ public static JSONObject openComment(String accesstoken,String msg_data_id,int index) throws WexinReqException { if (accesstoken != null) { String requestUrl = comment_open_url.replace("ACCESS_TOKEN", accesstoken); try { JSONObject obj = new JSONObject(); obj.put("msg_data_id", msg_data_id); obj.put("index", index); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); System.out.println("微信返回的结果:" + result.toString()); return result; } catch (Exception e) { throw new WexinReqException(e); } } else { throw new WexinReqException("accesstoken 为空,请检查!"); } } public static JSONObject closeComment(String accesstoken,String msg_data_id,int index) throws WexinReqException { if (accesstoken != null) { String requestUrl = comment_close_url.replace("ACCESS_TOKEN", accesstoken); try { JSONObject obj = new JSONObject(); obj.put("msg_data_id", msg_data_id); obj.put("index", index); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); System.out.println("微信返回的结果:" + result.toString()); return result; } catch (Exception e) { throw new WexinReqException(e); } } else { throw new WexinReqException("accesstoken 为空,请检查!"); } } /** * 查询评论列表 * @param accesstoken * @param params * { “msg_data_id” :"" , “index” : 1, “begin”: , “count”: , “type” : } * <p>参数讲解<br> * msg_data_id:群发返回的msg_data_id<br> * index:多图文时,用来指定第几篇图文,从0开始,不带默认返回该msg_data_id的第一篇图文<br> * begin:起始位置<br> * count:获取数目(>=50会被拒绝)<br> * type:type=0 普通评论&精选评论 type=1 普通评论 type=2 精选评论<br> * * @return * <p>{ <br> * “errcode”: 0, “errmsg” : “ok”, “total”: TOTAL,<br> * “comment”: [{ <br> * user_comment_id : "用户评论id",<br> * aroundopenid :"openid",<br> * aroundcreate_time : "评论时间",<br> * aroundcontent :"评论内容",<br> * aroundcomment_type :"是否精选评论,0为即非精选,1为true",<br> * reply :{ content :"作者回复内容",create_time : "作者回复时间 "} <br> * }] <br> * } * <p>错误返回如下:<br> * <br>{ “errcode” : 45009, “errmsg” : “reach max api daily quota limit” //没有剩余的调用次数 } * <br>{ “errcode” : 88000, “errmsg” : “open comment without comment privilege” //没有留言权限 } * <br>{ “errcode” : 88001, “errmsg” : “msg_data is not exists” //该图文不存在 } * <br>{ “errcode” : 88010, “errmsg” : “count range error. cout <= 0 or count > 50” //获取评论数目不合法 } */ public static JSONObject queuryComments(String accesstoken,JSONObject params) throws WexinReqException { if (accesstoken == null) { throw new WexinReqException("accesstoken 为空,请检查!"); } String requestUrl = comment_list_url.replace("ACCESS_TOKEN", accesstoken); try { JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", params.toString()); logger.info("查看文章的评论数据 结果:" + result.toString()); return result; } catch (Exception e) { throw new WexinReqException(e); } } /** * 将评论标记精选 * @param accesstoken * @param msg_data_id 群发返回的msg_data_id * @param index 多图文时,用来指定第几篇图文,从0开始,不带默认操作该msg_data_id的第一篇图文 * @param user_comment_id 用户评论id * @return * { “errcode”: ERRCODE, “errmsg” : ERRMSG } * <p> * <br>{ “errcode” : 45009, “errmsg” : “reach max api daily quota limit” //没有剩余的调用次数 } * <br>{ “errcode” : 88000, “errmsg” : “open comment without comment privilege” //没有留言权限 } * <br>{ “errcode” : 88001, “errmsg” : “msg_data is not exists” //该图文不存在 } * <br>{ “errcode” : 88003, “errmsg” : “elected comment upper limit” //精选评论数已达上限 } * <br>{ “errcode” : 88004, “errmsg” : “comment was deleted by user” //已被用户删除,无法精选 } * <br>{ “errcode” : 88008, “errmsg” : “comment is not exists” //该评论不存在 } * @throws WexinReqException */ public static JSONObject markelectComment(String accesstoken,String msg_data_id,int index,String user_comment_id) throws WexinReqException { if (accesstoken == null) { throw new WexinReqException("accesstoken 为空,请检查!"); } String requestUrl = comment_markelect.replace("ACCESS_TOKEN", accesstoken); try { JSONObject obj = new JSONObject(); obj.put("msg_data_id", msg_data_id); obj.put("index", index); obj.put("user_comment_id", user_comment_id); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); logger.info("将评论标记精选:" + result.toString()); return result; } catch (Exception e) { throw new WexinReqException(e); } } /** * 将评论取消精选 * @param accesstoken * @param msg_data_id 群发返回的msg_data_id * @param index 多图文时,用来指定第几篇图文,从0开始,不带默认操作该msg_data_id的第一篇图文 * @param user_comment_id 用户评论id * @return * { “errcode”: ERRCODE, “errmsg” : ERRMSG } * <p> * <br>{ “errcode” : 45009, “errmsg” : “reach max api daily quota limit” //没有剩余的调用次数 } * <br>{ “errcode” : 88000, “errmsg” : “open comment without comment privilege” //没有留言权限 } * <br>{ “errcode” : 88001, “errmsg” : “msg_data is not exists” //该图文不存在 } * <br>{ “errcode” : 88008, “errmsg” : “comment is not exists” //该评论不存在 } * @throws WexinReqException */ public static JSONObject unmarkelectComment(String accesstoken,String msg_data_id,int index,String user_comment_id) throws WexinReqException { if (accesstoken == null) { throw new WexinReqException("accesstoken 为空,请检查!"); } String requestUrl = comment_unmarkelect.replace("ACCESS_TOKEN", accesstoken); try { JSONObject obj = new JSONObject(); obj.put("msg_data_id", msg_data_id); obj.put("index", index); obj.put("user_comment_id", user_comment_id); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); logger.info("将评论取消精选:" + result.toString()); return result; } catch (Exception e) { throw new WexinReqException(e); } } /** * 删除评论 * @param accesstoken * @param msg_data_id 群发返回的msg_data_id * @param index 多图文时,用来指定第几篇图文,从0开始,不带默认操作该msg_data_id的第一篇图文 * @param user_comment_id 评论id * @return * { “errcode”: ERRCODE, “errmsg” : ERRMSG } * <p> *<br>{ “errcode” : 45009, “errmsg” : “reach max api daily quota limit” //没有剩余的调用次数 } *<br>{ “errcode” : 88000, “errmsg” : “open comment without comment privilege” //没有留言权限 } *<br>{ “errcode” : 88001, “errmsg” : “msg_data is not exists” //该图文不存在 } *<br>{ “errcode” : 88008, “errmsg” : “comment is not exists” //该评论不存在 } * @throws WexinReqException */ public static JSONObject deleteComment(String accesstoken,String msg_data_id,int index,String user_comment_id) throws WexinReqException { if (accesstoken == null) { throw new WexinReqException("accesstoken 为空,请检查!"); } String requestUrl = comment_delete.replace("ACCESS_TOKEN", accesstoken); try { JSONObject obj = new JSONObject(); obj.put("msg_data_id", msg_data_id); obj.put("index", index); obj.put("user_comment_id", user_comment_id); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); logger.info("删除评论:" + result.toString()); return result; } catch (Exception e) { throw new WexinReqException(e); } } /** * 回复评论 * @param accesstoken * @param msg_data_id 群发返回的msg_data_id * @param index 多图文时,用来指定第几篇图文,从0开始,不带默认操作该msg_data_id的第一篇图文 * @param user_comment_id 评论id * @param content 回复内容 * @return * { “errcode”: ERRCODE, “errmsg” : ERRMSG } * <p> * <br>{ “errcode” : 45009, “errmsg” : “reach max api daily quota limit” //没有剩余的调用次数 } * <br>{ “errcode” : 88000, “errmsg” : “open comment without comment privilege” //没有留言权限 } * <br>{ “errcode” : 88001, “errmsg” : “msg_data is not exists” //该图文不存在 } * <br>{ “errcode” : 88005, “errmsg” : “already reply” //已经回复过了 } * <br>{ “errcode” : 88007, “errmsg” : “reply content beyond max len or content len is zero”//回复超过长度限制或为0 } * <br>{ “errcode” : 88008, “errmsg” : “comment is not exists” //该评论不存在 } * @throws WexinReqException */ public static JSONObject replyComment(String accesstoken,String msg_data_id,int index,String user_comment_id,String content) throws WexinReqException { if (accesstoken == null) { throw new WexinReqException("accesstoken 为空,请检查!"); } String requestUrl = comment_reply_add.replace("ACCESS_TOKEN", accesstoken); try { JSONObject obj = new JSONObject(); obj.put("msg_data_id", msg_data_id); obj.put("index", index); obj.put("user_comment_id", user_comment_id); obj.put("content", content); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); logger.info("回复评论:" + result.toString()); return result; } catch (Exception e) { throw new WexinReqException(e); } } /** * 删除回复 * @param accesstoken * @param msg_data_id 群发返回的msg_data_id * @param index 多图文时,用来指定第几篇图文,从0开始,不带默认操作该msg_data_id的第一篇图文 * @param user_comment_id 评论id * @return * { “errcode”: ERRCODE, “errmsg” : ERRMSG } * <p> *<br> { “errcode” : 45009, “errmsg” : “reach max api daily quota limit” //没有剩余的调用次数 } *<br> { “errcode” : 88000, “errmsg” : “open comment without comment privilege” //没有留言权限 } * <br>{ “errcode” : 88001, “errmsg” : “msg_data is not exists” //该图文不存在 } * <br>{ “errcode” : 88008, “errmsg” : “comment is not exists” //该评论不存在 } *<br> { “errcode” : 87009, “errmsg” : “reply is not exists” //该回复不存在 } * @throws WexinReqException */ public static JSONObject deleteReplyComment(String accesstoken,String msg_data_id,int index,String user_comment_id) throws WexinReqException { if (accesstoken == null) { throw new WexinReqException("accesstoken 为空,请检查!"); } String requestUrl = comment_reply_delete.replace("ACCESS_TOKEN", accesstoken); try { JSONObject obj = new JSONObject(); obj.put("msg_data_id", msg_data_id); obj.put("index", index); obj.put("user_comment_id", user_comment_id); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); logger.info("删除回复:" + result.toString()); return result; } catch (Exception e) { throw new WexinReqException(e); } } public static void main(String[] args) throws WexinReqException { String accesstoken = ""; String msg_data_id = ""; int index = 0; openComment(accesstoken, msg_data_id, index); } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/JwTemplateMessageAPI.java
src/main/java/org/jeewx/api/wxsendmsg/JwTemplateMessageAPI.java
package org.jeewx.api.wxsendmsg; import com.alibaba.fastjson.JSONObject; import org.jeewx.api.core.exception.WexinReqException; import org.jeewx.api.core.req.WeiXinReqService; import org.jeewx.api.core.req.model.message.*; import org.jeewx.api.core.util.WeiXinConstant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 模板消息接口 * * @author lizr * */ public class JwTemplateMessageAPI { private static Logger logger = LoggerFactory .getLogger(JwTemplateMessageAPI.class); /** * 设置行业信息 * @param accessToken * @param industry_id1 * @param industry_id2 * @return * @throws WexinReqException */ public static String setIndustry(String accessToken,String industry_id1,String industry_id2) throws WexinReqException{ IndustryTemplateSet s = new IndustryTemplateSet(); s.setAccess_token(accessToken); s.setIndustry_id1(industry_id1); s.setIndustry_id2(industry_id2); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(s); String msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); return msg; } /** * 添加模板信息 * @param accessToken * @param template_id_short * @return * @throws WexinReqException */ public static String addTemplate(String accessToken,String template_id_short) throws WexinReqException{ IndustryTemplateAdd t = new IndustryTemplateAdd(); t.setAccess_token(accessToken); t.setTemplate_id_short(template_id_short); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(t); String msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); if("ok".equalsIgnoreCase(msg)){ msg = result.getString("template_id"); } return msg; } /** * 发送客服模板消息 * @param industryTemplateMessageSend * @return * @throws WexinReqException */ public static String sendTemplateMsg(IndustryTemplateMessageSend industryTemplateMessageSend) throws WexinReqException{ JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(industryTemplateMessageSend); String msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); return msg; } public static void main(String[] args){ try { String s = "qCU9cEJzhGSJxncRzuxC2Yx5zB4LNysB1_GVTYeRwWtsRydB7c7C6q2WlRFeX7XQg7edLiOQcO5juf0BcMXcWMgR8lEe3qutVMwR88WVCy0"; //JwTokenAPI.getAccessToken("wx00737224cb9dbc7d","b9479ebdb58d1c6b6efd4171ebe718b5"); System.out.println(s); //"qQo8f2B0D0ZnlTP-8TKOMWoDcGiCoAhICn09S_QKxMgpSVp0VG8rgg_8PAJhy893z4lU-kY89DsZAsC3M54zxQBxuwTehg2nC_dO75VEGqw"; //JwTokenAPI.getAccessToken("wx00737224cb9dbc7d","b9479ebdb58d1c6b6efd4171ebe718b5"); IndustryTemplateMessageSend industryTemplateMessageSend = new IndustryTemplateMessageSend(); industryTemplateMessageSend.setAccess_token(s); industryTemplateMessageSend.setTemplate_id("4m3vrpiSA-CPyL9YqHw2jKDlZSX6Sz65SoMKvA9BV1s"); industryTemplateMessageSend.setTouser("oR0jFtxn8q_UsSXsKT395GVaG8q0"); industryTemplateMessageSend.setUrl("www.baidu.com"); industryTemplateMessageSend.setTopcolor("#ffAADD"); TemplateMessage data = new TemplateMessage(); TemplateData first = new TemplateData(); first.setColor("#173177"); first.setValue("恭喜你购买成2323功!"); TemplateData keynote1= new TemplateData(); keynote1.setColor("#173177"); keynote1.setValue("巧克22力"); TemplateData keynote2= new TemplateData(); keynote2.setColor("39.8元"); keynote2.setValue("恭喜你购买成功!"); TemplateData keynote3= new TemplateData(); keynote3.setColor("#173177"); keynote3.setValue("2014年9月16日"); TemplateData remark= new TemplateData(); remark.setColor("#173177"); remark.setValue("欢迎再次购买!"); data.setFirst(first); data.setKeynote1(keynote1); data.setKeynote2(keynote2); data.setKeynote3(keynote3); data.setRemark(remark); industryTemplateMessageSend.setData(data); s = JwTemplateMessageAPI.sendTemplateMsg(industryTemplateMessageSend); System.out.println(s); // 4m3vrpiSA-CPyL9YqHw2jKDlZSX6Sz65SoMKvA9BV1s } catch (WexinReqException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/JwSendMessageAPI.java
src/main/java/org/jeewx/api/wxsendmsg/JwSendMessageAPI.java
package org.jeewx.api.wxsendmsg; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jeewx.api.core.common.HttpPostUtil; import org.jeewx.api.core.common.WxstoreUtils; import org.jeewx.api.core.exception.WexinReqException; import org.jeewx.api.core.req.model.user.Group; import org.jeewx.api.core.util.WeiXinReqUtil; import org.jeewx.api.wxbase.wxmedia.model.WxArticlesRequest; import org.jeewx.api.wxsendmsg.model.*; import org.jeewx.api.wxsendmsg.util.ReadImgUrls; import org.jeewx.api.wxuser.user.model.Wxuser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.StringReader; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; public class JwSendMessageAPI { private static Logger logger = LoggerFactory.getLogger(JwSendMessageAPI.class); // 消息预览URL private static String message_preview_url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=ACCESS_TOKEN"; // 上传媒体资源URL private static String upload_media_url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"; // 上传图文素材资源URL private static String upload_article_url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN"; // 根据分组进行群发URL private static String message_group_url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN"; // 根据OpenID列表群发URL private static String message_openid_url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=ACCESS_TOKEN"; // 删除群发URL private static String message_delete_url = "https://api.weixin.qq.com/cgi-bin/message/mass/delete?access_token=ACCESS_TOKEN"; // 查询群发消息发送状态URL private static String message_get_url = "https://api.weixin.qq.com/cgi-bin/message/mass/get?access_token=ACCESS_TOKEN"; //上传图文消息内的图片获取URL【订阅号与服务号认证后均可用】 private static String uploadimg_url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN"; /** * (群发图片上传)批量上传群发图文中的图片 * @param content 图文正文内容 * @param accesstoken 微信公众号Token * @param baseImageUrl 图片项目根路径 * @param domain 图文中图片域名 * @return */ public static String uploadArticleImgs(String content,String accesstoken,String baseImageUrl,String domain){ try { String[] urls = ReadImgUrls.getImgs(content); for(String imgurl:urls){ if(imgurl.indexOf("mmbiz.qpic.cn")!=-1){ continue; } // System.out.println("----------------imgurl------------------"+imgurl); String tempimgurl = imgurl; tempimgurl = tempimgurl.replace(domain,""); tempimgurl = baseImageUrl + tempimgurl; String newUrl = JwSendMessageAPI.uploadImg(accesstoken, tempimgurl); // if(oConvertUtils.isEmpty(newUrl)){ // throw new BusinessException("正文图片同步微信失败,请确认格式是否正确!"); // } // System.out.println("----------------newUrl------------------"+newUrl); content = content.replace(imgurl, newUrl); } } catch (Exception e) { System.err.println(e.toString()); } return content; } /** * 上传图文消息内的图片获取URL【订阅号与服务号认证后均可用】 * 请注意,本接口所上传的图片不占用公众号的素材库中图片数量的5000个的限制。图片仅支持jpg/png格式,大小必须在1MB以下。 * @param accesstoken * @param filePath * @param fileName * @return * @throws Exception */ public static String uploadImg(String accesstoken, String filePath){ try { if (accesstoken != null) { String requestUrl = uploadimg_url.replace("ACCESS_TOKEN", accesstoken); // File file = new File(filePath); // String contentType = WeiXinReqUtil.getFileContentType(filePath.substring(filePath.lastIndexOf(".") + 1)); // JSONObject result = WxstoreUtils.uploadMediaFile(requestUrl, file, contentType); HttpPostUtil u = new HttpPostUtil(requestUrl); u.addFileParameter("img", new File(filePath)); JSONObject result = JSONObject.parseObject(new String(u.send())); if(result!=null){ if(result.containsKey("url")){ return result.getString("url"); }else{ System.err.println(result.toString()); } } } } catch (Exception e) { System.err.println(e.toString()); } return ""; } //add--begin--author--ty---Date:20170526---for:图片同步微信返回JSONObject /** * 上传图文消息内的图片获取URL【订阅号与服务号认证后均可用] * @param accesstoken * @param filePath * @return {"url":""}或者 * {"errmsg":"","errcode":40001} */ public static JSONObject uploadImgReturnObj(String accesstoken, String filePath){ JSONObject result=new JSONObject(); try { if (accesstoken != null) { String requestUrl = uploadimg_url.replace("ACCESS_TOKEN", accesstoken); HttpPostUtil u = new HttpPostUtil(requestUrl); u.addFileParameter("img", new File(filePath)); result = JSONObject.parseObject(new String(u.send())); if(result!=null){ if(!result.containsKey("url")){ System.err.println(result.toString()); } } } } catch (Exception e) { result.put("errmsg", e.toString()); result.put("errcode", ""); System.err.println(e.toString()); } return result; } //add--end--author--ty---Date:20170526---for:图片同步微信返回JSONObject /** * 图文消息预览 * * @param touser * 接收人openid * @param wxArticles * 图文集合 * @throws WexinReqException */ public static void messagePrivate(String accesstoken, String touser, List<WxArticle> wxArticles) throws WexinReqException { if (accesstoken != null) { String requestUrl = message_preview_url.replace("ACCESS_TOKEN", accesstoken); try { String mediaId = getMediaId(accesstoken, wxArticles); JSONObject obj = new JSONObject(); JSONObject mpnews = new JSONObject(); obj.put("touser", touser); obj.put("msgtype", "mpnews"); mpnews.put("media_id", mediaId); obj.put("mpnews", mpnews); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); //System.out.println("微信返回的结果:" + result.toString()); } catch (Exception e) { throw new WexinReqException(e); } } else { throw new WexinReqException("accesstoken 为空,请检查!"); } } /** * 文本消息预览 * * @param touser * @param content * @throws Exception */ public static String messagePrivate(String accesstoken, String touser, String content) throws WexinReqException { String ret = ""; if (accesstoken != null) { String requestUrl = message_preview_url.replace("ACCESS_TOKEN", accesstoken); try { JSONObject obj = new JSONObject(); JSONObject text = new JSONObject(); obj.put("touser", touser); obj.put("msgtype", "text"); text.put("content", content); obj.put("text", text); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); //System.out.println("微信返回的结果:" + result.toString()); ret = result.toString(); } catch (Exception e) { throw new WexinReqException(e); } } else { throw new WexinReqException("accesstoken 为空,请检查!"); } return ret; } /** * 语音,图片,视频消息预览 * * @param touser * @param wxArticles * @throws Exception */ public static void messagePrivate(String accesstoken, String touser, WxMedia wxMedia) throws WexinReqException { if (accesstoken != null) { String requestUrl = message_preview_url.replace("ACCESS_TOKEN", accesstoken); try { String mediaId = getMediaId(accesstoken, wxMedia); JSONObject obj = new JSONObject(); JSONObject type = new JSONObject(); obj.put("touser", touser); obj.put("msgtype", wxMedia.getType()); type.put("media_id", mediaId); obj.put(wxMedia.getType(), type); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); //System.out.println("微信返回的结果:" + result.toString()); if (result.getInteger("errcode") != 0) { logger.error("多媒体消息预览失败!errcode=" + result.getString("errcode") + ",errmsg = " + result.getString("errmsg")); throw new Exception("多媒体消息预览失败!errcode=" + result.getString("errcode") + ",errmsg = " + result.getString("errmsg")); } } catch (Exception e) { throw new WexinReqException(e); } } else { throw new WexinReqException("accesstoken 为空,请检查!"); } } /** * 群发图文消息到指定的微信分组或所有人 * * @param accesstoken * @param is_to_all * 是否发送给所有人 ,ture 发送给所有人,false 按组发送 * @param group * 微信的用户组,如果is_to_all=false,则字段必须填写 * @param wxArticles * 图文素材集合 * @return * @throws WexinReqException */ public static SendMessageResponse sendMessageToGroupOrAllWithArticles(String accesstoken, boolean is_to_all, Group group, List<WxArticle> wxArticles) throws WexinReqException { SendMessageResponse response = null; if (accesstoken != null) { String requestUrl = message_group_url.replace("ACCESS_TOKEN", accesstoken); try { String mediaId = getMediaId(accesstoken, wxArticles); JSONObject obj = new JSONObject(); JSONObject filter = new JSONObject(); JSONObject mpnews = new JSONObject(); filter.put("is_to_all", is_to_all); if (!is_to_all) { filter.put("group_id", group.getId()); } obj.put("filter", filter); mpnews.put("media_id", mediaId); obj.put("mpnews", mpnews); obj.put("msgtype", "mpnews"); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); //System.out.println("微信返回的结果:" + result.toString()); response = (SendMessageResponse) JSONObject.toJavaObject(result, SendMessageResponse.class); } catch (Exception e) { throw new WexinReqException(e); } } else { throw new WexinReqException("accesstoken 为空,请检查!"); } return response; } /** * 群发文本消息到指定的微信分组或所有人 * * @param accesstoken * @param is_to_all * 是否发送给所有人 ,ture 发送给所有人,false 按组发送 * @param group * 微信的用户组,如果is_to_all=false,则字段必须填写 * @param content * 文本内容 * @return * @throws WexinReqException */ public static SendMessageResponse sendMessageToGroupOrAllWithText(String accesstoken, boolean is_to_all, Group group, String content) throws WexinReqException { SendMessageResponse response = null; if (accesstoken != null) { String requestUrl = message_group_url.replace("ACCESS_TOKEN", accesstoken); try { JSONObject obj = new JSONObject(); JSONObject filter = new JSONObject(); JSONObject text = new JSONObject(); filter.put("is_to_all", is_to_all); if (!is_to_all) { filter.put("group_id", group.getId()); } obj.put("filter", filter); text.put("content", content); obj.put("text", text); obj.put("msgtype", "text"); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); //System.out.println("微信返回的结果:" + result.toString()); response = (SendMessageResponse) JSONObject.toJavaObject(result, SendMessageResponse.class); } catch (Exception e) { throw new WexinReqException(e); } } else { throw new WexinReqException("accesstoken 为空,请检查!"); } return response; } /** * 使用语音、图片、视频群发消息到指定的微信分组或所有人 * * @param accesstoken * @param is_to_all * 是否发送给所有人 ,ture 发送给所有人,false 按组发送 * @param group * 微信的用户组,如果is_to_all=false,则字段必须填写 * @param wxMedia * 多媒体资源, 语音为voice, 图片为image,视频为video * @return * @throws WexinReqException */ public static SendMessageResponse sendMessageToGroupOrAllWithMedia(String accesstoken, boolean is_to_all,Group group, WxMedia wxMedia) throws WexinReqException { SendMessageResponse response = null; if (accesstoken != null) { String requestUrl = message_group_url.replace("ACCESS_TOKEN", accesstoken); try { String mediaId = getMediaId(accesstoken, wxMedia); JSONObject obj = new JSONObject(); JSONObject filter = new JSONObject(); JSONObject media = new JSONObject(); filter.put("is_to_all", is_to_all); if (!is_to_all) { filter.put("group_id", group.getId()); } obj.put("filter", filter); media.put("media_id", mediaId); obj.put(wxMedia.getType(), media); obj.put("msgtype", wxMedia.getType()); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); //System.out.println("微信返回的结果:" + result.toString()); response = (SendMessageResponse) JSONObject.toJavaObject(result, SendMessageResponse.class); } catch (Exception e) { throw new WexinReqException(e); } } else { throw new WexinReqException("accesstoken 为空,请检查!"); } return response; } /** * 群发图文消息到指定的微信openid数组 * * @param accesstoken * @param wxusers * 接受消息的微信用户数组 * @param wxArticles * 图文素材集合 * @return * @throws WexinReqException */ public static SendMessageResponse sendMessageToOpenidsWithArticles(String accesstoken, Wxuser[] wxusers, List<WxArticle> wxArticles) throws WexinReqException { SendMessageResponse response = null; if (accesstoken != null) { String requestUrl = message_openid_url.replace("ACCESS_TOKEN", accesstoken); List<String> openids = new ArrayList<String>(); for(Wxuser wxuser : wxusers) { openids.add(wxuser.getOpenid()); } try { String mediaId = getMediaId(accesstoken, wxArticles); JSONObject obj = new JSONObject(); JSONObject mpnews = new JSONObject(); obj.put("touser", openids); mpnews.put("media_id", mediaId); obj.put("mpnews", mpnews); obj.put("msgtype", "mpnews"); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); //System.out.println("微信返回的结果:" + result.toString()); response = (SendMessageResponse) JSONObject.toJavaObject(result, SendMessageResponse.class); } catch (Exception e) { throw new WexinReqException(e); } } else { throw new WexinReqException("accesstoken 为空,请检查!"); } return response; } /** * 群发文本消息到指定的微信openid数组 * * @param accesstoken * @param wxusers * 接受消息的微信用户数组 * @param content * 文本内容 * @return * @throws WexinReqException */ public static SendMessageResponse sendMessageToOpenidsWithText(String accesstoken, Wxuser[] wxusers, String content) throws WexinReqException { SendMessageResponse response = null; if (accesstoken != null) { String requestUrl = message_openid_url.replace("ACCESS_TOKEN", accesstoken); List<String> openids = new ArrayList<String>(); for(Wxuser wxuser : wxusers) { openids.add(wxuser.getOpenid()); } try { JSONObject obj = new JSONObject(); JSONObject text = new JSONObject(); obj.put("touser", openids); text.put("content", content); obj.put("text", text); obj.put("msgtype", "text"); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); //System.out.println("微信返回的结果:" + result.toString()); response = (SendMessageResponse) JSONObject.toJavaObject(result, SendMessageResponse.class); } catch (Exception e) { throw new WexinReqException(e); } } else { throw new WexinReqException("accesstoken 为空,请检查!"); } return response; } /** * 使用语音、图片、视频群发消息到指定的微信openid数组 * * @param accesstoken * @param wxusers * 接受消息的微信用户数组 * @param wxMedia * 多媒体资源, 语音为voice, 图片为image,视频为video * @return * @throws WexinReqException */ public static SendMessageResponse sendMessageToOpenidsWithMedia(String accesstoken, Wxuser[] wxusers, WxMedia wxMedia) throws WexinReqException { SendMessageResponse response = null; if (accesstoken != null) { String requestUrl = message_openid_url.replace("ACCESS_TOKEN", accesstoken); List<String> openids = new ArrayList<String>(); for(Wxuser wxuser : wxusers) { openids.add(wxuser.getOpenid()); } try { String mediaId = getMediaId(accesstoken, wxMedia); JSONObject obj = new JSONObject(); JSONObject media = new JSONObject(); obj.put("touser", openids); media.put("media_id", mediaId); obj.put(wxMedia.getType(), media); obj.put("msgtype", wxMedia.getType()); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); //System.out.println("微信返回的结果:" + result.toString()); response = (SendMessageResponse) JSONObject.toJavaObject(result, SendMessageResponse.class); } catch (Exception e) { throw new WexinReqException(e); } } else { throw new WexinReqException("accesstoken 为空,请检查!"); } return response; } /** * 根据群发的msg_id删除群发<br/> * 请注意,只有已经发送成功的消息才能删除删除消息只是将消息的图文详情页失效,已经收到的用户,还是能在其本地看到消息卡片。 * 另外,删除群发消息只能删除图文消息和视频消息,其他类型的消息一经发送,无法删除。 * * @param accesstoken * @param msg_id * 群发消息的msg_id * @return * @throws WexinReqException */ public static String deleteSendMessage(String accesstoken, String msg_id) throws WexinReqException { String response = null; if (accesstoken != null) { String requestUrl = message_delete_url.replace("ACCESS_TOKEN", accesstoken); try { JSONObject obj = new JSONObject(); obj.put("msg_id", msg_id); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); //System.out.println("微信返回的结果:" + result.toString()); response = result.toString(); } catch (Exception e) { throw new WexinReqException(e); } } else { throw new WexinReqException("accesstoken 为空,请检查!"); } return response; } /** * 根据群发的msg_id查询群发消息发送状态 * * @param accesstoken * @param msg_id * 群发消息的msg_id * @return true表示发送成功,false表示发送失败 * @throws WexinReqException */ public static boolean getSendMessageStatus(String accesstoken, String msg_id) throws WexinReqException { boolean response = false; if (accesstoken != null) { String requestUrl = message_get_url.replace("ACCESS_TOKEN", accesstoken); try { JSONObject obj = new JSONObject(); obj.put("msg_id", msg_id); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); //System.out.println("微信返回的结果:" + result.toString()); if (result.containsKey("msg_status")) { if ("SEND_SUCCESS".equalsIgnoreCase(result.getString("msg_status"))) { response = true; } } } catch (Exception e) { throw new WexinReqException(e); } } else { throw new WexinReqException("accesstoken 为空,请检查!"); } return response; } /** * * 根据微信事件推送群发结果获取群发消息的发送报告 * @param xmlString * 信事件推送群发结果xmlString * @return 微信发送报告实体对象 * @throws WexinReqException */ @SuppressWarnings("rawtypes") public static SendMessageReport getReportBySendMessageReturnString(String xmlString) throws WexinReqException { SendMessageReport report = new SendMessageReport(); SAXBuilder build = new SAXBuilder(); Document doc = null; try { doc = build.build(new StringReader(xmlString)); } catch (Exception e1) { e1.printStackTrace(); throw new WexinReqException(e1); } Element root = doc.getRootElement(); Iterator itr = (root.getChildren()).iterator(); Class<SendMessageReport> clazz = SendMessageReport.class; while (itr.hasNext()) { Element oneLevelDeep = (Element) itr.next(); // System.out.println("name ==>>" + oneLevelDeep.getName() + // ":::: value==>> " + oneLevelDeep.getText()); try { Field filed = clazz.getDeclaredField(oneLevelDeep.getName()); filed.setAccessible(true); filed.set(report, oneLevelDeep.getText()); filed.setAccessible(false); } catch (NoSuchFieldException e) { } catch (SecurityException e) { } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } } return report; } /** * 获取多媒体资源的mediaId * * @param accesstoken * @param wxMedia * @return * @throws WexinReqException */ public static String getMediaId(String accesstoken, WxMedia wxMedia) throws WexinReqException { WxMediaResponse response = uploadMediaFile(accesstoken, wxMedia.getFilePath(), wxMedia.getFileName(), wxMedia.getType()); if (response == null) { throw new WexinReqException("获取多媒体资源的mediaId失败"); } return response.getMedia_id(); } public static String getMediaId(String accesstoken, List<WxArticle> wxArticles) throws WexinReqException { WxArticlesResponse response = uploadArticles(accesstoken, wxArticles); if (response == null) { throw new WexinReqException("获取图文的mediaId失败"); } return response.getMedia_id(); } /** * 上传图文消息素材 * * @param accesstoken * @param wxArticles * 图文集合,数量不大于10 * @return WxArticlesResponse 上传图文消息素材返回结果 * @throws WexinReqException */ public static WxArticlesResponse uploadArticles(String accesstoken, List<WxArticle> wxArticles) throws WexinReqException { WxArticlesResponse wxArticlesResponse = null; if (wxArticles.size() == 0) { logger.error("没有上传的图文消息"); } else if (wxArticles.size() > 10) { logger.error("图文消息最多为10个图文"); } else { if (accesstoken != null) { String requestUrl = upload_article_url.replace("ACCESS_TOKEN", accesstoken); for (WxArticle article : wxArticles) { if (article.getFileName() != null && article.getFileName().length() > 0) { try { String mediaId = getFileMediaId(accesstoken, article); article.setThumb_media_id(mediaId); } catch (Exception e) { throw new WexinReqException(e); } } } WxArticlesRequest wxArticlesRequest = new WxArticlesRequest(); wxArticlesRequest.setArticles(wxArticles); JSONObject obj = JSONObject.parseObject(JSON.toJSONString(wxArticlesRequest)); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); //System.out.println("微信返回的结果:" + result.toString()); if (result.containsKey("errcode")) { logger.error("上传图文消息失败!errcode=" + result.getString("errcode") + ",errmsg = " + result.getString("errmsg")); throw new WexinReqException("上传图文消息失败!errcode=" + result.getString("errcode") + ",errmsg = " + result.getString("errmsg")); } else { wxArticlesResponse = new WxArticlesResponse(); wxArticlesResponse.setMedia_id(result.getString("media_id")); wxArticlesResponse.setType(result.getString("type")); wxArticlesResponse.setCreated_at(new Date(result.getLong("created_at") * 1000)); } } } return wxArticlesResponse; } /** * 获取文件上传文件的media_id * * @param accesstoken * @param article * @return * @throws WexinReqException */ public static String getFileMediaId(String accesstoken, WxArticle article) throws WexinReqException { WxMediaResponse response = uploadMediaFile(accesstoken, article.getFilePath(), article.getFileName(), "image"); if (response != null) { return response.getMedia_id(); } throw new WexinReqException("获取文件的media_id失败"); } /** * 上传媒体资源 * * @param filePath * @param fileName * @param type * 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb) * @return * @throws Exception */ public static WxMediaResponse uploadMediaFile(String accesstoken, String filePath, String fileName, String type) throws WexinReqException { WxMediaResponse mediaResource = null; if (accesstoken != null) { String requestUrl = upload_media_url.replace("ACCESS_TOKEN", accesstoken).replace("TYPE", type); File file = new File(filePath + fileName); String contentType = WeiXinReqUtil.getFileContentType(fileName.substring(fileName.lastIndexOf(".") + 1)); JSONObject result = WxstoreUtils.uploadMediaFile(requestUrl, file, contentType); //System.out.println("微信返回的结果:" + result.toString()); if (result.containsKey("errcode")) { logger.error("上传媒体资源失败!errcode=" + result.getString("errcode") + ",errmsg = " + result.getString("errmsg")); } else { // {"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789} mediaResource = new WxMediaResponse(); mediaResource.setMedia_id(result.getString("media_id")); mediaResource.setType(result.getString("type")); mediaResource.setCreated_at(new Date(result.getLong("created_at") * 1000)); } // return mediaResource; } return mediaResource; } public static void main(String[] args) throws WexinReqException { /* * String a = "" + "<xml>" + * "<ToUserName><![CDATA[gh_3e8adccde292]]></ToUserName>" + * "<FromUserName><![CDATA[oR5Gjjl_eiZoUpGozMo7dbBJ362A]]></FromUserName>" * + "<CreateTime>1394524295</CreateTime>" + * "<MsgType><![CDATA[event]]></MsgType>" + * "<Event><![CDATA[MASSSENDJOBFINISH]]></Event>" + * "<MsgID>1988</MsgID>" + "<Status><![CDATA[sendsuccess]]></Status>" + * "<TotalCount>100</TotalCount>" + "<FilterCount>80</FilterCount>" + * "<SentCount>75</SentCount>" + "<ErrorCount>5</ErrorCount>" + * "</xml>"; getReportBySendMessageReturnString(a); */ /*String a = "" + "{" + " \"errcode\":0," + " \"errmsg\":\"send job submission success\"," + " \"msg_id\":34182" + "}"; SendMessageResponse response = (SendMessageResponse) JSONObject.toBean(JSONObject.fromObject(a), SendMessageResponse.class); System.out.println(response);*/ /*List<String> a = new ArrayList<String>(); a.add("111"); a.add("3"); a.add("4"); a.add("e"); a.add("df"); a.add("222"); JSONObject aa = new JSONObject(); aa.put("user", a); System.out.println(aa.toString());*/ } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/JwKfaccountAPI.java
src/main/java/org/jeewx/api/wxsendmsg/JwKfaccountAPI.java
package org.jeewx.api.wxsendmsg; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.jeewx.api.core.exception.WexinReqException; import org.jeewx.api.core.req.WeiXinReqService; import org.jeewx.api.core.req.model.kfaccount.*; import org.jeewx.api.core.util.WeiXinConstant; import org.jeewx.api.wxsendmsg.model.WxKfaccount; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; /** * 微信客服管理处理 * * @author lizr * */ public class JwKfaccountAPI { private static Logger logger = LoggerFactory .getLogger(JwKfaccountAPI.class); /** * 添加客服 * kf_account 是 完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符。如果没有公众号微信号,请前往微信公众平台设置。 nickname 是 客服昵称,最长6个汉字或12个英文字符 password 是 客服账号登录密码,格式为密码明文的32位加密MD5值 * @param accessToken * @param kf_account * @param nickname * @param password * @return * @throws WexinReqException * */ public static String addKfacount(String accessToken, String kf_account, String nickname, String password) throws WexinReqException { KfaccountAdd kf = new KfaccountAdd(); kf.setAccess_token(accessToken); kf.setKf_account(kf_account); kf.setNickname(nickname); kf.setPassword(password); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(kf); String msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); return msg; } /** * 修改客服账号 * @param accessToken * @param kf_account * @param nickname * @param password * @return * @throws WexinReqException */ public static String modifyKfaccount(String accessToken, String kf_account, String nickname, String password) throws WexinReqException{ KfaccountUpdate kfUp = new KfaccountUpdate(); kfUp.setAccess_token(accessToken); kfUp.setKf_account(kf_account); kfUp.setNickname(nickname); kfUp.setPassword(password); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(kfUp); String msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); return msg; } /** * 删除客服账号 * @param accessToken * @param kf_account * @param nickname * @param password * @return * @throws WexinReqException */ public static String deleteKfaccount(String accessToken, String kf_account, String nickname, String password) throws WexinReqException{ KfaccountDel kfdel = new KfaccountDel(); kfdel.setAccess_token(accessToken); kfdel.setKf_account(kf_account); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(kfdel); String msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); return msg; } /** * 修改客服头像 * @param accessToken * @param kf_account * @param filePathName * @return * @throws WexinReqException */ public static String uploadKfaccountHeadimg(String accessToken,String kf_account,String filePathName ) throws WexinReqException{ KfaccountUploadheadimg kfUpload = new KfaccountUploadheadimg(); kfUpload.setAccess_token(accessToken); kfUpload.setFilePathName(filePathName); kfUpload.setKf_account(kf_account); kfUpload.setType("image"); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(kfUpload); String msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); return msg; } /** * 获取所有的客服账号信息 * @param accessToken * @return * @throws WexinReqException */ public static List<WxKfaccount> getAllKfaccount(String accessToken) throws WexinReqException{ KfaccountList kfGet = new KfaccountList(); kfGet.setAccess_token(accessToken); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(kfGet); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); List<WxKfaccount> lstWxKfaccount = null; JSONArray kf_list = result.getJSONArray("kf_list"); lstWxKfaccount = new ArrayList<WxKfaccount>(); WxKfaccount kfaccount = null; for(int i = 0; i < kf_list.size() ; i++){ kfaccount = (WxKfaccount) JSONObject.toJavaObject( kf_list.getJSONObject(i), WxKfaccount.class); lstWxKfaccount.add(kfaccount); } return lstWxKfaccount; } /** * * 发送客服信息 * access_token 是 调用接口凭证 touser 是 普通用户openid msgtype 是 消息类型,文本为text,图片为image,语音为voice,视频消息为video,音乐消息为music,图文消息为news content 是 文本消息内容 media_id 是 发送的图片/语音/视频的媒体ID thumb_media_id 是 缩略图的媒体ID title 否 图文消息/视频消息/音乐消息的标题 description 否 图文消息/视频消息/音乐消息的描述 musicurl 是 音乐链接 hqmusicurl 是 高品质音乐链接,wifi环境优先使用该链接播放音乐 url 否 图文消息被点击后跳转的链接 picurl 否 图文消息的图片链接,支持JPG、PNG格式,较好的效果为大图640*320,小图80*80 * @throws WexinReqException */ public static String sendKfMessage(KfcustomSend kfcustomSend) throws WexinReqException{ JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(kfcustomSend); String msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); return msg; } /** * 获取在线客服信息 * kf_account 完整客服账号,格式为:账号前缀@公众号微信号 status 客服在线状态 1:pc在线,2:手机在线。若pc和手机同时在线则为 1+2=3 kf_id 客服工号 auto_accept 客服设置的最大自动接入数 accepted_case 客服当前正在接待的会话数 * @param accessToken * @return * @throws WexinReqException */ public static List<WxKfaccount> getAllOnlineKfaccount(String accessToken) throws WexinReqException{ KfOnlineAccountList kfGet = new KfOnlineAccountList(); kfGet.setAccess_token(accessToken); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(kfGet); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); List<WxKfaccount> lstWxKfaccount = null; JSONArray kf_list = result.getJSONArray("kf_online_list"); lstWxKfaccount = new ArrayList<WxKfaccount>(); WxKfaccount kfaccount = null; for (int i = 0; i < kf_list.size(); i++) { kfaccount = (WxKfaccount) JSONObject.toJavaObject( kf_list.getJSONObject(i), WxKfaccount.class); lstWxKfaccount.add(kfaccount); } return lstWxKfaccount; } public static void main(String[] args){ try { String s = "qQo8f2B0D0ZnlTP-8TKOMWoDcGiCoAhICn09S_QKxMgpSVp0VG8rgg_8PAJhy893z4lU-kY89DsZAsC3M54zxQBxuwTehg2nC_dO75VEGqw"; //JwTokenAPI.getAccessToken("wx00737224cb9dbc7d","b9479ebdb58d1c6b6efd4171ebe718b5"); List<WxKfaccount> ls = JwKfaccountAPI.getAllOnlineKfaccount(s); for(WxKfaccount a : ls){ System.out.println(a.getKf_account()+"---"+a.getKf_id()+a.getKf_nick()); System.out.println(a.getKf_headimgurl()); } } catch (WexinReqException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/JwGetAutoReplyRuleAPI.java
src/main/java/org/jeewx/api/wxsendmsg/JwGetAutoReplyRuleAPI.java
package org.jeewx.api.wxsendmsg; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SimplePropertyPreFilter; import org.jeewx.api.core.exception.WexinReqException; import org.jeewx.api.core.req.WeiXinReqService; import org.jeewx.api.core.req.model.message.AutoReplyRuleGet; import org.jeewx.api.core.util.WeiXinConstant; import org.jeewx.api.wxsendmsg.model.WxArticleConfig; import org.jeewx.api.wxsendmsg.model.auto.AutoReplyInfoRule; import org.jeewx.api.wxsendmsg.model.auto.KeyWordAutoReplyInfo; import org.jeewx.api.wxsendmsg.model.auto.KeywordListInfo; import org.jeewx.api.wxsendmsg.model.auto.ReplyListInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; /** * 获取自动回复规则 * @author luobaoli * */ public class JwGetAutoReplyRuleAPI { private static Logger logger = LoggerFactory.getLogger(JwGetAutoReplyRuleAPI.class); /** * 获取自动回复规则 * @param accessToken * @return */ public static AutoReplyInfoRule getAutoReplyInfoRule(String accessToken) throws WexinReqException{ AutoReplyRuleGet arr = new AutoReplyRuleGet(); arr.setAccess_token(accessToken); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(arr); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); // AutoReplyInfoRule autoReplyInfoRule = (AutoReplyInfoRule) JSONObject.toJavaObject(result,new CustomJsonConfig(AutoReplyInfoRule.class, "keyword_autoreply_info")); SimplePropertyPreFilter keywordFilter = new SimplePropertyPreFilter(); keywordFilter.getExcludes().add("keyword_autoreply_info"); AutoReplyInfoRule autoReplyInfoRule = JSONObject.parseObject(JSONObject.toJSONString(result, keywordFilter), AutoReplyInfoRule.class); JSONObject keywordAutoReplyInfoJsonObj = result.getJSONObject("keyword_autoreply_info"); if(keywordAutoReplyInfoJsonObj!=null && !keywordAutoReplyInfoJsonObj.isEmpty()){ /**关键词自动回复的信息 */ JSONArray keywordAutoReplyInfos = keywordAutoReplyInfoJsonObj.getJSONArray("list"); if(keywordAutoReplyInfos!=null){ List<KeyWordAutoReplyInfo> listKeyWordAutoReplyInfo = new ArrayList<KeyWordAutoReplyInfo>(); for(int i=0;i<keywordAutoReplyInfos.size();i++){ // KeyWordAutoReplyInfo keyWordAutoReplyInfo = (KeyWordAutoReplyInfo) JSONObject.toJavaObject(keywordAutoReplyInfos.getJSONObject(i),new CustomJsonConfig(KeyWordAutoReplyInfo.class, new String[]{"keyword_list_info","reply_list_info"})); SimplePropertyPreFilter keywordReplyFilter = new SimplePropertyPreFilter(); keywordReplyFilter.getExcludes().add("keyword_list_info"); keywordReplyFilter.getExcludes().add("reply_list_info"); KeyWordAutoReplyInfo keyWordAutoReplyInfo = JSONObject.parseObject(JSONObject.toJSONString(keywordAutoReplyInfos.getJSONObject(i), keywordReplyFilter), KeyWordAutoReplyInfo.class); /**处理关键词列表 */ JSONArray keywordListInfos = keywordAutoReplyInfos.getJSONObject(i).getJSONArray("keyword_list_info"); if(keywordListInfos!=null){ List<KeywordListInfo> listKeywordListInfo = new ArrayList<KeywordListInfo>(); for(int j=0;j<keywordListInfos.size();j++){ KeywordListInfo keywordListInfo = (KeywordListInfo) JSONObject.toJavaObject(keywordListInfos.getJSONObject(j),KeywordListInfo.class); listKeywordListInfo.add(keywordListInfo); } keyWordAutoReplyInfo.setKeyword_list_info(listKeywordListInfo); } /**处理关键字回复信息 */ JSONArray replyListInfos = keywordAutoReplyInfos.getJSONObject(i).getJSONArray("reply_list_info"); if(replyListInfos!=null){ List<ReplyListInfo> listReplyListInfo = new ArrayList<ReplyListInfo>(); for(int j=0;j<replyListInfos.size();j++){ // ReplyListInfo replyListInfo = (ReplyListInfo) JSONObject.toJavaObject(keywordListInfos.getJSONObject(j),new CustomJsonConfig(ReplyListInfo.class, "news_info")); SimplePropertyPreFilter newsInfoFilter = new SimplePropertyPreFilter(); newsInfoFilter.getExcludes().add("news_info"); ReplyListInfo replyListInfo = JSONObject.parseObject(JSONObject.toJSONString(keywordListInfos.getJSONObject(j),newsInfoFilter), ReplyListInfo.class); /**处理关键字回复相关图文消息 */ JSONObject newsInfoJsonObj = replyListInfos.getJSONObject(j).getJSONObject("news_info"); if(newsInfoJsonObj!=null && !newsInfoJsonObj.isEmpty()){ JSONArray newsInfos = newsInfoJsonObj.getJSONArray("list"); List<WxArticleConfig> listNewsInfo = new ArrayList<WxArticleConfig>(); for (int k = 0; k < newsInfos.size(); k++) { WxArticleConfig wxArticleConfig = (WxArticleConfig) JSONObject.toJavaObject(newsInfos.getJSONObject(k), WxArticleConfig.class); listNewsInfo.add(wxArticleConfig); } replyListInfo.setNews_info(listNewsInfo); } listReplyListInfo.add(replyListInfo); } keyWordAutoReplyInfo.setReply_list_info(listReplyListInfo); } listKeyWordAutoReplyInfo.add(keyWordAutoReplyInfo); } autoReplyInfoRule.setKeyword_autoreply_info(listKeyWordAutoReplyInfo); } } return autoReplyInfoRule; } public static void main(String[] args) { try { //String s = JwTokenAPI.getAccessToken("wx298c4cc7312063df","fbf8cebf983c931bd7c1bee1498f8605"); String s = "chsqpXVzXmPgqgZrrZnQzxqEi2L-1qStuVDOeZ-hKlY-Gkdlca3Q2HE9__BXc5hNoU1Plpc56UyZ1QoaDMkRbVSi0iUUVb27GTMaTDBfmuY"; JwGetAutoReplyRuleAPI.getAutoReplyInfoRule(s); } catch (WexinReqException e) { e.printStackTrace(); } } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/JwSendTemplateMsgAPI.java
src/main/java/org/jeewx/api/wxsendmsg/JwSendTemplateMsgAPI.java
package org.jeewx.api.wxsendmsg; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.jeewx.api.core.common.WxstoreUtils; import org.jeewx.api.core.exception.WexinReqException; import org.jeewx.api.core.req.model.message.TemplateMessageSendResult; import org.jeewx.api.core.util.WeiXinConstant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 模板消息接口 * * */ public class JwSendTemplateMsgAPI { //设置行业信息 private static String set_industry = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=ACCESS_TOKEN"; //获取行业信息 private static String get_industry = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=ACCESS_TOKEN"; //获得模板ID private static String get_template_id = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=ACCESS_TOKEN"; //获取模板列表 private static String get_tamplate_list = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=ACCESS_TOKEN"; //删除模板 private static String del_template = "https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token=ACCESS_TOKEN"; //发送模板消息 private static String send_template_msg = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN"; private static Logger logger = LoggerFactory.getLogger(JwSendTemplateMsgAPI.class); /** * 设置行业信息 * @param accessToken * @param industry_id1 * @param industry_id2 * @return * @throws WexinReqException */ public static String setIndustry(String accessToken,String industry_id1,String industry_id2) throws WexinReqException{ String msg = ""; if (accessToken != null) { String requestUrl = set_industry.replace("ACCESS_TOKEN", accessToken); JSONObject obj = new JSONObject(); obj.put("industry_id1", industry_id1); obj.put("industry_id2", industry_id2); logger.info("设置行业信息方法执行前json参数 obj: "+obj.toString()); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); if(error == null){ msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); }else{ msg = result.toString(); } logger.info("设置行业信息方法执行后json参数 : "+result.toString()); } return msg; } /** * 获取行业信息 * @param accessToken * @param industry_id1 * @param industry_id2 * @return * @throws WexinReqException */ public static String getIndustry(String accessToken) throws WexinReqException{ String msg = ""; if (accessToken != null) { String requestUrl = get_industry.replace("ACCESS_TOKEN", accessToken); logger.info("获取行业信息方法执行前json参数 accessToken: "+accessToken); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "GET",null); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); if(error == null){ msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); }else{ msg = result.toString(); } logger.info("获取行业信息方法执行后json参数 : "+result.toString()); } return msg; } /** * 获取模板ID * @param accessToken * @return * @throws WexinReqException */ public static String getTemplateId(String accessToken) throws WexinReqException{ String msg = ""; if (accessToken != null) { String requestUrl = get_template_id.replace("ACCESS_TOKEN", accessToken); logger.info("获取模板ID方法执行前json参数 accessToken: "+accessToken); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", null); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); if(error == null){ msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); }else{ msg = result.toString(); } logger.info("获取模板ID方法执行后json参数 : "+result.toString()); } return msg; } /** * 获取模板列表 * @param accessToken * @return * @throws WexinReqException */ public static String getTemplateList(String accessToken) throws WexinReqException{ String msg = ""; if (accessToken != null) { String requestUrl = get_tamplate_list.replace("ACCESS_TOKEN", accessToken); logger.info("获取模板列表方法执行前json参数 accessToken: "+accessToken); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "GET",null); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); if(error == null){ msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); }else{ msg = result.toString(); } logger.info("获取模板列表方法执行后json参数 : "+result.toString()); } return msg; } /** * 删除模板 */ public static String delTemplate(String accessToken,String template_id) throws WexinReqException{ String msg = ""; if (accessToken != null) { String requestUrl = del_template.replace("ACCESS_TOKEN", accessToken); JSONObject obj = new JSONObject(); obj.put("template_id", template_id); logger.info("删除模板方法执行前json参数 : "+obj.toString()); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); if(error == null){ msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); }else{ msg = result.toString(); } logger.info("删除模板方法执行后json参数 : "+result.toString()); } return msg; } /** * 发送模板消息 * @param industryTemplateMessageSend * @return * @throws WexinReqException */ public static String sendTemplateMsg(String accessToken, TemplateMessageSendResult msgSend) throws WexinReqException { String msg = ""; if (accessToken != null) { String requestUrl = send_template_msg.replace("ACCESS_TOKEN", accessToken); JSONObject obj = JSONObject.parseObject(JSON.toJSONString(msgSend)); logger.info("发送模板消息方法执行前json参数 :{obj :" + obj.toString() + "}"); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); if (error == null) { msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); } else { msg = result.toString(); } logger.info("发送模板消息方法执行后json参数 :{result :" + result.toString() + "}"); } return msg; } public static void main(String[] args){ String accessToken = "MAMJfbrGDKIGPiQMfeSTYimX6dyitcvSVoUPzOLVe75erBTO9lRnfad6ov5rXgAkTjX-4ZujQnmLH8ZBnTCq0QCEwLgoYAZSp_HKbeJ24zUXCLbAIADIR"; try { JwSendTemplateMsgAPI.getIndustry(accessToken); } catch (WexinReqException e) { e.printStackTrace(); } } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/util/ReadImgUrls.java
src/main/java/org/jeewx/api/wxsendmsg/util/ReadImgUrls.java
package org.jeewx.api.wxsendmsg.util; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jeewx.api.core.util.FileUtils; public class ReadImgUrls { public static String[] getImgs(String content) { String img = ""; Pattern p_image; Matcher m_image; String str = ""; String[] images = null; String regEx_img = "(<img.*src\\s*=\\s*(.*?)[^>]*?>)"; p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE); m_image = p_image.matcher(content); while (m_image.find()) { img = m_image.group(); Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img); while (m.find()) { String tempSelected = m.group(1); if ("".equals(str)) { str = tempSelected; } else { String temp = tempSelected; if(temp.indexOf("mmbiz.qpic.cn")==-1){ str = str + "," + temp; } } } } //update-begin-author:taoYan date:20180531 for:TASK #2755 【图文素材】编辑器优化汇总-2 if(content.indexOf("background-image")>0){ String regEx_bg = "(background-image\\s*:\\s*url\\s*\\((&#39;)?http://\\S*\\);)"; p_image = Pattern.compile(regEx_bg, Pattern.CASE_INSENSITIVE); m_image = p_image.matcher(content); while (m_image.find()) { img = m_image.group(); if(img.indexOf("&#39;")>0){ img = img.replace("&#39;", ""); } Matcher m = Pattern.compile("\\(\\s*(http://\\S*)\\s*\\);").matcher(img); while (m.find()) { String tempSelected = m.group(1); if ("".equals(str)) { str = tempSelected; } else { String temp = tempSelected; if(temp.indexOf("mmbiz.qpic.cn")==-1){ str = str + "," + temp; } } } } } //update-end-author:taoYan date:20180531 for:TASK #2755 【图文素材】编辑器优化汇总-2 if (!"".equals(str)) { images = str.split(","); } return images; } public static void main(String[] args) { String baseImageUrl = System.getProperty("user.dir"); String domainUrl = "http://www.jeewx.com/jeewx"; try { String c = FileUtils.readFile("D:/workspace-JEECGONE/weixin4j/src/main/java/org/jeewx/api/wxsendmsg/uploadimg/1.html"); String[] urls = getImgs(c); for(String url:urls){ System.out.println(url); // url = url.replace(domainUrl, ""); // url = baseImageUrl + url; // System.out.println(url); } } catch (IOException e) { e.printStackTrace(); } } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/model/SendMessageResponse.java
src/main/java/org/jeewx/api/wxsendmsg/model/SendMessageResponse.java
package org.jeewx.api.wxsendmsg.model; /** * 微信群发返回的结果 * @author LIAIJUN * */ public class SendMessageResponse { private String errcode; private String errmsg; private String msg_id; public String getErrcode() { return errcode; } public void setErrcode(String errcode) { this.errcode = errcode; } public String getErrmsg() { return errmsg; } public void setErrmsg(String errmsg) { this.errmsg = errmsg; } public String getMsg_id() { return msg_id; } public void setMsg_id(String msg_id) { this.msg_id = msg_id; } @Override public String toString() { return "SendMessageResponse [errcode=" + errcode + ", errmsg=" + errmsg + ", msg_id=" + msg_id + "]"; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/model/WxMedia.java
src/main/java/org/jeewx/api/wxsendmsg/model/WxMedia.java
package org.jeewx.api.wxsendmsg.model; /** * 多媒体资源文件 * @author LIAIJUN * */ public class WxMedia { private String fileName; private String filePath; private String type; public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String toString() { return "WxMedia [fileName=" + fileName + ", filePath=" + filePath + ", type=" + type + "]"; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/model/WxMediaResponse.java
src/main/java/org/jeewx/api/wxsendmsg/model/WxMediaResponse.java
package org.jeewx.api.wxsendmsg.model; import java.util.Date; /** * 上传到微信的媒体资源文件bean * * @author LIAIJUN * */ public class WxMediaResponse { // {"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789} /** 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb) */ private String type; /** 媒体资源ID */ private String media_id; /** 创建时间 */ private Date created_at; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getMedia_id() { return media_id; } public void setMedia_id(String media_id) { this.media_id = media_id; } public Date getCreated_at() { return created_at; } public void setCreated_at(Date created_at) { this.created_at = created_at; } @Override public String toString() { return "WxMediaResponse [type=" + type + ", media_id=" + media_id + ", created_at=" + created_at + "]"; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/model/WxArticlesResponse.java
src/main/java/org/jeewx/api/wxsendmsg/model/WxArticlesResponse.java
package org.jeewx.api.wxsendmsg.model; import java.util.Date; /** * 上传图文消息素材返回结果 * * @author LIAIJUN * */ public class WxArticlesResponse { /** news,即图文消息 */ private String type; /** 媒体文件/图文消息上传后获取的唯一标识 */ private String media_id; /** 媒体文件上传时间 */ private Date created_at; /** 图片上传成功之后的路径 */ private String url; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getMedia_id() { return media_id; } public void setMedia_id(String media_id) { this.media_id = media_id; } public Date getCreated_at() { return created_at; } public void setCreated_at(Date created_at) { this.created_at = created_at; } @Override public String toString() { return "WxArticlesResponse [type=" + type + ", media_id=" + media_id + ", created_at=" + created_at + "]"; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/model/WxArticle.java
src/main/java/org/jeewx/api/wxsendmsg/model/WxArticle.java
package org.jeewx.api.wxsendmsg.model; /** * 图文消息 * @author LIAIJUN * */ public class WxArticle { /** 图文消息缩略图的media_id */ private String thumb_media_id; /** 图文消息的作者 */ private String author; /** 图文消息的标题 */ private String title; /** 在图文消息页面点击“阅读原文”后的页面 */ private String content_source_url; /** 图文消息页面的内容,支持HTML标签 */ private String content; /** 图文消息的描述 */ private String digest; /** 是否显示封面,1为显示,0为不显示 */ private String show_cover_pic; private String fileName; private String filePath; public String getThumb_media_id() { return thumb_media_id; } public void setThumb_media_id(String thumb_media_id) { this.thumb_media_id = thumb_media_id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent_source_url() { return content_source_url; } public void setContent_source_url(String content_source_url) { this.content_source_url = content_source_url; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getDigest() { return digest; } public void setDigest(String digest) { this.digest = digest; } public String getShow_cover_pic() { return show_cover_pic; } public void setShow_cover_pic(String show_cover_pic) { this.show_cover_pic = show_cover_pic; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } @Override public String toString() { return "WxArticle [thumb_media_id=" + thumb_media_id + ", author=" + author + ", title=" + title + ", content_source_url=" + content_source_url + ", content=" + content + ", digest=" + digest + ", show_cover_pic=" + show_cover_pic + ", fileName=" + fileName + ", filePath=" + filePath + "]"; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/model/WxKfaccount.java
src/main/java/org/jeewx/api/wxsendmsg/model/WxKfaccount.java
package org.jeewx.api.wxsendmsg.model; /** * 客服信息 * @author sfli.sir * */ public class WxKfaccount { private String kf_account; private String kf_nick; private String kf_id; private String kf_headimgurl; private String auto_accept; private String accepted_case; public String getAuto_accept() { return auto_accept; } public void setAuto_accept(String auto_accept) { this.auto_accept = auto_accept; } public String getAccepted_case() { return accepted_case; } public void setAccepted_case(String accepted_case) { this.accepted_case = accepted_case; } public String getKf_account() { return kf_account; } public void setKf_account(String kf_account) { this.kf_account = kf_account; } public String getKf_nick() { return kf_nick; } public void setKf_nick(String kf_nick) { this.kf_nick = kf_nick; } public String getKf_id() { return kf_id; } public void setKf_id(String kf_id) { this.kf_id = kf_id; } public String getKf_headimgurl() { return kf_headimgurl; } public void setKf_headimgurl(String kf_headimgurl) { this.kf_headimgurl = kf_headimgurl; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/model/WxArticleConfig.java
src/main/java/org/jeewx/api/wxsendmsg/model/WxArticleConfig.java
package org.jeewx.api.wxsendmsg.model; /** * 图文消息(用于"获取自定义菜单配置接口"和"获取自动回复规则") * @author luobaoli * */ public class WxArticleConfig { /** 图文消息缩略图的media_id */ private String thumb_media_id; /** 图文消息的标题 */ private String title; /** 图文消息的作者 */ private String author; /** 图文消息的摘要 */ private String digest; /** 自动回复的类型。关注后自动回复和消息自动回复的类型仅支持文本(text)、图片(img)、语音(voice)、视频(video),关键词自动回复则还多了图文消息(news)*/ private String type; /** 是否显示封面,1为显示,0为不显示 */ private String show_cover; /** 封面图片的URL*/ private String cover_ur; /** 正文的URL*/ private String content_url; /** 原文的URL,若置空则无查看原文入口*/ private String source_url; private String content;//预留 private String fileName;//预留 private String filePath;//预留 public String getThumb_media_id() { return thumb_media_id; } public void setThumb_media_id(String thumb_media_id) { this.thumb_media_id = thumb_media_id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDigest() { return digest; } public void setDigest(String digest) { this.digest = digest; } public String getShow_cover() { return show_cover; } public void setShow_cover(String show_cover) { this.show_cover = show_cover; } public String getCover_ur() { return cover_ur; } public void setCover_ur(String cover_ur) { this.cover_ur = cover_ur; } public String getContent_url() { return content_url; } public void setContent_url(String content_url) { this.content_url = content_url; } public String getSource_url() { return source_url; } public void setSource_url(String source_url) { this.source_url = source_url; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/model/SendMessageReport.java
src/main/java/org/jeewx/api/wxsendmsg/model/SendMessageReport.java
package org.jeewx.api.wxsendmsg.model; public class SendMessageReport { /** 公众号的微信号 */ private String ToUserName; /** 公众号群发助手的微信号,为mphelper */ private String FromUserName; /** 创建时间的时间戳 */ private String CreateTime; /** 消息类型,此处为event */ private String MsgType; /** 事件信息,此处为MASSSENDJOBFINISH */ private String Event; /** 群发的消息ID */ private String MsgID; /** * 群发的结构,为“send success”或“send fail”或“err(num)”。但send * success时,也有可能因用户拒收公众号的消息、系统错误等原因造成少量用户接收失败。err(num)是审核失败的具体原因,可能的情况如下: * err(10001), //涉嫌广告 err(20001), //涉嫌政治 err(20004), //涉嫌社会 err(20002), * //涉嫌色情 err(20006), //涉嫌违法犯罪 err(20008), //涉嫌欺诈 err(20013), //涉嫌版权 * err(22000), //涉嫌互推(互相宣传) err(21000), //涉嫌其他 */ private String Status; public String getToUserName() { return ToUserName; } public void setToUserName(String toUserName) { ToUserName = toUserName; } public String getFromUserName() { return FromUserName; } public void setFromUserName(String fromUserName) { FromUserName = fromUserName; } public String getCreateTime() { return CreateTime; } public void setCreateTime(String createTime) { CreateTime = createTime; } public String getMsgType() { return MsgType; } public void setMsgType(String msgType) { MsgType = msgType; } public String getEvent() { return Event; } public void setEvent(String event) { Event = event; } public String getMsgID() { return MsgID; } public void setMsgID(String msgID) { MsgID = msgID; } public String getStatus() { return Status; } public void setStatus(String status) { Status = status; } @Override public String toString() { return "SendMessageReport [ToUserName=" + ToUserName + ", FromUserName=" + FromUserName + ", CreateTime=" + CreateTime + ", MsgType=" + MsgType + ", Event=" + Event + ", MsgID=" + MsgID + ", Status=" + Status + "]"; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/model/auto/AutoReplyInfoRule.java
src/main/java/org/jeewx/api/wxsendmsg/model/auto/AutoReplyInfoRule.java
package org.jeewx.api.wxsendmsg.model.auto; import java.util.List; /** * 自动回复规则配置 * @author superuser * */ public class AutoReplyInfoRule { /** 关注后自动回复是否开启,0代表未开启,1代表开启 */ private String is_add_friend_reply_open; /** 消息自动回复是否开启,0代表未开启,1代表开启 */ private String is_autoreply_open; /** 关注后自动回复的信息 */ private AutoReplyInfo add_friend_autoreply_info; /** 消息自动回复的信息 */ private AutoReplyInfo message_default_autoreply_info; /** 关键词自动回复的信息 */ private List<KeyWordAutoReplyInfo> keyword_autoreply_info; public String getIs_add_friend_reply_open() { return is_add_friend_reply_open; } public void setIs_add_friend_reply_open(String is_add_friend_reply_open) { this.is_add_friend_reply_open = is_add_friend_reply_open; } public String getIs_autoreply_open() { return is_autoreply_open; } public void setIs_autoreply_open(String is_autoreply_open) { this.is_autoreply_open = is_autoreply_open; } public AutoReplyInfo getAdd_friend_autoreply_info() { return add_friend_autoreply_info; } public void setAdd_friend_autoreply_info(AutoReplyInfo add_friend_autoreply_info) { this.add_friend_autoreply_info = add_friend_autoreply_info; } public AutoReplyInfo getMessage_default_autoreply_info() { return message_default_autoreply_info; } public void setMessage_default_autoreply_info( AutoReplyInfo message_default_autoreply_info) { this.message_default_autoreply_info = message_default_autoreply_info; } public List<KeyWordAutoReplyInfo> getKeyword_autoreply_info() { return keyword_autoreply_info; } public void setKeyword_autoreply_info(List<KeyWordAutoReplyInfo> keyword_autoreply_info) { this.keyword_autoreply_info = keyword_autoreply_info; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/model/auto/KeywordListInfo.java
src/main/java/org/jeewx/api/wxsendmsg/model/auto/KeywordListInfo.java
package org.jeewx.api.wxsendmsg.model.auto; public class KeywordListInfo extends AutoReplyInfo{ /** 匹配模式,contain代表消息中含有该关键词即可,equal表示消息内容必须和关键词严格相同 */ private String match_mode; public String getMatch_mode() { return match_mode; } public void setMatch_mode(String match_mode) { this.match_mode = match_mode; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/model/auto/KeyWordAutoReplyInfo.java
src/main/java/org/jeewx/api/wxsendmsg/model/auto/KeyWordAutoReplyInfo.java
package org.jeewx.api.wxsendmsg.model.auto; import java.util.List; /** * 关键字信息 * @author superuser * */ public class KeyWordAutoReplyInfo { /** 规则名称 */ private String rule_name; /** 创建时间 */ private String create_time; /** 回复模式,reply_all代表全部回复,random_one代表随机回复其中一条 */ private String reply_mode; /** 匹配的关键词列表 */ private List<KeywordListInfo> keyword_list_info; /** 关键字回复内容 */ private List<ReplyListInfo> reply_list_info; public String getRule_name() { return rule_name; } public void setRule_name(String rule_name) { this.rule_name = rule_name; } public String getCreate_time() { return create_time; } public void setCreate_time(String create_time) { this.create_time = create_time; } public String getReply_mode() { return reply_mode; } public void setReply_mode(String reply_mode) { this.reply_mode = reply_mode; } public List<KeywordListInfo> getKeyword_list_info() { return keyword_list_info; } public void setKeyword_list_info(List<KeywordListInfo> keyword_list_info) { this.keyword_list_info = keyword_list_info; } public List<ReplyListInfo> getReply_list_info() { return reply_list_info; } public void setReply_list_info(List<ReplyListInfo> reply_list_info) { this.reply_list_info = reply_list_info; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/model/auto/ReplyListInfo.java
src/main/java/org/jeewx/api/wxsendmsg/model/auto/ReplyListInfo.java
package org.jeewx.api.wxsendmsg.model.auto; import java.util.List; import org.jeewx.api.wxsendmsg.model.WxArticleConfig; /** * 关键字回复内容 * @author luobaoli * */ public class ReplyListInfo extends AutoReplyInfo { /** 回复信息 */ private List<WxArticleConfig> news_info; public List<WxArticleConfig> getNews_info() { return news_info; } public void setNews_info(List<WxArticleConfig> news_info) { this.news_info = news_info; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxsendmsg/model/auto/AutoReplyInfo.java
src/main/java/org/jeewx/api/wxsendmsg/model/auto/AutoReplyInfo.java
package org.jeewx.api.wxsendmsg.model.auto; public class AutoReplyInfo { /** 自动回复的类型。关注后自动回复和消息自动回复的类型仅支持文本(text)、图片(img)、语音(voice)、视频(video),关键词自动回复则还多了图文消息(news) */ private String type; /** 对于文本类型,content是文本内容,对于图文、图片、语音、视频类型,content是mediaID */ private String content; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxaccount/JwAccountAPI.java
src/main/java/org/jeewx/api/wxaccount/JwAccountAPI.java
package org.jeewx.api.wxaccount; import com.alibaba.fastjson.JSONObject; import org.jeewx.api.core.exception.WexinReqException; import org.jeewx.api.core.req.WeiXinReqService; import org.jeewx.api.core.req.model.account.QrcodeActionInfo; import org.jeewx.api.core.req.model.account.QrcodeCreate; import org.jeewx.api.core.req.model.account.QrcodeScene; import org.jeewx.api.core.req.model.account.ShortUrlCreate; import org.jeewx.api.core.util.WeiXinConstant; import org.jeewx.api.wxaccount.model.WxQrcode; /** * 微信--生成二维码和长短链接切换 * * @author lizr * */ public class JwAccountAPI { /** * 二维码类型,QR_SCENE为临时, QR_LIMIT_SCENE为永久, QR_LIMIT_STR_SCENE为永久的字符串参数值 */ public static final String QRCODE_TYPE_SCENE = "QR_SCENE"; public static final String QRCODE_TYPE_LIMIT = "QR_LIMIT_SCENE"; public static final String QRCODE_TYPE_LIMIT_STR = "QR_LIMIT_STR_SCENE"; /** * 代表长链接转短链接 */ public static final String SHORT_URL_ACTION = "long2short"; /** * * expire_seconds 该二维码有效时间,以秒为单位。 最大不超过1800。 action_name 二维码类型,QR_SCENE为临时,QR_LIMIT_SCENE为永久,QR_LIMIT_STR_SCENE为永久的字符串参数值 action_info 二维码详细信息 scene_id 场景值ID,临时二维码时为32位非0整型,永久二维码时最大值为100000(目前参数只支持1--100000) scene_str 场景值ID(字符串形式的ID),字符串类型,长度限制为1到64,仅永久二维码支持此字段 * @param accessToken * @param scene_str * @param action_name * @param expire_seconds * @return * @throws WexinReqException */ public static WxQrcode createQrcode(String accessToken, String scene_str, String action_name, String expire_seconds) throws WexinReqException { QrcodeCreate qrcodeCreate = new QrcodeCreate(); qrcodeCreate.setAccess_token(accessToken); QrcodeActionInfo q = new QrcodeActionInfo(); QrcodeScene ss = new QrcodeScene(); ss.setScene_str(scene_str); q.setScene(ss); qrcodeCreate.setAction_info(q); qrcodeCreate.setExpire_seconds(expire_seconds); qrcodeCreate.setAction_name(action_name); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(qrcodeCreate); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); WxQrcode wxQrcode = null; wxQrcode = (WxQrcode) JSONObject.toJavaObject(result, WxQrcode.class); return wxQrcode; } /** * 获取短链接信息 * @param accessToken * @param longUrl * @return * @throws WexinReqException */ public static String getShortUrl(String accessToken,String longUrl) throws WexinReqException{ ShortUrlCreate uc = new ShortUrlCreate(); uc.setAccess_token(accessToken); uc.setLong_url(longUrl); uc.setAction(SHORT_URL_ACTION); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(uc); Object error = result.get("short_url"); String shortUrl = ""; if (error != null) { shortUrl = result.getString("short_url"); }else{ shortUrl = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); } return shortUrl; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxaccount/model/WxQrcode.java
src/main/java/org/jeewx/api/wxaccount/model/WxQrcode.java
package org.jeewx.api.wxaccount.model; public class WxQrcode { private String ticket; private String expire_seconds; private String url; public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getExpire_seconds() { return expire_seconds; } public void setExpire_seconds(String expire_seconds) { this.expire_seconds = expire_seconds; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxmenu/JwPersonalizedMenuAPI.java
src/main/java/org/jeewx/api/wxmenu/JwPersonalizedMenuAPI.java
package org.jeewx.api.wxmenu; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.jeewx.api.core.common.WxstoreUtils; import org.jeewx.api.core.req.model.menu.PersonalizedMenu; import org.jeewx.api.core.req.model.menu.WeixinButton; import org.jeewx.api.core.req.model.menu.WeixinMenuMatchrule; import org.jeewx.api.core.util.WeiXinConstant; import java.util.ArrayList; import java.util.List; /** * 微信个性化菜单--menu * * @author pit * */ public class JwPersonalizedMenuAPI { // 创建菜单 private static String create_menu = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=ACCESS_TOKEN"; // 删除个性化菜单 private static String delete_menu = "https://api.weixin.qq.com/cgi-bin/menu/delconditional?access_token=ACCESS_TOKEN"; // 测试个性化菜单匹配结果 private static String test_matchrule = "https://api.weixin.qq.com/cgi-bin/menu/trymatch?access_token=ACCESS_TOKEN"; /** * 创建个性化菜单 * button 是 一级菜单数组,个数应为1~3个 sub_button 否 二级菜单数组,个数应为1~5个 type 是 菜单的响应动作类型 name 是 菜单标题,不超过16个字节,子菜单不超过40个字节 key click等点击类型必须 菜单KEY值,用于消息接口推送,不超过128字节 url view类型必须 网页链接,用户点击菜单可打开链接,不超过256字节 matchrule 是 菜单匹配规则 group_id 否 用户分组id,可通过用户分组管理接口获取 sex 否 性别:男(1)女(2),不填则不做匹配 client_platform_type 否 客户端版本,当前只具体到系统型号:IOS(1), Android(2),Others(3),不填则不做匹配 country 否 国家信息,是用户在微信中设置的地区,具体请参考地区信息表 province 否 省份信息,是用户在微信中设置的地区,具体请参考地区信息表 city 否 城市信息,是用户在微信中设置的地区,具体请参考地区信息表 language 否 语言信息,是用户在微信中设置的语言,具体请参考语言表: 1、简体中文 "zh_CN" 2、繁体中文TW "zh_TW" 3、繁体中文HK "zh_HK" 4、英文 "en" 5、印尼 "id" 6、马来 "ms" 7、西班牙 "es" 8、韩国 "ko" 9、意大利 "it" 10、日本 "ja" 11、波兰 "pl" 12、葡萄牙 "pt" 13、俄国 "ru" 14、泰文 "th" 15、越南 "vi" 16、阿拉伯语 "ar" 17、北印度 "hi" 18、希伯来 "he" 19、土耳其 "tr" 20、德语 "de" 21、法语 "fr" * @param accessToken * @param menu 的json字符串 * @return menuid */ public static String createMenu(String accessToken,PersonalizedMenu menu){ String msg = ""; if (accessToken != null) { String requestUrl = create_menu.replace("ACCESS_TOKEN", accessToken); JSONObject obj = JSONObject.parseObject(JSON.toJSONString(menu)); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); if(error == null){ msg = result.getString("menuid"); }else{ msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); } } return msg; }//402676956 /** * 删除个性化菜单 * @param accessToken * @return errormsg */ public static String deleteMenu(String accessToken,Integer menu_id){ String msg = ""; if (accessToken != null) { String requestUrl = delete_menu.replace("ACCESS_TOKEN", accessToken); String json = "{\"menuid\": "+menu_id+"}"; JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", json); //Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); } return msg; } /** * 测试个性化菜单匹配结果 * @param accessToken * @param user_id user_id可以是粉丝的OpenID,也可以是粉丝的微信号。 * @return */ public static List<WeixinButton> testMatchrule(String accessToken,String user_id){ if (accessToken != null) { String requestUrl = test_matchrule.replace("ACCESS_TOKEN", accessToken); String json = "{\"user_id\": \""+user_id+"\"}"; JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", json); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); if(error == null){ JSONObject menu = result.getJSONObject("menu"); JSONArray button = menu.getJSONArray("button"); List<WeixinButton> btns = (List<WeixinButton>)button.toJavaObject(List.class); return btns; } } return null; } public static void main(String[] args) { WeixinMenuMatchrule matchrule = new WeixinMenuMatchrule(); matchrule.setSex("1"); List<WeixinButton> testsUb = new ArrayList<WeixinButton>(); WeixinButton w = new WeixinButton(); w.setName("测试菜单"); w.setType("click"); w.setKey("V1001_TODAY_MUSIC"); testsUb.add(w); PersonalizedMenu menu = new PersonalizedMenu(); menu.setButton(testsUb); menu.setMatchrule(matchrule); String s = JwPersonalizedMenuAPI.createMenu("UpIJXAUIzENJnR9WDD3kxCErxtxnFHVT_Sd3kHmtiauJwUi2PU6u5YFUHgKibd2_wDBlR6xjmHzXfO5zvYEV9ljeJGrwCZOcokZOXpiu6V1gjEf4oOzMUliKFYUdukJzNBEiABAIWZ",menu); List<WeixinButton> s3 = JwPersonalizedMenuAPI.testMatchrule("UpIJXAUIzENJnR9WDD3kxCErxtxnFHVT_Sd3kHmtiauJwUi2PU6u5YFUHgKibd2_wDBlR6xjmHzXfO5zvYEV9ljeJGrwCZOcokZOXpiu6V1gjEf4oOzMUliKFYUdukJzNBEiABAIWZ","oGCDRjooOuBCr7MM0cs1-KqAh_aU"); System.out.println(s); System.out.println(s3); } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
jeecgboot/weixin4j
https://github.com/jeecgboot/weixin4j/blob/9a0a503cc99e24c77de671890fae15ee3235669f/src/main/java/org/jeewx/api/wxmenu/JwMenuAPI.java
src/main/java/org/jeewx/api/wxmenu/JwMenuAPI.java
package org.jeewx.api.wxmenu; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SimplePropertyPreFilter; import org.jeewx.api.core.exception.WexinReqException; import org.jeewx.api.core.req.WeiXinReqService; import org.jeewx.api.core.req.model.menu.*; import org.jeewx.api.core.req.model.menu.config.CustomWeixinButtonConfig; import org.jeewx.api.core.req.model.menu.config.WeixinButtonExtend; import org.jeewx.api.core.util.WeiXinConstant; import org.jeewx.api.extend.CustomJsonConfig; import org.jeewx.api.wxsendmsg.model.WxArticleConfig; import java.util.ArrayList; import java.util.List; /** * 微信--menu * * @author lizr * */ public class JwMenuAPI { /** * 创建菜单 * button 是 一级菜单数组,个数应为1~3个 sub_button 否 二级菜单数组,个数应为1~5个 type 是 菜单的响应动作类型 name 是 菜单标题,不超过16个字节,子菜单不超过40个字节 key click等点击类型必须 菜单KEY值,用于消息接口推送,不超过128字节 url view类型必须 网页链接,用户点击菜单可打开链接,不超过256字节 appid 小程序appid ,在创建小程序菜单时候用到 pagepath 小程序的页面路径,在创建小程序菜单时候用到 * @param accessToken * @param button 的json字符串 * @throws WexinReqException */ public static String createMenu(String accessToken,List<WeixinButton> button) throws WexinReqException{ MenuCreate m = new MenuCreate(); m.setAccess_token(accessToken); m.setButton(button); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(m); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); String msg = ""; if(error == null){ msg = result.getString("groupid"); }else{ msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); } return msg; } /** * 获取所有的菜单 * @param accessToken * @return * @throws WexinReqException */ public static List<WeixinButton> getAllMenu(String accessToken) throws WexinReqException{ MenuGet g = new MenuGet(); g.setAccess_token(accessToken); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(g); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); List<WeixinButton> lstButton = null; JSONObject menu = result.getJSONObject("menu"); JSONArray buttons = menu.getJSONArray("button"); JSONArray subButtons = null; lstButton = new ArrayList<WeixinButton>(); WeixinButton btn = null; WeixinButton subBtn = null; List<WeixinButton> lstSubButton = null; for (int i = 0; i < buttons.size(); i++) { btn = (WeixinButton) JSONObject.toJavaObject(buttons.getJSONObject(i), WeixinButton.class); subButtons = buttons.getJSONObject(i).getJSONArray("sub_button"); if (subButtons != null) { lstSubButton = new ArrayList<WeixinButton>(); for (int j = 0; j < subButtons.size(); j++) { subBtn = (WeixinButton) JSONObject.toJavaObject( subButtons.getJSONObject(j), WeixinButton.class); lstSubButton.add(subBtn); } btn.setSub_button(lstSubButton); } lstButton.add(btn); } return lstButton; } /** * 删除所有的菜单 * @param accessToken * @return * @throws WexinReqException */ public static String deleteMenu(String accessToken) throws WexinReqException{ MenuDelete m = new MenuDelete(); m.setAccess_token(accessToken); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(m); String msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG); return msg; } //update-begin--Author:luobaoli Date:20150714 for:增加“获取自定义菜单配置接口”功能接口 //update-begin--Author:luobaoli Date:20150715 for:优化该方法的处理逻辑 /** * 获取自定义接口配置 * @param accessToken * @return * @throws WexinReqException */ public static CustomWeixinButtonConfig getAllMenuConfigure(String accessToken) throws WexinReqException{ MenuConfigureGet cmcg = new MenuConfigureGet(); cmcg.setAccess_token(accessToken); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(cmcg); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); // CustomWeixinButtonConfig customWeixinButtonConfig = (CustomWeixinButtonConfig) JSONObject.toJavaObject(result, new CustomJsonConfig(CustomWeixinButtonConfig.class,"selfmenu_info")); SimplePropertyPreFilter selfMenuFilter = new SimplePropertyPreFilter(); selfMenuFilter.getExcludes().add("selfmenu_info"); CustomWeixinButtonConfig customWeixinButtonConfig = JSONObject.parseObject(JSONObject.toJSONString(result, selfMenuFilter), CustomWeixinButtonConfig.class); JSONObject selfmenuInfo = result.getJSONObject("selfmenu_info"); if(selfmenuInfo!=null && !selfmenuInfo.isEmpty()){ /**处理父类菜单 */ JSONArray buttons = selfmenuInfo.getJSONArray("button"); List<WeixinButtonExtend> listButton = new ArrayList<WeixinButtonExtend>(); for(int i=0;i<buttons.size();i++){ // WeixinButtonExtend weixinButtonExtend = (WeixinButtonExtend) JSONObject.toJavaObject(buttons.getJSONObject(i),new CustomJsonConfig(WeixinButtonExtend.class,"sub_button")); SimplePropertyPreFilter subButtongFilter = new SimplePropertyPreFilter(); subButtongFilter.getExcludes().add("sub_button"); WeixinButtonExtend weixinButtonExtend = JSONObject.parseObject(JSONObject.toJSONString(buttons.getJSONObject(i), subButtongFilter), WeixinButtonExtend.class); /**处理子类菜单 */ JSONObject subButtonJsonObj = buttons.getJSONObject(i).getJSONObject("sub_button"); if(subButtonJsonObj!=null && !subButtonJsonObj.isEmpty()){ JSONArray subButtons = subButtonJsonObj.getJSONArray("list"); if (subButtons != null) { List<WeixinButtonExtend> listSubButton = new ArrayList<WeixinButtonExtend>(); for (int j = 0; j < subButtons.size(); j++) { // WeixinButtonExtend subBtn = (WeixinButtonExtend) JSONObject.toJavaObject(subButtons.getJSONObject(j), new CustomJsonConfig(WeixinButtonExtend.class,"news_info")); SimplePropertyPreFilter newsInfoFilter = new SimplePropertyPreFilter(); newsInfoFilter.getExcludes().add("news_info"); WeixinButtonExtend subBtn = JSONObject.parseObject(JSONObject.toJSONString(subButtons.getJSONObject(j), newsInfoFilter), WeixinButtonExtend.class); /**处理菜单关联的图文消息 */ JSONObject newsInfoJsonObj = subButtons.getJSONObject(j).getJSONObject("news_info"); if(newsInfoJsonObj!=null && !newsInfoJsonObj.isEmpty()){ JSONArray newsInfos = newsInfoJsonObj.getJSONArray("list"); List<WxArticleConfig> listNewsInfo = new ArrayList<WxArticleConfig>(); for (int k = 0; k < newsInfos.size(); k++) { WxArticleConfig wxArticleConfig = (WxArticleConfig) JSONObject.toJavaObject(newsInfos.getJSONObject(k), WxArticleConfig.class); listNewsInfo.add(wxArticleConfig); } subBtn.setNews_info(listNewsInfo); } listSubButton.add(subBtn); } weixinButtonExtend.setSub_button(listSubButton); } } listButton.add(weixinButtonExtend); } customWeixinButtonConfig.setSelfmenu_info(listButton); } return customWeixinButtonConfig; } //update-end--Author:luobaoli Date:20150715 for:优化该方法的处理逻辑 //update-end--Author:luobaoli Date:20150714 for:增加“获取自定义菜单配置接口”功能接口 public static void main(String[] args){ String s=""; try { s = "3DGIfJqqupzTPxvq_P-0ATDC2MDjFLqaz8S41SPmRIqLaA3PSb8FgN_PuhpZ5jEB4D6w7ZNeX3gbC3CfSOAz2wt4DxVKi2HD5BCjoecrB0Q"; // s = JwTokenAPI.getAccessToken("wx00737224cb9dbc7d","b9479ebdb58d1c6b6efd4171ebe718b5"); // s = JwTokenAPI.getAccessToken("wx298c4cc7312063df","fbf8cebf983c931bd7c1bee1498f8605"); System.out.println(s); // WeixinButton button = new WeixinButton(); CustomWeixinButtonConfig cb = JwMenuAPI.getAllMenuConfigure(s); // for(WeixinButton bb : b){ // System.out.println(bb.toString()); // } // List<WeixinButton> sub_button = new ArrayList<WeixinButton>(); // List<WeixinButton> testsUb = new ArrayList<WeixinButton>(); // WeixinButton w = new WeixinButton(); // w.setName("测试菜单"); // testsUb.add(w); // // WeixinButton w1 = new WeixinButton(); // /* // "type": "scancode_waitmsg", // "name": "扫码带提示", // "key": "rselfmenu_0_0", // */ // w1.setName("测试sub菜单"); // w1.setKey("rselfmenu_0_0"); // w1.setType("scancode_waitmsg"); // sub_button.add(w1); // w.setSub_button(sub_button); // // // //s = getMenuButtonJson("button",b); // /*Gson gson = new Gson(); // System.out.println(json);*/ // s= JwMenuAPI.createMenu(s,testsUb); // System.out.println(s); } catch (WexinReqException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
java
Apache-2.0
9a0a503cc99e24c77de671890fae15ee3235669f
2026-01-05T02:41:50.789942Z
false
memento/GeneticAlgorithm
https://github.com/memento/GeneticAlgorithm/blob/c61bf2adcc9bc0bd67092bf5c5f365cb27b7155e/src/fr/dieul/lab/geneticalgorithm/SimpleDemoGA.java
src/fr/dieul/lab/geneticalgorithm/SimpleDemoGA.java
package fr.dieul.lab.geneticalgorithm; import java.util.Random; import fr.dieul.lab.geneticalgorithm.model.Individual; import fr.dieul.lab.geneticalgorithm.model.Population; public class SimpleDemoGA { private Population population; private Individual fittest; private Individual secondFittest; private int generationCount; private static int numberOfGenes; private static int numberOfIndividuals; private static boolean verbose; private static boolean coloredGenes; public SimpleDemoGA() { this.population = new Population(numberOfIndividuals, numberOfGenes); this.generationCount = 0; } public static void main(String[] args) { Random rn = new Random(); //Set parameters here //Number of genes each individual has numberOfGenes = 20; //Number of individuals numberOfIndividuals = 5; //Verbosity (e.g. Should we print genetic pool in the console?) verbose = true; //Apply color to genes (if verbose = true) Note: this will slow down the process coloredGenes = true; //=================== //Initialize population SimpleDemoGA demo = new SimpleDemoGA(); demo.population = new Population(numberOfIndividuals, numberOfGenes); System.out.println("Population of "+demo.population.getPopSize()+" individual(s)."); //Calculate fitness of each individual demo.population.calculateFitness(); System.out.println("\nGeneration: " + demo.generationCount + " Fittest: " + demo.population.getFittestScore()); //show genetic pool showGeneticPool(demo.population.getIndividuals()); //While population gets an individual with maximum fitness while (demo.population.getFittestScore() < numberOfGenes) { ++demo.generationCount; //Do selection demo.selection(); //Do crossover demo.crossover(); //Do mutation under a random probability if (rn.nextInt()%7 < 5) { demo.mutation(); } //Add fittest offspring to population demo.addFittestOffspring(); //Calculate new fitness value demo.population.calculateFitness(); System.out.println("\nGeneration: " + demo.generationCount + " Fittest score: " + demo.population.getFittestScore()); //show genetic pool showGeneticPool(demo.population.getIndividuals()); } System.out.println("\nSolution found in generation " + demo.generationCount); System.out.println("Index of winner Individual: "+demo.population.getFittestIndex()); System.out.println("Fitness: "+demo.population.getFittestScore()); System.out.print("Genes: "); for (int i = 0; i < numberOfGenes; i++) { System.out.print(demo.population.selectFittest().getGenes()[i]); } System.out.println(""); } //Selection void selection() { //Select the most fittest individual fittest = population.selectFittest(); //Select the second most fittest individual secondFittest = population.selectSecondFittest(); } //Crossover void crossover() { Random rn = new Random(); //Select a random crossover point int crossOverPoint = rn.nextInt(this.numberOfGenes); //Swap values among parents for (int i = 0; i < crossOverPoint; i++) { int temp = fittest.getGenes()[i]; fittest.getGenes()[i] = secondFittest.getGenes()[i]; secondFittest.getGenes()[i] = temp; } } //Mutation void mutation() { Random rn = new Random(); //Select a random mutation point int mutationPoint = rn.nextInt(this.numberOfGenes); //Flip values at the mutation point if (fittest.getGenes()[mutationPoint] == 0) { fittest.getGenes()[mutationPoint] = 1; } else { fittest.getGenes()[mutationPoint] = 0; } mutationPoint = rn.nextInt(this.numberOfGenes); if (secondFittest.getGenes()[mutationPoint] == 0) { secondFittest.getGenes()[mutationPoint] = 1; } else { secondFittest.getGenes()[mutationPoint] = 0; } } //Get fittest offspring Individual getFittestOffspring() { if (fittest.getFitness() > secondFittest.getFitness()) { return fittest; } return secondFittest; } //Replace least fittest individual from most fittest offspring void addFittestOffspring() { //Update fitness values of offspring fittest.calcFitness(); secondFittest.calcFitness(); //Get index of least fit individual int leastFittestIndex = population.getLeastFittestIndex(); //Replace least fittest individual from most fittest offspring population.getIndividuals()[leastFittestIndex] = getFittestOffspring(); } //show genetic state of the population pool static void showGeneticPool(Individual[] individuals) { if(!verbose) return; System.out.println("==Genetic Pool=="); int increment=0; for (Individual individual:individuals) { System.out.println("> Individual "+increment+" | "+(coloredGenes?individual.toStringColor():individual.toString())+" |"); increment++; } System.out.println("================"); } }
java
Apache-2.0
c61bf2adcc9bc0bd67092bf5c5f365cb27b7155e
2026-01-05T02:42:28.208385Z
false
memento/GeneticAlgorithm
https://github.com/memento/GeneticAlgorithm/blob/c61bf2adcc9bc0bd67092bf5c5f365cb27b7155e/src/fr/dieul/lab/geneticalgorithm/util/ConsoleColors.java
src/fr/dieul/lab/geneticalgorithm/util/ConsoleColors.java
package fr.dieul.lab.geneticalgorithm.util; public class ConsoleColors { // Reset public static final String RESET = "\033[0m"; // Text Reset // Regular Colors public static final String BLACK = "\033[0;30m"; // BLACK public static final String RED = "\033[0;31m"; // RED public static final String GREEN = "\033[0;32m"; // GREEN public static final String YELLOW = "\033[0;33m"; // YELLOW public static final String BLUE = "\033[0;34m"; // BLUE public static final String PURPLE = "\033[0;35m"; // PURPLE public static final String CYAN = "\033[0;36m"; // CYAN public static final String WHITE = "\033[0;37m"; // WHITE // Bold public static final String BLACK_BOLD = "\033[1;30m"; // BLACK public static final String RED_BOLD = "\033[1;31m"; // RED public static final String GREEN_BOLD = "\033[1;32m"; // GREEN public static final String YELLOW_BOLD = "\033[1;33m"; // YELLOW public static final String BLUE_BOLD = "\033[1;34m"; // BLUE public static final String PURPLE_BOLD = "\033[1;35m"; // PURPLE public static final String CYAN_BOLD = "\033[1;36m"; // CYAN public static final String WHITE_BOLD = "\033[1;37m"; // WHITE // Underline public static final String BLACK_UNDERLINED = "\033[4;30m"; // BLACK public static final String RED_UNDERLINED = "\033[4;31m"; // RED public static final String GREEN_UNDERLINED = "\033[4;32m"; // GREEN public static final String YELLOW_UNDERLINED = "\033[4;33m"; // YELLOW public static final String BLUE_UNDERLINED = "\033[4;34m"; // BLUE public static final String PURPLE_UNDERLINED = "\033[4;35m"; // PURPLE public static final String CYAN_UNDERLINED = "\033[4;36m"; // CYAN public static final String WHITE_UNDERLINED = "\033[4;37m"; // WHITE // Background public static final String BLACK_BACKGROUND = "\033[40m"; // BLACK public static final String RED_BACKGROUND = "\033[41m"; // RED public static final String GREEN_BACKGROUND = "\033[42m"; // GREEN public static final String YELLOW_BACKGROUND = "\033[43m"; // YELLOW public static final String BLUE_BACKGROUND = "\033[44m"; // BLUE public static final String PURPLE_BACKGROUND = "\033[45m"; // PURPLE public static final String CYAN_BACKGROUND = "\033[46m"; // CYAN public static final String WHITE_BACKGROUND = "\033[47m"; // WHITE // High Intensity public static final String BLACK_BRIGHT = "\033[0;90m"; // BLACK public static final String RED_BRIGHT = "\033[0;91m"; // RED public static final String GREEN_BRIGHT = "\033[0;92m"; // GREEN public static final String YELLOW_BRIGHT = "\033[0;93m"; // YELLOW public static final String BLUE_BRIGHT = "\033[0;94m"; // BLUE public static final String PURPLE_BRIGHT = "\033[0;95m"; // PURPLE public static final String CYAN_BRIGHT = "\033[0;96m"; // CYAN public static final String WHITE_BRIGHT = "\033[0;97m"; // WHITE // Bold High Intensity public static final String BLACK_BOLD_BRIGHT = "\033[1;90m"; // BLACK public static final String RED_BOLD_BRIGHT = "\033[1;91m"; // RED public static final String GREEN_BOLD_BRIGHT = "\033[1;92m"; // GREEN public static final String YELLOW_BOLD_BRIGHT = "\033[1;93m";// YELLOW public static final String BLUE_BOLD_BRIGHT = "\033[1;94m"; // BLUE public static final String PURPLE_BOLD_BRIGHT = "\033[1;95m";// PURPLE public static final String CYAN_BOLD_BRIGHT = "\033[1;96m"; // CYAN public static final String WHITE_BOLD_BRIGHT = "\033[1;97m"; // WHITE // High Intensity backgrounds public static final String BLACK_BACKGROUND_BRIGHT = "\033[0;100m";// BLACK public static final String RED_BACKGROUND_BRIGHT = "\033[0;101m";// RED public static final String GREEN_BACKGROUND_BRIGHT = "\033[0;102m";// GREEN public static final String YELLOW_BACKGROUND_BRIGHT = "\033[0;103m";// YELLOW public static final String BLUE_BACKGROUND_BRIGHT = "\033[0;104m";// BLUE public static final String PURPLE_BACKGROUND_BRIGHT = "\033[0;105m"; // PURPLE public static final String CYAN_BACKGROUND_BRIGHT = "\033[0;106m"; // CYAN public static final String WHITE_BACKGROUND_BRIGHT = "\033[0;107m"; // WHITE }
java
Apache-2.0
c61bf2adcc9bc0bd67092bf5c5f365cb27b7155e
2026-01-05T02:42:28.208385Z
false
memento/GeneticAlgorithm
https://github.com/memento/GeneticAlgorithm/blob/c61bf2adcc9bc0bd67092bf5c5f365cb27b7155e/src/fr/dieul/lab/geneticalgorithm/util/package-info.java
src/fr/dieul/lab/geneticalgorithm/util/package-info.java
package fr.dieul.lab.geneticalgorithm.util; /* This package should contain all utility classes, that bring some features to the application but no business value*/
java
Apache-2.0
c61bf2adcc9bc0bd67092bf5c5f365cb27b7155e
2026-01-05T02:42:28.208385Z
false
memento/GeneticAlgorithm
https://github.com/memento/GeneticAlgorithm/blob/c61bf2adcc9bc0bd67092bf5c5f365cb27b7155e/src/fr/dieul/lab/geneticalgorithm/model/package-info.java
src/fr/dieul/lab/geneticalgorithm/model/package-info.java
package fr.dieul.lab.geneticalgorithm.model; /* This package should contain all the model/business classes such as Population, Individual*/
java
Apache-2.0
c61bf2adcc9bc0bd67092bf5c5f365cb27b7155e
2026-01-05T02:42:28.208385Z
false
memento/GeneticAlgorithm
https://github.com/memento/GeneticAlgorithm/blob/c61bf2adcc9bc0bd67092bf5c5f365cb27b7155e/src/fr/dieul/lab/geneticalgorithm/model/Individual.java
src/fr/dieul/lab/geneticalgorithm/model/Individual.java
package fr.dieul.lab.geneticalgorithm.model; import java.util.Arrays; import java.util.Random; import fr.dieul.lab.geneticalgorithm.util.ConsoleColors; //Individual class public class Individual implements Cloneable{ private int geneLength; private int fitness = 0; private int[] genes; public Individual(int geneLength) { //Initialization this.geneLength = geneLength; this.genes = new int[geneLength]; Random rn = new Random(); //Set genes randomly for each individual for (int i = 0; i < genes.length; i++) { genes[i] = Math.abs(rn.nextInt() % 2); } fitness = 0; } //Calculate fitness public void calcFitness() { fitness = 0; for (int i = 0; i < genes.length; i++) { if (genes[i] == 1) { ++fitness; } } } @Override protected Object clone() throws CloneNotSupportedException { Individual individual = (Individual)super.clone(); individual.genes = new int[geneLength]; for(int i = 0; i < individual.genes.length; i++){ individual.genes[i] = this.genes[i]; } return individual; } @Override public String toString() { //without colors return "[genes=" + Arrays.toString(genes) + "]"; } public String toStringColor() { //with colors String genesString = "[genes=["; int increment=0; for(int gene:genes) { //print gene if(gene == 0) genesString += ConsoleColors.BLACK_BOLD + ConsoleColors.RED_BACKGROUND_BRIGHT + gene + ConsoleColors.RESET; if(gene == 1) genesString += ConsoleColors.BLACK_BOLD + ConsoleColors.GREEN_BACKGROUND_BRIGHT + gene + ConsoleColors.RESET; //print comma if(increment<genes.length-1) genesString += ", "; increment++; } genesString += "]]"; return genesString; } //Getters and Setters public int getGeneLength() { return geneLength; } public void setGeneLength(int geneLength) { this.geneLength = geneLength; } public int getFitness() { return fitness; } public void setFitness(int fitness) { this.fitness = fitness; } public int[] getGenes() { return genes; } public void setGenes(int[] genes) { this.genes = genes; } }
java
Apache-2.0
c61bf2adcc9bc0bd67092bf5c5f365cb27b7155e
2026-01-05T02:42:28.208385Z
false
memento/GeneticAlgorithm
https://github.com/memento/GeneticAlgorithm/blob/c61bf2adcc9bc0bd67092bf5c5f365cb27b7155e/src/fr/dieul/lab/geneticalgorithm/model/Population.java
src/fr/dieul/lab/geneticalgorithm/model/Population.java
package fr.dieul.lab.geneticalgorithm.model; //Population class public class Population { private int popSize; private Individual[] individuals; private int geneLength; private int fittestScore = 0; /** * @purpose Initialize population * @param popSize is the population size * @param geneLength is the number of genes an individual will have */ public Population(int popSize, int geneLength) { super(); this.popSize = popSize; this.geneLength = geneLength; this.individuals = new Individual[popSize]; //Create a first population pool for (int i = 0; i < popSize; i++) { individuals[i] = new Individual(geneLength); } } //Get the fittest individual and update fittest score public Individual selectFittest() { int maxFit = Integer.MIN_VALUE; int maxFitIndex = 0; for (int i = 0; i < individuals.length; i++) { if (maxFit <= individuals[i].getFitness()) { maxFit = individuals[i].getFitness(); maxFitIndex = i; } } //update fittest score fittestScore = individuals[maxFitIndex].getFitness(); //try to return the fittest individual try { return (Individual) individuals[maxFitIndex].clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return null; } //Get the second most fittest individual public Individual selectSecondFittest() { int maxFit1 = 0; int maxFit2 = 0; for (int i = 0; i < individuals.length; i++) { if (individuals[i].getFitness() > individuals[maxFit1].getFitness()) { maxFit2 = maxFit1; maxFit1 = i; } else if (individuals[i].getFitness() > individuals[maxFit2].getFitness()) { maxFit2 = i; } } try { return (Individual) individuals[maxFit2].clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return null; } //Get index of least fittest individual public int getLeastFittestIndex() { int minFitVal = Integer.MAX_VALUE; int minFitIndex = 0; for (int i = 0; i < individuals.length; i++) { if (minFitVal >= individuals[i].getFitness()) { minFitVal = individuals[i].getFitness(); minFitIndex = i; } } return minFitIndex; } //Get index of the fittest individual public int getFittestIndex() { int maxFit = Integer.MIN_VALUE; int maxFitIndex = 0; for (int i = 0; i < individuals.length; i++) { if (maxFit <= individuals[i].getFitness()) { maxFit = individuals[i].getFitness(); maxFitIndex = i; } } return maxFitIndex; } //Calculate fitness of each individual public void calculateFitness() { for (int i = 0; i < individuals.length; i++) { individuals[i].calcFitness(); } selectFittest(); } //Getters and Setters public int getPopSize() { return popSize; } public void setPopSize(int popSize) { this.popSize = popSize; } public Individual[] getIndividuals() { return individuals; } public void setIndividuals(Individual[] individuals) { this.individuals = individuals; } public int getGeneLength() { return geneLength; } public void setGeneLength(int geneLength) { this.geneLength = geneLength; } public int getFittestScore() { return fittestScore; } public void setFittestScore(int fittestScore) { this.fittestScore = fittestScore; } }
java
Apache-2.0
c61bf2adcc9bc0bd67092bf5c5f365cb27b7155e
2026-01-05T02:42:28.208385Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/Main.java
tutorials/src/com/xoppa/blog/libgdx/Main.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx; import java.awt.BorderLayout; import java.awt.Container; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeSelectionModel; import javax.swing.tree.TreeSelectionModel; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.lwjgl.LwjglAWTCanvas; public class Main extends JFrame { private static final long serialVersionUID = -4296204662394260962L; public static String data; public static class AppDesc { public Class<? extends ApplicationListener> clazz; public String title; public int width; public int height; public String data; public AppDesc(String title, int width, int height, Class<? extends ApplicationListener> clazz, String data) { this.clazz = clazz; this.title = title; this.width = width; this.height = height; this.data = data; } public AppDesc(String title, int width, int height, Class<? extends ApplicationListener> clazz) { this(title, width, height, clazz, null); } @Override public String toString() { return title; } } public final static Object[] apps = { "Tutorials", new Object[] { "Basic 3D using libgdx", new AppDesc("step 1: render a cube", 640, 480, com.xoppa.blog.libgdx.g3d.basic3d.step1.Basic3DTest.class), new AppDesc("step 2: lights", 640, 480, com.xoppa.blog.libgdx.g3d.basic3d.step2.Basic3DTest.class), new AppDesc("step 3: camera controller", 640, 480, com.xoppa.blog.libgdx.g3d.basic3d.step3.Basic3DTest.class) }, new Object[] { "Load models using libgdx", new AppDesc("step 1: load a wavefrom model", 640, 480, com.xoppa.blog.libgdx.g3d.loadmodels.step1.LoadModelsTest.class, "loadmodels/data"), new AppDesc("step 2: use assetmanager", 640, 480, com.xoppa.blog.libgdx.g3d.loadmodels.step2.LoadModelsTest.class, "loadmodels/data"), new AppDesc("step 3: multiple instances", 640, 480, com.xoppa.blog.libgdx.g3d.loadmodels.step3.LoadModelsTest.class, "loadmodels/data"), new AppDesc("step 4: use fbx-conv", 640, 480, com.xoppa.blog.libgdx.g3d.loadmodels.step4.LoadModelsTest.class, "loadmodels/data") }, new Object[] { "Loading a scene using libgdx", new AppDesc("step 1: coding a scene", 640, 480, com.xoppa.blog.libgdx.g3d.loadscene.step1.LoadSceneTest.class, "loadscene/data"), new AppDesc("step 2: combining models", 640, 480, com.xoppa.blog.libgdx.g3d.loadscene.step2.LoadSceneTest.class, "loadscene/data"), new AppDesc("step 3: loading a modeled scene", 640, 480, com.xoppa.blog.libgdx.g3d.loadscene.step3.LoadSceneTest.class, "loadscene/data") }, new Object[] { "Behind the 3D scenes", new AppDesc("step 1: base code", 640, 480, com.xoppa.blog.libgdx.g3d.behindscenes.step1.BehindTheScenesTest.class, "behindscenes/data"), new AppDesc("step 2: using ModelLoader", 640, 480, com.xoppa.blog.libgdx.g3d.behindscenes.step2.BehindTheScenesTest.class, "behindscenes/data"), new AppDesc("step 3: change material by NodePart", 640, 480, com.xoppa.blog.libgdx.g3d.behindscenes.step3.BehindTheScenesTest.class, "behindscenes/data"), new AppDesc("step 4: change material by name", 640, 480, com.xoppa.blog.libgdx.g3d.behindscenes.step4.BehindTheScenesTest.class, "behindscenes/data"), new AppDesc("step 5: change material per ModelInstance", 640, 480, com.xoppa.blog.libgdx.g3d.behindscenes.step5.BehindTheScenesTest.class, "behindscenes/data"), new AppDesc("step 6: using a Renderable", 640, 480, com.xoppa.blog.libgdx.g3d.behindscenes.step6.BehindTheScenesTest.class, "behindscenes/data"), new AppDesc("step 7: using a Shader", 640, 480, com.xoppa.blog.libgdx.g3d.behindscenes.step7.BehindTheScenesTest.class, "behindscenes/data") }, new Object[] { "Creating a shader with libgdx", new AppDesc("step 1: render a sphere", 640, 480, com.xoppa.blog.libgdx.g3d.createshader.step1.ShaderTest.class, "createshader/data"), new AppDesc("step 2: render points", 640, 480, com.xoppa.blog.libgdx.g3d.createshader.step2.ShaderTest.class, "createshader/data"), new AppDesc("step 3: customize default shader", 640, 480, com.xoppa.blog.libgdx.g3d.createshader.step3.ShaderTest.class, "createshader/data"), new AppDesc("step 4: implement shader", 640, 480, com.xoppa.blog.libgdx.g3d.createshader.step4.ShaderTest.class, "createshader/data"), new AppDesc("step 5: enable depth test", 640, 480, com.xoppa.blog.libgdx.g3d.createshader.step5.ShaderTest.class, "createshader/data"), new AppDesc("step 6: cache uniform locations", 640, 480, com.xoppa.blog.libgdx.g3d.createshader.step6.ShaderTest.class, "createshader/data") }, new Object[] { "Using materials with libgdx", new AppDesc("step 1: using modelbatch", 640, 480, com.xoppa.blog.libgdx.g3d.usingmaterials.step1.MaterialTest.class, "usingmaterials/data"), new AppDesc("step 2: add a uniform", 640, 480, com.xoppa.blog.libgdx.g3d.usingmaterials.step2.MaterialTest.class, "usingmaterials/data"), new AppDesc("step 3: using userData", 640, 480, com.xoppa.blog.libgdx.g3d.usingmaterials.step3.MaterialTest.class, "usingmaterials/data"), new AppDesc("step 4: using ColorAttribute", 640, 480, com.xoppa.blog.libgdx.g3d.usingmaterials.step4.MaterialTest.class, "usingmaterials/data"), new AppDesc("step 5: implement canRender", 640, 480, com.xoppa.blog.libgdx.g3d.usingmaterials.step5.MaterialTest.class, "usingmaterials/data"), new AppDesc("step 6: add another color", 640, 480, com.xoppa.blog.libgdx.g3d.usingmaterials.step6.MaterialTest.class, "usingmaterials/data"), new AppDesc("step 7: use custom attribute", 640, 480, com.xoppa.blog.libgdx.g3d.usingmaterials.step7.MaterialTest.class, "usingmaterials/data"), new AppDesc("step 8: update canRender", 640, 480, com.xoppa.blog.libgdx.g3d.usingmaterials.step8.MaterialTest.class, "usingmaterials/data"), new AppDesc("step 9: create custom attribute", 640, 480, com.xoppa.blog.libgdx.g3d.usingmaterials.step9.MaterialTest.class, "usingmaterials/data") }, new Object[] { "3D Frustum culling", new AppDesc("step 1: no frustum culling", 640, 480, com.xoppa.blog.libgdx.g3d.frustumculling.step1.FrustumCullingTest.class, "loadscene/data"), new AppDesc("step 2: position culling", 640, 480, com.xoppa.blog.libgdx.g3d.frustumculling.step2.FrustumCullingTest.class, "loadscene/data"), new AppDesc("step 3: bounds culling", 640, 480, com.xoppa.blog.libgdx.g3d.frustumculling.step3.FrustumCullingTest.class, "loadscene/data"), new AppDesc("step 4: sphere culling", 640, 480, com.xoppa.blog.libgdx.g3d.frustumculling.step4.FrustumCullingTest.class, "loadscene/data") }, new Object[] { "Ray picking", new AppDesc("step 1: selecting objects", 640, 480, com.xoppa.blog.libgdx.g3d.raypicking.step1.RayPickingTest.class, "loadscene/data"), new AppDesc("step 2: moving objects", 640, 480, com.xoppa.blog.libgdx.g3d.raypicking.step2.RayPickingTest.class, "loadscene/data"), new AppDesc("step 3: preciser selecting objects", 640, 480, com.xoppa.blog.libgdx.g3d.raypicking.step3.RayPickingTest.class, "loadscene/data") }, new Object[] { "Shapes", new AppDesc("step 1: move code to GameObject", 640, 480, com.xoppa.blog.libgdx.g3d.shapes.step1.ShapeTest.class, "loadscene/data"), new AppDesc("step 2: Sphere shape", 640, 480, com.xoppa.blog.libgdx.g3d.shapes.step2.ShapeTest.class, "loadscene/data"), new AppDesc("step 3: Box shape", 640, 480, com.xoppa.blog.libgdx.g3d.shapes.step3.ShapeTest.class, "loadscene/data"), new AppDesc("step 4: Disc shape", 640, 480, com.xoppa.blog.libgdx.g3d.shapes.step4.ShapeTest.class, "loadscene/data") }, new Object[] { "Bullet: Collision detection", new AppDesc("step 1: no collision detection", 640, 480, com.xoppa.blog.libgdx.g3d.bullet.collision.step1.BulletTest.class), new AppDesc("step 2: using a collision algorithm", 640, 480, com.xoppa.blog.libgdx.g3d.bullet.collision.step2.BulletTest.class), new AppDesc("step 3: using a collision dispatcher", 640, 480, com.xoppa.blog.libgdx.g3d.bullet.collision.step3.BulletTest.class), new AppDesc("step 4: add more objects", 640, 480, com.xoppa.blog.libgdx.g3d.bullet.collision.step4.BulletTest.class), new AppDesc("step 5: using a ContactListener", 640, 480, com.xoppa.blog.libgdx.g3d.bullet.collision.step5.BulletTest.class), new AppDesc("step 6: optimize the callback method", 640, 480, com.xoppa.blog.libgdx.g3d.bullet.collision.step6.BulletTest.class), new AppDesc("step 7: using a collision world", 640, 480, com.xoppa.blog.libgdx.g3d.bullet.collision.step7.BulletTest.class), new AppDesc("step 8: using collision filtering", 640, 480, com.xoppa.blog.libgdx.g3d.bullet.collision.step8.BulletTest.class) }, new Object[] { "Bullet: Dynamics", new AppDesc("step 1: add physics properties", 640, 480, com.xoppa.blog.libgdx.g3d.bullet.dynamics.step1.BulletTest.class), new AppDesc("step 2: add a dynamics world", 640, 480, com.xoppa.blog.libgdx.g3d.bullet.dynamics.step2.BulletTest.class), new AppDesc("step 3: color objects on the ground", 640, 480, com.xoppa.blog.libgdx.g3d.bullet.dynamics.step3.BulletTest.class), new AppDesc("step 4: add motion state", 640, 480, com.xoppa.blog.libgdx.g3d.bullet.dynamics.step4.BulletTest.class), new AppDesc("step 5: contact callback filtering", 640, 480, com.xoppa.blog.libgdx.g3d.bullet.dynamics.step5.BulletTest.class), new AppDesc("step 6: kinematic body", 640, 480, com.xoppa.blog.libgdx.g3d.bullet.dynamics.step6.BulletTest.class) }, new Object[] { "A simple card game", new AppDesc("step 1: initial setup", 640, 480, com.xoppa.blog.libgdx.g3d.cardgame.step1.CardGame.class, "cardgame/data"), new AppDesc("step 2: use meaningfull units", 640, 480, com.xoppa.blog.libgdx.g3d.cardgame.step2.CardGame.class, "cardgame/data"), new AppDesc("step 3: structure the code", 640, 480, com.xoppa.blog.libgdx.g3d.cardgame.step3.CardGame.class, "cardgame/data"), new AppDesc("step 4: controlling the camera", 640, 480, com.xoppa.blog.libgdx.g3d.cardgame.step4.CardGame.class, "cardgame/data"), new AppDesc("step 5: add perspective", 640, 480, com.xoppa.blog.libgdx.g3d.cardgame.step5.CardGame.class, "cardgame/data"), new AppDesc("step 6: switch to ModelBatch", 640, 480, com.xoppa.blog.libgdx.g3d.cardgame.step6.CardGame.class, "cardgame/data"), new AppDesc("step 7: reduce render calls", 640, 480, com.xoppa.blog.libgdx.g3d.cardgame.step7.CardGame.class, "cardgame/data"), new AppDesc("step 8: add a table", 640, 480, com.xoppa.blog.libgdx.g3d.cardgame.step8.CardGame.class, "cardgame/data"), new AppDesc("step 9: keep the cards on the table", 640, 480, com.xoppa.blog.libgdx.g3d.cardgame.step9.CardGame.class, "cardgame/data"), new AppDesc("step A: animating the cards", 640, 480, com.xoppa.blog.libgdx.g3d.cardgame.stepa.CardGame.class, "cardgame/data") } }; LwjglAWTCanvas currentTest = null; public boolean runApp(final AppDesc appDesc) { ApplicationListener listener; try { listener = appDesc.clazz.newInstance(); } catch (InstantiationException e) { return false; } catch (IllegalAccessException e) { return false; } data = (appDesc.data == null || appDesc.data.isEmpty()) ? "data" : appDesc.data; Container container = getContentPane(); if (currentTest != null) { currentTest.stop(); container.remove(currentTest.getCanvas()); } currentTest = new LwjglAWTCanvas(listener); currentTest.getCanvas().setSize(appDesc.width, appDesc.height); container.add(currentTest.getCanvas(), BorderLayout.CENTER); pack(); return true; } public static void main(String[] args) throws Throwable { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); new Main(); } public Main() throws HeadlessException { super("Xoppa Libgdx Tutorials"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container container = getContentPane(); JPanel appList = new AppList(); appList.setSize(250, 600); container.add(appList, BorderLayout.LINE_START); pack(); setSize(900, 600); setLocationRelativeTo(null); setVisible(true); setDefaultCloseOperation(DISPOSE_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent arg0) { if (currentTest != null) currentTest.exit(); } }); } class AppList extends JPanel { private static final long serialVersionUID = 1582559224991888475L; public AppList () { setLayout(new BorderLayout()); final JButton button = new JButton("Run Test"); DefaultMutableTreeNode root = processHierarchy(apps); final JTree tree = new JTree(root); JScrollPane pane = new JScrollPane(tree); DefaultTreeSelectionModel m = new DefaultTreeSelectionModel(); m.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.setSelectionModel(m); tree.addMouseListener(new MouseAdapter() { public void mouseClicked (MouseEvent event) { if (event.getClickCount() == 2) button.doClick(); } }); tree.addKeyListener(new KeyAdapter() { public void keyPressed (KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) button.doClick(); } }); button.addActionListener(new ActionListener() { @Override public void actionPerformed (ActionEvent e) { Object obj = ((DefaultMutableTreeNode)tree.getLastSelectedPathComponent()).getUserObject(); if (obj instanceof AppDesc) { AppDesc app = (AppDesc)obj; //dispose(); runApp(app); } } }); add(pane, BorderLayout.CENTER); add(button, BorderLayout.SOUTH); } private DefaultMutableTreeNode processHierarchy(Object[] hierarchy) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(hierarchy[0]); DefaultMutableTreeNode child; for(int i=1; i<hierarchy.length; i++) { Object nodeSpecifier = hierarchy[i]; if (nodeSpecifier instanceof Object[]) child = processHierarchy((Object[])nodeSpecifier); else child = new DefaultMutableTreeNode(nodeSpecifier); node.add(child); } return node; } } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/loadmodels/step4/LoadModelsTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/loadmodels/step4/LoadModelsTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.loadmodels.step4; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.utils.Array; /** * See: http://blog.xoppa.com/loading-models-using-libgdx/ * @author Xoppa */ public class LoadModelsTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public ModelBatch modelBatch; public AssetManager assets; public Array<ModelInstance> instances = new Array<ModelInstance>(); public Environment environment; public boolean loading; @Override public void create () { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(7f, 7f, 7f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); assets = new AssetManager(); assets.load(data+"/ship.g3db", Model.class); loading = true; } private void doneLoading() { Model ship = assets.get(data+"/ship.g3db", Model.class); for (float x = -5f; x <= 5f; x += 2f) { for (float z = -5f; z <= 5f; z += 2f) { ModelInstance shipInstance = new ModelInstance(ship); shipInstance.transform.setToTranslation(x, 0, z); instances.add(shipInstance); } } loading = false; } @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/loadmodels/step1/LoadModelsTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/loadmodels/step1/LoadModelsTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.loadmodels.step1; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.loaders.ModelLoader; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.loader.ObjLoader; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; /** * See: http://blog.xoppa.com/loading-models-using-libgdx/ * @author Xoppa */ public class LoadModelsTest implements ApplicationListener { public Environment environment; public PerspectiveCamera cam; public CameraInputController camController; public ModelBatch modelBatch; public Model model; public ModelInstance instance; @Override public void create() { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(1f, 1f, 1f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); ModelLoader<?> loader = new ObjLoader(); model = loader.loadModel(Gdx.files.internal(data+"/ship.obj")); instance = new ModelInstance(model); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); } @Override public void render() { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instance, environment); modelBatch.end(); } @Override public void dispose() { modelBatch.dispose(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/loadmodels/step3/LoadModelsTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/loadmodels/step3/LoadModelsTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.loadmodels.step3; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.utils.Array; /** * See: http://blog.xoppa.com/loading-models-using-libgdx/ * @author Xoppa */ public class LoadModelsTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public ModelBatch modelBatch; public AssetManager assets; public Array<ModelInstance> instances = new Array<ModelInstance>(); public Environment environment; public boolean loading; @Override public void create () { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(7f, 7f, 7f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); assets = new AssetManager(); assets.load(data+"/ship.obj", Model.class); loading = true; } private void doneLoading() { Model ship = assets.get(data+"/ship.obj", Model.class); for (float x = -5f; x <= 5f; x += 2f) { for (float z = -5f; z <= 5f; z += 2f) { ModelInstance shipInstance = new ModelInstance(ship); shipInstance.transform.setToTranslation(x, 0, z); instances.add(shipInstance); } } loading = false; } @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/loadmodels/step2/LoadModelsTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/loadmodels/step2/LoadModelsTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.loadmodels.step2; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.utils.Array; /** * See: http://blog.xoppa.com/loading-models-using-libgdx/ * @author Xoppa */ public class LoadModelsTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public ModelBatch modelBatch; public AssetManager assets; public Array<ModelInstance> instances = new Array<ModelInstance>(); public Environment environment; public boolean loading; @Override public void create () { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(1f, 1f, 1f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); assets = new AssetManager(); assets.load(data+"/ship.obj", Model.class); loading = true; } private void doneLoading() { Model ship = assets.get(data+"/ship.obj", Model.class); ModelInstance shipInstance = new ModelInstance(ship); instances.add(shipInstance); loading = false; } @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/frustumculling/step4/FrustumCullingTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/frustumculling/step4/FrustumCullingTest.java
package com.xoppa.blog.libgdx.g3d.frustumculling.step4; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.Array; /** See: http://blog.xoppa.com/3d-frustum-culling-with-libgdx * @author Xoppa */ public class FrustumCullingTest implements ApplicationListener { public static class GameObject extends ModelInstance { public final Vector3 center = new Vector3(); public final Vector3 dimensions = new Vector3(); public final float radius; private final static BoundingBox bounds = new BoundingBox(); public GameObject(Model model, String rootNode, boolean mergeTransform) { super(model, rootNode, mergeTransform); calculateBoundingBox(bounds); bounds.getCenter(center); bounds.getDimensions(dimensions); radius = dimensions.len() / 2f; } } protected PerspectiveCamera cam; protected CameraInputController camController; protected ModelBatch modelBatch; protected AssetManager assets; protected Array<GameObject> instances = new Array<GameObject>(); protected Environment environment; protected boolean loading; protected Array<GameObject> blocks = new Array<GameObject>(); protected Array<GameObject> invaders = new Array<GameObject>(); protected ModelInstance ship; protected ModelInstance space; protected Stage stage; protected Label label; protected BitmapFont font; protected StringBuilder stringBuilder; @Override public void create () { stage = new Stage(); font = new BitmapFont(); label = new Label(" ", new Label.LabelStyle(font, Color.WHITE)); stage.addActor(label); stringBuilder = new StringBuilder(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); assets = new AssetManager(); assets.load(data+"/invaderscene.g3db", Model.class); loading = true; } private void doneLoading() { Model model = assets.get(data+"/invaderscene.g3db", Model.class); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; GameObject instance = new GameObject(model, id, true); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) ship = instance; else if (id.startsWith("block")) blocks.add(instance); else if (id.startsWith("invader")) invaders.add(instance); } loading = false; } private int visibleCount; @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); visibleCount = 0; for (final GameObject instance : instances) { if (isVisible(cam, instance)) { modelBatch.render(instance, environment); visibleCount++; } } if (space != null) modelBatch.render(space); modelBatch.end(); stringBuilder.setLength(0); stringBuilder.append(" FPS: ").append(Gdx.graphics.getFramesPerSecond()); stringBuilder.append(" Visible: ").append(visibleCount); label.setText(stringBuilder); stage.draw(); } private Vector3 position = new Vector3(); protected boolean isVisible(final Camera cam, final GameObject instance) { instance.transform.getTranslation(position); position.add(instance.center); return cam.frustum.sphereInFrustum(position, instance.radius); } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize(int width, int height) { stage.getViewport().update(width, height, true); } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/frustumculling/step1/FrustumCullingTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/frustumculling/step1/FrustumCullingTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.frustumculling.step1; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.Array; /** See: http://blog.xoppa.com/3d-frustum-culling-with-libgdx * @author Xoppa */ public class FrustumCullingTest implements ApplicationListener { protected PerspectiveCamera cam; protected CameraInputController camController; protected ModelBatch modelBatch; protected AssetManager assets; protected Array<ModelInstance> instances = new Array<ModelInstance>(); protected Environment environment; protected boolean loading; protected Array<ModelInstance> blocks = new Array<ModelInstance>(); protected Array<ModelInstance> invaders = new Array<ModelInstance>(); protected ModelInstance ship; protected ModelInstance space; protected Stage stage; protected Label label; protected BitmapFont font; protected StringBuilder stringBuilder; @Override public void create () { stage = new Stage(); font = new BitmapFont(); label = new Label(" ", new Label.LabelStyle(font, Color.WHITE)); stage.addActor(label); stringBuilder = new StringBuilder(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); assets = new AssetManager(); assets.load(data+"/invaderscene.g3db", Model.class); loading = true; } private void doneLoading() { Model model = assets.get(data+"/invaderscene.g3db", Model.class); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; ModelInstance instance = new ModelInstance(model, id, true); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) ship = instance; else if (id.startsWith("block")) blocks.add(instance); else if (id.startsWith("invader")) invaders.add(instance); } loading = false; } private int visibleCount; @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); visibleCount = 0; for (final ModelInstance instance : instances) { if (isVisible(cam, instance)) { modelBatch.render(instance, environment); visibleCount++; } } if (space != null) modelBatch.render(space); modelBatch.end(); stringBuilder.setLength(0); stringBuilder.append(" FPS: ").append(Gdx.graphics.getFramesPerSecond()); stringBuilder.append(" Visible: ").append(visibleCount); label.setText(stringBuilder); stage.draw(); } protected boolean isVisible(final Camera cam, final ModelInstance instance) { return true; // FIXME: Implement frustum culling } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize(int width, int height) { stage.getViewport().update(width, height, true); } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/frustumculling/step3/FrustumCullingTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/frustumculling/step3/FrustumCullingTest.java
package com.xoppa.blog.libgdx.g3d.frustumculling.step3; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.Array; /** See: http://blog.xoppa.com/3d-frustum-culling-with-libgdx * @author Xoppa */ public class FrustumCullingTest implements ApplicationListener { public static class GameObject extends ModelInstance { public final Vector3 center = new Vector3(); public final Vector3 dimensions = new Vector3(); private final static BoundingBox bounds = new BoundingBox(); public GameObject(Model model, String rootNode, boolean mergeTransform) { super(model, rootNode, mergeTransform); calculateBoundingBox(bounds); bounds.getCenter(center); bounds.getDimensions(dimensions); } } protected PerspectiveCamera cam; protected CameraInputController camController; protected ModelBatch modelBatch; protected AssetManager assets; protected Array<GameObject> instances = new Array<GameObject>(); protected Environment environment; protected boolean loading; protected Array<GameObject> blocks = new Array<GameObject>(); protected Array<GameObject> invaders = new Array<GameObject>(); protected ModelInstance ship; protected ModelInstance space; protected Stage stage; protected Label label; protected BitmapFont font; protected StringBuilder stringBuilder; @Override public void create () { stage = new Stage(); font = new BitmapFont(); label = new Label(" ", new Label.LabelStyle(font, Color.WHITE)); stage.addActor(label); stringBuilder = new StringBuilder(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); assets = new AssetManager(); assets.load(data+"/invaderscene.g3db", Model.class); loading = true; } private void doneLoading() { Model model = assets.get(data+"/invaderscene.g3db", Model.class); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; GameObject instance = new GameObject(model, id, true); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) ship = instance; else if (id.startsWith("block")) blocks.add(instance); else if (id.startsWith("invader")) invaders.add(instance); } loading = false; } private int visibleCount; @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); visibleCount = 0; for (final GameObject instance : instances) { if (isVisible(cam, instance)) { modelBatch.render(instance, environment); visibleCount++; } } if (space != null) modelBatch.render(space); modelBatch.end(); stringBuilder.setLength(0); stringBuilder.append(" FPS: ").append(Gdx.graphics.getFramesPerSecond()); stringBuilder.append(" Visible: ").append(visibleCount); label.setText(stringBuilder); stage.draw(); } private Vector3 position = new Vector3(); protected boolean isVisible(final Camera cam, final GameObject instance) { instance.transform.getTranslation(position); position.add(instance.center); return cam.frustum.boundsInFrustum(position, instance.dimensions); } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize(int width, int height) { stage.getViewport().update(width, height, true); } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/frustumculling/step2/FrustumCullingTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/frustumculling/step2/FrustumCullingTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.frustumculling.step2; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.Array; /** See: http://blog.xoppa.com/3d-frustum-culling-with-libgdx * @author Xoppa */ public class FrustumCullingTest implements ApplicationListener { protected PerspectiveCamera cam; protected CameraInputController camController; protected ModelBatch modelBatch; protected AssetManager assets; protected Array<ModelInstance> instances = new Array<ModelInstance>(); protected Environment environment; protected boolean loading; protected Array<ModelInstance> blocks = new Array<ModelInstance>(); protected Array<ModelInstance> invaders = new Array<ModelInstance>(); protected ModelInstance ship; protected ModelInstance space; protected Stage stage; protected Label label; protected BitmapFont font; protected StringBuilder stringBuilder; @Override public void create () { stage = new Stage(); font = new BitmapFont(); label = new Label(" ", new Label.LabelStyle(font, Color.WHITE)); stage.addActor(label); stringBuilder = new StringBuilder(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); assets = new AssetManager(); assets.load(data+"/invaderscene.g3db", Model.class); loading = true; } private void doneLoading() { Model model = assets.get(data+"/invaderscene.g3db", Model.class); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; ModelInstance instance = new ModelInstance(model, id, true); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) ship = instance; else if (id.startsWith("block")) blocks.add(instance); else if (id.startsWith("invader")) invaders.add(instance); } loading = false; } private int visibleCount; @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); visibleCount = 0; for (final ModelInstance instance : instances) { if (isVisible(cam, instance)) { modelBatch.render(instance, environment); visibleCount++; } } if (space != null) modelBatch.render(space); modelBatch.end(); stringBuilder.setLength(0); stringBuilder.append(" FPS: ").append(Gdx.graphics.getFramesPerSecond()); stringBuilder.append(" Visible: ").append(visibleCount); label.setText(stringBuilder); stage.draw(); } private Vector3 position = new Vector3(); protected boolean isVisible(final Camera cam, final ModelInstance instance) { instance.transform.getTranslation(position); return cam.frustum.pointInFrustum(position); } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize(int width, int height) { stage.getViewport().update(width, height, true); } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step4/ShaderTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step4/ShaderTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.createshader.step4; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.model.NodePart; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.DefaultTextureBinder; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class ShaderTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public RenderContext renderContext; public Model model; public Renderable renderable; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(2f, 2f, 2f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); NodePart blockPart = model.nodes.get(0).parts.get(0); renderable = new Renderable(); blockPart.setRenderable(renderable); renderable.environment = null; renderable.worldTransform.idt(); renderContext = new RenderContext(new DefaultTextureBinder(DefaultTextureBinder.WEIGHTED, 1)); shader = new TestShader(); shader.init(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); renderContext.begin(); shader.begin(cam, renderContext); shader.render(renderable); shader.end(); renderContext.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step4/TestShader.java
tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step4/TestShader.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.createshader.step4; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.GdxRuntimeException; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class TestShader implements Shader { ShaderProgram program; Camera camera; RenderContext context; @Override public void init() { String vert = Gdx.files.internal(data+"/test.vertex.glsl").readString(); String frag = Gdx.files.internal(data+"/test.fragment.glsl").readString(); program = new ShaderProgram(vert, frag); if (!program.isCompiled()) throw new GdxRuntimeException(program.getLog()); } @Override public void dispose() { program.dispose(); } @Override public void begin(Camera camera, RenderContext context) { this.camera = camera; this.context = context; program.begin(); program.setUniformMatrix("u_projViewTrans", camera.combined); } @Override public void render(Renderable renderable) { program.setUniformMatrix("u_worldTrans", renderable.worldTransform); renderable.meshPart.render(program); } @Override public void end() { program.end(); } @Override public int compareTo(Shader other) { return 0; } @Override public boolean canRender(Renderable instance) { return true; } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step5/ShaderTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step5/ShaderTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.createshader.step5; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.model.NodePart; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.DefaultTextureBinder; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class ShaderTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public RenderContext renderContext; public Model model; public Renderable renderable; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(2f, 2f, 2f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); NodePart blockPart = model.nodes.get(0).parts.get(0); renderable = new Renderable(); blockPart.setRenderable(renderable); renderable.environment = null; renderable.worldTransform.idt(); renderContext = new RenderContext(new DefaultTextureBinder(DefaultTextureBinder.WEIGHTED, 1)); shader = new TestShader(); shader.init(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); renderContext.begin(); shader.begin(cam, renderContext); shader.render(renderable); shader.end(); renderContext.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step5/TestShader.java
tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step5/TestShader.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.createshader.step5; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.GdxRuntimeException; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class TestShader implements Shader { ShaderProgram program; Camera camera; RenderContext context; @Override public void init() { String vert = Gdx.files.internal(data+"/test.vertex.glsl").readString(); String frag = Gdx.files.internal(data+"/test.fragment.glsl").readString(); program = new ShaderProgram(vert, frag); if (!program.isCompiled()) throw new GdxRuntimeException(program.getLog()); } @Override public void dispose() { program.dispose(); } @Override public void begin(Camera camera, RenderContext context) { this.camera = camera; this.context = context; program.begin(); program.setUniformMatrix("u_projViewTrans", camera.combined); context.setDepthTest(GL20.GL_LEQUAL); context.setCullFace(GL20.GL_BACK); } @Override public void render(Renderable renderable) { program.setUniformMatrix("u_worldTrans", renderable.worldTransform); renderable.meshPart.render(program); } @Override public void end() { program.end(); } @Override public int compareTo(Shader other) { return 0; } @Override public boolean canRender(Renderable instance) { return true; } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step1/ShaderTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step1/ShaderTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.createshader.step1; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.model.NodePart; import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.DefaultTextureBinder; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class ShaderTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public RenderContext renderContext; public Model model; public Renderable renderable; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(2f, 2f, 2f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); NodePart blockPart = model.nodes.get(0).parts.get(0); renderable = new Renderable(); blockPart.setRenderable(renderable); renderable.environment = null; renderable.worldTransform.idt(); renderContext = new RenderContext(new DefaultTextureBinder(DefaultTextureBinder.WEIGHTED, 1)); shader = new DefaultShader(renderable); shader.init(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); renderContext.begin(); shader.begin(cam, renderContext); shader.render(renderable); shader.end(); renderContext.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step6/ShaderTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step6/ShaderTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.createshader.step6; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.model.NodePart; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.DefaultTextureBinder; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class ShaderTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public RenderContext renderContext; public Model model; public Renderable renderable; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(2f, 2f, 2f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); NodePart blockPart = model.nodes.get(0).parts.get(0); renderable = new Renderable(); blockPart.setRenderable(renderable); renderable.environment = null; renderable.worldTransform.idt(); renderContext = new RenderContext(new DefaultTextureBinder(DefaultTextureBinder.WEIGHTED, 1)); shader = new TestShader(); shader.init(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); renderContext.begin(); shader.begin(cam, renderContext); shader.render(renderable); shader.end(); renderContext.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step6/TestShader.java
tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step6/TestShader.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.createshader.step6; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.GdxRuntimeException; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class TestShader implements Shader { ShaderProgram program; Camera camera; RenderContext context; int u_projTrans; int u_worldTrans; @Override public void init() { String vert = Gdx.files.internal(data+"/test.vertex.glsl").readString(); String frag = Gdx.files.internal(data+"/test.fragment.glsl").readString(); program = new ShaderProgram(vert, frag); if (!program.isCompiled()) throw new GdxRuntimeException(program.getLog()); u_projTrans = program.getUniformLocation("u_projViewTrans"); u_worldTrans = program.getUniformLocation("u_worldTrans"); } @Override public void dispose() { program.dispose(); } @Override public void begin(Camera camera, RenderContext context) { this.camera = camera; this.context = context; program.begin(); program.setUniformMatrix(u_projTrans, camera.combined); context.setDepthTest(GL20.GL_LEQUAL); context.setCullFace(GL20.GL_BACK); } @Override public void render(Renderable renderable) { program.setUniformMatrix(u_worldTrans, renderable.worldTransform); renderable.meshPart.render(program); } @Override public void end() { program.end(); } @Override public int compareTo(Shader other) { return 0; } @Override public boolean canRender(Renderable instance) { return true; } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step3/ShaderTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step3/ShaderTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.createshader.step3; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.model.NodePart; import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.DefaultTextureBinder; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class ShaderTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public RenderContext renderContext; public Model model; public Renderable renderable; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(2f, 2f, 2f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); NodePart blockPart = model.nodes.get(0).parts.get(0); renderable = new Renderable(); blockPart.setRenderable(renderable); renderable.environment = null; renderable.worldTransform.idt(); renderContext = new RenderContext(new DefaultTextureBinder(DefaultTextureBinder.WEIGHTED, 1)); String vert = Gdx.files.internal(data+"/test.vertex.glsl").readString(); String frag = Gdx.files.internal(data+"/test.fragment.glsl").readString(); shader = new DefaultShader(renderable, new DefaultShader.Config(vert, frag)); shader.init(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); renderContext.begin(); shader.begin(cam, renderContext); shader.render(renderable); shader.end(); renderContext.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step2/ShaderTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step2/ShaderTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.createshader.step2; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.model.NodePart; import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.DefaultTextureBinder; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class ShaderTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public RenderContext renderContext; public Model model; public Renderable renderable; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(2f, 2f, 2f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); NodePart blockPart = model.nodes.get(0).parts.get(0); renderable = new Renderable(); blockPart.setRenderable(renderable); renderable.meshPart.primitiveType = GL20.GL_POINTS; renderable.environment = null; renderable.worldTransform.idt(); renderContext = new RenderContext(new DefaultTextureBinder(DefaultTextureBinder.WEIGHTED, 1)); shader = new DefaultShader(renderable); shader.init(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); renderContext.begin(); shader.begin(cam, renderContext); shader.render(renderable); shader.end(); renderContext.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step4/BehindTheScenesTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step4/BehindTheScenesTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.behindscenes.step4; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.loaders.ModelLoader; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.model.Node; import com.badlogic.gdx.graphics.g3d.model.data.ModelData; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.TextureProvider; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.JsonReader; /** * See: http://blog.xoppa.com/behind-the-3d-scenes-part2/ * @author Xoppa */ public class BehindTheScenesTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public ModelBatch modelBatch; public Model model; public Array<ModelInstance> instances = new Array<ModelInstance>(); public Environment environment; public Array<ModelInstance> blocks = new Array<ModelInstance>(); public Array<ModelInstance> invaders = new Array<ModelInstance>(); public ModelInstance ship; public ModelInstance space; @Override public void create () { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelLoader<?> modelLoader = new G3dModelLoader(new JsonReader()); ModelData modelData = modelLoader.loadModelData(Gdx.files.internal(data+"/invaderscene.g3dj")); model = new Model(modelData, new TextureProvider.FileTextureProvider()); doneLoading(); } private void doneLoading() { Material blockMaterial = model.getMaterial("block_default1"); blockMaterial.set(ColorAttribute.createDiffuse(Color.YELLOW)); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; ModelInstance instance = new ModelInstance(model, id); Node node = instance.getNode(id); instance.transform.set(node.globalTransform); node.translation.set(0,0,0); node.scale.set(1,1,1); node.rotation.idt(); instance.calculateTransforms(); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) ship = instance; else if (id.startsWith("block")) blocks.add(instance); else if (id.startsWith("invader")) invaders.add(instance); } } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); if (space != null) modelBatch.render(space); modelBatch.end(); } @Override public void dispose () { modelBatch.dispose(); instances.clear(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step5/BehindTheScenesTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step5/BehindTheScenesTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.behindscenes.step5; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.loaders.ModelLoader; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader; import com.badlogic.gdx.graphics.g3d.model.Node; import com.badlogic.gdx.graphics.g3d.model.data.ModelData; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.TextureProvider; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.JsonReader; /** * See: http://blog.xoppa.com/behind-the-3d-scenes-part2/ * @author Xoppa */ public class BehindTheScenesTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public ModelBatch modelBatch; public Model model; public Array<ModelInstance> instances = new Array<ModelInstance>(); public Environment environment; public Array<ModelInstance> blocks = new Array<ModelInstance>(); public Array<ModelInstance> invaders = new Array<ModelInstance>(); public ModelInstance ship; public ModelInstance space; @Override public void create () { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelLoader<?> modelLoader = new G3dModelLoader(new JsonReader()); ModelData modelData = modelLoader.loadModelData(Gdx.files.internal(data+"/invaderscene.g3dj")); model = new Model(modelData, new TextureProvider.FileTextureProvider()); doneLoading(); } private void doneLoading() { for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; ModelInstance instance = new ModelInstance(model, id); Node node = instance.getNode(id); instance.transform.set(node.globalTransform); node.translation.set(0,0,0); node.scale.set(1,1,1); node.rotation.idt(); instance.calculateTransforms(); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) ship = instance; else if (id.startsWith("block")) blocks.add(instance); else if (id.startsWith("invader")) invaders.add(instance); } for (ModelInstance block : blocks) { float r = 0.5f + 0.5f * (float)Math.random(); float g = 0.5f + 0.5f * (float)Math.random(); float b = 0.5f + 0.5f * (float)Math.random(); block.materials.get(0).set(ColorAttribute.createDiffuse(r, g, b, 1)); } } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); if (space != null) modelBatch.render(space); modelBatch.end(); } @Override public void dispose () { modelBatch.dispose(); instances.clear(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step7/BehindTheScenesTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step7/BehindTheScenesTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.behindscenes.step7; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.loaders.ModelLoader; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader; import com.badlogic.gdx.graphics.g3d.model.NodePart; import com.badlogic.gdx.graphics.g3d.model.data.ModelData; import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.DefaultTextureBinder; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.g3d.utils.TextureProvider; import com.badlogic.gdx.utils.JsonReader; /** * See: http://blog.xoppa.com/behind-the-3d-scenes-part2/ * @author Xoppa */ public class BehindTheScenesTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public RenderContext renderContext; public Model model; public Environment environment; public Renderable renderable; @Override public void create () { environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(2f, 2f, 2f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelLoader<?> modelLoader = new G3dModelLoader(new JsonReader()); ModelData modelData = modelLoader.loadModelData(Gdx.files.internal(data+"/invaderscene.g3dj")); model = new Model(modelData, new TextureProvider.FileTextureProvider()); NodePart blockPart = model.getNode("ship").parts.get(0); renderable = new Renderable(); renderable.meshPart.set(blockPart.meshPart); renderable.material = blockPart.material; renderable.environment = environment; renderable.worldTransform.idt(); renderContext = new RenderContext(new DefaultTextureBinder(DefaultTextureBinder.WEIGHTED, 1)); shader = new DefaultShader(renderable); shader.init(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); renderContext.begin(); shader.begin(cam, renderContext); shader.render(renderable); shader.end(); renderContext.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step1/BehindTheScenesTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step1/BehindTheScenesTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.behindscenes.step1; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.model.Node; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.utils.Array; /** * See: http://blog.xoppa.com/behind-the-3d-scenes-part2/ * @author Xoppa */ public class BehindTheScenesTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public ModelBatch modelBatch; public AssetManager assets; public Array<ModelInstance> instances = new Array<ModelInstance>(); public Environment environment; public boolean loading; public Array<ModelInstance> blocks = new Array<ModelInstance>(); public Array<ModelInstance> invaders = new Array<ModelInstance>(); public ModelInstance ship; public ModelInstance space; @Override public void create () { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); assets = new AssetManager(); assets.load(data+"/invaderscene.g3db", Model.class); loading = true; } private void doneLoading() { Model model = assets.get(data+"/invaderscene.g3db", Model.class); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; ModelInstance instance = new ModelInstance(model, id); Node node = instance.getNode(id); instance.transform.set(node.globalTransform); node.translation.set(0,0,0); node.scale.set(1,1,1); node.rotation.idt(); instance.calculateTransforms(); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) ship = instance; else if (id.startsWith("block")) blocks.add(instance); else if (id.startsWith("invader")) invaders.add(instance); } loading = false; } @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); if (space != null) modelBatch.render(space); modelBatch.end(); } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step6/BehindTheScenesTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step6/BehindTheScenesTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.behindscenes.step6; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.loaders.ModelLoader; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader; import com.badlogic.gdx.graphics.g3d.model.NodePart; import com.badlogic.gdx.graphics.g3d.model.data.ModelData; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.TextureProvider; import com.badlogic.gdx.utils.JsonReader; /** * See: http://blog.xoppa.com/behind-the-3d-scenes-part2/ * @author Xoppa */ public class BehindTheScenesTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public ModelBatch modelBatch; public Model model; public Environment environment; public Renderable renderable; @Override public void create () { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(2f, 2f, 2f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelLoader<?> modelLoader = new G3dModelLoader(new JsonReader()); ModelData modelData = modelLoader.loadModelData(Gdx.files.internal(data+"/invaderscene.g3dj")); model = new Model(modelData, new TextureProvider.FileTextureProvider()); NodePart blockPart = model.getNode("ship").parts.get(0); renderable = new Renderable(); renderable.meshPart.set(blockPart.meshPart); renderable.material = blockPart.material; renderable.environment = environment; renderable.worldTransform.idt(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(renderable); modelBatch.end(); } @Override public void dispose () { modelBatch.dispose(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step3/BehindTheScenesTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step3/BehindTheScenesTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.behindscenes.step3; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.loaders.ModelLoader; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.model.Node; import com.badlogic.gdx.graphics.g3d.model.data.ModelData; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.TextureProvider; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.JsonReader; /** * See: http://blog.xoppa.com/behind-the-3d-scenes-part2/ * @author Xoppa */ public class BehindTheScenesTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public ModelBatch modelBatch; public Model model; public Array<ModelInstance> instances = new Array<ModelInstance>(); public Environment environment; public Array<ModelInstance> blocks = new Array<ModelInstance>(); public Array<ModelInstance> invaders = new Array<ModelInstance>(); public ModelInstance ship; public ModelInstance space; @Override public void create () { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelLoader<?> modelLoader = new G3dModelLoader(new JsonReader()); ModelData modelData = modelLoader.loadModelData(Gdx.files.internal(data+"/invaderscene.g3dj")); model = new Model(modelData, new TextureProvider.FileTextureProvider()); doneLoading(); } private void doneLoading() { Material blockMaterial = model.getNode("block1").parts.get(0).material; ColorAttribute colorAttribute = (ColorAttribute)blockMaterial.get(ColorAttribute.Diffuse); colorAttribute.color.set(Color.YELLOW); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; ModelInstance instance = new ModelInstance(model, id); Node node = instance.getNode(id); instance.transform.set(node.globalTransform); node.translation.set(0,0,0); node.scale.set(1,1,1); node.rotation.idt(); instance.calculateTransforms(); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) ship = instance; else if (id.startsWith("block")) blocks.add(instance); else if (id.startsWith("invader")) invaders.add(instance); } } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); if (space != null) modelBatch.render(space); modelBatch.end(); } @Override public void dispose () { modelBatch.dispose(); instances.clear(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step2/BehindTheScenesTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step2/BehindTheScenesTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.behindscenes.step2; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.loaders.ModelLoader; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader; import com.badlogic.gdx.graphics.g3d.model.Node; import com.badlogic.gdx.graphics.g3d.model.data.ModelData; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.TextureProvider; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.JsonReader; /** * See: http://blog.xoppa.com/behind-the-3d-scenes-part2/ * @author Xoppa */ public class BehindTheScenesTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public ModelBatch modelBatch; public Model model; public Array<ModelInstance> instances = new Array<ModelInstance>(); public Environment environment; public Array<ModelInstance> blocks = new Array<ModelInstance>(); public Array<ModelInstance> invaders = new Array<ModelInstance>(); public ModelInstance ship; public ModelInstance space; @Override public void create () { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelLoader<?> modelLoader = new G3dModelLoader(new JsonReader()); ModelData modelData = modelLoader.loadModelData(Gdx.files.internal(data+"/invaderscene.g3dj")); model = new Model(modelData, new TextureProvider.FileTextureProvider()); doneLoading(); } private void doneLoading() { for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; ModelInstance instance = new ModelInstance(model, id); Node node = instance.getNode(id); instance.transform.set(node.globalTransform); node.translation.set(0,0,0); node.scale.set(1,1,1); node.rotation.idt(); instance.calculateTransforms(); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) ship = instance; else if (id.startsWith("block")) blocks.add(instance); else if (id.startsWith("invader")) invaders.add(instance); } } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); if (space != null) modelBatch.render(space); modelBatch.end(); } @Override public void dispose () { modelBatch.dispose(); instances.clear(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/loadscene/step1/LoadSceneTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/loadscene/step1/LoadSceneTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.loadscene.step1; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; /** * See: http://blog.xoppa.com/loading-a-scene-with-libgdx/ * @author Xoppa */ public class LoadSceneTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public ModelBatch modelBatch; public AssetManager assets; public Array<ModelInstance> instances = new Array<ModelInstance>(); public Environment environment; public boolean loading; public Array<ModelInstance> blocks = new Array<ModelInstance>(); public Array<ModelInstance> invaders = new Array<ModelInstance>(); public ModelInstance ship; public ModelInstance space; @Override public void create () { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); assets = new AssetManager(); assets.load(data+"/ship.obj", Model.class); assets.load(data+"/block.obj", Model.class); assets.load(data+"/invader.obj", Model.class); assets.load(data+"/spacesphere.obj", Model.class); loading = true; } private void doneLoading() { ship = new ModelInstance(assets.get(data+"/ship.obj", Model.class)); ship.transform.setToRotation(Vector3.Y, 180).trn(0, 0, 6f); instances.add(ship); Model blockModel = assets.get(data+"/block.obj", Model.class); for (float x = -5f; x <= 5f; x += 2f) { ModelInstance block = new ModelInstance(blockModel); block.transform.setToTranslation(x, 0, 3f); instances.add(block); blocks.add(block); } Model invaderModel = assets.get(data+"/invader.obj", Model.class); for (float x = -5f; x <= 5f; x += 2f) { for (float z = -8f; z <= 0f; z += 2f) { ModelInstance invader = new ModelInstance(invaderModel); invader.transform.setToTranslation(x, 0, z); instances.add(invader); invaders.add(invader); } } space = new ModelInstance(assets.get(data+"/spacesphere.obj", Model.class)); loading = false; } @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); if (space != null) modelBatch.render(space); modelBatch.end(); } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/loadscene/step3/LoadSceneTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/loadscene/step3/LoadSceneTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.loadscene.step3; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.model.Node; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.utils.Array; /** * See: http://blog.xoppa.com/loading-a-scene-with-libgdx/ * @author Xoppa */ public class LoadSceneTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public ModelBatch modelBatch; public AssetManager assets; public Array<ModelInstance> instances = new Array<ModelInstance>(); public Environment environment; public boolean loading; public Array<ModelInstance> blocks = new Array<ModelInstance>(); public Array<ModelInstance> invaders = new Array<ModelInstance>(); public ModelInstance ship; public ModelInstance space; @Override public void create () { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); assets = new AssetManager(); assets.load(data+"/invaderscene.g3db", Model.class); loading = true; } private void doneLoading() { Model model = assets.get(data+"/invaderscene.g3db", Model.class); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; ModelInstance instance = new ModelInstance(model, id); Node node = instance.getNode(id); instance.transform.set(node.globalTransform); node.translation.set(0,0,0); node.scale.set(1,1,1); node.rotation.idt(); instance.calculateTransforms(); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) ship = instance; else if (id.startsWith("block")) blocks.add(instance); else if (id.startsWith("invader")) invaders.add(instance); } loading = false; } @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); if (space != null) modelBatch.render(space); modelBatch.end(); } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/loadscene/step2/LoadSceneTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/loadscene/step2/LoadSceneTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.loadscene.step2; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; /** * See: http://blog.xoppa.com/loading-a-scene-with-libgdx/ * @author Xoppa */ public class LoadSceneTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public ModelBatch modelBatch; public AssetManager assets; public Array<ModelInstance> instances = new Array<ModelInstance>(); public Environment environment; public boolean loading; public Array<ModelInstance> blocks = new Array<ModelInstance>(); public Array<ModelInstance> invaders = new Array<ModelInstance>(); public ModelInstance ship; public ModelInstance space; @Override public void create () { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); assets = new AssetManager(); assets.load(data+"/invaders.g3db", Model.class); loading = true; } private void doneLoading() { Model model = assets.get(data+"/invaders.g3db", Model.class); ship = new ModelInstance(model, "ship"); ship.transform.setToRotation(Vector3.Y, 180).trn(0, 0, 6f); instances.add(ship); for (float x = -5f; x <= 5f; x += 2f) { ModelInstance block = new ModelInstance(model, "block"); block.transform.setToTranslation(x, 0, 3f); instances.add(block); blocks.add(block); } for (float x = -5f; x <= 5f; x += 2f) { for (float z = -8f; z <= 0f; z += 2f) { ModelInstance invader = new ModelInstance(model, "invader"); invader.transform.setToTranslation(x, 0, z); instances.add(invader); invaders.add(invader); } } space = new ModelInstance(model, "space"); loading = false; } @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); if (space != null) modelBatch.render(space); modelBatch.end(); } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step8/MaterialTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step8/MaterialTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step8; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.utils.Array; import com.xoppa.blog.libgdx.g3d.usingmaterials.step7.TestShader.TestColorAttribute; /** * See: http://blog.xoppa.com/using-materials-with-libgdx * @author Xoppa */ public class MaterialTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public Model model; public Array<ModelInstance> instances = new Array<ModelInstance>(); public ModelBatch modelBatch; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 8f, 8f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); for (int x = -5; x <= 5; x+=2) { for (int z = -5; z<=5; z+=2) { ModelInstance instance = new ModelInstance(model, x, 0, z); ColorAttribute attrU = new TestColorAttribute(TestColorAttribute.DiffuseU, (x+5f)/10f, 1f - (z+5f)/10f, 0, 1); instance.materials.get(0).set(attrU); ColorAttribute attrV = new TestColorAttribute(TestColorAttribute.DiffuseV, 1f - (x+5f)/10f, 0, (z+5f)/10f, 1); instance.materials.get(0).set(attrV); instances.add(instance); } } shader = new TestShader(); shader.init(); modelBatch = new ModelBatch(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); for (ModelInstance instance : instances) modelBatch.render(instance, shader); modelBatch.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); modelBatch.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step8/TestShader.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step8/TestShader.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step8; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.GdxRuntimeException; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class TestShader implements Shader { public static class TestColorAttribute extends ColorAttribute { public final static String DiffuseUAlias = "diffuseUColor"; public final static long DiffuseU = register(DiffuseUAlias); public final static String DiffuseVAlias = "diffuseVColor"; public final static long DiffuseV = register(DiffuseVAlias); static { Mask = Mask | DiffuseU | DiffuseV; } public TestColorAttribute (long type, float r, float g, float b, float a) { super(type, r, g, b, a); } } ShaderProgram program; Camera camera; RenderContext context; int u_projTrans; int u_worldTrans; int u_colorU; int u_colorV; @Override public void init() { String vert = Gdx.files.internal(data+"/uvcolor.vertex.glsl").readString(); String frag = Gdx.files.internal(data+"/uvcolor.fragment.glsl").readString(); program = new ShaderProgram(vert, frag); if (!program.isCompiled()) throw new GdxRuntimeException(program.getLog()); u_projTrans = program.getUniformLocation("u_projTrans"); u_worldTrans = program.getUniformLocation("u_worldTrans"); u_colorU = program.getUniformLocation("u_colorU"); u_colorV = program.getUniformLocation("u_colorV"); } @Override public void dispose() { program.dispose(); } @Override public void begin(Camera camera, RenderContext context) { this.camera = camera; this.context = context; program.begin(); program.setUniformMatrix(u_projTrans, camera.combined); context.setDepthTest(GL20.GL_LEQUAL); context.setCullFace(GL20.GL_BACK); } @Override public void render(Renderable renderable) { program.setUniformMatrix(u_worldTrans, renderable.worldTransform); Color colorU = ((ColorAttribute)renderable.material.get(TestColorAttribute.DiffuseU)).color; Color colorV = ((ColorAttribute)renderable.material.get(TestColorAttribute.DiffuseV)).color; program.setUniformf(u_colorU, colorU.r, colorU.g, colorU.b); program.setUniformf(u_colorV, colorV.r, colorV.g, colorV.b); renderable.meshPart.render(program); } @Override public void end() { program.end(); } @Override public int compareTo(Shader other) { return 0; } @Override public boolean canRender(Renderable renderable) { return renderable.material.has(TestColorAttribute.DiffuseU | TestColorAttribute.DiffuseV); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step9/MaterialTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step9/MaterialTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step9; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.utils.Array; import com.xoppa.blog.libgdx.g3d.usingmaterials.step9.TestShader.DoubleColorAttribute; /** * See: http://blog.xoppa.com/using-materials-with-libgdx * @author Xoppa */ public class MaterialTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public Model model; public Array<ModelInstance> instances = new Array<ModelInstance>(); public ModelBatch modelBatch; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 8f, 8f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); Color colorU = new Color(), colorV = new Color(); for (int x = -5; x <= 5; x+=2) { for (int z = -5; z<=5; z+=2) { ModelInstance instance = new ModelInstance(model, x, 0, z); DoubleColorAttribute attr = new DoubleColorAttribute(DoubleColorAttribute.DiffuseUV, colorU.set((x+5f)/10f, 1f - (z+5f)/10f, 0, 1), colorV.set(1f - (x+5f)/10f, 0, (z+5f)/10f, 1)); instance.materials.get(0).set(attr); instances.add(instance); } } shader = new TestShader(); shader.init(); modelBatch = new ModelBatch(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); for (ModelInstance instance : instances) modelBatch.render(instance, shader); modelBatch.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); modelBatch.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step9/TestShader.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step9/TestShader.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step9; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g3d.Attribute; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.GdxRuntimeException; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * * @author Xoppa */ public class TestShader implements Shader { public static class DoubleColorAttribute extends Attribute { public final static String DiffuseUVAlias = "diffuseUVColor"; public final static long DiffuseUV = register(DiffuseUVAlias); public final Color color1 = new Color(); public final Color color2 = new Color(); protected DoubleColorAttribute (long type, Color c1, Color c2) { super(type); color1.set(c1); color2.set(c2); } @Override public Attribute copy () { return new DoubleColorAttribute(type, color1, color2); } @Override protected boolean equals (Attribute other) { DoubleColorAttribute attr = (DoubleColorAttribute) other; return type == other.type && color1.equals(attr.color1) && color2.equals(attr.color2); } @Override public int compareTo (Attribute other) { if (type != other.type) return (int) (type - other.type); DoubleColorAttribute attr = (DoubleColorAttribute) other; return color1.equals(attr.color1) ? attr.color2.toIntBits() - color2.toIntBits() : attr.color1.toIntBits() - color1.toIntBits(); } } ShaderProgram program; Camera camera; RenderContext context; int u_projTrans; int u_worldTrans; int u_colorU; int u_colorV; @Override public void init() { String vert = Gdx.files.internal(data + "/uvcolor.vertex.glsl") .readString(); String frag = Gdx.files.internal(data + "/uvcolor.fragment.glsl") .readString(); program = new ShaderProgram(vert, frag); if (!program.isCompiled()) throw new GdxRuntimeException(program.getLog()); u_projTrans = program.getUniformLocation("u_projTrans"); u_worldTrans = program.getUniformLocation("u_worldTrans"); u_colorU = program.getUniformLocation("u_colorU"); u_colorV = program.getUniformLocation("u_colorV"); } @Override public void dispose() { program.dispose(); } @Override public void begin(Camera camera, RenderContext context) { this.camera = camera; this.context = context; program.begin(); program.setUniformMatrix(u_projTrans, camera.combined); context.setDepthTest(GL20.GL_LEQUAL); context.setCullFace(GL20.GL_BACK); } @Override public void render(Renderable renderable) { program.setUniformMatrix(u_worldTrans, renderable.worldTransform); DoubleColorAttribute attribute = ((DoubleColorAttribute) renderable.material .get(DoubleColorAttribute.DiffuseUV)); program.setUniformf(u_colorU, attribute.color1.r, attribute.color1.g, attribute.color1.b); program.setUniformf(u_colorV, attribute.color2.r, attribute.color2.g, attribute.color2.b); renderable.meshPart.render(program); } @Override public void end() { program.end(); } @Override public int compareTo(Shader other) { return 0; } @Override public boolean canRender(Renderable renderable) { return renderable.material.has(DoubleColorAttribute.DiffuseUV); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step4/MaterialTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step4/MaterialTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step4; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.utils.Array; /** * See: http://blog.xoppa.com/using-materials-with-libgdx * @author Xoppa */ public class MaterialTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public Model model; public Array<ModelInstance> instances = new Array<ModelInstance>(); public ModelBatch modelBatch; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 8f, 8f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); for (int x = -5; x <= 5; x+=2) { for (int z = -5; z<=5; z+=2) { ModelInstance instance = new ModelInstance(model, x, 0, z); ColorAttribute attr = ColorAttribute.createDiffuse((x+5f)/10f, (z+5f)/10f, 0, 1); instance.materials.get(0).set(attr); instances.add(instance); } } shader = new TestShader(); shader.init(); modelBatch = new ModelBatch(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); for (ModelInstance instance : instances) modelBatch.render(instance, shader); modelBatch.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); modelBatch.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step4/TestShader.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step4/TestShader.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step4; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.GdxRuntimeException; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class TestShader implements Shader { ShaderProgram program; Camera camera; RenderContext context; int u_projTrans; int u_worldTrans; int u_color; @Override public void init() { String vert = Gdx.files.internal(data+"/color.vertex.glsl").readString(); String frag = Gdx.files.internal(data+"/color.fragment.glsl").readString(); program = new ShaderProgram(vert, frag); if (!program.isCompiled()) throw new GdxRuntimeException(program.getLog()); u_projTrans = program.getUniformLocation("u_projTrans"); u_worldTrans = program.getUniformLocation("u_worldTrans"); u_color = program.getUniformLocation("u_color"); } @Override public void dispose() { program.dispose(); } @Override public void begin(Camera camera, RenderContext context) { this.camera = camera; this.context = context; program.begin(); program.setUniformMatrix(u_projTrans, camera.combined); context.setDepthTest(GL20.GL_LEQUAL); context.setCullFace(GL20.GL_BACK); } @Override public void render(Renderable renderable) { program.setUniformMatrix(u_worldTrans, renderable.worldTransform); Color color = ((ColorAttribute)renderable.material.get(ColorAttribute.Diffuse)).color; program.setUniformf(u_color, color.r, color.g, color.b); renderable.meshPart.render(program); } @Override public void end() { program.end(); } @Override public int compareTo(Shader other) { return 0; } @Override public boolean canRender(Renderable instance) { return true; } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step5/MaterialTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step5/MaterialTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step5; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.utils.Array; /** * See: http://blog.xoppa.com/using-materials-with-libgdx * @author Xoppa */ public class MaterialTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public Model model; public Array<ModelInstance> instances = new Array<ModelInstance>(); public ModelBatch modelBatch; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 8f, 8f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); for (int x = -5; x <= 5; x+=2) { for (int z = -5; z<=5; z+=2) { ModelInstance instance = new ModelInstance(model, x, 0, z); ColorAttribute attr = ColorAttribute.createDiffuse((x+5f)/10f, (z+5f)/10f, 0, 1); instance.materials.get(0).set(attr); instances.add(instance); } } shader = new TestShader(); shader.init(); modelBatch = new ModelBatch(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); for (ModelInstance instance : instances) modelBatch.render(instance, shader); modelBatch.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); modelBatch.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step5/TestShader.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step5/TestShader.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step5; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.GdxRuntimeException; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class TestShader implements Shader { ShaderProgram program; Camera camera; RenderContext context; int u_projTrans; int u_worldTrans; int u_color; @Override public void init() { String vert = Gdx.files.internal(data+"/color.vertex.glsl").readString(); String frag = Gdx.files.internal(data+"/color.fragment.glsl").readString(); program = new ShaderProgram(vert, frag); if (!program.isCompiled()) throw new GdxRuntimeException(program.getLog()); u_projTrans = program.getUniformLocation("u_projTrans"); u_worldTrans = program.getUniformLocation("u_worldTrans"); u_color = program.getUniformLocation("u_color"); } @Override public void dispose() { program.dispose(); } @Override public void begin(Camera camera, RenderContext context) { this.camera = camera; this.context = context; program.begin(); program.setUniformMatrix(u_projTrans, camera.combined); context.setDepthTest(GL20.GL_LEQUAL); context.setCullFace(GL20.GL_BACK); } @Override public void render(Renderable renderable) { program.setUniformMatrix(u_worldTrans, renderable.worldTransform); Color color = ((ColorAttribute)renderable.material.get(ColorAttribute.Diffuse)).color; program.setUniformf(u_color, color.r, color.g, color.b); renderable.meshPart.render(program); } @Override public void end() { program.end(); } @Override public int compareTo(Shader other) { return 0; } @Override public boolean canRender(Renderable renderable) { return renderable.material.has(ColorAttribute.Diffuse); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step7/MaterialTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step7/MaterialTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step7; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.utils.Array; import com.xoppa.blog.libgdx.g3d.usingmaterials.step7.TestShader.TestColorAttribute; /** * See: http://blog.xoppa.com/using-materials-with-libgdx * @author Xoppa */ public class MaterialTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public Model model; public Array<ModelInstance> instances = new Array<ModelInstance>(); public ModelBatch modelBatch; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 8f, 8f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); for (int x = -5; x <= 5; x+=2) { for (int z = -5; z<=5; z+=2) { ModelInstance instance = new ModelInstance(model, x, 0, z); ColorAttribute attrU = new TestColorAttribute(TestColorAttribute.DiffuseU, (x+5f)/10f, 1f - (z+5f)/10f, 0, 1); instance.materials.get(0).set(attrU); ColorAttribute attrV = new TestColorAttribute(TestColorAttribute.DiffuseV, 1f - (x+5f)/10f, 0, (z+5f)/10f, 1); instance.materials.get(0).set(attrV); instances.add(instance); } } shader = new TestShader(); shader.init(); modelBatch = new ModelBatch(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); for (ModelInstance instance : instances) modelBatch.render(instance, shader); modelBatch.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); modelBatch.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step7/TestShader.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step7/TestShader.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step7; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.GdxRuntimeException; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class TestShader implements Shader { public static class TestColorAttribute extends ColorAttribute { public final static String DiffuseUAlias = "diffuseUColor"; public final static long DiffuseU = register(DiffuseUAlias); public final static String DiffuseVAlias = "diffuseVColor"; public final static long DiffuseV = register(DiffuseVAlias); static { Mask = Mask | DiffuseU | DiffuseV; } public TestColorAttribute (long type, float r, float g, float b, float a) { super(type, r, g, b, a); } } ShaderProgram program; Camera camera; RenderContext context; int u_projTrans; int u_worldTrans; int u_colorU; int u_colorV; @Override public void init() { String vert = Gdx.files.internal(data+"/uvcolor.vertex.glsl").readString(); String frag = Gdx.files.internal(data+"/uvcolor.fragment.glsl").readString(); program = new ShaderProgram(vert, frag); if (!program.isCompiled()) throw new GdxRuntimeException(program.getLog()); u_projTrans = program.getUniformLocation("u_projTrans"); u_worldTrans = program.getUniformLocation("u_worldTrans"); u_colorU = program.getUniformLocation("u_colorU"); u_colorV = program.getUniformLocation("u_colorV"); } @Override public void dispose() { program.dispose(); } @Override public void begin(Camera camera, RenderContext context) { this.camera = camera; this.context = context; program.begin(); program.setUniformMatrix(u_projTrans, camera.combined); context.setDepthTest(GL20.GL_LEQUAL); context.setCullFace(GL20.GL_BACK); } @Override public void render(Renderable renderable) { program.setUniformMatrix(u_worldTrans, renderable.worldTransform); Color colorU = ((ColorAttribute)renderable.material.get(TestColorAttribute.DiffuseU)).color; Color colorV = ((ColorAttribute)renderable.material.get(TestColorAttribute.DiffuseV)).color; program.setUniformf(u_colorU, colorU.r, colorU.g, colorU.b); program.setUniformf(u_colorV, colorV.r, colorV.g, colorV.b); renderable.meshPart.render(program); } @Override public void end() { program.end(); } @Override public int compareTo(Shader other) { return 0; } @Override public boolean canRender(Renderable renderable) { return renderable.material.has(ColorAttribute.Diffuse); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step1/MaterialTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step1/MaterialTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step1; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.utils.Array; /** * See: http://blog.xoppa.com/using-materials-with-libgdx * @author Xoppa */ public class MaterialTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public Model model; public Array<ModelInstance> instances = new Array<ModelInstance>(); public ModelBatch modelBatch; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 8f, 8f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); for (int x = -5; x <= 5; x+=2) { for (int z = -5; z<=5; z+=2) { instances.add(new ModelInstance(model, x, 0, z)); } } shader = new TestShader(); shader.init(); modelBatch = new ModelBatch(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); for (ModelInstance instance : instances) modelBatch.render(instance, shader); modelBatch.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); modelBatch.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step1/TestShader.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step1/TestShader.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step1; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.GdxRuntimeException; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class TestShader implements Shader { ShaderProgram program; Camera camera; RenderContext context; int u_projTrans; int u_worldTrans; @Override public void init() { String vert = Gdx.files.internal(data+"/test.vertex.glsl").readString(); String frag = Gdx.files.internal(data+"/test.fragment.glsl").readString(); program = new ShaderProgram(vert, frag); if (!program.isCompiled()) throw new GdxRuntimeException(program.getLog()); u_projTrans = program.getUniformLocation("u_projTrans"); u_worldTrans = program.getUniformLocation("u_worldTrans"); } @Override public void dispose() { program.dispose(); } @Override public void begin(Camera camera, RenderContext context) { this.camera = camera; this.context = context; program.begin(); program.setUniformMatrix(u_projTrans, camera.combined); context.setDepthTest(GL20.GL_LEQUAL); context.setCullFace(GL20.GL_BACK); } @Override public void render(Renderable renderable) { program.setUniformMatrix(u_worldTrans, renderable.worldTransform); renderable.meshPart.render(program); } @Override public void end() { program.end(); } @Override public int compareTo(Shader other) { return 0; } @Override public boolean canRender(Renderable instance) { return true; } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step6/MaterialTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step6/MaterialTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step6; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.utils.Array; /** * See: http://blog.xoppa.com/using-materials-with-libgdx * @author Xoppa */ public class MaterialTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public Model model; public Array<ModelInstance> instances = new Array<ModelInstance>(); public ModelBatch modelBatch; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 8f, 8f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); for (int x = -5; x <= 5; x+=2) { for (int z = -5; z<=5; z+=2) { ModelInstance instance = new ModelInstance(model, x, 0, z); ColorAttribute attr = ColorAttribute.createDiffuse((x+5f)/10f, (z+5f)/10f, 0, 1); instance.materials.get(0).set(attr); instances.add(instance); } } shader = new TestShader(); shader.init(); modelBatch = new ModelBatch(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); for (ModelInstance instance : instances) modelBatch.render(instance, shader); modelBatch.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); modelBatch.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step6/TestShader.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step6/TestShader.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step6; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.GdxRuntimeException; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class TestShader implements Shader { ShaderProgram program; Camera camera; RenderContext context; int u_projTrans; int u_worldTrans; int u_colorU; int u_colorV; @Override public void init() { String vert = Gdx.files.internal(data+"/uvcolor.vertex.glsl").readString(); String frag = Gdx.files.internal(data+"/uvcolor.fragment.glsl").readString(); program = new ShaderProgram(vert, frag); if (!program.isCompiled()) throw new GdxRuntimeException(program.getLog()); u_projTrans = program.getUniformLocation("u_projTrans"); u_worldTrans = program.getUniformLocation("u_worldTrans"); u_colorU = program.getUniformLocation("u_colorU"); u_colorV = program.getUniformLocation("u_colorV"); } @Override public void dispose() { program.dispose(); } @Override public void begin(Camera camera, RenderContext context) { this.camera = camera; this.context = context; program.begin(); program.setUniformMatrix(u_projTrans, camera.combined); context.setDepthTest(GL20.GL_LEQUAL); context.setCullFace(GL20.GL_BACK); } @Override public void render(Renderable renderable) { program.setUniformMatrix(u_worldTrans, renderable.worldTransform); Color colorU = ((ColorAttribute)renderable.material.get(ColorAttribute.Diffuse)).color; Color colorV = Color.BLUE; program.setUniformf(u_colorU, colorU.r, colorU.g, colorU.b); program.setUniformf(u_colorV, colorV.r, colorV.g, colorV.b); renderable.meshPart.render(program); } @Override public void end() { program.end(); } @Override public int compareTo(Shader other) { return 0; } @Override public boolean canRender(Renderable renderable) { return renderable.material.has(ColorAttribute.Diffuse); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step3/MaterialTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step3/MaterialTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step3; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.utils.Array; /** * See: http://blog.xoppa.com/using-materials-with-libgdx * @author Xoppa */ public class MaterialTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public Model model; public Array<ModelInstance> instances = new Array<ModelInstance>(); public ModelBatch modelBatch; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 8f, 8f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); for (int x = -5; x <= 5; x+=2) { for (int z = -5; z<=5; z+=2) { ModelInstance instance = new ModelInstance(model, x, 0, z); instance.userData = new Color((x+5f)/10f, (z+5f)/10f, 0, 1); instances.add(instance); } } shader = new TestShader(); shader.init(); modelBatch = new ModelBatch(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); for (ModelInstance instance : instances) modelBatch.render(instance, shader); modelBatch.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); modelBatch.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step3/TestShader.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step3/TestShader.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step3; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.GdxRuntimeException; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class TestShader implements Shader { ShaderProgram program; Camera camera; RenderContext context; int u_projTrans; int u_worldTrans; int u_color; @Override public void init() { String vert = Gdx.files.internal(data+"/color.vertex.glsl").readString(); String frag = Gdx.files.internal(data+"/color.fragment.glsl").readString(); program = new ShaderProgram(vert, frag); if (!program.isCompiled()) throw new GdxRuntimeException(program.getLog()); u_projTrans = program.getUniformLocation("u_projTrans"); u_worldTrans = program.getUniformLocation("u_worldTrans"); u_color = program.getUniformLocation("u_color"); } @Override public void dispose() { program.dispose(); } @Override public void begin(Camera camera, RenderContext context) { this.camera = camera; this.context = context; program.begin(); program.setUniformMatrix(u_projTrans, camera.combined); context.setDepthTest(GL20.GL_LEQUAL); context.setCullFace(GL20.GL_BACK); } @Override public void render(Renderable renderable) { program.setUniformMatrix(u_worldTrans, renderable.worldTransform); Color color = (Color)renderable.userData; program.setUniformf(u_color, color.r, color.g, color.b); renderable.meshPart.render(program); } @Override public void end() { program.end(); } @Override public int compareTo(Shader other) { return 0; } @Override public boolean canRender(Renderable instance) { return true; } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step2/MaterialTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step2/MaterialTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step2; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.utils.Array; /** * See: http://blog.xoppa.com/using-materials-with-libgdx * @author Xoppa */ public class MaterialTest implements ApplicationListener { public PerspectiveCamera cam; public CameraInputController camController; public Shader shader; public Model model; public Array<ModelInstance> instances = new Array<ModelInstance>(); public ModelBatch modelBatch; @Override public void create () { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 8f, 8f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20, new Material(), Usage.Position | Usage.Normal | Usage.TextureCoordinates); for (int x = -5; x <= 5; x+=2) { for (int z = -5; z<=5; z+=2) { instances.add(new ModelInstance(model, x, 0, z)); } } shader = new TestShader(); shader.init(); modelBatch = new ModelBatch(); } @Override public void render () { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); for (ModelInstance instance : instances) modelBatch.render(instance, shader); modelBatch.end(); } @Override public void dispose () { shader.dispose(); model.dispose(); modelBatch.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step2/TestShader.java
tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step2/TestShader.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.xoppa.blog.libgdx.g3d.usingmaterials.step2; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.GdxRuntimeException; /** * See: http://blog.xoppa.com/creating-a-shader-with-libgdx * @author Xoppa */ public class TestShader implements Shader { ShaderProgram program; Camera camera; RenderContext context; int u_projTrans; int u_worldTrans; int u_color; @Override public void init() { String vert = Gdx.files.internal(data+"/color.vertex.glsl").readString(); String frag = Gdx.files.internal(data+"/color.fragment.glsl").readString(); program = new ShaderProgram(vert, frag); if (!program.isCompiled()) throw new GdxRuntimeException(program.getLog()); u_projTrans = program.getUniformLocation("u_projTrans"); u_worldTrans = program.getUniformLocation("u_worldTrans"); u_color = program.getUniformLocation("u_color"); } @Override public void dispose() { program.dispose(); } @Override public void begin(Camera camera, RenderContext context) { this.camera = camera; this.context = context; program.begin(); program.setUniformMatrix(u_projTrans, camera.combined); context.setDepthTest(GL20.GL_LEQUAL); context.setCullFace(GL20.GL_BACK); } @Override public void render(Renderable renderable) { program.setUniformMatrix(u_worldTrans, renderable.worldTransform); program.setUniformf(u_color, MathUtils.random(), MathUtils.random(), MathUtils.random()); renderable.meshPart.render(program); } @Override public void end() { program.end(); } @Override public int compareTo(Shader other) { return 0; } @Override public boolean canRender(Renderable instance) { return true; } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/raypicking/step1/RayPickingTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/raypicking/step1/RayPickingTest.java
package com.xoppa.blog.libgdx.g3d.raypicking.step1; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.math.collision.Ray; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.Array; /** @see <a href="http://blog.xoppa.com/interacting-with-3d-objects/"Interacting with 3d objects</a> * @author Xoppa */ public class RayPickingTest extends InputAdapter implements ApplicationListener { public static class GameObject extends ModelInstance { public final Vector3 center = new Vector3(); public final Vector3 dimensions = new Vector3(); public final float radius; private final static BoundingBox bounds = new BoundingBox(); public GameObject (Model model, String rootNode, boolean mergeTransform) { super(model, rootNode, mergeTransform); calculateBoundingBox(bounds); bounds.getCenter(center); bounds.getDimensions(dimensions); radius = dimensions.len() / 2f; } } protected PerspectiveCamera cam; protected CameraInputController camController; protected ModelBatch modelBatch; protected AssetManager assets; protected Array<GameObject> instances = new Array<GameObject>(); protected Environment environment; protected boolean loading; protected Array<GameObject> blocks = new Array<GameObject>(); protected Array<GameObject> invaders = new Array<GameObject>(); protected ModelInstance ship; protected ModelInstance space; protected Stage stage; protected Label label; protected BitmapFont font; protected StringBuilder stringBuilder; private int visibleCount; private Vector3 position = new Vector3(); private int selected = -1, selecting = -1; private Material selectionMaterial; private Material originalMaterial; @Override public void create () { stage = new Stage(); font = new BitmapFont(); label = new Label(" ", new Label.LabelStyle(font, Color.WHITE)); stage.addActor(label); stringBuilder = new StringBuilder(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0, 0, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(new InputMultiplexer(this, camController)); assets = new AssetManager(); assets.load(data + "/invaderscene.g3db", Model.class); loading = true; selectionMaterial = new Material(); selectionMaterial.set(ColorAttribute.createDiffuse(Color.ORANGE)); originalMaterial = new Material(); } private void doneLoading () { Model model = assets.get(data + "/invaderscene.g3db", Model.class); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; GameObject instance = new GameObject(model, id, true); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) ship = instance; else if (id.startsWith("block")) blocks.add(instance); else if (id.startsWith("invader")) invaders.add(instance); } loading = false; } @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); visibleCount = 0; for (final GameObject instance : instances) { if (isVisible(cam, instance)) { modelBatch.render(instance, environment); visibleCount++; } } if (space != null) modelBatch.render(space); modelBatch.end(); stringBuilder.setLength(0); stringBuilder.append(" FPS: ").append(Gdx.graphics.getFramesPerSecond()); stringBuilder.append(" Visible: ").append(visibleCount); stringBuilder.append(" Selected: ").append(selected); label.setText(stringBuilder); stage.draw(); } protected boolean isVisible (final Camera cam, final GameObject instance) { instance.transform.getTranslation(position); position.add(instance.center); return cam.frustum.sphereInFrustum(position, instance.radius); } @Override public boolean touchDown (int screenX, int screenY, int pointer, int button) { selecting = getObject(screenX, screenY); return selecting >= 0; } @Override public boolean touchDragged (int screenX, int screenY, int pointer) { return selecting >= 0; } @Override public boolean touchUp (int screenX, int screenY, int pointer, int button) { if (selecting >= 0) { if (selecting == getObject(screenX, screenY)) setSelected(selecting); selecting = -1; return true; } return false; } public void setSelected (int value) { if (selected == value) return; if (selected >= 0) { Material mat = instances.get(selected).materials.get(0); mat.clear(); mat.set(originalMaterial); } selected = value; if (selected >= 0) { Material mat = instances.get(selected).materials.get(0); originalMaterial.clear(); originalMaterial.set(mat); mat.clear(); mat.set(selectionMaterial); } } public int getObject (int screenX, int screenY) { Ray ray = cam.getPickRay(screenX, screenY); int result = -1; float distance = -1; for (int i = 0; i < instances.size; ++i) { final GameObject instance = instances.get(i); instance.transform.getTranslation(position); position.add(instance.center); float dist2 = ray.origin.dst2(position); if (distance >= 0f && dist2 > distance) continue; if (Intersector.intersectRaySphere(ray, position, instance.radius, null)) { result = i; distance = dist2; } } return result; } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize (int width, int height) { stage.getViewport().update(width, height, true); } @Override public void pause () { } @Override public void resume () { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/raypicking/step3/RayPickingTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/raypicking/step3/RayPickingTest.java
package com.xoppa.blog.libgdx.g3d.raypicking.step3; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.math.collision.Ray; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.Array; /** @see <a href="http://blog.xoppa.com/interacting-with-3d-objects/"Interacting with 3d objects</a> * @author Xoppa */ public class RayPickingTest extends InputAdapter implements ApplicationListener { public static class GameObject extends ModelInstance { public final Vector3 center = new Vector3(); public final Vector3 dimensions = new Vector3(); public final float radius; private final static BoundingBox bounds = new BoundingBox(); public GameObject (Model model, String rootNode, boolean mergeTransform) { super(model, rootNode, mergeTransform); calculateBoundingBox(bounds); bounds.getCenter(center); bounds.getDimensions(dimensions); radius = dimensions.len() / 2f; } } protected PerspectiveCamera cam; protected CameraInputController camController; protected ModelBatch modelBatch; protected AssetManager assets; protected Array<GameObject> instances = new Array<GameObject>(); protected Environment environment; protected boolean loading; protected Array<GameObject> blocks = new Array<GameObject>(); protected Array<GameObject> invaders = new Array<GameObject>(); protected ModelInstance ship; protected ModelInstance space; protected Stage stage; protected Label label; protected BitmapFont font; protected StringBuilder stringBuilder; private int visibleCount; private Vector3 position = new Vector3(); private int selected = -1, selecting = -1; private Material selectionMaterial; private Material originalMaterial; @Override public void create () { stage = new Stage(); font = new BitmapFont(); label = new Label(" ", new Label.LabelStyle(font, Color.WHITE)); stage.addActor(label); stringBuilder = new StringBuilder(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0, 0, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(new InputMultiplexer(this, camController)); assets = new AssetManager(); assets.load(data + "/invaderscene.g3db", Model.class); loading = true; selectionMaterial = new Material(); selectionMaterial.set(ColorAttribute.createDiffuse(Color.ORANGE)); originalMaterial = new Material(); } private void doneLoading () { Model model = assets.get(data + "/invaderscene.g3db", Model.class); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; GameObject instance = new GameObject(model, id, true); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) ship = instance; else if (id.startsWith("block")) blocks.add(instance); else if (id.startsWith("invader")) invaders.add(instance); } loading = false; } @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); visibleCount = 0; for (final GameObject instance : instances) { if (isVisible(cam, instance)) { modelBatch.render(instance, environment); visibleCount++; } } if (space != null) modelBatch.render(space); modelBatch.end(); stringBuilder.setLength(0); stringBuilder.append(" FPS: ").append(Gdx.graphics.getFramesPerSecond()); stringBuilder.append(" Visible: ").append(visibleCount); stringBuilder.append(" Selected: ").append(selected); label.setText(stringBuilder); stage.draw(); } protected boolean isVisible (final Camera cam, final GameObject instance) { instance.transform.getTranslation(position); position.add(instance.center); return cam.frustum.sphereInFrustum(position, instance.radius); } @Override public boolean touchDown (int screenX, int screenY, int pointer, int button) { selecting = getObject(screenX, screenY); return selecting >= 0; } @Override public boolean touchDragged (int screenX, int screenY, int pointer) { if (selecting < 0) return false; if (selected == selecting) { Ray ray = cam.getPickRay(screenX, screenY); final float distance = -ray.origin.y / ray.direction.y; position.set(ray.direction).scl(distance).add(ray.origin); instances.get(selected).transform.setTranslation(position); } return true; } @Override public boolean touchUp (int screenX, int screenY, int pointer, int button) { if (selecting >= 0) { if (selecting == getObject(screenX, screenY)) setSelected(selecting); selecting = -1; return true; } return false; } public void setSelected (int value) { if (selected == value) return; if (selected >= 0) { Material mat = instances.get(selected).materials.get(0); mat.clear(); mat.set(originalMaterial); } selected = value; if (selected >= 0) { Material mat = instances.get(selected).materials.get(0); originalMaterial.clear(); originalMaterial.set(mat); mat.clear(); mat.set(selectionMaterial); } } public int getObject (int screenX, int screenY) { Ray ray = cam.getPickRay(screenX, screenY); int result = -1; float distance = -1; for (int i = 0; i < instances.size; ++i) { final GameObject instance = instances.get(i); instance.transform.getTranslation(position); position.add(instance.center); final float len = ray.direction.dot(position.x-ray.origin.x, position.y-ray.origin.y, position.z-ray.origin.z); if (len < 0f) continue; float dist2 = position.dst2(ray.origin.x+ray.direction.x*len, ray.origin.y+ray.direction.y*len, ray.origin.z+ray.direction.z*len); if (distance >= 0f && dist2 > distance) continue; if (dist2 <= instance.radius * instance.radius) { result = i; distance = dist2; } } return result; } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize (int width, int height) { stage.getViewport().update(width, height, true); } @Override public void pause () { } @Override public void resume () { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/raypicking/step2/RayPickingTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/raypicking/step2/RayPickingTest.java
package com.xoppa.blog.libgdx.g3d.raypicking.step2; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.math.collision.Ray; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.Array; /** @see <a href="http://blog.xoppa.com/interacting-with-3d-objects/"Interacting with 3d objects</a> * @author Xoppa */ public class RayPickingTest extends InputAdapter implements ApplicationListener { public static class GameObject extends ModelInstance { public final Vector3 center = new Vector3(); public final Vector3 dimensions = new Vector3(); public final float radius; private final static BoundingBox bounds = new BoundingBox(); public GameObject (Model model, String rootNode, boolean mergeTransform) { super(model, rootNode, mergeTransform); calculateBoundingBox(bounds); bounds.getCenter(center); bounds.getDimensions(dimensions); radius = dimensions.len() / 2f; } } protected PerspectiveCamera cam; protected CameraInputController camController; protected ModelBatch modelBatch; protected AssetManager assets; protected Array<GameObject> instances = new Array<GameObject>(); protected Environment environment; protected boolean loading; protected Array<GameObject> blocks = new Array<GameObject>(); protected Array<GameObject> invaders = new Array<GameObject>(); protected ModelInstance ship; protected ModelInstance space; protected Stage stage; protected Label label; protected BitmapFont font; protected StringBuilder stringBuilder; private int visibleCount; private Vector3 position = new Vector3(); private int selected = -1, selecting = -1; private Material selectionMaterial; private Material originalMaterial; @Override public void create () { stage = new Stage(); font = new BitmapFont(); label = new Label(" ", new Label.LabelStyle(font, Color.WHITE)); stage.addActor(label); stringBuilder = new StringBuilder(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0, 0, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(new InputMultiplexer(this, camController)); assets = new AssetManager(); assets.load(data + "/invaderscene.g3db", Model.class); loading = true; selectionMaterial = new Material(); selectionMaterial.set(ColorAttribute.createDiffuse(Color.ORANGE)); originalMaterial = new Material(); } private void doneLoading () { Model model = assets.get(data + "/invaderscene.g3db", Model.class); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; GameObject instance = new GameObject(model, id, true); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) ship = instance; else if (id.startsWith("block")) blocks.add(instance); else if (id.startsWith("invader")) invaders.add(instance); } loading = false; } @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); visibleCount = 0; for (final GameObject instance : instances) { if (isVisible(cam, instance)) { modelBatch.render(instance, environment); visibleCount++; } } if (space != null) modelBatch.render(space); modelBatch.end(); stringBuilder.setLength(0); stringBuilder.append(" FPS: ").append(Gdx.graphics.getFramesPerSecond()); stringBuilder.append(" Visible: ").append(visibleCount); stringBuilder.append(" Selected: ").append(selected); label.setText(stringBuilder); stage.draw(); } protected boolean isVisible (final Camera cam, final GameObject instance) { instance.transform.getTranslation(position); position.add(instance.center); return cam.frustum.sphereInFrustum(position, instance.radius); } @Override public boolean touchDown (int screenX, int screenY, int pointer, int button) { selecting = getObject(screenX, screenY); return selecting >= 0; } @Override public boolean touchDragged (int screenX, int screenY, int pointer) { if (selecting < 0) return false; if (selected == selecting) { Ray ray = cam.getPickRay(screenX, screenY); final float distance = -ray.origin.y / ray.direction.y; position.set(ray.direction).scl(distance).add(ray.origin); instances.get(selected).transform.setTranslation(position); } return true; } @Override public boolean touchUp (int screenX, int screenY, int pointer, int button) { if (selecting >= 0) { if (selecting == getObject(screenX, screenY)) setSelected(selecting); selecting = -1; return true; } return false; } public void setSelected (int value) { if (selected == value) return; if (selected >= 0) { Material mat = instances.get(selected).materials.get(0); mat.clear(); mat.set(originalMaterial); } selected = value; if (selected >= 0) { Material mat = instances.get(selected).materials.get(0); originalMaterial.clear(); originalMaterial.set(mat); mat.clear(); mat.set(selectionMaterial); } } public int getObject (int screenX, int screenY) { Ray ray = cam.getPickRay(screenX, screenY); int result = -1; float distance = -1; for (int i = 0; i < instances.size; ++i) { final GameObject instance = instances.get(i); instance.transform.getTranslation(position); position.add(instance.center); float dist2 = ray.origin.dst2(position); if (distance >= 0f && dist2 > distance) continue; if (Intersector.intersectRaySphere(ray, position, instance.radius, null)) { result = i; distance = dist2; } } return result; } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize (int width, int height) { stage.getViewport().update(width, height, true); } @Override public void pause () { } @Override public void resume () { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step8/CardGame.java
tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step8/CardGame.java
package com.xoppa.blog.libgdx.g3d.cardgame.step8; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.RenderableProvider; import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute; import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.ObjectSet; import com.badlogic.gdx.utils.Pool; public class CardGame implements ApplicationListener { public final static float CARD_WIDTH = 1f; public final static float CARD_HEIGHT = CARD_WIDTH * 277f / 200f; public final static float MINIMUM_VIEWPORT_SIZE = 5f; public enum Suit { Clubs("clubs", 0), Diamonds("diamonds", 1), Hearts("hearts", 2), Spades("spades", 3); public final String name; public final int index; private Suit(String name, int index) { this.name = name; this.index = index; } } public enum Pip { Ace(1), Two(2), Three(3), Four(4), Five(5), Six(6), Seven(7), Eight(8), Nine(9), Ten(10), Jack(11), Queen(12), King(13); public final int value; public final int index; private Pip(int value) { this.value = value; this.index = value - 1; } } public static class Card { public final Suit suit; public final Pip pip; public final float[] vertices; public final short[] indices; public final Matrix4 transform = new Matrix4(); public Card(Suit suit, Pip pip, Sprite back, Sprite front) { assert(front.getTexture() == back.getTexture()); this.suit = suit; this.pip = pip; front.setSize(CARD_WIDTH, CARD_HEIGHT); back.setSize(CARD_WIDTH, CARD_HEIGHT); front.setPosition(-front.getWidth() * 0.5f, -front.getHeight() * 0.5f); back.setPosition(-back.getWidth() * 0.5f, -back.getHeight() * 0.5f); vertices = convert(front.getVertices(), back.getVertices()); indices = new short[] {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4 }; } private static float[] convert(float[] front, float[] back) { return new float[] { front[Batch.X2], front[Batch.Y2], 0, 0, 0, 1, front[Batch.U2], front[Batch.V2], front[Batch.X1], front[Batch.Y1], 0, 0, 0, 1, front[Batch.U1], front[Batch.V1], front[Batch.X4], front[Batch.Y4], 0, 0, 0, 1, front[Batch.U4], front[Batch.V4], front[Batch.X3], front[Batch.Y3], 0, 0, 0, 1, front[Batch.U3], front[Batch.V3], back[Batch.X1], back[Batch.Y1], 0, 0, 0, -1, back[Batch.U1], back[Batch.V1], back[Batch.X2], back[Batch.Y2], 0, 0, 0, -1, back[Batch.U2], back[Batch.V2], back[Batch.X3], back[Batch.Y3], 0, 0, 0, -1, back[Batch.U3], back[Batch.V3], back[Batch.X4], back[Batch.Y4], 0, 0, 0, -1, back[Batch.U4], back[Batch.V4] }; } } public static class CardDeck { private final Card[][] cards; public CardDeck(TextureAtlas atlas, int backIndex) { cards = new Card[Suit.values().length][]; for (Suit suit : Suit.values()) { cards[suit.index] = new Card[Pip.values().length]; for (Pip pip : Pip.values()) { Sprite front = atlas.createSprite(suit.name, pip.value); Sprite back = atlas.createSprite("back", backIndex); cards[suit.index][pip.index] = new Card(suit, pip, back, front); } } } public Card getCard(Suit suit, Pip pip) { return cards[suit.index][pip.index]; } } public static class CardBatch extends ObjectSet<Card> implements RenderableProvider, Disposable { Renderable renderable; Mesh mesh; MeshBuilder meshBuilder; public CardBatch(Material material) { final int maxNumberOfCards = 52; final int maxNumberOfVertices = maxNumberOfCards * 8; final int maxNumberOfIndices = maxNumberOfCards * 12; mesh = new Mesh(false, maxNumberOfVertices, maxNumberOfIndices, VertexAttribute.Position(), VertexAttribute.Normal(), VertexAttribute.TexCoords(0)); meshBuilder = new MeshBuilder(); renderable = new Renderable(); renderable.material = material; } @Override public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) { meshBuilder.begin(mesh.getVertexAttributes()); meshBuilder.part("cards", GL20.GL_TRIANGLES, renderable.meshPart); for (Card card : this) { meshBuilder.setVertexTransform(card.transform); meshBuilder.addMesh(card.vertices, card.indices); } meshBuilder.end(mesh); renderables.add(renderable); } @Override public void dispose() { mesh.dispose(); } } TextureAtlas atlas; Sprite front; Sprite back; PerspectiveCamera cam; CardDeck deck; CardBatch cards; CameraInputController camController; ModelBatch modelBatch; Model tableTopModel; ModelInstance tableTop; Environment environment; @Override public void create() { modelBatch = new ModelBatch(); atlas = new TextureAtlas(data + "/carddeck.atlas"); Material material = new Material( TextureAttribute.createDiffuse(atlas.getTextures().first()), new BlendingAttribute(false, 1f), FloatAttribute.createAlphaTest(0.5f)); cards = new CardBatch(material); deck = new CardDeck(atlas, 3); Card card1 = deck.getCard(Suit.Diamonds, Pip.Queen); card1.transform.translate(-1, 0, 0); cards.add(card1); Card card2 = deck.getCard(Suit.Hearts, Pip.Seven); card2.transform.translate(0, 0, 0); cards.add(card2); Card card3 = deck.getCard(Suit.Spades, Pip.Ace); card3.transform.translate(1, 0, 0); cards.add(card3); cam = new PerspectiveCamera(); cam.position.set(0, 0, 10); cam.lookAt(0, 0, 0); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder builder = new ModelBuilder(); builder.begin(); builder.node().id = "top"; builder.part("top", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(new Color(0x63750A)))) .box(0f, 0f, -0.5f, 20f, 20f, 1f); tableTopModel = builder.end(); tableTop = new ModelInstance(tableTopModel); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1.f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -.4f, -.4f, -.4f)); } @Override public void resize(int width, int height) { float halfHeight = MINIMUM_VIEWPORT_SIZE * 0.5f; if (height > width) halfHeight *= (float)height / (float)width; float halfFovRadians = MathUtils.degreesToRadians * cam.fieldOfView * 0.5f; float distance = halfHeight / (float)Math.tan(halfFovRadians); cam.viewportWidth = width; cam.viewportHeight = height; cam.position.set(0, 0, distance); cam.lookAt(0, 0, 0); cam.update(); } @Override public void render() { final float delta = Math.min(1/30f, Gdx.graphics.getDeltaTime()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); camController.update(); cards.first().transform.rotate(Vector3.Y, 90 * delta); modelBatch.begin(cam); modelBatch.render(tableTop, environment); modelBatch.render(cards, environment); modelBatch.end(); } @Override public void pause() { // TODO Auto-generated method stub } @Override public void resume() { // TODO Auto-generated method stub } @Override public void dispose() { modelBatch.dispose(); atlas.dispose(); cards.dispose(); tableTopModel.dispose(); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step9/CardGame.java
tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step9/CardGame.java
package com.xoppa.blog.libgdx.g3d.cardgame.step9; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.RenderableProvider; import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute; import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.ObjectSet; import com.badlogic.gdx.utils.Pool; public class CardGame implements ApplicationListener { public final static float CARD_WIDTH = 1f; public final static float CARD_HEIGHT = CARD_WIDTH * 277f / 200f; public final static float MINIMUM_VIEWPORT_SIZE = 5f; public enum Suit { Clubs("clubs", 0), Diamonds("diamonds", 1), Hearts("hearts", 2), Spades("spades", 3); public final String name; public final int index; private Suit(String name, int index) { this.name = name; this.index = index; } } public enum Pip { Ace(1), Two(2), Three(3), Four(4), Five(5), Six(6), Seven(7), Eight(8), Nine(9), Ten(10), Jack(11), Queen(12), King(13); public final int value; public final int index; private Pip(int value) { this.value = value; this.index = value - 1; } } public static class Card { public final Suit suit; public final Pip pip; public final float[] vertices; public final short[] indices; public final Matrix4 transform = new Matrix4(); public final Vector3 position = new Vector3(); public float angle; public Card(Suit suit, Pip pip, Sprite back, Sprite front) { assert(front.getTexture() == back.getTexture()); this.suit = suit; this.pip = pip; front.setSize(CARD_WIDTH, CARD_HEIGHT); back.setSize(CARD_WIDTH, CARD_HEIGHT); front.setPosition(-front.getWidth() * 0.5f, -front.getHeight() * 0.5f); back.setPosition(-back.getWidth() * 0.5f, -back.getHeight() * 0.5f); vertices = convert(front.getVertices(), back.getVertices()); indices = new short[] {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4 }; } private static float[] convert(float[] front, float[] back) { return new float[] { front[Batch.X2], front[Batch.Y2], 0, 0, 0, 1, front[Batch.U2], front[Batch.V2], front[Batch.X1], front[Batch.Y1], 0, 0, 0, 1, front[Batch.U1], front[Batch.V1], front[Batch.X4], front[Batch.Y4], 0, 0, 0, 1, front[Batch.U4], front[Batch.V4], front[Batch.X3], front[Batch.Y3], 0, 0, 0, 1, front[Batch.U3], front[Batch.V3], back[Batch.X1], back[Batch.Y1], 0, 0, 0, -1, back[Batch.U1], back[Batch.V1], back[Batch.X2], back[Batch.Y2], 0, 0, 0, -1, back[Batch.U2], back[Batch.V2], back[Batch.X3], back[Batch.Y3], 0, 0, 0, -1, back[Batch.U3], back[Batch.V3], back[Batch.X4], back[Batch.Y4], 0, 0, 0, -1, back[Batch.U4], back[Batch.V4] }; } public void update() { float z = position.z + 0.5f * Math.abs(MathUtils.sinDeg(angle)); transform.setToRotation(Vector3.Y, angle); transform.trn(position.x, position.y, z); } } public static class CardDeck { private final Card[][] cards; public CardDeck(TextureAtlas atlas, int backIndex) { cards = new Card[Suit.values().length][]; for (Suit suit : Suit.values()) { cards[suit.index] = new Card[Pip.values().length]; for (Pip pip : Pip.values()) { Sprite front = atlas.createSprite(suit.name, pip.value); Sprite back = atlas.createSprite("back", backIndex); cards[suit.index][pip.index] = new Card(suit, pip, back, front); } } } public Card getCard(Suit suit, Pip pip) { return cards[suit.index][pip.index]; } } public static class CardBatch extends ObjectSet<Card> implements RenderableProvider, Disposable { Renderable renderable; Mesh mesh; MeshBuilder meshBuilder; public CardBatch(Material material) { final int maxNumberOfCards = 52; final int maxNumberOfVertices = maxNumberOfCards * 8; final int maxNumberOfIndices = maxNumberOfCards * 12; mesh = new Mesh(false, maxNumberOfVertices, maxNumberOfIndices, VertexAttribute.Position(), VertexAttribute.Normal(), VertexAttribute.TexCoords(0)); meshBuilder = new MeshBuilder(); renderable = new Renderable(); renderable.material = material; } @Override public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) { meshBuilder.begin(mesh.getVertexAttributes()); meshBuilder.part("cards", GL20.GL_TRIANGLES, renderable.meshPart); for (Card card : this) { meshBuilder.setVertexTransform(card.transform); meshBuilder.addMesh(card.vertices, card.indices); } meshBuilder.end(mesh); renderables.add(renderable); } @Override public void dispose() { mesh.dispose(); } } TextureAtlas atlas; Sprite front; Sprite back; PerspectiveCamera cam; CardDeck deck; CardBatch cards; CameraInputController camController; ModelBatch modelBatch; Model tableTopModel; ModelInstance tableTop; Environment environment; @Override public void create() { modelBatch = new ModelBatch(); atlas = new TextureAtlas(data + "/carddeck.atlas"); Material material = new Material( TextureAttribute.createDiffuse(atlas.getTextures().first()), new BlendingAttribute(false, 1f), FloatAttribute.createAlphaTest(0.5f)); cards = new CardBatch(material); deck = new CardDeck(atlas, 3); Card card1 = deck.getCard(Suit.Diamonds, Pip.Queen); card1.position.set(-1, 0, 0.01f); card1.update(); cards.add(card1); Card card2 = deck.getCard(Suit.Hearts, Pip.Seven); card2.position.set(0, 0, 0.01f); card2.update(); cards.add(card2); Card card3 = deck.getCard(Suit.Spades, Pip.Ace); card3.position.set(1, 0, 0.01f); card3.update(); cards.add(card3); cam = new PerspectiveCamera(); cam.position.set(0, 0, 10); cam.lookAt(0, 0, 0); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder builder = new ModelBuilder(); builder.begin(); builder.node().id = "top"; builder.part("top", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(new Color(0x63750A)))) .box(0f, 0f, -0.5f, 20f, 20f, 1f); tableTopModel = builder.end(); tableTop = new ModelInstance(tableTopModel); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1.f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -.4f, -.4f, -.4f)); } @Override public void resize(int width, int height) { float halfHeight = MINIMUM_VIEWPORT_SIZE * 0.5f; if (height > width) halfHeight *= (float)height / (float)width; float halfFovRadians = MathUtils.degreesToRadians * cam.fieldOfView * 0.5f; float distance = halfHeight / (float)Math.tan(halfFovRadians); cam.viewportWidth = width; cam.viewportHeight = height; cam.position.set(0, 0, distance); cam.lookAt(0, 0, 0); cam.update(); } @Override public void render() { final float delta = Math.min(1/30f, Gdx.graphics.getDeltaTime()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); camController.update(); Card card = cards.first(); card.angle = (card.angle + 90 * delta) % 360; card.update(); modelBatch.begin(cam); modelBatch.render(tableTop, environment); modelBatch.render(cards, environment); modelBatch.end(); } @Override public void pause() { // TODO Auto-generated method stub } @Override public void resume() { // TODO Auto-generated method stub } @Override public void dispose() { modelBatch.dispose(); atlas.dispose(); cards.dispose(); tableTopModel.dispose(); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/stepa/CardGame.java
tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/stepa/CardGame.java
package com.xoppa.blog.libgdx.g3d.cardgame.stepa; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.RenderableProvider; import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute; import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalShadowLight; import com.badlogic.gdx.graphics.g3d.model.MeshPart; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.DepthShaderProvider; import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.ObjectSet; import com.badlogic.gdx.utils.Pool; import com.xoppa.blog.libgdx.g3d.cardgame.step7.CardGame.CardBatch; public class CardGame implements ApplicationListener { public final static float CARD_WIDTH = 1f; public final static float CARD_HEIGHT = CARD_WIDTH * 277f / 200f; public final static float MINIMUM_VIEWPORT_SIZE = 7f; public enum Suit { Clubs("clubs", 0), Diamonds("diamonds", 1), Hearts("hearts", 2), Spades("spades", 3); public final String name; public final int index; private Suit(String name, int index) { this.name = name; this.index = index; } } public enum Pip { Ace(1), Two(2), Three(3), Four(4), Five(5), Six(6), Seven(7), Eight(8), Nine(9), Ten(10), Jack(11), Queen(12), King(13); public final int value; public final int index; private Pip(int value) { this.value = value; this.index = value - 1; } } public static class Card { public final Suit suit; public final Pip pip; private final float[] vertices; private final short[] indices; public final Matrix4 transform = new Matrix4(); public final Vector3 position = new Vector3(); public float angle; public Card(Suit suit, Pip pip, Sprite back, Sprite front) { assert(front.getTexture() == back.getTexture()); this.suit = suit; this.pip = pip; front.setPosition(-front.getWidth() * 0.5f, -front.getHeight() * 0.5f); back.setPosition(-back.getWidth() * 0.5f, -back.getHeight() * 0.5f); vertices = convert(front.getVertices(), back.getVertices()); indices = new short[] {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4 }; } private static float[] convert(float[] front, float[] back) { return new float[] { front[Batch.X2], front[Batch.Y2], 0.01f, 0, 0, 1, front[Batch.U2], front[Batch.V2], front[Batch.X1], front[Batch.Y1], 0.01f, 0, 0, 1, front[Batch.U1], front[Batch.V1], front[Batch.X4], front[Batch.Y4], 0.01f, 0, 0, 1, front[Batch.U4], front[Batch.V4], front[Batch.X3], front[Batch.Y3], 0.01f, 0, 0, 1, front[Batch.U3], front[Batch.V3], back[Batch.X1], back[Batch.Y1], -0.01f, 0, 0, -1, back[Batch.U1], back[Batch.V1], back[Batch.X2], back[Batch.Y2], -0.01f, 0, 0, -1, back[Batch.U2], back[Batch.V2], back[Batch.X3], back[Batch.Y3], -0.01f, 0, 0, -1, back[Batch.U3], back[Batch.V3], back[Batch.X4], back[Batch.Y4], -0.01f, 0, 0, -1, back[Batch.U4], back[Batch.V4] }; } public void update() { float z = position.z + 0.5f * Math.abs(MathUtils.sinDeg(angle)); transform.setToRotation(Vector3.Y, angle); transform.trn(position.x, position.y, z); } } public static class CardDeck { private final Card[][] cards; public CardDeck(TextureAtlas atlas, int backIndex) { cards = new Card[Suit.values().length][]; for (Suit suit : Suit.values()) { cards[suit.index] = new Card[Pip.values().length]; for (Pip pip : Pip.values()) { Sprite front = atlas.createSprite(suit.name, pip.value); front.setSize(CARD_WIDTH, CARD_HEIGHT); Sprite back = atlas.createSprite("back", backIndex); back.setSize(CARD_WIDTH, CARD_HEIGHT); cards[suit.index][pip.index] = new Card(suit, pip, back, front); } } } public Card getCard(Suit suit, Pip pip) { return cards[suit.index][pip.index]; } } public static class CardBatch extends ObjectSet<Card> implements RenderableProvider, Disposable { MeshBuilder meshBuilder; Mesh mesh; Renderable renderable; public CardBatch(Material material) { final int maxNumberOfCards = 52; final int maxNumberOfVertices = maxNumberOfCards * 8; final int maxNumberOfIndices = maxNumberOfCards * 12; mesh = new Mesh(false, maxNumberOfVertices, maxNumberOfIndices, VertexAttribute.Position(), VertexAttribute.Normal(), VertexAttribute.TexCoords(0)); meshBuilder = new MeshBuilder(); renderable = new Renderable(); renderable.material = material; } @Override public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) { meshBuilder.begin(mesh.getVertexAttributes()); meshBuilder.part("cards", GL20.GL_TRIANGLES, renderable.meshPart); for (Card card : this) { meshBuilder.setVertexTransform(card.transform); meshBuilder.addMesh(card.vertices, card.indices); } meshBuilder.end(mesh); renderable.shader = null; renderables.add(renderable); } @Override public void dispose() { mesh.dispose(); } } public static class CardAction { public CardActions parent; public Card card; public final Vector3 fromPosition = new Vector3(); public float fromAngle; public final Vector3 toPosition = new Vector3(); public float toAngle; public float speed; public float alpha; public CardAction(CardActions parent) { this.parent = parent; } public void reset(Card card) { this.card = card; fromPosition.set(card.position); fromAngle = card.angle; alpha = 0f; } public void update(float delta) { alpha += delta * speed; if (alpha >= 1f) { alpha = 1f; parent.actionComplete(this); } card.position.set(fromPosition).lerp(toPosition, alpha); card.angle = fromAngle + alpha * (toAngle - fromAngle); card.update(); } } public static class CardActions { Pool<CardAction> actionPool = new Pool<CardAction>() { protected CardAction newObject() { return new CardAction(CardActions.this); } }; Array<CardAction> actions = new Array<CardAction>(); public void actionComplete(CardAction action) { actions.removeValue(action, true); actionPool.free(action); } public void update(float delta) { for (CardAction action : actions) { action.update(delta); } } public void animate(Card card, float x, float y, float z, float angle, float speed) { CardAction action = actionPool.obtain(); action.reset(card); action.toPosition.set(x, y, z); action.toAngle = angle; action.speed = speed; actions.add(action); } } TextureAtlas atlas; Sprite front; Sprite back; PerspectiveCamera cam; CardDeck deck; CardBatch cards; CameraInputController camController; ModelBatch modelBatch; Model tableTopModel; ModelInstance tableTop; Environment environment; DirectionalShadowLight shadowLight; ModelBatch shadowBatch; CardActions actions; @Override public void create() { modelBatch = new ModelBatch(); atlas = new TextureAtlas(data + "/carddeck.atlas"); Material material = new Material( TextureAttribute.createDiffuse(atlas.getTextures().first()), new BlendingAttribute(false, 1f), FloatAttribute.createAlphaTest(0.2f)); cards = new CardBatch(material); deck = new CardDeck(atlas, 3); Card card = deck.getCard(Suit.Spades, Pip.King); card.position.set(3.5f, -2.5f, 0.01f); card.angle = 180f; card.update(); cards.add(card); cam = new PerspectiveCamera(); cam.position.set(0, 0, 10); cam.lookAt(0, 0, 0); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder builder = new ModelBuilder(); builder.begin(); builder.node().id = "top"; builder.part("top", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(new Color(0x63750A)))) .box(0f, 0f, -0.5f, 20f, 20f, 1f); tableTopModel = builder.end(); tableTop = new ModelInstance(tableTopModel); shadowBatch = new ModelBatch(new DepthShaderProvider()); shadowLight = new DirectionalShadowLight(1024, 1024, 10f, 10f, 1f, 20f); shadowLight.set(0.8f, 0.8f, 0.8f, -.4f, -.4f, -.4f); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1.f)); environment.add(shadowLight); environment.shadowMap = shadowLight; actions = new CardActions(); } @Override public void resize(int width, int height) { float halfHeight = MINIMUM_VIEWPORT_SIZE * 0.5f; if (height > width) halfHeight *= (float)height / (float)width; float halfFovRadians = MathUtils.degreesToRadians * cam.fieldOfView * 0.5f; float distance = halfHeight / (float)Math.tan(halfFovRadians); cam.viewportWidth = width; cam.viewportHeight = height; cam.position.set(0, 0, distance); cam.lookAt(0, 0, 0); cam.update(); } private float spawnTimer = -1f; @Override public void render() { final float delta = Math.min(1/30f, Gdx.graphics.getDeltaTime()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); camController.update(); if (spawnTimer < 0) { if (Gdx.input.justTouched()) spawnTimer = 1f; } else if ((spawnTimer -= delta) <= 0f) { spawnTimer = 0.25f; spawn(); } actions.update(delta); shadowLight.begin(Vector3.Zero, Vector3.Zero); shadowBatch.begin(shadowLight.getCamera()); shadowBatch.render(cards); shadowBatch.end(); shadowLight.end(); modelBatch.begin(cam); modelBatch.render(tableTop, environment); modelBatch.render(cards, environment); modelBatch.end(); } int pipIdx = -1; int suitIdx = 0; float spawnX = -0.5f; float spawnY = 0f; float spawnZ = 0f; public void spawn() { if (++pipIdx >= Pip.values().length) { pipIdx = 0; suitIdx = (suitIdx + 1) % Suit.values().length; } Suit suit = Suit.values()[suitIdx]; Pip pip = Pip.values()[pipIdx]; Gdx.app.log("Spawn", suit + " - " + pip); Card card = deck.getCard(suit, pip); card.position.set(3.5f, -2.5f, 0.01f); card.angle = 180; if (!cards.contains(card)) cards.add(card); spawnX = (spawnX + 0.5f); if (spawnX > 6f) { spawnX = 0f; spawnY = (spawnY + 0.5f) % 2f; } spawnZ += 0.001f; actions.animate(card, -3.5f + spawnX, 2.5f - spawnY, 0.01f + spawnZ, 0f, 1f); } @Override public void pause() { // TODO Auto-generated method stub } @Override public void resume() { // TODO Auto-generated method stub } @Override public void dispose() { modelBatch.dispose(); atlas.dispose(); cards.dispose(); tableTopModel.dispose(); shadowBatch.dispose(); shadowLight.dispose(); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step4/CardGame.java
tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step4/CardGame.java
package com.xoppa.blog.libgdx.g3d.cardgame.step4; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectSet; public class CardGame implements ApplicationListener { public final static float CARD_WIDTH = 1f; public final static float CARD_HEIGHT = CARD_WIDTH * 277f / 200f; public final static float MINIMUM_VIEWPORT_SIZE = 5f; public enum Suit { Clubs("clubs", 0), Diamonds("diamonds", 1), Hearts("hearts", 2), Spades("spades", 3); public final String name; public final int index; private Suit(String name, int index) { this.name = name; this.index = index; } } public enum Pip { Ace(1), Two(2), Three(3), Four(4), Five(5), Six(6), Seven(7), Eight(8), Nine(9), Ten(10), Jack(11), Queen(12), King(13); public final int value; public final int index; private Pip(int value) { this.value = value; this.index = value - 1; } } public static class Card { public final Suit suit; public final Pip pip; private final Sprite front; private final Sprite back; private boolean turned; public Card(Suit suit, Pip pip, Sprite back, Sprite front) { back.setSize(CARD_WIDTH, CARD_HEIGHT); front.setSize(CARD_WIDTH, CARD_HEIGHT); this.suit = suit; this.pip = pip; this.back = back; this.front = front; } public void setPosition(float x, float y) { front.setPosition(x - 0.5f * front.getWidth(), y - 0.5f * front.getHeight()); back.setPosition(x - 0.5f * back.getWidth(), y - 0.5f * back.getHeight()); } public void turn() { turned = !turned; } public void draw(Batch batch) { if (turned) back.draw(batch); else front.draw(batch); } } public static class CardDeck { private final Card[][] cards; public CardDeck(TextureAtlas atlas, int backIndex) { cards = new Card[Suit.values().length][]; for (Suit suit : Suit.values()) { cards[suit.index] = new Card[Pip.values().length]; for (Pip pip : Pip.values()) { Sprite front = atlas.createSprite(suit.name, pip.value); Sprite back = atlas.createSprite("back", backIndex); cards[suit.index][pip.index] = new Card(suit, pip, back, front); } } } public Card getCard(Suit suit, Pip pip) { return cards[suit.index][pip.index]; } } SpriteBatch spriteBatch; TextureAtlas atlas; Sprite front; Sprite back; OrthographicCamera cam; CardDeck deck; ObjectSet<Card> cards; CameraInputController camController; @Override public void create() { spriteBatch = new SpriteBatch(); atlas = new TextureAtlas(data + "/carddeck.atlas"); cards = new ObjectSet<Card>(); deck = new CardDeck(atlas, 3); Card card1 = deck.getCard(Suit.Diamonds, Pip.Queen); card1.setPosition(-1, 0); cards.add(card1); Card card2 = deck.getCard(Suit.Hearts, Pip.Four); card2.setPosition(0, 0); cards.add(card2); Card card3 = deck.getCard(Suit.Spades, Pip.Ace); card3.setPosition(1, 0); card3.turn(); cards.add(card3); cam = new OrthographicCamera(); cam.position.set(0, 0, 10); cam.lookAt(0, 0, 0); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); } @Override public void resize(int width, int height) { if (width > height) { cam.viewportHeight = MINIMUM_VIEWPORT_SIZE; cam.viewportWidth = cam.viewportHeight * (float)width / (float)height; } else { cam.viewportWidth = MINIMUM_VIEWPORT_SIZE; cam.viewportHeight = cam.viewportWidth * (float)height / (float)width; } cam.update(); } @Override public void render() { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); camController.update(); spriteBatch.setProjectionMatrix(cam.combined); spriteBatch.begin(); for (Card card : cards) card.draw(spriteBatch); spriteBatch.end(); } @Override public void pause() { // TODO Auto-generated method stub } @Override public void resume() { // TODO Auto-generated method stub } @Override public void dispose() { spriteBatch.dispose(); atlas.dispose(); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step5/CardGame.java
tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step5/CardGame.java
package com.xoppa.blog.libgdx.g3d.cardgame.step5; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectSet; public class CardGame implements ApplicationListener { public final static float CARD_WIDTH = 1f; public final static float CARD_HEIGHT = CARD_WIDTH * 277f / 200f; public final static float MINIMUM_VIEWPORT_SIZE = 5f; public enum Suit { Clubs("clubs", 0), Diamonds("diamonds", 1), Hearts("hearts", 2), Spades("spades", 3); public final String name; public final int index; private Suit(String name, int index) { this.name = name; this.index = index; } } public enum Pip { Ace(1), Two(2), Three(3), Four(4), Five(5), Six(6), Seven(7), Eight(8), Nine(9), Ten(10), Jack(11), Queen(12), King(13); public final int value; public final int index; private Pip(int value) { this.value = value; this.index = value - 1; } } public static class Card { public final Suit suit; public final Pip pip; private final Sprite front; private final Sprite back; private boolean turned; public Card(Suit suit, Pip pip, Sprite back, Sprite front) { back.setSize(CARD_WIDTH, CARD_HEIGHT); front.setSize(CARD_WIDTH, CARD_HEIGHT); this.suit = suit; this.pip = pip; this.back = back; this.front = front; } public void setPosition(float x, float y) { front.setPosition(x - 0.5f * front.getWidth(), y - 0.5f * front.getHeight()); back.setPosition(x - 0.5f * back.getWidth(), y - 0.5f * back.getHeight()); } public void turn() { turned = !turned; } public void draw(Batch batch) { if (turned) back.draw(batch); else front.draw(batch); } } public static class CardDeck { private final Card[][] cards; public CardDeck(TextureAtlas atlas, int backIndex) { cards = new Card[Suit.values().length][]; for (Suit suit : Suit.values()) { cards[suit.index] = new Card[Pip.values().length]; for (Pip pip : Pip.values()) { Sprite front = atlas.createSprite(suit.name, pip.value); Sprite back = atlas.createSprite("back", backIndex); cards[suit.index][pip.index] = new Card(suit, pip, back, front); } } } public Card getCard(Suit suit, Pip pip) { return cards[suit.index][pip.index]; } } SpriteBatch spriteBatch; TextureAtlas atlas; Sprite front; Sprite back; PerspectiveCamera cam; CardDeck deck; ObjectSet<Card> cards; CameraInputController camController; @Override public void create() { spriteBatch = new SpriteBatch(); atlas = new TextureAtlas(data + "/carddeck.atlas"); cards = new ObjectSet<Card>(); deck = new CardDeck(atlas, 3); Card card1 = deck.getCard(Suit.Diamonds, Pip.Queen); card1.setPosition(-1, 0); cards.add(card1); Card card2 = deck.getCard(Suit.Hearts, Pip.Four); card2.setPosition(0, 0); cards.add(card2); Card card3 = deck.getCard(Suit.Spades, Pip.Ace); card3.setPosition(1, 0); card3.turn(); cards.add(card3); cam = new PerspectiveCamera(); cam.position.set(0, 0, 10); cam.lookAt(0, 0, 0); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); } @Override public void resize(int width, int height) { float halfHeight = MINIMUM_VIEWPORT_SIZE * 0.5f; if (height > width) halfHeight *= (float)height / (float)width; float halfFovRadians = MathUtils.degreesToRadians * cam.fieldOfView * 0.5f; float distance = halfHeight / (float)Math.tan(halfFovRadians); cam.viewportWidth = width; cam.viewportHeight = height; cam.position.set(0, 0, distance); cam.lookAt(0, 0, 0); cam.update(); } @Override public void render() { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); camController.update(); spriteBatch.setProjectionMatrix(cam.combined); spriteBatch.begin(); for (Card card : cards) card.draw(spriteBatch); spriteBatch.end(); } @Override public void pause() { // TODO Auto-generated method stub } @Override public void resume() { // TODO Auto-generated method stub } @Override public void dispose() { spriteBatch.dispose(); atlas.dispose(); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false