def __init__(self, actor, label, sz, offset, rot): print(actor) self.width = sz[0] self.height = sz[1] #print("before attach",actor.get_actor_components()) mesh = actor.get_actor_component_by_type(SkeletalMeshComponent) # we need three parts, SceneCaptureActor, ATextureReader, RenderTargetTextures self.rendertarget = TextureRenderTarget2D() self.rendertarget.set_property("SizeX", self.width) self.rendertarget.set_property("SizeY", self.height) xform = FTransform() xform.translation = FVector(offset[0], offset[1], offset[2]) xform.rotation = FRotator(rot[0], rot[1], rot[2]) ue.log("vcam xlate {} rot {}".format(xform.translation, xform.rotation)) self.scene_capture = actor.get_actor_component_by_type( SceneCaptureComponent2D) self.scene_capture.set_relative_location(offset[0], offset[1], offset[2]) self.scene_capture.set_relative_rotation(rot[0], rot[1], rot[2]) self.scene_capture.set_property("TextureTarget", self.rendertarget) # add reader last self.reader = actor.add_actor_component( ue.find_class('ATextureReader'), label + "_rendertarget") self.reader.set_property('RenderTarget', self.rendertarget) self.reader.SetWidthHeight(sz[0], sz[1])
def fn_setTable(stringlist, tablename): newarraylist = [] if len(stringlist) == 0: return #버프 아이콘 경로 변경 arraylist = stringlist #ue.log('정말 진실인가? : ' + str(cb_bool)) for ttable in arraylist: if ue.find_asset(ttable) == None: #ue.log('정말 없다!') className = '?????' #ue.find_asset(ttable).get_class().get_name() # #asset.className path = ttable assetname = ttable.split('.')[1] uesasset = '없음' addall = className + ',' + path + ',' + assetname + ',' + uesasset newarraylist.append(addall) else: #ue.log('정말 있다!') if checkbox_bool.is_checked() == False: className = ue.find_asset(ttable).get_class().get_name() path = ttable assetname = ttable.split('.')[1] uesasset = '있음' addall = className + ',' + path + ',' + assetname + ',' + uesasset newarraylist.append(addall) ue.log('제대로나옴? : ' + tablename) #테이블에 작성 newslate.ClassTable(ctext, newarraylist, tablename)
def train_blocking(self): if (self.uobject.VerbosePythonLog): ue.log(self.uobject.TensorFlowModule + ' training started on bt thread.') #calculate the time it takes to train your network start = time.time() self.trained = self.tfapi.onBeginTraining() stop = time.time() if self.trained is None: ue.log( 'Training Note: no summary object returned from training. See your onBeginTraining(): method' ) return if 'summary' in self.trained: summary = self.trained['summary'] else: summary = {} summary['elapsed'] = stop - start #run callbacks only if we're still in a valid game world if (self.ValidGameWorld): ue.run_on_gt(self.training_complete, summary)
def begin_play(self): ue.log("begin object loader") self.pawn = self.uobject.get_owner() #self.world = ue.get_editor_world() self.datapath = str(self.pawn.get_property('datafilename')) self.objects = [] ue.log("------------------")
def change_operation(self, type): if (type == '+'): self.c = self.a + self.b elif (type == '-'): self.c = self.a - self.b ue.log('operation changed to ' + type)
def setup_complete(self): if (self.uobject.VerbosePythonLog): ue.log('Setup complete!') #train after setup has completed if toggled if (self.uobject.ShouldTrainOnBeginPlay): self.train()
def onBeginTraining(self): ue.log("starting avoid agent training") self.INPUT_SIZE = 10 self.OUTPUT_SIZE = 2 self.DISCOUNT_RATE = 0.99 self.REPLAY_MEMORY = 50000 self.BATCH_SIZE = 64 self.TARGET_UPDATE_FREQUENCY = 5 self.MAX_EPISODES = 5000 self.episode = 200 self.state = np.zeros(10) self.next_state = np.zeros(10) self.action = 1 self.reward = 0.0 self.done = False self.step_count = 0 self.replay_buffer = deque(maxlen=self.REPLAY_MEMORY) self.last_100_game_reward = deque(maxlen=100) self.sess = tf.compat.v1.Session() self.mainDQN = dqn.DQN(self.sess, self.INPUT_SIZE, self.OUTPUT_SIZE, name="main") self.targetDQN = dqn.DQN(self.sess, self.INPUT_SIZE, self.OUTPUT_SIZE, name="target") self.sess.run(tf.compat.v1.global_variables_initializer()) self.copy_ops = self.get_copy_var_ops(dest_scope_name="target", src_scope_name="main") self.sess.run(self.copy_ops) pass
def fill_toolbar(toolbar): icon1 = FSlateIcon('PyStyle', 'SolidBrush001') icon2 = FSlateIcon('PyStyle', 'ImageBrush001') toolbar.add_tool_bar_button('button001', 'Button001', 'Button001 tooltip', icon1, lambda: ue.log('Button001')) toolbar.add_tool_bar_button('button002', 'Button002', 'Button002 tooltip', icon2, lambda: ue.log('Button002'))
def begin_play(self): self.actor = self.uobject.get_owner() self.VehicleMovement = self.actor.VehicleMovement self.replay_buffer = ReplayBuffer(max_size=50000) ue.log('Begin Play on TorchActor class') ue.log(torch.cuda.is_available()) self.policy = TD3(lr, state_dim, action_dim, max_action) self.gen_target() self.last_state = [] self.last_reward = 0 self.last_action = None self.last_done = False self.frame = int(random.random() * 100) self.start_pos = self.uobject.get_actor_location() self.policy.load(directory, loadfilename) self.episode = 0 self.ep_frame = 0 self.ep_reward = 0 self.policy = master.policy self.boredom = 0.8 print("MASTER") print(master) self.my_id = master.get_id() self.actor.TextRender.call('SetText {}'.format(self.my_id))
def tensorinput(self, args): ue.log('TF inputs passed: ' + args) imgstruct = json.loads(args) pixelarray = imgstruct['pixels'] ue.log('image len: ' + str(len(pixelarray))) #do tf stuff here with passed image sess = self.trained['sess'] feed_dict = {self.trained['x']: [pixelarray]} ue.log(feed_dict) #get predicted result result = sess.run(self.trained['y'], feed_dict) ue.log(result) index, value = max(enumerate(result[0]), key=operator.itemgetter(1)) ue.log('max: ' + str(value) + 'at: ' + str(index)) #set the prediction result imgstruct['prediction'] = index #pass prediction back self.uobject.OnResultsFunction(json.dumps(imgstruct))
def on_epoch_end(self, epoch, logs={}): if (self.outer.shouldStop): #notify on first call if not (self.model.stop_training): ue.log('Early stop called!') self.model.stop_training = True else: #json convertible types are float64 not float32 logs['acc'] = np.float64(logs['acc']) accuracy = np.float64(logs['acc']) logs['loss'] = np.float64(logs['loss']) self.outer.callEvent("AccuracyUpdate", logs['acc'], True) self.outer.callEvent('TrainingUpdateEvent', logs, True) current = logs.get(self.monitor) if current is None: warnings.warn( "Early stopping requires %s available!" % self.monitor, RuntimeWarning) if current >= self.value: if self.verbose > 0: print("Epoch %05d: early stopping THR" % epoch) self.model.stop_training = True
def onJsonInput(self, jsonInput): #build the result object result = {'prediction':-1} #If we try to predict before training is complete if not hasattr(self, 'model'): ue.log_warning("Warning! No 'model' found, prediction invalid. Did training complete?") return result #prepare the input, reshape 784 array to a 1x28x28 array x_raw = jsonInput['pixels'] x = np.reshape(x_raw, (1, 28, 28)) predictions = self.model.predict(x) #ue.log(predictions) # #run the input through our network using stored model and graph # with self.graph.as_default(): # output = self.model.predict(x) #convert output array to max value prediction index (0-10) #index, value = max(enumerate(output[0]), key=operator.itemgetter(1)) index, value = max(enumerate(predictions[0]), key=operator.itemgetter(1)) #Optionally log the output so you can see the weights for each value and final prediction ue.log('Predictions array: ' + str(predictions) + ',\nPrediction: ' + str(index)) result['prediction'] = index return result
def fn_Dafultxlsx(datatablepath): xslxpath = datatablepath + '/TableResourcePath.xlsx' stringarray = [] sstring = [] sname = 'TableResourcePath' try: load_wb = openpyxl.load_workbook(xslxpath, data_only=True) except: ue.log('TableResourcePath.xlsx 엑셀파일을 찾지 못하였습니다.') return None load_ws = load_wb[sname] indexY = 2 indexX = 1 while True: #ue.log(load_ws.cell(indexY,indexX).value) sstring.append(load_ws.cell(indexY, indexX).value) indexX += 1 if not load_ws.cell(indexY, indexX).value: stringarray.append(sstring) indexY += 1 indexX = 1 sstring = [] if not load_ws.cell(indexY, indexX).value: break return stringarray
def parseJson(packagePath): try: with open(packagePath) as data_file: #TODO: catch file not found error package = json.load(data_file) ue.log( 'upymodule_importer::Resolving upymodule dependencies for ' + package['name']) pythonModules = package['pythonModules'] #loop over all the modules, check if we have them installed for module in pythonModules: version = pythonModules[module] ue.log("upymodule_importer::" + module + " " + version + " installed? " + str(pip.isInstalled(module))) if not pip.isInstalled(module, version): ue.log( 'upymodule_importer::Dependency not installed, fetching via pip...' ) pip.install(module + '==' + version) dependencyNoun = 'dependencies' if len(pythonModules) == 1: dependencyNoun = 'dependency' ue.log( 'upymodule_importer::' + str(len(pythonModules)) + ' ' + package['name'] + ' upymodule ' + dependencyNoun + ' resolved (if installation in progress, more async output will stream)' ) except: e = sys.exc_info()[0] ue.log('upymodule_importer::upymodule.json error: ' + str(e))
def run_fbx_to_ueasset(self, path_to_fbx=''): if path_to_fbx is None: ue.log("provide correct path to file and proper fbx name") else: path_to_fbx = get_full_path(path_to_fbx) ue.log("path_to_fbx = " + path_to_fbx) # configure the factory self.fbx_factory.ImportUI.bCreatePhysicsAsset = False self.fbx_factory.ImportUI.bImportMaterials = False self.fbx_factory.ImportUI.bImportTextures = False self.fbx_factory.ImportUI.bImportAnimations = False self.fbx_factory.ImportUI.bImportAsSkeletal = True self.fbx_factory.ImportUI.SkeletalMeshImportData.ImportUniformScale = 0.1 # import the mesh ue.log("starting to import fbx to unreal engine") ###### asset = factory.factory_import_object(filename, asset_name) # self.mesh = self.fbx_factory.factory_import_object(path_to_fbx, self.path_to_output_asset) self.mesh = self.fbx_factory.factory_import_object( path_to_fbx, self.path_to_output_asset) self.mesh = ue.find_asset(self.path_to_output_asset + '/test_test') ue.log("finished to import fbx to unreal engine ") self.mesh.save_package() ue.log("save uasset as package") ue.add_on_screen_debug_message(1, 30, self.mesh)
def open_submenu001(builder): builder.begin_section('submenu001', 'i am a tooltip') builder.add_menu_entry('sub_one', 'tooltip', lambda: ue.log('hello from submenu001')) builder.add_menu_entry('sub_one_2', 'tooltip 2', lambda: ue.log('hello again')) builder.end_section()
def tick(self, delta_seconds: float): start_time = time.clock() pawn = self.uobject.GetPawn() game_mode = pawn.GameMode score = self.get_score(game_mode) # Attribute this to previous action reward = self.current_score.update(score) screen = self.get_screen(pawn.GameMode) # Skip frames when no screen is available if screen is None or len(screen) == 0: return self.trainer.process_frame(screen, reward, reward != 0) # Make new action action = self.trainer.act() pawn.MovementDirection = get_action_direction(action) self.step_count += 1 if self.step_count % SNAPSHOT_PERIOD == 0: self.trainer.save_model(MODEL_PATH) # Log elapsed time finish_time = time.clock() elapsed = finish_time - start_time if LOG_TIMINGS: ue.log("Delta seconds: {}, time elapsed: {}".format( delta_seconds, elapsed))
def onBeginTraining(self): ue.log("starting MnistTutorial training") #reset the session each time we get training calls K.clear_session() #load mnist data set mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() #rescale 0-255 -> 0-1.0 x_train, x_test = x_train / 255.0, x_test / 255.0 #define model model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation=tf.nn.relu), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation=tf.nn.softmax) ]) model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) #this will do the actual training model.fit(x_train, y_train, epochs=1) model.evaluate(x_test, y_test) ue.log("Training complete.") #store our model and graph for prediction self.graph = tf.get_default_graph() self.model = model
def on_preexit(self): ue.log("on preexit") try: self.fstate.close() self.fcmd.close() except: ue.log("Error closing pipes")
def gen_converse_requests(self): """Yields: ConverseRequest messages to send to the API.""" converse_state = None if self.conversation_state: ue.log('Sending converse_state: %s', self.conversation_state) converse_state = embedded_assistant_pb2.ConverseState( conversation_state=self.conversation_state, ) config = embedded_assistant_pb2.ConverseConfig( audio_in_config=embedded_assistant_pb2.AudioInConfig( encoding='LINEAR16', sample_rate_hertz=self.conversation_stream.sample_rate, ), audio_out_config=embedded_assistant_pb2.AudioOutConfig( encoding='LINEAR16', sample_rate_hertz=self.conversation_stream.sample_rate, volume_percentage=self.conversation_stream.volume_percentage, ), converse_state=converse_state) # The first ConverseRequest must contain the ConverseConfig # and no audio data. yield embedded_assistant_pb2.ConverseRequest(config=config) for data in self.conversation_stream: # Subsequent requests need audio data, but not config. yield embedded_assistant_pb2.ConverseRequest(audio_in=data)
def onBeginTraining(self): ue.log("starting MnistTutorial training") #training parameters self.batch_size = 128 num_classes = 10 epochs = 1 (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(512, activation=tf.nn.relu), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(num_classes, activation=tf.nn.softmax) ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, epochs=epochs) model.evaluate(x_test, y_test) # self.outer.jsonPixels['pixels'] = self.outer.x_train[index].ravel().tolist() # self.outer.callEvent('PixelEvent', self.outer.jsonPixels, True) ue.log("Training complete.") #store our model for prediction #self.graph = tf.get_default_graph() self.model = model
def begin_episode(self, type): # for문에서 시작하는 함수 # 이 값은 BP에서의 for문 횟수와 일치해야한다. ue.log("Execution Begin Episode Event") self.e = 1. / ((self.episode / 10) + 1) self.done = False self.step_count = 0 pass
def fn_sp(self): try: st = fn_SaveDefaultSetting() table_path.set_text(st) if self.fn_resettable() != None: self.fn_resettable() except: ue.log('엑셀 기본 경로 설정을 취소 하였습니다')
async def spawn_server(host, port): try: coro = await asyncio.start_server(new_client_connected, host, port) ue.log('tcp server spawned on {0}:{1}'.format(host, port)) await coro.wait_closed() finally: coro.close() ue.log('tcp server ended')
def test(params=None): ue.log(type(params)) ue.log('starting test') if not params: t = Thread(target=testaction) else: t = Thread(target=testaction, args=(params, )) t.start()
async def new_client_connected(reader, writer): name = writer.get_extra_info("peername") ue.log("New client connection from {0}".format(name)) unpacker = msgpack.Unpacker(encoding="utf-8") # profile for n minutes after a connection #t = time.time() #last_prof = {} # last time we profiled while True: # wait for a line data = await reader.read(8) # read the num-byte header if not data: break # Read the incoming message. orig_len = int(data) received_len = 0 while True: data = await reader.read(min(orig_len - received_len, 8192)) if not data: send_message({"status": "error", "message": "No data of len {} received by socket.recv in call to method `recv`!". format(orig_len - received_len)}, writer) data_len = len(data) received_len += data_len unpacker.feed(data) if received_len == orig_len: break # Get the data. for message in unpacker: #response = None if not isinstance(message, dict): response = {"status": "error", "message": "Unknown message type ({})!".format(type(message).__name__)} else: #cmd = message.get("cmd") #if cmd not in last_prof or t > last_prof[cmd] + 30: # pr = cProfile.Profile() # pr.enable() # response = manage_message(message, writer) # pr.disable() # s = io.StringIO() # ps = pstats.Stats(pr, stream=s).sort_stats("cumulative") # ps.dump_stats("prof.{}.{}".format(cmd, int(t))) # last_prof[cmd] = t #else: response = manage_message(message, writer) # write back immediately if response: send_message(response, writer) # async calls -> do nothing here (async will handle it) #t = time.time() ue.log("Client {0} disconnected".format(name))
def json_input(self, args): if (self.uobject.VerbosePythonLog): ue.log(self.uobject.TensorFlowModule + ' input passed: ' + args) #branch based on threading if (self.uobject.ShouldUseMultithreading): ut.run_on_bt(self.json_input_blocking, args) else: self.json_input_blocking(args)
def json_input(self, args): if (self.uobject.VerbosePythonLog): ue.log(self.uobject.TensorFlowModule + ' input passed: ' + args) #pass the raw json to the script to handle resultJson = self.tfapi.onJsonInput(json.loads(args)) #pass prediction json back self.uobject.OnResultsFunction(json.dumps(resultJson))
def open_menu(builder): builder.begin_section('test1', 'test2') builder.add_menu_entry('one', 'two', lambda: ue.log('ciao 1')) builder.add_sub_menu('i am a submenu', 'tooltip for the submenu', open_submenu001) builder.add_menu_entry('three', 'four', lambda: ue.log('ciao 2')) builder.add_sub_menu('i am another submenu', 'tooltip for the second submenu', open_submenu002) builder.end_section()
def __add_received_dismantled_weapon(self, weapon): self._dismantled_weapons.append(weapon) if len(self._dismantled_weapons ) >= self._dismantled_weapons_needed_to_retrain: ue.log("Should retrain!") if not self._is_training: self.tf_component.train() self._is_training = True
def tensorinput(self, args): if(self.uobject.VerbosePythonLog): ue.log(self.uobject.TensorFlowModule + ' input passed: ' + args) #pass the raw json to the script to handle resultJson = self.tf.runJsonInput(self.trained, json.loads(args)) #pass prediction json back self.uobject.OnResultsFunction(json.dumps(resultJson))
def begin_play(self): if(self.uobject.VerbosePythonLog): ue.log('BeginPlay, importing TF module: ' + self.uobject.TensorFlowModule) self.tf = importlib.import_module(self.uobject.TensorFlowModule) imp.reload(self.tf) #train if(self.uobject.ShouldTrainOnBeginPlay): self.train()
def train(self, args=None): if(self.uobject.VerbosePythonLog): ue.log(self.uobject.TensorFlowModule + ' training scheduled.') if(self.uobject.ShouldUseMultithreading): try: ut.run_on_bt(self.trainBlocking) except: e = sys.exc_info()[0] ue.log('TensorFlowComponent error: ' + str(e)) else: self.trainBlocking()
def trainBlocking(self): if(self.uobject.VerbosePythonLog): ue.log(self.uobject.TensorFlowModule + ' training started on bt thread.') #calculate the time it takes to train your network start = time.time() self.trained = self.tf.train() stop = time.time() if 'summary' in self.trained: summary = self.trained['summary'] else: summary = {} summary['elapsed'] = stop-start ue.run_on_gt(self.trainingComplete, summary)
def main(data_dir): mnist = input_data.read_data_sets(data_dir, one_hot=True) ue.log("starting mnist simple") # Create the model x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.matmul(x, W) + b # Define loss and optimizer y_ = tf.placeholder(tf.float32, [None, 10]) # The raw formulation of cross-entropy, # # tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)), # reduction_indices=[1])) # # can be numerically unstable. # # So here we use tf.nn.softmax_cross_entropy_with_logits on the raw # outputs of 'y', and then average across the batch. cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess = tf.InteractiveSession() # Train tf.global_variables_initializer().run() for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) if i % 100 == 0: ue.log(i) # Test trained model correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) finalAccuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}) ue.log('final training accuracy: ' + str(finalAccuracy)) #return trained model stored = {'x':x, 'y':y, 'W':W,'b':b, 'session':sess} #ue.log('trained x: ' + str(stored['x'])) #ue.log('trained y: ' + str(stored['y'])) #ue.log('trained W: ' + str(stored['W'])) #ue.log('trained b: ' + str(stored['b'])) #store optional summary information stored['summary'] = {'x':str(x), 'y':str(y), 'W':str(W), 'b':str(b)} return stored
def runJsonInput(stored, jsonInput): #expect an image struct in json format pixelarray = jsonInput['pixels'] ue.log('image len: ' + str(len(pixelarray))) #embedd the input image pixels as 'x' feed_dict = {stored['x']: [pixelarray]} ue.log(feed_dict) #run our model result = runModelWithInput(stored['session'], stored, feed_dict) ue.log('result: ' + str(len(pixelarray))) #convert our raw result to a prediction index, value = max(enumerate(result[0]), key=operator.itemgetter(1)) ue.log('max: ' + str(value) + 'at: ' + str(index)) #set the prediction result in our json jsonInput['prediction'] = index return jsonInput
import unreal_engine as ue from unreal_engine import FARFilter _filter = FARFilter() _filter.class_names = ['StaticMesh'] # when passing True to the second argument of get_assets_by_filter(), you will get FAssetData instead of UObject for asset_data in ue.get_assets_by_filter(_filter, True): has_custom_thumbnail = asset_data.has_custom_thumbnail() has_cached_thumbnail = asset_data.has_cached_thumbnail() try: thumbnail = asset_data.get_thumbnail() except: thumbnail = None ue.log('Asset: {0} Loaded: {1} CustomThumbnail: {2} CachedThumbnail: {3} Thumbnail: {4}'.format(asset_data.object_path, asset_data.is_asset_loaded(), has_custom_thumbnail, has_cached_thumbnail, thumbnail))
def test_creation(self): new_blueprint = ue.create_blueprint(Actor, '/Game/Tests/Blueprints/Test0_' + self.random_string) ue.log(new_blueprint.ParentClass) self.assertEqual(new_blueprint.ParentClass, Actor) self.assertNotEqual(new_blueprint.ParentClass, Character)
from unreal_engine import SWindow, SProgressBar, SButton, SVerticalBox import unreal_engine as ue progress_bar = SProgressBar() canceled = False def cancel_operation(): global canceled ue.log_warning('slow operation canceled') canceled = True SWindow(title='slow task', sizing_rule=1)( SVerticalBox() ( progress_bar ) ( SButton(text='cancel', on_clicked=cancel_operation) ) ) for i in range(0, 10000): progress_bar.set_percent(1/10000 * i) ue.log('slow task iteration: {0}'.format(i)) if canceled: break ue.slate_tick()
#Add Anything you want to run on startup import unreal_engine as ue ue.log('Hi test')
curves = [] for i in range(0, self.scene.get_src_object_count()): obj = self.scene.get_src_object(i) # retrieve object properties for prop in self.get_properties(obj): curve_node = prop.get_curve_node(layer) if not curve_node: continue channels = [] for chan_num in range(0, curve_node.get_channels_count()): # always get the first curve curve = curve_node.get_curve(chan_num, 0) if not curve: continue keys = [] for key_id in range(0, curve.key_get_count()): keys.append((curve.key_get_seconds(key_id), curve.key_get_value(key_id))) channels.append({'name': curve_node.get_channel_name(chan_num), 'keys': keys}) curves.append({'object': obj.get_name(), 'class': obj.get_class_name(), 'property': prop.get_name(), 'channels': channels}) return curves filename = 'C:/Users/roberto/Downloads/testCam/testCam.fbx' #filename = 'C:/Users/Roberto/Desktop/Kaiju_Assets/Slicer/Animations/slicer_attack.fbx' extractor = FbxCurvesExtractor(filename) for stack in extractor.get_anim_stacks(): for layer in extractor.get_anim_layers(stack): for curve in extractor.get_anim_curves(layer): ue.log(curve)
def dumb(): ue.log('HELLO WORLD')
def open_menu(menu): menu.begin_section('test1', 'test2') menu.add_menu_entry('one', 'two', lambda: ue.log('ciao 1')) menu.add_menu_entry('three', 'four', lambda: ue.log('ciao 2')) menu.end_section()
def fill_toolbar(toolbar): icon1 = FSlateIcon('PyStyle', 'SolidBrush001') icon2 = FSlateIcon('PyStyle', 'ImageBrush001') toolbar.add_tool_bar_button('button001', 'Button001', 'Button001 tooltip', icon1, lambda: ue.log('Button001')) toolbar.add_tool_bar_button('button002', 'Button002', 'Button002 tooltip', icon2, lambda: ue.log('Button002'))
def clicked(geometry, pointer_event): ue.log('Hello') ue.log(geometry.fields()) ue.log(pointer_event.fields()) return True
def clicked2(): ue.log('Test') return True
def train(): print("Training started...") np.random.seed(1337) # for reproducibility batch_size = 128 nb_classes = 10 nb_epoch = 12 # input image dimensions img_rows, img_cols = 28, 28 # number of convolutional filters to use nb_filters = 32 # size of pooling area for max pooling pool_size = (2, 2) # convolution kernel size kernel_size = (3, 3) # the data, shuffled and split between train and test sets (X_train, y_train), (X_test, y_test) = mnist.load_data() if K.image_dim_ordering() == 'th': X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols) X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 ue.log('X_train shape:' + str(X_train.shape)) ue.log(str(X_train.shape[0]) + 'train samples') ue.log(str(X_test.shape[0]) + 'test samples') # convert class vectors to binary class matrices Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) model = Sequential() model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='valid', input_shape=input_shape)) model.add(Activation('relu')) model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1])) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=pool_size)) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(nb_classes)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy']) print(X_train) print(Y_train)
import unreal_engine as ue import os import png # run play in the editor and execute this script (with ue.exec) from the python console width, height = ue.editor_get_pie_viewport_size() pixels = ue.editor_get_pie_viewport_screenshot() ue.log("{0} {1} {2}".format(width, height, len(pixels))) png_pixels = [] for y in range(0, height): line = [] for x in range(0, width): index = y * width + x pixel = pixels[index] line.append([pixel.r, pixel.g, pixel.b, pixel.a]) png_pixels.append(line) path = os.path.expanduser("~/Desktop/pie_screenshot.png") png.from_array(png_pixels, 'RGBA').save(path)
def trainingComplete(self, summary): if(self.uobject.VerbosePythonLog): ue.log(self.uobject.TensorFlowModule + ' trained in ' + str(round(summary['elapsed'],2)) + ' seconds.') self.uobject.OnTrainingCompleteFunction(json.dumps(summary))
Author: Aymeric Damien Project: https://github.com/aymericdamien/TensorFlow-Examples/ ''' import tensorflow as tf import unreal_engine as ue # Basic constant operations # The value returned by the constructor represents the output # of the Constant op. a = tf.constant(2) b = tf.constant(3) # Launch the default graph. with tf.Session() as sess: ue.log("a=2, b=3") ue.log("Addition with constants: %i" % sess.run(a+b)) ue.log("Multiplication with constants: %i" % sess.run(a*b)) # Basic Operations with variable as graph input # The value returned by the constructor represents the output # of the Variable op. (define as input when running session) # tf Graph input a = tf.placeholder(tf.int16) b = tf.placeholder(tf.int16) # Define some operations add = tf.add(a, b) mul = tf.mul(a, b) # Launch the default graph.